import * as path from "path" import * as os from "os" import * as fs from "fs/promises" import { readFileSync } from "fs" import { randomBytes } from "crypto" import { downloadAndUnzipVSCode, runTests } from "@vscode/test-electron" import { LLMock } from "@copilotkit/aimock" import { addApplyDiffResultFixtures } from "./fixtures/apply-diff" import { addDeepSeekV4Fixtures } from "./fixtures/deepseek-v4" import { addExecuteCommandResultFixtures } from "./fixtures/execute-command" import { addFastExitShellRaceResultFixtures } from "./fixtures/fast-exit-shell-race" import { addZeroChunkShellRaceResultFixtures } from "./fixtures/zero-chunk-shell-race" import { addTerminalReuseShellRaceFixtures } from "./fixtures/terminal-reuse-shell-race" import { addLongRuningSilentCommandFixtures } from "./fixtures/long-running-silent-command" import { addColdShellInitFixtures } from "./fixtures/cold-shell-init" import { addTerminalProfileResultFixtures } from "./fixtures/terminal-profile" import { addListFilesResultFixtures } from "./fixtures/list-files" import { addReadFileResultFixtures } from "./fixtures/read-file" import { addSearchFilesResultFixtures } from "./fixtures/search-files" import { addSubtaskFixtures } from "./fixtures/subtasks" import { addUseMcpToolResultFixtures } from "./fixtures/use-mcp-tool" import { addWriteToFileResultFixtures } from "./fixtures/write-to-file" import { createScenarioWorkspace, preserveScenarioWorkspace, removeScenarioWorkspace, } from "./restart/scenarioWorkspace" import { runRestartScenario } from "./restart/vscodeCoordinator" function getCliFlagValue(flag: string) { return process.argv.find((arg, index) => process.argv[index - 1] === flag) } function isDeepSeekTargetedRun(testFile?: string, testGrep?: string) { if (testFile?.toLowerCase().includes("deepseek-v4.test")) { return true } // DeepSeek grep runs may target the suite name, file stem, or individual model IDs. return testGrep?.toLowerCase().includes("deepseek") ?? false } function isBedrockTargetedRun(testFile?: string, testGrep?: string) { if (testFile?.toLowerCase().includes("bedrock.test")) { return true } return testGrep?.toLowerCase().includes("bedrock") ?? false } function isRestartPersistenceTargetedRun(testFile?: string, testGrep?: string): boolean { if (testFile?.toLowerCase().includes("restart-persistence")) { return true } return testGrep?.toLowerCase().includes("restart persistence") ?? false } async function main() { const isRecord = process.env.AIMOCK_RECORD === "true" const testGrep = getCliFlagValue("--grep") || process.env.TEST_GREP const testFile = getCliFlagValue("--file") || process.env.TEST_FILE const isDeepSeekTest = isDeepSeekTargetedRun(testFile, testGrep) const isGeminiTest = testFile?.toLowerCase().includes("gemini.test") ?? false const isBedrockTest = isBedrockTargetedRun(testFile, testGrep) const isRestartPersistenceTest = isRestartPersistenceTargetedRun(testFile, testGrep) if (isRecord && isDeepSeekTest && !process.env.DEEPSEEK_API_KEY) { throw new Error("AIMOCK_RECORD=true requires DEEPSEEK_API_KEY to record DeepSeek fixtures") } if (isRecord && isGeminiTest && !process.env.GEMINI_API_KEY && !process.env.GOOGLE_API_KEY) { throw new Error("AIMOCK_RECORD=true requires GEMINI_API_KEY to record Gemini fixtures") } if (isRecord && !isDeepSeekTest && !isGeminiTest && !process.env.OPENROUTER_API_KEY) { throw new Error("AIMOCK_RECORD=true requires OPENROUTER_API_KEY to record fixtures") } // Record mode always needs aimock running (to capture traffic). // Replay mode starts aimock when no real API key is present or USE_MOCK is forced. const hasRealApiKey = isDeepSeekTest ? !!process.env.DEEPSEEK_API_KEY : isBedrockTest ? true // Bedrock test starts its own binary-event-stream mock server when no real token : !!(process.env.OPENROUTER_API_KEY || process.env.ANTHROPIC_API_KEY) const useMock = isRecord || !hasRealApiKey || process.env.USE_MOCK === "true" let mock: InstanceType | undefined const mockApiKey = randomBytes(32).toString("hex") // The folder containing the Extension Manifest package.json // Passed to `--extensionDevelopmentPath` const extensionDevelopmentPath = path.resolve(__dirname, "../../../src") // The path to the extension test script // Passed to --extensionTestsPath const extensionTestsPath = path.resolve(__dirname, "./suite/index") let testWorkspace: string | undefined let scenarioWorkspace: Awaited> | undefined let runFailed = false try { // Create a temporary workspace folder for regular tests. Restart scenarios own // all of their paths under the dedicated scenario root below. if (!isRestartPersistenceTest) { testWorkspace = await fs.mkdtemp(path.join(os.tmpdir(), "roo-test-workspace-")) } if (useMock) { const fixturesDir = path.resolve(__dirname, "../fixtures") mock = new LLMock({ port: 0, // random free port auth: { apiKeys: [mockApiKey] }, ...(isRecord && { record: { // OpenRouter is OpenAI-compatible; aimock proxies using the openai provider key. // Use /api (not /api/v1) — aimock appends the request path (/v1/chat/completions) // so including /v1 here would produce a doubled /v1/v1 upstream URL. providers: { openai: isDeepSeekTest ? "https://api.deepseek.com" : "https://openrouter.ai/api", // Recording credentials are supplied separately through providerKeys. anthropic: "https://api.anthropic.com", // Google AI recording is enabled only for its targeted suite. ...(isGeminiTest && { gemini: "https://generativelanguage.googleapis.com" }), }, // Authenticated aimock requests never forward inbound credentials. providerKeys: { openai: isDeepSeekTest ? process.env.DEEPSEEK_API_KEY : process.env.OPENROUTER_API_KEY, anthropic: process.env.ANTHROPIC_API_KEY, gemini: process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY, }, fixturePath: fixturesDir, }, }), }) mock.loadFixtureDir(fixturesDir) if (!isRecord) { addApplyDiffResultFixtures(mock) addExecuteCommandResultFixtures(mock) addFastExitShellRaceResultFixtures(mock) addZeroChunkShellRaceResultFixtures(mock) addTerminalReuseShellRaceFixtures(mock) addLongRuningSilentCommandFixtures(mock) addColdShellInitFixtures(mock) addTerminalProfileResultFixtures(mock) addListFilesResultFixtures(mock) addReadFileResultFixtures(mock) addSearchFilesResultFixtures(mock) addSubtaskFixtures(mock) addUseMcpToolResultFixtures(mock) addWriteToFileResultFixtures(mock) addDeepSeekV4Fixtures(mock) // The modes test (switch_mode → ask) triggers a second API call whose last // user message starts with directly — no // wrapper. JSON fixtures use substring matching so a bare "" // match would collide with all other requests. A regex anchored to the start // uniquely identifies this post-switch turn. Scope this fixture to the // OpenRouter default model so provider-specific suites (e.g. DeepSeek) // cannot accidentally match it. mock.addFixture({ match: { model: "openai/gpt-4.1", userMessage: /^/ }, response: { toolCalls: [ { name: "attempt_completion", arguments: JSON.stringify({ result: "Switched to ❓ Ask mode as requested." }), id: "call_modes_post_switch_001", }, ], }, }) } await mock.start() } // Get test filter from command line arguments or environment variable // Usage examples: // - npm run test:e2e -- --grep "write-to-file" // - TEST_GREP="apply-diff" npm run test:e2e // - TEST_FILE="task.test.js" npm run test:e2e // Pass test filters and mock URL as environment variables to the test runner const extensionTestsEnv = { ...process.env, ...(testGrep && { TEST_GREP: testGrep }), ...(testFile && { TEST_FILE: testFile }), ...(mock && { AIMOCK_URL: mock.url, E2E_AIMOCK_API_KEY: mockApiKey }), ...(mock && { E2E_MOCK_MODEL_LIST_FALLBACK: "true" }), } // Download VS Code, unzip it and run the integration test // Read VS Code version from package.json to keep in sync with @types/vscode const pkg = JSON.parse(readFileSync(path.resolve(__dirname, "../package.json"), "utf-8")) const vscodeVersion = process.env.VSCODE_VERSION || pkg.devDependencies["@types/vscode"] if (isRestartPersistenceTest) { scenarioWorkspace = await createScenarioWorkspace() const vscodeExecutablePath = await downloadAndUnzipVSCode({ version: vscodeVersion, extensionDevelopmentPath, }) await runRestartScenario({ vscodeExecutablePath, extensionDevelopmentPath, extensionTestsPath, scenario: "restart-persistence", workspace: scenarioWorkspace, environment: extensionTestsEnv, expectedExitPolicies: [ { phase: "create", termination: "graceful-quit", code: 1, signal: null }, { phase: "verify", termination: "graceful-quit", code: 1, signal: null }, ], }) } else { if (!testWorkspace) { throw new Error("Regular E2E runs require a temporary test workspace") } await runTests({ extensionDevelopmentPath, extensionTestsPath, launchArgs: [testWorkspace], extensionTestsEnv, version: vscodeVersion, }) } } catch (error) { runFailed = true console.error("Failed to run tests", error) process.exitCode = 1 } finally { if (testWorkspace) { await fs.rm(testWorkspace, { recursive: true, force: true }) } if (scenarioWorkspace) { // A failed restart scenario must stay inspectable: the phase // results, VS Code logs, and task files are copied to a stable // directory for CI artifact upload before the temp root goes away. if (runFailed) { try { const preservedAt = await preserveScenarioWorkspace(scenarioWorkspace) console.error(`Restart scenario workspace preserved for failure inspection: ${preservedAt}`) } catch (preserveError) { console.error("Failed to preserve the restart scenario workspace:", preserveError) } } else { await removeScenarioWorkspace(scenarioWorkspace) } } await mock?.stop() } } main().catch((error) => { console.error("Failed to initialize or clean up tests", error) process.exitCode = 1 })