Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 createCloudflareIsolateDriver,
4 type CloudflareIsolateDriverConfig,
5} from '../src/isolate-driver'
6import type { ToolBinding } from '@tanstack/ai-code-mode'
7import type { ExecuteRequest, ExecuteResponse } from '../src/types'
8
9const WORKER_URL = 'https://code-mode.example.com'
10
11function makeBinding(
12 name: string,
13 execute: (args: unknown) => Promise<unknown>,
14): ToolBinding {
15 return {
16 name,
17 description: `${name} tool`,
18 inputSchema: { type: 'object', properties: {} },
19 execute,
20 }
21}
22
23describe('createCloudflareIsolateDriver', () => {
24 let fetchMock: ReturnType<typeof vi.fn>
25
26 beforeEach(() => {
27 fetchMock = vi.fn()
28 vi.stubGlobal('fetch', fetchMock)
29 })
30
31 afterEach(() => {
32 vi.unstubAllGlobals()
33 })
34
35 describe('createContext', () => {
36 it('returns a context with execute and dispose', async () => {
37 fetchMock.mockResolvedValueOnce({
38 ok: true,
39 json: async () =>
40 ({
41 status: 'done',
42 success: true,
43 value: 42,
44 logs: [],
45 }) as ExecuteResponse,
46 })
47
48 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
49 const context = await driver.createContext({
50 bindings: {},
51 })
52
53 expect(context).toBeDefined()
54 expect(typeof context.execute).toBe('function')
55 expect(typeof context.dispose).toBe('function')
56
57 const result = await context.execute('return 42')
58 expect(result.success).toBe(true)
59 expect(result.value).toBe(42)
60 })
61 })
62
63 describe('execute - basic execution', () => {
64 it('sends code and tools in POST body, returns value when Worker returns done', async () => {
65 fetchMock.mockResolvedValueOnce({
66 ok: true,
67 json: async () =>
68 ({
69 status: 'done',
70 success: true,
71 value: { sum: 7 },
72 logs: ['hello'],
73 }) as ExecuteResponse,
74 })
75
76 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
77 const context = await driver.createContext({ bindings: {} })
78
79 const result = await context.execute('return { sum: 3 + 4 }')
80
81 expect(result.success).toBe(true)
82 expect(result.value).toEqual({ sum: 7 })
83 expect(result.logs).toEqual(['hello'])
84
85 expect(fetchMock).toHaveBeenCalledTimes(1)
86 const [url, options] = fetchMock.mock.calls[0]!
87 expect(url).toBe(WORKER_URL)
88 expect(options.method).toBe('POST')
89 expect(options.headers['Content-Type']).toBe('application/json')
90
91 const body: ExecuteRequest = JSON.parse(options.body)
92 expect(body.code).toBe('return { sum: 3 + 4 }')
93 expect(body.tools).toEqual([])
94 expect(body.toolResults).toBeUndefined()
95 })
96
97 it('includes timeout in request when provided in config', async () => {
98 fetchMock.mockResolvedValueOnce({
99 ok: true,
100 json: async () =>
101 ({
102 status: 'done',
103 success: true,
104 value: null,
105 logs: [],
106 }) as ExecuteResponse,
107 })
108
109 const driver = createCloudflareIsolateDriver({
110 workerUrl: WORKER_URL,
111 timeout: 5000,
112 })
113 const context = await driver.createContext({
114 bindings: {},
115 timeout: 10000,
116 })
117
118 await context.execute('return 1')
119
120 const body: ExecuteRequest = JSON.parse(fetchMock.mock.calls[0]![1].body)
121 expect(body.timeout).toBe(10000)
122 })
123 })
124
125 describe('execute - authorization header', () => {
126 it('forwards Authorization header when provided in config', async () => {
127 fetchMock.mockResolvedValueOnce({
128 ok: true,
129 json: async () =>
130 ({
131 status: 'done',
132 success: true,
133 value: null,
134 logs: [],
135 }) as ExecuteResponse,
136 })
137
138 const driver = createCloudflareIsolateDriver({
139 workerUrl: WORKER_URL,
140 authorization: 'Bearer secret-token',
141 })
142 const context = await driver.createContext({ bindings: {} })
143
144 await context.execute('return 1')
145
146 expect(fetchMock).toHaveBeenCalledWith(
147 WORKER_URL,
148 expect.objectContaining({
149 headers: expect.objectContaining({
150 Authorization: 'Bearer secret-token',
151 }),
152 }),
153 )
154 })
155
156 it('does not set Authorization when not provided', async () => {
157 fetchMock.mockResolvedValueOnce({
158 ok: true,
159 json: async () =>
160 ({
161 status: 'done',
162 success: true,
163 value: null,
164 logs: [],
165 }) as ExecuteResponse,
166 })
167
168 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
169 const context = await driver.createContext({ bindings: {} })
170
171 await context.execute('return 1')
172
173 const headers = fetchMock.mock.calls[0]![1].headers
174 expect(headers).not.toHaveProperty('Authorization')
175 })
176 })
177
178 describe('execute - tool call round-trip', () => {
179 it('executes tools locally when Worker returns need_tools, then sends results back', async () => {
180 const addBinding = makeBinding('add', async (args: unknown) => {
181 const { a, b } = args as { a: number; b: number }
182 return a + b
183 })
184
185 // First response: need_tools
186 fetchMock.mockResolvedValueOnce({
187 ok: true,
188 json: async () =>
189 ({
190 status: 'need_tools',
191 toolCalls: [{ id: 'add_1', name: 'add', args: { a: 2, b: 3 } }],
192 logs: ['before add'],
193 continuationId: 'cont-1',
194 }) as ExecuteResponse,
195 })
196
197 // Second response: done with value
198 fetchMock.mockResolvedValueOnce({
199 ok: true,
200 json: async () =>
201 ({
202 status: 'done',
203 success: true,
204 value: 5,
205 logs: ['after add'],
206 }) as ExecuteResponse,
207 })
208
209 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
210 const context = await driver.createContext({
211 bindings: { add: addBinding },
212 })
213
214 const result = await context.execute(
215 'const x = await add({ a: 2, b: 3 }); return x',
216 )
217
218 expect(result.success).toBe(true)
219 expect(result.value).toBe(5)
220 expect(result.logs).toEqual(['before add', 'after add'])
221
222 expect(fetchMock).toHaveBeenCalledTimes(2)
223
224 // First request: code + tools, no toolResults
225 const body1: ExecuteRequest = JSON.parse(fetchMock.mock.calls[0]![1].body)
226 expect(body1.toolResults).toBeUndefined()
227 expect(body1.tools).toHaveLength(1)
228 expect(body1.tools[0]!.name).toBe('add')
229
230 // Second request: same code + tools + toolResults
231 const body2: ExecuteRequest = JSON.parse(fetchMock.mock.calls[1]![1].body)
232 expect(body2.toolResults).toBeDefined()
233 expect(body2.toolResults!['add_1']).toEqual({ success: true, value: 5 })
234 })
235
236 it('accumulates toolResults across rounds for sequential tool calls', async () => {
237 // Reproduces a real bug: when user code calls two tools sequentially
238 // (e.g. `await A(); await B();`), wrap-code re-runs from the start each
239 // round and re-derives sequential `tc_<idx>` ids. If the driver wipes
240 // toolResults between rounds, round 3 misses tc_0, the wrapper re-throws,
241 // and the loop ping-pongs between {tc_0} and {tc_1} until MaxRoundsExceeded.
242 const a = makeBinding('A', async () => 'a')
243 const b = makeBinding('B', async () => 'b')
244
245 // Round 1: code re-runs, throws on tc_0
246 fetchMock.mockResolvedValueOnce({
247 ok: true,
248 json: async () =>
249 ({
250 status: 'need_tools',
251 toolCalls: [{ id: 'tc_0', name: 'A', args: {} }],
252 logs: [],
253 continuationId: 'c1',
254 }) as ExecuteResponse,
255 })
256
257 // Round 2: tc_0 cached, code re-runs, throws on tc_1
258 fetchMock.mockResolvedValueOnce({
259 ok: true,
260 json: async () =>
261 ({
262 status: 'need_tools',
263 toolCalls: [{ id: 'tc_1', name: 'B', args: {} }],
264 logs: [],
265 continuationId: 'c2',
266 }) as ExecuteResponse,
267 })
268
269 // Round 3: tc_0 + tc_1 BOTH must be present, code completes
270 fetchMock.mockResolvedValueOnce({
271 ok: true,
272 json: async () =>
273 ({
274 status: 'done',
275 success: true,
276 value: 'ab',
277 logs: [],
278 }) as ExecuteResponse,
279 })
280
281 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
282 const context = await driver.createContext({
283 bindings: { A: a, B: b },
284 })
285
286 const result = await context.execute(
287 'const x = await A({}); const y = await B({}); return x + y',
288 )
289
290 expect(result.success).toBe(true)
291 expect(result.value).toBe('ab')
292 expect(fetchMock).toHaveBeenCalledTimes(3)
293
294 // Round 3 body MUST include both tc_0 and tc_1 (regression guard)
295 const body3: ExecuteRequest = JSON.parse(fetchMock.mock.calls[2]![1].body)
296 expect(body3.toolResults!['tc_0']).toEqual({ success: true, value: 'a' })
297 expect(body3.toolResults!['tc_1']).toEqual({ success: true, value: 'b' })
298 })
299
300 it('handles multiple tool calls in one round', async () => {
301 const getA = makeBinding('getA', async () => 'A')
302 const getB = makeBinding('getB', async () => 'B')
303
304 fetchMock.mockResolvedValueOnce({
305 ok: true,
306 json: async () =>
307 ({
308 status: 'need_tools',
309 toolCalls: [
310 { id: 'getA_1', name: 'getA', args: {} },
311 { id: 'getB_1', name: 'getB', args: {} },
312 ],
313 logs: [],
314 continuationId: 'c1',
315 }) as ExecuteResponse,
316 })
317
318 fetchMock.mockResolvedValueOnce({
319 ok: true,
320 json: async () =>
321 ({
322 status: 'done',
323 success: true,
324 value: 'AB',
325 logs: [],
326 }) as ExecuteResponse,
327 })
328
329 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
330 const context = await driver.createContext({
331 bindings: { getA, getB },
332 })
333
334 const result = await context.execute(
335 'return (await getA({})) + (await getB({}))',
336 )
337
338 expect(result.success).toBe(true)
339 expect(result.value).toBe('AB')
340
341 const body2: ExecuteRequest = JSON.parse(fetchMock.mock.calls[1]![1].body)
342 expect(body2.toolResults!['getA_1']).toEqual({
343 success: true,
344 value: 'A',
345 })
346 expect(body2.toolResults!['getB_1']).toEqual({
347 success: true,
348 value: 'B',
349 })
350 })
351
352 it('reports tool execution errors in toolResults', async () => {
353 const failTool = makeBinding('failTool', async () => {
354 throw new Error('Tool failed')
355 })
356
357 fetchMock.mockResolvedValueOnce({
358 ok: true,
359 json: async () =>
360 ({
361 status: 'need_tools',
362 toolCalls: [{ id: 'failTool_1', name: 'failTool', args: {} }],
363 logs: [],
364 continuationId: 'c1',
365 }) as ExecuteResponse,
366 })
367
368 fetchMock.mockResolvedValueOnce({
369 ok: true,
370 json: async () =>
371 ({
372 status: 'done',
373 success: false,
374 error: { name: 'Error', message: 'Tool call failed' },
375 logs: [],
376 }) as ExecuteResponse,
377 })
378
379 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
380 const context = await driver.createContext({
381 bindings: { failTool },
382 })
383
384 await context.execute('await failTool({})')
385
386 const body2: ExecuteRequest = JSON.parse(fetchMock.mock.calls[1]![1].body)
387 expect(body2.toolResults!['failTool_1']).toEqual({
388 success: false,
389 error: 'Tool failed',
390 })
391 })
392
393 it('returns error for unknown tool name in toolCalls', async () => {
394 fetchMock.mockResolvedValueOnce({
395 ok: true,
396 json: async () =>
397 ({
398 status: 'need_tools',
399 toolCalls: [{ id: 'unknown_1', name: 'unknownTool', args: {} }],
400 logs: [],
401 continuationId: 'c1',
402 }) as ExecuteResponse,
403 })
404
405 fetchMock.mockResolvedValueOnce({
406 ok: true,
407 json: async () =>
408 ({
409 status: 'done',
410 success: false,
411 error: { name: 'Error', message: 'Tool result not found' },
412 logs: [],
413 }) as ExecuteResponse,
414 })
415
416 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
417 const context = await driver.createContext({ bindings: {} })
418
419 await context.execute('await unknownTool({})')
420
421 const body2: ExecuteRequest = JSON.parse(fetchMock.mock.calls[1]![1].body)
422 expect(body2.toolResults!['unknown_1']).toEqual({
423 success: false,
424 error: 'Unknown tool: unknownTool',
425 })
426 })
427 })
428
429 describe('execute - max tool rounds', () => {
430 it('returns MaxRoundsExceeded when Worker keeps returning need_tools', async () => {
431 const config: CloudflareIsolateDriverConfig = {
432 workerUrl: WORKER_URL,
433 maxToolRounds: 2,
434 }
435 const driver = createCloudflareIsolateDriver(config)
436 const addBinding = makeBinding('add', async () => 1)
437
438 // Always return need_tools (simulate Worker never finishing)
439 fetchMock.mockImplementation(() =>
440 Promise.resolve({
441 ok: true,
442 json: async () =>
443 ({
444 status: 'need_tools',
445 toolCalls: [{ id: 'add_1', name: 'add', args: {} }],
446 logs: [],
447 continuationId: 'c',
448 }) as ExecuteResponse,
449 }),
450 )
451
452 const context = await driver.createContext({
453 bindings: { add: addBinding },
454 })
455
456 const result = await context.execute('await add({})')
457
458 expect(result.success).toBe(false)
459 expect(result.error?.name).toBe('MaxRoundsExceeded')
460 expect(result.error?.message).toContain('2')
461 expect(fetchMock).toHaveBeenCalledTimes(2)
462 })
463 })
464
465 describe('execute - error handling', () => {
466 it('returns WorkerError when response is not ok', async () => {
467 fetchMock.mockResolvedValueOnce({
468 ok: false,
469 status: 500,
470 text: async () => 'Internal Server Error',
471 })
472
473 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
474 const context = await driver.createContext({ bindings: {} })
475
476 const result = await context.execute('return 1')
477
478 expect(result.success).toBe(false)
479 expect(result.error?.name).toBe('WorkerError')
480 expect(result.error?.message).toContain('500')
481 expect(result.error?.message).toContain('Internal Server Error')
482 })
483
484 it('returns error when Worker returns status: error', async () => {
485 fetchMock.mockResolvedValueOnce({
486 ok: true,
487 json: async () =>
488 ({
489 status: 'error',
490 error: {
491 name: 'WorkerLoaderNotAvailable',
492 message: 'LOADER binding is not available',
493 },
494 }) as ExecuteResponse,
495 })
496
497 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
498 const context = await driver.createContext({ bindings: {} })
499
500 const result = await context.execute('return 1')
501
502 expect(result.success).toBe(false)
503 expect(result.error?.name).toBe('WorkerLoaderNotAvailable')
504 expect(result.error?.message).toContain('LOADER')
505 })
506
507 it('returns error when Worker returns status: done with success: false', async () => {
508 fetchMock.mockResolvedValueOnce({
509 ok: true,
510 json: async () =>
511 ({
512 status: 'done',
513 success: false,
514 error: {
515 name: 'SyntaxError',
516 message: 'Unexpected token',
517 stack: '...',
518 },
519 logs: [],
520 }) as ExecuteResponse,
521 })
522
523 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
524 const context = await driver.createContext({ bindings: {} })
525
526 const result = await context.execute('syntax error!!!')
527
528 expect(result.success).toBe(false)
529 expect(result.error?.name).toBe('SyntaxError')
530 expect(result.error?.message).toBe('Unexpected token')
531 })
532
533 it('returns NetworkError when fetch throws', async () => {
534 fetchMock.mockRejectedValueOnce(new Error('ECONNREFUSED'))
535
536 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
537 const context = await driver.createContext({ bindings: {} })
538
539 const result = await context.execute('return 1')
540
541 expect(result.success).toBe(false)
542 expect(result.error?.name).toBe('NetworkError')
543 expect(result.error?.message).toContain('ECONNREFUSED')
544 })
545 })
546
547 describe('dispose', () => {
548 it('execute returns DisposedError after dispose', async () => {
549 const driver = createCloudflareIsolateDriver({ workerUrl: WORKER_URL })
550 const context = await driver.createContext({ bindings: {} })
551
552 await context.dispose()
553
554 const result = await context.execute('return 1')
555
556 expect(result.success).toBe(false)
557 expect(result.error?.name).toBe('DisposedError')
558 expect(result.error?.message).toContain('disposed')
559 expect(fetchMock).not.toHaveBeenCalled()
560 })
561 })
562})