Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { createQuickJSBunIsolateDriver } from '../src/isolate-driver'
3import type { ToolBinding } from '@tanstack/ai-code-mode'
4
5function makeBinding(
6 name: string,
7 execute: (args: unknown) => Promise<unknown>,
8): ToolBinding {
9 return {
10 name,
11 description: `${name} tool`,
12 inputSchema: { type: 'object', properties: {} },
13 execute,
14 }
15}
16
17// The driver only runs under Bun (quickjs-bun is built on bun:ffi). Under
18// Node the suite is skipped, mirroring how ai-isolate-node skips when the
19// isolated-vm addon is unavailable. Run locally with: bun test ./tests
20describe.skipIf(typeof Bun === 'undefined')(
21 'createQuickJSBunIsolateDriver',
22 () => {
23 describe('createContext', () => {
24 it('returns a context with execute and dispose', async () => {
25 const driver = createQuickJSBunIsolateDriver()
26 const context = await driver.createContext({ bindings: {} })
27
28 expect(context).toBeDefined()
29 expect(typeof context.execute).toBe('function')
30 expect(typeof context.dispose).toBe('function')
31
32 const result = await context.execute('return 42')
33 expect(result.success).toBe(true)
34 expect(result.value).toBe(42)
35 await context.dispose()
36 })
37 })
38
39 describe('execute - basic execution', () => {
40 it('evaluates arithmetic and returns value', async () => {
41 const driver = createQuickJSBunIsolateDriver()
42 const context = await driver.createContext({ bindings: {} })
43
44 const result = await context.execute('return 3 + 4')
45
46 expect(result.success).toBe(true)
47 expect(result.value).toBe(7)
48 await context.dispose()
49 })
50
51 it('evaluates string operations', async () => {
52 const driver = createQuickJSBunIsolateDriver()
53 const context = await driver.createContext({ bindings: {} })
54
55 const result = await context.execute('return "hello" + " " + "world"')
56
57 expect(result.success).toBe(true)
58 expect(result.value).toBe('hello world')
59 await context.dispose()
60 })
61
62 it('evaluates async code and returns value', async () => {
63 const driver = createQuickJSBunIsolateDriver()
64 const context = await driver.createContext({ bindings: {} })
65
66 const result = await context.execute(`
67 const x = await Promise.resolve(10);
68 return x + 2;
69 `)
70
71 expect(result.success).toBe(true)
72 expect(result.value).toBe(12)
73 await context.dispose()
74 })
75
76 it('returns object and array values', async () => {
77 const driver = createQuickJSBunIsolateDriver()
78 const context = await driver.createContext({ bindings: {} })
79
80 const result = await context.execute('return { a: 1, b: [2, 3] }')
81
82 expect(result.success).toBe(true)
83 expect(result.value).toEqual({ a: 1, b: [2, 3] })
84 await context.dispose()
85 })
86
87 it('returns undefined when code returns nothing', async () => {
88 const driver = createQuickJSBunIsolateDriver()
89 const context = await driver.createContext({ bindings: {} })
90
91 const result = await context.execute('const x = 1;')
92
93 expect(result.success).toBe(true)
94 expect(result.value).toBeUndefined()
95 await context.dispose()
96 })
97 })
98
99 describe('execute - tool bindings', () => {
100 it('injects tool and executes tool call', async () => {
101 const add = makeBinding('add', async (args: unknown) => {
102 const { a, b } = args as { a: number; b: number }
103 return a + b
104 })
105
106 const driver = createQuickJSBunIsolateDriver()
107 const context = await driver.createContext({
108 bindings: { add },
109 })
110
111 const result = await context.execute(`
112 const sum = await add({ a: 2, b: 3 });
113 return sum;
114 `)
115
116 expect(result.success).toBe(true)
117 expect(result.value).toBe(5)
118 await context.dispose()
119 })
120
121 it('supports multiple tools in one execution', async () => {
122 const getA = makeBinding('getA', async () => 'A')
123 const getB = makeBinding('getB', async () => 'B')
124
125 const driver = createQuickJSBunIsolateDriver()
126 const context = await driver.createContext({
127 bindings: { getA, getB },
128 })
129
130 const result = await context.execute(`
131 return (await getA({})) + (await getB({}));
132 `)
133
134 expect(result.success).toBe(true)
135 expect(result.value).toBe('AB')
136 await context.dispose()
137 })
138
139 it('supports concurrent tool calls via Promise.all', async () => {
140 const double = makeBinding('double', async (args: unknown) => {
141 const { n } = args as { n: number }
142 await new Promise((resolve) => setTimeout(resolve, 10))
143 return n * 2
144 })
145
146 const driver = createQuickJSBunIsolateDriver()
147 const context = await driver.createContext({
148 bindings: { double },
149 })
150
151 const result = await context.execute(`
152 const [a, b, c] = await Promise.all([
153 double({ n: 1 }),
154 double({ n: 2 }),
155 double({ n: 3 }),
156 ]);
157 return a + b + c;
158 `)
159
160 expect(result.success).toBe(true)
161 expect(result.value).toBe(12)
162 await context.dispose()
163 })
164
165 it('passes empty input when a tool is called without arguments', async () => {
166 let received: unknown = 'unset'
167 const probe = makeBinding('probe', async (args: unknown) => {
168 received = args
169 return 'ok'
170 })
171
172 const driver = createQuickJSBunIsolateDriver()
173 const context = await driver.createContext({
174 bindings: { probe },
175 })
176
177 const result = await context.execute('return await probe()')
178
179 expect(result.success).toBe(true)
180 expect(result.value).toBe('ok')
181 expect(received).toEqual({})
182 await context.dispose()
183 })
184
185 it('returns undefined for tools that resolve with undefined', async () => {
186 const noop = makeBinding('noop', async () => undefined)
187
188 const driver = createQuickJSBunIsolateDriver()
189 const context = await driver.createContext({
190 bindings: { noop },
191 })
192
193 const result = await context.execute('return typeof (await noop({}))')
194
195 expect(result.success).toBe(true)
196 expect(result.value).toBe('undefined')
197 await context.dispose()
198 })
199
200 it('surfaces tool execution errors', async () => {
201 const failTool = makeBinding('failTool', async () => {
202 throw new Error('Tool failed')
203 })
204
205 const driver = createQuickJSBunIsolateDriver()
206 const context = await driver.createContext({
207 bindings: { failTool },
208 })
209
210 const result = await context.execute('return await failTool({})')
211
212 expect(result.success).toBe(false)
213 expect(result.error?.message).toContain('Tool failed')
214 await context.dispose()
215 })
216
217 it('lets sandbox code catch tool errors', async () => {
218 const failTool = makeBinding('failTool', async () => {
219 throw new Error('Tool failed')
220 })
221
222 const driver = createQuickJSBunIsolateDriver()
223 const context = await driver.createContext({
224 bindings: { failTool },
225 })
226
227 const result = await context.execute(`
228 try {
229 await failTool({});
230 return 'no error';
231 } catch (e) {
232 return 'caught: ' + e.message;
233 }
234 `)
235
236 expect(result.success).toBe(true)
237 expect(result.value).toBe('caught: Tool failed')
238 await context.dispose()
239 })
240 })
241
242 describe('execute - timeout', () => {
243 it('returns timeout error when code runs too long', async () => {
244 const driver = createQuickJSBunIsolateDriver({ timeout: 50 })
245 const context = await driver.createContext({
246 bindings: {},
247 timeout: 50,
248 })
249
250 // Busy loop that should trigger interrupt handler
251 const result = await context.execute(`
252 const start = Date.now();
253 while (Date.now() - start < 500) {
254 // spin
255 }
256 return 1;
257 `)
258
259 expect(result.success).toBe(false)
260 expect(result.error?.name).toBe('TimeoutError')
261 await context.dispose()
262 })
263
264 it('returns timeout error when a tool call outlives the deadline', async () => {
265 const slow = makeBinding('slow', async () => {
266 await new Promise((resolve) => setTimeout(resolve, 500))
267 return 'too late'
268 })
269
270 const driver = createQuickJSBunIsolateDriver({ timeout: 50 })
271 const context = await driver.createContext({
272 bindings: { slow },
273 timeout: 50,
274 })
275
276 const start = Date.now()
277 const result = await context.execute('return await slow({})')
278 const elapsed = Date.now() - start
279
280 expect(result.success).toBe(false)
281 expect(result.error?.name).toBe('TimeoutError')
282 expect(elapsed).toBeLessThan(5000)
283 await context.dispose()
284 })
285
286 it('fails fast for promises no host work will resolve', async () => {
287 const driver = createQuickJSBunIsolateDriver({ timeout: 5000 })
288 const context = await driver.createContext({ bindings: {} })
289
290 const start = Date.now()
291 const result = await context.execute(
292 'return await new Promise(() => {})',
293 )
294 const elapsed = Date.now() - start
295
296 expect(result.success).toBe(false)
297 expect(result.error?.message).toContain('no host work')
298 // Should not wait for the full 5s timeout
299 expect(elapsed).toBeLessThan(1000)
300 await context.dispose()
301 })
302
303 it('does not leak a timed-out run’s queued jobs into the next execution', async () => {
304 const driver = createQuickJSBunIsolateDriver({ timeout: 50 })
305 const context = await driver.createContext({
306 bindings: {},
307 timeout: 50,
308 })
309
310 // Queue a microtask, then busy-loop past the deadline so the interrupt
311 // fires before the reaction can drain. Its console.log stays queued on
312 // the runtime's job queue.
313 const first = await context.execute(`
314 Promise.resolve().then(() => console.log('STALE_FROM_FIRST_RUN'));
315 const start = Date.now();
316 while (Date.now() - start < 500) { /* spin */ }
317 return 1;
318 `)
319 expect(first.success).toBe(false)
320 expect(first.error?.name).toBe('TimeoutError')
321
322 // Reusing the context must not run the previous run's stale reaction as
323 // part of — nor attribute its output to — this execution.
324 const second = await context.execute(
325 `console.log('SECOND_RUN'); return 2;`,
326 )
327 expect(second.success).toBe(true)
328 expect(second.value).toBe(2)
329 expect(second.logs).toContain('SECOND_RUN')
330 expect(second.logs ?? []).not.toContain('STALE_FROM_FIRST_RUN')
331 await context.dispose()
332 })
333 })
334
335 describe('execute - error handling', () => {
336 it('returns error for syntax errors', async () => {
337 const driver = createQuickJSBunIsolateDriver()
338 const context = await driver.createContext({ bindings: {} })
339
340 const result = await context.execute('syntax error!!!')
341
342 expect(result.success).toBe(false)
343 expect(result.error?.message).toBeDefined()
344 await context.dispose()
345 })
346
347 it('returns error for runtime errors', async () => {
348 const driver = createQuickJSBunIsolateDriver()
349 const context = await driver.createContext({ bindings: {} })
350
351 const result = await context.execute('throw new Error("oops")')
352
353 expect(result.success).toBe(false)
354 expect(result.error?.message).toContain('oops')
355 await context.dispose()
356 })
357
358 it('includes captured logs in failure results', async () => {
359 const driver = createQuickJSBunIsolateDriver()
360 const context = await driver.createContext({ bindings: {} })
361
362 const result = await context.execute(`
363 console.log("before failure");
364 throw new Error("oops");
365 `)
366
367 expect(result.success).toBe(false)
368 expect(result.logs).toContain('before failure')
369 await context.dispose()
370 })
371 })
372
373 describe('execute - console capture', () => {
374 it('captures console.log in logs', async () => {
375 const driver = createQuickJSBunIsolateDriver()
376 const context = await driver.createContext({ bindings: {} })
377
378 const result = await context.execute(`
379 console.log("hello");
380 console.log("world");
381 return 1;
382 `)
383
384 expect(result.success).toBe(true)
385 expect(result.logs).toContain('hello')
386 expect(result.logs).toContain('world')
387 await context.dispose()
388 })
389
390 it('captures console.error with ERROR prefix', async () => {
391 const driver = createQuickJSBunIsolateDriver()
392 const context = await driver.createContext({ bindings: {} })
393
394 const result = await context.execute(`
395 console.error("fail");
396 return 1;
397 `)
398
399 expect(result.success).toBe(true)
400 expect(result.logs?.some((l) => l.includes('fail'))).toBe(true)
401 expect(result.logs).toContain('ERROR: fail')
402 await context.dispose()
403 })
404
405 it('captures console.warn and console.info with prefixes', async () => {
406 const driver = createQuickJSBunIsolateDriver()
407 const context = await driver.createContext({ bindings: {} })
408
409 const result = await context.execute(`
410 console.warn("careful");
411 console.info("fyi");
412 return 1;
413 `)
414
415 expect(result.success).toBe(true)
416 expect(result.logs).toContain('WARN: careful')
417 expect(result.logs).toContain('INFO: fyi')
418 await context.dispose()
419 })
420 })
421
422 describe('dispose', () => {
423 it('execute returns DisposedError after dispose', async () => {
424 const driver = createQuickJSBunIsolateDriver()
425 const context = await driver.createContext({ bindings: {} })
426
427 await context.dispose()
428
429 const result = await context.execute('return 1')
430
431 expect(result.success).toBe(false)
432 expect(result.error?.name).toBe('DisposedError')
433 expect(result.error?.message).toContain('disposed')
434 })
435
436 it('dispose is idempotent', async () => {
437 const driver = createQuickJSBunIsolateDriver()
438 const context = await driver.createContext({ bindings: {} })
439
440 await context.dispose()
441 await expect(context.dispose()).resolves.toBeUndefined()
442 })
443 })
444
445 describe('memory isolation', () => {
446 it('contexts do not share state', async () => {
447 const driver = createQuickJSBunIsolateDriver()
448 const ctx1 = await driver.createContext({ bindings: {} })
449 const ctx2 = await driver.createContext({ bindings: {} })
450
451 await ctx1.execute('globalThis.__secret = 100; return 1')
452 const result2 = await ctx2.execute('return typeof globalThis.__secret')
453
454 expect(result2.success).toBe(true)
455 expect(result2.value).toBe('undefined')
456
457 await ctx1.dispose()
458 await ctx2.dispose()
459 })
460 })
461
462 describe('memoryLimit config', () => {
463 it('accepts memoryLimit via createContext and runs successfully', async () => {
464 const driver = createQuickJSBunIsolateDriver({ memoryLimit: 64 })
465 const context = await driver.createContext({
466 bindings: {},
467 memoryLimit: 64,
468 })
469
470 const result = await context.execute('return 1 + 1')
471
472 expect(result.success).toBe(true)
473 expect(result.value).toBe(2)
474 await context.dispose()
475 })
476
477 it('returns MemoryLimitError when allocation exceeds limit (does not crash)', async () => {
478 const driver = createQuickJSBunIsolateDriver({ memoryLimit: 1 })
479 const context = await driver.createContext({
480 bindings: {},
481 memoryLimit: 1,
482 })
483
484 const result = await context.execute(
485 `return "x".repeat(8 * 1024 * 1024);`,
486 )
487
488 expect(result.success).toBe(false)
489 expect(result.error?.name).toBe('MemoryLimitError')
490 expect(result.error?.message).toContain('memory limit')
491 })
492
493 it('returns MemoryLimitError when the heap is fully exhausted', async () => {
494 const driver = createQuickJSBunIsolateDriver({ memoryLimit: 1 })
495 const context = await driver.createContext({
496 bindings: {},
497 memoryLimit: 1,
498 })
499
500 const result = await context.execute(`
501 const items = [];
502 while (true) items.push(new Array(1000).fill('x').join(''));
503 `)
504
505 expect(result.success).toBe(false)
506 expect(result.error?.name).toBe('MemoryLimitError')
507 expect(result.error?.message).toContain('memory limit')
508 })
509
510 it('dispose is safe after memory limit error', async () => {
511 const driver = createQuickJSBunIsolateDriver({ memoryLimit: 1 })
512 const context = await driver.createContext({
513 bindings: {},
514 memoryLimit: 1,
515 })
516
517 await context.execute(`return "x".repeat(8 * 1024 * 1024);`)
518
519 await expect(context.dispose()).resolves.toBeUndefined()
520 })
521 })
522
523 describe('maxStackSize config', () => {
524 it('returns StackOverflowError for deep recursion when stack is small', async () => {
525 const driver = createQuickJSBunIsolateDriver({
526 maxStackSize: 32 * 1024,
527 timeout: 30000,
528 })
529 const context = await driver.createContext({ bindings: {} })
530
531 const result = await context.execute(`
532 function f(n) {
533 if (n <= 0) return 0;
534 return 1 + f(n - 1);
535 }
536 return f(200000);
537 `)
538
539 expect(result.success).toBe(false)
540 expect(result.error?.name).toBe('StackOverflowError')
541 expect(result.error?.message).toContain('stack')
542 await context.dispose()
543 })
544 })
545
546 describe('execute after fatal memory limit', () => {
547 it('returns DisposedError on subsequent execute after OOM', async () => {
548 const driver = createQuickJSBunIsolateDriver({ memoryLimit: 1 })
549 const context = await driver.createContext({
550 bindings: {},
551 memoryLimit: 1,
552 })
553
554 const first = await context.execute(
555 `return "x".repeat(8 * 1024 * 1024);`,
556 )
557 expect(first.success).toBe(false)
558 expect(first.error?.name).toBe('MemoryLimitError')
559
560 const second = await context.execute('return 42')
561 expect(second.success).toBe(false)
562 expect(second.error?.name).toBe('DisposedError')
563 expect(second.error?.message).toContain('disposed')
564 })
565 })
566
567 describe('execution serialization', () => {
568 it('serializes concurrent executes on the same context', async () => {
569 const driver = createQuickJSBunIsolateDriver()
570 const context = await driver.createContext({ bindings: {} })
571
572 const [first, second] = await Promise.all([
573 context.execute(
574 'globalThis.__order = (globalThis.__order ?? "") + "a"; return globalThis.__order',
575 ),
576 context.execute(
577 'globalThis.__order = (globalThis.__order ?? "") + "b"; return globalThis.__order',
578 ),
579 ])
580
581 expect(first.success).toBe(true)
582 expect(second.success).toBe(true)
583 expect(first.value).toBe('a')
584 expect(second.value).toBe('ab')
585 await context.dispose()
586 })
587 })
588
589 describe('console capture - non-string arguments', () => {
590 it('coerces numbers, booleans, objects, and mixed args', async () => {
591 const driver = createQuickJSBunIsolateDriver()
592 const context = await driver.createContext({ bindings: {} })
593
594 const result = await context.execute(`
595 console.log(42);
596 console.log(true);
597 console.log({ a: 1 });
598 console.log('count:', 3);
599 console.log(null, undefined);
600 return 'done';
601 `)
602
603 expect(result.success).toBe(true)
604 expect(result.value).toBe('done')
605 expect(result.logs).toContain('42')
606 expect(result.logs).toContain('true')
607 expect(result.logs).toContain('[object Object]')
608 expect(result.logs).toContain('count: 3')
609 expect(result.logs).toContain('null undefined')
610 await context.dispose()
611 })
612
613 it('does not let a throwing toString abort the execution', async () => {
614 const driver = createQuickJSBunIsolateDriver()
615 const context = await driver.createContext({ bindings: {} })
616
617 const result = await context.execute(`
618 const evil = { toString() { throw new Error('nope') } };
619 console.log(evil);
620 return 'survived';
621 `)
622
623 expect(result.success).toBe(true)
624 expect(result.value).toBe('survived')
625 expect(result.logs).toContain('[unprintable]')
626 await context.dispose()
627 })
628 })
629
630 describe('console capture - log buffer cap', () => {
631 it('truncates runaway log output instead of growing unbounded', async () => {
632 const driver = createQuickJSBunIsolateDriver({ timeout: 10000 })
633 const context = await driver.createContext({ bindings: {} })
634
635 const result = await context.execute(`
636 for (let i = 0; i < 100000; i++) console.log('x'.repeat(1000));
637 return 'done';
638 `)
639
640 expect(result.success).toBe(true)
641 expect(result.logs).toContain('[log output truncated]')
642 // Cap is 1,000,000 bytes; allow generous slack for the marker.
643 const totalBytes = (result.logs ?? []).reduce(
644 (sum, line) => sum + line.length,
645 0,
646 )
647 expect(totalBytes).toBeLessThan(1_100_000)
648 await context.dispose()
649 })
650 })
651
652 describe('maxToolCalls config', () => {
653 it('throws inside the sandbox once the tool-call budget is exhausted', async () => {
654 const ping = makeBinding('ping', async () => 'pong')
655 const driver = createQuickJSBunIsolateDriver({ maxToolCalls: 3 })
656 const context = await driver.createContext({ bindings: { ping } })
657
658 const result = await context.execute(`
659 let calls = 0;
660 try {
661 for (let i = 0; i < 100; i++) { await ping({}); calls++; }
662 } catch (e) {
663 return { calls, error: e.message };
664 }
665 return { calls, error: null };
666 `)
667
668 expect(result.success).toBe(true)
669 const value = result.value as { calls: number; error: string | null }
670 expect(value.calls).toBe(3)
671 expect(value.error).toContain('maximum of 3 tool calls')
672 await context.dispose()
673 })
674 })
675
676 describe('tool result exceeding the memory limit', () => {
677 it('fails with a normalized error and no unhandled rejection', async () => {
678 const onRejection = (reason: unknown) => {
679 throw reason instanceof Error ? reason : new Error(String(reason))
680 }
681 process.on('unhandledRejection', onRejection)
682 try {
683 const huge = makeBinding('huge', async () =>
684 'y'.repeat(16 * 1024 * 1024),
685 )
686 const driver = createQuickJSBunIsolateDriver({ memoryLimit: 2 })
687 const context = await driver.createContext({
688 bindings: { huge },
689 memoryLimit: 2,
690 })
691
692 const result = await context.execute('return await huge({})')
693
694 expect(result.success).toBe(false)
695 expect(result.error?.name).toBe('MemoryLimitError')
696
697 // The VM was released as fatal; the next execute is DisposedError.
698 const next = await context.execute('return 1')
699 expect(next.error?.name).toBe('DisposedError')
700
701 // Give any stray rejection a tick to surface before we detach.
702 await new Promise((resolve) => setTimeout(resolve, 50))
703 } finally {
704 process.off('unhandledRejection', onRejection)
705 }
706 })
707 })
708
709 describe('error normalization - thrown values', () => {
710 it('preserves the message of a thrown plain object', async () => {
711 const driver = createQuickJSBunIsolateDriver()
712 const context = await driver.createContext({ bindings: {} })
713
714 const result = await context.execute(
715 `throw { name: 'CustomError', message: 'custom obj' }`,
716 )
717
718 expect(result.success).toBe(false)
719 expect(result.error?.message).toBe('custom obj')
720 expect(result.error?.name).toBe('CustomError')
721 await context.dispose()
722 })
723
724 it('preserves a thrown string', async () => {
725 const driver = createQuickJSBunIsolateDriver()
726 const context = await driver.createContext({ bindings: {} })
727
728 const result = await context.execute(`throw 'bare string'`)
729
730 expect(result.success).toBe(false)
731 expect(result.error?.message).toBe('bare string')
732 await context.dispose()
733 })
734 })
735
736 describe('context reuse after non-fatal timeout', () => {
737 it('remains usable after a timed-out execution', async () => {
738 const driver = createQuickJSBunIsolateDriver({ timeout: 50 })
739 const context = await driver.createContext({
740 bindings: {},
741 timeout: 50,
742 })
743
744 const timedOut = await context.execute('while (true) {}')
745 expect(timedOut.success).toBe(false)
746 expect(timedOut.error?.name).toBe('TimeoutError')
747
748 const ok = await context.execute('return 7')
749 expect(ok.success).toBe(true)
750 expect(ok.value).toBe(7)
751 await context.dispose()
752 })
753 })
754 },
755)
756
757// This part of the contract is observable on Node.js (where bun:ffi is
758// unavailable), so it runs in regular CI.
759describe.skipIf(typeof Bun !== 'undefined')(
760 'createQuickJSBunIsolateDriver on Node.js',
761 () => {
762 it('rejects createContext with a descriptive runtime error', async () => {
763 const driver = createQuickJSBunIsolateDriver()
764
765 await expect(driver.createContext({ bindings: {} })).rejects.toThrow(
766 /requires the Bun runtime/,
767 )
768 })
769 },
770)