An app document drawn with your own components

Use Surfaces UI's documents, their checks, the agent prompts and the runtime with a component library of your own, and install none of ours. Two packages do it:

  • @surfaces-ui/document has no React: defineCatalog, the page and app documents, validateApp, catalogPrompt and appAgentPrompt.
  • @surfaces-ui/runtime draws a document in React with the renderers you give it. It has no components of its own: navigation and the theme are yours to draw.

@surfaces-ui/spec is those two plus this library's catalogs and renderers. This recipe does not import it, or @surfaces-ui/components.

The catalog is what an agent is told and what every document is checked against: a description, the props, and a valid example for each component. The value schemas (dynamicString, dataBinding, action, childList) are what let a prop be a literal, a binding or a function call:

catalog.ts:

ts
import { action, childList, dataBinding, defineCatalog, dynamicString } from "@surfaces-ui/document";
import { z } from "zod";

/**
 * A team's own catalog: six components, none of them from Surfaces UI. Each entry is what an agent is told (the
 * description), what is checked (the props) and a valid example, which the prompt and the docs are generated from.
 */
export const acmeCatalog = defineCatalog({
  id: "urn:acme:catalog:v1",
  title: "Acme",
  description: "Acme's own components: a stack, headings and text, a text box, a button and a link.",
  components: {
    Stack: {
      description: "Lays its children out one under another.",
      props: { children: childList },
      example: { id: "root", component: "Stack", children: ["title"] },
    },
    Title: {
      description: "The heading of a page.",
      props: { text: dynamicString },
      example: { id: "title", component: "Title", text: "Tickets" },
    },
    Words: {
      description: "A paragraph of plain text.",
      props: { text: dynamicString },
      example: { id: "words", component: "Words", text: { "@path": "/app/owner" } },
    },
    Entry: {
      description: "A labelled text box. What the person types is written to `value`.",
      props: { label: z.string(), value: dataBinding },
      example: { id: "owner", component: "Entry", label: "Owner", value: { "@path": "/app/owner" } },
    },
    Press: {
      description: "A button. Its action is an event sent back to you, or a function that acts, such as `navigate` or `setValue`.",
      props: { label: z.string(), action },
      events: { press: { description: "When pressed. Carries only the context declared in the action." } },
      example: { id: "open", component: "Press", label: "Open ticket 7", action: { functionCall: { "@call": "navigate", args: { to: "/tickets/[id]", values: { id: "7" } } } } },
    },
    Jump: {
      description: "A link to another route of the app.",
      props: { text: dynamicString, to: z.string().startsWith("/") },
      example: { id: "back", component: "Jump", text: "All tickets", to: "/" },
    },
  },
});

A renderer per component, in plain HTML here; yours would return your own components. props are already checked and resolved, component is what the document wrote. The app's navigation is drawn by acmeNav, a document's theme request reaches AcmeTheme, which maps it onto the team's own variables, and Press and Entry draw what an operation's server said. The shell says a success in a live region of its own; a refusal is the control's to say, so Press shows it as an alert (useRunState) and Entry shows the server's words beside the value it refused and takes focus (useRunFieldError). A button that draws neither leaves a person with no word of a refusal:

renderers.tsx:

tsx
import { type AppNavProps, type ComponentRenderer, type ThemeScopeProps, useAppLinks, useRunFieldError, useRunState } from "@surfaces-ui/runtime";
import { type CSSProperties, useEffect, useRef } from "react";

const words = (value: unknown) => (value == null ? "" : String(value));

/** A link to a route: the app says what address to show and how to go there in place. */
function Jump({ text, to }: { text: string; to: string }) {
  const links = useAppLinks();
  return (
    <a
      href={links ? links.href(to) : to}
      onClick={(event) => {
        if (!links || event.metaKey || event.ctrlKey) return;
        event.preventDefault();
        links.go(to);
      }}
    >
      {text}
    </a>
  );
}

const pathOf = (value: unknown) => (value && typeof value === "object" && "@path" in value ? String(value["@path"]) : undefined);

/**
 * A text box. When an operation was refused because of the value read from here, the server's words are shown
 * beside it (`useRunFieldError`), and the first one the server named takes focus.
 */
function Entry({ id, label, value, path, change }: { id: string; label: string; value: string; path?: string; change(value: string): void }) {
  const refused = useRunFieldError(path);
  const input = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (refused.first) input.current?.focus();
  }, [refused.first, refused.at]);
  return (
    <div className="acme-entry">
      <label>
        {label}
        <input ref={input} value={value} onChange={(event) => change(event.target.value)} aria-invalid={refused.message ? true : undefined} aria-describedby={refused.message ? `${id}-error` : undefined} />
      </label>
      {refused.message && <span id={`${id}-error`}>{refused.message}</span>}
    </div>
  );
}

/**
 * A button. When it runs an operation, the shell says a success in its own live region; a refusal is the button's
 * to say (`useRunState`), or a person would hear nothing.
 */
function Press({ id, label, press }: { id: string; label: string; press(): void }) {
  const { state, reread } = useRunState(id);
  const working = state?.status === "running" || state?.status === "approving";
  return (
    <>
      <button type="button" aria-disabled={working || undefined} onClick={press}>
        {working ? `${label} (working)` : label}
      </button>
      {state && ["invalid", "refused", "stale", "failed"].includes(state.status) && <p role="alert">{state.message}</p>}
      {reread && (
        <button type="button" onClick={reread}>
          Read again
        </button>
      )}
    </>
  );
}

/** Plain HTML for each component of the catalog. A renderer is given props that were already checked and resolved. */
export const acmeRenderers: Record<string, ComponentRenderer> = {
  // A container is given its children as the document wrote them (`component`), and asks the runtime to draw them.
  Stack: ({ component, children }) => <div className="acme-stack">{children(component.children)}</div>,
  Title: ({ props }) => <h1>{words(props.text)}</h1>,
  Words: ({ props }) => <p>{words(props.text)}</p>,
  Entry: ({ props, component, setData }) => (
    <Entry label={words(props.label)} value={words(props.value)} path={pathOf(component.value)} id={component.id} change={(value) => setData(component.value, value)} />
  ),
  Press: ({ props, component, dispatch }) => <Press id={component.id} label={words(props.label)} press={() => dispatch(component.action)} />,
  Jump: ({ props }) => <Jump text={words(props.text)} to={words(props.to)} />,
};

/** The app's navigation, drawn the team's own way. */
export function acmeNav({ title, items, go }: AppNavProps) {
  return (
    <nav aria-label={title} className="acme-nav">
      {items.map((item) => (
        <a
          key={item.to}
          href={item.href}
          aria-current={item.current ? "page" : undefined}
          onClick={(event) => {
            event.preventDefault();
            go(item.to);
          }}
        >
          {item.label}
        </a>
      ))}
    </nav>
  );
}

/**
 * A document may ask for a look (`theme`). The runtime hands the request over and draws nothing itself: here its
 * accent and corner radius become two of the team's own CSS variables, and the rest of the request is left alone.
 */
export function AcmeTheme({ request, children }: ThemeScopeProps) {
  const style = { "--acme-accent": request.accent, "--acme-radius": request.radius === undefined ? undefined : `${request.radius}px` } as CSSProperties;
  return (
    <div className="acme-theme" style={style}>
      {children}
    </div>
  );
}

The app is one document: three pages on routes, a value they share (/app/owner, kept in the address) and a value read from the address (/@route/id). It holds no code:

app.ts:

ts
import { A2UI_VERSION, type AppDocument, type SurfaceComponent } from "@surfaces-ui/document";
import { acmeCatalog } from "./catalog.js";

const page = (id: string, title: string, components: SurfaceComponent[]) => ({ id, title, catalogId: acmeCatalog.id, a2ui: A2UI_VERSION, components });

/** Two pages, a value they share and a value from the address: an app with no code per screen. */
export const ticketsApp: AppDocument = {
  id: "tickets",
  title: "Tickets",
  catalogId: acmeCatalog.id,
  a2ui: A2UI_VERSION,
  theme: { accent: "#0b6e4f", radius: 2 },
  state: { owner: { type: "string", default: "", keep: "url" } },
  nav: [
    { label: "Tickets", to: "/" },
    { label: "About", to: "/about" },
  ],
  pages: [
    {
      route: "/",
      page: page("list", "Tickets", [
        { id: "root", component: "Stack", children: ["title", "owner", "open"] },
        { id: "title", component: "Title", text: "Tickets" },
        { id: "owner", component: "Entry", label: "Owner", value: { "@path": "/app/owner" } },
        { id: "open", component: "Press", label: "Open ticket 7", action: { functionCall: { "@call": "navigate", args: { to: "/tickets/[id]", values: { id: "7" } } } } },
      ]),
    },
    {
      route: "/tickets/[id]",
      page: page("ticket", "Ticket", [
        { id: "root", component: "Stack", children: ["title", "who", "back"] },
        { id: "title", component: "Title", text: { "@call": "formatString", args: { value: "Ticket ${/@route/id}" } } },
        { id: "who", component: "Words", text: { "@call": "formatString", args: { value: "Owner: ${/app/owner|nobody yet}" } } },
        { id: "back", component: "Jump", text: "All tickets", to: "/" },
      ]),
    },
    {
      route: "/about",
      page: page("about", "About", [
        { id: "root", component: "Stack", children: ["title", "words"] },
        { id: "title", component: "Title", text: "About" },
        { id: "words", component: "Words", text: "Drawn with Acme's own components." },
      ]),
    },
  ],
};

The shell is the only React the app has. validateApp checks the routes, every navigate, each binding and every component against the catalog before anything is drawn:

App.tsx:

tsx
import { validateApp } from "@surfaces-ui/document";
import { AppView, useHashLocation } from "@surfaces-ui/runtime";
import { ticketsApp } from "./app.js";
import { acmeCatalog } from "./catalog.js";
import { AcmeTheme, acmeNav, acmeRenderers } from "./renderers.js";

/** The whole app: one document, the team's catalog and renderers, and the address kept in the hash. */
export function App() {
  const location = useHashLocation();
  const problems = validateApp(ticketsApp, acmeCatalog);
  if (problems.length > 0) return <pre role="alert">{problems.map((p) => `${p.path}: ${p.message}`).join("\n")}</pre>;
  return <AppView app={ticketsApp} catalog={acmeCatalog} renderers={acmeRenderers} nav={acmeNav} themeScope={AcmeTheme} {...location} />;
}

The test draws the app and moves through it, runs an operation from the team's own button against a stand-in backend (a success said once, then a refusal at its field), writes the agent prompts from the catalog (they leave out rules about components the catalog does not have), and bundles the app with Vite to list what is in it: of this repository's packages only document, runtime and trace (which the runtime records to when a recorder is above it), and no module of components, data, icons or spec:

own-components.test.tsx:

tsx
// @vitest-environment jsdom
import path from "node:path";
import { A2UI_VERSION, type AppDocument, appAgentPrompt, catalogPrompt, validateApp } from "@surfaces-ui/document";
import { AppView, RUN_STATUS, type RunOperations } from "@surfaces-ui/runtime";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { build } from "vite";
import { afterEach, describe, expect, it } from "vitest";
import { App } from "./App.js";
import { ticketsApp } from "./app.js";
import { acmeCatalog } from "./catalog.js";
import { acmeRenderers } from "./renderers.js";

afterEach(() => {
  cleanup();
  window.location.hash = "";
});

describe("an app document drawn with a team's own components", () => {
  it("passes validateApp against the team's catalog, and a wrong component is refused by name", () => {
    expect(validateApp(ticketsApp, acmeCatalog)).toEqual([]);
    const wrong = structuredClone(ticketsApp);
    (wrong.pages[2] as { page: { components: { component: string }[] } }).page.components[1]!.component = "Chart";
    expect(validateApp(wrong, acmeCatalog).map((p) => p.message).join(" ")).toMatch(/Chart/);
  });

  it("draws the page on the route with plain HTML, shares a value between pages and reads one from the address", async () => {
    render(<App />);
    expect(screen.getByRole("heading", { name: "Tickets" })).toBeTruthy();
    // The team's own navigation, with the current page marked.
    expect(screen.getByRole("link", { name: "Tickets" }).getAttribute("aria-current")).toBe("page");
    // The document's theme request reached the team's own theme scope.
    expect(document.querySelector<HTMLElement>(".acme-theme")!.style.getPropertyValue("--acme-accent")).toBe("#0b6e4f");

    fireEvent.change(screen.getByLabelText("Owner"), { target: { value: "Ada" } });
    // A value declared keep: "url" goes into the address.
    await waitFor(() => expect(window.location.hash).toBe("#/?owner=Ada"));

    fireEvent.click(screen.getByRole("button", { name: "Open ticket 7" }));
    await waitFor(() => expect(screen.getByRole("heading", { name: "Ticket 7" })).toBeTruthy());
    expect(screen.getByText("Owner: Ada")).toBeTruthy();
    expect(window.location.hash).toBe("#/tickets/7?owner=Ada");

    fireEvent.click(screen.getByRole("link", { name: "About" }));
    await waitFor(() => expect(screen.getByText("Drawn with Acme's own components.")).toBeTruthy());
    // Nothing of Surfaces UI's own look is on the page: no SideNav, no component class of ours inside the surface.
    expect(document.querySelector(".sf-sidenav, [class^='sf-a2-']")).toBeNull();
  });

  it("runs an operation from the team's own button, and the team's own inputs show what the server refused", async () => {
    const notes: AppDocument = {
      id: "notes",
      title: "Notes",
      catalogId: acmeCatalog.id,
      a2ui: A2UI_VERSION,
      operations: ["add-note"],
      pages: [
        {
          route: "/",
          page: {
            id: "home",
            title: "Add a note",
            catalogId: acmeCatalog.id,
            a2ui: A2UI_VERSION,
            data: { order: "", note: "" },
            components: [
              { id: "root", component: "Stack", children: ["order", "note", "add"] },
              { id: "order", component: "Entry", label: "Order", value: { "@path": "/order" } },
              { id: "note", component: "Entry", label: "Note", value: { "@path": "/note" } },
              { id: "add", component: "Press", label: "Add note", action: { functionCall: { "@call": "run", args: { operation: "add-note", args: { order_id: { "@path": "/order" }, note: { "@path": "/note" } }, then: { "@call": "setValue", args: { path: "/note", value: "" } } } } } },
            ],
          },
        },
      ],
    };
    expect(validateApp(notes, acmeCatalog, { operations: [{ id: "add-note", args: [{ name: "order_id", required: true }, { name: "note", required: true }] }] })).toEqual([]);
    // The team's backend: a number is an order, anything else is refused at its field.
    const operations: RunOperations = {
      getOperation: async () => ({ operation: { title: "Add note", refreshes: [] } }),
      run: async ({ args }) =>
        /^\d+$/.test(String(args.order_id))
          ? { status: RUN_STATUS.done, message: "Note added.", errors: [], affected: 1, skipped: [], runId: "r1" }
          : { status: RUN_STATUS.invalid, message: "Nothing ran. Fix the fields marked.", errors: [{ field: "order_id", message: "Enter a number." }], affected: 0, skipped: [], runId: "r2" },
    };
    render(<AppView app={notes} catalog={acmeCatalog} renderers={acmeRenderers} location="/" onNavigate={() => {}} storage={null} operations={operations} />);
    const live = () => document.querySelector(".sf-app-live")!.textContent!.trim();

    fireEvent.change(screen.getByLabelText("Order"), { target: { value: "1042" } });
    fireEvent.change(screen.getByLabelText("Note"), { target: { value: "Called back" } });
    fireEvent.click(screen.getByRole("button", { name: "Add note" }));
    await waitFor(() => expect(live()).toBe("Note added."));
    // `then` cleared the note.
    expect((screen.getByLabelText("Note") as HTMLInputElement).value).toBe("");

    fireEvent.change(screen.getByLabelText("Order"), { target: { value: "abc" } });
    fireEvent.change(screen.getByLabelText("Note"), { target: { value: "Wrong order" } });
    fireEvent.click(screen.getByRole("button", { name: "Add note" }));
    expect((await screen.findByRole("alert")).textContent).toBe("Nothing ran. Fix the fields marked.");
    const order = screen.getByLabelText("Order");
    expect(order.getAttribute("aria-invalid")).toBe("true");
    expect(document.getElementById(order.getAttribute("aria-describedby")!)!.textContent).toBe("Enter a number.");
    expect(document.activeElement).toBe(order);
    // The shell no longer says the earlier "Note added.", and the note was kept to be sent again.
    expect(live()).toBe("");
    expect((screen.getByLabelText("Note") as HTMLInputElement).value).toBe("Wrong order");
  });

  it("writes agent prompts from the team's catalog alone", () => {
    const prompt = catalogPrompt(acmeCatalog);
    for (const name of acmeCatalog.names) expect(prompt).toContain(`### ${name}`);
    // Rules about components this catalog does not have are left out.
    expect(prompt).not.toMatch(/DataGrid|`Form`|SQL|charts/);
    const app = appAgentPrompt(acmeCatalog, { example: ticketsApp });
    expect(app).toContain("`write_app`");
    expect(app).toContain('"component":"Jump"');
    expect(app).not.toMatch(/DataGrid|FilterBar/);
  });

  it("bundles with no module of @surfaces-ui/components, data, icons or spec", async () => {
    const here = import.meta.dirname;
    const result = await build({
      configFile: false,
      root: here,
      logLevel: "silent",
      define: { "process.env.NODE_ENV": '"production"' },
      build: { write: false, minify: true, lib: { entry: path.join(here, "main.tsx"), formats: ["es"], fileName: "app" }, rollupOptions: { output: { inlineDynamicImports: true } } },
    });
    const output = (Array.isArray(result) ? result : [result]).flatMap((r) => ("output" in r ? r.output : []));
    const chunks = output.filter((item) => item.type === "chunk");
    const modules = chunks.flatMap((chunk) => Object.keys(chunk.modules)).map((id) => id.replace(/\\/g, "/"));
    const ours = [...new Set(modules.map((id) => /\/packages\/([^/]+)\//.exec(id)?.[1]).filter(Boolean))].sort();
    // Exactly these packages of this repository are in the bundle.
    expect(ours).toEqual(["document", "runtime", "trace"]);
    expect(modules.filter((id) => /codemirror|echarts|apache-arrow|@surfaces-ui\/(components|data|icons|spec|proto)/.test(id))).toEqual([]);
    const bytes = chunks.reduce((sum, chunk) => sum + Buffer.byteLength(chunk.code), 0);
    // React and react-dom are most of it; components alone would add over a megabyte.
    expect(bytes).toBeLessThan(600_000);
  }, 120_000);
});

Measured on 5 December 2026 with packed copies of the packages (pnpm pack) installed alone in an empty project with npm, where node_modules/@surfaces-ui held document, runtime, tokens and trace and nothing else: the built app is 401 KB minified (120 KB gzipped), 75 modules. By source size, react-dom is 60% of it, zod 29%, document 4%, runtime 3%; no module of tokens is in it, since this app edits no page. It ran in Chromium at desktop and phone width with no console errors and no axe WCAG 2.2 AA violations on its three pages. For scale, @surfaces-ui/spec/react with every renderer is 3.0 MB minified (813 KB gzipped) before React.

Not in these two packages: arranging a page by hand (useArrange), JSX markup that draws (createMarkup), and the analytics and site catalogs. They are in @surfaces-ui/spec.

Source and test: apps/recipes/src/own-components