Open History to see the last commit
1/**
2 * Wiring test for the durable-run seam in `../src/adapters/text.ts`: the
3 * `runId` resolution, the journal option, and the attach-time alignment all
4 * come from `getSandboxDurability` (the capability `withSandbox(sandbox,
5 * { runs, durability })` provides) rather than being hardcoded.
6 *
7 * Every `runId` here is unique per test (`crypto.randomUUID()`), and every
8 * assertion is against the actual spawned/exec'd COMMAND string — not the
9 * journal file's existence — because the journal is deleted once a run
10 * reaches its `{"__exit":N}` sentinel (see `translate-determinism.test.ts`'s
11 * wiring block for the same rationale).
12 */
13import { afterAll, describe, expect, it } from 'vitest'
14import * as fsp from 'node:fs/promises'
15import * as os from 'node:os'
16import * as path from 'node:path'
17import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
18import {
19 chunkFingerprint,
20 createRunScopedIdGen,
21 exitSentinelLine,
22 journalPaths,
23} from '@tanstack/ai-sandbox'
24import { claudeCodeText } from '../src/index'
25import { translateSdkStream } from '../src/stream/translate'
26import {
27 capabilityContextWith,
28 fakeDurability,
29 noopLogger,
30 pollStrategyHandle,
31} from './fakes'
32import type { AdapterYieldChunk } from '@tanstack/ai'
33import type { AgentSdkMessage } from '../src/stream/sdk-types'
34
35const baseDir = path.join(
36 os.tmpdir(),
37 `tanstack-ai-cc-attach-test-${Date.now()}`,
38)
39const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
40
41afterAll(async () => {
42 try {
43 await fsp.rm(baseDir, { recursive: true, force: true })
44 } catch {
45 // Windows can report EBUSY here when a child process handle briefly
46 // outlives `sbx.destroy()`; a cleanup nicety, not part of what the test
47 // verifies.
48 }
49})
50
51// Same stand-in as `text-adapter.test.ts`: ignores its flags, reads the
52// prompt from stdin, then emits stream-json (system/init → assistant text →
53// result). The runner filename is asserted to be ABSENT from the spawned
54// commands on the attach path, proving the agent was never started.
55const FAKE_CLAUDE = [
56 `let input = ''`,
57 `process.stdin.on('data', (d) => { input += d })`,
58 `process.stdin.on('end', () => {`,
59 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
60 ` w({ type: 'system', subtype: 'init', session_id: 'sess-abc', model: 'haiku', tools: [] })`,
61 ` w({ type: 'assistant', message: { id: 'msg-1', content: [{ type: 'text', text: 'pong' }] }, parent_tool_use_id: null })`,
62 ` w({ type: 'result', subtype: 'success', result: 'pong', usage: { input_tokens: 1, output_tokens: 1 } })`,
63 `})`,
64].join('\n')
65
66function newRunId(label: string): string {
67 return `r-${label}-${crypto.randomUUID()}`
68}
69
70async function collect(
71 stream: AsyncIterable<AdapterYieldChunk>,
72): Promise<Array<AdapterYieldChunk>> {
73 const out: Array<AdapterYieldChunk> = []
74 for await (const chunk of stream) out.push(chunk)
75 return out
76}
77
78/**
79 * The DISTINCT `threadId`s stamped across a run's chunks.
80 *
81 * A set, not a list, because `threadId` appears on several chunk types
82 * (`RUN_STARTED`, `RUN_FINISHED`, …) and what matters is that they all agree on
83 * one id — the caller's on an attach, a generated one otherwise. Anything with
84 * more than one entry means the resolution ran twice.
85 */
86function threadIdsOf(chunks: Array<AdapterYieldChunk>): Array<string> {
87 const seen = new Set<string>()
88 for (const chunk of chunks) {
89 const value = (chunk as { threadId?: unknown }).threadId
90 if (typeof value === 'string') seen.add(value)
91 }
92 return [...seen]
93}
94
95/**
96 * Pre-populate a run's journal directly through the shell (never `fs.write` —
97 * see `journal.ts` rule 3: on local-process, `fs.write` resolves `/tmp` under
98 * the sandbox root while a shell redirect hits the real host `/tmp`, and only
99 * the latter is where the reader looks). Base64-encoded so the NDJSON content
100 * (which contains double quotes) never has to survive shell quoting.
101 */
102async function seedJournal(
103 sbx: Awaited<ReturnType<typeof provider.create>>,
104 runId: string,
105 lines: Array<AgentSdkMessage | { __exit: number }>,
106): Promise<void> {
107 const paths = journalPaths(runId)
108 // The exit sentinel is built by `exitSentinelLine`, never hand-JSON-stringified:
109 // it carries a per-run nonce so an agent's own stdout cannot forge it
110 // (`ai-sandbox`'s `journal.ts`), and a bare `{"__exit":0}` is therefore agent
111 // output that the reader deliberately does NOT stop at.
112 const content = `${lines
113 .map((l) =>
114 '__exit' in l ? exitSentinelLine(paths, l.__exit) : JSON.stringify(l),
115 )
116 .join('\n')}\n`
117 const b64 = Buffer.from(content, 'utf8').toString('base64')
118 const result = await sbx.process.exec(
119 `mkdir -p ${paths.dir} && printf '%s' ${b64} | base64 -d >> ${paths.journal}`,
120 )
121 if (result.exitCode !== 0) {
122 throw new Error(`seedJournal failed: ${result.stdout} ${result.stderr}`)
123 }
124}
125
126describe('claude-code durable-run wiring (attach path)', () => {
127 it('does NOT journal when no durability is wired — byte-identical to a pre-durability run', async () => {
128 // No `SandboxDurabilityCapability` provided at all (the default: an app
129 // that hasn't wired `runs`/`durability` into `withSandbox`). Before Phase
130 // 3 this adapter journaled every run unconditionally; this pins the new
131 // guarantee that a non-durable run's observable behavior — including
132 // "does spawnNdjson ever touch a journal file" — is unchanged.
133 const sbx = await provider.create({})
134 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
135 const recorder = pollStrategyHandle(sbx)
136 const runId = newRunId('no-durability')
137
138 const adapter = claudeCodeText('haiku', {
139 claudeExecutable: 'node fake-claude.mjs',
140 streamPartials: false,
141 emitDiff: false,
142 })
143
144 const chunks = await collect(
145 adapter.chatStream({
146 threadId: 'thread-1',
147 model: 'haiku',
148 messages: [{ role: 'user', content: 'say pong' }],
149 logger: noopLogger,
150 runId,
151 capabilities: capabilityContextWith(recorder.handle),
152 }),
153 )
154
155 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
156 // The agent still ran directly (unjournaled): the argv runner shows up,
157 // but no command anywhere references a journal path for this runId.
158 expect(
159 recorder.spawned.some((command) =>
160 command.includes('tanstack-claude-run-'),
161 ),
162 ).toBe(true)
163 const paths = journalPaths(runId)
164 expect(
165 recorder.spawned.some((command) => command.includes(paths.journal)),
166 ).toBe(false)
167
168 await sbx.destroy()
169 })
170
171 it('starts the agent and journals under the caller-supplied runId when NOT attaching', async () => {
172 const sbx = await provider.create({})
173 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
174 const recorder = pollStrategyHandle(sbx)
175 const runId = newRunId('not-attaching')
176
177 const adapter = claudeCodeText('haiku', {
178 claudeExecutable: 'node fake-claude.mjs',
179 streamPartials: false,
180 emitDiff: false,
181 })
182
183 const chunks = await collect(
184 adapter.chatStream({
185 threadId: 'thread-1',
186 model: 'haiku',
187 messages: [{ role: 'user', content: 'say pong' }],
188 logger: noopLogger,
189 runId,
190 capabilities: capabilityContextWith(
191 recorder.handle,
192 fakeDurability(runId, { attach: false }),
193 ),
194 }),
195 )
196
197 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
198
199 // The agent was actually started (`startJournaledAgent` spawns the runner).
200 expect(
201 recorder.spawned.some((command) =>
202 command.includes('tanstack-claude-run-'),
203 ),
204 ).toBe(true)
205
206 // ...and its output was journaled under a path derived from THIS runId.
207 const paths = journalPaths(runId)
208 const journaled = recorder.spawned.filter((command) =>
209 command.includes(paths.journal),
210 )
211 expect(journaled.length).toBeGreaterThan(0)
212 expect(journaled.some((command) => command.includes('>>'))).toBe(true)
213
214 await sbx.destroy()
215 })
216
217 it('does NOT start an agent when attaching — it only tails the existing journal', async () => {
218 const sbx = await provider.create({})
219 // No fake-claude.mjs written at all: if the adapter tried to start it,
220 // the run would fail with a "file not found"-shaped RUN_ERROR instead of
221 // producing the expected chunks below.
222 const runId = newRunId('attaching')
223 await seedJournal(sbx, runId, [
224 {
225 type: 'system',
226 subtype: 'init',
227 session_id: 'sess-attach',
228 model: 'haiku',
229 tools: [],
230 },
231 {
232 type: 'assistant',
233 message: { id: 'msg-1', content: [{ type: 'text', text: 'resumed' }] },
234 parent_tool_use_id: null,
235 },
236 {
237 type: 'result',
238 subtype: 'success',
239 result: 'resumed',
240 usage: { input_tokens: 1, output_tokens: 1 },
241 },
242 { __exit: 0 },
243 ])
244 const recorder = pollStrategyHandle(sbx)
245
246 const adapter = claudeCodeText('haiku', {
247 claudeExecutable: 'node fake-claude.mjs',
248 streamPartials: false,
249 emitDiff: false,
250 })
251
252 const chunks = await collect(
253 adapter.chatStream({
254 model: 'haiku',
255 messages: [{ role: 'user', content: 'say pong' }],
256 logger: noopLogger,
257 runId,
258 threadId: `t-attaching-${crypto.randomUUID()}`,
259 capabilities: capabilityContextWith(
260 recorder.handle,
261 fakeDurability(runId, { attach: true }),
262 ),
263 }),
264 )
265
266 // Translated from the pre-existing journal, proving the read (not a live
267 // spawn) is what produced this content.
268 const text = chunks
269 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
270 .map((c) => (c as { delta?: string }).delta ?? '')
271 .join('')
272 expect(text).toContain('resumed')
273 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
274
275 // No command ever referenced the argv runner: the agent was never
276 // started on the attach path.
277 expect(
278 recorder.spawned.some((command) =>
279 command.includes('tanstack-claude-run-'),
280 ),
281 ).toBe(false)
282
283 // A read command against this run's journal DID happen.
284 const paths = journalPaths(runId)
285 expect(
286 recorder.spawned.some((command) => command.includes(paths.journal)),
287 ).toBe(true)
288
289 await sbx.destroy()
290 })
291
292 it('suppresses already-delivered chunks on attach via alignedIfAttaching', async () => {
293 // Proves `alignedIfAttaching` is actually IN the pipe, not merely that a
294 // fresh translation of the journal happens to look right. A durability
295 // adapter whose stored log already holds a PREFIX of what this run's
296 // journal translates to must have that prefix suppressed from the
297 // delivered stream — that suppression is `alignedIfAttaching`'s entire
298 // job (`align.ts`), and nothing else in this call site removes chunks.
299 const sbx = await provider.create({})
300 const runId = newRunId('align-proof')
301 const threadId = `t-${runId}`
302 const seedMessages: Array<AgentSdkMessage> = [
303 {
304 type: 'system',
305 subtype: 'init',
306 session_id: 'sess-align',
307 model: 'haiku',
308 tools: [],
309 },
310 {
311 type: 'assistant',
312 message: { id: 'msg-1', content: [{ type: 'text', text: 'resumed' }] },
313 parent_tool_use_id: null,
314 },
315 {
316 type: 'result',
317 subtype: 'success',
318 result: 'resumed',
319 usage: { input_tokens: 1, output_tokens: 1 },
320 },
321 ]
322 await seedJournal(sbx, runId, [...seedMessages, { __exit: 0 }])
323
324 // Independently reproduce what `chatStream`'s own translation will emit:
325 // same messages, same `model`/`runId`/`threadId`, same
326 // `createRunScopedIdGen(runId)` — deterministic, per
327 // `translate-determinism.test.ts`.
328 async function* asMessages(): AsyncIterable<AgentSdkMessage> {
329 for (const m of seedMessages) yield m
330 }
331 const fullTranslation: Array<AdapterYieldChunk> = []
332 for await (const chunk of translateSdkStream(asMessages(), {
333 model: 'haiku',
334 runId,
335 threadId,
336 genId: createRunScopedIdGen(runId),
337 })) {
338 fullTranslation.push(chunk)
339 }
340 expect(fullTranslation.length).toBeGreaterThan(1)
341
342 // Mark everything but the LAST chunk as "already delivered" by a
343 // predecessor host: append it straight to the adapter this run's
344 // durability will read back via `snapshot()`.
345 const alreadyDelivered = fullTranslation.slice(0, -1)
346 const notYetDelivered = fullTranslation.slice(-1)
347 const durability = fakeDurability(runId, { attach: true })
348 await durability.adapter.append(alreadyDelivered)
349
350 const recorder = pollStrategyHandle(sbx)
351 const adapter = claudeCodeText('haiku', {
352 claudeExecutable: 'node fake-claude.mjs',
353 streamPartials: false,
354 emitDiff: false,
355 })
356
357 const chunks = await collect(
358 adapter.chatStream({
359 model: 'haiku',
360 messages: [{ role: 'user', content: 'say pong' }],
361 logger: noopLogger,
362 runId,
363 threadId,
364 capabilities: capabilityContextWith(recorder.handle, durability),
365 }),
366 )
367
368 // Every chunk in `alreadyDelivered` is suppressed; only the tail this
369 // durability adapter had NOT yet seen comes through. Compared via
370 // `chunkFingerprint` (key-order independent, excludes the wall-clock
371 // `timestamp`) since the two translations run at different instants.
372 expect(chunks.map(chunkFingerprint)).toEqual(
373 notYetDelivered.map(chunkFingerprint),
374 )
375
376 await sbx.destroy()
377 })
378
379 it('throws DurableRunIdRequiredError (surfaced as a RUN_ERROR) when durability is wired without a runId', async () => {
380 const sbx = await provider.create({})
381 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
382 // `fakeDurability` needs SOME runId to build its `memoryStream` adapter
383 // key, but that id is never passed to `chatStream` — the point of this
384 // test is the ABSENCE of `options.runId`.
385 const durability = fakeDurability(newRunId('unused-adapter-key'))
386
387 const adapter = claudeCodeText('haiku', {
388 claudeExecutable: 'node fake-claude.mjs',
389 streamPartials: false,
390 emitDiff: false,
391 })
392
393 const chunks = await collect(
394 adapter.chatStream({
395 threadId: 'thread-1',
396 model: 'haiku',
397 messages: [{ role: 'user', content: 'say pong' }],
398 logger: noopLogger,
399 // runId intentionally omitted
400 capabilities: capabilityContextWith(sbx, durability),
401 }),
402 )
403
404 const runError = chunks.find((c) => c.type === 'RUN_ERROR')
405 expect(runError).toBeDefined()
406 expect((runError as { message?: string }).message).toMatch(
407 /caller-supplied `runId`/,
408 )
409
410 await sbx.destroy()
411 })
412
413 it('carries a caller-supplied threadId into the chunks when ATTACHING', async () => {
414 const sbx = await provider.create({})
415 const runId = newRunId('attach-with-thread')
416 const threadId = `t-reused-${crypto.randomUUID()}`
417 await seedJournal(sbx, runId, [
418 {
419 type: 'system',
420 subtype: 'init',
421 session_id: 'sess-attach',
422 model: 'haiku',
423 tools: [],
424 },
425 {
426 type: 'assistant',
427 message: { id: 'msg-1', content: [{ type: 'text', text: 'resumed' }] },
428 parent_tool_use_id: null,
429 },
430 {
431 type: 'result',
432 subtype: 'success',
433 result: 'resumed',
434 usage: { input_tokens: 1, output_tokens: 1 },
435 },
436 { __exit: 0 },
437 ])
438 const recorder = pollStrategyHandle(sbx)
439
440 const adapter = claudeCodeText('haiku', {
441 claudeExecutable: 'node fake-claude.mjs',
442 streamPartials: false,
443 emitDiff: false,
444 })
445 const chunks = await collect(
446 adapter.chatStream({
447 model: 'haiku',
448 messages: [{ role: 'user', content: 'say pong' }],
449 logger: noopLogger,
450 runId,
451 threadId,
452 // Empty stored log, so nothing is suppressed and the chunks that carry
453 // `threadId` are observable.
454 capabilities: capabilityContextWith(
455 recorder.handle,
456 fakeDurability(runId, { attach: true }),
457 ),
458 }),
459 )
460
461 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
462 // Not merely "it did not throw": the id the caller passed must be the id
463 // stamped on the stream, which is the only thing that makes the replay
464 // alignable against the stored log.
465 expect(threadIdsOf(chunks)).toEqual([threadId])
466
467 await sbx.destroy()
468 })
469})