From 26ab6afda685d0403ddff8c42ea7635d87cc0b43 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 18:10:16 -0700 Subject: [PATCH] tests for headless mode --- package-lock.json | 47 +++-- package.json | 2 + src/commands/chat.ts | 2 +- src/e2e/headless-dynamic-responses.test.ts | 190 +++++++++++++++++++ src/e2e/headless-mock-llm.test.ts | 66 +++++++ src/index.ts | 7 +- src/test-helpers/README.md | 99 ++++++++++ src/test-helpers/mock-llm-server.ts | 180 ++++++++++++++++++ src/ui/__tests__/TUIChat.fileSearch.test.tsx | 7 +- 9 files changed, 581 insertions(+), 19 deletions(-) create mode 100644 src/e2e/headless-dynamic-responses.test.ts create mode 100644 src/e2e/headless-mock-llm.test.ts create mode 100644 src/test-helpers/README.md create mode 100644 src/test-helpers/mock-llm-server.ts diff --git a/package-lock.json b/package-lock.json index 5f5cb2a3b..bcedc33d2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -44,6 +44,7 @@ "@semantic-release/github": "^11.0.3", "@semantic-release/npm": "^12.0.2", "@types/diff": "^7.0.2", + "@types/express": "^5.0.3", "@types/glob": "^8.1.0", "@types/ignore-walk": "^4.0.3", "@types/ink-testing-library": "^1.0.4", @@ -53,6 +54,7 @@ "conventional-changelog-conventionalcommits": "^9.1.0", "cross-env": "^7.0.3", "execa": "^9.6.0", + "express": "^5.1.0", "ink-testing-library": "^4.0.0", "jest": "^29.7.0", "nock": "^14.0.5", @@ -4085,21 +4087,20 @@ "license": "MIT" }, "node_modules/@types/express": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", - "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.3.tgz", + "integrity": "sha512-wGA0NX93b19/dZC1J18tKWVIYWyyF2ZjT9vin/NRu0qzzvfVzWjs04iq2rQ3H65vCTQYlRqs3YHfY7zjdV+9Kw==", "license": "MIT", "dependencies": { "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", + "@types/express-serve-static-core": "^5.0.0", "@types/serve-static": "*" } }, "node_modules/@types/express-serve-static-core": { - "version": "4.19.6", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz", - "integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==", + "version": "5.0.7", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.7.tgz", + "integrity": "sha512-R+33OsgWw7rOhD1emjU7dzCDHucJrgJXMA5PYCzJxVil0dsyx5iBEPHqpPfiKNJQb7lZ1vxwoLR4Z87bBUpeGQ==", "license": "MIT", "dependencies": { "@types/node": "*", @@ -4302,9 +4303,9 @@ "dev": true }, "node_modules/@types/qs": { - "version": "6.9.18", - "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.18.tgz", - "integrity": "sha512-kK7dgTYDyGqS+e2Q4aK9X3D7q234CIZ1Bv0q/7Z5IwRDoADNU81xXJK/YVyLbLTZCoIwUoDoffFeF+p/eIklAA==", + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==", "license": "MIT" }, "node_modules/@types/range-parser": { @@ -7947,6 +7948,30 @@ } } }, + "node_modules/iron-session/node_modules/@types/express": { + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.23.tgz", + "integrity": "sha512-Crp6WY9aTYP3qPi2wGDo9iUe/rceX01UMhnF1jmwDcKCFM6cx7YhGP/Mpr3y9AASpfHixIG0E6azCcL5OcDHsQ==", + "license": "MIT", + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/iron-session/node_modules/@types/express-serve-static-core": { + "version": "4.19.6", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz", + "integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, "node_modules/iron-session/node_modules/@types/node": { "version": "17.0.45", "resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.45.tgz", diff --git a/package.json b/package.json index 367816c91..f6b0c09e2 100644 --- a/package.json +++ b/package.json @@ -63,6 +63,7 @@ "@semantic-release/github": "^11.0.3", "@semantic-release/npm": "^12.0.2", "@types/diff": "^7.0.2", + "@types/express": "^5.0.3", "@types/glob": "^8.1.0", "@types/ignore-walk": "^4.0.3", "@types/ink-testing-library": "^1.0.4", @@ -72,6 +73,7 @@ "conventional-changelog-conventionalcommits": "^9.1.0", "cross-env": "^7.0.3", "execa": "^9.6.0", + "express": "^5.1.0", "ink-testing-library": "^4.0.0", "jest": "^29.7.0", "nock": "^14.0.5", diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 32a745738..41216ad1c 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -126,7 +126,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // In headless mode, only print the final response if (options.headless && finalResponse.trim()) { - logger.info(finalResponse); + console.log(finalResponse); } // Save session after each successful response diff --git a/src/e2e/headless-dynamic-responses.test.ts b/src/e2e/headless-dynamic-responses.test.ts new file mode 100644 index 000000000..e81f16513 --- /dev/null +++ b/src/e2e/headless-dynamic-responses.test.ts @@ -0,0 +1,190 @@ +import { + cleanupTestContext, + createTestContext, + runCLI, +} from "../test-helpers/cli-helpers.js"; +import { + setupMockLLMTest, + cleanupMockLLMServer, + createMockLLMServer, + createMockLLMConfig, + type MockLLMServer, +} from "../test-helpers/mock-llm-server.js"; +import * as fs from "fs/promises"; +import * as path from "path"; + +describe("E2E: Headless Mode with Dynamic Responses", () => { + let context: any; + let mockServer: MockLLMServer; + + afterEach(async () => { + if (mockServer) { + await cleanupMockLLMServer(mockServer); + } + if (context) { + await cleanupTestContext(context); + } + }); + + it("should respond dynamically based on prompt content", async () => { + context = await createTestContext(); + + // Create a mock server with dynamic responses + mockServer = await setupMockLLMTest(context, { + response: (prompt: string) => { + if (prompt.includes("weather")) { + return "It's sunny and 72°F today!"; + } else if (prompt.includes("time")) { + return "The current time is 3:30 PM."; + } else { + return "I don't understand your question."; + } + }, + }); + + // Test weather query + const weatherResult = await runCLI(context, { + args: ["-p", "What's the weather like?", "--config", context.configPath], + timeout: 15000, + }); + expect(weatherResult.stdout).toContain("It's sunny and 72°F today!"); + + // Test time query + const timeResult = await runCLI(context, { + args: ["-p", "What time is it?", "--config", context.configPath], + timeout: 15000, + }); + expect(timeResult.stdout).toContain("The current time is 3:30 PM."); + + // Test unknown query + const unknownResult = await runCLI(context, { + args: ["-p", "Tell me about quantum physics", "--config", context.configPath], + timeout: 15000, + }); + expect(unknownResult.stdout).toContain("I don't understand your question."); + + // Verify all requests were tracked + expect(mockServer.requests).toHaveLength(3); + }); + + it("should work with non-streaming responses", async () => { + context = await createTestContext(); + + mockServer = await setupMockLLMTest(context, { + response: "Non-streaming response", + streaming: false, + }); + + const result = await runCLI(context, { + args: ["-p", "Test non-streaming", "--config", context.configPath], + timeout: 15000, + }); + + expect(result.stdout).toContain("Non-streaming response"); + expect(result.exitCode).toBe(0); + }); + + it("should handle multiple mock servers for different models", async () => { + context = await createTestContext(); + + // Create two different mock servers + const gpt4Server = await createMockLLMServer({ + response: "Response from GPT-4", + }); + + const claudeServer = await createMockLLMServer({ + response: "Response from Claude", + }); + + // Create a config with multiple models + const configContent = `name: Multi-Model Assistant +version: 1.0.0 +schema: v1 +models: + - name: test-gpt-4 + model: gpt-4 + provider: openai + apiKey: test-key-1 + apiBase: ${gpt4Server.url} + roles: + - chat + - name: test-claude + model: claude-2 + provider: anthropic + apiKey: test-key-2 + apiBase: ${claudeServer.url} +`; + + const configPath = path.join(context.testDir, "multi-model-config.yaml"); + await fs.writeFile(configPath, configContent); + context.configPath = configPath; + + // Create onboarding flag + const onboardingFlagPath = path.join(context.testDir, ".continue", ".onboarding_complete"); + await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true }); + await fs.writeFile(onboardingFlagPath, new Date().toISOString()); + + // Test with the first model (GPT-4 should be default) + const result = await runCLI(context, { + args: ["-p", "Hello", "--config", context.configPath], + timeout: 15000, + }); + + expect(result.stdout).toContain("Response from GPT-4"); + expect(gpt4Server.requests).toHaveLength(1); + expect(claudeServer.requests).toHaveLength(0); + + // Clean up extra servers + await cleanupMockLLMServer(gpt4Server); + await cleanupMockLLMServer(claudeServer); + }); + + it("should allow custom request handling", async () => { + context = await createTestContext(); + + let requestCount = 0; + const responses = ["First response", "Second response", "Third response"]; + + // Create server with custom handler + mockServer = await createMockLLMServer({ + customHandler: (req, res) => { + if (req.method === "POST" && req.url === "/chat/completions") { + const response = responses[requestCount % responses.length]; + requestCount++; + + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + "Connection": "keep-alive", + }); + + res.write(`data: {"choices":[{"delta":{"content":"${response}"},"index":0}]}\n\n`); + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + res.writeHead(404); + res.end(); + } + }, + }); + + // Set up the test environment + const configContent = createMockLLMConfig(mockServer); + const configPath = path.join(context.testDir, "test-config.yaml"); + await fs.writeFile(configPath, configContent); + context.configPath = configPath; + + const onboardingFlagPath = path.join(context.testDir, ".continue", ".onboarding_complete"); + await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true }); + await fs.writeFile(onboardingFlagPath, new Date().toISOString()); + + // Make multiple requests + for (let i = 0; i < 3; i++) { + const result = await runCLI(context, { + args: ["-p", `Request ${i + 1}`, "--config", context.configPath], + timeout: 15000, + }); + expect(result.stdout).toContain(responses[i]); + } + }); +}); \ No newline at end of file diff --git a/src/e2e/headless-mock-llm.test.ts b/src/e2e/headless-mock-llm.test.ts new file mode 100644 index 000000000..71a36ea83 --- /dev/null +++ b/src/e2e/headless-mock-llm.test.ts @@ -0,0 +1,66 @@ +import { + cleanupTestContext, + createTestContext, + runCLI, +} from "../test-helpers/cli-helpers.js"; +import { + setupMockLLMTest, + cleanupMockLLMServer, + type MockLLMServer, +} from "../test-helpers/mock-llm-server.js"; + +describe("E2E: Headless Mode with Mock Server", () => { + let context: any; + let mockServer: MockLLMServer; + + beforeEach(async () => { + context = await createTestContext(); + mockServer = await setupMockLLMTest(context, { + response: "Hello World!", + }); + }); + + afterEach(async () => { + await cleanupMockLLMServer(mockServer); + await cleanupTestContext(context); + }); + + it('should output "Hello World!" when using cn -p "Hi"', async () => { + const result = await runCLI(context, { + args: ["-p", "Hi", "--config", context.configPath], + timeout: 15000, + }); + + // Verify stdout contains "Hello World!" + expect(result.stdout).toContain("Hello World!"); + expect(result.exitCode).toBe(0); + }, 20000); + + it("should handle streaming responses correctly", async () => { + const result = await runCLI(context, { + args: ["-p", "Say hello", "--config", context.configPath], + timeout: 15000, + }); + + expect(result.stdout).toContain("Hello World!"); + expect(result.exitCode).toBe(0); + expect(mockServer.requests).toHaveLength(1); + // Find the user message (system message is first) + const userMessage = mockServer.requests[0].body.messages.find((m: any) => m.role === "user"); + expect(userMessage.content).toBe("Say hello"); + }, 20000); + + it("should work with longer prompts", async () => { + const result = await runCLI(context, { + args: ["-p", "Please respond with exactly 'Hello World!' and nothing else", "--config", context.configPath], + timeout: 15000, + }); + + expect(result.stdout).toContain("Hello World!"); + expect(result.exitCode).toBe(0); + expect(mockServer.requests).toHaveLength(1); + // Find the user message (system message is first) + const userMessage = mockServer.requests[0].body.messages.find((m: any) => m.role === "user"); + expect(userMessage.content).toBe("Please respond with exactly 'Hello World!' and nothing else"); + }, 20000); +}); \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index e3bf481fc..9a0eb78cd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -56,7 +56,12 @@ program console.log(`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`); logger.debug('Verbose logging enabled'); } - await chat(prompt, options); + // Map CLI options to chat options + const chatOptions = { + ...options, + headless: options.print, // Map --print to headless mode + }; + await chat(prompt, chatOptions); }); // Login subcommand diff --git a/src/test-helpers/README.md b/src/test-helpers/README.md new file mode 100644 index 000000000..583a40099 --- /dev/null +++ b/src/test-helpers/README.md @@ -0,0 +1,99 @@ +# Test Helpers + +This directory contains helper functions for testing the Continue CLI. + +## Mock LLM Server + +The `mock-llm-server.ts` module provides utilities for creating mock LLM servers in tests. This allows you to test the CLI's behavior without making real API calls. + +### Basic Usage + +```typescript +import { setupMockLLMTest, cleanupMockLLMServer } from "../test-helpers/mock-llm-server.js"; + +describe("My Test", () => { + let context: any; + let mockServer: MockLLMServer; + + beforeEach(async () => { + context = await createTestContext(); + mockServer = await setupMockLLMTest(context, { + response: "Hello from mock LLM!", + }); + }); + + afterEach(async () => { + await cleanupMockLLMServer(mockServer); + await cleanupTestContext(context); + }); + + it("should get response from mock", async () => { + const result = await runCLI(context, { + args: ["-p", "Test prompt", "--config", context.configPath], + }); + expect(result.stdout).toContain("Hello from mock LLM!"); + }); +}); +``` + +### Advanced Usage + +#### Dynamic Responses + +```typescript +mockServer = await setupMockLLMTest(context, { + response: (prompt: string) => { + if (prompt.includes("weather")) { + return "It's sunny!"; + } + return "Default response"; + }, +}); +``` + +#### Non-Streaming Responses + +```typescript +mockServer = await setupMockLLMTest(context, { + response: "Non-streaming response", + streaming: false, // Sends entire response at once instead of word-by-word +}); +``` + +Note: The CLI always expects SSE format, so responses are always sent as streaming events. The `streaming` option only controls whether the response is chunked word-by-word or sent all at once. + +#### Custom Request Handling + +```typescript +const mockServer = await createMockLLMServer({ + customHandler: (req, res) => { + // Custom logic here + res.writeHead(200); + res.end("Custom response"); + }, +}); +``` + +#### Request Tracking + +The mock server tracks all requests it receives: + +```typescript +// After making requests... +expect(mockServer.requests).toHaveLength(1); +expect(mockServer.requests[0].body.messages[0].content).toBe("User prompt"); +``` + +### API Reference + +#### `setupMockLLMTest(context, options)` +Sets up a complete test environment with mock LLM server, config file, and skips onboarding. + +#### `createMockLLMServer(options)` +Creates just the mock server without test environment setup. + +#### `createMockLLMConfig(mockServer, modelName)` +Generates a config YAML string for the mock server. + +#### `cleanupMockLLMServer(mockServer)` +Properly shuts down the mock server. \ No newline at end of file diff --git a/src/test-helpers/mock-llm-server.ts b/src/test-helpers/mock-llm-server.ts new file mode 100644 index 000000000..dd2100e22 --- /dev/null +++ b/src/test-helpers/mock-llm-server.ts @@ -0,0 +1,180 @@ +import * as http from "http"; +import { CLITestContext } from "./cli-helpers.js"; +import * as path from "path"; +import * as fs from "fs/promises"; + +export interface MockLLMServerOptions { + /** The response to send for chat completions. Can be a string or a function that returns a response based on the request. */ + response?: string | ((prompt: string) => string); + /** Whether to stream the response word by word (true) or send it all at once (false). Default: true + * Note: The response format is always SSE since the CLI expects streaming responses. */ + streaming?: boolean; + /** Custom handler for requests */ + customHandler?: (req: http.IncomingMessage, res: http.ServerResponse) => void; +} + +export interface MockLLMServer { + server: http.Server; + port: number; + url: string; + /** Track requests received by the server */ + requests: Array<{ + method: string; + url: string; + body: any; + timestamp: Date; + }>; +} + +/** + * Creates a mock LLM server for testing + * @param options Configuration options for the mock server + * @returns A promise that resolves to the mock server instance + */ +export async function createMockLLMServer( + options: MockLLMServerOptions = {} +): Promise { + const { + response = "Hello World!", + streaming = true, + customHandler + } = options; + + const requests: MockLLMServer["requests"] = []; + + const server = http.createServer((req, res) => { + // Allow custom handling + if (customHandler) { + customHandler(req, res); + return; + } + + // Collect request body + let body = ""; + req.on("data", (chunk) => { + body += chunk.toString(); + }); + + req.on("end", () => { + // Track the request + const requestData = { + method: req.method || "", + url: req.url || "", + body: body ? JSON.parse(body) : null, + timestamp: new Date(), + }; + requests.push(requestData); + + // Handle chat completions endpoint + if (req.method === "POST" && req.url === "/chat/completions") { + const requestBody = requestData.body; + // Find the last user message (there may be system messages before it) + const userMessages = requestBody?.messages?.filter((m: any) => m.role === "user") || []; + const prompt = userMessages[userMessages.length - 1]?.content || ""; + + const responseText = typeof response === "function" ? response(prompt) : response; + + // Always send streaming response since the CLI expects it + res.writeHead(200, { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + "Connection": "keep-alive", + }); + + if (streaming) { + // Split response into chunks for more realistic streaming + const words = responseText.split(" "); + words.forEach((word, index) => { + const content = index === 0 ? word : " " + word; + res.write(`data: {"choices":[{"delta":{"content":"${content}"},"index":0}]}\n\n`); + }); + } else { + // Send entire response in one chunk for non-streaming mode + res.write(`data: {"choices":[{"delta":{"content":"${responseText}"},"index":0}]}\n\n`); + } + + res.write(`data: [DONE]\n\n`); + res.end(); + } else { + // Return 404 for other endpoints + res.writeHead(404, { "Content-Type": "application/json" }); + res.end(JSON.stringify({ error: "Not found" })); + } + }); + }); + + // Start the server on a random port + return new Promise((resolve) => { + server.listen(0, () => { + const port = (server.address() as any).port; + resolve({ + server, + port, + url: `http://localhost:${port}`, + requests, + }); + }); + }); +} + +/** + * Creates a test configuration that uses a mock LLM server + * @param context The test context + * @param mockServer The mock server instance + * @param modelName The model name to use (default: "gpt-4") + * @returns The configuration content as a string + */ +export function createMockLLMConfig( + mockServer: MockLLMServer, + modelName: string = "gpt-4" +): string { + return `name: Test Assistant +version: 1.0.0 +schema: v1 +models: + - name: test-${modelName} + model: ${modelName} + provider: openai + apiKey: test-key + apiBase: ${mockServer.url} + roles: + - chat +`; +} + +/** + * Sets up a complete test environment with a mock LLM server + * @param context The test context + * @param options Options for the mock server + * @returns A promise that resolves to the mock server instance + */ +export async function setupMockLLMTest( + context: CLITestContext, + options: MockLLMServerOptions = {} +): Promise { + // Create mock server + const mockServer = await createMockLLMServer(options); + + // Create config file + const configContent = createMockLLMConfig(mockServer); + const configPath = path.join(context.testDir, "test-config.yaml"); + await fs.writeFile(configPath, configContent); + context.configPath = configPath; + + // Create onboarding flag to skip onboarding + const onboardingFlagPath = path.join(context.testDir, ".continue", ".onboarding_complete"); + await fs.mkdir(path.dirname(onboardingFlagPath), { recursive: true }); + await fs.writeFile(onboardingFlagPath, new Date().toISOString()); + + return mockServer; +} + +/** + * Cleans up a mock LLM server + * @param mockServer The mock server to clean up + */ +export async function cleanupMockLLMServer(mockServer: MockLLMServer): Promise { + return new Promise((resolve) => { + mockServer.server.close(() => resolve()); + }); +} \ No newline at end of file diff --git a/src/ui/__tests__/TUIChat.fileSearch.test.tsx b/src/ui/__tests__/TUIChat.fileSearch.test.tsx index a9a43a97f..2ba694c2b 100644 --- a/src/ui/__tests__/TUIChat.fileSearch.test.tsx +++ b/src/ui/__tests__/TUIChat.fileSearch.test.tsx @@ -50,12 +50,7 @@ describe("TUIChat - @ File Search Tests", () => { // Should show files containing "READ" - likely README.md if it exists in the actual filesystem // If not available, should at least show the @ character and navigation instructions - expect(frame).toContain("@"); - - // Should show navigation instructions - expect(frame).toContain( - "Use ↑/↓ to navigate, Enter to select, Tab to complete" - ); + expect(frame).toContain("@README.md"); }); it("shows navigation instructions in file search", async () => {