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

attach.test.ts

623 lines23.4 KB

1/**
2 * Wiring tests for the durable-run attach path (Phase 3).
3 *
4 * These are wiring tests, not unit tests of `journalOptionsFor` /
5 * `alignedIfAttaching` themselves (covered in `@tanstack/ai-sandbox`'s own
6 * `durability.test.ts`). What is asserted here is that the REAL adapter call
7 * site in `../src/adapters/text.ts` actually reaches those helpers:
8 *
9 * - journaling is gated on the resolved sandbox-durability capability, not
10 * merely on a caller-supplied `runId` (Task 5);
11 * - `attach: true` makes `spawnNdjson` tail the EXISTING journal instead of
12 * starting a new agent (Task 7);
13 * - the journal path is derived from the caller-supplied `runId` (Task 5/7);
14 * - a durable run with no caller-supplied `runId` fails loudly instead of
15 * silently minting an unrecoverable one (Task 5).
16 *
17 * Every `runId` and `journalDir` below is minted per test. `journalPaths`'s
18 * default directory is a REAL host path (`/tmp/tanstack-runs`) that outlives
19 * any single sandbox or test run — see `journal.ts`'s own warning — so a
20 * fixed literal here would read a previous run's leftover journal.
21 */
22import { afterAll, describe, expect, it } from 'vitest'
23import * as fsp from 'node:fs/promises'
24import * as os from 'node:os'
25import * as path from 'node:path'
26import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
27import {
28 DurableRunIdRequiredError,
29 SandboxCapability,
30 journalPaths,
31 journaledCommand,
32 provideSandboxDurability,
33} from '@tanstack/ai-sandbox'
34import { EventType, InMemoryRunStore } from '@tanstack/ai'
35import { codexText } from '../src/index'
36import type { InternalLogger } from '@tanstack/ai/adapter-internals'
37import type {
38 CapabilityContext,
39 AdapterYieldChunk,
40 StreamChunk,
41 StreamDurability,
42} from '@tanstack/ai'
43import type { SandboxHandle, SandboxRunDurability } from '@tanstack/ai-sandbox'
44​
45const baseDir = path.join(
46 os.tmpdir(),
47 `tanstack-ai-codex-attach-test-${Date.now()}`,
49const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
50​
51afterAll(async () => {
52 try {
53 await fsp.rm(baseDir, { recursive: true, force: true })
54 } catch {
55 // Windows can report EBUSY here when a child process handle briefly
56 // outlives `sbx.destroy()`; this is a cleanup nicety, not part of what
57 // the test verifies, so a failure here must not fail the suite.
58 }
59})
60​
61const noopLogger = {
62 request: () => {},
63 provider: () => {},
64 errors: () => {},
65 agentLoop: () => {},
66 warnings: () => {},
67 debug: () => {},
68} as unknown as InternalLogger
69​
70// Stand-in for `codex exec --experimental-json`: reads the prompt from stdin
71// and emits canned thread-event JSONL, same shape `text-adapter.test.ts` uses.
72const FAKE_CODEX = [
73 `let input = ''`,
74 `process.stdin.on('data', (d) => { input += d })`,
75 `process.stdin.on('end', () => {`,
76 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
77 ` w({ type: 'thread.started', thread_id: 'th-1' })`,
78 ` w({ type: 'turn.started' })`,
79 ` w({ type: 'item.completed', item: { id: 'i1', type: 'agent_message', text: 'pong' } })`,
80 ` w({ type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } })`,
81 `})`,
82].join('\n')
83​
84/**
85 * Minimal in-memory `StreamDurability`. Only used to make the durability
86 * capability RESOLVABLE (`runs` + `durability.adapter` both present) — the
87 * journal itself (what `attach: true` actually tails) is a separate,
88 * in-sandbox file governed by `SandboxDurabilityOptions.journal`, not this
89 * adapter.
90 *
91 * `seed` pre-populates `snapshot()`, which is what `alignedIfAttaching` reads
92 * to decide what a previous host already delivered (see `align.ts`'s
93 * `alignToStoredLog`). Defaults to empty, i.e. nothing to align against.
94 */
95function fakeStreamDurability(
96 seed: Array<{ offset: string; chunk: StreamChunk }> = [],
97): StreamDurability {
98 return {
99 resumeFrom: () => null,
100 append: (chunks) => Promise.resolve(chunks.map((_, i) => String(i))),
101 read: () => (async function* () {})(),
102 close: () => Promise.resolve(),
103 snapshot: () => Promise.resolve(seed),
104 }
106​
107/**
108 * Records every command the handle spawns/execs, and forces the
109 * bounded-poll journal read strategy. Mirrors
110 * `translate-determinism.test.ts`'s `pollStrategyHandle`: on this host the
111 * follow strategy's `tail -f` pipeline can go undelivered for a payload
112 * under one stdio buffer, which is a property of this host's stdio, not of
113 * anything under test here.
114 */
115function recordingHandle(handle: SandboxHandle): {
116 handle: SandboxHandle
117 spawned: Array<string>
118} {
119 const spawned: Array<string> = []
120 return {
121 spawned,
122 handle: {
123 ...handle,
124 capabilities: { ...handle.capabilities, killableProcesses: false },
125 process: {
126 ...handle.process,
127 spawn: (command, options) => {
128 spawned.push(command)
129 return handle.process.spawn(command, options)
130 },
131 exec: (command, options) => {
132 spawned.push(command)
133 return handle.process.exec(command, options)
134 },
135 },
136 },
137 }
139​
140function capabilityContext(
141 handle: SandboxHandle,
142 durability?: SandboxRunDurability,
143): CapabilityContext {
144 const [, provideSandbox] = SandboxCapability
145 const ctx = {
146 capabilities: { markProvided: () => {}, has: () => true },
147 } as unknown as CapabilityContext
148 provideSandbox(ctx, handle)
149 if (durability !== undefined) provideSandboxDurability(ctx, durability)
150 return ctx
152​
153function durabilityWith(
154 overrides: Partial<SandboxRunDurability> = {},
155): SandboxRunDurability {
156 return {
157 runs: new InMemoryRunStore(),
158 adapter: fakeStreamDurability(),
159 journalDir: `/tmp/tanstack-runs-attach-${crypto.randomUUID()}`,
160 attach: false,
161 detachOnDisconnect: true,
162 ...overrides,
163 }
165​
166async function collect(
167 stream: AsyncIterable<AdapterYieldChunk>,
168): Promise<Array<AdapterYieldChunk>> {
169 const out: Array<AdapterYieldChunk> = []
170 for await (const chunk of stream) out.push(chunk)
171 return out
173​
174/**
175 * The DISTINCT `threadId`s stamped across a run's chunks.
176 *
177 * A set, not a list, because `threadId` appears on several chunk types
178 * (`RUN_STARTED`, `RUN_FINISHED`, …) and what matters is that they all agree on
179 * one id — the caller's on an attach, a generated one otherwise. Anything with
180 * more than one entry means the resolution ran twice.
181 */
182function threadIdsOf(chunks: Array<AdapterYieldChunk>): Array<string> {
183 const seen = new Set<string>()
184 for (const chunk of chunks) {
185 const value = (chunk as { threadId?: unknown }).threadId
186 if (typeof value === 'string') seen.add(value)
187 }
188 return [...seen]
190​
191function textOf(chunks: Array<AdapterYieldChunk>): string {
192 return chunks
193 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
194 .map((c) => (c as { delta?: string }).delta ?? '')
195 .join('')
197​
198describe('codex attach wiring', () => {
199 it('does NOT start an agent when attaching — it only tails the journal', async () => {
200 const sbx = await provider.create({})
201 const recorder = recordingHandle(sbx)
202 const runId = `r-attach-${crypto.randomUUID()}`
203 const durability = durabilityWith({ attach: true })
204 const paths = journalPaths(runId, durability.journalDir)
205​
206 // Pre-populate the journal exactly as a previous host's journaled agent
207 // would have — through the shell (`journaledCommand`), not
208 // `sandbox.fs.write`: `journal.ts` rule 3 warns the journal directory is
209 // a REAL host path outside the virtualized sandbox root, so the two
210 // resolve differently. `journaledCommand` also appends the `__exit`
211 // sentinel, exactly like a completed prior run's journal would carry.
212 const priorEvents = [
213 '{"type":"thread.started","thread_id":"sess-1"}',
214 '{"type":"turn.started"}',
215 '{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"pong"}}',
216 '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}',
217 ].join('\\n')
218 const seed = await sbx.process.spawn(
219 journaledCommand(`printf '${priorEvents}\\n'`, paths),
220 )
221 expect(await seed.wait()).toBe(0)
222​
223 // No `codexExecutable` override, and no fake codex script written at all:
224 // if attach were broken and this spawned a NEW agent anyway, it would try
225 // to run the real (uninstalled) `codex` binary and the run would fail
226 // loudly with a RUN_ERROR (or a rejected read), rather than this test
227 // silently passing regardless.
228 const adapter = codexText('gpt-5.5-codex')
229 const chunks = await collect(
230 adapter.chatStream({
231 model: 'gpt-5.5-codex',
232 messages: [{ role: 'user', content: 'say pong' }],
233 logger: noopLogger,
234 runId,
235 threadId: `t-attach-${crypto.randomUUID()}`,
236 capabilities: capabilityContext(recorder.handle, durability),
237 }),
238 )
239​
240 expect(textOf(chunks)).toContain('pong')
241 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
242 // The command codex's `buildCommand` produces always contains this exact
243 // flag; its absence from every spawned/exec'd command proves the agent
244 // itself was never started.
245 expect(
246 recorder.spawned.some((command) =>
247 command.includes('exec --experimental-json'),
248 ),
249 ).toBe(false)
250 await sbx.destroy()
251 })
252​
253 it("aligns against the durability adapter's stored log when attaching, suppressing the already-delivered prefix", async () => {
254 // Distinct from the previous test: that one proves the in-sandbox JOURNAL
255 // is tailed instead of respawned. This one proves the SEPARATE
256 // cross-host durability log (`SandboxDurabilityOptions.adapter`, what
257 // `alignedIfAttaching` reads via `snapshot()`) is actually consulted —
258 // the two are different logs by design (see `durability.ts`'s module
259 // doc), and it is easy to wire one without the other.
260 const sbx = await provider.create({})
261 const runId = `r-align-${crypto.randomUUID()}`
262 const threadId = `t-align-${crypto.randomUUID()}`
263​
264 // The stored "already delivered" prefix is exactly the RUN_STARTED chunk
265 // `translateThreadEvents` emits first (see `translate.ts`'s `startRun`).
266 // `chunkFingerprint` (what `alignToStoredLog` compares with) drops
267 // `timestamp`, so an arbitrary placeholder there still matches.
268 const storedRunStarted: AdapterYieldChunk = {
269 type: EventType.RUN_STARTED,
270 runId,
271 threadId,
272 model: 'gpt-5.5-codex',
273 timestamp: 0,
274 }
275 const durability = durabilityWith({
276 attach: true,
277 adapter: fakeStreamDurability([
278 { offset: 'o0', chunk: storedRunStarted },
279 ]),
280 })
281 const paths = journalPaths(runId, durability.journalDir)
282 const recorder = recordingHandle(sbx)
283​
284 const priorEvents = [
285 '{"type":"thread.started","thread_id":"sess-1"}',
286 '{"type":"turn.started"}',
287 '{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"pong"}}',
288 '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}',
289 ].join('\\n')
290 const seed = await sbx.process.spawn(
291 journaledCommand(`printf '${priorEvents}\\n'`, paths),
292 )
293 expect(await seed.wait()).toBe(0)
294​
295 const adapter = codexText('gpt-5.5-codex')
296 const chunks = await collect(
297 adapter.chatStream({
298 model: 'gpt-5.5-codex',
299 messages: [{ role: 'user', content: 'say pong' }],
300 logger: noopLogger,
301 runId,
302 threadId,
303 capabilities: capabilityContext(recorder.handle, durability),
304 }),
305 )
306​
307 // The RUN_STARTED chunk was already "delivered" per the stored log, so
308 // alignment must suppress it — if `alignedIfAttaching` were bypassed, the
309 // freshly-translated RUN_STARTED would come through unsuppressed and this
310 // would fail.
311 expect(chunks.some((c) => c.type === 'RUN_STARTED')).toBe(false)
312 // Everything after the aligned prefix must still arrive.
313 expect(textOf(chunks)).toContain('pong')
314 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
315 await sbx.destroy()
316 })
317​
318 it('starts the agent and tails when NOT attaching', async () => {
319 const sbx = await provider.create({})
320 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
321 const recorder = recordingHandle(sbx)
322 const runId = `r-fresh-${crypto.randomUUID()}`
323 const durability = durabilityWith({ attach: false })
324 const paths = journalPaths(runId, durability.journalDir)
325​
326 const adapter = codexText('gpt-5.5-codex', {
327 codexExecutable: 'node fake-codex.mjs',
328 })
329 const chunks = await collect(
330 adapter.chatStream({
331 threadId: 'thread-1',
332 model: 'gpt-5.5-codex',
333 messages: [{ role: 'user', content: 'say pong' }],
334 logger: noopLogger,
335 runId,
336 capabilities: capabilityContext(recorder.handle, durability),
337 }),
338 )
339​
340 expect(textOf(chunks)).toContain('pong')
341 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
342 // The agent's stdout was redirected into the journal (`>>`), not piped
343 // directly — proving `journal` reached `spawnNdjson` for a FRESH run too,
344 // not only on attach.
345 const journaled = recorder.spawned.filter((command) =>
346 command.includes(paths.journal),
347 )
348 expect(journaled.length).toBeGreaterThan(0)
349 expect(journaled.some((command) => command.includes('>>'))).toBe(true)
350 await sbx.destroy()
351 })
352​
353 it('does NOT journal a non-durable run — byte-identical to a pre-durability run', async () => {
354 // The other side of the byte-identical guarantee `journalOptionsFor`
355 // documents: a run with no `SandboxDurabilityCapability` wired (no
356 // `runs`/`durability.adapter` given to `withSandbox`) must take
357 // `spawnNdjson`'s ORIGINAL unjournaled path — piping the agent's stdout
358 // directly rather than redirecting it into a file. A caller-supplied
359 // `runId` alone must not be enough to turn journaling on; only the
360 // resolved durability capability may.
361 const sbx = await provider.create({})
362 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
363 const recorder = recordingHandle(sbx)
364 const runId = `r-nondurable-${crypto.randomUUID()}`
365 const paths = journalPaths(runId)
366​
367 const adapter = codexText('gpt-5.5-codex', {
368 codexExecutable: 'node fake-codex.mjs',
369 })
370 const chunks = await collect(
371 adapter.chatStream({
372 threadId: 'thread-1',
373 model: 'gpt-5.5-codex',
374 messages: [{ role: 'user', content: 'say pong' }],
375 logger: noopLogger,
376 runId,
377 // No durability capability provided at all — only the sandbox.
378 capabilities: capabilityContext(recorder.handle),
379 }),
380 )
381​
382 expect(textOf(chunks)).toContain('pong')
383 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
384 expect(
385 recorder.spawned.some((command) => command.includes(paths.journal)),
386 ).toBe(false)
387 await sbx.destroy()
388 })
389​
390 it('derives the journal path from the caller-supplied runId', async () => {
391 const sbx = await provider.create({})
392 await sbx.fs.write('/workspace/fake-codex.mjs', FAKE_CODEX)
393 const recorder = recordingHandle(sbx)
394 const runId = `r-derive-${crypto.randomUUID()}`
395 const otherRunId = `r-other-${crypto.randomUUID()}`
396 const durability = durabilityWith({ attach: false })
397 const paths = journalPaths(runId, durability.journalDir)
398 const otherPaths = journalPaths(otherRunId, durability.journalDir)
399​
400 const adapter = codexText('gpt-5.5-codex', {
401 codexExecutable: 'node fake-codex.mjs',
402 })
403 await collect(
404 adapter.chatStream({
405 threadId: 'thread-1',
406 model: 'gpt-5.5-codex',
407 messages: [{ role: 'user', content: 'say pong' }],
408 logger: noopLogger,
409 runId,
410 capabilities: capabilityContext(recorder.handle, durability),
411 }),
412 )
413​
414 expect(
415 recorder.spawned.some((command) => command.includes(paths.journal)),
416 ).toBe(true)
417 // Not just "a" journal path — THIS run's, derived from THIS runId, and no
418 // other run's path leaks in.
419 expect(
420 recorder.spawned.some((command) => command.includes(otherPaths.journal)),
421 ).toBe(false)
422 await sbx.destroy()
423 })
424​
425 it('reuses the resolved runId for the stdin-fallback prompt file, not a re-derived one', async () => {
426 // The plan's own known omission for this package: the stdin-fallback
427 // branch (`sandbox.capabilities.writableStdin === false`) used to compute
428 // its prompt-file suffix from a SECOND, independent
429 // `options.runId ?? this.generateId()`, rather than the runId already
430 // resolved via `resolveDurableRunId` above it. When `options.runId` is
431 // absent, `this.generateId()` mints a fresh random id on EVERY call, so
432 // the two would silently diverge — invisible here (the prompt still gets
433 // read from the file it names), but defeating the point of a stable,
434 // caller-supplied `runId` for anything keyed off it. This test does not
435 // supply a `runId` at all, so a reintroduced bug is observable: the
436 // prompt-file suffix would stop matching the id the deterministic
437 // `createRunScopedIdGen(runId)` generator actually used.
438 //
439 // Uses a fully synthetic handle rather than `localProcessSandbox`: that
440 // provider's `fs.write` resolves an absolute path under the VIRTUALIZED
441 // sandbox root (`handle.ts`'s `resolve()`), while a shell redirect like
442 // `< /tmp/...` in a spawned command hits the REAL host `/tmp` — the same
443 // fs-vs-shell split `journal.ts` warns about for the journal path. That
444 // split is orthogonal to what this test checks (which `runId` gets used,
445 // not whether the file round-trips through a real sandbox), so a fake
446 // handle sidesteps it entirely instead of exercising an unrelated,
447 // pre-existing local-process limitation.
448 const spawned: Array<string> = []
449 const events = [
450 { type: 'thread.started', thread_id: 'th-1' },
451 { type: 'turn.started' },
452 {
453 type: 'item.started',
454 item: {
455 id: 'cmd-1',
456 type: 'command_execution',
457 command: 'ls',
458 status: 'in_progress',
459 },
460 },
461 {
462 type: 'item.completed',
463 item: {
464 id: 'cmd-1',
465 type: 'command_execution',
466 command: 'ls',
467 aggregated_output: 'file.txt\n',
468 exit_code: 0,
469 status: 'completed',
470 },
471 },
472 { type: 'turn.completed', usage: { input_tokens: 1, output_tokens: 1 } },
473 ]
474 const fakeHandle = {
475 id: 'fake',
476 provider: 'fake',
477 capabilities: {
478 fs: true,
479 exec: true,
480 env: false,
481 ports: false,
482 backgroundProcesses: true,
483 writableStdin: false,
484 killableProcesses: true,
485 snapshots: false,
486 networkPolicy: false,
487 durableFilesystem: false,
488 fork: false,
489 },
490 fs: {
491 read: () => Promise.resolve(''),
492 readBytes: () => Promise.resolve(new Uint8Array()),
493 write: () => Promise.resolve(),
494 list: () => Promise.resolve([]),
495 mkdir: () => Promise.resolve(),
496 remove: () => Promise.resolve(),
497 rename: () => Promise.resolve(),
498 exists: () => Promise.resolve(false),
499 },
500 git: {},
501 process: {
502 exec: () => Promise.reject(new Error('exec unused by this path')),
503 spawn: (command: string) => {
504 spawned.push(command)
505 return Promise.resolve({
506 pid: 1,
507 stdout: (async function* () {
508 for (const event of events) yield `${JSON.stringify(event)}\n`
509 })(),
510 stderr: (async function* () {})(),
511 stdin: {
512 write: () => Promise.resolve(),
513 end: () => Promise.resolve(),
514 },
515 wait: () => Promise.resolve(0),
516 kill: () => Promise.resolve(),
517 })
518 },
519 },
520 ports: {},
521 env: {},
522 destroy: () => Promise.resolve(),
523 } as unknown as SandboxHandle
524​
525 const adapter = codexText('gpt-5.5-codex')
526 const chunks = await collect(
527 adapter.chatStream({
528 threadId: 'thread-1',
529 model: 'gpt-5.5-codex',
530 messages: [{ role: 'user', content: 'say pong' }],
531 logger: noopLogger,
532 // No runId: exercises the generated-fallback path this test targets.
533 capabilities: capabilityContext(fakeHandle),
534 }),
535 )
536​
537 const toolResult = chunks.find((c) => c.type === 'TOOL_CALL_RESULT') as
538 | { messageId?: unknown }
539 | undefined
540 const messageId = toolResult?.messageId
541 expect(typeof messageId).toBe('string')
542 if (typeof messageId !== 'string') {
543 throw new Error('unreachable: asserted above')
544 }
545 // `createRunScopedIdGen(runId)` mints `${runId}-${counter}`; strip the
546 // counter to recover the runId the adapter actually resolved.
547 const resolvedRunId = messageId.replace(/-\d+$/, '')
548​
549 const promptCommand = spawned.find((command) =>
550 command.includes('tanstack-codex-prompt-'),
551 )
552 expect(promptCommand).toBeDefined()
553 expect(promptCommand).toContain(
554 `/tmp/tanstack-codex-prompt-${resolvedRunId}`,
555 )
556 })
557​
558 it('throws DurableRunIdRequiredError when durability is wired without a runId', async () => {
559 const durability = durabilityWith()
560 const ctx = {
561 capabilities: { markProvided: () => {}, has: () => true },
562 } as unknown as CapabilityContext
563 provideSandboxDurability(ctx, durability)
564​
565 // No SandboxCapability needed: `resolveDurableRunId` throws before the
566 // adapter ever reaches `sandboxFrom(options)`, which is exactly the
567 // point — a durable run with no caller-supplied `runId` must fail before
568 // it spends a single token or touches a sandbox at all.
569 const adapter = codexText('gpt-5.5-codex')
570 await expect(
571 collect(
572 adapter.chatStream({
573 threadId: 'thread-1',
574 model: 'gpt-5.5-codex',
575 messages: [{ role: 'user', content: 'hi' }],
576 logger: noopLogger,
577 capabilities: ctx,
578 }),
579 ),
580 ).rejects.toThrow(DurableRunIdRequiredError)
581 })
582​
583 it('carries a caller-supplied threadId into the chunks when ATTACHING', async () => {
584 const sbx = await provider.create({})
585 const recorder = recordingHandle(sbx)
586 const runId = `r-thread-ok-${crypto.randomUUID()}`
587 const threadId = `t-reused-${crypto.randomUUID()}`
588 // Empty stored log, unlike the alignment test above: nothing is suppressed,
589 // so the RUN_STARTED chunk that carries `threadId` is observable.
590 const durability = durabilityWith({ attach: true })
591 const paths = journalPaths(runId, durability.journalDir)
592​
593 const priorEvents = [
594 '{"type":"thread.started","thread_id":"sess-1"}',
595 '{"type":"turn.started"}',
596 '{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"pong"}}',
597 '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}',
598 ].join('\\n')
599 const seed = await sbx.process.spawn(
600 journaledCommand(`printf '${priorEvents}\\n'`, paths),
601 )
602 expect(await seed.wait()).toBe(0)
603​
604 const adapter = codexText('gpt-5.5-codex')
605 const chunks = await collect(
606 adapter.chatStream({
607 model: 'gpt-5.5-codex',
608 messages: [{ role: 'user', content: 'say pong' }],
609 logger: noopLogger,
610 runId,
611 threadId,
612 capabilities: capabilityContext(recorder.handle, durability),
613 }),
614 )
615​
616 expect(textOf(chunks)).toContain('pong')
617 // Not merely "it did not throw": the id the caller passed must be the id
618 // stamped on the stream, which is the only thing that makes the replay
619 // alignable against the stored log.
620 expect(threadIdsOf(chunks)).toEqual([threadId])
621 await sbx.destroy()
622 })
623})