Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Build a server-driven UI layer: components, schema, and safety.

  1. User

    Build a server-driven UI layer: components, schema, and safety.

  2. GLM Assistant

    The user wants a "server-driven UI layer" built. This is a broad request, so I need to structure the response to cover the essential components of a robust SDUI system: the schema definition, the server-side implementation, the client-side parsing and rendering, and safety/error handling mechanisms.

    1. Conceptualizing Server-Driven UI (SDUI):

    • Core Idea: The server sends data describing the UI (JSON usually), and the client renders it. This allows updating the UI without app store releases.
    • Key Components:
      • Schema: The contract between server and client (e.g., "Card", "List", "Text").
      • Server: The logic that constructs the response based on business logic.
      • Client: The engine that parses the schema and maps it to native components (React, Swift, Kotlin).
      • Safety: Handling unknown types, versioning, and validation.

    2. Structuring the Response: I'll break this down into four distinct layers:

    • Layer 1: The Schema (The Contract): Defining what the JSON looks like.
    • Layer 2: The Server (The Composer): How to build the JSON (using Node/TypeScript as an example).
    • Layer 3: The Client (The Renderer): How to consume the JSON (using React as a generic example).
    • Layer 4: Safety & Robustness: Error boundaries, versioning, and validation.

    3. Drafting Layer 1: The Schema

    • Format: JSON.
    • Structure: Need a root container, a list of components, and specific component properties.
    • Example: A "Hero" component and a "Button" component.
    • Validation: JSON Schema is a good mention here.

    4. Drafting Layer 2: The Server

    • Tech Stack: Node.js/TypeScript is the most readable and universal for this explanation.
    • Logic: A controller that returns a hardcoded (or logic-driven) UI tree.
    • Abstraction: We shouldn't just return raw JSON manually every time; a helper function or a UI Builder class makes it cleaner. Let's keep it simple: an endpoint returning the JSON.

    5. Drafting Layer 3: The Client

    • Tech Stack: React is the best choice for illustrating component mapping.
    • Component Registry: The core concept of SDUI clients. A dictionary/map where keys (component types) map to actual React components.
    • Recursive Rendering: The renderer needs to handle nested components (children).
    • The "Renderer" Component: A generic component that takes a JSON node and looks it up in the registry.

    6. Drafting Layer 4: Safety & Reliability (Crucial)

    • This is what separates a toy example from production code.
    • Unknown Types: What happens if the server sends "Carousel" but the app is old and doesn't have it? -> Fallback/Placeholder component.
    • Missing Properties: Default props.
    • Versioning: Schema versioning (e.g., min_version).
    • Analytics: Tracking what is rendered.

    7. Refining the Content (Self-Correction during drafting):

    • Initial thought: Just write code.
    • Correction: The prompt asks for "components, schema, and safety." I need to explain the architecture, not just dump code. I should explain why we are doing each step.
    • Type Safety: I should use TypeScript interfaces for the schema to demonstrate type safety on the server side.

    8. Final Code Structure Plan:

    • Schema Definition (TS Interfaces): UIComponent, TextProps, ContainerProps.
    • Server-Side (Node/Express):
      • An endpoint /api/ui.
      • Data construction.
    • Client-Side (React):
      • ComponentRegistry: Map<string, React.Component>.
      • ServerDrivenRenderer: The logic to pick component.
      • FallbackComponent: For safety.
    • Safety Section: Explicit points on validation, backward compatibility, and error boundaries.

    9. Writing the content:

    • Schema: Keep it flat or tree-based? Tree-based is standard. type field is essential. props field separates data from config.
    • Server: Simple mock data is fine.
    • Client: React.createElement is technically what ServerDrivenRenderer does, but mapping to a component variable is more readable for modern React users. I will use a component map approach.

    10. Review against constraints:

    • Did I cover components? Yes.
    • Did I cover schema? Yes.
    • Did I cover safety? Yes.

    11. Final Polish: Add comments explaining the code blocks. Use clear headings. (Proceeding to generate output based on this structure).

    (Self-Correction during code generation): Make sure to handle the recursive rendering case. If a Container has children, the Renderer must call itself.

    Let's write it out.

    • Schema: BaseComponent, Container, Text, Image.
    • Server: Express route returning JSON.
    • Client: Renderer component checking a componentMap.
    • Safety: try/catch in renderer, if (!Component) return Fallback.

    This looks solid. I will structure the answer clearly with these steps. Building a Server-Driven UI (SDUI) layer involves three pillars: a Schema (the contract), a Server (the composer), and a Client (the renderer).

    Here is a comprehensive guide to building a type-safe, scalable SDUI system using a generic JSON Schema approach.


    1. The Schema (The Contract)

    The most critical part of SDUI is the contract. Avoid sending raw HTML or strictly platform-specific code. Instead, send abstract components.

    We define a generic structure where every node has:

    1. type: The component identifier (e.g., hero_card, list).
    2. props: The data required to render that component (image URLs, text, colors).
    3. children: Nested nodes (optional).

    TypeScript Definitions (Shared between Server & Client)

    // Base interface for all components
    interface BaseComponent {
      type: string;
      id?: string; // Useful for analytics and diffing
      children?: UI_tree;
      props?: Record<string, any>;
    }
    
    // The root response from the server
    interface SDUIResponse {
      version: string; // Schema version for backward compatibility
      root: UI_tree;
    }
    
    type UI_tree = BaseComponent | BaseComponent[];
    

    2. The Server (The Composer)

    The server determines what the user should see based on business logic (user role, A/B tests, feature flags). It constructs the JSON tree.

    Example: Node.js / Express

    import express from 'express';
    const app = express();
    
    // Mock Database of UI Definitions
    const getHomeScreen = (user: string) => {
      return {
        version: "1.0",
        root: {
          type: "scroll_view",
          id: "home_root",
          children: [
            {
              type: "header",
              props: { title: `Welcome back, ${user}`, style: "bold" }
            },
            {
              type: "hero_card",
              id: "promo-banner",
              props: {
                imageUrl: "https://example.com/promo.jpg",
                ctaText: "Buy Now",
                action: { type: "deep_link", url: "app://promo/123" }
              }
            },
            {
              type: "list",
              props: { orientation: "vertical" },
              // Dynamically generated children
              children: [
                { type: "list_item", props: { text: "Settings" } },
                { type: "list_item", props: { text: "Logout" } }
              ]
            }
          ]
        }
      };
    };
    
    app.get('/api/ui/home', (req, res) => {
      const user = req.headers['x-user-id'] || 'Guest';
      
      // Logic: If user is admin, inject an extra admin panel
      const response = getHomeScreen(String(user));
      
      if (user === 'admin') {
        response.root.children.unshift({
          type: "admin_banner",
          props: { alert: "New tickets pending" }
        });
      }
    
      res.json(response);
    });
    
    app.listen(3000);
    

    3. The Client (The Renderer)

    The client is "dumb." It does not make layout decisions; it simply maps the type string to a native UI component.

    We use a Component Registry pattern. This decouples the parsing logic from the UI implementation.

    React Implementation

    import React from 'react';
    
    // 1. The Registry Map
    // Maps schema 'type' strings to actual React components
    const ComponentRegistry: Record<string, React.FC<any>> = {
      scroll_view: ({ children, ...props }) => <div style={{ overflowY: 'auto', height: '100vh' }} {...props}>{children}</div>,
      header: ({ title, style }) => <h1 style={{ fontWeight: style === 'bold' ? 'bold' : 'normal' }}>{title}</h1>,
      hero_card: ({ imageUrl, ctaText, action }) => (
        <div className="card" onClick={() => console.log("Action:", action)}>
          <img src={imageUrl} alt="Hero" style={{ width: '100%' }} />
          <button>{ctaText}</button>
        </div>
      ),
      list: ({ children, orientation }) => (
        <div style={{ display: 'flex', flexDirection: orientation === 'horizontal' ? 'row' : 'column' }}>
          {children}
        </div>
      ),
      list_item: ({ text }) => <div className="item">{text}</div>,
      admin_banner: ({ alert }) => <div style={{ background: 'red', color: 'white' }}>{alert}</div>
    };
    
    // 2. The Recursive Renderer
    // This component traverses the JSON tree
    const UIDecoder: React.FC<{ node: any }> = ({ node }) => {
      // Safety: Handle null/undefined nodes
      if (!node) return null;
    
      // If it's an array, map over it
      if (Array.isArray(node)) {
        return <>{node.map((child, i) => <UIDecoder key={child.id || i} node={child} />)}</>;
      }
    
      const Component = ComponentRegistry[node.type];
    
      // Safety: Handle unknown component types
      if (!Component) {
        console.warn(`Unknown component type: ${node.type}`);
        return <div style={{ color: 'red', border: '1px dashed red' }}>Unknown Type: {node.type}</div>;
      }
    
      // Recursively render children
      const { children, ...props } = node;
    
      return (
        <Component {...props}>
          {children ? <UIDecoder node={children} /> : null}
        </Component>
      );
    };
    
    // 3. Usage in App
    export default function App() {
      const [uiTree, setUiTree] = React.useState(null);
    
      React.useEffect(() => {
        fetch('http://localhost:3000/api/ui/home')
          .then(res => res.json())
          .then(data => setUiTree(data.root));
      }, []);
    
      if (!uiTree) return <div>Loading...</div>;
    
      return <UIDecoder node={uiTree} />;
    }
    

    4. Safety & Robustness

    In production, you cannot trust the server output blindly. Here is how to harden the layer:

    A. Schema Validation (Server-Side)

    Ensure the server never sends malformed JSON. Use a library like zod or ajv.

    import { z } from 'zod';
    
    const ActionSchema = z.object({
      type: z.enum(['deep_link', 'api_call']),
      url: z.string().url()
    });
    
    const ComponentSchema: z.ZodType<any> = z.lazy(() => z.object({
      type: z.string(),
      id: z.string().optional(),
      props: z.record(z.any()).optional(),
      children: z.union([ComponentSchema, z.array(ComponentSchema)]).optional()
    }));
    
    // Usage before sending response
    const safeResponse = ComponentSchema.parse(response.root);
    

    B. Client-Side Fallbacks

    1. Unknown Types: If the server sends type: "new_feature" but the user hasn't updated their app yet, the client should render null or a placeholder (as shown in the UIDecoder), preventing the app from crashing.
    2. Versioning:
      • Hard Versioning: The client sends X-Client-Version: 3. The server ensures it only returns components supported in v3.
      • Soft Versioning: The response includes min_client_version. The client checks this and ignores blocks it cannot render.

    C. Payload Size

    JSON can get large.

    1. Compression: Use Gzip/Brotli on your HTTP server.
    2. References: If passing large datasets (e.g., a list of 100 products), pass the data separately in a data key and reference it by ID in the UI tree to avoid repeating property keys.

    D. Security

    Never send raw HTML or executable strings.

    • Bad: { "type": "html", "content": "<script>stealCookies()</script>" }
    • Good: { "type": "text", "content": "Safe Text" } The client controls the rendering tags (e.g., <span>{content}</span>), which automatically sanitizes the input.

    Summary

    This architecture allows you to change the layout, swap component order, or add new features (by updating the server and ensuring the client has the corresponding component) without releasing a new native app binary.

    1. Server builds the tree.
    2. Client maps strings to components.
    3. Schema ensures they speak the same language.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.