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

registry-test.ts

497 lines15.1 KB

1/**
2 * Simulated test for dynamic ToolRegistry functionality
3 *
4 * Tests that:
5 * 1. codeModeWithSnippets returns a ToolRegistry instead of a tools array
6 * 2. The registry contains expected initial tools
7 * 3. Snippets registered mid-stream are immediately added to the registry
8 * 4. The newly registered snippet becomes available as a callable tool
9 */
10​
11import { EventType, chat, maxIterations } from '@tanstack/ai'
12import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
13import { codeModeWithSnippets } from '../src/code-mode-with-snippets'
14import {
15 createMockTextAdapter,
16 singleToolCall,
17 textResponse,
18} from './mock-adapter'
19import {
20 EXPECTED_SNIPPET_CODE,
21 EXPECTED_SNIPPET_INPUT_SCHEMA,
22 EXPECTED_SNIPPET_OUTPUT_SCHEMA,
23 addNumbersTool,
24 createTestStorage,
25 logError,
26 logInfo,
27 logSection,
28 logStep,
29 logSuccess,
30} from './test-utils'
31import type { ModelMessage, StreamChunk, ToolRegistry } from '@tanstack/ai'
32​
33/**
34 * Result from the registry test
35 */
36export interface RegistryTestResult {
37 passed: boolean
38 phases: {
39 setup: {
40 success: boolean
41 error?: string
42 details?: Record<string, unknown>
43 }
44 registration: {
45 success: boolean
46 error?: string
47 details?: Record<string, unknown>
48 }
49 verification: {
50 success: boolean
51 error?: string
52 details?: Record<string, unknown>
53 }
54 }
56​
57/**
58 * Create a mock adapter for snippet selection (no snippets initially)
59 */
60function createSnippetSelectionAdapter(snippetNames: Array<string>) {
61 return createMockTextAdapter({
62 responses: [textResponse(JSON.stringify(snippetNames))],
63 })
65​
66/**
67 * TypeScript code that the mock LLM will "generate" to add numbers
68 */
69const ADD_NUMBERS_CODE = `
70const a = 5;
71const b = 3;
72const result = await external_add_numbers({ a, b });
73console.log("Result:", result);
74return result;
76​
77/**
78 * Run the ToolRegistry simulated test
79 */
80export async function runRegistryTest(): Promise<RegistryTestResult> {
81 logSection('ToolRegistry Dynamic Registration Test')
82 logInfo(
83 'Testing that snippets registered mid-stream are immediately available',
84 )
85​
86 const storage = createTestStorage()
87 const driver = createNodeIsolateDriver({
88 memoryLimit: 128,
89 timeout: 30000,
90 })
91​
92 const result: RegistryTestResult = {
93 passed: false,
94 phases: {
95 setup: { success: false },
96 registration: { success: false },
97 verification: { success: false },
98 },
99 }
100​
101 // =========================================================================
102 // Phase 1: Setup - Verify registry is returned and has expected tools
103 // =========================================================================
104​
105 logSection('Phase 1: Registry Setup Verification')
106 logStep(1, 'Calling codeModeWithSnippets to get ToolRegistry')
107​
108 let registry: ToolRegistry
109​
110 try {
111 const selectionAdapter = createSnippetSelectionAdapter([])
112 const messages: Array<ModelMessage> = [
113 { role: 'user', content: 'What is 5 + 3?' },
114 ]
115​
116 const codeWithSnippetsResult = await codeModeWithSnippets({
117 config: {
118 driver,
119 tools: [addNumbersTool],
120 timeout: 30000,
121 memoryLimit: 128,
122 },
123 adapter: selectionAdapter,
124 snippets: {
125 storage,
126 maxSnippetsInContext: 5,
127 },
128 messages,
129 })
130​
131 registry = codeWithSnippetsResult.toolsRegistry
132​
133 // Verify registry is returned (not a tools array)
134 const hasGetTools = typeof registry.getTools === 'function'
135 const hasAdd = typeof registry.add === 'function'
136 const hasHas = typeof registry.has === 'function'
137​
138 if (!hasGetTools || !hasAdd || !hasHas) {
139 throw new Error(
140 'codeModeWithSnippets did not return a valid ToolRegistry',
141 )
142 }
143​
144 logSuccess('ToolRegistry returned from codeModeWithSnippets')
145​
146 // Check initial tools
147 const initialTools = registry.getTools()
148 const toolNames = initialTools.map((t) => t.name)
149 logInfo(`Initial tools: ${toolNames.join(', ')}`)
150​
151 const hasExecuteTypescript = registry.has('execute_typescript')
152 const hasSearchSnippets = registry.has('search_snippets')
153 const hasGetSnippet = registry.has('get_snippet')
154 const hasRegisterSnippet = registry.has('register_snippet')
155​
156 if (!hasExecuteTypescript) {
157 logError('Missing execute_typescript tool')
158 }
159 if (!hasSearchSnippets) {
160 logError('Missing search_snippets tool')
161 }
162 if (!hasGetSnippet) {
163 logError('Missing get_snippet tool')
164 }
165 if (!hasRegisterSnippet) {
166 logError('Missing register_snippet tool')
167 }
168​
169 const hasAllExpectedTools =
170 hasExecuteTypescript &&
171 hasSearchSnippets &&
172 hasGetSnippet &&
173 hasRegisterSnippet
174​
175 // Verify NO snippet tools exist yet (since no snippets in storage)
176 const snippetToolsBefore = toolNames.filter(
177 (n) => n.startsWith('snippet_') || n === 'add_two_numbers',
178 )
179 const noSnippetToolsYet = snippetToolsBefore.length === 0
180​
181 result.phases.setup = {
182 success: hasAllExpectedTools && noSnippetToolsYet,
183 details: {
184 toolCount: initialTools.length,
185 toolNames,
186 hasExecuteTypescript,
187 hasSearchSnippets,
188 hasGetSnippet,
189 hasRegisterSnippet,
190 noSnippetToolsYet,
191 },
192 }
193​
194 if (result.phases.setup.success) {
195 logSuccess('Phase 1 passed: Registry has all expected initial tools')
196 } else {
197 logError(
198 'Phase 1 failed: Missing expected tools or unexpected snippet tools',
199 )
200 logInfo(
201 `Details: ${JSON.stringify(result.phases.setup.details, null, 2)}`,
202 )
203 }
204 } catch (error) {
205 result.phases.setup = {
206 success: false,
207 error: error instanceof Error ? error.message : String(error),
208 }
209 logError(`Phase 1 error: ${result.phases.setup.error}`)
210 return result
211 }
212​
213 // =========================================================================
214 // Phase 2: Registration - Register a snippet mid-stream and verify it's added
215 // =========================================================================
216​
217 logSection('Phase 2: Mid-Stream Snippet Registration')
218 logStep(1, 'Setting up mock adapter for snippet registration')
219​
220 try {
221 const chatAdapter = createMockTextAdapter({
222 responses: [
223 // First: Execute TypeScript to test
224 singleToolCall(
225 'execute_typescript',
226 {
227 typescriptCode: ADD_NUMBERS_CODE,
228 },
229 'call_execute_1',
230 ),
231​
232 // Second: Register the snippet
233 singleToolCall(
234 'register_snippet',
235 {
236 name: 'add_two_numbers',
237 description: 'Add two numbers together using the add_numbers tool',
238 code: EXPECTED_SNIPPET_CODE,
239 inputSchema: JSON.stringify(EXPECTED_SNIPPET_INPUT_SCHEMA),
240 outputSchema: JSON.stringify(EXPECTED_SNIPPET_OUTPUT_SCHEMA),
241 usageHints: ['Use when the user wants to add two numbers'],
242 dependsOn: [],
243 },
244 'call_register_1',
245 ),
246​
247 // Third: Final response
248 textResponse('Done! I created an add_two_numbers snippet.'),
249 ],
250 onResponse: (index, response) => {
251 logInfo(
252 `Mock adapter response ${index + 1}: ${response.toolCalls ? `tool call to ${response.toolCalls[0]?.name}` : 'text'}`,
253 )
254 },
255 })
256​
257 const messages: Array<ModelMessage> = [
258 {
259 role: 'user',
260 content: 'Please add 5 + 3 and create a reusable snippet for it.',
261 },
262 ]
263​
264 // Count tools before
265 const toolsBefore = registry.getTools().length
266 logInfo(`Tools before chat: ${toolsBefore}`)
267​
268 logStep(2, 'Running chat with toolRegistry')
269​
270 const stream = chat({
271 adapter: chatAdapter as any,
272 messages: messages as any,
273 toolRegistry: registry, // <-- Using the registry, not tools array!
274 systemPrompts: ['You are a helpful assistant.'],
275 agentLoopStrategy: maxIterations(10),
276 })
277​
278 let registerSnippetCalled = false
279 let registerSnippetResult: any = null
280​
281 for await (const chunk of stream as AsyncIterable<StreamChunk>) {
282 if (chunk.type === 'tool_call') {
283 const toolName = chunk.toolCall.function.name
284 logInfo(`Tool called: ${toolName}`)
285 if (toolName === 'register_snippet') {
286 registerSnippetCalled = true
287 }
288 } else if (chunk.type === 'tool_result') {
289 logInfo(`Tool result for: ${chunk.toolCallId}`)
290 // Check if this is the register_snippet result
291 if (chunk.toolCallId === 'call_register_1') {
292 registerSnippetResult = chunk.result
293 logInfo(
294 `register_snippet result: ${JSON.stringify(registerSnippetResult)}`,
295 )
296 }
297 } else if (chunk.type === EventType.RUN_FINISHED) {
298 logInfo(`Chat done: ${chunk.metadata?.tanstack?.finishReason}`)
299 }
300 }
301​
302 // Check tools after
303 const toolsAfter = registry.getTools().length
304 logInfo(`Tools after chat: ${toolsAfter}`)
305​
306 const toolsIncreased = toolsAfter > toolsBefore
307 const hasNewSnippetTool = registry.has('add_two_numbers')
308​
309 result.phases.registration = {
310 success: registerSnippetCalled && toolsIncreased && hasNewSnippetTool,
311 details: {
312 registerSnippetCalled,
313 toolsBefore,
314 toolsAfter,
315 toolsIncreased,
316 hasNewSnippetTool,
317 registerSnippetResult,
318 },
319 }
320​
321 if (result.phases.registration.success) {
322 logSuccess(
323 'Phase 2 passed: Snippet registered and added to registry mid-stream',
324 )
325 } else {
326 logError('Phase 2 failed: Snippet was not properly added to registry')
327 logInfo(
328 `Details: ${JSON.stringify(result.phases.registration.details, null, 2)}`,
329 )
330 }
331 } catch (error) {
332 result.phases.registration = {
333 success: false,
334 error: error instanceof Error ? error.message : String(error),
335 }
336 logError(`Phase 2 error: ${result.phases.registration.error}`)
337 return result
338 }
339​
340 // =========================================================================
341 // Phase 3: Verification - Confirm the new snippet tool is callable
342 // =========================================================================
343​
344 logSection('Phase 3: Snippet Tool Verification')
345 logStep(1, 'Verifying the newly registered snippet is a callable tool')
346​
347 try {
348 // Get the snippet tool from the registry
349 const addTwoNumbersTool = registry.get('add_two_numbers')
350​
351 if (!addTwoNumbersTool) {
352 throw new Error('add_two_numbers tool not found in registry')
353 }
354​
355 logSuccess('add_two_numbers tool found in registry')
356​
357 // Verify it has the expected properties
358 const hasName = addTwoNumbersTool.name === 'add_two_numbers'
359 const hasDescription = typeof addTwoNumbersTool.description === 'string'
360 const hasInputSchema = addTwoNumbersTool.inputSchema !== undefined
361 const hasExecute = typeof (addTwoNumbersTool as any).execute === 'function'
362​
363 logInfo(`Tool name: ${addTwoNumbersTool.name}`)
364 logInfo(`Tool description: ${addTwoNumbersTool.description}`)
365 logInfo(`Has inputSchema: ${hasInputSchema}`)
366 logInfo(`Has execute function: ${hasExecute}`)
367​
368 // Now run a second chat that uses the snippet directly
369 logStep(2, 'Running a second chat that calls the snippet directly')
370​
371 const secondChatAdapter = createMockTextAdapter({
372 responses: [
373 // Directly call the newly registered snippet
374 singleToolCall(
375 'add_two_numbers',
376 {
377 a: 10,
378 b: 20,
379 },
380 'call_snippet_1',
381 ),
382​
383 // Final response
384 textResponse('The answer is 30.'),
385 ],
386 onResponse: (index, response) => {
387 logInfo(
388 `Second chat response ${index + 1}: ${response.toolCalls ? `tool call to ${response.toolCalls[0]?.name}` : 'text'}`,
389 )
390 },
391 })
392​
393 const messages2: Array<ModelMessage> = [
394 { role: 'user', content: 'What is 10 + 20?' },
395 ]
396​
397 const stream2 = chat({
398 adapter: secondChatAdapter as any,
399 messages: messages2 as any,
400 toolRegistry: registry,
401 systemPrompts: ['You are a helpful assistant.'],
402 agentLoopStrategy: maxIterations(5),
403 })
404​
405 let snippetToolCalled = false
406 let snippetToolResultReceived = false
407​
408 for await (const chunk of stream2 as AsyncIterable<StreamChunk>) {
409 if (chunk.type === 'tool_call') {
410 const toolName = chunk.toolCall.function.name
411 logInfo(`Tool called: ${toolName}`)
412 if (toolName === 'add_two_numbers') {
413 snippetToolCalled = true
414 }
415 } else if (chunk.type === 'tool_result') {
416 if (chunk.toolCallId === 'call_snippet_1') {
417 // The snippet executed and returned a result (value is in the execution context)
418 snippetToolResultReceived = true
419 logInfo('Snippet tool execution completed')
420 }
421 } else if (chunk.type === EventType.RUN_FINISHED) {
422 logInfo(`Second chat done: ${chunk.metadata?.tanstack?.finishReason}`)
423 }
424 }
425​
426 // The key verification is that:
427 // 1. The snippet tool exists in the registry
428 // 2. The chat function called it successfully
429 // 3. The tool_result was received (execution happened)
430 // The actual execution logs above show "[add_numbers] Adding 10 + 20" which proves
431 // the snippet code ran and called the external tool correctly.
432​
433 result.phases.verification = {
434 success:
435 hasName &&
436 hasDescription &&
437 snippetToolCalled &&
438 snippetToolResultReceived,
439 details: {
440 hasName,
441 hasDescription,
442 hasInputSchema,
443 hasExecute,
444 snippetToolCalled,
445 snippetToolResultReceived,
446 },
447 }
448​
449 if (result.phases.verification.success) {
450 logSuccess(
451 'Phase 3 passed: Snippet tool is callable and returns correct result',
452 )
453 } else {
454 logError('Phase 3 failed: Snippet tool verification failed')
455 logInfo(
456 `Details: ${JSON.stringify(result.phases.verification.details, null, 2)}`,
457 )
458 }
459 } catch (error) {
460 result.phases.verification = {
461 success: false,
462 error: error instanceof Error ? error.message : String(error),
463 }
464 logError(`Phase 3 error: ${result.phases.verification.error}`)
465 }
466​
467 // =========================================================================
468 // Final Result
469 // =========================================================================
470​
471 logSection('Test Results')
472​
473 result.passed =
474 result.phases.setup.success &&
475 result.phases.registration.success &&
476 result.phases.verification.success
477​
478 if (result.passed) {
479 logSuccess('All ToolRegistry tests passed!')
480 logInfo('✓ Registry returned from codeModeWithSnippets')
481 logInfo('✓ Snippets registered mid-stream are added to registry')
482 logInfo('✓ Newly registered snippets are callable as tools')
483 } else {
484 logError('Some ToolRegistry tests failed')
485 if (!result.phases.setup.success) {
486 logError(`Setup: ${result.phases.setup.error || 'Failed'}`)
487 }
488 if (!result.phases.registration.success) {
489 logError(`Registration: ${result.phases.registration.error || 'Failed'}`)
490 }
491 if (!result.phases.verification.success) {
492 logError(`Verification: ${result.phases.verification.error || 'Failed'}`)
493 }
494 }
495​
496 return result