Agent-readable docs index: /llms.txt. Full docs in one file: /llms-full.txt. Download /docs.zip to grep all markdown files locally.

Embed AI-generated screens in your app

Embed generated screens in your app

Your users describe a screen. Your agent loop writes the React code with @malleable/ui, and your app renders each build as soon as it exists.
your browser app your server (AI SDK) malleableui.dev useChat ──── POST /chat ─────────────▶ streamText({ tools }) write / edit tool: session.apply ──────────────────────▶ project session.build ◀──── { ok, url } ───── tool output.url ◀──── SSE ──────────────┘ import(url) ─▶ render end of turn: session.commit ───────────▶ git commit save commit.url in your database
A working example is in dashboard-demo/, deployed at https://demo.malleableui.dev. It uses spiceflow, D1 and Workers AI.

1. Tools

Write the tools yourself; they are a few lines each. Every tool that changes files also builds, so its output carries the url of a draft the browser can import.
import { Project, type Session } from '@malleable/ui' import { tool } from 'ai' import { z } from 'zod' async function applyAndBuild(session: Session, ops: Parameters<Session['apply']>[0]['ops']) { await session.apply({ ops }) const result = await session.build() if (!result.ok) return { ok: false as const, errors: result.errorText } // the model fixes these return { ok: true as const, url: result.url } // absolute, importable } export function createTools(session: Session) { return { write: tool({ description: 'Create or overwrite a file, then build', inputSchema: z.object({ path: z.string(), content: z.string() }), execute: ({ path, content }) => applyAndBuild(session, [{ op: 'write', path, content }]), }), edit: tool({ description: 'Replace one exact occurrence of oldString, then build', inputSchema: z.object({ path: z.string(), oldString: z.string(), newString: z.string() }), execute: (input) => applyAndBuild(session, [{ op: 'replace', ...input }]), }), read: tool({ description: 'Read a file', inputSchema: z.object({ path: z.string() }), execute: ({ path }) => session.read({ path }), }), } }
An edit whose oldString is missing throws REPLACE_NOT_FOUND. The AI SDK gives that error to the model, and the client sees the part as output-error.

2. Agent route

One chat turn is one session. Commit at the end and store the url: it is immutable, so later page loads only need import(componentUrl).
const project = new Project({ apiKey: env.MALLEABLE_API_KEY, id: view.projectId }) await project.init() // idempotent const session = await project.openSession({ author: { kind: 'agent', id: 'dashboard-agent' } }) await session.apply({ ops: [{ op: 'write', path: 'malleable.json', content: JSON.stringify({ entry: 'App.tsx', externalPackages }) }], }) const stream = createUIMessageStream({ originalMessages: messages, async execute({ writer }) { const modelMessages = await convertToModelMessages(messages) // model-only history for (let round = 0; ; round++) { const result = streamText({ model, instructions: SYSTEM_PROMPT, messages: modelMessages, tools, stopWhen: isStepCount(40) }) const chunks = toUIMessageStream({ stream: result.stream, tools, sendStart: round === 0, sendFinish: false }) for await (const chunk of chunks) writer.write(chunk) modelMessages.push(...(await result.responseMessages)) const commit = await session.commit({ message: prompt }) if (commit.ok) { writer.write({ type: 'data-commit', data: { url: commit.url } }) // drafts end with the session await db.views.update({ where: { id: viewId }, data: { componentUrl: commit.url } }) break } const feedback = commit.reason === 'conflict' ? commit.prompt : commit.errorText if (round === 2) throw new Error(`Changes not saved:\n${feedback}`) // hidden from the chat: the model fixes conflicts or build errors, then we commit again modelMessages.push({ role: 'user', content: feedback }) } writer.write({ type: 'finish' }) }, }) return createUIMessageStreamResponse({ stream })
Two chats can edit the same view at once. If another one committed first, commit merges. Overlapping edits come back as { reason: 'conflict', prompt }; the session files then hold conflict markers. The AI SDK has no hidden user messages, so the prompt goes only into modelMessages and the user never sees it. The model fixes the markers with its read and edit tools.
Tell the model in the system prompt where its component renders (layout around it, overlays, padding), which props it gets, which imports exist, and your design rules. See SYSTEM_PROMPT in dashboard-demo/src/agent.ts.

3. Pass data as props

Generated code should not call your APIs directly. Pass a typed client as a prop and describe it in the system prompt:
<Screen api={dashboardApi} /> // App.tsx: export default function App({ api }) { ... }

4. Share React through an import map

Built modules import externals bare (import { useState } from 'react'). The page needs a <script type="importmap"> that points them to your bundled copies, or hooks break with two Reacts.
PackageIn externalPackagesIn the import map
react, react-dom, react/jsx-runtimeyesalways
libraries you already ship (charts, icons)optional: one copy shared with your appyes, if external
every other npm packagenono: the module imports it from https://esm.sh/<pkg>@<version>
With spiceflow, React is in the map already. Add your libraries with importMap:
// vite.config.ts spiceflow({ entry: './src/app.tsx', importMap: { recharts: './src/import-map/recharts.ts', // export * from 'recharts' 'lucide-react': './src/import-map/lucide-react.ts', }, })
Every package in externalPackages must be in the import map, or import() fails with "Failed to resolve module specifier". Other packages load from esm.sh in the browser, so a Content-Security-Policy must allow https://esm.sh in script-src. esm.sh builds them with your externals left bare, so they use your React too.

5. Render the latest build

Derive the url from the chat messages. No effects: the latest successful tool output or data-commit part wins.
function previewUrl(messages: UIMessage[]) { const urls = messages.flatMap((m) => m.parts).flatMap((part) => { if (part.type === 'data-commit') return [part.data.url] if (['tool-write', 'tool-edit'].includes(part.type) && part.state === 'output-available' && part.output.ok) return [part.output.url] return [] }) return urls.at(-1) } import { preinit } from 'react-dom' import { STYLESHEET_PRECEDENCE, stylesheetUrl } from '@malleable/ui' const modules = new Map<string, Promise<{ default: ComponentType<{ api: Api }> }>>() function load(url: string) { if (!modules.has(url)) { preinit(stylesheetUrl(url), { as: 'style', precedence: STYLESHEET_PRECEDENCE }) // CSS and JS in parallel modules.set(url, import(/* @vite-ignore */ url)) } return modules.get(url)! } function Screen({ url }: { url: string }) { const View = use(load(url)).default return <View api={dashboardApi} /> } // in the editor component const url = useDeferredValue(previewUrl(messages) ?? view.componentUrl) return ( <Suspense fallback={<Spinner />}> <ErrorBoundary key={url}>{url && <Screen url={url} />}</ErrorBoundary> </Suspense> )
Render <Screen> only in the browser: the import map does not exist during SSR.

No flash between builds

A new build suspends until its module, its stylesheet and its data are ready. useDeferredValue keeps the old screen on display meanwhile, then React swaps in one paint.
new url ─▶ deferred render ─▶ import(index.js) ──┐ └▶ index.css (preinit) ┼─▶ all ready ─▶ swap, scroll position kept └▶ use(api.kpis()) ────┘ old screen stays visible meanwhile
  • Put <Suspense> outside the keyed error boundary. A Suspense boundary that mounts new shows its fallback even in a deferred render, and that is the white flash.
  • The built entry renders <link rel="stylesheet" precedence="malleable">, so React waits for the CSS. React keeps these sheets in <head>; each build scopes its CSS to its own data-malleable-root="<id>", so old sheets do not match new builds.
  • Data: pass an api that returns the same promise for the same call, and tell the model to read it with use(api.x()), not useEffect. Then the new build paints with data, not skeletons. See memoized in dashboard-demo/src/dashboard-api.ts.

6. Show what changed

Every build and commit result carries stats ({ files, additions, deletions }), so a +12 −3 badge costs no request. On click, fetch the diff: both full versions of each file, ready for featherdiff.
chat: ✓ Commit a1b2c3d +12 −3 ── click ──▶ project.diff({ to: sha }) bar: [+48 −12] ──────────────── click ──▶ project.diff({ from: firstBase, to: lastSha }) while the agent works ───────────▶ project.session({ id }).diff({ from: firstBase })
// agent route: tell the client where the turn started const session = await project.openSession({ author }) const { base } = await session.status() writer.write({ type: 'data-session', data: { id: session.id, base } }) // after commit writer.write({ type: 'data-commit', data: { url: commit.url, sha: commit.sha, stats: commit.stats } })
import { FileDiff } from 'featherdiff' import 'featherdiff/styles.css' {diff.files.map((f) => ( <FileDiff key={f.path} path={f.path} oldText={f.oldFile?.contents ?? null} newText={f.newFile?.contents ?? null} expandAll={expanded} /> ))}
  • Full contents, not patches, so collapsed unchanged lines expand on click, expandAll shows whole files, and syntax highlighting stays right inside multiline comments and strings.
  • The demo's chatDiffTarget in agent-chat.tsx derives the whole-chat diff from the message parts, and diff-view.tsx renders it.

Restore to a message

Each commit sha in the chat can be restored with project.restore({ sha }). It adds a new commit, so every later version stays restorable. Save the result as a chat message, so the user sees it and the model knows its files changed (convertDataPart in agent.ts).
✓ Commit 1ea5007 +5 −7 [⧉ copy] [± changes] [⋯] ─▶ Restore code to here ↺ Restored to 1ea5007 as c227adf +1 −1

7. Let the agent see the page

Two client tools run in the user's browser, so the agent sees what the user sees: their data, cookies and window size. The server defines them without execute; the browser runs them when the response ends on them, then sends the chat again.
model calls screenshot ──▶ request ends, no commit ──▶ onFinish (finishReason 'tool-calls') └─▶ run tools ──▶ addToolOutput ──▶ sendMessage() request 2 ──▶ openSession({ id }) reattaches the open session ──▶ model continues ──▶ commit
// server: no execute screenshot: tool({ inputSchema, outputSchema, toModelOutput: ({ output }) => ({ type: 'text', value: '…' }) }) // client: no sendAutomaticallyWhen, it would send a second time next to onFinish new Chat({ onFinish({ message, finishReason, isAbort, isError }) { if (isAbort || isError || finishReason !== 'tool-calls') return void continueTurn(message) // run tools, addToolOutput each, then one chat.sendMessage() }, })
  • Not onToolCall. The SDK awaits it mid-stream, before the outputs of server tools in the same step (the build url of a write) arrive, so the screenshot would show the old build.
  • screenshot uses getDisplayMedia with preferCurrentTab. The first call asks the user ("Share screen" button, because most browsers need a click). The stream stays open, so later calls are silent. After 10 seconds without permission, the tool fails and the agent continues.
  • Chrome only. Element Capture (track.restrictTo, Chrome 132+) keeps only the screen element in the frames, even under the chat overlay. Without it, Capture Handle must prove the user shared this tab; otherwise the tool fails, so another tab never reaches the model.
  • The tool waits until the screen renders the latest build (data-rendered-url) and the DOM is quiet for 300 ms, so chart animations finish.
  • evalJs runs agent code (an async function body) in the page, so it can test the screen like a user. Clicks use plain el.click(); only two helpers cover the traps: fill (React ignores el.value = x, so it uses the native setter plus input/change) and hover (recharts tooltips need mouse moves). It also measures (getBoundingClientRect, overflow). Same trust level as the screen, which is agent code imported into the page. Client tools of one step run in call order, so a click lands before the screenshot that checks it.
  • readConsole reads a ring buffer of console.* calls and uncaught errors, filled from page load. fromScreen marks entries whose stack runs through the generated code.
  • One turn, many requests. Keep the session open across them: reattach with openSession({ id }) while the last data-session part has no data-commit after it. A stopped turn resumes the same way, so its edits are not lost.
  • Images go in a user message. workers-ai-provider drops images in tool results, so the route adds the newest screenshot as a user message, and removes the image before it saves the chat. See screenshotMessage in agent.ts and client-tools.ts.

8. Let users push with their own agent

The open chat shows Copy prompt in the prompt bar. It copies a prompt with a git url (a 7 day token) and the screen rules, so Claude Code, Codex or any agent can clone the view and push to main.
Copy prompt ─▶ POST /git-prompt ─▶ project.createGitToken({ ttl }) ─▶ clone url + screen rules user's agent ─▶ git push ─────────▶ malleableui.dev builds, adds "Build dist for pushed sources" └─▶ live socket: update kind 'commit' ─▶ browser browser ─▶ POST /sync-pushes ─▶ project.log() ─▶ new pushed commits saved as chat messages (D1)
  • The chat in D1 is the only state. syncPushedCommits in agent.ts reads the log, keeps commits with author.kind === 'user' (git pushes; the app's own restores are excluded by id), and saves each as an assistant message with id git-<sha>. Idempotent, so any tab or reload can run it. It returns every recent push with the id of the message before it, so all tabs show the same order.
  • The url is the build commit's. A push has no fresh dist/; the commit the platform adds on top (parents[0] === sha, author system) has it. A sync before that commit landed saves the push's own url; a later sync replaces it, never the reverse.
  • The browser only signals. watchProject (no API key needed) triggers a sync on hello (pushes made while the page was closed), on commits not made by agents, and on build-error of a push.
  • Never append during a turn. The AI SDK extends the last message while it streams or waits for client tools. Pushes that arrive then wait until the turn ends, and go before the turn, so its newer commit stays the screen.
  • The model sees them. convertDataPart turns each push into a note ("Tommy pushed a1b2c3d: ... read files before editing"). A push between requests does not close the agent's open session.

Gotchas

  • Builds check syntax, not types. A missing import builds fine and throws at render. Key the error boundary by url so the next build retries, and offer a "fix it" message to the agent.
  • Drafts disappear when the session ends. Store and reload the commit url, not draft urls.
  • The generated CSS is scoped. It sits in @scope ([data-malleable-root="<build id>"]), and the entry wraps the component in a display: contents element with that attribute. Utilities never touch host elements, and theme variables live on the scope root, not :root. Needs Safari 17.4, Chrome 118, Firefox 146. Inside the view, generated utilities beat host utilities with the same name.
  • Theme the views from the host with the shadcn variables on :root (--background, --foreground, --border, --muted-foreground, --primary... as h s% l%). Set fonts on body: the generated --font-sans exists only inside the view.
  • Mobile Safari: use h-dvh, not h-screen, for a full-height shell, and pad fixed bottom UI with env(safe-area-inset-bottom). Inputs under 16px make iOS zoom on focus.
  • Tailwind v4 borders are currentColor. Tell the model to pair border with a color class (border-border).
  • import() runs the agent's code in your page. Fine for trusted admins. For untrusted prompts, render in a sandboxed iframe.