Elffuss BraidHub

kikocis/continue public

main · 6.5 KiBRawPermalink
1import * as fs from "fs/promises";
2import * as path from "path";
3
4import {
5 cleanupTestContext,
6 createTestContext,
7 runCLI,
8} from "../test-helpers/cli-helpers.js";
9import {
10 setupMockLLMTest,
11 cleanupMockLLMServer,
12 createMockLLMServer,
13 createMockLLMConfig,
14 type MockLLMServer,
15} from "../test-helpers/mock-llm-server.js";
16
17describe("E2E: Headless Mode with Dynamic Responses", () => {
18 let context: any;
19 let mockServer: MockLLMServer;
20 let extraServers: MockLLMServer[] = [];
21
22 beforeEach(async () => {
23 context = undefined;
24 mockServer = undefined as any;
25 extraServers = [];
26 });
27
28 afterEach(async () => {
29 // Clean up all extra servers first
30 if (extraServers.length > 0) {
31 await Promise.all(
32 extraServers.map((server) => cleanupMockLLMServer(server)),
33 );
34 extraServers = [];
35 }
36
37 // Clean up main server
38 if (mockServer) {
39 await cleanupMockLLMServer(mockServer);
40 mockServer = undefined as any;
41 }
42
43 // Clean up context last
44 if (context) {
45 await cleanupTestContext(context);
46 context = undefined;
47 }
48
49 // Small delay to ensure cleanup completes
50 await new Promise((resolve) => setTimeout(resolve, 50));
51 });
52
53 it("should respond dynamically based on prompt content", async () => {
54 context = await createTestContext();
55
56 // Create a mock server with dynamic responses
57 mockServer = await setupMockLLMTest(context, {
58 response: (prompt: string) => {
59 if (prompt.includes("weather")) {
60 return "It's sunny and 72°F today!";
61 } else if (prompt.includes("time")) {
62 return "The current time is 3:30 PM.";
63 } else {
64 return "I don't understand your question.";
65 }
66 },
67 });
68
69 // Test weather query
70 const weatherResult = await runCLI(context, {
71 args: ["-p", "--config", context.configPath, "What's the weather like?"],
72 timeout: 15000,
73 });
74 expect(weatherResult.stdout).toContain("It's sunny and 72°F today!");
75
76 // Test time query
77 const timeResult = await runCLI(context, {
78 args: ["-p", "--config", context.configPath, "What time is it?"],
79 timeout: 15000,
80 });
81 expect(timeResult.stdout).toContain("The current time is 3:30 PM.");
82
83 // Test unknown query
84 const unknownResult = await runCLI(context, {
85 args: [
86 "-p",
87 "--config",
88 context.configPath,
89 "Tell me about quantum physics",
90 ],
91 timeout: 15000,
92 });
93 expect(unknownResult.stdout).toContain("I don't understand your question.");
94
95 // Verify all requests were tracked
96 expect(mockServer.requests).toHaveLength(3);
97 });
98
99 it("should work with non-streaming responses", async () => {
100 context = await createTestContext();
101
102 mockServer = await setupMockLLMTest(context, {
103 response: "Non-streaming response",
104 streaming: false,
105 });
106
107 const result = await runCLI(context, {
108 args: ["-p", "--config", context.configPath, "Test non-streaming"],
109 timeout: 15000,
110 });
111
112 expect(result.stdout).toContain("Non-streaming response");
113 expect(result.exitCode).toBe(0);
114 }, 20000);
115
116 it("should handle multiple mock servers for different models", async () => {
117 context = await createTestContext();
118
119 // Create two different mock servers and track them for cleanup
120 const gpt4Server = await createMockLLMServer({
121 response: "Response from GPT-4",
122 });
123 extraServers.push(gpt4Server);
124
125 const claudeServer = await createMockLLMServer({
126 response: "Response from Claude",
127 });
128 extraServers.push(claudeServer);
129
130 // Create a config with multiple models
131 const configContent = `name: Multi-Model Assistant
132version: 1.0.0
133schema: v1
134models:
135 - name: test-gpt-4
136 model: gpt-4
137 provider: openai
138 apiKey: test-key-1
139 apiBase: ${gpt4Server.url}
140 roles:
141 - chat
142 - name: test-claude
143 model: claude-2
144 provider: anthropic
145 apiKey: test-key-2
146 apiBase: ${claudeServer.url}
147`;
148
149 const configPath = path.join(context.testDir, "multi-model-config.yaml");
150 await fs.writeFile(configPath, configContent);
151 context.configPath = configPath;
152
153 // Create onboarding flag
154 const onboardingFlagPath = path.join(
155 context.testDir,
156 ".continue",
157 ".onboarding_complete",
158 );
159 await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true });
160 await fs.writeFile(onboardingFlagPath, new Date().toISOString());
161
162 // Test with the first model (GPT-4 should be default)
163 const result = await runCLI(context, {
164 args: ["-p", "--config", context.configPath, "Hello"],
165 timeout: 15000,
166 });
167
168 expect(result.stdout).toContain("Response from GPT-4");
169 expect(gpt4Server.requests).toHaveLength(1);
170 expect(claudeServer.requests).toHaveLength(0);
171
172 // Servers will be cleaned up in afterEach
173 });
174
175 it("should allow custom request handling", async () => {
176 context = await createTestContext();
177
178 let requestCount = 0;
179 const responses = ["First response", "Second response", "Third response"];
180
181 // Create server with custom handler
182 mockServer = await createMockLLMServer({
183 customHandler: (req, res) => {
184 if (req.method === "POST" && req.url === "/chat/completions") {
185 const response = responses[requestCount % responses.length];
186 requestCount++;
187
188 res.writeHead(200, {
189 "Content-Type": "text/event-stream",
190 "Cache-Control": "no-cache",
191 Connection: "keep-alive",
192 });
193
194 res.write(
195 `data: {"choices":[{"delta":{"content":"${response}"},"index":0}]}\n\n`,
196 );
197 res.write(`data: [DONE]\n\n`);
198 res.end();
199 } else {
200 res.writeHead(404);
201 res.end();
202 }
203 },
204 });
205
206 // Set up the test environment
207 const configContent = createMockLLMConfig(mockServer);
208 const configPath = path.join(context.testDir, "test-config.yaml");
209 await fs.writeFile(configPath, configContent);
210 context.configPath = configPath;
211
212 const onboardingFlagPath = path.join(
213 context.testDir,
214 ".continue",
215 ".onboarding_complete",
216 );
217 await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true });
218 await fs.writeFile(onboardingFlagPath, new Date().toISOString());
219
220 // Make multiple requests
221 for (let i = 0; i < 3; i++) {
222 const result = await runCLI(context, {
223 args: ["-p", "--config", context.configPath, `Request ${i + 1}`],
224 timeout: 15000,
225 });
226 expect(result.stdout).toContain(responses[i]);
227 }
228 });
229});