Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

takeover.md

396 lines17.2 KB

1---
2title: Takeover & Detached Runs (Advanced)
3id: sandbox-takeover
4order: 13
5description: "Keep a sandboxed agent run alive when the browser tab closes. A disconnect detaches the run, and a later request on any server takes it over and continues the stream."
6keywords:
7 - detached run
8 - run takeover
9 - sandboxRunDriver
10 - detachOnDisconnect
11 - detachedRunTtlMs
12 - requestRunCancel
13 - JournalReplayDivergedError
14 - driverEpoch
15---
16​
17Takeover attaches a new connection to a run that is still in progress. A refresh, a closed laptop, or another replica does not destroy the sandbox.
18​
19Takeover keeps the run alive. A disconnect **detaches**: the agent keeps working, and the run record notes that nobody is watching. A later request, on any server, **takes the run over**. It replays what the client already saw, then streams the rest.
20​
21Read [Durable Runs](./durable-runs) first if you want the idea without code. This page is the wiring.
22​
23## Requirements
24​
25Takeover runs across replicas, so every piece must be shared:
26​
27- **One `RunStore` and one `SandboxInstanceStore` that every replica reads.** Pass the run store that chat persistence uses. Pass the instance store to `withSandbox` as `instances`, so the reaper can find each sandbox later. The run store must keep every durable-run field: `status`, `finishedAt`, `error`, `usage`, `sandboxKey`, `detachedSince`, `cancelRequested`, and `driverEpoch`. See [Takeover Internals](./takeover-advanced#what-the-runstore-must-keep).
28- **A distributed `LockStore`.** `InMemoryLockStore` cannot coordinate across hosts, so two replicas can drive one run and double its output. `withSandbox` warns when it sees one. See [Locks](../advanced/locks).
29- **One durability backend that every replica reaches**, for example `durableStream` from `@tanstack/ai-durable-stream`.
30- **A `runId` from the request.** A durable run without one throws `DurableRunIdRequiredError`, because no other host can find its journal.
31- **A scheduled reaper.** Without it, sandboxes of abandoned runs bill forever. See [Reaping & Retention](./reaping).
32​
33## Set up the server
34​
351. Put the shared pieces in one module. Both routes and the reaper import it.
36​
37```ts
38// run-setup.ts
39import { chat } from '@tanstack/ai'
40import { InMemoryLockStore, withLocks } from '@tanstack/ai/locks'
41import { claudeCodeText } from '@tanstack/ai-claude-code'
42import { durableStream } from '@tanstack/ai-durable-stream'
43import { memoryPersistence, withPersistence } from '@tanstack/ai-persistence'
44import {
45 InMemorySandboxInstanceStore,
46 createSecrets,
47 defineSandbox,
48 defineWorkspace,
49 githubRepo,
50 withSandbox,
51} from '@tanstack/ai-sandbox'
52import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
53import type { StreamChunk } from '@tanstack/ai'
54​
55// Local dev stand-ins. In production, use stores every replica reads and a
56// distributed LockStore. See Requirements.
57export const persistence = memoryPersistence()
58export const locks = new InMemoryLockStore()
59export const instances = new InMemorySandboxInstanceStore()
60export const { runs } = persistence.stores
61​
62// The Durable Streams backend every replica reaches.
63export const durableOptions = {
64 server: 'https://streams.example.com',
65 streamPrefix: 'agent-runs',
67​
68export const sandbox = defineSandbox({
69 id: 'repo-agent',
70 provider: dockerSandbox({ image: 'node:22' }),
71 workspace: defineWorkspace({
72 source: githubRepo({ repo: 'owner/app' }),
73 setup: [
74 'npm install -g @anthropic-ai/claude-code --include=optional && claude --version',
75 ],
76 secrets: createSecrets({
77 ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY ?? '',
78 }),
79 }),
80})
81​
82// The run's delivery log, from its id alone. Works with no live request,
83// so the reaper can use it too.
84export function durabilityFor(runId: string) {
85 const url = new URL('https://runs.internal/')
86 url.searchParams.set('runId', runId)
87 return durableStream(new Request(url), durableOptions)
89​
90// The claim gives `drive` an AbortSignal that fires when this host loses the
91// run. chat() takes an AbortController, so mirror one onto the other.
92function controllerFor(signal: AbortSignal): AbortController {
93 const controller = new AbortController()
94 const abort = (): void => controller.abort(signal.reason)
95 if (signal.aborted) abort()
96 else signal.addEventListener('abort', abort, { once: true })
97 return controller
99​
100// Continue an existing run. Used by the takeover route and by the reaper.
101export async function* driveRun(input: {
102 runId: string
103 threadId: string
104 signal: AbortSignal
105}): AsyncIterable<StreamChunk> {
106 // The client sent no history: it is reconnecting, not asking a question.
107 const messages = await persistence.stores.messages.loadThread(input.threadId)
108 const stream = chat({
109 adapter: claudeCodeText('claude-opus-4-8'),
110 messages,
111 // Reuse the threadId on the run record. A new one breaks the replay.
112 threadId: input.threadId,
113 runId: input.runId,
114 abortController: controllerFor(input.signal),
115 middleware: [
116 withPersistence(persistence),
117 withLocks(locks),
118 withSandbox(sandbox, {
119 runs,
120 instances,
121 // attach: true reads the run's existing journal. It does not start a
122 // second agent. Only a takeover sets it, never a POST handler.
123 durability: { adapter: durabilityFor(input.runId), attach: true },
124 }),
125 ],
126 })
127 for await (const chunk of stream) yield chunk
129```
130​
1312. Start durable runs in your `POST` route. Pass `runs` and `durability` together, and forward the `runId`.
132​
133```ts
134// routes/chat.ts
135import {
136 chat,
137 chatParamsFromRequest,
138 toServerSentEventsResponse,
139} from '@tanstack/ai'
140import { withLocks } from '@tanstack/ai/locks'
141import { claudeCodeText } from '@tanstack/ai-claude-code'
142import { durableStream } from '@tanstack/ai-durable-stream'
143import { withPersistence } from '@tanstack/ai-persistence'
144import { withSandbox } from '@tanstack/ai-sandbox'
145import {
146 durableOptions,
147 instances,
148 locks,
149 persistence,
150 runs,
151 sandbox,
152} from './run-setup'
153​
154export async function POST(request: Request) {
155 const { messages, threadId, runId } = await chatParamsFromRequest(request)
156 // @tanstack/ai-client sends X-Run-Id on every POST, so this addresses
157 // agent-runs/<runId>. Use ONE instance for the middleware and the response.
158 const adapter = durableStream(request, durableOptions)
159​
160 const stream = chat({
161 adapter: claudeCodeText('claude-opus-4-8'),
162 messages,
163 threadId,
164 runId,
165 // No abortController that mirrors request.signal here. See below.
166 middleware: [
167 withPersistence(persistence),
168 withLocks(locks),
169 withSandbox(sandbox, { runs, instances, durability: { adapter } }),
170 ],
171 })
172​
173 return toServerSentEventsResponse(stream, { durability: { adapter } })
175```
176​
177> [!WARNING]
178> Do not pass an `abortController` that mirrors `request.signal` on a durable run. If the client leaves while the sandbox builds, the abort stops `chat()` before the agent starts. The run does nothing, and no takeover can recover it, because there is no journal. The durable transport already tells `withSandbox` about the disconnect without an abort.
179​
1803. Take the run over in the `GET` handler that serves resumes. Add a `driver`.
181​
182```ts
183// routes/chat.ts: add this next to POST, and merge the imports.
184import { resumeServerSentEventsResponse } from '@tanstack/ai'
185import { durableStream } from '@tanstack/ai-durable-stream'
186import { sandboxRunDriver } from '@tanstack/ai-sandbox'
187import {
188 durabilityFor,
189 durableOptions,
190 driveRun,
191 locks,
192 runs,
193} from './run-setup'
194​
195export function GET(request: Request) {
196 return resumeServerSentEventsResponse({
197 // Replays the log from the offset on this request (?offset=-1 from a
198 // join, or Last-Event-ID from a reconnect).
199 adapter: durableStream(request, durableOptions),
200 // Claims the run and keeps driving it next to the replay.
201 driver: sandboxRunDriver({
202 request,
203 runs,
204 locks,
205 durability: durabilityFor,
206 drive: driveRun,
207 }),
208 })
210```
211​
212The response is the same with or without `driver`: it replays the log. The driver runs beside it and appends to the same log, and the response tails what lands. Because the drive goes through `chat()`, `withPersistence` still saves the transcript of a run that finished while nobody watched.
213​
214On a serverless platform, also pass `waitUntil: (promise) => ctx.waitUntil(promise)` to `sandboxRunDriver`, so the platform keeps the background drive alive.
215​
216## Rejoin from the client
217​
218A drop in the middle of a stream needs nothing. `useChat` reconnects with the last offset, and the server replays from the log.
219​
220A full page reload has no offset. The page must find the live run, then join it from the start. That join is the `GET` above, so joining and taking over are the same request.
221​
2221. Add an endpoint that returns the live run for a thread. `findActiveRun` looks it up by the stable `threadId`.
223​
224```ts
225// routes/chat-active.ts
226import { runs } from './run-setup'
227​
228export async function GET(request: Request) {
229 const threadId = new URL(request.url).searchParams.get('threadId')
230 if (threadId === null) {
231 return new Response('threadId is required', { status: 400 })
232 }
233 const active = await runs.findActiveRun(threadId)
234 return Response.json({ runId: active?.runId ?? null })
236```
237​
2382. On mount, ask for the live run and join it with `joinRun`.
239​
240```tsx
241import { fetchServerSentEvents } from '@tanstack/ai-client'
242import { useEffect, useState } from 'react'
243import type { StreamChunk } from '@tanstack/ai'
244​
245export function ResumeInFlight({ threadId }: { threadId: string }) {
246 const [chunks, setChunks] = useState<Array<StreamChunk>>([])
247​
248 useEffect(() => {
249 const controller = new AbortController()
250 const connection = fetchServerSentEvents('/api/chat')
251​
252 async function rejoin(): Promise<void> {
253 const response = await fetch(
254 `/api/chat/active?threadId=${encodeURIComponent(threadId)}`,
255 { signal: controller.signal },
256 )
257 const body: unknown = await response.json()
258 if (typeof body !== 'object' || body === null || !('runId' in body)) return
259 const runId = body.runId
260 if (typeof runId !== 'string') return
261 for await (const chunk of connection.joinRun(runId, controller.signal)) {
262 setChunks((previous) => [...previous, chunk])
263 }
264 }
265​
266 void rejoin().catch(() => {
267 // The run finished, or there was none. Nothing to rejoin.
268 })
269 return () => controller.abort()
270 }, [threadId])
271​
272 return <p>{chunks.length} events replayed</p>
274```
275​
276Reload the page while the agent works. The events replay, and new ones keep coming.
277​
278## Detach vs cancel
279​
280A user who presses Stop and a user who closes the tab make the same connection close. The server cannot tell them apart from the disconnect. So a Stop must also send its intent on a separate path. There are two, and either one is enough:
281​
282- **Durable:** `requestRunCancel(runs, runId)` sets `cancelRequested` on the run record. This is the only path that reaches a run driven by a different host, which is the normal case for a detached run.
283- **In-process:** abort the run's own `AbortController` with `RUN_CANCEL_REASON`. This is the fast path when the cancel lands on the driving host. Core reads the reason back, so `AbortInfo.cancelRequested` is `true` for this abort and `false` for a plain disconnect.
284​
2851. Add a cancel endpoint that uses both.
286​
287```ts
288// routes/chat-cancel.ts
289import { RUN_CANCEL_REASON, requestRunCancel } from '@tanstack/ai'
290import { runs } from './run-setup'
291​
292// Runs this process drives now. Add an entry where you create a run's
293// AbortController, and remove it when the run ends.
294export const driving = new Map<string, AbortController>()
295​
296export async function POST(request: Request) {
297 const body: unknown = await request.json()
298 if (typeof body !== 'object' || body === null || !('threadId' in body)) {
299 return new Response('threadId is required', { status: 400 })
300 }
301 const threadId = body.threadId
302 if (typeof threadId !== 'string') {
303 return new Response('threadId must be a string', { status: 400 })
304 }
305​
306 const active = await runs.findActiveRun(threadId)
307 if (!active) return new Response(null, { status: 204 })
308​
309 // Durable: a driver on another host sees it.
310 await requestRunCancel(runs, active.runId)
311 // In-process: a driver on this host stops at once.
312 driving.get(active.runId)?.abort(RUN_CANCEL_REASON)
313​
314 return new Response(null, { status: 204 })
316```
317​
318`requestRunCancel` writes no status. Only the driver knows when the agent is dead and the sandbox is gone, so only the driver writes `'aborted'`.
319​
3202. Make the Stop button call the endpoint. `chat.stop()` alone sends the server nothing, and a durable run keeps working, because that looks like a refresh.
321​
322```tsx
323import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
324​
325export function StoppableChat({ threadId }: { threadId: string }) {
326 const chat = useChat({
327 threadId,
328 connection: fetchServerSentEvents('/api/chat'),
329 })
330​
331 async function stopRun(): Promise<void> {
332 // Local: stop rendering the stream now.
333 chat.stop()
334 // Remote: tell the server that this is a cancel, not a lost connection.
335 await fetch('/api/chat/cancel', {
336 method: 'POST',
337 headers: { 'Content-Type': 'application/json' },
338 body: JSON.stringify({ threadId }),
339 })
340 }
341​
342 return <button onClick={() => void stopRun()}>Stop</button>
344```
345​
346Get this wrong in either direction and it costs you:
347​
348- A Stop that only calls `chat.stop()` leaks running sandboxes that keep spending tokens.
349- A server that treats every disconnect as a cancel kills a ten-minute refactor on a wifi blip.
350​
351### What each path writes
352​
353| Event | `withSandbox` | `withPersistence` | Delivery log |
354| --- | --- | --- | --- |
355| Disconnect on a durable run, `detachOnDisconnect` on, no cancel | Keeps the sandbox. Writes `detachedSince` and `sandboxKey`. | Writes nothing. The record stays `'running'`. | Stays open, with no terminal event. |
356| Cancel (either path) | Destroys the sandbox, always, even with `destroyOnComplete: false`. | Writes `'aborted'` and `finishedAt`. | Terminal `RUN_ERROR`, then closed. |
357| Disconnect on a non-durable run | Destroys the sandbox. | Writes `'aborted'`. | Terminal `RUN_ERROR`, then closed. |
358​
359`keepAlive` and `destroyOnComplete: false` apply to a successful finish only. They never keep a sandbox alive through a cancel.
360​
361The open log is what makes takeover work. A closed log ends the rejoining client's replay early. A stored `RUN_ERROR` is a chunk the journal replay cannot reproduce, so the replay diverges and a healthy run is marked `'failed'`.
362​
363### What cancel means on a provider that cannot kill
364​
365Some providers declare `killableProcesses: false`. Daytona, Vercel, and Cloudflare are among the bundled ones (see [the measured table](./providers#killableprocesses-across-the-bundled-providers)). On those, no signal reaches the agent process: `kill()` does not stop it, and no `AbortSignal` crosses the provider boundary.
366​
367There, **the sandbox destroy is the cancel**, not cleanup. It is the only thing that stops the agent. If a cancel does anything less (marks the record `'aborted'`, closes the log, skips the destroy), the UI says "stopped" while the agent keeps working and the sandbox keeps billing.
368​
369## How it works
370​
3711. The `POST` route starts the agent. The agent writes to the [journal](./journal), and the host appends each chunk to the delivery log.
3722. The client leaves. `withSandbox` sees a disconnect with no cancel, so it detaches: it keeps the sandbox and stamps `detachedSince` and `sandboxKey` on the run record. The log stays open.
3733. A client comes back and calls the `GET` route. `sandboxRunDriver` claims the run under a lock and bumps a fencing number on the record, so the old host cannot write to the run.
3744. The new host reads the journal from byte 0. It drops every chunk the log already holds and appends only the rest.
3755. If nobody comes back, the [reaper](./reaping) finishes the run or cancels it after a time limit, and then destroys the sandbox.
376​
377The fencing, the replay rules, and every error you can branch on are in [Takeover Internals](./takeover-advanced).
378​
379## Configuration
380​
381These options go in `withSandbox(sandbox, { durability: { ... } })`.
382​
383| Option | Default | What it does |
384| --- | --- | --- |
385| `adapter` | required | The run's delivery log. Use the same instance you give the response. |
386| `journal` | `/tmp/tanstack-runs` (`DEFAULT_JOURNAL_DIR`) | Journal directory inside the sandbox. |
387| `detachOnDisconnect` | `true` when durability is wired | `true`: a disconnect detaches. `false`: a disconnect destroys the sandbox, but a reload still replays the log. A cancel destroys in both cases. |
388| `attach` | `false` | Read an existing run's journal instead of starting an agent. Only a takeover `drive` sets it. |
389| `pollIntervalMs` | adapter default | Journal poll interval for providers that cannot follow a file. |
390| `attachWaitMs` | `10000` (`DEFAULT_ATTACH_JOURNAL_WAIT_MS`) | How long an attach waits for a live run's journal to appear. An unknown or finished run fails at once. |
391​
392There is no TTL option here. The time limit for a detached run is `detachedRunTtlMs` on `reapDetachedRuns`, and it lives only there. The reaper runs from a cron with no chat request, so it can never read a TTL set on `withSandbox`. See [Reaping & Retention](./reaping).
393​
394## Go deeper
395​
396For single-writer fencing, replay divergence, the run store contract, and the two run capabilities, see [Takeover Internals](./takeover-advanced).