Open History to see the last commit
1/**
2 * `compatible.ts` never journals: it drives the harness over a bidirectional ACP
3 * connection and has no `spawnNdjson`, no journal to tail, no
4 * `awaitAttachableJournal` to refuse a hopeless attach up front, and no
5 * `alignedIfAttaching` to suppress an already-delivered prefix. So an app that
6 * wires `withSandbox({ runs, durability })` and routes runs through this adapter
7 * gets something that LOOKS durable while being unrecoverable.
8 *
9 * The response splits on whether a first attempt has already run, and the
10 * asymmetry is the whole design:
11 *
12 * - A FRESH durable run only fails to be recoverable LATER. An app may knowingly
13 * accept that (durability is wired once at the middleware level, and not every
14 * run needs to survive a restart). That is a WARN — audible, not fatal — once
15 * per run.
16 * - An ATTACH has already spent its first attempt: `sandboxRunDriver`'s `drive()`
17 * sets `attach: true` only when a previous host was streaming this run.
18 * Proceeding re-runs the agent from scratch against the workspace that attempt
19 * mutated and double-appends its whole output to a log that still holds the
20 * first attempt's. That is a THROW —
21 * `DurableAttachNotSupportedError`, raised before the ACP connection opens.
22 *
23 * These tests drive `chatStream` for real — the actual `@agentclientprotocol/sdk`
24 * agent side spawned over stdio in a real `localProcessSandbox`, as in
25 * `compatible.test.ts` — because both checks sit inline in `chatStream`'s setup
26 * ahead of the spawn, so exercising the real path is what proves they fire (or
27 * don't) where the fix lives, not a hand-extracted copy of their condition.
28 */
29import { afterAll, describe, expect, it, vi } from 'vitest'
30import * as fsp from 'node:fs/promises'
31import * as os from 'node:os'
32import * as path from 'node:path'
33import { createRequire } from 'node:module'
34import { pathToFileURL } from 'node:url'
35import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
36import {
37 SandboxCapability,
38 SandboxDurabilityCapability,
39} from '@tanstack/ai-sandbox'
40import { InMemoryRunStore } from '@tanstack/ai'
41import { acpCompatible } from '../src/index'
42import type { InternalLogger } from '@tanstack/ai/adapter-internals'
43import type {
44 CapabilityContext,
45 AdapterYieldChunk,
46 StreamDurability,
47} from '@tanstack/ai'
48import type { SandboxHandle, SandboxRunDurability } from '@tanstack/ai-sandbox'
49
50const require = createRequire(import.meta.url)
51const SDK_URL = pathToFileURL(require.resolve('@agentclientprotocol/sdk')).href
52
53/** A minimal ACP agent that replies "pong" — the only output this file looks for. */
54const FAKE_ACP_AGENT = `
55import { AgentSideConnection, ndJsonStream, PROTOCOL_VERSION } from ${JSON.stringify(SDK_URL)}
56import { Readable, Writable } from 'node:stream'
57
58const input = Readable.toWeb(process.stdin)
59const output = Writable.toWeb(process.stdout)
60const stream = ndJsonStream(output, input)
61
62new AgentSideConnection((conn) => ({
63 async initialize() {
64 return { protocolVersion: PROTOCOL_VERSION, agentCapabilities: { loadSession: true }, authMethods: [] }
65 },
66 async authenticate() { return {} },
67 async newSession() { return { sessionId: 'sess-1' } },
68 async loadSession() { return {} },
69 async prompt(params) {
70 await conn.sessionUpdate({
71 sessionId: params.sessionId,
72 update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'pong' } },
73 })
74 return { stopReason: 'end_turn' }
75 },
76 async cancel() {},
77}), stream)
78`
79
80const baseDir = path.join(
81 os.tmpdir(),
82 `tanstack-ai-acp-durability-attach-${Date.now()}`,
83)
84// No removeOnDestroy: destroying a sandbox right after killing its agent races
85// the OS releasing the dir (EBUSY on Windows) — see compatible.test.ts.
86const provider = localProcessSandbox({ baseDir })
87
88afterAll(async () => {
89 await fsp.rm(baseDir, {
90 recursive: true,
91 force: true,
92 maxRetries: 10,
93 retryDelay: 100,
94 })
95})
96
97function noopLogger(): InternalLogger & { warn: ReturnType<typeof vi.fn> } {
98 return {
99 request: () => {},
100 provider: () => {},
101 errors: () => {},
102 agentLoop: () => {},
103 warnings: () => {},
104 debug: () => {},
105 warn: vi.fn(),
106 } as unknown as InternalLogger & { warn: ReturnType<typeof vi.fn> }
107}
108
109/**
110 * A `StreamDurability` whose methods are never expected to be exercised: this
111 * adapter does not journal, which is the very condition under test. If a case
112 * here ever started appending through it, that would be the bug.
113 */
114function fakeAdapterLog(): StreamDurability {
115 return {
116 resumeFrom: () => null,
117 append: (chunks) => Promise.resolve(chunks.map((_, i) => `o:${i}`)),
118 read: () => (async function* empty() {})(),
119 close: () => Promise.resolve(),
120 snapshot: () => Promise.resolve([]),
121 }
122}
123
124function durability(attach = false): SandboxRunDurability {
125 return {
126 runs: new InMemoryRunStore(),
127 adapter: fakeAdapterLog(),
128 journalDir: `/tmp/tanstack-acp-attach-unused-${Date.now()}`,
129 attach,
130 detachOnDisconnect: true,
131 }
132}
133
134function contextWith(
135 handle: SandboxHandle,
136 durabilityCapability?: 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 (durabilityCapability) provideSandboxDurability(ctx, durabilityCapability)
145 return ctx
146}
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
154}
155
156function textOf(chunks: Array<AdapterYieldChunk>): string {
157 return chunks
158 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
159 .map((c) => (c as { delta?: string }).delta ?? '')
160 .join('')
161}
162
163function adapter() {
164 return acpCompatible({
165 name: 'pi',
166 command: () => 'node fake-acp-agent.mjs',
167 })('pi-fast')
168}
169
170const SANDBOX_TEST_TIMEOUT = 60_000
171
172describe(
173 'acp durability on a never-journaling adapter',
174 { timeout: SANDBOX_TEST_TIMEOUT },
175 () => {
176 it('REFUSES an attach outright, instead of re-running the agent', async () => {
177 const sbx = await provider.create({})
178 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
179 const logger = noopLogger()
180
181 const chunks = await collect(
182 adapter().chatStream({
183 threadId: 'thread-1',
184 model: 'pi-fast',
185 runId: 'r-attach-refused',
186 messages: [{ role: 'user', content: 'say pong' }],
187 logger,
188 capabilities: contextWith(sbx, durability(true)),
189 }),
190 )
191
192 // The adapter's `catch` turns any throw into a RUN_ERROR chunk, so assert
193 // on that rather than on a rejection.
194 expect(chunks).toHaveLength(1)
195 const error = chunks[0] as { type: string; message?: string }
196 expect(error.type).toBe('RUN_ERROR')
197 expect(error.message).toContain('cannot ATTACH')
198
199 // The refusal must state the CONSEQUENCE, not merely the condition — that
200 // is what makes it actionable rather than something an operator retries.
201 expect(error.message).toMatch(/re-run the agent from scratch/i)
202 expect(error.message).toMatch(/double-append/i)
203 // And it must rule the retry out explicitly, because the neighbouring
204 // `JournalAttachUnavailableError` IS retryable and would otherwise be the
205 // natural reading.
206 expect(error.message).toMatch(/not a transient condition/i)
207
208 // THE POINT OF THE THROW: the agent never ran. `pong` is the fake agent's
209 // only output, so its absence proves `session.prompt(...)` was never
210 // reached — the workspace the previous attempt mutated was not re-driven
211 // and nothing was appended to the run log.
212 expect(textOf(chunks)).toBe('')
213 expect(chunks.some((c) => c.type === 'RUN_STARTED')).toBe(false)
214
215 // A refusal, not the warn escalated: warning here would mean it proceeded.
216 expect(logger.warn).not.toHaveBeenCalled()
217
218 await sbx.destroy()
219 })
220
221 it('warns exactly once and PROCEEDS on a fresh durable run', async () => {
222 const sbx = await provider.create({})
223 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
224 const logger = noopLogger()
225
226 const chunks = await collect(
227 adapter().chatStream({
228 threadId: 'thread-1',
229 model: 'pi-fast',
230 runId: 'r-fresh-durable',
231 messages: [{ role: 'user', content: 'say pong' }],
232 logger,
233 capabilities: contextWith(sbx, durability(false)),
234 }),
235 )
236
237 // Proceeding is half the assertion: a fresh durable run is NOT refused.
238 expect(chunks[0]).toMatchObject({ type: 'RUN_STARTED' })
239 expect(textOf(chunks)).toContain('pong')
240 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
241
242 // Once per run, not per chunk — a per-chunk warning would be worse than
243 // none, so the count is the assertion, not just that it fired.
244 expect(logger.warn).toHaveBeenCalledTimes(1)
245 const [message] = logger.warn.mock.calls[0] as [string]
246 expect(message).toMatch(/not be recoverable/i)
247 // It must name a fix, or it is only noise.
248 expect(message).toMatch(/journaling harness adapter/i)
249
250 await sbx.destroy()
251 })
252
253 it('is byte-identical to today when no durability is wired', async () => {
254 const sbx = await provider.create({})
255 await sbx.fs.write('/workspace/fake-acp-agent.mjs', FAKE_ACP_AGENT)
256 const logger = noopLogger()
257
258 const chunks = await collect(
259 adapter().chatStream({
260 threadId: 'thread-1',
261 model: 'pi-fast',
262 runId: 'r-no-durability',
263 messages: [{ role: 'user', content: 'say pong' }],
264 logger,
265 capabilities: contextWith(sbx),
266 }),
267 )
268
269 expect(chunks[0]).toMatchObject({ type: 'RUN_STARTED' })
270 expect(textOf(chunks)).toContain('pong')
271 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
272 // The common default must stay silent: neither check may fire when the
273 // app never asked for durability at all.
274 expect(logger.warn).not.toHaveBeenCalled()
275
276 await sbx.destroy()
277 })
278 },
279)