Open History to see the last commit
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> }
56}
57
58async function* stdoutOf(values: Array<string>): AsyncIterable<string> {
59 for (const v of values) {
60 await Promise.resolve()
61 yield v
62 }
63}
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> }
104}
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 }
115}
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 }
125}
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
139}
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
172}
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
177}
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 model: MODEL,
187 runId: 'r-attach-refused',
188 messages: [{ role: 'user', content: 'hi' }],
189 logger,
190 capabilities: contextWith(sandbox, durability(true)),
191 }),
192 3000,
193 )
194
195 // THE POINT OF THE THROW, asserted FIRST because it is the load-bearing
196 // safety property and the one whose failure must be legible: nothing ran. No
197 // opencode server was spawned, so the workspace the previous attempt mutated
198 // was not re-driven and nothing was appended to the run log.
199 expect(sandbox.spawns).toEqual([])
200 expect(chunks.some((c) => c.type === 'RUN_STARTED')).toBe(false)
201
202 // The adapter's `catch` turns any throw into a RUN_ERROR chunk, so assert on
203 // that rather than on a rejection.
204 const message = errorMessageOf(chunks)
205 expect(message).toContain('cannot ATTACH')
206
207 // The refusal must state the CONSEQUENCE, not merely the condition — that is
208 // what makes it actionable instead of something an operator retries.
209 expect(message).toMatch(/re-run the agent from scratch/i)
210 expect(message).toMatch(/double-append/i)
211 // And rule the retry out explicitly, because the neighbouring
212 // `JournalAttachUnavailableError` IS retryable.
213 expect(message).toMatch(/not a transient condition/i)
214
215 // A refusal, not the warn escalated: warning here would mean it proceeded.
216 expect(logger.warn).not.toHaveBeenCalled()
217 })
218
219 it('warns exactly once and PROCEEDS past the gate on a fresh durable run', async () => {
220 const sandbox = mockSandbox()
221 const logger = noopLogger()
222
223 const chunks = await collectWithin(
224 opencodeText(MODEL).chatStream({
225 model: MODEL,
226 runId: 'r-fresh-durable',
227 messages: [{ role: 'user', content: 'hi' }],
228 logger,
229 capabilities: contextWith(sandbox, durability(false)),
230 }),
231 3000,
232 )
233 // Settled, not abandoned: the run ends on the refused port 1.
234 expect(errorMessageOf(chunks)).toBeDefined()
235
236 // Once per run, not per chunk — a per-chunk warning would be worse than
237 // none, so the COUNT is the assertion, not merely that it fired.
238 expect(logger.warn).toHaveBeenCalledTimes(1)
239 const [message] = logger.warn.mock.calls[0] as [string]
240 expect(message).toMatch(/not be recoverable/i)
241 // It must name a fix, or it is only noise.
242 expect(message).toMatch(/journaling harness adapter/i)
243
244 // PROCEEDED: the fresh run is not refused, and the proof is that it reached
245 // the spawn the attach case never got to.
246 expect(sandbox.spawns.length).toBeGreaterThan(0)
247 })
248
249 it('is byte-identical to today when no durability is wired', async () => {
250 const sandbox = mockSandbox()
251 const logger = noopLogger()
252
253 const chunks = await collectWithin(
254 opencodeText(MODEL).chatStream({
255 model: MODEL,
256 runId: 'r-no-durability',
257 messages: [{ role: 'user', content: 'hi' }],
258 logger,
259 capabilities: contextWith(sandbox),
260 }),
261 3000,
262 )
263 // Settled, not abandoned: the run ends on the refused port 1.
264 expect(errorMessageOf(chunks)).toBeDefined()
265
266 // The common default stays silent and unchanged: neither check may fire when
267 // the app never asked for durability at all, and the run proceeds exactly as
268 // before to the same spawn.
269 expect(logger.warn).not.toHaveBeenCalled()
270 expect(sandbox.spawns.length).toBeGreaterThan(0)
271 })
272})