import { useEffect, useRef, useState } from 'react' import ReactMarkdown from 'react-markdown' import remarkGfm from 'remark-gfm' import { createFileRoute } from '@tanstack/react-router' import { colToLetter, formatValue } from '@tanstack/spreadsheet-core' import { useRevision } from '@tanstack/react-spreadsheet' import { fetchServerSentEvents, useChat } from '@tanstack/ai-react' import { approveAndRegister, exportCodeFunctions, } from '@tanstack/spreadsheet-codemode' import { createAgentCodeMode } from '../agent/tools' import { AGENT_COLS, AGENT_ROWS, CELLS, RUNWAY_FORMULA, freshWorkbook, } from '../agent/model' import { isError, isPendingValue } from '../seed' import type { AgentEvent } from '../agent/tools' import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core' import type { StagedFunction } from '@tanstack/spreadsheet-codemode' export const Route = createFileRoute('/agent')({ component: AgentRoute, }) type CodeMode = Awaited> const ACT1_PROMPT = 'Build a Q1 budget tracker: five categories with anchor budgets, ±20% guardrail bands, actuals, an OK/OVER/UNDER status, totals, and a runway line. Then verify your work.' const ACT2_PROMPT = 'Runway is wrong — it should exclude one-off hardware spikes.' function AgentRoute() { const [wb, setWb] = useState(freshWorkbook) const [resetN, setResetN] = useState(0) const [cm, setCm] = useState(null) // cm is built in the outer component so useChat has stable client tools from // the first render; its onEvent is routed to the inner demo via this ref. const eventsRef = useRef<(e: AgentEvent) => void>(() => {}) useEffect(() => { let alive = true setCm(null) createAgentCodeMode(wb, { onEvent: (e) => eventsRef.current(e) }).then( (r) => { if (alive) setCm(r) }, ) return () => { alive = false } }, [wb]) return (

Agent builds a sheet

A live agent (Claude Sonnet 4.6, via TanStack AI Code Mode) builds a Q1 budget tracker by writing TypeScript that runs in a{' '} QuickJS-WASM sandbox in your browser and calls tools that mutate this workbook. When the runway definition is wrong, it authors a Code Mode function, tests it, and — on your approval — it's registered and wired into the sheet. Only the model completion runs server-side (the API key never reaches the browser).

{cm ? ( { setWb(freshWorkbook()) setResetN((n) => n + 1) }} /> ) : (
Booting the in-browser sandbox…
)}
) } /* ---------------- the live demo ---------------- */ interface ActivityItem { kind: 'code' | 'tool' text: string } function AgentDemo({ wb, cm, eventsRef, onReset, }: { wb: Workbook cm: CodeMode eventsRef: React.MutableRefObject<(e: AgentEvent) => void> onReset: () => void }) { const rev = useRevision(wb) const [activity, setActivity] = useState>([]) const [staged, setStaged] = useState(null) const [registered, setRegistered] = useState(false) // Route Code Mode tool events (fired from inside the WASM isolate) to the feed. useEffect(() => { eventsRef.current = (e: AgentEvent) => { if (e.kind === 'code') setActivity((a) => [...a, { kind: 'code', text: e.code }]) else if (e.kind === 'tool') setActivity((a) => [ ...a, { kind: 'tool', text: `${e.name} — ${e.summary}` }, ]) else if (e.kind === 'staged') setStaged(e.staged) } }, [eventsRef]) const [input, setInput] = useState('') const chat = useChat({ threadId: 'agent', connection: fetchServerSentEvents('/api/agent'), tools: [cm.executeTypescript], forwardedProps: { codeModeSystemPrompt: cm.codeModeSystemPrompt }, }) const send = (text: string) => { const t = text.trim() if (!t || chat.isLoading) return void chat.sendMessage(t) } const submit = () => { send(input) setInput('') } // The runway formula references the cash/burn/one-off inputs, so it only makes // sense once the tracker is built — guard "Fix runway" to avoid a #NUM!. const built = typeof wb.getCell(CELLS.builtinRunway)?.value === 'number' const approve = () => { if (!staged?.passed) return approveAndRegister(wb, staged) wb.applyPatches([ ...wb.setInput(CELLS.trueRunwayLabel, 'True runway'), ...wb.setInput(CELLS.trueRunway, RUNWAY_FORMULA), ]) setRegistered(true) } const cellVal = (r: Ref): CellValue => wb.getCell(r)?.value ?? null const show = (r: Ref) => { const v = cellVal(r) if (v === null) return '—' if (isPendingValue(v)) return '…' return formatValue(v, wb.getFormat(r)) } return (
{/* ---------------- left: the live sheet ---------------- */}

The agent writes equations, not painted numbers — edit any{' '} blue anchor (column B) and the bands, status, and totals recalc.

{registered && }
{/* ---------------- right: the conversation ---------------- */}
Try: {chat.isLoading ? ( ) : ( )} {chat.isLoading ? 'thinking…' : 'idle'}
{chat.error && (
{chat.error.message}
)} {/* transcript: the model's narration + the TypeScript it runs */}
{chat.messages.length === 0 && (
Type a message below, or click a suggestion above. The agent is Claude Sonnet 4.6 writing TypeScript that runs in your browser.
)} {chat.messages.map((m, i) => ( ))} {activity.map((item, i) => (
{item.kind === 'code' ? ( <>
ran code in the sandbox
{item.text}
) : (
{item.text}
)}
))}
{/* approval gate for the authored function */} {staged && (
FN.TRUE_RUNWAY v{staged.compiled.version} {staged.passed ? 'examples pass' : 'examples fail'}
{staged.compiled.spec.source}
{staged.results.map((r, i) => ( ))}
args expected actual pass
({(r.args as Array).join(', ')}) {String(r.expected)} {String(r.actual)} {r.pass ? '✓' : '✗'}
)} {/* real chat input — type anything to the agent */}
{ e.preventDefault() submit() }} >