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

runner.test.ts

703 lines24.8 KB

1import { readFileSync } from 'node:fs'
2import { describe, expect, it } from 'vitest'
3import { EventType, memoryStream } from '@tanstack/ai'
4import {
5 readJournalNdjson,
6 spawnNdjson,
7 startJournaledAgent,
8 toLines,
9} from '../src/runner'
10import {
11 exitSentinelLine,
12 journalCleanupCommand,
13 journalExistsCommand,
14 journalFollowCommand,
15 journalPaths,
16 journalStderrReadCommand,
17} from '../src/journal'
18import { alignToStoredLog } from '../src/align'
19import type { StreamChunk } from '@tanstack/ai'
20import type {
21 ExecResult,
22 ProcessOptions,
23 SandboxHandle,
24 SpawnHandle,
25} from '../src/contracts'
26​
27/**
28 * The exit sentinel for run `r1` — the only runId these journal fixtures use.
29 *
30 * Built, never hand-written: the sentinel carries a per-run nonce so an agent's
31 * own stdout cannot forge it (`journal.ts`), and a literal `{"__exit":0}` in a
32 * fixture is therefore agent output that the reader must NOT stop at.
33 */
34function EXIT(exitCode: number): string {
35 return exitSentinelLine(journalPaths('r1'), exitCode)
37​
38async function* fromChunks(chunks: Array<string>): AsyncIterable<string> {
39 for (const c of chunks) {
40 // Yield asynchronously to mimic real stream scheduling.
41 await Promise.resolve()
42 yield c
43 }
45​
46async function collect<T>(it: AsyncIterable<T>): Promise<Array<T>> {
47 const out: Array<T> = []
48 for await (const v of it) out.push(v)
49 return out
51​
52/** Minimal handle whose process.spawn replays scripted stdout chunks. */
53function handleSpawning(chunks: Array<string>): SandboxHandle {
54 const spawnHandle: SpawnHandle = {
55 pid: 1,
56 stdout: fromChunks(chunks),
57 stderr: fromChunks([]),
58 stdin: { write: () => Promise.resolve(), end: () => Promise.resolve() },
59 wait: () => Promise.resolve(0),
60 kill: () => Promise.resolve(),
61 }
62 return {
63 id: 'fake',
64 provider: 'fake',
65 capabilities: {
66 fs: true,
67 exec: true,
68 env: true,
69 ports: false,
70 backgroundProcesses: true,
71 writableStdin: true,
72 killableProcesses: true,
73 snapshots: false,
74 networkPolicy: false,
75 durableFilesystem: false,
76 fork: false,
77 },
78 // Only process.spawn is exercised here.
79 fs: {} as SandboxHandle['fs'],
80 git: {} as SandboxHandle['git'],
81 process: {
82 exec: () => Promise.reject(new Error('unused')),
83 spawn: () => Promise.resolve(spawnHandle),
84 },
85 ports: { connect: () => Promise.reject(new Error('unused')) },
86 env: { set: () => Promise.resolve() },
87 destroy: () => Promise.resolve(),
88 }
90​
91describe('toLines', () => {
92 it('reassembles lines split across chunk boundaries', async () => {
93 const lines = await collect(
94 toLines(fromChunks(['{"a":', '1}\n{"b":2', '}\n'])),
95 )
96 expect(lines).toEqual(['{"a":1}', '{"b":2}'])
97 })
98​
99 it('emits a trailing unterminated line', async () => {
100 const lines = await collect(toLines(fromChunks(['one\ntwo'])))
101 expect(lines).toEqual(['one', 'two'])
102 })
103})
104​
105describe('spawnNdjson', () => {
106 it('parses NDJSON events from stdout, skipping blank + non-JSON lines', async () => {
107 const nonJson: Array<string> = []
108 const handle = handleSpawning([
109 'Claude Code starting...\n', // banner -> onNonJsonLine
110 '{"type":"text","delta":"hi"}\n',
111 '\n', // blank -> skipped
112 '{"type":"result","ok":true}\n',
113 ])
114 const events = await collect(
115 spawnNdjson(handle, 'claude -p --output-format stream-json', {
116 onNonJsonLine: (l) => nonJson.push(l),
117 }),
118 )
119 expect(events).toEqual([
120 { type: 'text', delta: 'hi' },
121 { type: 'result', ok: true },
122 ])
123 expect(nonJson).toEqual(['Claude Code starting...'])
124 })
125})
126​
127/**
128 * Handle that records commands and replays scripted stdout per spawn call.
129 *
130 * Journal scripts are RAW journal text, not a base64 frame: `journalFollowCommand`
131 * pipes into nothing, because any filter's stdio buffer would swallow the stream
132 * (see `journal.ts` rule 2).
133 */
134function scriptedHandle(scripts: Array<Array<string>>): {
135 handle: SandboxHandle
136 commands: Array<string>
137} {
138 const commands: Array<string> = []
139 let call = 0
140 const handle: SandboxHandle = {
141 ...handleSpawning([]),
142 process: {
143 exec: (command) => {
144 commands.push(command)
145 return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 })
146 },
147 spawn: (command) => {
148 commands.push(command)
149 const script = scripts[call] ?? []
150 call += 1
151 return Promise.resolve({
152 pid: -1,
153 stdout: fromChunks(script),
154 stderr: fromChunks([]),
155 stdin: {
156 write: () => Promise.resolve(),
157 end: () => Promise.resolve(),
158 },
159 wait: () => Promise.resolve(0),
160 kill: () => Promise.resolve(),
161 })
162 },
163 },
164 }
165 return { handle, commands }
167​
168describe('startJournaledAgent', () => {
169 it('spawns the agent with stdout redirected to the journal and does not read it', async () => {
170 const { handle, commands } = scriptedHandle([[]])
171 await startJournaledAgent(handle, 'claude -p', { journal: { runId: 'r1' } })
172 expect(commands).toHaveLength(1)
173 expect(commands[0]).toContain(`>> '/tmp/tanstack-runs/r1.ndjson'`)
174 expect(commands[0]).toContain(`2>> '/tmp/tanstack-runs/r1.err'`)
175 expect(commands[0]).toContain('claude -p')
176 })
177​
178 // The request's AbortSignal must NOT reach the agent spawn on the journaled
179 // path. Providers act on it at spawn time — local-process registers it to
180 // `killTree` the process group, and daytona and docker honor it too — so
181 // forwarding it means a client disconnect kills the journaled agent. It then
182 // writes no exit sentinel, and a successor host takes over a run that is
183 // already dead: exactly what journaling to a file instead of a pipe exists to
184 // prevent. The signal is still honored for the TAIL read, which
185 // `readJournalNdjson` wires up itself.
186 it('does not forward the request signal to the agent spawn, but keeps the other process options', async () => {
187 const seen: Array<ProcessOptions | undefined> = []
188 const controller = new AbortController()
189 const handle: SandboxHandle = {
190 ...handleSpawning([]),
191 process: {
192 exec: () => Promise.reject(new Error('unused')),
193 spawn: (_command, opts) => {
194 seen.push(opts)
195 return Promise.resolve({
196 pid: -1,
197 stdout: fromChunks([]),
198 stderr: fromChunks([]),
199 stdin: {
200 write: () => Promise.resolve(),
201 end: () => Promise.resolve(),
202 },
203 wait: () => Promise.resolve(0),
204 kill: () => Promise.resolve(),
205 })
206 },
207 },
208 }
209​
210 await startJournaledAgent(handle, 'claude -p', {
211 journal: { runId: 'r1' },
212 signal: controller.signal,
213 cwd: '/workspace',
214 })
215​
216 expect(seen).toHaveLength(1)
217 const opts = seen[0]
218 expect(opts).toBeDefined()
219 // Asserting on the KEY, not on `opts?.signal === undefined`: passing
220 // `signal: undefined` explicitly would satisfy the latter while still letting
221 // a provider that checks `'signal' in opts` register an abort handler.
222 expect(opts !== undefined && 'signal' in opts).toBe(false)
223 // The strip is surgical — everything else a spawn needs still arrives.
224 expect(opts?.cwd).toBe('/workspace')
225 })
226​
227 it('writes stdin input then closes it, exactly as the unjournaled path does', async () => {
228 const written: Array<string> = []
229 let ended = false
230 const base = handleSpawning([])
231 const handle: SandboxHandle = {
232 ...base,
233 process: {
234 exec: () => Promise.reject(new Error('unused')),
235 spawn: () =>
236 Promise.resolve({
237 pid: -1,
238 stdout: fromChunks([]),
239 stderr: fromChunks([]),
240 stdin: {
241 write: (data: string) => {
242 written.push(data)
243 return Promise.resolve()
244 },
245 end: () => {
246 ended = true
247 return Promise.resolve()
248 },
249 },
250 wait: () => Promise.resolve(0),
251 kill: () => Promise.resolve(),
252 }),
253 },
254 }
255 await startJournaledAgent(handle, 'codex exec', {
256 journal: { runId: 'r1' },
257 input: 'the prompt',
258 })
259 expect(written).toEqual(['the prompt'])
260 expect(ended).toBe(true)
261 })
262​
263 it('returns without awaiting the agent process (a hung wait() must not block the trigger)', async () => {
264 let waitCalled = false
265 const base = handleSpawning([])
266 const handle: SandboxHandle = {
267 ...base,
268 process: {
269 exec: () => Promise.reject(new Error('unused')),
270 spawn: () =>
271 Promise.resolve({
272 pid: -1,
273 stdout: fromChunks([]),
274 stderr: fromChunks([]),
275 stdin: {
276 write: () => Promise.resolve(),
277 end: () => Promise.resolve(),
278 },
279 // Never resolves. If startJournaledAgent awaited this, the test
280 // would hang until Vitest's timeout — the whole point of
281 // journaling is that the trigger returns immediately while the
282 // agent keeps running.
283 wait: () =>
284 new Promise<number>(() => {
285 waitCalled = true
286 }),
287 kill: () => Promise.resolve(),
288 }),
289 },
290 }
291 await startJournaledAgent(handle, 'agent', { journal: { runId: 'r1' } })
292 // Reaching here at all proves startJournaledAgent did not await wait().
293 expect(waitCalled).toBe(false)
294 })
295})
296​
297describe('readJournalNdjson', () => {
298 it('parses journal lines as JSON and stops at the exit sentinel', async () => {
299 const { handle } = scriptedHandle([[`{"a":1}\n{"b":2}\n${EXIT(0)}\n`]])
300 expect(
301 await collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
302 ).toEqual([{ a: 1 }, { b: 2 }])
303 })
304​
305 it('throws on a non-zero exit sentinel so the adapter emits RUN_ERROR', async () => {
306 const { handle } = scriptedHandle([[`{"a":1}\n${EXIT(7)}\n`]])
307 await expect(
308 collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
309 ).rejects.toThrow(/exited with code 7/)
310 })
311​
312 it('routes a non-JSON line to onNonJsonLine instead of failing the run', async () => {
313 const seen: Array<string> = []
314 const { handle } = scriptedHandle([
315 [`Claude Code starting...\n{"a":1}\n${EXIT(0)}\n`],
316 ])
317 expect(
318 await collect(
319 readJournalNdjson(handle, {
320 journal: { runId: 'r1' },
321 onNonJsonLine: (line) => seen.push(line),
322 }),
323 ),
324 ).toEqual([{ a: 1 }])
325 expect(seen).toEqual(['Claude Code starting...'])
326 })
327​
328 it('reads from byte 0 on attach, so alignment sees the whole run', async () => {
329 const { handle, commands } = scriptedHandle([[`${EXIT(0)}\n`]])
330 await collect(
331 readJournalNdjson(handle, { journal: { runId: 'r1', attach: true } }),
332 )
333 // `commands[0]` is the attach preflight's `test -f`; the tail follows it.
334 expect(commands.some((command) => command.includes('tail -c +1 -f'))).toBe(
335 true,
336 )
337 })
338})
339​
340/**
341 * Handle that records EVERY sandbox interaction in one ordered timeline, which
342 * is what the journal-cleanup contract is actually about: not that an `rm` is
343 * issued, but that it is issued after the sentinel, after the reader is stopped,
344 * and never on an abort.
345 */
346function timelineHandle(
347 script: Array<string>,
348 execImpl?: (command: string) => Promise<ExecResult>,
349): { handle: SandboxHandle; timeline: Array<string> } {
350 const timeline: Array<string> = []
351 const handle: SandboxHandle = {
352 ...handleSpawning([]),
353 process: {
354 exec: (command) => {
355 timeline.push(`exec:${command}`)
356 return (
357 execImpl?.(command) ??
358 Promise.resolve({ stdout: '', stderr: '', exitCode: 0 })
359 )
360 },
361 spawn: (command) => {
362 timeline.push(`spawn:${command}`)
363 return Promise.resolve({
364 pid: -1,
365 stdout: fromChunks(script),
366 stderr: fromChunks([]),
367 stdin: {
368 write: () => Promise.resolve(),
369 end: () => Promise.resolve(),
370 },
371 wait: () => Promise.resolve(0),
372 kill: () => {
373 timeline.push('kill')
374 return Promise.resolve()
375 },
376 })
377 },
378 },
379 }
380 return { handle, timeline }
382​
383const R1 = journalPaths('r1')
384​
385/** base64-frame text the way `journalStderrReadCommand`'s pipeline would. */
386function stderrFrame(text: string): string {
387 return btoa(text)
389​
390describe('readJournalNdjson journal cleanup', () => {
391 it('deletes both files after a ZERO-exit sentinel, once the read has finished', async () => {
392 const { handle, timeline } = timelineHandle([`{"a":1}\n${EXIT(0)}\n`])
393 const events: Array<unknown> = []
394 for await (const event of readJournalNdjson(handle, {
395 journal: { runId: 'r1' },
396 })) {
397 events.push(event)
398 timeline.push('yield')
399 }
400 expect(events).toEqual([{ a: 1 }])
401 // The exact order is the deliverable: read, deliver, stop the tail, THEN rm.
402 expect(timeline).toEqual([
403 `spawn:${journalFollowCommand(R1, 0)}`,
404 'yield',
405 'kill',
406 `exec:${journalCleanupCommand(R1)}`,
407 ])
408 expect(journalCleanupCommand(R1)).toBe(
409 `rm -f '/tmp/tanstack-runs/r1.ndjson' '/tmp/tanstack-runs/r1.err'`,
410 )
411 })
412​
413 it('deletes after a NON-ZERO sentinel too, because the run is still terminal', async () => {
414 const { handle, timeline } = timelineHandle([`${EXIT(7)}\n`], (command) =>
415 Promise.resolve({
416 stdout: command.startsWith('tail')
417 ? stderrFrame('boom: tool not found\n')
418 : '',
419 stderr: '',
420 exitCode: 0,
421 }),
422 )
423 await expect(
424 collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
425 ).rejects.toThrow(/exited with code 7: boom: tool not found/)
426 // Sidecar read first (the rm destroys it), cleanup second, throw last.
427 expect(timeline.filter((entry) => entry.startsWith('exec:'))).toEqual([
428 `exec:${journalStderrReadCommand(R1)}`,
429 `exec:${journalCleanupCommand(R1)}`,
430 ])
431 })
432​
433 it('does NOT delete anything when the consumer aborts mid-read', async () => {
434 // An abort is not terminal. The consumer may be handing off to a successor
435 // host that still needs every journal byte, so both files must survive.
436 const controller = new AbortController()
437 const { handle, timeline } = timelineHandle(['{"a":1}\n', '{"b":2}\n'])
438 const events: Array<unknown> = []
439 for await (const event of readJournalNdjson(handle, {
440 journal: { runId: 'r1' },
441 signal: controller.signal,
442 })) {
443 events.push(event)
444 controller.abort()
445 }
446 expect(events).toEqual([{ a: 1 }])
447 expect(timeline.some((entry) => entry.includes('rm -f'))).toBe(false)
448 expect(timeline.filter((entry) => entry.startsWith('exec:'))).toEqual([])
449 })
450​
451 it('THROWS, and deletes nothing, when the stream ends without a sentinel and nobody aborted', async () => {
452 // A sentinel-less end with an UNaborted signal is a torn-down read: the
453 // `tail` was killed, the sandbox went away, the pipe broke. The iterable ends
454 // with no error, so returning here made the adapter emit a normally
455 // completing but silently TRUNCATED run — in a function whose documented job
456 // is to throw so the adapter converts it into a RUN_ERROR. It must throw, and
457 // still delete nothing: the run may be mid-flight and a successor host may
458 // need every byte.
459 const { handle, timeline } = timelineHandle(['{"a":1}\n'])
460 const events: Array<unknown> = []
461 const error = await (async () => {
462 try {
463 for await (const event of readJournalNdjson(handle, {
464 journal: { runId: 'r1' },
465 })) {
466 events.push(event)
467 }
468 return null
469 } catch (cause: unknown) {
470 return cause
471 }
472 })()
473 expect(events).toEqual([{ a: 1 }])
474 expect(error).toBeInstanceOf(Error)
475 if (!(error instanceof Error)) throw new Error('expected a thrown Error')
476 expect(error.message).toMatch(/without an exit sentinel/)
477 expect(timeline.filter((entry) => entry.startsWith('exec:'))).toEqual([])
478 })
479​
480 it('returns quietly, deleting nothing, when the CONSUMER aborted instead', async () => {
481 // The other arm of the same branch, and the reason a bare `return` was not
482 // safe to keep for both: an abort is the caller withdrawing, not a diagnosis
483 // about the run, so it must NOT become a RUN_ERROR for a run that is very
484 // possibly healthy and about to be taken over.
485 const controller = new AbortController()
486 const { handle, timeline } = timelineHandle(['{"a":1}\n'])
487 const events: Array<unknown> = []
488 for await (const event of readJournalNdjson(handle, {
489 journal: { runId: 'r1' },
490 signal: controller.signal,
491 })) {
492 events.push(event)
493 controller.abort()
494 }
495 expect(events).toEqual([{ a: 1 }])
496 expect(timeline.filter((entry) => entry.startsWith('exec:'))).toEqual([])
497 })
498​
499 it('does not stop at an {"__exit":0} line the AGENT printed, and delivers it as an event', async () => {
500 // The forgery, at the reader instead of the reaper: an agent that echoes a
501 // fixture or dumps a file can put this exact line in the journal, because its
502 // stdout and the sentinel share one unframed file. Stopping there truncates a
503 // live run and (worse) reports it as exit 0. The nonce is what separates them,
504 // so the unnonced line is just another event.
505 const { handle, timeline } = timelineHandle([
506 `{"__exit":0}\n{"a":1}\n${EXIT(0)}\n`,
507 ])
508 expect(
509 await collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
510 ).toEqual([{ __exit: 0 }, { a: 1 }])
511 // And the run really did reach its own sentinel, so cleanup ran exactly once.
512 expect(
513 timeline.filter((entry) => entry === `exec:${journalCleanupCommand(R1)}`),
514 ).toHaveLength(1)
515 })
516​
517 it('never deletes before the sentinel is observed', async () => {
518 const { handle, timeline } = timelineHandle([
519 '{"a":1}\n',
520 '{"b":2}\n',
521 `${EXIT(0)}\n`,
522 ])
523 const seenAtCleanup: Array<number> = []
524 let delivered = 0
525 for await (const event of readJournalNdjson(handle, {
526 journal: { runId: 'r1' },
527 })) {
528 void event
529 delivered += 1
530 if (timeline.some((entry) => entry.includes('rm -f'))) {
531 seenAtCleanup.push(delivered)
532 }
533 }
534 // No `rm` was observed while events were still being delivered, and the run
535 // did deliver every event before the sentinel.
536 expect(seenAtCleanup).toEqual([])
537 expect(delivered).toBe(2)
538 expect(timeline[timeline.length - 1]).toBe(
539 `exec:${journalCleanupCommand(R1)}`,
540 )
541 })
542​
543 it('a failing rm never fails a run that already completed', async () => {
544 const { handle } = timelineHandle([`{"a":1}\n${EXIT(0)}\n`], (command) =>
545 command.startsWith('rm -f')
546 ? Promise.reject(new Error('rm: /tmp: read-only file system'))
547 : Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }),
548 )
549 expect(
550 await collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
551 ).toEqual([{ a: 1 }])
552 })
553​
554 it('a failing rm does not mask the real non-zero-exit error', async () => {
555 const { handle } = timelineHandle([`${EXIT(7)}\n`], (command) =>
556 command.startsWith('rm -f')
557 ? Promise.reject(new Error('rm: /tmp: read-only file system'))
558 : Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }),
559 )
560 await expect(
561 collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
562 ).rejects.toThrow(/exited with code 7/)
563 })
564​
565 it('a failing sidecar read still throws the exit-code error, without stderr', async () => {
566 const { handle } = timelineHandle([`${EXIT(7)}\n`], (command) =>
567 command.startsWith('tail')
568 ? Promise.reject(new Error('exec unavailable'))
569 : Promise.resolve({ stdout: '', stderr: '', exitCode: 0 }),
570 )
571 await expect(
572 collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
573 ).rejects.toThrow(/^Agent process exited with code 7$/)
574 })
575​
576 it('a corrupt sidecar frame still throws the exit-code error', async () => {
577 // `decodeBase64Stream` fails loud on a mid-quantum remainder. That must not
578 // replace the agent's failure with a decoding failure.
579 const { handle } = timelineHandle([`${EXIT(7)}\n`], (command) =>
580 Promise.resolve({
581 stdout: command.startsWith('tail') ? 'aaaaa' : '',
582 stderr: '',
583 exitCode: 0,
584 }),
585 )
586 await expect(
587 collect(readJournalNdjson(handle, { journal: { runId: 'r1' } })),
588 ).rejects.toThrow(/^Agent process exited with code 7$/)
589 })
590​
591 it('bounds the attached stderr the same way the unjournaled path does', async () => {
592 const { handle } = timelineHandle([`${EXIT(7)}\n`], (command) =>
593 Promise.resolve({
594 stdout: command.startsWith('tail') ? stderrFrame('x'.repeat(4000)) : '',
595 stderr: '',
596 exitCode: 0,
597 }),
598 )
599 const error = await collect(
600 readJournalNdjson(handle, { journal: { runId: 'r1' } }),
601 ).catch((cause: unknown) => cause)
602 if (!(error instanceof Error)) throw new Error('expected a thrown Error')
603 expect(error.message).toHaveLength(
604 'Agent process exited with code 7: '.length + 1000,
605 )
606 })
607})
608​
609describe('a late takeover after journal cleanup', () => {
610 it('is safe by construction: alignment reads the event log, not the journal', () => {
611 // The ordering argument only holds if nothing downstream of terminal needs
612 // the journal. `alignToStoredLog` is that downstream step, and its input is
613 // the stored log: it takes no SandboxHandle and no JournalPaths, and reads
614 // the delivered prefix with `durability.snapshot()`. Asserted against the
615 // source so a future edit that reaches for the journal breaks here.
616 const source = readFileSync(
617 new URL('../src/align.ts', import.meta.url),
618 'utf8',
619 )
620 expect(source).toContain('options.durability.snapshot()')
621 for (const forbidden of [
622 'paths.journal',
623 'JournalPaths',
624 'SandboxHandle',
625 'readJournal',
626 'journalReadCommand',
627 'journalFollowCommand',
628 "from './journal",
629 ]) {
630 expect(source).not.toContain(forbidden)
631 }
632 })
633​
634 it('re-aligns a replayed prefix from the stored log with zero sandbox access', async () => {
635 // End to end: a run reaches its sentinel and its journal is deleted, and a
636 // successor host can still suppress the delivered prefix and forward only
637 // the remainder — using the log alone.
638 const { handle, timeline } = timelineHandle([`{"a":1}\n${EXIT(0)}\n`])
639 await collect(readJournalNdjson(handle, { journal: { runId: 'r1' } }))
640 expect(timeline).toContain(`exec:${journalCleanupCommand(R1)}`)
641​
642 const durability = memoryStream(
643 new Request('http://test.local/api/chat?runId=runner-cleanup-takeover', {
644 method: 'POST',
645 }),
646 )
647 const chunk = (delta: string): StreamChunk => ({
648 type: EventType.TEXT_MESSAGE_CONTENT,
649 messageId: 'm1',
650 delta,
651 timestamp: 1,
652 })
653 await durability.append([chunk('a')])
654 const forwarded: Array<StreamChunk> = []
655 for await (const out of alignToStoredLog(
656 (async function* () {
657 yield chunk('a')
658 yield chunk('b')
659 })(),
660 { durability },
661 )) {
662 forwarded.push(out)
663 }
664 expect(forwarded).toEqual([chunk('b')])
665 })
666})
667​
668describe('spawnNdjson with journaling', () => {
669 it('starts the agent journaled and reads the journal back, one code path', async () => {
670 const { handle, commands } = scriptedHandle([
671 [], // the agent spawn
672 [`{"a":1}\n${EXIT(0)}\n`], // the tail spawn
673 ])
674 expect(
675 await collect(spawnNdjson(handle, 'agent', { journal: { runId: 'r1' } })),
676 ).toEqual([{ a: 1 }])
677 expect(commands[0]).toContain(`>> '/tmp/tanstack-runs/r1.ndjson'`)
678 expect(commands[1]).toContain(
679 `tail -c +1 -f '/tmp/tanstack-runs/r1.ndjson'`,
680 )
681 })
682​
683 it('skips the agent spawn when attaching to a run already in flight', async () => {
684 const { handle, commands } = scriptedHandle([[`${EXIT(0)}\n`]])
685 await collect(
686 spawnNdjson(handle, 'agent', { journal: { runId: 'r1', attach: true } }),
687 )
688 // Three commands, none of them an agent: the attach preflight's `test -f`
689 // (which `scriptedHandle`'s exec answers with exit 0, i.e. "the journal is
690 // already there"), the tail, then the cleanup `rm` the terminal sentinel
691 // triggers. The agent is already running elsewhere.
692 expect(commands).toHaveLength(3)
693 expect(commands[0]).toBe(journalExistsCommand(R1))
694 expect(commands[1]).toContain('tail -c +1 -f')
695 expect(commands[2]).toBe(journalCleanupCommand(R1))
696 expect(commands.some((command) => command.includes('agent'))).toBe(false)
697 })
698​
699 it('keeps the unjournaled path byte-identical when no journal option is passed', async () => {
700 const handle = handleSpawning(['{"a":1}\n'])
701 expect(await collect(spawnNdjson(handle, 'agent'))).toEqual([{ a: 1 }])
702 })
703})