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

simulated-test.ts

433 lines12.9 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 threadId: 'test-cli',
151 config: {
152 driver,
153 tools: [addNumbersTool],
154 timeout: 30000,
155 memoryLimit: 128,
156 },
157 adapter: phase1SelectionAdapter, // Used for snippet selection (returns [])
158 snippets: {
159 storage,
160 maxSnippetsInContext: 5,
161 },
162 messages: messages1,
163 })
164​
165 const tools1 = registry1.getTools()
166 logInfo(
167 `Phase 1 tools available: ${tools1.map((t: any) => t.name).join(', ')}`,
168 )
169 logInfo(`System prompt length: ${systemPrompt1.length} chars`)
170​
171 // Run the chat
172 logStep(3, 'Executing chat with mock adapter')
173​
174 const stream1 = chat({
175 threadId: 'test-cli',
176 adapter: phase1ChatAdapter as any,
177 messages: messages1 as any,
178 toolRegistry: registry1, // Use the registry instead of tools array
179 systemPrompts: [systemPrompt1],
180 agentLoopStrategy: maxIterations(10),
181 })
182​
183 let toolCallCount1 = 0
184 let executeTypescriptCalled = false
185 let registerSnippetCalled = false
186​
187 for await (const chunk of stream1 as AsyncIterable<StreamChunk>) {
188 if (chunk.type === 'tool_call') {
189 toolCallCount1++
190 const toolName = chunk.toolCall.function.name
191 logInfo(`Tool called: ${toolName}`)
192 if (toolName === 'execute_typescript') {
193 executeTypescriptCalled = true
194 }
195 if (toolName === 'register_snippet') {
196 registerSnippetCalled = true
197 }
198 } else if (chunk.type === 'tool_result') {
199 logInfo(`Tool result received for: ${chunk.toolCallId}`)
200 } else if (chunk.type === 'content') {
201 // Content streaming
202 } else if (chunk.type === EventType.RUN_FINISHED) {
203 logInfo(`Phase 1 done: ${chunk.metadata?.tanstack?.finishReason}`)
204 }
205 }
206​
207 // Verify snippet was created
208 const snippetIndex = await storage.loadIndex()
209 const snippetCreated = snippetIndex.some(
210 (s) => s.name === 'add_two_numbers',
211 )
212​
213 if (snippetCreated) {
214 result.snippetCreated = true
215 logSuccess('Snippet "add_two_numbers" was created successfully')
216 } else {
217 logError('Snippet was not created')
218 }
219​
220 result.phases.phase1 = {
221 success:
222 executeTypescriptCalled && registerSnippetCalled && snippetCreated,
223 details: {
224 toolCallCount: toolCallCount1,
225 executeTypescriptCalled,
226 registerSnippetCalled,
227 snippetCreated,
228 snippetsInStorage: snippetIndex.length,
229 },
230 }
231​
232 if (result.phases.phase1.success) {
233 logSuccess('Phase 1 completed successfully')
234 } else {
235 logError('Phase 1 failed')
236 logInfo(
237 `Details: ${JSON.stringify(result.phases.phase1.details, null, 2)}`,
238 )
239 }
240 } catch (error) {
241 result.phases.phase1 = {
242 success: false,
243 error: error instanceof Error ? error.message : String(error),
244 }
245 logError(`Phase 1 error: ${result.phases.phase1.error}`)
246 }
247​
248 // =========================================================================
249 // Phase 2: Second run - Use the saved snippet
250 // =========================================================================
251​
252 logSection('Phase 2: Snippet Reuse')
253 logStep(1, 'Setting up mock adapter with snippet usage responses')
254​
255 // Mock adapter for snippet selection in Phase 2 - returns the snippet we created
256 const phase2SelectionAdapter = createSnippetSelectionAdapter([
257 'add_two_numbers',
258 ])
259​
260 // Mock responses for Phase 2 main chat:
261 // 1. Call the add_two_numbers snippet directly (not execute_typescript)
262 // 2. Provide the final answer
263 const phase2ChatAdapter = createMockTextAdapter({
264 responses: [
265 // Response 1: Call the snippet directly
266 singleToolCall(
267 'add_two_numbers',
268 {
269 a: 10,
270 b: 20,
271 },
272 'call_snippet_1',
273 ),
274​
275 // Response 2: Final answer
276 textResponse(
277 'The answer is 30. I used the add_two_numbers snippet to calculate this.',
278 ),
279 ],
280 onResponse: (index, response) => {
281 logInfo(
282 `Mock adapter returning response ${index + 1}: ${response.toolCalls ? `tool call to ${response.toolCalls[0]?.name}` : 'text response'}`,
283 )
284 },
285 })
286​
287 try {
288 logStep(
289 2,
290 'Running code mode with snippets (second run, snippet should be available)',
291 )
292​
293 const messages2: Array<ModelMessage> = [
294 { role: 'user', content: 'What is 10 + 20?' },
295 ]
296​
297 // Get registry and system prompt with snippets integration
298 // Note: We use the selection adapter for snippet selection (returns ['add_two_numbers'])
299 const {
300 registry: registry2,
301 systemPrompt: systemPrompt2,
302 selectedSnippets,
303 } = await codeModeWithSnippets({
304 threadId: 'test-cli',
305 config: {
306 driver,
307 tools: [addNumbersTool],
308 timeout: 30000,
309 memoryLimit: 128,
310 },
311 adapter: phase2SelectionAdapter, // Used for snippet selection (returns ['add_two_numbers'])
312 snippets: {
313 storage,
314 maxSnippetsInContext: 5,
315 },
316 messages: messages2,
317 })
318​
319 const tools2 = registry2.getTools()
320 logInfo(
321 `Phase 2 tools available: ${tools2.map((t: any) => t.name).join(', ')}`,
322 )
323 logInfo(
324 `Selected snippets: ${selectedSnippets.map((s) => s.name).join(', ') || 'none'}`,
325 )
326 logInfo(`System prompt length: ${systemPrompt2.length} chars`)
327​
328 // Check if snippet is now available as a tool
329 const snippetToolAvailable = registry2.has('add_two_numbers')
330 if (snippetToolAvailable) {
331 logSuccess('Snippet "add_two_numbers" is now available as a tool')
332 } else {
333 logWarning(
334 'Snippet is not available as a tool (may not have been selected)',
335 )
336 }
337​
338 // Run the chat
339 logStep(3, 'Executing chat with mock adapter')
340​
341 const stream2 = chat({
342 threadId: 'test-cli',
343 adapter: phase2ChatAdapter as any,
344 messages: messages2 as any,
345 toolRegistry: registry2, // Use the registry instead of tools array
346 systemPrompts: [systemPrompt2],
347 agentLoopStrategy: maxIterations(10),
348 })
349​
350 let toolCallCount2 = 0
351 let snippetCalled = false
352 let executeTypescriptCalledPhase2 = false
353​
354 for await (const chunk of stream2 as AsyncIterable<StreamChunk>) {
355 if (chunk.type === 'tool_call') {
356 toolCallCount2++
357 const toolName = chunk.toolCall.function.name
358 logInfo(`Tool called: ${toolName}`)
359 if (toolName === 'add_two_numbers') {
360 snippetCalled = true
361 }
362 if (toolName === 'execute_typescript') {
363 executeTypescriptCalledPhase2 = true
364 }
365 } else if (chunk.type === 'tool_result') {
366 logInfo(`Tool result received for: ${chunk.toolCallId}`)
367 } else if (chunk.type === EventType.RUN_FINISHED) {
368 logInfo(`Phase 2 done: ${chunk.metadata?.tanstack?.finishReason}`)
369 }
370 }
371​
372 result.snippetUsed = snippetCalled && !executeTypescriptCalledPhase2
373​
374 result.phases.phase2 = {
375 success: snippetCalled,
376 details: {
377 toolCallCount: toolCallCount2,
378 snippetCalled,
379 executeTypescriptCalled: executeTypescriptCalledPhase2,
380 snippetToolAvailable,
381 selectedSnippetCount: selectedSnippets.length,
382 },
383 }
384​
385 if (result.phases.phase2.success) {
386 logSuccess('Phase 2 completed successfully')
387 } else {
388 logError('Phase 2 failed')
389 logInfo(
390 `Details: ${JSON.stringify(result.phases.phase2.details, null, 2)}`,
391 )
392 }
393 } catch (error) {
394 result.phases.phase2 = {
395 success: false,
396 error: error instanceof Error ? error.message : String(error),
397 }
398 logError(`Phase 2 error: ${result.phases.phase2.error}`)
399 }
400​
401 // =========================================================================
402 // Final Result
403 // =========================================================================
404​
405 logSection('Test Results')
406​
407 result.passed = result.phases.phase1.success && result.phases.phase2.success
408​
409 if (result.passed) {
410 logSuccess('All tests passed!')
411 logInfo(`✓ Snippet created: ${result.snippetCreated}`)
412 logInfo(`✓ Snippet used: ${result.snippetUsed}`)
413 } else {
414 logError('Some tests failed')
415 if (!result.phases.phase1.success) {
416 logError(
417 `Phase 1 (Snippet Creation): ${result.phases.phase1.error || 'Failed'}`,
418 )
419 }
420 if (!result.phases.phase2.success) {
421 logError(
422 `Phase 2 (Snippet Reuse): ${result.phases.phase2.error || 'Failed'}`,
423 )
424 }
425 }
426​
427 return result
429​
430// Allow running directly
431function logWarning(message: string) {
432 console.log(`\x1b[33m⚠️ ${message}\x1b[0m`)