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

code-mode-with-snippets.test.ts

75 lines2.4 KB

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: '',
24​
25describe('codeModeWithSnippets', () => {
26 it('passes the abort signal, thread id, 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 threadId: 'thread-1',
49 config: { driver, tools: [tool] },
50 adapter: {} as AnyTextAdapter,
51 snippets: { storage: createMemorySnippetStorage([snippet]) },
52 messages: [],
53 })
54 const controller = new AbortController()
55​
56 await toolsRegistry.get('execute_typescript')!.execute!(
57 { typescriptCode: 'return await snippet_load({})' },
58 {
59 emitCustomEvent: vi.fn(),
60 threadId: 'thread-1',
61 abortSignal: controller.signal,
62 context: { userId: 'u1' },
63 },
64 )
65​
66 expect(fetchData).toHaveBeenCalledWith(
67 {},
68 expect.objectContaining({
69 threadId: 'thread-1',
70 abortSignal: controller.signal,
71 context: { userId: 'u1' },
72 }),
73 )
74 })
75})