@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
dashboard-demo/, deployed at https://demo.malleableui.dev. It uses spiceflow, D1 and Workers AI.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 }), }), } }
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.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 })
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.SYSTEM_PROMPT in dashboard-demo/src/agent.ts.<Screen api={dashboardApi} /> // App.tsx: export default function App({ api }) { ... }
import { useState } from 'react'). The page needs a <script type="importmap"> that points them to your bundled copies, or hooks break with two Reacts.| Package | In externalPackages | In the import map |
react, react-dom, react/jsx-runtime | yes | always |
| libraries you already ship (charts, icons) | optional: one copy shared with your app | yes, if external |
| every other npm package | no | no: the module imports it from https://esm.sh/<pkg>@<version> |
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', }, })
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.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> )
<Screen> only in the browser: the import map does not exist during SSR.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
<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.<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.use(api.x()), not useEffect. Then the new build paints with data, not skeletons. See memoized in dashboard-demo/src/dashboard-api.ts.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} /> ))}
expandAll shows whole files, and syntax highlighting stays right inside multiline comments and strings.chatDiffTarget in agent-chat.tsx derives the whole-chat diff from the message parts, and diff-view.tsx renders it.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
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() }, })
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.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.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.data-rendered-url) and the DOM is quiet for 300 ms, so chart animations finish.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.console.* calls and uncaught errors, filled from page load. fromScreen marks entries whose stack runs through the generated code.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.screenshotMessage in agent.ts and client-tools.ts.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)
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.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.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.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.@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.:root (--background, --foreground, --border, --muted-foreground, --primary... as h s% l%). Set fonts on body: the generated --font-sans exists only inside the view.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.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.