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

attach.test.ts

576 lines20.4 KB

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()}`,
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()}`
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
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]
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 }
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 model: 'haiku',
147 messages: [{ role: 'user', content: 'say pong' }],
148 logger: noopLogger,
149 runId,
150 capabilities: capabilityContextWith(recorder.handle),
151 }),
152 )
153​
154 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
155 // The agent still ran directly (unjournaled): the argv runner shows up,
156 // but no command anywhere references a journal path for this runId.
157 expect(
158 recorder.spawned.some((command) =>
159 command.includes('tanstack-claude-run-'),
160 ),
161 ).toBe(true)
162 const paths = journalPaths(runId)
163 expect(
164 recorder.spawned.some((command) => command.includes(paths.journal)),
165 ).toBe(false)
166​
167 await sbx.destroy()
168 })
169​
170 it('starts the agent and journals under the caller-supplied runId when NOT attaching', async () => {
171 const sbx = await provider.create({})
172 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
173 const recorder = pollStrategyHandle(sbx)
174 const runId = newRunId('not-attaching')
175​
176 const adapter = claudeCodeText('haiku', {
177 claudeExecutable: 'node fake-claude.mjs',
178 streamPartials: false,
179 emitDiff: false,
180 })
181​
182 const chunks = await collect(
183 adapter.chatStream({
184 model: 'haiku',
185 messages: [{ role: 'user', content: 'say pong' }],
186 logger: noopLogger,
187 runId,
188 capabilities: capabilityContextWith(
189 recorder.handle,
190 fakeDurability(runId, { attach: false }),
191 ),
192 }),
193 )
194​
195 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
196​
197 // The agent was actually started (`startJournaledAgent` spawns the runner).
198 expect(
199 recorder.spawned.some((command) =>
200 command.includes('tanstack-claude-run-'),
201 ),
202 ).toBe(true)
203​
204 // ...and its output was journaled under a path derived from THIS runId.
205 const paths = journalPaths(runId)
206 const journaled = recorder.spawned.filter((command) =>
207 command.includes(paths.journal),
208 )
209 expect(journaled.length).toBeGreaterThan(0)
210 expect(journaled.some((command) => command.includes('>>'))).toBe(true)
211​
212 await sbx.destroy()
213 })
214​
215 it('does NOT start an agent when attaching — it only tails the existing journal', async () => {
216 const sbx = await provider.create({})
217 // No fake-claude.mjs written at all: if the adapter tried to start it,
218 // the run would fail with a "file not found"-shaped RUN_ERROR instead of
219 // producing the expected chunks below.
220 const runId = newRunId('attaching')
221 await seedJournal(sbx, runId, [
222 {
223 type: 'system',
224 subtype: 'init',
225 session_id: 'sess-attach',
226 model: 'haiku',
227 tools: [],
228 },
229 {
230 type: 'assistant',
231 message: { id: 'msg-1', content: [{ type: 'text', text: 'resumed' }] },
232 parent_tool_use_id: null,
233 },
234 {
235 type: 'result',
236 subtype: 'success',
237 result: 'resumed',
238 usage: { input_tokens: 1, output_tokens: 1 },
239 },
240 { __exit: 0 },
241 ])
242 const recorder = pollStrategyHandle(sbx)
243​
244 const adapter = claudeCodeText('haiku', {
245 claudeExecutable: 'node fake-claude.mjs',
246 streamPartials: false,
247 emitDiff: false,
248 })
249​
250 const chunks = await collect(
251 adapter.chatStream({
252 model: 'haiku',
253 messages: [{ role: 'user', content: 'say pong' }],
254 logger: noopLogger,
255 runId,
256 // A real attach always has the run record's `threadId` — core's
257 // `startRunDriver` hands it to `drive({ runId, threadId, signal })` —
258 // and `resolveDurableThreadId` now REQUIRES it, because an attach that
259 // mints a fresh one stamps every chunk with an id the stored log cannot
260 // match. Omitting it here (as this test originally did) exercised a
261 // configuration that could never align; supplying it keeps the subject
262 // of this test — that no agent is spawned on attach — unchanged.
263 threadId: `t-attaching-${crypto.randomUUID()}`,
264 capabilities: capabilityContextWith(
265 recorder.handle,
266 fakeDurability(runId, { attach: true }),
267 ),
268 }),
269 )
270​
271 // Translated from the pre-existing journal, proving the read (not a live
272 // spawn) is what produced this content.
273 const text = chunks
274 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
275 .map((c) => (c as { delta?: string }).delta ?? '')
276 .join('')
277 expect(text).toContain('resumed')
278 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
279​
280 // No command ever referenced the argv runner: the agent was never
281 // started on the attach path.
282 expect(
283 recorder.spawned.some((command) =>
284 command.includes('tanstack-claude-run-'),
285 ),
286 ).toBe(false)
287​
288 // A read command against this run's journal DID happen.
289 const paths = journalPaths(runId)
290 expect(
291 recorder.spawned.some((command) => command.includes(paths.journal)),
292 ).toBe(true)
293​
294 await sbx.destroy()
295 })
296​
297 it('suppresses already-delivered chunks on attach via alignedIfAttaching', async () => {
298 // Proves `alignedIfAttaching` is actually IN the pipe, not merely that a
299 // fresh translation of the journal happens to look right. A durability
300 // adapter whose stored log already holds a PREFIX of what this run's
301 // journal translates to must have that prefix suppressed from the
302 // delivered stream — that suppression is `alignedIfAttaching`'s entire
303 // job (`align.ts`), and nothing else in this call site removes chunks.
304 const sbx = await provider.create({})
305 const runId = newRunId('align-proof')
306 const threadId = `t-${runId}`
307 const seedMessages: Array<AgentSdkMessage> = [
308 {
309 type: 'system',
310 subtype: 'init',
311 session_id: 'sess-align',
312 model: 'haiku',
313 tools: [],
314 },
315 {
316 type: 'assistant',
317 message: { id: 'msg-1', content: [{ type: 'text', text: 'resumed' }] },
318 parent_tool_use_id: null,
319 },
320 {
321 type: 'result',
322 subtype: 'success',
323 result: 'resumed',
324 usage: { input_tokens: 1, output_tokens: 1 },
325 },
326 ]
327 await seedJournal(sbx, runId, [...seedMessages, { __exit: 0 }])
328​
329 // Independently reproduce what `chatStream`'s own translation will emit:
330 // same messages, same `model`/`runId`/`threadId`, same
331 // `createRunScopedIdGen(runId)` — deterministic, per
332 // `translate-determinism.test.ts`.
333 async function* asMessages(): AsyncIterable<AgentSdkMessage> {
334 for (const m of seedMessages) yield m
335 }
336 const fullTranslation: Array<AdapterYieldChunk> = []
337 for await (const chunk of translateSdkStream(asMessages(), {
338 model: 'haiku',
339 runId,
340 threadId,
341 genId: createRunScopedIdGen(runId),
342 })) {
343 fullTranslation.push(chunk)
344 }
345 expect(fullTranslation.length).toBeGreaterThan(1)
346​
347 // Mark everything but the LAST chunk as "already delivered" by a
348 // predecessor host: append it straight to the adapter this run's
349 // durability will read back via `snapshot()`.
350 const alreadyDelivered = fullTranslation.slice(0, -1)
351 const notYetDelivered = fullTranslation.slice(-1)
352 const durability = fakeDurability(runId, { attach: true })
353 await durability.adapter.append(alreadyDelivered)
354​
355 const recorder = pollStrategyHandle(sbx)
356 const adapter = claudeCodeText('haiku', {
357 claudeExecutable: 'node fake-claude.mjs',
358 streamPartials: false,
359 emitDiff: false,
360 })
361​
362 const chunks = await collect(
363 adapter.chatStream({
364 model: 'haiku',
365 messages: [{ role: 'user', content: 'say pong' }],
366 logger: noopLogger,
367 runId,
368 threadId,
369 capabilities: capabilityContextWith(recorder.handle, durability),
370 }),
371 )
372​
373 // Every chunk in `alreadyDelivered` is suppressed; only the tail this
374 // durability adapter had NOT yet seen comes through. Compared via
375 // `chunkFingerprint` (key-order independent, excludes the wall-clock
376 // `timestamp`) since the two translations run at different instants.
377 expect(chunks.map(chunkFingerprint)).toEqual(
378 notYetDelivered.map(chunkFingerprint),
379 )
380​
381 await sbx.destroy()
382 })
383​
384 it('throws DurableRunIdRequiredError (surfaced as a RUN_ERROR) when durability is wired without a runId', async () => {
385 const sbx = await provider.create({})
386 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
387 // `fakeDurability` needs SOME runId to build its `memoryStream` adapter
388 // key, but that id is never passed to `chatStream` — the point of this
389 // test is the ABSENCE of `options.runId`.
390 const durability = fakeDurability(newRunId('unused-adapter-key'))
391​
392 const adapter = claudeCodeText('haiku', {
393 claudeExecutable: 'node fake-claude.mjs',
394 streamPartials: false,
395 emitDiff: false,
396 })
397​
398 const chunks = await collect(
399 adapter.chatStream({
400 model: 'haiku',
401 messages: [{ role: 'user', content: 'say pong' }],
402 logger: noopLogger,
403 // runId intentionally omitted
404 capabilities: capabilityContextWith(sbx, durability),
405 }),
406 )
407​
408 const runError = chunks.find((c) => c.type === 'RUN_ERROR')
409 expect(runError).toBeDefined()
410 expect((runError as { message?: string }).message).toMatch(
411 /caller-supplied `runId`/,
412 )
413​
414 await sbx.destroy()
415 })
416​
417 it('throws DurableThreadIdRequiredError (surfaced as a RUN_ERROR) when ATTACHING without a threadId', async () => {
418 // The silent-divergence hole this closes: `threadId` lands in every emitted
419 // chunk, so an attach that mints a fresh one replays a stream the stored log
420 // cannot match at index 0. Before this guard the run started, read the
421 // journal, and only then failed alignment mid-stream.
422 const sbx = await provider.create({})
423 const runId = newRunId('attach-no-thread')
424 // No journal seeded and no fake agent written: the refusal must precede
425 // both, so neither is needed for this to fail deterministically.
426 const adapter = claudeCodeText('haiku', {
427 claudeExecutable: 'node fake-claude.mjs',
428 streamPartials: false,
429 emitDiff: false,
430 })
431​
432 const chunks = await collect(
433 adapter.chatStream({
434 model: 'haiku',
435 messages: [{ role: 'user', content: 'say pong' }],
436 logger: noopLogger,
437 runId,
438 // threadId intentionally omitted — the whole point of this test.
439 capabilities: capabilityContextWith(
440 sbx,
441 fakeDurability(runId, { attach: true }),
442 ),
443 }),
444 )
445​
446 const runError = chunks.find((c) => c.type === 'RUN_ERROR')
447 expect(runError).toBeDefined()
448 expect((runError as { message?: string }).message).toMatch(
449 /ATTACHING durable sandboxed run requires the run record's `threadId`/,
450 )
451​
452 await sbx.destroy()
453 })
454​
455 it('carries a caller-supplied threadId into the chunks when ATTACHING', async () => {
456 const sbx = await provider.create({})
457 const runId = newRunId('attach-with-thread')
458 const threadId = `t-reused-${crypto.randomUUID()}`
459 await seedJournal(sbx, runId, [
460 {
461 type: 'system',
462 subtype: 'init',
463 session_id: 'sess-attach',
464 model: 'haiku',
465 tools: [],
466 },
467 {
468 type: 'assistant',
469 message: { id: 'msg-1', content: [{ type: 'text', text: 'resumed' }] },
470 parent_tool_use_id: null,
471 },
472 {
473 type: 'result',
474 subtype: 'success',
475 result: 'resumed',
476 usage: { input_tokens: 1, output_tokens: 1 },
477 },
478 { __exit: 0 },
479 ])
480 const recorder = pollStrategyHandle(sbx)
481​
482 const adapter = claudeCodeText('haiku', {
483 claudeExecutable: 'node fake-claude.mjs',
484 streamPartials: false,
485 emitDiff: false,
486 })
487 const chunks = await collect(
488 adapter.chatStream({
489 model: 'haiku',
490 messages: [{ role: 'user', content: 'say pong' }],
491 logger: noopLogger,
492 runId,
493 threadId,
494 // Empty stored log, so nothing is suppressed and the chunks that carry
495 // `threadId` are observable.
496 capabilities: capabilityContextWith(
497 recorder.handle,
498 fakeDurability(runId, { attach: true }),
499 ),
500 }),
501 )
502​
503 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
504 // Not merely "it did not throw": the id the caller passed must be the id
505 // stamped on the stream, which is the only thing that makes the replay
506 // alignable against the stored log.
507 expect(threadIdsOf(chunks)).toEqual([threadId])
508​
509 await sbx.destroy()
510 })
511​
512 it('lets a durable FRESH run generate its own threadId', async () => {
513 // The regression bar for the guard: a fresh durable run is the run that
514 // ESTABLISHES the threadId, so it must still mint one. A guard keyed on
515 // `durable` alone (rather than durable AND attaching) would break this.
516 const sbx = await provider.create({})
517 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
518 const recorder = pollStrategyHandle(sbx)
519 const runId = newRunId('fresh-thread')
520​
521 const adapter = claudeCodeText('haiku', {
522 claudeExecutable: 'node fake-claude.mjs',
523 streamPartials: false,
524 emitDiff: false,
525 })
526 const chunks = await collect(
527 adapter.chatStream({
528 model: 'haiku',
529 messages: [{ role: 'user', content: 'say pong' }],
530 logger: noopLogger,
531 runId,
532 // threadId intentionally omitted.
533 capabilities: capabilityContextWith(
534 recorder.handle,
535 fakeDurability(runId, { attach: false }),
536 ),
537 }),
538 )
539​
540 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
541 const threadIds = threadIdsOf(chunks)
542 expect(threadIds).toHaveLength(1)
543 expect(threadIds[0]).toMatch(/.+/)
544​
545 await sbx.destroy()
546 })
547​
548 it('lets a NON-durable run generate its own threadId, unchanged', async () => {
549 const sbx = await provider.create({})
550 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
551 const recorder = pollStrategyHandle(sbx)
552​
553 const adapter = claudeCodeText('haiku', {
554 claudeExecutable: 'node fake-claude.mjs',
555 streamPartials: false,
556 emitDiff: false,
557 })
558 const chunks = await collect(
559 adapter.chatStream({
560 model: 'haiku',
561 messages: [{ role: 'user', content: 'say pong' }],
562 logger: noopLogger,
563 // Neither runId nor threadId, and no durability capability: exactly a
564 // pre-durability run.
565 capabilities: capabilityContextWith(recorder.handle),
566 }),
567 )
568​
569 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
570 const threadIds = threadIdsOf(chunks)
571 expect(threadIds).toHaveLength(1)
572 expect(threadIds[0]).toMatch(/.+/)
573​
574 await sbx.destroy()
575 })
576})