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

text-adapter.test.ts

318 lines12.6 KB

1/**
2 * Deterministic test of the in-sandbox Claude Code adapter.
3 *
4 * Instead of the real `claude` CLI (nondeterministic, needs an API key — see
5 * the gated live smoke in testing/e2e), this runs a FAKE agent CLI: a tiny node
6 * script that reads the prompt from stdin and emits canned `stream-json`
7 * messages on stdout, exactly as `claude -p --output-format stream-json` would.
8 * It runs inside a real local-process sandbox, exercising the full
9 * spawn → stdout NDJSON → translate → StreamChunk path.
10 */
11import { afterAll, describe, expect, it } from 'vitest'
12import * as fsp from 'node:fs/promises'
13import * as os from 'node:os'
14import * as path from 'node:path'
15import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
16import { SandboxCapability } from '@tanstack/ai-sandbox'
17import { claudeCodeText } from '../src/index'
18import type { InternalLogger } from '@tanstack/ai/adapter-internals'
19import type { AdapterYieldChunk, CapabilityContext } from '@tanstack/ai'
20import type { SandboxHandle } from '@tanstack/ai-sandbox'
21​
22const baseDir = path.join(os.tmpdir(), `tanstack-ai-cc-test-${Date.now()}`)
23const provider = localProcessSandbox({ baseDir, removeOnDestroy: true })
24​
25afterAll(async () => {
26 await fsp.rm(baseDir, { recursive: true, force: true })
27})
28​
29// A stand-in for the `claude` CLI: ignores its flags, reads the prompt from
30// stdin, then emits stream-json (system/init → assistant text → result).
31const FAKE_CLAUDE = [
32 `let input = ''`,
33 `process.stdin.on('data', (d) => { input += d })`,
34 `process.stdin.on('end', () => {`,
35 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
36 ` w({ type: 'system', subtype: 'init', session_id: 'sess-abc', model: 'haiku', tools: [] })`,
37 ` w({ type: 'stream_event', event: { type: 'message_start', message: { id: 'msg-1' } }, parent_tool_use_id: null })`,
38 ` w({ type: 'stream_event', event: { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu-1', name: 'Read' } }, parent_tool_use_id: null })`,
39 ` w({ type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"file":' } }, parent_tool_use_id: null })`,
40 ` w({ type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '"a.ts"}' } }, parent_tool_use_id: null })`,
41 ` w({ type: 'stream_event', event: { type: 'content_block_stop', index: 0 }, parent_tool_use_id: null })`,
42 ` w({ type: 'assistant', message: { id: 'msg-1', content: [{ type: 'tool_use', id: 'toolu-1', name: 'Read', input: { file: 'a.ts' } }] }, parent_tool_use_id: null })`,
43 ` w({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu-1', content: 'file contents' }] }, parent_tool_use_id: null })`,
44 // Echo IS_SANDBOX so the test can assert local-process does not set it.
45 ` w({ type: 'assistant', message: { id: 'msg-2', content: [{ type: 'text', text: 'pong IS_SANDBOX=' + process.env.IS_SANDBOX }] }, parent_tool_use_id: null })`,
46 ` w({ type: 'result', subtype: 'success', result: 'pong', usage: { input_tokens: 1, output_tokens: 1 } })`,
47 `})`,
48].join('\n')
49​
50const noopLogger = {
51 request: () => {},
52 provider: () => {},
53 errors: () => {},
54 agentLoop: () => {},
55 warnings: () => {},
56 debug: () => {},
57} as unknown as InternalLogger
58​
59/** Build a capability context that hands the adapter the given sandbox. */
60function capabilityContextWith(handle: SandboxHandle): CapabilityContext {
61 const [, provideSandbox] = SandboxCapability
62 const ctx = {
63 capabilities: { markProvided: () => {}, has: () => true },
64 } as unknown as CapabilityContext
65 provideSandbox(ctx, handle)
66 return ctx
68​
69async function collect(
70 stream: AsyncIterable<AdapterYieldChunk>,
71): Promise<Array<AdapterYieldChunk>> {
72 const out: Array<AdapterYieldChunk> = []
73 for await (const chunk of stream) out.push(chunk)
74 return out
76​
77describe('claude-code in-sandbox adapter', () => {
78 it('spawns the agent CLI in the sandbox and streams translated events', async () => {
79 const sbx = await provider.create({})
80 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
81​
82 const adapter = claudeCodeText('haiku', {
83 // Relative executable + cwd=/workspace (mapped to the sandbox root).
84 claudeExecutable: 'node fake-claude.mjs',
85 emitDiff: false,
86 })
87​
88 const chunks = await collect(
89 adapter.chatStream({
90 threadId: 'thread-1',
91 model: 'haiku',
92 messages: [{ role: 'user', content: 'say pong' }],
93 logger: noopLogger,
94 capabilities: capabilityContextWith(sbx),
95 }),
96 )
97​
98 const types = chunks.map((c) => c.type as string)
99 expect(types[0]).toBe('RUN_STARTED')
100​
101 const sessionEvent = chunks.find(
102 (c) =>
103 c.type === 'CUSTOM' &&
104 (c as { name?: string }).name === 'claude-code.session-id',
105 )
106 expect(sessionEvent).toBeDefined()
107 expect(
108 (sessionEvent as { value: { sessionId: string } }).value.sessionId,
109 ).toBe('sess-abc')
110​
111 const text = chunks
112 .filter((c) => c.type === 'TEXT_MESSAGE_CONTENT')
113 .map((c) => (c as { delta?: string }).delta ?? '')
114 .join('')
115 expect(text).toContain('pong')
116 // Isolated sandboxes set IS_SANDBOX=1. local-process must not.
117 expect(text).toContain('IS_SANDBOX=undefined')
118​
119 const args = chunks.filter((c) => c.type === 'TOOL_CALL_ARGS')
120 expect(args.map((chunk) => chunk.delta)).toEqual(['{"file":', '"a.ts"}'])
121 expect(args.every((chunk) => !('args' in chunk))).toBe(true)
122​
123 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
124​
125 await sbx.destroy()
126 })
127​
128 it('requires a sandbox capability', async () => {
129 const adapter = claudeCodeText('haiku', { emitDiff: false })
130 const chunks = await collect(
131 adapter.chatStream({
132 threadId: 'thread-1',
133 model: 'haiku',
134 messages: [{ role: 'user', content: 'hi' }],
135 logger: noopLogger,
136 // no capabilities provided
137 }),
138 )
139 const err = chunks.find((c) => c.type === 'RUN_ERROR')
140 expect(err).toBeDefined()
141 expect((err as { message?: string }).message).toMatch(/requires a sandbox/i)
142 })
143​
144 it('bridges chat()-provided tools (starts + tears down the MCP bridge)', async () => {
145 const sbx = await provider.create({})
146 await sbx.fs.write('/workspace/fake-claude.mjs', FAKE_CLAUDE)
147 const adapter = claudeCodeText('haiku', {
148 claudeExecutable: 'node fake-claude.mjs',
149 streamPartials: false,
150 emitDiff: false,
151 })
152 // The fake claude ignores the injected --mcp-config; this checks that
153 // passing tools no longer errors and the bridge lifecycle is clean.
154 const chunks = await collect(
155 adapter.chatStream({
156 threadId: 'thread-1',
157 model: 'haiku',
158 messages: [{ role: 'user', content: 'say pong' }],
159 logger: noopLogger,
160 capabilities: capabilityContextWith(sbx),
161 tools: [
162 {
163 name: 'getTime',
164 description: 'x',
165 inputSchema: { type: 'object', properties: {} },
166 execute: () => Promise.resolve('now'),
167 } as never,
168 ],
169 }),
170 )
171 expect(chunks.some((c) => c.type === 'RUN_ERROR')).toBe(false)
172 expect(chunks.some((c) => c.type === 'RUN_FINISHED')).toBe(true)
173 await sbx.destroy()
174 })
175​
176 it('passes --json-schema and emits structured-output.complete', async () => {
177 const fake = [
178 `import { writeFileSync } from 'node:fs'`,
179 `writeFileSync('argv.txt', process.argv.slice(2).join(' '))`,
180 `let input = ''`,
181 `process.stdin.on('data', (d) => { input += d })`,
182 `process.stdin.on('end', () => {`,
183 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
184 ` w({ type: 'system', subtype: 'init', session_id: 'sess-so', model: 'haiku', tools: [] })`,
185 ` w({ type: 'assistant', message: { id: 'msg-1', content: [{ type: 'text', text: 'looking' }] }, parent_tool_use_id: null })`,
186 ` w({ type: 'result', subtype: 'success', result: 'done', structured_output: { summary: 'ok' }, usage: { input_tokens: 1, output_tokens: 1 } })`,
187 `})`,
188 ].join('\n')
189​
190 const sbx = await provider.create({})
191 await sbx.fs.write('/workspace/fake-claude.mjs', fake)
192​
193 const adapter = claudeCodeText('haiku', {
194 claudeExecutable: 'node fake-claude.mjs',
195 streamPartials: false,
196 emitDiff: false,
197 settingSources: ['project', 'local'],
198 })
199​
200 const chunks = await collect(
201 adapter.chatStream({
202 threadId: 'thread-1',
203 model: 'haiku',
204 messages: [{ role: 'user', content: 'summarize' }],
205 logger: noopLogger,
206 capabilities: capabilityContextWith(sbx),
207 outputSchema: {
208 type: 'object',
209 properties: { summary: { type: 'string' } },
210 required: ['summary'],
211 },
212 }),
213 )
214​
215 const argv = await sbx.fs.read('/workspace/argv.txt')
216 expect(argv).not.toContain('--bare')
217 expect(argv).toContain('--setting-sources')
218 expect(argv).toContain('project,local')
219 expect(argv).toContain('--json-schema')
220 expect(argv).toContain('"type":"object"')
221 expect(argv).toContain('"summary"')
222 expect(argv).not.toContain('tanstack-output-schema')
223 expect(argv).not.toMatch(/--json-schema\s+\./)
224​
225 const complete = chunks.find(
226 (c) => c.type === 'CUSTOM' && c.name === 'structured-output.complete',
227 )
228 expect(complete).toBeDefined()
229 if (complete?.type === 'CUSTOM') {
230 expect(complete.value).toEqual(
231 expect.objectContaining({ object: { summary: 'ok' } }),
232 )
233 }
234​
235 await sbx.destroy()
236 })
237​
238 it('uses project as the default setting source', async () => {
239 const fake = [
240 `import { writeFileSync } from 'node:fs'`,
241 `writeFileSync('argv.txt', process.argv.slice(2).join(' '))`,
242 `let input = ''`,
243 `process.stdin.on('data', (d) => { input += d })`,
244 `process.stdin.on('end', () => {`,
245 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
246 ` w({ type: 'system', subtype: 'init', session_id: 'sess-default', model: 'haiku', tools: [] })`,
247 ` w({ type: 'result', subtype: 'success', result: 'ok', usage: { input_tokens: 1, output_tokens: 1 } })`,
248 `})`,
249 ].join('\n')
250 const sbx = await provider.create({})
251 await sbx.fs.write('/workspace/fake-claude.mjs', fake)
252​
253 try {
254 const adapter = claudeCodeText('haiku', {
255 claudeExecutable: 'node fake-claude.mjs',
256 streamPartials: false,
257 emitDiff: false,
258 })
259 await collect(
260 adapter.chatStream({
261 threadId: 'thread-1',
262 model: 'haiku',
263 messages: [{ role: 'user', content: 'hi' }],
264 logger: noopLogger,
265 capabilities: capabilityContextWith(sbx),
266 }),
267 )
268​
269 expect(await sbx.fs.read('/workspace/argv.txt')).toMatch(
270 /--setting-sources project(?:\s|$)/,
271 )
272 } finally {
273 await sbx.destroy()
274 }
275 })
276​
277 it('copies ANTHROPIC_API_KEY from the host process into the CLI env', async () => {
278 const fake = [
279 `import { writeFileSync } from 'node:fs'`,
280 `writeFileSync('auth-probe.txt', process.env.ANTHROPIC_API_KEY ? 'set' : 'missing')`,
281 `let input = ''`,
282 `process.stdin.on('data', (d) => { input += d })`,
283 `process.stdin.on('end', () => {`,
284 ` const w = (o) => process.stdout.write(JSON.stringify(o) + '\\n')`,
285 ` w({ type: 'system', subtype: 'init', session_id: 'sess-auth', model: 'haiku', tools: [] })`,
286 ` w({ type: 'assistant', message: { id: 'msg-1', content: [{ type: 'text', text: 'ok' }] }, parent_tool_use_id: null })`,
287 ` w({ type: 'result', subtype: 'success', result: 'ok', usage: { input_tokens: 1, output_tokens: 1 } })`,
288 `})`,
289 ].join('\n')
290​
291 const previous = process.env.ANTHROPIC_API_KEY
292 process.env.ANTHROPIC_API_KEY = 'sk-test-not-a-real-key'
293 const sbx = await provider.create({})
294 try {
295 await sbx.fs.write('/workspace/fake-claude.mjs', fake)
296 const adapter = claudeCodeText('haiku', {
297 claudeExecutable: 'node fake-claude.mjs',
298 streamPartials: false,
299 emitDiff: false,
300 })
301 const chunks = await collect(
302 adapter.chatStream({
303 threadId: 'thread-1',
304 model: 'haiku',
305 messages: [{ role: 'user', content: 'hi' }],
306 logger: noopLogger,
307 capabilities: capabilityContextWith(sbx),
308 }),
309 )
310 expect(chunks.some((c) => c.type === 'RUN_ERROR')).toBe(false)
311 expect(await sbx.fs.read('/workspace/auth-probe.txt')).toBe('set')
312 } finally {
313 if (previous === undefined) delete process.env.ANTHROPIC_API_KEY
314 else process.env.ANTHROPIC_API_KEY = previous
315 await sbx.destroy()
316 }
317 })
318})