From 502f49f8df1eed3fd7183fc405a4d0698f07cd85 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 10 Aug 2025 22:29:23 -0400 Subject: [PATCH] fix: make sure that anthropic api key only works --- src/e2e/headless-anthropic-api-key.test.ts | 115 +++++++++++++++++++++ src/onboarding.ts | 11 +- src/services/index.ts | 13 +++ src/telemetry/posthogService.ts | 2 +- vitest.e2e.config.ts | 15 +++ 5 files changed, 154 insertions(+), 2 deletions(-) create mode 100644 src/e2e/headless-anthropic-api-key.test.ts create mode 100644 vitest.e2e.config.ts diff --git a/src/e2e/headless-anthropic-api-key.test.ts b/src/e2e/headless-anthropic-api-key.test.ts new file mode 100644 index 000000000..721a62b0d --- /dev/null +++ b/src/e2e/headless-anthropic-api-key.test.ts @@ -0,0 +1,115 @@ +import * as fs from "fs/promises"; +import * as path from "path"; + +import { + cleanupTestContext, + createTestContext, + runCLI, +} from "../test-helpers/cli-helpers.js"; +import { + cleanupMockLLMServer, + type MockLLMServer, + createMockLLMServer, +} from "../test-helpers/mock-llm-server.js"; + +describe("E2E: Headless Mode with ANTHROPIC_API_KEY", () => { + let context: any; + let mockServer: MockLLMServer; + + beforeEach(async () => { + context = await createTestContext(); + }); + + afterEach(async () => { + if (mockServer) { + await cleanupMockLLMServer(mockServer); + } + await cleanupTestContext(context); + }); + + it("should work when ANTHROPIC_API_KEY is set in environment", async () => { + // Create a mock LLM server using the same pattern as working tests + mockServer = await createMockLLMServer({ + response: "Hello! This is a response from Claude.", + }); + + // Use OpenAI provider pointing to mock server (same as working tests) + const configContent = `name: Test Assistant +version: 1.0.0 +schema: v1 +models: + - name: test-claude + model: claude-3-5-sonnet + provider: openai + apiKey: test-key + apiBase: ${mockServer.url} + roles: + - chat +`; + + 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()); + + const result = await runCLI(context, { + args: ["-p", "--config", context.configPath, "Hi there"], + env: { + ANTHROPIC_API_KEY: "test-api-key-from-env" + }, + timeout: 15000, + }); + + // Verify the CLI successfully runs (even if not using env var in this test) + expect(result.stdout).toContain("Hello! This is a response from Claude."); + expect(result.exitCode).toBe(0); + expect(mockServer.requests).toHaveLength(1); + + // Find the user message in the request + const userMessage = mockServer.requests[0].body.messages.find( + (m: any) => m.role === "user" + ); + expect(userMessage.content).toBe("Hi there"); + }, 20000); + + it("should create config and work with ANTHROPIC_API_KEY when no config exists", async () => { + // This test verifies the main fix: CLI automatically creates config from ANTHROPIC_API_KEY + // when no config file exists in headless mode + + const result = await runCLI(context, { + args: ["-p", "test prompt"], + env: { + ANTHROPIC_API_KEY: "sk-test-invalid-key-format", + CONTINUE_GLOBAL_DIR: context.testDir + "/.continue" + }, + expectError: true, + timeout: 15000, + }); + + // Should fail with authentication error (not service initialization error) + // This proves the fix works and CLI reaches the API call stage + expect(result.stderr).toContain("authentication_error"); + + // Should NOT contain the old error about service initialization + expect(result.stderr).not.toContain("Failed to initialize ConfigService"); + + // Verify config.yaml was automatically created + const configPath = path.join(context.testDir, ".continue", "config.yaml"); + const configExists = await fs.stat(configPath).then(() => true).catch(() => false); + expect(configExists).toBe(true); + + if (configExists) { + const configContent = await fs.readFile(configPath, "utf-8"); + expect(configContent).toContain("anthropic/claude-4-sonnet"); + expect(configContent).toContain("ANTHROPIC_API_KEY: sk-test-invalid-key-format"); + } + }, 20000); +}); \ No newline at end of file diff --git a/src/onboarding.ts b/src/onboarding.ts index 536ead963..45ca7ba61 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -78,7 +78,16 @@ export async function runOnboardingFlow( !process.stdin.isTTY; if (isTestEnv) { - // In test/CI environment, return a minimal working configuration + // In test/CI environment, check for ANTHROPIC_API_KEY first + if (process.env.ANTHROPIC_API_KEY) { + console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); + await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); + console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); + const result = await initialize(authConfig, CONFIG_PATH); + return { ...result, wasOnboarded: false }; + } + + // Otherwise return a minimal working configuration const result = await initialize(authConfig, undefined); return { ...result, wasOnboarded: false }; } diff --git a/src/services/index.ts b/src/services/index.ts index e79c5d49d..9cf495db0 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -47,6 +47,19 @@ export async function initializeServices( wasOnboarded = onboardingResult.wasOnboarded; } + // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided + if (options.headless && !options.configPath && process.env.ANTHROPIC_API_KEY) { + const { createOrUpdateConfig } = await import("../onboarding.js"); + const { env } = await import("../env.js"); + const path = await import("path"); + + const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); + await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); + + // Update options to use the created config + options.configPath = CONFIG_PATH; + } + // Initialize mode service with tool permission overrides if (options.toolPermissionOverrides) { const overrides = { ...options.toolPermissionOverrides }; diff --git a/src/telemetry/posthogService.ts b/src/telemetry/posthogService.ts index ef66bfc69..8eb694aea 100644 --- a/src/telemetry/posthogService.ts +++ b/src/telemetry/posthogService.ts @@ -1,6 +1,6 @@ import os from "node:os"; -import * as node_machine_id from "node-machine-id"; +import node_machine_id from "node-machine-id"; import type { PostHog as PostHogType } from "posthog-node"; import { isAuthenticatedConfig, loadAuthConfig } from "../auth/workos.js"; diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts new file mode 100644 index 000000000..1c562c37a --- /dev/null +++ b/vitest.e2e.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + environment: "node", + setupFiles: ["./vitest.setup.ts"], + include: ["src/e2e/**/*.test.ts"], + testTimeout: 30000, + hookTimeout: 30000, + }, + resolve: { + extensions: [".js", ".ts", ".tsx", ".json"], + }, +}); \ No newline at end of file