Generate a whole app with Claude
Have Claude write a whole app, several pages with navigation, a list that opens each record, shared filters and forms, as one AppDocument, and run it with no code per screen. The document is JSON: you can save it, review it, change it by hand, or ask Claude to change it.
How it fits together:
appAgentPrompt(catalog, options)from@surfaces-ui/specis the system prompt: the app format (routes,/appstate,/@routevalues,navigate, a grid row that opens a record), a worked example that itself passes the checks, and the catalog.components: commonAnalyticsComponentswrites the common components in full and lists the rest, which Claude reads withcomponent_docswhen it needs one.appToolfrom@surfaces-ui/agentis thewrite_apptool. It runs your check (parseApp, thenvalidateApp, thenvalidateAppDataagainst the data), and when the app has problems it returns every one to Claude as the tool's error: a link to a route that does not exist, a route value it does not give, a binding to state it never declared, a component the catalog refuses, and from the data: a source that is not there, SQL that fails, a column its query does not have, with the columns it does. Claude fixes them and sends the app again in the same turn. Only an app with no problems reachesonApp.dataToolsgives Claudelist_tablesanddescribe_table(names, types and keys, never values), so the SQL it writes uses real tables and columns.
The agent:
agent.ts:
import Anthropic from "@anthropic-ai/sdk";
import { type AgentBackend, appTool, componentDocsTool, dataTools } from "@surfaces-ui/agent";
import { type Effort, anthropicAgent } from "@surfaces-ui/agent-anthropic";
import type { DataSource } from "@surfaces-ui/data";
import { type AppDocument, analyticsCatalog, appAgentPrompt, commonAnalyticsComponents, componentDocs, parseApp, validateApp, validateAppData } from "@surfaces-ui/spec";
/**
* Every problem in an app the model sent: its shape first, then routes, links, bindings and each component, and
* only when those pass, the data: a source that is not there, SQL that fails, a column its query does not have.
*/
export async function appProblems(app: unknown, dataSource: DataSource) {
const parsed = parseApp(app);
if ("problems" in parsed) return parsed.problems;
const problems = validateApp(parsed.app, analyticsCatalog);
return problems.length > 0 ? problems : (await validateAppData(parsed.app, analyticsCatalog, dataSource)).problems;
}
export interface AppAgentOptions {
/** Default `claude-sonnet-5-5`. */
model?: string;
effort?: Effort;
/** The sources the model may look at. Default: every source. */
sourceIds?: string[];
/** Model calls in one turn before it is stopped. Default 8. */
maxSteps?: number;
/** Told of every `write_app` call and the problems it had (none when the app was kept). */
onCheck?(problems: { path: string; message: string }[]): void;
}
/**
* Claude writing whole apps. It looks at the data with `list_tables` and `describe_table`, reads any component it
* was not given in full with `component_docs`, and sends the app with `write_app`. An app with problems goes back
* to Claude to fix in the same turn; only one with none reaches `onApp`, to save, show or run.
*/
export function appAgent(dataSource: DataSource, onApp: (app: AppDocument) => void | string | Promise<void | string>, client: Anthropic = new Anthropic(), options: AppAgentOptions = {}): AgentBackend {
const check = async (app: unknown) => {
const problems = await appProblems(app, dataSource);
options.onCheck?.(problems);
return problems;
};
return anthropicAgent({
client,
...(options.model ? { model: options.model } : {}),
...(options.effort ? { effort: options.effort } : {}),
...(options.maxSteps ? { maxSteps: options.maxSteps } : {}),
system: appAgentPrompt(analyticsCatalog, { dialect: "DuckDB", dataTools: true, components: commonAnalyticsComponents }),
tools: [
...dataTools(dataSource, options.sourceIds ? { sourceIds: options.sourceIds } : {}),
componentDocsTool({ names: Object.keys(analyticsCatalog.components), docs: (names) => componentDocs(analyticsCatalog, names) }),
appTool({ check, onApp: (app) => onApp((parseApp(app) as { app: AppDocument }).app) }),
],
});
}To run what Claude wrote, give the document to AppView from @surfaces-ui/spec/react with your router's location, or useHashLocation() for none; or, in a plain HTML page, surfaces.mountApp(element, app, { dataSource }) from @surfaces-ui/page. A route that needs something a document cannot hold, such as a chat connected to an agent, is a slot ({ "route": "/chat", "slot": "chat", "title": "Chat" }) that you fill with slots on AppView. create-surfaces writes an app laid out this way: src/app.json and one shell file.
validateAppData runs each distinct statement once, for one row, and reads only the header that lists its columns: no row is read, and the same SQL used by five components is one query. sql that is a binding cannot be run; it is listed in the report's skipped, not in problems.
The test drives the real Anthropic adapter with a transport that replays scripted replies, so the model here is scripted. Its first app links to /customer/[id] where the route is /customers/[id], and filters on /app/filters without declaring it; both problems go back. Its second app is a sound document that totals lifetime_val, a column the table does not have: the data check says so and names the columns there are. The third app is kept, and that app is then run: the list opens a customer, whose page shows that customer's lifetime value. It needs no API key and no network.
The scripted model:
script.ts:
import Anthropic from "@anthropic-ai/sdk";
import { analyticsCatalog } from "@surfaces-ui/spec";
/** Server-sent events for one streamed message, as the Messages API sends them. */
export function sse(blocks: ({ type: "text"; text: string } | { type: "tool_use"; id: string; name: string; input: unknown })[], stopReason: string): string {
const events: [string, unknown][] = [
["message_start", { type: "message_start", message: { id: "msg", type: "message", role: "assistant", model: "claude-sonnet-5-5", content: [], stop_reason: null, usage: { input_tokens: 100, output_tokens: 0 } } }],
];
blocks.forEach((block, index) => {
if (block.type === "text") {
events.push(["content_block_start", { type: "content_block_start", index, content_block: { type: "text", text: "" } }]);
events.push(["content_block_delta", { type: "content_block_delta", index, delta: { type: "text_delta", text: block.text } }]);
} else {
events.push(["content_block_start", { type: "content_block_start", index, content_block: { type: "tool_use", id: block.id, name: block.name, input: {} } }]);
events.push(["content_block_delta", { type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: JSON.stringify(block.input) } }]);
}
events.push(["content_block_stop", { type: "content_block_stop", index }]);
});
events.push(["message_delta", { type: "message_delta", delta: { stop_reason: stopReason }, usage: { output_tokens: 20 } }]);
events.push(["message_stop", { type: "message_stop" }]);
return events.map(([name, data]) => `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`).join("");
}
/** An Anthropic client whose transport answers each request with the next scripted stream, recording what was sent. */
export function scripted(replies: string[]) {
const sent: { system?: unknown; messages: { role: string; content: unknown }[] }[] = [];
const fetch = async (_url: RequestInfo | URL, init?: RequestInit) => {
sent.push(JSON.parse(String(init?.body)));
return new Response(replies.shift() ?? "", { status: 200, headers: { "content-type": "text/event-stream" } });
};
return { client: new Anthropic({ apiKey: "test-key", fetch: fetch as typeof globalThis.fetch, maxRetries: 0, dangerouslyAllowBrowser: true /* jsdom, with a scripted transport */ }), sent };
}
export const customers = [
{ customer_id: "c1", name: "Ada", segment: "Retail", lifetime_value: 1200 },
{ customer_id: "c2", name: "Grace", segment: "Wholesale", lifetime_value: 5400 },
];
const page = (id: string, title: string, components: unknown[]) => ({ id, title, catalogId: analyticsCatalog.id, components });
/** What the model writes first: a link to a route that does not exist, and a filter on state it never declared. */
export const first = {
id: "crm",
title: "Customers",
catalogId: analyticsCatalog.id,
nav: [{ label: "Customers", to: "/" }],
pages: [
{
route: "/",
page: page("list", "Customers", [
{
id: "root",
component: "DataGrid",
sourceId: "memory",
sql: "SELECT * FROM customers",
label: "Customers",
height: 300,
filters: { "@path": "/app/filters" },
rowKey: "customer_id",
action: { functionCall: { "@call": "navigate", args: { to: "/customer/[id]", values: { id: { "@path": "/@event/key" } } } } },
},
]),
},
{
route: "/customers/[id]",
page: page("one", "Customer", [
{ id: "root", component: "Column", children: ["value", "back"] },
{ id: "value", component: "Metric", sourceId: "memory", sql: "SELECT * FROM customers", column: "lifetime_value", aggregate: "sum", label: "Lifetime value", filters: [{ column: "customer_id", op: "eq", values: [{ "@path": "/@route/id" }] }] },
{ id: "back", component: "Link", text: "All customers", url: "/" },
]),
},
],
};
/**
* What it sends after reading those problems: the route spelled right and the state declared, so the document itself
* is sound. But the customer's page still totals `lifetime_val`, and the table's column is `lifetime_value`: only the
* data can say so.
*/
export const second = structuredClone(first) as typeof first & { state?: unknown };
second.state = { filters: { type: "array", default: [], keep: "session" } };
(second.pages[0]!.page.components[0] as { action: { functionCall: { args: { to: string } } } }).action.functionCall.args.to = "/customers/[id]";
(second.pages[1]!.page.components[1] as { column: string }).column = "lifetime_val";
/** What it sends after being told the columns the query has. */
export const fixed = structuredClone(second);
(fixed.pages[1]!.page.components[1] as { column: string }).column = "lifetime_value";
/** The model's three replies, in order, and then its closing words. */
export const replies = () => [
sse([{ type: "tool_use", id: "t1", name: "write_app", input: { app: first } }], "tool_use"),
sse([{ type: "tool_use", id: "t2", name: "write_app", input: { app: second } }], "tool_use"),
sse([{ type: "tool_use", id: "t3", name: "write_app", input: { app: fixed } }], "tool_use"),
sse([{ type: "text", text: "A customer list that opens each customer's lifetime value." }], "end_turn"),
];
/** What `write_app` answered each time, read from what the model was sent next. */
export function toolAnswers(sent: { messages: { role: string; content: unknown }[] }[]): { text: string; refused: boolean }[] {
return sent.slice(1).flatMap((request) => {
const content = request.messages.at(-1)?.content;
const results = Array.isArray(content) ? (content as { type?: string; content?: unknown; is_error?: boolean }[]).filter((part) => part.type === "tool_result") : [];
return results.map((result) => {
const inner = result.content;
const text = typeof inner === "string" ? inner : Array.isArray(inner) ? (inner as { text?: string }[]).map((part) => part.text ?? "").join("") : "";
// A refusal arrives as `{ "error": "…" }`; the words are what matter here.
let words = text;
try {
const read = JSON.parse(text) as { error?: unknown };
if (typeof read.error === "string") words = read.error;
} catch {
// Not JSON: the text as it is.
}
return { text: words, refused: result.is_error === true };
});
});
}The test:
generate-app.test.tsx:
// @vitest-environment jsdom
import { DataSourceProvider, ThemeProvider } from "@surfaces-ui/components";
import { memoryDataSource } from "@surfaces-ui/data";
import { type AppDocument, analyticsCatalog } from "@surfaces-ui/spec";
import { AppView, analyticsRenderers } from "@surfaces-ui/spec/react";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useState } from "react";
import { afterEach, describe, expect, it } from "vitest";
import { appAgent } from "./agent.js";
import { customers, replies, scripted, toolAnswers } from "./script.js";
afterEach(cleanup);
const dataSource = memoryDataSource({ tables: { customers } });
describe("generate a whole app with Claude", () => {
it("returns every problem to Claude, a wrong column among them, keeps only the fixed app, and the app it keeps runs", async () => {
const { client, sent } = scripted(replies());
const kept: AppDocument[] = [];
const agent = appAgent(dataSource, (app) => void kept.push(app), client);
for await (const _ of agent.send({ input: { case: "text", value: "Build me a small CRM over customers" } })) void _;
// The system prompt is the app prompt; Claude was sent its first app's problems as the tool's error.
expect(JSON.stringify(sent[0]!.system)).toContain("write_app");
const [one, two, three] = toolAnswers(sent);
expect(one!.refused).toBe(true);
expect(one!.text).toContain("/customer/[id]");
expect(one!.text).toContain("is not a route of this app");
expect(one!.text).toContain("/app/filters is not declared in the app's state.");
// Its second app is a sound document, so the data is asked: the column is not there, and Claude is told which are.
expect(two!.refused).toBe(true);
expect(two!.text).toContain('- /pages/1/page/value/column: "lifetime_val" is not a column of this component\'s query. Columns: customer_id, name, segment, lifetime_value.');
expect(three!.refused).toBe(false);
expect(kept).toHaveLength(1);
// The kept app runs: the list opens a customer, whose page shows that customer's value.
function Host() {
const [location, setLocation] = useState("/");
return (
<ThemeProvider storage={null}>
<DataSourceProvider dataSource={dataSource}>
<AppView app={kept[0]!} catalog={analyticsCatalog} renderers={analyticsRenderers} location={location} onNavigate={setLocation} storage={null} />
</DataSourceProvider>
</ThemeProvider>
);
}
render(<Host />);
fireEvent.click(await screen.findByText("Grace"));
await waitFor(() => expect(screen.getByText("5,400")).toBeTruthy());
fireEvent.click(screen.getByRole("link", { name: "All customers" }));
expect(await screen.findByText("Ada")).toBeTruthy();
});
});The same turn can be watched in a browser: pnpm --filter @surfaces-ui/recipes exec vite src/generate-app serves a page (Page.tsx) that runs it on a press and lists what write_app answered each time, above the kept app. The app create-surfaces writes is checked against the retail sample the same way in retail.test.ts, on DuckDB behind the dev server.
Run against the live API on 5 December 2026 (the eval): over six briefs, every app Sonnet 5.5, Opus 5.5 and Fable 5.2 had kept ran in a browser with right figures, and about half of first attempts were refused, always for one of two reasons the prompt now covers. eval/ beside this recipe is the harness; pnpm eval:apps runs it with a key, and it is skipped without one.
Source and test: apps/recipes/src/generate-app