Open History to see the last commit
1# Sandbox Web (TanStack AI)
2
3A web chat where an AI coding agent builds and runs a real app **inside a
4sandbox**, then hands back a live preview URL — and the run is **durable**: it
5survives a refresh, a closed tab, and a lost connection.
6
7The stack is deliberately fixed — **Claude Code** (the `claude` CLI, model
8`claude-opus-4-8`) in a **Docker** sandbox — because this app is the runnable demo of
9the [durable runs](../../docs/sandbox/durable-runs.md) journal-only tier, and
10durability's one hard requirement is that a run be reconstructible from its
11`runId` alone (the takeover route and the reaper have nothing else). One
12adapter on one provider keeps that rebuild — and the whole example — small.
13For the same `chat()` + `withSandbox()` wiring switched across harnesses live
14in the UI, see [`sandbox-cloudflare`](../sandbox-cloudflare) (its edge/
15Durable-Object sibling, running Claude Code, Codex, or Grok Build).
16
17## How it works
18
191. The browser's `useChat` POSTs `{ messages, data: { threadId } }` to
20 `/api/run` (the run id rides the `X-Run-Id` header, minted by the client).
212. The route runs `chat({ adapter, middleware: [withPersistence, withLocks,
22withSandbox(sandbox, { runs, durability })], … })` — see
23 [`src/run-durable.ts`](./src/run-durable.ts) for the one shared assembly.
243. `withSandbox` resumes-or-creates the thread's sandbox; the `claude` CLI runs
25 inside it and streams its events back out through the journal.
264. The agent scaffolds a self-contained TanStack Start app, runs its dev server
27 on port **5173**, and mints the preview URL via the bridged `exposePreview`
28 host tool (Docker is same-machine, so host tools are bridged over MCP).
29
30## Durable runs (survive a refresh; Stop is a real cancel)
31
32`withSandbox` gets a `RunStore` + a delivery-durability adapter
33(`memoryStream`), the thread id and transcript persist in `localStorage`, and
34`/api/run` serves both the producing `POST` and the `joinRun`/takeover `GET`.
35
36Try it, in order:
37
381. **Refresh mid-run.** Start a build, wait for tool calls to begin, refresh
39 the tab. The agent never stops; the page comes back, rejoins the run from
40 the delivery log, and streams the rest — no repeated text, no gap.
412. **Close the tab entirely,** reopen `localhost:3002` a minute later. Same
42 thing: the stored thread id finds the active run (`/api/run/active`) and
43 the whole run so far replays, then tails live.
443. **Stop is a cancel.** The Stop button calls `/api/run/cancel` — the durable
45 band records `cancelRequested`, the in-process band aborts with
46 `RUN_CANCEL_REASON`, and the sandbox is destroyed. Contrast with a refresh,
47 which detaches. A disconnect and a Stop produce the identical TCP close;
48 only the endpoint tells the server which one you meant.
494. **Abandon a run** (close the tab and don't come back). Within ~5 minutes
50 the scheduled reaper sweeps it: finished runs are finalized, expired ones
51 destroyed — watch for `[reaper]` lines in the dev-server console. This is
52 the easy-to-forget half of the opt-in; without it, detached sandboxes bill
53 forever.
54
55The tier's documented trade: every store here is in-process memory, so log
56durability equals the dev server's lifetime — a **server** restart forgets
57runs (the takeover route then just serves nothing and the UI starts clean).
58Surviving that needs the log-first tier (a durable `StreamDurability` backend
59— what [`sandbox-cloudflare`](../sandbox-cloudflare) gets from a Durable
60Object) plus durable `RunStore`/`LockStore` backends.
61
62## Prerequisites
63
64- a running **Docker daemon**
65- `ANTHROPIC_API_KEY` — see [`.env.example`](./.env.example)
66
67## Run
68
69```bash
70# from the repo root: build the workspace packages first
71pnpm install
72pnpm build
73
74cd examples/sandbox-web
75cp .env.example .env # set ANTHROPIC_API_KEY
76pnpm dev # http://localhost:3002
77```
78
79Then ask it to build something, e.g. _"Build a polished kanban board with
80drag-and-drop and localStorage, then give me the preview URL."_ — and refresh
81the page mid-build.
82
83> The first message per thread is slow: it pulls `node:22` (once) and installs
84> the `claude` CLI in the fresh container. Pre-bake an image with the CLI and
85> set `SANDBOX_IMAGE=<your-image>` to skip that.
86
87## Swapping the stack
88
89The fixed choices live in one file, [`src/sandbox-agent.ts`](./src/sandbox-agent.ts):
90`buildAdapter()` (the harness), `buildSandbox()` (the provider + CLI install +
91secrets), and `missingEnv()` (the auth check). Swap `claudeCodeText` for
92`codexText` / `grokBuildText` and `dockerSandbox` for another provider and the
93durable wiring is unchanged — it only ever sees the definitions. If you make
94the stack a **per-request browser choice** instead, every route that arrives
95with only a `runId` (takeover, reaper) needs that choice stored server-side —
96see the note at the top of [`src/run-durable.ts`](./src/run-durable.ts).
97
98## Limitations
99
100- **Previews are localhost-only** (not shareable): the preview URL maps the
101 container's published port on your machine.
102- **One preview port (5173).** Only the port published at create time is
103 reachable, so the agent must run its dev server on 5173 (the recipe +
104 guidance enforce this).