Merge pull request #180 from continuedev/anthropic-key

fix: make sure that anthropic api key only works
This commit is contained in:
Nate Sesti 2025-08-10 19:46:43 -07:00 • committed by GitHub
commit cf1277fcdd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 168 additions and 5 deletions

View file

@ -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);
});

View file

@ -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 };
}

View file

@ -8,6 +8,7 @@ import { initializeServices } from "./index.js";
// Mock the onboarding module
vi.mock("../onboarding.js", () => ({
initializeWithOnboarding: vi.fn().mockResolvedValue({ wasOnboarded: false }),
createOrUpdateConfig: vi.fn().mockResolvedValue(undefined),
}));
// Mock auth module

View file

@ -47,6 +47,23 @@ 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 };

View file

@ -11,9 +11,15 @@ vi.mock("../auth/workos.js", () => ({
isAuthenticatedConfig: vi.fn(),
}));
vi.mock("node-machine-id", () => ({
machineIdSync: vi.fn(() => "test-machine-id"),
}));
vi.mock("node-machine-id", () => {
const mockFn = vi.fn(() => "test-machine-id");
return {
default: {
machineIdSync: mockFn,
},
machineIdSync: mockFn,
};
});
// Import after mocks are set up
import { loadAuthConfig, isAuthenticatedConfig } from "../auth/workos.js";

View file

@ -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";

15
vitest.e2e.config.ts Normal file
View file

@ -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"],
},
});