From 25fe40a5469d6c2f26708bf9e11c9f96515b2054 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 1 Mar 2026 10:30:41 -0800 Subject: [PATCH] Add smoke tests for real API connectivity Add a new smoke-api test suite that proves the CLI can complete real LLM round-trips against the Anthropic API. Tests cover headless mode, serve mode, and all-tools execution. Runs sequentially to avoid rate limits, skips gracefully when API keys are missing (fork PRs), and is wired into CI as a required check with allowed-skips. Co-Authored-By: Claude Opus 4.6 --- .github/workflows/cli-pr-checks.yml | 49 ++++ extensions/cli/package.json | 1 + .../src/smoke-api/headless-all-tools.test.ts | 79 +++++ .../src/smoke-api/headless-anthropic.test.ts | 39 +++ .../smoke-api/headless-continue-proxy.test.ts | 39 +++ .../cli/src/smoke-api/serve-anthropic.test.ts | 87 ++++++ .../cli/src/smoke-api/smoke-api-helpers.ts | 270 ++++++++++++++++++ extensions/cli/vitest.smoke-api.config.ts | 19 ++ 8 files changed, 583 insertions(+) create mode 100644 extensions/cli/src/smoke-api/headless-all-tools.test.ts create mode 100644 extensions/cli/src/smoke-api/headless-anthropic.test.ts create mode 100644 extensions/cli/src/smoke-api/headless-continue-proxy.test.ts create mode 100644 extensions/cli/src/smoke-api/serve-anthropic.test.ts create mode 100644 extensions/cli/src/smoke-api/smoke-api-helpers.ts create mode 100644 extensions/cli/vitest.smoke-api.config.ts diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index 6084b1610..f60a02882 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -119,6 +119,52 @@ jobs: cd extensions/cli npm run test:e2e + smoke-api: + # Only runs when secrets are available (not on fork PRs) + if: github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: 20 + cache: "npm" + cache-dependency-path: extensions/cli/package-lock.json + + - name: Setup packages + uses: ./.github/actions/setup-packages + - name: Setup core component + uses: ./.github/actions/setup-component + with: + component: core + include-root: true + + - name: Build core + run: | + cd core + npm run build + + - name: Install dependencies + run: | + cd extensions/cli + npm ci --include=optional + + - name: Build + run: | + cd extensions/cli + npm run build + + - name: Run smoke API tests + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} + run: | + cd extensions/cli + npm run test:smoke-api + # GitHub does not have a way of requiring that all checks pass (you must manually select each job) # This action at least lets us manage the list of required tests via source control # so that creators of new jobs can add them to this list @@ -128,9 +174,12 @@ jobs: needs: - lint - test + - smoke-api steps: - name: Decide whether the needed jobs succeeded or failed uses: re-actors/alls-green@release/v1 with: + # smoke-api is allowed to skip for fork PRs that lack secrets + allowed-skips: smoke-api jobs: ${{ toJSON(needs) }} diff --git a/extensions/cli/package.json b/extensions/cli/package.json index 98e2b26d5..59a371460 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -14,6 +14,7 @@ "test:ui": "vitest --ui", "test:e2e": "vitest run --config vitest.e2e.config.ts", "test:smoke": "node smoke-test.mjs", + "test:smoke-api": "vitest run --config vitest.smoke-api.config.ts", "build:tsc": "tsc -p tsconfig.build.json", "build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../terminal-security && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i", "build:validate": "node validate-aliases.mjs", diff --git a/extensions/cli/src/smoke-api/headless-all-tools.test.ts b/extensions/cli/src/smoke-api/headless-all-tools.test.ts new file mode 100644 index 000000000..290ee12dd --- /dev/null +++ b/extensions/cli/src/smoke-api/headless-all-tools.test.ts @@ -0,0 +1,79 @@ +import { execSync } from "child_process"; +import fs from "fs/promises"; +import path from "path"; + +import { describe, it, expect, beforeEach, afterEach } from "vitest"; + +import { + createSmokeContext, + cleanupSmokeContext, + writeAnthropicConfig, + runHeadless, + type SmokeTestContext, +} from "./smoke-api-helpers.js"; + +const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; + +describe.skipIf(!ANTHROPIC_API_KEY)( + "Smoke: Headless → all tools round-trip", + () => { + let ctx: SmokeTestContext; + + beforeEach(async () => { + ctx = await createSmokeContext(); + await writeAnthropicConfig(ctx, ANTHROPIC_API_KEY!); + + // Seed a file for the model to read/edit + await fs.writeFile( + path.join(ctx.testDir, "seed.txt"), + "line one\nline two\nline three\n", + ); + + // Initialize a git repo so Diff tool works + const gitEnv = { + ...process.env, + GIT_AUTHOR_NAME: "test", + GIT_AUTHOR_EMAIL: "test@test.com", + GIT_COMMITTER_NAME: "test", + GIT_COMMITTER_EMAIL: "test@test.com", + }; + execSync("git init", { cwd: ctx.testDir, env: gitEnv }); + execSync("git add .", { cwd: ctx.testDir, env: gitEnv }); + execSync('git commit -m "init"', { cwd: ctx.testDir, env: gitEnv }); + }); + + afterEach(async () => { + await cleanupSmokeContext(ctx); + }); + + const PROMPT = `You have access to tools. I need you to call EACH of the following tools in order, then say "ALL_TOOLS_DONE" when finished. + +1. List: list the files in the current directory "." +2. Write: create a file called "created.txt" with content "smoke test" +3. Read: read the file "created.txt" +4. Edit: edit "created.txt" — replace "smoke test" with "smoke test edited" +5. MultiEdit: edit "seed.txt" — replace "line one" with "LINE ONE" and "line two" with "LINE TWO" +6. Search: search for "LINE" in the current directory "." +7. Bash: run the command "echo tool-test-ok" +8. Diff: show the git diff in the current directory +9. Fetch: fetch the URL "https://httpbin.org/get" +10. Checklist: create a checklist with a single item "smoke test passed" + +After all tools complete, say exactly "ALL_TOOLS_DONE" as your final message.`; + + it( + "should exercise 10 built-in tools and complete successfully", + async () => { + const result = await runHeadless( + ctx, + ["-p", "--auto", "--config", ctx.configPath, PROMPT], + { timeout: 120000 }, + ); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain("ALL_TOOLS_DONE"); + }, + 180000, + ); + }, +); diff --git a/extensions/cli/src/smoke-api/headless-anthropic.test.ts b/extensions/cli/src/smoke-api/headless-anthropic.test.ts new file mode 100644 index 000000000..571e43e09 --- /dev/null +++ b/extensions/cli/src/smoke-api/headless-anthropic.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; + +import { + createSmokeContext, + cleanupSmokeContext, + writeAnthropicConfig, + runHeadless, + type SmokeTestContext, +} from "./smoke-api-helpers.js"; + +const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; + +describe.skipIf(!ANTHROPIC_API_KEY)( + "Smoke: Headless → real Anthropic API", + () => { + let ctx: SmokeTestContext; + + beforeEach(async () => { + ctx = await createSmokeContext(); + await writeAnthropicConfig(ctx, ANTHROPIC_API_KEY!); + }); + + afterEach(async () => { + await cleanupSmokeContext(ctx); + }); + + it("should complete a round-trip and return a response", async () => { + const result = await runHeadless(ctx, [ + "-p", + "--config", + ctx.configPath, + "Reply with exactly the word 'hello' and nothing else.", + ]); + + expect(result.exitCode).toBe(0); + expect(result.stdout.toLowerCase()).toContain("hello"); + }); + }, +); diff --git a/extensions/cli/src/smoke-api/headless-continue-proxy.test.ts b/extensions/cli/src/smoke-api/headless-continue-proxy.test.ts new file mode 100644 index 000000000..54f6100e8 --- /dev/null +++ b/extensions/cli/src/smoke-api/headless-continue-proxy.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; + +import { + createSmokeContext, + cleanupSmokeContext, + writeContinueProxyConfig, + runHeadless, + type SmokeTestContext, +} from "./smoke-api-helpers.js"; + +const CONTINUE_API_KEY = process.env.CONTINUE_API_KEY; + +describe.skipIf(!CONTINUE_API_KEY)( + "Smoke: Headless → real Continue proxy", + () => { + let ctx: SmokeTestContext; + + beforeEach(async () => { + ctx = await createSmokeContext(); + await writeContinueProxyConfig(ctx, CONTINUE_API_KEY!); + }); + + afterEach(async () => { + await cleanupSmokeContext(ctx); + }); + + it("should complete a round-trip and return a response", async () => { + const result = await runHeadless(ctx, [ + "-p", + "--config", + ctx.configPath, + "Reply with exactly the word 'hello' and nothing else.", + ]); + + expect(result.exitCode).toBe(0); + expect(result.stdout.toLowerCase()).toContain("hello"); + }); + }, +); diff --git a/extensions/cli/src/smoke-api/serve-anthropic.test.ts b/extensions/cli/src/smoke-api/serve-anthropic.test.ts new file mode 100644 index 000000000..3031dca21 --- /dev/null +++ b/extensions/cli/src/smoke-api/serve-anthropic.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; + +import { + createSmokeContext, + cleanupSmokeContext, + writeAnthropicConfig, + spawnServe, + waitForPattern, + pollUntilIdle, + shutdownServe, + type SmokeTestContext, +} from "./smoke-api-helpers.js"; + +import type { Subprocess } from "execa"; + +const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY; + +describe.skipIf(!ANTHROPIC_API_KEY)( + "Smoke: Serve mode → real Anthropic API", + () => { + let ctx: SmokeTestContext; + let proc: Subprocess; + const port = 18321; // high port to avoid collisions + const baseUrl = `http://127.0.0.1:${port}`; + + beforeEach(async () => { + ctx = await createSmokeContext(); + await writeAnthropicConfig(ctx, ANTHROPIC_API_KEY!); + }); + + afterEach(async () => { + if (proc) { + await shutdownServe(proc, baseUrl); + } + await cleanupSmokeContext(ctx); + }); + + it("should accept a message via HTTP and return a response in state", async () => { + proc = spawnServe(ctx, [ + "--port", + String(port), + "--config", + ctx.configPath, + ]); + + // Wait for the server to start + await waitForPattern(proc, "Server started", 30000); + + // Send a message + const msgRes = await fetch(`${baseUrl}/message`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + message: + "Reply with exactly the word 'hello' and nothing else.", + }), + }); + expect(msgRes.ok).toBe(true); + + // Poll until the agent finishes processing + const state = await pollUntilIdle(baseUrl, 60000); + + // State shape: { session: { history: ChatHistoryItem[] }, ... } + // Each ChatHistoryItem has { message: { role, content }, ... } + const history: any[] = state.session?.history ?? []; + const assistantItems = history.filter( + (item: any) => item.message?.role === "assistant", + ); + expect(assistantItems.length).toBeGreaterThan(0); + + const lastMsg = assistantItems[assistantItems.length - 1].message; + const content = + typeof lastMsg.content === "string" + ? lastMsg.content + : lastMsg.content + ?.filter((p: any) => p.type === "text") + .map((p: any) => p.text) + .join(""); + + expect(content?.toLowerCase()).toContain("hello"); + + // Graceful exit + const exitRes = await fetch(`${baseUrl}/exit`, { method: "POST" }); + expect(exitRes.ok).toBe(true); + }); + }, +); diff --git a/extensions/cli/src/smoke-api/smoke-api-helpers.ts b/extensions/cli/src/smoke-api/smoke-api-helpers.ts new file mode 100644 index 000000000..cde6b9f67 --- /dev/null +++ b/extensions/cli/src/smoke-api/smoke-api-helpers.ts @@ -0,0 +1,270 @@ +import fs from "fs/promises"; +import os from "os"; +import path from "path"; + +import { execaNode, type Subprocess } from "execa"; + +export interface SmokeTestContext { + cliPath: string; + testDir: string; + configPath: string; +} + +/** + * Creates an isolated test directory and resolves the CLI entry point. + */ +export async function createSmokeContext(): Promise { + const cliPath = path.resolve("dist/cn.js"); + + try { + await fs.access(cliPath); + } catch { + throw new Error( + `CLI not found at ${cliPath}. Run 'npm run build' first.`, + ); + } + + const testDir = await fs.mkdtemp(path.join(os.tmpdir(), "cn-smoke-")); + + // Create onboarding flag so the CLI skips onboarding flow + const continueDir = path.join(testDir, ".continue"); + await fs.mkdir(continueDir, { recursive: true }); + await fs.writeFile( + path.join(continueDir, ".onboarding_complete"), + new Date().toISOString(), + ); + + return { cliPath, testDir, configPath: "" }; +} + +/** + * Removes the temp directory created by createSmokeContext. + */ +export async function cleanupSmokeContext(ctx: SmokeTestContext): Promise { + try { + await fs.rm(ctx.testDir, { recursive: true, force: true }); + } catch { + // ignore + } +} + +// Override via SMOKE_MODEL env var. Falls back to claude-3-haiku which is +// widely available and cheap. +const SMOKE_MODEL = + process.env.SMOKE_MODEL || "claude-3-haiku-20240307"; + +/** + * Writes a YAML config that points at the real Anthropic API. + */ +export async function writeAnthropicConfig( + ctx: SmokeTestContext, + apiKey: string, +): Promise { + const yaml = `name: Smoke Test +version: 1.0.0 +schema: v1 +models: + - name: smoke-haiku + model: ${SMOKE_MODEL} + provider: anthropic + apiKey: "${apiKey}" + defaultCompletionOptions: + maxTokens: 1024 + roles: + - chat +`; + const configPath = path.join(ctx.testDir, "smoke-config.yaml"); + await fs.writeFile(configPath, yaml); + ctx.configPath = configPath; + return configPath; +} + +/** + * Writes a YAML config that uses the Continue proxy (CONTINUE_API_KEY). + */ +export async function writeContinueProxyConfig( + ctx: SmokeTestContext, + apiKey: string, +): Promise { + const yaml = `name: Smoke Test +version: 1.0.0 +schema: v1 +models: + - name: smoke-haiku + model: ${SMOKE_MODEL} + provider: continue-proxy + apiKey: "${apiKey}" + defaultCompletionOptions: + maxTokens: 1024 + roles: + - chat +`; + const configPath = path.join(ctx.testDir, "smoke-config.yaml"); + await fs.writeFile(configPath, yaml); + ctx.configPath = configPath; + return configPath; +} + +/** + * Runs `cn` (headless) and returns stdout/stderr/exitCode. + */ +export async function runHeadless( + ctx: SmokeTestContext, + args: string[], + opts: { timeout?: number; env?: Record } = {}, +): Promise<{ stdout: string; stderr: string; exitCode: number }> { + const { timeout = 60000, env = {} } = opts; + + const result = await execaNode(ctx.cliPath, args, { + cwd: ctx.testDir, + env: { + ...process.env, + CONTINUE_CLI_TEST: "true", + HOME: ctx.testDir, + USERPROFILE: ctx.testDir, + FORCE_NO_TTY: "true", + ...env, + }, + timeout, + reject: false, + }); + + return { + stdout: result.stdout, + stderr: result.stderr, + exitCode: result.exitCode ?? 0, + }; +} + +/** + * Spawns `cn serve` as a background subprocess and returns it along with + * a helper to wait for the server to be ready. + */ +export function spawnServe( + ctx: SmokeTestContext, + args: string[], + opts: { env?: Record } = {}, +): Subprocess { + return execaNode(ctx.cliPath, ["serve", ...args], { + cwd: ctx.testDir, + env: { + ...process.env, + CONTINUE_CLI_TEST: "true", + HOME: ctx.testDir, + USERPROFILE: ctx.testDir, + ...opts.env, + }, + reject: false, + }); +} + +/** + * Waits for a pattern to appear in the subprocess stdout/stderr. + */ +export function waitForPattern( + proc: Subprocess, + pattern: string, + timeout = 30000, +): Promise { + return new Promise((resolve, reject) => { + let output = ""; + const timer = setTimeout(() => { + reject( + new Error( + `Timeout (${timeout}ms) waiting for pattern: "${pattern}"\nCollected output:\n${output}`, + ), + ); + }, timeout); + + const check = (data: Buffer | string) => { + output += data.toString(); + if (output.includes(pattern)) { + clearTimeout(timer); + resolve(output); + } + }; + + proc.stdout?.on("data", check); + proc.stderr?.on("data", check); + + proc.on("exit", () => { + clearTimeout(timer); + reject( + new Error( + `Process exited before pattern "${pattern}" was found.\nCollected output:\n${output}`, + ), + ); + }); + }); +} + +/** + * Polls GET /state until the agent has finished processing a response. + * + * Because there is a small gap between POST /message returning and the + * server flipping isProcessing to true, we first wait for isProcessing + * to become true (or for an assistant message to appear), then wait for + * isProcessing to become false. + */ +export async function pollUntilIdle( + baseUrl: string, + timeout = 60000, + interval = 1000, +): Promise { + const deadline = Date.now() + timeout; + let sawProcessing = false; + + while (Date.now() < deadline) { + try { + const res = await fetch(`${baseUrl}/state`); + if (res.ok) { + const state = await res.json(); + + if (state.isProcessing) { + sawProcessing = true; + } + + // Only return when we know the agent actually ran: + // either we saw it processing and it stopped, or there's + // already an assistant message in the history. + if (!state.isProcessing && sawProcessing) { + return state; + } + + const history = state.session?.history ?? []; + const hasAssistant = history.some( + (item: any) => item.message?.role === "assistant", + ); + if (!state.isProcessing && hasAssistant) { + return state; + } + } + } catch { + // server not ready yet — retry + } + await new Promise((r) => setTimeout(r, interval)); + } + + throw new Error(`pollUntilIdle timed out after ${timeout}ms`); +} + +/** + * Gracefully shuts down a serve subprocess via POST /exit, then kills it. + */ +export async function shutdownServe( + proc: Subprocess, + baseUrl: string, +): Promise { + try { + await fetch(`${baseUrl}/exit`, { method: "POST" }); + } catch { + // server may already be gone + } + + // Give it a moment to close gracefully + await new Promise((r) => setTimeout(r, 500)); + + if (!proc.killed) { + proc.kill("SIGTERM"); + } +} diff --git a/extensions/cli/vitest.smoke-api.config.ts b/extensions/cli/vitest.smoke-api.config.ts new file mode 100644 index 000000000..7229dafcf --- /dev/null +++ b/extensions/cli/vitest.smoke-api.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + environment: "node", + // No setupFiles — vitest.setup.ts mocks global.fetch which breaks real API calls + include: ["src/smoke-api/**/*.test.ts"], + testTimeout: 60000, + hookTimeout: 60000, + retry: 2, + // Run sequentially to avoid rate-limiting from real API calls + fileParallelism: false, + sequence: { concurrent: false }, + }, + resolve: { + extensions: [".js", ".ts", ".tsx", ".json"], + }, +});