Open History to see the last commit
1/**
2 * Tests for the in-sandbox OpenCode adapter.
3 *
4 * The OpenCode HTTP session itself is the `@opencode-ai/sdk`'s and is reused
5 * unchanged via its `baseUrl` connect path; the new piece is spawning
6 * `opencode serve` inside the sandbox and exposing its port. We test that
7 * server-launch helper (readiness detection + port exposure) and the adapter's
8 * missing-sandbox path. A full session round-trip is covered by the gated live
9 * path.
10 */
11import { describe, expect, it } from 'vitest'
12import { startOpencodeServerInSandbox } from '../src/process/sandbox-server'
13import { opencodeText } from '../src/index'
14import type { InternalLogger } from '@tanstack/ai/adapter-internals'
15import type { StreamChunk } from '@tanstack/ai'
16import type { SandboxHandle, SpawnHandle } from '@tanstack/ai-sandbox'
17
18const noopLogger = {
19 request: () => {},
20 provider: () => {},
21 errors: () => {},
22 agentLoop: () => {},
23 warnings: () => {},
24 debug: () => {},
25} as unknown as InternalLogger
26
27async function* chunks(values: Array<string>): AsyncIterable<string> {
28 for (const v of values) {
29 await Promise.resolve()
30 yield v
31 }
32}
33
34/** Mock sandbox whose spawn emits a scripted stdout and whose port resolves. */
35function mockSandbox(stdout: Array<string>): SandboxHandle {
36 const spawnHandle: SpawnHandle = {
37 pid: 1,
38 stdout: chunks(stdout),
39 stderr: chunks([]),
40 stdin: { write: () => Promise.resolve(), end: () => Promise.resolve() },
41 wait: () => Promise.resolve(0),
42 kill: () => Promise.resolve(),
43 }
44 return {
45 id: 'sbx',
46 provider: 'mock',
47 capabilities: {} as SandboxHandle['capabilities'],
48 fs: {} as SandboxHandle['fs'],
49 git: {} as SandboxHandle['git'],
50 process: {
51 exec: () => Promise.reject(new Error('unused')),
52 spawn: () => Promise.resolve(spawnHandle),
53 },
54 ports: {
55 connect: (port) => Promise.resolve({ url: `http://127.0.0.1:${port}` }),
56 },
57 env: { set: () => Promise.resolve() },
58 destroy: () => Promise.resolve(),
59 }
60}
61
62async function collect(
63 stream: AsyncIterable<StreamChunk>,
64): Promise<Array<StreamChunk>> {
65 const out: Array<StreamChunk> = []
66 for await (const chunk of stream) out.push(chunk)
67 return out
68}
69
70describe('startOpencodeServerInSandbox', () => {
71 it('resolves baseUrl once the server logs readiness', async () => {
72 const sandbox = mockSandbox([
73 'booting...\n',
74 'opencode server listening on http://0.0.0.0:4096\n',
75 ])
76 const server = await startOpencodeServerInSandbox(sandbox, {
77 port: 4096,
78 cwd: '/workspace',
79 })
80 expect(server.baseUrl).toBe('http://127.0.0.1:4096')
81 await server.dispose()
82 })
83
84 it('rejects if the server exits before becoming ready', async () => {
85 const sandbox = mockSandbox(['fatal: cannot bind port\n'])
86 await expect(
87 startOpencodeServerInSandbox(sandbox, {
88 port: 4096,
89 cwd: '/workspace',
90 timeoutMs: 1000,
91 }),
92 ).rejects.toThrow(/before becoming ready/i)
93 })
94})
95
96describe('opencode adapter', () => {
97 it('requires a sandbox capability', async () => {
98 const adapter = opencodeText('anthropic/claude-sonnet-4-5')
99 const result = await collect(
100 adapter.chatStream({
101 model: 'anthropic/claude-sonnet-4-5',
102 messages: [{ role: 'user', content: 'hi' }],
103 logger: noopLogger,
104 }),
105 )
106 const err = result.find((c) => c.type === 'RUN_ERROR')
107 expect((err as { message?: string }).message).toMatch(/requires a sandbox/i)
108 })
109})