Repository navigation
Expand file tree
/
Copy pathrunTest.ts
More file actions
292 lines (261 loc) · 11 KB
/
Copy pathrunTest.ts
File metadata and controls
292 lines (261 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import * as path from "path"
import * as os from "os"
import * as fs from "fs/promises"
import { readFileSync } from "fs"
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"
import { toolResultContains } from "./fixtures/tool-result"
import { addViewStateFixtures } from "./fixtures/view-state"
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<typeof LLMock> | undefined
// 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<ReturnType<typeof createScenarioWorkspace>> | 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
...(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",
// aimock forwards the x-api-key header from the Anthropic SDK to the real API.
anthropic: "https://api.anthropic.com",
// aimock forwards the x-goog-api-key header from the Google AI SDK.
...(isGeminiTest && { gemini: "https://generativelanguage.googleapis.com" }),
},
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)
addViewStateFixtures(mock)
// Model-agnostic predicate fixtures for the view-state suite's post-switch
// turns. They coexist with the legacy model-scoped regex fixture below
// (shared response id call_modes_post_switch_001) so the modes suite keeps
// its OpenRouter-scoped match while view-state runs under any default model.
mock.addFixture({
match: {
predicate: (req) => toolResultContains(req, "call_modes_switch_001", []),
},
response: {
toolCalls: [
{
name: "attempt_completion",
arguments: JSON.stringify({ result: "Switched to ❓ Ask mode as requested." }),
id: "call_modes_post_switch_001",
},
],
},
})
mock.addFixture({
match: {
predicate: (req) => toolResultContains(req, "call_modes_switch_002", []),
},
response: {
toolCalls: [
{
name: "attempt_completion",
arguments: JSON.stringify({ result: "Switched to 🪲 Debug mode as requested." }),
id: "call_modes_post_switch_002",
},
],
},
})
// The modes test (switch_mode → ask) triggers a second API call whose last
// user message starts with <environment_details> directly — no <user_message>
// wrapper. JSON fixtures use substring matching so a bare "<environment_details>"
// 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: /^<environment_details>/ },
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 }),
...(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
})