|
| 1 | +import http from 'http'; |
| 2 | +import express from 'express'; |
| 3 | +import { WebSocketServer, WebSocket } from 'ws'; |
| 4 | +import { WebSocketHandler } from '../websocket/handler.js'; |
| 5 | +import { ProjectManager } from '../project/state.js'; |
| 6 | +import { LLMOrchestrator } from '../llm/orchestrator.js'; |
| 7 | +import { LLMConfig, Message } from '@ai-video-editor/shared-types'; |
| 8 | +import { LLMProviderInterface, MCPTool, StreamChunk, ToolCall, ToolExecutor, LLMProviderOptions } from '../llm/types.js'; |
| 9 | + |
| 10 | +// Mock provider that returns tool calls on the first call, then text on the second |
| 11 | +let streamChatCallCount = 0; |
| 12 | + |
| 13 | +class MockToolProvider implements LLMProviderInterface { |
| 14 | + async getModels(): Promise<string[]> { |
| 15 | + return ['mock-model']; |
| 16 | + } |
| 17 | + |
| 18 | + async chat(messages: Message[]): Promise<{ content: string; toolCalls?: ToolCall[] }> { |
| 19 | + return { content: 'Mock chat response' }; |
| 20 | + } |
| 21 | + |
| 22 | + async *streamChat(messages: Message[]): AsyncIterable<StreamChunk> { |
| 23 | + streamChatCallCount++; |
| 24 | + |
| 25 | + if (streamChatCallCount === 1) { |
| 26 | + // First call: return text + a tool call |
| 27 | + yield { done: false, content: 'Let me search for that. ' }; |
| 28 | + yield { |
| 29 | + done: false, |
| 30 | + toolCall: { |
| 31 | + toolName: 'search_images', |
| 32 | + toolCallId: 'call-1', |
| 33 | + args: { query: 'sunset' } |
| 34 | + } |
| 35 | + }; |
| 36 | + yield { done: true }; |
| 37 | + } else if (streamChatCallCount === 2) { |
| 38 | + // Second call (after tool result): return another tool call for multi-turn |
| 39 | + yield { done: false, content: 'Found images. Now downloading. ' }; |
| 40 | + yield { |
| 41 | + done: false, |
| 42 | + toolCall: { |
| 43 | + toolName: 'download_asset', |
| 44 | + toolCallId: 'call-2', |
| 45 | + args: { url: 'https://example.com/sunset.jpg' } |
| 46 | + } |
| 47 | + }; |
| 48 | + yield { done: true }; |
| 49 | + } else { |
| 50 | + // Third call: final text response |
| 51 | + yield { done: false, content: 'Done! The sunset image has been added.' }; |
| 52 | + yield { done: true }; |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +async function runTest() { |
| 58 | + console.log('=== WebSocket Multi-Turn Tool Recursion Test ==='); |
| 59 | + |
| 60 | + const projectDir = './test-ws-tool-recursion'; |
| 61 | + const fs = await import('fs'); |
| 62 | + if (fs.existsSync(projectDir)) { |
| 63 | + fs.rmSync(projectDir, { recursive: true, force: true }); |
| 64 | + } |
| 65 | + |
| 66 | + const app = express(); |
| 67 | + const server = http.createServer(app); |
| 68 | + const wss = new WebSocketServer({ server }); |
| 69 | + const projectManager = new ProjectManager(projectDir); |
| 70 | + |
| 71 | + const mockConfig: LLMConfig = { |
| 72 | + provider: 'copilot', |
| 73 | + apiKey: '', |
| 74 | + model: 'mock-model' |
| 75 | + }; |
| 76 | + |
| 77 | + const orchestrator = new LLMOrchestrator(mockConfig); |
| 78 | + (orchestrator as any).provider = new MockToolProvider(); |
| 79 | + |
| 80 | + const wsHandler = new WebSocketHandler(wss, projectManager, orchestrator); |
| 81 | + |
| 82 | + const port = 3097; |
| 83 | + await new Promise<void>(resolve => server.listen(port, resolve)); |
| 84 | + console.log(`Test server on port ${port}`); |
| 85 | + |
| 86 | + try { |
| 87 | + const ws = new WebSocket(`ws://localhost:${port}`); |
| 88 | + await new Promise<void>((resolve, reject) => { |
| 89 | + ws.on('open', resolve); |
| 90 | + ws.on('error', reject); |
| 91 | + }); |
| 92 | + |
| 93 | + streamChatCallCount = 0; |
| 94 | + |
| 95 | + const responses: any[] = []; |
| 96 | + const toolCalls: any[] = []; |
| 97 | + const toolResults: any[] = []; |
| 98 | + let doneCount = 0; |
| 99 | + |
| 100 | + const responsePromise = new Promise<void>((resolve) => { |
| 101 | + ws.on('message', (data) => { |
| 102 | + const msg = JSON.parse(data.toString()); |
| 103 | + if (msg.type === 'copilot.response') { |
| 104 | + responses.push(msg.payload); |
| 105 | + if (msg.payload.done) { |
| 106 | + doneCount++; |
| 107 | + setTimeout(() => resolve(), 500); |
| 108 | + } |
| 109 | + } else if (msg.type === 'copilot.tool_call') { |
| 110 | + toolCalls.push(msg.payload); |
| 111 | + } else if (msg.type === 'copilot.tool_result') { |
| 112 | + toolResults.push(msg.payload); |
| 113 | + } |
| 114 | + }); |
| 115 | + }); |
| 116 | + |
| 117 | + ws.send(JSON.stringify({ |
| 118 | + type: 'copilot.message', |
| 119 | + payload: { content: 'Add a sunset image', model: 'mock-model' } |
| 120 | + })); |
| 121 | + |
| 122 | + await responsePromise; |
| 123 | + |
| 124 | + // Verify: streamChat should be called 3 times (initial + 2 tool recursions) |
| 125 | + console.log(`streamChat called ${streamChatCallCount} time(s)`); |
| 126 | + if (streamChatCallCount !== 3) { |
| 127 | + throw new Error(`Expected streamChat to be called 3 times for multi-turn tool use, but was called ${streamChatCallCount} times`); |
| 128 | + } |
| 129 | + |
| 130 | + // Verify: exactly ONE done:true signal |
| 131 | + if (doneCount !== 1) { |
| 132 | + throw new Error(`Expected 1 done signal, got ${doneCount}`); |
| 133 | + } |
| 134 | + |
| 135 | + // Verify: 2 tool calls were made |
| 136 | + if (toolCalls.length !== 2) { |
| 137 | + throw new Error(`Expected 2 tool calls, got ${toolCalls.length}: ${JSON.stringify(toolCalls)}`); |
| 138 | + } |
| 139 | + if (toolCalls[0].tool !== 'search_images') { |
| 140 | + throw new Error(`Expected first tool call to be 'search_images', got '${toolCalls[0].tool}'`); |
| 141 | + } |
| 142 | + if (toolCalls[1].tool !== 'download_asset') { |
| 143 | + throw new Error(`Expected second tool call to be 'download_asset', got '${toolCalls[1].tool}'`); |
| 144 | + } |
| 145 | + |
| 146 | + // Verify: 2 tool results were returned |
| 147 | + if (toolResults.length !== 2) { |
| 148 | + throw new Error(`Expected 2 tool results, got ${toolResults.length}`); |
| 149 | + } |
| 150 | + |
| 151 | + // Verify: all content was received |
| 152 | + const contentResponses = responses.filter(r => r.content && r.content.length > 0 && !r.done); |
| 153 | + const fullContent = contentResponses.map(r => r.content).join(''); |
| 154 | + if (!fullContent.includes('Let me search for that.')) { |
| 155 | + throw new Error(`Missing first turn content in: "${fullContent}"`); |
| 156 | + } |
| 157 | + if (!fullContent.includes('Done! The sunset image has been added.')) { |
| 158 | + throw new Error(`Missing final turn content in: "${fullContent}"`); |
| 159 | + } |
| 160 | + |
| 161 | + console.log('[PASS] Multi-turn tool recursion works correctly (3 LLM calls)'); |
| 162 | + console.log('[PASS] Single done signal sent'); |
| 163 | + console.log(`[PASS] 2 tool calls executed: ${toolCalls.map(t => t.tool).join(', ')}`); |
| 164 | + console.log(`[PASS] Full content received: "${fullContent}"`); |
| 165 | + |
| 166 | + ws.close(); |
| 167 | + } catch (err) { |
| 168 | + console.error('Test failed:', err); |
| 169 | + process.exit(1); |
| 170 | + } finally { |
| 171 | + server.close(); |
| 172 | + const fs = await import('fs'); |
| 173 | + if (fs.existsSync(projectDir)) { |
| 174 | + fs.rmSync(projectDir, { recursive: true, force: true }); |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + console.log('=== All multi-turn tool recursion tests passed ==='); |
| 179 | +} |
| 180 | + |
| 181 | +runTest().catch(err => { |
| 182 | + console.error('Test error:', err); |
| 183 | + process.exit(1); |
| 184 | +}); |
0 commit comments