Elffuss BraidHub

kikocis/continue public

main · 8.3 KiBRawPermalink
1import * as fs from "fs/promises";
2import * as http from "http";
3import * as path from "path";
4
5import { CLITestContext } from "./cli-helpers.js";
6
7export interface MockLLMServerOptions {
8 /** The response to send for chat completions. Can be a string or a function that returns a response based on the request. */
9 response?: string | ((prompt: string) => string);
10 /** Whether to stream the response word by word (true) or send it all at once (false). Default: true
11 * Note: The response format is always SSE since the CLI expects streaming responses. */
12 streaming?: boolean;
13 /** Custom handler for requests */
14 customHandler?: (req: http.IncomingMessage, res: http.ServerResponse) => void;
15}
16
17export interface MockLLMServer {
18 server: http.Server;
19 port: number;
20 url: string;
21 /** Track requests received by the server */
22 requests: Array<{
23 method: string;
24 url: string;
25 body: any;
26 timestamp: Date;
27 }>;
28}
29
30/**
31 * Creates a mock LLM server for testing
32 * @param options Configuration options for the mock server
33 * @returns A promise that resolves to the mock server instance
34 */
35export async function createMockLLMServer(
36 options: MockLLMServerOptions = {},
37): Promise<MockLLMServer> {
38 const {
39 response = "Hello World!",
40 streaming = true,
41 customHandler,
42 } = options;
43
44 const requests: MockLLMServer["requests"] = [];
45
46 const server = http.createServer((req, res) => {
47 // Allow custom handling
48 if (customHandler) {
49 customHandler(req, res);
50 return;
51 }
52
53 // Set CORS headers to prevent any potential browser-related issues
54 res.setHeader("Access-Control-Allow-Origin", "*");
55 res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
56 res.setHeader(
57 "Access-Control-Allow-Headers",
58 "Content-Type, Authorization",
59 );
60
61 if (req.method === "OPTIONS") {
62 res.writeHead(200);
63 res.end();
64 return;
65 }
66
67 // Collect request body
68 let body = "";
69 req.on("data", (chunk) => {
70 body += chunk.toString();
71 });
72
73 req.on("end", () => {
74 // Track the request
75 const requestData = {
76 method: req.method || "",
77 url: req.url || "",
78 body: body
79 ? (() => {
80 try {
81 return JSON.parse(body);
82 } catch {
83 return body;
84 }
85 })()
86 : null,
87 timestamp: new Date(),
88 };
89 requests.push(requestData);
90
91 // Handle chat completions endpoint
92 if (req.method === "POST" && req.url === "/chat/completions") {
93 const requestBody = requestData.body;
94 // Find the last user message (there may be system messages before it)
95 const userMessages =
96 requestBody?.messages?.filter((m: any) => m.role === "user") || [];
97 const prompt = userMessages[userMessages.length - 1]?.content || "";
98
99 const responseText =
100 typeof response === "function" ? response(prompt) : response;
101
102 // Always send streaming response since the CLI expects it
103 res.writeHead(200, {
104 "Content-Type": "text/event-stream",
105 "Cache-Control": "no-cache",
106 Connection: "keep-alive",
107 "Access-Control-Allow-Origin": "*",
108 });
109
110 if (streaming) {
111 // Split response into chunks for more realistic streaming
112 const words = responseText.split(" ");
113 words.forEach((word, index) => {
114 const content = index === 0 ? word : " " + word;
115 // Properly escape JSON content
116 const escapedContent = JSON.stringify(content).slice(1, -1);
117 res.write(
118 `data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`,
119 );
120 });
121 } else {
122 // Send entire response in one chunk for non-streaming mode
123 // Properly escape JSON content
124 const escapedContent = JSON.stringify(responseText).slice(1, -1);
125 res.write(
126 `data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`,
127 );
128 }
129
130 res.write(`data: [DONE]\n\n`);
131 res.end();
132 } else {
133 // Return 404 for other endpoints
134 res.writeHead(404, { "Content-Type": "application/json" });
135 res.end(JSON.stringify({ error: "Not found" }));
136 }
137 });
138
139 // Handle connection errors gracefully
140 req.on("error", (err) => {
141 console.error("Request error:", err);
142 if (!res.headersSent) {
143 res.writeHead(500);
144 res.end("Internal Server Error");
145 }
146 });
147 });
148
149 // Handle server errors
150 server.on("error", (err) => {
151 console.error("Server error:", err);
152 });
153
154 // Set keep-alive timeout to help with cleanup
155 server.keepAliveTimeout = 1000;
156 server.headersTimeout = 2000;
157
158 // Start the server on a random port
159 return new Promise((resolve, reject) => {
160 server.listen(0, "127.0.0.1", () => {
161 const address = server.address();
162 if (!address || typeof address === "string") {
163 reject(new Error("Failed to get server address"));
164 return;
165 }
166
167 // Use unref() to prevent keeping the process alive unnecessarily
168 server.unref();
169
170 resolve({
171 server,
172 port: address.port,
173 url: `http://127.0.0.1:${address.port}`,
174 requests,
175 });
176 });
177
178 server.on("error", reject);
179 });
180}
181
182/**
183 * Creates a test configuration that uses a mock LLM server
184 * @param context The test context
185 * @param mockServer The mock server instance
186 * @param modelName The model name to use (default: "gpt-4")
187 * @returns The configuration content as a string
188 */
189export function createMockLLMConfig(
190 mockServer: MockLLMServer,
191 modelName: string = "gpt-4",
192): string {
193 return `name: Test Assistant
194version: 1.0.0
195schema: v1
196models:
197 - name: test-${modelName}
198 model: ${modelName}
199 provider: openai
200 apiKey: test-key
201 apiBase: ${mockServer.url}
202 roles:
203 - chat
204`;
205}
206
207/**
208 * Sets up a complete test environment with a mock LLM server
209 * @param context The test context
210 * @param options Options for the mock server
211 * @returns A promise that resolves to the mock server instance
212 */
213export async function setupMockLLMTest(
214 context: CLITestContext,
215 options: MockLLMServerOptions = {},
216): Promise<MockLLMServer> {
217 // Create mock server
218 const mockServer = await createMockLLMServer(options);
219
220 // Create config file
221 const configContent = createMockLLMConfig(mockServer);
222 const configPath = path.join(context.testDir, "test-config.yaml");
223 await fs.writeFile(configPath, configContent);
224 context.configPath = configPath;
225
226 // Create onboarding flag to skip onboarding
227 const onboardingFlagPath = path.join(
228 context.testDir,
229 ".continue",
230 ".onboarding_complete",
231 );
232 await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true });
233 await fs.writeFile(onboardingFlagPath, new Date().toISOString());
234
235 return mockServer;
236}
237
238/**
239 * Cleans up a mock LLM server
240 * @param mockServer The mock server to clean up
241 */
242export async function cleanupMockLLMServer(
243 mockServer: MockLLMServer,
244): Promise<void> {
245 return new Promise((resolve) => {
246 if (!mockServer?.server) {
247 resolve();
248 return;
249 }
250
251 let resolved = false;
252 const resolveOnce = () => {
253 if (!resolved) {
254 resolved = true;
255 resolve();
256 }
257 };
258
259 // Destroy all active connections immediately
260 if (typeof mockServer.server.closeAllConnections === "function") {
261 mockServer.server.closeAllConnections();
262 }
263
264 // Set a shorter keep-alive timeout before closing
265 mockServer.server.keepAliveTimeout = 0;
266 mockServer.server.headersTimeout = 0;
267
268 // Try to close the server gracefully first
269 if (mockServer.server.listening) {
270 mockServer.server.close((err: any) => {
271 if (err && err.code !== "ERR_SERVER_NOT_RUNNING") {
272 console.error("Error closing mock server:", err);
273 }
274 resolveOnce();
275 });
276
277 // Force close after a short timeout
278 setTimeout(() => {
279 if (mockServer.server.listening) {
280 mockServer.server.closeAllConnections?.();
281 // Use unref to prevent keeping the process alive
282 mockServer.server.unref();
283 }
284 resolveOnce();
285 }, 100);
286 } else {
287 resolveOnce();
288 }
289
290 // Fallback timeout to ensure cleanup doesn't hang
291 setTimeout(resolveOnce, 200);
292 });
293}