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

durability-attach.test.ts

275 lines10.0 KB

1/**
2 * The OpenCode adapter never journals: it drives the harness over the opencode
3 * HTTP server, so there is 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. An app that
6 * wires `withSandbox({ runs, durability })` and routes runs here therefore gets
7 * something that LOOKS durable while being unrecoverable.
8 *
9 * The response splits on whether a first attempt has already run:
10 *
11 * - A FRESH durable run only fails to be recoverable LATER, which an app may
12 * knowingly accept. That is a WARN — audible, not fatal — once per run.
13 * - An ATTACH has already spent its first attempt (`sandboxRunDriver`'s `drive()`
14 * sets `attach: true` only when a previous host was streaming this run), so
15 * proceeding re-runs the agent against the workspace that attempt mutated and
16 * double-appends its output to the run log. That is a THROW.
17 *
18 * The gate sits immediately after the sandbox is resolved and BEFORE
19 * `startOpencodeServerInSandbox`, which is what makes the refusal testable
20 * without a live opencode server: on the attach path nothing is ever spawned, and
21 * `mockSandbox` below records whether a spawn was attempted. That recorded flag
22 * is the real assertion — the error message alone would not prove the agent
23 * didn't run.
24 */
25import { describe, expect, it, vi } from 'vitest'
26import {
27 SandboxCapability,
28 SandboxDurabilityCapability,
29} from '@tanstack/ai-sandbox'
30import { InMemoryRunStore } from '@tanstack/ai'
31import { opencodeText } from '../src/index'
32import type { InternalLogger } from '@tanstack/ai/adapter-internals'
33import type {
34 CapabilityContext,
35 AdapterYieldChunk,
36 StreamDurability,
37} from '@tanstack/ai'
38import type {
39 SandboxHandle,
40 SandboxRunDurability,
41 SpawnHandle,
42} from '@tanstack/ai-sandbox'
43​
44const MODEL = 'anthropic/claude-sonnet-4-5'
45​
46function noopLogger(): InternalLogger & { warn: ReturnType<typeof vi.fn> } {
47 return {
48 request: () => {},
49 provider: () => {},
50 errors: () => {},
51 agentLoop: () => {},
52 warnings: () => {},
53 debug: () => {},
54 warn: vi.fn(),
55 } as unknown as InternalLogger & { warn: ReturnType<typeof vi.fn> }
57​
58async function* stdoutOf(values: Array<string>): AsyncIterable<string> {
59 for (const v of values) {
60 await Promise.resolve()
61 yield v
62 }
64​
65/**
66 * A sandbox that RECORDS whether the adapter tried to spawn anything. The
67 * server-readiness line is scripted so the fresh-durable case gets past the
68 * launch helper and proves the run continued rather than being refused.
69 */
70function mockSandbox(): SandboxHandle & { spawns: Array<string> } {
71 const spawns: Array<string> = []
72 const spawnHandle: SpawnHandle = {
73 pid: 1,
74 stdout: stdoutOf(['opencode server listening on http://0.0.0.0:4096\n']),
75 stderr: stdoutOf([]),
76 stdin: { write: () => Promise.resolve(), end: () => Promise.resolve() },
77 wait: () => Promise.resolve(0),
78 kill: () => Promise.resolve(),
79 }
80 const handle = {
81 id: 'sbx',
82 provider: 'mock',
83 capabilities: {} as SandboxHandle['capabilities'],
84 fs: { write: () => Promise.resolve() } as unknown as SandboxHandle['fs'],
85 git: {} as SandboxHandle['git'],
86 process: {
87 exec: () => Promise.reject(new Error('unused')),
88 spawn: (command: string) => {
89 spawns.push(command)
90 return Promise.resolve(spawnHandle)
91 },
92 },
93 ports: {
94 // Port 1 refuses at once, so a run that passes the gate fails its first
95 // HTTP call and ends. A real port (4096) could be in use on the host,
96 // and then how far the run got before the file ended varied per machine.
97 connect: () => Promise.resolve({ url: 'http://127.0.0.1:1' }),
98 },
99 env: { set: () => Promise.resolve() },
100 destroy: () => Promise.resolve(),
101 spawns,
102 }
103 return handle as unknown as SandboxHandle & { spawns: Array<string> }
105​
106/** Never expected to be exercised: this adapter does not journal, which is the condition under test. */
107function fakeAdapterLog(): StreamDurability {
108 return {
109 resumeFrom: () => null,
110 append: (chunks) => Promise.resolve(chunks.map((_, i) => `o:${i}`)),
111 read: () => (async function* empty() {})(),
112 close: () => Promise.resolve(),
113 snapshot: () => Promise.resolve([]),
114 }
116​
117function durability(attach = false): SandboxRunDurability {
118 return {
119 runs: new InMemoryRunStore(),
120 adapter: fakeAdapterLog(),
121 journalDir: '/tmp/tanstack-opencode-attach-unused',
122 attach,
123 detachOnDisconnect: true,
124 }
126​
127function contextWith(
128 handle: SandboxHandle,
129 durabilityCapability?: SandboxRunDurability,
130): CapabilityContext {
131 const [, provideSandbox] = SandboxCapability
132 const [, provideSandboxDurability] = SandboxDurabilityCapability
133 const ctx = {
134 capabilities: { markProvided: () => {}, has: () => true },
135 } as unknown as CapabilityContext
136 provideSandbox(ctx, handle)
137 if (durabilityCapability) provideSandboxDurability(ctx, durabilityCapability)
138 return ctx
140​
141/**
142 * Drain the stream, but give up after `ms` and return what arrived.
143 *
144 * Every run here ends on its own (the refusal at once, a run past the gate when
145 * its first HTTP call to port 1 is refused). The bound only keeps a regression
146 * from showing up as "test timed out" instead of the assertion that caught it.
147 */
148async function collectWithin(
149 stream: AsyncIterable<AdapterYieldChunk>,
150 ms: number,
151): Promise<Array<AdapterYieldChunk>> {
152 const out: Array<AdapterYieldChunk> = []
153 const iterator = stream[Symbol.asyncIterator]()
154 const deadline = Date.now() + ms
155 for (;;) {
156 const remaining = deadline - Date.now()
157 if (remaining <= 0) break
158 const step = await Promise.race([
159 iterator.next(),
160 new Promise<'timeout'>((resolve) =>
161 setTimeout(() => resolve('timeout'), remaining),
162 ),
163 ])
164 if (step === 'timeout') break
165 if (step.done === true) return out
166 out.push(step.value)
167 }
168 // Abandoned, not awaited: an async generator serializes its queue, so
169 // `return()` would wait behind the `next()` that just failed to settle.
170 void Promise.resolve(iterator.return?.()).catch(() => {})
171 return out
173​
174function errorMessageOf(chunks: Array<AdapterYieldChunk>): string | undefined {
175 const err = chunks.find((c) => c.type === 'RUN_ERROR')
176 return (err as { message?: string } | undefined)?.message
178​
179describe('opencode durability on a never-journaling adapter', () => {
180 it('REFUSES an attach outright, without spawning the harness', async () => {
181 const sandbox = mockSandbox()
182 const logger = noopLogger()
183​
184 const chunks = await collectWithin(
185 opencodeText(MODEL).chatStream({
186 threadId: 'thread-1',
187 model: MODEL,
188 runId: 'r-attach-refused',
189 messages: [{ role: 'user', content: 'hi' }],
190 logger,
191 capabilities: contextWith(sandbox, durability(true)),
192 }),
193 3000,
194 )
195​
196 // THE POINT OF THE THROW, asserted FIRST because it is the load-bearing
197 // safety property and the one whose failure must be legible: nothing ran. No
198 // opencode server was spawned, so the workspace the previous attempt mutated
199 // was not re-driven and nothing was appended to the run log.
200 expect(sandbox.spawns).toEqual([])
201 expect(chunks.some((c) => c.type === 'RUN_STARTED')).toBe(false)
202​
203 // The adapter's `catch` turns any throw into a RUN_ERROR chunk, so assert on
204 // that rather than on a rejection.
205 const message = errorMessageOf(chunks)
206 expect(message).toContain('cannot ATTACH')
207​
208 // The refusal must state the CONSEQUENCE, not merely the condition — that is
209 // what makes it actionable instead of something an operator retries.
210 expect(message).toMatch(/re-run the agent from scratch/i)
211 expect(message).toMatch(/double-append/i)
212 // And rule the retry out explicitly, because the neighbouring
213 // `JournalAttachUnavailableError` IS retryable.
214 expect(message).toMatch(/not a transient condition/i)
215​
216 // A refusal, not the warn escalated: warning here would mean it proceeded.
217 expect(logger.warn).not.toHaveBeenCalled()
218 })
219​
220 it('warns exactly once and PROCEEDS past the gate on a fresh durable run', async () => {
221 const sandbox = mockSandbox()
222 const logger = noopLogger()
223​
224 const chunks = await collectWithin(
225 opencodeText(MODEL).chatStream({
226 threadId: 'thread-1',
227 model: MODEL,
228 runId: 'r-fresh-durable',
229 messages: [{ role: 'user', content: 'hi' }],
230 logger,
231 capabilities: contextWith(sandbox, durability(false)),
232 }),
233 3000,
234 )
235 // Settled, not abandoned: the run ends on the refused port 1.
236 expect(errorMessageOf(chunks)).toBeDefined()
237​
238 // Once per run, not per chunk — a per-chunk warning would be worse than
239 // none, so the COUNT is the assertion, not merely that it fired.
240 expect(logger.warn).toHaveBeenCalledTimes(1)
241 const [message] = logger.warn.mock.calls[0] as [string]
242 expect(message).toMatch(/not be recoverable/i)
243 // It must name a fix, or it is only noise.
244 expect(message).toMatch(/journaling harness adapter/i)
245​
246 // PROCEEDED: the fresh run is not refused, and the proof is that it reached
247 // the spawn the attach case never got to.
248 expect(sandbox.spawns.length).toBeGreaterThan(0)
249 })
250​
251 it('is byte-identical to today when no durability is wired', async () => {
252 const sandbox = mockSandbox()
253 const logger = noopLogger()
254​
255 const chunks = await collectWithin(
256 opencodeText(MODEL).chatStream({
257 threadId: 'thread-1',
258 model: MODEL,
259 runId: 'r-no-durability',
260 messages: [{ role: 'user', content: 'hi' }],
261 logger,
262 capabilities: contextWith(sandbox),
263 }),
264 3000,
265 )
266 // Settled, not abandoned: the run ends on the refused port 1.
267 expect(errorMessageOf(chunks)).toBeDefined()
268​
269 // The common default stays silent and unchanged: neither check may fire when
270 // the app never asked for durability at all, and the run proceeds exactly as
271 // before to the same spawn.
272 expect(logger.warn).not.toHaveBeenCalled()
273 expect(sandbox.spawns.length).toBeGreaterThan(0)
274 })
275})