Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { z } from 'zod'
3import { toolDefinition } from '@tanstack/ai'
4import { codeModeWithSnippets } from '../src/code-mode-with-snippets'
5import { createMemorySnippetStorage } from '../src/storage/memory-storage'
6import type { AnyTextAdapter } from '@tanstack/ai'
7import type { IsolateDriver, ToolBinding } from '@tanstack/ai-code-mode'
8import type { Snippet } from '../src/types'
9
10const snippet: Snippet = {
11 id: 'id',
12 name: 'load',
13 description: 'Loads data',
14 code: 'return await external_fetchData({})',
15 inputSchema: {},
16 outputSchema: {},
17 usageHints: [],
18 dependsOn: [],
19 trustLevel: 'untrusted',
20 stats: { executions: 0, successRate: 0 },
21 createdAt: '',
22 updatedAt: '',
23}
24
25describe('codeModeWithSnippets', () => {
26 it('passes the abort signal and runtime context through snippet_* to external_* calls', async () => {
27 const fetchData = vi.fn().mockResolvedValue('ok')
28 const tool = toolDefinition({
29 name: 'fetchData',
30 description: 'Fetch data',
31 inputSchema: z.object({}),
32 }).server(fetchData)
33
34 // Each sandbox calls the first binding that its code needs:
35 // execute_typescript calls snippet_load, and the snippet calls external_fetchData.
36 const driver: IsolateDriver = {
37 createContext: async ({ bindings }) => ({
38 execute: vi.fn().mockImplementation(async () => {
39 const binding: ToolBinding | undefined =
40 bindings['snippet_load'] ?? bindings['external_fetchData']
41 return { success: true, value: await binding!.execute({}), logs: [] }
42 }),
43 dispose: async () => {},
44 }),
45 }
46
47 const { toolsRegistry } = await codeModeWithSnippets({
48 config: { driver, tools: [tool] },
49 adapter: {} as AnyTextAdapter,
50 snippets: { storage: createMemorySnippetStorage([snippet]) },
51 messages: [],
52 })
53 const controller = new AbortController()
54
55 await toolsRegistry.get('execute_typescript')!.execute!(
56 { typescriptCode: 'return await snippet_load({})' },
57 {
58 emitCustomEvent: vi.fn(),
59 abortSignal: controller.signal,
60 context: { userId: 'u1' },
61 },
62 )
63
64 expect(fetchData).toHaveBeenCalledWith(
65 {},
66 expect.objectContaining({
67 abortSignal: controller.signal,
68 context: { userId: 'u1' },
69 }),
70 )
71 })
72})