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

registry-test.ts

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