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

attach.test.ts

478 lines17.1 KB

1/**
2 * Durable-run wiring for the Grok Build NDJSON path: the journal options the
3 * spawn receives, and the alignment an ATTACHING run routes through.
4 *
5 * These tests deliberately drive the real `localProcessSandbox` rather than a
6 * fake handle, because the two things under test are both path-derived: the
7 * journal file location comes from `runId` + the configured directory through a
8 * shell redirect, and the attach read finds (or does not find) that exact file.
9 * A fake `process.spawn` would let a wrong path pass.
10 *
11 * WHICH SEAM IS UNDER TEST. `ai-grok-build` has two protocol paths and only one
12 * of them journals:
13 *
14 * - `chatStreamAcp` (protocol `'acp'`, the default) merges `translateAcpStream`
15 * with the bridge channel via `mergeChunkStreams`. It never calls
16 * `spawnNdjson`, so it writes no journal and has no stored log to replay.
17 * - `chatStreamNdjson` (protocol `'streaming-json'`) is the journaled path:
18 * `spawnNdjson(..., { journal })` then `translateThreadEvents`.
19 *
20 * So the alignment seam is `translateThreadEvents`, NOT the ACP merge. Every
21 * assertion below is on the streaming-json path, and `aligns the final
22 * translated chunk sequence…` fails outright if the wrap is moved to the ACP
23 * merge, because that leaves this path unaligned.
24 */
25import { afterAll, describe, expect, it } from 'vitest'
26import * as fsp from 'node:fs/promises'
27import * as os from 'node:os'
28import * as path from 'node:path'
29import { randomUUID } from 'node:crypto'
30import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
31import {
32 SandboxCapability,
33 SandboxDurabilityCapability,
34 chunkFingerprint,
35 exitSentinelLine,
36 journalPaths,
37} from '@tanstack/ai-sandbox'
38import { InMemoryRunStore } from '@tanstack/ai'
39import { grokBuildText } from '../src/index'
40import type { SandboxHandle, SandboxRunDurability } from '@tanstack/ai-sandbox'
41import type { InternalLogger } from '@tanstack/ai/adapter-internals'
42import type {
43 CapabilityContext,
44 AdapterYieldChunk,
45 StreamDurability,
46} from '@tanstack/ai'
47​
48const baseDir = path.join(
49 os.tmpdir(),
50 `tanstack-ai-grok-build-attach-${Date.now()}`,
52const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
53​
54/**
55 * A journal directory scoped to this file's run. `/tmp/...` and not the
56 * `baseDir` above on purpose: the journal is written through a shell redirect,
57 * which resolves `/tmp` against the real shell root rather than the sandbox
58 * root (see `journal.ts` rule 3), so pointing it at the sandbox dir would just
59 * be misleading about where the bytes land.
60 */
61const JOURNAL_DIR = `/tmp/tanstack-grok-attach-${randomUUID()}`
62​
63afterAll(async () => {
64 const sbx = await provider.create({})
65 await sbx.process.exec(`rm -rf '${JOURNAL_DIR}'`)
66 await sbx.destroy()
67 await fsp.rm(baseDir, { recursive: true, force: true })
68})
69​
70/** Native grok `streaming-json` events, as the harness would have written them. */
71const JOURNAL_EVENTS = [
72 `{"type":"text","data":"po"}`,
73 `{"type":"text","data":"ng"}`,
74 `{"type":"end","stopReason":"EndTurn","sessionId":"sess-1"}`,
76​
77// The agent-exit sentinel `readJournalNdjson` stops at is NOT a constant: it
78// carries a per-run nonce derived from the runId, so that an agent's own stdout
79// (which lands in the same unframed file) cannot forge it. `seedJournal` builds
80// it with `exitSentinelLine`.
81​
82/**
83 * A fake agent for the NON-attach runs, emitting the same events the seeded
84 * journal holds so both directions describe one run.
85 */
86const FAKE_GROK = [
87 `const w = (s) => process.stdout.write(s + '\\n')`,
88 ...JOURNAL_EVENTS.map((line) => `w(${JSON.stringify(line)})`),
89].join('\n')
90​
91const noopLogger = {
92 request: () => {},
93 provider: () => {},
94 errors: () => {},
95 agentLoop: () => {},
96 warnings: () => {},
97 debug: () => {},
98} as unknown as InternalLogger
99​
100/**
101 * A `StreamDurability` that is a real accumulating list, so `snapshot()`
102 * reflects state rather than always answering empty. Only `snapshot` matters
103 * here — the adapter reads the log, it never appends to it.
104 */
105function fakeLog(entries: Array<AdapterYieldChunk> = []): StreamDurability {
106 const stored = [...entries]
107 return {
108 resumeFrom: () => null,
109 append: (chunks) => {
110 const start = stored.length
111 stored.push(...chunks)
112 return Promise.resolve(chunks.map((_, i) => `o:${start + i}`))
113 },
114 read: () => (async function* empty() {})(),
115 close: () => Promise.resolve(),
116 snapshot: () =>
117 Promise.resolve(stored.map((chunk, i) => ({ offset: `o:${i}`, chunk }))),
118 }
120​
121function durabilityWith(
122 adapter: StreamDurability,
123 attach: boolean,
124): SandboxRunDurability {
125 return {
126 runs: new InMemoryRunStore(),
127 adapter,
128 journalDir: JOURNAL_DIR,
129 attach,
130 detachOnDisconnect: true,
131 }
133​
134function contextWith(
135 handle: SandboxHandle,
136 durability?: SandboxRunDurability,
137): CapabilityContext {
138 const [, provideSandbox] = SandboxCapability
139 const [, provideSandboxDurability] = SandboxDurabilityCapability
140 const ctx = {
141 capabilities: { markProvided: () => {}, has: () => true },
142 } as unknown as CapabilityContext
143 provideSandbox(ctx, handle)
144 if (durability) provideSandboxDurability(ctx, durability)
145 return ctx
147​
148async function collect(
149 stream: AsyncIterable<AdapterYieldChunk>,
150): Promise<Array<AdapterYieldChunk>> {
151 const out: Array<AdapterYieldChunk> = []
152 for await (const chunk of stream) out.push(chunk)
153 return out
155​
156/**
157 * The DISTINCT `threadId`s stamped across a run's chunks.
158 *
159 * A set, not a list, because `threadId` appears on several chunk types
160 * (`RUN_STARTED`, `RUN_FINISHED`, …) and what matters is that they all agree on
161 * one id — the caller's on an attach, a generated one otherwise. Anything with
162 * more than one entry means the resolution ran twice.
163 */
164function threadIdsOf(chunks: Array<AdapterYieldChunk>): Array<string> {
165 const seen = new Set<string>()
166 for (const chunk of chunks) {
167 const value = (chunk as { threadId?: unknown }).threadId
168 if (typeof value === 'string') seen.add(value)
169 }
170 return [...seen]
172​
173/** Compare chunks ignoring wall-clock fields, exactly as alignment does. */
174function fingerprints(chunks: Array<AdapterYieldChunk>): Array<string> {
175 return chunks.map(chunkFingerprint)
177​
178/**
179 * Write a complete, terminalized journal for `runId` through the shell.
180 *
181 * Re-seeded before every attach run because `readJournalNdjson` DELETES the
182 * journal once it reads the `{"__exit":0}` sentinel (a terminal run's record is
183 * the event log, not the journal), so a second attach would otherwise find
184 * nothing.
185 */
186async function seedJournal(
187 sbx: SandboxHandle,
188 runId: string,
189 events: Array<string> = JOURNAL_EVENTS,
190): Promise<void> {
191 const paths = journalPaths(runId, JOURNAL_DIR)
192 const body = [...events, exitSentinelLine(paths, 0)]
193 .map((line) => `printf '%s\\n' '${line}'`)
194 .join('; ')
195 const result = await sbx.process.exec(
196 `mkdir -p '${paths.dir}' && { ${body}; } > '${paths.journal}'`,
197 )
198 expect(result.exitCode).toBe(0)
200​
201function adapter() {
202 return grokBuildText('grok-build', {
203 grokExecutable: 'node fake-grok.mjs',
204 protocol: 'streaming-json',
205 // The git-diff chunk is live output from this host and sits OUTSIDE the
206 // alignment wrap by design; disabled here so the alignment assertions are
207 // about the translated sequence alone. Asserted separately below.
208 emitDiff: false,
209 })
211​
212/**
213 * A stable `threadId` for the takeover assertions.
214 *
215 * `chatStream` falls back to `this.generateId()` for a missing `threadId`, and
216 * that id is a clock-plus-random value that lands in every chunk — so two
217 * replays of the same journal without a caller-supplied `threadId` diverge on
218 * `RUN_STARTED` before the first text chunk. A real takeover recomputes the
219 * `threadId` from the run record for exactly this reason; alignment is only
220 * meaningful when it does.
221 */
222const THREAD_ID = 'th-attach'
223​
224function run(
225 sbx: SandboxHandle,
226 options: {
227 runId?: string
228 threadId?: string
229 durability?: SandboxRunDurability
230 },
231): AsyncIterable<AdapterYieldChunk> {
232 return adapter().chatStream({
233 threadId: options.threadId ?? 'thread-1',
234 model: 'grok-build',
235 messages: [{ role: 'user', content: 'say pong' }],
236 logger: noopLogger,
237 capabilities: contextWith(sbx, options.durability),
238 ...(options.runId === undefined ? {} : { runId: options.runId }),
239 })
241​
242/**
243 * Every test here creates a real sandbox and, on the attach path, tails a real
244 * journal file through a shell — so the default 5s budget is not enough. The
245 * generous window is a timeout, not an expected duration.
246 */
247const SANDBOX_TEST_TIMEOUT = 90_000
248​
249describe(
250 'grok-build durable runId + journal wiring',
251 { timeout: SANDBOX_TEST_TIMEOUT },
252 () => {
253 it('keeps the generated-id fallback and stays unjournaled when durability is NOT wired', async () => {
254 const sbx = await provider.create({})
255 await sbx.fs.write('/workspace/fake-grok.mjs', FAKE_GROK)
256​
257 // No `runId`, no durability capability: today's behavior exactly.
258 const chunks = await collect(run(sbx, {}))
259​
260 expect(chunks.some((c) => c.type === 'RUN_STARTED')).toBe(true)
261 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
262 const text = chunks
263 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
264 .map((c) => (c as { delta?: string }).delta ?? '')
265 .join('')
266 expect(text).toBe('pong')
267​
268 // `journalOptionsFor` returned undefined, so the spawn took its original
269 // unjournaled path and nothing was written to the journal directory.
270 const listing = await sbx.process.exec(`ls '${JOURNAL_DIR}' 2>/dev/null`)
271 expect(listing.stdout).toBe('')
272​
273 await sbx.destroy()
274 })
275​
276 it('throws DurableRunIdRequiredError when durability is wired without a runId', async () => {
277 const sbx = await provider.create({})
278 await sbx.fs.write('/workspace/fake-grok.mjs', FAKE_GROK)
279​
280 // The adapter's `catch` turns any throw into a RUN_ERROR chunk, so assert on
281 // that rather than on a rejection.
282 const chunks = await collect(
283 run(sbx, { durability: durabilityWith(fakeLog(), false) }),
284 )
285​
286 expect(chunks).toHaveLength(1)
287 const error = chunks[0] as { type: string; message?: string }
288 expect(error.type).toBe('RUN_ERROR')
289 expect(error.message).toContain('caller-supplied `runId`')
290​
291 await sbx.destroy()
292 })
293​
294 it('journals under the resolved runId in the configured directory', async () => {
295 const sbx = await provider.create({})
296 await sbx.fs.write('/workspace/fake-grok.mjs', FAKE_GROK)
297 const runId = `r-${randomUUID()}`
298​
299 await collect(
300 run(sbx, { runId, durability: durabilityWith(fakeLog(), false) }),
301 )
302​
303 // The journal itself is deleted on the sentinel, but its stderr sidecar is
304 // only removed alongside it — so the surviving evidence of the path is the
305 // directory the run created, named from `journalDir`, and the fact that the
306 // ATTACH assertions below can find a journal written at exactly
307 // `journalPaths(runId, JOURNAL_DIR).journal`.
308 const dirExists = await sbx.process.exec(`test -d '${JOURNAL_DIR}'`)
309 expect(dirExists.exitCode).toBe(0)
310​
311 await sbx.destroy()
312 })
313 },
315​
316describe(
317 'grok-build attach alignment (the translateThreadEvents seam)',
318 { timeout: SANDBOX_TEST_TIMEOUT },
319 () => {
320 /**
321 * THE LOAD-BEARING TEST.
322 *
323 * It asserts the IDENTITY of what alignment compares against the stored log:
324 * seeded with the complete translated sequence, an attach delivers nothing;
325 * seeded with all but the last, it delivers exactly that last chunk. Both only
326 * hold if the aligned stream is the FINAL translated chunk sequence, because
327 * `alignToStoredLog` throws `JournalReplayDivergedError` on the first
328 * fingerprint mismatch and throws again if the replay is shorter than the log.
329 *
330 * This is what distinguishes the two candidate seams. `chatStreamAcp`'s
331 * `mergeChunkStreams` is in a different method on a different protocol; wrap
332 * there instead and this path is unaligned, so the stored prefix is not
333 * suppressed and both assertions below fail.
334 */
335 it('aligns the final translated chunk sequence against the stored log', async () => {
336 const sbx = await provider.create({})
337 const runId = `r-${randomUUID()}`
338​
339 // A first attach against an EMPTY log establishes what a replay of this
340 // journal produces — the reference sequence.
341 await seedJournal(sbx, runId)
342 const replayed = await collect(
343 run(sbx, {
344 runId,
345 threadId: THREAD_ID,
346 durability: durabilityWith(fakeLog(), true),
347 }),
348 )
349 expect(replayed.length).toBeGreaterThan(2)
350 expect(replayed.some((c) => c.type === 'RUN_STARTED')).toBe(true)
351 expect(replayed.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
352​
353 // Seeded with the COMPLETE sequence: every replayed chunk matches a stored
354 // one, one-for-one and in order, so nothing is left to deliver. A log whose
355 // entries were anything other than these translated chunks — raw harness
356 // events, pre-translation ACP updates — could not align at all.
357 await seedJournal(sbx, runId)
358 const nothingNew = await collect(
359 run(sbx, {
360 runId,
361 threadId: THREAD_ID,
362 durability: durabilityWith(fakeLog(replayed), true),
363 }),
364 )
365 expect(nothingNew).toEqual([])
366​
367 // Seeded with all but the last: exactly the undelivered tail comes through,
368 // and it is fingerprint-identical to the final translated chunk.
369 await seedJournal(sbx, runId)
370 const tail = await collect(
371 run(sbx, {
372 runId,
373 threadId: THREAD_ID,
374 durability: durabilityWith(fakeLog(replayed.slice(0, -1)), true),
375 }),
376 )
377 expect(fingerprints(tail)).toEqual(fingerprints(replayed.slice(-1)))
378​
379 await sbx.destroy()
380 })
381​
382 it('does NOT align a non-attach durable run, so a fresh run delivers its own chunks even against a populated log', async () => {
383 const sbx = await provider.create({})
384 await sbx.fs.write('/workspace/fake-grok.mjs', FAKE_GROK)
385 const runId = `r-${randomUUID()}`
386​
387 await seedJournal(sbx, runId)
388 const reference = await collect(
389 run(sbx, { runId, durability: durabilityWith(fakeLog(), true) }),
390 )
391​
392 // Same runId, a log already holding the whole sequence, but `attach: false`.
393 // Alignment must be skipped entirely: suppressing a fresh run's own output
394 // because a colliding runId left entries in the log is silent data loss.
395 const freshRunId = `r-${randomUUID()}`
396 const fresh = await collect(
397 run(sbx, {
398 runId: freshRunId,
399 durability: durabilityWith(fakeLog(reference), false),
400 }),
401 )
402​
403 expect(fresh.some((c) => c.type === 'RUN_STARTED')).toBe(true)
404 expect(fresh.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
405 const text = fresh
406 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
407 .map((c) => (c as { delta?: string }).delta ?? '')
408 .join('')
409 expect(text).toBe('pong')
410​
411 await sbx.destroy()
412 })
413​
414 it('derives the journal path from the runId, so an attach replays ITS run and not another', async () => {
415 const sbx = await provider.create({})
416 const alpha = `r-${randomUUID()}`
417 const beta = `r-${randomUUID()}`
418​
419 // Two journals side by side in the same directory, distinguished only by
420 // runId. An attach for `beta` must read `beta`'s bytes.
421 await seedJournal(sbx, alpha, [
422 `{"type":"text","data":"alpha"}`,
423 `{"type":"end","stopReason":"EndTurn","sessionId":"s-alpha"}`,
424 ])
425 await seedJournal(sbx, beta, [
426 `{"type":"text","data":"beta"}`,
427 `{"type":"end","stopReason":"EndTurn","sessionId":"s-beta"}`,
428 ])
429​
430 const chunks = await collect(
431 run(sbx, {
432 runId: beta,
433 threadId: THREAD_ID,
434 durability: durabilityWith(fakeLog(), true),
435 }),
436 )
437​
438 const text = chunks
439 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
440 .map((c) => (c as { delta?: string }).delta ?? '')
441 .join('')
442 expect(text).toBe('beta')
443 expect(text).not.toContain('alpha')
444​
445 await sbx.destroy()
446 })
447 },
449​
450describe(
451 'grok-build durable threadId (an attach must reuse the record’s)',
452 { timeout: SANDBOX_TEST_TIMEOUT },
453 () => {
454 it('carries a caller-supplied threadId into the chunks when ATTACHING', async () => {
455 const sbx = await provider.create({})
456 const runId = `r-${randomUUID()}`
457 const threadId = `t-reused-${randomUUID()}`
458 await seedJournal(sbx, runId)
459​
460 // Empty stored log, so nothing is suppressed and the chunks that carry
461 // `threadId` are observable.
462 const chunks = await collect(
463 run(sbx, {
464 runId,
465 threadId,
466 durability: durabilityWith(fakeLog(), true),
467 }),
468 )
469​
470 // Not merely "it did not throw": the id the caller passed must be the id
471 // stamped on the stream, which is the only thing that makes the replay
472 // alignable against the stored log.
473 expect(threadIdsOf(chunks)).toEqual([threadId])
474​
475 await sbx.destroy()
476 })
477 },