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

simulated-test.ts

429 lines12.8 KB

1/**
2 * Simulated test for the snippets system
3 *
4 * Uses a mock adapter with predetermined responses to test:
5 * 1. First run: Create a snippet using code mode
6 * 2. Second run: Use the saved snippet
7 */
8​
9import { EventType, chat, maxIterations } from '@tanstack/ai'
10import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
11import { codeModeWithSnippets } from '../src/code-mode-with-snippets'
12import {
13 createMockTextAdapter,
14 singleToolCall,
15 textResponse,
16} from './mock-adapter'
17import {
18 EXPECTED_SNIPPET_CODE,
19 EXPECTED_SNIPPET_INPUT_SCHEMA,
20 EXPECTED_SNIPPET_OUTPUT_SCHEMA,
21 addNumbersTool,
22 createTestStorage,
23 logError,
24 logInfo,
25 logSection,
26 logStep,
27 logSuccess,
28} from './test-utils'
29import type { ModelMessage, StreamChunk, ToolRegistry } from '@tanstack/ai'
30import type { TestResult } from './test-utils'
31​
32/**
33 * Create a mock adapter specifically for snippet selection
34 * Returns JSON arrays of snippet names based on the snippet index
35 */
36function createSnippetSelectionAdapter(snippetNames: Array<string>) {
37 return createMockTextAdapter({
38 responses: [
39 // Always return the snippet names as JSON array
40 textResponse(JSON.stringify(snippetNames)),
41 ],
42 })
44​
45/**
46 * TypeScript code that the mock LLM will "generate" to add numbers
47 */
48const ADD_NUMBERS_CODE = `
49const a = 5;
50const b = 3;
51const result = await external_add_numbers({ a, b });
52console.log("Result:", result);
53return result;
55​
56/**
57 * Run the simulated test
58 */
59export async function runSimulatedTest(): Promise<TestResult> {
60 logSection('Simulated Snippets Test')
61 logInfo('Testing snippet creation and reuse with mock adapter')
62​
63 // Create shared storage that persists between phases
64 const storage = createTestStorage()
65 const driver = createNodeIsolateDriver({
66 memoryLimit: 128,
67 timeout: 30000,
68 })
69​
70 const result: TestResult = {
71 passed: false,
72 phases: {
73 phase1: { success: false },
74 phase2: { success: false },
75 },
76 snippetCreated: false,
77 snippetUsed: false,
78 }
79​
80 // =========================================================================
81 // Phase 1: First run - Create snippet using code mode
82 // =========================================================================
83​
84 logSection('Phase 1: Snippet Creation')
85 logStep(1, 'Setting up mock adapter with snippet creation responses')
86​
87 // Mock adapter for snippet selection in Phase 1 (no snippets exist yet)
88 const phase1SelectionAdapter = createSnippetSelectionAdapter([])
89​
90 // Mock responses for Phase 1 main chat:
91 // 1. First, use execute_typescript to solve the problem
92 // 2. Then, register the snippet for future use
93 // 3. Finally, provide the answer
94 const phase1ChatAdapter = createMockTextAdapter({
95 responses: [
96 // Response 1: Execute TypeScript to add numbers
97 singleToolCall(
98 'execute_typescript',
99 {
100 typescriptCode: ADD_NUMBERS_CODE,
101 },
102 'call_execute_1',
103 ),
104​
105 // Response 2: Register the snippet
106 singleToolCall(
107 'register_snippet',
108 {
109 name: 'add_two_numbers',
110 description: 'Add two numbers together using the add_numbers tool',
111 code: EXPECTED_SNIPPET_CODE,
112 inputSchema: JSON.stringify(EXPECTED_SNIPPET_INPUT_SCHEMA),
113 outputSchema: JSON.stringify(EXPECTED_SNIPPET_OUTPUT_SCHEMA),
114 usageHints: ['Use when the user wants to add two numbers'],
115 dependsOn: [],
116 },
117 'call_register_1',
118 ),
119​
120 // Response 3: Final answer
121 textResponse(
122 'The answer is 8. I have also saved this as a snippet called "add_two_numbers" for future use.',
123 ),
124 ],
125 onResponse: (index, response) => {
126 logInfo(
127 `Mock adapter returning response ${index + 1}: ${response.toolCalls ? `tool call to ${response.toolCalls[0]?.name}` : 'text response'}`,
128 )
129 },
130 })
131​
132 try {
133 logStep(
134 2,
135 'Running code mode with snippets (first run, no existing snippets)',
136 )
137​
138 const messages1: Array<ModelMessage> = [
139 {
140 role: 'user',
141 content:
142 'What is 5 + 3? Please create a snippet for adding numbers after solving this.',
143 },
144 ]
145​
146 // Get registry and system prompt with snippets integration
147 // Note: We use the selection adapter for snippet selection, then the chat adapter for the actual chat
148 const { toolsRegistry: registry1, systemPrompt: systemPrompt1 } =
149 await codeModeWithSnippets({
150 config: {
151 driver,
152 tools: [addNumbersTool],
153 timeout: 30000,
154 memoryLimit: 128,
155 },
156 adapter: phase1SelectionAdapter, // Used for snippet selection (returns [])
157 snippets: {
158 storage,
159 maxSnippetsInContext: 5,
160 },
161 messages: messages1,
162 })
163​
164 const tools1 = registry1.getTools()
165 logInfo(
166 `Phase 1 tools available: ${tools1.map((t: any) => t.name).join(', ')}`,
167 )
168 logInfo(`System prompt length: ${systemPrompt1.length} chars`)
169​
170 // Run the chat
171 logStep(3, 'Executing chat with mock adapter')
172​
173 const stream1 = chat({
174 adapter: phase1ChatAdapter as any,
175 messages: messages1 as any,
176 toolRegistry: registry1, // Use the registry instead of tools array
177 systemPrompts: [systemPrompt1],
178 agentLoopStrategy: maxIterations(10),
179 })
180​
181 let toolCallCount1 = 0
182 let executeTypescriptCalled = false
183 let registerSnippetCalled = false
184​
185 for await (const chunk of stream1 as AsyncIterable<StreamChunk>) {
186 if (chunk.type === 'tool_call') {
187 toolCallCount1++
188 const toolName = chunk.toolCall.function.name
189 logInfo(`Tool called: ${toolName}`)
190 if (toolName === 'execute_typescript') {
191 executeTypescriptCalled = true
192 }
193 if (toolName === 'register_snippet') {
194 registerSnippetCalled = true
195 }
196 } else if (chunk.type === 'tool_result') {
197 logInfo(`Tool result received for: ${chunk.toolCallId}`)
198 } else if (chunk.type === 'content') {
199 // Content streaming
200 } else if (chunk.type === EventType.RUN_FINISHED) {
201 logInfo(`Phase 1 done: ${chunk.metadata?.tanstack?.finishReason}`)
202 }
203 }
204​
205 // Verify snippet was created
206 const snippetIndex = await storage.loadIndex()
207 const snippetCreated = snippetIndex.some(
208 (s) => s.name === 'add_two_numbers',
209 )
210​
211 if (snippetCreated) {
212 result.snippetCreated = true
213 logSuccess('Snippet "add_two_numbers" was created successfully')
214 } else {
215 logError('Snippet was not created')
216 }
217​
218 result.phases.phase1 = {
219 success:
220 executeTypescriptCalled && registerSnippetCalled && snippetCreated,
221 details: {
222 toolCallCount: toolCallCount1,
223 executeTypescriptCalled,
224 registerSnippetCalled,
225 snippetCreated,
226 snippetsInStorage: snippetIndex.length,
227 },
228 }
229​
230 if (result.phases.phase1.success) {
231 logSuccess('Phase 1 completed successfully')
232 } else {
233 logError('Phase 1 failed')
234 logInfo(
235 `Details: ${JSON.stringify(result.phases.phase1.details, null, 2)}`,
236 )
237 }
238 } catch (error) {
239 result.phases.phase1 = {
240 success: false,
241 error: error instanceof Error ? error.message : String(error),
242 }
243 logError(`Phase 1 error: ${result.phases.phase1.error}`)
244 }
245​
246 // =========================================================================
247 // Phase 2: Second run - Use the saved snippet
248 // =========================================================================
249​
250 logSection('Phase 2: Snippet Reuse')
251 logStep(1, 'Setting up mock adapter with snippet usage responses')
252​
253 // Mock adapter for snippet selection in Phase 2 - returns the snippet we created
254 const phase2SelectionAdapter = createSnippetSelectionAdapter([
255 'add_two_numbers',
256 ])
257​
258 // Mock responses for Phase 2 main chat:
259 // 1. Call the add_two_numbers snippet directly (not execute_typescript)
260 // 2. Provide the final answer
261 const phase2ChatAdapter = createMockTextAdapter({
262 responses: [
263 // Response 1: Call the snippet directly
264 singleToolCall(
265 'add_two_numbers',
266 {
267 a: 10,
268 b: 20,
269 },
270 'call_snippet_1',
271 ),
272​
273 // Response 2: Final answer
274 textResponse(
275 'The answer is 30. I used the add_two_numbers snippet to calculate this.',
276 ),
277 ],
278 onResponse: (index, response) => {
279 logInfo(
280 `Mock adapter returning response ${index + 1}: ${response.toolCalls ? `tool call to ${response.toolCalls[0]?.name}` : 'text response'}`,
281 )
282 },
283 })
284​
285 try {
286 logStep(
287 2,
288 'Running code mode with snippets (second run, snippet should be available)',
289 )
290​
291 const messages2: Array<ModelMessage> = [
292 { role: 'user', content: 'What is 10 + 20?' },
293 ]
294​
295 // Get registry and system prompt with snippets integration
296 // Note: We use the selection adapter for snippet selection (returns ['add_two_numbers'])
297 const {
298 registry: registry2,
299 systemPrompt: systemPrompt2,
300 selectedSnippets,
301 } = await codeModeWithSnippets({
302 config: {
303 driver,
304 tools: [addNumbersTool],
305 timeout: 30000,
306 memoryLimit: 128,
307 },
308 adapter: phase2SelectionAdapter, // Used for snippet selection (returns ['add_two_numbers'])
309 snippets: {
310 storage,
311 maxSnippetsInContext: 5,
312 },
313 messages: messages2,
314 })
315​
316 const tools2 = registry2.getTools()
317 logInfo(
318 `Phase 2 tools available: ${tools2.map((t: any) => t.name).join(', ')}`,
319 )
320 logInfo(
321 `Selected snippets: ${selectedSnippets.map((s) => s.name).join(', ') || 'none'}`,
322 )
323 logInfo(`System prompt length: ${systemPrompt2.length} chars`)
324​
325 // Check if snippet is now available as a tool
326 const snippetToolAvailable = registry2.has('add_two_numbers')
327 if (snippetToolAvailable) {
328 logSuccess('Snippet "add_two_numbers" is now available as a tool')
329 } else {
330 logWarning(
331 'Snippet is not available as a tool (may not have been selected)',
332 )
333 }
334​
335 // Run the chat
336 logStep(3, 'Executing chat with mock adapter')
337​
338 const stream2 = chat({
339 adapter: phase2ChatAdapter as any,
340 messages: messages2 as any,
341 toolRegistry: registry2, // Use the registry instead of tools array
342 systemPrompts: [systemPrompt2],
343 agentLoopStrategy: maxIterations(10),
344 })
345​
346 let toolCallCount2 = 0
347 let snippetCalled = false
348 let executeTypescriptCalledPhase2 = false
349​
350 for await (const chunk of stream2 as AsyncIterable<StreamChunk>) {
351 if (chunk.type === 'tool_call') {
352 toolCallCount2++
353 const toolName = chunk.toolCall.function.name
354 logInfo(`Tool called: ${toolName}`)
355 if (toolName === 'add_two_numbers') {
356 snippetCalled = true
357 }
358 if (toolName === 'execute_typescript') {
359 executeTypescriptCalledPhase2 = true
360 }
361 } else if (chunk.type === 'tool_result') {
362 logInfo(`Tool result received for: ${chunk.toolCallId}`)
363 } else if (chunk.type === EventType.RUN_FINISHED) {
364 logInfo(`Phase 2 done: ${chunk.metadata?.tanstack?.finishReason}`)
365 }
366 }
367​
368 result.snippetUsed = snippetCalled && !executeTypescriptCalledPhase2
369​
370 result.phases.phase2 = {
371 success: snippetCalled,
372 details: {
373 toolCallCount: toolCallCount2,
374 snippetCalled,
375 executeTypescriptCalled: executeTypescriptCalledPhase2,
376 snippetToolAvailable,
377 selectedSnippetCount: selectedSnippets.length,
378 },
379 }
380​
381 if (result.phases.phase2.success) {
382 logSuccess('Phase 2 completed successfully')
383 } else {
384 logError('Phase 2 failed')
385 logInfo(
386 `Details: ${JSON.stringify(result.phases.phase2.details, null, 2)}`,
387 )
388 }
389 } catch (error) {
390 result.phases.phase2 = {
391 success: false,
392 error: error instanceof Error ? error.message : String(error),
393 }
394 logError(`Phase 2 error: ${result.phases.phase2.error}`)
395 }
396​
397 // =========================================================================
398 // Final Result
399 // =========================================================================
400​
401 logSection('Test Results')
402​
403 result.passed = result.phases.phase1.success && result.phases.phase2.success
404​
405 if (result.passed) {
406 logSuccess('All tests passed!')
407 logInfo(`✓ Snippet created: ${result.snippetCreated}`)
408 logInfo(`✓ Snippet used: ${result.snippetUsed}`)
409 } else {
410 logError('Some tests failed')
411 if (!result.phases.phase1.success) {
412 logError(
413 `Phase 1 (Snippet Creation): ${result.phases.phase1.error || 'Failed'}`,
414 )
415 }
416 if (!result.phases.phase2.success) {
417 logError(
418 `Phase 2 (Snippet Reuse): ${result.phases.phase2.error || 'Failed'}`,
419 )
420 }
421 }
422​
423 return result
425​
426// Allow running directly
427function logWarning(message: string) {
428 console.log(`\x1b[33m⚠️ ${message}\x1b[0m`)