feat: durable, reconnectable sandboxed agent runs #1015
main fromrefs/pull/1015/head·merged by AlemTuzlak View on GitHubDurable, reconnectable sandboxed agent runs. A client disconnect detaches the run instead of destroying the sandbox; a later request takes it over and keeps streaming; a reaper finalizes or expires runs nobody comes back for.
Verified end to end by testing/e2e/tests/durable-takeover.spec.ts — a real mid-stream disconnect, an attach, and the stream continues with the transcript intact and no duplicated prefix.
Note on the base. This PR was opened against
feat/persistence-sandbox, which was later deleted upstream, so GitHub retargeted it tomain.mainhas since squash-merged that foundation itself (#988 sandbox instance durability, #1011 generation run persistence), andmainis now merged into this branch — so the PR no longer carries the foundation and there is nothing to split out. One resolution worth flagging: #1004 madeRunStore.findActiveRunrequired, but this branch had relocatedRunStoreinto@tanstack/ai, and that file merged cleanly — so the merge had to re-apply the requirement by hand or it would have silently reverted #1004. It is now required in core, gone from the conformance suite'sskipMethods, and forwarded unconditionally byfenceRunStore.
The problem#
You are building something like ChatGPT, except the assistant is a coding agent that works inside a sandbox and can take ten minutes to finish a task.
Ten minutes is a long time for a browser tab. The user refreshes. Closes the laptop. Loses wifi. Or their next request lands on a different replica than the one running the job.
What used to happen#
The connection dropping killed everything. The sandbox was destroyed, the work was thrown away, and the user came back to nothing.
That was not a bug — it was the least-bad option available. When you close the pipe to an agent running in a sandbox, the agent does not stop. It keeps working and keeps spending money on tokens. So destroying the sandbox was the only reliable way to be sure a disconnected job stopped burning cash.
Which is exactly right if the user pressed Stop. And completely wrong if they just refreshed the page.
What this PR changes#
It teaches the system to tell those two situations apart, and to handle the refresh case properly. Four pieces:
1. A disconnect no longer kills anything. It detaches: the agent keeps working, the sandbox stays up, and the run record notes "nobody is watching this, as of 3:42pm."
2. The agent writes its output to a file instead of down the wire. This is the key trick. If the agent talks directly to the browser, its words vanish the moment the browser leaves. If it writes to a file inside the sandbox, the words are still sitting there when someone comes back.
3. Someone comes back, and we pick up mid-sentence. A new request — possibly on a different replica — reads that file, works out how much the user already saw, and streams only the part they missed. No repeated paragraphs, no gaps.
4. Something has to clean up after the people who never come back. Otherwise a sandbox runs forever on a job nobody will ever read. So there is a sweeper: it finds abandoned runs, checks whether the agent finished on its own, and either wraps them up or shuts them down.
The two parts that sound over-engineered but are not#
Making sure two replicas never both drive one run. If a user opens the same thread in two tabs, or a load balancer sends a retry elsewhere, two replicas could both try to continue one run — and the user would see doubled text and contradictory "finished" messages. So a replica has to take a numbered ticket to drive a run, and if a newer replica takes a higher number, the older one is locked out of writing anything at all. Not merely discouraged — unable to append to the log or mark the run finished.
Making "the agent finished" impossible to fake. The way we know a run ended is that a special line appears at the end of that file. But the agent itself writes that file, and agents write whatever the model says. If a model happened to print that line, the sweeper would believe a running job had ended and would shut down a live sandbox. So the line includes a secret value derived from the run's own id. The agent cannot produce it, so it cannot get its own sandbox destroyed.
What you have to do to use it#
Two things, and the second is easy to forget:
- Turn it on — give
withSandboxboth a run store and a durability backend. Passing only one leaves you with exactly today's destroy-on-disconnect behavior, silently, because you have not asked for durability. - Actually schedule the sweeper — cron, a queue, a Durable Object
alarm(), whatever the platform offers.
Do the first and not the second and everything looks fine, then sandboxes bill indefinitely and disconnected readers wait forever on logs nothing will ever close. A real distributed LockStore is also required; the in-memory one cannot coordinate across hosts.
This explanation ships as docs/sandbox/durable-runs.md, ordered ahead of the three wiring pages.
What ships#
Run lifecycle (@tanstack/ai) — RunRecord gains sandboxKey, detachedSince, driverEpoch, cancelRequested; RunStore.listReclaimable; isTerminalRunStatus / isRunStatus; out-of-band cancel via requestRunCancel / wasCancelRequested.
Detach on disconnect (@tanstack/ai-sandbox) — withSandbox({ runs, durability }) records detachedSince + sandboxKey and leaves the sandbox up. A detached run's delivery log stays open (RunDetachedCapability) so a successor can continue it.
Takeover — sandboxRunDriver claims a run under a lease, fences it by epoch, waits for quiescence, replays from byte 0 and aligns against the stored log so only the remainder is appended. A superseded driver can write neither the event log nor a terminal run status.
Reaping — reapDetachedRuns, pruneJournals, reclaimSandbox / sandboxReclaimer. The reaper never drives a run to discover whether it finished: an injected hasFinished probe reads the in-sandbox journal out of band, because entering the drive writes a terminal status and closes the log on every path.
Journal — a nonced, unforgeable exit sentinel; injective filename encoding; a fail-closed decoder; bounded attach preflight (JournalAttachUnavailableError).
Breaking changes#
All pre-1.0, and the durability surface has never been published, so these break no released consumer.
onAbortwritesaborted(terminal, withfinishedAt);interruptedis no longer terminal-shaped.RunDeps.durabilityis a per-run factory(runId) => StreamDurability<TOffset>.SandboxDurabilityOptions.detachedRunTtlis removed — it was validated, parsed, and read by nothing.ReapOptions.detachedRunTtlMsis the only TTL.SandboxCapabilities.killableProcessesis now required.
Read this before enabling durability#
The reaper ships as a function, not a scheduler. An app that wires durability and never calls reapDetachedRuns has nothing closing detached delivery logs: tailers park forever, the TTL is enforced by nothing, and sandboxes bill indefinitely. Wiring durability and scheduling the sweep are two separate integration steps. See docs/sandbox/reaping.md.
A real LockStore is required — InMemoryLockStore cannot coordinate across hosts, and withSandbox warns when it is used with durability.
Review#
34 fix commits across four review rounds (8 reviewers on the feature, then re-reviews of the fixes themselves). Notable findings, all fixed:
- The detach guard included
!terminalPersisted, and an agent-loop run emits oneRUN_FINISHEDper iteration — so detach was defeated for every tool-calling run. durableStreamrestarted its sequence at 1 on takeover, so a takeover's appends were silently discarded by the reader's dedup.- Three of four
killableProcesses: truedeclarations were false when measured: Docker'sstream.destroy()detached only the client, local-process POSIX killed a forking shell, and Vercel'skill()was a no-op that never called the SDK's real kill. Vercel and Daytona are nowfalse; Docker's is fixed and falsifiable. - The exit sentinel was forgeable from ordinary agent stdout, which could get a live sandbox destroyed by the reaper.
- An attach against a run with no journal hung forever, and self-perpetuated once triggered.
isTerminalRunStatususedin, so'toString'was terminal — reachable from any user-implemented store, and a consumer deletes journals.- One middleware's failing teardown cancelled every later middleware's teardown.
- The conformance suite asserted the reader stopped, never that the remote process died — which is how the false capability claims survived it. It now asserts the process is gone.
Known limitations#
- Sprites
killableProcesses: trueis unmeasured — the one remainingtrue. Its server-side kill endpoint is confirmed to be issued; what it signals (process group vs. pid) is not. NeedsSPRITES_API_KEY. - Vercel, Daytona, and Sprites journal-conformance suites are registered but render named skips without credentials. A secrets-gated nightly job would close this.
packages/ai-sandbox/tests/harness-cwd.test.ts › maps nested virtual paths under /workspace on local-processfails on Windows (path separators). Pre-existing and unrelated.- Event-log retention stays the application's job, inside its own
StreamDurabilitybackend.
Verification#
ai 1390 · ai-sandbox 602/603 (the Windows case above) · ai-persistence 95 · ai-durable-stream 45 · adapters 261 · providers 214 including Docker 37/37 under REQUIRE_DOCKER=1 and BusyBox conformance · E2E 390 passed / 0 failed · kiira 894/894 · publint 15/15 · sherif, knip, format and 17 typechecks clean.
Run directly per package rather than through nx, which is unreliable on this machine.
Summary by CodeRabbit#
- New Features
- Added durable sandbox runs that survive disconnects, support replay and takeover, and enforce single-writer safety.
- Added persistent run journals, deterministic replay alignment, cancellation tracking, snapshots, and detached-run reaping.
- Added unified run statuses, structured errors, resumable stream improvements, and provider capability reporting.
- Bug Fixes
- Improved process cleanup, Windows and Docker termination, stream handling, timeouts, teardown, and middleware error isolation.
- Documentation
- Added guides covering durable runs, journals, takeover, persistence, reaping, and provider behavior.
- 1
🚀 Changeset Version Preview#
31 package(s) bumped directly, 21 bumped as dependents.
🟥 Major bumps#
Package Version Reason @tanstack/ai-acp0.2.3 → 1.0.0 Changeset @tanstack/ai-angular0.3.1 → 1.0.0 Changeset @tanstack/ai-byteplus0.0.0 → 1.0.0 Changeset @tanstack/ai-claude-code0.2.3 → 1.0.0 Changeset @tanstack/ai-codex0.2.3 → 1.0.0 Changeset @tanstack/ai-durable-stream0.0.0 → 1.0.0 Changeset @tanstack/ai-grok-build0.2.3 → 1.0.0 Changeset @tanstack/ai-memory0.0.0 → 1.0.0 Changeset @tanstack/ai-openai0.17.1 → 1.0.0 Changeset @tanstack/ai-opencode0.2.3 → 1.0.0 Changeset @tanstack/ai-openrouter0.15.10 → 1.0.0 Changeset @tanstack/ai-persistence0.0.0 → 1.0.0 Changeset @tanstack/ai-preact0.11.1 → 1.0.0 Changeset @tanstack/ai-react0.18.1 → 1.0.0 Changeset @tanstack/ai-sandbox0.2.4 → 1.0.0 Changeset @tanstack/ai-sandbox-cloudflare0.2.4 → 1.0.0 Changeset @tanstack/ai-sandbox-daytona0.2.0 → 1.0.0 Changeset @tanstack/ai-sandbox-docker0.2.0 → 1.0.0 Changeset @tanstack/ai-sandbox-local-process0.2.0 → 1.0.0 Changeset @tanstack/ai-sandbox-sprites0.2.1 → 1.0.0 Changeset @tanstack/ai-sandbox-vercel0.2.0 → 1.0.0 Changeset @tanstack/ai-solid0.15.1 → 1.0.0 Changeset @tanstack/ai-svelte0.15.1 → 1.0.0 Changeset @tanstack/ai-vue0.15.1 → 1.0.0 Changeset @tanstack/openai-base0.9.9 → 1.0.0 Changeset @tanstack/ai-anthropic0.16.3 → 1.0.0 Dependent @tanstack/ai-bedrock0.1.4 → 1.0.0 Dependent @tanstack/ai-code-mode0.3.8 → 1.0.0 Dependent @tanstack/ai-code-mode-skills0.3.11 → 1.0.0 Dependent @tanstack/ai-elevenlabs0.2.34 → 1.0.0 Dependent @tanstack/ai-fal0.9.12 → 1.0.0 Dependent @tanstack/ai-gemini0.20.1 → 1.0.0 Dependent @tanstack/ai-grok0.14.9 → 1.0.0 Dependent @tanstack/ai-groq0.5.3 → 1.0.0 Dependent @tanstack/ai-isolate-node0.1.47 → 1.0.0 Dependent @tanstack/ai-isolate-quickjs0.1.47 → 1.0.0 Dependent @tanstack/ai-mistral0.2.3 → 1.0.0 Dependent @tanstack/ai-ollama0.8.16 → 1.0.0 Dependent @tanstack/ai-react-ui0.8.15 → 1.0.0 Dependent @tanstack/ai-solid-ui0.7.14 → 1.0.0 Dependent 🟨 Minor bumps#
Package Version Reason @tanstack/ai0.42.0 → 0.43.0 Changeset @tanstack/ai-client0.22.1 → 0.23.0 Changeset @tanstack/ai-devtools-core0.4.24 → 0.5.0 Changeset @tanstack/ai-event-client0.6.8 → 0.7.0 Changeset @tanstack/ai-utils0.3.1 → 0.4.0 Changeset 🟩 Patch bumps#
Package Version Reason @tanstack/ai-mcp0.2.5 → 0.2.6 Changeset @tanstack/ai-isolate-cloudflare0.2.38 → 0.2.39 Dependent @tanstack/ai-vue-ui0.2.34 → 0.2.35 Dependent @tanstack/preact-ai-devtools0.1.67 → 0.1.68 Dependent @tanstack/react-ai-devtools0.2.67 → 0.2.68 Dependent @tanstack/solid-ai-devtools0.2.67 → 0.2.68 Dependent ag-ui0.0.2 → 0.0.3 Dependent View your CI Pipeline Execution ↗ for commit e4fd0c1722e3c42eee6b13602125846e3a44b9c4
Command Status Duration Result nx run-many --targets=build --exclude=examples/...✅ Succeeded 1m 50s View ↗
☁️ Nx Cloud last updated this comment at
2026-08-04 14:26:09UTC@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@1015@tanstack/ai-acp
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-acp@1015@tanstack/ai-angular
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-angular@1015@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@1015@tanstack/ai-bedrock
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-bedrock@1015@tanstack/ai-byteplus
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-byteplus@1015@tanstack/ai-claude-code
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-claude-code@1015@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@1015@tanstack/ai-code-mode
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode@1015@tanstack/ai-code-mode-skills
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode-skills@1015@tanstack/ai-codex
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-codex@1015@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@1015@tanstack/ai-durable-stream
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-durable-stream@1015@tanstack/ai-elevenlabs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-elevenlabs@1015@tanstack/ai-event-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-event-client@1015@tanstack/ai-fal
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-fal@1015@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@1015@tanstack/ai-grok
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@1015@tanstack/ai-grok-build
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok-build@1015@tanstack/ai-groq
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-groq@1015@tanstack/ai-isolate-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-cloudflare@1015@tanstack/ai-isolate-node
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-node@1015@tanstack/ai-isolate-quickjs
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs@1015@tanstack/ai-mcp
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mcp@1015@tanstack/ai-memory
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-memory@1015@tanstack/ai-mistral
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-mistral@1015@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@1015@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@1015@tanstack/ai-opencode
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-opencode@1015@tanstack/ai-openrouter
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@1015@tanstack/ai-persistence
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-persistence@1015@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@1015@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@1015@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@1015@tanstack/ai-sandbox
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox@1015@tanstack/ai-sandbox-cloudflare
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-cloudflare@1015@tanstack/ai-sandbox-daytona
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-daytona@1015@tanstack/ai-sandbox-docker
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-docker@1015@tanstack/ai-sandbox-local-process
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-local-process@1015@tanstack/ai-sandbox-sprites
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-sprites@1015@tanstack/ai-sandbox-vercel
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-sandbox-vercel@1015@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@1015@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@1015@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@1015@tanstack/ai-utils
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-utils@1015@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@1015@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@1015@tanstack/openai-base
npm i https://pkg.pr.new/TanStack/ai/@tanstack/openai-base@1015@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@1015@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@1015@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@1015commit:
e4fd0c1AlemTuzlak changed the title
Actionable comments posted: 14
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
🟡 Minor comments (21)
packages/ai-codex/src/adapters/text.ts-215-241 (1)
215-241: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winMove the durability resolution inside the
tryblock.resolveDurableRunIdandresolveDurableThreadIdthrowDurableRunIdRequiredError/DurableThreadIdRequiredErrorwhen durability is wired without a caller-supplied id. Here both calls sit before thetryat line 249, so the error escapeschatStreamand rejects the async iterator. The catch at line 406 never runs, and noRUN_ERRORchunk is emitted.The sibling adapters resolve inside the
try:packages/ai-claude-code/src/adapters/text.ts(line 326, inside thetryat line 307) andpackages/ai-grok-build/src/adapters/text.ts(line 521, inside thetryat line 507). The same misconfiguration therefore surfaces as a stream chunk on those adapters and as a rejection on this one.Move the three declarations into the
tryblock, afterconst sandbox = this.sandboxFrom(options), and keepchannelcreation after them.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-codex/src/adapters/text.ts` around lines 215 - 241, Move the durability lookup and the declarations of durability, runId, and threadId from before the try into the try block, placing them after const sandbox = this.sandboxFrom(options). Keep channel creation after these declarations so DurableRunIdRequiredError and DurableThreadIdRequiredError are handled by chatStream’s existing catch and emitted as RUN_ERROR chunks.packages/ai-sandbox/src/chunk-identity.ts-92-99 (1)
92-99: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThe
"__undefined__"sentinel collides with a real string value.stableStringifyencodes a present-but-undefinedfield as the quoted string"__undefined__". A field whose real value is the string__undefined__encodes to the identical text throughJSON.stringify. So{ a: undefined }and{ a: '__undefined__' }produce the same fingerprint, which contradicts the guarantee documented at Lines 117-121.A false match makes
alignToStoredLogsuppress a replayed chunk that does not equal the stored chunk. Use an unquoted token instead. Every real string is quoted byJSON.stringify, so an unquoted token cannot be produced by any string value.🐛 Proposed fix
const parts = keys.map((key) => { const entry = record[key] + // Unquoted on purpose: `JSON.stringify` quotes every real string, so no + // string value can produce this token and collide with an explicit + // `undefined`. const encoded = - entry === undefined - ? '"__undefined__"' - : stableStringify(entry, undefined) + entry === undefined ? 'undefined' : stableStringify(entry, undefined) return `${JSON.stringify(key)}:${encoded}` })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/chunk-identity.ts` around lines 92 - 99, Update the undefined-field encoding in the keys mapping near stableStringify so it uses an unquoted sentinel token rather than the quoted "__undefined__" string. Preserve JSON.stringify encoding for all real values, ensuring present undefined fields remain distinct from the literal string "__undefined__" in the generated fingerprint.packages/ai-sandbox/src/run.ts-116-120 (1)
116-120: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winCorrect the "called exactly once per run" claim.
RunController.attachcallsthis.deps.durability(runId)again at Line 437, outsidepipeToRunLog. So the factory is called at least twice for a run that is both driven and tailed in the same process. An implementer who reads this line literally may build a one-shot factory that mints a fresh, unshared instance per call, andattachwould then read a log that does not observe the driver's appends.State the real requirement: the factory must return a log that resolves to the same stored run for the same
runId, and it may be called more than once.📝 Proposed doc fix
- * Called exactly once per run, at the start of {`@link` pipeToRunLog}. An - * implementation MUST return the same instance for the same `runId` within a - * process if it wants `snapshot()` to see its own appends. + * Called once per drive, at the start of {`@link` pipeToRunLog}, and again by + * {`@link` RunController.attach} for every tail of the same run. An + * implementation MUST therefore be callable more than once per `runId`, and + * every instance it returns for one `runId` MUST resolve to the SAME stored + * log — otherwise `attach` tails a log the driver never appended to and + * `snapshot()` cannot see the driver's own appends.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/run.ts` around lines 116 - 120, Update the durability factory documentation near the durability callback type to remove the claim that it is called exactly once per run. State instead that the factory may be called multiple times and must resolve the same stored run/log for a given runId so separate instances observe the same appends.packages/ai-sandbox/package.json-62-62 (1)
62-62: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse
workspace:*for the internal@tanstack/aidependency.peerDependenciesdeclares"@tanstack/ai": "workspace:^", whiledevDependenciesusesworkspace:*. The coding guidelines require theworkspace:*protocol for internal package dependencies.As per coding guidelines: "Use the
workspace:*protocol for internal package dependencies inpackage.json."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/package.json` at line 62, Update the `@tanstack/ai` entry in peerDependencies to use the workspace:* protocol, matching its devDependencies declaration and the repository’s internal dependency convention.Source: Coding guidelines
docs/sandbox/providers.md-252-261 (1)
252-261: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winResolve the contradiction between the stated rule and the Sprites row.
Line 252 states that anything that cannot be measured stays
false. The Sprites row then declarestrue (unverified)and says the endpoint behavior is "undocumented and unmeasured". A reader cannot tell which statement governs a new provider. Either state the exception for a real server-side kill explicitly in the rule, or align the Sprites value with the rule.#!/bin/bash # Confirm the value each bundled provider actually declares. rg -n -C 2 'killableProcesses' packages/ai-sandbox-*/src🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/providers.md` around lines 252 - 261, Resolve the contradiction between the introductory rule and the Sprites row: either revise the rule near “Anything that cannot be measured yet stays false” to explicitly allow a documented exception for real server-side kill mechanisms, or change the Sprites `killableProcesses` value to `false` while retaining its unverified endpoint details. Ensure the documented policy and provider value consistently communicate which rule governs unmeasured behavior.packages/ai-sandbox-docker/src/handle.ts-226-236 (1)
226-236: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRe-check the pid before you print
KILL_FAILED_MARKER.The shell sends
kill -KILLand then immediately runskill -0 "$pid". Signal delivery and process teardown are asynchronous, sokill -0can still succeed for a process that is about to die, and it also succeeds for a zombie that has not been reaped yet. The result is alogger.warnabout an orphan on a successful kill. That weakens exactly the in-band evidence channelkillableProcesses: truedepends on.Add a short bounded re-check after the
KILLbefore reporting.🛠️ Proposed bounded verification
` kill -KILL -"$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null`, // Verify, do not assume: ask the kernel whether the pid is still there. - ` if kill -0 "$pid" 2>/dev/null; then`, + ` j=0`, + ` while [ "$j" -lt 10 ] && kill -0 "$pid" 2>/dev/null; do`, + ` sleep 0.05`, + ` j=$((j+1))`, + ` done`, + ` if kill -0 "$pid" 2>/dev/null; then`, ` echo ${KILL_FAILED_MARKER} pid="$pid" >&2`, ` fi`,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-docker/src/handle.ts` around lines 226 - 236, Add a short bounded polling re-check between the SIGKILL and the existing kill -0 verification in the shell command assembled by the process-kill logic. Repeatedly test whether the pid remains present, sleeping briefly between attempts, and only echo KILL_FAILED_MARKER if it is still present after the bounded window; preserve the existing no-pid behavior and marker symbols.packages/ai-sandbox/src/shell.ts-209-245 (1)
209-245: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winA timed-out
run()leaves an orphan resolver inpending.Promise.race([nextLine(), deadline])abandons thenextLine()promise when the deadline wins, but its resolver stays queued inpending. On the timeout path the shell is still alive by definition, sodrainStdoutdelivers the next stdout line to that abandoned resolver. A caller that catches the timeout and callsrun()again then loses its first line, and the sentinel protocol is offset by one for every later command.Track the parked resolver and drop it when the deadline fires.
🛠️ Sketch of a cancellable read
+ /** Read the next line, with a way to withdraw the waiter on timeout. */ + function nextLineCancellable(): { + line: Promise<string | null> + cancel: () => void + } { + const buffered = lineBuffer.shift() + if (buffered !== undefined) { + return { line: Promise.resolve(buffered), cancel: () => {} } + } + if (streamDone) return { line: Promise.resolve(null), cancel: () => {} } + let resolver: (line: string | null) => void = () => {} + const line = new Promise<string | null>((resolve) => { + resolver = resolve + pending.push(resolve) + }) + return { + line, + cancel: () => { + const i = pending.indexOf(resolver) + if (i >= 0) pending.splice(i, 1) + }, + } + }Then in the loop:
- const line = await Promise.race([nextLine(), deadline]) + const read = nextLineCancellable() + const line = await Promise.race([read.line, deadline]) if (line === TIMED_OUT) { + read.cancel() throw new Error(🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/shell.ts` around lines 209 - 245, Update the read flow around nextLine() and the deadline in run() to track the pending resolver for the current stdout read and remove it from pending when the timeout wins. Ensure the timed-out read is cancelled before throwing, while preserving normal line handling and sentinel processing for non-timeout runs.packages/ai-sandbox-docker/tests/docker.test.ts-64-65 (1)
64-65: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThis assertion does not check what the comment claims.
The comment says the check proves "the snapshot really captured this container's filesystem."
inspected.Idis non-empty for every image the daemon can inspect, so the assertion holds even for an image with no captured layers. Either drop the line or assert something filesystem-specific, for example thatinspected.Sizeis greater than zero, or that a file written into the container earlier in this test is readable from a sandbox restored offsnapshotTag.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-docker/tests/docker.test.ts` around lines 64 - 65, Replace the ineffective inspected.Id assertion in the snapshot verification test with a filesystem-specific check: verify inspected.Size is greater than zero or confirm that a file written earlier is readable after restoring from snapshotTag. Keep the assertion aligned with the comment’s claim that the container filesystem was captured.packages/ai-sandbox-daytona/tests/journal.conformance.test.ts-21-36 (1)
21-36: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winTreat an empty
DAYTONA_API_KEYas unavailable.Line 26 passes
{ apiKey: '' }when the environment variable is empty. Lines 34-36 treat that same value as unsupported. If CI injects an empty secret, a handle-creation case can fail instead of reporting the named unsupported state. Use the same truthiness check for both paths.Proposed fix
- const provider = daytonaSandbox(apiKey !== undefined ? { apiKey } : {}) + const provider = daytonaSandbox(apiKey ? { apiKey } : {})🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-daytona/tests/journal.conformance.test.ts` around lines 21 - 36, Update the DAYTONA_API_KEY handling in the createHandle callback and unsupported spread so an empty string is treated as unavailable consistently. Use a truthiness check when deciding whether to pass apiKey to daytonaSandbox, preserving the existing unsupported state for missing or empty credentials.packages/ai-sandbox/tests/reclaim.test.ts-76-87 (1)
76-87: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winLine 86 asserts on a counter that the test disconnected.
Line 77 replaces
provider.destroyaftertrackDestroyswrapped it. The wrapper no longer runs, sodestroyedstays empty whatever the implementation does. The assertion at line 86 can never fail, and it reads as "destroy was never called" whilereclaimSandboxdoes call it and observes the rejection.Reject from inside the tracked wrapper so the id is still recorded.
💚 Proposed fix
const { provider, destroyed } = trackDestroys(makeFakeProvider()) - provider.destroy = () => Promise.reject(new Error('already gone')) + const tracked = provider.destroy + provider.destroy = (input) => { + void tracked(input) + return Promise.reject(new Error('already gone')) + } const instances = await storeWith('k1', 'fake', 'sbx-1') const outcome = await reclaimSandbox(record({ sandboxKey: 'k1' }), { provider, instances, }) // The delete is unconditional — but the outcome must NOT claim success. expect(outcome).toBe('destroy-failed') expect(await instances.get('k1')).toBeNull() - expect(destroyed).toEqual([]) + // Destroy WAS attempted against the recorded sandbox; it simply failed. + expect(destroyed).toEqual(['sbx-1'])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/tests/reclaim.test.ts` around lines 76 - 87, Update the test setup around trackDestroys and provider.destroy so the tracked wrapper remains installed while its implementation rejects with “already gone”; configure the rejection inside that wrapper rather than replacing provider.destroy afterward. Preserve the existing outcome, instance removal, and destroyed assertions so the test verifies reclaimSandbox calls destroy and handles the rejection.packages/ai-grok-build/tests/attach.test.ts-387-401 (1)
387-401: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThe comment and the code disagree on the runId, so the colliding-runId case is not covered.
The comment states "Same runId, a log already holding the whole sequence, but
attach: false", and it names the hazard as a colliding runId. The code passesfreshRunId, which is a different id from the seededrunId. The test therefore proves only that a non-attach run delivers its own chunks. It does not pin the case the comment describes. The journal seeded atrunIdis also unused by the fresh run.Either reuse
runIdfor the fresh run to exercise the collision, or update the comment to match the weaker guarantee.♻️ Proposed fix to exercise the documented case
- const freshRunId = `r-${randomUUID()}` + // Same runId as the seeded journal: alignment must still be skipped. const fresh = await collect( run(sbx, { - runId: freshRunId, + runId, durability: durabilityWith(fakeLog(reference), false), }), )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-grok-build/tests/attach.test.ts` around lines 387 - 401, Update the test’s second run invocation to reuse the seeded runId instead of freshRunId, so it exercises attach: false with an existing journal entry for the same run. Keep the surrounding reference log setup and assertions unchanged, and retain the comment describing the colliding-runId behavior.packages/ai-sandbox-local-process/tests/local-process.test.ts-136-158 (1)
136-158: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRelease the probe process in a
finally, so a failed assertion does not orphan a 31-yearsleep.proc.kill()andsbx.destroy()run only on the success path. If the visibility assertion at Line 144 fails, the test throws first, andsleep 987654321plus itsshwrapper survive on the host until reboot. The same applies if the survivor assertion at Line 156 fails.♻️ Proposed guard
const proc = await sbx.process.spawn(`sleep ${KILL_PROBE_SLEEP}`) - // Guard the guard: if the probe were never visible, its absence after the - // kill would prove nothing at all. - let visible = await probeRows() - for (let i = 0; i < 20 && visible === ''; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 100)) - visible = await probeRows() - } - expect(visible).toContain(KILL_PROBE_SLEEP) - - // Default signal on purpose — the realistic call path, and the one - // `killableProcesses: true` is a promise about. - await proc.kill() - await proc.wait() - - let survivors = await probeRows() - for (let i = 0; i < 20 && survivors !== ''; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 100)) - survivors = await probeRows() - } - expect(survivors).toBe('') - - await sbx.destroy() + try { + // Guard the guard: if the probe were never visible, its absence after + // the kill would prove nothing at all. + let visible = await probeRows() + for (let i = 0; i < 20 && visible === ''; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 100)) + visible = await probeRows() + } + expect(visible).toContain(KILL_PROBE_SLEEP) + + // Default signal on purpose — the realistic call path, and the one + // `killableProcesses: true` is a promise about. + await proc.kill() + await proc.wait() + + let survivors = await probeRows() + for (let i = 0; i < 20 && survivors !== ''; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 100)) + survivors = await probeRows() + } + expect(survivors).toBe('') + } finally { + await proc.kill().catch(() => {}) + await sbx.destroy() + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-local-process/tests/local-process.test.ts` around lines 136 - 158, Wrap the probe lifecycle in a try/finally block so cleanup always runs when either assertion or polling fails. Keep the existing visibility, kill, wait, and survivor assertions in the try block, and move proc.kill() and sbx.destroy() into finally, ensuring the spawned process is released even on test failure.docs/sandbox/journal.md-27-30 (1)
27-30: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd a language to the fenced block.
markdownlint reports MD040 here. Use
textfor the path listing.📝 Proposed fix
-``` +```text /tmp/tanstack-runs/<runId>.ndjson every NDJSON event the agent emitted /tmp/tanstack-runs/<runId>.err the agent's stderr, kept separate ```🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/journal.md` around lines 27 - 30, Update the fenced code block containing the /tmp/tanstack-runs path listing to declare the text language, preserving both listing entries unchanged.Source: Linters/SAST tools
docs/sandbox/reaping.md-341-342 (1)
341-342: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winFix the broken anchor.
The heading at line 520 is
## Sizing \detachedRunTtlMs` and the sweep interval, which slugs tosizing-detachedrunttlms-and-the-sweep-interval. The link omits the trailingms`, so it resolves to nothing.🐛 Proposed fix
-reasonable start — see [sizing](`#sizing-detachedrunttl-and-the-sweep-interval`)). +reasonable start — see [sizing](`#sizing-detachedrunttlms-and-the-sweep-interval`)).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/reaping.md` around lines 341 - 342, Update the sizing link in the vercel.json registration guidance to use the heading’s correct anchor, including the trailing “ms” in “detachedrunttlms”.Source: Linters/SAST tools
packages/ai-sandbox/src/testkit/journal-conformance.ts-195-196 (1)
195-196: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winPROBE_MAX_TICKSdoes not bound the probe inside the case timeout.The loop sleeps 1s per tick, so 600 ticks is about 600s.
CASE_TIMEOUT_MSis 180s. The comment states that nothing can outlive the suite, but the probe can keep writing for roughly seven minutes after the case times out and thefinallyteardown never ran. Reduce the cap below the case timeout.♻️ Proposed change
-/** Iteration cap on the kill probe's loop, so nothing can outlive the suite. */ -const PROBE_MAX_TICKS = 600 +/** + * Iteration cap on the kill probe's loop, so nothing can outlive the suite. One + * tick per second, so this must stay under `CASE_TIMEOUT_MS`. + */ +const PROBE_MAX_TICKS = 150🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/testkit/journal-conformance.ts` around lines 195 - 196, Reduce PROBE_MAX_TICKS so the kill probe’s one-second-per-tick loop completes within CASE_TIMEOUT_MS, including reasonable timeout overhead. Update the adjacent comment to accurately state that the cap keeps the probe bounded by the case timeout and preserves the existing teardown behavior.packages/ai-sandbox/tests/journal.test.ts-197-204 (1)
197-204: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThe truncation assertion is vacuous.
journaledCommandnever emits a newline, sonot.toContain("> '/tmp/tanstack-runs/r1.ndjson'\n")passes for both>>and a truncating>. Assert the absence of a truncating redirect directly.♻️ Proposed assertion
- expect(journaledCommand('x', journalPaths('r1'))).not.toContain( - `> '/tmp/tanstack-runs/r1.ndjson'\n`, - ) + expect(journaledCommand('x', journalPaths('r1'))).not.toMatch( + /[^>]> '\/tmp\/tanstack-runs\/r1\.ndjson'/, + )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/tests/journal.test.ts` around lines 197 - 204, Update the truncation assertion in the journaledCommand test to check directly that the command does not contain the single-redirect form for the journal path, without relying on a trailing newline. Keep the existing append-redirection assertion unchanged.packages/ai-sandbox/src/testkit/journal-conformance.ts-470-475 (1)
470-475: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winAwait the spawn call, so a spawn failure fails the case.
void handle.process.spawn(...)discards the returned promise. Ifspawnrejects, the result is an unhandled rejection attributed to an unrelated point in the run, not a failure of this case. The comment explains whywait()must not be called; that reason does not apply to thespawncall itself.🐛 Proposed fix
- void handle.process.spawn(journaledCommand(agentCommand, paths)) + await handle.process.spawn(journaledCommand(agentCommand, paths))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/testkit/journal-conformance.ts` around lines 470 - 475, In the process-launch setup around handle.process.spawn, await the promise returned by spawn so any launch failure fails the conformance case directly. Keep the existing behavior of avoiding a later SpawnHandle.wait() call and preserve the __exit sentinel as the completion check after the awaited spawn.docs/persistence/overview.md-156-156 (1)
156-156: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winCorrect the reload lifecycle statement.
Line 156 says both layers assume that work has finished. Line 152 says delivery durability can rejoin a still-streaming run. Limit the statement to already-produced transcript data, then state that delivery durability can also tail a live producer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/overview.md` at line 156, Update the reload lifecycle statement near the sandboxed agent discussion to limit the “work is over” assumption to replaying or reading already-produced transcript data. Clarify that delivery durability can rejoin and continue tailing a still-streaming run, while preserving the existing distinction that a sandboxed agent requires takeover to keep driving after its host disappears.packages/ai-sandbox/tests/journal-bytes.test.ts-142-150 (1)
142-150: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winCorrect the byte arithmetic in the comment.
The comment says the line is
1 + 4 + 1 = 6bytes plus the newline, which is 7. The assertion expectsendPosition: 9, and 9 is right:[,", 🌍 (4 bytes),",]is 8 bytes, plus the newline. The comment omits the brackets.📝 Proposed fix
- // '🌍' is 4 bytes; the line is 1 + 4 + 1 = 6 bytes plus the newline. + // '🌍' is 4 bytes; the line `["🌍"]` is 1 + 1 + 4 + 1 + 1 = 8 bytes, plus + // the newline.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/tests/journal-bytes.test.ts` around lines 142 - 150, Correct the explanatory comment in the test near toJournalLines to include both brackets in the byte count: `[`, `"`, the four-byte emoji, `"`, and `]` total 8 bytes, plus the newline. Keep the existing endPosition assertion unchanged.docs/sandbox/takeover.md-84-87 (1)
84-87: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd a language to the fenced block.
markdownlint reports MD040 here. The block holds error text, so
textis the right fence language.📝 Proposed fix
-``` +```text durableStream: a runId is required: send it as an X-Run-Id header or a ?runId query param</details> <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.
In
@docs/sandbox/takeover.mdaround lines 84 - 87, Update the fenced block containing the durableStream error text to declare the text language, using a text fence to satisfy Markdown linting.</details> <!-- cr-comment:v1:a15f84778137d5314413b04b --> _Source: Linters/SAST tools_ </blockquote></details> <details> <summary>docs/persistence/build-your-own-adapter.md-668-674 (1)</summary><blockquote> `668-674`: _📐 Maintainability & Code Quality_ | _🟡 Minor_ | _⚡ Quick win_ **Update the description of the `examples/ts-react-chat` adapter.** This paragraph says the example "declares those same two omissions", and lines 883-885 say it "implements only the three required methods plus `findActiveRun`". Both statements are stale in this PR. `examples/ts-react-chat/src/lib/sqlite-persistence.test.ts` passes `skipMethods: ['runs.listByThread']` only, and its new SQL-NULL test fails outright if `runs.listReclaimable` is absent. A reader following this page would declare an omission for a method the example implements and tests. <details> <summary>📝 Proposed fix</summary> ```diff -pass, and a declared omission shows up in the test output as a skipped case -rather than as nothing at all. When this is green, your adapter is a drop-in for -`withPersistence`. The `examples/ts-react-chat` app runs this suite against its -SQLite backend and declares those same two omissions. +pass, and a declared omission shows up in the test output as a skipped case +rather than as nothing at all. When this is green, your adapter is a drop-in for +`withPersistence`. The `examples/ts-react-chat` app runs this suite against its +SQLite backend and declares one omission, `runs.listByThread`.Apply the matching correction at lines 883-885:
-The reference implementation, `MemoryRunStore` in -`packages/ai-persistence/src/memory.ts`, implements all six. The -`examples/ts-react-chat` SQLite adapter (`src/lib/sqlite-persistence.ts`) -implements only the three required methods plus `findActiveRun`, which is a -fine illustration that the rest stay optional. +The reference implementation, `MemoryRunStore` in +`packages/ai-persistence/src/memory.ts`, implements all six. The +`examples/ts-react-chat` SQLite adapter (`src/lib/sqlite-persistence.ts`) +implements the three required methods plus `findActiveRun` and +`listReclaimable`, and omits `listByThread`, which is a fine illustration that +the rest stay optional.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-adapter.md` around lines 668 - 674, Update the adapter description in this paragraph and the corresponding text around the example implementation to state that the ts-react-chat adapter declares only skipMethods: ['runs.listByThread']; remove the claim that it omits both state-store keys or implements only three required methods, and acknowledge that runs.listReclaimable is implemented and covered by the SQL-NULL test.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/resumable-streams/advanced.md`: - Around line 200-218: Update appendAfterStored to validate the stored prefix against the corresponding replayed chunks before slicing. Compare each chunk in stored with replayed, throw immediately on the first mismatch, and only append the remaining replayed chunks after the entire prefix matches. In `@examples/ts-react-chat/src/lib/sqlite-persistence.ts`: - Around line 60-65: Update the schema initialization flow in sqlite-persistence.ts to run an idempotent migration immediately after SCHEMA_SQL is applied and before createRunStore prepares statements. Add any missing runs columns—error_code, sandbox_key, detached_since, cancel_requested, and driver_epoch—using the existing database connection, and ensure migrate is invoked for every supported database URL, including persistent non-memory databases. In `@packages/ai-durable-stream/src/durable-stream.ts`: - Around line 790-823: Update collectSnapshot to call ensureCreated() before readWindows, preserving the existing createdHere short-circuit so snapshot() returns an empty result for streams that do not yet exist instead of rejecting. Keep the current timeout, entry collection, and sequence seeding behavior unchanged. In `@packages/ai-sandbox-cloudflare/src/coordinator.ts`: - Around line 199-205: Update the local settle callback around onRunSettled so exceptions from either invocation are caught and reported, ensuring done.then(settle, settle) always produces a fulfilled promise for ctx.waitUntil. Preserve passing input.runId to onRunSettled and use the coordinator’s existing error-reporting mechanism. In `@packages/ai-sandbox-cloudflare/src/run-driver.ts`: - Around line 70-71: Update the stream consumption logic in run-driver.ts to race iterator progress against the provided AbortSignal instead of relying on nonstandard return?.()/throwReason behavior. When the signal aborts, handle the resulting completion or error so the run finishes with status aborted, including for an async source that never yields; add a regression test covering that never-yielding source. In `@packages/ai-sandbox-cloudflare/tests/run-log.test.ts`: - Around line 1-2: Move the run-log unit test from the tests directory to sit beside run-log.ts as run-log.test.ts, and update its InMemoryRunEventLog and isTerminalRunStatus import from the parent-relative path to the local ./run-log module. In `@packages/ai-sandbox-daytona/tests/journal.conformance.test.ts`: - Around line 1-37: Move the tests out of package-level tests directories and colocate them with their covered source modules: move packages/ai-sandbox-daytona/tests/journal.conformance.test.ts beside packages/ai-sandbox-daytona/src/index.ts and update its relative import; move packages/ai-sandbox/tests/testkit-subpath.test.ts beside the testkit entry module exporting the covered symbols; move packages/ai-persistence/tests/memory.test.ts beside packages/ai-persistence/src/memory.ts and update its relative import; move packages/ai-persistence/tests/error-abort.test.ts beside the persistence module implementing the abort behavior; and move packages/ai/tests/stream-durability.test.ts beside packages/ai/src/stream-durability.ts and update its relative import. In `@packages/ai-sandbox-docker/tests/docker.test.ts`: - Around line 334-342: Update the polling loop around probeRows to tolerate transient survivors: poll repeatedly until the result is empty or all attempts are exhausted, then perform a single final assertion on the settled result. Preserve the existing polling interval and retry count. In `@packages/ai-sandbox-local-process/src/handle.ts`: - Around line 506-526: Update terminateChildren to escalate a still-running POSIX process tree with SIGKILL when waitForExit reports false after the initial termination signal. Reuse the existing killTree path to perform the escalation while preserving killTree’s single-signal semantics for direct SpawnHandle.kill(signal) calls and the existing Windows behavior. In `@packages/ai-sandbox-local-process/tests/kill-tree.test.ts`: - Around line 182-217: Ensure both test bodies in packages/ai-sandbox-local-process/tests/kill-tree.test.ts at lines 182-217 and 239-267 wrap all work after provider.create() or noisy.create() in try/finally blocks, respectively; move each sandbox’s destroy call into its finally block so cleanup runs when parsing, killing, polling, or assertions fail. In `@packages/ai-sandbox/src/journal-reader.ts`: - Around line 153-168: Prevent abandoned iterator.next() promises from producing unhandled rejections in both helpers: at packages/ai-sandbox/src/journal-reader.ts lines 153-168, store iterator.next() locally and attach a swallowing catch before racing it with aborted; apply the same change at lines 218-239 for the first-value race against expired. Preserve the existing abort, stall, and cleanup behavior. In `@packages/ai-sandbox/src/middleware.ts`: - Around line 456-465: Guard the await of wasCancelRequested in the onAbort cancellation check so a durable-store rejection is treated as no durable cancel request. Ensure the rejection is contained and execution continues into the existing detach-or-destroy handling, including the subsequent guarded detach write and fallback to definition.destroy. In `@packages/ai-sandbox/src/runner.ts`: - Around line 99-105: Update toProcessOptions to omit signal along with onNonJsonLine, input, and journal before passing options to the journaled agent spawn, ensuring the spawned agent outlives request cancellation. Preserve signal handling in readJournalNdjson and its journal-reading flow so tail reads still respond to the request AbortSignal. In `@packages/ai/src/stream-to-response.ts`: - Around line 750-764: Update startRunDriver so the promise-level catch wraps the entire async body, including resolveResumeRunId(driver.request), rather than only catching later run-record operations. Ensure both waitUntil and the fallback path receive a non-rejecting promise, while preserving the existing logging and early-return behavior. --- Minor comments: In `@docs/persistence/build-your-own-adapter.md`: - Around line 668-674: Update the adapter description in this paragraph and the corresponding text around the example implementation to state that the ts-react-chat adapter declares only skipMethods: ['runs.listByThread']; remove the claim that it omits both state-store keys or implements only three required methods, and acknowledge that runs.listReclaimable is implemented and covered by the SQL-NULL test. In `@docs/persistence/overview.md`: - Line 156: Update the reload lifecycle statement near the sandboxed agent discussion to limit the “work is over” assumption to replaying or reading already-produced transcript data. Clarify that delivery durability can rejoin and continue tailing a still-streaming run, while preserving the existing distinction that a sandboxed agent requires takeover to keep driving after its host disappears. In `@docs/sandbox/journal.md`: - Around line 27-30: Update the fenced code block containing the /tmp/tanstack-runs path listing to declare the text language, preserving both listing entries unchanged. In `@docs/sandbox/providers.md`: - Around line 252-261: Resolve the contradiction between the introductory rule and the Sprites row: either revise the rule near “Anything that cannot be measured yet stays false” to explicitly allow a documented exception for real server-side kill mechanisms, or change the Sprites `killableProcesses` value to `false` while retaining its unverified endpoint details. Ensure the documented policy and provider value consistently communicate which rule governs unmeasured behavior. In `@docs/sandbox/reaping.md`: - Around line 341-342: Update the sizing link in the vercel.json registration guidance to use the heading’s correct anchor, including the trailing “ms” in “detachedrunttlms”. In `@docs/sandbox/takeover.md`: - Around line 84-87: Update the fenced block containing the durableStream error text to declare the text language, using a text fence to satisfy Markdown linting. In `@packages/ai-codex/src/adapters/text.ts`: - Around line 215-241: Move the durability lookup and the declarations of durability, runId, and threadId from before the try into the try block, placing them after const sandbox = this.sandboxFrom(options). Keep channel creation after these declarations so DurableRunIdRequiredError and DurableThreadIdRequiredError are handled by chatStream’s existing catch and emitted as RUN_ERROR chunks. In `@packages/ai-grok-build/tests/attach.test.ts`: - Around line 387-401: Update the test’s second run invocation to reuse the seeded runId instead of freshRunId, so it exercises attach: false with an existing journal entry for the same run. Keep the surrounding reference log setup and assertions unchanged, and retain the comment describing the colliding-runId behavior. In `@packages/ai-sandbox-daytona/tests/journal.conformance.test.ts`: - Around line 21-36: Update the DAYTONA_API_KEY handling in the createHandle callback and unsupported spread so an empty string is treated as unavailable consistently. Use a truthiness check when deciding whether to pass apiKey to daytonaSandbox, preserving the existing unsupported state for missing or empty credentials. In `@packages/ai-sandbox-docker/src/handle.ts`: - Around line 226-236: Add a short bounded polling re-check between the SIGKILL and the existing kill -0 verification in the shell command assembled by the process-kill logic. Repeatedly test whether the pid remains present, sleeping briefly between attempts, and only echo KILL_FAILED_MARKER if it is still present after the bounded window; preserve the existing no-pid behavior and marker symbols. In `@packages/ai-sandbox-docker/tests/docker.test.ts`: - Around line 64-65: Replace the ineffective inspected.Id assertion in the snapshot verification test with a filesystem-specific check: verify inspected.Size is greater than zero or confirm that a file written earlier is readable after restoring from snapshotTag. Keep the assertion aligned with the comment’s claim that the container filesystem was captured. In `@packages/ai-sandbox-local-process/tests/local-process.test.ts`: - Around line 136-158: Wrap the probe lifecycle in a try/finally block so cleanup always runs when either assertion or polling fails. Keep the existing visibility, kill, wait, and survivor assertions in the try block, and move proc.kill() and sbx.destroy() into finally, ensuring the spawned process is released even on test failure. In `@packages/ai-sandbox/package.json`: - Line 62: Update the `@tanstack/ai` entry in peerDependencies to use the workspace:* protocol, matching its devDependencies declaration and the repository’s internal dependency convention. In `@packages/ai-sandbox/src/chunk-identity.ts`: - Around line 92-99: Update the undefined-field encoding in the keys mapping near stableStringify so it uses an unquoted sentinel token rather than the quoted "__undefined__" string. Preserve JSON.stringify encoding for all real values, ensuring present undefined fields remain distinct from the literal string "__undefined__" in the generated fingerprint. In `@packages/ai-sandbox/src/run.ts`: - Around line 116-120: Update the durability factory documentation near the durability callback type to remove the claim that it is called exactly once per run. State instead that the factory may be called multiple times and must resolve the same stored run/log for a given runId so separate instances observe the same appends. In `@packages/ai-sandbox/src/shell.ts`: - Around line 209-245: Update the read flow around nextLine() and the deadline in run() to track the pending resolver for the current stdout read and remove it from pending when the timeout wins. Ensure the timed-out read is cancelled before throwing, while preserving normal line handling and sentinel processing for non-timeout runs. In `@packages/ai-sandbox/src/testkit/journal-conformance.ts`: - Around line 195-196: Reduce PROBE_MAX_TICKS so the kill probe’s one-second-per-tick loop completes within CASE_TIMEOUT_MS, including reasonable timeout overhead. Update the adjacent comment to accurately state that the cap keeps the probe bounded by the case timeout and preserves the existing teardown behavior. - Around line 470-475: In the process-launch setup around handle.process.spawn, await the promise returned by spawn so any launch failure fails the conformance case directly. Keep the existing behavior of avoiding a later SpawnHandle.wait() call and preserve the __exit sentinel as the completion check after the awaited spawn. In `@packages/ai-sandbox/tests/journal-bytes.test.ts`: - Around line 142-150: Correct the explanatory comment in the test near toJournalLines to include both brackets in the byte count: `[`, `"`, the four-byte emoji, `"`, and `]` total 8 bytes, plus the newline. Keep the existing endPosition assertion unchanged. In `@packages/ai-sandbox/tests/journal.test.ts`: - Around line 197-204: Update the truncation assertion in the journaledCommand test to check directly that the command does not contain the single-redirect form for the journal path, without relying on a trailing newline. Keep the existing append-redirection assertion unchanged. In `@packages/ai-sandbox/tests/reclaim.test.ts`: - Around line 76-87: Update the test setup around trackDestroys and provider.destroy so the tracked wrapper remains installed while its implementation rejects with “already gone”; configure the rejection inside that wrapper rather than replacing provider.destroy afterward. Preserve the existing outcome, instance removal, and destroyed assertions so the test verifies reclaimSandbox calls destroy and handles the rejection. --- Nitpick comments: In @.changeset/durable-stream-runid-resolution.md: - Around line 1-3: Update the changeset release level from patch to minor to document the breaking behavior change where requests without a header or query run id now throw instead of generating one. In @.changeset/local-process-kill-tree-verified.md: - Around line 1-3: Update the changeset front matter for `@tanstack/ai-sandbox-local-process` from patch to minor to reflect the new public logger option on localProcessSandbox and the exported LocalProcessLogger type. In `@packages/ai-acp/tests/durability-attach.test.ts`: - Around line 176-274: Wrap each test body in the durability attach test suite with a try/finally around the sandbox-dependent assertions, and move await sbx.destroy() into the finally block. Apply this to the tests shown, including the refusal, fresh durable run, and no-durability cases, so cleanup runs even when assertions or setup-dependent operations fail. In `@packages/ai-acp/tests/run-id-fallback.test.ts`: - Around line 14-34: Update the tests in the “acp runId resolution” suite to exercise the ACP adapter’s runId resolution in packages/ai-acp/src/adapters/compatible.ts rather than calling resolveDurableRunId directly. Cover both the generated fallback and caller-supplied runId paths, or spy on resolveDurableRunId to verify the adapter invokes it with durable: false and the expected arguments. In `@packages/ai-claude-code/tests/attach.test.ts`: - Around line 118-120: Update the shell command in the attach test’s journal-seeding flow to single-quote both interpolated paths, paths.dir and paths.journal, while preserving the existing base64 write behavior. Follow the quoting approach used by the seedJournal implementation in the grok-build sibling. In `@packages/ai-durable-stream/tests/offset-composition.test-d.ts`: - Around line 11-16: Update the variance description in the offset-composition test comment to state that StreamDurability is invariant in TOffset, reflecting its use in both input and output positions. Keep the surrounding explanation and referenced symbols unchanged. In `@packages/ai-grok-build/tests/translate-determinism.test.ts`: - Around line 160-198: Remove the journal-specific rationale and best-effort journal cleanup from this test, since capabilityContextWith(sbx) supplies only SandboxCapability and keeps the execution unjournaled. Preserve the unique runId generation and message ID shape assertions; only add SandboxDurabilityCapability wiring if this test is explicitly intended to validate journaling. In `@packages/ai-opencode/tests/durability-attach.test.ts`: - Around line 46-137: Extract the shared noopLogger, fakeAdapterLog, durability, and contextWith helpers into `@tanstack/ai-sandbox`’s existing testkit subpath, preserving the SandboxRunDurability, SandboxCapability, and SandboxDurabilityCapability contract. In packages/ai-opencode/tests/durability-attach.test.ts lines 46-137 and packages/ai-grok-build/tests/durability-protocol-warning.test.ts lines 151-203, remove the local definitions and import the shared implementations instead. In `@packages/ai-persistence/tests/abort-status.test.ts`: - Around line 168-199: Extract the duplicated interrupt-boundary adapter setup from the inline adapter in the “interrupt status shape” test and interruptThenHangAdapter into a shared interruptAdapter(signal?: AbortSignal) helper. Centralize the RUN_STARTED and interrupt RUN_FINISHED chunks there, and retain the optional abort-wait behavior only when a signal is provided; update both call sites to use the helper. In `@packages/ai-sandbox-daytona/tests/handle.test.ts`: - Around line 1-2: Move packages/ai-sandbox-daytona/tests/handle.test.ts beside packages/ai-sandbox-daytona/src/handle.ts, and move packages/ai/tests/run-store.test.ts beside packages/ai/src/activities/chat/middleware/run-store.ts; preserve both tests’ contents and update imports only as needed after relocation. In `@packages/ai-sandbox-docker/tests/docker-daemon.ts`: - Around line 63-79: Bound the Docker connectivity check in dockerDaemonGate by racing the Dockerode ping against a short timeout, converting timeout rejection into the existing describeError failure path. Preserve the current behavior: return the named unsupported result when Docker is optional, and throw the existing hard failure when dockerIsRequired() is true. In `@packages/ai-sandbox-local-process/src/handle.ts`: - Around line 837-845: Update spawnProcess around the abort listener registration to retain the listener callback and remove it when the spawned child closes, using the child process close handling to perform cleanup. Preserve the once-only abort behavior while ensuring completed children no longer respond to later aborts on a shared AbortSignal. In `@packages/ai-sandbox-local-process/src/index.ts`: - Around line 3-15: Remove the Windows-specific helpers classifyTaskkillResult, msysDescendantWinPids, parseMsysProcessTable, and taskkillPid from the package root exports in index.ts, while preserving LocalProcessHandle, LOCAL_PROCESS_CAPS, and the public types. Keep tests importing the helpers directly from handle, or expose them only through a dedicated subpath if that package convention is required. In `@packages/ai-sandbox-local-process/tests/destroy-teardown.test.ts`: - Around line 205-210: Replace the fixed 200 ms timeout in the destroy-teardown test with an explicit child-process readiness signal: have the holder child write a recognizable line to stdout after establishing its CWD, then await that line before calling removeDirWithRetry. Preserve the existing assertions for exactly one “still busy” warning and the directory metadata. In `@packages/ai-sandbox-local-process/tests/journal.conformance.test.ts`: - Around line 14-16: Update the afterAll cleanup in journal.conformance.test.ts to configure fsp.rm with removal retries, including the retry count and retry delay used by the corresponding takeover.conformance.test.ts cleanup. Preserve recursive and force deletion so teardown tolerates directories briefly remaining pinned by exiting processes. In `@packages/ai-sandbox-local-process/tests/reaper.conformance.test.ts`: - Around line 25-27: Make the afterAll cleanup around fsp.rm non-fatal by wrapping the baseDir removal in try/catch and swallowing cleanup errors such as Windows EBUSY; preserve the existing recursive, forceful removal behavior. In `@packages/ai-sandbox-local-process/tests/takeover.conformance.test.ts`: - Around line 20-22: Update the afterAll cleanup in the takeover conformance test to use the same bounded removal-retry pattern as destroy-teardown.test.ts, so transient EBUSY failures from a live process CWD are retried before teardown ultimately fails. In `@packages/ai-sandbox-vercel/tests/vercel.test.ts`: - Around line 110-122: Update the abort propagation test around makeHandle(sandbox).process.spawn to replace the fixed setTimeout(0) delay with vi.waitFor wrapping the kill assertion, allowing the async abort handler to complete before verifying kill was called with SIGKILL. In `@packages/ai-sandbox/src/align.ts`: - Around line 278-291: Replace the plain Error thrown by the short-replay branch in the alignment loop with JournalReplayDivergedError or an appropriate dedicated subclass, passing the trailing index as required by its constructor. Preserve the existing divergence message and ensure truncated replays are identifiable via instanceof JournalReplayDivergedError. In `@packages/ai-sandbox/src/driver.ts`: - Around line 175-201: Resolve input.durability(i.runId) once at the start of pipe, store the returned durability instance, and reuse it for both awaitLogQuiescence and fenceDurability. Ensure the fenced factory no longer invokes input.durability a second time, while preserving the existing claim validation and fencing behavior. In `@packages/ai-sandbox/src/run.ts`: - Around line 307-317: Consider batching buffered chunks before calling durability.append in the stream loop to reduce sequential network round trips, while preserving append’s per-chunk offset contract. Flush the batch immediately when a terminal RUN_ERROR chunk is encountered, and account for the epoch-fence implications of larger batches; this is optional follow-up work rather than a required PR change. In `@packages/ai-sandbox/src/sandbox.ts`: - Around line 269-279: Align SandboxDefinition.destroy with reclaim.ts by choosing and explicitly implementing a consistent failed-destroy policy, ensuring store.delete(key) is handled according to that policy even when provider.destroy aborts or rejects. Review every caller of SandboxDefinition.destroy, including definition.destroy and sandbox.destroy usages, and update them to explicitly handle any rejection introduced by the timeout. In `@packages/ai-sandbox/tests/durability.test.ts`: - Around line 258-263: Update the “withSandbox durability options declare no TTL” test to check both detachedRunTtl and detachedRunTtlMs on each of SandboxDurabilityOptions and SandboxRunDurability, preserving the existing type-level assertion style. In `@packages/ai-sandbox/tests/middleware-durability.test.ts`: - Around line 142-152: Remove the unused runs field from the Harness type and the returned harness object around the middleware test harness factory. Do not create a fallback InMemoryRunStore there; retain the middleware’s existing store wiring and leave the other harness fields unchanged. In `@packages/ai-sandbox/tests/run-driver.test.ts`: - Around line 42-50: Update textChunk to return the object literal directly as StreamChunk, removing the `as unknown as StreamChunk` double cast while preserving its existing fields and values. In `@packages/ai/tests/resume-driver.test.ts`: - Around line 413-447: Strengthen the test around resumeServerSentEventsResponse so it explicitly verifies the mocked driver.drive was invoked, distinguishing the thrown-drive path from the existing “not driving this run” path. Keep the current logging assertion and response behavior checks unchanged.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
docs/resumable-streams/advanced.md lines 215 to 233@@ -181,0 +198,21 @@198+degraded experience.199+200+The mechanism for it is `snapshot()` plus plain `append`, not caller-chosen201+offsets. Read what the log already holds, compare it against your replay,202+suppress the matching prefix, and append only the remainder:203+204+```ts205+import { memoryStream } from '@tanstack/ai'206+import type { StreamChunk } from '@tanstack/ai'207+208+async function appendAfterStored(209+ request: Request,210+ replayed: Array<StreamChunk>,211+) {212+ const durability = memoryStream(request)213+ const stored = await durability.snapshot()214+ // `snapshot` returns without waiting, even while the log is open, so this215+ // works on a log whose previous producer died without calling `close()`.216+ const remainder = replayed.slice(stored.length)217+ if (remainder.length > 0) await durability.append(remainder)218+}🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Validate the stored prefix before slicing.
The text requires a replay comparison, but line 216 only removes
stored.lengthentries. If replay diverges within that prefix, this sample appends an invalid remainder instead of failing. That can duplicate text or corrupt tool-call arguments.Compare each stored chunk with the matching replayed chunk, throw on the first mismatch, and append only after the validated prefix.
Proposed documentation sample
async function appendAfterStored( request: Request, replayed: Array<StreamChunk>, + sameChunk: (stored: StreamChunk, replayed: StreamChunk) => boolean, ) { const durability = memoryStream(request) const stored = await durability.snapshot() - // `snapshot` returns without waiting, even while the log is open, so this - // works on a log whose previous producer died without calling `close()`. + if (replayed.length < stored.length) { + throw new Error('replay ended before the stored journal') + } + for (let index = 0; index < stored.length; index += 1) { + const entry = stored[index] + const replayedChunk = replayed[index] + if ( + entry === undefined || + replayedChunk === undefined || + !sameChunk(entry.chunk, replayedChunk) + ) { + throw new Error(`replay diverged at chunk ${index}`) + } + } const remainder = replayed.slice(stored.length) if (remainder.length > 0) await durability.append(remainder) }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
import { memoryStream } from '`@tanstack/ai`' import type { StreamChunk } from '`@tanstack/ai`' async function appendAfterStored( request: Request, replayed: Array<StreamChunk>, sameChunk: (stored: StreamChunk, replayed: StreamChunk) => boolean, ) { const durability = memoryStream(request) const stored = await durability.snapshot() if (replayed.length < stored.length) { throw new Error('replay ended before the stored journal') } for (let index = 0; index < stored.length; index += 1) { const entry = stored[index] const replayedChunk = replayed[index] if ( entry === undefined || replayedChunk === undefined || !sameChunk(entry.chunk, replayedChunk) ) { throw new Error(`replay diverged at chunk ${index}`) } } const remainder = replayed.slice(stored.length) if (remainder.length > 0) await durability.append(remainder) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/resumable-streams/advanced.md` around lines 200 - 218, Update appendAfterStored to validate the stored prefix against the corresponding replayed chunks before slicing. Compare each chunk in stored with replayed, throw immediately on the first mismatch, and only append the remaining replayed chunks after the entire prefix matches.@@ -57,4 +57,9 @@5757 started_at integer NOT NULL,5858 finished_at integer,5959 error text,60- usage_json text60+ error_code text,61+ usage_json text,62+ sandbox_key text,63+ detached_since integer,64+ cancel_requested integer,65+ driver_epoch integer🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Add an additive migration for the new
runscolumns.CREATE TABLE IF NOT EXISTS runsdoes not alter a table that already exists. A database file created by the previous version has noerror_code,sandbox_key,detached_since,cancel_requested, ordriver_epochcolumn. Two failures follow on such a file:createRunStorepreparesreclaimableStmteagerly (Line 221).node:sqliteresolves column names at prepare time, so the factory throwsno such column: detached_sincebefore any request is served.updateemitsSET detached_since = ?and fails at runtime for the same reason.
Add idempotent
ALTER TABLE ... ADD COLUMNstatements after the schema is applied. SQLite allows adding a nullable column without a table rewrite.🛠️ Suggested additive migration
const RUNS_COLUMNS: Array<[string, string]> = [ ['error_code', 'text'], ['sandbox_key', 'text'], ['detached_since', 'integer'], ['cancel_requested', 'integer'], ['driver_epoch', 'integer'], ] // Run AFTER SCHEMA_SQL, BEFORE any statement is prepared. `CREATE TABLE IF NOT // EXISTS` is a no-op on an existing table, so a database created by an earlier // version reaches this point without the durable-run columns. function migrateRuns(db: DatabaseSync): void { const existing = new Set( (db.prepare('SELECT name FROM pragma_table_info(?)').all('runs') as Array<{ name: string }>).map((r) => r.name), ) for (const [column, type] of RUNS_COLUMNS) { if (!existing.has(column)) { db.exec(`ALTER TABLE runs ADD COLUMN ${column} ${type}`) } } }Confirm how
migrateis wired and whether a non-:memory:url is supported, because that decides whether this path is reachable in the example.#!/bin/bash # Description: Inspect the schema application path and url handling in the example store. fd -t f 'sqlite-persistence.ts' -x sh -c 'echo "== {}"; rg -n -C6 "SCHEMA_SQL|migrate|url|DatabaseSync" "{}"'🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/ts-react-chat/src/lib/sqlite-persistence.ts` around lines 60 - 65, Update the schema initialization flow in sqlite-persistence.ts to run an idempotent migration immediately after SCHEMA_SQL is applied and before createRunStore prepares statements. Add any missing runs columns—error_code, sandbox_key, detached_since, cancel_requested, and driver_epoch—using the existing database connection, and ensure migrate is invoked for every supported database URL, including persistent non-memory databases.✅ Addressed in commits b5989ba to 615a425
@@ -534,0 +803,21 @@803+ try {804+ const entries: Array<{805+ offset: DurableStreamOffset806+ chunk: StreamChunk807+ }> = []808+ for await (const entry of readWindows('-1', controller.signal, true)) {809+ entries.push(entry)810+ }811+ if (timedOut) {812+ throw new DurableStreamError(813+ `snapshot exceeded operationTimeoutMs (${operationTimeoutMs}ms) before the backend reported upToDate`,814+ )815+ }816+ // A completed snapshot has seen every record stored, so `observeSeq` has817+ // already moved `nextSeq` past the log's tail.818+ seqSeeded = true819+ return entries820+ } finally {821+ clearTimeout(timer)822+ }823+ }🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
snapshot()can reject on a stream that was never created.collectSnapshotissues the read directly and never callsensureCreated().readWindowsthrowshttpFailure('read', response)for a non-OK response, so aGETagainst a stream the backend does not hold yet surfaces as a rejection rather than an empty snapshot.That path is reachable.
awaitLogQuiescenceinpackages/ai-sandbox/src/driver.ts(lines 143-205 of the supplied snippet) callssnapshot()twice before the first append, so a first-time producer snapshots a stream that noPUThas created.memoryStream.snapshot()resolves to[]for an unknown run, so the two adapters disagree on this contract.Call
ensureCreated()at the start ofcollectSnapshot, which also lets it reuse thecreatedHereshort-circuit.🐛 Proposed fix
const controller = new AbortController() let timedOut = false + // Create-then-read, so a snapshot taken before the first append answers + // `[]` instead of a 404 from the backend. + await ensureCreated() + if (createdHere) { + seqSeeded = true + return [] + } const timer = setTimeout(() => {#!/bin/bash # Confirm snapshot() is called before any append, and how peers behave for an unknown run. rg -nP -C4 '\bsnapshot\s*\(' packages/ai-sandbox/src/driver.ts packages/ai/src/stream-durability.ts rg -nP -C6 'awaitLogQuiescence' packages/ai-sandbox/src rg -nP -C4 'snapshot' packages/ai-durable-stream/tests/durable-stream.test.tsAlso applies to: 935-936
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-durable-stream/src/durable-stream.ts` around lines 790 - 823, Update collectSnapshot to call ensureCreated() before readWindows, preserving the existing createdHere short-circuit so snapshot() returns an empty result for streams that do not yet exist instead of rejecting. Keep the current timeout, entry collection, and sequence seeding behavior unchanged.✅ Addressed in commits b5989ba to 615a425
packages/ai-sandbox-cloudflare/src/coordinator.ts lines 185 to 191@@ -172,6 +196,10 @@172196 threadId: input.threadId,173197 stream,174198 })175- // Keep the instance alive until the run is terminal; `pipeToRunLog` never176- // rejects (failures land in the log), so no `.catch` is needed.177- this.ctx.waitUntil(done.finally(() => this.onRunSettled(input.runId)))199+ // Keep the instance alive until the run is terminal. `pipeToRunLog` never200+ // rejects (failures land in the log), but this must not DEPEND on that:201+ // `.finally` adopts a rejection, which would hand `waitUntil` a rejected202+ // promise. Two-argument `then` settles fulfilled either way while still203+ // running the settle hook.204+ const settle = (): void => this.onRunSettled(input.runId)205+ this.ctx.waitUntil(done.then(settle, settle))🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== locate coordinator.ts ==" fd -a 'coordinator\.ts$' . | sed 's#^\./##' echo "== git diff stat ==" git diff --stat echo "== relevant coordinator excerpt ==" file="$(fd 'coordinator\.ts$' . | head -n1)" if [ -n "${file:-}" ]; then nl -ba "$file" | sed -n '170,225p' echo "== onRunSettled references ==" rg -n "onRunSettled|waitUntil|pipeToRunLog|done" "$file" fi echo "== Promise.then semantics probe ==" node - <<'JS' function settledFromThen(v, thenArg) { let thenResolved = false let thenRejected = false let settledValue const p = Promise.resolve(v) .then(thenArg, thenArg) .then(v => { thenResolved = true; settledValue = v }, e => { thenRejected = true; settledValue = e }) return { p, thenResolved, thenRejected, settledValue } } const thrown = new Error('hook error') const p = settledFromThen(undefined, () => Promise.resolve(undefined).then(() => { throw thrown }) ).p p.catch(e => console.log(JSON.stringify({error: e.message}, e => e.message))) setTimeout(() => { console.log(JSON.stringify({thenResolved: false, thenRejected: true})) }, 10) JSRepository: TanStack/ai
Length of output: 1911
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== repository status ==" pwd git status --short || true git ls-files | sed -n '1,80p' echo "== locate coordinator.ts ==" fd -a 'coordinator\.ts$' . | sed 's#^\./##' || true echo "== reference excerpt if file exists ==" file="$(fd 'coordinator\.ts$' . | head -n1 || true)" if [ -n "${file:-}" ]; then echo "-- file: $file --" wc -l "$file" nl -ba "$file" | sed -n '170,225p' echo "== symbols ==" rg -n "onRunSettled|waitUntil|pipeToRunLog|done|class .*Coordinator|extends .*Coordinator" "$file" || true fi echo "== package context ==" if [ -f packages/ai-sandbox-cloudflare/src/coordinator.ts ]; then nl -ba packages/ai-sandbox-cloudflare/src/coordinator.ts | sed -n '170,225p' rg -n "onRunSettled|waitUntil|pipeToRunLog|done|class .*Coordinator|extends .*Coordinator" packages/ai-sandbox-cloudflare/src/coordinator.ts fi echo "== Promise.then callback exception propagation probe ==" node - <<'JS' function run(name, runValue) { const [thenResolved, thenRejected] = (() => { let r = false let e = false const p = Promise.resolve(runValue) .then(() => { throw new Error('callback error') }, () => { throw new Error('callback error') }) .then( v => r = v, err => { e = err; throw err } ).then( v => r = v, err => e = err ) return [p, r, e] })() console.log(name) Promise.all([thenResolved, thenRejected]).then(([resolved, rejected], err) => { console.log(JSON.stringify({name, resolved, rejected: rejected && rejected.message}), null, 2) }) } run('fulfilled run thrown by then callback', undefined) run('rejected run thrown by catchError callback', undefined) setTimeout(() => {}, 10) JSRepository: TanStack/ai
Length of output: 1911
🌐 Web query:
MDN Promise then documentation callback error returned promise rejected adopts rejection💡 Result:
When you call the.then method on a Promise, it always returns a new, pending Promise [1][2]. The state of this new promise is determined by the result of the executed callback (onFulfilled or onRejected) [1][3]: 1. If the callback returns a value, the new promise is fulfilled with that value [1][3]. 2. If the callback throws an error, the new promise is rejected with that error as its reason [1][3]. 3. If the callback returns a promise (or thenable), the new promise adopts the state of the returned promise [1][3]. This means if the returned promise is rejected, the promise returned by.then will also be rejected with the same reason [1][2]. In summary, if your callback returns a promise that subsequently rejects, or if the callback itself throws an error, the promise returned by.then will reject [1][2]. This mechanism allows for chaining, where a rejection can be propagated down the chain until it is caught by a rejection handler [4]. If no handler is present, the rejection continues to propagate [5].
Citations:
- 1: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
- 2: https://devdoc.net/web/developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then.html
- 3: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise?redirectlocale=en-US&redirectslug=Web%2FAPI%2FPromise
- 4: https://jsguides.dev/reference/async-apis/promise-prototype-then/
- 5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Contain exceptions from
onRunSettled.done.then(settle, settle)returns a rejected promise if either callback throws. If a subclass throws fromonRunSettled, that rejection is passed toctx.waitUntil. Catch exceptions insidesettleand report them instead of letting the hook fail the wait-until promise.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-cloudflare/src/coordinator.ts` around lines 199 - 205, Update the local settle callback around onRunSettled so exceptions from either invocation are caught and reported, ensuring done.then(settle, settle) always produces a fulfilled promise for ctx.waitUntil. Preserve passing input.runId to onRunSettled and use the coordinator’s existing error-reporting mechanism.packages/ai-sandbox-cloudflare/src/run-driver.ts lines 70 to 71Outdated@@ -0,0 +51,21 @@51+52+/** Render an unknown thrown value as a stable error message. */53+function messageOf(error: unknown): string {54+ return error instanceof Error ? error.message : String(error)55+}56+57+/** Build the synthetic RUN_ERROR chunk appended when the stream throws. */58+function syntheticRunError(message: string): StreamChunk {59+ const chunk: { type: EventType.RUN_ERROR; message: string } = {60+ type: EventType.RUN_ERROR,61+ message,62+ }63+ return chunk64+}65+66+export interface PipeToRunLogOptions {67+ log: RunEventLog68+ runId: string69+ threadId?: string70+ /** Abort consumption mid-stream; the run finishes as `aborted`. */71+ signal?: AbortSignal🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Locate file and relevant sections" fd -a 'run-driver.ts|run-driver' . | sed 's#^\./##' echo echo "Outline" ast-grep outline packages/ai-sandbox-cloudflare/src/run-driver.ts --view expanded || true echo echo "Relevant lines" nl -ba packages/ai-sandbox-cloudflare/src/run-driver.ts | sed -n '55,90p;170,200p' echo echo "Search symbol usages" rg -n "PipeToRunLogOptions|pipeToRunLog|signal\?:" packages/ai-sandbox-cloudflare/src/run-driver.tsRepository: TanStack/ai
Length of output: 1911
🌐 Web query:
TanStack ai packages ai-sandbox-cloudflare src run-driver.ts PipeToRunLogOptions signal💡 Result:
In the context of the TanStack AI ecosystem, specifically within the
@tanstack/ai-sandbox-cloudflarepackage and its internal runners, the components you referenced relate to the edge-native orchestration of coding agents [1][2]. 1. run-driver.ts: This internal file is associated with the sandbox harness runner [1]. When using@tanstack/ai-sandbox-cloudflarein colocated mode,runInContainerHarness(from/runner) is used to bridge the container's environment with the Cloudflare Worker [1][2]. This setup allows an agent loop, the sandbox container, and a live preview URL to exist at the edge [1]. 2. PipeToRunLogOptions: This is a configuration type (or related interface) involved in logging and event management within the sandbox environment [2]. It governs how run logs are piped or handled, ensuring that events (often mirrored over Durable Objects in the Cloudflare runtime) are correctly captured and persisted [2]. 3. signal: In TanStack AI orchestration,signalrefers to anAbortSignal[3]. It is used to handle run cancellation and process lifecycle management [3][4]. When passed to orchestration functions, it allows the system to abort ongoing operations (such asfetchrequests or AI chat iterations) effectively [3][4]. In summary, these components form part of the infrastructure for building edge-native AI coding agents that can scaffold, modify, and preview applications directly within a Cloudflare environment [1][5]. Therun-driverhandles the execution harness,PipeToRunLogOptionsmanages the flow of execution telemetry, andsignalprovides the standard mechanism for aborting these processes [1][2][3].Citations:
- 1: https://tanstack.com/ai/latest/docs/sandbox/cloudflare
- 2: https://github.com/TanStack/ai/blob/4ab149fd46a1cf55691266cdd118fdc9999c0b2a/packages/ai-sandbox/skills/ai-sandbox/SKILL.md
- 3: https://github.com/TanStack/ai/blob/worktree-cryptic-singing-wadler/docs/api/ai-orchestration.md
- 4: https://github.com/TanStack/ai/blob/4ab149fd46a1cf55691266cdd118fdc9999c0b2a/packages/ai/skills/ai-core/middleware/SKILL.md
- 5: https://tanstack.com/ai/latest/docs/sandbox/quick-start
🌐 Web query:
site:github.com/TanStack/ai packages/ai-sandbox-cloudflare/src/run-driver.ts "signal\?\:"💡 Result:
In the context of the TanStack AI framework, specifically within
@tanstack/ai-sandbox-cloudflare, the signal property (often typed asAbortSignal?) refers to a standard Web API AbortSignal used for request cancellation [1][2][3]. When present in modules likerun-driver.tsor related orchestration and middleware code, it is used to propagate cancellation signals through the system [2][3]. This allows long-running operations—such as AI model chat requests, tool execution, or sandbox processes—to be aborted gracefully when the client disconnects or the user explicitly triggers an abort [2][3][4]. Key characteristics include: - Abort Propagation: The signal is often passed to native Web APIs like fetch or custom logic to ensure that ongoing work is terminated when the signal fires [2][4]. - Middleware Integration: In chat middleware and sandbox hooks, it is part of the context object (e.g., ChatMiddlewareContext) provided to hooks, allowing developers to check for abortion or pass the signal to their own side effects [3][4][5]. - Orchestration: In workflow and orchestration APIs, it is used to manage the lifecycle of a run, allowing for the cancellation of active streams [1][2]. If you are encountering this in your codebase, it indicates an interface or function parameter designed to receive an external abort signal to facilitate responsive, cancellable execution [2][3].Citations:
- 1: https://github.com/TanStack/ai/blob/worktree-cryptic-singing-wadler/docs/api/ai-orchestration.md
- 2: https://github.com/TanStack/ai/blob/worktree-cryptic-singing-wadler/docs/orchestration/workflows.md
- 3: https://github.com/TanStack/ai/blob/main/packages/ai/src/activities/chat/middleware/types.ts
- 4: https://github.com/TanStack/ai/blob/4ab149fd46a1cf55691266cdd118fdc9999c0b2a/packages/ai/skills/ai-core/tool-calling/SKILL.md
- 5: https://github.com/TanStack/ai/blob/4ab149fd46a1cf55691266cdd118fdc9999c0b2a/packages/ai/skills/ai-core/middleware/SKILL.md
🌐 Web query:
github.com TanStack ai packages ai-sandbox-cloudflare src run-driver.ts "for await"💡 Result:
The TanStack AI SDK uses the
for awaitsyntax extensively to consume asynchronous streams generated by various components of the library, including agent runs, workflow executions, and chat completions [1][2][3]. In the context of the@tanstack/ai-sandbox-cloudflarepackage and related orchestration code (often involving run drivers or controllers),for awaitis the standard pattern for iterating over theAsyncIterablestream of chunks produced by an AI operation [1][3]. When an agent or workflow is initiated, it returns an asynchronous stream of events or content deltas. Developers usefor awaitto process these chunks sequentially as they arrive [1][3]: for await (const chunk of stream) { // Process individual chunks (e.g., text, tool calls, lifecycle events) } Within the orchestration engine (such as the logic found in packages likeai-orchestrationor sandbox runners),for awaitloops are used to drain or attach to running operations [4][2]. For instance, when managing workflows or agent runs: 1. Operations return anAsyncIterablethat encapsulates the execution state [1][2]. 2. Consumers (like server routes handling streaming responses or CLI tools) usefor awaitto iterate over thestreamorrunWorkflowoutput to handle UI updates, state persistence, or piping the output to the client [5][6][2]. 3. This pattern ensures that all lifecycle events—such asFINISHED,TEXT_MESSAGE_CONTENT, or pause/approval requests—are observed as they are yielded by the underlying generator [1][6][2]. If you are examiningrun-driver.tsor similar files, you are likely looking at the implementation of a coordinator that drives these generators, wherefor awaitis used to consume the output of a sandbox or agent runner, effectively bridging the execution engine with the requested output format [4][2].Citations:
- 1: https://tanstack.com/ai/latest/docs/getting-started/quick-start-server
- 2: https://github.com/TanStack/ai/pull/542
- 3: https://github.com/TanStack/ai/blob/main/packages/typescript/ai-client/README.md
- 4: https://github.com/TanStack/ai/blob/4ab149fd46a1cf55691266cdd118fdc9999c0b2a/packages/ai-sandbox/skills/ai-sandbox/SKILL.md
- 5: https://github.com/TanStack/ai/blob/worktree-cryptic-singing-wadler/docs/api/ai-orchestration.md
- 6: https://github.com/TanStack/ai/blob/worktree-cryptic-singing-wadler/docs/orchestration/workflows.md
🌐 Web query:
github.com TanStack/ai "pipeToRunLog" "Iterator.return"💡 Result:
In the TanStack AI library,
pipeToRunLogis a driver utility used to process streams, specifically by pumping achat()stream into a log [1][2]. RegardingIterator.return, this is not a specific public API or function directly exposed asTanStack/ai.pipeToRunLog.Iterator.return. Instead,Iterator.returnrefers to the standard JavaScript/TypeScript AsyncIterator protocol [3]. When working with AsyncIterables in TanStack AI (such as those returned bychat()or orchestration workflows), calling.return()on an iterator is the standard way to programmatically signal that you want to stop consuming the stream [3][4]. In the context of TanStack AI: -pipeToRunLogis designed to be robust; it pumps streams into a log and does not reject [1][2]. Stream errors are converted into terminalRUN_ERRORevents so that consumers can observe failures [1][2]. - When managing custom streams or integrating with other protocols (like converting anAsyncIterableto aReadableStream), you may explicitly calliterator.return?.()within acancelorfinallyblock to ensure resources are cleaned up and the upstream generator is closed properly [5][3]. If you are encountering this in a stack trace or code snippet, it is likely the engine or a wrapper cleaning up an active generator/workflow after a connection drop, abort, or completion [5][3].Citations:
- 1: https://github.com/TanStack/ai/blob/4ab149fd46a1cf55691266cdd118fdc9999c0b2a/packages/ai-sandbox/skills/ai-sandbox/SKILL.md
- 2: https://tessl.io/registry/skills/github/TanStack/ai/ai-sandbox
- 3: https://github.com/trpc/trpc/issues/6103
- 4: https://orpc.dev/docs/client/event-iterator
- 5: https://github.com/TanStack/ai/blob/worktree-cryptic-singing-wadler/docs/orchestration/workflows.md
🌐 Web query:
github.com TanStack/ai raw packages/ai-sandbox-cloudflare/src/run-driver.ts💡 Result:
The path
packages/ai-sandbox-cloudflare/src/run-driver.tsrefers to internal implementation files within the TanStack AI repository [1][2]. In the TanStack AI architecture, the@tanstack/ai-sandbox-cloudflarepackage provides functionality for running AI sandbox environments on Cloudflare's infrastructure [3][4]. While specific implementation files likerun-driver.tsare subject to change as part of the internal library codebase [5][6], they generally facilitate the integration between the TanStack AI sandbox orchestrator and the Cloudflare runtime [3][4]. This package typically manages: 1. Sandbox lifecycle: Creating and managing sandbox environments (often using Durable Objects) [4][7]. 2. Execution Harness: Supporting different modes of operation, such as 'colocated' (where a container harness runs in-environment) or DO-driven execution [3][4]. 3. Tool Execution: Bridging tool calls between the host process and the sandbox environment [3][8]. For developers working with this functionality, the public API is exposed through packages like@tanstack/ai-sandbox-cloudflare[3] and@tanstack/ai-isolate-cloudflare[9][8]. You should rely on the exported functions—such ascreateCloudflareSandboxAgent[3] orcreateCloudflareIsolateDriver[9]—rather than referencing internal source files directly, as internal file structures may be refactored [5][6]. For detailed usage, refer to the official TanStack AI documentation for Sandbox Providers [10] or Code Mode Isolates [11].Citations:
- 1: https://github.com/TanStack/ai
- 2: https://github.com/TanStack/ai/blob/main/README.md
- 3: https://tanstack.com/ai/latest/docs/sandbox/cloudflare
- 4: https://github.com/TanStack/ai/blob/4ab149fd46a1cf55691266cdd118fdc9999c0b2a/packages/ai-sandbox/skills/ai-sandbox/SKILL.md
- 5: https://github.com/TanStack/ai/tree/refs/heads/main
- 6: https://github.com/TanStack/ai/releases
- 7: https://github.com/TanStack/ai/releases/tag/%40tanstack/ai-sandbox-cloudflare%400.2.1
- 8: https://registry.npmjs.org/@tanstack/ai-isolate-cloudflare
- 9: https://tanstack.com/ai/latest/docs/code-mode/code-mode-isolates.md
- 10: https://tanstack.com/ai/latest/docs/sandbox/providers
- 11: https://tanstack.com/ai/latest/docs/code-mode/code-mode-isolates
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Show node availability and package data if installed" node --version 2>/dev/null || true npm list `@tanstack/ai-sandbox-cloudflare` 2>/dev/null | head -20 || true echo echo "Run a read-only AsyncIterator race probe using Node built-ins only" node - <<'JS' const signal = AbortSignal.any([AbortSignal.timeout(200)]); console.log(signal.aborted ? 'immediate' : 'initial'); async function neverYield() { console.log(asyncIteratorCount); while (true) { await new Promise(resolve => setTimeout(resolve, 5000)); } } for await (const chunk of neverYield()[Symbol.asyncIterator]()) { console.log('chunk', chunk); } JSRepository: TanStack/ai
Length of output: 1911
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Attempt lightweight read-only source checkout" git ls-files packages/ai-sandbox-cloudflare/src/run-driver.ts echo echo "Probe Node race behavior without cloning repo" node - <<'JS' let stopped = false ;(async () => { const signal = AbortSignal.timeout(350) const source = { [Symbol.asyncIterator]() { return { next() { return new Promise(resolve => { stopped = true setTimeout(() => resolve({ done: false, value: 'chunk' }), 2_000_000) }) }, return() { stopped = false return { done: true } } } } } for await (const chunk of source) { console.log('chunk', chunk) } console.log('loop_still_running_check', !stopped) })() setTimeout(() => process.exit(0), 1_200) JSRepository: TanStack/ai
Length of output: 1911
Propagate abort through the stream.
return?.()/throwReasonis not standard in this runtime/context here, so race iterator progress with thesignaland handle the returned completion/error instead. Add a regression test with an async source that never yields.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-cloudflare/src/run-driver.ts` around lines 70 - 71, Update the stream consumption logic in run-driver.ts to race iterator progress against the provided AbortSignal instead of relying on nonstandard return?.()/throwReason behavior. When the signal aborts, handle the resulting completion or error so the run finishes with status aborted, including for an async source that never yields; add a regression test covering that never-yielding source.packages/ai-sandbox-daytona/tests/journal.conformance.test.ts lines 1 to 37@@ -0,0 +17,21 @@17+import { runJournalConformance } from '@tanstack/ai-sandbox/testkit'18+import { daytonaSandbox } from '../src/index'19+20+// Auto-gate: these cases create real, billed cloud sandboxes.21+const apiKey = process.env.DAYTONA_API_KEY22+23+runJournalConformance({24+ name: 'daytona',25+ createHandle: async () => {26+ const provider = daytonaSandbox(apiKey !== undefined ? { apiKey } : {})27+ const handle = await provider.create({})28+ return { handle, dispose: () => handle.destroy() }29+ },30+ followUnsupported: {31+ reason:32+ 'killableProcesses is false — kill() only aborts the client-side poll loop and deleteSession is not documented to terminate a running command',33+ },34+ ...(apiKey35+ ? {}36+ : { unsupported: { reason: 'no DAYTONA_API_KEY in the environment' } }),37+})📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift
Place the changed unit tests beside their source modules.
These changed
*.test.tsfiles remain in package-leveltests/directories. The repository rule requires unit tests alongside the source they cover.packages/ai-sandbox-daytona/tests/journal.conformance.test.ts#L1-L37: move this test besidepackages/ai-sandbox-daytona/src/index.tsand update its relative import.packages/ai-sandbox/tests/testkit-subpath.test.ts#L1-L31: move this test beside the testkit entry module that exports the covered symbols.packages/ai-persistence/tests/memory.test.ts#L50-L78: move this test besidepackages/ai-persistence/src/memory.tsand update its relative import.packages/ai-persistence/tests/error-abort.test.ts#L94-L359: move this test beside the persistence module that implements the covered abort behavior.packages/ai/tests/stream-durability.test.ts#L403-L521: move this test besidepackages/ai/src/stream-durability.tsand update its relative import.
As per coding guidelines, “Place unit tests in
*.test.tsfiles alongside the source they cover.”📍 Affects 5 files
packages/ai-sandbox-daytona/tests/journal.conformance.test.ts#L1-L37(this comment)packages/ai-sandbox/tests/testkit-subpath.test.ts#L1-L31packages/ai-persistence/tests/memory.test.ts#L50-L78packages/ai-persistence/tests/error-abort.test.ts#L94-L359packages/ai/tests/stream-durability.test.ts#L403-L521
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-daytona/tests/journal.conformance.test.ts` around lines 1 - 37, Move the tests out of package-level tests directories and colocate them with their covered source modules: move packages/ai-sandbox-daytona/tests/journal.conformance.test.ts beside packages/ai-sandbox-daytona/src/index.ts and update its relative import; move packages/ai-sandbox/tests/testkit-subpath.test.ts beside the testkit entry module exporting the covered symbols; move packages/ai-persistence/tests/memory.test.ts beside packages/ai-persistence/src/memory.ts and update its relative import; move packages/ai-persistence/tests/error-abort.test.ts beside the persistence module implementing the abort behavior; and move packages/ai/tests/stream-durability.test.ts beside packages/ai/src/stream-durability.ts and update its relative import.Source: Coding guidelines
@@ -44,0 +322,21 @@322+ // exec; the container-side shell has not necessarily run its `echo $$`323+ // yet. `journal-reader` kills its follower this promptly on abort.324+ //325+ // With a bare `cat` on the pid file, `$pid` is empty here, `[ -n "$pid" ]`326+ // is false, NO signal is sent, and `stream.destroy()` only detaches the327+ // client — the exact pre-fix orphan. The bounded retry in328+ // `killRecordedPidCommand` is what closes it.329+ const proc = await handle.process.spawn(330+ `echo up; sleep ${KILL_PROBE_SLEEP}`,331+ )332+ await proc.kill()333+334+ // BusyBox `ps` prints argv, so a survivor is attributable to this test335+ // by its unique sleep duration. Poll: the racing shell may not have336+ // reached `sleep` yet when kill() ran, in which case the kill lands on337+ // its group and the process never appears at all — either way nothing338+ // may be running once things settle.339+ for (let i = 0; i < 12; i += 1) {340+ await new Promise((resolve) => setTimeout(resolve, 250))341+ expect(await probeRows()).toBe('')342+ }🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
The loop asserts on every poll, so a transient survivor fails the test.
The comment states that the racing shell may not have reached
sleepwhenkill()ran, and that "either way nothing may be running once things settle." The code does not wait for settling. It callsexpect(await probeRows()).toBe('')inside every iteration, so the first poll is already a hard assertion and the remaining 11 add no tolerance. If the probe is visible for one 250ms window, the test fails. Poll until empty, then assert once.🐛 Proposed fix
- for (let i = 0; i < 12; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 250)) - expect(await probeRows()).toBe('') - } + let survivors = await probeRows() + for (let i = 0; i < 12 && survivors !== ''; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 250)) + survivors = await probeRows() + } + expect(survivors).toBe('')📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
// BusyBox `ps` prints argv, so a survivor is attributable to this test // by its unique sleep duration. Poll: the racing shell may not have // reached `sleep` yet when kill() ran, in which case the kill lands on // its group and the process never appears at all — either way nothing // may be running once things settle. let survivors = await probeRows() for (let i = 0; i < 12 && survivors !== ''; i += 1) { await new Promise((resolve) => setTimeout(resolve, 250)) survivors = await probeRows() } expect(survivors).toBe('')🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-docker/tests/docker.test.ts` around lines 334 - 342, Update the polling loop around probeRows to tolerate transient survivors: poll repeatedly until the result is empty or all attempts are exhausted, then perform a single final assertion on the settled result. Preserve the existing polling interval and retry count.✅ Addressed in commits b5989ba to 615a425
@@ -131,0 +506,21 @@506+ if (process.platform !== 'win32') {507+ try {508+ // Negative pid = "the whole group", reaching the descendants that509+ // signalling `pid` alone would orphan.510+ process.kill(-pid, signal ?? 'SIGTERM')511+ } catch (error) {512+ // ESRCH means the group is already gone — the ordinary "it exited on its513+ // own" teardown, not a failure, and must stay silent (see the514+ // already-exited reasoning on `classifyTaskkillResult`). Anything else and515+ // we still try the wrapper alone: worse than a group kill, better than516+ // giving up.517+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') {518+ logger?.warn('local-process: could not signal the process group', {519+ pid,520+ error: error instanceof Error ? error.message : String(error),521+ })522+ child.kill(signal)523+ }524+ }525+ return526+ }🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Escalate to
SIGKILLon the POSIX path.killTreesendssignal ?? 'SIGTERM'to the group once and never escalates. A process that ignores or blocksSIGTERMtherefore survives, andLOCAL_PROCESS_CAPS.killableProcesses: truepromises forcible termination. The Windows branch escalates throughtaskkill /F, and the Docker handle escalates toSIGKILLunconditionally for the same reason, so POSIX is the weaker half of the same contract.The visible effect is in
terminateChildren: the child stays alive for the wholeCHILD_EXIT_TIMEOUT_MSwait, is logged as a straggler, and then keeps its CWD handle whileremoveDirWithRetryruns.One option is to escalate in
terminateChildrenafterwaitForExitreportsfalse, sokillTreekeeps its single-signal semantics forSpawnHandle.kill(signal).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-local-process/src/handle.ts` around lines 506 - 526, Update terminateChildren to escalate a still-running POSIX process tree with SIGKILL when waitForExit reports false after the initial termination signal. Reuse the existing killTree path to perform the escalation while preserving killTree’s single-signal semantics for direct SpawnHandle.kill(signal) calls and the existing Windows behavior.✅ Addressed in commits b5989ba to 615a425
@@ -0,0 +197,21 @@197+ )198+ const descendants = msysDescendantWinPids(table, proc.pid)199+ // Guard the guard: if this is empty the assertion below is vacuous.200+ expect(descendants.length).toBeGreaterThan(0)201+202+ await proc.kill()203+ // Windows process teardown is not instantaneous — and a FIXED sleep is204+ // the same "assume, don't verify" mistake this suite exists to catch. 500ms205+ // was under the real cost: `taskkill /T` alone measures ~1.9-3.0s on a206+ // loaded machine, so this asserted before the kill had landed and failed207+ // ~1 run in 4 under full-suite load (leaving the very `tail.exe` it is208+ // meant to prove dead). Poll for the outcome instead, up to a bound.209+ const deadline = Date.now() + 15_000210+ let survivors = descendants.filter((pid) => isAlive(pid))211+ while (survivors.length > 0 && Date.now() < deadline) {212+ await new Promise((resolve) => setTimeout(resolve, 100))213+ survivors = survivors.filter((pid) => isAlive(pid))214+ }215+216+ expect(survivors).toEqual([])217+ await sbx.destroy()🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guarantee sandbox cleanup when an assertion fails.
sbx.destroy()runs only on the success path. IfparseMsysProcessTable,proc.kill(), or an assertion throws, the test can leave the sandbox and its child processes alive. This can leak thetail.exeprocess that this test must clean up.packages/ai-sandbox-local-process/tests/kill-tree.test.ts#L182-L217: Wrap the test body afterprovider.create()intry/finally, and callawait sbx.destroy()infinally.packages/ai-sandbox-local-process/tests/kill-tree.test.ts#L239-L267: Wrap the test body afternoisy.create()intry/finally, and callawait sbx.destroy()infinally.
📍 Affects 1 file
packages/ai-sandbox-local-process/tests/kill-tree.test.ts#L182-L217(this comment)packages/ai-sandbox-local-process/tests/kill-tree.test.ts#L239-L267
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-local-process/tests/kill-tree.test.ts` around lines 182 - 217, Ensure both test bodies in packages/ai-sandbox-local-process/tests/kill-tree.test.ts at lines 182-217 and 239-267 wrap all work after provider.create() or noisy.create() in try/finally blocks, respectively; move each sandbox’s destroy call into its finally block so cleanup runs when parsing, killing, polling, or assertions fail.✅ Addressed in commits b5989ba to 615a425
packages/ai-sandbox/src/journal-reader.ts lines 153 to 168@@ -0,0 +148,21 @@148+ let onAbort: (() => void) | undefined149+ const aborted = new Promise<typeof ABORTED>((resolve) => {150+ onAbort = () => resolve(ABORTED)151+ signal.addEventListener('abort', onAbort, { once: true })152+ })153+ const iterator = source[Symbol.asyncIterator]()154+ try {155+ for (;;) {156+ const next = await Promise.race([iterator.next(), aborted])157+ if (next === ABORTED || next.done === true) return158+ yield next.value159+ }160+ } finally {161+ if (onAbort) signal.removeEventListener('abort', onAbort)162+ // NOT awaited. On an async generator, `return()` queues behind the pending163+ // `next()` we just abandoned, so awaiting it would block for exactly as164+ // long as the stream we gave up waiting for — reintroducing the hang this165+ // helper exists to remove. The rejection is swallowed for the same reason166+ // `kill` is best-effort below: the source may already be gone.167+ void iterator.return?.().catch(() => {})168+ }🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Unhandled rejection from a promise lost to
Promise.race. Both helpers raceiterator.next()against a second promise and then abandon the loser. The abandonednext()keeps no rejection handler, so a source that rejects afterwards — a killedtail, a closed transport — produces an unhandled rejection, which terminates the process under Node's default policy. Both abort and stall paths are exactly where that rejection is expected.packages/ai-sandbox/src/journal-reader.ts#L153-L168: hold theiterator.next()promise in a local, call.catch(() => {})on it, then race that local againstaborted.packages/ai-sandbox/src/journal-reader.ts#L218-L239: apply the same pattern to the first-value race againstexpired.
📍 Affects 1 file
packages/ai-sandbox/src/journal-reader.ts#L153-L168(this comment)packages/ai-sandbox/src/journal-reader.ts#L218-L239
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/journal-reader.ts` around lines 153 - 168, Prevent abandoned iterator.next() promises from producing unhandled rejections in both helpers: at packages/ai-sandbox/src/journal-reader.ts lines 153-168, store iterator.next() locally and attach a swallowing catch before racing it with aborted; apply the same change at lines 218-239 for the first-value race against expired. Preserve the existing abort, stall, and cleanup behavior.packages/ai-sandbox/src/middleware.ts lines 456 to 465Outdated@@ -320,7 +446,20 @@320446321- async onAbort(ctx, _info: AbortInfo) {447+ async onAbort(ctx, info: AbortInfo) {322448 const state = runState.get(ctx)323449 if (!state) return324450451+ // First on BOTH branches: a diff still in flight must be drained whether452+ // the sandbox is about to be destroyed or merely detached, or the final453+ // file's diff is dropped.325454 await drainWatcher(state, 'abort')326455456+ const durability = state.durability457+ // A user pressing Stop and a user closing the tab produce the IDENTICAL458+ // connection close, so intent is never inferred from the disconnect. It459+ // arrives out of band, and either band is authoritative: in-process (the460+ // abort reason carried the cancel sentinel) or durable (another host461+ // recorded it on the run record).462+ const cancelled =463+ info.cancelRequested === true ||464+ (durability !== undefined &&465+ (await wasCancelRequested(durability.runs, ctx.runId)))🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Guard the durable cancel probe; it is now the only unguarded await on the abort path.
wasCancelRequestedreads the run store, and a store read can reject. That rejection escapesonAbort, so neither branch below runs: nodetachedSince/sandboxKeyis written,provideRunDetachednever runs, anddefinition.destroyis never reached. The sandbox then stays up with no record that makes it reclaimable — the same failure shape the detach write at Lines 477-490 was already hardened against.Treat an unanswered probe as "no durable cancel recorded" and continue. The detach branch that follows is guarded and falls back to destroy.
🔒️ Proposed fix
- const cancelled = - info.cancelRequested === true || - (durability !== undefined && - (await wasCancelRequested(durability.runs, ctx.runId))) + let cancelled = info.cancelRequested === true + if (!cancelled && durability !== undefined) { + // GUARDED for the same reason the detach write below is: an unhandled + // rejection here skips BOTH branches, leaving a sandbox that is neither + // detached-and-reclaimable nor destroyed. + try { + cancelled = await wasCancelRequested(durability.runs, ctx.runId) + } catch (error) { + state.logger?.warn( + 'sandbox durable cancel probe failed; treating the run as not cancelled', + { runId: ctx.runId, error }, + ) + } + }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const durability = state.durability // A user pressing Stop and a user closing the tab produce the IDENTICAL // connection close, so intent is never inferred from the disconnect. It // arrives out of band, and either band is authoritative: in-process (the // abort reason carried the cancel sentinel) or durable (another host // recorded it on the run record). let cancelled = info.cancelRequested === true if (!cancelled && durability !== undefined) { // GUARDED for the same reason the detach write below is: an unhandled // rejection here skips BOTH branches, leaving a sandbox that is neither // detached-and-reclaimable nor destroyed. try { cancelled = await wasCancelRequested(durability.runs, ctx.runId) } catch (error) { state.logger?.warn( 'sandbox durable cancel probe failed; treating the run as not cancelled', { runId: ctx.runId, error }, ) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/middleware.ts` around lines 456 - 465, Guard the await of wasCancelRequested in the onAbort cancellation check so a durable-store rejection is treated as no durable cancel request. Ensure the rejection is contained and execution continues into the existing detach-or-destroy handling, including the subsequent guarded detach write and fallback to definition.destroy.@@ -23 +85,21 @@85+ attachWaitMs?: number86+}87+88+type JournaledOptions = SpawnNdjsonOptions & { journal: JournalOptions }89+90+function isJournaled(options: SpawnNdjsonOptions): options is JournaledOptions {91+ return options.journal !== undefined92+}93+94+function resolvePaths(options: JournaledOptions) {95+ return journalPaths(options.journal.runId, options.journal.dir)96+}97+98+/** Strip the runner-only options, leaving what `handle.process.spawn` accepts. */99+function toProcessOptions(options: SpawnNdjsonOptions): ProcessOptions {100+ const { onNonJsonLine, input, journal, ...rest } = options101+ void onNonJsonLine102+ void input103+ void journal104+ return rest23105 }🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Do not forward the request
AbortSignalto the journaled agent spawn.toProcessOptionsstrips onlyonNonJsonLine,input, andjournal, sosignalis forwarded tohandle.process.spawn(journaledCommand(...)). If a provider terminates the spawned process when that signal aborts, a client disconnect kills the journaled agent. The agent then writes no exit sentinel, and the successor host takes over a run that is already dead — which is the opposite of the guarantee this module documents at lines 10-15 and 129-136.The signal is still needed for the tail read:
readJournalNdjsonforwards it toreadJournalandawaitAttachableJournalon its own. Only the agent spawn should outlive the request.🔒️ Proposed fix
export async function startJournaledAgent( handle: SandboxHandle, command: string, options: JournaledOptions, ): Promise<void> { const paths = resolvePaths(options) + // The agent must OUTLIVE this request. Forwarding the consumer's signal here + // would let a disconnect kill the very process journaling exists to protect; + // the signal belongs to the tail read in `readJournalNdjson`, not to the spawn. + const { signal, ...spawnOptions } = toProcessOptions(options) + void signal const proc = await handle.process.spawn( journaledCommand(command, paths), - toProcessOptions(options), + spawnOptions, )#!/bin/bash # Check whether providers terminate a spawned process when ProcessOptions.signal aborts. rg -nP -C6 '\bspawn\s*\(' --type=ts -g 'packages/ai-sandbox-*/src/**' | rg -n -C6 'signal|abort|kill' # And confirm the declared contract for the option. rg -nP -C8 'interface ProcessOptions' packages/ai-sandbox/src/contracts.tsAlso applies to: 138-152
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/runner.ts` around lines 99 - 105, Update toProcessOptions to omit signal along with onNonJsonLine, input, and journal before passing options to the journaled agent spawn, ensuring the spawned agent outlives request cancellation. Preserve signal handling in readJournalNdjson and its journal-reading flow so tail reads still respond to the request AbortSignal.✅ Addressed in commits b5989ba to 615a425
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 14
Note
Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.
🟡 Minor comments (21)
packages/ai-codex/src/adapters/text.ts-215-241 (1)
215-241: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winMove the durability resolution inside the
tryblock.resolveDurableRunIdandresolveDurableThreadIdthrowDurableRunIdRequiredError/DurableThreadIdRequiredErrorwhen durability is wired without a caller-supplied id. Here both calls sit before thetryat line 249, so the error escapeschatStreamand rejects the async iterator. The catch at line 406 never runs, and noRUN_ERRORchunk is emitted.The sibling adapters resolve inside the
try:packages/ai-claude-code/src/adapters/text.ts(line 326, inside thetryat line 307) andpackages/ai-grok-build/src/adapters/text.ts(line 521, inside thetryat line 507). The same misconfiguration therefore surfaces as a stream chunk on those adapters and as a rejection on this one.Move the three declarations into the
tryblock, afterconst sandbox = this.sandboxFrom(options), and keepchannelcreation after them.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-codex/src/adapters/text.ts` around lines 215 - 241, Move the durability lookup and the declarations of durability, runId, and threadId from before the try into the try block, placing them after const sandbox = this.sandboxFrom(options). Keep channel creation after these declarations so DurableRunIdRequiredError and DurableThreadIdRequiredError are handled by chatStream’s existing catch and emitted as RUN_ERROR chunks.packages/ai-sandbox/src/chunk-identity.ts-92-99 (1)
92-99: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThe
"__undefined__"sentinel collides with a real string value.stableStringifyencodes a present-but-undefinedfield as the quoted string"__undefined__". A field whose real value is the string__undefined__encodes to the identical text throughJSON.stringify. So{ a: undefined }and{ a: '__undefined__' }produce the same fingerprint, which contradicts the guarantee documented at Lines 117-121.A false match makes
alignToStoredLogsuppress a replayed chunk that does not equal the stored chunk. Use an unquoted token instead. Every real string is quoted byJSON.stringify, so an unquoted token cannot be produced by any string value.🐛 Proposed fix
const parts = keys.map((key) => { const entry = record[key] + // Unquoted on purpose: `JSON.stringify` quotes every real string, so no + // string value can produce this token and collide with an explicit + // `undefined`. const encoded = - entry === undefined - ? '"__undefined__"' - : stableStringify(entry, undefined) + entry === undefined ? 'undefined' : stableStringify(entry, undefined) return `${JSON.stringify(key)}:${encoded}` })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/chunk-identity.ts` around lines 92 - 99, Update the undefined-field encoding in the keys mapping near stableStringify so it uses an unquoted sentinel token rather than the quoted "__undefined__" string. Preserve JSON.stringify encoding for all real values, ensuring present undefined fields remain distinct from the literal string "__undefined__" in the generated fingerprint.packages/ai-sandbox/src/run.ts-116-120 (1)
116-120: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winCorrect the "called exactly once per run" claim.
RunController.attachcallsthis.deps.durability(runId)again at Line 437, outsidepipeToRunLog. So the factory is called at least twice for a run that is both driven and tailed in the same process. An implementer who reads this line literally may build a one-shot factory that mints a fresh, unshared instance per call, andattachwould then read a log that does not observe the driver's appends.State the real requirement: the factory must return a log that resolves to the same stored run for the same
runId, and it may be called more than once.📝 Proposed doc fix
- * Called exactly once per run, at the start of {`@link` pipeToRunLog}. An - * implementation MUST return the same instance for the same `runId` within a - * process if it wants `snapshot()` to see its own appends. + * Called once per drive, at the start of {`@link` pipeToRunLog}, and again by + * {`@link` RunController.attach} for every tail of the same run. An + * implementation MUST therefore be callable more than once per `runId`, and + * every instance it returns for one `runId` MUST resolve to the SAME stored + * log — otherwise `attach` tails a log the driver never appended to and + * `snapshot()` cannot see the driver's own appends.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/run.ts` around lines 116 - 120, Update the durability factory documentation near the durability callback type to remove the claim that it is called exactly once per run. State instead that the factory may be called multiple times and must resolve the same stored run/log for a given runId so separate instances observe the same appends.packages/ai-sandbox/package.json-62-62 (1)
62-62: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse
workspace:*for the internal@tanstack/aidependency.peerDependenciesdeclares"@tanstack/ai": "workspace:^", whiledevDependenciesusesworkspace:*. The coding guidelines require theworkspace:*protocol for internal package dependencies.As per coding guidelines: "Use the
workspace:*protocol for internal package dependencies inpackage.json."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/package.json` at line 62, Update the `@tanstack/ai` entry in peerDependencies to use the workspace:* protocol, matching its devDependencies declaration and the repository’s internal dependency convention.Source: Coding guidelines
docs/sandbox/providers.md-252-261 (1)
252-261: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winResolve the contradiction between the stated rule and the Sprites row.
Line 252 states that anything that cannot be measured stays
false. The Sprites row then declarestrue (unverified)and says the endpoint behavior is "undocumented and unmeasured". A reader cannot tell which statement governs a new provider. Either state the exception for a real server-side kill explicitly in the rule, or align the Sprites value with the rule.#!/bin/bash # Confirm the value each bundled provider actually declares. rg -n -C 2 'killableProcesses' packages/ai-sandbox-*/src🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/providers.md` around lines 252 - 261, Resolve the contradiction between the introductory rule and the Sprites row: either revise the rule near “Anything that cannot be measured yet stays false” to explicitly allow a documented exception for real server-side kill mechanisms, or change the Sprites `killableProcesses` value to `false` while retaining its unverified endpoint details. Ensure the documented policy and provider value consistently communicate which rule governs unmeasured behavior.packages/ai-sandbox-docker/src/handle.ts-226-236 (1)
226-236: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRe-check the pid before you print
KILL_FAILED_MARKER.The shell sends
kill -KILLand then immediately runskill -0 "$pid". Signal delivery and process teardown are asynchronous, sokill -0can still succeed for a process that is about to die, and it also succeeds for a zombie that has not been reaped yet. The result is alogger.warnabout an orphan on a successful kill. That weakens exactly the in-band evidence channelkillableProcesses: truedepends on.Add a short bounded re-check after the
KILLbefore reporting.🛠️ Proposed bounded verification
` kill -KILL -"$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null`, // Verify, do not assume: ask the kernel whether the pid is still there. - ` if kill -0 "$pid" 2>/dev/null; then`, + ` j=0`, + ` while [ "$j" -lt 10 ] && kill -0 "$pid" 2>/dev/null; do`, + ` sleep 0.05`, + ` j=$((j+1))`, + ` done`, + ` if kill -0 "$pid" 2>/dev/null; then`, ` echo ${KILL_FAILED_MARKER} pid="$pid" >&2`, ` fi`,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-docker/src/handle.ts` around lines 226 - 236, Add a short bounded polling re-check between the SIGKILL and the existing kill -0 verification in the shell command assembled by the process-kill logic. Repeatedly test whether the pid remains present, sleeping briefly between attempts, and only echo KILL_FAILED_MARKER if it is still present after the bounded window; preserve the existing no-pid behavior and marker symbols.packages/ai-sandbox/src/shell.ts-209-245 (1)
209-245: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winA timed-out
run()leaves an orphan resolver inpending.Promise.race([nextLine(), deadline])abandons thenextLine()promise when the deadline wins, but its resolver stays queued inpending. On the timeout path the shell is still alive by definition, sodrainStdoutdelivers the next stdout line to that abandoned resolver. A caller that catches the timeout and callsrun()again then loses its first line, and the sentinel protocol is offset by one for every later command.Track the parked resolver and drop it when the deadline fires.
🛠️ Sketch of a cancellable read
+ /** Read the next line, with a way to withdraw the waiter on timeout. */ + function nextLineCancellable(): { + line: Promise<string | null> + cancel: () => void + } { + const buffered = lineBuffer.shift() + if (buffered !== undefined) { + return { line: Promise.resolve(buffered), cancel: () => {} } + } + if (streamDone) return { line: Promise.resolve(null), cancel: () => {} } + let resolver: (line: string | null) => void = () => {} + const line = new Promise<string | null>((resolve) => { + resolver = resolve + pending.push(resolve) + }) + return { + line, + cancel: () => { + const i = pending.indexOf(resolver) + if (i >= 0) pending.splice(i, 1) + }, + } + }Then in the loop:
- const line = await Promise.race([nextLine(), deadline]) + const read = nextLineCancellable() + const line = await Promise.race([read.line, deadline]) if (line === TIMED_OUT) { + read.cancel() throw new Error(🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/shell.ts` around lines 209 - 245, Update the read flow around nextLine() and the deadline in run() to track the pending resolver for the current stdout read and remove it from pending when the timeout wins. Ensure the timed-out read is cancelled before throwing, while preserving normal line handling and sentinel processing for non-timeout runs.packages/ai-sandbox-docker/tests/docker.test.ts-64-65 (1)
64-65: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThis assertion does not check what the comment claims.
The comment says the check proves "the snapshot really captured this container's filesystem."
inspected.Idis non-empty for every image the daemon can inspect, so the assertion holds even for an image with no captured layers. Either drop the line or assert something filesystem-specific, for example thatinspected.Sizeis greater than zero, or that a file written into the container earlier in this test is readable from a sandbox restored offsnapshotTag.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-docker/tests/docker.test.ts` around lines 64 - 65, Replace the ineffective inspected.Id assertion in the snapshot verification test with a filesystem-specific check: verify inspected.Size is greater than zero or confirm that a file written earlier is readable after restoring from snapshotTag. Keep the assertion aligned with the comment’s claim that the container filesystem was captured.packages/ai-sandbox-daytona/tests/journal.conformance.test.ts-21-36 (1)
21-36: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winTreat an empty
DAYTONA_API_KEYas unavailable.Line 26 passes
{ apiKey: '' }when the environment variable is empty. Lines 34-36 treat that same value as unsupported. If CI injects an empty secret, a handle-creation case can fail instead of reporting the named unsupported state. Use the same truthiness check for both paths.Proposed fix
- const provider = daytonaSandbox(apiKey !== undefined ? { apiKey } : {}) + const provider = daytonaSandbox(apiKey ? { apiKey } : {})🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-daytona/tests/journal.conformance.test.ts` around lines 21 - 36, Update the DAYTONA_API_KEY handling in the createHandle callback and unsupported spread so an empty string is treated as unavailable consistently. Use a truthiness check when deciding whether to pass apiKey to daytonaSandbox, preserving the existing unsupported state for missing or empty credentials.packages/ai-sandbox/tests/reclaim.test.ts-76-87 (1)
76-87: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winLine 86 asserts on a counter that the test disconnected.
Line 77 replaces
provider.destroyaftertrackDestroyswrapped it. The wrapper no longer runs, sodestroyedstays empty whatever the implementation does. The assertion at line 86 can never fail, and it reads as "destroy was never called" whilereclaimSandboxdoes call it and observes the rejection.Reject from inside the tracked wrapper so the id is still recorded.
💚 Proposed fix
const { provider, destroyed } = trackDestroys(makeFakeProvider()) - provider.destroy = () => Promise.reject(new Error('already gone')) + const tracked = provider.destroy + provider.destroy = (input) => { + void tracked(input) + return Promise.reject(new Error('already gone')) + } const instances = await storeWith('k1', 'fake', 'sbx-1') const outcome = await reclaimSandbox(record({ sandboxKey: 'k1' }), { provider, instances, }) // The delete is unconditional — but the outcome must NOT claim success. expect(outcome).toBe('destroy-failed') expect(await instances.get('k1')).toBeNull() - expect(destroyed).toEqual([]) + // Destroy WAS attempted against the recorded sandbox; it simply failed. + expect(destroyed).toEqual(['sbx-1'])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/tests/reclaim.test.ts` around lines 76 - 87, Update the test setup around trackDestroys and provider.destroy so the tracked wrapper remains installed while its implementation rejects with “already gone”; configure the rejection inside that wrapper rather than replacing provider.destroy afterward. Preserve the existing outcome, instance removal, and destroyed assertions so the test verifies reclaimSandbox calls destroy and handles the rejection.packages/ai-grok-build/tests/attach.test.ts-387-401 (1)
387-401: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winThe comment and the code disagree on the runId, so the colliding-runId case is not covered.
The comment states "Same runId, a log already holding the whole sequence, but
attach: false", and it names the hazard as a colliding runId. The code passesfreshRunId, which is a different id from the seededrunId. The test therefore proves only that a non-attach run delivers its own chunks. It does not pin the case the comment describes. The journal seeded atrunIdis also unused by the fresh run.Either reuse
runIdfor the fresh run to exercise the collision, or update the comment to match the weaker guarantee.♻️ Proposed fix to exercise the documented case
- const freshRunId = `r-${randomUUID()}` + // Same runId as the seeded journal: alignment must still be skipped. const fresh = await collect( run(sbx, { - runId: freshRunId, + runId, durability: durabilityWith(fakeLog(reference), false), }), )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-grok-build/tests/attach.test.ts` around lines 387 - 401, Update the test’s second run invocation to reuse the seeded runId instead of freshRunId, so it exercises attach: false with an existing journal entry for the same run. Keep the surrounding reference log setup and assertions unchanged, and retain the comment describing the colliding-runId behavior.packages/ai-sandbox-local-process/tests/local-process.test.ts-136-158 (1)
136-158: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRelease the probe process in a
finally, so a failed assertion does not orphan a 31-yearsleep.proc.kill()andsbx.destroy()run only on the success path. If the visibility assertion at Line 144 fails, the test throws first, andsleep 987654321plus itsshwrapper survive on the host until reboot. The same applies if the survivor assertion at Line 156 fails.♻️ Proposed guard
const proc = await sbx.process.spawn(`sleep ${KILL_PROBE_SLEEP}`) - // Guard the guard: if the probe were never visible, its absence after the - // kill would prove nothing at all. - let visible = await probeRows() - for (let i = 0; i < 20 && visible === ''; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 100)) - visible = await probeRows() - } - expect(visible).toContain(KILL_PROBE_SLEEP) - - // Default signal on purpose — the realistic call path, and the one - // `killableProcesses: true` is a promise about. - await proc.kill() - await proc.wait() - - let survivors = await probeRows() - for (let i = 0; i < 20 && survivors !== ''; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 100)) - survivors = await probeRows() - } - expect(survivors).toBe('') - - await sbx.destroy() + try { + // Guard the guard: if the probe were never visible, its absence after + // the kill would prove nothing at all. + let visible = await probeRows() + for (let i = 0; i < 20 && visible === ''; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 100)) + visible = await probeRows() + } + expect(visible).toContain(KILL_PROBE_SLEEP) + + // Default signal on purpose — the realistic call path, and the one + // `killableProcesses: true` is a promise about. + await proc.kill() + await proc.wait() + + let survivors = await probeRows() + for (let i = 0; i < 20 && survivors !== ''; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 100)) + survivors = await probeRows() + } + expect(survivors).toBe('') + } finally { + await proc.kill().catch(() => {}) + await sbx.destroy() + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-local-process/tests/local-process.test.ts` around lines 136 - 158, Wrap the probe lifecycle in a try/finally block so cleanup always runs when either assertion or polling fails. Keep the existing visibility, kill, wait, and survivor assertions in the try block, and move proc.kill() and sbx.destroy() into finally, ensuring the spawned process is released even on test failure.docs/sandbox/journal.md-27-30 (1)
27-30: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd a language to the fenced block.
markdownlint reports MD040 here. Use
textfor the path listing.📝 Proposed fix
-``` +```text /tmp/tanstack-runs/<runId>.ndjson every NDJSON event the agent emitted /tmp/tanstack-runs/<runId>.err the agent's stderr, kept separate ```🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/journal.md` around lines 27 - 30, Update the fenced code block containing the /tmp/tanstack-runs path listing to declare the text language, preserving both listing entries unchanged.Source: Linters/SAST tools
docs/sandbox/reaping.md-341-342 (1)
341-342: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winFix the broken anchor.
The heading at line 520 is
## Sizing \detachedRunTtlMs` and the sweep interval, which slugs tosizing-detachedrunttlms-and-the-sweep-interval. The link omits the trailingms`, so it resolves to nothing.🐛 Proposed fix
-reasonable start — see [sizing](`#sizing-detachedrunttl-and-the-sweep-interval`)). +reasonable start — see [sizing](`#sizing-detachedrunttlms-and-the-sweep-interval`)).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/reaping.md` around lines 341 - 342, Update the sizing link in the vercel.json registration guidance to use the heading’s correct anchor, including the trailing “ms” in “detachedrunttlms”.Source: Linters/SAST tools
packages/ai-sandbox/src/testkit/journal-conformance.ts-195-196 (1)
195-196: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winPROBE_MAX_TICKSdoes not bound the probe inside the case timeout.The loop sleeps 1s per tick, so 600 ticks is about 600s.
CASE_TIMEOUT_MSis 180s. The comment states that nothing can outlive the suite, but the probe can keep writing for roughly seven minutes after the case times out and thefinallyteardown never ran. Reduce the cap below the case timeout.♻️ Proposed change
-/** Iteration cap on the kill probe's loop, so nothing can outlive the suite. */ -const PROBE_MAX_TICKS = 600 +/** + * Iteration cap on the kill probe's loop, so nothing can outlive the suite. One + * tick per second, so this must stay under `CASE_TIMEOUT_MS`. + */ +const PROBE_MAX_TICKS = 150🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/testkit/journal-conformance.ts` around lines 195 - 196, Reduce PROBE_MAX_TICKS so the kill probe’s one-second-per-tick loop completes within CASE_TIMEOUT_MS, including reasonable timeout overhead. Update the adjacent comment to accurately state that the cap keeps the probe bounded by the case timeout and preserves the existing teardown behavior.packages/ai-sandbox/tests/journal.test.ts-197-204 (1)
197-204: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThe truncation assertion is vacuous.
journaledCommandnever emits a newline, sonot.toContain("> '/tmp/tanstack-runs/r1.ndjson'\n")passes for both>>and a truncating>. Assert the absence of a truncating redirect directly.♻️ Proposed assertion
- expect(journaledCommand('x', journalPaths('r1'))).not.toContain( - `> '/tmp/tanstack-runs/r1.ndjson'\n`, - ) + expect(journaledCommand('x', journalPaths('r1'))).not.toMatch( + /[^>]> '\/tmp\/tanstack-runs\/r1\.ndjson'/, + )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/tests/journal.test.ts` around lines 197 - 204, Update the truncation assertion in the journaledCommand test to check directly that the command does not contain the single-redirect form for the journal path, without relying on a trailing newline. Keep the existing append-redirection assertion unchanged.packages/ai-sandbox/src/testkit/journal-conformance.ts-470-475 (1)
470-475: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winAwait the spawn call, so a spawn failure fails the case.
void handle.process.spawn(...)discards the returned promise. Ifspawnrejects, the result is an unhandled rejection attributed to an unrelated point in the run, not a failure of this case. The comment explains whywait()must not be called; that reason does not apply to thespawncall itself.🐛 Proposed fix
- void handle.process.spawn(journaledCommand(agentCommand, paths)) + await handle.process.spawn(journaledCommand(agentCommand, paths))🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/src/testkit/journal-conformance.ts` around lines 470 - 475, In the process-launch setup around handle.process.spawn, await the promise returned by spawn so any launch failure fails the conformance case directly. Keep the existing behavior of avoiding a later SpawnHandle.wait() call and preserve the __exit sentinel as the completion check after the awaited spawn.docs/persistence/overview.md-156-156 (1)
156-156: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winCorrect the reload lifecycle statement.
Line 156 says both layers assume that work has finished. Line 152 says delivery durability can rejoin a still-streaming run. Limit the statement to already-produced transcript data, then state that delivery durability can also tail a live producer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/overview.md` at line 156, Update the reload lifecycle statement near the sandboxed agent discussion to limit the “work is over” assumption to replaying or reading already-produced transcript data. Clarify that delivery durability can rejoin and continue tailing a still-streaming run, while preserving the existing distinction that a sandboxed agent requires takeover to keep driving after its host disappears.packages/ai-sandbox/tests/journal-bytes.test.ts-142-150 (1)
142-150: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winCorrect the byte arithmetic in the comment.
The comment says the line is
1 + 4 + 1 = 6bytes plus the newline, which is 7. The assertion expectsendPosition: 9, and 9 is right:[,", 🌍 (4 bytes),",]is 8 bytes, plus the newline. The comment omits the brackets.📝 Proposed fix
- // '🌍' is 4 bytes; the line is 1 + 4 + 1 = 6 bytes plus the newline. + // '🌍' is 4 bytes; the line `["🌍"]` is 1 + 1 + 4 + 1 + 1 = 8 bytes, plus + // the newline.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox/tests/journal-bytes.test.ts` around lines 142 - 150, Correct the explanatory comment in the test near toJournalLines to include both brackets in the byte count: `[`, `"`, the four-byte emoji, `"`, and `]` total 8 bytes, plus the newline. Keep the existing endPosition assertion unchanged.docs/sandbox/takeover.md-84-87 (1)
84-87: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd a language to the fenced block.
markdownlint reports MD040 here. The block holds error text, so
textis the right fence language.📝 Proposed fix
-``` +```text durableStream: a runId is required: send it as an X-Run-Id header or a ?runId query param</details> <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.
In
@docs/sandbox/takeover.mdaround lines 84 - 87, Update the fenced block containing the durableStream error text to declare the text language, using a text fence to satisfy Markdown linting.</details> <!-- cr-comment:v1:a15f84778137d5314413b04b --> _Source: Linters/SAST tools_ </blockquote></details> <details> <summary>docs/persistence/build-your-own-adapter.md-668-674 (1)</summary><blockquote> `668-674`: _📐 Maintainability & Code Quality_ | _🟡 Minor_ | _⚡ Quick win_ **Update the description of the `examples/ts-react-chat` adapter.** This paragraph says the example "declares those same two omissions", and lines 883-885 say it "implements only the three required methods plus `findActiveRun`". Both statements are stale in this PR. `examples/ts-react-chat/src/lib/sqlite-persistence.test.ts` passes `skipMethods: ['runs.listByThread']` only, and its new SQL-NULL test fails outright if `runs.listReclaimable` is absent. A reader following this page would declare an omission for a method the example implements and tests. <details> <summary>📝 Proposed fix</summary> ```diff -pass, and a declared omission shows up in the test output as a skipped case -rather than as nothing at all. When this is green, your adapter is a drop-in for -`withPersistence`. The `examples/ts-react-chat` app runs this suite against its -SQLite backend and declares those same two omissions. +pass, and a declared omission shows up in the test output as a skipped case +rather than as nothing at all. When this is green, your adapter is a drop-in for +`withPersistence`. The `examples/ts-react-chat` app runs this suite against its +SQLite backend and declares one omission, `runs.listByThread`.Apply the matching correction at lines 883-885:
-The reference implementation, `MemoryRunStore` in -`packages/ai-persistence/src/memory.ts`, implements all six. The -`examples/ts-react-chat` SQLite adapter (`src/lib/sqlite-persistence.ts`) -implements only the three required methods plus `findActiveRun`, which is a -fine illustration that the rest stay optional. +The reference implementation, `MemoryRunStore` in +`packages/ai-persistence/src/memory.ts`, implements all six. The +`examples/ts-react-chat` SQLite adapter (`src/lib/sqlite-persistence.ts`) +implements the three required methods plus `findActiveRun` and +`listReclaimable`, and omits `listByThread`, which is a fine illustration that +the rest stay optional.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-adapter.md` around lines 668 - 674, Update the adapter description in this paragraph and the corresponding text around the example implementation to state that the ts-react-chat adapter declares only skipMethods: ['runs.listByThread']; remove the claim that it omits both state-store keys or implements only three required methods, and acknowledge that runs.listReclaimable is implemented and covered by the SQL-NULL test.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/resumable-streams/advanced.md`: - Around line 200-218: Update appendAfterStored to validate the stored prefix against the corresponding replayed chunks before slicing. Compare each chunk in stored with replayed, throw immediately on the first mismatch, and only append the remaining replayed chunks after the entire prefix matches. In `@examples/ts-react-chat/src/lib/sqlite-persistence.ts`: - Around line 60-65: Update the schema initialization flow in sqlite-persistence.ts to run an idempotent migration immediately after SCHEMA_SQL is applied and before createRunStore prepares statements. Add any missing runs columns—error_code, sandbox_key, detached_since, cancel_requested, and driver_epoch—using the existing database connection, and ensure migrate is invoked for every supported database URL, including persistent non-memory databases. In `@packages/ai-durable-stream/src/durable-stream.ts`: - Around line 790-823: Update collectSnapshot to call ensureCreated() before readWindows, preserving the existing createdHere short-circuit so snapshot() returns an empty result for streams that do not yet exist instead of rejecting. Keep the current timeout, entry collection, and sequence seeding behavior unchanged. In `@packages/ai-sandbox-cloudflare/src/coordinator.ts`: - Around line 199-205: Update the local settle callback around onRunSettled so exceptions from either invocation are caught and reported, ensuring done.then(settle, settle) always produces a fulfilled promise for ctx.waitUntil. Preserve passing input.runId to onRunSettled and use the coordinator’s existing error-reporting mechanism. In `@packages/ai-sandbox-cloudflare/src/run-driver.ts`: - Around line 70-71: Update the stream consumption logic in run-driver.ts to race iterator progress against the provided AbortSignal instead of relying on nonstandard return?.()/throwReason behavior. When the signal aborts, handle the resulting completion or error so the run finishes with status aborted, including for an async source that never yields; add a regression test covering that never-yielding source. In `@packages/ai-sandbox-cloudflare/tests/run-log.test.ts`: - Around line 1-2: Move the run-log unit test from the tests directory to sit beside run-log.ts as run-log.test.ts, and update its InMemoryRunEventLog and isTerminalRunStatus import from the parent-relative path to the local ./run-log module. In `@packages/ai-sandbox-daytona/tests/journal.conformance.test.ts`: - Around line 1-37: Move the tests out of package-level tests directories and colocate them with their covered source modules: move packages/ai-sandbox-daytona/tests/journal.conformance.test.ts beside packages/ai-sandbox-daytona/src/index.ts and update its relative import; move packages/ai-sandbox/tests/testkit-subpath.test.ts beside the testkit entry module exporting the covered symbols; move packages/ai-persistence/tests/memory.test.ts beside packages/ai-persistence/src/memory.ts and update its relative import; move packages/ai-persistence/tests/error-abort.test.ts beside the persistence module implementing the abort behavior; and move packages/ai/tests/stream-durability.test.ts beside packages/ai/src/stream-durability.ts and update its relative import. In `@packages/ai-sandbox-docker/tests/docker.test.ts`: - Around line 334-342: Update the polling loop around probeRows to tolerate transient survivors: poll repeatedly until the result is empty or all attempts are exhausted, then perform a single final assertion on the settled result. Preserve the existing polling interval and retry count. In `@packages/ai-sandbox-local-process/src/handle.ts`: - Around line 506-526: Update terminateChildren to escalate a still-running POSIX process tree with SIGKILL when waitForExit reports false after the initial termination signal. Reuse the existing killTree path to perform the escalation while preserving killTree’s single-signal semantics for direct SpawnHandle.kill(signal) calls and the existing Windows behavior. In `@packages/ai-sandbox-local-process/tests/kill-tree.test.ts`: - Around line 182-217: Ensure both test bodies in packages/ai-sandbox-local-process/tests/kill-tree.test.ts at lines 182-217 and 239-267 wrap all work after provider.create() or noisy.create() in try/finally blocks, respectively; move each sandbox’s destroy call into its finally block so cleanup runs when parsing, killing, polling, or assertions fail. In `@packages/ai-sandbox/src/journal-reader.ts`: - Around line 153-168: Prevent abandoned iterator.next() promises from producing unhandled rejections in both helpers: at packages/ai-sandbox/src/journal-reader.ts lines 153-168, store iterator.next() locally and attach a swallowing catch before racing it with aborted; apply the same change at lines 218-239 for the first-value race against expired. Preserve the existing abort, stall, and cleanup behavior. In `@packages/ai-sandbox/src/middleware.ts`: - Around line 456-465: Guard the await of wasCancelRequested in the onAbort cancellation check so a durable-store rejection is treated as no durable cancel request. Ensure the rejection is contained and execution continues into the existing detach-or-destroy handling, including the subsequent guarded detach write and fallback to definition.destroy. In `@packages/ai-sandbox/src/runner.ts`: - Around line 99-105: Update toProcessOptions to omit signal along with onNonJsonLine, input, and journal before passing options to the journaled agent spawn, ensuring the spawned agent outlives request cancellation. Preserve signal handling in readJournalNdjson and its journal-reading flow so tail reads still respond to the request AbortSignal. In `@packages/ai/src/stream-to-response.ts`: - Around line 750-764: Update startRunDriver so the promise-level catch wraps the entire async body, including resolveResumeRunId(driver.request), rather than only catching later run-record operations. Ensure both waitUntil and the fallback path receive a non-rejecting promise, while preserving the existing logging and early-return behavior. --- Minor comments: In `@docs/persistence/build-your-own-adapter.md`: - Around line 668-674: Update the adapter description in this paragraph and the corresponding text around the example implementation to state that the ts-react-chat adapter declares only skipMethods: ['runs.listByThread']; remove the claim that it omits both state-store keys or implements only three required methods, and acknowledge that runs.listReclaimable is implemented and covered by the SQL-NULL test. In `@docs/persistence/overview.md`: - Line 156: Update the reload lifecycle statement near the sandboxed agent discussion to limit the “work is over” assumption to replaying or reading already-produced transcript data. Clarify that delivery durability can rejoin and continue tailing a still-streaming run, while preserving the existing distinction that a sandboxed agent requires takeover to keep driving after its host disappears. In `@docs/sandbox/journal.md`: - Around line 27-30: Update the fenced code block containing the /tmp/tanstack-runs path listing to declare the text language, preserving both listing entries unchanged. In `@docs/sandbox/providers.md`: - Around line 252-261: Resolve the contradiction between the introductory rule and the Sprites row: either revise the rule near “Anything that cannot be measured yet stays false” to explicitly allow a documented exception for real server-side kill mechanisms, or change the Sprites `killableProcesses` value to `false` while retaining its unverified endpoint details. Ensure the documented policy and provider value consistently communicate which rule governs unmeasured behavior. In `@docs/sandbox/reaping.md`: - Around line 341-342: Update the sizing link in the vercel.json registration guidance to use the heading’s correct anchor, including the trailing “ms” in “detachedrunttlms”. In `@docs/sandbox/takeover.md`: - Around line 84-87: Update the fenced block containing the durableStream error text to declare the text language, using a text fence to satisfy Markdown linting. In `@packages/ai-codex/src/adapters/text.ts`: - Around line 215-241: Move the durability lookup and the declarations of durability, runId, and threadId from before the try into the try block, placing them after const sandbox = this.sandboxFrom(options). Keep channel creation after these declarations so DurableRunIdRequiredError and DurableThreadIdRequiredError are handled by chatStream’s existing catch and emitted as RUN_ERROR chunks. In `@packages/ai-grok-build/tests/attach.test.ts`: - Around line 387-401: Update the test’s second run invocation to reuse the seeded runId instead of freshRunId, so it exercises attach: false with an existing journal entry for the same run. Keep the surrounding reference log setup and assertions unchanged, and retain the comment describing the colliding-runId behavior. In `@packages/ai-sandbox-daytona/tests/journal.conformance.test.ts`: - Around line 21-36: Update the DAYTONA_API_KEY handling in the createHandle callback and unsupported spread so an empty string is treated as unavailable consistently. Use a truthiness check when deciding whether to pass apiKey to daytonaSandbox, preserving the existing unsupported state for missing or empty credentials. In `@packages/ai-sandbox-docker/src/handle.ts`: - Around line 226-236: Add a short bounded polling re-check between the SIGKILL and the existing kill -0 verification in the shell command assembled by the process-kill logic. Repeatedly test whether the pid remains present, sleeping briefly between attempts, and only echo KILL_FAILED_MARKER if it is still present after the bounded window; preserve the existing no-pid behavior and marker symbols. In `@packages/ai-sandbox-docker/tests/docker.test.ts`: - Around line 64-65: Replace the ineffective inspected.Id assertion in the snapshot verification test with a filesystem-specific check: verify inspected.Size is greater than zero or confirm that a file written earlier is readable after restoring from snapshotTag. Keep the assertion aligned with the comment’s claim that the container filesystem was captured. In `@packages/ai-sandbox-local-process/tests/local-process.test.ts`: - Around line 136-158: Wrap the probe lifecycle in a try/finally block so cleanup always runs when either assertion or polling fails. Keep the existing visibility, kill, wait, and survivor assertions in the try block, and move proc.kill() and sbx.destroy() into finally, ensuring the spawned process is released even on test failure. In `@packages/ai-sandbox/package.json`: - Line 62: Update the `@tanstack/ai` entry in peerDependencies to use the workspace:* protocol, matching its devDependencies declaration and the repository’s internal dependency convention. In `@packages/ai-sandbox/src/chunk-identity.ts`: - Around line 92-99: Update the undefined-field encoding in the keys mapping near stableStringify so it uses an unquoted sentinel token rather than the quoted "__undefined__" string. Preserve JSON.stringify encoding for all real values, ensuring present undefined fields remain distinct from the literal string "__undefined__" in the generated fingerprint. In `@packages/ai-sandbox/src/run.ts`: - Around line 116-120: Update the durability factory documentation near the durability callback type to remove the claim that it is called exactly once per run. State instead that the factory may be called multiple times and must resolve the same stored run/log for a given runId so separate instances observe the same appends. In `@packages/ai-sandbox/src/shell.ts`: - Around line 209-245: Update the read flow around nextLine() and the deadline in run() to track the pending resolver for the current stdout read and remove it from pending when the timeout wins. Ensure the timed-out read is cancelled before throwing, while preserving normal line handling and sentinel processing for non-timeout runs. In `@packages/ai-sandbox/src/testkit/journal-conformance.ts`: - Around line 195-196: Reduce PROBE_MAX_TICKS so the kill probe’s one-second-per-tick loop completes within CASE_TIMEOUT_MS, including reasonable timeout overhead. Update the adjacent comment to accurately state that the cap keeps the probe bounded by the case timeout and preserves the existing teardown behavior. - Around line 470-475: In the process-launch setup around handle.process.spawn, await the promise returned by spawn so any launch failure fails the conformance case directly. Keep the existing behavior of avoiding a later SpawnHandle.wait() call and preserve the __exit sentinel as the completion check after the awaited spawn. In `@packages/ai-sandbox/tests/journal-bytes.test.ts`: - Around line 142-150: Correct the explanatory comment in the test near toJournalLines to include both brackets in the byte count: `[`, `"`, the four-byte emoji, `"`, and `]` total 8 bytes, plus the newline. Keep the existing endPosition assertion unchanged. In `@packages/ai-sandbox/tests/journal.test.ts`: - Around line 197-204: Update the truncation assertion in the journaledCommand test to check directly that the command does not contain the single-redirect form for the journal path, without relying on a trailing newline. Keep the existing append-redirection assertion unchanged. In `@packages/ai-sandbox/tests/reclaim.test.ts`: - Around line 76-87: Update the test setup around trackDestroys and provider.destroy so the tracked wrapper remains installed while its implementation rejects with “already gone”; configure the rejection inside that wrapper rather than replacing provider.destroy afterward. Preserve the existing outcome, instance removal, and destroyed assertions so the test verifies reclaimSandbox calls destroy and handles the rejection. --- Nitpick comments: In @.changeset/durable-stream-runid-resolution.md: - Around line 1-3: Update the changeset release level from patch to minor to document the breaking behavior change where requests without a header or query run id now throw instead of generating one. In @.changeset/local-process-kill-tree-verified.md: - Around line 1-3: Update the changeset front matter for `@tanstack/ai-sandbox-local-process` from patch to minor to reflect the new public logger option on localProcessSandbox and the exported LocalProcessLogger type. In `@packages/ai-acp/tests/durability-attach.test.ts`: - Around line 176-274: Wrap each test body in the durability attach test suite with a try/finally around the sandbox-dependent assertions, and move await sbx.destroy() into the finally block. Apply this to the tests shown, including the refusal, fresh durable run, and no-durability cases, so cleanup runs even when assertions or setup-dependent operations fail. In `@packages/ai-acp/tests/run-id-fallback.test.ts`: - Around line 14-34: Update the tests in the “acp runId resolution” suite to exercise the ACP adapter’s runId resolution in packages/ai-acp/src/adapters/compatible.ts rather than calling resolveDurableRunId directly. Cover both the generated fallback and caller-supplied runId paths, or spy on resolveDurableRunId to verify the adapter invokes it with durable: false and the expected arguments. In `@packages/ai-claude-code/tests/attach.test.ts`: - Around line 118-120: Update the shell command in the attach test’s journal-seeding flow to single-quote both interpolated paths, paths.dir and paths.journal, while preserving the existing base64 write behavior. Follow the quoting approach used by the seedJournal implementation in the grok-build sibling. In `@packages/ai-durable-stream/tests/offset-composition.test-d.ts`: - Around line 11-16: Update the variance description in the offset-composition test comment to state that StreamDurability is invariant in TOffset, reflecting its use in both input and output positions. Keep the surrounding explanation and referenced symbols unchanged. In `@packages/ai-grok-build/tests/translate-determinism.test.ts`: - Around line 160-198: Remove the journal-specific rationale and best-effort journal cleanup from this test, since capabilityContextWith(sbx) supplies only SandboxCapability and keeps the execution unjournaled. Preserve the unique runId generation and message ID shape assertions; only add SandboxDurabilityCapability wiring if this test is explicitly intended to validate journaling. In `@packages/ai-opencode/tests/durability-attach.test.ts`: - Around line 46-137: Extract the shared noopLogger, fakeAdapterLog, durability, and contextWith helpers into `@tanstack/ai-sandbox`’s existing testkit subpath, preserving the SandboxRunDurability, SandboxCapability, and SandboxDurabilityCapability contract. In packages/ai-opencode/tests/durability-attach.test.ts lines 46-137 and packages/ai-grok-build/tests/durability-protocol-warning.test.ts lines 151-203, remove the local definitions and import the shared implementations instead. In `@packages/ai-persistence/tests/abort-status.test.ts`: - Around line 168-199: Extract the duplicated interrupt-boundary adapter setup from the inline adapter in the “interrupt status shape” test and interruptThenHangAdapter into a shared interruptAdapter(signal?: AbortSignal) helper. Centralize the RUN_STARTED and interrupt RUN_FINISHED chunks there, and retain the optional abort-wait behavior only when a signal is provided; update both call sites to use the helper. In `@packages/ai-sandbox-daytona/tests/handle.test.ts`: - Around line 1-2: Move packages/ai-sandbox-daytona/tests/handle.test.ts beside packages/ai-sandbox-daytona/src/handle.ts, and move packages/ai/tests/run-store.test.ts beside packages/ai/src/activities/chat/middleware/run-store.ts; preserve both tests’ contents and update imports only as needed after relocation. In `@packages/ai-sandbox-docker/tests/docker-daemon.ts`: - Around line 63-79: Bound the Docker connectivity check in dockerDaemonGate by racing the Dockerode ping against a short timeout, converting timeout rejection into the existing describeError failure path. Preserve the current behavior: return the named unsupported result when Docker is optional, and throw the existing hard failure when dockerIsRequired() is true. In `@packages/ai-sandbox-local-process/src/handle.ts`: - Around line 837-845: Update spawnProcess around the abort listener registration to retain the listener callback and remove it when the spawned child closes, using the child process close handling to perform cleanup. Preserve the once-only abort behavior while ensuring completed children no longer respond to later aborts on a shared AbortSignal. In `@packages/ai-sandbox-local-process/src/index.ts`: - Around line 3-15: Remove the Windows-specific helpers classifyTaskkillResult, msysDescendantWinPids, parseMsysProcessTable, and taskkillPid from the package root exports in index.ts, while preserving LocalProcessHandle, LOCAL_PROCESS_CAPS, and the public types. Keep tests importing the helpers directly from handle, or expose them only through a dedicated subpath if that package convention is required. In `@packages/ai-sandbox-local-process/tests/destroy-teardown.test.ts`: - Around line 205-210: Replace the fixed 200 ms timeout in the destroy-teardown test with an explicit child-process readiness signal: have the holder child write a recognizable line to stdout after establishing its CWD, then await that line before calling removeDirWithRetry. Preserve the existing assertions for exactly one “still busy” warning and the directory metadata. In `@packages/ai-sandbox-local-process/tests/journal.conformance.test.ts`: - Around line 14-16: Update the afterAll cleanup in journal.conformance.test.ts to configure fsp.rm with removal retries, including the retry count and retry delay used by the corresponding takeover.conformance.test.ts cleanup. Preserve recursive and force deletion so teardown tolerates directories briefly remaining pinned by exiting processes. In `@packages/ai-sandbox-local-process/tests/reaper.conformance.test.ts`: - Around line 25-27: Make the afterAll cleanup around fsp.rm non-fatal by wrapping the baseDir removal in try/catch and swallowing cleanup errors such as Windows EBUSY; preserve the existing recursive, forceful removal behavior. In `@packages/ai-sandbox-local-process/tests/takeover.conformance.test.ts`: - Around line 20-22: Update the afterAll cleanup in the takeover conformance test to use the same bounded removal-retry pattern as destroy-teardown.test.ts, so transient EBUSY failures from a live process CWD are retried before teardown ultimately fails. In `@packages/ai-sandbox-vercel/tests/vercel.test.ts`: - Around line 110-122: Update the abort propagation test around makeHandle(sandbox).process.spawn to replace the fixed setTimeout(0) delay with vi.waitFor wrapping the kill assertion, allowing the async abort handler to complete before verifying kill was called with SIGKILL. In `@packages/ai-sandbox/src/align.ts`: - Around line 278-291: Replace the plain Error thrown by the short-replay branch in the alignment loop with JournalReplayDivergedError or an appropriate dedicated subclass, passing the trailing index as required by its constructor. Preserve the existing divergence message and ensure truncated replays are identifiable via instanceof JournalReplayDivergedError. In `@packages/ai-sandbox/src/driver.ts`: - Around line 175-201: Resolve input.durability(i.runId) once at the start of pipe, store the returned durability instance, and reuse it for both awaitLogQuiescence and fenceDurability. Ensure the fenced factory no longer invokes input.durability a second time, while preserving the existing claim validation and fencing behavior. In `@packages/ai-sandbox/src/run.ts`: - Around line 307-317: Consider batching buffered chunks before calling durability.append in the stream loop to reduce sequential network round trips, while preserving append’s per-chunk offset contract. Flush the batch immediately when a terminal RUN_ERROR chunk is encountered, and account for the epoch-fence implications of larger batches; this is optional follow-up work rather than a required PR change. In `@packages/ai-sandbox/src/sandbox.ts`: - Around line 269-279: Align SandboxDefinition.destroy with reclaim.ts by choosing and explicitly implementing a consistent failed-destroy policy, ensuring store.delete(key) is handled according to that policy even when provider.destroy aborts or rejects. Review every caller of SandboxDefinition.destroy, including definition.destroy and sandbox.destroy usages, and update them to explicitly handle any rejection introduced by the timeout. In `@packages/ai-sandbox/tests/durability.test.ts`: - Around line 258-263: Update the “withSandbox durability options declare no TTL” test to check both detachedRunTtl and detachedRunTtlMs on each of SandboxDurabilityOptions and SandboxRunDurability, preserving the existing type-level assertion style. In `@packages/ai-sandbox/tests/middleware-durability.test.ts`: - Around line 142-152: Remove the unused runs field from the Harness type and the returned harness object around the middleware test harness factory. Do not create a fallback InMemoryRunStore there; retain the middleware’s existing store wiring and leave the other harness fields unchanged. In `@packages/ai-sandbox/tests/run-driver.test.ts`: - Around line 42-50: Update textChunk to return the object literal directly as StreamChunk, removing the `as unknown as StreamChunk` double cast while preserving its existing fields and values. In `@packages/ai/tests/resume-driver.test.ts`: - Around line 413-447: Strengthen the test around resumeServerSentEventsResponse so it explicitly verifies the mocked driver.drive was invoked, distinguishing the thrown-drive path from the existing “not driving this run” path. Keep the current logging assertion and response behavior checks unchanged.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
🛑 Comments failed to post (2)
packages/ai-sandbox-cloudflare/tests/run-log.test.ts (1)
1-2: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Place this unit test beside
src/run-log.ts.Move this file to
packages/ai-sandbox-cloudflare/src/run-log.test.ts. Update the import to use./run-log.As per coding guidelines, “Place unit tests in
*.test.tsfiles alongside the source they cover.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-cloudflare/tests/run-log.test.ts` around lines 1 - 2, Move the run-log unit test from the tests directory to sit beside run-log.ts as run-log.test.ts, and update its InMemoryRunEventLog and isTerminalRunStatus import from the parent-relative path to the local ./run-log module.Source: Coding guidelines
packages/ai/src/stream-to-response.ts (1)
750-764: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Close the one gap in
startRunDriver's "total by construction" contract.Line 753 calls
resolveResumeRunId(driver.request)outside anytry. If it throws, the async body rejects, and the rejection escapes the documented guarantee.waitUntilthen receives a rejected promise, which is the exact process-fatal or instance-fatal outcome the JSDoc says this function prevents. Thevoid promise.catch(() => {})fallback only protects the branch withoutwaitUntil.A throw is reachable from client input: run-id resolution parses the request URL and its query string, and
decodeURIComponentraisesURIErroron a malformed percent-escape.Attach the catch to the promise itself, so both branches are covered regardless of which statement threw.
🛡️ Proposed fix
- const promise = (async () => { + const promise = (async () => { const runId = resolveResumeRunId(driver.request) if (runId === null) return- })() + })().catch((error: unknown) => { + // Totality is the contract: there is no caller to report to, and a + // rejection handed to `waitUntil` is fatal to the worker/Durable Object. + logger?.errors('resume driver: failed before the drive started', { error }) + })With the catch attached, keep
void promise.catch(() => {})or drop it; the promise can no longer reject.#!/bin/bash # Description: Check whether resolveResumeRunId can throw on client-supplied input. rg -n --type=ts -C10 'export function resolveResumeRunId' packages/ai/src🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/src/stream-to-response.ts` around lines 750 - 764, Update startRunDriver so the promise-level catch wraps the entire async body, including resolveResumeRunId(driver.request), rather than only catching later run-record operations. Ensure both waitUntil and the fallback path receive a non-rejecting promise, while preserving the existing logging and early-return behavior.Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/ai/skills/ai-core/middleware/SKILL.md`: - Around line 715-778: Update the terminal-hook isolation documentation to replace the nonexistent runTerminalHook reference with the actual captureTerminalHook method name. Leave the surrounding hook-guarding guidance unchanged.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
9b6f692d-b3a8-4804-8d7f-bd2ed10a7315📥 Commits
Reviewing files that changed from the base of the PR and between a45ed8929bbc8c0bad43bb4865aa82b5680d557b and 108397cff9929432321f91f8d31e38a23e580c9a.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (59)
.changeset/bootstrap-shell-fails-fast.md.changeset/detached-run-log-stays-open.md.changeset/durable-run-types.md.changeset/fresh-client-tail.md.changeset/middleware-terminal-hook-isolation.md.changeset/reap-detached-runs.md.changeset/run-status-guard.md.changeset/run-store-find-active-run-required.md.changeset/sandbox-kill-claims-measured.mddocs/config.jsondocs/persistence/build-your-own-adapter.mddocs/persistence/chat-persistence.mddocs/persistence/internals.mddocs/persistence/overview.mddocs/resumable-streams/advanced.mddocs/resumable-streams/overview.mddocs/sandbox/durable-runs.mddocs/sandbox/journal.mddocs/sandbox/reaping.mddocs/sandbox/takeover.mdexamples/ts-react-chat/src/lib/sqlite-persistence.test.tsexamples/ts-react-chat/src/lib/sqlite-persistence.tspackages/ai-persistence/skills/ai-persistence/build-cloudflare-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/build-custom-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/build-drizzle-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/build-prisma-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/stores/SKILL.mdpackages/ai-persistence/src/index.tspackages/ai-persistence/src/memory.tspackages/ai-persistence/src/middleware.tspackages/ai-persistence/src/reconstruct-generation.tspackages/ai-persistence/src/reconstruct.tspackages/ai-persistence/src/testkit/conformance.tspackages/ai-persistence/src/types.tspackages/ai-persistence/tests/error-abort.test.tspackages/ai-persistence/tests/memory.test.tspackages/ai-sandbox/skills/ai-sandbox/SKILL.mdpackages/ai-sandbox/src/claim.tspackages/ai-sandbox/tests/attach-preflight.test.tspackages/ai-sandbox/tests/fence-record.test.tspackages/ai-sandbox/tests/reap.test.tspackages/ai-sandbox/tests/run-driver.test.tspackages/ai/skills/ai-core/client-persistence/SKILL.mdpackages/ai/skills/ai-core/media-generation/SKILL.mdpackages/ai/skills/ai-core/middleware/SKILL.mdpackages/ai/skills/ai-core/tool-calling/SKILL.mdpackages/ai/src/activities/chat/index.tspackages/ai/src/activities/chat/middleware/compose.tspackages/ai/src/activities/chat/middleware/run-store.tspackages/ai/src/activities/chat/middleware/types.tspackages/ai/src/index.tspackages/ai/src/stream-durability.tspackages/ai/src/stream-to-response.tspackages/ai/tests/resume-driver.test.tspackages/ai/tests/run-cancel.test.tspackages/ai/tests/stream-delivery-contract.test.tspackages/ai/tests/stream-durability.test.tstesting/e2e/src/routeTree.gen.tstesting/e2e/src/routes/api.durable-takeover.ts
🚧 Files skipped from review as they are similar to previous changes (31)
- docs/resumable-streams/overview.md
- docs/persistence/internals.md
- packages/ai-persistence/src/memory.ts
- packages/ai-persistence/tests/memory.test.ts
- docs/persistence/chat-persistence.md
- docs/resumable-streams/advanced.md
- packages/ai-persistence/tests/error-abort.test.ts
- .changeset/bootstrap-shell-fails-fast.md
- .changeset/middleware-terminal-hook-isolation.md
- .changeset/reap-detached-runs.md
- .changeset/detached-run-log-stays-open.md
- .changeset/sandbox-kill-claims-measured.md
- packages/ai/tests/run-cancel.test.ts
- .changeset/run-status-guard.md
- docs/persistence/overview.md
- packages/ai/tests/resume-driver.test.ts
- examples/ts-react-chat/src/lib/sqlite-persistence.test.ts
- packages/ai-persistence/src/testkit/conformance.ts
- examples/ts-react-chat/src/lib/sqlite-persistence.ts
- packages/ai-sandbox/tests/run-driver.test.ts
- packages/ai-persistence/src/index.ts
- packages/ai-sandbox/tests/attach-preflight.test.ts
- packages/ai-sandbox/tests/reap.test.ts
- docs/sandbox/journal.md
- docs/config.json
- docs/sandbox/takeover.md
- packages/ai/src/stream-to-response.ts
- packages/ai-sandbox/src/claim.ts
- testing/e2e/src/routes/api.durable-takeover.ts
- .changeset/durable-run-types.md
- docs/sandbox/reaping.md
packages/ai/skills/ai-core/middleware/SKILL.md lines 715 to 778@@ -685,9 +762,17 @@762+ ctx.defer(763+ fetch('/api/analytics', {764+ method: 'POST',765+ body: JSON.stringify({ duration: info.duration }),766+ }),767+ )768+ },685769 }686770 ```687771688-Wrap all middleware hooks in try-catch to prevent analytics or logging failures689-from killing the chat stream. For async side effects, prefer `ctx.defer()` which690-runs after the terminal hook and isolates failures.772+Rule: put the try-catch where the framework has none — `onChunk` and `onConfig`773+(and the other transform hooks: `onStructuredOutputConfig`, `onBeforeToolCall`,774+`onAfterToolCall`). For async side effects in the terminal hooks, prefer775+`ctx.defer()`, which runs after the terminal hook and isolates failures.691776692-Source: docs/advanced/middleware.md777+Source: docs/advanced/middleware.md, `packages/ai/src/activities/chat/middleware/compose.ts`693778📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Fix the function name referenced in the terminal-hook isolation doc.
The doc states terminal hooks are wrapped by core's
runTerminalHook. The actual private method inpackages/ai/src/activities/chat/middleware/compose.tsis namedcaptureTerminalHook. NorunTerminalHooksymbol exists in that file. Update the doc to reference the correct name so anyone tracing this guarantee back to source finds it.📝 Proposed fix
-(`onFinish`, `onAbort`, `onError`) are individually wrapped** by core's -`runTerminalHook`: a throw there is logged on the `errors` channel and the next +(`onFinish`, `onAbort`, `onError`) are individually wrapped** by core's +`captureTerminalHook`: a throw there is logged on the `errors` channel and the next📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
### b. MEDIUM: Middleware exceptions breaking the stream — in `onChunk` / `onConfig` Know which hooks the framework already guards. **The terminal hooks (`onFinish`, `onAbort`, `onError`) are individually wrapped** by core's `captureTerminalHook`: a throw there is logged on the `errors` channel and the next middleware's terminal hook still runs, so a failed analytics `POST` in `onFinish` cannot break the stream or replace the abort reason. Guarding those is about keeping your own bookkeeping intact, not about protecting the run. **`onChunk` and `onConfig` are NOT guarded, deliberately** — they are transforms on the data path, where swallowing a throw would forward a chunk or a config the middleware had decided to reject. A throw from either fails the whole stream. That is where an unhandled error actually costs you a response:🧰 Tools
🪛 SkillSpector (2.4.4)
[warning] 557: [AS3] Skill Enumeration: Skill enumerates or reads other installed skills. Access to other skills' SKILL.md files or the skills directory reveals prompt instructions, capabilities, and secrets that should be invisible to peer skills.
Remediation: Remove all code or instructions that list or read other skills' files or directories. Skills should operate independently; cross-skill access is a privilege escalation.
(Agent Snooping (AS3))
[warning] 784: [AS3] Skill Enumeration: Skill enumerates or reads other installed skills. Access to other skills' SKILL.md files or the skills directory reveals prompt instructions, capabilities, and secrets that should be invisible to peer skills.
Remediation: Remove all code or instructions that list or read other skills' files or directories. Skills should operate independently; cross-skill access is a privilege escalation.
(Agent Snooping (AS3))
[warning] 55: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 59: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 59: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 60: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 62: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 63: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 64: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 65: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 66: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 67: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 68: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 69: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 85: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 87: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 88: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 89: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 90: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 91: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 253: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
[warning] 258: [MP2] Context Window Stuffing: Skill attempts to fill the context window with filler content, displacing legitimate instructions and safety constraints. This can degrade agent performance or bypass safety boundaries.
Remediation: Implement context-window management that detects and rejects padding or stuffing attempts. Prioritize system instructions over user-injected content.
(Memory Poisoning (MP2))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai/skills/ai-core/middleware/SKILL.md` around lines 715 - 778, Update the terminal-hook isolation documentation to replace the nonexistent runTerminalHook reference with the actual captureTerminalHook method name. Leave the surrounding hook-guarding guidance unchanged.Cloudflare feedback#
The CF path ("DO owns the run + clients tail a DO-backed event log") shouldn't be documented as a Cloudflare specialization — it's the log-first tier of the portable protocol, and most of it already exists:
StreamDurabilityis the required half of the durability wiring,ai-durable-streamis a multi-host backend with cursor replay, andalign.tsalready reconciles journal → stored log on attach. The only genuinely CF-specific piece is the DO's supervised lifetime (driver outlives requests,alarm()); off CF, journal + takeover is the substitute for that, so it stays mandatory — just demoted to driver-recovery duty.Asks#
Docs
- Name the two tiers explicitly: journal-only (zero infra; log durability = sandbox lifetime) vs log-first (clients only tail the log; reconnect never touches the sandbox; journal = warm reattach / pump-resume only). CF is the log-first tier with DO-backed implementations, not a parallel architecture.
- One-sentence precedence rule when both exist: log wins for clients, journal wins for the pump's resume position (what
align.tsimplements). - CF non-goals:
/tmpjournal is not durable (durableFilesystem: false); refresh safety ≠ sleep survival; document thesleepAfterfootgun (a detached-but-quiet run can sleep the container and look like durability failed). Prefer named sandbox (threadId) in CF examples. - Keep the three layers separate in CF docs: run/events → DO log; workspace → re-bootstrap /
mountBucket; artifacts → R2.
Runtime / API
- Ship non-CF log backends so log-first is real off Workers: a Node/SQLite or Postgres durable-streams server, or
StreamDurability+RunStore+LockStorerecipes for Redis/Postgres. - Converge the CF package onto the portable seams (the
run-log.tsheader already marks its legacy vocabulary as deferred migration): DO log becomes aStreamDurabilitybackend, coordinator a platform binding of the portable driver,alarm()a binding of the reaper. Ship the DOalarm()reaper example, not only generic cron. - Keep disconnect = detach tail; Stop = explicit cancel on the CF path, and when
killableProcesses: false, document what cancel actually does (destroy vs "marked cancelled, still running").
Verification
- CF journal/kill conformance should be measured or named-skip, never a silent pass.
Keep as-is#
Detach vs Stop, both-or-neither
runs+durability, unforgeable exit sentinel, measuredkillableProcesses, non-driving reaper.Summary: promote what CF proved — clients tail a log, the sandbox is never touched on reconnect, cancel is explicit — to the documented production tier of the one portable protocol, with the journal officially demoted to driver recovery whenever a real log backend is wired. Cost worth stating: log-first double-writes every chunk (journal + log), and journal-only must remain the zero-infra default.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
docs/persistence/internals.md (1)
186-191: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse the compound modifier “end-to-end”.
Change “end to end” to “end-to-end” in the SQLite sentence.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/internals.md` around lines 186 - 191, Update the SQLite sentence in the adapter documentation to use the compound modifier “end-to-end” instead of “end to end,” without changing the surrounding content.Source: Linters/SAST tools
docs/persistence/build-your-own-chat-adapter.md (4)
91-92: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winValidate persisted JSON before returning it.
JSON.parsereturns untrusted data. The type annotation at Line 91 does not validateModelMessage. Corrupt JSON can throw during hydration, and valid JSON with the wrong shape can reach message, run, or interrupt consumers. Add runtime validation or Standard Schema parsing for typed values, and handle parse failures with each store’s safe fallback.Based on learnings: hand-written persistence adapters must narrow or validate parsed values before use.
Also applies to: 159-160, 346-350, 447-448
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-chat-adapter.md` around lines 91 - 92, Validate the result of JSON.parse in each persistence adapter before returning or using it, rather than relying on the Array<ModelMessage> annotation. Apply runtime or Standard Schema validation at the persisted-value boundaries around the visible parsed assignments and the additional locations noted, and route both parse and validation failures through each store’s existing safe fallback behavior.Source: Learnings
505-528: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winAdd the client side of the chat example.
This section shows only the server
POSThandler. Add a client example that sendsthreadId,runId, and optionalresume, then consumes the SSE response.Based on coding guidelines: applicable documentation examples must show both server and client sides.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-chat-adapter.md` around lines 505 - 528, Extend the chat adapter documentation example with a client-side example corresponding to the server POST handler. Show the client sending threadId, runId, and optional resume in the request, then consuming the returned SSE stream; keep the existing server example unchanged.Source: Coding guidelines
200-210: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winRead the stored row after the insert attempt.
The initial
SELECTandINSERT ... ON CONFLICT DO NOTHINGare separate operations. If another writer inserts the run after Line 201, the insert does nothing, but this method returns the caller’s input instead of the stored record. This breakscreateOrResumeidempotency.Proposed fix
async createOrResume(input) { - const existing = select.get(input.runId) - if (existing) return mapRun(existing) const status: RunStatus = input.status ?? 'running' - insert.run(input.runId, input.threadId, status, input.startedAt) - return { - runId: input.runId, - threadId: input.threadId, - status, - startedAt: input.startedAt, - } + insert.run(input.runId, input.threadId, status, input.startedAt) + const row = select.get(input.runId) + if (!row) throw new Error(`Run ${input.runId} was not persisted`) + return mapRun(row) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-chat-adapter.md` around lines 200 - 210, Update createOrResume so it reads the stored run row again after insert.run completes, including when the insert is skipped due to a conflict, and returns that persisted row through mapRun. Preserve the existing early return for rows found by the initial select and avoid returning caller-provided input values after the insert attempt.
95-95: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winSerialize JSON-bound values with
undefinedhandling.JSON.stringifycan resolve toundefined, which the SQLite bind helpers should not receive. Use a checked serialization helper forsaveThread, usage writes, interrupt payload/response writes, and metadata writes.Proposed fix
+function stringifyJson(value: unknown): string { + const json = JSON.stringify(value) + if (json === undefined) { + throw new TypeError('Value is not JSON-serializable') + } + return json +}Replace the affected
JSON.stringify(...)calls withstringifyJson(...).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-chat-adapter.md` at line 95, Replace the affected JSON.stringify calls in saveThread, usage writes, interrupt payload/response writes, and metadata writes with the existing stringifyJson helper, ensuring every SQLite bind receives a defined serialized value.Source: Coding guidelines
🧹 Nitpick comments (1)
docs/persistence/build-your-own-chat-adapter.md (1)
25-43: 🚀 Performance & Scalability | 🔵 TrivialAdd indexes for the implemented run queries.
createRunStoreimplements active-run lookup, thread listing, and reclaimable-run lookup, but the schema defines no supporting indexes. Add indexes for(thread_id, status, started_at)and(status, detached_since)before the runs table grows.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/build-your-own-chat-adapter.md` around lines 25 - 43, Update the SQL schema in the documented createRunStore setup to add indexes supporting the implemented runs queries: a composite index on runs(thread_id, status, started_at) and another on runs(status, detached_since). Define them alongside the runs table creation, using IF NOT EXISTS consistently with the existing schema.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/persistence/store-reference.md`: - Around line 147-153: Update the durable-field paragraph to identify four lifecycle fields, explicitly including sandboxKey. Describe sandboxKey as identifying the sandbox, detachedSince as driving reaping, cancelRequested as recording cancellation intent, and driverEpoch as fencing superseded drivers; retain that update must accept and round-trip all four fields. --- Outside diff comments: In `@docs/persistence/build-your-own-chat-adapter.md`: - Around line 91-92: Validate the result of JSON.parse in each persistence adapter before returning or using it, rather than relying on the Array<ModelMessage> annotation. Apply runtime or Standard Schema validation at the persisted-value boundaries around the visible parsed assignments and the additional locations noted, and route both parse and validation failures through each store’s existing safe fallback behavior. - Around line 505-528: Extend the chat adapter documentation example with a client-side example corresponding to the server POST handler. Show the client sending threadId, runId, and optional resume in the request, then consuming the returned SSE stream; keep the existing server example unchanged. - Around line 200-210: Update createOrResume so it reads the stored run row again after insert.run completes, including when the insert is skipped due to a conflict, and returns that persisted row through mapRun. Preserve the existing early return for rows found by the initial select and avoid returning caller-provided input values after the insert attempt. - Line 95: Replace the affected JSON.stringify calls in saveThread, usage writes, interrupt payload/response writes, and metadata writes with the existing stringifyJson helper, ensuring every SQLite bind receives a defined serialized value. In `@docs/persistence/internals.md`: - Around line 186-191: Update the SQLite sentence in the adapter documentation to use the compound modifier “end-to-end” instead of “end to end,” without changing the surrounding content. --- Nitpick comments: In `@docs/persistence/build-your-own-chat-adapter.md`: - Around line 25-43: Update the SQL schema in the documented createRunStore setup to add indexes supporting the implemented runs queries: a composite index on runs(thread_id, status, started_at) and another on runs(status, detached_since). Define them alongside the runs table creation, using IF NOT EXISTS consistently with the existing schema.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
df821ee0-d63f-47fa-95ce-3664e88f8f2b📥 Commits
Reviewing files that changed from the base of the PR and between 108397cff9929432321f91f8d31e38a23e580c9a and 374d49df08ee24f722af5c1e1d360064d3929688.
📒 Files selected for processing (16)
docs/config.jsondocs/persistence/build-your-own-adapter.mddocs/persistence/build-your-own-chat-adapter.mddocs/persistence/chat-persistence.mddocs/persistence/internals.mddocs/persistence/overview.mddocs/persistence/store-reference.mddocs/sandbox/reaping.mddocs/sandbox/takeover.mdpackages/ai-persistence/skills/ai-persistence/build-cloudflare-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/build-custom-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/build-drizzle-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/build-prisma-adapter/SKILL.mdpackages/ai-persistence/skills/ai-persistence/stores/SKILL.mdpackages/ai-persistence/src/index.tspackages/ai/skills/ai-core/client-persistence/SKILL.md
💤 Files with no reviewable changes (1)
- packages/ai-persistence/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- docs/config.json
- docs/persistence/chat-persistence.md
- docs/sandbox/reaping.md
- docs/sandbox/takeover.md
- docs/persistence/build-your-own-adapter.md
@@ -77,0 +133,21 @@133+absent, and the conformance suite skips a method's test cases once you declare134+the omission in `skipMethods`. Implement the ones your app needs:135+136+- Skip `listByThread` and you cannot render a thread's past runs.137+- Skip `listReclaimable` and the store cannot be reaped: `reapDetachedRuns`138+ feature-detects it, logs one line, and sweeps nothing, so detached runs are139+ never finalized and their sandboxes never reclaimed. `detachedSince` *is*140+ populated for you by `withSandbox`'s detach path, and note that the reaper is a141+ function the application schedules, so implementing this method is necessary142+ but not by itself sufficient. See143+ [Takeover & Detached Runs](../sandbox/takeover#configuration) for the option,144+ and [Reaping & Retention](../sandbox/reaping) for the sweep itself and the145+ schedules that drive it.146+147+The three fields a durable, reclaimable run depends on (`detachedSince`,148+`cancelRequested`, and `driverEpoch`) are the ones a hand-written backend tends149+to drop, and each omission breaks one mechanism silently rather than loudly: no150+`driverEpoch` means takeover has no fence, no `cancelRequested` means a Stop151+button cannot reach a run driven by another replica, and no `detachedSince` (or152+`sandboxKey`) means nothing can find the detached sandbox again. `update` must153+accept and round-trip all of them.🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Correct the durable-field inventory and field roles.
The paragraph calls these “three fields” but omits
sandboxKey, then groupscancelRequestedwith sandbox discovery. Document four lifecycle fields:sandboxKeyidentifies the sandbox.detachedSincedrives reaping.cancelRequestedrecords cancellation intent.driverEpochfences superseded drivers.
This distinction is important for hand-written adapters.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/persistence/store-reference.md` around lines 147 - 153, Update the durable-field paragraph to identify four lifecycle fields, explicitly including sandboxKey. Describe sandboxKey as identifying the sandbox, detachedSince as driving reaping, cancelRequested as recording cancellation intent, and driverEpoch as fencing superseded drivers; retain that update must accept and round-trip all four fields.✅ Addressed in commits 6feb564 to e4fd0c1
Noticed the focus on durable, reconnectable sandbox runs. I specialize in maintaining agent state across connection drops.
tombeckenham reviewed
Noticed the focus on durable, reconnectable sandbox runs. I specialize in maintaining agent state across connection drops.
Hey @Me333-jjj what are you thoughts on the PR?
docs/sandbox/journal.md line 36@@ -0,0 +16,21 @@16+17+# The Run Journal18+19+A sandboxed coding agent can work for ten minutes. If the host process holding20+the agent's stdout pipe goes away in minute three, that pipe breaks, the agent21+gets a `SIGPIPE`, and the work is gone. Nothing is left to read, because the22+only copy of the agent's output was in flight.23+24+So the agent does not write to a pipe. Its stdout is redirected to a file inside25+the sandbox, and the host tails that file:26+27+```28+/tmp/tanstack-runs/<runId>.ndjson every NDJSON event the agent emitted29+/tmp/tanstack-runs/<runId>.err the agent's stderr, kept separate30+```31+32+Because there is no pipe, there is no reader whose disappearance can signal the33+agent. And because the journal is a file, a reader can start at byte 0 whenever34+it likes.35+36+## You have to ask for a journalI'm starting to think we should be a opinionated. Is there any reason why the user would not want to ask for a journal? Should it be on by default?
docs/sandbox/journal.md lines 107 to 110@@ -0,0 +90,21 @@90+ // no help on a POST route; `durableStream` does — see ./takeover.91+ const adapter = memoryStream(request)92+ const stream = chat({93+ adapter: claudeCodeText('claude-sonnet-4-6'),94+ messages,95+ threadId,96+ // Without this a durable run throws: the journal path and the deterministic97+ // message ids are both derived from it, so a later reader can only find the98+ // journal of a run whose `runId` it can recompute.99+ runId,100+ // BOTH options, or there is no journal to read.101+ middleware: [withSandbox(sandbox, { runs, durability: { adapter } })],102+ })103+ return toServerSentEventsResponse(stream, { durability: { adapter } })104+}105+```106+107+`@tanstack/ai-client` mints a fresh `runId` for every run and puts it in the108+AG-UI request body, which is what `chatParamsFromRequest` hands back. So the109+client half of this is nothing at all: `useChat` already sends a unique id per110+run, and reconnecting behaviour is unchanged.I totally miss this section. When would they use journals without using ai-client...
We should be leading with. tanstack-ai already mints the runId, so don't worry about it
We should be leading with. tanstack-ai already mints the runId, so don't worry about it
docs/sandbox/journal.md lines 54 to 61@@ -0,0 +41,21 @@41+only when that run is **durable**, which means `withSandbox` was given **both**42+`runs` and `durability` — `withSandbox(sandbox, { runs, durability: { adapter } })`,43+as the snippet below does. Pass neither (a plain `withSandbox(sandbox)`) or only one, and there is no44+journal at all: `journalOptionsFor` answers `undefined`, `spawnNdjson` takes its45+original unjournaled path, and the agent's stdout is a pipe again, exactly as it46+was before this feature existed. Nothing warns — a half-configured app has not47+asked for durability, so there is nothing to warn about. If you go looking for48+`/tmp/tanstack-runs/<runId>.ndjson` after running a plain `withSandbox(sandbox)`,49+you will not find it, and the reason is here rather than in your provider.50+51+Why both: a record with no event log cannot be replayed, and a log with no record52+cannot be found, claimed, or reaped. There is no useful half.53+54+## Give every run an id you can recompute55+56+The journal path is derived from `runId` alone, so a `runId` you cannot57+reproduce is a journal nobody can find. Adapters fall back to a random internal58+id on a **non-durable** run; on a durable one there is no fallback at all —59+`chatStream` throws `DurableRunIdRequiredError`, deliberately, because an id no60+successor host can recompute produces a run that streams normally and is61+silently unrecoverable.This runId section makes it sound more complicated than it is. It reads like the user has to create runIds manually and store them somewhere.
docs/sandbox/journal.md lines 207 to 213@@ -0,0 +193,21 @@193+194+```ts195+import { journalPaths, journalReadStrategy, readJournal } from '@tanstack/ai-sandbox'196+import { handle } from './sandbox-handle'197+198+console.log(journalReadStrategy(handle)) // 'follow' | 'poll'199+200+const lines = readJournal(handle, {201+ paths: journalPaths('run-2a7f'),202+ strategy: 'poll',203+ pollIntervalMs: 100,204+})205+```206+207+## The exit sentinel carries a nonce208+209+The line a run's shell appends after the agent exits is not the bare210+`{"__exit":N}` it once was. It now carries a second field too:211+212+```json213+{"__exit":0,"__nonce":"3f9c1a7b..."}This is maybe getting into detail that probably should live in comments rather than user facing docs.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
docs/sandbox/takeover.md (1)
414-433: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winNote the missing authorization check in the cancel-endpoint sample.
The handler takes
threadIdstraight from the request body and cancels its active run with no ownership check. Add a short comment noting that production endpoints must authorize the caller againstthreadIdbefore callingrequestRunCancel, so this sample isn't copied as-is into an unauthenticated route.Based on learnings from a related persistence-doc review: "do not rely on client-provided threadId as an authorization mechanism... authorize thread ownership/visibility at the route boundary before any persistence reads or writes."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/takeover.md` around lines 414 - 433, Add a short comment in the POST handler before the findActiveRun/requestRunCancel flow stating that production routes must authorize the caller’s ownership or visibility of the client-provided threadId at the route boundary before persistence access or cancellation; leave the cancellation logic unchanged.Source: Learnings
♻️ Duplicate comments (1)
packages/ai-sandbox-cloudflare/src/coordinator.ts (1)
190-191: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winContain exceptions from
onRunSettledbefore handing the promise towaitUntil.settle()calls the overridableonRunSettledhook directly. If a subclass override throws,done.then(settle, settle)returns a rejected promise, and that rejection reachesctx.waitUntil. Wrap the call insettleso it always resolves.🛠️ Proposed fix
- const settle = (): void => this.onRunSettled(input.runId) + const settle = (): void => { + try { + this.onRunSettled(input.runId) + } catch (error) { + console.error( + `[sandbox-coordinator] onRunSettled failed for run ${input.runId}:`, + error, + ) + } + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-cloudflare/src/coordinator.ts` around lines 190 - 191, Update the local settle function in the coordinator completion flow to catch and contain any exception thrown by the overridable onRunSettled hook, ensuring settle always resolves before its promise is passed to ctx.waitUntil. Preserve invocation on both fulfillment and rejection paths of done.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/sandbox/cloudflare.md`: - Around line 158-161: Add an authorization caveat beside the threadId naming guidance: routes must verify the caller owns or may access the client-supplied threadId at the route boundary before naming, reusing, or reconnecting to the sandbox. Make clear that threadId alone is not an authorization mechanism, consistent with the existing thread-ownership guidance for persistence. In `@docs/sandbox/durable-runs.md`: - Around line 102-106: Add the text language tag to the fenced diagram code block in the durable-runs documentation, changing the opening fence to use text while preserving the diagram content unchanged. In `@packages/ai-sandbox-cloudflare/src/durability.ts`: - Around line 140-144: Update the durability backend’s close handler so it does not call log.finish(runId, 'completed') after a failed terminal runs.update, which can overwrite the original status and error. Keep close as a no-op, or implement a separate update-failure wake-up path that preserves the run flow’s original status/error. In `@packages/ai-sandbox-cloudflare/tests/driver-binding.test.ts`: - Around line 103-110: Update the test around collect(log.read('r1')) to synchronize on explicit evidence that the live reader is parked and subscribed before calling ac.abort() and release(). Replace the single timer-turn delay with the existing reader-waiting signal or observable state, while preserving the expectation that only sequence 0 is received and done.status is aborted. --- Outside diff comments: In `@docs/sandbox/takeover.md`: - Around line 414-433: Add a short comment in the POST handler before the findActiveRun/requestRunCancel flow stating that production routes must authorize the caller’s ownership or visibility of the client-provided threadId at the route boundary before persistence access or cancellation; leave the cancellation logic unchanged. --- Duplicate comments: In `@packages/ai-sandbox-cloudflare/src/coordinator.ts`: - Around line 190-191: Update the local settle function in the coordinator completion flow to catch and contain any exception thrown by the overridable onRunSettled hook, ensuring settle always resolves before its promise is passed to ctx.waitUntil. Preserve invocation on both fulfillment and rejection paths of done.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
b4a75d56-f981-44d3-a755-75d387cab96f📥 Commits
Reviewing files that changed from the base of the PR and between 374d49df08ee24f722af5c1e1d360064d3929688 and e607c0b434db00467834c30cb965d90e02faaa50.
📒 Files selected for processing (18)
.changeset/durable-run-types.mddocs/config.jsondocs/sandbox/cloudflare.mddocs/sandbox/durable-runs.mddocs/sandbox/journal.mddocs/sandbox/providers.mddocs/sandbox/reaping.mddocs/sandbox/takeover.mdexamples/sandbox-cloudflare/wrangler.jsoncpackages/ai-sandbox-cloudflare/src/agent.tspackages/ai-sandbox-cloudflare/src/coordinator.tspackages/ai-sandbox-cloudflare/src/durability.tspackages/ai-sandbox-cloudflare/src/run-log-do.tspackages/ai-sandbox-cloudflare/src/run-log.tspackages/ai-sandbox-cloudflare/tests/driver-binding.test.tspackages/ai-sandbox-cloudflare/tests/journal.conformance.test.tspackages/ai-sandbox-cloudflare/tests/run-log-do.test.tspackages/ai-sandbox-cloudflare/tests/run-log.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- docs/sandbox/providers.md
- docs/sandbox/reaping.md
- .changeset/durable-run-types.md
- docs/config.json
docs/sandbox/cloudflare.md lines 158 to 161@@ -89,0 +141,21 @@141+142+- **The journal is not durable here.** `cloudflareSandbox` declares143+ `durableFilesystem: false`: the `/tmp` journal lives exactly as long as the144+ container instance. That is fine — on this tier the DO log is the durable145+ copy and the journal is driver recovery — but it means the journal must never146+ be treated as the store of record.147+- **Refresh safety is not sleep survival.** The log makes *reconnecting148+ clients* safe. It does not keep the container awake: if the container stops,149+ the agent process dies mid-run like anywhere else, and what the log preserves150+ is everything emitted up to that point.151+- **The `sleepAfter` footgun.** The Sandbox container class carries a152+ `sleepAfter` idle timeout. A run that is *detached but quiet* — nobody153+ connected, the agent thinking or waiting — can look idle, and an idle154+ container sleeps. The symptom is a run that "died for no reason" while the155+ log dutifully preserved its prefix, which reads as durability failing when it156+ is the container lifecycle working as configured. Size `sleepAfter` well157+ above your longest expected quiet stretch before relying on detached runs.158+- **Name the sandbox by `threadId`.** Prefer159+ `defineSandbox({ id: input.threadId, … })` (as `examples/sandbox-cloudflare`160+ does) over a fixed id: reconnects, `exposePreview`, and `reuse: 'thread'`161+ then all address the same container even across DO eviction.🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
Add an authorization caveat next to the
threadIdsandbox-naming guidance.This section tells readers to key sandbox identity by
input.threadIdso reconnects andreuse: 'thread'address the same container. It does not state thatthreadIdmust be authorized server-side before use. If a route accepts a client-suppliedthreadIdand names or reconnects to a sandbox by it without checking ownership, a caller can reconnect to, tail, or drive another user's sandbox by supplying itsthreadId.Add a line stating that the route must authorize the caller against
threadId(owner/session check) before naming, reusing, or reconnecting to the sandbox, the same way persistence docs require thread ownership checks before loading transcript data.Based on learnings: "do not rely on client-provided threadId as an authorization mechanism... authorize thread ownership/visibility at the route boundary before any persistence reads or writes."
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/cloudflare.md` around lines 158 - 161, Add an authorization caveat beside the threadId naming guidance: routes must verify the caller owns or may access the client-supplied threadId at the route boundary before naming, reusing, or reconnecting to the sandbox. Make clear that threadId alone is not an authorization mechanism, consistent with the existing thread-ownership guidance for persistence.Source: Learnings
docs/sandbox/durable-runs.md lines 165 to 169@@ -0,0 +86,21 @@86+### Making "the agent finished" impossible to fake87+88+The way we know a run ended is that a special line appears at the end of the89+journal file. But the _agent itself_ writes that file, and agents write whatever90+the model says.91+92+If a model happened to print that line, the reaper would believe a running job93+had ended and would shut down a live sandbox. So the line includes a secret94+value derived from the run's own id. The agent cannot produce it, so it cannot95+get its own sandbox destroyed.96+97+## Two pipes can break, and they need different fixes98+99+A run's output crosses two pipes on its way to the user, and everything on100+this page is a fix for one of them breaking:101+102+```103+agent (in sandbox) ──[capture]──▶ server host ──[delivery]──▶ client104+ │105+ └──▶ durable delivery log106+```📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Add a language tag to the fenced diagram block.
markdownlint(MD040) flags this fenced code block for missing a language. Add a language such astextto keep the linter clean.📝 Suggested fix
-``` +```text agent (in sandbox) ──[capture]──▶ server host ──[delivery]──▶ client │ └──▶ durable delivery log</details> <!-- suggestion_start --> <details> <summary>📝 Committable suggestion</summary> > ‼️ **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion🧰 Tools
🪛 markdownlint-cli2 (0.23.1)
[warning] 102-102: Fenced code blocks should have a language specified
(MD040, fenced-code-language)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/durable-runs.md` around lines 102 - 106, Add the text language tag to the fenced diagram code block in the durable-runs documentation, changing the opening fence to use text while preserving the diagram content unchanged.Source: Linters/SAST tools
packages/ai-sandbox-cloudflare/src/durability.ts lines 140 to 144@@ -0,0 +124,21 @@124+ const offsets: Array<string> = []125+ for (const chunk of chunks) {126+ offsets.push(encodeOffset(runId, await log.append(runId, chunk)))127+ }128+ return offsets129+ },130+ read: async function* (offset, signal) {131+ const fromSeq = await seqAfter(offset)132+ const events = log.read(runId, {133+ fromSeq,134+ ...(signal !== undefined ? { signal } : {}),135+ })136+ for await (const event of events) {137+ yield { offset: encodeOffset(runId, event.seq), chunk: event.chunk }138+ }139+ },140+ // See the module header: normally a no-op (the driver's terminal141+ // `runs.update` already ended the shared record); `'completed'` lands only142+ // when that update failed, where unwedging parked readers beats leaving143+ // them on a log nothing will ever end.144+ close: () => log.finish(runId, 'completed'),🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== files ==" git ls-files | rg '(^|/)durability\.ts$|stream-durability\.ts$' || true echo "== target excerpt ==" sed -n '1,230p' packages/ai-sandbox-cloudflare/src/durability.ts echo "== stream durability excerpt ==" sed -n '1,260p' packages/ai/src/stream-durability.ts echo "== usages of close fn and finish ==" rg -n "finish\\(|close:\\s*\\(|runs\\.update|terminal|unwedging|parked readers|shared record" packages/ai-sandbox-cloudflare/src/durability.ts packages/ai/src/stream-durability.tsRepository: TanStack/ai
Length of output: 18403
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== run-log files ==" git ls-files | rg '(^|/)run-log\.ts$|run-log-store\.ts$|run-controllers|run-driver' || true echo "== run-log close/terminal implementations ==" for f in $(git ls-files | rg 'packages/.*/(run-log|run-log-store)\.ts$'); do echo "--- $f ---" sed -n '1,260p' "$f" done echo "== stream durability memory close implementation ==" sed -n '420,540p' packages/ai/src/stream-durability.ts echo "== run driver terminal patches/closes ==" rg -n "runs\.update\(|\.close\(\)|finish\\(|RUN_(FINISHED|ERROR)|run_finished|run_error|status:" packages -g '*.ts' -g '*.tsx' | head -n 250Repository: TanStack/ai
Length of output: 40334
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== run-log implementation ==" sed -n '60,225p' packages/ai-sandbox-cloudflare/src/run-log.ts echo "== run-log DO implementation ==" sed -n '80,180p' packages/ai-sandbox-cloudflare/src/run-log-do.ts echo "== core run.ts finish flow ==" sed -n '160,375p' packages/ai-sandbox/src/run.ts echo "== claim durable close flow ==" sed -n '360,470p' packages/ai-sandbox/src/claim.tsRepository: TanStack/ai
Length of output: 23738
Don’t use
close()to fix a failed terminal record write.close()is only a no-op here whenruns.update(...)already terminalized the shared record. If the update failed, the driver is still terminalizing once with the originalstatus/errorfrom the run flow; usingclose()with'completed'can overwrite a real'failed'/'aborted'outcome and hide the originalerror.Keep
close()as a no-op for this backend, or split the “wake parked readers on update failure” case into its own path instead of callinglog.finish(runId, 'completed').🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-cloudflare/src/durability.ts` around lines 140 - 144, Update the durability backend’s close handler so it does not call log.finish(runId, 'completed') after a failed terminal runs.update, which can overwrite the original status and error. Keep close as a no-op, or implement a separate update-failure wake-up path that preserves the run flow’s original status/error.packages/ai-sandbox-cloudflare/tests/driver-binding.test.ts lines 103 to 110@@ -0,0 +90,21 @@90+ yield text('a')91+ await gate92+ }93+ const { done } = controllerFor(log).start({94+ runId: 'r1',95+ threadId: 't1',96+ stream: gated(),97+ signal: ac.signal,98+ })99+100+ // Reader tails while the run is live. Core's driver will terminalize via101+ // `runs.update('aborted')`, NOT `log.finish` — if that update did not wake102+ // the in-memory waiter set, this reader would park forever.103+ const reading = collect(log.read('r1'))104+ await new Promise((resolve) => setTimeout(resolve, 0))105+ ac.abort()106+ release()107+108+ expect((await done).status).toBe('aborted')109+ const events = await reading110+ expect(events.map((e) => e.seq)).toEqual([0])🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Prove that the live reader is parked before cancellation.
Line 104 only delays for one timer turn. It does not verify that
log.read('r1')is waiting. If terminalization occurs before the reader subscribes, the test still passes and does not detect a missing wake-up fromruns.update().Proposed test change
- const reading = collect(log.read('r1')) + const reader = log.read('r1')[Symbol.asyncIterator]() + const first = await reader.next() + expect(first.value?.seq).toBe(0) + + const terminal = reader.next() + let settled = false + void terminal.then(() => { + settled = true + }) await new Promise((resolve) => setTimeout(resolve, 0)) + expect(settled).toBe(false) ac.abort() release() expect((await done).status).toBe('aborted') - const events = await reading - expect(events.map((e) => e.seq)).toEqual([0]) + expect((await terminal).done).toBe(true)📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const reader = log.read('r1')[Symbol.asyncIterator]() const first = await reader.next() expect(first.value?.seq).toBe(0) const terminal = reader.next() let settled = false void terminal.then(() => { settled = true }) await new Promise((resolve) => setTimeout(resolve, 0)) expect(settled).toBe(false) ac.abort() release() expect((await done).status).toBe('aborted') expect((await terminal).done).toBe(true)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-sandbox-cloudflare/tests/driver-binding.test.ts` around lines 103 - 110, Update the test around collect(log.read('r1')) to synchronize on explicit evidence that the live reader is parked and subscribed before calling ac.abort() and release(). Replace the single timer-turn delay with the existing reader-waiting signal or observable state, while preserving the expectation that only sequence 0 is received and done.status is aborted.Actionable comments posted: 8
🧹 Nitpick comments (1)
examples/sandbox-web/src/routes/api.run.cancel.ts (1)
23-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winValidate the body with Zod.
The repository guideline requires Zod for schema validation. The sibling route
examples/sandbox-web/src/routes/api.run.tsalready validates its body withz.preprocessandz.object. Use the same approach here so the two run routes stay consistent. A Zod schema also rejects an emptythreadId, which the current type check accepts.As per coding guidelines: "Use Zod for schema validation and tool definition with toolDefinition()".
♻️ Proposed refactor
+import { z } from 'zod' + +const cancelBodySchema = z.object({ threadId: z.string().min(1) })let body: unknown try { body = await request.json() } catch { return new Response('invalid JSON body', { status: 400 }) } - if ( - body === null || - typeof body !== 'object' || - !('threadId' in body) || - typeof body.threadId !== 'string' - ) { - return new Response('threadId is required', { status: 400 }) - } + const parsed = cancelBodySchema.safeParse(body) + if (!parsed.success) { + return new Response('threadId is required', { status: 400 }) + } - const active = await runs.findActiveRun(body.threadId) + const active = await runs.findActiveRun(parsed.data.threadId)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/sandbox-web/src/routes/api.run.cancel.ts` around lines 23 - 36, Replace the manual body checks in the cancel route with Zod validation, matching the z.preprocess and z.object pattern used by the sibling api.run route. Define a schema requiring a non-empty string threadId, parse the JSON body through it, and preserve the existing 400 response for invalid JSON or validation failures.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/adapters/opencode.md`: - Line 33: Update the sandbox-web note in docs/adapters/opencode.md:33-33 and docs/adapters/codex.md:27-27 to remove the “one-line change” claim and state that switching adapters also requires updating the workspace setup command to install the corresponding CLI and configuring the provider secret; preserve the existing adapter-swap guidance. In `@docs/sandbox/overview.md`: - Around line 124-137: Remove the repeated sandbox-web description from the documentation, keeping the first complete description with its repository link and the separate sandbox-cloudflare reference intact. In `@examples/sandbox-web/src/routes/api.run.cancel.ts`: - Around line 38-43: Document the missing authorization boundary before the runs.findActiveRun lookup in examples/sandbox-web/src/routes/api.run.cancel.ts lines 38-43: add a comment stating that multi-user deployments must derive the user from server-side session state and authorize thread ownership before recording the cancellation. Add the same comment before the runs.findActiveRun(threadId) lookup in examples/sandbox-web/src/routes/api.run.active.ts lines 15-22; no behavior change is requested. In `@examples/sandbox-web/src/routes/api.run.ts`: - Around line 161-188: Wrap the successful toServerSentEventsResponse call in a finally block that deletes driving’s runId entry when the stream completes or aborts. Keep the existing catch cleanup for setup errors, and ensure all entries created by driving.set in the surrounding route are removed after the produced run finishes. In `@examples/sandbox-web/src/routes/index.tsx`: - Around line 381-388: Update stopRun so the promise returned by the /api/run/cancel fetch is handled instead of discarded. Add rejection handling that logs or surfaces cancellation failures while preserving the existing stop() behavior and request payload. - Around line 324-327: Guard the localStorage write in the thread persistence useEffect by wrapping setItem(THREAD_KEY, threadId) in the same error-handling approach used by loadOrCreateThreadId. Keep the effect’s dependency on threadId and ensure storage failures are caught without interrupting rendering. In `@examples/sandbox-web/src/run-durable.ts`: - Around line 149-159: Update hasFinished to resume the existing sandbox through the provider’s resume() operation instead of buildSandbox(...).ensure(), preventing detached-run probes from creating replacement containers. Preserve the existing probeRunExit call and unknown-state error handling, and only use ensure when the container is confirmed present. In `@packages/ai-client/src/chat-client.ts`: - Around line 1510-1539: Update the joinRun error handling in packages/ai-client/src/chat-client.ts:1510-1539 to distinguish an explicit unknown-or-expired-run refusal from generic pre-attachment network, CORS, transport, or parser failures, and set refused only for that signal so the persisted pointer is cleared exclusively on confirmed refusal. In packages/ai-client/tests/resume-snapshot.test.ts:597-616, update the refusal scenario to use the explicit signal and add coverage proving a generic pre-attachment failure preserves the pointer. --- Nitpick comments: In `@examples/sandbox-web/src/routes/api.run.cancel.ts`: - Around line 23-36: Replace the manual body checks in the cancel route with Zod validation, matching the z.preprocess and z.object pattern used by the sibling api.run route. Define a schema requiring a non-empty string threadId, parse the JSON body through it, and preserve the existing 400 response for invalid JSON or validation failures.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
0aaf5f27-a446-466a-bb7e-44aaf8eaf76a📥 Commits
Reviewing files that changed from the base of the PR and between e607c0b434db00467834c30cb965d90e02faaa50 and 1afae7c192b7e8ff64241ae3eae183e36d87794f.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (26)
.changeset/run-accepted-marker.mddocs/adapters/claude-code.mddocs/adapters/codex.mddocs/adapters/opencode.mddocs/sandbox/overview.mdexamples/sandbox-web/.env.exampleexamples/sandbox-web/README.mdexamples/sandbox-web/package.jsonexamples/sandbox-web/src/routeTree.gen.tsexamples/sandbox-web/src/routes/api.run.active.tsexamples/sandbox-web/src/routes/api.run.cancel.tsexamples/sandbox-web/src/routes/api.run.tsexamples/sandbox-web/src/routes/index.tsxexamples/sandbox-web/src/run-durable.tsexamples/sandbox-web/src/sandbox-agent.tsexamples/sandbox-web/src/sandbox-options.tspackages/ai-client/src/chat-client.tspackages/ai-client/tests/resume-snapshot.test.tspackages/ai-durable-stream/tests/durable-stream.test.tspackages/ai/src/index.tspackages/ai/src/stream-to-response.tspackages/ai/tests/stream-delivery-contract.test.tspackages/ai/tests/stream-to-response-detached.test.tspackages/ai/tests/stream-to-response-durability.test.tstesting/e2e/tests/delivery-durability.spec.tstesting/e2e/tests/durable-takeover.spec.ts
💤 Files with no reviewable changes (1)
- examples/sandbox-web/src/sandbox-options.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- packages/ai/tests/stream-delivery-contract.test.ts
- testing/e2e/tests/durable-takeover.spec.ts
- packages/ai/src/index.ts
- packages/ai-durable-stream/tests/durable-stream.test.ts
docs/adapters/opencode.md line 33Outdated@@ -30,4 +30,4 @@3030 opencode auth login3131 ```323233-A runnable demo lives at [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web) — switch the harness (Claude Code, Codex, OpenCode, Grok Build) and sandbox provider per run, with session resume, the harness tool timeline, permission modes, and tool bridging, wired into a TanStack Start app.33+A runnable demo lives at [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare) — pick Claude Code, Codex, or Grok Build in the UI, with session resume, the harness tool timeline, and tool bridging, wired into a TanStack Start app on Workers. For the same wiring on plain Node with durable, refresh-surviving runs (Grok Build on Docker), see [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web) — swapping in this adapter is a one-line change (`src/sandbox-agent.ts`).📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Both adapter docs overstate the sandbox-web swap.
examples/sandbox-web/src/sandbox-agent.tsfixes more than the adapter:buildAdapter()returnsgrokBuildText(GROK_MODEL), and the same file pins the Grok CLI install command insetup, the Grok ACP port inpublishPorts, and theXAI_API_KEYsecret. A reader who changes onlybuildAdapter()gets a sandbox without the target CLI and without credentials.docs/adapters/opencode.md#L33-L33: replace "a one-line change" with a statement that the swap changes the adapter, the workspace setup command that installsopencode, and the provider secret.docs/adapters/codex.md#L27-L27: apply the same correction for the Codex CLI install command and its provider secret.
📍 Affects 2 files
docs/adapters/opencode.md#L33-L33(this comment)docs/adapters/codex.md#L27-L27
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/adapters/opencode.md` at line 33, Update the sandbox-web note in docs/adapters/opencode.md:33-33 and docs/adapters/codex.md:27-27 to remove the “one-line change” claim and state that switching adapters also requires updating the workspace setup command to install the corresponding CLI and configuring the provider secret; preserve the existing adapter-swap guidance.@@ -123,12 +125,13 @@123125 [`examples/sandbox-web`](https://github.com/TanStack/ai/tree/main/examples/sandbox-web):124-a "build me an app" agent you can point at any harness (Claude Code, Codex,125-OpenCode, Grok Build) and any provider (Docker, local-process, Vercel, Daytona)126-per run from the UI — it scaffolds an app inside the sandbox, runs the dev server,127-and hands back a live preview URL, streaming the agent's output and the resulting128-diff. For a coding agent running at the edge, see126+a "build me an app" agent (Grok Build in a Docker sandbox) with **durable127+runs** wired — it scaffolds an app inside the sandbox, runs the dev server,128+and hands back a live preview URL, and the run survives a page refresh, a129+closed tab, and an explicit Stop is a real cancel. For a coding agent running130+at the edge — with the harness (Claude Code, Codex, Grok Build) picked per run131+from the UI — see129132 [`examples/sandbox-cloudflare`](https://github.com/TanStack/ai/tree/main/examples/sandbox-cloudflare).130133131134 For a **web** chat where the agent builds and runs an app inside a sandbox and132-hands back a live preview URL, see `examples/sandbox-web` — one app with harness133-(Claude Code / Codex / OpenCode / Grok) and provider (Docker / local / Vercel /134-Daytona) pickers.135+hands back a live preview URL — with durable, refresh-surviving runs — see136+`examples/sandbox-web` (Grok Build on Docker; the stack is fixed in one file137+and swappable).📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Remove the duplicate
sandbox-webdescription.Lines 124-132 and lines 134-137 describe the same example. Keep one description and retain its repository link.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/sandbox/overview.md` around lines 124 - 137, Remove the repeated sandbox-web description from the documentation, keeping the first complete description with its repository link and the separate sandbox-cloudflare reference intact.✅ Addressed in commits b5989ba to 6039377
examples/sandbox-web/src/routes/api.run.cancel.ts lines 38 to 43@@ -0,0 +23,21 @@23+ let body: unknown24+ try {25+ body = await request.json()26+ } catch {27+ return new Response('invalid JSON body', { status: 400 })28+ }29+ if (30+ body === null ||31+ typeof body !== 'object' ||32+ !('threadId' in body) ||33+ typeof body.threadId !== 'string'34+ ) {35+ return new Response('threadId is required', { status: 400 })36+ }37+38+ const active = await runs.findActiveRun(body.threadId)39+ if (!active) return new Response(null, { status: 204 })40+41+ await requestRunCancel(runs, active.runId)42+ driving.get(active.runId)?.abort(RUN_CANCEL_REASON)43+ return new Response(null, { status: 204 })🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
Both run routes act on a caller-supplied
threadIdwith no ownership check. The shared root cause is that each route treats the client-providedthreadIdas sufficient authority. Any caller who learns athreadIdcan read its active run or cancel it. The example is single-user, so this is not exploitable here, but readers copy example routes into multi-user apps.examples/sandbox-web/src/routes/api.run.cancel.ts#L38-L43: add a comment aboveruns.findActiveRun(...)stating that a multi-user deployment must derive the user from server-side session state and authorize thread ownership before the cancel is recorded.examples/sandbox-web/src/routes/api.run.active.ts#L15-L22: add the same note before theruns.findActiveRun(threadId)lookup.
Based on learnings: do not rely on client-provided
threadIdas an authorization mechanism; derive identity from server-side session state and authorize thread ownership at the route boundary before any persistence reads or writes.📍 Affects 2 files
examples/sandbox-web/src/routes/api.run.cancel.ts#L38-L43(this comment)examples/sandbox-web/src/routes/api.run.active.ts#L15-L22
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/sandbox-web/src/routes/api.run.cancel.ts` around lines 38 - 43, Document the missing authorization boundary before the runs.findActiveRun lookup in examples/sandbox-web/src/routes/api.run.cancel.ts lines 38-43: add a comment stating that multi-user deployments must derive the user from server-side session state and authorize thread ownership before recording the cancellation. Add the same comment before the runs.findActiveRun(threadId) lookup in examples/sandbox-web/src/routes/api.run.active.ts lines 15-22; no behavior change is requested.Source: Learnings
@@ -253,12 +178,11 @@178+ attach: false,179+ durability: adapter,180+ ...(sessionId !== undefined ? { sessionId } : {}),181+ })253182254- return new Response(255- toServerSentEventsStream(stream, abortController),256- {257- headers: {258- 'Content-Type': 'text/event-stream',259- 'Cache-Control': 'no-cache',260- Connection: 'keep-alive',261- },262- },263- )183+ return toServerSentEventsResponse(stream, {184+ abortController,185+ durability: { adapter },186+ })264187 } catch (error) {188+ driving.delete(runId)🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Description: Inspect toServerSentEventsResponse options for a completion/finalize callback. fd -t f 'stream-to-response.ts' packages/ai/src --exec ast-grep outline {} --items all rg -nP --type=ts -C6 '(onComplete|onFinish|onClose|finally|signal)\b' packages/ai/src/stream-to-response.ts | head -60Repository: TanStack/ai
Length of output: 4780
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== locate api.run.ts and relevant helpers == " fd -t f 'api.run.ts|run-durable.ts|stream-to-response.ts' . | sed 's#^\./##' echo "== api.run.ts outline ==" ast-grep outline examples/sandbox-web/src/routes/api.run.ts --view expanded || true echo "== api.run.ts relevant lines == " sed -n '1,230p' examples/sandbox-web/src/routes/api.run.ts | cat -n echo "== run-durable.ts relevant driving maps/usages ==" rg -n -C 8 '\b(driving|driveRun|driving\.set|driving\.delete|driving\.get)\b' examples/sandbox-web/src/run-durable.ts examples/sandbox-web/src/routes/api.run.ts examples/sandbox-web/src/run-durable.ts echo "== stream-to-response response options/signals ==" sed -n '740,825p' packages/ai/src/stream-to-response.ts | cat -n rg -n -C 3 'toServerSentEventsResponse\(|StreamDurability|AbortSignal|abortController|signal' examples/sandbox-web/src/routes/api.run.ts packages/ai/src/stream-to-response.tsRepository: TanStack/ai
Length of output: 50367
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== api.run routes cancel handler ==" sed -n '228,290p' examples/sandbox-web/src/routes/api.run.ts | cat -n echo "== stream-to-response constructor options ==" sed -n '658,745p' packages/ai/src/stream-to-response.ts | cat -n echo "== completion hook occurrences in response helpers ==" rg -n -C 4 'function toServerSentEventsResponse|interface .*Response.*Options|onComplete|onFinish|onClose|finally\(|signal\.__|aborted' packages/ai/src/stream-to-response.ts | head -200 echo "== static control-flow facts ==" python3 - <<'PY' from pathlib import Path api = Path('examples/sandbox-web/src/routes/api.run.ts').read_text() lines = api.splitlines() # Track the POST handler's catch/delete and success-return locations by line numbers only. post_start = next(i for i,l in enumerate(lines,1) if post_str := 'POST: {' in l) catch_line = next(i for i,l in enumerate(lines[post_start-1:], start=post_start) if 'driving.delete(runId)' in l) return_after_try = max(i for i,l in enumerate(lines[post_start-1:], start=post_start) if 'return toServerSentEventsResponse(stream' in l if i<catch_line) print(f'catch_block_locates_delete=false') for i,l in enumerate(lines[catch_line - 10:catch_line + 12], start=catch_line-10): print(f'{i}: {l}') PYRepository: TanStack/ai
Length of output: 7874
Delete
drivingentries when the produced run completes.examples/sandbox-web/src/routes/api.run.tssetsdriving.set(runId, abortController)on the success path, buttoServerSentEventsResponse()returns before the stream finishes and has no completion callback. Remove the entry infinallyaround the stream return so slow/aborted runs do not keepAbortControllerobjects and stale cancel targets in memory for the process lifetime.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/sandbox-web/src/routes/api.run.ts` around lines 161 - 188, Wrap the successful toServerSentEventsResponse call in a finally block that deletes driving’s runId entry when the stream completes or aborts. Keep the existing catch cleanup for setup errors, and ensure all entries created by driving.set in the surrounding route are removed after the produced run finishes.✅ Addressed in commits b5989ba to 6039377
examples/sandbox-web/src/routes/index.tsx lines 324 to 327@@ -311,16 +319,9 @@311- harness,312- provider,313319 ...(harnessSessionId ? { sessionId: harnessSessionId } : {}),314- ...(harness === 'grok' ? { grokModel, grokProtocol, grokTransport } : {}),315320 }),316- [317- threadId,318- harness,319- provider,320- harnessSessionId,321- grokModel,322- grokProtocol,323- grokTransport,324- ],321+ [threadId, harnessSessionId],325322 )326323324+ // Persist the durable identity so a reload comes back to the same thread.325+ useEffect(() => {326+ localStorage.setItem(THREAD_KEY, threadId)327+ }, [threadId])🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Guard the localStorage write.
loadOrCreateThreadIdwraps the read intry/catchbecause storage access can throw. This write is unguarded. In a restricted storage mode, or when the quota is exceeded,setItemthrows inside the effect and breaks the render.🛡️ Proposed fix
useEffect(() => { - localStorage.setItem(THREAD_KEY, threadId) + try { + localStorage.setItem(THREAD_KEY, threadId) + } catch { + // Unwritable storage — the thread stays in memory for this session. + } }, [threadId])📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
// Persist the durable identity so a reload comes back to the same thread. useEffect(() => { try { localStorage.setItem(THREAD_KEY, threadId) } catch { // Unwritable storage — the thread stays in memory for this session. } }, [threadId])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/sandbox-web/src/routes/index.tsx` around lines 324 - 327, Guard the localStorage write in the thread persistence useEffect by wrapping setItem(THREAD_KEY, threadId) in the same error-handling approach used by loadOrCreateThreadId. Keep the effect’s dependency on threadId and ensure storage failures are caught without interrupting rendering.examples/sandbox-web/src/routes/index.tsx lines 381 to 388@@ -368,7 +370,19 @@368- setHarnessSessionId(undefined)369- setProvider(next)370370 setThreadId(crypto.randomUUID())371371 }372372373373 const waiting = sandboxWaitKind(isLoading, messages)374374375+ /**376+ * A real cancel, not just a closed stream. `stop()` alone aborts the local377+ * read — on a durable run that is indistinguishable from a refresh, so the378+ * agent would keep working (and billing). The endpoint records intent and379+ * destroys the sandbox.380+ */381+ function stopRun() {382+ stop()383+ void fetch('/api/run/cancel', {384+ method: 'POST',385+ headers: { 'Content-Type': 'application/json' },386+ body: JSON.stringify({ threadId }),387+ })388+ }🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Handle a failed cancel request.
void fetch(...)discards the promise. If the request rejects, for example when the browser is offline, the result is an unhandled promise rejection. The user also gets no signal that the cancel did not reach the server, whilestop()already ended the local stream. Add acatchand log or surface the failure.🛡️ Proposed fix
void fetch('/api/run/cancel', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ threadId }), - }) + }).catch((error: unknown) => { + // The run stays live server-side; the reaper's TTL is the backstop. + console.error('[cancel] request failed:', error) + })📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
function stopRun() { stop() void fetch('/api/run/cancel', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ threadId }), }).catch((error: unknown) => { // The run stays live server-side; the reaper's TTL is the backstop. console.error('[cancel] request failed:', error) }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/sandbox-web/src/routes/index.tsx` around lines 381 - 388, Update stopRun so the promise returned by the /api/run/cancel fetch is handled instead of discarded. Add rejection handling that logs or surfaces cancellation failures while preserving the existing stop() behavior and request payload.examples/sandbox-web/src/run-durable.ts lines 249 to 263@@ -0,0 +139,21 @@139+ driving.delete(input.runId)140+ }141+}142+143+/**144+ * Whether a detached run's agent already finished, by probing its journal tail145+ * for the exit sentinel. `ensure` resumes the thread's sandbox (`reuse:146+ * 'thread'`); if it had to CREATE one the probe finds no journal and answers147+ * `producing` — the fail-safe direction, and the TTL still bounds the run.148+ */149+async function hasFinished(record: RunRecord): Promise<RunExitProbe> {150+ try {151+ const handle = await buildSandbox(record.threadId).ensure({152+ threadId: record.threadId,153+ runId: 'run',154+ })155+ return await probeRunExit({ handle, runId: record.runId })156+ } catch (error) {157+ return { state: 'unknown', error }158+ }159+}🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Description: Inspect SandboxDefinition for ensure/resume/exists semantics. fd -t f 'contracts.ts|definition.ts' packages/ai-sandbox/src --exec ast-grep outline {} --items all rg -nP --type=ts -C4 '\b(ensure|resume|lookup|exists)\s*[?(:]' packages/ai-sandbox/src | head -80Repository: TanStack/ai
Length of output: 8158
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Locate relevant files" fd -t f 'definition|contracts|run-durable|sandbox' . | sed -n '1,120p' echo echo "Outline run-durable" ast-grep outline examples/sandbox-web/src/run-durable.ts --items all || true echo echo "Relevant run-durable sections" nl -ba examples/sandbox-web/src/run-durable.ts | sed -n '1,260p' echo echo "Search for SandboxDefinition.ensure and implementations" rg -n --type=ts -C6 'interface SandboxDefinition|type SandboxDefinition|ensure\(|resume\(|buildSandbox|createSandbox|Docker|docker|GROK_CLI_INSTALL_COMMAND' . | sed -n '1,260p'Repository: TanStack/ai
Length of output: 2841
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Run-durable hasFinished/reaper sections" awk '{printf "%5d\t%s\n", NR, $0}' examples/sandbox-web/src/run-durable.ts | sed -n '130,260p' echo echo "Find SandboxDefinition and ensure implementation candidates" rg -n --type=ts -C4 'interface\s+SandboxDefinition|type\s+SandboxDefinition|function\s+buildSandbox|export\s+function\s+buildSandbox|buildSandbox\s*=|ensure:|ensure\(' packages examples testing | sed -n '1,240p' echo echo "Docker/container setup commands in sandbox-web" rg -n --type=ts -C3 'GROK_CLI_INSTALL_COMMAND|reclaim|hasFinished|probeRunExit|ensure\(' examples/sandbox-web/src packages/ai-sandbox/src | sed -n '1,240p'Repository: TanStack/ai
Length of output: 41126
Use provider.resume() in the detached-run probe.
ensure()is resumed-or-created, sohasFinished()can start a replacement sandbox for runs whose container was already removed. The probe then reads an empty journal and reportsproducing, keeping the run alive until its TTL while later reclaim destruction runs after a newly created container. Call provider.resume() for this scan instead of callingensure()unless the container is still present.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@examples/sandbox-web/src/run-durable.ts` around lines 149 - 159, Update hasFinished to resume the existing sandbox through the provider’s resume() operation instead of buildSandbox(...).ensure(), preventing detached-run probes from creating replacement containers. Preserve the existing probeRunExit call and unknown-state error handling, and only use ensure when the container is confirmed present.@@ -1518,10 +1523,17 @@15181523 }15191524 } finally {15201525 clearTimeout(connectTimer)1521- if (!attached) {1522- // Never reached the run (unknown / evicted / unreachable in time): the1523- // pointer is dead. Clear it so it does not retry and re-pin the UI on1524- // the next load. The server's persisted transcript is still loaded.1526+ if (!attached && refused) {1527+ // The server REFUSED the join (unknown / evicted run): the pointer is1528+ // dead. Clear it so it does not retry and re-pin the UI on the next1529+ // load. The server's persisted transcript is still loaded.1530+ //1531+ // A connect-deadline abort (or an external abort) deliberately does1532+ // NOT clear it: the run may simply not have produced yet — a durable1533+ // run whose middleware is still booting a sandbox emits nothing for1534+ // a while — and clearing on a timeout would permanently orphan a run1535+ // that is still going. The pointer survives for the next load, which1536+ // costs that load one more bounded connect attempt.15251537 this.lastResume = null15261538 this.persistor?.persistResumeSnapshot(null)15271539 }🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Do not treat every pre-attachment error as a server refusal.
A network, CORS, transport, or parser error can occur before
joinRunyields its first chunk. The current code setsrefused = truefor each such error and deletes the persisted pointer. This can orphan an active durable run after a transient client failure.Add an explicit refusal signal to the
joinRuncontract. Clear the pointer only for that signal. Preserve it for generic pre-attachment errors.packages/ai-client/src/chat-client.ts#L1510-L1539: classify only an explicit unknown-or-expired-run response as a refusal.packages/ai-client/tests/resume-snapshot.test.ts#L597-L616: use the explicit refusal signal in this test and add a generic pre-attachment failure case that preserves the pointer.
📍 Affects 2 files
packages/ai-client/src/chat-client.ts#L1510-L1539(this comment)packages/ai-client/tests/resume-snapshot.test.ts#L597-L616
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/ai-client/src/chat-client.ts` around lines 1510 - 1539, Update the joinRun error handling in packages/ai-client/src/chat-client.ts:1510-1539 to distinguish an explicit unknown-or-expired-run refusal from generic pre-attachment network, CORS, transport, or parser failures, and set refused only for that signal so the persisted pointer is cleared exclusively on confirmed refusal. In packages/ai-client/tests/resume-snapshot.test.ts:597-616, update the refusal scenario to use the explicit signal and add coverage proving a generic pre-attachment failure preserves the pointer.✅ Addressed in commits b5989ba to 6039377
tombeckenham approved these changes
AlemTuzlak merged thisd9d1e1f
AlemTuzlak closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
This PR adds durable sandbox runs with journals, replay alignment, takeover fencing, cancellation tracking, reaping, provider process controls, shared run persistence, adapter integration, and end-to-end validation.
Changes#
Durable sandbox runs
packages/ai/src/...,packages/ai-persistence/src/...,packages/ai-sandbox/src/run.tspackages/ai-sandbox/src/journal.ts,packages/ai-sandbox/src/runner.ts,packages/ai-sandbox/src/claim.ts,packages/ai-sandbox/src/reap.tspackages/ai-sandbox-{local-process,docker,cloudflare,daytona,sprites,vercel}/...packages/ai-{claude-code,codex,grok-build,acp,opencode}/...,packages/ai-sandbox-cloudflare/...,testing/e2e/...docs/...,.changeset/...,packages/*/skills/....github/workflows/pr.yml,packages/ai-sandbox/src/testkit/...Estimated code review effort: 5 (Critical) | ~120 minutes
Sequence Diagram(s)#
Possibly related PRs
RunStore.findActiveRuncontract.Suggested labels:
persistenceSuggested reviewers:
jherr,tombeckenham🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share