The user wants a design for a "Server-Driven UI" (SDUI) protocol.
The core components requested are:
- Templates: How to represent UI structure on the server.
- Diffing: How to update the UI efficiently (sending changes, not full reloads).
- Safety: Ensuring the UI doesn't crash, respects type constraints, and handles invalid data gracefully.
This is a system design and architecture task. I need to provide a conceptual framework, a protocol specification (likely JSON-based for clarity), and explain the mechanisms for each component.
Step 1: Core Concept & Philosophy
- Goal: The server controls the layout and logic flow; the client is a "dumb" renderer.
- Analogy: Think of it like a remote control for a TV. The buttons (UI) are defined by the signal, but the TV (Client) knows how to draw a button.
Step 2: Designing the "Templates" (The Payload)
- The server sends a tree structure.
- Need a schema.
- Key elements:
type (e.g., VStack, Text, Image).
properties (props like color, text content, URL).
children (nested views).
actions (what happens on click -> server event).
bindings (optional, for local state optimization, but maybe keep it simple first: action-based).
- Versioning: Crucial for backwards compatibility. If the server sends
type: "CarouselV2" and the app is old, it breaks. Need fallbacks or versioning.
Step 3: Designing the "Diffing" (The Update Mechanism)
- Naive approach: Send the whole screen on every change. Bandwidth heavy.
- Better approach: JSON Patch (RFC 6902).
- Best approach: Virtual DOM diffing or specific "Diff" instructions.
- Protocol Strategy:
- Initial load:
{ "type": "full_load", "root": { ... } }
- Update:
{ "type": "patch", "ops": [ { "op": "replace", "path": "/header/title", "value": "New Title" } ] }
- Identifier: Nodes need IDs (not just array indices) to be robust.
Step 4: Designing "Safety" (The Resilience)
- Type Safety: Strongly typed models on the client.
- Null Handling: Missing props shouldn't crash the app.
- Unknown Types: What if server sends
SuperWidget but client doesn't have it? -> Render a placeholder or nothing (fail gracefully).
- Actions: Don't execute arbitrary code. Use strict command pattern (e.g.,
navigate, post_data).
- Security: Sanitize input (prevent XSS if webview involved, though less relevant for native, still good practice).
Step 5: Structuring the Response
I will structure the answer into clear sections:
- High-Level Architecture: The contract between Server and Client.
- The Protocol Specification (JSON Schema): Concrete examples of the payload.
- Component Registry (Templates): How the client maps strings to UI components.
- Diffing Strategy: How to handle updates without re-downloading everything.
- Safety & Resilience: Defensive coding strategies.
- Action Protocol: Handling user interaction.
Refining the content:
- Templates: I should distinguish between "Layout" (VStack/HStack) and "Components" (ProductCard).
- Diffing: Mentioning JSON Patch is standard, but maybe a custom "Component Diffing" is easier to explain. Let's stick to a generic ID-based patching system.
- Safety: The concept of "Schema Evolution" is important.
Drafting the Protocol (Mental Sandbox):
Self-Correction during drafting:
- Is "Templates" the right word? Usually, in SDUI, we send the instance tree, not just a template with data binding. However, often we send a "CardTemplate" and pass data to it to reduce payload size.
- Decision: I will describe a "Declarative Tree" approach, but mention "Component Libraries" (server references a component name, client implements it).
Final Polish:
Make sure to emphasize that the Client owns the styling and implementation, while the Server owns the structure and logic.
Let's write the code examples in clear JSON and pseudo-code (Swift/Kotlin/TypeScript agnostic concepts).
Key sections to write:
- Protocol Overview (The "Wire" format).
- Template System (The "Registry" on client).
- Diffing Engine (Optimizing updates).
- Safety Layer (The "Guardrails").
Let's get specific on Safety:
- Graceful Degradation: If
type is unknown, render FallbackComponent (maybe just the text content or a generic box).
- Contract Versioning:
protocol_version: 1.2.
- Action Safety: never send code (JS) to execute. Send intents:
{ action: "open_url", url: "..." }.
Let's produce the response.
Building a Server-Driven UI (SDUI) system requires shifting your mindset from "fetching data to fill views" to "sending views to display data." The server becomes the source of truth for layout, logic, and content, while the client becomes a lightweight rendering engine.
Below is a comprehensive design for an SDUI protocol, focusing on View Primitives, Diffing/Patching, and Type Safety.
1. The Core Protocol: The "View Tree"
Instead of sending HTML or platform-specific code (SwiftUI/Kotlin), we define a generic Abstract Syntax Tree (AST) for UI.
The Contract (JSON Example)
The server responds with a tree of nodes. Each node has a type (the component name), a properties object (props), and children.
{
"protocol_version": "1.0",
"root": {
"id": "screen_root",
"type": "FlexContainer",
"properties": { "direction": "vertical", "padding": 16 },
"children": [
{
"id": "header_title",
"type": "Text",
"properties": {
"content": "Welcome Back",
"style": "h1",
"color": "#000000"
}
},
{
"id": "action_button",
"type": "Button",
"properties": {
"label": "Click Me",
"action": { "type": "deep_link", "uri": "app://settings" }
}
}
]
}
}
Client-Side Mapping (The Registry)
The client maintains a Registry that maps the string "FlexContainer" or "Text" to native widgets.
- iOS:
FlexContainer maps to UICollectionViewComposableLayout.
- Android:
FlexContainer maps to Compose Column/Row.
- Web:
FlexContainer maps to <div style="display: flex">.
2. Safety: The 3-Layer Shield
The biggest risk in SDUI is the server sending malformed data that crashes the app. We need three layers of defense.
Layer A: Schema Validation (Server-Side)
Never generate JSON manually. Use a strongly typed builder pattern on the backend.
// Backend Kotlin code
fun renderScreen(): ViewNode {
return FlexContainer(
padding = 16,
children = listOf(
Text(id = "title", content = "Hello", style = Style.H1)
)
).toNode() // Serializes to JSON strictly
}
Layer B: Contract Versioning
Clients inevitably lag behind servers. The payload must include a version.
- Request: Client sends
Accept-Version: 1.2.
- Response: Server returns payload compatible with
1.2.
- Rule: If the server wants to use a new component
CoolMap, it must check if the client version supports it. If not, fallback to a Text link.
Layer C: Client-Side Fail-Safes (The "Red Box")
If the client encounters a type it doesn't recognize (e.g., legacy app, new server feature), it renders a Fallback Component instead of crashing.
- Strict Mode (Dev): Crash the app to alert developers.
- Safe Mode (Prod): Render a placeholder (e.g., a gray box with the ID) or simply
null (ignore the node).
// iOS Swift Example
func resolveComponent(type: String, props: JSON) -> View {
switch type {
case "Text": return TextView(props)
case "Image": return ImageView(props)
default:
log.warning("Unknown component: \(type)")
return FallbackView(id: props["id"]) // Safety!
}
}
3. Diffing: Minimizing Payloads
Sending the entire tree for every small interaction (like typing a character or clicking a button) is wasteful. We need a Diffing Protocol.
State: The "Screen ID"
When the client renders a screen, it holds the current state in memory. When it requests an update (pagination, refresh), it sends a context_id or state_hash.
Strategy A: JSON Patch (RFC 6902)
Instead of sending the full tree, the server sends a list of operations.
Request: User scrolls to bottom.
Response:
{
"ops": [
{
"op": "add",
"path": "/root/children/-",
"value": { "type": "Text", "properties": { "content": "Item 20" } }
}
]
}
Strategy B: Fragment Replacement (Simpler)
Assign unique IDs to every node. The server sends a "Patch" payload replacing specific IDs.
Server Response:
{
"patches": [
{
"op": "replace",
"target_id": "header_title",
"node": {
"type": "Text",
"properties": { "content": "Updated Title" }
}
}
]
}
Optimization: Stable IDs
To perform animations (insert/delete rows) effectively, your diff algorithm must rely on Stable IDs, not array indices.
- Client: Uses an algorithm like Heckel's Algorithm or simply compares old list vs. new list based on IDs to dispatch
Insert(20), Delete(5) animations.
4. Interactivity & Logic
A static UI is easy. Handling logic (e.g., "Disable button if text is empty") is hard.
Level 1: Server Roundtrip (Safe, Slow)
Every button click sends a request to the server. The server returns a new tree or a patch.
- Pros: Maximum logic control.
- Cons: High latency.
Level 2: Local Actions (Fast)
The server defines "Intents" that the client can execute without network calls.
"action": {
"type": "local_toggle",
"target_id": "hidden_section",
"animation": "fade"
}
The client simply toggles the visibility of the node with id="hidden_section" locally.
Level 3: Bound Variables (Complex)
The server sends a generic "state" blob. The UI binds to it.
- Server:
{ "state": { "is_valid": false } }
- UI:
Button(enabled: bind("is_valid"))
- Action:
TextInput(onChange: update_local_state("is_valid", true))
5. Implementation Checklist
- Naming Convention: strictly namespaced types (e.g.,
myApp.Header vs System.Header).
- Assets: Never send image binaries. Send URLs (
https://cdn.../img.png) or local asset references (asset://icon_chevron).
- Analytics: The server should embed tracking metadata in the nodes.
"meta": { "impression_id": "abc-123", "click_id": "xyz" }
- Security: Sanitize all text input to prevent injection attacks (if using WebView bridges) or parsing crashes.
Summary Architecture
- Server acts as the "Frontend without a Head." It defines the UI structure.
- Protocol is a JSON AST of primitive components.
- Client is a "Virtual Machine" that maps AST to Native Views.
- Diffing updates the UI via JSON Patches or Fragment Replacement to save bandwidth.
- Safety ensures unknown components render as placeholders, not crashes.