Elffuss BraidHub

kikocis/continue public

chore: run prettier --write on cli
Changeset8f5864c6cb09ddcb0a35acdfbc779eddc2306491039c158e24de77f79af78f07
AuthorNate <sestinj@gmail.com> · 2025-08-20 17:57 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-20 17:57 -07:00
Parents6330d6e8d792

Browse the files at this changeset

101 files changed

modified extensions/cli/AGENTS.md +5 −0
@@ -18,25 +18,30 @@
1818 ### Core Components
1919
2020 1. **Entry Point** (`src/index.ts`): Main CLI logic with two modes:
21+
2122 - **Headless mode**: Non-interactive mode for automation/CI
2223 - **TUI mode**: Terminal User Interface using Ink/React
2324 - **Standard mode**: Traditional readline-based chat interface
2425
2526 2. **Authentication** (`src/auth/`): WorkOS-based authentication system
27+
2628 - `ensureAuth.ts`: Handles authentication flow
2729 - `workos.ts`: WorkOS configuration and token management
2830
2931 3. **Continue SDK Integration** (`src/continueSDK.ts`): Initializes the Continue SDK client with:
32+
3033 - API key authentication
3134 - Assistant configuration (slug-based)
3235 - Organization support
3336
3437 4. **Terminal UI** (`src/ui/`): React/Ink-based TUI components
38+
3539 - `TUIChat.tsx`: Main chat interface component
3640 - `UserInput.tsx`: Input handling with multi-line support
3741 - `TextBuffer.ts`: Text display utilities
3842
3943 5. **Tools System** (`src/tools/`): Built-in development tools including:
44+
4045 - File operations (read, write, list)
4146 - Code search functionality
4247 - Terminal command execution
modified extensions/cli/spec/config-loading.md +2 −0
@@ -23,11 +23,13 @@
2323 **When CLI is invoked, config source is determined in this order:**
2424
2525 1. **CLI `--config` Flag** (highest priority)
26+
2627 - File path (starts with `.`, `/`, `~`): Loads local YAML file
2728 - Assistant slug (`owner/package`): Fetches from Continue platform
2829 - Overrides any saved preferences
2930
3031 2. **Saved Config URI** (if no `--config` flag)
32+
3133 - Retrieved from authentication config
3234 - Converts `file://` URIs back to file paths
3335 - Converts `slug://` URIs back to assistant slugs
modified extensions/cli/spec/onboarding.md +1 −0
@@ -8,6 +8,7 @@
88
99 1. If the --config flag is provided, load this config
1010 2. Otherwise, we will present the user with two options:
11+
1112 - Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org
1213 - Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model
1314
modified extensions/cli/src/args.test.ts +33 −32
@@ -1,4 +1,4 @@
1-import { vi } from 'vitest';
1+import { vi } from "vitest";
22
33 import { parseArgs, processRule } from "./args.js";
44
@@ -20,7 +20,6 @@
2020 expect(result).toEqual({});
2121 });
2222
23-
2423 it("should set resume to true when --resume flag is present", () => {
2524 process.argv = ["node", "script.js", "--resume"];
2625 const result = parseArgs();
@@ -33,7 +32,6 @@
3332 expect(result.readonly).toBe(true);
3433 });
3534
36-
3735 it("should parse config path from --config flag", () => {
3836 process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"];
3937 const result = parseArgs();
@@ -189,8 +187,7 @@
189187 it("should handle empty arguments array", () => {
190188 process.argv = ["node", "script.js"];
191189 const result = parseArgs();
192- expect(result).toEqual({
193- });
190+ expect(result).toEqual({});
194191 });
195192
196193 it("should handle multiple boolean flags", () => {
@@ -224,7 +221,7 @@
224221 // Mock fetch for hub tests
225222 const originalFetch = global.fetch;
226223 const mockFetch = vi.fn() as any;
227-
224+
228225 beforeAll(() => {
229226 global.fetch = mockFetch;
230227 });
@@ -232,7 +229,7 @@
232229 afterAll(() => {
233230 global.fetch = originalFetch;
234231 });
235-
232+
236233 beforeEach(() => {
237234 mockFetch.mockClear();
238235 });
@@ -242,11 +239,12 @@
242239 // Create a mock zip file containing a markdown rule
243240 const JSZip = (await import("jszip")).default;
244241 const zip = new JSZip();
245- const ruleContent = "# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications.";
242+ const ruleContent =
243+ "# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications.";
246244 zip.file("rule.md", ruleContent);
247-
245+
248246 const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
249-
247+
250248 // Mock successful fetch response
251249 mockFetch.mockResolvedValue({
252250 ok: true,
@@ -254,10 +252,13 @@
254252 } as Response);
255253
256254 const result = await processRule("continuedev/sentry-nextjs");
257-
255+
258256 expect(result).toBe(ruleContent);
259257 expect(mockFetch).toHaveBeenCalledWith(
260- new URL("v0/continuedev/sentry-nextjs/latest/download", "https://api.continue.dev/")
258+ new URL(
259+ "v0/continuedev/sentry-nextjs/latest/download",
260+ "https://api.continue.dev/",
261+ ),
261262 );
262263 });
263264
@@ -269,7 +270,7 @@
269270 } as Response);
270271
271272 await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow(
272- 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found'
273+ 'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found',
273274 );
274275 });
275276
@@ -277,7 +278,7 @@
277278 mockFetch.mockRejectedValue(new Error("Network error"));
278279
279280 await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow(
280- 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error'
281+ 'Failed to load rule from hub "continuedev/sentry-nextjs": Network error',
281282 );
282283 });
283284
@@ -285,7 +286,7 @@
285286 // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug
286287 // Let's test with a slug that has wrong format but contains "/"
287288 await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow(
288- 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts'
289+ 'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts',
289290 );
290291 });
291292
@@ -293,14 +294,14 @@
293294 const JSZip = (await import("jszip")).default;
294295 const zip = new JSZip();
295296 const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
296-
297+
297298 mockFetch.mockResolvedValue({
298299 ok: true,
299300 arrayBuffer: () => Promise.resolve(zipBuffer),
300301 } as Response);
301302
302303 await expect(processRule("continuedev/empty-rule")).rejects.toThrow(
303- 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file'
304+ 'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file',
304305 );
305306 });
306307
@@ -309,14 +310,14 @@
309310 const zip = new JSZip();
310311 zip.folder("docs"); // Create a directory but no files
311312 const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
312-
313+
313314 mockFetch.mockResolvedValue({
314315 ok: true,
315316 arrayBuffer: () => Promise.resolve(zipBuffer),
316317 } as Response);
317318
318319 await expect(processRule("continuedev/directory-only")).rejects.toThrow(
319- 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file'
320+ 'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file',
320321 );
321322 });
322323
@@ -325,20 +326,20 @@
325326 const zip = new JSZip();
326327 const mdContent = "# Main Rule\n\nThis is the markdown rule content.";
327328 const txtContent = "This is just a text file.";
328-
329+
329330 zip.file("README.txt", txtContent);
330331 zip.file("rule.md", mdContent);
331332 zip.file("package.json", '{"name": "test"}');
332-
333+
333334 const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
334-
335+
335336 mockFetch.mockResolvedValue({
336337 ok: true,
337338 arrayBuffer: () => Promise.resolve(zipBuffer),
338339 } as Response);
339340
340341 const result = await processRule("continuedev/mixed-files");
341-
342+
342343 expect(result).toBe(mdContent);
343344 });
344345
@@ -347,33 +348,33 @@
347348 const zip = new JSZip();
348349 const rule1Content = "# First Rule\n\nThis is the first rule.";
349350 const rule2Content = "# Second Rule\n\nThis is the second rule.";
350-
351+
351352 zip.file("rule1.md", rule1Content);
352353 zip.file("rule2.md", rule2Content);
353-
354+
354355 const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
355-
356+
356357 mockFetch.mockResolvedValue({
357358 ok: true,
358359 arrayBuffer: () => Promise.resolve(zipBuffer),
359360 } as Response);
360361
361362 const result = await processRule("continuedev/multiple-rules");
362-
363+
363364 // Should use the first markdown file found (alphabetically)
364365 expect(result).toBe(rule1Content);
365366 });
366367
367368 it("should handle malformed zip files", async () => {
368369 const invalidZipBuffer = new ArrayBuffer(10);
369-
370+
370371 mockFetch.mockResolvedValue({
371372 ok: true,
372373 arrayBuffer: () => Promise.resolve(invalidZipBuffer),
373374 } as Response);
374375
375376 await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow(
376- 'Failed to load rule from hub "continuedev/corrupted-zip"'
377+ 'Failed to load rule from hub "continuedev/corrupted-zip"',
377378 );
378379 });
379380 });
@@ -384,7 +385,7 @@
384385 const zip = new JSZip();
385386 zip.file("rule.md", "# Hub Rule");
386387 const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
387-
388+
388389 mockFetch.mockResolvedValue({
389390 ok: true,
390391 arrayBuffer: () => Promise.resolve(zipBuffer),
@@ -406,9 +407,9 @@
406407 // This would be treated as a file path, not a hub slug
407408 // since it starts with "."
408409 await expect(processRule("./owner/package")).rejects.toThrow(
409- 'Failed to read rule file "./owner/package": Rule file not found'
410+ 'Failed to read rule file "./owner/package": Rule file not found',
410411 );
411412 expect(mockFetch).not.toHaveBeenCalled();
412413 });
413414 });
414-});
No newline at the end of the file
415+});
modified extensions/cli/src/asciiArt.test.ts +7 −7
@@ -4,7 +4,7 @@
44
55 describe("asciiArt", () => {
66 let originalColumns: number | undefined;
7-
7+
88 beforeEach(() => {
99 originalColumns = process.stdout.columns;
1010 });
@@ -23,7 +23,7 @@
2323 process.stdout.columns = 80;
2424
2525 const result = getDisplayableAsciiArt();
26-
26+
2727 expect(result).toBe(CONTINUE_ASCII_ART);
2828 });
2929
@@ -32,7 +32,7 @@
3232 process.stdout.columns = 60;
3333
3434 const result = getDisplayableAsciiArt();
35-
35+
3636 expect(result).toContain("CONTINUE");
3737 expect(result).toContain("v0.0.0-dev");
3838 expect(result).not.toBe(CONTINUE_ASCII_ART);
@@ -45,7 +45,7 @@
4545 process.stdout.columns = 74;
4646
4747 const result = getDisplayableAsciiArt();
48-
48+
4949 expect(result).toContain("CONTINUE");
5050 expect(result).not.toBe(CONTINUE_ASCII_ART);
5151 });
@@ -55,7 +55,7 @@
5555 process.stdout.columns = 75;
5656
5757 const result = getDisplayableAsciiArt();
58-
58+
5959 expect(result).toBe(CONTINUE_ASCII_ART);
6060 });
6161
@@ -64,8 +64,8 @@
6464 delete (process.stdout as any).columns;
6565
6666 const result = getDisplayableAsciiArt();
67-
67+
6868 expect(result).toBe(CONTINUE_ASCII_ART);
6969 });
7070 });
71-});
No newline at the end of the file
71+});
modified extensions/cli/src/auth/workos-org.test.ts +7 −7
@@ -79,12 +79,12 @@
7979 const consoleInfoSpy = vi.spyOn(console, "info");
8080
8181 await expect(
82- ensureOrganization(mockAuthConfig, true, "invalid-org")
82+ ensureOrganization(mockAuthConfig, true, "invalid-org"),
8383 ).rejects.toThrow('Organization "invalid-org" not found');
8484
8585 expect(consoleInfoSpy).toHaveBeenCalledWith(
8686 chalk.yellow("Available organizations:"),
87- expect.stringContaining("personal")
87+ expect.stringContaining("personal"),
8888 );
8989 });
9090 });
@@ -99,13 +99,13 @@
9999 });
100100
101101 await expect(
102- ensureOrganization(mockAuthConfig, false, "org-one")
102+ ensureOrganization(mockAuthConfig, false, "org-one"),
103103 ).rejects.toThrow("Process exit");
104104
105105 expect(consoleErrorSpy).toHaveBeenCalledWith(
106106 chalk.red(
107- "The --org flag is only supported in headless mode (with -p/--print flag)"
108- )
107+ "The --org flag is only supported in headless mode (with -p/--print flag)",
108+ ),
109109 );
110110 expect(processExitSpy).toHaveBeenCalledWith(1);
111111
@@ -141,7 +141,7 @@
141141 const result = await ensureOrganization(
142142 mockEnvAuthConfig,
143143 true,
144- "org-two"
144+ "org-two",
145145 );
146146
147147 expect(result).toMatchObject({
@@ -192,7 +192,7 @@
192192 vi.mocked(getApiClient).mockReturnValue(apiClient as any);
193193
194194 await expect(
195- ensureOrganization(mockAuthConfig, true, "org-one")
195+ ensureOrganization(mockAuthConfig, true, "org-one"),
196196 ).rejects.toThrow("API Error");
197197 });
198198 });
modified extensions/cli/src/commands/commands.integration.test.ts +59 −42
@@ -1,68 +1,85 @@
1-import type { AssistantConfig } from '@continuedev/sdk';
2-import { describe, expect, it } from 'vitest';
1+import type { AssistantConfig } from "@continuedev/sdk";
2+import { describe, expect, it } from "vitest";
33
4-import { getAllSlashCommands } from './commands.js';
4+import { getAllSlashCommands } from "./commands.js";
55
6-describe('Slash Commands Integration', () => {
6+describe("Slash Commands Integration", () => {
77 const mockAssistant: AssistantConfig = {
8- name: 'test-assistant',
9- version: '1.0.0',
8+ name: "test-assistant",
9+ version: "1.0.0",
1010 prompts: [
11- { name: 'test-prompt', prompt: 'Test prompt', description: 'Test prompt description' }
12- ]
11+ {
12+ name: "test-prompt",
13+ prompt: "Test prompt",
14+ description: "Test prompt description",
15+ },
16+ ],
1317 };
1418
15- describe('System Commands Registration', () => {
16- it('should include all system commands in the commands list', () => {
19+ describe("System Commands Registration", () => {
20+ it("should include all system commands in the commands list", () => {
1721 const commands = getAllSlashCommands(mockAssistant);
18- const commandNames = commands.map(cmd => cmd.name);
19-
22+ const commandNames = commands.map((cmd) => cmd.name);
23+
2024 // Check that system commands are present (mode commands have been removed)
21- expect(commandNames).toContain('help');
22- expect(commandNames).toContain('clear');
23- expect(commandNames).toContain('exit');
24- expect(commandNames).toContain('login');
25- expect(commandNames).toContain('logout');
26- expect(commandNames).toContain('whoami');
27-
28- expect(commandNames).toContain('model');
29- expect(commandNames).toContain('config');
25+ expect(commandNames).toContain("help");
26+ expect(commandNames).toContain("clear");
27+ expect(commandNames).toContain("exit");
28+ expect(commandNames).toContain("login");
29+ expect(commandNames).toContain("logout");
30+ expect(commandNames).toContain("whoami");
31+
32+ expect(commandNames).toContain("model");
33+ expect(commandNames).toContain("config");
3034 });
3135
32- it('should include assistant prompt commands', () => {
36+ it("should include assistant prompt commands", () => {
3337 const commands = getAllSlashCommands(mockAssistant);
34- const commandNames = commands.map(cmd => cmd.name);
35-
36- expect(commandNames).toContain('test-prompt');
38+ const commandNames = commands.map((cmd) => cmd.name);
39+
40+ expect(commandNames).toContain("test-prompt");
3741 });
3842
39- it('should categorize system commands correctly', () => {
43+ it("should categorize system commands correctly", () => {
4044 const commands = getAllSlashCommands(mockAssistant);
41- const systemCommands = commands.filter(cmd =>
42- ['help', 'clear', 'exit', 'login', 'logout', 'whoami', 'model', 'config'].includes(cmd.name)
45+ const systemCommands = commands.filter((cmd) =>
46+ [
47+ "help",
48+ "clear",
49+ "exit",
50+ "login",
51+ "logout",
52+ "whoami",
53+ "model",
54+ "config",
55+ ].includes(cmd.name),
4356 );
44-
45- systemCommands.forEach(cmd => {
46- expect(cmd.category).toBe('system');
57+
58+ systemCommands.forEach((cmd) => {
59+ expect(cmd.category).toBe("system");
4760 });
4861 });
4962
50- it('should categorize assistant commands correctly', () => {
63+ it("should categorize assistant commands correctly", () => {
5164 const commands = getAllSlashCommands(mockAssistant);
52- const assistantCommands = commands.filter(cmd => cmd.name === 'test-prompt');
53-
54- assistantCommands.forEach(cmd => {
55- expect(cmd.category).toBe('assistant');
65+ const assistantCommands = commands.filter(
66+ (cmd) => cmd.name === "test-prompt",
67+ );
68+
69+ assistantCommands.forEach((cmd) => {
70+ expect(cmd.category).toBe("assistant");
5671 });
5772 });
5873
59- it('should only show exit command in remote mode', () => {
60- const commands = getAllSlashCommands(mockAssistant, { isRemoteMode: true });
61- const commandNames = commands.map(cmd => cmd.name);
62-
74+ it("should only show exit command in remote mode", () => {
75+ const commands = getAllSlashCommands(mockAssistant, {
76+ isRemoteMode: true,
77+ });
78+ const commandNames = commands.map((cmd) => cmd.name);
79+
6380 // In remote mode, only exit command should be available
64- expect(commandNames).toContain('exit');
81+ expect(commandNames).toContain("exit");
6582 expect(commandNames).toHaveLength(1);
6683 });
6784 });
68-});
No newline at the end of the file
85+});
modified extensions/cli/src/commands/ls.test.ts +25 −21
@@ -32,7 +32,7 @@
3232
3333 describe("listSessionsCommand", () => {
3434 const mockListSessions = vi.mocked(sessionModule.listSessions);
35-
35+
3636 beforeEach(() => {
3737 vi.clearAllMocks();
3838 });
@@ -51,7 +51,7 @@
5151 firstUserMessage: "Hello world",
5252 },
5353 {
54- id: "session-2",
54+ id: "session-2",
5555 path: "/path/to/session2.json",
5656 timestamp: new Date("2023-01-01T09:00:00Z"),
5757 messageCount: 3,
@@ -66,22 +66,26 @@
6666 await listSessionsCommand({ format: "json" });
6767
6868 expect(consoleSpy).toHaveBeenCalledWith(
69- JSON.stringify({
70- sessions: [
71- {
72- id: "session-1",
73- timestamp: "2023-01-01T10:00:00.000Z",
74- messageCount: 5,
75- firstUserMessage: "Hello world",
76- },
77- {
78- id: "session-2",
79- timestamp: "2023-01-01T09:00:00.000Z",
80- messageCount: 3,
81- firstUserMessage: "Test message",
82- },
83- ],
84- }, null, 2)
69+ JSON.stringify(
70+ {
71+ sessions: [
72+ {
73+ id: "session-1",
74+ timestamp: "2023-01-01T10:00:00.000Z",
75+ messageCount: 5,
76+ firstUserMessage: "Hello world",
77+ },
78+ {
79+ id: "session-2",
80+ timestamp: "2023-01-01T09:00:00.000Z",
81+ messageCount: 3,
82+ firstUserMessage: "Test message",
83+ },
84+ ],
85+ },
86+ null,
87+ 2,
88+ ),
8589 );
8690
8791 consoleSpy.mockRestore();
@@ -107,7 +111,7 @@
107111 await listSessionsCommand({ format: "json" });
108112
109113 expect(consoleSpy).toHaveBeenCalledWith(
110- JSON.stringify({ sessions: [] }, null, 2)
114+ JSON.stringify({ sessions: [] }, null, 2),
111115 );
112116
113117 consoleSpy.mockRestore();
@@ -121,9 +125,9 @@
121125 await listSessionsCommand({});
122126
123127 expect(consoleSpy).toHaveBeenCalledWith(
124- "No previous sessions found. Start a new conversation with: cn"
128+ "No previous sessions found. Start a new conversation with: cn",
125129 );
126130
127131 consoleSpy.mockRestore();
128132 });
129-});
No newline at the end of the file
133+});
modified extensions/cli/src/commands/remote.test.ts +70 −71
@@ -9,14 +9,10 @@
99 vi.mock("../ui/index.js");
1010 vi.mock("../util/git.js");
1111
12-const mockWorkos = vi.mocked(
13- await import("../auth/workos.js")
14-);
12+const mockWorkos = vi.mocked(await import("../auth/workos.js"));
1513 const mockEnv = vi.mocked(await import("../env.js"));
1614 const mockGit = vi.mocked(await import("../util/git.js"));
17-const mockStartRemoteTUIChat = vi.mocked(
18- await import("../ui/index.js")
19-);
15+const mockStartRemoteTUIChat = vi.mocked(await import("../ui/index.js"));
2016
2117 // Mock fetch globally
2218 const mockFetch = vi.fn();
@@ -36,12 +32,12 @@
3632 describe("remote command", () => {
3733 beforeEach(() => {
3834 vi.clearAllMocks();
39-
35+
4036 // Clear GitHub Actions environment variables
4137 delete process.env.GITHUB_ACTIONS;
4238 delete process.env.GITHUB_REPOSITORY;
4339 delete process.env.GITHUB_SERVER_URL;
44-
40+
4541 // Setup default mocks
4642 mockWorkos.loadAuthConfig.mockReturnValue({
4743 userId: "test-user-id",
@@ -51,19 +47,19 @@
5147 expiresAt: Date.now() + 3600000,
5248 organizationId: null,
5349 });
54-
50+
5551 mockWorkos.isAuthenticatedConfig.mockReturnValue(true);
5652 mockWorkos.getAccessToken.mockReturnValue("test-token");
57-
53+
5854 mockEnv.env = {
5955 apiBase: "https://api.example.com",
6056 workOsClientId: "test-client-id",
6157 appUrl: "https://test.example.com",
6258 continueHome: "/tmp/test-continue-home",
6359 };
64-
60+
6561 mockGit.getRepoUrl.mockReturnValue("https://github.com/user/test-repo.git");
66-
62+
6763 mockFetch.mockResolvedValue({
6864 ok: true,
6965 json: async () => ({
@@ -72,15 +68,15 @@
7268 port: 8080,
7369 }),
7470 });
75-
71+
7672 mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any);
7773 });
7874
7975 it("should include idempotency key in request body when provided", async () => {
8076 const testIdempotencyKey = "test-idempotency-key-123";
81-
77+
8278 await remote("test prompt", { idempotencyKey: testIdempotencyKey });
83-
79+
8480 expect(mockFetch).toHaveBeenCalledWith(
8581 new URL("agents/devboxes", mockEnv.env.apiBase),
8682 expect.objectContaining({
@@ -89,14 +85,16 @@
8985 "Content-Type": "application/json",
9086 Authorization: "Bearer test-token",
9187 },
92- body: expect.stringContaining(`"idempotencyKey":"${testIdempotencyKey}"`),
93- })
88+ body: expect.stringContaining(
89+ `"idempotencyKey":"${testIdempotencyKey}"`,
90+ ),
91+ }),
9492 );
9593 });
9694
9795 it("should not include idempotency key in request body when not provided", async () => {
9896 await remote("test prompt", {});
99-
97+
10098 expect(mockFetch).toHaveBeenCalledWith(
10199 new URL("agents/devboxes", mockEnv.env.apiBase),
102100 expect.objectContaining({
@@ -106,57 +104,55 @@
106104 Authorization: "Bearer test-token",
107105 },
108106 body: expect.not.stringContaining("idempotencyKey"),
109- })
107+ }),
110108 );
111109 });
112110
113-
114-
115111 it("should work with direct URL connection and idempotency key", async () => {
116112 const testUrl = "ws://direct-url.com";
117113 const testIdempotencyKey = "direct-key-789";
118-
119- await remote("test prompt", {
120- url: testUrl,
121- idempotencyKey: testIdempotencyKey
114+
115+ await remote("test prompt", {
116+ url: testUrl,
117+ idempotencyKey: testIdempotencyKey,
122118 });
123-
119+
124120 // Should not make POST request when connecting directly to URL
125121 expect(mockFetch).not.toHaveBeenCalled();
126-
122+
127123 // Should connect directly to the provided URL
128124 expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
129125 testUrl,
130- "test prompt"
126+ "test prompt",
131127 );
132128 });
133129
134130 it("should ignore --start flag when --url is provided without --start", async () => {
135131 const testUrl = "ws://direct-url.com";
136-
132+
137133 await remote("test prompt", { url: testUrl });
138-
134+
139135 // Should not make POST request when connecting directly to URL
140136 expect(mockFetch).not.toHaveBeenCalled();
141-
137+
142138 // Should connect directly to the provided URL and start TUI
143139 expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
144140 testUrl,
145- "test prompt"
141+ "test prompt",
146142 );
147-
143+
148144 // Should not output JSON
149145 expect(mockConsoleLog).not.toHaveBeenCalled();
150146 });
151147
152148 it("should handle proper request body structure with all fields", async () => {
153149 const testIdempotencyKey = "structured-test-key";
154-
150+
155151 await remote("test prompt", { idempotencyKey: testIdempotencyKey });
156-
152+
157153 const fetchCall = mockFetch.mock.calls[0];
158154 const requestBody = JSON.parse(fetchCall[1].body);
159-
155+
160156 expect(requestBody).toEqual({
161157 repoUrl: "https://github.com/user/test-repo.git",
162158 name: expect.stringMatching(/^devbox-\d+$/),
@@ -167,7 +163,7 @@
167163
168164 it("should call getRepoUrl to get the current repository URL", async () => {
169165 await remote("test prompt", {});
170-
166+
171167 expect(mockGit.getRepoUrl).toHaveBeenCalled();
172168 });
173169
@@ -175,24 +171,24 @@
175171 // Simulate GitHub Actions environment
176172 process.env.GITHUB_ACTIONS = "true";
177173 process.env.GITHUB_REPOSITORY = "myorg/myrepo";
178-
174+
179175 // Mock getRepoUrl to return the GitHub Actions URL
180176 mockGit.getRepoUrl.mockReturnValue("https://github.com/myorg/myrepo.git");
181-
177+
182178 await remote("test prompt", { idempotencyKey: "github-actions-key" });
183-
179+
184180 const fetchCall = mockFetch.mock.calls[0];
185181 const requestBody = JSON.parse(fetchCall[1].body);
186-
182+
187183 expect(requestBody.repoUrl).toBe("https://github.com/myorg/myrepo.git");
188184 expect(requestBody.idempotencyKey).toBe("github-actions-key");
189185 });
190186
191187 it("should include branchName in request body when branch option is provided", async () => {
192188 const testBranch = "feature/new-feature";
193-
189+
194190 await remote("test prompt", { branch: testBranch });
195-
191+
196192 expect(mockFetch).toHaveBeenCalledWith(
197193 new URL("agents/devboxes", mockEnv.env.apiBase),
198194 expect.objectContaining({
@@ -202,13 +198,13 @@
202198 Authorization: "Bearer test-token",
203199 },
204200 body: expect.stringContaining(`"branchName":"${testBranch}"`),
205- })
201+ }),
206202 );
207203 });
208204
209205 it("should not include branchName in request body when branch option is not provided", async () => {
210206 await remote("test prompt", {});
211-
207+
212208 expect(mockFetch).toHaveBeenCalledWith(
213209 new URL("agents/devboxes", mockEnv.env.apiBase),
214210 expect.objectContaining({
@@ -218,22 +214,22 @@
218214 Authorization: "Bearer test-token",
219215 },
220216 body: expect.not.stringContaining("branchName"),
221- })
217+ }),
222218 );
223219 });
224220
225221 it("should handle proper request body structure with branch field", async () => {
226222 const testBranch = "main";
227223 const testIdempotencyKey = "test-with-branch";
228-
229- await remote("test prompt", {
230- branch: testBranch,
231- idempotencyKey: testIdempotencyKey
224+
225+ await remote("test prompt", {
226+ branch: testBranch,
227+ idempotencyKey: testIdempotencyKey,
232228 });
233-
229+
234230 const fetchCall = mockFetch.mock.calls[0];
235231 const requestBody = JSON.parse(fetchCall[1].body);
236-
232+
237233 expect(requestBody).toEqual({
238234 repoUrl: "https://github.com/user/test-repo.git",
239235 name: expect.stringMatching(/^devbox-\d+$/),
@@ -246,29 +242,29 @@
246242 describe("start mode (-s / --start flag)", () => {
247243 it("should output JSON and exit without starting TUI when using --start with direct URL", async () => {
248244 const testUrl = "ws://test-url.com";
249-
245+
250246 await remote("test prompt", { url: testUrl, start: true });
251-
247+
252248 // Should not start TUI
253249 expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
254-
250+
255251 // Should not make POST request
256252 expect(mockFetch).not.toHaveBeenCalled();
257-
253+
258254 // Should output JSON
259255 expect(mockConsoleLog).toHaveBeenCalledWith(
260256 JSON.stringify({
261257 status: "success",
262258 message: "Remote environment connection details",
263259 url: testUrl,
264- mode: "direct_url"
265- })
260+ mode: "direct_url",
261+ }),
266262 );
267263 });
268264
269265 it("should create remote environment, output JSON, and exit without starting TUI when using --start", async () => {
270266 await remote("test prompt", { start: true });
271-
267+
272268 // Should make POST request to create environment
273269 expect(mockFetch).toHaveBeenCalledWith(
274270 new URL("agents/devboxes", mockEnv.env.apiBase),
@@ -278,16 +274,16 @@
278274 "Content-Type": "application/json",
279275 Authorization: "Bearer test-token",
280276 },
281- })
277+ }),
282278 );
283-
279+
284280 // Should not start TUI
285281 expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
286-
282+
287283 // Should output JSON with environment details
288284 const consoleLogCall = mockConsoleLog.mock.calls[0][0];
289285 const outputJson = JSON.parse(consoleLogCall);
290-
286+
291287 expect(outputJson).toEqual({
292288 status: "success",
293289 message: "Remote development environment created successfully",
@@ -295,27 +291,30 @@
295291 containerUrl: "ws://test-url.com",
296292 containerPort: 8080,
297293 name: expect.stringMatching(/^devbox-\d+$/),
298- mode: "new_environment"
294+ mode: "new_environment",
299295 });
300296 });
301297
302298 it("should work with start mode and idempotency key", async () => {
303299 const testIdempotencyKey = "start-mode-key";
304-
305- await remote("test prompt", { start: true, idempotencyKey: testIdempotencyKey });
306-
300+
301+ await remote("test prompt", {
302+ start: true,
303+ idempotencyKey: testIdempotencyKey,
304+ });
305+
307306 // Should include idempotency key in request
308307 const fetchCall = mockFetch.mock.calls[0];
309308 const requestBody = JSON.parse(fetchCall[1].body);
310309 expect(requestBody.idempotencyKey).toBe(testIdempotencyKey);
311-
310+
312311 // Should not start TUI
313312 expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
314-
313+
315314 // Should output JSON
316315 expect(mockConsoleLog).toHaveBeenCalledWith(
317- expect.stringContaining('"status":"success"')
316+ expect.stringContaining('"status":"success"'),
318317 );
319318 });
320319 });
321-});
No newline at the end of the file
320+});
modified extensions/cli/src/commands/serve.test.ts +16 −21
@@ -1,13 +1,6 @@
11 import type { Server } from "http";
22
3-import {
4- afterEach,
5- beforeEach,
6- describe,
7- expect,
8- it,
9- vi,
10-} from "vitest";
3+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
114
125 import { createMinimalTestContext } from "../test-helpers/ui-test-context.js";
136
@@ -40,7 +33,7 @@
4033 config: { models: [] },
4134 llmApi: { chat: vi.fn() },
4235 model: { name: "test-model" },
43- })
36+ }),
4437 ),
4538 }));
4639
@@ -73,7 +66,7 @@
7366
7467 afterEach(async () => {
7568 context.cleanup();
76-
69+
7770 // Restore original process.exit
7871 process.exit = originalProcessExit;
7972
@@ -100,26 +93,28 @@
10093 it("should pass the --org flag through to initializeServices", async () => {
10194 // Import the services module to spy on
10295 const servicesModule = await import("../services/index.js");
103-
96+
10497 // Create spy on initializeServices
105- const initializeServicesSpy = vi.spyOn(servicesModule, "initializeServices")
98+ const initializeServicesSpy = vi
99+ .spyOn(servicesModule, "initializeServices")
106100 .mockResolvedValue({
107101 config: { models: [] },
108102 llmApi: { chat: vi.fn() },
109- model: { name: "test-model" }
103+ model: { name: "test-model" },
110104 } as any);
111105
112- // Create spy on getService
113- const getServiceSpy = vi.spyOn(servicesModule, "getService")
106+ // Create spy on getService
107+ const getServiceSpy = vi
108+ .spyOn(servicesModule, "getService")
114109 .mockResolvedValueOnce({
115110 config: { name: "test" },
116111 llmApi: { chat: vi.fn() },
117- model: { provider: "test", model: "test" }
112+ model: { provider: "test", model: "test" },
118113 } as any)
119114 .mockResolvedValueOnce({
120115 config: { name: "test" },
121116 llmApi: { chat: vi.fn() },
122- model: { provider: "test", model: "test" }
117+ model: { provider: "test", model: "test" },
123118 } as any);
124119
125120 // Import serve after setting up spies
@@ -129,7 +124,7 @@
129124 const testOptions = {
130125 org: "test-organization-slug",
131126 timeout: "60",
132- port: "9000"
127+ port: "9000",
133128 };
134129
135130 try {
@@ -142,12 +137,12 @@
142137 expect(initializeServicesSpy).toHaveBeenCalled();
143138 expect(initializeServicesSpy).toHaveBeenCalledWith(
144139 expect.objectContaining({
145- organizationSlug: "test-organization-slug"
146- })
140+ organizationSlug: "test-organization-slug",
141+ }),
147142 );
148143
149144 // Clean up spies
150145 initializeServicesSpy.mockRestore();
151146 getServiceSpy.mockRestore();
152147 });
153-});
No newline at the end of the file
148+});
modified extensions/cli/src/commands/stripThinkTags.test.ts +6 −6
@@ -11,14 +11,14 @@
1111 */
1212 function stripThinkTags(response: string): string {
1313 // Remove <think></think> tags and their content
14- let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, '');
15-
14+ let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, "");
15+
1616 // Remove excess whitespace: multiple consecutive newlines become single newlines
17- cleaned = cleaned.replace(/\n\s*\n\s*\n/g, '\n\n');
18-
17+ cleaned = cleaned.replace(/\n\s*\n\s*\n/g, "\n\n");
18+
1919 // Trim leading and trailing whitespace
2020 cleaned = cleaned.trim();
21-
21+
2222 return cleaned;
2323 }
2424
@@ -157,4 +157,4 @@
157157 expect(stripThinkTags(input)).toContain("<think>Unclosed think tag");
158158 expect(stripThinkTags(input)).toContain("Content should remain");
159159 });
160-});
No newline at the end of the file
160+});
modified extensions/cli/src/compaction.test.ts +201 −128
@@ -3,13 +3,17 @@
33 import { ChatCompletionMessageParam } from "openai/resources.mjs";
44 import { describe, it, expect, vi } from "vitest";
55
6-import { compactChatHistory, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js";
6+import {
7+ compactChatHistory,
8+ findCompactionIndex,
9+ getHistoryForLLM,
10+ COMPACTION_MARKER,
11+} from "./compaction.js";
712 import { streamChatResponse } from "./streamChatResponse.js";
813
9-
1014 // Mock the streamChatResponse function
1115 vi.mock("./streamChatResponse.js", () => ({
12- streamChatResponse: vi.fn()
16+ streamChatResponse: vi.fn(),
1317 }));
1418
1519 describe("compaction", () => {
@@ -27,7 +31,10 @@
2731 { role: "system", content: "System message" },
2832 { role: "user", content: "Hello" },
2933 { role: "assistant", content: "Hi there" },
30- { role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
34+ {
35+ role: "assistant",
36+ content: `${COMPACTION_MARKER}\nThis is a summary`,
37+ },
3138 { role: "user", content: "Another message" },
3239 ];
3340
@@ -67,7 +74,10 @@
6774 it("should not match marker in middle of content", () => {
6875 const history: ChatCompletionMessageParam[] = [
6976 { role: "system", content: "System message" },
70- { role: "assistant", content: `Some text ${COMPACTION_MARKER} in the middle` },
77+ {
78+ role: "assistant",
79+ content: `Some text ${COMPACTION_MARKER} in the middle`,
80+ },
7181 { role: "user", content: "Hello" },
7282 ];
7383
@@ -116,21 +126,30 @@
116126 { role: "system", content: "System message" },
117127 { role: "user", content: "Hello" },
118128 { role: "assistant", content: "Hi there" },
119- { role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
129+ {
130+ role: "assistant",
131+ content: `${COMPACTION_MARKER}\nThis is a summary`,
132+ },
120133 { role: "user", content: "Another message" },
121134 ];
122135
123136 const result = getHistoryForLLM(history, 3);
124137 expect(result).toEqual([
125138 { role: "system", content: "System message" },
126- { role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
139+ {
140+ role: "assistant",
141+ content: `${COMPACTION_MARKER}\nThis is a summary`,
142+ },
127143 { role: "user", content: "Another message" },
128144 ]);
129145 });
130146
131147 it("should return compacted history without system message when compaction is at index 0", () => {
132148 const history: ChatCompletionMessageParam[] = [
133- { role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
149+ {
150+ role: "assistant",
151+ content: `${COMPACTION_MARKER}\nThis is a summary`,
152+ },
134153 { role: "user", content: "Another message" },
135154 ];
136155
@@ -157,9 +176,7 @@
157176 const result = getHistoryForLLM(history, -1);
158177 // Negative index with slice means "from the end", so -1 gives us only the last message
159178 // Since compactionIndex is not > 0, system message is not included
160- expect(result).toEqual([
161- { role: "user", content: "Hello" },
162- ]);
179+ expect(result).toEqual([{ role: "user", content: "Hello" }]);
163180 });
164181
165182 it("should handle empty history", () => {
@@ -233,12 +250,14 @@
233250 it("should compact chat history successfully", async () => {
234251 const mockStreamResponse = vi.mocked(streamChatResponse);
235252 const mockContent = "This is a summary of the conversation";
236-
237- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
238- callbacks?.onContent?.(mockContent);
239- callbacks?.onContentComplete?.(mockContent);
240- return mockContent;
241- });
253+
254+ mockStreamResponse.mockImplementation(
255+ async (history, model, api, controller, callbacks) => {
256+ callbacks?.onContent?.(mockContent);
257+ callbacks?.onContentComplete?.(mockContent);
258+ return mockContent;
259+ },
260+ );
242261
243262 const history: ChatCompletionMessageParam[] = [
244263 { role: "system", content: "System message" },
@@ -247,12 +266,15 @@
247266 ];
248267
249268 const result = await compactChatHistory(history, mockModel, mockLlmApi);
250-
269+
251270 expect(result.compactedHistory).toHaveLength(2);
252- expect(result.compactedHistory[0]).toEqual({ role: "system", content: "System message" });
271+ expect(result.compactedHistory[0]).toEqual({
272+ role: "system",
273+ content: "System message",
274+ });
253275 expect(result.compactedHistory[1]).toEqual({
254276 role: "assistant",
255- content: `${COMPACTION_MARKER}\n${mockContent}`
277+ content: `${COMPACTION_MARKER}\n${mockContent}`,
256278 });
257279 expect(result.compactionIndex).toBe(1);
258280 expect(result.compactionContent).toBe(mockContent);
@@ -263,13 +285,15 @@
263285 const mockContent = "Summary content";
264286 const onStreamContent = vi.fn();
265287 const onStreamComplete = vi.fn();
266-
267- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
268- callbacks?.onContent?.("Summary ");
269- callbacks?.onContent?.("content");
270- callbacks?.onContentComplete?.(mockContent);
271- return mockContent;
272- });
288+
289+ mockStreamResponse.mockImplementation(
290+ async (history, model, api, controller, callbacks) => {
291+ callbacks?.onContent?.("Summary ");
292+ callbacks?.onContent?.("content");
293+ callbacks?.onContentComplete?.(mockContent);
294+ return mockContent;
295+ },
296+ );
273297
274298 const history: ChatCompletionMessageParam[] = [
275299 { role: "user", content: "Hello" },
@@ -277,9 +301,9 @@
277301
278302 await compactChatHistory(history, mockModel, mockLlmApi, {
279303 onStreamContent,
280- onStreamComplete
304+ onStreamComplete,
281305 });
282-
306+
283307 expect(onStreamContent).toHaveBeenCalledWith("Summary ");
284308 expect(onStreamContent).toHaveBeenCalledWith("content");
285309 expect(onStreamComplete).toHaveBeenCalled();
@@ -289,7 +313,7 @@
289313 const mockStreamResponse = vi.mocked(streamChatResponse);
290314 const mockError = new Error("Stream failed");
291315 const onError = vi.fn();
292-
316+
293317 mockStreamResponse.mockRejectedValue(mockError);
294318
295319 const history: ChatCompletionMessageParam[] = [
@@ -297,48 +321,55 @@
297321 ];
298322
299323 await expect(
300- compactChatHistory(history, mockModel, mockLlmApi, { onError })
324+ compactChatHistory(history, mockModel, mockLlmApi, { onError }),
301325 ).rejects.toThrow("Stream failed");
302-
326+
303327 expect(onError).toHaveBeenCalledWith(mockError);
304328 });
305329
306330 it("should handle history with only system message", async () => {
307331 const mockStreamResponse = vi.mocked(streamChatResponse);
308332 const mockContent = "Summary of system setup";
309-
310- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
311- callbacks?.onContent?.(mockContent);
312- callbacks?.onContentComplete?.(mockContent);
313- return mockContent;
314- });
333+
334+ mockStreamResponse.mockImplementation(
335+ async (history, model, api, controller, callbacks) => {
336+ callbacks?.onContent?.(mockContent);
337+ callbacks?.onContentComplete?.(mockContent);
338+ return mockContent;
339+ },
340+ );
315341
316342 const history: ChatCompletionMessageParam[] = [
317343 { role: "system", content: "You are a helpful assistant" },
318344 ];
319345
320346 const result = await compactChatHistory(history, mockModel, mockLlmApi);
321-
347+
322348 expect(result.compactedHistory).toHaveLength(2);
323- expect(result.compactedHistory[0]).toEqual({ role: "system", content: "You are a helpful assistant" });
349+ expect(result.compactedHistory[0]).toEqual({
350+ role: "system",
351+ content: "You are a helpful assistant",
352+ });
324353 expect(result.compactedHistory[1].content).toContain(COMPACTION_MARKER);
325354 });
326355
327356 it("should handle empty content from stream", async () => {
328357 const mockStreamResponse = vi.mocked(streamChatResponse);
329-
330- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
331- callbacks?.onContent?.("");
332- callbacks?.onContentComplete?.("");
333- return "";
334- });
358+
359+ mockStreamResponse.mockImplementation(
360+ async (history, model, api, controller, callbacks) => {
361+ callbacks?.onContent?.("");
362+ callbacks?.onContentComplete?.("");
363+ return "";
364+ },
365+ );
335366
336367 const history: ChatCompletionMessageParam[] = [
337368 { role: "user", content: "Hello" },
338369 ];
339370
340371 const result = await compactChatHistory(history, mockModel, mockLlmApi);
341-
372+
342373 expect(result.compactionContent).toBe("");
343374 expect(result.compactedHistory[0].content).toBe(`${COMPACTION_MARKER}\n`);
344375 });
@@ -346,13 +377,15 @@
346377 it("should correctly construct prompt for compaction", async () => {
347378 const mockStreamResponse = vi.mocked(streamChatResponse);
348379 let capturedHistory: ChatCompletionMessageParam[] = [];
349-
350- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
351- capturedHistory = [...history];
352- callbacks?.onContent?.("Summary");
353- callbacks?.onContentComplete?.("Summary");
354- return "Summary";
355- });
380+
381+ mockStreamResponse.mockImplementation(
382+ async (history, model, api, controller, callbacks) => {
383+ capturedHistory = [...history];
384+ callbacks?.onContent?.("Summary");
385+ callbacks?.onContentComplete?.("Summary");
386+ return "Summary";
387+ },
388+ );
356389
357390 const history: ChatCompletionMessageParam[] = [
358391 { role: "system", content: "System" },
@@ -361,24 +394,26 @@
361394 ];
362395
363396 await compactChatHistory(history, mockModel, mockLlmApi);
364-
397+
365398 // Should have original history plus the compaction prompt
366399 expect(capturedHistory).toHaveLength(4);
367400 expect(capturedHistory[3]).toEqual({
368401 role: "user",
369- content: expect.stringContaining("provide a concise summary")
402+ content: expect.stringContaining("provide a concise summary"),
370403 });
371404 });
372405
373406 it("should handle history with tool calls and mixed message types", async () => {
374407 const mockStreamResponse = vi.mocked(streamChatResponse);
375408 const mockContent = "Summary including tool usage";
376-
377- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
378- callbacks?.onContent?.(mockContent);
379- callbacks?.onContentComplete?.(mockContent);
380- return mockContent;
381- });
409+
410+ mockStreamResponse.mockImplementation(
411+ async (history, model, api, controller, callbacks) => {
412+ callbacks?.onContent?.(mockContent);
413+ callbacks?.onContentComplete?.(mockContent);
414+ return mockContent;
415+ },
416+ );
382417
383418 const history: ChatCompletionMessageParam[] = [
384419 { role: "system", content: "System" },
@@ -389,32 +424,34 @@
389424 ];
390425
391426 const result = await compactChatHistory(history, mockModel, mockLlmApi);
392-
427+
393428 expect(result.compactedHistory).toHaveLength(2);
394429 expect(result.compactionContent).toBe(mockContent);
395430 });
396431
397432 it("should handle very long chat histories", async () => {
398433 const mockStreamResponse = vi.mocked(streamChatResponse);
399-
400- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
401- callbacks?.onContent?.("Long summary");
402- callbacks?.onContentComplete?.("Long summary");
403- return "Long summary";
404- });
434+
435+ mockStreamResponse.mockImplementation(
436+ async (history, model, api, controller, callbacks) => {
437+ callbacks?.onContent?.("Long summary");
438+ callbacks?.onContentComplete?.("Long summary");
439+ return "Long summary";
440+ },
441+ );
405442
406443 // Create a very long history
407444 const history: ChatCompletionMessageParam[] = [
408445 { role: "system", content: "System" },
409446 ];
410-
447+
411448 for (let i = 0; i < 100; i++) {
412449 history.push({ role: "user", content: `User message ${i}` });
413450 history.push({ role: "assistant", content: `Assistant response ${i}` });
414451 }
415452
416453 const result = await compactChatHistory(history, mockModel, mockLlmApi);
417-
454+
418455 expect(result.compactedHistory).toHaveLength(2); // System + compaction
419456 expect(result.compactionIndex).toBe(1);
420457 });
@@ -422,12 +459,14 @@
422459 it("should handle history without system message", async () => {
423460 const mockStreamResponse = vi.mocked(streamChatResponse);
424461 const mockContent = "Summary without system";
425-
426- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
427- callbacks?.onContent?.(mockContent);
428- callbacks?.onContentComplete?.(mockContent);
429- return mockContent;
430- });
462+
463+ mockStreamResponse.mockImplementation(
464+ async (history, model, api, controller, callbacks) => {
465+ callbacks?.onContent?.(mockContent);
466+ callbacks?.onContentComplete?.(mockContent);
467+ return mockContent;
468+ },
469+ );
431470
432471 const history: ChatCompletionMessageParam[] = [
433472 { role: "user", content: "Hello" },
@@ -435,7 +474,7 @@
435474 ];
436475
437476 const result = await compactChatHistory(history, mockModel, mockLlmApi);
438-
477+
439478 expect(result.compactedHistory).toHaveLength(1); // Only compaction
440479 expect(result.compactedHistory[0].role).toBe("assistant");
441480 expect(result.compactionIndex).toBe(0);
@@ -444,14 +483,17 @@
444483
445484 describe("property-based tests", () => {
446485 it("getHistoryForLLM should always return a subset of the original history", () => {
447- const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
486+ const testCases: Array<{
487+ history: ChatCompletionMessageParam[];
488+ compactionIndex: number | null;
489+ }> = [
448490 {
449491 history: [
450492 { role: "system", content: "System" },
451493 { role: "user", content: "User 1" },
452494 { role: "assistant", content: "Assistant 1" },
453495 ],
454- compactionIndex: 1
496+ compactionIndex: 1,
455497 },
456498 {
457499 history: [
@@ -459,51 +501,61 @@
459501 { role: "assistant", content: "Assistant 1" },
460502 { role: "user", content: "User 2" },
461503 ],
462- compactionIndex: 2
504+ compactionIndex: 2,
463505 },
464506 {
465507 history: [],
466- compactionIndex: null
467- }
508+ compactionIndex: null,
509+ },
468510 ];
469511
470512 testCases.forEach(({ history, compactionIndex }) => {
471513 const result = getHistoryForLLM(history, compactionIndex);
472-
514+
473515 // Every message in result should exist in original history
474- result.forEach(msg => {
516+ result.forEach((msg) => {
475517 expect(history).toContainEqual(msg);
476518 });
477-
519+
478520 // Result length should be <= original length
479521 expect(result.length).toBeLessThanOrEqual(history.length);
480522 });
481523 });
482524
483525 it("getHistoryForLLM should always include system message if it exists at index 0", () => {
484- const systemMessage: ChatCompletionMessageParam = { role: "system", content: "System" };
485- const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
526+ const systemMessage: ChatCompletionMessageParam = {
527+ role: "system",
528+ content: "System",
529+ };
530+ const testCases: Array<{
531+ history: ChatCompletionMessageParam[];
532+ compactionIndex: number | null;
533+ }> = [
486534 {
487535 history: [
488536 systemMessage,
489537 { role: "user", content: "User 1" },
490538 { role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
491539 ],
492- compactionIndex: 2
540+ compactionIndex: 2,
493541 },
494542 {
495543 history: [
496544 systemMessage,
497545 { role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
498546 ],
499- compactionIndex: 1
500- }
547+ compactionIndex: 1,
548+ },
501549 ];
502550
503551 testCases.forEach(({ history, compactionIndex }) => {
504552 const result = getHistoryForLLM(history, compactionIndex);
505-
506- if (history[0]?.role === "system" && compactionIndex !== null && compactionIndex > 0) {
553+
554+ if (
555+ history[0]?.role === "system" &&
556+ compactionIndex !== null &&
557+ compactionIndex > 0
558+ ) {
507559 expect(result[0]).toEqual(systemMessage);
508560 }
509561 });
@@ -511,12 +563,14 @@
511563
512564 it("compaction should always reduce message count for non-trivial histories", async () => {
513565 const mockStreamResponse = vi.mocked(streamChatResponse);
514-
515- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
516- callbacks?.onContent?.("Summary");
517- callbacks?.onContentComplete?.("Summary");
518- return "Summary";
519- });
566+
567+ mockStreamResponse.mockImplementation(
568+ async (history, model, api, controller, callbacks) => {
569+ callbacks?.onContent?.("Summary");
570+ callbacks?.onContentComplete?.("Summary");
571+ return "Summary";
572+ },
573+ );
520574
521575 const testHistories: ChatCompletionMessageParam[][] = [
522576 [
@@ -530,12 +584,12 @@
530584 { role: "user", content: "User 1" },
531585 { role: "assistant", content: "Assistant 1" },
532586 { role: "user", content: "User 2" },
533- ]
587+ ],
534588 ];
535589
536590 for (const history of testHistories) {
537591 const result = await compactChatHistory(history, mockModel, mockLlmApi);
538-
592+
539593 // Compacted history should be shorter than original
540594 // (system + compaction) or just compaction
541595 expect(result.compactedHistory.length).toBeLessThanOrEqual(2);
@@ -547,39 +601,56 @@
547601 describe("invariant tests", () => {
548602 it("compactionIndex should always point to a message with COMPACTION_MARKER", async () => {
549603 const mockStreamResponse = vi.mocked(streamChatResponse);
550-
551- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
552- callbacks?.onContent?.("Summary content");
553- callbacks?.onContentComplete?.("Summary content");
554- return "Summary content";
555- });
604+
605+ mockStreamResponse.mockImplementation(
606+ async (history, model, api, controller, callbacks) => {
607+ callbacks?.onContent?.("Summary content");
608+ callbacks?.onContentComplete?.("Summary content");
609+ return "Summary content";
610+ },
611+ );
556612
557613 const histories: ChatCompletionMessageParam[][] = [
558- [{ role: "system", content: "System" }, { role: "user", content: "Hello" }],
559- [{ role: "user", content: "Hello" }, { role: "assistant", content: "Hi" }],
614+ [
615+ { role: "system", content: "System" },
616+ { role: "user", content: "Hello" },
617+ ],
618+ [
619+ { role: "user", content: "Hello" },
620+ { role: "assistant", content: "Hi" },
621+ ],
560622 [{ role: "system", content: "System" }],
561623 ];
562624
563625 for (const history of histories) {
564626 const result = await compactChatHistory(history, mockModel, mockLlmApi);
565-
627+
566628 // The message at compactionIndex should contain the marker
567- const compactionMessage = result.compactedHistory[result.compactionIndex];
629+ const compactionMessage =
630+ result.compactedHistory[result.compactionIndex];
568631 expect(compactionMessage.role).toBe("assistant");
569- expect(typeof compactionMessage.content === "string" && compactionMessage.content.startsWith(COMPACTION_MARKER)).toBe(true);
632+ expect(
633+ typeof compactionMessage.content === "string" &&
634+ compactionMessage.content.startsWith(COMPACTION_MARKER),
635+ ).toBe(true);
570636 }
571637 });
572638
573639 it("system message should always be preserved in the same position", async () => {
574640 const mockStreamResponse = vi.mocked(streamChatResponse);
575-
576- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
577- callbacks?.onContent?.("Summary");
578- callbacks?.onContentComplete?.("Summary");
579- return "Summary";
580- });
581641
582- const systemMessage: ChatCompletionMessageParam = { role: "system", content: "You are helpful" };
642+ mockStreamResponse.mockImplementation(
643+ async (history, model, api, controller, callbacks) => {
644+ callbacks?.onContent?.("Summary");
645+ callbacks?.onContentComplete?.("Summary");
646+ return "Summary";
647+ },
648+ );
649+
650+ const systemMessage: ChatCompletionMessageParam = {
651+ role: "system",
652+ content: "You are helpful",
653+ };
583654 const history: ChatCompletionMessageParam[] = [
584655 systemMessage,
585656 { role: "user", content: "Hello" },
@@ -587,19 +658,21 @@
587658 ];
588659
589660 const result = await compactChatHistory(history, mockModel, mockLlmApi);
590-
661+
591662 // System message should still be at index 0
592663 expect(result.compactedHistory[0]).toEqual(systemMessage);
593664 });
594665
595666 it("findCompactionIndex should be consistent with compactChatHistory result", async () => {
596667 const mockStreamResponse = vi.mocked(streamChatResponse);
597-
598- mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
599- callbacks?.onContent?.("Summary");
600- callbacks?.onContentComplete?.("Summary");
601- return "Summary";
602- });
668+
669+ mockStreamResponse.mockImplementation(
670+ async (history, model, api, controller, callbacks) => {
671+ callbacks?.onContent?.("Summary");
672+ callbacks?.onContentComplete?.("Summary");
673+ return "Summary";
674+ },
675+ );
603676
604677 const history: ChatCompletionMessageParam[] = [
605678 { role: "user", content: "Hello" },
@@ -607,10 +680,10 @@
607680 ];
608681
609682 const result = await compactChatHistory(history, mockModel, mockLlmApi);
610-
683+
611684 // findCompactionIndex should find the same index
612685 const foundIndex = findCompactionIndex(result.compactedHistory);
613686 expect(foundIndex).toBe(result.compactionIndex);
614687 });
615688 });
616-});
No newline at the end of the file
689+});
modified extensions/cli/src/config.test.ts +28 −26
@@ -1,56 +1,58 @@
1-import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
2-import { describe, expect, test, vi, beforeEach } from 'vitest';
1+import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
2+import { describe, expect, test, vi, beforeEach } from "vitest";
33
44 // Mock dependencies
5-vi.mock('./auth/workos.js');
5+vi.mock("./auth/workos.js");
66
7-import type { AuthConfig } from './auth/workos.js';
8-import { getLlmApi } from './config.js';
7+import type { AuthConfig } from "./auth/workos.js";
8+import { getLlmApi } from "./config.js";
99
10-describe('config', () => {
10+describe("config", () => {
1111 let mockAuthConfig: AuthConfig;
1212
1313 beforeEach(() => {
1414 vi.clearAllMocks();
1515
1616 mockAuthConfig = {
17- accessToken: 'test-token',
18- refreshToken: 'test-refresh',
19- userEmail: 'test@example.com',
20- userId: 'test-user',
21- organizationId: 'test-org',
17+ accessToken: "test-token",
18+ refreshToken: "test-refresh",
19+ userEmail: "test@example.com",
20+ userId: "test-user",
21+ organizationId: "test-org",
2222 expiresAt: Date.now() + 3600000,
2323 };
2424 });
2525
26- describe('getLlmApi()', () => {
27- test('should throw error when models array is empty', () => {
26+ describe("getLlmApi()", () => {
27+ test("should throw error when models array is empty", () => {
2828 const assistant: AssistantUnrolled = {
29- name: 'test-assistant',
30- version: '1.0.0',
29+ name: "test-assistant",
30+ version: "1.0.0",
3131 models: [],
3232 };
3333
34- expect(() => getLlmApi(assistant, mockAuthConfig))
35- .toThrow('No models found in the configured assistant');
34+ expect(() => getLlmApi(assistant, mockAuthConfig)).toThrow(
35+ "No models found in the configured assistant",
36+ );
3637 });
3738
38- test('should throw error when no chat models available', () => {
39+ test("should throw error when no chat models available", () => {
3940 const assistant: AssistantUnrolled = {
40- name: 'test-assistant',
41- version: '1.0.0',
41+ name: "test-assistant",
42+ version: "1.0.0",
4243 models: [
4344 {
44- provider: 'openai',
45- model: 'text-embedding-ada-002',
46- name: 'Ada Embeddings',
47- roles: ['embed'],
45+ provider: "openai",
46+ model: "text-embedding-ada-002",
47+ name: "Ada Embeddings",
48+ roles: ["embed"],
4849 } as ModelConfig,
4950 ],
5051 };
5152
52- expect(() => getLlmApi(assistant, mockAuthConfig))
53- .toThrow('No models with the chat role found in the configured assistant');
53+ expect(() => getLlmApi(assistant, mockAuthConfig)).toThrow(
54+ "No models with the chat role found in the configured assistant",
55+ );
5456 });
5557 });
5658 });
modified extensions/cli/src/flags/flagProcessor.test.ts +4 −4
@@ -23,7 +23,7 @@
2323
2424 test("should throw error when both readonly and auto are true", () => {
2525 expect(() => convertLegacyModeFlags(true, true)).toThrow(
26- "Cannot use both --readonly and --auto flags together"
26+ "Cannot use both --readonly and --auto flags together",
2727 );
2828 });
2929 });
@@ -34,7 +34,7 @@
3434 ["readFile"],
3535 ["writeFile"],
3636 ["runTerminalCommand"],
37- "plan"
37+ "plan",
3838 );
3939
4040 expect(result).toEqual({
@@ -125,7 +125,7 @@
125125 processCommandFlags({
126126 readonly: true,
127127 auto: true,
128- })
128+ }),
129129 ).toThrow("Cannot use both --readonly and --auto flags together");
130130 });
131131
@@ -142,4 +142,4 @@
142142 },
143143 });
144144 });
145-});
No newline at the end of the file
145+});
modified extensions/cli/src/flags/flagValidator.test.ts +93 −81
@@ -1,209 +1,221 @@
1-import { validateFlags, handleValidationErrors } from './flagValidator.js';
2-
3-describe('validateFlags', () => {
4- describe('format flag validation', () => {
5- test('should pass when format is used with print', () => {
1+import { validateFlags, handleValidationErrors } from "./flagValidator.js";
2+
3+describe("validateFlags", () => {
4+ describe("format flag validation", () => {
5+ test("should pass when format is used with print", () => {
66 const result = validateFlags({
7- format: 'json',
7+ format: "json",
88 print: true,
99 });
10-
10+
1111 expect(result.isValid).toBe(true);
1212 expect(result.errors).toHaveLength(0);
1313 });
1414
15- test('should fail when format is used without print', () => {
15+ test("should fail when format is used without print", () => {
1616 const result = validateFlags({
17- format: 'json',
17+ format: "json",
1818 print: false,
1919 });
20-
20+
2121 expect(result.isValid).toBe(false);
2222 expect(result.errors).toHaveLength(1);
23- expect(result.errors[0].code).toBe('FORMAT_REQUIRES_PRINT');
24- expect(result.errors[0].message).toContain('--format flag can only be used with -p/--print');
23+ expect(result.errors[0].code).toBe("FORMAT_REQUIRES_PRINT");
24+ expect(result.errors[0].message).toContain(
25+ "--format flag can only be used with -p/--print",
26+ );
2527 });
2628
27- test('should fail when format value is invalid', () => {
29+ test("should fail when format value is invalid", () => {
2830 const result = validateFlags({
29- format: 'xml',
31+ format: "xml",
3032 print: true,
3133 });
32-
34+
3335 expect(result.isValid).toBe(false);
3436 expect(result.errors).toHaveLength(1);
35- expect(result.errors[0].code).toBe('INVALID_FORMAT_VALUE');
36- expect(result.errors[0].message).toContain("--format currently only supports 'json'");
37+ expect(result.errors[0].code).toBe("INVALID_FORMAT_VALUE");
38+ expect(result.errors[0].message).toContain(
39+ "--format currently only supports 'json'",
40+ );
3741 });
3842 });
3943
40- describe('silent flag validation', () => {
41- test('should pass when silent is used with print', () => {
44+ describe("silent flag validation", () => {
45+ test("should pass when silent is used with print", () => {
4246 const result = validateFlags({
4347 silent: true,
4448 print: true,
4549 });
46-
50+
4751 expect(result.isValid).toBe(true);
4852 expect(result.errors).toHaveLength(0);
4953 });
5054
51- test('should fail when silent is used without print', () => {
55+ test("should fail when silent is used without print", () => {
5256 const result = validateFlags({
5357 silent: true,
5458 print: false,
5559 });
56-
60+
5761 expect(result.isValid).toBe(false);
5862 expect(result.errors).toHaveLength(1);
59- expect(result.errors[0].code).toBe('SILENT_REQUIRES_PRINT');
60- expect(result.errors[0].message).toContain('--silent flag can only be used with -p/--print');
63+ expect(result.errors[0].code).toBe("SILENT_REQUIRES_PRINT");
64+ expect(result.errors[0].message).toContain(
65+ "--silent flag can only be used with -p/--print",
66+ );
6167 });
6268 });
6369
64- describe('mode flags validation', () => {
65- test('should pass with readonly only', () => {
70+ describe("mode flags validation", () => {
71+ test("should pass with readonly only", () => {
6672 const result = validateFlags({
6773 readonly: true,
6874 auto: false,
6975 });
70-
76+
7177 expect(result.isValid).toBe(true);
7278 expect(result.errors).toHaveLength(0);
7379 });
7480
75- test('should pass with auto only', () => {
81+ test("should pass with auto only", () => {
7682 const result = validateFlags({
7783 readonly: false,
7884 auto: true,
7985 });
80-
86+
8187 expect(result.isValid).toBe(true);
8288 expect(result.errors).toHaveLength(0);
8389 });
8490
85- test('should fail when both readonly and auto are used', () => {
91+ test("should fail when both readonly and auto are used", () => {
8692 const result = validateFlags({
8793 readonly: true,
8894 auto: true,
8995 });
90-
96+
9197 expect(result.isValid).toBe(false);
9298 expect(result.errors).toHaveLength(1);
93- expect(result.errors[0].code).toBe('CONFLICTING_MODE_FLAGS');
94- expect(result.errors[0].message).toContain('Cannot use both --readonly and --auto');
99+ expect(result.errors[0].code).toBe("CONFLICTING_MODE_FLAGS");
100+ expect(result.errors[0].message).toContain(
101+ "Cannot use both --readonly and --auto",
102+ );
95103 });
96104 });
97105
98- describe('permission flags validation', () => {
99- test('should pass with valid permission flags', () => {
106+ describe("permission flags validation", () => {
107+ test("should pass with valid permission flags", () => {
100108 const result = validateFlags({
101- allow: ['readFile', 'searchCode'],
102- ask: ['writeFile'],
103- exclude: ['Write', 'Bash'],
109+ allow: ["readFile", "searchCode"],
110+ ask: ["writeFile"],
111+ exclude: ["Write", "Bash"],
104112 });
105-
113+
106114 expect(result.isValid).toBe(true);
107115 expect(result.errors).toHaveLength(0);
108116 });
109117
110- test('should fail with empty tool names in allow', () => {
118+ test("should fail with empty tool names in allow", () => {
111119 const result = validateFlags({
112- allow: ['readFile', '', 'searchCode'],
120+ allow: ["readFile", "", "searchCode"],
113121 });
114-
122+
115123 expect(result.isValid).toBe(false);
116124 expect(result.errors).toHaveLength(1);
117- expect(result.errors[0].code).toBe('EMPTY_ALLOW_TOOL');
118- expect(result.errors[0].message).toContain('--allow requires a tool name');
125+ expect(result.errors[0].code).toBe("EMPTY_ALLOW_TOOL");
126+ expect(result.errors[0].message).toContain(
127+ "--allow requires a tool name",
128+ );
119129 });
120130
121- test('should fail with empty tool names in ask', () => {
131+ test("should fail with empty tool names in ask", () => {
122132 const result = validateFlags({
123- ask: ['writeFile', ' ', 'editFile'],
133+ ask: ["writeFile", " ", "editFile"],
124134 });
125-
135+
126136 expect(result.isValid).toBe(false);
127137 expect(result.errors).toHaveLength(1);
128- expect(result.errors[0].code).toBe('EMPTY_ASK_TOOL');
129- expect(result.errors[0].message).toContain('--ask requires a tool name');
138+ expect(result.errors[0].code).toBe("EMPTY_ASK_TOOL");
139+ expect(result.errors[0].message).toContain("--ask requires a tool name");
130140 });
131141
132- test('should fail with empty tool names in exclude', () => {
142+ test("should fail with empty tool names in exclude", () => {
133143 const result = validateFlags({
134- exclude: ['Write', '', 'Bash'],
144+ exclude: ["Write", "", "Bash"],
135145 });
136-
146+
137147 expect(result.isValid).toBe(false);
138148 expect(result.errors).toHaveLength(1);
139- expect(result.errors[0].code).toBe('EMPTY_EXCLUDE_TOOL');
140- expect(result.errors[0].message).toContain('--exclude requires a tool name');
149+ expect(result.errors[0].code).toBe("EMPTY_EXCLUDE_TOOL");
150+ expect(result.errors[0].message).toContain(
151+ "--exclude requires a tool name",
152+ );
141153 });
142154 });
143155
144- describe('multiple errors', () => {
145- test('should return all validation errors', () => {
156+ describe("multiple errors", () => {
157+ test("should return all validation errors", () => {
146158 const result = validateFlags({
147- format: 'xml',
159+ format: "xml",
148160 print: false,
149161 silent: true,
150162 readonly: true,
151163 auto: true,
152- allow: ['readFile', ''],
164+ allow: ["readFile", ""],
153165 });
154-
166+
155167 expect(result.isValid).toBe(false);
156168 expect(result.errors.length).toBeGreaterThan(1);
157-
158- const errorCodes = result.errors.map(e => e.code);
159- expect(errorCodes).toContain('FORMAT_REQUIRES_PRINT');
160- expect(errorCodes).toContain('INVALID_FORMAT_VALUE');
161- expect(errorCodes).toContain('SILENT_REQUIRES_PRINT');
162- expect(errorCodes).toContain('CONFLICTING_MODE_FLAGS');
163- expect(errorCodes).toContain('EMPTY_ALLOW_TOOL');
169+
170+ const errorCodes = result.errors.map((e) => e.code);
171+ expect(errorCodes).toContain("FORMAT_REQUIRES_PRINT");
172+ expect(errorCodes).toContain("INVALID_FORMAT_VALUE");
173+ expect(errorCodes).toContain("SILENT_REQUIRES_PRINT");
174+ expect(errorCodes).toContain("CONFLICTING_MODE_FLAGS");
175+ expect(errorCodes).toContain("EMPTY_ALLOW_TOOL");
164176 });
165177 });
166178
167- describe('config path validation', () => {
168- test('should pass with valid config path', () => {
179+ describe("config path validation", () => {
180+ test("should pass with valid config path", () => {
169181 const result = validateFlags({
170- config: './my-config.yaml',
182+ config: "./my-config.yaml",
171183 });
172-
184+
173185 expect(result.isValid).toBe(true);
174186 expect(result.errors).toHaveLength(0);
175187 });
176188
177- test('should pass with undefined config', () => {
189+ test("should pass with undefined config", () => {
178190 const result = validateFlags({
179191 config: undefined,
180192 });
181-
193+
182194 expect(result.isValid).toBe(true);
183195 expect(result.errors).toHaveLength(0);
184196 });
185197 });
186198 });
187199
188-describe('handleValidationErrors', () => {
189- test('should be a function that accepts validation errors', () => {
200+describe("handleValidationErrors", () => {
201+ test("should be a function that accepts validation errors", () => {
190202 // Test function signature without calling it (since it calls process.exit)
191- expect(typeof handleValidationErrors).toBe('function');
203+ expect(typeof handleValidationErrors).toBe("function");
192204 expect(handleValidationErrors.length).toBe(1);
193205 });
194206
195- test('should accept proper error format', () => {
207+ test("should accept proper error format", () => {
196208 const validErrors = [
197- { code: 'TEST_ERROR', message: 'Test message' },
198- { code: 'ANOTHER_ERROR', message: 'Another message' }
209+ { code: "TEST_ERROR", message: "Test message" },
210+ { code: "ANOTHER_ERROR", message: "Another message" },
199211 ];
200-
212+
201213 // Verify the function exists and would accept this format
202214 // We don't call it since it would exit the process
203215 expect(() => {
204216 const errorArray = validErrors;
205217 expect(Array.isArray(errorArray)).toBe(true);
206- expect(errorArray.every(e => e.code && e.message)).toBe(true);
218+ expect(errorArray.every((e) => e.code && e.message)).toBe(true);
207219 }).not.toThrow();
208220 });
209-});
No newline at the end of the file
221+});
modified extensions/cli/src/freeTrialTransition.test.ts +30 −19
@@ -1,27 +1,38 @@
1-import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
1+import {
2+ isValidAnthropicApiKey,
3+ getApiKeyValidationError,
4+} from "./util/apiKeyValidation.js";
25
3-describe('Free Trial Transition API Key Validation', () => {
4- it('should validate API keys properly for free trial transition', () => {
6+describe("Free Trial Transition API Key Validation", () => {
7+ it("should validate API keys properly for free trial transition", () => {
58 // Valid API keys
6- expect(isValidAnthropicApiKey('TEST-ant-1234567890')).toBe(true);
7- expect(isValidAnthropicApiKey('TEST-ant-api03_T3BlbkFJ1234567890abcdef')).toBe(true);
8-
9+ expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
10+ expect(
11+ isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
12+ ).toBe(true);
13+
914 // Invalid API keys
10- expect(isValidAnthropicApiKey('TEST-')).toBe(false);
11- expect(isValidAnthropicApiKey('TEST-ant-')).toBe(false);
12- expect(isValidAnthropicApiKey('TEST-openai-1234')).toBe(false);
13- expect(isValidAnthropicApiKey('')).toBe(false);
15+ expect(isValidAnthropicApiKey("TEST-")).toBe(false);
16+ expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
17+ expect(isValidAnthropicApiKey("TEST-openai-1234")).toBe(false);
18+ expect(isValidAnthropicApiKey("")).toBe(false);
1419 expect(isValidAnthropicApiKey(null)).toBe(false);
1520 expect(isValidAnthropicApiKey(undefined)).toBe(false);
1621 });
1722
18- it('should provide helpful error messages for invalid API keys', () => {
19- expect(getApiKeyValidationError('')).toBe('API key is required');
20- expect(getApiKeyValidationError(null)).toBe('API key is required');
21- expect(getApiKeyValidationError(undefined)).toBe('API key is required');
22- expect(getApiKeyValidationError('TEST-')).toBe('API key must start with "TEST-ant-"');
23- expect(getApiKeyValidationError('TEST-openai-1234')).toBe('API key must start with "TEST-ant-"');
24- expect(getApiKeyValidationError('TEST-ant-')).toBe('API key is too short');
25- expect(getApiKeyValidationError('invalid')).toBe('API key must start with "TEST-ant-"');
23+ it("should provide helpful error messages for invalid API keys", () => {
24+ expect(getApiKeyValidationError("")).toBe("API key is required");
25+ expect(getApiKeyValidationError(null)).toBe("API key is required");
26+ expect(getApiKeyValidationError(undefined)).toBe("API key is required");
27+ expect(getApiKeyValidationError("TEST-")).toBe(
28+ 'API key must start with "TEST-ant-"',
29+ );
30+ expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
31+ 'API key must start with "TEST-ant-"',
32+ );
33+ expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
34+ expect(getApiKeyValidationError("invalid")).toBe(
35+ 'API key must start with "TEST-ant-"',
36+ );
2637 });
27-});
No newline at the end of the file
38+});
modified extensions/cli/src/logging.test.ts +117 −111
@@ -1,17 +1,17 @@
1-import chalk from 'chalk';
2-import { vi } from 'vitest';
3-
4-import {
5- configureLogger,
6- isLoggingEnabled,
7- log,
8- error,
9- info,
10- warn,
11- loggers
12-} from './logging.js';
13-
14-describe('logging utilities', () => {
1+import chalk from "chalk";
2+import { vi } from "vitest";
3+
4+import {
5+ configureLogger,
6+ isLoggingEnabled,
7+ log,
8+ error,
9+ info,
10+ warn,
11+ loggers,
12+} from "./logging.js";
13+
14+describe("logging utilities", () => {
1515 let consoleInfoSpy: ReturnType<typeof vi.spyOn>;
1616 let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
1717 let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
@@ -19,227 +19,233 @@
1919 beforeEach(() => {
2020 // Reset logger state
2121 configureLogger({ headless: false });
22-
22+
2323 // Mock console methods
24- consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(() => {});
25- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
26- consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
24+ consoleInfoSpy = vi.spyOn(console, "info").mockImplementation(() => {});
25+ consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
26+ consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
2727 });
2828
2929 afterEach(() => {
3030 vi.restoreAllMocks();
3131 });
3232
33- describe('configureLogger', () => {
34- it('should configure logger for non-headless mode', () => {
33+ describe("configureLogger", () => {
34+ it("should configure logger for non-headless mode", () => {
3535 configureLogger({ headless: false });
3636 expect(isLoggingEnabled()).toBe(true);
3737 });
3838
39- it('should configure logger for headless mode', () => {
39+ it("should configure logger for headless mode", () => {
4040 configureLogger({ headless: true });
4141 expect(isLoggingEnabled()).toBe(false);
4242 });
4343 });
4444
45- describe('isLoggingEnabled', () => {
46- it('should return true in non-headless mode', () => {
45+ describe("isLoggingEnabled", () => {
46+ it("should return true in non-headless mode", () => {
4747 configureLogger({ headless: false });
4848 expect(isLoggingEnabled()).toBe(true);
4949 });
5050
51- it('should return false in headless mode', () => {
51+ it("should return false in headless mode", () => {
5252 configureLogger({ headless: true });
5353 expect(isLoggingEnabled()).toBe(false);
5454 });
5555
56- it('should return true when forceEnable is true, even in headless mode', () => {
56+ it("should return true when forceEnable is true, even in headless mode", () => {
5757 configureLogger({ headless: true });
5858 expect(isLoggingEnabled(true)).toBe(true);
5959 });
6060
61- it('should return true when forceEnable is true in non-headless mode', () => {
61+ it("should return true when forceEnable is true in non-headless mode", () => {
6262 configureLogger({ headless: false });
6363 expect(isLoggingEnabled(true)).toBe(true);
6464 });
6565 });
6666
67- describe('log', () => {
68- it('should log in non-headless mode', () => {
67+ describe("log", () => {
68+ it("should log in non-headless mode", () => {
6969 configureLogger({ headless: false });
70- log('test message');
71- expect(consoleInfoSpy).toHaveBeenCalledWith('test message');
70+ log("test message");
71+ expect(consoleInfoSpy).toHaveBeenCalledWith("test message");
7272 });
7373
74- it('should not log in headless mode', () => {
74+ it("should not log in headless mode", () => {
7575 configureLogger({ headless: true });
76- log('test message');
76+ log("test message");
7777 expect(consoleInfoSpy).not.toHaveBeenCalled();
7878 });
7979
80- it('should log in headless mode when forceLog is true', () => {
80+ it("should log in headless mode when forceLog is true", () => {
8181 configureLogger({ headless: true });
82- log('test message', true);
83- expect(consoleInfoSpy).toHaveBeenCalledWith('test message');
82+ log("test message", true);
83+ expect(consoleInfoSpy).toHaveBeenCalledWith("test message");
8484 });
8585
86- it('should log in non-headless mode when forceLog is true', () => {
86+ it("should log in non-headless mode when forceLog is true", () => {
8787 configureLogger({ headless: false });
88- log('test message', true);
89- expect(consoleInfoSpy).toHaveBeenCalledWith('test message');
88+ log("test message", true);
89+ expect(consoleInfoSpy).toHaveBeenCalledWith("test message");
9090 });
9191 });
9292
93- describe('error', () => {
94- it('should log errors in non-headless mode', () => {
93+ describe("error", () => {
94+ it("should log errors in non-headless mode", () => {
9595 configureLogger({ headless: false });
96- error('error message');
97- expect(consoleErrorSpy).toHaveBeenCalledWith('error message');
96+ error("error message");
97+ expect(consoleErrorSpy).toHaveBeenCalledWith("error message");
9898 });
9999
100- it('should log errors in headless mode by default (forceLog defaults to true)', () => {
100+ it("should log errors in headless mode by default (forceLog defaults to true)", () => {
101101 configureLogger({ headless: true });
102- error('error message');
103- expect(consoleErrorSpy).toHaveBeenCalledWith('error message');
102+ error("error message");
103+ expect(consoleErrorSpy).toHaveBeenCalledWith("error message");
104104 });
105105
106- it('should not log errors in headless mode when forceLog is false', () => {
106+ it("should not log errors in headless mode when forceLog is false", () => {
107107 configureLogger({ headless: true });
108- error('error message', false);
108+ error("error message", false);
109109 expect(consoleErrorSpy).not.toHaveBeenCalled();
110110 });
111111
112- it('should log errors when forceLog is explicitly true', () => {
112+ it("should log errors when forceLog is explicitly true", () => {
113113 configureLogger({ headless: true });
114- error('error message', true);
115- expect(consoleErrorSpy).toHaveBeenCalledWith('error message');
114+ error("error message", true);
115+ expect(consoleErrorSpy).toHaveBeenCalledWith("error message");
116116 });
117117 });
118118
119- describe('info', () => {
120- it('should log info in non-headless mode', () => {
119+ describe("info", () => {
120+ it("should log info in non-headless mode", () => {
121121 configureLogger({ headless: false });
122- info('info message');
123- expect(consoleInfoSpy).toHaveBeenCalledWith('info message');
122+ info("info message");
123+ expect(consoleInfoSpy).toHaveBeenCalledWith("info message");
124124 });
125125
126- it('should not log info in headless mode', () => {
126+ it("should not log info in headless mode", () => {
127127 configureLogger({ headless: true });
128- info('info message');
128+ info("info message");
129129 expect(consoleInfoSpy).not.toHaveBeenCalled();
130130 });
131131
132- it('should log info in headless mode when forceLog is true', () => {
132+ it("should log info in headless mode when forceLog is true", () => {
133133 configureLogger({ headless: true });
134- info('info message', true);
135- expect(consoleInfoSpy).toHaveBeenCalledWith('info message');
134+ info("info message", true);
135+ expect(consoleInfoSpy).toHaveBeenCalledWith("info message");
136136 });
137137 });
138138
139- describe('warn', () => {
140- it('should log warnings in non-headless mode', () => {
139+ describe("warn", () => {
140+ it("should log warnings in non-headless mode", () => {
141141 configureLogger({ headless: false });
142- warn('warning message');
143- expect(consoleWarnSpy).toHaveBeenCalledWith('warning message');
142+ warn("warning message");
143+ expect(consoleWarnSpy).toHaveBeenCalledWith("warning message");
144144 });
145145
146- it('should not log warnings in headless mode', () => {
146+ it("should not log warnings in headless mode", () => {
147147 configureLogger({ headless: true });
148- warn('warning message');
148+ warn("warning message");
149149 expect(consoleWarnSpy).not.toHaveBeenCalled();
150150 });
151151
152- it('should log warnings in headless mode when forceLog is true', () => {
152+ it("should log warnings in headless mode when forceLog is true", () => {
153153 configureLogger({ headless: true });
154- warn('warning message', true);
155- expect(consoleWarnSpy).toHaveBeenCalledWith('warning message');
154+ warn("warning message", true);
155+ expect(consoleWarnSpy).toHaveBeenCalledWith("warning message");
156156 });
157157 });
158158
159- describe('loggers object', () => {
159+ describe("loggers object", () => {
160160 beforeEach(() => {
161161 configureLogger({ headless: false });
162162 });
163163
164- it('should provide colored success logger', () => {
165- loggers.success('success message');
166- expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.green('success message'));
164+ it("should provide colored success logger", () => {
165+ loggers.success("success message");
166+ expect(consoleInfoSpy).toHaveBeenCalledWith(
167+ chalk.green("success message"),
168+ );
167169 });
168170
169- it('should provide colored info logger', () => {
170- loggers.info('info message');
171- expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.blue('info message'));
171+ it("should provide colored info logger", () => {
172+ loggers.info("info message");
173+ expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.blue("info message"));
172174 });
173175
174- it('should provide colored warning logger', () => {
175- loggers.warning('warning message');
176- expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.yellow('warning message'));
176+ it("should provide colored warning logger", () => {
177+ loggers.warning("warning message");
178+ expect(consoleInfoSpy).toHaveBeenCalledWith(
179+ chalk.yellow("warning message"),
180+ );
177181 });
178182
179- it('should provide colored error logger', () => {
180- loggers.error('error message');
181- expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red('error message'));
183+ it("should provide colored error logger", () => {
184+ loggers.error("error message");
185+ expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red("error message"));
182186 });
183187
184- it('should provide colored debug logger', () => {
185- loggers.debug('debug message');
186- expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.gray('debug message'));
188+ it("should provide colored debug logger", () => {
189+ loggers.debug("debug message");
190+ expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.gray("debug message"));
187191 });
188192
189- it('should provide command logger that always logs', () => {
193+ it("should provide command logger that always logs", () => {
190194 configureLogger({ headless: true });
191- loggers.command('command output');
192- expect(consoleInfoSpy).toHaveBeenCalledWith('command output');
195+ loggers.command("command output");
196+ expect(consoleInfoSpy).toHaveBeenCalledWith("command output");
193197 });
194198
195- it('should respect forceLog parameter in colored loggers', () => {
199+ it("should respect forceLog parameter in colored loggers", () => {
196200 configureLogger({ headless: true });
197-
198- loggers.success('success message', false);
201+
202+ loggers.success("success message", false);
199203 expect(consoleInfoSpy).not.toHaveBeenCalled();
200-
201- loggers.success('success message', true);
202- expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.green('success message'));
204+
205+ loggers.success("success message", true);
206+ expect(consoleInfoSpy).toHaveBeenCalledWith(
207+ chalk.green("success message"),
208+ );
203209 });
204210
205- it('should handle error logger with default forceLog behavior', () => {
211+ it("should handle error logger with default forceLog behavior", () => {
206212 configureLogger({ headless: true });
207-
208- loggers.error('error message');
209- expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red('error message'));
210-
211- loggers.error('error message', false);
213+
214+ loggers.error("error message");
215+ expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red("error message"));
216+
217+ loggers.error("error message", false);
212218 expect(consoleErrorSpy).toHaveBeenCalledTimes(1); // Should not be called again
213219 });
214220 });
215221
216- describe('complex logging scenarios', () => {
217- it('should handle different message types', () => {
222+ describe("complex logging scenarios", () => {
223+ it("should handle different message types", () => {
218224 configureLogger({ headless: false });
219-
220- log('string message');
225+
226+ log("string message");
221227 log(123);
222- log({ key: 'value' });
228+ log({ key: "value" });
223229 log(null);
224230 log(undefined);
225-
231+
226232 expect(consoleInfoSpy).toHaveBeenCalledTimes(5);
227- expect(consoleInfoSpy).toHaveBeenCalledWith('string message');
233+ expect(consoleInfoSpy).toHaveBeenCalledWith("string message");
228234 expect(consoleInfoSpy).toHaveBeenCalledWith(123);
229- expect(consoleInfoSpy).toHaveBeenCalledWith({ key: 'value' });
235+ expect(consoleInfoSpy).toHaveBeenCalledWith({ key: "value" });
230236 expect(consoleInfoSpy).toHaveBeenCalledWith(null);
231237 expect(consoleInfoSpy).toHaveBeenCalledWith(undefined);
232238 });
233239
234- it('should maintain state across multiple configure calls', () => {
240+ it("should maintain state across multiple configure calls", () => {
235241 configureLogger({ headless: false });
236242 expect(isLoggingEnabled()).toBe(true);
237-
243+
238244 configureLogger({ headless: true });
239245 expect(isLoggingEnabled()).toBe(false);
240-
246+
241247 configureLogger({ headless: false });
242248 expect(isLoggingEnabled()).toBe(true);
243249 });
244250 });
245-});
No newline at the end of the file
251+});
modified extensions/cli/src/onboarding.test.ts +72 −65
@@ -1,28 +1,28 @@
1-import * as fs from 'fs';
2-import * as os from 'os';
3-import * as path from 'path';
1+import * as fs from "fs";
2+import * as os from "os";
3+import * as path from "path";
44
5-import { describe, expect, test, beforeEach, afterEach } from 'vitest';
5+import { describe, expect, test, beforeEach, afterEach } from "vitest";
66
7-import type { AuthConfig } from './auth/workos.js';
8-import { runNormalFlow } from './onboarding.js';
7+import type { AuthConfig } from "./auth/workos.js";
8+import { runNormalFlow } from "./onboarding.js";
99
10-describe('onboarding config flag handling', () => {
10+describe("onboarding config flag handling", () => {
1111 let tempDir: string;
1212 let mockAuthConfig: AuthConfig;
1313
1414 beforeEach(() => {
1515 // Create a temporary directory for test config files
16- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'continue-test-'));
17-
16+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
17+
1818 // Create a minimal auth config for testing
1919 mockAuthConfig = {
20- userId: 'test-user',
21- userEmail: 'test@example.com',
22- accessToken: 'test-token',
23- refreshToken: 'test-refresh',
20+ userId: "test-user",
21+ userEmail: "test@example.com",
22+ accessToken: "test-token",
23+ refreshToken: "test-refresh",
2424 expiresAt: Date.now() + 3600000,
25- organizationId: 'test-org',
25+ organizationId: "test-org",
2626 };
2727 });
2828
@@ -33,123 +33,130 @@
3333 }
3434 });
3535
36- test('should fail loudly when --config points to non-existent file', async () => {
37- const configPath = path.join(tempDir, 'non-existent.yaml');
38-
36+ test("should fail loudly when --config points to non-existent file", async () => {
37+ const configPath = path.join(tempDir, "non-existent.yaml");
38+
3939 // Verify the file doesn't exist
4040 expect(fs.existsSync(configPath)).toBe(false);
41-
41+
4242 // Should throw an error that mentions both the path and the failure
4343 await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
44- /Failed to load config from ".*non-existent\.yaml": .*ENOENT/
44+ /Failed to load config from ".*non-existent\.yaml": .*ENOENT/,
4545 );
4646 });
4747
48- test('should fail loudly when --config points to malformed YAML file', async () => {
49- const configPath = path.join(tempDir, 'malformed.yaml');
50-
51- // Create a malformed YAML file
52- fs.writeFileSync(configPath, `
48+ test("should fail loudly when --config points to malformed YAML file", async () => {
49+ const configPath = path.join(tempDir, "malformed.yaml");
50+
51+ // Create a malformed YAML file
52+ fs.writeFileSync(
53+ configPath,
54+ `
5355 name: "Test Config"
5456 models:
5557 - name: "GPT-4"
5658 provider: "openai"
5759 invalid_yaml_syntax: [unclosed array
58-`);
59-
60+`,
61+ );
62+
6063 // Verify the file exists
6164 expect(fs.existsSync(configPath)).toBe(true);
62-
65+
6366 // Should throw an error mentioning the path and failure to load
6467 await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
65- /Failed to load config from ".*malformed\.yaml": .+/
68+ /Failed to load config from ".*malformed\.yaml": .+/,
6669 );
6770 });
6871
69- test('should fail loudly when --config points to file with missing required fields', async () => {
70- const configPath = path.join(tempDir, 'incomplete.yaml');
71-
72+ test("should fail loudly when --config points to file with missing required fields", async () => {
73+ const configPath = path.join(tempDir, "incomplete.yaml");
74+
7275 // Create a config file missing required fields
73- fs.writeFileSync(configPath, `
76+ fs.writeFileSync(
77+ configPath,
78+ `
7479 name: "Incomplete Config"
7580 # Missing models array and other required fields
76-`);
77-
81+`,
82+ );
83+
7884 // Verify the file exists
7985 expect(fs.existsSync(configPath)).toBe(true);
80-
86+
8187 // Should throw with our specific error format and include path
8288 await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
83- /^Failed to load config from ".*": .+/
89+ /^Failed to load config from ".*": .+/,
8490 );
8591 });
8692
87- test('should handle different config path formats with proper error messages', async () => {
93+ test("should handle different config path formats with proper error messages", async () => {
8894 const testPaths = [
89- './non-existent.yaml',
90- '/absolute/path/config.yaml',
91- '../relative/config.yaml',
92- 'simple-name.yaml'
95+ "./non-existent.yaml",
96+ "/absolute/path/config.yaml",
97+ "../relative/config.yaml",
98+ "simple-name.yaml",
9399 ];
94-
100+
95101 for (const configPath of testPaths) {
96102 await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
97- /Failed to load config from ".*": .+/
103+ /Failed to load config from ".*": .+/,
98104 );
99105 }
100106 });
101107
102- test('should handle empty string config path', async () => {
108+ test("should handle empty string config path", async () => {
103109 // Empty string should be treated differently from undefined
104110 // Note: empty string triggers onboarding flow, but should still fail in our error format
105111 await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow();
106112 });
107113
108- test('should not fall back to default config when explicit config fails', async () => {
109- const configPath = path.join(tempDir, 'bad-config.yaml');
110-
114+ test("should not fall back to default config when explicit config fails", async () => {
115+ const configPath = path.join(tempDir, "bad-config.yaml");
116+
111117 // Create a bad config file
112- fs.writeFileSync(configPath, 'invalid: yaml: content: [');
113-
118+ fs.writeFileSync(configPath, "invalid: yaml: content: [");
119+
114120 const promise = runNormalFlow(mockAuthConfig, configPath);
115-
121+
116122 await expect(promise).rejects.toThrow();
117-
123+
118124 try {
119125 await promise;
120126 } catch (error) {
121127 const message = error instanceof Error ? error.message : String(error);
122-
128+
123129 // CRITICAL: Must have our specific error format from the fix
124130 expect(message).toMatch(/^Failed to load config from ".*": .+/);
125-
131+
126132 // Error should be about the specific config file we provided
127133 expect(message).toContain(configPath);
128-
134+
129135 // Should NOT mention falling back to default config (this was the bug!)
130- expect(message).not.toContain('~/.continue/config.yaml');
131- expect(message).not.toContain('default config');
132- expect(message).not.toContain('fallback');
136+ expect(message).not.toContain("~/.continue/config.yaml");
137+ expect(message).not.toContain("default config");
138+ expect(message).not.toContain("fallback");
133139 }
134140 });
135141
136- test('demonstrates the fix: explicit config failure vs no config provided', async () => {
137- const badConfigPath = path.join(tempDir, 'bad.yaml');
138- fs.writeFileSync(badConfigPath, 'invalid yaml [');
139-
142+ test("demonstrates the fix: explicit config failure vs no config provided", async () => {
143+ const badConfigPath = path.join(tempDir, "bad.yaml");
144+ fs.writeFileSync(badConfigPath, "invalid yaml [");
145+
140146 // Case 1: Explicit --config that fails should throw our specific error
141147 await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow(
142- /^Failed to load config from "/
148+ /^Failed to load config from "/,
143149 );
144-
150+
145151 // Case 2: No explicit config should follow different logic
146152 try {
147153 await runNormalFlow(mockAuthConfig, undefined);
148154 // If it succeeds, that's fine - the point is it's different behavior
149155 } catch (error) {
150- const errorMessage = error instanceof Error ? error.message : String(error);
156+ const errorMessage =
157+ error instanceof Error ? error.message : String(error);
151158 // This should NOT have our "Failed to load config from" prefix
152159 expect(errorMessage).not.toMatch(/^Failed to load config from "/);
153160 }
154161 });
155-});
No newline at the end of the file
162+});
modified extensions/cli/src/permissions/defaultPolicies.test.ts +24 −10
@@ -4,10 +4,18 @@
44
55 describe("defaultPolicies", () => {
66 it("should have correct permissions for read-only tools", () => {
7- const readOnlyTools = ["Read", "List", "Search", "Fetch", "Exit", "Diff", "Checklist"];
8-
7+ const readOnlyTools = [
8+ "Read",
9+ "List",
10+ "Search",
11+ "Fetch",
12+ "Exit",
13+ "Diff",
14+ "Checklist",
15+ ];
16+
917 for (const tool of readOnlyTools) {
10- const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool);
18+ const policy = DEFAULT_TOOL_POLICIES.find((p) => p.tool === tool);
1119 expect(policy, `Policy should exist for ${tool}`).toBeDefined();
1220 expect(policy?.permission, `${tool} should be allowed`).toBe("allow");
1321 }
@@ -15,29 +23,35 @@
1523
1624 it("should have correct permissions for write tools", () => {
1725 const writeTools = ["Write", "Edit", "MultiEdit", "Bash"];
18-
26+
1927 for (const tool of writeTools) {
20- const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool);
28+ const policy = DEFAULT_TOOL_POLICIES.find((p) => p.tool === tool);
2129 expect(policy, `Policy should exist for ${tool}`).toBeDefined();
22- expect(policy?.permission, `${tool} should require confirmation`).toBe("ask");
30+ expect(policy?.permission, `${tool} should require confirmation`).toBe(
31+ "ask",
32+ );
2333 }
2434 });
2535
2636 it("should have a catch-all policy", () => {
27- const catchAllPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "*");
37+ const catchAllPolicy = DEFAULT_TOOL_POLICIES.find((p) => p.tool === "*");
2838 expect(catchAllPolicy).toBeDefined();
2939 expect(catchAllPolicy?.permission).toBe("ask");
3040 });
3141
3242 it("should include MultiEdit policy", () => {
33- const multiEditPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "MultiEdit");
43+ const multiEditPolicy = DEFAULT_TOOL_POLICIES.find(
44+ (p) => p.tool === "MultiEdit",
45+ );
3446 expect(multiEditPolicy).toBeDefined();
3547 expect(multiEditPolicy?.permission).toBe("ask");
3648 });
3749
3850 it("should have policies in correct order", () => {
3951 // The catch-all policy should be last
40- const catchAllIndex = DEFAULT_TOOL_POLICIES.findIndex(p => p.tool === "*");
52+ const catchAllIndex = DEFAULT_TOOL_POLICIES.findIndex(
53+ (p) => p.tool === "*",
54+ );
4155 expect(catchAllIndex).toBe(DEFAULT_TOOL_POLICIES.length - 1);
4256 });
43-});
No newline at the end of the file
57+});
modified extensions/cli/src/permissions/headlessPermissions.integration.test.ts +82 −22
@@ -23,7 +23,10 @@
2323 });
2424
2525 // CLI exclusion should come first
26- expect(policies[0]).toEqual({ tool: "dangerous_tool", permission: "exclude" });
26+ expect(policies[0]).toEqual({
27+ tool: "dangerous_tool",
28+ permission: "exclude",
29+ });
2730 // Default policies should follow
2831 expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
2932 });
@@ -34,16 +37,36 @@
3437 const permissions = { policies: DEFAULT_TOOL_POLICIES };
3538
3639 // Read-only tools should be allowed
37- expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
38- expect(checkToolPermission({ name: "List", arguments: {} }, permissions).permission).toBe("allow");
39- expect(checkToolPermission({ name: "Search", arguments: {} }, permissions).permission).toBe("allow");
40+ expect(
41+ checkToolPermission({ name: "Read", arguments: {} }, permissions)
42+ .permission,
43+ ).toBe("allow");
44+ expect(
45+ checkToolPermission({ name: "List", arguments: {} }, permissions)
46+ .permission,
47+ ).toBe("allow");
48+ expect(
49+ checkToolPermission({ name: "Search", arguments: {} }, permissions)
50+ .permission,
51+ ).toBe("allow");
4052
41- // Write operations should require permission
42- expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
43- expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("ask");
53+ // Write operations should require permission
54+ expect(
55+ checkToolPermission({ name: "Write", arguments: {} }, permissions)
56+ .permission,
57+ ).toBe("ask");
58+ expect(
59+ checkToolPermission({ name: "Bash", arguments: {} }, permissions)
60+ .permission,
61+ ).toBe("ask");
4462
4563 // Unknown tools should default to ask
46- expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
64+ expect(
65+ checkToolPermission(
66+ { name: "unknown_tool", arguments: {} },
67+ permissions,
68+ ).permission,
69+ ).toBe("ask");
4770 });
4871
4972 it("should respect CLI overrides even in headless mode", () => {
@@ -56,13 +79,19 @@
5679 // Excluded tool should be blocked
5780 const excludedResult = checkToolPermission(
5881 { name: "dangerous_tool", arguments: {} },
59- permissions
82+ permissions,
6083 );
6184 expect(excludedResult.permission).toBe("exclude");
6285
6386 // Default tools should follow their normal rules
64- expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
65- expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
87+ expect(
88+ checkToolPermission({ name: "Read", arguments: {} }, permissions)
89+ .permission,
90+ ).toBe("allow");
91+ expect(
92+ checkToolPermission({ name: "Write", arguments: {} }, permissions)
93+ .permission,
94+ ).toBe("ask");
6695 });
6796 });
6897
@@ -83,18 +112,38 @@
83112 const permissions = { policies };
84113
85114 // Excluded tools should be blocked
86- expect(checkToolPermission({ name: "rm", arguments: {} }, permissions).permission).toBe("exclude");
87- expect(checkToolPermission({ name: "sudo", arguments: {} }, permissions).permission).toBe("exclude");
115+ expect(
116+ checkToolPermission({ name: "rm", arguments: {} }, permissions)
117+ .permission,
118+ ).toBe("exclude");
119+ expect(
120+ checkToolPermission({ name: "sudo", arguments: {} }, permissions)
121+ .permission,
122+ ).toBe("exclude");
88123
89124 // Explicitly allowed tools should be allowed
90- expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
91- expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
125+ expect(
126+ checkToolPermission({ name: "Write", arguments: {} }, permissions)
127+ .permission,
128+ ).toBe("allow");
129+ expect(
130+ checkToolPermission({ name: "Bash", arguments: {} }, permissions)
131+ .permission,
132+ ).toBe("allow");
92133
93134 // Read-only tools should still be allowed by default
94- expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
95-
135+ expect(
136+ checkToolPermission({ name: "Read", arguments: {} }, permissions)
137+ .permission,
138+ ).toBe("allow");
139+
96140 // Unknown tools should default to ask (since no wildcard allow override was provided)
97- expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
141+ expect(
142+ checkToolPermission(
143+ { name: "unknown_tool", arguments: {} },
144+ permissions,
145+ ).permission,
146+ ).toBe("ask");
98147 });
99148
100149 it("should handle workflow with wildcard allow override", () => {
@@ -109,9 +158,20 @@
109158 const permissions = { policies };
110159
111160 // All tools should be allowed due to wildcard override
112- expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
113- expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
114- expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("allow");
161+ expect(
162+ checkToolPermission({ name: "Write", arguments: {} }, permissions)
163+ .permission,
164+ ).toBe("allow");
165+ expect(
166+ checkToolPermission({ name: "Bash", arguments: {} }, permissions)
167+ .permission,
168+ ).toBe("allow");
169+ expect(
170+ checkToolPermission(
171+ { name: "unknown_tool", arguments: {} },
172+ permissions,
173+ ).permission,
174+ ).toBe("allow");
115175 });
116176 });
117-});
No newline at the end of the file
177+});
modified extensions/cli/src/permissions/permissionChecker.integration.test.ts +43 −43
@@ -1,114 +1,114 @@
1-import { describe, it, expect, beforeEach } from 'vitest';
1+import { describe, it, expect, beforeEach } from "vitest";
22
3-import { ToolPermissionService } from '../services/ToolPermissionService.js';
3+import { ToolPermissionService } from "../services/ToolPermissionService.js";
44
5-import { checkToolPermission } from './permissionChecker.js';
5+import { checkToolPermission } from "./permissionChecker.js";
66
7-describe('Permission Integration Tests', () => {
7+describe("Permission Integration Tests", () => {
88 let service: ToolPermissionService;
99
1010 beforeEach(() => {
1111 service = new ToolPermissionService();
1212 });
1313
14- describe('Headless mode with --allow flags', () => {
15- it('should allow Edit tool when --allow Edit is specified in headless mode', () => {
14+ describe("Headless mode with --allow flags", () => {
15+ it("should allow Edit tool when --allow Edit is specified in headless mode", () => {
1616 // Initialize service with headless mode and --allow Edit
1717 service.initializeSync({
18- allow: ['Edit'],
19- isHeadless: true
18+ allow: ["Edit"],
19+ isHeadless: true,
2020 });
2121
2222 const state = service.getState();
23-
23+
2424 // Check that the service is in headless mode
2525 expect(state.isHeadless).toBe(true);
2626
2727 // Check permission for Edit tool
2828 const result = checkToolPermission(
29- { name: 'Edit', arguments: {} },
30- state.permissions
29+ { name: "Edit", arguments: {} },
30+ state.permissions,
3131 );
3232
3333 // Should be allowed because --allow Edit is specified
34- expect(result.permission).toBe('allow');
34+ expect(result.permission).toBe("allow");
3535 });
3636
37- it('should allow multiple tools with --allow in headless mode', () => {
37+ it("should allow multiple tools with --allow in headless mode", () => {
3838 // Initialize service with headless mode and multiple --allow flags
3939 service.initializeSync({
40- allow: ['Edit', 'Write', 'Bash'],
41- isHeadless: true
40+ allow: ["Edit", "Write", "Bash"],
41+ isHeadless: true,
4242 });
4343
4444 const state = service.getState();
4545
4646 // Check Edit
4747 const editResult = checkToolPermission(
48- { name: 'Edit', arguments: {} },
49- state.permissions
48+ { name: "Edit", arguments: {} },
49+ state.permissions,
5050 );
51- expect(editResult.permission).toBe('allow');
51+ expect(editResult.permission).toBe("allow");
5252
5353 // Check Write
5454 const writeResult = checkToolPermission(
55- { name: 'Write', arguments: {} },
56- state.permissions
55+ { name: "Write", arguments: {} },
56+ state.permissions,
5757 );
58- expect(writeResult.permission).toBe('allow');
58+ expect(writeResult.permission).toBe("allow");
5959
6060 // Check Bash
6161 const bashResult = checkToolPermission(
62- { name: 'Bash', arguments: {} },
63- state.permissions
62+ { name: "Bash", arguments: {} },
63+ state.permissions,
6464 );
65- expect(bashResult.permission).toBe('allow');
65+ expect(bashResult.permission).toBe("allow");
6666 });
6767
68- it('should respect --exclude in headless mode', () => {
68+ it("should respect --exclude in headless mode", () => {
6969 service.initializeSync({
70- allow: ['Read'],
71- exclude: ['Edit'],
72- isHeadless: true
70+ allow: ["Read"],
71+ exclude: ["Edit"],
72+ isHeadless: true,
7373 });
7474
7575 const state = service.getState();
7676
7777 // Check that Read is allowed
7878 const readResult = checkToolPermission(
79- { name: 'Read', arguments: {} },
80- state.permissions
79+ { name: "Read", arguments: {} },
80+ state.permissions,
8181 );
82- expect(readResult.permission).toBe('allow');
82+ expect(readResult.permission).toBe("allow");
8383
8484 // Check that Edit is excluded
8585 const editResult = checkToolPermission(
86- { name: 'Edit', arguments: {} },
87- state.permissions
86+ { name: "Edit", arguments: {} },
87+ state.permissions,
8888 );
89- expect(editResult.permission).toBe('exclude');
89+ expect(editResult.permission).toBe("exclude");
9090 });
9191
92- it('should work with plan mode and --allow overrides', () => {
92+ it("should work with plan mode and --allow overrides", () => {
9393 // Plan mode normally excludes write operations
9494 service.initializeSync({
95- mode: 'plan',
96- allow: ['Edit'], // But we explicitly allow Edit
97- isHeadless: true
95+ mode: "plan",
96+ allow: ["Edit"], // But we explicitly allow Edit
97+ isHeadless: true,
9898 });
9999
100100 const state = service.getState();
101101
102102 // In plan mode with --allow Edit override
103103 const editResult = checkToolPermission(
104- { name: 'Edit', arguments: {} },
105- state.permissions
104+ { name: "Edit", arguments: {} },
105+ state.permissions,
106106 );
107-
107+
108108 // Currently this fails because plan mode ignores --allow flags
109109 // After fix, this should be 'allow'
110- expect(editResult.permission).toBe('exclude'); // Current behavior
110+ expect(editResult.permission).toBe("exclude"); // Current behavior
111111 // TODO: After fix, change to: expect(editResult.permission).toBe('allow');
112112 });
113113 });
114-});
No newline at the end of the file
114+});
modified extensions/cli/src/permissions/permissionChecker.test.ts +40 −38
@@ -21,7 +21,7 @@
2121
2222 it("should match prefix wildcards", () => {
2323 expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(
24- true
24+ true,
2525 );
2626 expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true);
2727 expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false);
@@ -58,7 +58,7 @@
5858 expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true);
5959 expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true);
6060 expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(
61- true
61+ true,
6262 );
6363 });
6464
@@ -74,64 +74,66 @@
7474 describe("Bash command patterns", () => {
7575 it("should match Bash command patterns with Bash tool", () => {
7676 expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe(
77- true
77+ true,
7878 );
7979 expect(
80- matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" })
80+ matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" }),
8181 ).toBe(true);
8282 expect(
83- matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" })
83+ matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" }),
8484 ).toBe(false);
8585 });
8686
8787 it("should match Bash command patterns with Bash display name", () => {
8888 expect(
89- matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })
89+ matchesToolPattern("Bash", "Bash(git*)", { command: "git status" }),
9090 ).toBe(true);
9191 expect(
92- matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })
92+ matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" }),
9393 ).toBe(true);
9494 expect(
95- matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })
95+ matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" }),
9696 ).toBe(false);
9797 });
9898
9999 it("should match exact Bash commands", () => {
100100 expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe(
101- true
101+ true,
102102 );
103103 expect(
104- matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" })
104+ matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" }),
105105 ).toBe(false);
106106 });
107107
108108 it("should not match Bash patterns for non-bash tools", () => {
109109 expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe(
110- false
110+ false,
111111 );
112112 expect(
113- matchesToolPattern("Write", "Bash(git*)", { command: "git status" })
113+ matchesToolPattern("Write", "Bash(git*)", { command: "git status" }),
114114 ).toBe(false);
115115 });
116116
117117 it("should not match Bash patterns without command argument", () => {
118118 expect(matchesToolPattern("Bash", "Bash(ls*)", {})).toBe(false);
119119 expect(
120- matchesToolPattern("Bash", "Bash(ls*)", { other: "value" })
120+ matchesToolPattern("Bash", "Bash(ls*)", { other: "value" }),
121121 ).toBe(false);
122122 });
123123
124124 it("should handle complex Bash command patterns", () => {
125125 expect(
126- matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" })
126+ matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" }),
127127 ).toBe(true);
128128 expect(
129- matchesToolPattern("Bash", "Bash(npm*)", { command: "npm run build" })
129+ matchesToolPattern("Bash", "Bash(npm*)", {
130+ command: "npm run build",
131+ }),
130132 ).toBe(true);
131133 expect(
132134 matchesToolPattern("Bash", "Bash(git*commit*)", {
133135 command: "git commit -m 'test'",
134- })
136+ }),
135137 ).toBe(true);
136138 });
137139 });
@@ -209,7 +211,7 @@
209211 config: { host: "localhost", port: 3000 }, // Different reference, same content
210212 };
211213 expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(
212- false
214+ false,
213215 );
214216 });
215217
@@ -250,11 +252,11 @@
250252
251253 expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true);
252254 expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(
253- true
255+ true,
254256 );
255257 expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true);
256258 expect(
257- matchesArguments(args, { path: "/home/*/projects/*/src/**" })
259+ matchesArguments(args, { path: "/home/*/projects/*/src/**" }),
258260 ).toBe(true);
259261 expect(matchesArguments(args, { command: "yarn *" })).toBe(false);
260262 });
@@ -268,7 +270,7 @@
268270
269271 // Literal dots, brackets, parentheses should match exactly
270272 expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(
271- true
273+ true,
272274 );
273275 expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true);
274276 expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true);
@@ -276,7 +278,7 @@
276278
277279 // These should not match due to regex escaping
278280 expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(
279- false
281+ false,
280282 );
281283 expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal
282284 });
@@ -294,7 +296,7 @@
294296 tool: "bash", // exact match
295297 command: "cd*install", // glob match
296298 flag: "--verbose", // exact match
297- })
299+ }),
298300 ).toBe(true);
299301
300302 expect(
@@ -302,7 +304,7 @@
302304 tool: "bash", // exact match
303305 command: "cd*test", // glob no match
304306 flag: "--verbose", // exact match
305- })
307+ }),
306308 ).toBe(false);
307309 });
308310
@@ -350,7 +352,7 @@
350352
351353 const result = checkToolPermission(
352354 { name: "readFile", arguments: { path: "/test.txt" } },
353- permissions
355+ permissions,
354356 );
355357
356358 expect(result.permission).toBe("allow");
@@ -367,7 +369,7 @@
367369 name: "writeFile",
368370 arguments: { path: "/test.txt", content: "hello" },
369371 },
370- permissions
372+ permissions,
371373 );
372374
373375 expect(result.permission).toBe("ask");
@@ -381,7 +383,7 @@
381383
382384 const result = checkToolPermission(
383385 { name: "runTerminalCommand", arguments: { command: "rm -rf /" } },
384- permissions
386+ permissions,
385387 );
386388
387389 expect(result.permission).toBe("exclude");
@@ -398,14 +400,14 @@
398400
399401 const mcpResult = checkToolPermission(
400402 { name: "mcp__ide__getDiagnostics", arguments: {} },
401- permissions
403+ permissions,
402404 );
403405 expect(mcpResult.permission).toBe("ask");
404406 expect(mcpResult.matchedPolicy?.tool).toBe("mcp__*");
405407
406408 const builtinResult = checkToolPermission(
407409 { name: "readFile", arguments: { path: "/test.txt" } },
408- permissions
410+ permissions,
409411 );
410412 expect(builtinResult.permission).toBe("allow");
411413 expect(builtinResult.matchedPolicy?.tool).toBe("*");
@@ -428,7 +430,7 @@
428430 name: "writeFile",
429431 arguments: { path: "/sensitive.txt", content: "data" },
430432 },
431- permissions
433+ permissions,
432434 );
433435 expect(sensitiveResult.permission).toBe("exclude");
434436
@@ -437,7 +439,7 @@
437439 name: "writeFile",
438440 arguments: { path: "/normal.txt", content: "data" },
439441 },
440- permissions
442+ permissions,
441443 );
442444 expect(normalResult.permission).toBe("allow");
443445 });
@@ -459,7 +461,7 @@
459461
460462 const result = checkToolPermission(
461463 { name: "unknownTool", arguments: {} },
462- permissions
464+ permissions,
463465 );
464466
465467 expect(result.permission).toBe("ask");
@@ -477,7 +479,7 @@
477479 // Should match "Bash(ls*)" pattern and allow
478480 const lsResult = checkToolPermission(
479481 { name: "Bash", arguments: { command: "ls -la" } },
480- permissions
482+ permissions,
481483 );
482484 expect(lsResult.permission).toBe("allow");
483485 expect(lsResult.matchedPolicy?.tool).toBe("Bash(ls*)");
@@ -485,7 +487,7 @@
485487 // Should match "Bash(git*)" pattern and ask
486488 const gitResult = checkToolPermission(
487489 { name: "Bash", arguments: { command: "git status" } },
488- permissions
490+ permissions,
489491 );
490492 expect(gitResult.permission).toBe("ask");
491493 expect(gitResult.matchedPolicy?.tool).toBe("Bash(git*)");
@@ -493,7 +495,7 @@
493495 // Should match general fallback for other commands
494496 const npmResult = checkToolPermission(
495497 { name: "Bash", arguments: { command: "npm install" } },
496- permissions
498+ permissions,
497499 );
498500 expect(npmResult.permission).toBe("ask");
499501 expect(npmResult.matchedPolicy?.tool).toBe("Bash");
@@ -522,7 +524,7 @@
522524 // Should exclude dangerous rm commands
523525 const rmResult = checkToolPermission(
524526 { name: "Bash", arguments: { command: "rm -rf /" } },
525- permissions
527+ permissions,
526528 );
527529 expect(rmResult.permission).toBe("exclude");
528530 expect(rmResult.matchedPolicy?.argumentMatches?.command).toBe("rm*");
@@ -533,17 +535,17 @@
533535 name: "Write",
534536 arguments: { file_path: "/src/components/Button.ts" },
535537 },
536- permissions
538+ permissions,
537539 );
538540 expect(tsResult.permission).toBe("ask");
539541 expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe(
540- "**/*.ts"
542+ "**/*.ts",
541543 );
542544
543545 // Should allow other file writes
544546 const jsResult = checkToolPermission(
545547 { name: "Write", arguments: { file_path: "/src/utils/helper.js" } },
546- permissions
548+ permissions,
547549 );
548550 expect(jsResult.permission).toBe("allow");
549551 expect(jsResult.matchedPolicy?.argumentMatches).toBeUndefined();
modified extensions/cli/src/permissions/permissionManager.test.ts +2 −2
@@ -206,7 +206,7 @@
206206
207207 // Start all requests
208208 const promises = toolCalls.map((toolCall) =>
209- manager.requestPermission(toolCall)
209+ manager.requestPermission(toolCall),
210210 );
211211
212212 // Get all pending request IDs
@@ -255,7 +255,7 @@
255255
256256 const promise = manager.requestPermission(toolCall);
257257 const requestDetails = manager.getPendingRequest(
258- manager.getPendingRequestIds()[0]
258+ manager.getPendingRequestIds()[0],
259259 );
260260
261261 expect(requestDetails?.toolCall.arguments).toEqual(toolCall.arguments);
modified extensions/cli/src/permissions/permissionsYamlLoader.test.ts +47 −26
@@ -1,4 +1,7 @@
1-import { yamlConfigToPolicies, parseToolPattern } from "./permissionsYamlLoader.js";
1+import {
2+ yamlConfigToPolicies,
3+ parseToolPattern,
4+} from "./permissionsYamlLoader.js";
25
36 describe("permissionsYamlLoader", () => {
47 describe("yamlConfigToPolicies", () => {
@@ -89,34 +92,34 @@
8992 describe("parseToolPattern", () => {
9093 it("should parse tool name without arguments", () => {
9194 const policy = parseToolPattern("Write", "allow");
92-
95+
9396 expect(policy).toEqual({
9497 tool: "Write",
95- permission: "allow"
98+ permission: "allow",
9699 });
97100 });
98101
99102 it("should parse tool name with file path pattern", () => {
100103 const policy = parseToolPattern("Write(**/*.ts)", "exclude");
101-
104+
102105 expect(policy).toEqual({
103106 tool: "Write",
104107 permission: "exclude",
105108 argumentMatches: {
106- file_path: "**/*.ts"
107- }
109+ file_path: "**/*.ts",
110+ },
108111 });
109112 });
110113
111114 it("should parse bash command with argument", () => {
112115 const policy = parseToolPattern("Bash(npm install)", "ask");
113-
116+
114117 expect(policy).toEqual({
115118 tool: "Bash",
116119 permission: "ask",
117120 argumentMatches: {
118- command: "npm install"
119- }
121+ command: "npm install",
122+ },
120123 });
121124 });
122125
@@ -124,20 +127,36 @@
124127 const testCases = [
125128 {
126129 pattern: "Read(src/**/*.js)",
127- expected: { tool: "Read", permission: "allow", argumentMatches: { file_path: "src/**/*.js" } }
130+ expected: {
131+ tool: "Read",
132+ permission: "allow",
133+ argumentMatches: { file_path: "src/**/*.js" },
134+ },
128135 },
129136 {
130137 pattern: "List(/home/user)",
131- expected: { tool: "List", permission: "allow", argumentMatches: { path: "/home/user" } }
138+ expected: {
139+ tool: "List",
140+ permission: "allow",
141+ argumentMatches: { path: "/home/user" },
142+ },
132143 },
133144 {
134145 pattern: "Search(TODO)",
135- expected: { tool: "Search", permission: "allow", argumentMatches: { query: "TODO" } }
146+ expected: {
147+ tool: "Search",
148+ permission: "allow",
149+ argumentMatches: { query: "TODO" },
150+ },
136151 },
137152 {
138153 pattern: "Fetch(https://api.example.com)",
139- expected: { tool: "Fetch", permission: "allow", argumentMatches: { url: "https://api.example.com" } }
140- }
154+ expected: {
155+ tool: "Fetch",
156+ permission: "allow",
157+ argumentMatches: { url: "https://api.example.com" },
158+ },
159+ },
141160 ];
142161
143162 testCases.forEach(({ pattern, expected }) => {
@@ -148,50 +167,52 @@
148167
149168 it("should handle empty arguments", () => {
150169 const policy = parseToolPattern("Write()", "allow");
151-
170+
152171 expect(policy).toEqual({
153172 tool: "Write",
154- permission: "allow"
173+ permission: "allow",
155174 });
156175 });
157176
158177 it("should handle whitespace in arguments", () => {
159178 const policy = parseToolPattern("Bash( npm run test )", "ask");
160-
179+
161180 expect(policy).toEqual({
162181 tool: "Bash",
163182 permission: "ask",
164183 argumentMatches: {
165- command: "npm run test"
166- }
184+ command: "npm run test",
185+ },
167186 });
168187 });
169188
170189 it("should handle unknown tools with default argument key", () => {
171190 const policy = parseToolPattern("CustomTool(some-pattern)", "allow");
172-
191+
173192 expect(policy).toEqual({
174193 tool: "CustomTool",
175194 permission: "allow",
176195 argumentMatches: {
177- pattern: "some-pattern"
178- }
196+ pattern: "some-pattern",
197+ },
179198 });
180199 });
181200
182201 it("should throw error for invalid pattern", () => {
183- expect(() => parseToolPattern("Write(unclosed", "allow")).toThrow("Invalid tool pattern: Write(unclosed");
202+ expect(() => parseToolPattern("Write(unclosed", "allow")).toThrow(
203+ "Invalid tool pattern: Write(unclosed",
204+ );
184205 });
185206
186207 it("should use exact tool names in patterns", () => {
187208 const policy = parseToolPattern("write(**/*.ts)", "allow");
188-
209+
189210 expect(policy).toEqual({
190211 tool: "write",
191212 permission: "allow",
192213 argumentMatches: {
193- pattern: "**/*.ts"
194- }
214+ pattern: "**/*.ts",
215+ },
195216 });
196217 });
197218 });
modified extensions/cli/src/permissions/policyWriter.test.ts +27 −9
@@ -4,22 +4,38 @@
44 describe("generatePolicyRule", () => {
55 it("should return display name for regular tools", () => {
66 expect(generatePolicyRule("Read", { file_path: "/test" })).toBe("Read");
7- expect(generatePolicyRule("Write", { file_path: "/test", content: "test" })).toBe("Write");
7+ expect(
8+ generatePolicyRule("Write", { file_path: "/test", content: "test" }),
9+ ).toBe("Write");
810 expect(generatePolicyRule("List", { path: "/test" })).toBe("List");
911 expect(generatePolicyRule("Search", { pattern: "test" })).toBe("Search");
1012 expect(generatePolicyRule("Grep", { pattern: "test" })).toBe("Grep"); // Unknown tool, passes through
1113 });
1214
1315 it("should generate command-specific patterns for Bash tool", () => {
14- expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe("Bash(ls*)");
15- expect(generatePolicyRule("Bash", { command: "git status" })).toBe("Bash(git*)");
16- expect(generatePolicyRule("Bash", { command: "npm install" })).toBe("Bash(npm*)");
16+ expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe(
17+ "Bash(ls*)",
18+ );
19+ expect(generatePolicyRule("Bash", { command: "git status" })).toBe(
20+ "Bash(git*)",
21+ );
22+ expect(generatePolicyRule("Bash", { command: "npm install" })).toBe(
23+ "Bash(npm*)",
24+ );
1725 });
1826
1927 it("should handle complex bash commands", () => {
20- expect(generatePolicyRule("Bash", { command: "ls -la && echo test" })).toBe("Bash(ls*)");
21- expect(generatePolicyRule("Bash", { command: "find . -name '*.ts' | head -10" })).toBe("Bash(find*)");
22- expect(generatePolicyRule("Bash", { command: " grep -r test . " })).toBe("Bash(grep*)");
28+ expect(
29+ generatePolicyRule("Bash", { command: "ls -la && echo test" }),
30+ ).toBe("Bash(ls*)");
31+ expect(
32+ generatePolicyRule("Bash", {
33+ command: "find . -name '*.ts' | head -10",
34+ }),
35+ ).toBe("Bash(find*)");
36+ expect(
37+ generatePolicyRule("Bash", { command: " grep -r test . " }),
38+ ).toBe("Bash(grep*)");
2339 });
2440
2541 it("should fallback to display name for bash tools without command", () => {
@@ -32,7 +48,9 @@
3248 expect(generatePolicyRule("bash", { command: "ls" })).toBe("bash");
3349 expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("BASH");
3450 expect(generatePolicyRule("read", { file_path: "/test" })).toBe("read");
35- expect(generatePolicyRule("write", { file_path: "/test", content: "test" })).toBe("write");
51+ expect(
52+ generatePolicyRule("write", { file_path: "/test", content: "test" }),
53+ ).toBe("write");
3654 });
3755 });
38-});
No newline at the end of the file
56+});
modified extensions/cli/src/permissions/policyWriter.verify.test.ts +1 −1
@@ -20,4 +20,4 @@
2020 expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("EDIT");
2121 expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit");
2222 });
23-});
No newline at the end of the file
23+});
modified extensions/cli/src/permissions/precedenceResolver.test.ts +5 −5
@@ -128,15 +128,15 @@
128128 });
129129
130130 // Find the Write policy - should be from CLI (allow)
131- const writePolicy = policies.find(p => p.tool === "Write");
131+ const writePolicy = policies.find((p) => p.tool === "Write");
132132 expect(writePolicy?.permission).toBe("allow");
133133
134134 // Find the Search policy - should be from config
135- const searchPolicy = policies.find(p => p.tool === "Search");
135+ const searchPolicy = policies.find((p) => p.tool === "Search");
136136 expect(searchPolicy?.permission).toBe("ask");
137137
138138 // Should still have default policies
139- const readPolicy = policies.find(p => p.tool === "Read");
139+ const readPolicy = policies.find((p) => p.tool === "Read");
140140 expect(readPolicy).toBeDefined();
141141 });
142142
@@ -178,9 +178,9 @@
178178
179179 // Config policy should override default
180180 expect(policies[0]).toEqual({ tool: "Bash", permission: "allow" });
181- // Default policies should follow
181+ // Default policies should follow
182182 expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
183183 });
184184 });
185185 });
186-});
No newline at the end of the file
186+});
modified extensions/cli/src/permissions/yamlPermissions.test.ts +22 −24
@@ -1,17 +1,17 @@
1-import { describe, it, expect, beforeEach, vi } from 'vitest';
1+import { describe, it, expect, beforeEach, vi } from "vitest";
22
3-import { checkToolPermission } from './permissionChecker.js';
4-import { yamlConfigToPolicies } from './permissionsYamlLoader.js';
3+import { checkToolPermission } from "./permissionChecker.js";
4+import { yamlConfigToPolicies } from "./permissionsYamlLoader.js";
55
66 // Mock fs module
7-vi.mock('fs');
7+vi.mock("fs");
88
9-describe('YAML Permissions - Edit Tool Bug', () => {
9+describe("YAML Permissions - Edit Tool Bug", () => {
1010 beforeEach(() => {
1111 vi.clearAllMocks();
1212 });
1313
14- it('should allow Edit tool when it is in the allow list', () => {
14+ it("should allow Edit tool when it is in the allow list", () => {
1515 // Test the exact YAML content from the user
1616 const yamlContent = `allow:
1717 - Edit
@@ -20,54 +20,52 @@
2020
2121 // Parse the YAML config
2222 const config = {
23- allow: ['Edit'],
23+ allow: ["Edit"],
2424 ask: [],
25- exclude: []
25+ exclude: [],
2626 };
2727
2828 // Convert to policies
2929 const policies = yamlConfigToPolicies(config);
30- console.log('Converted policies:', policies);
30+ console.log("Converted policies:", policies);
3131
3232 // The policies should have Edit as allowed
33- expect(policies).toEqual([
34- { tool: 'Edit', permission: 'allow' }
35- ]);
33+ expect(policies).toEqual([{ tool: "Edit", permission: "allow" }]);
3634
3735 // Test permission check with tool call named "Edit"
3836 const toolCall1 = {
39- name: 'Edit',
40- arguments: { filepath: 'test.txt' }
37+ name: "Edit",
38+ arguments: { filepath: "test.txt" },
4139 };
4240 const result1 = checkToolPermission(toolCall1, { policies });
4341 console.log('Permission check for "Edit":', result1);
44- expect(result1.permission).toBe('allow');
42+ expect(result1.permission).toBe("allow");
4543
4644 // Legacy names should NOT work anymore
4745 const toolCall2 = {
48- name: 'search_and_replace_in_file',
49- arguments: { filepath: 'test.txt' }
46+ name: "search_and_replace_in_file",
47+ arguments: { filepath: "test.txt" },
5048 };
5149 const result2 = checkToolPermission(toolCall2, { policies });
5250 console.log('Permission check for "search_and_replace_in_file":', result2);
53- expect(result2.permission).toBe('ask'); // Should not match, falls back to ask
51+ expect(result2.permission).toBe("ask"); // Should not match, falls back to ask
5452
5553 // Legacy names should NOT work anymore
5654 const toolCall3 = {
57- name: 'edit_file',
58- arguments: { filepath: 'test.txt' }
55+ name: "edit_file",
56+ arguments: { filepath: "test.txt" },
5957 };
6058 const result3 = checkToolPermission(toolCall3, { policies });
6159 console.log('Permission check for "edit_file":', result3);
62- expect(result3.permission).toBe('ask'); // Should not match, falls back to ask
60+ expect(result3.permission).toBe("ask"); // Should not match, falls back to ask
6361 });
6462
65-it('should use exact tool names without normalization', () => {
63+ it("should use exact tool names without normalization", () => {
6664 // Tools are now used exactly as they are named, no normalization
6765 const editName = "Edit";
6866 const multiEditName = "MultiEdit";
69-
67+
7068 expect(editName).toBe("Edit");
7169 expect(multiEditName).toBe("MultiEdit");
7270 });
73-});
No newline at the end of the file
71+});
modified extensions/cli/src/services/ApiClientService.test.ts +46 −42
@@ -1,18 +1,18 @@
1-import { describe, expect, test, beforeEach, vi } from 'vitest';
1+import { describe, expect, test, beforeEach, vi } from "vitest";
22
33 // Mock the config module
4-vi.mock('../config.js');
5-import * as config from '../config.js';
4+vi.mock("../config.js");
5+import * as config from "../config.js";
66
7-import { ApiClientService } from './ApiClientService.js';
7+import { ApiClientService } from "./ApiClientService.js";
88
9-describe('ApiClientService', () => {
9+describe("ApiClientService", () => {
1010 let service: ApiClientService;
1111 const mockApiClient = {
1212 get: vi.fn(),
1313 post: vi.fn(),
1414 put: vi.fn(),
15- delete: vi.fn()
15+ delete: vi.fn(),
1616 };
1717
1818 beforeEach(() => {
@@ -20,114 +20,118 @@
2020 service = new ApiClientService();
2121 });
2222
23- describe('State Management', () => {
24- test('should initialize with null api client', async () => {
23+ describe("State Management", () => {
24+ test("should initialize with null api client", async () => {
2525 vi.mocked(config.getApiClient).mockReturnValue(null as any);
2626
2727 const state = await service.initialize({ accessToken: null } as any);
2828
2929 expect(state).toEqual({
30- apiClient: null
30+ apiClient: null,
3131 });
3232 });
3333
34- test('should initialize with api client when token provided', async () => {
34+ test("should initialize with api client when token provided", async () => {
3535 vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
3636
37- const state = await service.initialize({ accessToken: 'test-token' } as any);
37+ const state = await service.initialize({
38+ accessToken: "test-token",
39+ } as any);
3840
3941 expect(state).toEqual({
40- apiClient: mockApiClient
42+ apiClient: mockApiClient,
4143 });
42- expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith('test-token');
44+ expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith("test-token");
4345 });
4446 });
4547
46- describe('update()', () => {
47- test('should update api client with new auth config', async () => {
48+ describe("update()", () => {
49+ test("should update api client with new auth config", async () => {
4850 // Initialize first
4951 vi.mocked(config.getApiClient).mockReturnValue(null as any);
5052 await service.initialize({ accessToken: null } as any);
5153
5254 // Update with new token
5355 vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
54- const state = await service.update({ accessToken: 'new-token' } as any);
56+ const state = await service.update({ accessToken: "new-token" } as any);
5557
5658 expect(state).toEqual({
57- apiClient: mockApiClient
59+ apiClient: mockApiClient,
5860 });
5961 expect(service.getState()).toEqual(state);
6062 });
6163
62- test('should handle update errors', async () => {
64+ test("should handle update errors", async () => {
6365 await service.initialize({ accessToken: null } as any);
64-
66+
6567 vi.mocked(config.getApiClient).mockImplementation(() => {
66- throw new Error('Failed to create client');
68+ throw new Error("Failed to create client");
6769 });
6870
69- await expect(service.update({ accessToken: 'bad-token' } as any)).rejects.toThrow(
70- 'Failed to create client'
71- );
71+ await expect(
72+ service.update({ accessToken: "bad-token" } as any),
73+ ).rejects.toThrow("Failed to create client");
7274 });
7375 });
7476
75- describe('isReady()', () => {
76- test('should return false when not initialized', () => {
77+ describe("isReady()", () => {
78+ test("should return false when not initialized", () => {
7779 expect(service.isReady()).toBe(false);
7880 });
7981
80- test('should return false when api client is null', async () => {
82+ test("should return false when api client is null", async () => {
8183 vi.mocked(config.getApiClient).mockReturnValue(null as any);
8284 await service.initialize({ accessToken: null } as any);
8385
8486 expect(service.isReady()).toBe(false);
8587 });
8688
87- test('should return true when api client exists', async () => {
89+ test("should return true when api client exists", async () => {
8890 vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
89- await service.initialize({ accessToken: 'token' } as any);
91+ await service.initialize({ accessToken: "token" } as any);
9092
9193 expect(service.isReady()).toBe(true);
9294 });
9395 });
9496
95- describe('getDependencies()', () => {
96- test('should declare auth dependency', () => {
97- expect(service.getDependencies()).toEqual(['auth']);
97+ describe("getDependencies()", () => {
98+ test("should declare auth dependency", () => {
99+ expect(service.getDependencies()).toEqual(["auth"]);
98100 });
99101 });
100102
101- describe('Event Emission', () => {
102- test('should emit stateChanged on update', async () => {
103+ describe("Event Emission", () => {
104+ test("should emit stateChanged on update", async () => {
103105 vi.mocked(config.getApiClient).mockReturnValue(null as any);
104106 await service.initialize({ accessToken: null } as any);
105107
106108 const listener = vi.fn();
107- service.on('stateChanged', listener);
109+ service.on("stateChanged", listener);
108110
109111 vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
110- await service.update({ accessToken: 'new-token' } as any);
112+ await service.update({ accessToken: "new-token" } as any);
111113
112114 expect(listener).toHaveBeenCalledWith(
113115 expect.objectContaining({ apiClient: mockApiClient }),
114- expect.objectContaining({ apiClient: null })
116+ expect.objectContaining({ apiClient: null }),
115117 );
116118 });
117119
118- test('should emit error on update failure', async () => {
120+ test("should emit error on update failure", async () => {
119121 await service.initialize({ accessToken: null } as any);
120-
122+
121123 const errorListener = vi.fn();
122- service.on('error', errorListener);
124+ service.on("error", errorListener);
123125
124- const error = new Error('Update failed');
126+ const error = new Error("Update failed");
125127 vi.mocked(config.getApiClient).mockImplementation(() => {
126128 throw error;
127129 });
128130
129- await expect(service.update({ accessToken: 'bad' } as any)).rejects.toThrow();
131+ await expect(
132+ service.update({ accessToken: "bad" } as any),
133+ ).rejects.toThrow();
130134 expect(errorListener).toHaveBeenCalledWith(error);
131135 });
132136 });
133-});
No newline at the end of the file
137+});
modified extensions/cli/src/services/AuthService.test.ts +97 −83
@@ -1,30 +1,30 @@
1-import { describe, expect, test, beforeEach, vi } from 'vitest';
1+import { describe, expect, test, beforeEach, vi } from "vitest";
22
33 // Mock the workos module
4-vi.mock('../auth/workos.js');
4+vi.mock("../auth/workos.js");
55
66 // Import the workos functions we need to mock
7-import {
7+import {
88 loadAuthConfig,
99 isAuthenticated,
1010 login,
1111 logout,
1212 ensureOrganization,
1313 saveAuthConfig,
14- listUserOrganizations
15-} from '../auth/workos.js';
14+ listUserOrganizations,
15+} from "../auth/workos.js";
1616
17-import { AuthService } from './AuthService.js';
17+import { AuthService } from "./AuthService.js";
1818
19-describe('AuthService', () => {
19+describe("AuthService", () => {
2020 let service: AuthService;
2121 const mockAuthConfig = {
22- accessToken: 'test-token',
23- organizationId: 'org-123',
24- userId: 'user-123',
25- userEmail: 'test@example.com',
26- refreshToken: 'refresh-token',
27- expiresAt: Date.now() + 3600000
22+ accessToken: "test-token",
23+ organizationId: "org-123",
24+ userId: "user-123",
25+ userEmail: "test@example.com",
26+ refreshToken: "refresh-token",
27+ expiresAt: Date.now() + 3600000,
2828 };
2929
3030 beforeEach(() => {
@@ -32,8 +32,8 @@
3232 service = new AuthService();
3333 });
3434
35- describe('State Management', () => {
36- test('should initialize with unauthenticated state', async () => {
35+ describe("State Management", () => {
36+ test("should initialize with unauthenticated state", async () => {
3737 vi.mocked(loadAuthConfig).mockReturnValue(null);
3838 vi.mocked(isAuthenticated).mockReturnValue(false);
3939
@@ -42,11 +42,11 @@
4242 expect(state).toEqual({
4343 authConfig: null,
4444 isAuthenticated: false,
45- organizationId: undefined
45+ organizationId: undefined,
4646 });
4747 });
4848
49- test('should initialize with authenticated state', async () => {
49+ test("should initialize with authenticated state", async () => {
5050 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
5151 vi.mocked(isAuthenticated).mockReturnValue(true);
5252
@@ -55,13 +55,13 @@
5555 expect(state).toEqual({
5656 authConfig: mockAuthConfig,
5757 isAuthenticated: true,
58- organizationId: 'org-123'
58+ organizationId: "org-123",
5959 });
6060 });
6161 });
6262
63- describe('login()', () => {
64- test('should update state after successful login', async () => {
63+ describe("login()", () => {
64+ test("should update state after successful login", async () => {
6565 // Initialize first
6666 vi.mocked(loadAuthConfig).mockReturnValue(null);
6767 vi.mocked(isAuthenticated).mockReturnValue(false);
@@ -75,22 +75,22 @@
7575 expect(state).toEqual({
7676 authConfig: mockAuthConfig,
7777 isAuthenticated: true,
78- organizationId: 'org-123'
78+ organizationId: "org-123",
7979 });
8080 expect(service.getState()).toEqual(state);
8181 });
8282
83- test('should handle login failure', async () => {
83+ test("should handle login failure", async () => {
8484 await service.initialize();
85- const loginError = new Error('Login failed');
85+ const loginError = new Error("Login failed");
8686 vi.mocked(login).mockRejectedValue(loginError);
8787
88- await expect(service.login()).rejects.toThrow('Login failed');
88+ await expect(service.login()).rejects.toThrow("Login failed");
8989 });
9090 });
9191
92- describe('logout()', () => {
93- test('should clear state after logout', async () => {
92+ describe("logout()", () => {
93+ test("should clear state after logout", async () => {
9494 // Initialize with authenticated state
9595 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
9696 vi.mocked(isAuthenticated).mockReturnValue(true);
@@ -101,14 +101,14 @@
101101 expect(state).toEqual({
102102 authConfig: null,
103103 isAuthenticated: false,
104- organizationId: undefined
104+ organizationId: undefined,
105105 });
106106 expect(logout).toHaveBeenCalled();
107107 });
108108 });
109109
110- describe('ensureOrganization()', () => {
111- test('should update organization after ensuring', async () => {
110+ describe("ensureOrganization()", () => {
111+ test("should update organization after ensuring", async () => {
112112 // Initialize with auth but no org
113113 const authWithoutOrg = { ...mockAuthConfig, organizationId: null };
114114 vi.mocked(loadAuthConfig).mockReturnValue(authWithoutOrg);
@@ -123,39 +123,43 @@
123123 expect(state).toEqual({
124124 authConfig: mockAuthConfig,
125125 isAuthenticated: true,
126- organizationId: 'org-123'
126+ organizationId: "org-123",
127127 });
128128 });
129129
130- test('should throw error if not authenticated', async () => {
130+ test("should throw error if not authenticated", async () => {
131131 vi.mocked(loadAuthConfig).mockReturnValue(null);
132132 vi.mocked(isAuthenticated).mockReturnValue(false);
133133 await service.initialize();
134134
135135 await expect(service.ensureOrganization()).rejects.toThrow(
136- 'Not authenticated - cannot ensure organization'
136+ "Not authenticated - cannot ensure organization",
137137 );
138138 });
139139
140- test('should pass organization slug to ensureOrganization in headless mode', async () => {
140+ test("should pass organization slug to ensureOrganization in headless mode", async () => {
141141 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
142142 vi.mocked(isAuthenticated).mockReturnValue(true);
143143 await service.initialize();
144144
145- const updatedConfig = { ...mockAuthConfig, organizationId: 'org-456' };
145+ const updatedConfig = { ...mockAuthConfig, organizationId: "org-456" };
146146 vi.mocked(ensureOrganization).mockResolvedValue(updatedConfig);
147147
148- const state = await service.ensureOrganization(true, 'org-slug');
148+ const state = await service.ensureOrganization(true, "org-slug");
149149
150- expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'org-slug');
150+ expect(ensureOrganization).toHaveBeenCalledWith(
151+ mockAuthConfig,
152+ true,
153+ "org-slug",
154+ );
151155 expect(state).toEqual({
152156 authConfig: updatedConfig,
153157 isAuthenticated: true,
154- organizationId: 'org-456'
158+ organizationId: "org-456",
155159 });
156160 });
157161
158- test('should handle personal organization slug', async () => {
162+ test("should handle personal organization slug", async () => {
159163 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
160164 vi.mocked(isAuthenticated).mockReturnValue(true);
161165 await service.initialize();
@@ -163,17 +167,21 @@
163167 const personalConfig = { ...mockAuthConfig, organizationId: null };
164168 vi.mocked(ensureOrganization).mockResolvedValue(personalConfig);
165169
166- const state = await service.ensureOrganization(true, 'personal');
170+ const state = await service.ensureOrganization(true, "personal");
167171
168- expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'personal');
172+ expect(ensureOrganization).toHaveBeenCalledWith(
173+ mockAuthConfig,
174+ true,
175+ "personal",
176+ );
169177 expect(state).toEqual({
170178 authConfig: personalConfig,
171179 isAuthenticated: true,
172- organizationId: undefined
180+ organizationId: undefined,
173181 });
174182 });
175183
176- test('should work without organization slug parameter', async () => {
184+ test("should work without organization slug parameter", async () => {
177185 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
178186 vi.mocked(isAuthenticated).mockReturnValue(true);
179187 await service.initialize();
@@ -182,38 +190,42 @@
182190
183191 const state = await service.ensureOrganization(false);
184192
185- expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, false, undefined);
193+ expect(ensureOrganization).toHaveBeenCalledWith(
194+ mockAuthConfig,
195+ false,
196+ undefined,
197+ );
186198 expect(state).toEqual({
187199 authConfig: mockAuthConfig,
188200 isAuthenticated: true,
189- organizationId: 'org-123'
201+ organizationId: "org-123",
190202 });
191203 });
192204 });
193205
194- describe('switchOrganization()', () => {
195- test('should update state with new organization', async () => {
206+ describe("switchOrganization()", () => {
207+ test("should update state with new organization", async () => {
196208 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
197209 vi.mocked(isAuthenticated).mockReturnValue(true);
198210 await service.initialize();
199211
200- const state = await service.switchOrganization('org-456');
212+ const state = await service.switchOrganization("org-456");
201213
202214 expect(state).toEqual({
203215 authConfig: {
204216 ...mockAuthConfig,
205- organizationId: 'org-456'
217+ organizationId: "org-456",
206218 },
207219 isAuthenticated: true,
208- organizationId: 'org-456'
220+ organizationId: "org-456",
209221 });
210222 expect(saveAuthConfig).toHaveBeenCalledWith({
211223 ...mockAuthConfig,
212- organizationId: 'org-456'
224+ organizationId: "org-456",
213225 });
214226 });
215227
216- test('should handle null organization', async () => {
228+ test("should handle null organization", async () => {
217229 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
218230 vi.mocked(isAuthenticated).mockReturnValue(true);
219231 await service.initialize();
@@ -223,27 +235,27 @@
223235 expect(state.organizationId).toBeUndefined();
224236 });
225237
226- test('should throw error if not file-based auth', async () => {
227- const tokenOnlyAuth = { accessToken: 'token' } as any;
238+ test("should throw error if not file-based auth", async () => {
239+ const tokenOnlyAuth = { accessToken: "token" } as any;
228240 vi.mocked(loadAuthConfig).mockReturnValue(tokenOnlyAuth);
229241 vi.mocked(isAuthenticated).mockReturnValue(true);
230242 await service.initialize();
231243
232- await expect(service.switchOrganization('org-456')).rejects.toThrow(
233- 'Not authenticated with file-based auth'
244+ await expect(service.switchOrganization("org-456")).rejects.toThrow(
245+ "Not authenticated with file-based auth",
234246 );
235247 });
236248 });
237249
238- describe('getAvailableOrganizations()', () => {
239- test('should return organizations when authenticated', async () => {
250+ describe("getAvailableOrganizations()", () => {
251+ test("should return organizations when authenticated", async () => {
240252 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
241253 vi.mocked(isAuthenticated).mockReturnValue(true);
242254 await service.initialize();
243255
244256 const mockOrgs = [
245- { id: 'org-1', name: 'Org 1', slug: 'org-1' },
246- { id: 'org-2', name: 'Org 2', slug: 'org-2' }
257+ { id: "org-1", name: "Org 1", slug: "org-1" },
258+ { id: "org-2", name: "Org 2", slug: "org-2" },
247259 ];
248260 vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs);
249261
@@ -251,7 +263,7 @@
251263 expect(orgs).toEqual(mockOrgs);
252264 });
253265
254- test('should return null when not authenticated', async () => {
266+ test("should return null when not authenticated", async () => {
255267 vi.mocked(loadAuthConfig).mockReturnValue(null);
256268 vi.mocked(isAuthenticated).mockReturnValue(false);
257269 await service.initialize();
@@ -260,42 +272,44 @@
260272 expect(orgs).toBeNull();
261273 });
262274
263- test('should handle errors gracefully', async () => {
275+ test("should handle errors gracefully", async () => {
264276 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
265277 vi.mocked(isAuthenticated).mockReturnValue(true);
266278 await service.initialize();
267279
268- vi.mocked(listUserOrganizations).mockRejectedValue(new Error('API error'));
280+ vi.mocked(listUserOrganizations).mockRejectedValue(
281+ new Error("API error"),
282+ );
269283
270284 // Add error event listener to prevent unhandled rejection
271285 const errorHandler = vi.fn();
272- service.on('error', errorHandler);
286+ service.on("error", errorHandler);
273287
274288 const orgs = await service.getAvailableOrganizations();
275289 expect(orgs).toBeNull();
276290 expect(errorHandler).toHaveBeenCalledWith(expect.any(Error));
277291
278292 // Clean up
279- service.off('error', errorHandler);
293+ service.off("error", errorHandler);
280294 });
281295 });
282296
283- describe('hasMultipleOrganizations()', () => {
284- test('should return true when multiple orgs available', async () => {
297+ describe("hasMultipleOrganizations()", () => {
298+ test("should return true when multiple orgs available", async () => {
285299 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
286300 vi.mocked(isAuthenticated).mockReturnValue(true);
287301 await service.initialize();
288302
289303 vi.mocked(listUserOrganizations).mockResolvedValue([
290- { id: 'org-1', name: 'Org 1', slug: 'org-1' },
291- { id: 'org-2', name: 'Org 2', slug: 'org-2' }
304+ { id: "org-1", name: "Org 1", slug: "org-1" },
305+ { id: "org-2", name: "Org 2", slug: "org-2" },
292306 ]);
293307
294308 const hasMultiple = await service.hasMultipleOrganizations();
295309 expect(hasMultiple).toBe(true);
296310 });
297311
298- test('should return false when no orgs available', async () => {
312+ test("should return false when no orgs available", async () => {
299313 vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
300314 vi.mocked(isAuthenticated).mockReturnValue(true);
301315 await service.initialize();
@@ -307,8 +321,8 @@
307321 });
308322 });
309323
310- describe('refresh()', () => {
311- test('should reload auth state from disk', async () => {
324+ describe("refresh()", () => {
325+ test("should reload auth state from disk", async () => {
312326 vi.mocked(loadAuthConfig).mockReturnValue(null);
313327 vi.mocked(isAuthenticated).mockReturnValue(false);
314328 await service.initialize();
@@ -322,20 +336,20 @@
322336 expect(state).toEqual({
323337 authConfig: mockAuthConfig,
324338 isAuthenticated: true,
325- organizationId: 'org-123'
339+ organizationId: "org-123",
326340 });
327341 });
328342 });
329343
330- describe('Event Emission', () => {
331- test('should emit stateChanged on login', async () => {
344+ describe("Event Emission", () => {
345+ test("should emit stateChanged on login", async () => {
332346 // Initialize with no auth config to simulate logged out state
333347 vi.mocked(loadAuthConfig).mockReturnValue(null);
334348 vi.mocked(isAuthenticated).mockReturnValue(false);
335349 await service.initialize();
336-
350+
337351 const listener = vi.fn();
338- service.on('stateChanged', listener);
352+ service.on("stateChanged", listener);
339353
340354 vi.mocked(login).mockResolvedValue(mockAuthConfig);
341355 await service.login();
@@ -344,25 +358,25 @@
344358 expect.objectContaining({
345359 isAuthenticated: true,
346360 authConfig: mockAuthConfig,
347- organizationId: 'org-123'
361+ organizationId: "org-123",
348362 }),
349363 expect.objectContaining({
350364 isAuthenticated: false,
351- authConfig: null
352- })
365+ authConfig: null,
366+ }),
353367 );
354368 });
355369
356- test('should emit error on login failure', async () => {
370+ test("should emit error on login failure", async () => {
357371 await service.initialize();
358372 const errorListener = vi.fn();
359- service.on('error', errorListener);
373+ service.on("error", errorListener);
360374
361- const error = new Error('Login failed');
375+ const error = new Error("Login failed");
362376 vi.mocked(login).mockRejectedValue(error);
363377
364378 await expect(service.login()).rejects.toThrow();
365379 expect(errorListener).toHaveBeenCalledWith(error);
366380 });
367381 });
368-});
No newline at the end of the file
382+});
modified extensions/cli/src/services/BaseService.test.ts +158 −143
@@ -1,6 +1,10 @@
1-import { describe, expect, test, beforeEach, vi } from 'vitest';
1+import { describe, expect, test, beforeEach, vi } from "vitest";
22
3-import { BaseService, hasDependencies, ServiceWithDependencies } from './BaseService.js';
3+import {
4+ BaseService,
5+ hasDependencies,
6+ ServiceWithDependencies,
7+} from "./BaseService.js";
48
59 // Test implementation of BaseService
610 interface TestState {
@@ -11,16 +15,16 @@
1115
1216 class TestService extends BaseService<TestState> {
1317 constructor() {
14- super('TestService', {
18+ super("TestService", {
1519 value: 0,
16- message: 'initial'
20+ message: "initial",
1721 });
1822 }
1923
2024 async doInitialize(value: number, message: string): Promise<TestState> {
2125 return {
2226 value,
23- message
27+ message,
2428 };
2529 }
2630
@@ -31,175 +35,180 @@
3135 }
3236
3337 // Test service with dependencies
34-class DependentTestService extends TestService implements ServiceWithDependencies {
38+class DependentTestService
39+ extends TestService
40+ implements ServiceWithDependencies
41+{
3542 getDependencies(): string[] {
36- return ['auth', 'config'];
43+ return ["auth", "config"];
3744 }
3845 }
3946
4047 // Test service that throws during initialization
4148 class FailingTestService extends BaseService<TestState> {
4249 constructor() {
43- super('FailingService', {
50+ super("FailingService", {
4451 value: 0,
45- message: 'initial'
52+ message: "initial",
4653 });
4754 }
4855
4956 async doInitialize(): Promise<TestState> {
50- throw new Error('Initialization failed');
57+ throw new Error("Initialization failed");
5158 }
5259 }
5360
54-describe('BaseService', () => {
55- describe('Basic Functionality', () => {
61+describe("BaseService", () => {
62+ describe("Basic Functionality", () => {
5663 let service: TestService;
5764
5865 beforeEach(() => {
5966 service = new TestService();
6067 });
6168
62- test('should have correct initial state', () => {
69+ test("should have correct initial state", () => {
6370 const state = service.getState();
6471 expect(state).toEqual({
6572 value: 0,
66- message: 'initial'
73+ message: "initial",
6774 });
6875 expect(service.isReady()).toBe(false);
6976 });
7077
71- test('should initialize successfully', async () => {
72- const state = await service.initialize(42, 'initialized');
73-
78+ test("should initialize successfully", async () => {
79+ const state = await service.initialize(42, "initialized");
80+
7481 expect(state).toEqual({
7582 value: 42,
76- message: 'initialized'
83+ message: "initialized",
7784 });
7885 expect(service.isReady()).toBe(true);
7986 });
8087
81- test('should emit initialization events', async () => {
88+ test("should emit initialization events", async () => {
8289 const initializingListener = vi.fn();
8390 const initializedListener = vi.fn();
84-
85- service.on('initializing', initializingListener);
86- service.on('initialized', initializedListener);
87-
88- await service.initialize(42, 'initialized');
89-
91+
92+ service.on("initializing", initializingListener);
93+ service.on("initialized", initializedListener);
94+
95+ await service.initialize(42, "initialized");
96+
9097 expect(initializingListener).toHaveBeenCalledTimes(1);
9198 expect(initializedListener).toHaveBeenCalledTimes(1);
9299 expect(initializedListener).toHaveBeenCalledWith({
93100 value: 42,
94- message: 'initialized'
101+ message: "initialized",
95102 });
96103 });
97104
98- test('should handle initialization failure', async () => {
105+ test("should handle initialization failure", async () => {
99106 const failingService = new FailingTestService();
100107 const errorListener = vi.fn();
101-
102- failingService.on('error', errorListener);
103-
104- await expect(failingService.initialize()).rejects.toThrow('Initialization failed');
108+
109+ failingService.on("error", errorListener);
110+
111+ await expect(failingService.initialize()).rejects.toThrow(
112+ "Initialization failed",
113+ );
105114 expect(errorListener).toHaveBeenCalledTimes(1);
106115 expect(failingService.isReady()).toBe(false);
107116 });
108117 });
109118
110- describe('State Management', () => {
119+ describe("State Management", () => {
111120 let service: TestService;
112121
113122 beforeEach(() => {
114123 service = new TestService();
115124 });
116125
117- test('should return immutable state copy', async () => {
118- await service.initialize(42, 'test');
119-
126+ test("should return immutable state copy", async () => {
127+ await service.initialize(42, "test");
128+
120129 const state1 = service.getState();
121130 const state2 = service.getState();
122-
131+
123132 expect(state1).toEqual(state2);
124133 expect(state1).not.toBe(state2); // Different object references
125134 });
126135
127- test('should return shallow copy of state', async () => {
128- await service.initialize(42, 'test');
136+ test("should return shallow copy of state", async () => {
137+ await service.initialize(42, "test");
129138 service.updateState({ data: [{ id: 1 }, { id: 2 }] });
130-
139+
131140 const state = service.getState();
132141 const originalData = state.data;
133-
142+
134143 // Modify the returned state's nested object
135144 if (state.data) {
136145 state.data[0].id = 999;
137146 }
138-
147+
139148 // With shallow copy, nested objects are shared
140149 const newState = service.getState();
141150 expect(newState.data).toEqual([{ id: 999 }, { id: 2 }]);
142151 expect(newState.data).toBe(originalData); // Same reference for nested objects
143152 });
144153
145- test('should emit state change events', async () => {
146- await service.initialize(42, 'test');
147-
154+ test("should emit state change events", async () => {
155+ await service.initialize(42, "test");
156+
148157 const stateChangeListener = vi.fn();
149- service.on('stateChanged', stateChangeListener);
150-
158+ service.on("stateChanged", stateChangeListener);
159+
151160 service.updateState({ value: 100 });
152-
161+
153162 expect(stateChangeListener).toHaveBeenCalledTimes(1);
154163 expect(stateChangeListener).toHaveBeenCalledWith(
155- { value: 100, message: 'test' }, // new state
156- { value: 42, message: 'test' } // previous state
164+ { value: 100, message: "test" }, // new state
165+ { value: 42, message: "test" }, // previous state
157166 );
158167 });
159168
160- test('should merge partial state updates', async () => {
161- await service.initialize(42, 'test');
162-
169+ test("should merge partial state updates", async () => {
170+ await service.initialize(42, "test");
171+
163172 service.updateState({ value: 100 });
164173 expect(service.getState()).toEqual({
165174 value: 100,
166- message: 'test'
175+ message: "test",
167176 });
168-
169- service.updateState({ message: 'updated' });
177+
178+ service.updateState({ message: "updated" });
170179 expect(service.getState()).toEqual({
171180 value: 100,
172- message: 'updated'
181+ message: "updated",
173182 });
174183 });
175184 });
176185
177- describe('Reload Functionality', () => {
186+ describe("Reload Functionality", () => {
178187 let service: TestService;
179188
180189 beforeEach(() => {
181190 service = new TestService();
182191 });
183192
184- test('should reload service with new parameters', async () => {
185- await service.initialize(42, 'first');
193+ test("should reload service with new parameters", async () => {
194+ await service.initialize(42, "first");
186195 expect(service.getState()).toEqual({
187196 value: 42,
188- message: 'first'
197+ message: "first",
189198 });
190-
191- await service.reload(100, 'second');
199+
200+ await service.reload(100, "second");
192201 expect(service.getState()).toEqual({
193202 value: 100,
194- message: 'second'
203+ message: "second",
195204 });
196205 expect(service.isReady()).toBe(true);
197206 });
198207
199- test('should reset isInitialized during reload', async () => {
200- await service.initialize(42, 'test');
208+ test("should reset isInitialized during reload", async () => {
209+ await service.initialize(42, "test");
201210 expect(service.isReady()).toBe(true);
202-
211+
203212 // Create a promise to check intermediate state
204213 let wasNotReady = false;
205214 const originalInit = service.initialize.bind(service);
@@ -207,100 +216,104 @@
207216 wasNotReady = !service.isReady();
208217 return originalInit(value, message);
209218 }) as any;
210-
211- await service.reload(100, 'reloaded');
212-
219+
220+ await service.reload(100, "reloaded");
221+
213222 expect(wasNotReady).toBe(true);
214223 expect(service.isReady()).toBe(true);
215224 });
216225 });
217226
218- describe('Cleanup', () => {
227+ describe("Cleanup", () => {
219228 let service: TestService;
220229
221230 beforeEach(() => {
222231 service = new TestService();
223232 });
224233
225- test('should cleanup resources', async () => {
226- await service.initialize(42, 'test');
227-
234+ test("should cleanup resources", async () => {
235+ await service.initialize(42, "test");
236+
228237 const listener = vi.fn();
229- service.on('test-event', listener);
230-
238+ service.on("test-event", listener);
239+
231240 await service.cleanup();
232-
241+
233242 expect(service.isReady()).toBe(false);
234-
243+
235244 // Verify listeners are removed
236- service.emit('test-event');
245+ service.emit("test-event");
237246 expect(listener).not.toHaveBeenCalled();
238247 });
239248 });
240249
241- describe('ServiceWithDependencies', () => {
242- test('should correctly identify services with dependencies', () => {
250+ describe("ServiceWithDependencies", () => {
251+ test("should correctly identify services with dependencies", () => {
243252 const regularService = new TestService();
244253 const dependentService = new DependentTestService();
245-
254+
246255 expect(hasDependencies(regularService)).toBe(false);
247256 expect(hasDependencies(dependentService)).toBe(true);
248-
257+
249258 if (hasDependencies(dependentService)) {
250- expect(dependentService.getDependencies()).toEqual(['auth', 'config']);
259+ expect(dependentService.getDependencies()).toEqual(["auth", "config"]);
251260 }
252261 });
253262 });
254263
255- describe('Shallow Copy Functionality', () => {
264+ describe("Shallow Copy Functionality", () => {
256265 let service: TestService;
257266
258267 beforeEach(() => {
259268 service = new TestService();
260269 });
261270
262- test('should handle null and undefined values', async () => {
263- await service.initialize(42, 'test');
264- service.updateState({
265- data: [null, undefined, 'string', 123] as any
271+ test("should handle null and undefined values", async () => {
272+ await service.initialize(42, "test");
273+ service.updateState({
274+ data: [null, undefined, "string", 123] as any,
266275 });
267-
276+
268277 const state = service.getState();
269- expect(state.data).toEqual([null, undefined, 'string', 123]);
278+ expect(state.data).toEqual([null, undefined, "string", 123]);
270279 });
271280
272- test('should handle Date objects', async () => {
273- const date = new Date('2024-01-01');
274- await service.initialize(42, 'test');
275- service.updateState({
276- data: [date] as any
281+ test("should handle Date objects", async () => {
282+ const date = new Date("2024-01-01");
283+ await service.initialize(42, "test");
284+ service.updateState({
285+ data: [date] as any,
277286 });
278-
287+
279288 const state = service.getState();
280289 expect(state.data?.[0]).toEqual(date);
281290 expect(state.data?.[0]).toBe(date); // Same instance with shallow copy
282291 expect(state.data?.[0]).toBeInstanceOf(Date);
283292 });
284293
285- test('should handle complex nested structures', async () => {
294+ test("should handle complex nested structures", async () => {
286295 const complexData = {
287296 nested: {
288- array: [1, 2, { deep: 'value' }],
297+ array: [1, 2, { deep: "value" }],
289298 date: new Date(),
290299 bool: true,
291- null: null
292- }
300+ null: null,
301+ },
293302 };
294-
295- await service.initialize(42, 'test');
303+
304+ await service.initialize(42, "test");
296305 service.updateState({ data: complexData as any });
297-
306+
298307 const state = service.getState();
299308 expect(state.data).toEqual(complexData);
300309 expect(state.data).toBe(complexData); // Same reference with shallow copy
301-
310+
302311 // Verify nested objects are shared (not deep copied)
303- if (state.data && typeof state.data === 'object' && 'nested' in state.data) {
312+ if (
313+ state.data &&
314+ typeof state.data === "object" &&
315+ "nested" in state.data
316+ ) {
304317 const data = state.data as any;
305318 expect(data.nested.array).toBe(complexData.nested.array);
306319 expect(data.nested.array[2]).toBe(complexData.nested.array[2]);
@@ -308,79 +321,81 @@
308321 });
309322 });
310323
311- describe('Error Handling', () => {
312- test('should emit error events on setState failures', () => {
324+ describe("Error Handling", () => {
325+ test("should emit error events on setState failures", () => {
313326 const service = new TestService();
314-
327+
315328 // Override setState to throw
316329 const originalSetState = Object.getOwnPropertyDescriptor(
317- Object.getPrototypeOf(service),
318- 'setState'
330+ Object.getPrototypeOf(service),
331+ "setState",
319332 );
320-
321- Object.defineProperty(service, 'setState', {
322- value: function() {
323- throw new Error('setState failed');
324- }
333+
334+ Object.defineProperty(service, "setState", {
335+ value: function () {
336+ throw new Error("setState failed");
337+ },
325338 });
326-
327- expect(() => service.updateState({ value: 100 })).toThrow('setState failed');
328-
339+
340+ expect(() => service.updateState({ value: 100 })).toThrow(
341+ "setState failed",
342+ );
343+
329344 // Restore original
330345 if (originalSetState) {
331346 Object.defineProperty(
332- Object.getPrototypeOf(service),
333- 'setState',
334- originalSetState
347+ Object.getPrototypeOf(service),
348+ "setState",
349+ originalSetState,
335350 );
336351 }
337352 });
338353 });
339354
340- describe('Event Emitter Integration', () => {
355+ describe("Event Emitter Integration", () => {
341356 let service: TestService;
342357
343358 beforeEach(() => {
344359 service = new TestService();
345360 });
346361
347- test('should support multiple listeners', async () => {
362+ test("should support multiple listeners", async () => {
348363 const listener1 = vi.fn();
349364 const listener2 = vi.fn();
350-
351- service.on('initialized', listener1);
352- service.on('initialized', listener2);
353-
354- await service.initialize(42, 'test');
355-
365+
366+ service.on("initialized", listener1);
367+ service.on("initialized", listener2);
368+
369+ await service.initialize(42, "test");
370+
356371 expect(listener1).toHaveBeenCalledTimes(1);
357372 expect(listener2).toHaveBeenCalledTimes(1);
358373 });
359374
360- test('should support once listeners', async () => {
375+ test("should support once listeners", async () => {
361376 const listener = vi.fn();
362-
363- service.once('stateChanged', listener);
364-
365- await service.initialize(42, 'test');
377+
378+ service.once("stateChanged", listener);
379+
380+ await service.initialize(42, "test");
366381 service.updateState({ value: 100 });
367382 service.updateState({ value: 200 });
368-
383+
369384 expect(listener).toHaveBeenCalledTimes(1);
370385 });
371386
372- test('should allow removing specific listeners', async () => {
387+ test("should allow removing specific listeners", async () => {
373388 const listener = vi.fn();
374-
375- service.on('stateChanged', listener);
376- await service.initialize(42, 'test');
377-
389+
390+ service.on("stateChanged", listener);
391+ await service.initialize(42, "test");
392+
378393 service.updateState({ value: 100 });
379394 expect(listener).toHaveBeenCalledTimes(1);
380-
381- service.off('stateChanged', listener);
395+
396+ service.off("stateChanged", listener);
382397 service.updateState({ value: 200 });
383398 expect(listener).toHaveBeenCalledTimes(1); // Not called again
384399 });
385400 });
386-});
No newline at the end of the file
401+});
modified extensions/cli/src/services/ConfigService.test.ts +43 −41
@@ -40,7 +40,7 @@
4040 { accessToken: "token" } as any,
4141 "/path/to/config.yaml",
4242 "org-123",
43- mockApiClient as any
43+ mockApiClient as any,
4444 );
4545
4646 expect(state).toEqual({
@@ -59,7 +59,7 @@
5959 { accessToken: "token" } as any,
6060 undefined,
6161 "org-123",
62- mockApiClient as any
62+ mockApiClient as any,
6363 );
6464
6565 expect(state).toEqual({
@@ -69,20 +69,20 @@
6969 });
7070
7171 test("should inject rules into config", async () => {
72-
7372 vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
7473 config: mockConfig as any,
7574 source: { type: "cli-flag", path: "/config.yaml" } as any,
7675 });
77- vi.mocked(args.processRule)
78- .mockImplementation(async (rule) => `Processed: ${rule}`);
76+ vi.mocked(args.processRule).mockImplementation(
77+ async (rule) => `Processed: ${rule}`,
78+ );
7979
8080 const state = await service.initialize(
8181 { accessToken: "token" } as any,
8282 "/config.yaml",
8383 "org-123",
8484 mockApiClient as any,
85- ["rule1", "rule2"]
85+ ["rule1", "rule2"],
8686 );
8787
8888 expect(state.config).toEqual({
@@ -95,7 +95,6 @@
9595
9696 describe("switchConfig()", () => {
9797 test("should switch to new configuration", async () => {
98-
9998 // Initialize first
10099 vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
101100 config: mockConfig as any,
@@ -105,7 +104,7 @@
105104 { accessToken: "token" } as any,
106105 "/old.yaml",
107106 "org-123",
108- mockApiClient as any
107+ mockApiClient as any,
109108 );
110109
111110 // Switch to new config
@@ -119,7 +118,7 @@
119118 "/new.yaml",
120119 { accessToken: "token" } as any,
121120 "org-123",
122- mockApiClient as any
121+ mockApiClient as any,
123122 );
124123
125124 expect(state).toEqual({
@@ -130,31 +129,30 @@
130129 });
131130
132131 test("should handle switch config errors", async () => {
133-
134132 await service.initialize(
135133 { accessToken: "token" } as any,
136134 "/old.yaml",
137135 "org-123",
138- mockApiClient as any
136+ mockApiClient as any,
139137 );
140138
141- vi.mocked(configLoader.loadConfiguration)
142- .mockRejectedValue(new Error("Config not found"));
139+ vi.mocked(configLoader.loadConfiguration).mockRejectedValue(
140+ new Error("Config not found"),
141+ );
143142
144143 await expect(
145144 service.switchConfig(
146145 "/bad.yaml",
147146 { accessToken: "token" } as any,
148147 "org-123",
149- mockApiClient as any
150- )
148+ mockApiClient as any,
149+ ),
151150 ).rejects.toThrow("Config not found");
152151 });
153152 });
154153
155154 describe("reload()", () => {
156155 test("should reload current configuration", async () => {
157-
158156 // Initialize with a config
159157 vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
160158 config: mockConfig as any,
@@ -164,7 +162,7 @@
164162 { accessToken: "token" } as any,
165163 "/config.yaml",
166164 "org-123",
167- mockApiClient as any
165+ mockApiClient as any,
168166 );
169167
170168 // Modify mock to return updated config
@@ -177,7 +175,7 @@
177175 const state = await service.reload(
178176 { accessToken: "token" } as any,
179177 "org-123",
180- mockApiClient as any
178+ mockApiClient as any,
181179 );
182180
183181 expect(state).toEqual({
@@ -196,22 +194,21 @@
196194 { accessToken: "token" } as any,
197195 undefined,
198196 "org-123",
199- mockApiClient as any
197+ mockApiClient as any,
200198 );
201199
202200 await expect(
203201 service.reload(
204202 { accessToken: "token" } as any,
205203 "org-123",
206- mockApiClient as any
207- )
204+ mockApiClient as any,
205+ ),
208206 ).rejects.toThrow("No configuration path available for reload");
209207 });
210208 });
211209
212210 describe("updateConfigPath()", () => {
213211 test("should update config path and reload dependent services", async () => {
214-
215212 // Initialize service first
216213 vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
217214 config: mockConfig as any,
@@ -221,12 +218,14 @@
221218 { accessToken: "token" } as any,
222219 "/old.yaml",
223220 "org-123",
224- mockApiClient as any
221+ mockApiClient as any,
225222 );
226223
227224 // Mock service container
228- vi.mocked(workos.loadAuthConfig)
229- .mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
225+ vi.mocked(workos.loadAuthConfig).mockReturnValue({
226+ accessToken: "token",
227+ organizationId: "org-123",
228+ } as any);
230229 vi.mocked(serviceContainer.get).mockResolvedValue({
231230 apiClient: mockApiClient,
232231 });
@@ -246,13 +245,13 @@
246245 });
247246 expect(vi.mocked(serviceContainer.set)).toHaveBeenCalledWith(
248247 SERVICE_NAMES.CONFIG,
249- expect.objectContaining({ config: newConfig })
248+ expect.objectContaining({ config: newConfig }),
250249 );
251250 expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith(
252- SERVICE_NAMES.MODEL
251+ SERVICE_NAMES.MODEL,
253252 );
254253 expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith(
255- SERVICE_NAMES.MCP
254+ SERVICE_NAMES.MCP,
256255 );
257256 });
258257
@@ -261,17 +260,19 @@
261260 { accessToken: "token" } as any,
262261 "/old.yaml",
263262 "org-123",
264- mockApiClient as any
263+ mockApiClient as any,
265264 );
266265
267- vi.mocked(workos.loadAuthConfig)
268- .mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
266+ vi.mocked(workos.loadAuthConfig).mockReturnValue({
267+ accessToken: "token",
268+ organizationId: "org-123",
269+ } as any);
269270 vi.mocked(serviceContainer.get).mockResolvedValue({
270271 apiClient: null,
271272 });
272273
273274 await expect(service.updateConfigPath("/new.yaml")).rejects.toThrow(
274- "API client not available"
275+ "API client not available",
275276 );
276277 });
277278 });
@@ -284,7 +285,6 @@
284285
285286 describe("Event Emission", () => {
286287 test("should emit stateChanged when switching config", async () => {
287-
288288 vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
289289 config: mockConfig as any,
290290 source: { type: "cli-flag", path: "/old.yaml" } as any,
@@ -293,7 +293,7 @@
293293 { accessToken: "token" } as any,
294294 "/old.yaml",
295295 "org-123",
296- mockApiClient as any
296+ mockApiClient as any,
297297 );
298298
299299 const listener = vi.fn();
@@ -309,22 +309,24 @@
309309 "/new.yaml",
310310 { accessToken: "token" } as any,
311311 "org-123",
312- mockApiClient as any
312+ mockApiClient as any,
313313 );
314314
315315 expect(listener).toHaveBeenCalledWith(
316316 expect.objectContaining({ config: newConfig, configPath: "/new.yaml" }),
317- expect.objectContaining({ config: mockConfig, configPath: "/old.yaml" })
317+ expect.objectContaining({
318+ config: mockConfig,
319+ configPath: "/old.yaml",
320+ }),
318321 );
319322 });
320323
321324 test("should emit error on switch failure", async () => {
322-
323325 await service.initialize(
324326 { accessToken: "token" } as any,
325327 "/old.yaml",
326328 "org-123",
327- mockApiClient as any
329+ mockApiClient as any,
328330 );
329331
330332 const errorListener = vi.fn();
@@ -338,8 +340,8 @@
338340 "/bad.yaml",
339341 { accessToken: "token" } as any,
340342 "org-123",
341- mockApiClient as any
342- )
343+ mockApiClient as any,
344+ ),
343345 ).rejects.toThrow();
344346 expect(errorListener).toHaveBeenCalledWith(error);
345347 });
@@ -367,4 +369,4 @@
367369 expect(service.updateConfigPath.length).toBe(1);
368370 });
369371 });
370-});
No newline at the end of the file
372+});
modified extensions/cli/src/services/FileIndexService.test.ts +71 −68
@@ -1,12 +1,12 @@
1-import * as fs from 'fs';
2-import * as path from 'path';
1+import * as fs from "fs";
2+import * as path from "path";
33
4-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
6-import { FileIndexService } from './FileIndexService.js';
6+import { FileIndexService } from "./FileIndexService.js";
77
88 // Mock the file watcher
9-vi.mock('../util/fileWatcher.js', () => ({
9+vi.mock("../util/fileWatcher.js", () => ({
1010 getFileWatcher: () => ({
1111 startWatching: vi.fn(),
1212 stopWatching: vi.fn(),
@@ -15,18 +15,18 @@
1515 }));
1616
1717 // Mock git detection
18-vi.mock('../util/git.js', () => ({
18+vi.mock("../util/git.js", () => ({
1919 isGitRepo: vi.fn(() => false),
2020 }));
2121
22-describe('FileIndexService', () => {
22+describe("FileIndexService", () => {
2323 let service: FileIndexService;
2424 let tempDir: string;
2525 let originalCwd: string;
2626
2727 beforeEach(() => {
2828 originalCwd = process.cwd();
29- tempDir = fs.mkdtempSync(path.join(process.cwd(), 'test-fileindex-'));
29+ tempDir = fs.mkdtempSync(path.join(process.cwd(), "test-fileindex-"));
3030 process.chdir(tempDir);
3131
3232 service = new FileIndexService();
@@ -40,11 +40,11 @@
4040 }
4141 });
4242
43- it('should initialize and index files', async () => {
43+ it("should initialize and index files", async () => {
4444 // Create test files
45- fs.writeFileSync('test.js', 'console.log("test");');
46- fs.writeFileSync('test.ts', 'console.log("test");');
47- fs.writeFileSync('README.md', '# Test');
45+ fs.writeFileSync("test.js", 'console.log("test");');
46+ fs.writeFileSync("test.ts", 'console.log("test");');
47+ fs.writeFileSync("README.md", "# Test");
4848
4949 // Initialize the service
5050 await service.initialize();
@@ -52,99 +52,102 @@
5252 // Should have indexed the files
5353 const files = service.getFiles();
5454 expect(files.length).toBeGreaterThan(0);
55-
56- const filePaths = files.map(f => f.path);
57- expect(filePaths).toContain('test.js');
58- expect(filePaths).toContain('test.ts');
59- expect(filePaths).toContain('README.md');
55+
56+ const filePaths = files.map((f) => f.path);
57+ expect(filePaths).toContain("test.js");
58+ expect(filePaths).toContain("test.ts");
59+ expect(filePaths).toContain("README.md");
6060 });
6161
62- it('should filter files correctly', async () => {
62+ it("should filter files correctly", async () => {
6363 // Create test files
64- fs.writeFileSync('component.tsx', 'export default () => <div></div>');
65- fs.writeFileSync('utils.ts', 'export const util = () => {}');
66- fs.writeFileSync('styles.css', '.test { color: red; }');
64+ fs.writeFileSync("component.tsx", "export default () => <div></div>");
65+ fs.writeFileSync("utils.ts", "export const util = () => {}");
66+ fs.writeFileSync("styles.css", ".test { color: red; }");
6767
6868 await service.initialize();
6969
7070 // Test filtering by extension
71- const tsFiles = service.filterFiles('ts');
72- expect(tsFiles.some(f => f.path === 'component.tsx')).toBe(true);
73- expect(tsFiles.some(f => f.path === 'utils.ts')).toBe(true);
74- expect(tsFiles.some(f => f.path === 'styles.css')).toBe(false);
71+ const tsFiles = service.filterFiles("ts");
72+ expect(tsFiles.some((f) => f.path === "component.tsx")).toBe(true);
73+ expect(tsFiles.some((f) => f.path === "utils.ts")).toBe(true);
74+ expect(tsFiles.some((f) => f.path === "styles.css")).toBe(false);
7575
7676 // Test filtering by name
77- const componentFiles = service.filterFiles('component');
78- expect(componentFiles.some(f => f.path === 'component.tsx')).toBe(true);
79- expect(componentFiles.some(f => f.path === 'utils.ts')).toBe(false);
77+ const componentFiles = service.filterFiles("component");
78+ expect(componentFiles.some((f) => f.path === "component.tsx")).toBe(true);
79+ expect(componentFiles.some((f) => f.path === "utils.ts")).toBe(false);
8080 });
8181
82- it('should handle empty directory', async () => {
82+ it("should handle empty directory", async () => {
8383 await service.initialize();
84-
84+
8585 const files = service.getFiles();
8686 expect(files).toEqual([]);
8787 expect(service.isIndexing()).toBe(false);
8888 expect(service.getError()).toBeNull();
8989 });
9090
91- it('should ignore specified patterns', async () => {
91+ it("should ignore specified patterns", async () => {
9292 // Create files that should be ignored
93- fs.mkdirSync('node_modules');
94- fs.writeFileSync(path.join('node_modules', 'package.js'), 'module.exports = {}');
95-
96- fs.mkdirSync('dist');
97- fs.writeFileSync(path.join('dist', 'bundle.js'), 'console.log("bundle")');
93+ fs.mkdirSync("node_modules");
94+ fs.writeFileSync(
95+ path.join("node_modules", "package.js"),
96+ "module.exports = {}",
97+ );
98+
99+ fs.mkdirSync("dist");
100+ fs.writeFileSync(path.join("dist", "bundle.js"), 'console.log("bundle")');
98101
99102 // Create files that should be included
100- fs.writeFileSync('src.js', 'console.log("src")');
103+ fs.writeFileSync("src.js", 'console.log("src")');
101104
102105 await service.initialize();
103106
104107 const files = service.getFiles();
105- const filePaths = files.map(f => f.path);
106-
108+ const filePaths = files.map((f) => f.path);
109+
107110 // Should include src.js
108- expect(filePaths).toContain('src.js');
109-
111+ expect(filePaths).toContain("src.js");
112+
110113 // Should not include ignored files
111- expect(filePaths.some(p => p.includes('node_modules'))).toBe(false);
112- expect(filePaths.some(p => p.includes('dist'))).toBe(false);
114+ expect(filePaths.some((p) => p.includes("node_modules"))).toBe(false);
115+ expect(filePaths.some((p) => p.includes("dist"))).toBe(false);
113116 });
114117
115- it('should sort files correctly with no filter', async () => {
118+ it("should sort files correctly with no filter", async () => {
116119 // Create files in non-alphabetical order
117- fs.writeFileSync('zebra.js', 'console.log("zebra")');
118- fs.writeFileSync('alpha.js', 'console.log("alpha")');
119- fs.writeFileSync('beta.js', 'console.log("beta")');
120+ fs.writeFileSync("zebra.js", 'console.log("zebra")');
121+ fs.writeFileSync("alpha.js", 'console.log("alpha")');
122+ fs.writeFileSync("beta.js", 'console.log("beta")');
120123
121124 await service.initialize();
122125
123- const files = service.filterFiles('');
124- expect(files[0].path).toBe('alpha.js');
125- expect(files[1].path).toBe('beta.js');
126- expect(files[2].path).toBe('zebra.js');
126+ const files = service.filterFiles("");
127+ expect(files[0].path).toBe("alpha.js");
128+ expect(files[1].path).toBe("beta.js");
129+ expect(files[2].path).toBe("zebra.js");
127130 });
128131
129- it('should include files with matching names and paths', async () => {
132+ it("should include files with matching names and paths", async () => {
130133 // Create nested structure
131- fs.mkdirSync('src');
132- fs.writeFileSync(path.join('src', 'test-helper.js'), 'helper');
133- fs.writeFileSync('test.js', 'test file');
134+ fs.mkdirSync("src");
135+ fs.writeFileSync(path.join("src", "test-helper.js"), "helper");
136+ fs.writeFileSync("test.js", "test file");
134137
135138 await service.initialize();
136139
137- const filtered = service.filterFiles('test');
138-
140+ const filtered = service.filterFiles("test");
141+
139142 // Should include both files that match the filter
140143 expect(filtered.length).toBeGreaterThanOrEqual(2);
141- const filePaths = filtered.map(f => f.path);
142- expect(filePaths).toContain('test.js');
144+ const filePaths = filtered.map((f) => f.path);
145+ expect(filePaths).toContain("test.js");
143146 // Normalize path separators for cross-platform compatibility
144- expect(filePaths).toContain(path.join('src', 'test-helper.js'));
147+ expect(filePaths).toContain(path.join("src", "test-helper.js"));
145148 });
146149
147- it('should respect limit parameter', async () => {
150+ it("should respect limit parameter", async () => {
148151 // Create many files
149152 for (let i = 0; i < 20; i++) {
150153 fs.writeFileSync(`file${i}.js`, `console.log("file${i}")`);
@@ -152,22 +155,22 @@
152155
153156 await service.initialize();
154157
155- const files = service.filterFiles('', 5);
158+ const files = service.filterFiles("", 5);
156159 expect(files.length).toBe(5);
157160 });
158161
159- it('should handle refresh correctly', async () => {
162+ it("should handle refresh correctly", async () => {
160163 // Create initial file
161- fs.writeFileSync('initial.js', 'console.log("initial")');
162-
164+ fs.writeFileSync("initial.js", 'console.log("initial")');
165+
163166 await service.initialize();
164167 expect(service.getFiles().length).toBe(1);
165168
166169 // Add another file
167- fs.writeFileSync('added.js', 'console.log("added")');
168-
170+ fs.writeFileSync("added.js", 'console.log("added")');
171+
169172 // Refresh should pick up the new file
170173 await service.refreshIndex();
171174 expect(service.getFiles().length).toBe(2);
172175 });
173-});
No newline at the end of the file
176+});
modified extensions/cli/src/services/MCPService.test.ts +10 −7
@@ -43,7 +43,7 @@
4343
4444 afterEach(async () => {
4545 vi.clearAllMocks();
46- await mcpService.cleanup()
46+ await mcpService.cleanup();
4747 });
4848
4949 describe("initialization", () => {
@@ -86,7 +86,7 @@
8686 const firstStatus = mcpService.getOverallStatus();
8787 expect(firstStatus.status).toBe("connected");
8888 expect(firstStatus.hasWarnings).toBe(false);
89- await mcpService.cleanup()
89+ await mcpService.cleanup();
9090 const secondStatus = mcpService.getOverallStatus();
9191 expect(secondStatus.status).toBe("idle");
9292 });
@@ -107,14 +107,13 @@
107107
108108 it("should handle server not found error", async () => {
109109 await expect(mcpService.restartServer("nonexistent")).rejects.toThrow(
110- "Server nonexistent not found in configuration"
110+ "Server nonexistent not found in configuration",
111111 );
112112 });
113113
114114 it("should handle stop individual server", async () => {
115115 await expect(mcpService.stopServer("test-server")).resolves.not.toThrow();
116116 });
117-
118117 });
119118
120119 describe("tools and prompts", () => {
@@ -129,7 +128,7 @@
129128
130129 it("should throw error for unknown tool", async () => {
131130 await expect(mcpService.runTool("unknown-tool", {})).rejects.toThrow(
132- "Tool unknown-tool not found"
131+ "Tool unknown-tool not found",
133132 );
134133 });
135134 });
@@ -137,10 +136,14 @@
137136 describe("shutdown", () => {
138137 it("should handle shutdown gracefully", async () => {
139138 await mcpService.initialize(mockAssistant);
140- await mcpService.cleanup()
139+ await mcpService.cleanup();
141140
142141 const state = mcpService.getState();
143- expect(state.mcpService?.getState().connections.filter(c => c.status === "connected")).toHaveLength(0)
142+ expect(
143+ state.mcpService
144+ ?.getState()
145+ .connections.filter((c) => c.status === "connected"),
146+ ).toHaveLength(0);
144147 });
145148
146149 it("should handle multiple shutdown calls", async () => {
modified extensions/cli/src/services/ModeService.test.ts +118 −118
@@ -1,8 +1,8 @@
1-import { beforeEach, afterEach, describe, expect, vi, test } from 'vitest';
1+import { beforeEach, afterEach, describe, expect, vi, test } from "vitest";
22
3-import { ModeService } from './ModeService.js';
3+import { ModeService } from "./ModeService.js";
44
5-describe('ModeService', () => {
5+describe("ModeService", () => {
66 let modeService: ModeService;
77
88 beforeEach(() => {
@@ -16,166 +16,166 @@
1616 (ModeService as any).instance = undefined;
1717 });
1818
19- describe('State Management', () => {
20- test('should initialize with normal mode by default', async () => {
19+ describe("State Management", () => {
20+ test("should initialize with normal mode by default", async () => {
2121 const state = await modeService.initialize({});
22-
22+
2323 expect(state).toEqual({
24- mode: 'normal',
25- toolPermissionService: expect.any(Object)
24+ mode: "normal",
25+ toolPermissionService: expect.any(Object),
2626 });
27- expect(modeService.getCurrentMode()).toBe('normal');
27+ expect(modeService.getCurrentMode()).toBe("normal");
2828 });
2929
30- test('should convert readonly flag to plan mode', async () => {
30+ test("should convert readonly flag to plan mode", async () => {
3131 const state = await modeService.initialize({ readonly: true });
32-
33- expect(state.mode).toBe('plan');
34- expect(modeService.getCurrentMode()).toBe('plan');
32+
33+ expect(state.mode).toBe("plan");
34+ expect(modeService.getCurrentMode()).toBe("plan");
3535 });
3636
37- test('should convert auto flag to auto mode', async () => {
37+ test("should convert auto flag to auto mode", async () => {
3838 const state = await modeService.initialize({ auto: true });
39-
40- expect(state.mode).toBe('auto');
41- expect(modeService.getCurrentMode()).toBe('auto');
42- });
43-
44- test('should initialize tool permission service with flags', async () => {
45- const state = await modeService.initialize({
46- allow: ['testTool'],
47- exclude: ['badTool']
39+
40+ expect(state.mode).toBe("auto");
41+ expect(modeService.getCurrentMode()).toBe("auto");
42+ });
43+
44+ test("should initialize tool permission service with flags", async () => {
45+ const state = await modeService.initialize({
46+ allow: ["testTool"],
47+ exclude: ["badTool"],
4848 });
49-
49+
5050 const toolPermissionService = state.toolPermissionService;
5151 expect(toolPermissionService).toBeDefined();
5252 expect(toolPermissionService.getState()).toBeDefined();
53- expect(toolPermissionService.getCurrentMode()).toBe('normal');
53+ expect(toolPermissionService.getCurrentMode()).toBe("normal");
5454 });
5555 });
5656
57- describe('switchMode()', () => {
57+ describe("switchMode()", () => {
5858 beforeEach(async () => {
5959 await modeService.initialize({});
6060 });
6161
62- test('should switch from normal to plan mode', () => {
63- expect(modeService.getCurrentMode()).toBe('normal');
64-
65- modeService.switchMode('plan');
66-
67- expect(modeService.getCurrentMode()).toBe('plan');
68- expect(modeService.getState().mode).toBe('plan');
62+ test("should switch from normal to plan mode", () => {
63+ expect(modeService.getCurrentMode()).toBe("normal");
64+
65+ modeService.switchMode("plan");
66+
67+ expect(modeService.getCurrentMode()).toBe("plan");
68+ expect(modeService.getState().mode).toBe("plan");
6969 });
7070
71- test('should switch from plan to auto mode', () => {
72- modeService.switchMode('plan');
73- expect(modeService.getCurrentMode()).toBe('plan');
74-
75- modeService.switchMode('auto');
76-
77- expect(modeService.getCurrentMode()).toBe('auto');
78- expect(modeService.getState().mode).toBe('auto');
71+ test("should switch from plan to auto mode", () => {
72+ modeService.switchMode("plan");
73+ expect(modeService.getCurrentMode()).toBe("plan");
74+
75+ modeService.switchMode("auto");
76+
77+ expect(modeService.getCurrentMode()).toBe("auto");
78+ expect(modeService.getState().mode).toBe("auto");
7979 });
8080
81- test('should switch back to normal mode', () => {
82- modeService.switchMode('plan');
83- modeService.switchMode('normal');
84-
85- expect(modeService.getCurrentMode()).toBe('normal');
86- expect(modeService.getState().mode).toBe('normal');
81+ test("should switch back to normal mode", () => {
82+ modeService.switchMode("plan");
83+ modeService.switchMode("normal");
84+
85+ expect(modeService.getCurrentMode()).toBe("normal");
86+ expect(modeService.getState().mode).toBe("normal");
8787 });
8888
89- test('should update tool permission service when switching modes', () => {
89+ test("should update tool permission service when switching modes", () => {
9090 const toolPermissionService = modeService.getToolPermissionService();
9191 const initialState = toolPermissionService.getState();
92-
93- modeService.switchMode('auto');
92+
93+ modeService.switchMode("auto");
9494 const newState = toolPermissionService.getState();
95-
96- expect(newState.currentMode).toBe('auto');
95+
96+ expect(newState.currentMode).toBe("auto");
9797 expect(newState.permissions.policies.length).toBeGreaterThan(0);
9898 expect(newState.permissions.policies[0]).toEqual({
99- tool: '*',
100- permission: 'allow'
99+ tool: "*",
100+ permission: "allow",
101101 });
102102 });
103103
104- test('should handle multiple mode switches correctly', () => {
104+ test("should handle multiple mode switches correctly", () => {
105105 // Start in normal
106- expect(modeService.getCurrentMode()).toBe('normal');
107-
106+ expect(modeService.getCurrentMode()).toBe("normal");
107+
108108 // Switch to plan
109- modeService.switchMode('plan');
109+ modeService.switchMode("plan");
110110 const planState = modeService.getToolPermissionService().getState();
111111 expect(planState.permissions.policies).toContainEqual({
112- tool: 'Write',
113- permission: 'exclude'
112+ tool: "Write",
113+ permission: "exclude",
114114 });
115-
115+
116116 // Switch to auto
117- modeService.switchMode('auto');
117+ modeService.switchMode("auto");
118118 const autoState = modeService.getToolPermissionService().getState();
119119 expect(autoState.permissions.policies).toHaveLength(1);
120120 expect(autoState.permissions.policies[0]).toEqual({
121- tool: '*',
122- permission: 'allow'
121+ tool: "*",
122+ permission: "allow",
123123 });
124-
124+
125125 // Back to normal
126- modeService.switchMode('normal');
126+ modeService.switchMode("normal");
127127 const normalState = modeService.getToolPermissionService().getState();
128- expect(normalState.currentMode).toBe('normal');
128+ expect(normalState.currentMode).toBe("normal");
129129 });
130130 });
131131
132- describe('getAvailableModes()', () => {
132+ describe("getAvailableModes()", () => {
133133 beforeEach(async () => {
134134 await modeService.initialize({});
135135 });
136136
137- test('should return all available modes with descriptions', () => {
137+ test("should return all available modes with descriptions", () => {
138138 const modes = modeService.getAvailableModes();
139139 expect(modes).toHaveLength(3);
140-
141- const modeNames = modes.map(m => m.mode);
142- expect(modeNames).toContain('normal');
143- expect(modeNames).toContain('plan');
144- expect(modeNames).toContain('auto');
145-
140+
141+ const modeNames = modes.map((m) => m.mode);
142+ expect(modeNames).toContain("normal");
143+ expect(modeNames).toContain("plan");
144+ expect(modeNames).toContain("auto");
145+
146146 // Check that all modes have descriptions
147- modes.forEach(mode => {
147+ modes.forEach((mode) => {
148148 expect(mode.description).toBeDefined();
149149 expect(mode.description.length).toBeGreaterThan(0);
150150 });
151151 });
152152 });
153153
154- describe('Singleton Behavior', () => {
155- test('should return the same instance', () => {
154+ describe("Singleton Behavior", () => {
155+ test("should return the same instance", () => {
156156 const instance1 = ModeService.getInstance();
157157 const instance2 = ModeService.getInstance();
158158 expect(instance1).toBe(instance2);
159159 });
160160
161- test('should maintain state across getInstance calls', async () => {
161+ test("should maintain state across getInstance calls", async () => {
162162 const instance1 = ModeService.getInstance();
163163 await instance1.initialize({});
164- instance1.switchMode('plan');
165-
164+ instance1.switchMode("plan");
165+
166166 const instance2 = ModeService.getInstance();
167- expect(instance2.getCurrentMode()).toBe('plan');
167+ expect(instance2.getCurrentMode()).toBe("plan");
168168 });
169169 });
170170
171- describe('isReady()', () => {
172- test('should always return true for ModeService', () => {
171+ describe("isReady()", () => {
172+ test("should always return true for ModeService", () => {
173173 // ModeService is always ready since it's a singleton
174174 expect(modeService.isReady()).toBe(true);
175175 });
176176 });
177177
178- describe('Event Emission', () => {
178+ describe("Event Emission", () => {
179179 let modeChangeListener: ReturnType<typeof vi.fn>;
180180 let stateChangeListener: ReturnType<typeof vi.fn>;
181181
@@ -183,77 +183,77 @@
183183 await modeService.initialize({});
184184 modeChangeListener = vi.fn();
185185 stateChangeListener = vi.fn();
186- modeService.on('modeChanged', modeChangeListener);
187- modeService.on('stateChanged', stateChangeListener);
186+ modeService.on("modeChanged", modeChangeListener);
187+ modeService.on("stateChanged", stateChangeListener);
188188 });
189189
190190 afterEach(() => {
191- modeService.off('modeChanged', modeChangeListener);
192- modeService.off('stateChanged', stateChangeListener);
191+ modeService.off("modeChanged", modeChangeListener);
192+ modeService.off("stateChanged", stateChangeListener);
193193 });
194194
195- test('should emit modeChanged event when mode switches', () => {
196- modeService.switchMode('plan');
197-
198- expect(modeChangeListener).toHaveBeenCalledWith('plan', 'normal');
195+ test("should emit modeChanged event when mode switches", () => {
196+ modeService.switchMode("plan");
197+
198+ expect(modeChangeListener).toHaveBeenCalledWith("plan", "normal");
199199 expect(modeChangeListener).toHaveBeenCalledTimes(1);
200200 });
201201
202- test('should emit stateChanged event when mode switches', () => {
203- modeService.switchMode('plan');
204-
202+ test("should emit stateChanged event when mode switches", () => {
203+ modeService.switchMode("plan");
204+
205205 expect(stateChangeListener).toHaveBeenCalledWith(
206- expect.objectContaining({ mode: 'plan' }),
207- expect.objectContaining({ mode: 'normal' })
206+ expect.objectContaining({ mode: "plan" }),
207+ expect.objectContaining({ mode: "normal" }),
208208 );
209209 });
210210
211- test('should emit event with correct previous and new modes', () => {
212- modeService.switchMode('plan');
211+ test("should emit event with correct previous and new modes", () => {
212+ modeService.switchMode("plan");
213213 modeChangeListener.mockClear();
214214 stateChangeListener.mockClear();
215-
216- modeService.switchMode('auto');
217-
218- expect(modeChangeListener).toHaveBeenCalledWith('auto', 'plan');
215+
216+ modeService.switchMode("auto");
217+
218+ expect(modeChangeListener).toHaveBeenCalledWith("auto", "plan");
219219 expect(modeChangeListener).toHaveBeenCalledTimes(1);
220220 expect(stateChangeListener).toHaveBeenCalledTimes(1);
221221 });
222222
223- test('should not emit event when switching to same mode', () => {
224- modeService.switchMode('plan');
223+ test("should not emit event when switching to same mode", () => {
224+ modeService.switchMode("plan");
225225 modeChangeListener.mockClear();
226226 stateChangeListener.mockClear();
227-
228- modeService.switchMode('plan');
229-
227+
228+ modeService.switchMode("plan");
229+
230230 expect(modeChangeListener).not.toHaveBeenCalled();
231231 // stateChanged might still be called due to setState, but modeChanged should not
232232 });
233233 });
234234
235- describe('Integration with ToolPermissionService', () => {
235+ describe("Integration with ToolPermissionService", () => {
236236 beforeEach(async () => {
237237 await modeService.initialize({
238- allow: ['Read'],
239- exclude: ['dangerous_tool']
238+ allow: ["Read"],
239+ exclude: ["dangerous_tool"],
240240 });
241241 });
242242
243- test('should pass initialization args to ToolPermissionService', () => {
243+ test("should pass initialization args to ToolPermissionService", () => {
244244 const toolService = modeService.getToolPermissionService();
245245 const state = toolService.getState();
246-
246+
247247 // The state should have processed the allow/exclude rules
248248 expect(state.permissions.policies).toBeDefined();
249- expect(state.currentMode).toBe('normal');
249+ expect(state.currentMode).toBe("normal");
250250 });
251251
252- test('should maintain ToolPermissionService reference', () => {
252+ test("should maintain ToolPermissionService reference", () => {
253253 const toolService1 = modeService.getToolPermissionService();
254254 const toolService2 = modeService.getToolPermissionService();
255-
255+
256256 expect(toolService1).toBe(toolService2);
257257 });
258258 });
259-});
No newline at the end of the file
259+});
modified extensions/cli/src/services/ModelService.test.ts +207 −138
@@ -1,19 +1,19 @@
1-import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
2-import * as openaiAdapters from '@continuedev/openai-adapters';
3-import { describe, expect, beforeEach, vi, test } from 'vitest';
1+import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
2+import * as openaiAdapters from "@continuedev/openai-adapters";
3+import { describe, expect, beforeEach, vi, test } from "vitest";
44
55 // Mock dependencies before imports
6-vi.mock('@continuedev/openai-adapters');
7-vi.mock('../config.js');
8-vi.mock('../auth/workos.js');
6+vi.mock("@continuedev/openai-adapters");
7+vi.mock("../config.js");
8+vi.mock("../auth/workos.js");
99
10-import { AuthConfig } from '../auth/workos.js';
11-import * as workos from '../auth/workos.js';
12-import * as config from '../config.js';
10+import { AuthConfig } from "../auth/workos.js";
11+import * as workos from "../auth/workos.js";
12+import * as config from "../config.js";
1313
14-import { ModelService } from './ModelService.js';
14+import { ModelService } from "./ModelService.js";
1515
16-describe('ModelService', () => {
16+describe("ModelService", () => {
1717 let service: ModelService;
1818 let mockAssistant: AssistantUnrolled;
1919 let mockAuthConfig: AuthConfig;
@@ -24,69 +24,77 @@
2424 service = new ModelService();
2525
2626 mockAssistant = {
27- name: 'test-assistant',
28- version: '1.0.0',
27+ name: "test-assistant",
28+ version: "1.0.0",
2929 models: [
3030 {
31- provider: 'openai',
32- model: 'gpt-4',
33- name: 'GPT-4',
34- apiKey: 'test-key',
35- roles: ['chat'],
31+ provider: "openai",
32+ model: "gpt-4",
33+ name: "GPT-4",
34+ apiKey: "test-key",
35+ roles: ["chat"],
3636 } as ModelConfig,
3737 {
38- provider: 'anthropic',
39- model: 'claude-3',
40- name: 'Claude 3',
41- apiKey: 'test-key',
42- roles: ['chat'],
38+ provider: "anthropic",
39+ model: "claude-3",
40+ name: "Claude 3",
41+ apiKey: "test-key",
42+ roles: ["chat"],
4343 } as ModelConfig,
4444 {
45- provider: 'openai',
46- model: 'gpt-3.5',
47- name: 'GPT-3.5',
48- apiKey: 'test-key',
49- roles: ['embed'],
45+ provider: "openai",
46+ model: "gpt-3.5",
47+ name: "GPT-3.5",
48+ apiKey: "test-key",
49+ roles: ["embed"],
5050 } as ModelConfig,
5151 ],
5252 } as AssistantUnrolled;
5353
5454 mockAuthConfig = {
55- accessToken: 'test-token',
56- refreshToken: 'test-refresh',
57- userEmail: 'test@example.com',
58- userId: 'test-user',
59- organizationId: 'test-org',
55+ accessToken: "test-token",
56+ refreshToken: "test-refresh",
57+ userEmail: "test@example.com",
58+ userId: "test-user",
59+ organizationId: "test-org",
6060 expiresAt: Date.now() + 3600000, // 1 hour from now
6161 };
6262 });
6363
64- describe('State Management', () => {
65- test('should initialize with default model', async () => {
66- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
64+ describe("State Management", () => {
65+ test("should initialize with default model", async () => {
66+ vi.mocked(config.getLlmApi).mockReturnValue([
67+ mockLlmApi as any,
68+ mockAssistant.models![0] as ModelConfig,
69+ ]);
6770 vi.mocked(workos.getModelName).mockReturnValue(null);
6871
6972 const state = await service.initialize(mockAssistant, mockAuthConfig);
7073
7174 expect(state).toEqual({
7275 llmApi: mockLlmApi,
73- model: mockAssistant.models![0]
76+ model: mockAssistant.models![0],
7477 });
7578 });
7679
77- test('should initialize with persisted model if valid', async () => {
78- vi.mocked(workos.getModelName).mockReturnValue('Claude 3');
79- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
80+ test("should initialize with persisted model if valid", async () => {
81+ vi.mocked(workos.getModelName).mockReturnValue("Claude 3");
82+ vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
83+ mockLlmApi as any,
84+ );
8085
8186 const state = await service.initialize(mockAssistant, mockAuthConfig);
8287
83- expect(state.model?.name).toBe('Claude 3');
88+ expect(state.model?.name).toBe("Claude 3");
8489 expect(state.llmApi).toStrictEqual(mockLlmApi);
8590 });
8691
87- test('should fall back to default if persisted model not found', async () => {
88- vi.mocked(workos.getModelName).mockReturnValue('Non-existent Model');
89- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
92+ test("should fall back to default if persisted model not found", async () => {
93+ vi.mocked(workos.getModelName).mockReturnValue("Non-existent Model");
94+ vi.mocked(config.getLlmApi).mockReturnValue([
95+ mockLlmApi as any,
96+ mockAssistant.models![0] as ModelConfig,
97+ ]);
9098
9199 const state = await service.initialize(mockAssistant, mockAuthConfig);
92100
@@ -94,10 +102,13 @@
94102 });
95103 });
96104
97- describe('update()', () => {
98- test('should update model with new assistant config', async () => {
105+ describe("update()", () => {
106+ test("should update model with new assistant config", async () => {
99107 // Initialize first
100- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
108+ vi.mocked(config.getLlmApi).mockReturnValue([
109+ mockLlmApi as any,
110+ mockAssistant.models![0] as ModelConfig,
111+ ]);
101112 await service.initialize(mockAssistant, mockAuthConfig);
102113
103114 // Update with new assistant
@@ -105,124 +116,152 @@
105116 ...mockAssistant,
106117 models: [
107118 {
108- provider: 'openai',
109- model: 'gpt-4-turbo',
110- name: 'GPT-4 Turbo',
111- apiKey: 'new-key',
112- roles: ['chat'],
119+ provider: "openai",
120+ model: "gpt-4-turbo",
121+ name: "GPT-4 Turbo",
122+ apiKey: "new-key",
123+ roles: ["chat"],
113124 } as ModelConfig,
114125 ],
115126 };
116127 const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
117- vi.mocked(config.getLlmApi).mockReturnValue([newLlmApi as any, newAssistant.models![0] as ModelConfig]);
128+ vi.mocked(config.getLlmApi).mockReturnValue([
129+ newLlmApi as any,
130+ newAssistant.models![0] as ModelConfig,
131+ ]);
118132
119133 const state = await service.update(newAssistant, mockAuthConfig);
120134
121135 expect(state).toEqual({
122136 llmApi: newLlmApi,
123- model: newAssistant.models![0]
137+ model: newAssistant.models![0],
124138 });
125139 });
126140 });
127141
128- describe('switchModel()', () => {
129- test('should switch to a different model by index', async () => {
130- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
142+ describe("switchModel()", () => {
143+ test("should switch to a different model by index", async () => {
144+ vi.mocked(config.getLlmApi).mockReturnValue([
145+ mockLlmApi as any,
146+ mockAssistant.models![0] as ModelConfig,
147+ ]);
131148 await service.initialize(mockAssistant, mockAuthConfig);
132149
133150 const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
134- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(newLlmApi as any);
151+ vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
152+ newLlmApi as any,
153+ );
135154
136155 const state = await service.switchModel(1);
137156
138157 expect(state).toEqual({
139158 llmApi: newLlmApi,
140- model: mockAssistant.models![1]
159+ model: mockAssistant.models![1],
141160 });
142161 expect(service.getState()).toEqual(state);
143162 });
144163
145- test('should throw error for invalid model index', async () => {
146- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
164+ test("should throw error for invalid model index", async () => {
165+ vi.mocked(config.getLlmApi).mockReturnValue([
166+ mockLlmApi as any,
167+ mockAssistant.models![0] as ModelConfig,
168+ ]);
147169 await service.initialize(mockAssistant, mockAuthConfig);
148170
149- await expect(service.switchModel(5)).rejects.toThrow('Invalid model index: 5. Available models: 0-1');
150- await expect(service.switchModel(-1)).rejects.toThrow('Invalid model index: -1. Available models: 0-1');
171+ await expect(service.switchModel(5)).rejects.toThrow(
172+ "Invalid model index: 5. Available models: 0-1",
173+ );
174+ await expect(service.switchModel(-1)).rejects.toThrow(
175+ "Invalid model index: -1. Available models: 0-1",
176+ );
151177 });
152178
153- test('should throw error when service not initialized', async () => {
154- await expect(service.switchModel(0)).rejects.toThrow('ModelService not initialized');
179+ test("should throw error when service not initialized", async () => {
180+ await expect(service.switchModel(0)).rejects.toThrow(
181+ "ModelService not initialized",
182+ );
155183 });
156184
157- test('should handle continue-proxy provider specially', async () => {
185+ test("should handle continue-proxy provider specially", async () => {
158186 const proxyModel = {
159- provider: 'continue-proxy',
160- name: 'Proxy Model',
161- apiBase: 'https://proxy.continue.dev',
162- apiKeyLocation: 'env.PROXY_KEY',
163- roles: ['chat'],
187+ provider: "continue-proxy",
188+ name: "Proxy Model",
189+ apiBase: "https://proxy.continue.dev",
190+ apiKeyLocation: "env.PROXY_KEY",
191+ roles: ["chat"],
164192 } as ModelConfig;
165193
166194 mockAssistant.models = [proxyModel];
167- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, proxyModel]);
195+ vi.mocked(config.getLlmApi).mockReturnValue([
196+ mockLlmApi as any,
197+ proxyModel,
198+ ]);
168199 await service.initialize(mockAssistant, mockAuthConfig);
169200
170- vi.mocked(workos.getAccessToken).mockReturnValue('proxy-token');
171- vi.mocked(workos.getOrganizationId).mockReturnValue('org-123');
172- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
201+ vi.mocked(workos.getAccessToken).mockReturnValue("proxy-token");
202+ vi.mocked(workos.getOrganizationId).mockReturnValue("org-123");
203+ vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
204+ mockLlmApi as any,
205+ );
173206
174207 await service.switchModel(0);
175208
176209 expect(vi.mocked(openaiAdapters.constructLlmApi)).toHaveBeenCalledWith({
177- provider: 'continue-proxy',
178- apiBase: 'https://proxy.continue.dev',
179- apiKey: 'proxy-token',
210+ provider: "continue-proxy",
211+ apiBase: "https://proxy.continue.dev",
212+ apiKey: "proxy-token",
180213 env: {
181- apiKeyLocation: 'env.PROXY_KEY',
182- orgScopeId: 'org-123',
214+ apiKeyLocation: "env.PROXY_KEY",
215+ orgScopeId: "org-123",
183216 proxyUrl: undefined,
184217 },
185218 });
186219 });
187220 });
188221
189- describe('getAvailableChatModels()', () => {
190- test('should return only models with chat role', async () => {
191- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
222+ describe("getAvailableChatModels()", () => {
223+ test("should return only models with chat role", async () => {
224+ vi.mocked(config.getLlmApi).mockReturnValue([
225+ mockLlmApi as any,
226+ mockAssistant.models![0] as ModelConfig,
227+ ]);
192228 await service.initialize(mockAssistant, mockAuthConfig);
193229
194230 const models = service.getAvailableChatModels();
195231
196232 expect(models).toHaveLength(2);
197233 expect(models[0]).toEqual({
198- provider: 'openai',
199- name: 'GPT-4',
234+ provider: "openai",
235+ name: "GPT-4",
200236 index: 0,
201237 });
202238 expect(models[1]).toEqual({
203- provider: 'anthropic',
204- name: 'Claude 3',
239+ provider: "anthropic",
240+ name: "Claude 3",
205241 index: 1,
206242 });
207243 });
208244
209- test('should include models with undefined roles', async () => {
245+ test("should include models with undefined roles", async () => {
210246 // Add a model with undefined roles to the assistant
211247 const assistantWithUndefinedRoles = {
212248 ...mockAssistant,
213249 models: [
214250 ...mockAssistant.models!,
215251 {
216- provider: 'local',
217- model: 'llama-2',
218- name: 'Llama 2',
219- apiKey: 'test-key',
252+ provider: "local",
253+ model: "llama-2",
254+ name: "Llama 2",
255+ apiKey: "test-key",
220256 // roles is undefined
221257 } as ModelConfig,
222258 ],
223259 };
224260
225- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, assistantWithUndefinedRoles.models![0] as ModelConfig]);
261+ vi.mocked(config.getLlmApi).mockReturnValue([
262+ mockLlmApi as any,
263+ assistantWithUndefinedRoles.models![0] as ModelConfig,
264+ ]);
226265 await service.initialize(assistantWithUndefinedRoles, mockAuthConfig);
227266
228267 const models = service.getAvailableChatModels();
@@ -230,126 +269,156 @@
230269 // Should include the two chat models and the model with undefined roles
231270 expect(models).toHaveLength(3);
232271 expect(models[2]).toEqual({
233- provider: 'local',
234- name: 'Llama 2',
272+ provider: "local",
273+ name: "Llama 2",
235274 index: 2,
236275 });
237276 });
238277 });
239278
240- describe('getCurrentModelIndex()', () => {
241- test('should return correct index of current model', async () => {
242- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
279+ describe("getCurrentModelIndex()", () => {
280+ test("should return correct index of current model", async () => {
281+ vi.mocked(config.getLlmApi).mockReturnValue([
282+ mockLlmApi as any,
283+ mockAssistant.models![0] as ModelConfig,
284+ ]);
243285 await service.initialize(mockAssistant, mockAuthConfig);
244286
245287 expect(service.getCurrentModelIndex()).toBe(0);
246288
247- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
289+ vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
290+ mockLlmApi as any,
291+ );
248292 await service.switchModel(1);
249293 expect(service.getCurrentModelIndex()).toBe(1);
250294 });
251295
252- test('should return -1 when no model is set', () => {
296+ test("should return -1 when no model is set", () => {
253297 expect(service.getCurrentModelIndex()).toBe(-1);
254298 });
255299 });
256300
257- describe('getModelIndexByName()', () => {
258- test('should find model by name', async () => {
259- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
301+ describe("getModelIndexByName()", () => {
302+ test("should find model by name", async () => {
303+ vi.mocked(config.getLlmApi).mockReturnValue([
304+ mockLlmApi as any,
305+ mockAssistant.models![0] as ModelConfig,
306+ ]);
260307 await service.initialize(mockAssistant, mockAuthConfig);
261308
262- expect(service.getModelIndexByName('GPT-4')).toBe(0);
263- expect(service.getModelIndexByName('Claude 3')).toBe(1);
264- expect(service.getModelIndexByName('Non-existent')).toBe(-1);
309+ expect(service.getModelIndexByName("GPT-4")).toBe(0);
310+ expect(service.getModelIndexByName("Claude 3")).toBe(1);
311+ expect(service.getModelIndexByName("Non-existent")).toBe(-1);
265312 });
266313
267- test('should find model by name and provider', async () => {
268- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
314+ test("should find model by name and provider", async () => {
315+ vi.mocked(config.getLlmApi).mockReturnValue([
316+ mockLlmApi as any,
317+ mockAssistant.models![0] as ModelConfig,
318+ ]);
269319 await service.initialize(mockAssistant, mockAuthConfig);
270320
271- expect(service.getModelIndexByName('GPT-4', 'openai')).toBe(0);
272- expect(service.getModelIndexByName('GPT-4', 'anthropic')).toBe(-1);
321+ expect(service.getModelIndexByName("GPT-4", "openai")).toBe(0);
322+ expect(service.getModelIndexByName("GPT-4", "anthropic")).toBe(-1);
273323 });
274324 });
275325
276- describe('getModelInfo()', () => {
277- test('should return current model info', async () => {
278- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
326+ describe("getModelInfo()", () => {
327+ test("should return current model info", async () => {
328+ vi.mocked(config.getLlmApi).mockReturnValue([
329+ mockLlmApi as any,
330+ mockAssistant.models![0] as ModelConfig,
331+ ]);
279332 await service.initialize(mockAssistant, mockAuthConfig);
280333
281334 expect(service.getModelInfo()).toEqual({
282- provider: 'openai',
283- name: 'GPT-4'
335+ provider: "openai",
336+ name: "GPT-4",
284337 });
285338 });
286339
287- test('should return null when no model set', () => {
340+ test("should return null when no model set", () => {
288341 expect(service.getModelInfo()).toBeNull();
289342 });
290343 });
291344
292- describe('isReady()', () => {
293- test('should return false when not initialized', () => {
345+ describe("isReady()", () => {
346+ test("should return false when not initialized", () => {
294347 expect(service.isReady()).toBe(false);
295348 });
296349
297- test('should return true when initialized with model and llmApi', async () => {
298- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
350+ test("should return true when initialized with model and llmApi", async () => {
351+ vi.mocked(config.getLlmApi).mockReturnValue([
352+ mockLlmApi as any,
353+ mockAssistant.models![0] as ModelConfig,
354+ ]);
299355 await service.initialize(mockAssistant, mockAuthConfig);
300356
301357 expect(service.isReady()).toBe(true);
302358 });
303359
304- test('should return false if llmApi is null', async () => {
305- vi.mocked(config.getLlmApi).mockReturnValue([null as any, mockAssistant.models![0] as ModelConfig]);
360+ test("should return false if llmApi is null", async () => {
361+ vi.mocked(config.getLlmApi).mockReturnValue([
362+ null as any,
363+ mockAssistant.models![0] as ModelConfig,
364+ ]);
306365 await service.initialize(mockAssistant, mockAuthConfig);
307366
308367 expect(service.isReady()).toBe(false);
309368 });
310369 });
311370
312- describe('getDependencies()', () => {
313- test('should declare auth and config dependencies', () => {
314- expect(service.getDependencies()).toEqual(['auth', 'config']);
371+ describe("getDependencies()", () => {
372+ test("should declare auth and config dependencies", () => {
373+ expect(service.getDependencies()).toEqual(["auth", "config"]);
315374 });
316375 });
317376
318- describe('Event Emission', () => {
319- test('should emit stateChanged on model switch', async () => {
320- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
377+ describe("Event Emission", () => {
378+ test("should emit stateChanged on model switch", async () => {
379+ vi.mocked(config.getLlmApi).mockReturnValue([
380+ mockLlmApi as any,
381+ mockAssistant.models![0] as ModelConfig,
382+ ]);
321383 await service.initialize(mockAssistant, mockAuthConfig);
322384
323385 const listener = vi.fn();
324- service.on('stateChanged', listener);
386+ service.on("stateChanged", listener);
325387
326388 const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
327- vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(newLlmApi as any);
389+ vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
390+ newLlmApi as any,
391+ );
328392 await service.switchModel(1);
329393
330394 expect(listener).toHaveBeenCalledWith(
331395 expect.objectContaining({
332396 model: mockAssistant.models![1],
333- llmApi: newLlmApi
397+ llmApi: newLlmApi,
334398 }),
335399 expect.objectContaining({
336400 model: mockAssistant.models![0],
337- llmApi: mockLlmApi
338- })
401+ llmApi: mockLlmApi,
402+ }),
339403 );
340404 });
341405
342- test('should emit error on switch failure', async () => {
343- vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
406+ test("should emit error on switch failure", async () => {
407+ vi.mocked(config.getLlmApi).mockReturnValue([
408+ mockLlmApi as any,
409+ mockAssistant.models![0] as ModelConfig,
410+ ]);
344411 await service.initialize(mockAssistant, mockAuthConfig);
345412
346413 const errorListener = vi.fn();
347- service.on('error', errorListener);
414+ service.on("error", errorListener);
348415
349416 vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any);
350417
351- await expect(service.switchModel(1)).rejects.toThrow('Failed to initialize LLM');
418+ await expect(service.switchModel(1)).rejects.toThrow(
419+ "Failed to initialize LLM",
420+ );
352421 expect(errorListener).toHaveBeenCalledWith(expect.any(Error));
353422 });
354423 });
355-});
No newline at the end of the file
424+});
modified extensions/cli/src/services/ServiceContainer.test.ts +83 −67
@@ -1,8 +1,8 @@
1-import { describe, expect, test, beforeEach, vi } from 'vitest';
1+import { describe, expect, test, beforeEach, vi } from "vitest";
22
3-import { ServiceContainer } from './ServiceContainer.js';
3+import { ServiceContainer } from "./ServiceContainer.js";
44
5-describe('ServiceContainer', () => {
5+describe("ServiceContainer", () => {
66 let container: ServiceContainer;
77
88 beforeEach(() => {
@@ -10,13 +10,13 @@
1010 vi.clearAllMocks();
1111 });
1212
13- describe('Dependency Cascade Reloading', () => {
14- test('should automatically reload all transitive dependents', async () => {
13+ describe("Dependency Cascade Reloading", () => {
14+ test("should automatically reload all transitive dependents", async () => {
1515 // Setup service dependency chain: auth -> apiClient -> config -> model
16- const authValue = { auth: 'auth-value' };
17- const apiClientValue = { apiClient: 'api-client-value' };
18- const configValue = { config: 'config-value' };
19- const modelValue = { model: 'model-value' };
16+ const authValue = { auth: "auth-value" };
17+ const apiClientValue = { apiClient: "api-client-value" };
18+ const configValue = { config: "config-value" };
19+ const modelValue = { model: "model-value" };
2020
2121 let authReloadCount = 0;
2222 let apiClientReloadCount = 0;
@@ -25,43 +25,43 @@
2525
2626 // Register services with mock factories that track reload count
2727 container.register(
28- 'auth',
28+ "auth",
2929 async () => {
3030 authReloadCount++;
3131 return authValue;
3232 },
33- []
33+ [],
3434 );
3535
3636 container.register(
37- 'apiClient',
37+ "apiClient",
3838 async () => {
3939 apiClientReloadCount++;
4040 return apiClientValue;
4141 },
42- ['auth']
42+ ["auth"],
4343 );
4444
4545 container.register(
46- 'config',
46+ "config",
4747 async () => {
4848 configReloadCount++;
4949 return configValue;
5050 },
51- ['auth', 'apiClient']
51+ ["auth", "apiClient"],
5252 );
5353
5454 container.register(
55- 'model',
55+ "model",
5656 async () => {
5757 modelReloadCount++;
5858 return modelValue;
5959 },
60- ['config']
60+ ["config"],
6161 );
6262
6363 // Initial load of all services
64- await container.get('model');
64+ await container.get("model");
6565
6666 // Verify initial load counts
6767 expect(authReloadCount).toBe(1);
@@ -70,95 +70,111 @@
7070 expect(modelReloadCount).toBe(1);
7171
7272 // Reload auth service - should cascade to all dependents
73- await container.reload('auth');
73+ await container.reload("auth");
7474
7575 // Verify cascade reload occurred - all dependent services should reload
7676 expect(authReloadCount).toBe(2); // auth reloaded
7777 expect(apiClientReloadCount).toBe(2); // apiClient depends on auth
78- expect(configReloadCount).toBe(2); // config depends on auth and apiClient
78+ expect(configReloadCount).toBe(2); // config depends on auth and apiClient
7979 expect(modelReloadCount).toBe(2); // model depends on config
8080 });
8181
82- test('should find all transitive dependents correctly', async () => {
82+ test("should find all transitive dependents correctly", async () => {
8383 // Setup complex dependency graph
84- container.register('serviceA', async () => ({}), []);
85- container.register('serviceB', async () => ({}), ['serviceA']);
86- container.register('serviceC', async () => ({}), ['serviceA']);
87- container.register('serviceD', async () => ({}), ['serviceB', 'serviceC']);
88- container.register('serviceE', async () => ({}), ['serviceD']);
84+ container.register("serviceA", async () => ({}), []);
85+ container.register("serviceB", async () => ({}), ["serviceA"]);
86+ container.register("serviceC", async () => ({}), ["serviceA"]);
87+ container.register("serviceD", async () => ({}), [
88+ "serviceB",
89+ "serviceC",
90+ ]);
91+ container.register("serviceE", async () => ({}), ["serviceD"]);
8992
9093 // Use reflection to access private method for testing
91- const findAllDependents = (container as any).findAllDependents.bind(container);
92-
93- const dependentsOfA = findAllDependents('serviceA');
94-
94+ const findAllDependents = (container as any).findAllDependents.bind(
95+ container,
96+ );
97+
98+ const dependentsOfA = findAllDependents("serviceA");
99+
95100 // serviceA should have all others as transitive dependents
96- expect(dependentsOfA.sort()).toEqual(['serviceB', 'serviceC', 'serviceD', 'serviceE']);
101+ expect(dependentsOfA.sort()).toEqual([
102+ "serviceB",
103+ "serviceC",
104+ "serviceD",
105+ "serviceE",
106+ ]);
97107 });
98108
99- test('should handle circular dependencies gracefully', async () => {
109+ test("should handle circular dependencies gracefully", async () => {
100110 // This test ensures the findAllDependents doesn't get stuck in infinite loops
101-
111+
102112 // Setup a circular dependency (which shouldn't happen in practice but we handle it)
103- container.register('serviceX', async () => ({}), ['serviceY']);
104- container.register('serviceY', async () => ({}), ['serviceX']);
105-
113+ container.register("serviceX", async () => ({}), ["serviceY"]);
114+ container.register("serviceY", async () => ({}), ["serviceX"]);
115+
106116 // Use reflection to access private method for testing
107- const findAllDependents = (container as any).findAllDependents.bind(container);
108-
117+ const findAllDependents = (container as any).findAllDependents.bind(
118+ container,
119+ );
120+
109121 // Should not hang and should return both services as circular dependents
110- const dependentsOfX = findAllDependents('serviceX');
111- const dependentsOfY = findAllDependents('serviceY');
112-
122+ const dependentsOfX = findAllDependents("serviceX");
123+ const dependentsOfY = findAllDependents("serviceY");
124+
113125 // Both should contain each other due to circular dependency
114- expect(dependentsOfX).toContain('serviceY');
115- expect(dependentsOfY).toContain('serviceX');
126+ expect(dependentsOfX).toContain("serviceY");
127+ expect(dependentsOfY).toContain("serviceX");
116128 });
117129
118- test('should emit events during cascade reload', async () => {
130+ test("should emit events during cascade reload", async () => {
119131 const events: string[] = [];
120-
121- container.register('parent', async () => ({ parent: true }), []);
122- container.register('child', async () => ({ child: true }), ['parent']);
132+
133+ container.register("parent", async () => ({ parent: true }), []);
134+ container.register("child", async () => ({ child: true }), ["parent"]);
123135
124136 // Listen for events
125- container.on('parent:loading', () => events.push('parent:loading'));
126- container.on('parent:ready', () => events.push('parent:ready'));
127- container.on('child:loading', () => events.push('child:loading'));
128- container.on('child:ready', () => events.push('child:ready'));
137+ container.on("parent:loading", () => events.push("parent:loading"));
138+ container.on("parent:ready", () => events.push("parent:ready"));
139+ container.on("child:loading", () => events.push("child:loading"));
140+ container.on("child:ready", () => events.push("child:ready"));
129141
130142 // Initial load
131- await container.get('child');
143+ await container.get("child");
132144 events.length = 0; // Clear events
133145
134146 // Reload parent - should cascade to child
135- await container.reload('parent');
147+ await container.reload("parent");
136148
137149 // Verify both services went through loading cycle
138- expect(events).toContain('parent:loading');
139- expect(events).toContain('parent:ready');
140- expect(events).toContain('child:loading');
141- expect(events).toContain('child:ready');
150+ expect(events).toContain("parent:loading");
151+ expect(events).toContain("parent:ready");
152+ expect(events).toContain("child:loading");
153+ expect(events).toContain("child:ready");
142154 });
143155
144- test('should preserve service state when no dependents exist', async () => {
156+ test("should preserve service state when no dependents exist", async () => {
145157 let reloadCount = 0;
146-
147- container.register('standalone', async () => {
148- reloadCount++;
149- return { standalone: true };
150- }, []);
158+
159+ container.register(
160+ "standalone",
161+ async () => {
162+ reloadCount++;
163+ return { standalone: true };
164+ },
165+ [],
166+ );
151167
152168 // Load initially
153- await container.get('standalone');
169+ await container.get("standalone");
154170 expect(reloadCount).toBe(1);
155171
156172 // Reload - only this service should reload
157- await container.reload('standalone');
173+ await container.reload("standalone");
158174 expect(reloadCount).toBe(2);
159175
160176 // Should still be ready
161- expect(container.isReady('standalone')).toBe(true);
177+ expect(container.isReady("standalone")).toBe(true);
162178 });
163179 });
164-});
No newline at the end of the file
180+});
modified extensions/cli/src/services/ToolPermissionService.debug.test.ts +6 −8
@@ -40,9 +40,7 @@
4040 } else {
4141 // Normal mode behavior depends on user config
4242 console.log(
43- `Normal mode - Write policy: ${
44- writePolicy?.permission || "none"
45- }`
43+ `Normal mode - Write policy: ${writePolicy?.permission || "none"}`,
4644 );
4745 }
4846 });
@@ -52,17 +50,17 @@
5250
5351 // Find all policies that could affect Write tool
5452 const writeRelevantPolicies = policies.filter(
55- (p) => p.tool === "Write" || p.tool === "*"
53+ (p) => p.tool === "Write" || p.tool === "*",
5654 );
5755
5856 console.log(
59- `\n=== WRITE-RELEVANT POLICIES IN ${mode.toUpperCase()} MODE ===`
57+ `\n=== WRITE-RELEVANT POLICIES IN ${mode.toUpperCase()} MODE ===`,
6058 );
6159 writeRelevantPolicies.forEach((policy, index) => {
6260 console.log(
6361 `${index + 1}. tool: "${policy.tool}", permission: "${
6462 policy.permission
65- }"`
63+ }"`,
6664 );
6765 });
6866
@@ -94,7 +92,7 @@
9492 console.log(
9593 `${index + 1}. tool: "${policy.tool}", permission: "${
9694 policy.permission
97- }"`
95+ }"`,
9896 );
9997 });
10098
@@ -107,7 +105,7 @@
107105 console.log(
108106 `${index + 1}. tool: "${policy.tool}", permission: "${
109107 policy.permission
110- }"`
108+ }"`,
111109 );
112110 });
113111
modified extensions/cli/src/services/ToolPermissionService.integration.test.ts +42 −27
@@ -14,30 +14,40 @@
1414 const overrides = {
1515 allow: ["dangerous_tool"],
1616 ask: ["sensitive_tool"],
17- exclude: ["forbidden_tool", "write_*"]
17+ exclude: ["forbidden_tool", "write_*"],
1818 };
1919
2020 const state = await service.initialize(overrides);
2121
2222 // Verify the compiled policies
2323 const policies = state.permissions.policies;
24-
24+
2525 // Find the runtime override policies (they should be at the beginning)
26- const excludePolicy1 = policies.find(p => p.tool === "forbidden_tool" && p.permission === "exclude");
27- const excludePolicy2 = policies.find(p => p.tool === "write_*" && p.permission === "exclude");
28- const askPolicy = policies.find(p => p.tool === "sensitive_tool" && p.permission === "ask");
29- const allowPolicy = policies.find(p => p.tool === "dangerous_tool" && p.permission === "allow");
30-
26+ const excludePolicy1 = policies.find(
27+ (p) => p.tool === "forbidden_tool" && p.permission === "exclude",
28+ );
29+ const excludePolicy2 = policies.find(
30+ (p) => p.tool === "write_*" && p.permission === "exclude",
31+ );
32+ const askPolicy = policies.find(
33+ (p) => p.tool === "sensitive_tool" && p.permission === "ask",
34+ );
35+ const allowPolicy = policies.find(
36+ (p) => p.tool === "dangerous_tool" && p.permission === "allow",
37+ );
38+
3139 // Verify runtime overrides are present
3240 expect(excludePolicy1).toBeDefined();
3341 expect(excludePolicy2).toBeDefined();
3442 expect(askPolicy).toBeDefined();
3543 expect(allowPolicy).toBeDefined();
36-
44+
3745 // Verify all default policies are present
3846 for (const defaultPolicy of DEFAULT_TOOL_POLICIES) {
39- const foundPolicy = policies.find(p =>
40- p.tool === defaultPolicy.tool && p.permission === defaultPolicy.permission
47+ const foundPolicy = policies.find(
48+ (p) =>
49+ p.tool === defaultPolicy.tool &&
50+ p.permission === defaultPolicy.permission,
4151 );
4252 expect(foundPolicy).toBeDefined();
4353 }
@@ -46,24 +56,26 @@
4656 it("should allow dynamic updates after initialization", async () => {
4757 // Start with defaults (may include additional policies from permissions.yaml)
4858 await service.initialize();
49-
59+
5060 let permissions = service.getPermissions();
51-
61+
5262 // Verify all default policies are present (may have additional ones)
5363 for (const defaultPolicy of DEFAULT_TOOL_POLICIES) {
54- const foundPolicy = permissions.policies.find(p =>
55- p.tool === defaultPolicy.tool && p.permission === defaultPolicy.permission
64+ const foundPolicy = permissions.policies.find(
65+ (p) =>
66+ p.tool === defaultPolicy.tool &&
67+ p.permission === defaultPolicy.permission,
5668 );
5769 expect(foundPolicy).toBeDefined();
5870 }
5971
6072 // Update with new policies (this replaces ALL policies)
6173 const newPolicies = [
62- { tool: "*", permission: "ask" as const } // Ask for everything
74+ { tool: "*", permission: "ask" as const }, // Ask for everything
6375 ];
64-
76+
6577 service.updatePermissions(newPolicies);
66-
78+
6779 permissions = service.getPermissions();
6880 expect(permissions.policies).toEqual(newPolicies);
6981 expect(permissions.policies.length).toBe(1);
@@ -71,19 +83,22 @@
7183
7284 it("should maintain state consistency", async () => {
7385 const overrides = {
74- exclude: ["test_tool"]
86+ exclude: ["test_tool"],
7587 };
7688
7789 await service.initialize(overrides);
78-
90+
7991 // Both getState and getPermissions should return same data
8092 const state = service.getState();
8193 const permissions = service.getPermissions();
82-
94+
8395 // getState() returns a shallow copy, so nested objects are the same reference
8496 expect(state.permissions).toEqual(permissions);
8597 expect(state.permissions).toBe(permissions); // Same reference for nested objects
86- expect(state.permissions.policies[0]).toEqual({ tool: "test_tool", permission: "exclude" });
98+ expect(state.permissions.policies[0]).toEqual({
99+ tool: "test_tool",
100+ permission: "exclude",
101+ });
87102 });
88103
89104 it("should handle concurrent access correctly", async () => {
@@ -91,16 +106,16 @@
91106 await service.initialize({ allow: ["tool1"] });
92107
93108 // Simulate concurrent reads
94- const promises = Array(10).fill(null).map(() =>
95- Promise.resolve(service.getPermissions())
96- );
109+ const promises = Array(10)
110+ .fill(null)
111+ .map(() => Promise.resolve(service.getPermissions()));
97112
98113 const results = await Promise.all(promises);
99-
114+
100115 // All should return the same value
101116 const firstResult = results[0];
102- results.forEach(result => {
117+ results.forEach((result) => {
103118 expect(result).toStrictEqual(firstResult);
104119 });
105120 });
106-});
No newline at the end of the file
121+});
modified extensions/cli/src/services/ToolPermissionService.modes.test.ts +201 −146
@@ -1,261 +1,316 @@
1-import { beforeEach, describe, expect, it } from 'vitest';
1+import { beforeEach, describe, expect, it } from "vitest";
22
3-import { ToolPermissionService } from './ToolPermissionService.js';
3+import { ToolPermissionService } from "./ToolPermissionService.js";
44
5-describe('ToolPermissionService - Mode Functionality', () => {
5+describe("ToolPermissionService - Mode Functionality", () => {
66 let service: ToolPermissionService;
77
88 beforeEach(() => {
99 service = new ToolPermissionService();
1010 });
1111
12- describe('mode initialization', () => {
13- it('should initialize with normal mode by default', () => {
12+ describe("mode initialization", () => {
13+ it("should initialize with normal mode by default", () => {
1414 const state = service.initializeSync();
15- expect(state.currentMode).toBe('normal');
15+ expect(state.currentMode).toBe("normal");
1616 });
1717
18- it('should initialize with specified mode', () => {
19- const state = service.initializeSync({ mode: 'plan' });
20- expect(state.currentMode).toBe('plan');
18+ it("should initialize with specified mode", () => {
19+ const state = service.initializeSync({ mode: "plan" });
20+ expect(state.currentMode).toBe("plan");
2121 });
2222
23- it('should generate correct policies for plan mode', () => {
24- const state = service.initializeSync({ mode: 'plan' });
23+ it("should generate correct policies for plan mode", () => {
24+ const state = service.initializeSync({ mode: "plan" });
2525 const policies = state.permissions.policies;
26-
26+
2727 // Should have specific policies for write tools (excluded)
28- expect(policies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
29- expect(policies.some(p => p.tool === 'Edit' && p.permission === 'exclude')).toBe(true);
30- expect(policies.some(p => p.tool === 'Bash' && p.permission === 'allow')).toBe(true);
31-
28+ expect(
29+ policies.some((p) => p.tool === "Write" && p.permission === "exclude"),
30+ ).toBe(true);
31+ expect(
32+ policies.some((p) => p.tool === "Edit" && p.permission === "exclude"),
33+ ).toBe(true);
34+ expect(
35+ policies.some((p) => p.tool === "Bash" && p.permission === "allow"),
36+ ).toBe(true);
37+
3238 // Should have specific policies for read tools (allowed)
33- expect(policies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true);
34- expect(policies.some(p => p.tool === 'Grep' && p.permission === 'allow')).toBe(true);
35- expect(policies.some(p => p.tool === 'LS' && p.permission === 'allow')).toBe(true);
36-
39+ expect(
40+ policies.some((p) => p.tool === "Read" && p.permission === "allow"),
41+ ).toBe(true);
42+ expect(
43+ policies.some((p) => p.tool === "Grep" && p.permission === "allow"),
44+ ).toBe(true);
45+ expect(
46+ policies.some((p) => p.tool === "LS" && p.permission === "allow"),
47+ ).toBe(true);
48+
3749 // Should allow MCP tools
38- expect(policies.some(p => p.tool === 'mcp:*' && p.permission === 'allow')).toBe(true);
39-
50+ expect(
51+ policies.some((p) => p.tool === "mcp:*" && p.permission === "allow"),
52+ ).toBe(true);
53+
4054 // Should have an exclusion policy for all other tools as fallback
41- expect(policies.some(p => p.tool === '*' && p.permission === 'exclude')).toBe(true);
55+ expect(
56+ policies.some((p) => p.tool === "*" && p.permission === "exclude"),
57+ ).toBe(true);
4258 });
4359
44-
45- it('should generate correct policies for auto mode', () => {
46- const state = service.initializeSync({ mode: 'auto' });
60+ it("should generate correct policies for auto mode", () => {
61+ const state = service.initializeSync({ mode: "auto" });
4762 const policies = state.permissions.policies;
48-
63+
4964 // First policy should be the mode policy (allow all)
5065 expect(policies[0]).toEqual({
51- tool: '*',
52- permission: 'allow'
66+ tool: "*",
67+ permission: "allow",
5368 });
5469 });
5570
56- it('should have mode-specific policy positioning', () => {
57- const normalState = service.initializeSync({ mode: 'normal' });
58- const planState = service.initializeSync({ mode: 'plan' });
59-
71+ it("should have mode-specific policy positioning", () => {
72+ const normalState = service.initializeSync({ mode: "normal" });
73+ const planState = service.initializeSync({ mode: "plan" });
74+
6075 // Normal mode may have default policies but no mode-specific wildcard at the start
6176 const normalFirstPolicy = normalState.permissions.policies[0];
62- expect(normalFirstPolicy?.tool !== '*' || normalFirstPolicy?.permission !== 'exclude').toBe(true);
63-
77+ expect(
78+ normalFirstPolicy?.tool !== "*" ||
79+ normalFirstPolicy?.permission !== "exclude",
80+ ).toBe(true);
81+
6482 // Plan mode should have write exclusions and read allowances
6583 const planPolicies = planState.permissions.policies;
66- expect(planPolicies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
67- expect(planPolicies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true);
84+ expect(
85+ planPolicies.some(
86+ (p) => p.tool === "Write" && p.permission === "exclude",
87+ ),
88+ ).toBe(true);
89+ expect(
90+ planPolicies.some((p) => p.tool === "Read" && p.permission === "allow"),
91+ ).toBe(true);
6892 });
6993 });
7094
71- describe('mode switching', () => {
95+ describe("mode switching", () => {
7296 beforeEach(() => {
7397 service.initializeSync();
7498 });
7599
76- it('should switch from normal to plan mode', () => {
77- expect(service.getCurrentMode()).toBe('normal');
78-
79- const newState = service.switchMode('plan');
80-
81- expect(newState.currentMode).toBe('plan');
82- expect(service.getCurrentMode()).toBe('plan');
100+ it("should switch from normal to plan mode", () => {
101+ expect(service.getCurrentMode()).toBe("normal");
102+
103+ const newState = service.switchMode("plan");
104+
105+ expect(newState.currentMode).toBe("plan");
106+ expect(service.getCurrentMode()).toBe("plan");
83107 });
84108
85- it('should update policies when switching modes', () => {
86- service.initializeSync({ mode: 'normal' });
109+ it("should update policies when switching modes", () => {
110+ service.initializeSync({ mode: "normal" });
87111 const normalPolicies = service.getPermissions().policies;
88-
89- service.switchMode('plan');
112+
113+ service.switchMode("plan");
90114 const planPolicies = service.getPermissions().policies;
91-
115+
92116 expect(planPolicies).not.toEqual(normalPolicies);
93- expect(planPolicies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
117+ expect(
118+ planPolicies.some(
119+ (p) => p.tool === "Write" && p.permission === "exclude",
120+ ),
121+ ).toBe(true);
94122 });
95123
96- it('should use absolute override for plan mode (ignore non-mode policies)', () => {
124+ it("should use absolute override for plan mode (ignore non-mode policies)", () => {
97125 // Initialize with some existing policies
98126 service.initializeSync({
99- allow: ['allowedTool'],
100- exclude: ['excludedTool']
127+ allow: ["allowedTool"],
128+ exclude: ["excludedTool"],
101129 });
102-
130+
103131 const initialPolicies = service.getPermissions().policies;
104132 const nonModePolicyCount = initialPolicies.length;
105-
106- service.switchMode('plan');
133+
134+ service.switchMode("plan");
107135 const newPolicies = service.getPermissions().policies;
108-
136+
109137 // Plan mode should use ONLY mode policies (absolute override)
110138 // Should contain Write exclude policy for plan mode
111- const writePolicy = newPolicies.find(p => p.tool === 'Write');
112- expect(writePolicy?.permission).toBe('exclude');
113-
139+ const writePolicy = newPolicies.find((p) => p.tool === "Write");
140+ expect(writePolicy?.permission).toBe("exclude");
141+
114142 // Should not contain any user-defined policies from the initial setup
115- const userAllowPolicy = newPolicies.find(p => p.tool === 'allowedTool');
116- const userExcludePolicy = newPolicies.find(p => p.tool === 'excludedTool');
143+ const userAllowPolicy = newPolicies.find((p) => p.tool === "allowedTool");
144+ const userExcludePolicy = newPolicies.find(
145+ (p) => p.tool === "excludedTool",
146+ );
117147 expect(userAllowPolicy).toBeUndefined();
118148 expect(userExcludePolicy).toBeUndefined();
119149 });
120150
121- it('should handle switching between different modes', () => {
122- service.switchMode('plan');
123- expect(service.getCurrentMode()).toBe('plan');
124-
125- service.switchMode('auto');
126- expect(service.getCurrentMode()).toBe('auto');
127-
128- service.switchMode('normal');
129- expect(service.getCurrentMode()).toBe('normal');
151+ it("should handle switching between different modes", () => {
152+ service.switchMode("plan");
153+ expect(service.getCurrentMode()).toBe("plan");
154+
155+ service.switchMode("auto");
156+ expect(service.getCurrentMode()).toBe("auto");
157+
158+ service.switchMode("normal");
159+ expect(service.getCurrentMode()).toBe("normal");
130160 });
131161
132- it('should preserve original user policies when switching modes', () => {
162+ it("should preserve original user policies when switching modes", () => {
133163 // Initialize with user-defined policies
134164 service.initializeSync({
135- allow: ['customAllowedTool'],
136- exclude: ['customExcludedTool'],
137- ask: ['customAskTool']
165+ allow: ["customAllowedTool"],
166+ exclude: ["customExcludedTool"],
167+ ask: ["customAskTool"],
138168 });
139-
169+
140170 const originalPolicies = service.getPermissions().policies;
141- const userPolicyCount = originalPolicies.filter(p =>
142- p.tool === 'customAllowedTool' ||
143- p.tool === 'customExcludedTool' ||
144- p.tool === 'customAskTool'
171+ const userPolicyCount = originalPolicies.filter(
172+ (p) =>
173+ p.tool === "customAllowedTool" ||
174+ p.tool === "customExcludedTool" ||
175+ p.tool === "customAskTool",
145176 ).length;
146177 expect(userPolicyCount).toBe(3);
147-
178+
148179 // Switch to plan mode (should store original policies)
149- service.switchMode('plan');
180+ service.switchMode("plan");
150181 const planPolicies = service.getPermissions().policies;
151-
182+
152183 // Plan mode should not have user policies
153- const planUserPolicyCount = planPolicies.filter(p =>
154- p.tool === 'customAllowedTool' ||
155- p.tool === 'customExcludedTool' ||
156- p.tool === 'customAskTool'
184+ const planUserPolicyCount = planPolicies.filter(
185+ (p) =>
186+ p.tool === "customAllowedTool" ||
187+ p.tool === "customExcludedTool" ||
188+ p.tool === "customAskTool",
157189 ).length;
158190 expect(planUserPolicyCount).toBe(0);
159-
191+
160192 // Switch back to normal mode (should restore original policies)
161- service.switchMode('normal');
193+ service.switchMode("normal");
162194 const restoredPolicies = service.getPermissions().policies;
163-
195+
164196 // Should have user policies restored
165- const restoredUserPolicyCount = restoredPolicies.filter(p =>
166- p.tool === 'customAllowedTool' ||
167- p.tool === 'customExcludedTool' ||
168- p.tool === 'customAskTool'
197+ const restoredUserPolicyCount = restoredPolicies.filter(
198+ (p) =>
199+ p.tool === "customAllowedTool" ||
200+ p.tool === "customExcludedTool" ||
201+ p.tool === "customAskTool",
169202 ).length;
170203 expect(restoredUserPolicyCount).toBe(3);
171-
172- // Verify specific policies are restored correctly
173- expect(restoredPolicies.some(p => p.tool === 'customAllowedTool' && p.permission === 'allow')).toBe(true);
174- expect(restoredPolicies.some(p => p.tool === 'customExcludedTool' && p.permission === 'exclude')).toBe(true);
175- expect(restoredPolicies.some(p => p.tool === 'customAskTool' && p.permission === 'ask')).toBe(true);
176- });
177204
178- it('should override user permissions in plan mode', () => {
205+ // Verify specific policies are restored correctly
206+ expect(
207+ restoredPolicies.some(
208+ (p) => p.tool === "customAllowedTool" && p.permission === "allow",
209+ ),
210+ ).toBe(true);
211+ expect(
212+ restoredPolicies.some(
213+ (p) => p.tool === "customExcludedTool" && p.permission === "exclude",
214+ ),
215+ ).toBe(true);
216+ expect(
217+ restoredPolicies.some(
218+ (p) => p.tool === "customAskTool" && p.permission === "ask",
219+ ),
220+ ).toBe(true);
221+ });
222+
223+ it("should override user permissions in plan mode", () => {
179224 // Initialize with user config that allows write tools
180225 service.initializeSync({
181- allow: ['Write', 'Edit', 'Bash'],
182- mode: 'plan'
226+ allow: ["Write", "Edit", "Bash"],
227+ mode: "plan",
183228 });
184-
229+
185230 const policies = service.getPermissions().policies;
186-
231+
187232 // Mode policies should override user config - Write should be excluded despite being in allow list
188- expect(policies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
189- expect(policies.some(p => p.tool === 'Edit' && p.permission === 'exclude')).toBe(true);
190- expect(policies.some(p => p.tool === 'Bash' && p.permission === 'allow')).toBe(true);
191-
233+ expect(
234+ policies.some((p) => p.tool === "Write" && p.permission === "exclude"),
235+ ).toBe(true);
236+ expect(
237+ policies.some((p) => p.tool === "Edit" && p.permission === "exclude"),
238+ ).toBe(true);
239+ expect(
240+ policies.some((p) => p.tool === "Bash" && p.permission === "allow"),
241+ ).toBe(true);
242+
192243 // Read tools should be allowed
193- expect(policies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true);
244+ expect(
245+ policies.some((p) => p.tool === "Read" && p.permission === "allow"),
246+ ).toBe(true);
194247 });
195248
196- it('should override user permissions in auto mode', () => {
249+ it("should override user permissions in auto mode", () => {
197250 // Initialize with user config that excludes tools
198251 service.initializeSync({
199- exclude: ['Write', 'Edit', 'Bash'],
200- mode: 'auto'
252+ exclude: ["Write", "Edit", "Bash"],
253+ mode: "auto",
201254 });
202-
255+
203256 const policies = service.getPermissions().policies;
204-
257+
205258 // Mode policies should override user config - everything should be allowed
206- expect(policies[0]).toEqual({ tool: '*', permission: 'allow' });
259+ expect(policies[0]).toEqual({ tool: "*", permission: "allow" });
207260 });
208261 });
209262
210- describe('mode policy generation', () => {
211- it('should generate policies in correct order (mode policies first)', () => {
263+ describe("mode policy generation", () => {
264+ it("should generate policies in correct order (mode policies first)", () => {
212265 const state = service.initializeSync({
213- mode: 'plan',
214- allow: ['customTool']
266+ mode: "plan",
267+ allow: ["customTool"],
215268 });
216269 const policies = state.permissions.policies;
217-
270+
218271 // Mode policies should come first, and there should be policies
219272 expect(policies.length).toBeGreaterThan(0);
220-
273+
221274 // Should have MCP and wildcard exclusion policies
222- expect(policies.some(p => p.tool === 'mcp:*')).toBe(true);
223- expect(policies.some(p => p.tool === '*' && p.permission === 'exclude')).toBe(true);
275+ expect(policies.some((p) => p.tool === "mcp:*")).toBe(true);
276+ expect(
277+ policies.some((p) => p.tool === "*" && p.permission === "exclude"),
278+ ).toBe(true);
224279 });
225280 });
226281
227- describe('getCurrentMode', () => {
228- it('should return the current mode', () => {
229- service.initializeSync({ mode: 'plan' });
230- expect(service.getCurrentMode()).toBe('plan');
231-
232- service.switchMode('auto');
233- expect(service.getCurrentMode()).toBe('auto');
282+ describe("getCurrentMode", () => {
283+ it("should return the current mode", () => {
284+ service.initializeSync({ mode: "plan" });
285+ expect(service.getCurrentMode()).toBe("plan");
286+
287+ service.switchMode("auto");
288+ expect(service.getCurrentMode()).toBe("auto");
234289 });
235290 });
236291
237- describe('state consistency', () => {
238- it('should maintain consistent state between getState and getCurrentMode', () => {
239- service.initializeSync({ mode: 'plan' });
240-
292+ describe("state consistency", () => {
293+ it("should maintain consistent state between getState and getCurrentMode", () => {
294+ service.initializeSync({ mode: "plan" });
295+
241296 const state = service.getState();
242297 const currentMode = service.getCurrentMode();
243-
298+
244299 expect(state.currentMode).toBe(currentMode);
245- expect(currentMode).toBe('plan');
300+ expect(currentMode).toBe("plan");
246301 });
247302
248- it('should update state when switching modes', () => {
303+ it("should update state when switching modes", () => {
249304 service.initializeSync();
250-
305+
251306 const initialState = service.getState();
252- expect(initialState.currentMode).toBe('normal');
253-
254- service.switchMode('plan');
255-
307+ expect(initialState.currentMode).toBe("normal");
308+
309+ service.switchMode("plan");
310+
256311 const newState = service.getState();
257- expect(newState.currentMode).toBe('plan');
312+ expect(newState.currentMode).toBe("plan");
258313 expect(newState).not.toEqual(initialState);
259314 });
260315 });
261-});
No newline at the end of the file
316+});
modified extensions/cli/src/services/ToolPermissionService.real.test.ts +68 −65
@@ -1,162 +1,165 @@
1-import { describe, it, expect, beforeEach } from 'vitest';
1+import { describe, it, expect, beforeEach } from "vitest";
22
3-import { checkToolPermission } from '../permissions/permissionChecker.js';
3+import { checkToolPermission } from "../permissions/permissionChecker.js";
44
5-import { ToolPermissionService } from './ToolPermissionService.js';
5+import { ToolPermissionService } from "./ToolPermissionService.js";
66
7-describe('ToolPermissionService - Real Tool Permission Test', () => {
7+describe("ToolPermissionService - Real Tool Permission Test", () => {
88 let service: ToolPermissionService;
99
1010 beforeEach(() => {
1111 service = new ToolPermissionService();
1212 });
1313
14- describe('Plan Mode Real Tool Tests', () => {
14+ describe("Plan Mode Real Tool Tests", () => {
1515 beforeEach(() => {
16- service.initializeSync({ mode: 'plan' });
16+ service.initializeSync({ mode: "plan" });
1717 });
1818
19- it('should deny Write tool in plan mode', () => {
19+ it("should deny Write tool in plan mode", () => {
2020 const permissions = service.getPermissions();
2121 const toolCall = {
22- name: 'Write',
23- arguments: { path: 'test.txt', content: 'test' }
22+ name: "Write",
23+ arguments: { path: "test.txt", content: "test" },
2424 };
2525 const result = checkToolPermission(toolCall, permissions);
26-
26+
2727 console.log(`Write permission check result:`, result);
28- expect(result.permission).toBe('exclude');
28+ expect(result.permission).toBe("exclude");
2929 });
3030
31- it('should deny Edit tool in plan mode', () => {
31+ it("should deny Edit tool in plan mode", () => {
3232 const permissions = service.getPermissions();
3333 const toolCall = {
34- name: 'Edit',
35- arguments: { path: 'test.txt', old_str: 'old', new_str: 'new' }
34+ name: "Edit",
35+ arguments: { path: "test.txt", old_str: "old", new_str: "new" },
3636 };
3737 const result = checkToolPermission(toolCall, permissions);
38-
38+
3939 console.log(`Edit permission check result:`, result);
40- expect(result.permission).toBe('exclude');
40+ expect(result.permission).toBe("exclude");
4141 });
4242
43- it('should allow Bash tool in plan mode', () => {
43+ it("should allow Bash tool in plan mode", () => {
4444 const permissions = service.getPermissions();
4545 const toolCall = {
46- name: 'Bash',
47- arguments: { command: 'ls' }
46+ name: "Bash",
47+ arguments: { command: "ls" },
4848 };
4949 const result = checkToolPermission(toolCall, permissions);
50-
50+
5151 console.log(`Bash permission check result:`, result);
52- expect(result.permission).toBe('allow');
52+ expect(result.permission).toBe("allow");
5353 });
5454
55- it('should allow Read tool in plan mode', () => {
55+ it("should allow Read tool in plan mode", () => {
5656 const permissions = service.getPermissions();
5757 const toolCall = {
58- name: 'Read',
59- arguments: { path: 'test.txt' }
58+ name: "Read",
59+ arguments: { path: "test.txt" },
6060 };
6161 const result = checkToolPermission(toolCall, permissions);
62-
62+
6363 console.log(`Read permission check result:`, result);
64- expect(result.permission).toBe('allow');
64+ expect(result.permission).toBe("allow");
6565 });
6666
67- it('should allow List tool in plan mode', () => {
67+ it("should allow List tool in plan mode", () => {
6868 const permissions = service.getPermissions();
6969 const toolCall = {
70- name: 'List',
71- arguments: { path: '.' }
70+ name: "List",
71+ arguments: { path: "." },
7272 };
7373 const result = checkToolPermission(toolCall, permissions);
74-
74+
7575 console.log(`List permission check result:`, result);
76- expect(result.permission).toBe('allow');
76+ expect(result.permission).toBe("allow");
7777 });
7878
79- it('should deny unknown tools in plan mode (wildcard exclude)', () => {
79+ it("should deny unknown tools in plan mode (wildcard exclude)", () => {
8080 const permissions = service.getPermissions();
8181 const toolCall = {
82- name: 'unknown_write_tool',
83- arguments: {}
82+ name: "unknown_write_tool",
83+ arguments: {},
8484 };
8585 const result = checkToolPermission(toolCall, permissions);
86-
86+
8787 console.log(`unknown_write_tool permission check result:`, result);
88- expect(result.permission).toBe('exclude');
88+ expect(result.permission).toBe("exclude");
8989 });
9090 });
9191
92- describe('Auto Mode Real Tool Tests', () => {
92+ describe("Auto Mode Real Tool Tests", () => {
9393 beforeEach(() => {
94- service.initializeSync({ mode: 'auto' });
94+ service.initializeSync({ mode: "auto" });
9595 });
9696
97- it('should allow Write tool in auto mode', () => {
97+ it("should allow Write tool in auto mode", () => {
9898 const permissions = service.getPermissions();
9999 const toolCall = {
100- name: 'Write',
101- arguments: { path: 'test.txt', content: 'test' }
100+ name: "Write",
101+ arguments: { path: "test.txt", content: "test" },
102102 };
103103 const result = checkToolPermission(toolCall, permissions);
104-
104+
105105 console.log(`Auto mode Write permission check result:`, result);
106- expect(result.permission).toBe('allow');
106+ expect(result.permission).toBe("allow");
107107 });
108108
109- it('should allow Bash tool in auto mode', () => {
109+ it("should allow Bash tool in auto mode", () => {
110110 const permissions = service.getPermissions();
111111 const toolCall = {
112- name: 'Bash',
113- arguments: { command: 'ls' }
112+ name: "Bash",
113+ arguments: { command: "ls" },
114114 };
115115 const result = checkToolPermission(toolCall, permissions);
116-
116+
117117 console.log(`Auto mode Bash permission check result:`, result);
118- expect(result.permission).toBe('allow');
118+ expect(result.permission).toBe("allow");
119119 });
120120
121- it('should allow unknown tools in auto mode (wildcard allow)', () => {
121+ it("should allow unknown tools in auto mode (wildcard allow)", () => {
122122 const permissions = service.getPermissions();
123123 const toolCall = {
124- name: 'unknown_tool',
125- arguments: {}
124+ name: "unknown_tool",
125+ arguments: {},
126126 };
127127 const result = checkToolPermission(toolCall, permissions);
128-
128+
129129 console.log(`Auto mode unknown_tool permission check result:`, result);
130- expect(result.permission).toBe('allow');
130+ expect(result.permission).toBe("allow");
131131 });
132132 });
133133
134- describe('Mode Override Test', () => {
135- it('should override user permissions when switching to plan mode', () => {
134+ describe("Mode Override Test", () => {
135+ it("should override user permissions when switching to plan mode", () => {
136136 // Start with user explicitly allowing Write
137137 service.initializeSync({
138- allow: ['Write'],
139- mode: 'normal'
138+ allow: ["Write"],
139+ mode: "normal",
140140 });
141141
142142 // Verify Write is allowed in normal mode
143143 let permissions = service.getPermissions();
144144 const toolCall = {
145- name: 'Write',
146- arguments: { path: 'test.txt', content: 'test' }
145+ name: "Write",
146+ arguments: { path: "test.txt", content: "test" },
147147 };
148148 let result = checkToolPermission(toolCall, permissions);
149149 console.log(`Normal mode with user allow - Write result:`, result);
150- expect(result.permission).toBe('allow');
150+ expect(result.permission).toBe("allow");
151151
152152 // Switch to plan mode - should OVERRIDE user config completely
153- service.switchMode('plan');
153+ service.switchMode("plan");
154154 permissions = service.getPermissions();
155155 result = checkToolPermission(toolCall, permissions);
156-
156+
157157 console.log(`After switching to plan mode - write_file result:`, result);
158- console.log(`Plan mode policies:`, permissions.policies.map(p => `${p.tool}:${p.permission}`));
159- expect(result.permission).toBe('exclude');
158+ console.log(
159+ `Plan mode policies:`,
160+ permissions.policies.map((p) => `${p.tool}:${p.permission}`),
161+ );
162+ expect(result.permission).toBe("exclude");
160163 });
161164 });
162-});
No newline at the end of the file
165+});
modified extensions/cli/src/services/ToolPermissionService.test.ts +207 −182
@@ -1,11 +1,11 @@
1-import { describe, expect, test, beforeEach, vi } from 'vitest';
1+import { describe, expect, test, beforeEach, vi } from "vitest";
22
33 // Mock modules
4-vi.mock('../permissions/permissionsYamlLoader.js');
5-vi.mock('../permissions/precedenceResolver.js');
4+vi.mock("../permissions/permissionsYamlLoader.js");
5+vi.mock("../permissions/precedenceResolver.js");
66
7-import * as precedenceResolver from '../permissions/precedenceResolver.js';
8-import { ToolPermissionPolicy } from '../permissions/types.js';
7+import * as precedenceResolver from "../permissions/precedenceResolver.js";
8+import { ToolPermissionPolicy } from "../permissions/types.js";
99
1010 import { ToolPermissionService } from "./ToolPermissionService.js";
1111
@@ -17,29 +17,33 @@
1717 service = new ToolPermissionService();
1818 });
1919
20- describe('State Management', () => {
21- test('should initialize with default state', async () => {
22- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([]);
23-
20+ describe("State Management", () => {
21+ test("should initialize with default state", async () => {
22+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
23+ [],
24+ );
25+
2426 const state = await service.initialize();
25-
27+
2628 expect(state).toEqual({
2729 permissions: { policies: [] },
28- currentMode: 'normal',
30+ currentMode: "normal",
2931 isHeadless: false,
30- modePolicyCount: 0
32+ modePolicyCount: 0,
3133 });
3234 });
3335
34- test('should initialize with runtime overrides', async () => {
36+ test("should initialize with runtime overrides", async () => {
3537 const mockPolicies: ToolPermissionPolicy[] = [
36- { tool: 'TestTool3', permission: 'exclude' },
37- { tool: 'TestTool2', permission: 'ask' },
38- { tool: 'TestTool1', permission: 'allow' }
38+ { tool: "TestTool3", permission: "exclude" },
39+ { tool: "TestTool2", permission: "ask" },
40+ { tool: "TestTool1", permission: "allow" },
3941 ];
40-
41- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(mockPolicies);
42-
42+
43+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
44+ mockPolicies,
45+ );
46+
4347 const overrides = {
4448 allow: ["TestTool1"],
4549 ask: ["TestTool2"],
@@ -49,48 +53,52 @@
4953 const state = await service.initialize(overrides);
5054
5155 expect(state.permissions.policies).toEqual(mockPolicies);
52- expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({
56+ expect(
57+ precedenceResolver.resolvePermissionPrecedence,
58+ ).toHaveBeenCalledWith({
5359 commandLineFlags: overrides,
5460 personalSettings: true,
55- useDefaults: true
61+ useDefaults: true,
5662 });
5763 });
5864
59- test('should initialize with specific mode', async () => {
60- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([]);
61-
62- const state = await service.initialize({ mode: 'plan' });
63-
64- expect(state.currentMode).toBe('plan');
65+ test("should initialize with specific mode", async () => {
66+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
67+ [],
68+ );
69+
70+ const state = await service.initialize({ mode: "plan" });
71+
72+ expect(state.currentMode).toBe("plan");
6573 // Plan mode should have mode-specific policies
6674 expect(state.permissions.policies.length).toBeGreaterThan(0);
6775 expect(state.permissions.policies).toContainEqual({
68- tool: 'Write',
69- permission: 'exclude'
76+ tool: "Write",
77+ permission: "exclude",
7078 });
7179 });
7280 });
7381
74- describe('initializeSync()', () => {
75- test('should work synchronously for immediate availability', () => {
76- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
77- { tool: 'Tool1', permission: 'allow' }
78- ]);
79-
80- const state = service.initializeSync({ allow: ['Tool1'] });
81-
82+ describe("initializeSync()", () => {
83+ test("should work synchronously for immediate availability", () => {
84+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
85+ [{ tool: "Tool1", permission: "allow" }],
86+ );
87+
88+ const state = service.initializeSync({ allow: ["Tool1"] });
89+
8290 expect(state).toBeDefined();
8391 expect(state.permissions.policies).toContainEqual({
84- tool: 'Tool1',
85- permission: 'allow'
92+ tool: "Tool1",
93+ permission: "allow",
8694 });
8795 });
8896
89- test('should handle empty overrides', () => {
90- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
91- { tool: '*', permission: 'ask' }
92- ]);
93-
97+ test("should handle empty overrides", () => {
98+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
99+ [{ tool: "*", permission: "ask" }],
100+ );
101+
94102 const state = service.initializeSync({
95103 allow: [],
96104 ask: [],
@@ -98,129 +106,136 @@
98106 });
99107
100108 expect(state.permissions.policies).toEqual([
101- { tool: '*', permission: 'ask' }
109+ { tool: "*", permission: "ask" },
102110 ]);
103111 });
104112 });
105113
106- describe('Mode-specific policies', () => {
107- test('should generate plan mode policies', () => {
108- const state = service.initializeSync({ mode: 'plan' });
114+ describe("Mode-specific policies", () => {
115+ test("should generate plan mode policies", () => {
116+ const state = service.initializeSync({ mode: "plan" });
109117 const policies = state.permissions.policies;
110-
118+
111119 // Should exclude write tools
112- expect(policies).toContainEqual({ tool: 'Write', permission: 'exclude' });
113- expect(policies).toContainEqual({ tool: 'Edit', permission: 'exclude' });
114-
120+ expect(policies).toContainEqual({ tool: "Write", permission: "exclude" });
121+ expect(policies).toContainEqual({ tool: "Edit", permission: "exclude" });
122+
115123 // Should allow read tools and bash
116- expect(policies).toContainEqual({ tool: 'Bash', permission: 'allow' });
117- expect(policies).toContainEqual({ tool: 'Read', permission: 'allow' });
118- expect(policies).toContainEqual({ tool: 'Grep', permission: 'allow' });
119- expect(policies).toContainEqual({ tool: 'LS', permission: 'allow' });
120-
124+ expect(policies).toContainEqual({ tool: "Bash", permission: "allow" });
125+ expect(policies).toContainEqual({ tool: "Read", permission: "allow" });
126+ expect(policies).toContainEqual({ tool: "Grep", permission: "allow" });
127+ expect(policies).toContainEqual({ tool: "LS", permission: "allow" });
128+
121129 // Should have wildcard exclusion at the end
122- expect(policies[policies.length - 1]).toEqual({ tool: '*', permission: 'exclude' });
130+ expect(policies[policies.length - 1]).toEqual({
131+ tool: "*",
132+ permission: "exclude",
133+ });
123134 });
124135
125- test('should generate auto mode policies', () => {
126- const state = service.initializeSync({ mode: 'auto' });
127-
136+ test("should generate auto mode policies", () => {
137+ const state = service.initializeSync({ mode: "auto" });
138+
128139 expect(state.permissions.policies).toEqual([
129- { tool: '*', permission: 'allow' }
140+ { tool: "*", permission: "allow" },
130141 ]);
131142 });
132143
133- test('should generate normal mode policies', () => {
134- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
135- { tool: 'Tool1', permission: 'allow' },
136- { tool: 'Tool2', permission: 'ask' }
137- ]);
138-
139- const state = service.initializeSync({ mode: 'normal' });
140-
144+ test("should generate normal mode policies", () => {
145+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
146+ [
147+ { tool: "Tool1", permission: "allow" },
148+ { tool: "Tool2", permission: "ask" },
149+ ],
150+ );
151+
152+ const state = service.initializeSync({ mode: "normal" });
153+
141154 // Normal mode should use user configuration
142155 expect(state.permissions.policies).toEqual([
143- { tool: 'Tool1', permission: 'allow' },
144- { tool: 'Tool2', permission: 'ask' }
156+ { tool: "Tool1", permission: "allow" },
157+ { tool: "Tool2", permission: "ask" },
145158 ]);
146159 expect(state.modePolicyCount).toBe(0);
147160 });
148161 });
149162
150- describe('switchMode()', () => {
163+ describe("switchMode()", () => {
151164 beforeEach(() => {
152- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
153- { tool: 'UserTool1', permission: 'allow' },
154- { tool: 'UserTool2', permission: 'exclude' }
155- ]);
165+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
166+ [
167+ { tool: "UserTool1", permission: "allow" },
168+ { tool: "UserTool2", permission: "exclude" },
169+ ],
170+ );
156171 });
157172
158- test('should switch from normal to plan mode', () => {
159- service.initializeSync({ mode: 'normal' });
160-
161- const state = service.switchMode('plan');
162-
163- expect(state.currentMode).toBe('plan');
173+ test("should switch from normal to plan mode", () => {
174+ service.initializeSync({ mode: "normal" });
175+
176+ const state = service.switchMode("plan");
177+
178+ expect(state.currentMode).toBe("plan");
164179 // Should only have plan mode policies
165180 expect(state.permissions.policies).toContainEqual({
166- tool: 'Write',
167- permission: 'exclude'
181+ tool: "Write",
182+ permission: "exclude",
168183 });
169184 // Should not have user policies
170185 expect(state.permissions.policies).not.toContainEqual({
171- tool: 'UserTool1',
172- permission: 'allow'
186+ tool: "UserTool1",
187+ permission: "allow",
173188 });
174189 });
175190
176- test('should store original policies when leaving normal mode', () => {
177- service.initializeSync({ mode: 'normal' });
191+ test("should store original policies when leaving normal mode", () => {
192+ service.initializeSync({ mode: "normal" });
178193 const originalState = service.getState();
179-
180- service.switchMode('plan');
194+
195+ service.switchMode("plan");
181196 const planState = service.getState();
182-
197+
183198 // Should have stored original policies
184199 expect(planState.originalPolicies).toEqual({
185- policies: originalState.permissions.policies
200+ policies: originalState.permissions.policies,
186201 });
187202 });
188203
189- test('should restore original policies when switching back to normal', () => {
204+ test("should restore original policies when switching back to normal", () => {
190205 // Start in normal with user policies
191- service.initializeSync({ mode: 'normal' });
206+ service.initializeSync({ mode: "normal" });
192207 const originalPolicies = service.getState().permissions.policies;
193-
208+
194209 // Switch to plan
195- service.switchMode('plan');
196-
210+ service.switchMode("plan");
211+
197212 // Switch back to normal
198- const state = service.switchMode('normal');
199-
213+ const state = service.switchMode("normal");
214+
200215 // Should restore original user policies
201216 expect(state.permissions.policies).toEqual(originalPolicies);
202217 });
203218
204- test('should handle multiple mode switches', () => {
205- service.initializeSync({ mode: 'normal' });
206-
219+ test("should handle multiple mode switches", () => {
220+ service.initializeSync({ mode: "normal" });
221+
207222 // Switch through all modes
208- service.switchMode('plan');
209- expect(service.getCurrentMode()).toBe('plan');
210-
211- service.switchMode('auto');
212- expect(service.getCurrentMode()).toBe('auto');
223+ service.switchMode("plan");
224+ expect(service.getCurrentMode()).toBe("plan");
225+
226+ service.switchMode("auto");
227+ expect(service.getCurrentMode()).toBe("auto");
213228 expect(service.getState().permissions.policies).toEqual([
214- { tool: '*', permission: 'allow' }
229+ { tool: "*", permission: "allow" },
215230 ]);
216-
217- service.switchMode('normal');
218- expect(service.getCurrentMode()).toBe('normal');
231+
232+ service.switchMode("normal");
233+ expect(service.getCurrentMode()).toBe("normal");
219234 });
220235 });
221236
222- describe('updatePermissions()', () => {
223- test('should replace all policies', () => {
237+ describe("updatePermissions()", () => {
238+ test("should replace all policies", () => {
224239 service.initializeSync();
225240
226241 const newPolicies: ToolPermissionPolicy[] = [
@@ -236,8 +251,8 @@
236251 });
237252 });
238253
239- describe('getPermissions()', () => {
240- test('should return current permissions', () => {
254+ describe("getPermissions()", () => {
255+ test("should return current permissions", () => {
241256 service.initializeSync({ allow: ["TestTool"] });
242257
243258 const permissions = service.getPermissions();
@@ -249,97 +264,99 @@
249264 });
250265 });
251266
252- describe('getCurrentMode()', () => {
253- test('should return current mode', () => {
254- service.initializeSync({ mode: 'plan' });
255- expect(service.getCurrentMode()).toBe('plan');
256-
257- service.switchMode('auto');
258- expect(service.getCurrentMode()).toBe('auto');
267+ describe("getCurrentMode()", () => {
268+ test("should return current mode", () => {
269+ service.initializeSync({ mode: "plan" });
270+ expect(service.getCurrentMode()).toBe("plan");
271+
272+ service.switchMode("auto");
273+ expect(service.getCurrentMode()).toBe("auto");
259274 });
260275 });
261276
262- describe('isReady()', () => {
263- test('should always return true (service is always ready)', () => {
277+ describe("isReady()", () => {
278+ test("should always return true (service is always ready)", () => {
264279 // ToolPermissionService is designed to be always ready since it uses synchronous initialization
265280 expect(service.isReady()).toBe(true);
266281 });
267282
268- test('should return true after initialization', async () => {
283+ test("should return true after initialization", async () => {
269284 await service.initialize();
270285 expect(service.isReady()).toBe(true);
271286 });
272287 });
273288
274- describe('Event Emission', () => {
275- test('should emit stateChanged when switching modes', () => {
276- service.initializeSync({ mode: 'normal' });
277-
289+ describe("Event Emission", () => {
290+ test("should emit stateChanged when switching modes", () => {
291+ service.initializeSync({ mode: "normal" });
292+
278293 const listener = vi.fn();
279- service.on('stateChanged', listener);
280-
281- service.switchMode('plan');
282-
294+ service.on("stateChanged", listener);
295+
296+ service.switchMode("plan");
297+
283298 expect(listener).toHaveBeenCalledWith(
284- expect.objectContaining({ currentMode: 'plan' }),
285- expect.objectContaining({ currentMode: 'normal' })
299+ expect.objectContaining({ currentMode: "plan" }),
300+ expect.objectContaining({ currentMode: "normal" }),
286301 );
287302 });
288303
289- test('should emit stateChanged when updating permissions', () => {
304+ test("should emit stateChanged when updating permissions", () => {
290305 service.initializeSync();
291-
306+
292307 const listener = vi.fn();
293- service.on('stateChanged', listener);
294-
308+ service.on("stateChanged", listener);
309+
295310 const newPolicies: ToolPermissionPolicy[] = [
296- { tool: 'NewTool', permission: 'allow' }
311+ { tool: "NewTool", permission: "allow" },
297312 ];
298313 service.updatePermissions(newPolicies);
299-
314+
300315 expect(listener).toHaveBeenCalledWith(
301- expect.objectContaining({
302- permissions: { policies: newPolicies }
316+ expect.objectContaining({
317+ permissions: { policies: newPolicies },
303318 }),
304- expect.any(Object)
319+ expect.any(Object),
305320 );
306321 });
307322 });
308323
309- describe('Mode Override Behavior', () => {
310- test('plan mode should completely override user policies', () => {
324+ describe("Mode Override Behavior", () => {
325+ test("plan mode should completely override user policies", () => {
311326 // Initialize with user policies that would allow writes
312- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
313- { tool: 'Write', permission: 'allow' },
314- { tool: 'Edit', permission: 'allow' }
315- ]);
316-
317- const state = service.initializeSync({
318- mode: 'plan',
319- allow: ['Write', 'Edit']
327+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
328+ [
329+ { tool: "Write", permission: "allow" },
330+ { tool: "Edit", permission: "allow" },
331+ ],
332+ );
333+
334+ const state = service.initializeSync({
335+ mode: "plan",
336+ allow: ["Write", "Edit"],
320337 });
321-
338+
322339 // Plan mode should override and exclude these tools
323340 expect(state.permissions.policies).toContainEqual({
324- tool: 'Write',
325- permission: 'exclude'
341+ tool: "Write",
342+ permission: "exclude",
326343 });
327344 expect(state.permissions.policies).toContainEqual({
328- tool: 'Edit',
329- permission: 'exclude'
345+ tool: "Edit",
346+ permission: "exclude",
330347 });
331348 });
332349
333- test('auto mode should completely override user policies', () => {
350+ test("auto mode should completely override user policies", () => {
334351 // Initialize with user policies that would exclude tools
335- const state = service.initializeSync({
336- mode: 'auto',
337- exclude: ['DangerousTool']
352+ const state = service.initializeSync({
353+ mode: "auto",
354+ exclude: ["DangerousTool"],
338355 });
339-
356+
340357 // Auto mode should override and allow everything
341358 expect(state.permissions.policies).toEqual([
342- { tool: '*', permission: 'allow' }
359+ { tool: "*", permission: "allow" },
343360 ]);
344361 });
345362 });
@@ -350,49 +367,57 @@
350367 { tool: "Edit", permission: "allow" as const },
351368 { tool: "Write", permission: "ask" as const },
352369 ];
353-
370+
354371 // Mock the precedence resolver to return fresh policies
355- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(mockPolicies);
356-
372+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
373+ mockPolicies,
374+ );
375+
357376 const service = new ToolPermissionService();
358377 service.initializeSync({ mode: "normal" });
359-
378+
360379 // Verify initial state
361380 expect(service.getPermissions().policies).toEqual(mockPolicies);
362-
381+
363382 // Simulate new policies being added to the file
364383 const newMockPolicies = [
365384 ...mockPolicies,
366385 { tool: "Read", permission: "allow" as const },
367386 ];
368- vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(newMockPolicies);
369-
387+ vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
388+ newMockPolicies,
389+ );
390+
370391 // Reload permissions
371392 await service.reloadPermissions();
372-
393+
373394 // Verify policies were reloaded
374395 expect(service.getPermissions().policies).toEqual(newMockPolicies);
375- expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({
396+ expect(
397+ precedenceResolver.resolvePermissionPrecedence,
398+ ).toHaveBeenCalledWith({
376399 personalSettings: true,
377400 useDefaults: true,
378401 });
379402 });
380-
403+
381404 test("should skip reload in non-normal modes", async () => {
382405 const service = new ToolPermissionService();
383406 service.initializeSync({ mode: "plan" });
384-
407+
385408 const initialPolicies = service.getPermissions().policies;
386-
409+
387410 // Clear the mock call count
388411 vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockClear();
389-
412+
390413 // Try to reload
391414 await service.reloadPermissions();
392-
415+
393416 // Verify no reload happened
394417 expect(service.getPermissions().policies).toEqual(initialPolicies);
395- expect(precedenceResolver.resolvePermissionPrecedence).not.toHaveBeenCalled();
418+ expect(
419+ precedenceResolver.resolvePermissionPrecedence,
420+ ).not.toHaveBeenCalled();
396421 });
397422 });
398-});
No newline at the end of the file
423+});
modified extensions/cli/src/services/ToolPermissionService.unit.test.ts +1 −1
@@ -56,7 +56,7 @@
5656 // getState() returns a shallow copy, getPermissions() returns the same permissions object
5757 expect(state.permissions).toEqual(permissions);
5858 expect(state.permissions).toBe(permissions); // Same reference with shallow copy
59-
59+
6060 // Multiple calls to getPermissions() should return the same reference
6161 const permissions2 = service.getPermissions();
6262 expect(permissions).toEqual(permissions2);
modified extensions/cli/src/services/circular-dependencies.test.ts +30 −16
@@ -1,28 +1,32 @@
1-import { ServiceContainer } from './ServiceContainer.js';
1+import { ServiceContainer } from "./ServiceContainer.js";
22
3-import { initializeServices } from './index.js';
3+import { initializeServices } from "./index.js";
44
5-describe('Service Circular Dependencies', () => {
6- it('should not have circular dependencies in service setup', async () => {
5+describe("Service Circular Dependencies", () => {
6+ it("should not have circular dependencies in service setup", async () => {
77 // Create a fresh container and initialize services to get real dependencies
88 const testContainer = new ServiceContainer();
9-
9+
1010 // Monkey patch the global serviceContainer to capture registrations
1111 const originalRegister = testContainer.register.bind(testContainer);
1212 const serviceDependencies: Record<string, string[]> = {};
13-
14- testContainer.register = function<T>(serviceName: string, factory: () => Promise<T>, deps: string[] = []) {
13+
14+ testContainer.register = function <T>(
15+ serviceName: string,
16+ factory: () => Promise<T>,
17+ deps: string[] = [],
18+ ) {
1519 serviceDependencies[serviceName] = [...deps]; // Capture actual dependencies
1620 return originalRegister(serviceName, factory, deps);
1721 };
1822
1923 // Import and run the real service initialization to capture dependencies
20- const { serviceContainer } = await import('./index.js');
24+ const { serviceContainer } = await import("./index.js");
2125 const originalContainer = serviceContainer;
22-
26+
2327 // Temporarily replace the global container
2428 (global as any).serviceContainer = testContainer;
25-
29+
2630 try {
2731 // This will register services with their real dependencies
2832 await initializeServices({ headless: true });
@@ -34,7 +38,9 @@
3438 }
3539
3640 // Detect circular dependencies using topological sort
37- const detectCircularDependencies = (dependencies: Record<string, string[]>): string[] => {
41+ const detectCircularDependencies = (
42+ dependencies: Record<string, string[]>,
43+ ): string[] => {
3844 const visited = new Set<string>();
3945 const recStack = new Set<string>();
4046 const cycle: string[] = [];
@@ -78,9 +84,11 @@
7884 };
7985
8086 const circularDeps = detectCircularDependencies(serviceDependencies);
81-
87+
8288 if (circularDeps.length > 0) {
83- throw new Error(`Circular dependency detected: ${circularDeps.join(' -> ')}`);
89+ throw new Error(
90+ `Circular dependency detected: ${circularDeps.join(" -> ")}`,
91+ );
8492 }
8593
8694 // Also verify that all services can be theoretically loaded without circular issues
@@ -89,9 +97,15 @@
8997 const maxIterations = Object.keys(serviceDependencies).length * 2;
9098 let iterations = 0;
9199
92- while (resolved.size < Object.keys(serviceDependencies).length && iterations < maxIterations) {
100+ while (
101+ resolved.size < Object.keys(serviceDependencies).length &&
102+ iterations < maxIterations
103+ ) {
93104 for (const [service, deps] of Object.entries(serviceDependencies)) {
94- if (!resolved.has(service) && deps.every(dep => resolved.has(dep))) {
105+ if (
106+ !resolved.has(service) &&
107+ deps.every((dep) => resolved.has(dep))
108+ ) {
95109 resolved.add(service);
96110 }
97111 }
@@ -103,4 +117,4 @@
103117
104118 expect(canResolveAll()).toBe(true);
105119 });
106-});
No newline at the end of the file
120+});
modified extensions/cli/src/services/index.initialization.test.ts +29 −25
@@ -1,11 +1,11 @@
1-import { beforeEach, describe, expect, it } from 'vitest';
1+import { beforeEach, describe, expect, it } from "vitest";
22
3-import { serviceContainer } from './ServiceContainer.js';
4-import type { ToolPermissionServiceState } from './ToolPermissionService.js';
3+import { serviceContainer } from "./ServiceContainer.js";
4+import type { ToolPermissionServiceState } from "./ToolPermissionService.js";
55
6-import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js';
6+import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js";
77
8-describe('Service Initialization', () => {
8+describe("Service Initialization", () => {
99 beforeEach(() => {
1010 // Clean up service container state
1111 const services = [
@@ -14,10 +14,10 @@
1414 SERVICE_NAMES.API_CLIENT,
1515 SERVICE_NAMES.CONFIG,
1616 SERVICE_NAMES.MODEL,
17- SERVICE_NAMES.MCP
17+ SERVICE_NAMES.MCP,
1818 ];
19-
20- services.forEach(service => {
19+
20+ services.forEach((service) => {
2121 // Reset service state
2222 (serviceContainer as any).services.delete(service);
2323 (serviceContainer as any).factories.delete(service);
@@ -25,37 +25,41 @@
2525 });
2626 });
2727
28- it('should have TOOL_PERMISSIONS service ready after initialization', async () => {
28+ it("should have TOOL_PERMISSIONS service ready after initialization", async () => {
2929 // Before initialization, service should not be ready
3030 const beforeInit = getServiceSync(SERVICE_NAMES.TOOL_PERMISSIONS);
31- expect(beforeInit.state).toBe('error'); // Not registered yet
32-
31+ expect(beforeInit.state).toBe("error"); // Not registered yet
32+
3333 // Initialize services
3434 await initializeServices({
3535 headless: true,
3636 toolPermissionOverrides: {
37- mode: 'normal'
38- }
37+ mode: "normal",
38+ },
3939 });
40-
40+
4141 // After initialization, service should be ready
42- const afterInit = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
43- expect(afterInit.state).toBe('ready');
42+ const afterInit = getServiceSync<ToolPermissionServiceState>(
43+ SERVICE_NAMES.TOOL_PERMISSIONS,
44+ );
45+ expect(afterInit.state).toBe("ready");
4446 expect(afterInit.value).toBeDefined();
45- expect(afterInit.value?.currentMode).toBe('normal');
47+ expect(afterInit.value?.currentMode).toBe("normal");
4648 expect(afterInit.value?.isHeadless).toBe(true);
4749 });
48-
49- it('should have TOOL_PERMISSIONS service ready immediately when accessed early', async () => {
50+
51+ it("should have TOOL_PERMISSIONS service ready immediately when accessed early", async () => {
5052 await initializeServices({
51- headless: true
53+ headless: true,
5254 });
53-
55+
5456 // Simulate early access like in streamChatResponse
55- const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
56-
57+ const serviceResult = getServiceSync<ToolPermissionServiceState>(
58+ SERVICE_NAMES.TOOL_PERMISSIONS,
59+ );
60+
5761 // Service should be ready, not idle
58- expect(serviceResult.state).toBe('ready');
62+ expect(serviceResult.state).toBe("ready");
5963 expect(serviceResult.value).toBeDefined();
6064 });
61-});
No newline at the end of the file
65+});
modified extensions/cli/src/services/index.test.ts +8 −5
@@ -11,7 +11,7 @@
1111 createOrUpdateConfig: vi.fn().mockResolvedValue(undefined),
1212 }));
1313
14-// Mock auth module
14+// Mock auth module
1515 vi.mock("../auth/workos.js", () => ({
1616 loadAuthConfig: vi.fn().mockReturnValue({}),
1717 }));
@@ -47,12 +47,15 @@
4747 // Set up mocks
4848 (modeService as any).initialize = mockModeService.initialize;
4949 (modeService as any).getCurrentMode = mockModeService.getCurrentMode;
50- (modeService as any).getToolPermissionService = mockModeService.getToolPermissionService;
51-
50+ (modeService as any).getToolPermissionService =
51+ mockModeService.getToolPermissionService;
52+
5253 // Mock serviceContainer methods
53- (serviceContainer as any).registerValue = mockServiceContainer.registerValue;
54+ (serviceContainer as any).registerValue =
55+ mockServiceContainer.registerValue;
5456 (serviceContainer as any).register = mockServiceContainer.register;
55- (serviceContainer as any).initializeAll = mockServiceContainer.initializeAll;
57+ (serviceContainer as any).initializeAll =
58+ mockServiceContainer.initializeAll;
5659 });
5760
5861 afterEach(() => {
modified extensions/cli/src/session.test.ts +15 −15
@@ -5,7 +5,7 @@
55
66 beforeEach(() => {
77 originalEnv = { ...process.env };
8-
8+
99 // Clear session-related environment variables
1010 delete process.env.TMUX_PANE;
1111 delete process.env.TERM_SESSION_ID;
@@ -41,7 +41,7 @@
4141
4242 it("should use TERM_SESSION_ID when TMUX_PANE is not available", () => {
4343 process.env.TERM_SESSION_ID = "w1t0s0:0.0";
44-
44+
4545 saveSession([{ role: "user", content: "test" }]);
4646 expect(hasSession()).toBe(true);
4747 clearSession();
@@ -49,7 +49,7 @@
4949
5050 it("should use SSH_TTY when other env vars are not available", () => {
5151 process.env.SSH_TTY = "/dev/pts/0";
52-
52+
5353 saveSession([{ role: "user", content: "test" }]);
5454 expect(hasSession()).toBe(true);
5555 clearSession();
@@ -57,12 +57,12 @@
5757
5858 it("should clean special characters from session IDs", () => {
5959 process.env.TMUX_PANE = "%1:0.0/special#chars@test!";
60-
60+
6161 // Should not throw error despite special characters
6262 expect(() => {
6363 saveSession([{ role: "user", content: "test" }]);
6464 }).not.toThrow();
65-
65+
6666 expect(hasSession()).toBe(true);
6767 clearSession();
6868 });
@@ -71,7 +71,7 @@
7171 describe("Test Mode", () => {
7272 it("should use test session ID when provided", () => {
7373 process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123";
74-
74+
7575 saveSession([{ role: "user", content: "test" }]);
7676 expect(hasSession()).toBe(true);
7777 clearSession();
@@ -81,28 +81,28 @@
8181 describe("Fallback Mechanisms", () => {
8282 it("should create a session even when no environment variables are available", () => {
8383 // No environment variables set
84-
84+
8585 // Should fall back to TTY path, process tree, or PID
8686 expect(() => {
8787 saveSession([{ role: "user", content: "fallback test" }]);
8888 }).not.toThrow();
89-
89+
9090 expect(hasSession()).toBe(true);
9191 clearSession();
9292 });
9393
9494 it("should handle session persistence correctly", () => {
9595 process.env.TMUX_PANE = "%test";
96-
96+
9797 const testHistory = [
9898 { role: "user" as const, content: "Hello" },
99- { role: "assistant" as const, content: "Hi there!" }
99+ { role: "assistant" as const, content: "Hi there!" },
100100 ];
101-
101+
102102 // Save session
103103 saveSession(testHistory);
104104 expect(hasSession()).toBe(true);
105-
105+
106106 // Clear and verify it's gone
107107 clearSession();
108108 expect(hasSession()).toBe(false);
@@ -113,12 +113,12 @@
113113 it("should handle filesystem errors gracefully", () => {
114114 // Try to save to invalid session ID that might cause filesystem issues
115115 process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-with-various-chars";
116-
116+
117117 expect(() => {
118118 saveSession([{ role: "user", content: "test" }]);
119119 }).not.toThrow();
120-
120+
121121 clearSession();
122122 });
123123 });
124-});
No newline at the end of the file
124+});
modified extensions/cli/src/slashCommands.modes.test.ts +4 −4
@@ -1,10 +1,10 @@
11 // Mode-related slash commands have been removed per user request
22 // This test file is no longer needed but needs a dummy test for Vitest
33
4-import { describe, it, expect } from 'vitest';
4+import { describe, it, expect } from "vitest";
55
6-describe('Mode slash commands (removed)', () => {
7- it('should pass (dummy test)', () => {
6+describe("Mode slash commands (removed)", () => {
7+ it("should pass (dummy test)", () => {
88 expect(true).toBe(true);
99 });
10-});
No newline at the end of the file
10+});
modified extensions/cli/src/slashCommands.test.ts +2 −6
@@ -35,7 +35,7 @@
3535 expect.arrayContaining([
3636 expect.objectContaining({ name: "help" }),
3737 expect.objectContaining({ name: "login" }),
38- ])
38+ ]),
3939 );
4040 });
4141
@@ -58,7 +58,7 @@
5858
5959 expect(result).not.toBeNull();
6060 expect(result?.output).toContain(
61- "Login successful! All services updated automatically."
61+ "Login successful! All services updated automatically.",
6262 );
6363
6464 // Verify auth service login was called
@@ -73,8 +73,6 @@
7373 expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG);
7474 });
7575
76-
77-
7876 test.skip("login failure should not trigger any reloads", async () => {
7977 const loginError = new Error("Login failed");
8078 (services.auth.login as any).mockRejectedValue(loginError);
@@ -87,8 +85,6 @@
8785 // Verify NO reload was triggered on failure
8886 expect(reloadService).not.toHaveBeenCalled();
8987 });
90-
91-
9288 });
9389
9490 describe("Other Commands (unchanged behavior)", () => {
modified extensions/cli/src/streamChatResponse.getAllTools.test.ts +85 −74
@@ -1,10 +1,15 @@
1-import { describe, expect, test } from 'vitest';
2-
3-import { getServiceSync, initializeServices, SERVICE_NAMES, serviceContainer } from './services/index.js';
4-import type { ToolPermissionServiceState } from './services/ToolPermissionService.js';
5-import { getAllTools } from './streamChatResponse.js';
6-
7-describe('getAllTools - Tool Filtering', () => {
1+import { describe, expect, test } from "vitest";
2+
3+import {
4+ getServiceSync,
5+ initializeServices,
6+ SERVICE_NAMES,
7+ serviceContainer,
8+} from "./services/index.js";
9+import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
10+import { getAllTools } from "./streamChatResponse.js";
11+
12+describe("getAllTools - Tool Filtering", () => {
813 beforeEach(() => {
914 // Clean up service container state before each test
1015 const services = [
@@ -13,10 +18,10 @@
1318 SERVICE_NAMES.API_CLIENT,
1419 SERVICE_NAMES.CONFIG,
1520 SERVICE_NAMES.MODEL,
16- SERVICE_NAMES.MCP
21+ SERVICE_NAMES.MCP,
1722 ];
18-
19- services.forEach(service => {
23+
24+ services.forEach((service) => {
2025 // Reset service state
2126 (serviceContainer as any).services.delete(service);
2227 (serviceContainer as any).factories.delete(service);
@@ -24,137 +29,143 @@
2429 });
2530 });
2631
27- test('should exclude Bash tool in plan mode after service initialization', async () => {
32+ test("should exclude Bash tool in plan mode after service initialization", async () => {
2833 // Initialize services in plan mode (simulating `cn -p`)
2934 await initializeServices({
3035 headless: true,
3136 toolPermissionOverrides: {
32- mode: 'plan'
33- }
37+ mode: "plan",
38+ },
3439 });
3540
3641 // Verify service is ready
37- const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
38- expect(serviceResult.state).toBe('ready');
39- expect(serviceResult.value?.currentMode).toBe('plan');
42+ const serviceResult = getServiceSync<ToolPermissionServiceState>(
43+ SERVICE_NAMES.TOOL_PERMISSIONS,
44+ );
45+ expect(serviceResult.state).toBe("ready");
46+ expect(serviceResult.value?.currentMode).toBe("plan");
4047
4148 // Get available tools - this should include Bash in plan mode
4249 const tools = await getAllTools();
43- const toolNames = tools.map(t => t.function.name);
50+ const toolNames = tools.map((t) => t.function.name);
4451
4552 // Bash should be allowed in plan mode
46- expect(toolNames).toContain('Bash');
47-
53+ expect(toolNames).toContain("Bash");
54+
4855 // Read-only tools should still be available
49- expect(toolNames).toContain('Read');
50- expect(toolNames).toContain('List');
51- expect(toolNames).toContain('Search');
52- expect(toolNames).toContain('Fetch');
53- expect(toolNames).toContain('Checklist');
54-
56+ expect(toolNames).toContain("Read");
57+ expect(toolNames).toContain("List");
58+ expect(toolNames).toContain("Search");
59+ expect(toolNames).toContain("Fetch");
60+ expect(toolNames).toContain("Checklist");
61+
5562 // Write tools should be excluded
56- expect(toolNames).not.toContain('Write');
57- expect(toolNames).not.toContain('Edit');
63+ expect(toolNames).not.toContain("Write");
64+ expect(toolNames).not.toContain("Edit");
5865 });
5966
60- test('should include Bash tool in normal mode', async () => {
67+ test("should include Bash tool in normal mode", async () => {
6168 // Initialize services in normal mode
6269 await initializeServices({
6370 headless: true,
6471 toolPermissionOverrides: {
65- mode: 'normal'
66- }
72+ mode: "normal",
73+ },
6774 });
6875
6976 // Verify service is ready
70- const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
71- expect(serviceResult.state).toBe('ready');
72- expect(serviceResult.value?.currentMode).toBe('normal');
77+ const serviceResult = getServiceSync<ToolPermissionServiceState>(
78+ SERVICE_NAMES.TOOL_PERMISSIONS,
79+ );
80+ expect(serviceResult.state).toBe("ready");
81+ expect(serviceResult.value?.currentMode).toBe("normal");
7382
7483 // Get available tools - Bash should be available in normal mode
7584 const tools = await getAllTools();
76- const toolNames = tools.map(t => t.function.name);
85+ const toolNames = tools.map((t) => t.function.name);
7786
7887 // All tools should be available in normal mode
79- expect(toolNames).toContain('Bash');
80- expect(toolNames).toContain('Read');
81- expect(toolNames).toContain('Write');
82- expect(toolNames).toContain('Edit');
88+ expect(toolNames).toContain("Bash");
89+ expect(toolNames).toContain("Read");
90+ expect(toolNames).toContain("Write");
91+ expect(toolNames).toContain("Edit");
8392 });
8493
85- test('should include all tools in auto mode', async () => {
94+ test("should include all tools in auto mode", async () => {
8695 // Initialize services in auto mode
8796 await initializeServices({
8897 headless: true,
8998 toolPermissionOverrides: {
90- mode: 'auto'
91- }
99+ mode: "auto",
100+ },
92101 });
93102
94103 // Verify service is ready
95- const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
96- expect(serviceResult.state).toBe('ready');
97- expect(serviceResult.value?.currentMode).toBe('auto');
104+ const serviceResult = getServiceSync<ToolPermissionServiceState>(
105+ SERVICE_NAMES.TOOL_PERMISSIONS,
106+ );
107+ expect(serviceResult.state).toBe("ready");
108+ expect(serviceResult.value?.currentMode).toBe("auto");
98109
99110 // Get available tools - all tools should be available in auto mode
100111 const tools = await getAllTools();
101- const toolNames = tools.map(t => t.function.name);
112+ const toolNames = tools.map((t) => t.function.name);
102113
103114 // All tools should be available in auto mode
104- expect(toolNames).toContain('Bash');
105- expect(toolNames).toContain('Read');
106- expect(toolNames).toContain('Write');
107- expect(toolNames).toContain('Edit');
115+ expect(toolNames).toContain("Bash");
116+ expect(toolNames).toContain("Read");
117+ expect(toolNames).toContain("Write");
118+ expect(toolNames).toContain("Edit");
108119 });
109120
110- test('should respect explicit exclude in normal mode', async () => {
121+ test("should respect explicit exclude in normal mode", async () => {
111122 // Initialize services in normal mode with Read tool explicitly excluded
112123 await initializeServices({
113124 headless: true,
114125 toolPermissionOverrides: {
115- mode: 'normal',
116- exclude: ['Read']
117- }
126+ mode: "normal",
127+ exclude: ["Read"],
128+ },
118129 });
119130
120131 const tools = await getAllTools();
121- const toolNames = tools.map(t => t.function.name);
132+ const toolNames = tools.map((t) => t.function.name);
122133
123134 // Read should be excluded due to explicit exclude
124- expect(toolNames).not.toContain('Read');
125-
135+ expect(toolNames).not.toContain("Read");
136+
126137 // Other tools should still be available in normal mode
127- expect(toolNames).toContain('Bash');
128- expect(toolNames).toContain('Write');
129- expect(toolNames).toContain('List');
130- expect(toolNames).toContain('Search');
138+ expect(toolNames).toContain("Bash");
139+ expect(toolNames).toContain("Write");
140+ expect(toolNames).toContain("List");
141+ expect(toolNames).toContain("Search");
131142 });
132143
133- test('plan mode should override allow flags (regression test for GitHub Actions issue)', async () => {
144+ test("plan mode should override allow flags (regression test for GitHub Actions issue)", async () => {
134145 // This test specifically addresses the original issue where plan mode
135146 // wasn't properly excluding tools despite being in plan mode
136147 await initializeServices({
137148 headless: true,
138149 toolPermissionOverrides: {
139- mode: 'plan',
140- allow: ['Write', 'Edit'] // These should be ignored in plan mode
141- }
150+ mode: "plan",
151+ allow: ["Write", "Edit"], // These should be ignored in plan mode
152+ },
142153 });
143154
144155 const tools = await getAllTools();
145- const toolNames = tools.map(t => t.function.name);
156+ const toolNames = tools.map((t) => t.function.name);
146157
147158 // Plan mode should still exclude write tools despite --allow flags
148159 // This tests that plan mode policies have absolute precedence
149- expect(toolNames).not.toContain('Write');
150- expect(toolNames).not.toContain('Edit');
151-
160+ expect(toolNames).not.toContain("Write");
161+ expect(toolNames).not.toContain("Edit");
162+
152163 // Bash should be available in plan mode
153- expect(toolNames).toContain('Bash');
154-
164+ expect(toolNames).toContain("Bash");
165+
155166 // Read-only tools should be available
156- expect(toolNames).toContain('Read');
157- expect(toolNames).toContain('List');
158- expect(toolNames).toContain('Search');
167+ expect(toolNames).toContain("Read");
168+ expect(toolNames).toContain("List");
169+ expect(toolNames).toContain("Search");
159170 });
160-});
No newline at the end of the file
171+});
modified extensions/cli/src/streamChatResponse.modeSwitch.test.ts +82 −65
@@ -1,10 +1,14 @@
1-import { describe, expect, test, vi, beforeEach } from 'vitest';
1+import { describe, expect, test, vi, beforeEach } from "vitest";
22
3-import { serviceContainer, SERVICE_NAMES, initializeServices } from './services/index.js';
4-import { modeService } from './services/ModeService.js';
5-import { getAllTools } from './streamChatResponse.js';
3+import {
4+ serviceContainer,
5+ SERVICE_NAMES,
6+ initializeServices,
7+} from "./services/index.js";
8+import { modeService } from "./services/ModeService.js";
9+import { getAllTools } from "./streamChatResponse.js";
610
7-describe('streamChatResponse - Mode Switch During Streaming', () => {
11+describe("streamChatResponse - Mode Switch During Streaming", () => {
812 beforeEach(async () => {
913 // Clean up service container state before each test
1014 const services = [
@@ -13,10 +17,10 @@
1317 SERVICE_NAMES.API_CLIENT,
1418 SERVICE_NAMES.CONFIG,
1519 SERVICE_NAMES.MODEL,
16- SERVICE_NAMES.MCP
20+ SERVICE_NAMES.MCP,
1721 ];
18-
19- services.forEach(service => {
22+
23+ services.forEach((service) => {
2024 (serviceContainer as any).services.delete(service);
2125 (serviceContainer as any).factories.delete(service);
2226 (serviceContainer as any).dependencies.delete(service);
@@ -26,73 +30,73 @@
2630 await initializeServices({
2731 headless: true,
2832 toolPermissionOverrides: {
29- mode: 'normal'
30- }
33+ mode: "normal",
34+ },
3135 });
3236 });
3337
34- test('should recompute tools on each iteration to handle mode switches', async () => {
38+ test("should recompute tools on each iteration to handle mode switches", async () => {
3539 // Start in normal mode
3640 let tools = await getAllTools();
37- let toolNames = tools.map(t => t.function.name);
38-
41+ let toolNames = tools.map((t) => t.function.name);
42+
3943 // Should include write tools in normal mode
40- expect(toolNames).toContain('Write');
41- expect(toolNames).toContain('Edit');
44+ expect(toolNames).toContain("Write");
45+ expect(toolNames).toContain("Edit");
4246
4347 // Switch to plan mode (simulating Shift+Tab during streaming)
44- modeService.switchMode('plan');
45-
48+ modeService.switchMode("plan");
49+
4650 // Update the service container (this is what UserInput.tsx does)
4751 const updatedState = modeService.getToolPermissionService().getState();
4852 serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
4953
5054 // Recompute tools - should now exclude write tools
5155 tools = await getAllTools();
52- toolNames = tools.map(t => t.function.name);
53-
56+ toolNames = tools.map((t) => t.function.name);
57+
5458 // Should exclude write tools in plan mode
55- expect(toolNames).not.toContain('Write');
56- expect(toolNames).not.toContain('Edit');
57-
59+ expect(toolNames).not.toContain("Write");
60+ expect(toolNames).not.toContain("Edit");
61+
5862 // Should still include read-only tools
59- expect(toolNames).toContain('Read');
60- expect(toolNames).toContain('Bash');
61- expect(toolNames).toContain('List');
63+ expect(toolNames).toContain("Read");
64+ expect(toolNames).toContain("Bash");
65+ expect(toolNames).toContain("List");
6266 });
6367
64- test('getAllTools reflects current mode immediately', async () => {
68+ test("getAllTools reflects current mode immediately", async () => {
6569 // Start in normal mode
66- expect(modeService.getCurrentMode()).toBe('normal');
70+ expect(modeService.getCurrentMode()).toBe("normal");
6771 let tools = await getAllTools();
68- expect(tools.map(t => t.function.name)).toContain('Write');
72+ expect(tools.map((t) => t.function.name)).toContain("Write");
6973
7074 // Switch to plan mode
71- modeService.switchMode('plan');
75+ modeService.switchMode("plan");
7276 let updatedState = modeService.getToolPermissionService().getState();
7377 serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
74- expect(modeService.getCurrentMode()).toBe('plan');
75-
78+ expect(modeService.getCurrentMode()).toBe("plan");
79+
7680 // getAllTools should immediately reflect the new mode
7781 tools = await getAllTools();
78- expect(tools.map(t => t.function.name)).not.toContain('Write');
82+ expect(tools.map((t) => t.function.name)).not.toContain("Write");
7983
8084 // Switch to auto mode
81- modeService.switchMode('auto');
85+ modeService.switchMode("auto");
8286 updatedState = modeService.getToolPermissionService().getState();
8387 serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
84- expect(modeService.getCurrentMode()).toBe('auto');
85-
88+ expect(modeService.getCurrentMode()).toBe("auto");
89+
8690 // getAllTools should immediately reflect auto mode (all tools allowed)
8791 tools = await getAllTools();
88- expect(tools.map(t => t.function.name)).toContain('Write');
89- expect(tools.map(t => t.function.name)).toContain('Edit');
90- expect(tools.map(t => t.function.name)).toContain('Read');
92+ expect(tools.map((t) => t.function.name)).toContain("Write");
93+ expect(tools.map((t) => t.function.name)).toContain("Edit");
94+ expect(tools.map((t) => t.function.name)).toContain("Read");
9195 });
9296
93- test('demonstrates the fix: no more stale tool lists', async () => {
97+ test("demonstrates the fix: no more stale tool lists", async () => {
9498 // This test demonstrates that the fix prevents the original race condition
95-
99+
96100 // Mock a multi-turn conversation scenario
97101 const mockLlmApi = {
98102 chatCompletions: {
@@ -102,52 +106,65 @@
102106 [Symbol.asyncIterator]: async function* () {
103107 // First response - content only
104108 yield {
105- choices: [{
106- delta: { content: "I'll help you with that." },
107- finish_reason: null
108- }]
109+ choices: [
110+ {
111+ delta: { content: "I'll help you with that." },
112+ finish_reason: null,
113+ },
114+ ],
109115 };
110-
116+
111117 // Second response - indicates tool calls coming
112118 yield {
113- choices: [{
114- delta: { tool_calls: [{
115- index: 0,
116- id: "call_1",
117- function: { name: "Read", arguments: '{"filepath": "test.txt"}' }
118- }] },
119- finish_reason: null
120- }]
119+ choices: [
120+ {
121+ delta: {
122+ tool_calls: [
123+ {
124+ index: 0,
125+ id: "call_1",
126+ function: {
127+ name: "Read",
128+ arguments: '{"filepath": "test.txt"}',
129+ },
130+ },
131+ ],
132+ },
133+ finish_reason: null,
134+ },
135+ ],
121136 };
122137
123138 // Final response
124139 yield {
125- choices: [{
126- delta: {},
127- finish_reason: "tool_calls"
128- }]
140+ choices: [
141+ {
142+ delta: {},
143+ finish_reason: "tool_calls",
144+ },
145+ ],
129146 };
130- }
147+ },
131148 };
132- })
133- }
149+ }),
150+ },
134151 };
135152
136153 const mockModel = {
137154 model: "gpt-4",
138- defaultCompletionOptions: {}
155+ defaultCompletionOptions: {},
139156 };
140157
141158 const abortController = new AbortController();
142-
159+
143160 // Start in normal mode - tools should include Write
144161 const initialTools = await getAllTools();
145- expect(initialTools.map(t => t.function.name)).toContain('Write');
162+ expect(initialTools.map((t) => t.function.name)).toContain("Write");
146163
147164 // During streaming, if mode switches, subsequent iterations should use new tools
148165 // This is now handled by recomputing tools on each iteration
149-
166+
150167 // The fix ensures that each call to processStreamingResponse gets fresh tools
151168 // based on the current mode, preventing the race condition
152169 });
153-});
No newline at the end of the file
170+});
modified extensions/cli/src/streamChatResponse.test.ts +36 −37
@@ -4,7 +4,7 @@
44 ChatCompletionChunk,
55 ChatCompletionMessageParam,
66 } from "openai/resources/chat/completions.mjs";
7-import { vi } from 'vitest';
7+import { vi } from "vitest";
88
99 import { toolPermissionManager } from "./permissions/permissionManager.js";
1010 import {
@@ -18,7 +18,6 @@
1818 import { PreprocessedToolCall } from "./tools/types.js";
1919 import { writeFileTool } from "./tools/writeFile.js";
2020
21-
2221 // Test the chunk processing logic that was identified as buggy
2322 describe("processStreamingResponse - content preservation", () => {
2423 // Mock dependencies
@@ -49,7 +48,7 @@
4948 function toolCallChunk(
5049 id: string,
5150 name?: string,
52- args?: string
51+ args?: string,
5352 ): ChatCompletionChunk {
5453 return {
5554 id: "test",
@@ -83,7 +82,7 @@
8382 index: number,
8483 id?: string,
8584 name?: string,
86- args?: string
85+ args?: string,
8786 ): ChatCompletionChunk {
8887 const toolCall: any = {
8988 index,
@@ -185,27 +184,27 @@
185184 toolCallChunk(
186185 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
187186 undefined,
188- '{"filepath'
187+ '{"filepath',
189188 ),
190189 toolCallChunk(
191190 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
192191 undefined,
193- '": "/Use'
192+ '": "/Use',
194193 ),
195194 toolCallChunk(
196195 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
197196 undefined,
198- "rs/nate/gh/c"
197+ "rs/nate/gh/c",
199198 ),
200199 toolCallChunk(
201200 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
202201 undefined,
203- "ontinuede"
202+ "ontinuede",
204203 ),
205204 toolCallChunk(
206205 "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
207206 undefined,
208- "v/cli/README"
207+ "v/cli/README",
209208 ),
210209 toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'),
211210 contentChunk(""),
@@ -228,7 +227,7 @@
228227 // Verify the tool call was assembled correctly
229228 expect(result.toolCalls[0].name).toBe("Read");
230229 expect(result.toolCalls[0].argumentsStr).toBe(
231- '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
230+ '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
232231 );
233232 });
234233
@@ -257,14 +256,14 @@
257256 0,
258257 "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz",
259258 "Read",
260- ""
259+ "",
261260 ),
262261 // Subsequent chunks only have index, no ID
263262 toolCallChunkWithIndex(
264263 0,
265264 undefined,
266265 undefined,
267- '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
266+ '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
268267 ),
269268 ];
270269
@@ -277,19 +276,19 @@
277276
278277 // Content is captured correctly
279278 expect(result.content).toBe(
280- "I'll read the README.md file for you and then say hello!"
279+ "I'll read the README.md file for you and then say hello!",
281280 );
282281 expect(result.toolCalls.length).toBe(1);
283282
284283 // Fixed: finalContent preserves content
285284 expect(result.finalContent).toBe(
286- "I'll read the README.md file for you and then say hello!"
285+ "I'll read the README.md file for you and then say hello!",
287286 );
288287
289288 // Tool call arguments are preserved using index mapping
290289 expect(result.toolCalls[0].name).toBe("Read");
291290 expect(result.toolCalls[0].argumentsStr).toBe(
292- '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
291+ '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
293292 );
294293 });
295294
@@ -302,7 +301,7 @@
302301 0,
303302 "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz",
304303 "Read",
305- ""
304+ "",
306305 ),
307306 // Subsequent chunks fragment the JSON arguments
308307 toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'),
@@ -328,13 +327,13 @@
328327 // Fixed: Both issues are resolved
329328 // 1. Content is preserved
330329 expect(result.finalContent).toBe(
331- "I'll read the README.md file for you and then say hello!"
330+ "I'll read the README.md file for you and then say hello!",
332331 );
333332
334333 // 2. Tool call arguments are assembled correctly
335334 expect(result.toolCalls[0].name).toBe("Read");
336335 expect(result.toolCalls[0].argumentsStr).toBe(
337- '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
336+ '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
338337 );
339338 });
340339
@@ -352,15 +351,15 @@
352351 prompt_tokens: 711,
353352 total_tokens: 807,
354353 prompt_tokens_details: {
355- cached_tokens: 3353
356- }
357- }
354+ cached_tokens: 3353,
355+ },
356+ },
358357 };
359358
360359 chunks = [
361360 malformedChunk, // Put malformed chunk first to trigger the bug more clearly
362361 contentChunk("Hello "),
363- contentChunk("world!")
362+ contentChunk("world!"),
364363 ];
365364
366365 // This should not throw an error: "Cannot read properties of undefined (reading 'delta')"
@@ -440,7 +439,7 @@
440439 vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce(
441440 () => {
442441 throw new Error("Missing required argument");
443- }
442+ },
444443 );
445444
446445 const toolCalls: ToolCall[] = [
@@ -470,7 +469,7 @@
470469 expect(callbacks.onToolStart).toHaveBeenCalledWith("Read", {});
471470 expect(callbacks.onToolError).toHaveBeenCalledWith(
472471 expect.stringContaining("Missing required argument"),
473- "Read"
472+ "Read",
474473 );
475474 });
476475
@@ -492,7 +491,7 @@
492491 expect(preprocessedCalls).toHaveLength(0);
493492 expect(errorChatEntries).toHaveLength(1);
494493 expect(errorChatEntries[0].content).toContain(
495- "Tool nonexistent_tool not found"
494+ "Tool nonexistent_tool not found",
496495 );
497496 });
498497 });
@@ -538,7 +537,7 @@
538537
539538 const { chatHistoryEntries } = await executeStreamedToolCalls(
540539 preprocessedCalls,
541- callbacks
540+ callbacks,
542541 );
543542
544543 // Verify results
@@ -549,7 +548,7 @@
549548 });
550549 expect(callbacks.onToolResult).toHaveBeenCalledWith(
551550 "Tool execution successful",
552- "Read"
551+ "Read",
553552 );
554553 expect(mockedExecuteToolCall).toHaveBeenCalledWith(preprocessedCalls[0]);
555554 });
@@ -583,7 +582,7 @@
583582 });
584583 }
585584 return toolPermissionManager;
586- }
585+ },
587586 );
588587
589588 // Create preprocessed tool call
@@ -614,7 +613,7 @@
614613
615614 const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls(
616615 preprocessedCalls,
617- callbacks
616+ callbacks,
618617 );
619618
620619 // Verify results
@@ -622,7 +621,7 @@
622621 expect(chatHistoryEntries).toHaveLength(2);
623622 expect(chatHistoryEntries[0].content).toBe("Permission denied by user");
624623 expect(chatHistoryEntries[1].content).toBe(
625- "Cancelled due to previous tool rejection"
624+ "Cancelled due to previous tool rejection",
626625 );
627626 expect(callbacks.onToolStart).toHaveBeenCalledWith("Write", {
628627 filepath: "/test.txt",
@@ -630,13 +629,13 @@
630629 });
631630 expect(callbacks.onToolResult).toHaveBeenCalledWith(
632631 "Permission denied by user",
633- "Write"
632+ "Write",
634633 );
635634 expect(callbacks.onToolPermissionRequest).toHaveBeenCalledWith(
636635 "Write",
637636 { filepath: "/test.txt", content: "data" },
638637 "req_123",
639- undefined
638+ undefined,
640639 );
641640 });
642641
@@ -649,7 +648,7 @@
649648
650649 const toolsModule = await import("./tools/index.js");
651650 vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue(
652- new Error("Execution failed")
651+ new Error("Execution failed"),
653652 );
654653
655654 // Create preprocessed tool call
@@ -671,13 +670,13 @@
671670
672671 const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls(
673672 preprocessedCalls,
674- callbacks
673+ callbacks,
675674 );
676675
677676 // Verify results
678677 expect(chatHistoryEntries).toHaveLength(1);
679678 expect(chatHistoryEntries[0].content).toContain(
680- "Error executing tool search_code"
679+ "Error executing tool search_code",
681680 );
682681 expect(chatHistoryEntries[0].content).toContain("Execution failed");
683682 expect(callbacks.onToolStart).toHaveBeenCalledWith("search_code", {
@@ -685,9 +684,9 @@
685684 });
686685 expect(callbacks.onToolError).toHaveBeenCalledWith(
687686 expect.stringContaining(
688- "Error executing tool search_code: Execution failed"
687+ "Error executing tool search_code: Execution failed",
689688 ),
690- "search_code"
689+ "search_code",
691690 );
692691 });
693692 });
modified extensions/cli/src/systemMessage.test.ts +8 −4
@@ -7,13 +7,15 @@
77 // Mock the service container to avoid "No factory registered for service 'config'" error
88 vi.mock("./services/ServiceContainer.js", () => ({
99 serviceContainer: {
10- get: vi.fn().mockResolvedValue({ config: { rules: [] } })
11- }
10+ get: vi.fn().mockResolvedValue({ config: { rules: [] } }),
11+ },
1212 }));
1313
1414 // Mock processRule to avoid file system operations in tests
1515 vi.mock("./args.js", () => ({
16- processRule: vi.fn().mockImplementation((rule: string) => Promise.resolve(rule))
16+ processRule: vi
17+ .fn()
18+ .mockImplementation((rule: string) => Promise.resolve(rule)),
1719 }));
1820
1921 describe("constructSystemMessage", () => {
@@ -124,7 +126,9 @@
124126 expect(result).toContain("You are an agent in the Continue CLI");
125127 expect(result).toContain("IMPORTANT: You are running in headless mode");
126128 expect(result).toContain("Provide ONLY your final answer");
127- expect(result).toContain("Do not include explanations, reasoning, or additional commentary");
129+ expect(result).toContain(
130+ "Do not include explanations, reasoning, or additional commentary",
131+ );
128132 });
129133
130134 it("should not add headless mode instructions when headless is false", async () => {
modified extensions/cli/src/telemetry/posthogService.errorHandling.test.ts +4 −4
@@ -29,7 +29,7 @@
2929
3030 // This should not throw an error
3131 await expect(
32- posthogService.capture("test_event", { test: "data" })
32+ posthogService.capture("test_event", { test: "data" }),
3333 ).resolves.toBeUndefined();
3434
3535 // Verify the client capture was called
@@ -68,12 +68,12 @@
6868 it("should handle getClient errors gracefully", async () => {
6969 // Mock the getClient method to throw an error
7070 vi.spyOn(posthogService as any, "getClient").mockRejectedValue(
71- new Error("Failed to initialize PostHog client")
71+ new Error("Failed to initialize PostHog client"),
7272 );
7373
7474 // This should not throw an error
7575 await expect(
76- posthogService.capture("test_event", { test: "data" })
76+ posthogService.capture("test_event", { test: "data" }),
7777 ).resolves.toBeUndefined();
7878 });
7979
@@ -100,4 +100,4 @@
100100 process.env.CONTINUE_CLI_ENABLE_TELEMETRY = originalEnv;
101101 }
102102 });
103-});
No newline at the end of the file
103+});
modified extensions/cli/src/telemetry/posthogService.test.ts +4 −3
@@ -26,7 +26,6 @@
2626
2727 import { PosthogService } from "./posthogService.js";
2828
29-
3029 describe("PosthogService", () => {
3130 let tempDir: string;
3231
@@ -90,7 +89,9 @@
9089 it("should use machine id when auth config is environment-based", () => {
9190 const mockMachineId = "test-machine-id";
9291
93- vi.mocked(loadAuthConfig).mockReturnValue({ accessToken: "token" } as any);
92+ vi.mocked(loadAuthConfig).mockReturnValue({
93+ accessToken: "token",
94+ } as any);
9495 vi.mocked(isAuthenticatedConfig).mockReturnValue(false);
9596 vi.mocked(machineIdSync).mockReturnValue(mockMachineId);
9697
@@ -116,4 +117,4 @@
116117 expect(service.isEnabled).toBe(false);
117118 });
118119 });
119-});
No newline at the end of the file
120+});
modified extensions/cli/src/test-helpers/__tests__/renderWithServices.test.tsx +3 −3
@@ -1,7 +1,7 @@
1-describe('renderWithServices', () => {
2- it('is tested through actual usage in component tests', () => {
1+describe("renderWithServices", () => {
2+ it("is tested through actual usage in component tests", () => {
33 // This utility is tested through its usage in real component tests
44 // rather than in isolation due to module mocking complexities
55 expect(true).toBe(true);
66 });
7-});
No newline at the end of the file
7+});
modified extensions/cli/src/test-helpers/__tests__/testServiceContainer.test.ts +69 −69
@@ -1,14 +1,14 @@
11 import { vi } from "vitest";
22
3-import { createTestServiceContainer } from '../testServiceContainer.js';
3+import { createTestServiceContainer } from "../testServiceContainer.js";
44
5-describe('TestServiceContainer', () => {
5+describe("TestServiceContainer", () => {
66 afterEach(() => {
77 vi.clearAllTimers();
88 });
9- it('should create a container with extended methods', () => {
9+ it("should create a container with extended methods", () => {
1010 const container = createTestServiceContainer();
11-
11+
1212 expect(container).toBeDefined();
1313 expect(container.resolveService).toBeDefined();
1414 expect(container.rejectService).toBeDefined();
@@ -16,108 +16,108 @@
1616 expect(container.waitForService).toBeDefined();
1717 });
1818
19- it('should allow controlled service resolution', async () => {
19+ it("should allow controlled service resolution", async () => {
2020 const container = createTestServiceContainer();
21-
21+
2222 // Register a service
23- container.register('test', () => Promise.resolve('should not resolve'));
24-
23+ container.register("test", () => Promise.resolve("should not resolve"));
24+
2525 // Load the service - this will create a pending promise
26- const loadPromise = container.load('test');
27-
26+ const loadPromise = container.load("test");
27+
2828 // Service should be in loading state
29- const state = container.getSync('test');
30- expect(state.state).toBe('loading');
31-
29+ const state = container.getSync("test");
30+ expect(state.state).toBe("loading");
31+
3232 // Resolve the service with our controlled value
33- container.resolveService('test', 'controlled value');
34-
33+ container.resolveService("test", "controlled value");
34+
3535 // Wait for the load promise to complete
3636 const loadedValue = await loadPromise;
37- expect(loadedValue).toBe('controlled value');
38-
37+ expect(loadedValue).toBe("controlled value");
38+
3939 // Check the resolved value
40- const result = container.getSync('test');
41- expect(result.state).toBe('ready');
42- expect(result.value).toBe('controlled value');
40+ const result = container.getSync("test");
41+ expect(result.state).toBe("ready");
42+ expect(result.value).toBe("controlled value");
4343 });
4444
45- it('should allow controlled service rejection', async () => {
45+ it("should allow controlled service rejection", async () => {
4646 const container = createTestServiceContainer();
47-
47+
4848 // Register a service
49- container.register('failing', () => Promise.resolve('should not resolve'));
50-
49+ container.register("failing", () => Promise.resolve("should not resolve"));
50+
5151 // Load the service and handle the rejection
52- const loadPromise = container.load('failing');
53-
52+ const loadPromise = container.load("failing");
53+
5454 // Reject the service
55- const error = new Error('Controlled failure');
56- container.rejectService('failing', error);
57-
55+ const error = new Error("Controlled failure");
56+ container.rejectService("failing", error);
57+
5858 // Expect the load promise to reject
59- await expect(loadPromise).rejects.toThrow('Controlled failure');
60-
59+ await expect(loadPromise).rejects.toThrow("Controlled failure");
60+
6161 // Check the error state
62- const result = container.getSync('failing');
63- expect(result.state).toBe('error');
62+ const result = container.getSync("failing");
63+ expect(result.state).toBe("error");
6464 expect(result.error).toBe(error);
6565 });
6666
67- it('should wait for multiple services', async () => {
67+ it("should wait for multiple services", async () => {
6868 const container = createTestServiceContainer();
69-
69+
7070 // Register multiple services
71- container.register('service1', () => Promise.resolve());
72- container.register('service2', () => Promise.resolve());
73- container.register('service3', () => Promise.resolve());
74-
71+ container.register("service1", () => Promise.resolve());
72+ container.register("service2", () => Promise.resolve());
73+ container.register("service3", () => Promise.resolve());
74+
7575 // Load all services
76- container.load('service1');
77- container.load('service2');
78- container.load('service3');
79-
76+ container.load("service1");
77+ container.load("service2");
78+ container.load("service3");
79+
8080 // Resolve them in different order
81- setTimeout(() => container.resolveService('service2', 'value2'), 10);
82- setTimeout(() => container.resolveService('service1', 'value1'), 20);
83- setTimeout(() => container.resolveService('service3', 'value3'), 30);
84-
81+ setTimeout(() => container.resolveService("service2", "value2"), 10);
82+ setTimeout(() => container.resolveService("service1", "value1"), 20);
83+ setTimeout(() => container.resolveService("service3", "value3"), 30);
84+
8585 // Wait for all to be ready
86- await container.waitForReady('service1', 'service2', 'service3');
87-
86+ await container.waitForReady("service1", "service2", "service3");
87+
8888 // All should be ready
89- expect(container.isReady('service1')).toBe(true);
90- expect(container.isReady('service2')).toBe(true);
91- expect(container.isReady('service3')).toBe(true);
89+ expect(container.isReady("service1")).toBe(true);
90+ expect(container.isReady("service2")).toBe(true);
91+ expect(container.isReady("service3")).toBe(true);
9292 });
9393
94- it('should handle pre-resolved services', () => {
94+ it("should handle pre-resolved services", () => {
9595 const container = createTestServiceContainer();
96-
96+
9797 // Register a service that resolves immediately
98- container.register('immediate', () => Promise.resolve('immediate value'));
99-
98+ container.register("immediate", () => Promise.resolve("immediate value"));
99+
100100 // The factory should be replaced with our controlled factory
101101 // So it should not resolve immediately
102- const state = container.getSync('immediate');
103- expect(state.state).toBe('idle');
102+ const state = container.getSync("immediate");
103+ expect(state.state).toBe("idle");
104104 });
105105
106- it('should support waitForService helper', async () => {
106+ it("should support waitForService helper", async () => {
107107 const container = createTestServiceContainer();
108-
108+
109109 // Register and load a service
110- container.register('async', () => Promise.resolve());
111- container.load('async');
112-
110+ container.register("async", () => Promise.resolve());
111+ container.load("async");
112+
113113 // Set up the wait before resolving
114- const waitPromise = container.waitForService('async');
115-
114+ const waitPromise = container.waitForService("async");
115+
116116 // Resolve the service
117- container.resolveService('async', 'async value');
118-
117+ container.resolveService("async", "async value");
118+
119119 // Wait should resolve with the value
120120 const value = await waitPromise;
121- expect(value).toBe('async value');
121+ expect(value).toBe("async value");
122122 });
123-});
No newline at the end of the file
123+});
modified extensions/cli/src/tools/edit.test.ts +16 −10
@@ -50,7 +50,7 @@
5050 };
5151
5252 await expect(editTool.preprocess!(args)).rejects.toThrow(
53- `You must use the Read tool to read ${testFilePath} before editing it.`
53+ `You must use the Read tool to read ${testFilePath} before editing it.`,
5454 );
5555 });
5656
@@ -66,7 +66,7 @@
6666 };
6767
6868 await expect(editTool.preprocess!(args)).rejects.toThrow(
69- `File ${nonExistentFile} does not exist`
69+ `File ${nonExistentFile} does not exist`,
7070 );
7171 });
7272
@@ -81,7 +81,7 @@
8181 };
8282
8383 await expect(editTool.preprocess!(args)).rejects.toThrow(
84- "String not found in file: Not found"
84+ "String not found in file: Not found",
8585 );
8686 });
8787
@@ -96,7 +96,7 @@
9696 };
9797
9898 await expect(editTool.preprocess!(args)).rejects.toThrow(
99- 'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.'
99+ 'String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
100100 );
101101 });
102102
@@ -110,7 +110,7 @@
110110 };
111111
112112 await expect(editTool.preprocess!(args)).rejects.toThrow(
113- "old_string and new_string must be different"
113+ "old_string and new_string must be different",
114114 );
115115 });
116116
@@ -154,7 +154,7 @@
154154 const result = await editTool.preprocess!(args);
155155
156156 expect(result.args.newContent).toBe(
157- "Hello universe\nThis is a test file\nGoodbye universe"
157+ "Hello universe\nThis is a test file\nGoodbye universe",
158158 );
159159 });
160160 });
@@ -170,8 +170,14 @@
170170
171171 const result = await editTool.run(args);
172172
173- expect(result).toBe(`Successfully edited ${testFilePath}\nDiff:\nmocked diff`);
174- expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8");
173+ expect(result).toBe(
174+ `Successfully edited ${testFilePath}\nDiff:\nmocked diff`,
175+ );
176+ expect(fs.writeFileSync).toHaveBeenCalledWith(
177+ testFilePath,
178+ newContent,
179+ "utf-8",
180+ );
175181 });
176182
177183 it("should throw error if file write fails", async () => {
@@ -186,7 +192,7 @@
186192 };
187193
188194 await expect(editTool.run(args)).rejects.toThrow(
189- `Error: failed to edit ${testFilePath}: Write failed`
195+ `Error: failed to edit ${testFilePath}: Write failed`,
190196 );
191197 });
192198 });
@@ -205,4 +211,4 @@
205211 expect(result.args.newContent).toContain("Hi there");
206212 });
207213 });
208-});
No newline at the end of the file
214+});
modified extensions/cli/src/tools/formatters.test.ts +11 −13
@@ -22,10 +22,10 @@
2222
2323 it("should format tool name with relative path argument", () => {
2424 expect(formatToolCall("Write", { filepath: "README.md" })).toBe(
25- "Write(README.md)"
25+ "Write(README.md)",
2626 );
2727 expect(formatToolCall("Read", { filepath: "src/index.ts" })).toBe(
28- "Read(src/index.ts)"
28+ "Read(src/index.ts)",
2929 );
3030 });
3131
@@ -33,26 +33,24 @@
3333 expect(
3434 formatToolCall("Write", {
3535 filepath: "/Users/test/project/README.md",
36- })
36+ }),
3737 ).toBe("Write(README.md)");
3838
3939 expect(
4040 formatToolCall("Read", {
4141 filepath: "/Users/test/project/src/components/App.tsx",
42- })
42+ }),
4343 ).toBe("Read(src/components/App.tsx)");
4444 });
4545
4646 it("should handle absolute paths outside the project", () => {
47- expect(
48- formatToolCall("Write", { filepath: "/Users/other/file.txt" })
49- ).toBe("Write(../../other/file.txt)");
47+ expect(formatToolCall("Write", { filepath: "/Users/other/file.txt" })).toBe(
48+ "Write(../../other/file.txt)",
49+ );
5050 });
5151
5252 it("should handle non-path arguments", () => {
53- expect(formatToolCall("Search", { pattern: "TODO" })).toBe(
54- "Search(TODO)"
55- );
53+ expect(formatToolCall("Search", { pattern: "TODO" })).toBe("Search(TODO)");
5654 expect(formatToolCall("Search", { pattern: 123 })).toBe("Search(123)");
5755 });
5856
@@ -61,7 +59,7 @@
6159 formatToolCall("Write", {
6260 filepath: "test.txt",
6361 content: "Hello world",
64- })
62+ }),
6563 ).toBe("Write(test.txt)");
6664 });
6765 });
@@ -82,10 +80,10 @@
8280
8381 it("should convert absolute paths to relative", () => {
8482 expect(formatToolArgument("/Users/test/project/README.md")).toBe(
85- "README.md"
83+ "README.md",
8684 );
8785 expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe(
88- "src/index.ts"
86+ "src/index.ts",
8987 );
9088 });
9189
modified extensions/cli/src/tools/multiEdit.test.ts +31 −19
@@ -54,7 +54,7 @@
5454 };
5555
5656 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
57- `You must use the Read tool to read ${testFilePath} before editing it.`
57+ `You must use the Read tool to read ${testFilePath} before editing it.`,
5858 );
5959 });
6060
@@ -74,7 +74,7 @@
7474 };
7575
7676 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
77- `File ${nonExistentFile} does not exist`
77+ `File ${nonExistentFile} does not exist`,
7878 );
7979 });
8080
@@ -87,7 +87,7 @@
8787 };
8888
8989 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
90- "edits array is required and must contain at least one edit"
90+ "edits array is required and must contain at least one edit",
9191 );
9292 });
9393
@@ -105,7 +105,7 @@
105105 };
106106
107107 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
108- "Edit 1: old_string is required"
108+ "Edit 1: old_string is required",
109109 );
110110 });
111111
@@ -123,7 +123,7 @@
123123 };
124124
125125 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
126- "Edit 1: new_string is required"
126+ "Edit 1: new_string is required",
127127 );
128128 });
129129
@@ -141,7 +141,7 @@
141141 };
142142
143143 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
144- "Edit 1: old_string and new_string must be different"
144+ "Edit 1: old_string and new_string must be different",
145145 );
146146 });
147147
@@ -160,7 +160,7 @@
160160 };
161161
162162 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
163- 'Edit 1: String not found in file: "Not found"'
163+ 'Edit 1: String not found in file: "Not found"',
164164 );
165165 });
166166
@@ -179,7 +179,7 @@
179179 };
180180
181181 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
182- 'Edit 1: String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.'
182+ 'Edit 1: String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
183183 );
184184 });
185185
@@ -236,7 +236,7 @@
236236 const result = await multiEditTool.preprocess!(args);
237237
238238 expect(result.args.newContent).toBe(
239- "Hi there\nThis is a test file\nSee you later"
239+ "Hi there\nThis is a test file\nSee you later",
240240 );
241241 expect(result.args.editCount).toBe(2);
242242 expect(result.preview?.[0]?.content).toContain("Will apply 2 edits");
@@ -259,7 +259,7 @@
259259 const result = await multiEditTool.preprocess!(args);
260260
261261 expect(result.args.newContent).toBe(
262- "Hello universe\nThis is a test file\nGoodbye universe"
262+ "Hello universe\nThis is a test file\nGoodbye universe",
263263 );
264264 });
265265
@@ -309,7 +309,7 @@
309309 const result = await multiEditTool.preprocess!(args);
310310
311311 expect(result.args.newContent).toBe(
312- "Greetings cosmos\nThis is a test file\nGoodbye world"
312+ "Greetings cosmos\nThis is a test file\nGoodbye world",
313313 );
314314 });
315315 });
@@ -327,8 +327,14 @@
327327
328328 const result = await multiEditTool.run(args);
329329
330- expect(result).toBe(`Successfully edited ${testFilePath} with 1 edit\nDiff:\nmocked diff`);
331- expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8");
330+ expect(result).toBe(
331+ `Successfully edited ${testFilePath} with 1 edit\nDiff:\nmocked diff`,
332+ );
333+ expect(fs.writeFileSync).toHaveBeenCalledWith(
334+ testFilePath,
335+ newContent,
336+ "utf-8",
337+ );
332338 });
333339
334340 it("should return correct message for multiple edits", async () => {
@@ -342,7 +348,9 @@
342348
343349 const result = await multiEditTool.run(args);
344350
345- expect(result).toBe(`Successfully edited ${testFilePath} with 3 edits\nDiff:\nmocked diff`);
351+ expect(result).toBe(
352+ `Successfully edited ${testFilePath} with 3 edits\nDiff:\nmocked diff`,
353+ );
346354 });
347355
348356 it("should return correct message for new file creation", async () => {
@@ -356,7 +364,9 @@
356364
357365 const result = await multiEditTool.run(args);
358366
359- expect(result).toBe(`Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`);
367+ expect(result).toBe(
368+ `Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`,
369+ );
360370 });
361371
362372 it("should throw error if file write fails", async () => {
@@ -373,7 +383,7 @@
373383 };
374384
375385 await expect(multiEditTool.run(args)).rejects.toThrow(
376- `Error: failed to edit ${testFilePath}: Write failed`
386+ `Error: failed to edit ${testFilePath}: Write failed`,
377387 );
378388 });
379389 });
@@ -397,7 +407,9 @@
397407 const result = await multiEditTool.preprocess!(args);
398408
399409 expect(result.args.file_path).toBe(absolutePath);
400- expect(result.args.newContent).toBe("Hi there\nThis is a test file\nGoodbye world");
410+ expect(result.args.newContent).toBe(
411+ "Hi there\nThis is a test file\nGoodbye world",
412+ );
401413 });
402414
403415 it("should handle relative paths with subdirectories", async () => {
@@ -462,7 +474,7 @@
462474 it("should handle relative path for new file creation", async () => {
463475 const relativePath = "new-file.txt";
464476 const absolutePath = path.resolve(process.cwd(), relativePath);
465-
477+
466478 vi.mocked(fs.existsSync).mockImplementation((path) => {
467479 // Parent directory (cwd) exists, but file doesn't
468480 if (path === process.cwd()) return true;
@@ -506,4 +518,4 @@
506518 expect(result.args.newContent).toContain("Hi there");
507519 });
508520 });
509-});
No newline at the end of the file
521+});
modified extensions/cli/src/tools/preprocess.test.ts +6 −6
@@ -1,7 +1,7 @@
11 import * as fs from "fs";
22
33 import * as diff from "diff";
4-import { describe, it, expect, beforeEach, vi } from 'vitest';
4+import { describe, it, expect, beforeEach, vi } from "vitest";
55
66 // Mock fs module
77 vi.mock("fs", async () => {
@@ -397,7 +397,7 @@
397397 };
398398
399399 await expect(
400- searchAndReplaceInFileTool.preprocess!(args)
400+ searchAndReplaceInFileTool.preprocess!(args),
401401 ).rejects.toThrowError(/file .* does not exist/);
402402 });
403403
@@ -411,9 +411,9 @@
411411 };
412412
413413 await expect(
414- searchAndReplaceInFileTool.preprocess!(args)
414+ searchAndReplaceInFileTool.preprocess!(args),
415415 ).rejects.toThrowError(
416- "No complete search/replace blocks found in any diffs"
416+ "No complete search/replace blocks found in any diffs",
417417 );
418418 });
419419
@@ -433,7 +433,7 @@
433433 };
434434
435435 await expect(
436- searchAndReplaceInFileTool.preprocess!(args)
436+ searchAndReplaceInFileTool.preprocess!(args),
437437 ).rejects.toThrowError(/Search content not found in block 1:/);
438438 });
439439
@@ -461,7 +461,7 @@
461461 const result = await searchAndReplaceInFileTool.preprocess!(args);
462462
463463 expect(result.args.newContent).toBe(
464- "modified line 1\nline 2\nmodified line 3\nline 4"
464+ "modified line 1\nline 2\nmodified line 3\nline 4",
465465 );
466466 });
467467 });
modified extensions/cli/src/tools/runTerminalCommand.test.ts +118 −83
@@ -2,9 +2,9 @@
22
33 describe("runTerminalCommandTool", () => {
44 const TEST_TIMEOUT_MS = 1000; // 1 second for tests
5-
5+
66 beforeAll(() => {
7- process.env.NODE_ENV = 'test';
7+ process.env.NODE_ENV = "test";
88 process.env.TEST_TERMINAL_TIMEOUT = String(TEST_TIMEOUT_MS);
99 });
1010
@@ -13,7 +13,9 @@
1313 });
1414 describe("basic command execution", () => {
1515 it("should execute simple echo command and return stdout", async () => {
16- const result = await runTerminalCommandTool.run({ command: "echo 'hello world'" });
16+ const result = await runTerminalCommandTool.run({
17+ command: "echo 'hello world'",
18+ });
1719 expect(result.trim()).toBe("hello world");
1820 });
1921
@@ -24,11 +26,11 @@
2426
2527 it("should execute directory listing command and return file listings", async () => {
2628 // Use a cross-platform command that works on both Unix and Windows
27- const command = process.platform === 'win32' ? 'dir' : 'ls -la .';
29+ const command = process.platform === "win32" ? "dir" : "ls -la .";
2830 const result = await runTerminalCommandTool.run({ command });
29-
31+
3032 // On Windows, look for <DIR> entries, on Unix look for . and ..
31- if (process.platform === 'win32') {
33+ if (process.platform === "win32") {
3234 expect(result).toContain(".");
3335 } else {
3436 expect(result).toContain(".");
@@ -37,99 +39,131 @@
3739 });
3840
3941 it("should handle commands with multiple arguments", async () => {
40- const result = await runTerminalCommandTool.run({ command: "echo 'arg1' 'arg2' 'arg3'" });
42+ const result = await runTerminalCommandTool.run({
43+ command: "echo 'arg1' 'arg2' 'arg3'",
44+ });
4145 expect(result.trim()).toBe("arg1 arg2 arg3");
4246 });
4347 });
4448
4549 describe("error handling", () => {
4650 it("should reject with error message for non-existent commands", async () => {
47- await expect(runTerminalCommandTool.run({ command: "nonexistentcommand12345" }))
48- .rejects.toMatch(/Error \(exit code 127\):/);
51+ await expect(
52+ runTerminalCommandTool.run({ command: "nonexistentcommand12345" }),
53+ ).rejects.toMatch(/Error \(exit code 127\):/);
4954 });
5055
5156 it("should handle commands with non-zero exit codes and stderr", async () => {
52- await expect(runTerminalCommandTool.run({ command: "sh -c 'echo error >&2; exit 1'" }))
53- .rejects.toMatch(/Error \(exit code 1\): error/);
57+ await expect(
58+ runTerminalCommandTool.run({
59+ command: "sh -c 'echo error >&2; exit 1'",
60+ }),
61+ ).rejects.toMatch(/Error \(exit code 1\): error/);
5462 });
5563
5664 it("should resolve when commands have non-zero exit codes but no stderr", async () => {
57- const result = await runTerminalCommandTool.run({ command: "sh -c 'exit 1'" });
65+ const result = await runTerminalCommandTool.run({
66+ command: "sh -c 'exit 1'",
67+ });
5868 expect(result).toBe("");
5969 });
6070
6171 it("should handle commands that write to stderr", async () => {
62- const result = await runTerminalCommandTool.run({ command: "sh -c 'echo \"error message\" >&2; echo \"success\"'" });
72+ const result = await runTerminalCommandTool.run({
73+ command: 'sh -c \'echo "error message" >&2; echo "success"\'',
74+ });
6375 expect(result).toContain("success");
6476 expect(result).toContain("Stderr: error message");
6577 });
6678 });
6779
6880 describe("timeout functionality", () => {
69- it("should timeout commands that produce no output for configured duration", async () => {
70- // Create a command that sleeps longer than the timeout
71- const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep 0.5s longer than timeout
72- const startTime = Date.now();
73- const result = await runTerminalCommandTool.run({ command: `sleep ${sleepDuration}` });
74- const endTime = Date.now();
75- const elapsed = endTime - startTime;
76-
77- // Should timeout within a reasonable margin of the configured timeout
78- expect(elapsed).toBeLessThan(TEST_TIMEOUT_MS + 200); // Allow 200ms margin
79- expect(elapsed).toBeGreaterThan(TEST_TIMEOUT_MS - 100); // Allow 100ms margin
80- expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`);
81- }, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer
82-
83- it("should not timeout commands that continuously produce output", async () => {
84- // Create a command that produces output at intervals shorter than timeout
85- const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
86- const iterations = 3;
87- const startTime = Date.now();
88- const result = await runTerminalCommandTool.run({
89- command: `for i in $(seq 1 ${iterations}); do echo "output $i"; sleep ${outputInterval}; done`
90- });
91- const endTime = Date.now();
92-
93- // Should complete normally
94- expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
95- expect(result).toContain("output 1");
96- expect(result).toContain(`output ${iterations}`);
97- expect(result).not.toContain("[Command timed out");
98- }, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer
99-
100- it("should reset timeout when command produces stderr output", async () => {
101- // Create a command that produces stderr output periodically
102- const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
103- const iterations = 3;
104- const startTime = Date.now();
105- const result = await runTerminalCommandTool.run({
106- command: `for i in $(seq 1 ${iterations}); do echo "error $i" >&2; sleep ${outputInterval}; done; echo 'done'`
107- });
108- const endTime = Date.now();
109-
110- // Should complete normally
111- expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
112- expect(result).toContain("done");
113- expect(result).toContain("Stderr: error 1");
114- expect(result).not.toContain("[Command timed out");
115- }, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer
116-
117- it("should include partial output when timing out", async () => {
118- // Create a command that produces some output then stops
119- const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep longer than timeout
120- const result = await runTerminalCommandTool.run({
121- command: `echo 'initial output'; sleep ${sleepDuration}`
122- });
123-
124- expect(result).toContain("initial output");
125- expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`);
126- }, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer
81+ it(
82+ "should timeout commands that produce no output for configured duration",
83+ async () => {
84+ // Create a command that sleeps longer than the timeout
85+ const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep 0.5s longer than timeout
86+ const startTime = Date.now();
87+ const result = await runTerminalCommandTool.run({
88+ command: `sleep ${sleepDuration}`,
89+ });
90+ const endTime = Date.now();
91+ const elapsed = endTime - startTime;
92+
93+ // Should timeout within a reasonable margin of the configured timeout
94+ expect(elapsed).toBeLessThan(TEST_TIMEOUT_MS + 200); // Allow 200ms margin
95+ expect(elapsed).toBeGreaterThan(TEST_TIMEOUT_MS - 100); // Allow 100ms margin
96+ expect(result).toContain(
97+ `[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`,
98+ );
99+ },
100+ TEST_TIMEOUT_MS + 2000,
101+ ); // Set test timeout with buffer
102+
103+ it(
104+ "should not timeout commands that continuously produce output",
105+ async () => {
106+ // Create a command that produces output at intervals shorter than timeout
107+ const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
108+ const iterations = 3;
109+ const startTime = Date.now();
110+ const result = await runTerminalCommandTool.run({
111+ command: `for i in $(seq 1 ${iterations}); do echo "output $i"; sleep ${outputInterval}; done`,
112+ });
113+ const endTime = Date.now();
114+
115+ // Should complete normally
116+ expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
117+ expect(result).toContain("output 1");
118+ expect(result).toContain(`output ${iterations}`);
119+ expect(result).not.toContain("[Command timed out");
120+ },
121+ TEST_TIMEOUT_MS * 3,
122+ ); // Set test timeout with buffer
123+
124+ it(
125+ "should reset timeout when command produces stderr output",
126+ async () => {
127+ // Create a command that produces stderr output periodically
128+ const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
129+ const iterations = 3;
130+ const startTime = Date.now();
131+ const result = await runTerminalCommandTool.run({
132+ command: `for i in $(seq 1 ${iterations}); do echo "error $i" >&2; sleep ${outputInterval}; done; echo 'done'`,
133+ });
134+ const endTime = Date.now();
135+
136+ // Should complete normally
137+ expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
138+ expect(result).toContain("done");
139+ expect(result).toContain("Stderr: error 1");
140+ expect(result).not.toContain("[Command timed out");
141+ },
142+ TEST_TIMEOUT_MS * 3,
143+ ); // Set test timeout with buffer
144+
145+ it(
146+ "should include partial output when timing out",
147+ async () => {
148+ // Create a command that produces some output then stops
149+ const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep longer than timeout
150+ const result = await runTerminalCommandTool.run({
151+ command: `echo 'initial output'; sleep ${sleepDuration}`,
152+ });
153+
154+ expect(result).toContain("initial output");
155+ expect(result).toContain(
156+ `[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`,
157+ );
158+ },
159+ TEST_TIMEOUT_MS + 2000,
160+ ); // Set test timeout with buffer
127161 });
128162
129163 describe("output handling", () => {
130164 it("should preserve line breaks in output", async () => {
131- const result = await runTerminalCommandTool.run({
132- command: "printf 'line1\\nline2\\nline3'"
165+ const result = await runTerminalCommandTool.run({
166+ command: "printf 'line1\\nline2\\nline3'",
133167 });
134168 expect(result).toContain("line1\nline2\nline3");
135169 });
@@ -141,13 +175,13 @@
141175
142176 it("should handle large output", async () => {
143177 // Generate a command that produces substantial output
144- const result = await runTerminalCommandTool.run({
145- command: "seq 1 1000"
178+ const result = await runTerminalCommandTool.run({
179+ command: "seq 1 1000",
146180 });
147181 expect(result).toContain("1\n");
148182 expect(result).toContain("1000");
149183 // Count lines to ensure all output is captured
150- const lines = result.trim().split('\n');
184+ const lines = result.trim().split("\n");
151185 expect(lines).toHaveLength(1000);
152186 });
153187 });
@@ -159,24 +193,25 @@
159193 });
160194
161195 it("should handle commands with pipes", async () => {
162- const result = await runTerminalCommandTool.run({
163- command: "echo 'hello world' | wc -w"
196+ const result = await runTerminalCommandTool.run({
197+ command: "echo 'hello world' | wc -w",
164198 });
165199 expect(result.trim()).toBe("2");
166200 });
167201
168202 it("should handle commands with redirections", async () => {
169- const result = await runTerminalCommandTool.run({
170- command: "echo 'test' > /tmp/test-file && cat /tmp/test-file && rm /tmp/test-file"
203+ const result = await runTerminalCommandTool.run({
204+ command:
205+ "echo 'test' > /tmp/test-file && cat /tmp/test-file && rm /tmp/test-file",
171206 });
172207 expect(result.trim()).toBe("test");
173208 });
174209
175210 it("should handle commands with environment variables", async () => {
176- const result = await runTerminalCommandTool.run({
177- command: "TEST_VAR='hello' sh -c 'echo $TEST_VAR'"
211+ const result = await runTerminalCommandTool.run({
212+ command: "TEST_VAR='hello' sh -c 'echo $TEST_VAR'",
178213 });
179214 expect(result.trim()).toBe("hello");
180215 });
181216 });
182-});
No newline at the end of the file
217+});
modified extensions/cli/src/tools/searchCode.test.ts +25 −22
@@ -1,51 +1,54 @@
1-
21 // Since we want to test just the interface and not the internals,
32 // let's create a simplified version of the run function to test the truncation logic
43 describe("searchCodeTool", () => {
54 // We'll test the functionality without mocking the dependencies
6- // Instead, we'll focus on the core truncation logic by directly checking
5+ // Instead, we'll focus on the core truncation logic by directly checking
76 // if truncation happens with large outputs
87
98 it("should include truncation message when output exceeds limit", () => {
109 // Create a large sample output (more than 100 lines)
11- const largeOutput = Array.from({ length: 150 }, (_, i) =>
12- `file${i}.ts:${i}:const foo = 'bar';`
10+ const largeOutput = Array.from(
11+ { length: 150 },
12+ (_, i) => `file${i}.ts:${i}:const foo = 'bar';`,
1313 ).join("\n");
14-
14+
1515 // Check if the truncation logic is applied by the function
16- const truncatedOutput = `Search results for pattern "foo":\n\n${largeOutput.split('\n').slice(0, 100).join('\n')}\n\n[Results truncated: showing 100 of 150 matches]`;
17-
16+ const truncatedOutput = `Search results for pattern "foo":\n\n${largeOutput.split("\n").slice(0, 100).join("\n")}\n\n[Results truncated: showing 100 of 150 matches]`;
17+
1818 // Verify the truncation message is included and only 100 lines are shown
19- const lines = truncatedOutput.split('\n');
20- const nonEmptyLines = lines.filter(line => line.trim() !== '');
21-
19+ const lines = truncatedOutput.split("\n");
20+ const nonEmptyLines = lines.filter((line) => line.trim() !== "");
21+
2222 // Count the content lines (excluding header and truncation message)
2323 const contentLines = nonEmptyLines.slice(1, -1);
24-
24+
2525 // Check that we have exactly 100 content lines
2626 expect(contentLines.length).toBe(100);
27-
27+
2828 // Check that the truncation message is present
29- expect(truncatedOutput).toContain("[Results truncated: showing 100 of 150 matches]");
29+ expect(truncatedOutput).toContain(
30+ "[Results truncated: showing 100 of 150 matches]",
31+ );
3032 });
3133
3234 it("should not include truncation message when output is within limit", () => {
3335 // Create a sample output (less than 100 lines)
34- const smallOutput = Array.from({ length: 50 }, (_, i) =>
35- `file${i}.ts:${i}:const foo = 'bar';`
36+ const smallOutput = Array.from(
37+ { length: 50 },
38+ (_, i) => `file${i}.ts:${i}:const foo = 'bar';`,
3639 ).join("\n");
37-
40+
3841 // Format the output as the function would
3942 const output = `Search results for pattern "foo":\n\n${smallOutput}`;
40-
43+
4144 // Verify no truncation message is included
4245 expect(output).not.toContain("[Results truncated:");
43-
46+
4447 // Count the lines
45- const lines = output.split('\n');
46- const nonEmptyLines = lines.filter(line => line.trim() !== '');
47-
48+ const lines = output.split("\n");
49+ const nonEmptyLines = lines.filter((line) => line.trim() !== "");
50+
4851 // Check that we have the expected number of lines (header + 50 content lines)
4952 expect(nonEmptyLines.length).toBe(51);
5053 });
51-});
No newline at the end of the file
54+});
modified extensions/cli/src/ui/ColoredDiff.test.ts +52 −28
@@ -11,10 +11,12 @@
1111 return "world";
1212 }`;
1313
14- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
14+ const { lastFrame } = render(
15+ React.createElement(ColoredDiff, { diffContent }),
16+ );
1517 const frame = lastFrame();
1618
17- expect(frame).toContain("console.log(\"added line\")");
19+ expect(frame).toContain('console.log("added line")');
1820 expect(frame).toContain("+");
1921 });
2022
@@ -25,10 +27,12 @@
2527 return "world";
2628 }`;
2729
28- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
30+ const { lastFrame } = render(
31+ React.createElement(ColoredDiff, { diffContent }),
32+ );
2933 const frame = lastFrame();
3034
31- expect(frame).toContain("console.log(\"removed line\")");
35+ expect(frame).toContain('console.log("removed line")');
3236 expect(frame).toContain("-");
3337 });
3438
@@ -40,11 +44,13 @@
4044 return "world";
4145 }`;
4246
43- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
47+ const { lastFrame } = render(
48+ React.createElement(ColoredDiff, { diffContent }),
49+ );
4450 const frame = lastFrame();
4551
4652 expect(frame).toContain("function hello()");
47- expect(frame).toContain("return \"world\"");
53+ expect(frame).toContain('return "world"');
4854 });
4955
5056 it("renders word-level diffs for modified lines", () => {
@@ -54,18 +60,22 @@
5460 + return "new text";
5561 }`;
5662
57- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
63+ const { lastFrame } = render(
64+ React.createElement(ColoredDiff, { diffContent }),
65+ );
5866 const frame = lastFrame();
5967
60- expect(frame).toContain("return \"");
61- expect(frame).toContain("text\"");
68+ expect(frame).toContain('return "');
69+ expect(frame).toContain('text"');
6270 // Should show both old and new versions for word-level diff
6371 expect(frame).toContain("-");
6472 expect(frame).toContain("+");
6573 });
6674
6775 it("handles empty diff content", () => {
68- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent: "" }));
76+ const { lastFrame } = render(
77+ React.createElement(ColoredDiff, { diffContent: "" }),
78+ );
6979 const frame = lastFrame();
7080
7181 expect(frame).toContain("No changes detected");
@@ -73,13 +83,17 @@
7383
7484 it("truncates long diffs", () => {
7585 // Create a diff with more than 16 lines
76- const lines = Array.from({ length: 20 }, (_, i) => `+ line ${i + 1}`).join('\n');
86+ const lines = Array.from({ length: 20 }, (_, i) => `+ line ${i + 1}`).join(
87+ "\n",
88+ );
7789 const diffContent = `@@ -1,1 +1,20 @@
7890 function hello() {
7991 ${lines}
8092 }`;
8193
82- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
94+ const { lastFrame } = render(
95+ React.createElement(ColoredDiff, { diffContent }),
96+ );
8397 const frame = lastFrame();
8498
8599 expect(frame).toContain("more lines");
@@ -95,13 +109,15 @@
95109 return x + y;
96110 }`;
97111
98- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
112+ const { lastFrame } = render(
113+ React.createElement(ColoredDiff, { diffContent }),
114+ );
99115 const frame = lastFrame();
100116
101117 // Should render word-level diffs
102- expect(frame).toContain("const x = \"");
103- expect(frame).toContain("value\"");
104- expect(frame).toContain("const y = \"another");
118+ expect(frame).toContain('const x = "');
119+ expect(frame).toContain('value"');
120+ expect(frame).toContain('const y = "another');
105121 });
106122
107123 it("handles single-type changes without word-level diffing", () => {
@@ -112,12 +128,14 @@
112128 return "world";
113129 }`;
114130
115- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
131+ const { lastFrame } = render(
132+ React.createElement(ColoredDiff, { diffContent }),
133+ );
116134 const frame = lastFrame();
117135
118136 // Should render as normal line additions, not word-level
119- expect(frame).toContain("console.log(\"new line 1\")");
120- expect(frame).toContain("console.log(\"new line 2\")");
137+ expect(frame).toContain('console.log("new line 1")');
138+ expect(frame).toContain('console.log("new line 2")');
121139 expect(frame).toContain("+");
122140 });
123141
@@ -128,7 +146,9 @@
128146 + return "new text";
129147 }`;
130148
131- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
149+ const { lastFrame } = render(
150+ React.createElement(ColoredDiff, { diffContent }),
151+ );
132152 const frame = lastFrame();
133153
134154 // Extract just the line numbers and content, ignoring colors/styling
@@ -136,8 +156,8 @@
136156 expect(frame).toContain("function hello()");
137157 expect(frame).toContain("- ");
138158 expect(frame).toContain("+ ");
139- expect(frame).toContain("return \"");
140- expect(frame).toContain("text\"");
159+ expect(frame).toContain('return "');
160+ expect(frame).toContain('text"');
141161
142162 // Verify we have both old and new text content
143163 // Word-level diff splits these into separate words
@@ -156,20 +176,22 @@
156176 +const y = "hello universe";
157177 const z = 3;`;
158178
159- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
179+ const { lastFrame } = render(
180+ React.createElement(ColoredDiff, { diffContent }),
181+ );
160182 const frame = lastFrame();
161183
162184 // All original text should be preserved
163185 expect(frame).toContain("const x = 1");
164186 expect(frame).toContain("const z = 3");
165-
187+
166188 // Both old and new versions should be shown
167189 // Word-level diff splits these into separate words
168190 expect(frame).toContain("hello");
169191 expect(frame).toContain("world");
170192 expect(frame).toContain("universe");
171- expect(frame).toContain("const y = \"");
172-
193+ expect(frame).toContain('const y = "');
194+
173195 // Should have proper line prefixes
174196 expect(frame).toContain("- ");
175197 expect(frame).toContain("+ ");
@@ -184,7 +206,9 @@
184206 + return result.data;
185207 }`;
186208
187- const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
209+ const { lastFrame } = render(
210+ React.createElement(ColoredDiff, { diffContent }),
211+ );
188212 const frame = lastFrame();
189213
190214 // Check that all unique content appears
@@ -204,4 +228,4 @@
204228 expect(frame).toContain("- ");
205229 expect(frame).toContain("+ ");
206230 });
207-});
No newline at the end of the file
231+});
modified extensions/cli/src/ui/MarkdownRenderer.test.tsx +3 −3
@@ -132,13 +132,13 @@
132132
133133 it("handles headings with multiple words", () => {
134134 const result = renderMarkdown(
135- "# This is a long heading with multiple words"
135+ "# This is a long heading with multiple words",
136136 );
137137 expect(result.length).toBe(1);
138138 expect(React.isValidElement(result[0])).toBe(true);
139139 expect((result[0] as any).props.bold).toBe(true);
140140 expect((result[0] as any).props.children).toBe(
141- "This is a long heading with multiple words"
141+ "This is a long heading with multiple words",
142142 );
143143 });
144144
@@ -183,7 +183,7 @@
183183
184184 it("handles code blocks mixed with other formatting", () => {
185185 const result = renderMarkdown(
186- "Here's some code:\n```\nfunction test() {\n return 42;\n}\n```\nAnd **bold** text"
186+ "Here's some code:\n```\nfunction test() {\n return 42;\n}\n```\nAnd **bold** text",
187187 );
188188 expect(result.length).toBe(5);
189189 expect(result[0]).toBe("Here's some code:\n");
modified extensions/cli/src/ui/ModelCapabilityWarning.test.tsx +27 −21
@@ -1,43 +1,49 @@
1-import { render } from 'ink-testing-library';
2-import React from 'react';
3-import { describe, expect, test } from 'vitest';
1+import { render } from "ink-testing-library";
2+import React from "react";
3+import { describe, expect, test } from "vitest";
44
5-import { ModelCapabilityWarning } from './ModelCapabilityWarning.js';
5+import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js";
66
7-describe('ModelCapabilityWarning', () => {
8- test('should render warning message with model name', () => {
7+describe("ModelCapabilityWarning", () => {
8+ test("should render warning message with model name", () => {
99 const { lastFrame } = render(
10- React.createElement(ModelCapabilityWarning, { modelName: 'gpt-3-davinci' })
10+ React.createElement(ModelCapabilityWarning, {
11+ modelName: "gpt-3-davinci",
12+ }),
1113 );
12-
14+
1315 const frame = lastFrame();
1416 if (frame) {
15- expect(frame).toContain('Model Capability Warning');
16- expect(frame).toContain('gpt-3-davinci');
17- expect(frame).toContain('is not recommended for use with cn due to limited reasoning and tool');
18- expect(frame).toContain('calling capabilities');
17+ expect(frame).toContain("Model Capability Warning");
18+ expect(frame).toContain("gpt-3-davinci");
19+ expect(frame).toContain(
20+ "is not recommended for use with cn due to limited reasoning and tool",
21+ );
22+ expect(frame).toContain("calling capabilities");
1923 }
2024 });
2125
22- test('should handle model names with slashes', () => {
26+ test("should handle model names with slashes", () => {
2327 const { lastFrame } = render(
24- React.createElement(ModelCapabilityWarning, { modelName: 'local/mistral-7b' })
28+ React.createElement(ModelCapabilityWarning, {
29+ modelName: "local/mistral-7b",
30+ }),
2531 );
26-
32+
2733 const frame = lastFrame();
2834 if (frame) {
29- expect(frame).toContain('local/mistral-7b');
35+ expect(frame).toContain("local/mistral-7b");
3036 }
3137 });
3238
33- test('should display warning icon', () => {
39+ test("should display warning icon", () => {
3440 const { lastFrame } = render(
35- React.createElement(ModelCapabilityWarning, { modelName: 'test-model' })
41+ React.createElement(ModelCapabilityWarning, { modelName: "test-model" }),
3642 );
37-
43+
3844 const frame = lastFrame();
3945 if (frame) {
40- expect(frame).toContain('⚠️');
46+ expect(frame).toContain("⚠️");
4147 }
4248 });
43-});
No newline at the end of the file
49+});
modified extensions/cli/src/ui/SessionSelector.test.tsx +14 −20
@@ -1,10 +1,4 @@
1-import {
2- subDays,
3- subMonths,
4- subYears,
5- startOfDay,
6- addHours
7-} from "date-fns";
1+import { subDays, subMonths, subYears, startOfDay, addHours } from "date-fns";
82 import { render } from "ink-testing-library";
93 import React from "react";
104 import { describe, expect, it, vi, beforeEach } from "vitest";
@@ -38,7 +32,7 @@
3832 firstUserMessage: "Today's session",
3933 },
4034 {
41- id: "session-2",
35+ id: "session-2",
4236 path: "/test/session-2.json",
4337 timestamp: yesterday,
4438 messageCount: 5,
@@ -47,7 +41,7 @@
4741 {
4842 id: "session-3",
4943 path: "/test/session-3.json",
50- timestamp: thisWeek,
44+ timestamp: thisWeek,
5145 messageCount: 8,
5246 firstUserMessage: "This week's session",
5347 },
@@ -56,7 +50,7 @@
5650 path: "/test/session-4.json",
5751 timestamp: thisYear,
5852 messageCount: 12,
59- firstUserMessage: "This year's session",
53+ firstUserMessage: "This year's session",
6054 },
6155 {
6256 id: "session-5",
@@ -68,35 +62,35 @@
6862 ];
6963
7064 const { lastFrame } = render(
71- <SessionSelector
65+ <SessionSelector
7266 sessions={sessions}
7367 onSelect={mockOnSelect}
7468 onExit={mockOnExit}
75- />
69+ />,
7670 );
7771
7872 // Check that the output contains expected date formats
7973 expect(lastFrame()).toContain("2:00 PM"); // Today should show time
8074 expect(lastFrame()).toContain("yesterday"); // Yesterday should show "yesterday"
81-
75+
8276 // This week should show day name (we can't predict exact day without knowing when test runs)
8377 // but we can check it doesn't contain "ago" which was the old format
8478 expect(lastFrame()).not.toContain("days ago");
85-
79+
8680 // This year should show month/day format like "Oct 18" (no "ago")
8781 expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}/); // MMM d format
88-
82+
8983 // Last year should include the year
9084 expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}, \d{4}/); // MMM d, yyyy format
9185 });
9286
9387 it("handles empty sessions gracefully", () => {
9488 const { lastFrame } = render(
95- <SessionSelector
89+ <SessionSelector
9690 sessions={[]}
9791 onSelect={mockOnSelect}
9892 onExit={mockOnExit}
99- />
93+ />,
10094 );
10195
10296 expect(lastFrame()).toContain("No previous sessions found");
@@ -115,13 +109,13 @@
115109 ];
116110
117111 const { lastFrame } = render(
118- <SessionSelector
112+ <SessionSelector
119113 sessions={sessions}
120114 onSelect={mockOnSelect}
121115 onExit={mockOnExit}
122- />
116+ />,
123117 );
124118
125119 expect(lastFrame()).toContain("(no messages)");
126120 });
127-});
No newline at the end of the file
121+});
modified extensions/cli/src/ui/SyntaxHighlighter.test.ts +62 −62
@@ -1,186 +1,186 @@
1-import { detectLanguage } from './SyntaxHighlighter.js';
1+import { detectLanguage } from "./SyntaxHighlighter.js";
22
3-describe('detectLanguage', () => {
4- it('should detect JavaScript from import statements', () => {
3+describe("detectLanguage", () => {
4+ it("should detect JavaScript from import statements", () => {
55 const code = `import React from 'react';`;
6- expect(detectLanguage(code)).toBe('javascript');
6+ expect(detectLanguage(code)).toBe("javascript");
77 });
88
9- it('should detect JavaScript from require statements', () => {
9+ it("should detect JavaScript from require statements", () => {
1010 const code = `const fs = require('fs');`;
11- expect(detectLanguage(code)).toBe('javascript');
11+ expect(detectLanguage(code)).toBe("javascript");
1212 });
1313
14- it('should detect JavaScript from function declarations', () => {
14+ it("should detect JavaScript from function declarations", () => {
1515 const code = `function myFunction() { return true; }`;
16- expect(detectLanguage(code)).toBe('javascript');
16+ expect(detectLanguage(code)).toBe("javascript");
1717 });
1818
19- it('should detect TypeScript from interface declarations', () => {
19+ it("should detect TypeScript from interface declarations", () => {
2020 const code = `interface User { name: string; }`;
21- expect(detectLanguage(code)).toBe('typescript');
21+ expect(detectLanguage(code)).toBe("typescript");
2222 });
2323
24- it('should detect TypeScript from type declarations', () => {
24+ it("should detect TypeScript from type declarations", () => {
2525 const code = `type UserType = { name: string; };`;
26- expect(detectLanguage(code)).toBe('typescript');
26+ expect(detectLanguage(code)).toBe("typescript");
2727 });
2828
29- it('should detect Python from function definitions', () => {
29+ it("should detect Python from function definitions", () => {
3030 const code = `def my_function():
3131 return True`;
32- expect(detectLanguage(code)).toBe('python');
32+ expect(detectLanguage(code)).toBe("python");
3333 });
3434
35- it('should detect Python from class definitions', () => {
35+ it("should detect Python from class definitions", () => {
3636 const code = `class MyClass:
3737 def __init__(self):
3838 pass`;
39- expect(detectLanguage(code)).toBe('python');
39+ expect(detectLanguage(code)).toBe("python");
4040 });
4141
42- it('should detect Java from public class declarations', () => {
42+ it("should detect Java from public class declarations", () => {
4343 const code = `public class MyClass {
4444 public static void main(String[] args) {
4545 }
4646 }`;
47- expect(detectLanguage(code)).toBe('java');
47+ expect(detectLanguage(code)).toBe("java");
4848 });
4949
50- it('should detect C from include statements', () => {
50+ it("should detect C from include statements", () => {
5151 const code = `#include <stdio.h>
5252 int main() {
5353 return 0;
5454 }`;
55- expect(detectLanguage(code)).toBe('c');
55+ expect(detectLanguage(code)).toBe("c");
5656 });
5757
58- it('should detect C++ from using namespace', () => {
58+ it("should detect C++ from using namespace", () => {
5959 const code = `using namespace std;
6060 int main() {
6161 return 0;
6262 }`;
63- expect(detectLanguage(code)).toBe('cpp');
63+ expect(detectLanguage(code)).toBe("cpp");
6464 });
6565
66- it('should detect C# from using System', () => {
66+ it("should detect C# from using System", () => {
6767 const code = `using System;
6868 public class Program {
6969 public static void Main() {
7070 }
7171 }`;
72- expect(detectLanguage(code)).toBe('csharp');
72+ expect(detectLanguage(code)).toBe("csharp");
7373 });
7474
75- it('should detect Go from package main', () => {
75+ it("should detect Go from package main", () => {
7676 const code = `package main
7777 import "fmt"
7878 func main() {
7979 fmt.Println("Hello, World!")
8080 }`;
81- expect(detectLanguage(code)).toBe('go');
81+ expect(detectLanguage(code)).toBe("go");
8282 });
8383
84- it('should detect Rust from function syntax', () => {
84+ it("should detect Rust from function syntax", () => {
8585 const code = `fn main() {
8686 println!("Hello, World!");
8787 }`;
88- expect(detectLanguage(code)).toBe('rust');
88+ expect(detectLanguage(code)).toBe("rust");
8989 });
9090
91- it('should detect PHP from opening tag', () => {
91+ it("should detect PHP from opening tag", () => {
9292 const code = `<?php
9393 echo "Hello, World!";
9494 ?>`;
95- expect(detectLanguage(code)).toBe('php');
95+ expect(detectLanguage(code)).toBe("php");
9696 });
9797
98- it('should detect SQL from SELECT statements', () => {
98+ it("should detect SQL from SELECT statements", () => {
9999 const code = `SELECT * FROM users WHERE id = 1;`;
100- expect(detectLanguage(code)).toBe('sql');
100+ expect(detectLanguage(code)).toBe("sql");
101101 });
102102
103- it('should detect SQL with case insensitive matching', () => {
103+ it("should detect SQL with case insensitive matching", () => {
104104 const code = `select name from users where active = true;`;
105- expect(detectLanguage(code)).toBe('sql');
105+ expect(detectLanguage(code)).toBe("sql");
106106 });
107107
108- it('should detect JSON from object syntax', () => {
108+ it("should detect JSON from object syntax", () => {
109109 const code = `{
110110 "name": "John",
111111 "age": 30
112112 }`;
113- expect(detectLanguage(code)).toBe('json');
113+ expect(detectLanguage(code)).toBe("json");
114114 });
115115
116- it('should detect bash from shebang', () => {
116+ it("should detect bash from shebang", () => {
117117 const code = `#!/bin/bash
118118 echo "Hello, World!"`;
119- expect(detectLanguage(code)).toBe('bash');
119+ expect(detectLanguage(code)).toBe("bash");
120120 });
121121
122- it('should detect HTML from DOCTYPE', () => {
122+ it("should detect HTML from DOCTYPE", () => {
123123 const code = `<!DOCTYPE html>
124124 <html>
125125 <head>
126126 <title>Test</title>
127127 </head>
128128 </html>`;
129- expect(detectLanguage(code)).toBe('html');
129+ expect(detectLanguage(code)).toBe("html");
130130 });
131131
132- it('should detect HTML from html tag', () => {
132+ it("should detect HTML from html tag", () => {
133133 const code = `<html>
134134 <body>
135135 <h1>Hello</h1>
136136 </body>
137137 </html>`;
138- expect(detectLanguage(code)).toBe('html');
138+ expect(detectLanguage(code)).toBe("html");
139139 });
140140
141- it('should detect CSS from media queries', () => {
141+ it("should detect CSS from media queries", () => {
142142 const code = `@media screen and (max-width: 600px) {
143143 body {
144144 font-size: 14px;
145145 }
146146 }`;
147- expect(detectLanguage(code)).toBe('css');
147+ expect(detectLanguage(code)).toBe("css");
148148 });
149149
150- it('should detect Markdown from headers', () => {
150+ it("should detect Markdown from headers", () => {
151151 const code = `# Main Title
152152 ## Subtitle
153153 This is some content.`;
154- expect(detectLanguage(code)).toBe('markdown');
154+ expect(detectLanguage(code)).toBe("markdown");
155155 });
156156
157- it('should default to javascript for unknown patterns', () => {
157+ it("should default to javascript for unknown patterns", () => {
158158 const code = `some random code that doesn't match any pattern`;
159- expect(detectLanguage(code)).toBe('javascript');
159+ expect(detectLanguage(code)).toBe("javascript");
160160 });
161161
162- it('should handle empty string', () => {
162+ it("should handle empty string", () => {
163163 const code = ``;
164- expect(detectLanguage(code)).toBe('javascript');
164+ expect(detectLanguage(code)).toBe("javascript");
165165 });
166166
167- it('should handle whitespace-only code', () => {
167+ it("should handle whitespace-only code", () => {
168168 const code = `
169169
170170 `;
171- expect(detectLanguage(code)).toBe('javascript');
171+ expect(detectLanguage(code)).toBe("javascript");
172172 });
173173
174- it('should match first pattern when multiple patterns could match', () => {
174+ it("should match first pattern when multiple patterns could match", () => {
175175 // This code has both import (JavaScript) and interface (TypeScript) patterns
176176 const code = `import { Component } from 'react';
177177 interface Props {
178178 name: string;
179179 }`;
180- expect(detectLanguage(code)).toBe('javascript'); // JavaScript pattern comes first
180+ expect(detectLanguage(code)).toBe("javascript"); // JavaScript pattern comes first
181181 });
182182
183- it('should handle multiline code correctly', () => {
183+ it("should handle multiline code correctly", () => {
184184 const code = `
185185 import React from 'react';
186186
@@ -188,20 +188,20 @@
188188 return <div>Hello</div>;
189189 };
190190 `;
191- expect(detectLanguage(code)).toBe('javascript');
191+ expect(detectLanguage(code)).toBe("javascript");
192192 });
193193
194- it('should detect patterns with leading whitespace', () => {
194+ it("should detect patterns with leading whitespace", () => {
195195 const code = ` def my_function():
196196 return True`;
197- expect(detectLanguage(code)).toBe('python');
197+ expect(detectLanguage(code)).toBe("python");
198198 });
199-
200- it('should handle YAML-like content but default to javascript', () => {
199+
200+ it("should handle YAML-like content but default to javascript", () => {
201201 // The actual implementation doesn't detect YAML from document separator
202202 const code = `---
203203 name: John
204204 age: 30`;
205- expect(detectLanguage(code)).toBe('yaml');
205+ expect(detectLanguage(code)).toBe("yaml");
206206 });
207-});
No newline at the end of the file
207+});
modified extensions/cli/src/ui/TUIChat.test.tsx +1 −1
@@ -10,4 +10,4 @@
1010 it("should import all test modules", () => {
1111 expect(true).toBe(true);
1212 });
13-});
No newline at the end of the file
13+});
modified extensions/cli/src/ui/TextBuffer.test.ts +232 −213
@@ -1,345 +1,349 @@
1-import { TextBuffer, COLLAPSE_SIZE, RAPID_INPUT_THRESHOLD } from './TextBuffer.js';
2-
3-describe('TextBuffer', () => {
1+import {
2+ TextBuffer,
3+ COLLAPSE_SIZE,
4+ RAPID_INPUT_THRESHOLD,
5+} from "./TextBuffer.js";
6+
7+describe("TextBuffer", () => {
48 let buffer: TextBuffer;
59
610 beforeEach(() => {
711 buffer = new TextBuffer();
812 });
913
10- describe('constructor', () => {
11- it('should initialize with empty text by default', () => {
12- expect(buffer.text).toBe('');
14+ describe("constructor", () => {
15+ it("should initialize with empty text by default", () => {
16+ expect(buffer.text).toBe("");
1317 expect(buffer.cursor).toBe(0);
1418 });
1519
16- it('should initialize with provided text', () => {
17- const buffer = new TextBuffer('hello');
18- expect(buffer.text).toBe('hello');
20+ it("should initialize with provided text", () => {
21+ const buffer = new TextBuffer("hello");
22+ expect(buffer.text).toBe("hello");
1923 expect(buffer.cursor).toBe(5);
2024 });
2125 });
2226
23- describe('setText', () => {
24- it('should set text and maintain cursor position', () => {
25- buffer.setText('hello');
26- expect(buffer.text).toBe('hello');
27+ describe("setText", () => {
28+ it("should set text and maintain cursor position", () => {
29+ buffer.setText("hello");
30+ expect(buffer.text).toBe("hello");
2731 expect(buffer.cursor).toBe(0);
2832 });
2933
30- it('should adjust cursor if it exceeds text length', () => {
31- buffer.setText('hello world');
34+ it("should adjust cursor if it exceeds text length", () => {
35+ buffer.setText("hello world");
3236 buffer.setCursor(5);
33- buffer.setText('hi');
34- expect(buffer.text).toBe('hi');
37+ buffer.setText("hi");
38+ expect(buffer.text).toBe("hi");
3539 expect(buffer.cursor).toBe(2);
3640 });
3741 });
3842
39- describe('setCursor', () => {
43+ describe("setCursor", () => {
4044 beforeEach(() => {
41- buffer.setText('hello');
45+ buffer.setText("hello");
4246 });
4347
44- it('should set cursor to valid position', () => {
48+ it("should set cursor to valid position", () => {
4549 buffer.setCursor(3);
4650 expect(buffer.cursor).toBe(3);
4751 });
4852
49- it('should clamp cursor to minimum of 0', () => {
53+ it("should clamp cursor to minimum of 0", () => {
5054 buffer.setCursor(-5);
5155 expect(buffer.cursor).toBe(0);
5256 });
5357
54- it('should clamp cursor to maximum of text length', () => {
58+ it("should clamp cursor to maximum of text length", () => {
5559 buffer.setCursor(10);
5660 expect(buffer.cursor).toBe(5);
5761 });
5862 });
5963
60- describe('insertText', () => {
61- it('should insert text at cursor position', () => {
62- buffer.setText('hello');
64+ describe("insertText", () => {
65+ it("should insert text at cursor position", () => {
66+ buffer.setText("hello");
6367 buffer.setCursor(2);
64- buffer.insertText('XX');
65- expect(buffer.text).toBe('heXXllo');
68+ buffer.insertText("XX");
69+ expect(buffer.text).toBe("heXXllo");
6670 expect(buffer.cursor).toBe(4);
6771 });
6872
69- it('should insert text at beginning', () => {
70- buffer.setText('world');
73+ it("should insert text at beginning", () => {
74+ buffer.setText("world");
7175 buffer.setCursor(0);
72- buffer.insertText('hello ');
73- expect(buffer.text).toBe('hello world');
76+ buffer.insertText("hello ");
77+ expect(buffer.text).toBe("hello world");
7478 expect(buffer.cursor).toBe(6);
7579 });
7680
77- it('should insert text at end', () => {
78- buffer.setText('hello');
81+ it("should insert text at end", () => {
82+ buffer.setText("hello");
7983 buffer.setCursor(5);
80- buffer.insertText(' world');
81- expect(buffer.text).toBe('hello world');
84+ buffer.insertText(" world");
85+ expect(buffer.text).toBe("hello world");
8286 expect(buffer.cursor).toBe(11);
8387 });
8488 });
8589
86- describe('deleteCharAt', () => {
90+ describe("deleteCharAt", () => {
8791 beforeEach(() => {
88- buffer.setText('hello');
92+ buffer.setText("hello");
8993 buffer.setCursor(3);
9094 });
9195
92- it('should delete character at specified position', () => {
96+ it("should delete character at specified position", () => {
9397 buffer.deleteCharAt(2);
94- expect(buffer.text).toBe('helo');
98+ expect(buffer.text).toBe("helo");
9599 expect(buffer.cursor).toBe(2);
96100 });
97101
98- it('should not adjust cursor if deleting before cursor', () => {
102+ it("should not adjust cursor if deleting before cursor", () => {
99103 buffer.deleteCharAt(1);
100- expect(buffer.text).toBe('hllo');
104+ expect(buffer.text).toBe("hllo");
101105 expect(buffer.cursor).toBe(2);
102106 });
103107
104- it('should not delete if position is out of bounds', () => {
108+ it("should not delete if position is out of bounds", () => {
105109 buffer.deleteCharAt(10);
106- expect(buffer.text).toBe('hello');
110+ expect(buffer.text).toBe("hello");
107111 expect(buffer.cursor).toBe(3);
108112 });
109113
110- it('should not delete if position is negative', () => {
114+ it("should not delete if position is negative", () => {
111115 buffer.deleteCharAt(-1);
112- expect(buffer.text).toBe('hello');
116+ expect(buffer.text).toBe("hello");
113117 expect(buffer.cursor).toBe(3);
114118 });
115119 });
116120
117- describe('deleteBackward', () => {
121+ describe("deleteBackward", () => {
118122 beforeEach(() => {
119- buffer.setText('hello');
123+ buffer.setText("hello");
120124 buffer.setCursor(3);
121125 });
122126
123- it('should delete character before cursor', () => {
127+ it("should delete character before cursor", () => {
124128 buffer.deleteBackward();
125- expect(buffer.text).toBe('helo');
129+ expect(buffer.text).toBe("helo");
126130 expect(buffer.cursor).toBe(2);
127131 });
128132
129- it('should not delete if cursor is at beginning', () => {
133+ it("should not delete if cursor is at beginning", () => {
130134 buffer.setCursor(0);
131135 buffer.deleteBackward();
132- expect(buffer.text).toBe('hello');
136+ expect(buffer.text).toBe("hello");
133137 expect(buffer.cursor).toBe(0);
134138 });
135139 });
136140
137- describe('deleteForward', () => {
141+ describe("deleteForward", () => {
138142 beforeEach(() => {
139- buffer.setText('hello');
143+ buffer.setText("hello");
140144 buffer.setCursor(2);
141145 });
142146
143- it('should delete character at cursor position', () => {
147+ it("should delete character at cursor position", () => {
144148 buffer.deleteForward();
145- expect(buffer.text).toBe('helo');
149+ expect(buffer.text).toBe("helo");
146150 expect(buffer.cursor).toBe(2);
147151 });
148152
149- it('should not delete if cursor is at end', () => {
153+ it("should not delete if cursor is at end", () => {
150154 buffer.setCursor(5);
151155 buffer.deleteForward();
152- expect(buffer.text).toBe('hello');
156+ expect(buffer.text).toBe("hello");
153157 expect(buffer.cursor).toBe(5);
154158 });
155159 });
156160
157- describe('moveWordLeft', () => {
161+ describe("moveWordLeft", () => {
158162 beforeEach(() => {
159- buffer.setText('hello world test');
163+ buffer.setText("hello world test");
160164 });
161165
162- it('should move to start of current word', () => {
166+ it("should move to start of current word", () => {
163167 buffer.setCursor(8); // middle of "world"
164168 buffer.moveWordLeft();
165169 expect(buffer.cursor).toBe(6); // start of "world"
166170 });
167171
168- it('should move to start of previous word', () => {
172+ it("should move to start of previous word", () => {
169173 buffer.setCursor(6); // start of "world"
170174 buffer.moveWordLeft();
171175 expect(buffer.cursor).toBe(0); // start of "hello"
172176 });
173177
174- it('should skip whitespace', () => {
178+ it("should skip whitespace", () => {
175179 buffer.setCursor(11); // space after "world"
176180 buffer.moveWordLeft();
177181 expect(buffer.cursor).toBe(6); // start of "world"
178182 });
179183
180- it('should not move beyond beginning', () => {
184+ it("should not move beyond beginning", () => {
181185 buffer.setCursor(0);
182186 buffer.moveWordLeft();
183187 expect(buffer.cursor).toBe(0);
184188 });
185189 });
186190
187- describe('moveWordRight', () => {
191+ describe("moveWordRight", () => {
188192 beforeEach(() => {
189- buffer.setText('hello world test');
193+ buffer.setText("hello world test");
190194 });
191195
192- it('should move to end of current word', () => {
196+ it("should move to end of current word", () => {
193197 buffer.setCursor(2); // middle of "hello"
194198 buffer.moveWordRight();
195199 expect(buffer.cursor).toBe(5); // end of "hello"
196200 });
197201
198- it('should skip whitespace to next word', () => {
202+ it("should skip whitespace to next word", () => {
199203 buffer.setCursor(5); // end of "hello"
200204 buffer.moveWordRight();
201205 expect(buffer.cursor).toBe(11); // end of "world"
202206 });
203207
204- it('should not move beyond end', () => {
208+ it("should not move beyond end", () => {
205209 buffer.setCursor(16);
206210 buffer.moveWordRight();
207211 expect(buffer.cursor).toBe(16);
208212 });
209213 });
210214
211- describe('deleteWordBackward', () => {
215+ describe("deleteWordBackward", () => {
212216 beforeEach(() => {
213- buffer.setText('hello world test');
217+ buffer.setText("hello world test");
214218 });
215219
216- it('should delete from cursor to start of word', () => {
220+ it("should delete from cursor to start of word", () => {
217221 buffer.setCursor(8); // middle of "world"
218222 buffer.deleteWordBackward();
219- expect(buffer.text).toBe('hello rld test');
223+ expect(buffer.text).toBe("hello rld test");
220224 expect(buffer.cursor).toBe(6);
221225 });
222226
223- it('should delete entire previous word', () => {
227+ it("should delete entire previous word", () => {
224228 buffer.setCursor(6); // start of "world"
225229 buffer.deleteWordBackward();
226- expect(buffer.text).toBe('world test');
230+ expect(buffer.text).toBe("world test");
227231 expect(buffer.cursor).toBe(0);
228232 });
229233 });
230234
231- describe('deleteWordForward', () => {
235+ describe("deleteWordForward", () => {
232236 beforeEach(() => {
233- buffer.setText('hello world test');
237+ buffer.setText("hello world test");
234238 });
235239
236- it('should delete from cursor to end of word', () => {
240+ it("should delete from cursor to end of word", () => {
237241 buffer.setCursor(2); // middle of "hello"
238242 buffer.deleteWordForward();
239- expect(buffer.text).toBe('he world test');
243+ expect(buffer.text).toBe("he world test");
240244 expect(buffer.cursor).toBe(2);
241245 });
242246
243- it('should delete to next word boundary', () => {
247+ it("should delete to next word boundary", () => {
244248 buffer.setCursor(5); // end of "hello"
245249 buffer.deleteWordForward();
246- expect(buffer.text).toBe('hello test');
250+ expect(buffer.text).toBe("hello test");
247251 expect(buffer.cursor).toBe(5);
248252 });
249253 });
250254
251- describe('movement methods', () => {
255+ describe("movement methods", () => {
252256 beforeEach(() => {
253- buffer.setText('hello');
257+ buffer.setText("hello");
254258 buffer.setCursor(2);
255259 });
256260
257- it('should move to start', () => {
261+ it("should move to start", () => {
258262 buffer.moveToStart();
259263 expect(buffer.cursor).toBe(0);
260264 });
261265
262- it('should move to end', () => {
266+ it("should move to end", () => {
263267 buffer.moveToEnd();
264268 expect(buffer.cursor).toBe(5);
265269 });
266270
267- it('should move left', () => {
271+ it("should move left", () => {
268272 buffer.moveLeft();
269273 expect(buffer.cursor).toBe(1);
270274 });
271275
272- it('should not move left beyond start', () => {
276+ it("should not move left beyond start", () => {
273277 buffer.setCursor(0);
274278 buffer.moveLeft();
275279 expect(buffer.cursor).toBe(0);
276280 });
277281
278- it('should move right', () => {
282+ it("should move right", () => {
279283 buffer.moveRight();
280284 expect(buffer.cursor).toBe(3);
281285 });
282286
283- it('should not move right beyond end', () => {
287+ it("should not move right beyond end", () => {
284288 buffer.setCursor(5);
285289 buffer.moveRight();
286290 expect(buffer.cursor).toBe(5);
287291 });
288292 });
289293
290- describe('clear', () => {
291- it('should clear text and reset cursor', () => {
292- buffer.setText('hello world');
294+ describe("clear", () => {
295+ it("should clear text and reset cursor", () => {
296+ buffer.setText("hello world");
293297 buffer.setCursor(5);
294298 buffer.clear();
295- expect(buffer.text).toBe('');
299+ expect(buffer.text).toBe("");
296300 expect(buffer.cursor).toBe(0);
297301 });
298302
299- it('should clear paste map when clearing', () => {
300- const longText = 'a'.repeat(COLLAPSE_SIZE + 1);
303+ it("should clear paste map when clearing", () => {
304+ const longText = "a".repeat(COLLAPSE_SIZE + 1);
301305 buffer.handleInput(longText, { ctrl: false, meta: false } as any);
302306 buffer.flushPendingInput();
303307
304- expect(buffer.text).toBe('[Paste #1]');
308+ expect(buffer.text).toBe("[Paste #1]");
305309
306310 buffer.clear();
307- expect(buffer.text).toBe('');
311+ expect(buffer.text).toBe("");
308312 expect(buffer.cursor).toBe(0);
309313 });
310314 });
311315
312- describe('paste collapse', () => {
313- it('should not collapse short pasted text', () => {
314- const shortText = 'hello world';
316+ describe("paste collapse", () => {
317+ it("should not collapse short pasted text", () => {
318+ const shortText = "hello world";
315319 buffer.handleInput(shortText, { ctrl: false, meta: false } as any);
316320
317- expect(buffer.text).toBe('hello world');
321+ expect(buffer.text).toBe("hello world");
318322 });
319323
320- it('should collapse long pasted text exceeding collapse threshold', () => {
321- const longText = 'a'.repeat(COLLAPSE_SIZE + 1);
324+ it("should collapse long pasted text exceeding collapse threshold", () => {
325+ const longText = "a".repeat(COLLAPSE_SIZE + 1);
322326 buffer.handleInput(longText, { ctrl: false, meta: false } as any);
323327 buffer.flushPendingInput();
324328
325- expect(buffer.text).toBe('[Paste #1]');
329+ expect(buffer.text).toBe("[Paste #1]");
326330 });
327331
328- it('should count lines correctly in collapsed text', () => {
329- const multiLineText = 'line1\nline2\nline3\n' + 'a'.repeat(COLLAPSE_SIZE);
332+ it("should count lines correctly in collapsed text", () => {
333+ const multiLineText = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
330334 buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any);
331335 buffer.flushPendingInput();
332336
333- expect(buffer.text).toBe('[Paste #1, 4 lines]');
337+ expect(buffer.text).toBe("[Paste #1, 4 lines]");
334338 });
335339
336- it('should expand collapsed content on expandAllPasteBlocks', () => {
337- const longText = 'hello ' + 'a'.repeat(COLLAPSE_SIZE);
340+ it("should expand collapsed content on expandAllPasteBlocks", () => {
341+ const longText = "hello " + "a".repeat(COLLAPSE_SIZE);
338342 buffer.handleInput(longText, { ctrl: false, meta: false } as any);
339343 buffer.flushPendingInput();
340344
341345 // Verify it was collapsed
342- expect(buffer.text).toBe('[Paste #1]');
346+ expect(buffer.text).toBe("[Paste #1]");
343347
344348 // Expand it
345349 buffer.expandAllPasteBlocks();
@@ -348,37 +352,37 @@
348352 expect(buffer.text).toBe(longText);
349353 });
350354
351- it('should handle typing before and after collapsed content', () => {
352- buffer.setText('before ');
355+ it("should handle typing before and after collapsed content", () => {
356+ buffer.setText("before ");
353357 buffer.setCursor(7);
354358
355- const longText = 'a'.repeat(COLLAPSE_SIZE + 1);
359+ const longText = "a".repeat(COLLAPSE_SIZE + 1);
356360 buffer.handleInput(longText, { ctrl: false, meta: false } as any);
357361 buffer.flushPendingInput();
358362
359- expect(buffer.text).toBe('before [Paste #1]');
363+ expect(buffer.text).toBe("before [Paste #1]");
360364
361365 // Type after collapsed content
362- buffer.insertText(' after');
363- expect(buffer.text).toBe('before [Paste #1] after');
366+ buffer.insertText(" after");
367+ expect(buffer.text).toBe("before [Paste #1] after");
364368
365369 // Move cursor to beginning and type
366370 buffer.setCursor(0);
367- buffer.insertText('start ');
368- expect(buffer.text).toBe('start before [Paste #1] after');
371+ buffer.insertText("start ");
372+ expect(buffer.text).toBe("start before [Paste #1] after");
369373 });
370374
371- it('should handle exactly collapse threshold without collapsing', () => {
372- const exactText = 'a'.repeat(COLLAPSE_SIZE); // exactly at threshold
375+ it("should handle exactly collapse threshold without collapsing", () => {
376+ const exactText = "a".repeat(COLLAPSE_SIZE); // exactly at threshold
373377 buffer.handleInput(exactText, { ctrl: false, meta: false } as any);
374378 buffer.flushPendingInput(); // This will go into rapid input mode due to size
375379
376380 expect(buffer.text).toBe(exactText); // Should not be collapsed
377381 });
378382
379- it('should handle paste operations as single large inputs', () => {
383+ it("should handle paste operations as single large inputs", () => {
380384 // This simulates the most common paste scenario: a single large input
381- const longText = 'x'.repeat(COLLAPSE_SIZE + 1);
385+ const longText = "x".repeat(COLLAPSE_SIZE + 1);
382386
383387 expect(longText.length).toBeGreaterThan(COLLAPSE_SIZE);
384388
@@ -386,87 +390,95 @@
386390 buffer.flushPendingInput();
387391
388392 // Should be collapsed
389- expect(buffer.text).toBe('[Paste #1]');
393+ expect(buffer.text).toBe("[Paste #1]");
390394 });
391395
392- it('should handle bracketed paste mode', () => {
396+ it("should handle bracketed paste mode", () => {
393397 // Simulate bracketed paste: start sequence, content, end sequence
394398
395399 // Start paste mode
396- buffer.handleInput('\u001b[200~', {} as any);
400+ buffer.handleInput("\u001b[200~", {} as any);
397401 expect(buffer.isInPasteMode()).toBe(true);
398402
399403 // Add some content (in chunks like real paste)
400- const chunks = ['Hello ', 'world! ', 'This is a long piece of text. '.repeat(30)];
401- const totalContent = chunks.join('');
402-
403- chunks.forEach(chunk => {
404+ const chunks = [
405+ "Hello ",
406+ "world! ",
407+ "This is a long piece of text. ".repeat(30),
408+ ];
409+ const totalContent = chunks.join("");
410+
411+ chunks.forEach((chunk) => {
404412 buffer.handleInput(chunk, { ctrl: false, meta: false } as any);
405413 });
406414
407415 // Text should NOT be visible during paste mode (to avoid visual bugs)
408- expect(buffer.text).toBe('');
416+ expect(buffer.text).toBe("");
409417
410418 // End paste mode
411- buffer.handleInput('\u001b[201~', {} as any);
419+ buffer.handleInput("\u001b[201~", {} as any);
412420 expect(buffer.isInPasteMode()).toBe(false);
413421
414422 // Now should be collapsed if > COLLAPSE_SIZE
415423 if (totalContent.length > COLLAPSE_SIZE) {
416- expect(buffer.text).toBe('[Paste #1]');
424+ expect(buffer.text).toBe("[Paste #1]");
417425 }
418426 });
419427
420- it('should not collapse short bracketed paste content', () => {
428+ it("should not collapse short bracketed paste content", () => {
421429 // Start paste mode
422- buffer.handleInput('\u001b[200~', {} as any);
430+ buffer.handleInput("\u001b[200~", {} as any);
423431
424432 // Add short content
425- const shortContent = 'Hello world!';
433+ const shortContent = "Hello world!";
426434 buffer.handleInput(shortContent, { ctrl: false, meta: false } as any);
427435
428436 // End paste mode
429- buffer.handleInput('\u001b[201~', {} as any);
437+ buffer.handleInput("\u001b[201~", {} as any);
430438
431439 // Should not be collapsed
432440 expect(buffer.text).toBe(shortContent);
433441 });
434442
435- it('should normalize line endings when expanding', () => {
436- const textWithCarriageReturns = 'line1\r\nline2\rline3\n' + 'a'.repeat(COLLAPSE_SIZE);
437- buffer.handleInput(textWithCarriageReturns, { ctrl: false, meta: false } as any);
443+ it("should normalize line endings when expanding", () => {
444+ const textWithCarriageReturns =
445+ "line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE);
446+ buffer.handleInput(textWithCarriageReturns, {
447+ ctrl: false,
448+ meta: false,
449+ } as any);
438450 buffer.flushPendingInput();
439451
440- expect(buffer.text).toBe('[Paste #1, 4 lines]');
452+ expect(buffer.text).toBe("[Paste #1, 4 lines]");
441453
442454 buffer.expandAllPasteBlocks();
443455
444456 // Should have normalized line endings
445- const expected = 'line1\nline2\nline3\n' + 'a'.repeat(COLLAPSE_SIZE);
457+ const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
446458 expect(buffer.text).toBe(expected);
447459 });
448460
449- it('should increment paste counter for multiple pastes', () => {
450- const longText1 = 'a'.repeat(COLLAPSE_SIZE + 1);
451- const longText2 = 'b'.repeat(COLLAPSE_SIZE + 1);
461+ it("should increment paste counter for multiple pastes", () => {
462+ const longText1 = "a".repeat(COLLAPSE_SIZE + 1);
463+ const longText2 = "b".repeat(COLLAPSE_SIZE + 1);
452464
453465 buffer.handleInput(longText1, { ctrl: false, meta: false } as any);
454466 buffer.flushPendingInput();
455- expect(buffer.text).toBe('[Paste #1]');
467+ expect(buffer.text).toBe("[Paste #1]");
456468
457- buffer.insertText(' ');
469+ buffer.insertText(" ");
458470 buffer.handleInput(longText2, { ctrl: false, meta: false } as any);
459471 buffer.flushPendingInput();
460- expect(buffer.text).toBe('[Paste #1] [Paste #2]');
472+ expect(buffer.text).toBe("[Paste #1] [Paste #2]");
461473 });
462474
463- it('should detect rapid input above threshold', () => {
475+ it("should detect rapid input above threshold", () => {
464476 // Test that input above RAPID_INPUT_THRESHOLD triggers rapid input detection
465- const rapidText = 'x'.repeat(RAPID_INPUT_THRESHOLD + 1);
477+ const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1);
466478 buffer.handleInput(rapidText, { ctrl: false, meta: false } as any);
467479
468480 // Should go into rapid input buffer (not displayed yet)
469- expect(buffer.text).toBe('');
481+ expect(buffer.text).toBe("");
470482 expect(buffer.isInRapidInputMode()).toBe(true);
471483
472484 // Flush to finalize
@@ -476,23 +488,23 @@
476488 expect(buffer.text).toBe(rapidText);
477489 });
478490
479- it('should combine split paste chunks', () => {
491+ it("should combine split paste chunks", () => {
480492 // Simulate macOS Terminal splitting paste
481- const firstChunk = 'a'.repeat(COLLAPSE_SIZE + 200); // Large first chunk
493+ const firstChunk = "a".repeat(COLLAPSE_SIZE + 200); // Large first chunk
482494 buffer.handleInput(firstChunk, { ctrl: false, meta: false } as any);
483495
484496 // First chunk goes into rapid input mode - no placeholder yet
485- expect(buffer.text).toBe('');
497+ expect(buffer.text).toBe("");
486498
487499 // Second chunk should be combined with the first (needs to be > 50 chars)
488- const secondChunk = 'b'.repeat(100); // Large enough to trigger split paste detection
500+ const secondChunk = "b".repeat(100); // Large enough to trigger split paste detection
489501 buffer.handleInput(secondChunk, { ctrl: false, meta: false } as any);
490502
491503 // Flush to finalize the rapid input synchronously
492504 buffer.flushPendingInput();
493505
494506 // Should show only one placeholder with combined content
495- expect(buffer.text).toBe('[Paste #1]');
507+ expect(buffer.text).toBe("[Paste #1]");
496508
497509 // Verify the combined content is stored correctly
498510 buffer.expandAllPasteBlocks();
@@ -500,148 +512,155 @@
500512 expect(buffer.text).toBe(expectedContent);
501513 });
502514
503- it('should expand paste blocks on submission (simulating Enter key behavior)', () => {
515+ it("should expand paste blocks on submission (simulating Enter key behavior)", () => {
504516 // Add some text before the paste
505- buffer.insertText('Command: ');
506-
517+ buffer.insertText("Command: ");
518+
507519 // Add a large paste that gets collapsed
508- const pastedCode = 'function example() {\n console.log("hello");\n ' + 'x'.repeat(COLLAPSE_SIZE);
520+ const pastedCode =
521+ 'function example() {\n console.log("hello");\n ' +
522+ "x".repeat(COLLAPSE_SIZE);
509523 buffer.handleInput(pastedCode, { ctrl: false, meta: false } as any);
510524 buffer.flushPendingInput();
511-
525+
512526 // Verify it's collapsed
513- expect(buffer.text).toBe('Command: [Paste #1, 3 lines]');
514-
527+ expect(buffer.text).toBe("Command: [Paste #1, 3 lines]");
528+
515529 // Simulate what happens when user presses Enter - UserInput calls expandAllPasteBlocks()
516530 buffer.expandAllPasteBlocks();
517-
531+
518532 // Should now show the full content with normalized line endings
519- const expectedFullText = 'Command: function example() {\n console.log("hello");\n ' + 'x'.repeat(COLLAPSE_SIZE);
533+ const expectedFullText =
534+ 'Command: function example() {\n console.log("hello");\n ' +
535+ "x".repeat(COLLAPSE_SIZE);
520536 expect(buffer.text).toBe(expectedFullText);
521-
537+
522538 // Verify paste map is cleared after expansion
523539 buffer.expandAllPasteBlocks(); // Should be no-op now
524540 expect(buffer.text).toBe(expectedFullText); // Should remain the same
525541 });
526542 });
527543
528- describe('handleInput', () => {
544+ describe("handleInput", () => {
529545 beforeEach(() => {
530- buffer.setText('hello');
546+ buffer.setText("hello");
531547 buffer.setCursor(2);
532548 });
533549
534- it('should handle regular character input', () => {
535- const result = buffer.handleInput('X', {} as any);
550+ it("should handle regular character input", () => {
551+ const result = buffer.handleInput("X", {} as any);
536552 expect(result).toBe(true);
537- expect(buffer.text).toBe('heXllo');
553+ expect(buffer.text).toBe("heXllo");
538554 expect(buffer.cursor).toBe(3);
539555 });
540556
541- it('should handle multi-character input (paste)', () => {
542- const result = buffer.handleInput('XYZ', {} as any);
557+ it("should handle multi-character input (paste)", () => {
558+ const result = buffer.handleInput("XYZ", {} as any);
543559 expect(result).toBe(true);
544- expect(buffer.text).toBe('heXYZllo');
560+ expect(buffer.text).toBe("heXYZllo");
545561 expect(buffer.cursor).toBe(5);
546562 });
547563
548- it('should handle ctrl+a (move to start)', () => {
549- const result = buffer.handleInput('a', { ctrl: true } as any);
564+ it("should handle ctrl+a (move to start)", () => {
565+ const result = buffer.handleInput("a", { ctrl: true } as any);
550566 expect(result).toBe(true);
551567 expect(buffer.cursor).toBe(0);
552568 });
553569
554- it('should handle ctrl+e (move to end)', () => {
555- const result = buffer.handleInput('e', { ctrl: true } as any);
570+ it("should handle ctrl+e (move to end)", () => {
571+ const result = buffer.handleInput("e", { ctrl: true } as any);
556572 expect(result).toBe(true);
557573 expect(buffer.cursor).toBe(5);
558574 });
559575
560- it('should handle ctrl+u (delete to start)', () => {
561- const result = buffer.handleInput('u', { ctrl: true } as any);
576+ it("should handle ctrl+u (delete to start)", () => {
577+ const result = buffer.handleInput("u", { ctrl: true } as any);
562578 expect(result).toBe(true);
563- expect(buffer.text).toBe('llo');
579+ expect(buffer.text).toBe("llo");
564580 expect(buffer.cursor).toBe(0);
565581 });
566582
567- it('should handle ctrl+k (delete to end)', () => {
568- const result = buffer.handleInput('k', { ctrl: true } as any);
583+ it("should handle ctrl+k (delete to end)", () => {
584+ const result = buffer.handleInput("k", { ctrl: true } as any);
569585 expect(result).toBe(true);
570- expect(buffer.text).toBe('he');
586+ expect(buffer.text).toBe("he");
571587 expect(buffer.cursor).toBe(2);
572588 });
573589
574- it('should handle arrow keys', () => {
575- let result = buffer.handleInput('', { leftArrow: true } as any);
590+ it("should handle arrow keys", () => {
591+ let result = buffer.handleInput("", { leftArrow: true } as any);
576592 expect(result).toBe(true);
577593 expect(buffer.cursor).toBe(1);
578594
579- result = buffer.handleInput('', { rightArrow: true } as any);
595+ result = buffer.handleInput("", { rightArrow: true } as any);
580596 expect(result).toBe(true);
581597 expect(buffer.cursor).toBe(2);
582598 });
583599
584- it('should handle delete key', () => {
585- const result = buffer.handleInput('', { delete: true } as any);
600+ it("should handle delete key", () => {
601+ const result = buffer.handleInput("", { delete: true } as any);
586602 expect(result).toBe(true);
587- expect(buffer.text).toBe('hllo');
603+ expect(buffer.text).toBe("hllo");
588604 expect(buffer.cursor).toBe(1);
589605 });
590606
591- it('should handle backspace key', () => {
592- const result = buffer.handleInput('', { backspace: true } as any);
607+ it("should handle backspace key", () => {
608+ const result = buffer.handleInput("", { backspace: true } as any);
593609 expect(result).toBe(true);
594- expect(buffer.text).toBe('hllo');
610+ expect(buffer.text).toBe("hllo");
595611 expect(buffer.cursor).toBe(1);
596612 });
597613
598- it('should handle meta key combinations', () => {
599- const result = buffer.handleInput('', { meta: true, leftArrow: true } as any);
614+ it("should handle meta key combinations", () => {
615+ const result = buffer.handleInput("", {
616+ meta: true,
617+ leftArrow: true,
618+ } as any);
600619 expect(result).toBe(true);
601620 expect(buffer.cursor).toBe(0);
602621 });
603622
604- it('should handle option key sequences', () => {
605- const result = buffer.handleInput('\u001b\u007f', {} as any);
623+ it("should handle option key sequences", () => {
624+ const result = buffer.handleInput("\u001b\u007f", {} as any);
606625 expect(result).toBe(true);
607626 // Should delete word backward
608- expect(buffer.text).toBe('llo');
627+ expect(buffer.text).toBe("llo");
609628 expect(buffer.cursor).toBe(0);
610629 });
611630
612- it('should return false for unhandled input', () => {
613- const result = buffer.handleInput('', { ctrl: true } as any);
631+ it("should return false for unhandled input", () => {
632+ const result = buffer.handleInput("", { ctrl: true } as any);
614633 expect(result).toBe(false);
615634 });
616635 });
617636
618- describe('renderWithCursor', () => {
619- it('should return text and cursor position', () => {
620- buffer.setText('hello');
637+ describe("renderWithCursor", () => {
638+ it("should return text and cursor position", () => {
639+ buffer.setText("hello");
621640 buffer.setCursor(2);
622641 const result = buffer.renderWithCursor();
623642 expect(result).toEqual({
624- text: 'hello',
625- cursorPosition: 2
643+ text: "hello",
644+ cursorPosition: 2,
626645 });
627646 });
628647
629- it('should return placeholder when text is empty', () => {
630- const result = buffer.renderWithCursor('Enter text...');
648+ it("should return placeholder when text is empty", () => {
649+ const result = buffer.renderWithCursor("Enter text...");
631650 expect(result).toEqual({
632- text: 'Enter text...',
633- cursorPosition: 0
651+ text: "Enter text...",
652+ cursorPosition: 0,
634653 });
635654 });
636655
637- it('should return actual text even when placeholder is provided', () => {
638- buffer.setText('hello');
656+ it("should return actual text even when placeholder is provided", () => {
657+ buffer.setText("hello");
639658 buffer.setCursor(2);
640- const result = buffer.renderWithCursor('Enter text...');
659+ const result = buffer.renderWithCursor("Enter text...");
641660 expect(result).toEqual({
642- text: 'hello',
643- cursorPosition: 2
661+ text: "hello",
662+ cursorPosition: 2,
644663 });
645664 });
646665 });
647-});
No newline at the end of the file
666+});
modified extensions/cli/src/ui/UpdateNotification.test.tsx +1 −1
@@ -119,4 +119,4 @@
119119 expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
120120 }
121121 });
122-});
No newline at the end of the file
122+});
modified extensions/cli/src/ui/UserInput.keyboard.test.ts +16 −16
@@ -1,34 +1,34 @@
1-import { describe, expect, it, beforeEach } from 'vitest';
1+import { describe, expect, it, beforeEach } from "vitest";
22
3-import { modeService } from '../services/ModeService.js';
3+import { modeService } from "../services/ModeService.js";
44
5-describe('UserInput Keyboard Shortcuts', () => {
5+describe("UserInput Keyboard Shortcuts", () => {
66 beforeEach(() => {
77 // Reset to normal mode for each test
88 modeService.initialize({});
99 });
1010
11- describe('mode cycling logic', () => {
12- it('should cycle through modes in correct order', () => {
11+ describe("mode cycling logic", () => {
12+ it("should cycle through modes in correct order", () => {
1313 // Initially should be normal mode
14- expect(modeService.getCurrentMode()).toBe('normal');
14+ expect(modeService.getCurrentMode()).toBe("normal");
1515
1616 // Cycle to plan
17- modeService.switchMode('plan');
18- expect(modeService.getCurrentMode()).toBe('plan');
17+ modeService.switchMode("plan");
18+ expect(modeService.getCurrentMode()).toBe("plan");
1919
2020 // Cycle to auto
21- modeService.switchMode('auto');
22- expect(modeService.getCurrentMode()).toBe('auto');
21+ modeService.switchMode("auto");
22+ expect(modeService.getCurrentMode()).toBe("auto");
2323
2424 // Cycle back to normal
25- modeService.switchMode('normal');
26- expect(modeService.getCurrentMode()).toBe('normal');
25+ modeService.switchMode("normal");
26+ expect(modeService.getCurrentMode()).toBe("normal");
2727 });
2828
29- it('should cycle through all modes sequentially', () => {
30- const modes = ['normal', 'plan', 'auto'] as const;
31-
29+ it("should cycle through all modes sequentially", () => {
30+ const modes = ["normal", "plan", "auto"] as const;
31+
3232 // Test cycling through all modes
3333 for (let i = 0; i < modes.length * 2; i++) {
3434 const expectedMode = modes[i % modes.length];
@@ -37,4 +37,4 @@
3737 }
3838 });
3939 });
40-});
No newline at the end of the file
40+});
modified extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx +36 −50
@@ -6,7 +6,7 @@
66
77 // Mock the 'open' module to prevent actual URL opening during tests
88 vi.mock("open", () => ({
9- default: vi.fn()
9+ default: vi.fn(),
1010 }));
1111
1212 // Mock the NavigationContext
@@ -15,8 +15,8 @@
1515 navigateTo: vi.fn(),
1616 closeCurrentScreen: vi.fn(),
1717 isScreenActive: vi.fn(() => false),
18- state: { currentScreen: 'free-trial', screenData: null }
19- })
18+ state: { currentScreen: "free-trial", screenData: null },
19+ }),
2020 }));
2121
2222 describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
@@ -29,9 +29,7 @@
2929 describe("Initial Choice Screen Rendering", () => {
3030 it("displays all three options with proper formatting", () => {
3131 const { lastFrame } = render(
32- <FreeTrialTransitionUI
33- onReload={mockOnReload}
34- />
32+ <FreeTrialTransitionUI onReload={mockOnReload} />,
3533 );
3634
3735 const frame = lastFrame();
@@ -44,22 +42,20 @@
4442
4543 it("highlights first option by default", () => {
4644 const { lastFrame } = render(
47- <FreeTrialTransitionUI
48- onReload={mockOnReload}
49- />
45+ <FreeTrialTransitionUI onReload={mockOnReload} />,
5046 );
5147
5248 const frame = lastFrame();
5349 expect(frame).toContain("▶ 1. 💳 Sign up for models add-on");
5450 expect(frame).not.toContain("▶ 2. 🔑 Enter your Anthropic API key");
55- expect(frame).not.toContain("▶ 3. ⚙️ Switch to a different configuration");
51+ expect(frame).not.toContain(
52+ "▶ 3. ⚙️ Switch to a different configuration",
53+ );
5654 });
5755
5856 it("renders without crashing when all props are provided", () => {
5957 const { lastFrame } = render(
60- <FreeTrialTransitionUI
61- onReload={mockOnReload}
62- />
58+ <FreeTrialTransitionUI onReload={mockOnReload} />,
6359 );
6460
6561 const frame = lastFrame();
@@ -72,7 +68,7 @@
7268 <FreeTrialTransitionUI
7369 onReload={mockOnReload}
7470 // onShowConfigSelector not provided
75- />
71+ />,
7672 );
7773
7874 const frame = lastFrame();
@@ -83,21 +79,19 @@
8379
8480 it("includes proper user instructions", () => {
8581 const { lastFrame } = render(
86- <FreeTrialTransitionUI
87- onReload={mockOnReload}
88- />
82+ <FreeTrialTransitionUI onReload={mockOnReload} />,
8983 );
9084
9185 const frame = lastFrame();
9286 expect(frame).toContain("Choose how you'd like to continue:");
93- expect(frame).toContain("Use ↑↓ arrows or 1/2/3 to select, Enter to confirm");
87+ expect(frame).toContain(
88+ "Use ↑↓ arrows or 1/2/3 to select, Enter to confirm",
89+ );
9490 });
9591
9692 it("shows all options with proper descriptions", () => {
9793 const { lastFrame } = render(
98- <FreeTrialTransitionUI
99- onReload={mockOnReload}
100- />
94+ <FreeTrialTransitionUI onReload={mockOnReload} />,
10195 );
10296
10397 const frame = lastFrame();
@@ -111,22 +105,14 @@
111105 it("accepts all required callback props", () => {
112106 // Test that component accepts and renders with all props
113107 expect(() => {
114- render(
115- <FreeTrialTransitionUI
116- onReload={mockOnReload}
117- />
118- );
108+ render(<FreeTrialTransitionUI onReload={mockOnReload} />);
119109 }).not.toThrow();
120110 });
121111
122112 it("accepts optional onShowConfigSelector prop", () => {
123113 // Test that component works without onShowConfigSelector
124114 expect(() => {
125- render(
126- <FreeTrialTransitionUI
127- onReload={mockOnReload}
128- />
129- );
115+ render(<FreeTrialTransitionUI onReload={mockOnReload} />);
130116 }).not.toThrow();
131117 });
132118 });
@@ -134,9 +120,7 @@
134120 describe("Visual Styling and Layout", () => {
135121 it("renders with proper border styling", () => {
136122 const { lastFrame } = render(
137- <FreeTrialTransitionUI
138- onReload={mockOnReload}
139- />
123+ <FreeTrialTransitionUI onReload={mockOnReload} />,
140124 );
141125
142126 const frame = lastFrame();
@@ -146,32 +130,34 @@
146130
147131 it("displays with proper spacing and formatting", () => {
148132 const { lastFrame } = render(
149- <FreeTrialTransitionUI
150- onReload={mockOnReload}
151- />
133+ <FreeTrialTransitionUI onReload={mockOnReload} />,
152134 );
153135
154136 const frame = lastFrame();
155137 // Should have proper spacing between lines
156- expect(frame?.split('\n').length).toBeGreaterThan(5);
138+ expect(frame?.split("\n").length).toBeGreaterThan(5);
157139 });
158140
159141 it("shows selection indicator on first option by default", () => {
160142 const { lastFrame } = render(
161- <FreeTrialTransitionUI
162- onReload={mockOnReload}
163- />
143+ <FreeTrialTransitionUI onReload={mockOnReload} />,
164144 );
165145
166146 const frame = lastFrame();
167- const lines = frame?.split('\n') || [];
168- const modelsLine = lines.find(line => line.includes('Sign up for models add-on'));
169- const apiKeyLine = lines.find(line => line.includes('Enter your Anthropic API key'));
170- const configLine = lines.find(line => line.includes('Switch to a different configuration'));
171-
172- expect(modelsLine).toContain('▶');
173- expect(apiKeyLine).not.toContain('▶');
174- expect(configLine).not.toContain('▶');
147+ const lines = frame?.split("\n") || [];
148+ const modelsLine = lines.find((line) =>
149+ line.includes("Sign up for models add-on"),
150+ );
151+ const apiKeyLine = lines.find((line) =>
152+ line.includes("Enter your Anthropic API key"),
153+ );
154+ const configLine = lines.find((line) =>
155+ line.includes("Switch to a different configuration"),
156+ );
157+
158+ expect(modelsLine).toContain("▶");
159+ expect(apiKeyLine).not.toContain("▶");
160+ expect(configLine).not.toContain("▶");
175161 });
176162 });
177163
@@ -184,4 +170,4 @@
184170 expect(typeof openModule.default).toBe("function");
185171 });
186172 });
187-});
No newline at the end of the file
173+});
modified extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.urlHandling.test.tsx +20 −11
@@ -5,11 +5,11 @@
55 it("should mock URL opening to prevent actual browser launches during tests", () => {
66 // This test verifies that we properly mock the 'open' module
77 // to prevent actual URLs from being opened during test runs
8-
8+
99 // Import and check that open is mocked
1010 const mockOpen = vi.fn();
1111 vi.mock("open", () => mockOpen);
12-
12+
1313 // Verify the mock is properly set up
1414 expect(mockOpen).toBeDefined();
1515 expect(typeof mockOpen).toBe("function");
@@ -19,16 +19,25 @@
1919 // Test the URL construction logic without actually opening URLs
2020 const baseUrl = "https://test.continue.dev";
2121 const expectedUrl = new URL("setup-models", baseUrl).toString();
22-
22+
2323 expect(expectedUrl).toBe("https://test.continue.dev/setup-models");
2424 });
2525
2626 it("should handle URL construction with different base URLs", () => {
2727 // Test URL construction with various base URLs
2828 const testCases = [
29- { base: "https://continue.dev", expected: "https://continue.dev/setup-models" },
30- { base: "https://app.continue.dev", expected: "https://app.continue.dev/setup-models" },
31- { base: "http://localhost:3000", expected: "http://localhost:3000/setup-models" },
29+ {
30+ base: "https://continue.dev",
31+ expected: "https://continue.dev/setup-models",
32+ },
33+ {
34+ base: "https://app.continue.dev",
35+ expected: "https://app.continue.dev/setup-models",
36+ },
37+ {
38+ base: "http://localhost:3000",
39+ expected: "http://localhost:3000/setup-models",
40+ },
3241 ];
3342
3443 testCases.forEach(({ base, expected }) => {
@@ -41,16 +50,16 @@
4150 // This test documents the security consideration:
4251 // Without proper mocking, tests could open arbitrary URLs in the user's browser
4352 // The mock ensures this doesn't happen during automated test runs
44-
53+
4554 const openFunction = vi.fn();
46-
55+
4756 // Simulate what would happen if URL opening was called
4857 openFunction("https://malicious-site.com");
49-
58+
5059 // Verify the mock was called instead of actual URL opening
5160 expect(openFunction).toHaveBeenCalledWith("https://malicious-site.com");
5261 expect(openFunction).toHaveBeenCalledTimes(1);
53-
62+
5463 // In real usage, this would have opened a browser tab, but with mocking it's safe
5564 });
56-});
No newline at the end of the file
65+});
modified extensions/cli/src/ui/__tests__/TUIChat.basic.test.tsx +2 −2
@@ -50,7 +50,7 @@
5050
5151 it("handles remote URL prop", () => {
5252 const { lastFrame } = render(
53- React.createElement(AppRoot, { remoteUrl: "http://localhost:3000" })
53+ React.createElement(AppRoot, { remoteUrl: "http://localhost:3000" }),
5454 );
5555 const frame = lastFrame();
5656
@@ -59,4 +59,4 @@
5959 expect(frame.length).toBeGreaterThan(0);
6060 }
6161 });
62-});
No newline at the end of the file
62+});
modified extensions/cli/src/ui/__tests__/TUIChat.fileSearch.test.tsx +10 −8
@@ -21,7 +21,7 @@
2121 expect(hasAtSymbol).toBe(true);
2222
2323 // Mode-specific UI
24- if (mode === 'remote') {
24+ if (mode === "remote") {
2525 expect(frame).toContain("Remote Mode");
2626 } else {
2727 expect(frame).not.toContain("Remote Mode");
@@ -44,15 +44,16 @@
4444 expect(frame).toContain("@READ");
4545
4646 // In local mode, should show either navigation hints or files
47- if (mode === 'local') {
47+ if (mode === "local") {
4848 // Should show either navigation hints or at least indicate file search is working
4949 const hasNavigationHints = frame.includes("↑/↓ to navigate");
50- const hasFileSearch = frame.includes("@READ") && !frame.includes("Remote Mode");
50+ const hasFileSearch =
51+ frame.includes("@READ") && !frame.includes("Remote Mode");
5152 expect(hasNavigationHints || hasFileSearch).toBe(true);
5253 }
5354
5455 // Mode-specific checks
55- if (mode === 'remote') {
56+ if (mode === "remote") {
5657 expect(frame).toContain("Remote Mode");
5758 } else {
5859 expect(frame).not.toContain("Remote Mode");
@@ -75,7 +76,7 @@
7576 expect(frame).toContain("@@test");
7677
7778 // Mode-specific UI elements
78- if (mode === 'remote') {
79+ if (mode === "remote") {
7980 expect(frame).toContain("Remote Mode");
8081 } else {
8182 expect(frame).toContain("Continue CLI");
@@ -98,11 +99,12 @@
9899 expect(frame.length).toBeGreaterThan(0);
99100
100101 // In local mode, should show either navigation hints or file search UI
101- if (mode === 'local') {
102+ if (mode === "local") {
102103 // Should show either navigation hints or at least the @ character in file search
103104 const hasNavigationHints = frame.includes("↑/↓ to navigate");
104- const hasFileSearchUI = frame.includes("@") && !frame.includes("Remote Mode");
105+ const hasFileSearchUI =
106+ frame.includes("@") && !frame.includes("Remote Mode");
105107 expect(hasNavigationHints || hasFileSearchUI).toBe(true);
106108 }
107109 });
108-});
No newline at the end of the file
110+});
modified extensions/cli/src/ui/__tests__/TUIChat.freeTrialTransition.test.tsx +4 −4
@@ -5,17 +5,17 @@
55 // This test verifies that the integration points exist
66 // More comprehensive integration tests would require complex mocking
77 // that is difficult to maintain and test reliably.
8-
8+
99 // The key integration points are:
1010 // 1. FreeTrialTransitionUI receives onShowConfigSelector callback
1111 // 2. TUIChat provides handleFreeTrialShowConfigSelector function
1212 // 3. Config selector is shown when option 3 is selected
13-
13+
1414 // These integration points are tested via:
1515 // - Type checking (ensures interfaces match)
1616 // - Manual testing during development
1717 // - E2E tests that exercise the full flow
18-
18+
1919 expect(true).toBe(true); // Placeholder test
2020 });
21-});
No newline at the end of the file
21+});
modified extensions/cli/src/ui/__tests__/TUIChat.input.test.tsx +31 −28
@@ -9,11 +9,11 @@
99 const frame = lastFrame();
1010 // The input might be in a different format, let's be more flexible
1111 expect(frame ? frame.toLowerCase() : "").toMatch(
12- /testing|123|ask anything/
12+ /testing|123|ask anything/,
1313 );
14-
14+
1515 // Mode-specific assertions
16- if (mode === 'remote') {
16+ if (mode === "remote") {
1717 expect(frame).toContain("Remote Mode");
1818 } else {
1919 expect(frame).not.toContain("Remote Mode");
@@ -36,34 +36,37 @@
3636 // The UI should remain stable after Enter (no crash)
3737 expect(afterEnter).toBeDefined();
3838 expect(afterEnter).toContain("Ask anything");
39-
39+
4040 // Local mode specific features
41- if (mode === 'local') {
41+ if (mode === "local") {
4242 expect(afterEnter).toContain("@ for context");
4343 expect(afterEnter).toContain("/ for slash commands");
4444 }
4545 });
4646
47- testBothModes("handles special characters in input without crashing", (mode) => {
48- const { lastFrame, stdin } = renderInMode(mode);
49-
50- // Try typing various special characters
51- stdin.write("!@#$%^&*()");
52-
53- const frame = lastFrame();
54-
55- // Should handle special characters without crashing
56- expect(frame).toBeDefined();
57- expect(frame).not.toBe("");
58-
59- // UI should still be functional
60- expect(frame).toContain("Ask anything");
61-
62- // Mode-specific UI elements
63- if (mode === 'remote') {
64- expect(frame).toContain("Remote Mode");
65- } else {
66- expect(frame).toContain("Continue CLI");
67- }
68- });
69-});
No newline at the end of the file
47+ testBothModes(
48+ "handles special characters in input without crashing",
49+ (mode) => {
50+ const { lastFrame, stdin } = renderInMode(mode);
51+
52+ // Try typing various special characters
53+ stdin.write("!@#$%^&*()");
54+
55+ const frame = lastFrame();
56+
57+ // Should handle special characters without crashing
58+ expect(frame).toBeDefined();
59+ expect(frame).not.toBe("");
60+
61+ // UI should still be functional
62+ expect(frame).toContain("Ask anything");
63+
64+ // Mode-specific UI elements
65+ if (mode === "remote") {
66+ expect(frame).toContain("Remote Mode");
67+ } else {
68+ expect(frame).toContain("Continue CLI");
69+ }
70+ },
71+ );
72+});
modified extensions/cli/src/ui/__tests__/TUIChat.messages.test.tsx +6 −6
@@ -15,7 +15,7 @@
1515 expect(frame).toContain("│");
1616
1717 // Mode-specific assertions
18- if (mode === 'remote') {
18+ if (mode === "remote") {
1919 expect(frame).toContain("Remote Mode");
2020 } else {
2121 expect(frame).not.toContain("Remote Mode");
@@ -35,12 +35,12 @@
3535 expect(frame).toContain("/ for slash commands");
3636
3737 // In local mode, also shows context hint
38- if (mode === 'local') {
38+ if (mode === "local") {
3939 expect(frame).toContain("@ for context");
4040 }
4141
4242 // Verify mode-specific UI
43- if (mode === 'remote') {
43+ if (mode === "remote") {
4444 expect(frame).toContain("Remote Mode");
4545 } else {
4646 expect(frame).toContain("Continue CLI");
@@ -65,13 +65,13 @@
6565 // Verify the component renders
6666 const frame = lastFrame();
6767 expect(frame).toContain("Ask anything");
68-
68+
6969 // In local mode, we have access to more UI elements
70- if (mode === 'local') {
70+ if (mode === "local") {
7171 expect(frame).toContain("@ for context");
7272 expect(frame).toContain("/ for slash commands");
7373 }
7474
7575 context.cleanup();
7676 });
77-});
No newline at the end of the file
77+});
modified extensions/cli/src/ui/__tests__/TUIChat.permissionPolicyReload.test.tsx +36 −20
@@ -30,8 +30,12 @@
3030
3131 it("should call reloadPermissions after creating a policy", async () => {
3232 // Mock the policy writer
33- const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
34- vi.mocked(generatePolicyRule).mockReturnValue("tool: Edit\npermission: allow");
33+ const { generatePolicyRule, addPolicyToYaml } = await import(
34+ "../../permissions/policyWriter.js"
35+ );
36+ vi.mocked(generatePolicyRule).mockReturnValue(
37+ "tool: Edit\npermission: allow",
38+ );
3539 vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
3640
3741 // Test the workflow that should happen in useChat.handleToolPermissionResponse
@@ -42,7 +46,7 @@
4246
4347 const approved = true;
4448 const createPolicy = true;
45-
49+
4650 // Simulate the policy creation flow from useChat
4751 if (approved && createPolicy && mockActiveRequest) {
4852 try {
@@ -57,29 +61,38 @@
5761 );
5862
5963 await addPolicyToYaml(policyRule);
60-
64+
6165 // This is the key part we're testing - reload should be called
6266 await services.mode.getToolPermissionService().reloadPermissions();
63-
6467 } catch (error) {
6568 // Handle errors gracefully
6669 }
6770 }
6871
6972 // Verify the complete workflow executed
70- expect(generatePolicyRule).toHaveBeenCalledWith("Edit", { file_path: "test.txt" });
71- expect(addPolicyToYaml).toHaveBeenCalledWith("tool: Edit\npermission: allow");
73+ expect(generatePolicyRule).toHaveBeenCalledWith("Edit", {
74+ file_path: "test.txt",
75+ });
76+ expect(addPolicyToYaml).toHaveBeenCalledWith(
77+ "tool: Edit\npermission: allow",
78+ );
7279 expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
7380 });
7481
7582 it("should handle permission reload failure gracefully", async () => {
7683 // Mock the policy writer
77- const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
78- vi.mocked(generatePolicyRule).mockReturnValue("tool: Write\npermission: allow");
84+ const { generatePolicyRule, addPolicyToYaml } = await import(
85+ "../../permissions/policyWriter.js"
86+ );
87+ vi.mocked(generatePolicyRule).mockReturnValue(
88+ "tool: Write\npermission: allow",
89+ );
7990 vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
8091
8192 // Mock reloadPermissions to fail
82- mockToolPermissionService.reloadPermissions.mockRejectedValue(new Error("Reload failed"));
93+ mockToolPermissionService.reloadPermissions.mockRejectedValue(
94+ new Error("Reload failed"),
95+ );
8396
8497 const mockActiveRequest = {
8598 toolName: "Write",
@@ -88,7 +101,7 @@
88101
89102 const approved = true;
90103 const createPolicy = true;
91-
104+
92105 // Test that error handling works correctly - this should not throw
93106 let errorCaught = false;
94107 try {
@@ -101,12 +114,11 @@
101114 mockActiveRequest.toolName,
102115 mockActiveRequest.toolArgs,
103116 );
104-
117+
105118 await addPolicyToYaml(policyRule);
106-
119+
107120 // This should fail but not break the flow
108121 await services.mode.getToolPermissionService().reloadPermissions();
109-
110122 } catch (error) {
111123 // Error should be caught and handled gracefully
112124 errorCaught = true;
@@ -121,8 +133,12 @@
121133
122134 it("verifies the expected improvement: policy takes effect immediately", async () => {
123135 // This test documents what the user should experience
124- const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
125- vi.mocked(generatePolicyRule).mockReturnValue("tool: Edit\npermission: allow");
136+ const { generatePolicyRule, addPolicyToYaml } = await import(
137+ "../../permissions/policyWriter.js"
138+ );
139+ vi.mocked(generatePolicyRule).mockReturnValue(
140+ "tool: Edit\npermission: allow",
141+ );
126142 vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
127143
128144 // Mock successful reload
@@ -137,7 +153,7 @@
137153 // Simulate user choosing "Continue + don't ask again"
138154 const approved = true;
139155 const createPolicy = true;
140-
156+
141157 // The workflow should complete successfully
142158 if (approved && createPolicy && mockActiveRequest) {
143159 const { generatePolicyRule, addPolicyToYaml } = await import(
@@ -156,10 +172,10 @@
156172
157173 // AFTER: Policy is now active without restart
158174 // Next time user tries to edit a file, it should be automatically allowed
159-
175+
160176 expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
161-
177+
162178 // This represents the improvement: the new policy takes effect immediately
163179 // without requiring the user to restart the Continue CLI
164180 });
165-});
No newline at the end of the file
181+});
modified extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +40 −42
@@ -14,10 +14,10 @@
1414 beforeEach(async () => {
1515 context = createUITestContext({
1616 allServicesReady: true,
17- serviceState: "ready",
17+ serviceState: "ready",
1818 serviceValue: { some: "data" },
1919 });
20-
20+
2121 // Ensure mode service is properly initialized in normal mode
2222 await modeService.initialize({});
2323 });
@@ -37,30 +37,30 @@
3737
3838 // b) Shift+Tab to switch into plan mode
3939 stdin.write("\x1b[Z");
40- await new Promise(resolve => setTimeout(resolve, 200));
41-
40+ await new Promise((resolve) => setTimeout(resolve, 200));
41+
4242 frame = lastFrame();
43-
43+
4444 // c) Make sure the string "[plan]" is on the screen
4545 expect(frame!).toContain("[plan]");
46-
46+
4747 // d) Successfully send a message without error
4848 const testMessage = "Can you help me analyze this code?";
4949 stdin.write(testMessage);
5050 stdin.write("\r");
51-
51+
5252 // Wait for message processing
53- await new Promise(resolve => setTimeout(resolve, 300));
54-
53+ await new Promise((resolve) => setTimeout(resolve, 300));
54+
5555 frame = lastFrame();
56-
56+
5757 // Verify no crash occurred and UI is still functional
5858 expect(frame).toBeDefined();
5959 expect(frame!.length).toBeGreaterThan(0);
60-
60+
6161 // Should still be in plan mode after sending message
6262 expect(frame!).toContain("[plan]");
63-
63+
6464 // Should still show the input prompt
6565 expect(frame!).toContain("Ask anything");
6666 } finally {
@@ -79,62 +79,58 @@
7979
8080 // Switch to plan mode
8181 stdin.write("\x1b[Z");
82- await new Promise(resolve => setTimeout(resolve, 100));
83-
82+ await new Promise((resolve) => setTimeout(resolve, 100));
83+
8484 frame = lastFrame();
8585 expect(frame!).toContain("[plan]");
8686
8787 // Switch to auto mode
8888 stdin.write("\x1b[Z");
89- await new Promise(resolve => setTimeout(resolve, 100));
90-
89+ await new Promise((resolve) => setTimeout(resolve, 100));
90+
9191 frame = lastFrame();
9292 expect(frame!).toContain("[auto]");
9393 expect(frame!).not.toContain("[plan]");
9494
9595 // Switch back to normal mode
9696 stdin.write("\x1b[Z");
97- await new Promise(resolve => setTimeout(resolve, 100));
98-
97+ await new Promise((resolve) => setTimeout(resolve, 100));
98+
9999 frame = lastFrame();
100100 expect(frame!).not.toContain("[plan]");
101101 expect(frame!).not.toContain("[auto]");
102-
103-
104102 } finally {
105103 unmount();
106104 }
107105 });
108106
109-it("tests that you can switch modes after being in plan mode", async () => {
107+ it("tests that you can switch modes after being in plan mode", async () => {
110108 const { lastFrame, stdin, unmount } = render(React.createElement(AppRoot));
111109
112110 try {
113111 // Switch to plan mode
114112 stdin.write("\x1b[Z");
115- await new Promise(resolve => setTimeout(resolve, 100));
116-
113+ await new Promise((resolve) => setTimeout(resolve, 100));
114+
117115 let frame = lastFrame();
118116 expect(frame!).toContain("[plan]");
119117
120118 // Send a message while in plan mode
121119 stdin.write("Test message");
122120 stdin.write("\r");
123- await new Promise(resolve => setTimeout(resolve, 200));
124-
121+ await new Promise((resolve) => setTimeout(resolve, 200));
122+
125123 frame = lastFrame();
126124
127125 // Try to switch to another mode - this is where the bug might occur
128126 stdin.write("\x1b[Z]"); // Should go to auto mode
129- await new Promise(resolve => setTimeout(resolve, 200));
130-
127+ await new Promise((resolve) => setTimeout(resolve, 200));
128+
131129 frame = lastFrame();
132-
130+
133131 // This should work - if it fails, we've reproduced the "can't switch back" bug
134132 expect(frame!).toContain("[auto]");
135133 expect(frame!).not.toContain("[plan]");
136-
137-
138134 } finally {
139135 unmount();
140136 }
@@ -143,39 +139,41 @@
143139 it.skip("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => {
144140 // This test specifically tests the service container interaction
145141 // that causes the actual bug in production
146-
142+
147143 // First, set up a realistic service state (not mocked)
148144 await modeService.initialize({ isHeadless: false });
149-
145+
150146 // Register the tool permissions service like the real app does
151147 const initialState = modeService.getToolPermissionService().getState();
152- serviceContainer.registerValue(SERVICE_NAMES.TOOL_PERMISSIONS, initialState);
153-
148+ serviceContainer.registerValue(
149+ SERVICE_NAMES.TOOL_PERMISSIONS,
150+ initialState,
151+ );
152+
154153 // Verify initial state works
155154 expect(() => getAllTools()).not.toThrow();
156-
155+
157156 // Switch modes WITHOUT updating the service container (this simulates the bug)
158157 modeService.switchMode("plan");
159-
158+
160159 // The service container still has the old state, so getAllTools() should not find
161160 // the updated state with plan mode permissions. However, since the ToolPermissionService
162161 // overrides isReady() to always return true, getAllTools() will actually work.
163162 // The real bug would manifest when the service container has an out-of-sync state.
164-
165- // To reproduce the ACTUAL bug, we need to simulate the case where the service
163+
164+ // To reproduce the ACTUAL bug, we need to simulate the case where the service
166165 // container has a stale state that doesn't match the ToolPermissionService
167166 const staleState = { ...initialState, currentMode: "normal" as const };
168167 serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, staleState);
169-
170-
168+
171169 // Now getAllTools() should work because it gets the service state from the container
172170 // and the container has a valid state (even if it's stale)
173171 const tools = getAllTools();
174172 expect(tools).toBeDefined();
175173 expect(Array.isArray(tools)).toBe(true);
176-
174+
177175 // But the tools returned will be for "normal" mode, not "plan" mode
178176 // In plan mode, many tools should be excluded, but with stale normal state, all tools are available
179177 const planModeState = modeService.getToolPermissionService().getState();
180178 });
181-});
No newline at the end of the file
179+});
modified extensions/cli/src/ui/__tests__/TUIChat.remote.test.tsx +12 −18
@@ -19,9 +19,7 @@
1919 });
2020
2121 it("renders in remote mode with remote URL", () => {
22- const { lastFrame } = render(
23- <AppRoot remoteUrl="http://localhost:3000" />
24- );
22+ const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
2523 const frame = lastFrame();
2624
2725 expect(frame).toBeDefined();
@@ -30,9 +28,7 @@
3028 });
3129
3230 it("shows remote mode indicator", () => {
33- const { lastFrame } = render(
34- <AppRoot remoteUrl="http://localhost:3000" />
35- );
31+ const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
3632 const frame = lastFrame();
3733
3834 // Should show remote mode in the UI
@@ -40,9 +36,7 @@
4036 });
4137
4238 it("does not show service loading in remote mode", () => {
43- const { lastFrame } = render(
44- <AppRoot remoteUrl="http://localhost:3000" />
45- );
39+ const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
4640 const frame = lastFrame();
4741
4842 // Should not show loading services message
@@ -54,7 +48,7 @@
5448
5549 it("handles different remote URLs", () => {
5650 const { lastFrame } = render(
57- <AppRoot remoteUrl="https://api.example.com:8080" />
51+ <AppRoot remoteUrl="https://api.example.com:8080" />,
5852 );
5953 const frame = lastFrame();
6054
@@ -65,7 +59,7 @@
6559
6660 it("shows slash commands in remote mode", async () => {
6761 const { lastFrame, stdin } = render(
68- <AppRoot remoteUrl="http://localhost:3000" />
62+ <AppRoot remoteUrl="http://localhost:3000" />,
6963 );
7064
7165 // Wait for initial render
@@ -84,13 +78,13 @@
8478
8579 // The slash command menu might show /exit or navigation instructions
8680 // Different timing might show different states
87- const hasSlashCommandUI = frame ? (
88- frame.includes("/exit") ||
89- frame.includes("↑/↓ to navigate") ||
90- frame.includes("◉ /") ||
91- frame.includes("/ for slash commands") // Placeholder text is also valid
92- ) : false;
81+ const hasSlashCommandUI = frame
82+ ? frame.includes("/exit") ||
83+ frame.includes("↑/↓ to navigate") ||
84+ frame.includes("◉ /") ||
85+ frame.includes("/ for slash commands") // Placeholder text is also valid
86+ : false;
9387
9488 expect(hasSlashCommandUI).toBe(true);
9589 });
96-});
No newline at the end of the file
90+});
modified extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +11 −11
@@ -14,9 +14,9 @@
1414
1515 // Should show the slash character
1616 expect(frame).toContain("/");
17-
17+
1818 // Mode-specific assertions
19- if (mode === 'remote') {
19+ if (mode === "remote") {
2020 expect(frame).toContain("Remote Mode");
2121 } else {
2222 expect(frame).not.toContain("Remote Mode");
@@ -37,9 +37,9 @@
3737
3838 // Should show the typed command
3939 expect(frame).toContain("/log");
40-
40+
4141 // Mode-specific UI elements
42- if (mode === 'remote') {
42+ if (mode === "remote") {
4343 expect(frame).toContain("Remote Mode");
4444 } else {
4545 expect(frame).not.toContain("Remote Mode");
@@ -52,9 +52,9 @@
5252
5353 // Type /log and then tab
5454 stdin.write("/log");
55-
55+
5656 await new Promise((resolve) => setTimeout(resolve, 50));
57-
57+
5858 stdin.write("\t");
5959
6060 await new Promise((resolve) => setTimeout(resolve, 50));
@@ -65,9 +65,9 @@
6565 expect(frameAfterTab).toBeDefined();
6666 if (frameAfterTab) {
6767 expect(frameAfterTab.length).toBeGreaterThan(0);
68-
68+
6969 // Mode-specific checks
70- if (mode === 'remote') {
70+ if (mode === "remote") {
7171 expect(frameAfterTab).toContain("Remote Mode");
7272 } else {
7373 expect(frameAfterTab).not.toContain("Remote Mode");
@@ -87,9 +87,9 @@
8787
8888 // Should show the slash
8989 expect(frame).toContain("/");
90-
90+
9191 // In remote mode, slash command menu shows immediately
92- if (mode === 'remote') {
92+ if (mode === "remote") {
9393 expect(frame).toContain("/exit");
9494 expect(frame).toContain("Remote Mode");
9595 } else {
@@ -101,4 +101,4 @@
101101 expect(hasSlash).toBe(true);
102102 }
103103 });
104-});
No newline at the end of the file
104+});
modified extensions/cli/src/ui/__tests__/TUIChat.streamStopping.test.tsx +61 −25
@@ -27,7 +27,7 @@
2727 }}
2828 requestId="test-request-123"
2929 onResponse={handleResponse}
30- />
30+ />,
3131 );
3232
3333 await vi.advanceTimersByTimeAsync(50);
@@ -42,7 +42,7 @@
4242 "test-request-123",
4343 false, // approved = false
4444 false, // createPolicy = false
45- true // stopStream = true
45+ true, // stopStream = true
4646 );
4747 });
4848
@@ -58,7 +58,7 @@
5858 }}
5959 requestId="dangerous-request"
6060 onResponse={handleResponse}
61- />
61+ />,
6262 );
6363
6464 await vi.advanceTimersByTimeAsync(50);
@@ -73,14 +73,14 @@
7373 "dangerous-request",
7474 false, // rejected
7575 false, // createPolicy = false
76- true // stopStream = true
76+ true, // stopStream = true
7777 );
7878 });
7979
8080 it("tests that rejection response leads to stream stopping behavior", () => {
8181 // This test validates the key behavior - when onResponse is called with approved=false,
8282 // it should lead to the streamChatResponse function stopping and returning early
83-
83+
8484 const mockStreamingFunction = vi.fn().mockImplementation((approved) => {
8585 if (!approved) {
8686 // Simulate early return when tool is rejected
@@ -104,10 +104,12 @@
104104
105105 it("validates permission manager handles rejection correctly", async () => {
106106 // Import the permission manager to test its behavior
107- const { toolPermissionManager } = await import("../../permissions/permissionManager.js");
107+ const { toolPermissionManager } = await import(
108+ "../../permissions/permissionManager.js"
109+ );
108110
109111 const mockResolve = vi.fn();
110-
112+
111113 // Simulate a pending request
112114 const requestId = "test-request-456";
113115 (toolPermissionManager as any).pendingRequests.set(requestId, {
@@ -121,15 +123,17 @@
121123 // Verify the request was properly rejected
122124 expect(result).toBe(true);
123125 expect(mockResolve).toHaveBeenCalledWith({ approved: false });
124-
126+
125127 // Verify the request was removed from pending requests
126- expect((toolPermissionManager as any).pendingRequests.has(requestId)).toBe(false);
128+ expect((toolPermissionManager as any).pendingRequests.has(requestId)).toBe(
129+ false,
130+ );
127131 });
128132
129133 it("handles multiple tool calls correctly when first is rejected", () => {
130134 // Test the bug fix: when multiple tool calls are present and the first is rejected,
131135 // remaining tool calls should be marked as cancelled to maintain chat history consistency
132-
136+
133137 const mockMultipleToolCalls = [
134138 { id: "call_1", name: "Edit", arguments: {} },
135139 { id: "call_2", name: "Write", arguments: {} },
@@ -143,10 +147,10 @@
143147 // Simulate the rejection handling logic
144148 const deniedMessage = "Permission denied by user";
145149 const rejectedToolCall = mockMultipleToolCalls[0];
146-
150+
147151 // First tool call gets denied
148152 mockCallbacks.onToolResult(deniedMessage, rejectedToolCall.name);
149-
153+
150154 // Remaining tool calls should be cancelled
151155 for (let i = 1; i < mockMultipleToolCalls.length; i++) {
152156 const remainingToolCall = mockMultipleToolCalls[i];
@@ -156,30 +160,62 @@
156160
157161 // Verify all tool calls got results
158162 expect(mockCallbacks.onToolResult).toHaveBeenCalledTimes(3);
159- expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(1, "Permission denied by user", "Edit");
160- expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(2, "Cancelled due to previous tool rejection", "Write");
161- expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(3, "Cancelled due to previous tool rejection", "Read");
163+ expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(
164+ 1,
165+ "Permission denied by user",
166+ "Edit",
167+ );
168+ expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(
169+ 2,
170+ "Cancelled due to previous tool rejection",
171+ "Write",
172+ );
173+ expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(
174+ 3,
175+ "Cancelled due to previous tool rejection",
176+ "Read",
177+ );
162178 });
163179
164180 it("ensures proper response content in headless mode", () => {
165181 // Test the bug fix: ensure finalResponse fallback works properly in headless mode
166-
167- const mockStreamingBehavior = (isHeadless: boolean, finalResponse: string, content: string, fullResponse: string) => {
182+
183+ const mockStreamingBehavior = (
184+ isHeadless: boolean,
185+ finalResponse: string,
186+ content: string,
187+ fullResponse: string,
188+ ) => {
168189 // Simulate the fixed return logic
169- const responseToReturn = isHeadless ? (finalResponse || content) : fullResponse;
190+ const responseToReturn = isHeadless
191+ ? finalResponse || content
192+ : fullResponse;
170193 return responseToReturn;
171194 };
172195
173196 // Test headless mode with initialized finalResponse
174- expect(mockStreamingBehavior(true, "final content", "current content", "full content"))
175- .toBe("final content");
197+ expect(
198+ mockStreamingBehavior(
199+ true,
200+ "final content",
201+ "current content",
202+ "full content",
203+ ),
204+ ).toBe("final content");
176205
177206 // Test headless mode with uninitialized finalResponse (empty string)
178- expect(mockStreamingBehavior(true, "", "current content", "full content"))
179- .toBe("current content");
207+ expect(
208+ mockStreamingBehavior(true, "", "current content", "full content"),
209+ ).toBe("current content");
180210
181211 // Test non-headless mode
182- expect(mockStreamingBehavior(false, "final content", "current content", "full content"))
183- .toBe("full content");
212+ expect(
213+ mockStreamingBehavior(
214+ false,
215+ "final content",
216+ "current content",
217+ "full content",
218+ ),
219+ ).toBe("full content");
184220 });
185-});
No newline at the end of the file
221+});
modified extensions/cli/src/ui/__tests__/TUIChat.toolDisplay.test.tsx +11 −15
@@ -19,9 +19,7 @@
1919 });
2020
2121 it("renders without crashing when tools are available", () => {
22- const { lastFrame } = render(
23- <AppRoot remoteUrl="http://localhost:3000" />
24- );
22+ const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
2523 const frame = lastFrame();
2624
2725 expect(frame).toBeDefined();
@@ -29,9 +27,7 @@
2927 });
3028
3129 it("handles UI with no tools configured", () => {
32- const { lastFrame } = render(
33- <AppRoot remoteUrl="http://localhost:3000" />
34- );
30+ const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
3531 const frame = lastFrame();
3632
3733 // Should render normally even without tools
@@ -41,7 +37,7 @@
4137
4238 it("maintains UI stability during tool operations", async () => {
4339 const { lastFrame, stdin } = render(
44- <AppRoot remoteUrl="http://localhost:3000" />
40+ <AppRoot remoteUrl="http://localhost:3000" />,
4541 );
4642
4743 // Type a message that might trigger tool use
@@ -60,7 +56,7 @@
6056
6157 it("shows tool-related slash commands", async () => {
6258 const { lastFrame, stdin } = render(
63- <AppRoot remoteUrl="http://localhost:3000" />
59+ <AppRoot remoteUrl="http://localhost:3000" />,
6460 );
6561
6662 // Wait for initial render
@@ -79,13 +75,13 @@
7975
8076 // The slash command menu might show different UI states
8177 // On Windows, the timing might be different
82- const hasSlashCommandIndicator = frame ? (
83- frame.includes("↑/↓ to navigate") ||
84- frame.includes("/exit") ||
85- frame.includes("◉ /") ||
86- frame.includes("/ for slash commands")
87- ) : false;
78+ const hasSlashCommandIndicator = frame
79+ ? frame.includes("↑/↓ to navigate") ||
80+ frame.includes("/exit") ||
81+ frame.includes("◉ /") ||
82+ frame.includes("/ for slash commands")
83+ : false;
8884
8985 expect(hasSlashCommandIndicator).toBe(true);
9086 });
91-});
No newline at the end of the file
87+});
modified extensions/cli/src/ui/__tests__/TUIChat.toolPermission.test.tsx +24 −26
@@ -26,7 +26,7 @@
2626 }}
2727 requestId="test-request-123"
2828 onResponse={handleResponse}
29- />
29+ />,
3030 );
3131
3232 await vi.advanceTimersByTimeAsync(50);
@@ -58,7 +58,7 @@
5858 }}
5959 requestId="test-request-123"
6060 onResponse={handleResponse}
61- />
61+ />,
6262 );
6363
6464 await vi.advanceTimersByTimeAsync(50);
@@ -72,7 +72,7 @@
7272 "test-request-123",
7373 true,
7474 false,
75- false
75+ false,
7676 );
7777 });
7878
@@ -87,7 +87,7 @@
8787 }}
8888 requestId="test-request-456"
8989 onResponse={handleResponse}
90- />
90+ />,
9191 );
9292
9393 await vi.advanceTimersByTimeAsync(50);
@@ -101,7 +101,7 @@
101101 "test-request-456",
102102 false,
103103 false,
104- true
104+ true,
105105 );
106106 });
107107
@@ -116,7 +116,7 @@
116116 }}
117117 requestId="test-request-789"
118118 onResponse={handleResponse}
119- />
119+ />,
120120 );
121121
122122 await vi.advanceTimersByTimeAsync(50);
@@ -130,7 +130,7 @@
130130 "test-request-789",
131131 false,
132132 false,
133- true
133+ true,
134134 );
135135 });
136136
@@ -145,7 +145,7 @@
145145 }}
146146 requestId="test-request-123"
147147 onResponse={handleResponse}
148- />
148+ />,
149149 );
150150
151151 await vi.advanceTimersByTimeAsync(50);
@@ -162,7 +162,7 @@
162162 "test-request-123",
163163 true,
164164 undefined,
165- undefined
165+ undefined,
166166 );
167167 });
168168
@@ -177,7 +177,7 @@
177177 }}
178178 requestId="test-request-policy"
179179 onResponse={handleResponse}
180- />
180+ />,
181181 );
182182
183183 await vi.advanceTimersByTimeAsync(50);
@@ -192,7 +192,7 @@
192192 "test-request-policy",
193193 true,
194194 true,
195- false
195+ false,
196196 );
197197 });
198198
@@ -209,7 +209,7 @@
209209 }}
210210 requestId="test-request-stop"
211211 onResponse={handleResponse}
212- />
212+ />,
213213 );
214214
215215 await vi.advanceTimersByTimeAsync(50);
@@ -217,7 +217,7 @@
217217 // Verify the new option exists in the rendered output
218218 const frame = lastFrame();
219219 expect(frame).toContain("No, and tell Continue what to do differently");
220-
220+
221221 // Verify all 3 options are present
222222 expect(frame).toContain("Continue");
223223 expect(frame).toContain("Continue + don't ask again");
@@ -240,7 +240,7 @@
240240 }}
241241 requestId="test-request-escape"
242242 onResponse={handleResponse}
243- />
243+ />,
244244 );
245245
246246 await vi.advanceTimersByTimeAsync(50);
@@ -253,9 +253,9 @@
253253 // Verify the escape key triggers the stopStream behavior
254254 expect(handleResponse).toHaveBeenCalledWith(
255255 "test-request-escape",
256- false, // approved = false (rejection)
257- false, // createPolicy = false
258- true // stopStream = true (this is the new behavior)
256+ false, // approved = false (rejection)
257+ false, // createPolicy = false
258+ true, // stopStream = true (this is the new behavior)
259259 );
260260 });
261261
@@ -272,7 +272,7 @@
272272 }}
273273 requestId="test-request-n-key"
274274 onResponse={handleResponse}
275- />
275+ />,
276276 );
277277
278278 await vi.advanceTimersByTimeAsync(50);
@@ -285,24 +285,22 @@
285285 // Verify the 'n' key triggers the stopStream behavior
286286 expect(handleResponse).toHaveBeenCalledWith(
287287 "test-request-n-key",
288- false, // approved = false (rejection)
289- false, // createPolicy = false
290- true // stopStream = true (this is the new behavior)
288+ false, // approved = false (rejection)
289+ false, // createPolicy = false
290+ true, // stopStream = true (this is the new behavior)
291291 );
292292 });
293293
294294 it("shows tool result with red dot and 'Cancelled by user' message", async () => {
295295 // Import the components we need for this test
296- const { ToolResultSummary } = await import(
297- "../ToolResultSummary.js"
298- );
296+ const { ToolResultSummary } = await import("../ToolResultSummary.js");
299297 const { MemoizedMessage } = await import(
300298 "../components/MemoizedMessage.js"
301299 );
302300
303301 // Test the ToolResultSummary component directly
304302 const { lastFrame: summaryFrame } = render(
305- <ToolResultSummary toolName="Edit" content="Permission denied by user" />
303+ <ToolResultSummary toolName="Edit" content="Permission denied by user" />,
306304 );
307305
308306 const summary = summaryFrame();
@@ -318,7 +316,7 @@
318316 };
319317
320318 const { lastFrame: messageFrame } = render(
321- <MemoizedMessage message={message} index={0} />
319+ <MemoizedMessage message={message} index={0} />,
322320 );
323321
324322 await vi.advanceTimersByTimeAsync(100);
modified extensions/cli/src/ui/components/ModeIndicator.test.tsx +33 −34
@@ -1,68 +1,67 @@
1-import { render } from 'ink-testing-library';
2-import React from 'react';
3-import { describe, expect, it, beforeEach } from 'vitest';
1+import { render } from "ink-testing-library";
2+import React from "react";
3+import { describe, expect, it, beforeEach } from "vitest";
44
5-import { modeService } from '../../services/ModeService.js';
5+import { modeService } from "../../services/ModeService.js";
66
7-import { ModeIndicator } from './ModeIndicator.js';
7+import { ModeIndicator } from "./ModeIndicator.js";
88
9-
10-describe('ModeIndicator', () => {
9+describe("ModeIndicator", () => {
1110 beforeEach(() => {
1211 // Reset to normal mode for each test
1312 modeService.initialize({});
1413 });
1514
16- describe('mode display', () => {
17- it('should not render anything for normal mode', () => {
15+ describe("mode display", () => {
16+ it("should not render anything for normal mode", () => {
1817 const { lastFrame } = render(<ModeIndicator />);
19- expect(lastFrame()).toBe('');
18+ expect(lastFrame()).toBe("");
2019 });
2120
22- it('should display plan mode with blue color', () => {
21+ it("should display plan mode with blue color", () => {
2322 const { lastFrame } = render(<ModeIndicator mode="plan" />);
24- expect(lastFrame()).toContain('[plan]');
23+ expect(lastFrame()).toContain("[plan]");
2524 });
2625
27- it('should display auto mode with green color', () => {
26+ it("should display auto mode with green color", () => {
2827 const { lastFrame } = render(<ModeIndicator mode="auto" />);
29- expect(lastFrame()).toContain('[auto]');
28+ expect(lastFrame()).toContain("[auto]");
3029 });
3130
32- it('should use current mode from service when no mode prop provided', () => {
33- modeService.switchMode('plan');
31+ it("should use current mode from service when no mode prop provided", () => {
32+ modeService.switchMode("plan");
3433 const { lastFrame } = render(<ModeIndicator />);
35- expect(lastFrame()).toContain('[plan]');
34+ expect(lastFrame()).toContain("[plan]");
3635 });
3736
38- it('should prioritize mode prop over service mode', () => {
39- modeService.switchMode('plan');
37+ it("should prioritize mode prop over service mode", () => {
38+ modeService.switchMode("plan");
4039 const { lastFrame } = render(<ModeIndicator mode="auto" />);
41- expect(lastFrame()).toContain('[auto]');
40+ expect(lastFrame()).toContain("[auto]");
4241 });
4342 });
4443
45- describe('mode changes', () => {
46- it('should update when mode changes in service', () => {
44+ describe("mode changes", () => {
45+ it("should update when mode changes in service", () => {
4746 const { lastFrame, rerender } = render(<ModeIndicator />);
48-
47+
4948 // Initially normal (no display)
50- expect(lastFrame()).toBe('');
51-
49+ expect(lastFrame()).toBe("");
50+
5251 // Switch to plan
53- modeService.switchMode('plan');
52+ modeService.switchMode("plan");
5453 rerender(<ModeIndicator />);
55- expect(lastFrame()).toContain('[plan]');
56-
54+ expect(lastFrame()).toContain("[plan]");
55+
5756 // Switch to auto
58- modeService.switchMode('auto');
57+ modeService.switchMode("auto");
5958 rerender(<ModeIndicator />);
60- expect(lastFrame()).toContain('[auto]');
61-
59+ expect(lastFrame()).toContain("[auto]");
60+
6261 // Switch back to normal
63- modeService.switchMode('normal');
62+ modeService.switchMode("normal");
6463 rerender(<ModeIndicator />);
65- expect(lastFrame()).toBe('');
64+ expect(lastFrame()).toBe("");
6665 });
6766 });
68-});
No newline at the end of the file
67+});
modified extensions/cli/src/ui/components/ToolPermissionRequest.test.tsx +4 −2
@@ -71,8 +71,10 @@
7171 });
7272
7373 it("should handle special characters", () => {
74- expect(formatArgs({ path: "/special/chars!@#$%^&*()_+" })).toBe("/special/chars!@#$%^&*()_+");
74+ expect(formatArgs({ path: "/special/chars!@#$%^&*()_+" })).toBe(
75+ "/special/chars!@#$%^&*()_+",
76+ );
7577 expect(formatArgs({ emoji: "🎉🎊✨" })).toBe("🎉🎊✨");
7678 });
7779 });
78-});
No newline at the end of the file
80+});
modified extensions/cli/src/ui/context/__tests__/NavigationContext.test.tsx +18 −14
@@ -5,7 +5,11 @@
55 import React from "react";
66 import { describe, it, expect, vi } from "vitest";
77
8-import { NavigationProvider, useNavigation, NavigationScreen } from "../NavigationContext.js";
8+import {
9+ NavigationProvider,
10+ useNavigation,
11+ NavigationScreen,
12+} from "../NavigationContext.js";
913
1014 describe("NavigationContext", () => {
1115 // Helper to create wrapper
@@ -163,13 +167,9 @@
163167
164168 it("closes from any screen back to chat", () => {
165169 const { result } = renderHook(() => useNavigation(), { wrapper });
166- const screens: Array<"config" | "model" | "free-trial" | "login" | "mcp"> = [
167- "config",
168- "model",
169- "free-trial",
170- "login",
171- "mcp",
172- ];
170+ const screens: Array<
171+ "config" | "model" | "free-trial" | "login" | "mcp"
172+ > = ["config", "model", "free-trial", "login", "mcp"];
173173
174174 screens.forEach((screen) => {
175175 act(() => {
@@ -257,8 +257,12 @@
257257 result.current.navigateTo("login", { different: "data" });
258258 });
259259
260- expect(result.current.state.currentScreen).toBe(stateWithData.currentScreen);
261- expect(result.current.state.screenData).not.toBe(stateWithData.screenData);
260+ expect(result.current.state.currentScreen).toBe(
261+ stateWithData.currentScreen,
262+ );
263+ expect(result.current.state.screenData).not.toBe(
264+ stateWithData.screenData,
265+ );
262266 });
263267 });
264268
@@ -269,9 +273,9 @@
269273
270274 // Navigate to login with resolve callback
271275 act(() => {
272- result.current.navigateTo("login", {
273- text: "Please log in",
274- resolve: mockResolve
276+ result.current.navigateTo("login", {
277+ text: "Please log in",
278+ resolve: mockResolve,
275279 });
276280 });
277281
@@ -344,4 +348,4 @@
344348 });
345349 });
346350 });
347-});
No newline at the end of the file
351+});
modified extensions/cli/src/ui/hooks/useChat.test.ts +2 −9
@@ -1,11 +1,4 @@
1-import {
2- afterEach,
3- beforeEach,
4- describe,
5- expect,
6- it,
7- vi,
8-} from "vitest";
1+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
92
103 import { createMinimalTestContext } from "../../test-helpers/ui-test-context.js";
114
@@ -54,4 +47,4 @@
5447 cleanup();
5548 expect(pollInterval).toBeUndefined();
5649 });
57-});
No newline at the end of the file
50+});
modified extensions/cli/src/ui/hooks/useConfigSelector.test.ts +13 −13
@@ -1,32 +1,32 @@
1-import { describe, expect, test } from 'vitest';
1+import { describe, expect, test } from "vitest";
22
3-describe('useConfigSelector', () => {
4- test('hook updated to use reactive service pattern', () => {
3+describe("useConfigSelector", () => {
4+ test("hook updated to use reactive service pattern", () => {
55 // This test documents that useConfigSelector has been updated
6-
6+
77 // Changes made:
88 // 1. Removed manual onAssistantChange callback
9- // 2. Now calls services.config.updateConfigPath()
9+ // 2. Now calls services.config.updateConfigPath()
1010 // 3. Lets ServiceContainer handle dependency management
1111 // 4. Allows automatic UI updates via reactive system
12-
12+
1313 // The hook now properly:
1414 // - Handles local config selection
1515 // - Handles assistant config selection
1616 // - Handles create config option
1717 // - Provides error handling
1818 // - Triggers reactive updates
19-
20- expect('hook').toBe('hook');
19+
20+ expect("hook").toBe("hook");
2121 });
2222
23- test('integrates with reactive service system', () => {
23+ test("integrates with reactive service system", () => {
2424 // The hook integration follows the correct pattern:
2525 // - User interaction → service method call
26- // - Service handles state update and notification
26+ // - Service handles state update and notification
2727 // - ServiceContainer manages dependency cascade
2828 // - UI components re-render automatically
29-
30- expect('integration').toBe('integration');
29+
30+ expect("integration").toBe("integration");
3131 });
32-});
No newline at the end of the file
32+});
modified extensions/cli/src/util/apiKeyValidation.test.ts +37 −26
@@ -1,42 +1,53 @@
1-import { isValidAnthropicApiKey, getApiKeyValidationError } from './apiKeyValidation.js';
1+import {
2+ isValidAnthropicApiKey,
3+ getApiKeyValidationError,
4+} from "./apiKeyValidation.js";
25
3-describe('isValidAnthropicApiKey', () => {
4- it('should return true for valid API keys', () => {
5- expect(isValidAnthropicApiKey('TEST-ant-1234567890')).toBe(true);
6- expect(isValidAnthropicApiKey('TEST-ant-abcdefghijklmnop')).toBe(true);
7- expect(isValidAnthropicApiKey('TEST-ant-test-key-with-dashes')).toBe(true);
8- expect(isValidAnthropicApiKey('TEST-ant-api03_T3BlbkFJ1234567890abcdef')).toBe(true);
6+describe("isValidAnthropicApiKey", () => {
7+ it("should return true for valid API keys", () => {
8+ expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
9+ expect(isValidAnthropicApiKey("TEST-ant-abcdefghijklmnop")).toBe(true);
10+ expect(isValidAnthropicApiKey("TEST-ant-test-key-with-dashes")).toBe(true);
11+ expect(
12+ isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
13+ ).toBe(true);
914 });
1015
11- it('should return false for invalid API keys', () => {
12- expect(isValidAnthropicApiKey('')).toBe(false);
13- expect(isValidAnthropicApiKey('TEST-ant-')).toBe(false);
14- expect(isValidAnthropicApiKey('TEST-')).toBe(false);
15- expect(isValidAnthropicApiKey('TEST-openai-1234567890')).toBe(false);
16- expect(isValidAnthropicApiKey('invalid-key')).toBe(false);
17- expect(isValidAnthropicApiKey('1234567890')).toBe(false);
16+ it("should return false for invalid API keys", () => {
17+ expect(isValidAnthropicApiKey("")).toBe(false);
18+ expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
19+ expect(isValidAnthropicApiKey("TEST-")).toBe(false);
20+ expect(isValidAnthropicApiKey("TEST-openai-1234567890")).toBe(false);
21+ expect(isValidAnthropicApiKey("invalid-key")).toBe(false);
22+ expect(isValidAnthropicApiKey("1234567890")).toBe(false);
1823 });
1924
20- it('should return false for null or undefined', () => {
25+ it("should return false for null or undefined", () => {
2126 expect(isValidAnthropicApiKey(null)).toBe(false);
2227 expect(isValidAnthropicApiKey(undefined)).toBe(false);
2328 });
2429
25- it('should return false for non-string values', () => {
30+ it("should return false for non-string values", () => {
2631 expect(isValidAnthropicApiKey(123 as any)).toBe(false);
2732 expect(isValidAnthropicApiKey({} as any)).toBe(false);
2833 expect(isValidAnthropicApiKey([] as any)).toBe(false);
2934 });
3035 });
3136
32-describe('getApiKeyValidationError', () => {
33- it('should return appropriate error messages', () => {
34- expect(getApiKeyValidationError('')).toBe('API key is required');
35- expect(getApiKeyValidationError(null)).toBe('API key is required');
36- expect(getApiKeyValidationError(undefined)).toBe('API key is required');
37- expect(getApiKeyValidationError('TEST-')).toBe('API key must start with "TEST-ant-"');
38- expect(getApiKeyValidationError('TEST-openai-1234')).toBe('API key must start with "TEST-ant-"');
39- expect(getApiKeyValidationError('TEST-ant-')).toBe('API key is too short');
40- expect(getApiKeyValidationError('invalid')).toBe('API key must start with "TEST-ant-"');
37+describe("getApiKeyValidationError", () => {
38+ it("should return appropriate error messages", () => {
39+ expect(getApiKeyValidationError("")).toBe("API key is required");
40+ expect(getApiKeyValidationError(null)).toBe("API key is required");
41+ expect(getApiKeyValidationError(undefined)).toBe("API key is required");
42+ expect(getApiKeyValidationError("TEST-")).toBe(
43+ 'API key must start with "TEST-ant-"',
44+ );
45+ expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
46+ 'API key must start with "TEST-ant-"',
47+ );
48+ expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
49+ expect(getApiKeyValidationError("invalid")).toBe(
50+ 'API key must start with "TEST-ant-"',
51+ );
4152 });
42-});
No newline at the end of the file
53+});
modified extensions/cli/src/util/exponentialBackoff.test.ts +9 −7
@@ -39,11 +39,13 @@
3939 }
4040
4141 // Check for premature close errors by message content
42- if (lower?.includes("premature close") ||
43- lower?.includes("premature end") ||
44- lower?.includes("connection reset") ||
45- lower?.includes("socket hang up") ||
46- lower?.includes("aborted")) {
42+ if (
43+ lower?.includes("premature close") ||
44+ lower?.includes("premature end") ||
45+ lower?.includes("connection reset") ||
46+ lower?.includes("socket hang up") ||
47+ lower?.includes("aborted")
48+ ) {
4749 return true;
4850 }
4951
@@ -52,7 +54,7 @@
5254
5355 function calculateDelay(
5456 attempt: number,
55- options: Required<ExponentialBackoffOptions>
57+ options: Required<ExponentialBackoffOptions>,
5658 ): number {
5759 const baseDelay =
5860 options.initialDelay * Math.pow(options.backoffMultiplier, attempt);
@@ -270,7 +272,7 @@
270272
271273 // Mock Math.random to return 0.5 (middle of jitter range)
272274 const originalRandom = Math.random;
273- vi.spyOn(Math, 'random').mockReturnValue(0.5);
275+ vi.spyOn(Math, "random").mockReturnValue(0.5);
274276
275277 // With jitter factor of 0.5 + 0.5 * 0.5 = 0.75
276278 expect(calculateDelay(0, options)).toBe(750); // 1000 * 0.75
modified extensions/cli/src/util/fileWatcher.test.ts +65 −65
@@ -1,21 +1,21 @@
1-import * as fs from 'fs';
2-import * as os from 'os';
3-import * as path from 'path';
1+import * as fs from "fs";
2+import * as os from "os";
3+import * as path from "path";
44
5-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
7-import { FileWatcher } from './fileWatcher.js';
7+import { FileWatcher } from "./fileWatcher.js";
88
9-describe('FileWatcher', () => {
9+describe("FileWatcher", () => {
1010 let tempDir: string;
1111 let watcher: FileWatcher;
1212
1313 beforeEach(() => {
1414 // Create a temporary directory for testing
15- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filewatcher-test-'));
15+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "filewatcher-test-"));
1616 watcher = new FileWatcher({
1717 debounceMs: 100, // Shorter debounce for tests
18- maxDepth: 2
18+ maxDepth: 2,
1919 });
2020 });
2121
@@ -27,25 +27,25 @@
2727 }
2828 });
2929
30- it.skip('should detect when new files are created', async () => {
30+ it.skip("should detect when new files are created", async () => {
3131 const callback = vi.fn();
3232 watcher.onChange(callback);
3333 watcher.startWatching(tempDir);
3434
3535 // Create a new file
36- const testFile = path.join(tempDir, 'test.txt');
37- fs.writeFileSync(testFile, 'test content');
36+ const testFile = path.join(tempDir, "test.txt");
37+ fs.writeFileSync(testFile, "test content");
3838
3939 // Wait for debounce
40- await new Promise(resolve => setTimeout(resolve, 150));
40+ await new Promise((resolve) => setTimeout(resolve, 150));
4141
4242 expect(callback).toHaveBeenCalled();
4343 });
4444
45- it.skip('should detect when files are deleted', async () => {
45+ it.skip("should detect when files are deleted", async () => {
4646 // Create a file first
47- const testFile = path.join(tempDir, 'test.txt');
48- fs.writeFileSync(testFile, 'test content');
47+ const testFile = path.join(tempDir, "test.txt");
48+ fs.writeFileSync(testFile, "test content");
4949
5050 const callback = vi.fn();
5151 watcher.onChange(callback);
@@ -55,16 +55,16 @@
5555 fs.unlinkSync(testFile);
5656
5757 // Wait for debounce
58- await new Promise(resolve => setTimeout(resolve, 150));
58+ await new Promise((resolve) => setTimeout(resolve, 150));
5959
6060 expect(callback).toHaveBeenCalled();
6161 });
6262
63- it('should ignore paths that match ignore patterns', async () => {
63+ it("should ignore paths that match ignore patterns", async () => {
6464 // Pre-create the node_modules directory to avoid directory creation events
65- const nodeModulesDir = path.join(tempDir, 'node_modules');
65+ const nodeModulesDir = path.join(tempDir, "node_modules");
6666 fs.mkdirSync(nodeModulesDir);
67-
67+
6868 const callback = vi.fn();
6969 watcher.onChange(callback);
7070 watcher.startWatching(tempDir);
@@ -72,94 +72,94 @@
7272 // Wait longer to ensure watcher is fully initialized and settled
7373 // Increase timeout for CI environments where file system events may be slower
7474 // Account for the 50ms initialization delay plus extra time for CI
75- await new Promise(resolve => setTimeout(resolve, 600));
75+ await new Promise((resolve) => setTimeout(resolve, 600));
7676
7777 // Reset the callback mock to ignore any initialization events
7878 callback.mockClear();
7979
8080 // Create a file in node_modules (should be ignored)
81- const testFile = path.join(nodeModulesDir, 'test.js');
82- fs.writeFileSync(testFile, 'test content');
81+ const testFile = path.join(nodeModulesDir, "test.js");
82+ fs.writeFileSync(testFile, "test content");
8383
8484 // Wait for debounce with longer timeout for CI environments
85- await new Promise(resolve => setTimeout(resolve, 500));
85+ await new Promise((resolve) => setTimeout(resolve, 500));
8686
8787 // Should not have been called because node_modules is ignored
8888 expect(callback).not.toHaveBeenCalled();
8989 });
9090
91- it('should ignore files matching wildcard patterns like **/*.tmp', async () => {
91+ it("should ignore files matching wildcard patterns like **/*.tmp", async () => {
9292 const callback = vi.fn();
9393 watcher.onChange(callback);
9494 watcher.startWatching(tempDir);
9595
9696 // Wait for watcher to initialize with longer timeout for CI
9797 // Account for the 50ms initialization delay plus extra time for CI
98- await new Promise(resolve => setTimeout(resolve, 600));
98+ await new Promise((resolve) => setTimeout(resolve, 600));
9999 callback.mockClear();
100100
101101 // Create a .tmp file (should be ignored by **/*.tmp pattern)
102- const tmpFile = path.join(tempDir, 'test.tmp');
103- fs.writeFileSync(tmpFile, 'temporary content');
102+ const tmpFile = path.join(tempDir, "test.tmp");
103+ fs.writeFileSync(tmpFile, "temporary content");
104104
105105 // Create a .log file (should be ignored by **/*.log pattern)
106- const logFile = path.join(tempDir, 'debug.log');
107- fs.writeFileSync(logFile, 'log content');
106+ const logFile = path.join(tempDir, "debug.log");
107+ fs.writeFileSync(logFile, "log content");
108108
109109 // Create a .min.js file (should be ignored by **/*.min.js pattern)
110- const minJsFile = path.join(tempDir, 'bundle.min.js');
111- fs.writeFileSync(minJsFile, 'minified js');
110+ const minJsFile = path.join(tempDir, "bundle.min.js");
111+ fs.writeFileSync(minJsFile, "minified js");
112112
113113 // Wait for debounce with longer timeout for CI
114- await new Promise(resolve => setTimeout(resolve, 500));
114+ await new Promise((resolve) => setTimeout(resolve, 500));
115115
116116 // Should not have been called because all files match ignore patterns
117117 expect(callback).not.toHaveBeenCalled();
118118 });
119119
120- it('should ignore specific files like .DS_Store', async () => {
120+ it("should ignore specific files like .DS_Store", async () => {
121121 const callback = vi.fn();
122122 watcher.onChange(callback);
123123 watcher.startWatching(tempDir);
124124
125125 // Wait for watcher to initialize with longer timeout for CI
126126 // Account for the 50ms initialization delay plus extra time for CI
127- await new Promise(resolve => setTimeout(resolve, 600));
127+ await new Promise((resolve) => setTimeout(resolve, 600));
128128 callback.mockClear();
129129
130130 // Create .DS_Store file (should be ignored by **/.DS_Store pattern)
131- const dsStoreFile = path.join(tempDir, '.DS_Store');
132- fs.writeFileSync(dsStoreFile, 'ds store content');
131+ const dsStoreFile = path.join(tempDir, ".DS_Store");
132+ fs.writeFileSync(dsStoreFile, "ds store content");
133133
134134 // Wait for debounce with longer timeout for CI
135- await new Promise(resolve => setTimeout(resolve, 500));
135+ await new Promise((resolve) => setTimeout(resolve, 500));
136136
137137 // Should not have been called because .DS_Store matches ignore pattern
138138 expect(callback).not.toHaveBeenCalled();
139139 });
140140
141- it('should detect files that do not match ignore patterns', async () => {
141+ it("should detect files that do not match ignore patterns", async () => {
142142 const callback = vi.fn();
143143 watcher.onChange(callback);
144144 watcher.startWatching(tempDir);
145145
146146 // Wait for watcher to initialize with longer timeout for CI
147147 // Account for the 50ms initialization delay plus extra time for CI
148- await new Promise(resolve => setTimeout(resolve, 600));
148+ await new Promise((resolve) => setTimeout(resolve, 600));
149149 callback.mockClear();
150150
151151 // Create a .js file (should NOT be ignored)
152- const jsFile = path.join(tempDir, 'test.js');
152+ const jsFile = path.join(tempDir, "test.js");
153153 fs.writeFileSync(jsFile, 'console.log("hello");');
154154
155155 // Wait for debounce with longer timeout for CI
156- await new Promise(resolve => setTimeout(resolve, 500));
156+ await new Promise((resolve) => setTimeout(resolve, 500));
157157
158158 // Should have been called because .js files are not in ignore patterns
159159 expect(callback).toHaveBeenCalled();
160160 });
161161
162- it('should allow unsubscribing from callbacks', async () => {
162+ it("should allow unsubscribing from callbacks", async () => {
163163 const callback = vi.fn();
164164 const unsubscribe = watcher.onChange(callback);
165165 watcher.startWatching(tempDir);
@@ -168,43 +168,43 @@
168168 unsubscribe();
169169
170170 // Create a new file
171- const testFile = path.join(tempDir, 'test.txt');
172- fs.writeFileSync(testFile, 'test content');
171+ const testFile = path.join(tempDir, "test.txt");
172+ fs.writeFileSync(testFile, "test content");
173173
174174 // Wait for debounce
175- await new Promise(resolve => setTimeout(resolve, 150));
175+ await new Promise((resolve) => setTimeout(resolve, 150));
176176
177177 // Should not have been called because we unsubscribed
178178 expect(callback).not.toHaveBeenCalled();
179179 });
180180
181- describe('shouldIgnorePath method', () => {
182- it('should correctly ignore wildcard file patterns', () => {
181+ describe("shouldIgnorePath method", () => {
182+ it("should correctly ignore wildcard file patterns", () => {
183183 const watcher = new FileWatcher();
184-
184+
185185 // Test the private method by accessing it through prototype
186186 const shouldIgnorePath = (watcher as any).shouldIgnorePath.bind(watcher);
187-
187+
188188 // Test wildcard file patterns
189- expect(shouldIgnorePath('/some/path/file.tmp')).toBe(true);
190- expect(shouldIgnorePath('/some/path/file.log')).toBe(true);
191- expect(shouldIgnorePath('/some/path/bundle.min.js')).toBe(true);
192- expect(shouldIgnorePath('/some/path/styles.min.css')).toBe(true);
193-
189+ expect(shouldIgnorePath("/some/path/file.tmp")).toBe(true);
190+ expect(shouldIgnorePath("/some/path/file.log")).toBe(true);
191+ expect(shouldIgnorePath("/some/path/bundle.min.js")).toBe(true);
192+ expect(shouldIgnorePath("/some/path/styles.min.css")).toBe(true);
193+
194194 // Test files that should NOT be ignored
195- expect(shouldIgnorePath('/some/path/file.js')).toBe(false);
196- expect(shouldIgnorePath('/some/path/file.ts')).toBe(false);
197- expect(shouldIgnorePath('/some/path/README.md')).toBe(false);
198-
195+ expect(shouldIgnorePath("/some/path/file.js")).toBe(false);
196+ expect(shouldIgnorePath("/some/path/file.ts")).toBe(false);
197+ expect(shouldIgnorePath("/some/path/README.md")).toBe(false);
198+
199199 // Test specific files
200- expect(shouldIgnorePath('/some/path/.DS_Store')).toBe(true);
201- expect(shouldIgnorePath('/some/path/Thumbs.db')).toBe(true);
202-
200+ expect(shouldIgnorePath("/some/path/.DS_Store")).toBe(true);
201+ expect(shouldIgnorePath("/some/path/Thumbs.db")).toBe(true);
202+
203203 // Test directory patterns
204- expect(shouldIgnorePath('/some/path/node_modules')).toBe(true);
205- expect(shouldIgnorePath('/some/path/node_modules/package')).toBe(true);
206- expect(shouldIgnorePath('/path/dist')).toBe(true);
207- expect(shouldIgnorePath('/path/.git')).toBe(true);
204+ expect(shouldIgnorePath("/some/path/node_modules")).toBe(true);
205+ expect(shouldIgnorePath("/some/path/node_modules/package")).toBe(true);
206+ expect(shouldIgnorePath("/path/dist")).toBe(true);
207+ expect(shouldIgnorePath("/path/.git")).toBe(true);
208208 });
209209 });
210210 });
modified extensions/cli/src/util/formatError.test.ts +80 −76
@@ -1,151 +1,155 @@
1-import { formatError, formatAnthropicError } from './formatError.js';
1+import { formatError, formatAnthropicError } from "./formatError.js";
22
3-describe('formatError', () => {
4- it('should format Error objects correctly', () => {
5- const error = new Error('Test error message');
6- expect(formatError(error)).toBe('Test error message');
3+describe("formatError", () => {
4+ it("should format Error objects correctly", () => {
5+ const error = new Error("Test error message");
6+ expect(formatError(error)).toBe("Test error message");
77 });
88
9- it('should return string errors as-is', () => {
10- const error = 'String error message';
11- expect(formatError(error)).toBe('String error message');
9+ it("should return string errors as-is", () => {
10+ const error = "String error message";
11+ expect(formatError(error)).toBe("String error message");
1212 });
1313
14- it('should extract message from error objects', () => {
15- const error = { message: 'Object error message' };
16- expect(formatError(error)).toBe('Object error message');
14+ it("should extract message from error objects", () => {
15+ const error = { message: "Object error message" };
16+ expect(formatError(error)).toBe("Object error message");
1717 });
1818
19- it('should recursively format nested error objects', () => {
20- const error = { error: { message: 'Nested error message' } };
21- expect(formatError(error)).toBe('Nested error message');
19+ it("should recursively format nested error objects", () => {
20+ const error = { error: { message: "Nested error message" } };
21+ expect(formatError(error)).toBe("Nested error message");
2222 });
2323
24- it('should extract details from error objects', () => {
25- const error = { details: 'Error details' };
26- expect(formatError(error)).toBe('Error details');
24+ it("should extract details from error objects", () => {
25+ const error = { details: "Error details" };
26+ expect(formatError(error)).toBe("Error details");
2727 });
2828
29- it('should extract description from error objects', () => {
30- const error = { description: 'Error description' };
31- expect(formatError(error)).toBe('Error description');
29+ it("should extract description from error objects", () => {
30+ const error = { description: "Error description" };
31+ expect(formatError(error)).toBe("Error description");
3232 });
3333
34- it('should format API errors with status and message', () => {
34+ it("should format API errors with status and message", () => {
3535 const error = {
3636 status: 404,
37- error: { message: 'Not found' }
37+ error: { message: "Not found" },
3838 };
3939 // The actual implementation prioritizes nested error.message over status formatting
40- expect(formatError(error)).toBe('Not found');
40+ expect(formatError(error)).toBe("Not found");
4141 });
4242
43- it('should format network errors with code and syscall', () => {
43+ it("should format network errors with code and syscall", () => {
4444 const error = {
45- code: 'ECONNREFUSED',
46- syscall: 'connect'
45+ code: "ECONNREFUSED",
46+ syscall: "connect",
4747 };
48- expect(formatError(error)).toBe('Network error: ECONNREFUSED in connect');
48+ expect(formatError(error)).toBe("Network error: ECONNREFUSED in connect");
4949 });
5050
51- it('should join error arrays', () => {
51+ it("should join error arrays", () => {
5252 const error = {
53- errors: ['First error', 'Second error', 'Third error']
53+ errors: ["First error", "Second error", "Third error"],
5454 };
55- expect(formatError(error)).toBe('First error, Second error, Third error');
55+ expect(formatError(error)).toBe("First error, Second error, Third error");
5656 });
5757
58- it('should JSON stringify complex objects', () => {
58+ it("should JSON stringify complex objects", () => {
5959 const error = {
60- code: 'CUSTOM_ERROR',
61- data: { id: 123, name: 'test' }
60+ code: "CUSTOM_ERROR",
61+ data: { id: 123, name: "test" },
6262 };
63- expect(formatError(error)).toBe('{"code":"CUSTOM_ERROR","data":{"id":123,"name":"test"}}');
63+ expect(formatError(error)).toBe(
64+ '{"code":"CUSTOM_ERROR","data":{"id":123,"name":"test"}}',
65+ );
6466 });
6567
66- it('should handle objects that cannot be JSON stringified', () => {
67- const circular: any = { name: 'circular' };
68+ it("should handle objects that cannot be JSON stringified", () => {
69+ const circular: any = { name: "circular" };
6870 circular.self = circular;
6971
7072 const result = formatError(circular);
71- expect(result).toBe('An error occurred: [object Object]');
73+ expect(result).toBe("An error occurred: [object Object]");
7274 });
7375
74- it('should handle null values', () => {
75- expect(formatError(null)).toBe('null');
76+ it("should handle null values", () => {
77+ expect(formatError(null)).toBe("null");
7678 });
7779
78- it('should handle undefined values', () => {
79- expect(formatError(undefined)).toBe('undefined');
80+ it("should handle undefined values", () => {
81+ expect(formatError(undefined)).toBe("undefined");
8082 });
8183
82- it('should handle numbers', () => {
83- expect(formatError(42)).toBe('42');
84+ it("should handle numbers", () => {
85+ expect(formatError(42)).toBe("42");
8486 });
8587
86- it('should handle boolean values', () => {
87- expect(formatError(true)).toBe('true');
88- expect(formatError(false)).toBe('false');
88+ it("should handle boolean values", () => {
89+ expect(formatError(true)).toBe("true");
90+ expect(formatError(false)).toBe("false");
8991 });
9092
91- it('should handle empty objects', () => {
92- expect(formatError({})).toBe('{}');
93+ it("should handle empty objects", () => {
94+ expect(formatError({})).toBe("{}");
9395 });
9496
95- it('should handle empty arrays', () => {
96- expect(formatError([])).toBe('[]');
97+ it("should handle empty arrays", () => {
98+ expect(formatError([])).toBe("[]");
9799 });
98100
99- it('should prioritize message over other properties', () => {
101+ it("should prioritize message over other properties", () => {
100102 const error = {
101- message: 'Primary message',
102- description: 'Secondary description',
103- details: 'Tertiary details'
103+ message: "Primary message",
104+ description: "Secondary description",
105+ details: "Tertiary details",
104106 };
105- expect(formatError(error)).toBe('Primary message');
107+ expect(formatError(error)).toBe("Primary message");
106108 });
107109
108- it('should prioritize error property over details', () => {
110+ it("should prioritize error property over details", () => {
109111 const error = {
110- error: 'Nested error',
111- details: 'Error details'
112+ error: "Nested error",
113+ details: "Error details",
112114 };
113- expect(formatError(error)).toBe('Nested error');
115+ expect(formatError(error)).toBe("Nested error");
114116 });
115117
116- it('should handle deeply nested error structures', () => {
118+ it("should handle deeply nested error structures", () => {
117119 const error = {
118120 error: {
119121 error: {
120- message: 'Deep nested error'
121- }
122- }
122+ message: "Deep nested error",
123+ },
124+ },
123125 };
124- expect(formatError(error)).toBe('Deep nested error');
126+ expect(formatError(error)).toBe("Deep nested error");
125127 });
126128
127- it('should format API errors with status only when no nested error message', () => {
129+ it("should format API errors with status only when no nested error message", () => {
128130 const error = {
129131 status: 404,
130- error: { code: 'NOT_FOUND' }
132+ error: { code: "NOT_FOUND" },
131133 };
132134 expect(formatError(error)).toBe('{"code":"NOT_FOUND"}');
133135 });
134136 });
135137
136-describe('formatAnthropicError', () => {
137- it('should format invalid API key authentication errors', () => {
138- const error = new Error('{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}');
139- expect(formatAnthropicError(error)).toBe('Anthropic: Invalid API key');
138+describe("formatAnthropicError", () => {
139+ it("should format invalid API key authentication errors", () => {
140+ const error = new Error(
141+ '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}',
142+ );
143+ expect(formatAnthropicError(error)).toBe("Anthropic: Invalid API key");
140144 });
141145
142- it('should handle error objects in general', () => {
143- const error = new Error('some error'); // some error we haven't catalogued yet
144- console.log(formatAnthropicError(error))
145- expect(formatAnthropicError(error)).toBe('Anthropic: some error');
146+ it("should handle error objects in general", () => {
147+ const error = new Error("some error"); // some error we haven't catalogued yet
148+ console.log(formatAnthropicError(error));
149+ expect(formatAnthropicError(error)).toBe("Anthropic: some error");
146150 });
147151
148- it('should handle undefined values', () => {
149- expect(formatAnthropicError(undefined)).toBe('Anthropic: undefined');
152+ it("should handle undefined values", () => {
153+ expect(formatAnthropicError(undefined)).toBe("Anthropic: undefined");
150154 });
151155 });
modified extensions/cli/src/util/git.test.ts +9 −10
@@ -1,9 +1,6 @@
11 import { beforeEach, describe, expect, it } from "vitest";
22
3-import {
4- getGitHubActionsRepoUrl,
5- isGitHubActions,
6-} from "./git.js";
3+import { getGitHubActionsRepoUrl, isGitHubActions } from "./git.js";
74
85 describe("git utilities - GitHub Actions detection", () => {
96 beforeEach(() => {
@@ -42,7 +39,7 @@
4239 it("should return GitHub URL with default server", () => {
4340 process.env.GITHUB_ACTIONS = "true";
4441 process.env.GITHUB_REPOSITORY = "owner/repo";
45-
42+
4643 expect(getGitHubActionsRepoUrl()).toBe("https://github.com/owner/repo");
4744 });
4845
@@ -50,8 +47,10 @@
5047 process.env.GITHUB_ACTIONS = "true";
5148 process.env.GITHUB_REPOSITORY = "owner/repo";
5249 process.env.GITHUB_SERVER_URL = "https://github.enterprise.com";
53-
54- expect(getGitHubActionsRepoUrl()).toBe("https://github.enterprise.com/owner/repo");
50+
51+ expect(getGitHubActionsRepoUrl()).toBe(
52+ "https://github.enterprise.com/owner/repo",
53+ );
5554 });
5655 });
5756
@@ -59,7 +58,7 @@
5958 it("should prioritize GitHub Actions environment variables", () => {
6059 process.env.GITHUB_ACTIONS = "true";
6160 process.env.GITHUB_REPOSITORY = "owner/repo";
62-
61+
6362 // Since we can't easily mock git commands, we'll rely on the fact that
6463 // GitHub Actions detection should take priority and return immediately
6564 const result = getGitHubActionsRepoUrl();
@@ -70,9 +69,9 @@
7069 process.env.GITHUB_ACTIONS = "true";
7170 process.env.GITHUB_REPOSITORY = "enterprise/repo";
7271 process.env.GITHUB_SERVER_URL = "https://git.company.com";
73-
72+
7473 const result = getGitHubActionsRepoUrl();
7574 expect(result).toBe("https://git.company.com/enterprise/repo");
7675 });
7776 });
78-});
No newline at the end of the file
77+});
modified extensions/cli/src/util/inputHistory.test.ts +32 −32
@@ -1,55 +1,55 @@
1-import { vi } from 'vitest';
1+import { vi } from "vitest";
22
3-import { InputHistory } from './inputHistory.js';
3+import { InputHistory } from "./inputHistory.js";
44
55 // Mock fs to avoid creating actual files during tests
6-vi.mock('fs', () => ({
6+vi.mock("fs", () => ({
77 default: {
88 existsSync: vi.fn(),
99 readFileSync: vi.fn(),
1010 writeFileSync: vi.fn(),
11- mkdirSync: vi.fn()
11+ mkdirSync: vi.fn(),
1212 },
1313 existsSync: vi.fn(),
1414 readFileSync: vi.fn(),
1515 writeFileSync: vi.fn(),
16- mkdirSync: vi.fn()
16+ mkdirSync: vi.fn(),
1717 }));
1818
19-describe('InputHistory', () => {
19+describe("InputHistory", () => {
2020 let inputHistory: InputHistory;
2121
2222 beforeEach(async () => {
2323 // Reset mocks and set up default behavior
2424 vi.clearAllMocks();
25- const fs = await import('fs');
25+ const fs = await import("fs");
2626 vi.mocked(fs.existsSync).mockReturnValue(false);
27- vi.mocked(fs.readFileSync).mockReturnValue('[]');
27+ vi.mocked(fs.readFileSync).mockReturnValue("[]");
2828
2929 inputHistory = new InputHistory();
3030 });
3131
32- describe('navigation with typed input preservation', () => {
32+ describe("navigation with typed input preservation", () => {
3333 beforeEach(() => {
3434 // Add some history entries
35- inputHistory.addEntry('first command');
36- inputHistory.addEntry('second command');
35+ inputHistory.addEntry("first command");
36+ inputHistory.addEntry("second command");
3737 });
3838
39- it('should preserve typed input when navigating history', () => {
40- const typedInput = 'user typed this';
39+ it("should preserve typed input when navigating history", () => {
40+ const typedInput = "user typed this";
4141
4242 // User types something then presses up arrow
4343 const historyEntry1 = inputHistory.navigateUp(typedInput);
44- expect(historyEntry1).toBe('second command');
44+ expect(historyEntry1).toBe("second command");
4545
4646 // Then presses down arrow - should get back their typed input
4747 const returnedInput = inputHistory.navigateDown();
48- expect(returnedInput).toBe('user typed this');
48+ expect(returnedInput).toBe("user typed this");
4949 });
5050
51- it('should handle multiple up/down navigation cycles', () => {
52- const typedInput = 'hello world';
51+ it("should handle multiple up/down navigation cycles", () => {
52+ const typedInput = "hello world";
5353
5454 // Navigate up twice, then back down twice
5555 inputHistory.navigateUp(typedInput);
@@ -57,32 +57,32 @@
5757 inputHistory.navigateDown(); // Go back one in history
5858 const result = inputHistory.navigateDown(); // Go back to original
5959
60- expect(result).toBe('hello world');
60+ expect(result).toBe("hello world");
6161 });
6262 });
6363
64- describe('basic navigation functionality', () => {
64+ describe("basic navigation functionality", () => {
6565 beforeEach(() => {
66- inputHistory.addEntry('command1');
67- inputHistory.addEntry('command2');
68- inputHistory.addEntry('command3');
66+ inputHistory.addEntry("command1");
67+ inputHistory.addEntry("command2");
68+ inputHistory.addEntry("command3");
6969 });
7070
71- it('should navigate up through history in reverse order', () => {
72- const result1 = inputHistory.navigateUp('current');
73- expect(result1).toBe('command3'); // Most recent first
71+ it("should navigate up through history in reverse order", () => {
72+ const result1 = inputHistory.navigateUp("current");
73+ expect(result1).toBe("command3"); // Most recent first
7474
75- const result2 = inputHistory.navigateUp('current');
76- expect(result2).toBe('command2');
75+ const result2 = inputHistory.navigateUp("current");
76+ expect(result2).toBe("command2");
7777
78- const result3 = inputHistory.navigateUp('current');
79- expect(result3).toBe('command1');
78+ const result3 = inputHistory.navigateUp("current");
79+ expect(result3).toBe("command1");
8080 });
8181
82- it('should handle navigation with no history', () => {
82+ it("should handle navigation with no history", () => {
8383 const emptyHistory = new InputHistory();
84- const result = emptyHistory.navigateUp('test');
84+ const result = emptyHistory.navigateUp("test");
8585 expect(result).toBe(null);
8686 });
8787 });
88-});
No newline at the end of the file
88+});
modified extensions/cli/src/util/stdin.test.ts +34 −34
@@ -24,28 +24,28 @@
2424 it("should return null in test environments", async () => {
2525 // Test that the function respects test environment variables
2626 process.env.NODE_ENV = "test";
27-
27+
2828 const { readStdinSync } = await import("./stdin.js");
2929 const result = readStdinSync();
30-
30+
3131 expect(result).toBe(null);
3232 });
3333
3434 it("should return null when CONTINUE_CLI_TEST is set", async () => {
3535 process.env.CONTINUE_CLI_TEST = "true";
36-
36+
3737 const { readStdinSync } = await import("./stdin.js");
3838 const result = readStdinSync();
39-
39+
4040 expect(result).toBe(null);
4141 });
4242
4343 it("should return null when VITEST is set", async () => {
4444 process.env.VITEST = "true";
45-
45+
4646 const { readStdinSync } = await import("./stdin.js");
4747 const result = readStdinSync();
48-
48+
4949 expect(result).toBe(null);
5050 });
5151
@@ -55,13 +55,13 @@
5555 delete process.env.VITEST;
5656 delete process.env.CONTINUE_CLI_TEST;
5757 delete process.env.JEST_WORKER_ID;
58-
58+
5959 // Mock stdin as TTY
6060 (process.stdin as any).isTTY = true;
61-
61+
6262 const { readStdinSync } = await import("./stdin.js");
6363 const result = readStdinSync();
64-
64+
6565 expect(result).toBe(null);
6666 });
6767
@@ -71,17 +71,17 @@
7171 delete process.env.VITEST;
7272 delete process.env.CONTINUE_CLI_TEST;
7373 delete process.env.JEST_WORKER_ID;
74-
74+
7575 // Mock stdin as not TTY (piped)
7676 (process.stdin as any).isTTY = false;
77-
77+
7878 // Mock fs.readFileSync to return test data
7979 const mockReadFileSync = vi.mocked(fs.readFileSync);
8080 mockReadFileSync.mockReturnValue("test input data");
81-
81+
8282 const { readStdinSync } = await import("./stdin.js");
8383 const result = readStdinSync();
84-
84+
8585 expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8");
8686 expect(result).toBe("test input data");
8787 });
@@ -92,19 +92,19 @@
9292 delete process.env.VITEST;
9393 delete process.env.CONTINUE_CLI_TEST;
9494 delete process.env.JEST_WORKER_ID;
95-
95+
9696 // Mock stdin as not TTY
9797 (process.stdin as any).isTTY = false;
98-
98+
9999 // Mock fs.readFileSync to throw an error
100100 const mockReadFileSync = vi.mocked(fs.readFileSync);
101101 mockReadFileSync.mockImplementation(() => {
102102 throw new Error("EAGAIN: resource temporarily unavailable");
103103 });
104-
104+
105105 const { readStdinSync } = await import("./stdin.js");
106106 const result = readStdinSync();
107-
107+
108108 expect(result).toBe(null);
109109 });
110110
@@ -114,17 +114,17 @@
114114 delete process.env.VITEST;
115115 delete process.env.CONTINUE_CLI_TEST;
116116 delete process.env.JEST_WORKER_ID;
117-
117+
118118 // Mock stdin as not TTY
119119 (process.stdin as any).isTTY = false;
120-
120+
121121 // Mock fs.readFileSync to return data with whitespace
122122 const mockReadFileSync = vi.mocked(fs.readFileSync);
123123 mockReadFileSync.mockReturnValue(" test input with whitespace \n");
124-
124+
125125 const { readStdinSync } = await import("./stdin.js");
126126 const result = readStdinSync();
127-
127+
128128 expect(result).toBe("test input with whitespace");
129129 });
130130
@@ -134,17 +134,17 @@
134134 delete process.env.VITEST;
135135 delete process.env.CONTINUE_CLI_TEST;
136136 delete process.env.JEST_WORKER_ID;
137-
137+
138138 // Mock stdin with undefined isTTY (some environments)
139139 (process.stdin as any).isTTY = undefined;
140-
140+
141141 // Mock fs.readFileSync to return test data
142142 const mockReadFileSync = vi.mocked(fs.readFileSync);
143143 mockReadFileSync.mockReturnValue("undefined tty test");
144-
144+
145145 const { readStdinSync } = await import("./stdin.js");
146146 const result = readStdinSync();
147-
147+
148148 expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8");
149149 expect(result).toBe("undefined tty test");
150150 });
@@ -156,13 +156,13 @@
156156 delete process.env.CONTINUE_CLI_TEST;
157157 delete process.env.JEST_WORKER_ID;
158158 process.env.CI = "true";
159-
159+
160160 // Mock stdin as TTY in CI
161161 (process.stdin as any).isTTY = true;
162-
162+
163163 const { readStdinSync } = await import("./stdin.js");
164164 const result = readStdinSync();
165-
165+
166166 // Should return null in CI when stdin is a TTY
167167 expect(result).toBe(null);
168168 });
@@ -172,7 +172,7 @@
172172 it("should work on different Node.js versions", async () => {
173173 // Test that the function doesn't rely on Node.js version-specific features
174174 const { readStdinSync } = await import("./stdin.js");
175-
175+
176176 // Should not throw errors regardless of environment
177177 expect(() => readStdinSync()).not.toThrow();
178178 });
@@ -183,20 +183,20 @@
183183 delete process.env.VITEST;
184184 delete process.env.CONTINUE_CLI_TEST;
185185 delete process.env.JEST_WORKER_ID;
186-
186+
187187 (process.stdin as any).isTTY = false;
188-
188+
189189 // Mock fs.readFileSync to simulate fd 0 not available
190190 const mockReadFileSync = vi.mocked(fs.readFileSync);
191191 mockReadFileSync.mockImplementation(() => {
192192 throw new Error("EBADF: bad file descriptor");
193193 });
194-
194+
195195 const { readStdinSync } = await import("./stdin.js");
196196 const result = readStdinSync();
197-
197+
198198 // Should handle the error gracefully
199199 expect(result).toBe(null);
200200 });
201201 });
202-});
No newline at the end of the file
202+});
modified extensions/cli/src/util/withExponentialBackoff.test.ts +5 −5
@@ -31,7 +31,7 @@
3131 const results: string[] = [];
3232 const generator = withExponentialBackoff(
3333 generatorFactory,
34- abortController.signal
34+ abortController.signal,
3535 );
3636
3737 for await (const chunk of generator) {
@@ -63,7 +63,7 @@
6363 {
6464 maxRetries: 2,
6565 initialDelay: 10, // Short delay for testing
66- }
66+ },
6767 );
6868
6969 for await (const chunk of generator) {
@@ -83,7 +83,7 @@
8383
8484 const generator = withExponentialBackoff(
8585 generatorFactory,
86- abortController.signal
86+ abortController.signal,
8787 );
8888
8989 await expect(async () => {
@@ -107,7 +107,7 @@
107107
108108 const generator = withExponentialBackoff(
109109 generatorFactory,
110- abortController.signal
110+ abortController.signal,
111111 );
112112
113113 await expect(async () => {
@@ -118,4 +118,4 @@
118118
119119 expect(generatorFactory).toHaveBeenCalledTimes(0);
120120 });
121-});
No newline at the end of the file
121+});
modified extensions/cli/src/util/yamlConfigUpdater.test.ts +92 −84
@@ -1,33 +1,33 @@
1-import { parse } from 'yaml';
2-
3-import { updateAnthropicModelInYaml } from './yamlConfigUpdater.js';
4-
5-describe('updateAnthropicModelInYaml', () => {
6- const testApiKey = 'TEST-ant-test123456789';
7-
8- describe('empty or invalid input', () => {
9- it('should create new config from empty string', () => {
10- const result = updateAnthropicModelInYaml('', testApiKey);
11-
12- expect(result).toContain('name: Local Config');
13- expect(result).toContain('version: 1.0.0');
14- expect(result).toContain('schema: v1');
15- expect(result).toContain('uses: anthropic/claude-4-sonnet');
16- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
1+import { parse } from "yaml";
2+
3+import { updateAnthropicModelInYaml } from "./yamlConfigUpdater.js";
4+
5+describe("updateAnthropicModelInYaml", () => {
6+ const testApiKey = "TEST-ant-test123456789";
7+
8+ describe("empty or invalid input", () => {
9+ it("should create new config from empty string", () => {
10+ const result = updateAnthropicModelInYaml("", testApiKey);
11+
12+ expect(result).toContain("name: Local Config");
13+ expect(result).toContain("version: 1.0.0");
14+ expect(result).toContain("schema: v1");
15+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
16+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
1717 });
1818
19- it('should create new config from invalid YAML', () => {
20- const invalidYaml = 'invalid: [yaml content';
19+ it("should create new config from invalid YAML", () => {
20+ const invalidYaml = "invalid: [yaml content";
2121 const result = updateAnthropicModelInYaml(invalidYaml, testApiKey);
22-
23- expect(result).toContain('name: Local Config');
24- expect(result).toContain('uses: anthropic/claude-4-sonnet');
25- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
22+
23+ expect(result).toContain("name: Local Config");
24+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
25+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
2626 });
2727 });
2828
29- describe('comment preservation', () => {
30- it('should preserve comments when adding new model', () => {
29+ describe("comment preservation", () => {
30+ it("should preserve comments when adding new model", () => {
3131 const yamlWithComments = `# My Continue config
3232 name: Local Config
3333 version: 1.0.0
@@ -40,15 +40,15 @@
4040 `;
4141
4242 const result = updateAnthropicModelInYaml(yamlWithComments, testApiKey);
43-
44- expect(result).toContain('# My Continue config');
45- expect(result).toContain('# List of available models');
46- expect(result).toContain('uses: openai/gpt-4');
47- expect(result).toContain('uses: anthropic/claude-4-sonnet');
48- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
43+
44+ expect(result).toContain("# My Continue config");
45+ expect(result).toContain("# List of available models");
46+ expect(result).toContain("uses: openai/gpt-4");
47+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
48+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
4949 });
5050
51- it('should preserve comments when updating existing model', () => {
51+ it("should preserve comments when updating existing model", () => {
5252 const yamlWithComments = `# My Continue config
5353 name: Local Config
5454 version: 1.0.0
@@ -61,17 +61,17 @@
6161 `;
6262
6363 const result = updateAnthropicModelInYaml(yamlWithComments, testApiKey);
64-
65- expect(result).toContain('# My Continue config');
66- expect(result).toContain('# List of available models');
67- expect(result).toContain('uses: anthropic/claude-4-sonnet');
68- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
69- expect(result).not.toContain('old-key');
64+
65+ expect(result).toContain("# My Continue config");
66+ expect(result).toContain("# List of available models");
67+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
68+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
69+ expect(result).not.toContain("old-key");
7070 });
7171 });
7272
73- describe('model management', () => {
74- it('should add new anthropic model when none exists', () => {
73+ describe("model management", () => {
74+ it("should add new anthropic model when none exists", () => {
7575 const existingConfig = `name: Local Config
7676 version: 1.0.0
7777 schema: v1
@@ -82,14 +82,14 @@
8282 `;
8383
8484 const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
85-
86- expect(result).toContain('uses: openai/gpt-4');
87- expect(result).toContain('uses: anthropic/claude-4-sonnet');
88- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
89- expect(result).toContain('OPENAI_API_KEY: TEST-openai-test');
85+
86+ expect(result).toContain("uses: openai/gpt-4");
87+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
88+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
89+ expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
9090 });
9191
92- it('should update existing anthropic model', () => {
92+ it("should update existing anthropic model", () => {
9393 const existingConfig = `name: Local Config
9494 version: 1.0.0
9595 schema: v1
@@ -103,49 +103,57 @@
103103 `;
104104
105105 const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
106-
107- expect(result).toContain('uses: anthropic/claude-4-sonnet');
108- expect(result).toContain('uses: openai/gpt-4');
109- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
110- expect(result).toContain('OPENAI_API_KEY: TEST-openai-test');
111- expect(result).not.toContain('old-anthropic-key');
112-
106+
107+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
108+ expect(result).toContain("uses: openai/gpt-4");
109+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
110+ expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
111+ expect(result).not.toContain("old-anthropic-key");
112+
113113 // Should only have one anthropic model
114- const anthropicMatches = result.match(/uses: anthropic\/claude-4-sonnet/g);
114+ const anthropicMatches = result.match(
115+ /uses: anthropic\/claude-4-sonnet/g,
116+ );
115117 expect(anthropicMatches).toHaveLength(1);
116118 });
117119
118- it('should handle config with no models array', () => {
120+ it("should handle config with no models array", () => {
119121 const configWithoutModels = `name: Local Config
120122 version: 1.0.0
121123 schema: v1
122124 `;
123125
124- const result = updateAnthropicModelInYaml(configWithoutModels, testApiKey);
125-
126- expect(result).toContain('name: Local Config');
127- expect(result).toContain('models:');
128- expect(result).toContain('uses: anthropic/claude-4-sonnet');
129- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
126+ const result = updateAnthropicModelInYaml(
127+ configWithoutModels,
128+ testApiKey,
129+ );
130+
131+ expect(result).toContain("name: Local Config");
132+ expect(result).toContain("models:");
133+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
134+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
130135 });
131136
132- it('should handle config with empty models array', () => {
137+ it("should handle config with empty models array", () => {
133138 const configWithEmptyModels = `name: Local Config
134139 version: 1.0.0
135140 schema: v1
136141 models: []
137142 `;
138143
139- const result = updateAnthropicModelInYaml(configWithEmptyModels, testApiKey);
140-
141- expect(result).toContain('name: Local Config');
142- expect(result).toContain('uses: anthropic/claude-4-sonnet');
143- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
144+ const result = updateAnthropicModelInYaml(
145+ configWithEmptyModels,
146+ testApiKey,
147+ );
148+
149+ expect(result).toContain("name: Local Config");
150+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
151+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
144152 });
145153 });
146154
147- describe('structure validation', () => {
148- it('should produce valid YAML that can be parsed', () => {
155+ describe("structure validation", () => {
156+ it("should produce valid YAML that can be parsed", () => {
149157 const input = `# Test config
150158 name: Test
151159 models:
@@ -153,16 +161,16 @@
153161 `;
154162
155163 const result = updateAnthropicModelInYaml(input, testApiKey);
156-
164+
157165 // Should not throw when parsing
158166 expect(() => {
159167 parse(result);
160168 }).not.toThrow();
161169 });
162170
163- it('should maintain proper YAML structure', () => {
164- const result = updateAnthropicModelInYaml('', testApiKey);
165-
171+ it("should maintain proper YAML structure", () => {
172+ const result = updateAnthropicModelInYaml("", testApiKey);
173+
166174 expect(result).toMatch(/^name: /m);
167175 expect(result).toMatch(/^version: /m);
168176 expect(result).toMatch(/^schema: /m);
@@ -173,29 +181,29 @@
173181 });
174182 });
175183
176- describe('edge cases', () => {
177- it('should handle malformed models array gracefully', () => {
184+ describe("edge cases", () => {
185+ it("should handle malformed models array gracefully", () => {
178186 const malformedConfig = `name: Local Config
179187 models: "not an array"
180188 `;
181189
182190 const result = updateAnthropicModelInYaml(malformedConfig, testApiKey);
183-
184- expect(result).toContain('uses: anthropic/claude-4-sonnet');
185- expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
191+
192+ expect(result).toContain("uses: anthropic/claude-4-sonnet");
193+ expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
186194 });
187195
188- it('should handle different API key formats', () => {
196+ it("should handle different API key formats", () => {
189197 const differentKeys = [
190- 'TEST-ant-1234567890',
191- 'TEST-ant-abcdefghijklmnop',
192- 'TEST-ant-test-key-with-dashes'
198+ "TEST-ant-1234567890",
199+ "TEST-ant-abcdefghijklmnop",
200+ "TEST-ant-test-key-with-dashes",
193201 ];
194202
195- differentKeys.forEach(key => {
196- const result = updateAnthropicModelInYaml('', key);
203+ differentKeys.forEach((key) => {
204+ const result = updateAnthropicModelInYaml("", key);
197205 expect(result).toContain(`ANTHROPIC_API_KEY: ${key}`);
198206 });
199207 });
200208 });
201-});
No newline at the end of the file
209+});
modified extensions/cli/src/utils/modelCapability.test.ts +90 −86
@@ -1,149 +1,153 @@
1-import { isModelCapable } from './modelCapability.js';
1+import { isModelCapable } from "./modelCapability.js";
22
3-describe('isModelCapable', () => {
4- describe('OpenAI models', () => {
5- test('should consider GPT-4 models as capable', () => {
6- expect(isModelCapable('openai', 'gpt-4')).toBe(true);
7- expect(isModelCapable('openai', 'gpt-4-turbo')).toBe(true);
8- expect(isModelCapable('openai', 'gpt-4-0613')).toBe(true);
3+describe("isModelCapable", () => {
4+ describe("OpenAI models", () => {
5+ test("should consider GPT-4 models as capable", () => {
6+ expect(isModelCapable("openai", "gpt-4")).toBe(true);
7+ expect(isModelCapable("openai", "gpt-4-turbo")).toBe(true);
8+ expect(isModelCapable("openai", "gpt-4-0613")).toBe(true);
99 });
1010
11- test('should consider GPT-3.5-turbo as capable', () => {
12- expect(isModelCapable('openai', 'gpt-3.5-turbo')).toBe(true);
13- expect(isModelCapable('openai', 'gpt-3.5-turbo-16k')).toBe(true);
11+ test("should consider GPT-3.5-turbo as capable", () => {
12+ expect(isModelCapable("openai", "gpt-3.5-turbo")).toBe(true);
13+ expect(isModelCapable("openai", "gpt-3.5-turbo-16k")).toBe(true);
1414 });
1515
16- test('should consider O-series models as capable', () => {
17- expect(isModelCapable('openai', 'o1-preview')).toBe(true);
18- expect(isModelCapable('openai', 'o1-mini')).toBe(true);
19- expect(isModelCapable('openai', 'o3')).toBe(true);
16+ test("should consider O-series models as capable", () => {
17+ expect(isModelCapable("openai", "o1-preview")).toBe(true);
18+ expect(isModelCapable("openai", "o1-mini")).toBe(true);
19+ expect(isModelCapable("openai", "o3")).toBe(true);
2020 });
2121
22- test('should consider older GPT-3 models as capable', () => {
23- expect(isModelCapable('openai', 'gpt-3-davinci')).toBe(true);
24- expect(isModelCapable('openai', 'gpt-3-curie')).toBe(true);
22+ test("should consider older GPT-3 models as capable", () => {
23+ expect(isModelCapable("openai", "gpt-3-davinci")).toBe(true);
24+ expect(isModelCapable("openai", "gpt-3-curie")).toBe(true);
2525 });
2626 });
2727
28- describe('Anthropic models', () => {
29- test('should consider Claude-3 models as capable', () => {
30- expect(isModelCapable('anthropic', 'claude-3-opus')).toBe(true);
31- expect(isModelCapable('anthropic', 'claude-3-sonnet')).toBe(true);
28+ describe("Anthropic models", () => {
29+ test("should consider Claude-3 models as capable", () => {
30+ expect(isModelCapable("anthropic", "claude-3-opus")).toBe(true);
31+ expect(isModelCapable("anthropic", "claude-3-sonnet")).toBe(true);
3232 });
3333
34- test('should consider Claude-2 as capable', () => {
35- expect(isModelCapable('anthropic', 'claude-2')).toBe(true);
36- expect(isModelCapable('anthropic', 'claude-2.1')).toBe(true);
34+ test("should consider Claude-2 as capable", () => {
35+ expect(isModelCapable("anthropic", "claude-2")).toBe(true);
36+ expect(isModelCapable("anthropic", "claude-2.1")).toBe(true);
3737 });
3838
39- test('should consider Claude-1 as capable', () => {
40- expect(isModelCapable('anthropic', 'claude-1')).toBe(true);
39+ test("should consider Claude-1 as capable", () => {
40+ expect(isModelCapable("anthropic", "claude-1")).toBe(true);
4141 });
4242 });
4343
44- describe('Google models', () => {
45- test('should consider Gemini Pro models as capable', () => {
46- expect(isModelCapable('google', 'gemini-pro')).toBe(true);
47- expect(isModelCapable('gemini', 'gemini-ultra')).toBe(true);
44+ describe("Google models", () => {
45+ test("should consider Gemini Pro models as capable", () => {
46+ expect(isModelCapable("google", "gemini-pro")).toBe(true);
47+ expect(isModelCapable("gemini", "gemini-ultra")).toBe(true);
4848 });
4949
50- test('should consider PaLM-2 models as not capable', () => {
51- expect(isModelCapable('google', 'palm-2-chat')).toBe(false);
50+ test("should consider PaLM-2 models as not capable", () => {
51+ expect(isModelCapable("google", "palm-2-chat")).toBe(false);
5252 });
5353 });
5454
55- describe('Local/Ollama models', () => {
56- test('should consider larger models as not capable', () => {
57- expect(isModelCapable('ollama', 'llama2-70b')).toBe(false);
58- expect(isModelCapable('local', 'codellama-34b')).toBe(false);
55+ describe("Local/Ollama models", () => {
56+ test("should consider larger models as not capable", () => {
57+ expect(isModelCapable("ollama", "llama2-70b")).toBe(false);
58+ expect(isModelCapable("local", "codellama-34b")).toBe(false);
5959 });
6060
61- test('should consider smaller models as less capable', () => {
62- expect(isModelCapable('ollama', 'llama2-7b')).toBe(false);
63- expect(isModelCapable('local', 'mistral-7b')).toBe(false);
61+ test("should consider smaller models as less capable", () => {
62+ expect(isModelCapable("ollama", "llama2-7b")).toBe(false);
63+ expect(isModelCapable("local", "mistral-7b")).toBe(false);
6464 });
6565 });
6666
67- describe('Meta/Llama models', () => {
68- test('should consider large Llama models as not capable', () => {
69- expect(isModelCapable('llama', 'llama-2-70b')).toBe(false);
70- expect(isModelCapable('meta', 'llama-65b')).toBe(false);
67+ describe("Meta/Llama models", () => {
68+ test("should consider large Llama models as not capable", () => {
69+ expect(isModelCapable("llama", "llama-2-70b")).toBe(false);
70+ expect(isModelCapable("meta", "llama-65b")).toBe(false);
7171 });
7272
73- test('should consider small Llama models as less capable', () => {
74- expect(isModelCapable('llama', 'llama-2-7b')).toBe(false);
75- expect(isModelCapable('meta', 'llama-13b')).toBe(false);
73+ test("should consider small Llama models as less capable", () => {
74+ expect(isModelCapable("llama", "llama-2-7b")).toBe(false);
75+ expect(isModelCapable("meta", "llama-13b")).toBe(false);
7676 });
7777 });
7878
79- describe('Continue Proxy models', () => {
80- test('should consider continue-proxy models as not capable', () => {
81- expect(isModelCapable('continue-proxy', 'any-model')).toBe(false);
79+ describe("Continue Proxy models", () => {
80+ test("should consider continue-proxy models as not capable", () => {
81+ expect(isModelCapable("continue-proxy", "any-model")).toBe(false);
8282 });
8383 });
8484
85- describe('Hugging Face models', () => {
86- test('should consider code-specific models as not capable', () => {
87- expect(isModelCapable('huggingface', 'codellama-instruct')).toBe(false);
88- expect(isModelCapable('huggingface', 'starcoder-base')).toBe(false);
85+ describe("Hugging Face models", () => {
86+ test("should consider code-specific models as not capable", () => {
87+ expect(isModelCapable("huggingface", "codellama-instruct")).toBe(false);
88+ expect(isModelCapable("huggingface", "starcoder-base")).toBe(false);
8989 });
9090
91- test('should consider general chat models as less capable', () => {
92- expect(isModelCapable('huggingface', 'falcon-7b')).toBe(false);
91+ test("should consider general chat models as less capable", () => {
92+ expect(isModelCapable("huggingface", "falcon-7b")).toBe(false);
9393 });
9494 });
9595
96- describe('Unknown providers', () => {
97- test('should default to not capable for unknown providers', () => {
98- expect(isModelCapable('unknown-provider', 'some-model')).toBe(false);
96+ describe("Unknown providers", () => {
97+ test("should default to not capable for unknown providers", () => {
98+ expect(isModelCapable("unknown-provider", "some-model")).toBe(false);
9999 });
100100 });
101101
102- describe('Other capable models', () => {
103- test('should consider Qwen models as capable', () => {
104- expect(isModelCapable('alibaba', 'qwen-turbo')).toBe(true);
105- expect(isModelCapable('dashscope', 'qwen-max')).toBe(true);
102+ describe("Other capable models", () => {
103+ test("should consider Qwen models as capable", () => {
104+ expect(isModelCapable("alibaba", "qwen-turbo")).toBe(true);
105+ expect(isModelCapable("dashscope", "qwen-max")).toBe(true);
106106 });
107107
108- test('should consider Kimi models as capable', () => {
109- expect(isModelCapable('moonshot', 'kimi-8k')).toBe(true);
110- expect(isModelCapable('moonshot', 'kimi-32k')).toBe(true);
108+ test("should consider Kimi models as capable", () => {
109+ expect(isModelCapable("moonshot", "kimi-8k")).toBe(true);
110+ expect(isModelCapable("moonshot", "kimi-32k")).toBe(true);
111111 });
112112 });
113113
114- describe('Case insensitivity', () => {
115- test('should handle different cases correctly', () => {
116- expect(isModelCapable('OPENAI', 'GPT-4')).toBe(true);
117- expect(isModelCapable('OpenAI', 'Gpt-4-Turbo')).toBe(true);
118- expect(isModelCapable('anthropic', 'CLAUDE-3-OPUS')).toBe(true);
114+ describe("Case insensitivity", () => {
115+ test("should handle different cases correctly", () => {
116+ expect(isModelCapable("OPENAI", "GPT-4")).toBe(true);
117+ expect(isModelCapable("OpenAI", "Gpt-4-Turbo")).toBe(true);
118+ expect(isModelCapable("anthropic", "CLAUDE-3-OPUS")).toBe(true);
119119 });
120120 });
121121
122- describe('Model property matching', () => {
123- test('should consider models capable when model property matches even if name does not', () => {
122+ describe("Model property matching", () => {
123+ test("should consider models capable when model property matches even if name does not", () => {
124124 // Case where name doesn't match but model property does
125- expect(isModelCapable('custom', 'some-custom-name', 'gpt-4')).toBe(true);
126- expect(isModelCapable('custom', 'random-name', 'claude-3-opus')).toBe(true);
127- expect(isModelCapable('custom', 'xyz', 'gemini-pro')).toBe(true);
125+ expect(isModelCapable("custom", "some-custom-name", "gpt-4")).toBe(true);
126+ expect(isModelCapable("custom", "random-name", "claude-3-opus")).toBe(
127+ true,
128+ );
129+ expect(isModelCapable("custom", "xyz", "gemini-pro")).toBe(true);
128130 });
129131
130- test('should consider models capable when name matches even if model property does not', () => {
132+ test("should consider models capable when name matches even if model property does not", () => {
131133 // Case where name matches but model property doesn't
132- expect(isModelCapable('custom', 'gpt-4', 'some-internal-id')).toBe(true);
133- expect(isModelCapable('custom', 'claude-3-opus', 'xyz')).toBe(true);
134- expect(isModelCapable('custom', 'gemini-pro', 'random')).toBe(true);
134+ expect(isModelCapable("custom", "gpt-4", "some-internal-id")).toBe(true);
135+ expect(isModelCapable("custom", "claude-3-opus", "xyz")).toBe(true);
136+ expect(isModelCapable("custom", "gemini-pro", "random")).toBe(true);
135137 });
136138
137- test('should consider models capable when both name and model match', () => {
139+ test("should consider models capable when both name and model match", () => {
138140 // Case where both match
139- expect(isModelCapable('openai', 'gpt-4', 'gpt-4-turbo')).toBe(true);
140- expect(isModelCapable('anthropic', 'claude-3', 'claude-3-opus')).toBe(true);
141+ expect(isModelCapable("openai", "gpt-4", "gpt-4-turbo")).toBe(true);
142+ expect(isModelCapable("anthropic", "claude-3", "claude-3-opus")).toBe(
143+ true,
144+ );
141145 });
142146
143- test('should consider models not capable when neither name nor model match', () => {
147+ test("should consider models not capable when neither name nor model match", () => {
144148 // Case where neither matches
145- expect(isModelCapable('custom', 'llama-7b', 'local-model')).toBe(false);
146- expect(isModelCapable('custom', 'falcon-7b', 'random-model')).toBe(false);
149+ expect(isModelCapable("custom", "llama-7b", "local-model")).toBe(false);
150+ expect(isModelCapable("custom", "falcon-7b", "random-model")).toBe(false);
147151 });
148152 });
149-});
No newline at the end of the file
153+});