The user wants a design for a Server-Driven UI (SDUI) protocol.
Key components requested are:
Templates: How to define the UI structure on the server.
Diffing: How to efficiently update the UI without sending the whole tree every time.
Safety: How to ensure the client doesn't crash or execute malicious code, and handling versioning/compatibility.
1. High-Level Philosophy:
Client: Dumb views, smart logic (sort of). The client is a rendering engine. It knows how to draw a "Card," a "List," an "Image," etc., but doesn't know what to draw until the server tells it.
Server: The source of truth for layout, content, and flow.
Protocol: Needs to be serialization format agnostic (JSON/Protobuf) but assumes strong typing.
2. Part 1: Templates (The "What")
Concept: We need a way to describe UI nodes.
Approach: A Component-based tree structure.
Core Elements:
type: What component is it? (e.g., HeroBanner, ListItem).
properties: The data (title, image_url, color).
children: Nested components.
actions: What happens on click? (URL, deeplink, event tracking).
Layout System: Flexbox (via Yoga or similar) is the industry standard for cross-platform layout. Let's abstract it into a style object.
Template vs. Data: Should we separate them?
Option A: Send full tree every time. (Easiest, but heavy).
Option B: Send generic templates + data bindings. (Efficient, reusable).
Decision: I'll propose a "Hybrid Component Model." The server sends specific component types, but internally the server might use templates to generate these responses. For the protocol itself, the "Template" is usually the definition of the available components the client knows how to render.
Refinement: Let's define the Schema of the payload. It's a tree of UIElement.
3. Part 2: Diffing (The "Update")
Problem: Bandwidth and latency. Redrawing the whole screen causes flicker and high data usage.
Approaches:
HTTP ETag / Last-Modified: Good for caching, but not granular updates within a screen.
JSON-Patch (RFC 6902): Standard, but heavy for large trees.
State Synchronization: Client sends state, server returns new tree. (Simple, but high bandwidth).
Virtual DOM / Tree Diffing (Server-side): Server calculates the diff and sends Patch operations.
ID-based targeting: Every node needs a stable ID.
Decision: I'll propose a Patch-based Protocol.
The initial load sends the full Tree.
Subsequent updates (via WebSockets, SSE, or polling) send a list of Operations (Insert, Update, Delete, Move).
Requires stable IDs (uid) for every node.
4. Part 3: Safety (The "Guardrails")
Problem: Bad data, unsupported versions, malicious scripts.
Versioning:
Client sends X-Client-Version or X-Schema-Version.
Server must respond with compatible components.
Fallbacks: If the server sends NewCoolComponent and the client is old, the client should ignore it or render a fallback (EmptyView).
Type Safety:
Strict contracts. Protocol Buffers (Protobuf) are better than JSON for this, but JSON is easier to explain. I'll assume JSON for readability but mention code generation.
Required vs Optional fields.
Visual Safety:
Limiting image sizes.
Sanitizing text inputs (prevent XSS if there's a WebView).
Avoiding infinite loops in lists.
Performance Safety:
Max depth of tree.
Max number of nodes.
5. Structuring the Response:
I will structure the design document into logical sections:
Core Architecture: The relationship between Client and Server.
The Data Model (Templates): JSON Schema definition.
The Communication Protocol (Diffing): How updates work.
Safety & Resilience: Handling errors and versions.
Example Workflow: A concrete walkthrough.
Drafting the Content - Iteration details:
The Template: Let's make the distinction between "Abstract Template" (reusable) and "Concrete Instance" (what is sent). Actually, in SDUI, usually the server sends the rendered tree. However, to support "Diffing" effectively, we need a way to reference parts of the tree. Let's introduce id fields.
Diffing Logic:
Scenario: User likes an item.
Client: Sends POST /action { type: "like", element_id: "123" }.
Server Response: Instead of full page JSON, returns { diff: [ { op: "update", id: "123", props: { "is_liked": true } } ] }.
Safety:
Unknown Keys: Client must ignore keys it doesn't understand (Robustness Principle).
Missing Keys: Default values must exist.
WebView: If a component is a WebView, the server shouldn't send arbitrary HTML if possible, or the client must sanitize it heavily. Better to use native components.
Refining the "Template" aspect:
Often, "Server Driven UI" implies the server sends a tree of Components.
Example:
This is the standard approach.
However, some systems (like Airbnb's) define "Sections" (Templates) and "Items" (Data).
I will stick to the Component Tree approach (like SwiftUI/Jetpack Compose but serialized) as it's more flexible for Diffing.
Let's refine the Diffing part.
To diff, you need identity.
If I have a list of 3 items, and one is inserted in the middle, how do I know?
Approach 1: Index-based diffing (React style). Hard to do over network.
Approach 2: Key-based diffing (IDs). Every node has a UUID.
Decision:IDs are mandatory.
Let's write the response.
Designing a Server-Driven UI (SDUI) protocol requires balancing flexibility for the server with stability and performance on the client. The goal is to move the logic of presentation to the backend while the client remains a generic rendering engine.
Here is a comprehensive design for an SDUI protocol, focusing on Component Templates, Tree Diffing, and Runtime Safety.
1. Core Architecture: The Generic Tree
The fundamental unit of the protocol is a tree structure. The server does not send HTML or XML; it sends a serialization of a component tree.
The Schema (JSON Example)
The protocol defines a Node. Every node has:
type: The component identifier (e.g., Container, Text, Button).
id: A unique identifier for diffing and event targeting.
properties: Strongly typed data inputs for the component.
Sending full trees for every screen request is bandwidth-heavy and makes the server code verbose. We introduce a Template Registry pattern.
Concept
The server maintains a registry of reusable layouts (e.g., ProductCard, StoryCarousel). The response payload can reference these templates and inject data into them.
Protocol Extension
Client Handshake: On app launch, the client sends supported_templates: ["card_v1", "list_v2"].
Response Structure:
templates: Definitions of the structure (cached by client).
data: The specific content to inject into the template slots.
The biggest risk in SDUI is the server crashing the app (e.g., sending a String to an Integer prop) or executing malicious logic.
A. Schema Validation (The Contract)
The Client acts as the strict enforcer.
Component Registry: The client defines the valid types (e.g., Text, Image).
Property Schema: The client defines strict types for properties.
If the server sends Text but provides an Integer for the value property, the client must not crash. It should either cast safely, render a placeholder, or log a non-fatal error.
B. The "Sandbox" Principle
The server should never be able to execute arbitrary code on the client.
No eval(): The protocol must not support raw JavaScript or native code strings.
Action Whitelisting: The client defines a finite list of capabilities (Actions).
navigate_to: (DeepLink)
http_request: (REST call)
log_event: (Analytics)
show_toast: (UI Notification)
Action Execution: When an action is triggered, the client resolves it. The server only says what to do, not how to do it.
C. Versioning Compatibility
What happens if the server sends a component the app doesn't support yet?
Fallback Nodes: The schema supports a fallback field.
json
{
"type": "FancyNewButton", // Client < v2.0 doesn't know this
"fallback": {
"type": "StandardButton", // Client v1.0 knows this
"properties": { "text": "Click Me" }
}
}
If no fallback is provided and the type is unknown, the client renders a generic "Unsupported Content" placeholder.
D. Async Resource Safety
UI trees often reference external resources (images/fonts).
Protocol: Resources are URLs, not blobs.
Client Safety: The client must enforce timeouts and cache policies so a bad URL doesn't hang the UI thread.
5. Full Lifecycle Summary
Handshake: Client sends SupportedSchemas: [1.0, 1.1] and Capabilities: [deeplinks, http].
Initial Load: Server sends full Tree JSON. Client parses, validates types (rejecting unknown nodes), and renders.
Interaction: User taps button. Action object triggers a request to Server.
Diff: Server responds with Patch. Client applies changes to the specific IDs. Animations occur automatically on property change (e.g., color fade).
Failure: If a property type is wrong, Client discards the property update but keeps the node alive.
This design ensures the Server has total control over the layout without compromising the stability of the Client application.