Changesets · Branches · Tags · Compare
| Changeset | 8f5864c6cb09ddcb0a35acdfbc779eddc2306491039c158e24de77f79af78f07 |
|---|---|
| Author | Nate <sestinj@gmail.com> · 2025-08-20 17:57 -07:00 |
| Committer | Nate <sestinj@gmail.com> · 2025-08-20 17:57 -07:00 |
| Parents | 6330d6e8d792 |
101 files changed
modified extensions/cli/AGENTS.md +5 −0
| @@ -18,25 +18,30 @@ | ||
| 18 | 18 | ### Core Components |
| 19 | 19 | |
| 20 | 20 | 1. **Entry Point** (`src/index.ts`): Main CLI logic with two modes: |
| 21 | + | |
| 21 | 22 | - **Headless mode**: Non-interactive mode for automation/CI |
| 22 | 23 | - **TUI mode**: Terminal User Interface using Ink/React |
| 23 | 24 | - **Standard mode**: Traditional readline-based chat interface |
| 24 | 25 | |
| 25 | 26 | 2. **Authentication** (`src/auth/`): WorkOS-based authentication system |
| 27 | + | |
| 26 | 28 | - `ensureAuth.ts`: Handles authentication flow |
| 27 | 29 | - `workos.ts`: WorkOS configuration and token management |
| 28 | 30 | |
| 29 | 31 | 3. **Continue SDK Integration** (`src/continueSDK.ts`): Initializes the Continue SDK client with: |
| 32 | + | |
| 30 | 33 | - API key authentication |
| 31 | 34 | - Assistant configuration (slug-based) |
| 32 | 35 | - Organization support |
| 33 | 36 | |
| 34 | 37 | 4. **Terminal UI** (`src/ui/`): React/Ink-based TUI components |
| 38 | + | |
| 35 | 39 | - `TUIChat.tsx`: Main chat interface component |
| 36 | 40 | - `UserInput.tsx`: Input handling with multi-line support |
| 37 | 41 | - `TextBuffer.ts`: Text display utilities |
| 38 | 42 | |
| 39 | 43 | 5. **Tools System** (`src/tools/`): Built-in development tools including: |
| 44 | + | |
| 40 | 45 | - File operations (read, write, list) |
| 41 | 46 | - Code search functionality |
| 42 | 47 | - Terminal command execution |
modified extensions/cli/spec/config-loading.md +2 −0
| @@ -23,11 +23,13 @@ | ||
| 23 | 23 | **When CLI is invoked, config source is determined in this order:** |
| 24 | 24 | |
| 25 | 25 | 1. **CLI `--config` Flag** (highest priority) |
| 26 | + | |
| 26 | 27 | - File path (starts with `.`, `/`, `~`): Loads local YAML file |
| 27 | 28 | - Assistant slug (`owner/package`): Fetches from Continue platform |
| 28 | 29 | - Overrides any saved preferences |
| 29 | 30 | |
| 30 | 31 | 2. **Saved Config URI** (if no `--config` flag) |
| 32 | + | |
| 31 | 33 | - Retrieved from authentication config |
| 32 | 34 | - Converts `file://` URIs back to file paths |
| 33 | 35 | - Converts `slug://` URIs back to assistant slugs |
modified extensions/cli/spec/onboarding.md +1 −0
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | 1. If the --config flag is provided, load this config |
| 10 | 10 | 2. Otherwise, we will present the user with two options: |
| 11 | + | |
| 11 | 12 | - 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 |
| 12 | 13 | - 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 |
| 13 | 14 |
modified extensions/cli/src/args.test.ts +33 −32
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { vi } from 'vitest'; | |
| 1 | +import { vi } from "vitest"; | |
| 2 | 2 | |
| 3 | 3 | import { parseArgs, processRule } from "./args.js"; |
| 4 | 4 | |
| @@ -20,7 +20,6 @@ | ||
| 20 | 20 | expect(result).toEqual({}); |
| 21 | 21 | }); |
| 22 | 22 | |
| 23 | - | |
| 24 | 23 | it("should set resume to true when --resume flag is present", () => { |
| 25 | 24 | process.argv = ["node", "script.js", "--resume"]; |
| 26 | 25 | const result = parseArgs(); |
| @@ -33,7 +32,6 @@ | ||
| 33 | 32 | expect(result.readonly).toBe(true); |
| 34 | 33 | }); |
| 35 | 34 | |
| 36 | - | |
| 37 | 35 | it("should parse config path from --config flag", () => { |
| 38 | 36 | process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"]; |
| 39 | 37 | const result = parseArgs(); |
| @@ -189,8 +187,7 @@ | ||
| 189 | 187 | it("should handle empty arguments array", () => { |
| 190 | 188 | process.argv = ["node", "script.js"]; |
| 191 | 189 | const result = parseArgs(); |
| 192 | - expect(result).toEqual({ | |
| 193 | - }); | |
| 190 | + expect(result).toEqual({}); | |
| 194 | 191 | }); |
| 195 | 192 | |
| 196 | 193 | it("should handle multiple boolean flags", () => { |
| @@ -224,7 +221,7 @@ | ||
| 224 | 221 | // Mock fetch for hub tests |
| 225 | 222 | const originalFetch = global.fetch; |
| 226 | 223 | const mockFetch = vi.fn() as any; |
| 227 | - | |
| 224 | + | |
| 228 | 225 | beforeAll(() => { |
| 229 | 226 | global.fetch = mockFetch; |
| 230 | 227 | }); |
| @@ -232,7 +229,7 @@ | ||
| 232 | 229 | afterAll(() => { |
| 233 | 230 | global.fetch = originalFetch; |
| 234 | 231 | }); |
| 235 | - | |
| 232 | + | |
| 236 | 233 | beforeEach(() => { |
| 237 | 234 | mockFetch.mockClear(); |
| 238 | 235 | }); |
| @@ -242,11 +239,12 @@ | ||
| 242 | 239 | // Create a mock zip file containing a markdown rule |
| 243 | 240 | const JSZip = (await import("jszip")).default; |
| 244 | 241 | 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."; | |
| 246 | 244 | zip.file("rule.md", ruleContent); |
| 247 | - | |
| 245 | + | |
| 248 | 246 | const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); |
| 249 | - | |
| 247 | + | |
| 250 | 248 | // Mock successful fetch response |
| 251 | 249 | mockFetch.mockResolvedValue({ |
| 252 | 250 | ok: true, |
| @@ -254,10 +252,13 @@ | ||
| 254 | 252 | } as Response); |
| 255 | 253 | |
| 256 | 254 | const result = await processRule("continuedev/sentry-nextjs"); |
| 257 | - | |
| 255 | + | |
| 258 | 256 | expect(result).toBe(ruleContent); |
| 259 | 257 | 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 | + ), | |
| 261 | 262 | ); |
| 262 | 263 | }); |
| 263 | 264 | |
| @@ -269,7 +270,7 @@ | ||
| 269 | 270 | } as Response); |
| 270 | 271 | |
| 271 | 272 | 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', | |
| 273 | 274 | ); |
| 274 | 275 | }); |
| 275 | 276 | |
| @@ -277,7 +278,7 @@ | ||
| 277 | 278 | mockFetch.mockRejectedValue(new Error("Network error")); |
| 278 | 279 | |
| 279 | 280 | 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', | |
| 281 | 282 | ); |
| 282 | 283 | }); |
| 283 | 284 | |
| @@ -285,7 +286,7 @@ | ||
| 285 | 286 | // "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug |
| 286 | 287 | // Let's test with a slug that has wrong format but contains "/" |
| 287 | 288 | 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', | |
| 289 | 290 | ); |
| 290 | 291 | }); |
| 291 | 292 | |
| @@ -293,14 +294,14 @@ | ||
| 293 | 294 | const JSZip = (await import("jszip")).default; |
| 294 | 295 | const zip = new JSZip(); |
| 295 | 296 | const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); |
| 296 | - | |
| 297 | + | |
| 297 | 298 | mockFetch.mockResolvedValue({ |
| 298 | 299 | ok: true, |
| 299 | 300 | arrayBuffer: () => Promise.resolve(zipBuffer), |
| 300 | 301 | } as Response); |
| 301 | 302 | |
| 302 | 303 | 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', | |
| 304 | 305 | ); |
| 305 | 306 | }); |
| 306 | 307 | |
| @@ -309,14 +310,14 @@ | ||
| 309 | 310 | const zip = new JSZip(); |
| 310 | 311 | zip.folder("docs"); // Create a directory but no files |
| 311 | 312 | const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); |
| 312 | - | |
| 313 | + | |
| 313 | 314 | mockFetch.mockResolvedValue({ |
| 314 | 315 | ok: true, |
| 315 | 316 | arrayBuffer: () => Promise.resolve(zipBuffer), |
| 316 | 317 | } as Response); |
| 317 | 318 | |
| 318 | 319 | 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', | |
| 320 | 321 | ); |
| 321 | 322 | }); |
| 322 | 323 | |
| @@ -325,20 +326,20 @@ | ||
| 325 | 326 | const zip = new JSZip(); |
| 326 | 327 | const mdContent = "# Main Rule\n\nThis is the markdown rule content."; |
| 327 | 328 | const txtContent = "This is just a text file."; |
| 328 | - | |
| 329 | + | |
| 329 | 330 | zip.file("README.txt", txtContent); |
| 330 | 331 | zip.file("rule.md", mdContent); |
| 331 | 332 | zip.file("package.json", '{"name": "test"}'); |
| 332 | - | |
| 333 | + | |
| 333 | 334 | const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); |
| 334 | - | |
| 335 | + | |
| 335 | 336 | mockFetch.mockResolvedValue({ |
| 336 | 337 | ok: true, |
| 337 | 338 | arrayBuffer: () => Promise.resolve(zipBuffer), |
| 338 | 339 | } as Response); |
| 339 | 340 | |
| 340 | 341 | const result = await processRule("continuedev/mixed-files"); |
| 341 | - | |
| 342 | + | |
| 342 | 343 | expect(result).toBe(mdContent); |
| 343 | 344 | }); |
| 344 | 345 | |
| @@ -347,33 +348,33 @@ | ||
| 347 | 348 | const zip = new JSZip(); |
| 348 | 349 | const rule1Content = "# First Rule\n\nThis is the first rule."; |
| 349 | 350 | const rule2Content = "# Second Rule\n\nThis is the second rule."; |
| 350 | - | |
| 351 | + | |
| 351 | 352 | zip.file("rule1.md", rule1Content); |
| 352 | 353 | zip.file("rule2.md", rule2Content); |
| 353 | - | |
| 354 | + | |
| 354 | 355 | const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); |
| 355 | - | |
| 356 | + | |
| 356 | 357 | mockFetch.mockResolvedValue({ |
| 357 | 358 | ok: true, |
| 358 | 359 | arrayBuffer: () => Promise.resolve(zipBuffer), |
| 359 | 360 | } as Response); |
| 360 | 361 | |
| 361 | 362 | const result = await processRule("continuedev/multiple-rules"); |
| 362 | - | |
| 363 | + | |
| 363 | 364 | // Should use the first markdown file found (alphabetically) |
| 364 | 365 | expect(result).toBe(rule1Content); |
| 365 | 366 | }); |
| 366 | 367 | |
| 367 | 368 | it("should handle malformed zip files", async () => { |
| 368 | 369 | const invalidZipBuffer = new ArrayBuffer(10); |
| 369 | - | |
| 370 | + | |
| 370 | 371 | mockFetch.mockResolvedValue({ |
| 371 | 372 | ok: true, |
| 372 | 373 | arrayBuffer: () => Promise.resolve(invalidZipBuffer), |
| 373 | 374 | } as Response); |
| 374 | 375 | |
| 375 | 376 | 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"', | |
| 377 | 378 | ); |
| 378 | 379 | }); |
| 379 | 380 | }); |
| @@ -384,7 +385,7 @@ | ||
| 384 | 385 | const zip = new JSZip(); |
| 385 | 386 | zip.file("rule.md", "# Hub Rule"); |
| 386 | 387 | const zipBuffer = await zip.generateAsync({ type: "arraybuffer" }); |
| 387 | - | |
| 388 | + | |
| 388 | 389 | mockFetch.mockResolvedValue({ |
| 389 | 390 | ok: true, |
| 390 | 391 | arrayBuffer: () => Promise.resolve(zipBuffer), |
| @@ -406,9 +407,9 @@ | ||
| 406 | 407 | // This would be treated as a file path, not a hub slug |
| 407 | 408 | // since it starts with "." |
| 408 | 409 | 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', | |
| 410 | 411 | ); |
| 411 | 412 | expect(mockFetch).not.toHaveBeenCalled(); |
| 412 | 413 | }); |
| 413 | 414 | }); |
| 414 | -}); | |
| No newline at the end of the file | ||
| 415 | +}); |
modified extensions/cli/src/asciiArt.test.ts +7 −7
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | |
| 5 | 5 | describe("asciiArt", () => { |
| 6 | 6 | let originalColumns: number | undefined; |
| 7 | - | |
| 7 | + | |
| 8 | 8 | beforeEach(() => { |
| 9 | 9 | originalColumns = process.stdout.columns; |
| 10 | 10 | }); |
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | process.stdout.columns = 80; |
| 24 | 24 | |
| 25 | 25 | const result = getDisplayableAsciiArt(); |
| 26 | - | |
| 26 | + | |
| 27 | 27 | expect(result).toBe(CONTINUE_ASCII_ART); |
| 28 | 28 | }); |
| 29 | 29 | |
| @@ -32,7 +32,7 @@ | ||
| 32 | 32 | process.stdout.columns = 60; |
| 33 | 33 | |
| 34 | 34 | const result = getDisplayableAsciiArt(); |
| 35 | - | |
| 35 | + | |
| 36 | 36 | expect(result).toContain("CONTINUE"); |
| 37 | 37 | expect(result).toContain("v0.0.0-dev"); |
| 38 | 38 | expect(result).not.toBe(CONTINUE_ASCII_ART); |
| @@ -45,7 +45,7 @@ | ||
| 45 | 45 | process.stdout.columns = 74; |
| 46 | 46 | |
| 47 | 47 | const result = getDisplayableAsciiArt(); |
| 48 | - | |
| 48 | + | |
| 49 | 49 | expect(result).toContain("CONTINUE"); |
| 50 | 50 | expect(result).not.toBe(CONTINUE_ASCII_ART); |
| 51 | 51 | }); |
| @@ -55,7 +55,7 @@ | ||
| 55 | 55 | process.stdout.columns = 75; |
| 56 | 56 | |
| 57 | 57 | const result = getDisplayableAsciiArt(); |
| 58 | - | |
| 58 | + | |
| 59 | 59 | expect(result).toBe(CONTINUE_ASCII_ART); |
| 60 | 60 | }); |
| 61 | 61 | |
| @@ -64,8 +64,8 @@ | ||
| 64 | 64 | delete (process.stdout as any).columns; |
| 65 | 65 | |
| 66 | 66 | const result = getDisplayableAsciiArt(); |
| 67 | - | |
| 67 | + | |
| 68 | 68 | expect(result).toBe(CONTINUE_ASCII_ART); |
| 69 | 69 | }); |
| 70 | 70 | }); |
| 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 @@ | ||
| 79 | 79 | const consoleInfoSpy = vi.spyOn(console, "info"); |
| 80 | 80 | |
| 81 | 81 | await expect( |
| 82 | - ensureOrganization(mockAuthConfig, true, "invalid-org") | |
| 82 | + ensureOrganization(mockAuthConfig, true, "invalid-org"), | |
| 83 | 83 | ).rejects.toThrow('Organization "invalid-org" not found'); |
| 84 | 84 | |
| 85 | 85 | expect(consoleInfoSpy).toHaveBeenCalledWith( |
| 86 | 86 | chalk.yellow("Available organizations:"), |
| 87 | - expect.stringContaining("personal") | |
| 87 | + expect.stringContaining("personal"), | |
| 88 | 88 | ); |
| 89 | 89 | }); |
| 90 | 90 | }); |
| @@ -99,13 +99,13 @@ | ||
| 99 | 99 | }); |
| 100 | 100 | |
| 101 | 101 | await expect( |
| 102 | - ensureOrganization(mockAuthConfig, false, "org-one") | |
| 102 | + ensureOrganization(mockAuthConfig, false, "org-one"), | |
| 103 | 103 | ).rejects.toThrow("Process exit"); |
| 104 | 104 | |
| 105 | 105 | expect(consoleErrorSpy).toHaveBeenCalledWith( |
| 106 | 106 | 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 | + ), | |
| 109 | 109 | ); |
| 110 | 110 | expect(processExitSpy).toHaveBeenCalledWith(1); |
| 111 | 111 | |
| @@ -141,7 +141,7 @@ | ||
| 141 | 141 | const result = await ensureOrganization( |
| 142 | 142 | mockEnvAuthConfig, |
| 143 | 143 | true, |
| 144 | - "org-two" | |
| 144 | + "org-two", | |
| 145 | 145 | ); |
| 146 | 146 | |
| 147 | 147 | expect(result).toMatchObject({ |
| @@ -192,7 +192,7 @@ | ||
| 192 | 192 | vi.mocked(getApiClient).mockReturnValue(apiClient as any); |
| 193 | 193 | |
| 194 | 194 | await expect( |
| 195 | - ensureOrganization(mockAuthConfig, true, "org-one") | |
| 195 | + ensureOrganization(mockAuthConfig, true, "org-one"), | |
| 196 | 196 | ).rejects.toThrow("API Error"); |
| 197 | 197 | }); |
| 198 | 198 | }); |
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"; | |
| 3 | 3 | |
| 4 | -import { getAllSlashCommands } from './commands.js'; | |
| 4 | +import { getAllSlashCommands } from "./commands.js"; | |
| 5 | 5 | |
| 6 | -describe('Slash Commands Integration', () => { | |
| 6 | +describe("Slash Commands Integration", () => { | |
| 7 | 7 | const mockAssistant: AssistantConfig = { |
| 8 | - name: 'test-assistant', | |
| 9 | - version: '1.0.0', | |
| 8 | + name: "test-assistant", | |
| 9 | + version: "1.0.0", | |
| 10 | 10 | 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 | + ], | |
| 13 | 17 | }; |
| 14 | 18 | |
| 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", () => { | |
| 17 | 21 | const commands = getAllSlashCommands(mockAssistant); |
| 18 | - const commandNames = commands.map(cmd => cmd.name); | |
| 19 | - | |
| 22 | + const commandNames = commands.map((cmd) => cmd.name); | |
| 23 | + | |
| 20 | 24 | // 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"); | |
| 30 | 34 | }); |
| 31 | 35 | |
| 32 | - it('should include assistant prompt commands', () => { | |
| 36 | + it("should include assistant prompt commands", () => { | |
| 33 | 37 | 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"); | |
| 37 | 41 | }); |
| 38 | 42 | |
| 39 | - it('should categorize system commands correctly', () => { | |
| 43 | + it("should categorize system commands correctly", () => { | |
| 40 | 44 | 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), | |
| 43 | 56 | ); |
| 44 | - | |
| 45 | - systemCommands.forEach(cmd => { | |
| 46 | - expect(cmd.category).toBe('system'); | |
| 57 | + | |
| 58 | + systemCommands.forEach((cmd) => { | |
| 59 | + expect(cmd.category).toBe("system"); | |
| 47 | 60 | }); |
| 48 | 61 | }); |
| 49 | 62 | |
| 50 | - it('should categorize assistant commands correctly', () => { | |
| 63 | + it("should categorize assistant commands correctly", () => { | |
| 51 | 64 | 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"); | |
| 56 | 71 | }); |
| 57 | 72 | }); |
| 58 | 73 | |
| 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 | + | |
| 63 | 80 | // In remote mode, only exit command should be available |
| 64 | - expect(commandNames).toContain('exit'); | |
| 81 | + expect(commandNames).toContain("exit"); | |
| 65 | 82 | expect(commandNames).toHaveLength(1); |
| 66 | 83 | }); |
| 67 | 84 | }); |
| 68 | -}); | |
| No newline at the end of the file | ||
| 85 | +}); |
modified extensions/cli/src/commands/ls.test.ts +25 −21
| @@ -32,7 +32,7 @@ | ||
| 32 | 32 | |
| 33 | 33 | describe("listSessionsCommand", () => { |
| 34 | 34 | const mockListSessions = vi.mocked(sessionModule.listSessions); |
| 35 | - | |
| 35 | + | |
| 36 | 36 | beforeEach(() => { |
| 37 | 37 | vi.clearAllMocks(); |
| 38 | 38 | }); |
| @@ -51,7 +51,7 @@ | ||
| 51 | 51 | firstUserMessage: "Hello world", |
| 52 | 52 | }, |
| 53 | 53 | { |
| 54 | - id: "session-2", | |
| 54 | + id: "session-2", | |
| 55 | 55 | path: "/path/to/session2.json", |
| 56 | 56 | timestamp: new Date("2023-01-01T09:00:00Z"), |
| 57 | 57 | messageCount: 3, |
| @@ -66,22 +66,26 @@ | ||
| 66 | 66 | await listSessionsCommand({ format: "json" }); |
| 67 | 67 | |
| 68 | 68 | 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 | + ), | |
| 85 | 89 | ); |
| 86 | 90 | |
| 87 | 91 | consoleSpy.mockRestore(); |
| @@ -107,7 +111,7 @@ | ||
| 107 | 111 | await listSessionsCommand({ format: "json" }); |
| 108 | 112 | |
| 109 | 113 | expect(consoleSpy).toHaveBeenCalledWith( |
| 110 | - JSON.stringify({ sessions: [] }, null, 2) | |
| 114 | + JSON.stringify({ sessions: [] }, null, 2), | |
| 111 | 115 | ); |
| 112 | 116 | |
| 113 | 117 | consoleSpy.mockRestore(); |
| @@ -121,9 +125,9 @@ | ||
| 121 | 125 | await listSessionsCommand({}); |
| 122 | 126 | |
| 123 | 127 | 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", | |
| 125 | 129 | ); |
| 126 | 130 | |
| 127 | 131 | consoleSpy.mockRestore(); |
| 128 | 132 | }); |
| 129 | -}); | |
| No newline at the end of the file | ||
| 133 | +}); |
modified extensions/cli/src/commands/remote.test.ts +70 −71
| @@ -9,14 +9,10 @@ | ||
| 9 | 9 | vi.mock("../ui/index.js"); |
| 10 | 10 | vi.mock("../util/git.js"); |
| 11 | 11 | |
| 12 | -const mockWorkos = vi.mocked( | |
| 13 | - await import("../auth/workos.js") | |
| 14 | -); | |
| 12 | +const mockWorkos = vi.mocked(await import("../auth/workos.js")); | |
| 15 | 13 | const mockEnv = vi.mocked(await import("../env.js")); |
| 16 | 14 | 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")); | |
| 20 | 16 | |
| 21 | 17 | // Mock fetch globally |
| 22 | 18 | const mockFetch = vi.fn(); |
| @@ -36,12 +32,12 @@ | ||
| 36 | 32 | describe("remote command", () => { |
| 37 | 33 | beforeEach(() => { |
| 38 | 34 | vi.clearAllMocks(); |
| 39 | - | |
| 35 | + | |
| 40 | 36 | // Clear GitHub Actions environment variables |
| 41 | 37 | delete process.env.GITHUB_ACTIONS; |
| 42 | 38 | delete process.env.GITHUB_REPOSITORY; |
| 43 | 39 | delete process.env.GITHUB_SERVER_URL; |
| 44 | - | |
| 40 | + | |
| 45 | 41 | // Setup default mocks |
| 46 | 42 | mockWorkos.loadAuthConfig.mockReturnValue({ |
| 47 | 43 | userId: "test-user-id", |
| @@ -51,19 +47,19 @@ | ||
| 51 | 47 | expiresAt: Date.now() + 3600000, |
| 52 | 48 | organizationId: null, |
| 53 | 49 | }); |
| 54 | - | |
| 50 | + | |
| 55 | 51 | mockWorkos.isAuthenticatedConfig.mockReturnValue(true); |
| 56 | 52 | mockWorkos.getAccessToken.mockReturnValue("test-token"); |
| 57 | - | |
| 53 | + | |
| 58 | 54 | mockEnv.env = { |
| 59 | 55 | apiBase: "https://api.example.com", |
| 60 | 56 | workOsClientId: "test-client-id", |
| 61 | 57 | appUrl: "https://test.example.com", |
| 62 | 58 | continueHome: "/tmp/test-continue-home", |
| 63 | 59 | }; |
| 64 | - | |
| 60 | + | |
| 65 | 61 | mockGit.getRepoUrl.mockReturnValue("https://github.com/user/test-repo.git"); |
| 66 | - | |
| 62 | + | |
| 67 | 63 | mockFetch.mockResolvedValue({ |
| 68 | 64 | ok: true, |
| 69 | 65 | json: async () => ({ |
| @@ -72,15 +68,15 @@ | ||
| 72 | 68 | port: 8080, |
| 73 | 69 | }), |
| 74 | 70 | }); |
| 75 | - | |
| 71 | + | |
| 76 | 72 | mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any); |
| 77 | 73 | }); |
| 78 | 74 | |
| 79 | 75 | it("should include idempotency key in request body when provided", async () => { |
| 80 | 76 | const testIdempotencyKey = "test-idempotency-key-123"; |
| 81 | - | |
| 77 | + | |
| 82 | 78 | await remote("test prompt", { idempotencyKey: testIdempotencyKey }); |
| 83 | - | |
| 79 | + | |
| 84 | 80 | expect(mockFetch).toHaveBeenCalledWith( |
| 85 | 81 | new URL("agents/devboxes", mockEnv.env.apiBase), |
| 86 | 82 | expect.objectContaining({ |
| @@ -89,14 +85,16 @@ | ||
| 89 | 85 | "Content-Type": "application/json", |
| 90 | 86 | Authorization: "Bearer test-token", |
| 91 | 87 | }, |
| 92 | - body: expect.stringContaining(`"idempotencyKey":"${testIdempotencyKey}"`), | |
| 93 | - }) | |
| 88 | + body: expect.stringContaining( | |
| 89 | + `"idempotencyKey":"${testIdempotencyKey}"`, | |
| 90 | + ), | |
| 91 | + }), | |
| 94 | 92 | ); |
| 95 | 93 | }); |
| 96 | 94 | |
| 97 | 95 | it("should not include idempotency key in request body when not provided", async () => { |
| 98 | 96 | await remote("test prompt", {}); |
| 99 | - | |
| 97 | + | |
| 100 | 98 | expect(mockFetch).toHaveBeenCalledWith( |
| 101 | 99 | new URL("agents/devboxes", mockEnv.env.apiBase), |
| 102 | 100 | expect.objectContaining({ |
| @@ -106,57 +104,55 @@ | ||
| 106 | 104 | Authorization: "Bearer test-token", |
| 107 | 105 | }, |
| 108 | 106 | body: expect.not.stringContaining("idempotencyKey"), |
| 109 | - }) | |
| 107 | + }), | |
| 110 | 108 | ); |
| 111 | 109 | }); |
| 112 | 110 | |
| 113 | - | |
| 114 | - | |
| 115 | 111 | it("should work with direct URL connection and idempotency key", async () => { |
| 116 | 112 | const testUrl = "ws://direct-url.com"; |
| 117 | 113 | 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, | |
| 122 | 118 | }); |
| 123 | - | |
| 119 | + | |
| 124 | 120 | // Should not make POST request when connecting directly to URL |
| 125 | 121 | expect(mockFetch).not.toHaveBeenCalled(); |
| 126 | - | |
| 122 | + | |
| 127 | 123 | // Should connect directly to the provided URL |
| 128 | 124 | expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith( |
| 129 | 125 | testUrl, |
| 130 | - "test prompt" | |
| 126 | + "test prompt", | |
| 131 | 127 | ); |
| 132 | 128 | }); |
| 133 | 129 | |
| 134 | 130 | it("should ignore --start flag when --url is provided without --start", async () => { |
| 135 | 131 | const testUrl = "ws://direct-url.com"; |
| 136 | - | |
| 132 | + | |
| 137 | 133 | await remote("test prompt", { url: testUrl }); |
| 138 | - | |
| 134 | + | |
| 139 | 135 | // Should not make POST request when connecting directly to URL |
| 140 | 136 | expect(mockFetch).not.toHaveBeenCalled(); |
| 141 | - | |
| 137 | + | |
| 142 | 138 | // Should connect directly to the provided URL and start TUI |
| 143 | 139 | expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith( |
| 144 | 140 | testUrl, |
| 145 | - "test prompt" | |
| 141 | + "test prompt", | |
| 146 | 142 | ); |
| 147 | - | |
| 143 | + | |
| 148 | 144 | // Should not output JSON |
| 149 | 145 | expect(mockConsoleLog).not.toHaveBeenCalled(); |
| 150 | 146 | }); |
| 151 | 147 | |
| 152 | 148 | it("should handle proper request body structure with all fields", async () => { |
| 153 | 149 | const testIdempotencyKey = "structured-test-key"; |
| 154 | - | |
| 150 | + | |
| 155 | 151 | await remote("test prompt", { idempotencyKey: testIdempotencyKey }); |
| 156 | - | |
| 152 | + | |
| 157 | 153 | const fetchCall = mockFetch.mock.calls[0]; |
| 158 | 154 | const requestBody = JSON.parse(fetchCall[1].body); |
| 159 | - | |
| 155 | + | |
| 160 | 156 | expect(requestBody).toEqual({ |
| 161 | 157 | repoUrl: "https://github.com/user/test-repo.git", |
| 162 | 158 | name: expect.stringMatching(/^devbox-\d+$/), |
| @@ -167,7 +163,7 @@ | ||
| 167 | 163 | |
| 168 | 164 | it("should call getRepoUrl to get the current repository URL", async () => { |
| 169 | 165 | await remote("test prompt", {}); |
| 170 | - | |
| 166 | + | |
| 171 | 167 | expect(mockGit.getRepoUrl).toHaveBeenCalled(); |
| 172 | 168 | }); |
| 173 | 169 | |
| @@ -175,24 +171,24 @@ | ||
| 175 | 171 | // Simulate GitHub Actions environment |
| 176 | 172 | process.env.GITHUB_ACTIONS = "true"; |
| 177 | 173 | process.env.GITHUB_REPOSITORY = "myorg/myrepo"; |
| 178 | - | |
| 174 | + | |
| 179 | 175 | // Mock getRepoUrl to return the GitHub Actions URL |
| 180 | 176 | mockGit.getRepoUrl.mockReturnValue("https://github.com/myorg/myrepo.git"); |
| 181 | - | |
| 177 | + | |
| 182 | 178 | await remote("test prompt", { idempotencyKey: "github-actions-key" }); |
| 183 | - | |
| 179 | + | |
| 184 | 180 | const fetchCall = mockFetch.mock.calls[0]; |
| 185 | 181 | const requestBody = JSON.parse(fetchCall[1].body); |
| 186 | - | |
| 182 | + | |
| 187 | 183 | expect(requestBody.repoUrl).toBe("https://github.com/myorg/myrepo.git"); |
| 188 | 184 | expect(requestBody.idempotencyKey).toBe("github-actions-key"); |
| 189 | 185 | }); |
| 190 | 186 | |
| 191 | 187 | it("should include branchName in request body when branch option is provided", async () => { |
| 192 | 188 | const testBranch = "feature/new-feature"; |
| 193 | - | |
| 189 | + | |
| 194 | 190 | await remote("test prompt", { branch: testBranch }); |
| 195 | - | |
| 191 | + | |
| 196 | 192 | expect(mockFetch).toHaveBeenCalledWith( |
| 197 | 193 | new URL("agents/devboxes", mockEnv.env.apiBase), |
| 198 | 194 | expect.objectContaining({ |
| @@ -202,13 +198,13 @@ | ||
| 202 | 198 | Authorization: "Bearer test-token", |
| 203 | 199 | }, |
| 204 | 200 | body: expect.stringContaining(`"branchName":"${testBranch}"`), |
| 205 | - }) | |
| 201 | + }), | |
| 206 | 202 | ); |
| 207 | 203 | }); |
| 208 | 204 | |
| 209 | 205 | it("should not include branchName in request body when branch option is not provided", async () => { |
| 210 | 206 | await remote("test prompt", {}); |
| 211 | - | |
| 207 | + | |
| 212 | 208 | expect(mockFetch).toHaveBeenCalledWith( |
| 213 | 209 | new URL("agents/devboxes", mockEnv.env.apiBase), |
| 214 | 210 | expect.objectContaining({ |
| @@ -218,22 +214,22 @@ | ||
| 218 | 214 | Authorization: "Bearer test-token", |
| 219 | 215 | }, |
| 220 | 216 | body: expect.not.stringContaining("branchName"), |
| 221 | - }) | |
| 217 | + }), | |
| 222 | 218 | ); |
| 223 | 219 | }); |
| 224 | 220 | |
| 225 | 221 | it("should handle proper request body structure with branch field", async () => { |
| 226 | 222 | const testBranch = "main"; |
| 227 | 223 | 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, | |
| 232 | 228 | }); |
| 233 | - | |
| 229 | + | |
| 234 | 230 | const fetchCall = mockFetch.mock.calls[0]; |
| 235 | 231 | const requestBody = JSON.parse(fetchCall[1].body); |
| 236 | - | |
| 232 | + | |
| 237 | 233 | expect(requestBody).toEqual({ |
| 238 | 234 | repoUrl: "https://github.com/user/test-repo.git", |
| 239 | 235 | name: expect.stringMatching(/^devbox-\d+$/), |
| @@ -246,29 +242,29 @@ | ||
| 246 | 242 | describe("start mode (-s / --start flag)", () => { |
| 247 | 243 | it("should output JSON and exit without starting TUI when using --start with direct URL", async () => { |
| 248 | 244 | const testUrl = "ws://test-url.com"; |
| 249 | - | |
| 245 | + | |
| 250 | 246 | await remote("test prompt", { url: testUrl, start: true }); |
| 251 | - | |
| 247 | + | |
| 252 | 248 | // Should not start TUI |
| 253 | 249 | expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled(); |
| 254 | - | |
| 250 | + | |
| 255 | 251 | // Should not make POST request |
| 256 | 252 | expect(mockFetch).not.toHaveBeenCalled(); |
| 257 | - | |
| 253 | + | |
| 258 | 254 | // Should output JSON |
| 259 | 255 | expect(mockConsoleLog).toHaveBeenCalledWith( |
| 260 | 256 | JSON.stringify({ |
| 261 | 257 | status: "success", |
| 262 | 258 | message: "Remote environment connection details", |
| 263 | 259 | url: testUrl, |
| 264 | - mode: "direct_url" | |
| 265 | - }) | |
| 260 | + mode: "direct_url", | |
| 261 | + }), | |
| 266 | 262 | ); |
| 267 | 263 | }); |
| 268 | 264 | |
| 269 | 265 | it("should create remote environment, output JSON, and exit without starting TUI when using --start", async () => { |
| 270 | 266 | await remote("test prompt", { start: true }); |
| 271 | - | |
| 267 | + | |
| 272 | 268 | // Should make POST request to create environment |
| 273 | 269 | expect(mockFetch).toHaveBeenCalledWith( |
| 274 | 270 | new URL("agents/devboxes", mockEnv.env.apiBase), |
| @@ -278,16 +274,16 @@ | ||
| 278 | 274 | "Content-Type": "application/json", |
| 279 | 275 | Authorization: "Bearer test-token", |
| 280 | 276 | }, |
| 281 | - }) | |
| 277 | + }), | |
| 282 | 278 | ); |
| 283 | - | |
| 279 | + | |
| 284 | 280 | // Should not start TUI |
| 285 | 281 | expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled(); |
| 286 | - | |
| 282 | + | |
| 287 | 283 | // Should output JSON with environment details |
| 288 | 284 | const consoleLogCall = mockConsoleLog.mock.calls[0][0]; |
| 289 | 285 | const outputJson = JSON.parse(consoleLogCall); |
| 290 | - | |
| 286 | + | |
| 291 | 287 | expect(outputJson).toEqual({ |
| 292 | 288 | status: "success", |
| 293 | 289 | message: "Remote development environment created successfully", |
| @@ -295,27 +291,30 @@ | ||
| 295 | 291 | containerUrl: "ws://test-url.com", |
| 296 | 292 | containerPort: 8080, |
| 297 | 293 | name: expect.stringMatching(/^devbox-\d+$/), |
| 298 | - mode: "new_environment" | |
| 294 | + mode: "new_environment", | |
| 299 | 295 | }); |
| 300 | 296 | }); |
| 301 | 297 | |
| 302 | 298 | it("should work with start mode and idempotency key", async () => { |
| 303 | 299 | 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 | + | |
| 307 | 306 | // Should include idempotency key in request |
| 308 | 307 | const fetchCall = mockFetch.mock.calls[0]; |
| 309 | 308 | const requestBody = JSON.parse(fetchCall[1].body); |
| 310 | 309 | expect(requestBody.idempotencyKey).toBe(testIdempotencyKey); |
| 311 | - | |
| 310 | + | |
| 312 | 311 | // Should not start TUI |
| 313 | 312 | expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled(); |
| 314 | - | |
| 313 | + | |
| 315 | 314 | // Should output JSON |
| 316 | 315 | expect(mockConsoleLog).toHaveBeenCalledWith( |
| 317 | - expect.stringContaining('"status":"success"') | |
| 316 | + expect.stringContaining('"status":"success"'), | |
| 318 | 317 | ); |
| 319 | 318 | }); |
| 320 | 319 | }); |
| 321 | -}); | |
| No newline at the end of the file | ||
| 320 | +}); |
modified extensions/cli/src/commands/serve.test.ts +16 −21
| @@ -1,13 +1,6 @@ | ||
| 1 | 1 | import type { Server } from "http"; |
| 2 | 2 | |
| 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"; | |
| 11 | 4 | |
| 12 | 5 | import { createMinimalTestContext } from "../test-helpers/ui-test-context.js"; |
| 13 | 6 | |
| @@ -40,7 +33,7 @@ | ||
| 40 | 33 | config: { models: [] }, |
| 41 | 34 | llmApi: { chat: vi.fn() }, |
| 42 | 35 | model: { name: "test-model" }, |
| 43 | - }) | |
| 36 | + }), | |
| 44 | 37 | ), |
| 45 | 38 | })); |
| 46 | 39 | |
| @@ -73,7 +66,7 @@ | ||
| 73 | 66 | |
| 74 | 67 | afterEach(async () => { |
| 75 | 68 | context.cleanup(); |
| 76 | - | |
| 69 | + | |
| 77 | 70 | // Restore original process.exit |
| 78 | 71 | process.exit = originalProcessExit; |
| 79 | 72 | |
| @@ -100,26 +93,28 @@ | ||
| 100 | 93 | it("should pass the --org flag through to initializeServices", async () => { |
| 101 | 94 | // Import the services module to spy on |
| 102 | 95 | const servicesModule = await import("../services/index.js"); |
| 103 | - | |
| 96 | + | |
| 104 | 97 | // Create spy on initializeServices |
| 105 | - const initializeServicesSpy = vi.spyOn(servicesModule, "initializeServices") | |
| 98 | + const initializeServicesSpy = vi | |
| 99 | + .spyOn(servicesModule, "initializeServices") | |
| 106 | 100 | .mockResolvedValue({ |
| 107 | 101 | config: { models: [] }, |
| 108 | 102 | llmApi: { chat: vi.fn() }, |
| 109 | - model: { name: "test-model" } | |
| 103 | + model: { name: "test-model" }, | |
| 110 | 104 | } as any); |
| 111 | 105 | |
| 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") | |
| 114 | 109 | .mockResolvedValueOnce({ |
| 115 | 110 | config: { name: "test" }, |
| 116 | 111 | llmApi: { chat: vi.fn() }, |
| 117 | - model: { provider: "test", model: "test" } | |
| 112 | + model: { provider: "test", model: "test" }, | |
| 118 | 113 | } as any) |
| 119 | 114 | .mockResolvedValueOnce({ |
| 120 | 115 | config: { name: "test" }, |
| 121 | 116 | llmApi: { chat: vi.fn() }, |
| 122 | - model: { provider: "test", model: "test" } | |
| 117 | + model: { provider: "test", model: "test" }, | |
| 123 | 118 | } as any); |
| 124 | 119 | |
| 125 | 120 | // Import serve after setting up spies |
| @@ -129,7 +124,7 @@ | ||
| 129 | 124 | const testOptions = { |
| 130 | 125 | org: "test-organization-slug", |
| 131 | 126 | timeout: "60", |
| 132 | - port: "9000" | |
| 127 | + port: "9000", | |
| 133 | 128 | }; |
| 134 | 129 | |
| 135 | 130 | try { |
| @@ -142,12 +137,12 @@ | ||
| 142 | 137 | expect(initializeServicesSpy).toHaveBeenCalled(); |
| 143 | 138 | expect(initializeServicesSpy).toHaveBeenCalledWith( |
| 144 | 139 | expect.objectContaining({ |
| 145 | - organizationSlug: "test-organization-slug" | |
| 146 | - }) | |
| 140 | + organizationSlug: "test-organization-slug", | |
| 141 | + }), | |
| 147 | 142 | ); |
| 148 | 143 | |
| 149 | 144 | // Clean up spies |
| 150 | 145 | initializeServicesSpy.mockRestore(); |
| 151 | 146 | getServiceSpy.mockRestore(); |
| 152 | 147 | }); |
| 153 | -}); | |
| No newline at the end of the file | ||
| 148 | +}); |
modified extensions/cli/src/commands/stripThinkTags.test.ts +6 −6
| @@ -11,14 +11,14 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | function stripThinkTags(response: string): string { |
| 13 | 13 | // 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 | + | |
| 16 | 16 | // 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 | + | |
| 19 | 19 | // Trim leading and trailing whitespace |
| 20 | 20 | cleaned = cleaned.trim(); |
| 21 | - | |
| 21 | + | |
| 22 | 22 | return cleaned; |
| 23 | 23 | } |
| 24 | 24 | |
| @@ -157,4 +157,4 @@ | ||
| 157 | 157 | expect(stripThinkTags(input)).toContain("<think>Unclosed think tag"); |
| 158 | 158 | expect(stripThinkTags(input)).toContain("Content should remain"); |
| 159 | 159 | }); |
| 160 | -}); | |
| No newline at the end of the file | ||
| 160 | +}); |
modified extensions/cli/src/compaction.test.ts +201 −128
| @@ -3,13 +3,17 @@ | ||
| 3 | 3 | import { ChatCompletionMessageParam } from "openai/resources.mjs"; |
| 4 | 4 | import { describe, it, expect, vi } from "vitest"; |
| 5 | 5 | |
| 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"; | |
| 7 | 12 | import { streamChatResponse } from "./streamChatResponse.js"; |
| 8 | 13 | |
| 9 | - | |
| 10 | 14 | // Mock the streamChatResponse function |
| 11 | 15 | vi.mock("./streamChatResponse.js", () => ({ |
| 12 | - streamChatResponse: vi.fn() | |
| 16 | + streamChatResponse: vi.fn(), | |
| 13 | 17 | })); |
| 14 | 18 | |
| 15 | 19 | describe("compaction", () => { |
| @@ -27,7 +31,10 @@ | ||
| 27 | 31 | { role: "system", content: "System message" }, |
| 28 | 32 | { role: "user", content: "Hello" }, |
| 29 | 33 | { 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 | + }, | |
| 31 | 38 | { role: "user", content: "Another message" }, |
| 32 | 39 | ]; |
| 33 | 40 | |
| @@ -67,7 +74,10 @@ | ||
| 67 | 74 | it("should not match marker in middle of content", () => { |
| 68 | 75 | const history: ChatCompletionMessageParam[] = [ |
| 69 | 76 | { 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 | + }, | |
| 71 | 81 | { role: "user", content: "Hello" }, |
| 72 | 82 | ]; |
| 73 | 83 | |
| @@ -116,21 +126,30 @@ | ||
| 116 | 126 | { role: "system", content: "System message" }, |
| 117 | 127 | { role: "user", content: "Hello" }, |
| 118 | 128 | { 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 | + }, | |
| 120 | 133 | { role: "user", content: "Another message" }, |
| 121 | 134 | ]; |
| 122 | 135 | |
| 123 | 136 | const result = getHistoryForLLM(history, 3); |
| 124 | 137 | expect(result).toEqual([ |
| 125 | 138 | { 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 | + }, | |
| 127 | 143 | { role: "user", content: "Another message" }, |
| 128 | 144 | ]); |
| 129 | 145 | }); |
| 130 | 146 | |
| 131 | 147 | it("should return compacted history without system message when compaction is at index 0", () => { |
| 132 | 148 | 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 | + }, | |
| 134 | 153 | { role: "user", content: "Another message" }, |
| 135 | 154 | ]; |
| 136 | 155 | |
| @@ -157,9 +176,7 @@ | ||
| 157 | 176 | const result = getHistoryForLLM(history, -1); |
| 158 | 177 | // Negative index with slice means "from the end", so -1 gives us only the last message |
| 159 | 178 | // 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" }]); | |
| 163 | 180 | }); |
| 164 | 181 | |
| 165 | 182 | it("should handle empty history", () => { |
| @@ -233,12 +250,14 @@ | ||
| 233 | 250 | it("should compact chat history successfully", async () => { |
| 234 | 251 | const mockStreamResponse = vi.mocked(streamChatResponse); |
| 235 | 252 | 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 | + ); | |
| 242 | 261 | |
| 243 | 262 | const history: ChatCompletionMessageParam[] = [ |
| 244 | 263 | { role: "system", content: "System message" }, |
| @@ -247,12 +266,15 @@ | ||
| 247 | 266 | ]; |
| 248 | 267 | |
| 249 | 268 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 250 | - | |
| 269 | + | |
| 251 | 270 | 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 | + }); | |
| 253 | 275 | expect(result.compactedHistory[1]).toEqual({ |
| 254 | 276 | role: "assistant", |
| 255 | - content: `${COMPACTION_MARKER}\n${mockContent}` | |
| 277 | + content: `${COMPACTION_MARKER}\n${mockContent}`, | |
| 256 | 278 | }); |
| 257 | 279 | expect(result.compactionIndex).toBe(1); |
| 258 | 280 | expect(result.compactionContent).toBe(mockContent); |
| @@ -263,13 +285,15 @@ | ||
| 263 | 285 | const mockContent = "Summary content"; |
| 264 | 286 | const onStreamContent = vi.fn(); |
| 265 | 287 | 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 | + ); | |
| 273 | 297 | |
| 274 | 298 | const history: ChatCompletionMessageParam[] = [ |
| 275 | 299 | { role: "user", content: "Hello" }, |
| @@ -277,9 +301,9 @@ | ||
| 277 | 301 | |
| 278 | 302 | await compactChatHistory(history, mockModel, mockLlmApi, { |
| 279 | 303 | onStreamContent, |
| 280 | - onStreamComplete | |
| 304 | + onStreamComplete, | |
| 281 | 305 | }); |
| 282 | - | |
| 306 | + | |
| 283 | 307 | expect(onStreamContent).toHaveBeenCalledWith("Summary "); |
| 284 | 308 | expect(onStreamContent).toHaveBeenCalledWith("content"); |
| 285 | 309 | expect(onStreamComplete).toHaveBeenCalled(); |
| @@ -289,7 +313,7 @@ | ||
| 289 | 313 | const mockStreamResponse = vi.mocked(streamChatResponse); |
| 290 | 314 | const mockError = new Error("Stream failed"); |
| 291 | 315 | const onError = vi.fn(); |
| 292 | - | |
| 316 | + | |
| 293 | 317 | mockStreamResponse.mockRejectedValue(mockError); |
| 294 | 318 | |
| 295 | 319 | const history: ChatCompletionMessageParam[] = [ |
| @@ -297,48 +321,55 @@ | ||
| 297 | 321 | ]; |
| 298 | 322 | |
| 299 | 323 | await expect( |
| 300 | - compactChatHistory(history, mockModel, mockLlmApi, { onError }) | |
| 324 | + compactChatHistory(history, mockModel, mockLlmApi, { onError }), | |
| 301 | 325 | ).rejects.toThrow("Stream failed"); |
| 302 | - | |
| 326 | + | |
| 303 | 327 | expect(onError).toHaveBeenCalledWith(mockError); |
| 304 | 328 | }); |
| 305 | 329 | |
| 306 | 330 | it("should handle history with only system message", async () => { |
| 307 | 331 | const mockStreamResponse = vi.mocked(streamChatResponse); |
| 308 | 332 | 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 | + ); | |
| 315 | 341 | |
| 316 | 342 | const history: ChatCompletionMessageParam[] = [ |
| 317 | 343 | { role: "system", content: "You are a helpful assistant" }, |
| 318 | 344 | ]; |
| 319 | 345 | |
| 320 | 346 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 321 | - | |
| 347 | + | |
| 322 | 348 | 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 | + }); | |
| 324 | 353 | expect(result.compactedHistory[1].content).toContain(COMPACTION_MARKER); |
| 325 | 354 | }); |
| 326 | 355 | |
| 327 | 356 | it("should handle empty content from stream", async () => { |
| 328 | 357 | 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 | + ); | |
| 335 | 366 | |
| 336 | 367 | const history: ChatCompletionMessageParam[] = [ |
| 337 | 368 | { role: "user", content: "Hello" }, |
| 338 | 369 | ]; |
| 339 | 370 | |
| 340 | 371 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 341 | - | |
| 372 | + | |
| 342 | 373 | expect(result.compactionContent).toBe(""); |
| 343 | 374 | expect(result.compactedHistory[0].content).toBe(`${COMPACTION_MARKER}\n`); |
| 344 | 375 | }); |
| @@ -346,13 +377,15 @@ | ||
| 346 | 377 | it("should correctly construct prompt for compaction", async () => { |
| 347 | 378 | const mockStreamResponse = vi.mocked(streamChatResponse); |
| 348 | 379 | 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 | + ); | |
| 356 | 389 | |
| 357 | 390 | const history: ChatCompletionMessageParam[] = [ |
| 358 | 391 | { role: "system", content: "System" }, |
| @@ -361,24 +394,26 @@ | ||
| 361 | 394 | ]; |
| 362 | 395 | |
| 363 | 396 | await compactChatHistory(history, mockModel, mockLlmApi); |
| 364 | - | |
| 397 | + | |
| 365 | 398 | // Should have original history plus the compaction prompt |
| 366 | 399 | expect(capturedHistory).toHaveLength(4); |
| 367 | 400 | expect(capturedHistory[3]).toEqual({ |
| 368 | 401 | role: "user", |
| 369 | - content: expect.stringContaining("provide a concise summary") | |
| 402 | + content: expect.stringContaining("provide a concise summary"), | |
| 370 | 403 | }); |
| 371 | 404 | }); |
| 372 | 405 | |
| 373 | 406 | it("should handle history with tool calls and mixed message types", async () => { |
| 374 | 407 | const mockStreamResponse = vi.mocked(streamChatResponse); |
| 375 | 408 | 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 | + ); | |
| 382 | 417 | |
| 383 | 418 | const history: ChatCompletionMessageParam[] = [ |
| 384 | 419 | { role: "system", content: "System" }, |
| @@ -389,32 +424,34 @@ | ||
| 389 | 424 | ]; |
| 390 | 425 | |
| 391 | 426 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 392 | - | |
| 427 | + | |
| 393 | 428 | expect(result.compactedHistory).toHaveLength(2); |
| 394 | 429 | expect(result.compactionContent).toBe(mockContent); |
| 395 | 430 | }); |
| 396 | 431 | |
| 397 | 432 | it("should handle very long chat histories", async () => { |
| 398 | 433 | 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 | + ); | |
| 405 | 442 | |
| 406 | 443 | // Create a very long history |
| 407 | 444 | const history: ChatCompletionMessageParam[] = [ |
| 408 | 445 | { role: "system", content: "System" }, |
| 409 | 446 | ]; |
| 410 | - | |
| 447 | + | |
| 411 | 448 | for (let i = 0; i < 100; i++) { |
| 412 | 449 | history.push({ role: "user", content: `User message ${i}` }); |
| 413 | 450 | history.push({ role: "assistant", content: `Assistant response ${i}` }); |
| 414 | 451 | } |
| 415 | 452 | |
| 416 | 453 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 417 | - | |
| 454 | + | |
| 418 | 455 | expect(result.compactedHistory).toHaveLength(2); // System + compaction |
| 419 | 456 | expect(result.compactionIndex).toBe(1); |
| 420 | 457 | }); |
| @@ -422,12 +459,14 @@ | ||
| 422 | 459 | it("should handle history without system message", async () => { |
| 423 | 460 | const mockStreamResponse = vi.mocked(streamChatResponse); |
| 424 | 461 | 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 | + ); | |
| 431 | 470 | |
| 432 | 471 | const history: ChatCompletionMessageParam[] = [ |
| 433 | 472 | { role: "user", content: "Hello" }, |
| @@ -435,7 +474,7 @@ | ||
| 435 | 474 | ]; |
| 436 | 475 | |
| 437 | 476 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 438 | - | |
| 477 | + | |
| 439 | 478 | expect(result.compactedHistory).toHaveLength(1); // Only compaction |
| 440 | 479 | expect(result.compactedHistory[0].role).toBe("assistant"); |
| 441 | 480 | expect(result.compactionIndex).toBe(0); |
| @@ -444,14 +483,17 @@ | ||
| 444 | 483 | |
| 445 | 484 | describe("property-based tests", () => { |
| 446 | 485 | 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 | + }> = [ | |
| 448 | 490 | { |
| 449 | 491 | history: [ |
| 450 | 492 | { role: "system", content: "System" }, |
| 451 | 493 | { role: "user", content: "User 1" }, |
| 452 | 494 | { role: "assistant", content: "Assistant 1" }, |
| 453 | 495 | ], |
| 454 | - compactionIndex: 1 | |
| 496 | + compactionIndex: 1, | |
| 455 | 497 | }, |
| 456 | 498 | { |
| 457 | 499 | history: [ |
| @@ -459,51 +501,61 @@ | ||
| 459 | 501 | { role: "assistant", content: "Assistant 1" }, |
| 460 | 502 | { role: "user", content: "User 2" }, |
| 461 | 503 | ], |
| 462 | - compactionIndex: 2 | |
| 504 | + compactionIndex: 2, | |
| 463 | 505 | }, |
| 464 | 506 | { |
| 465 | 507 | history: [], |
| 466 | - compactionIndex: null | |
| 467 | - } | |
| 508 | + compactionIndex: null, | |
| 509 | + }, | |
| 468 | 510 | ]; |
| 469 | 511 | |
| 470 | 512 | testCases.forEach(({ history, compactionIndex }) => { |
| 471 | 513 | const result = getHistoryForLLM(history, compactionIndex); |
| 472 | - | |
| 514 | + | |
| 473 | 515 | // Every message in result should exist in original history |
| 474 | - result.forEach(msg => { | |
| 516 | + result.forEach((msg) => { | |
| 475 | 517 | expect(history).toContainEqual(msg); |
| 476 | 518 | }); |
| 477 | - | |
| 519 | + | |
| 478 | 520 | // Result length should be <= original length |
| 479 | 521 | expect(result.length).toBeLessThanOrEqual(history.length); |
| 480 | 522 | }); |
| 481 | 523 | }); |
| 482 | 524 | |
| 483 | 525 | 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 | + }> = [ | |
| 486 | 534 | { |
| 487 | 535 | history: [ |
| 488 | 536 | systemMessage, |
| 489 | 537 | { role: "user", content: "User 1" }, |
| 490 | 538 | { role: "assistant", content: `${COMPACTION_MARKER}\nSummary` }, |
| 491 | 539 | ], |
| 492 | - compactionIndex: 2 | |
| 540 | + compactionIndex: 2, | |
| 493 | 541 | }, |
| 494 | 542 | { |
| 495 | 543 | history: [ |
| 496 | 544 | systemMessage, |
| 497 | 545 | { role: "assistant", content: `${COMPACTION_MARKER}\nSummary` }, |
| 498 | 546 | ], |
| 499 | - compactionIndex: 1 | |
| 500 | - } | |
| 547 | + compactionIndex: 1, | |
| 548 | + }, | |
| 501 | 549 | ]; |
| 502 | 550 | |
| 503 | 551 | testCases.forEach(({ history, compactionIndex }) => { |
| 504 | 552 | 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 | + ) { | |
| 507 | 559 | expect(result[0]).toEqual(systemMessage); |
| 508 | 560 | } |
| 509 | 561 | }); |
| @@ -511,12 +563,14 @@ | ||
| 511 | 563 | |
| 512 | 564 | it("compaction should always reduce message count for non-trivial histories", async () => { |
| 513 | 565 | 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 | + ); | |
| 520 | 574 | |
| 521 | 575 | const testHistories: ChatCompletionMessageParam[][] = [ |
| 522 | 576 | [ |
| @@ -530,12 +584,12 @@ | ||
| 530 | 584 | { role: "user", content: "User 1" }, |
| 531 | 585 | { role: "assistant", content: "Assistant 1" }, |
| 532 | 586 | { role: "user", content: "User 2" }, |
| 533 | - ] | |
| 587 | + ], | |
| 534 | 588 | ]; |
| 535 | 589 | |
| 536 | 590 | for (const history of testHistories) { |
| 537 | 591 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 538 | - | |
| 592 | + | |
| 539 | 593 | // Compacted history should be shorter than original |
| 540 | 594 | // (system + compaction) or just compaction |
| 541 | 595 | expect(result.compactedHistory.length).toBeLessThanOrEqual(2); |
| @@ -547,39 +601,56 @@ | ||
| 547 | 601 | describe("invariant tests", () => { |
| 548 | 602 | it("compactionIndex should always point to a message with COMPACTION_MARKER", async () => { |
| 549 | 603 | 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 | + ); | |
| 556 | 612 | |
| 557 | 613 | 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 | + ], | |
| 560 | 622 | [{ role: "system", content: "System" }], |
| 561 | 623 | ]; |
| 562 | 624 | |
| 563 | 625 | for (const history of histories) { |
| 564 | 626 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 565 | - | |
| 627 | + | |
| 566 | 628 | // The message at compactionIndex should contain the marker |
| 567 | - const compactionMessage = result.compactedHistory[result.compactionIndex]; | |
| 629 | + const compactionMessage = | |
| 630 | + result.compactedHistory[result.compactionIndex]; | |
| 568 | 631 | 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); | |
| 570 | 636 | } |
| 571 | 637 | }); |
| 572 | 638 | |
| 573 | 639 | it("system message should always be preserved in the same position", async () => { |
| 574 | 640 | 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 | - }); | |
| 581 | 641 | |
| 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 | + }; | |
| 583 | 654 | const history: ChatCompletionMessageParam[] = [ |
| 584 | 655 | systemMessage, |
| 585 | 656 | { role: "user", content: "Hello" }, |
| @@ -587,19 +658,21 @@ | ||
| 587 | 658 | ]; |
| 588 | 659 | |
| 589 | 660 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 590 | - | |
| 661 | + | |
| 591 | 662 | // System message should still be at index 0 |
| 592 | 663 | expect(result.compactedHistory[0]).toEqual(systemMessage); |
| 593 | 664 | }); |
| 594 | 665 | |
| 595 | 666 | it("findCompactionIndex should be consistent with compactChatHistory result", async () => { |
| 596 | 667 | 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 | + ); | |
| 603 | 676 | |
| 604 | 677 | const history: ChatCompletionMessageParam[] = [ |
| 605 | 678 | { role: "user", content: "Hello" }, |
| @@ -607,10 +680,10 @@ | ||
| 607 | 680 | ]; |
| 608 | 681 | |
| 609 | 682 | const result = await compactChatHistory(history, mockModel, mockLlmApi); |
| 610 | - | |
| 683 | + | |
| 611 | 684 | // findCompactionIndex should find the same index |
| 612 | 685 | const foundIndex = findCompactionIndex(result.compactedHistory); |
| 613 | 686 | expect(foundIndex).toBe(result.compactionIndex); |
| 614 | 687 | }); |
| 615 | 688 | }); |
| 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"; | |
| 3 | 3 | |
| 4 | 4 | // Mock dependencies |
| 5 | -vi.mock('./auth/workos.js'); | |
| 5 | +vi.mock("./auth/workos.js"); | |
| 6 | 6 | |
| 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"; | |
| 9 | 9 | |
| 10 | -describe('config', () => { | |
| 10 | +describe("config", () => { | |
| 11 | 11 | let mockAuthConfig: AuthConfig; |
| 12 | 12 | |
| 13 | 13 | beforeEach(() => { |
| 14 | 14 | vi.clearAllMocks(); |
| 15 | 15 | |
| 16 | 16 | 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", | |
| 22 | 22 | expiresAt: Date.now() + 3600000, |
| 23 | 23 | }; |
| 24 | 24 | }); |
| 25 | 25 | |
| 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", () => { | |
| 28 | 28 | const assistant: AssistantUnrolled = { |
| 29 | - name: 'test-assistant', | |
| 30 | - version: '1.0.0', | |
| 29 | + name: "test-assistant", | |
| 30 | + version: "1.0.0", | |
| 31 | 31 | models: [], |
| 32 | 32 | }; |
| 33 | 33 | |
| 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 | + ); | |
| 36 | 37 | }); |
| 37 | 38 | |
| 38 | - test('should throw error when no chat models available', () => { | |
| 39 | + test("should throw error when no chat models available", () => { | |
| 39 | 40 | const assistant: AssistantUnrolled = { |
| 40 | - name: 'test-assistant', | |
| 41 | - version: '1.0.0', | |
| 41 | + name: "test-assistant", | |
| 42 | + version: "1.0.0", | |
| 42 | 43 | models: [ |
| 43 | 44 | { |
| 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"], | |
| 48 | 49 | } as ModelConfig, |
| 49 | 50 | ], |
| 50 | 51 | }; |
| 51 | 52 | |
| 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 | + ); | |
| 54 | 56 | }); |
| 55 | 57 | }); |
| 56 | 58 | }); |
modified extensions/cli/src/flags/flagProcessor.test.ts +4 −4
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | |
| 24 | 24 | test("should throw error when both readonly and auto are true", () => { |
| 25 | 25 | expect(() => convertLegacyModeFlags(true, true)).toThrow( |
| 26 | - "Cannot use both --readonly and --auto flags together" | |
| 26 | + "Cannot use both --readonly and --auto flags together", | |
| 27 | 27 | ); |
| 28 | 28 | }); |
| 29 | 29 | }); |
| @@ -34,7 +34,7 @@ | ||
| 34 | 34 | ["readFile"], |
| 35 | 35 | ["writeFile"], |
| 36 | 36 | ["runTerminalCommand"], |
| 37 | - "plan" | |
| 37 | + "plan", | |
| 38 | 38 | ); |
| 39 | 39 | |
| 40 | 40 | expect(result).toEqual({ |
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | processCommandFlags({ |
| 126 | 126 | readonly: true, |
| 127 | 127 | auto: true, |
| 128 | - }) | |
| 128 | + }), | |
| 129 | 129 | ).toThrow("Cannot use both --readonly and --auto flags together"); |
| 130 | 130 | }); |
| 131 | 131 | |
| @@ -142,4 +142,4 @@ | ||
| 142 | 142 | }, |
| 143 | 143 | }); |
| 144 | 144 | }); |
| 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", () => { | |
| 6 | 6 | const result = validateFlags({ |
| 7 | - format: 'json', | |
| 7 | + format: "json", | |
| 8 | 8 | print: true, |
| 9 | 9 | }); |
| 10 | - | |
| 10 | + | |
| 11 | 11 | expect(result.isValid).toBe(true); |
| 12 | 12 | expect(result.errors).toHaveLength(0); |
| 13 | 13 | }); |
| 14 | 14 | |
| 15 | - test('should fail when format is used without print', () => { | |
| 15 | + test("should fail when format is used without print", () => { | |
| 16 | 16 | const result = validateFlags({ |
| 17 | - format: 'json', | |
| 17 | + format: "json", | |
| 18 | 18 | print: false, |
| 19 | 19 | }); |
| 20 | - | |
| 20 | + | |
| 21 | 21 | expect(result.isValid).toBe(false); |
| 22 | 22 | 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 | + ); | |
| 25 | 27 | }); |
| 26 | 28 | |
| 27 | - test('should fail when format value is invalid', () => { | |
| 29 | + test("should fail when format value is invalid", () => { | |
| 28 | 30 | const result = validateFlags({ |
| 29 | - format: 'xml', | |
| 31 | + format: "xml", | |
| 30 | 32 | print: true, |
| 31 | 33 | }); |
| 32 | - | |
| 34 | + | |
| 33 | 35 | expect(result.isValid).toBe(false); |
| 34 | 36 | 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 | + ); | |
| 37 | 41 | }); |
| 38 | 42 | }); |
| 39 | 43 | |
| 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", () => { | |
| 42 | 46 | const result = validateFlags({ |
| 43 | 47 | silent: true, |
| 44 | 48 | print: true, |
| 45 | 49 | }); |
| 46 | - | |
| 50 | + | |
| 47 | 51 | expect(result.isValid).toBe(true); |
| 48 | 52 | expect(result.errors).toHaveLength(0); |
| 49 | 53 | }); |
| 50 | 54 | |
| 51 | - test('should fail when silent is used without print', () => { | |
| 55 | + test("should fail when silent is used without print", () => { | |
| 52 | 56 | const result = validateFlags({ |
| 53 | 57 | silent: true, |
| 54 | 58 | print: false, |
| 55 | 59 | }); |
| 56 | - | |
| 60 | + | |
| 57 | 61 | expect(result.isValid).toBe(false); |
| 58 | 62 | 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 | + ); | |
| 61 | 67 | }); |
| 62 | 68 | }); |
| 63 | 69 | |
| 64 | - describe('mode flags validation', () => { | |
| 65 | - test('should pass with readonly only', () => { | |
| 70 | + describe("mode flags validation", () => { | |
| 71 | + test("should pass with readonly only", () => { | |
| 66 | 72 | const result = validateFlags({ |
| 67 | 73 | readonly: true, |
| 68 | 74 | auto: false, |
| 69 | 75 | }); |
| 70 | - | |
| 76 | + | |
| 71 | 77 | expect(result.isValid).toBe(true); |
| 72 | 78 | expect(result.errors).toHaveLength(0); |
| 73 | 79 | }); |
| 74 | 80 | |
| 75 | - test('should pass with auto only', () => { | |
| 81 | + test("should pass with auto only", () => { | |
| 76 | 82 | const result = validateFlags({ |
| 77 | 83 | readonly: false, |
| 78 | 84 | auto: true, |
| 79 | 85 | }); |
| 80 | - | |
| 86 | + | |
| 81 | 87 | expect(result.isValid).toBe(true); |
| 82 | 88 | expect(result.errors).toHaveLength(0); |
| 83 | 89 | }); |
| 84 | 90 | |
| 85 | - test('should fail when both readonly and auto are used', () => { | |
| 91 | + test("should fail when both readonly and auto are used", () => { | |
| 86 | 92 | const result = validateFlags({ |
| 87 | 93 | readonly: true, |
| 88 | 94 | auto: true, |
| 89 | 95 | }); |
| 90 | - | |
| 96 | + | |
| 91 | 97 | expect(result.isValid).toBe(false); |
| 92 | 98 | 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 | + ); | |
| 95 | 103 | }); |
| 96 | 104 | }); |
| 97 | 105 | |
| 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", () => { | |
| 100 | 108 | 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"], | |
| 104 | 112 | }); |
| 105 | - | |
| 113 | + | |
| 106 | 114 | expect(result.isValid).toBe(true); |
| 107 | 115 | expect(result.errors).toHaveLength(0); |
| 108 | 116 | }); |
| 109 | 117 | |
| 110 | - test('should fail with empty tool names in allow', () => { | |
| 118 | + test("should fail with empty tool names in allow", () => { | |
| 111 | 119 | const result = validateFlags({ |
| 112 | - allow: ['readFile', '', 'searchCode'], | |
| 120 | + allow: ["readFile", "", "searchCode"], | |
| 113 | 121 | }); |
| 114 | - | |
| 122 | + | |
| 115 | 123 | expect(result.isValid).toBe(false); |
| 116 | 124 | 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 | + ); | |
| 119 | 129 | }); |
| 120 | 130 | |
| 121 | - test('should fail with empty tool names in ask', () => { | |
| 131 | + test("should fail with empty tool names in ask", () => { | |
| 122 | 132 | const result = validateFlags({ |
| 123 | - ask: ['writeFile', ' ', 'editFile'], | |
| 133 | + ask: ["writeFile", " ", "editFile"], | |
| 124 | 134 | }); |
| 125 | - | |
| 135 | + | |
| 126 | 136 | expect(result.isValid).toBe(false); |
| 127 | 137 | 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"); | |
| 130 | 140 | }); |
| 131 | 141 | |
| 132 | - test('should fail with empty tool names in exclude', () => { | |
| 142 | + test("should fail with empty tool names in exclude", () => { | |
| 133 | 143 | const result = validateFlags({ |
| 134 | - exclude: ['Write', '', 'Bash'], | |
| 144 | + exclude: ["Write", "", "Bash"], | |
| 135 | 145 | }); |
| 136 | - | |
| 146 | + | |
| 137 | 147 | expect(result.isValid).toBe(false); |
| 138 | 148 | 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 | + ); | |
| 141 | 153 | }); |
| 142 | 154 | }); |
| 143 | 155 | |
| 144 | - describe('multiple errors', () => { | |
| 145 | - test('should return all validation errors', () => { | |
| 156 | + describe("multiple errors", () => { | |
| 157 | + test("should return all validation errors", () => { | |
| 146 | 158 | const result = validateFlags({ |
| 147 | - format: 'xml', | |
| 159 | + format: "xml", | |
| 148 | 160 | print: false, |
| 149 | 161 | silent: true, |
| 150 | 162 | readonly: true, |
| 151 | 163 | auto: true, |
| 152 | - allow: ['readFile', ''], | |
| 164 | + allow: ["readFile", ""], | |
| 153 | 165 | }); |
| 154 | - | |
| 166 | + | |
| 155 | 167 | expect(result.isValid).toBe(false); |
| 156 | 168 | 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"); | |
| 164 | 176 | }); |
| 165 | 177 | }); |
| 166 | 178 | |
| 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", () => { | |
| 169 | 181 | const result = validateFlags({ |
| 170 | - config: './my-config.yaml', | |
| 182 | + config: "./my-config.yaml", | |
| 171 | 183 | }); |
| 172 | - | |
| 184 | + | |
| 173 | 185 | expect(result.isValid).toBe(true); |
| 174 | 186 | expect(result.errors).toHaveLength(0); |
| 175 | 187 | }); |
| 176 | 188 | |
| 177 | - test('should pass with undefined config', () => { | |
| 189 | + test("should pass with undefined config", () => { | |
| 178 | 190 | const result = validateFlags({ |
| 179 | 191 | config: undefined, |
| 180 | 192 | }); |
| 181 | - | |
| 193 | + | |
| 182 | 194 | expect(result.isValid).toBe(true); |
| 183 | 195 | expect(result.errors).toHaveLength(0); |
| 184 | 196 | }); |
| 185 | 197 | }); |
| 186 | 198 | }); |
| 187 | 199 | |
| 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", () => { | |
| 190 | 202 | // Test function signature without calling it (since it calls process.exit) |
| 191 | - expect(typeof handleValidationErrors).toBe('function'); | |
| 203 | + expect(typeof handleValidationErrors).toBe("function"); | |
| 192 | 204 | expect(handleValidationErrors.length).toBe(1); |
| 193 | 205 | }); |
| 194 | 206 | |
| 195 | - test('should accept proper error format', () => { | |
| 207 | + test("should accept proper error format", () => { | |
| 196 | 208 | 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" }, | |
| 199 | 211 | ]; |
| 200 | - | |
| 212 | + | |
| 201 | 213 | // Verify the function exists and would accept this format |
| 202 | 214 | // We don't call it since it would exit the process |
| 203 | 215 | expect(() => { |
| 204 | 216 | const errorArray = validErrors; |
| 205 | 217 | 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); | |
| 207 | 219 | }).not.toThrow(); |
| 208 | 220 | }); |
| 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"; | |
| 2 | 5 | |
| 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", () => { | |
| 5 | 8 | // 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 | + | |
| 9 | 14 | // 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); | |
| 14 | 19 | expect(isValidAnthropicApiKey(null)).toBe(false); |
| 15 | 20 | expect(isValidAnthropicApiKey(undefined)).toBe(false); |
| 16 | 21 | }); |
| 17 | 22 | |
| 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 | + ); | |
| 26 | 37 | }); |
| 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", () => { | |
| 15 | 15 | let consoleInfoSpy: ReturnType<typeof vi.spyOn>; |
| 16 | 16 | let consoleErrorSpy: ReturnType<typeof vi.spyOn>; |
| 17 | 17 | let consoleWarnSpy: ReturnType<typeof vi.spyOn>; |
| @@ -19,227 +19,233 @@ | ||
| 19 | 19 | beforeEach(() => { |
| 20 | 20 | // Reset logger state |
| 21 | 21 | configureLogger({ headless: false }); |
| 22 | - | |
| 22 | + | |
| 23 | 23 | // 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(() => {}); | |
| 27 | 27 | }); |
| 28 | 28 | |
| 29 | 29 | afterEach(() => { |
| 30 | 30 | vi.restoreAllMocks(); |
| 31 | 31 | }); |
| 32 | 32 | |
| 33 | - describe('configureLogger', () => { | |
| 34 | - it('should configure logger for non-headless mode', () => { | |
| 33 | + describe("configureLogger", () => { | |
| 34 | + it("should configure logger for non-headless mode", () => { | |
| 35 | 35 | configureLogger({ headless: false }); |
| 36 | 36 | expect(isLoggingEnabled()).toBe(true); |
| 37 | 37 | }); |
| 38 | 38 | |
| 39 | - it('should configure logger for headless mode', () => { | |
| 39 | + it("should configure logger for headless mode", () => { | |
| 40 | 40 | configureLogger({ headless: true }); |
| 41 | 41 | expect(isLoggingEnabled()).toBe(false); |
| 42 | 42 | }); |
| 43 | 43 | }); |
| 44 | 44 | |
| 45 | - describe('isLoggingEnabled', () => { | |
| 46 | - it('should return true in non-headless mode', () => { | |
| 45 | + describe("isLoggingEnabled", () => { | |
| 46 | + it("should return true in non-headless mode", () => { | |
| 47 | 47 | configureLogger({ headless: false }); |
| 48 | 48 | expect(isLoggingEnabled()).toBe(true); |
| 49 | 49 | }); |
| 50 | 50 | |
| 51 | - it('should return false in headless mode', () => { | |
| 51 | + it("should return false in headless mode", () => { | |
| 52 | 52 | configureLogger({ headless: true }); |
| 53 | 53 | expect(isLoggingEnabled()).toBe(false); |
| 54 | 54 | }); |
| 55 | 55 | |
| 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", () => { | |
| 57 | 57 | configureLogger({ headless: true }); |
| 58 | 58 | expect(isLoggingEnabled(true)).toBe(true); |
| 59 | 59 | }); |
| 60 | 60 | |
| 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", () => { | |
| 62 | 62 | configureLogger({ headless: false }); |
| 63 | 63 | expect(isLoggingEnabled(true)).toBe(true); |
| 64 | 64 | }); |
| 65 | 65 | }); |
| 66 | 66 | |
| 67 | - describe('log', () => { | |
| 68 | - it('should log in non-headless mode', () => { | |
| 67 | + describe("log", () => { | |
| 68 | + it("should log in non-headless mode", () => { | |
| 69 | 69 | configureLogger({ headless: false }); |
| 70 | - log('test message'); | |
| 71 | - expect(consoleInfoSpy).toHaveBeenCalledWith('test message'); | |
| 70 | + log("test message"); | |
| 71 | + expect(consoleInfoSpy).toHaveBeenCalledWith("test message"); | |
| 72 | 72 | }); |
| 73 | 73 | |
| 74 | - it('should not log in headless mode', () => { | |
| 74 | + it("should not log in headless mode", () => { | |
| 75 | 75 | configureLogger({ headless: true }); |
| 76 | - log('test message'); | |
| 76 | + log("test message"); | |
| 77 | 77 | expect(consoleInfoSpy).not.toHaveBeenCalled(); |
| 78 | 78 | }); |
| 79 | 79 | |
| 80 | - it('should log in headless mode when forceLog is true', () => { | |
| 80 | + it("should log in headless mode when forceLog is true", () => { | |
| 81 | 81 | 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"); | |
| 84 | 84 | }); |
| 85 | 85 | |
| 86 | - it('should log in non-headless mode when forceLog is true', () => { | |
| 86 | + it("should log in non-headless mode when forceLog is true", () => { | |
| 87 | 87 | 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"); | |
| 90 | 90 | }); |
| 91 | 91 | }); |
| 92 | 92 | |
| 93 | - describe('error', () => { | |
| 94 | - it('should log errors in non-headless mode', () => { | |
| 93 | + describe("error", () => { | |
| 94 | + it("should log errors in non-headless mode", () => { | |
| 95 | 95 | configureLogger({ headless: false }); |
| 96 | - error('error message'); | |
| 97 | - expect(consoleErrorSpy).toHaveBeenCalledWith('error message'); | |
| 96 | + error("error message"); | |
| 97 | + expect(consoleErrorSpy).toHaveBeenCalledWith("error message"); | |
| 98 | 98 | }); |
| 99 | 99 | |
| 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)", () => { | |
| 101 | 101 | configureLogger({ headless: true }); |
| 102 | - error('error message'); | |
| 103 | - expect(consoleErrorSpy).toHaveBeenCalledWith('error message'); | |
| 102 | + error("error message"); | |
| 103 | + expect(consoleErrorSpy).toHaveBeenCalledWith("error message"); | |
| 104 | 104 | }); |
| 105 | 105 | |
| 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", () => { | |
| 107 | 107 | configureLogger({ headless: true }); |
| 108 | - error('error message', false); | |
| 108 | + error("error message", false); | |
| 109 | 109 | expect(consoleErrorSpy).not.toHaveBeenCalled(); |
| 110 | 110 | }); |
| 111 | 111 | |
| 112 | - it('should log errors when forceLog is explicitly true', () => { | |
| 112 | + it("should log errors when forceLog is explicitly true", () => { | |
| 113 | 113 | 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"); | |
| 116 | 116 | }); |
| 117 | 117 | }); |
| 118 | 118 | |
| 119 | - describe('info', () => { | |
| 120 | - it('should log info in non-headless mode', () => { | |
| 119 | + describe("info", () => { | |
| 120 | + it("should log info in non-headless mode", () => { | |
| 121 | 121 | configureLogger({ headless: false }); |
| 122 | - info('info message'); | |
| 123 | - expect(consoleInfoSpy).toHaveBeenCalledWith('info message'); | |
| 122 | + info("info message"); | |
| 123 | + expect(consoleInfoSpy).toHaveBeenCalledWith("info message"); | |
| 124 | 124 | }); |
| 125 | 125 | |
| 126 | - it('should not log info in headless mode', () => { | |
| 126 | + it("should not log info in headless mode", () => { | |
| 127 | 127 | configureLogger({ headless: true }); |
| 128 | - info('info message'); | |
| 128 | + info("info message"); | |
| 129 | 129 | expect(consoleInfoSpy).not.toHaveBeenCalled(); |
| 130 | 130 | }); |
| 131 | 131 | |
| 132 | - it('should log info in headless mode when forceLog is true', () => { | |
| 132 | + it("should log info in headless mode when forceLog is true", () => { | |
| 133 | 133 | 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"); | |
| 136 | 136 | }); |
| 137 | 137 | }); |
| 138 | 138 | |
| 139 | - describe('warn', () => { | |
| 140 | - it('should log warnings in non-headless mode', () => { | |
| 139 | + describe("warn", () => { | |
| 140 | + it("should log warnings in non-headless mode", () => { | |
| 141 | 141 | configureLogger({ headless: false }); |
| 142 | - warn('warning message'); | |
| 143 | - expect(consoleWarnSpy).toHaveBeenCalledWith('warning message'); | |
| 142 | + warn("warning message"); | |
| 143 | + expect(consoleWarnSpy).toHaveBeenCalledWith("warning message"); | |
| 144 | 144 | }); |
| 145 | 145 | |
| 146 | - it('should not log warnings in headless mode', () => { | |
| 146 | + it("should not log warnings in headless mode", () => { | |
| 147 | 147 | configureLogger({ headless: true }); |
| 148 | - warn('warning message'); | |
| 148 | + warn("warning message"); | |
| 149 | 149 | expect(consoleWarnSpy).not.toHaveBeenCalled(); |
| 150 | 150 | }); |
| 151 | 151 | |
| 152 | - it('should log warnings in headless mode when forceLog is true', () => { | |
| 152 | + it("should log warnings in headless mode when forceLog is true", () => { | |
| 153 | 153 | 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"); | |
| 156 | 156 | }); |
| 157 | 157 | }); |
| 158 | 158 | |
| 159 | - describe('loggers object', () => { | |
| 159 | + describe("loggers object", () => { | |
| 160 | 160 | beforeEach(() => { |
| 161 | 161 | configureLogger({ headless: false }); |
| 162 | 162 | }); |
| 163 | 163 | |
| 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 | + ); | |
| 167 | 169 | }); |
| 168 | 170 | |
| 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")); | |
| 172 | 174 | }); |
| 173 | 175 | |
| 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 | + ); | |
| 177 | 181 | }); |
| 178 | 182 | |
| 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")); | |
| 182 | 186 | }); |
| 183 | 187 | |
| 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")); | |
| 187 | 191 | }); |
| 188 | 192 | |
| 189 | - it('should provide command logger that always logs', () => { | |
| 193 | + it("should provide command logger that always logs", () => { | |
| 190 | 194 | 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"); | |
| 193 | 197 | }); |
| 194 | 198 | |
| 195 | - it('should respect forceLog parameter in colored loggers', () => { | |
| 199 | + it("should respect forceLog parameter in colored loggers", () => { | |
| 196 | 200 | configureLogger({ headless: true }); |
| 197 | - | |
| 198 | - loggers.success('success message', false); | |
| 201 | + | |
| 202 | + loggers.success("success message", false); | |
| 199 | 203 | 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 | + ); | |
| 203 | 209 | }); |
| 204 | 210 | |
| 205 | - it('should handle error logger with default forceLog behavior', () => { | |
| 211 | + it("should handle error logger with default forceLog behavior", () => { | |
| 206 | 212 | 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); | |
| 212 | 218 | expect(consoleErrorSpy).toHaveBeenCalledTimes(1); // Should not be called again |
| 213 | 219 | }); |
| 214 | 220 | }); |
| 215 | 221 | |
| 216 | - describe('complex logging scenarios', () => { | |
| 217 | - it('should handle different message types', () => { | |
| 222 | + describe("complex logging scenarios", () => { | |
| 223 | + it("should handle different message types", () => { | |
| 218 | 224 | configureLogger({ headless: false }); |
| 219 | - | |
| 220 | - log('string message'); | |
| 225 | + | |
| 226 | + log("string message"); | |
| 221 | 227 | log(123); |
| 222 | - log({ key: 'value' }); | |
| 228 | + log({ key: "value" }); | |
| 223 | 229 | log(null); |
| 224 | 230 | log(undefined); |
| 225 | - | |
| 231 | + | |
| 226 | 232 | expect(consoleInfoSpy).toHaveBeenCalledTimes(5); |
| 227 | - expect(consoleInfoSpy).toHaveBeenCalledWith('string message'); | |
| 233 | + expect(consoleInfoSpy).toHaveBeenCalledWith("string message"); | |
| 228 | 234 | expect(consoleInfoSpy).toHaveBeenCalledWith(123); |
| 229 | - expect(consoleInfoSpy).toHaveBeenCalledWith({ key: 'value' }); | |
| 235 | + expect(consoleInfoSpy).toHaveBeenCalledWith({ key: "value" }); | |
| 230 | 236 | expect(consoleInfoSpy).toHaveBeenCalledWith(null); |
| 231 | 237 | expect(consoleInfoSpy).toHaveBeenCalledWith(undefined); |
| 232 | 238 | }); |
| 233 | 239 | |
| 234 | - it('should maintain state across multiple configure calls', () => { | |
| 240 | + it("should maintain state across multiple configure calls", () => { | |
| 235 | 241 | configureLogger({ headless: false }); |
| 236 | 242 | expect(isLoggingEnabled()).toBe(true); |
| 237 | - | |
| 243 | + | |
| 238 | 244 | configureLogger({ headless: true }); |
| 239 | 245 | expect(isLoggingEnabled()).toBe(false); |
| 240 | - | |
| 246 | + | |
| 241 | 247 | configureLogger({ headless: false }); |
| 242 | 248 | expect(isLoggingEnabled()).toBe(true); |
| 243 | 249 | }); |
| 244 | 250 | }); |
| 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"; | |
| 4 | 4 | |
| 5 | -import { describe, expect, test, beforeEach, afterEach } from 'vitest'; | |
| 5 | +import { describe, expect, test, beforeEach, afterEach } from "vitest"; | |
| 6 | 6 | |
| 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"; | |
| 9 | 9 | |
| 10 | -describe('onboarding config flag handling', () => { | |
| 10 | +describe("onboarding config flag handling", () => { | |
| 11 | 11 | let tempDir: string; |
| 12 | 12 | let mockAuthConfig: AuthConfig; |
| 13 | 13 | |
| 14 | 14 | beforeEach(() => { |
| 15 | 15 | // 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 | + | |
| 18 | 18 | // Create a minimal auth config for testing |
| 19 | 19 | 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", | |
| 24 | 24 | expiresAt: Date.now() + 3600000, |
| 25 | - organizationId: 'test-org', | |
| 25 | + organizationId: "test-org", | |
| 26 | 26 | }; |
| 27 | 27 | }); |
| 28 | 28 | |
| @@ -33,123 +33,130 @@ | ||
| 33 | 33 | } |
| 34 | 34 | }); |
| 35 | 35 | |
| 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 | + | |
| 39 | 39 | // Verify the file doesn't exist |
| 40 | 40 | expect(fs.existsSync(configPath)).toBe(false); |
| 41 | - | |
| 41 | + | |
| 42 | 42 | // Should throw an error that mentions both the path and the failure |
| 43 | 43 | 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/, | |
| 45 | 45 | ); |
| 46 | 46 | }); |
| 47 | 47 | |
| 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 | + ` | |
| 53 | 55 | name: "Test Config" |
| 54 | 56 | models: |
| 55 | 57 | - name: "GPT-4" |
| 56 | 58 | provider: "openai" |
| 57 | 59 | invalid_yaml_syntax: [unclosed array |
| 58 | -`); | |
| 59 | - | |
| 60 | +`, | |
| 61 | + ); | |
| 62 | + | |
| 60 | 63 | // Verify the file exists |
| 61 | 64 | expect(fs.existsSync(configPath)).toBe(true); |
| 62 | - | |
| 65 | + | |
| 63 | 66 | // Should throw an error mentioning the path and failure to load |
| 64 | 67 | await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( |
| 65 | - /Failed to load config from ".*malformed\.yaml": .+/ | |
| 68 | + /Failed to load config from ".*malformed\.yaml": .+/, | |
| 66 | 69 | ); |
| 67 | 70 | }); |
| 68 | 71 | |
| 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 | + | |
| 72 | 75 | // Create a config file missing required fields |
| 73 | - fs.writeFileSync(configPath, ` | |
| 76 | + fs.writeFileSync( | |
| 77 | + configPath, | |
| 78 | + ` | |
| 74 | 79 | name: "Incomplete Config" |
| 75 | 80 | # Missing models array and other required fields |
| 76 | -`); | |
| 77 | - | |
| 81 | +`, | |
| 82 | + ); | |
| 83 | + | |
| 78 | 84 | // Verify the file exists |
| 79 | 85 | expect(fs.existsSync(configPath)).toBe(true); |
| 80 | - | |
| 86 | + | |
| 81 | 87 | // Should throw with our specific error format and include path |
| 82 | 88 | await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( |
| 83 | - /^Failed to load config from ".*": .+/ | |
| 89 | + /^Failed to load config from ".*": .+/, | |
| 84 | 90 | ); |
| 85 | 91 | }); |
| 86 | 92 | |
| 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 () => { | |
| 88 | 94 | 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", | |
| 93 | 99 | ]; |
| 94 | - | |
| 100 | + | |
| 95 | 101 | for (const configPath of testPaths) { |
| 96 | 102 | await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow( |
| 97 | - /Failed to load config from ".*": .+/ | |
| 103 | + /Failed to load config from ".*": .+/, | |
| 98 | 104 | ); |
| 99 | 105 | } |
| 100 | 106 | }); |
| 101 | 107 | |
| 102 | - test('should handle empty string config path', async () => { | |
| 108 | + test("should handle empty string config path", async () => { | |
| 103 | 109 | // Empty string should be treated differently from undefined |
| 104 | 110 | // Note: empty string triggers onboarding flow, but should still fail in our error format |
| 105 | 111 | await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow(); |
| 106 | 112 | }); |
| 107 | 113 | |
| 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 | + | |
| 111 | 117 | // Create a bad config file |
| 112 | - fs.writeFileSync(configPath, 'invalid: yaml: content: ['); | |
| 113 | - | |
| 118 | + fs.writeFileSync(configPath, "invalid: yaml: content: ["); | |
| 119 | + | |
| 114 | 120 | const promise = runNormalFlow(mockAuthConfig, configPath); |
| 115 | - | |
| 121 | + | |
| 116 | 122 | await expect(promise).rejects.toThrow(); |
| 117 | - | |
| 123 | + | |
| 118 | 124 | try { |
| 119 | 125 | await promise; |
| 120 | 126 | } catch (error) { |
| 121 | 127 | const message = error instanceof Error ? error.message : String(error); |
| 122 | - | |
| 128 | + | |
| 123 | 129 | // CRITICAL: Must have our specific error format from the fix |
| 124 | 130 | expect(message).toMatch(/^Failed to load config from ".*": .+/); |
| 125 | - | |
| 131 | + | |
| 126 | 132 | // Error should be about the specific config file we provided |
| 127 | 133 | expect(message).toContain(configPath); |
| 128 | - | |
| 134 | + | |
| 129 | 135 | // 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"); | |
| 133 | 139 | } |
| 134 | 140 | }); |
| 135 | 141 | |
| 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 | + | |
| 140 | 146 | // Case 1: Explicit --config that fails should throw our specific error |
| 141 | 147 | await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow( |
| 142 | - /^Failed to load config from "/ | |
| 148 | + /^Failed to load config from "/, | |
| 143 | 149 | ); |
| 144 | - | |
| 150 | + | |
| 145 | 151 | // Case 2: No explicit config should follow different logic |
| 146 | 152 | try { |
| 147 | 153 | await runNormalFlow(mockAuthConfig, undefined); |
| 148 | 154 | // If it succeeds, that's fine - the point is it's different behavior |
| 149 | 155 | } catch (error) { |
| 150 | - const errorMessage = error instanceof Error ? error.message : String(error); | |
| 156 | + const errorMessage = | |
| 157 | + error instanceof Error ? error.message : String(error); | |
| 151 | 158 | // This should NOT have our "Failed to load config from" prefix |
| 152 | 159 | expect(errorMessage).not.toMatch(/^Failed to load config from "/); |
| 153 | 160 | } |
| 154 | 161 | }); |
| 155 | -}); | |
| No newline at the end of the file | ||
| 162 | +}); |
modified extensions/cli/src/permissions/defaultPolicies.test.ts +24 −10
| @@ -4,10 +4,18 @@ | ||
| 4 | 4 | |
| 5 | 5 | describe("defaultPolicies", () => { |
| 6 | 6 | 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 | + | |
| 9 | 17 | 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); | |
| 11 | 19 | expect(policy, `Policy should exist for ${tool}`).toBeDefined(); |
| 12 | 20 | expect(policy?.permission, `${tool} should be allowed`).toBe("allow"); |
| 13 | 21 | } |
| @@ -15,29 +23,35 @@ | ||
| 15 | 23 | |
| 16 | 24 | it("should have correct permissions for write tools", () => { |
| 17 | 25 | const writeTools = ["Write", "Edit", "MultiEdit", "Bash"]; |
| 18 | - | |
| 26 | + | |
| 19 | 27 | 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); | |
| 21 | 29 | 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 | + ); | |
| 23 | 33 | } |
| 24 | 34 | }); |
| 25 | 35 | |
| 26 | 36 | 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 === "*"); | |
| 28 | 38 | expect(catchAllPolicy).toBeDefined(); |
| 29 | 39 | expect(catchAllPolicy?.permission).toBe("ask"); |
| 30 | 40 | }); |
| 31 | 41 | |
| 32 | 42 | 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 | + ); | |
| 34 | 46 | expect(multiEditPolicy).toBeDefined(); |
| 35 | 47 | expect(multiEditPolicy?.permission).toBe("ask"); |
| 36 | 48 | }); |
| 37 | 49 | |
| 38 | 50 | it("should have policies in correct order", () => { |
| 39 | 51 | // 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 | + ); | |
| 41 | 55 | expect(catchAllIndex).toBe(DEFAULT_TOOL_POLICIES.length - 1); |
| 42 | 56 | }); |
| 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 @@ | ||
| 23 | 23 | }); |
| 24 | 24 | |
| 25 | 25 | // 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 | + }); | |
| 27 | 30 | // Default policies should follow |
| 28 | 31 | expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES); |
| 29 | 32 | }); |
| @@ -34,16 +37,36 @@ | ||
| 34 | 37 | const permissions = { policies: DEFAULT_TOOL_POLICIES }; |
| 35 | 38 | |
| 36 | 39 | // 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"); | |
| 40 | 52 | |
| 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"); | |
| 44 | 62 | |
| 45 | 63 | // 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"); | |
| 47 | 70 | }); |
| 48 | 71 | |
| 49 | 72 | it("should respect CLI overrides even in headless mode", () => { |
| @@ -56,13 +79,19 @@ | ||
| 56 | 79 | // Excluded tool should be blocked |
| 57 | 80 | const excludedResult = checkToolPermission( |
| 58 | 81 | { name: "dangerous_tool", arguments: {} }, |
| 59 | - permissions | |
| 82 | + permissions, | |
| 60 | 83 | ); |
| 61 | 84 | expect(excludedResult.permission).toBe("exclude"); |
| 62 | 85 | |
| 63 | 86 | // 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"); | |
| 66 | 95 | }); |
| 67 | 96 | }); |
| 68 | 97 | |
| @@ -83,18 +112,38 @@ | ||
| 83 | 112 | const permissions = { policies }; |
| 84 | 113 | |
| 85 | 114 | // 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"); | |
| 88 | 123 | |
| 89 | 124 | // 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"); | |
| 92 | 133 | |
| 93 | 134 | // 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 | + | |
| 96 | 140 | // 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"); | |
| 98 | 147 | }); |
| 99 | 148 | |
| 100 | 149 | it("should handle workflow with wildcard allow override", () => { |
| @@ -109,9 +158,20 @@ | ||
| 109 | 158 | const permissions = { policies }; |
| 110 | 159 | |
| 111 | 160 | // 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"); | |
| 115 | 175 | }); |
| 116 | 176 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { ToolPermissionService } from '../services/ToolPermissionService.js'; | |
| 3 | +import { ToolPermissionService } from "../services/ToolPermissionService.js"; | |
| 4 | 4 | |
| 5 | -import { checkToolPermission } from './permissionChecker.js'; | |
| 5 | +import { checkToolPermission } from "./permissionChecker.js"; | |
| 6 | 6 | |
| 7 | -describe('Permission Integration Tests', () => { | |
| 7 | +describe("Permission Integration Tests", () => { | |
| 8 | 8 | let service: ToolPermissionService; |
| 9 | 9 | |
| 10 | 10 | beforeEach(() => { |
| 11 | 11 | service = new ToolPermissionService(); |
| 12 | 12 | }); |
| 13 | 13 | |
| 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", () => { | |
| 16 | 16 | // Initialize service with headless mode and --allow Edit |
| 17 | 17 | service.initializeSync({ |
| 18 | - allow: ['Edit'], | |
| 19 | - isHeadless: true | |
| 18 | + allow: ["Edit"], | |
| 19 | + isHeadless: true, | |
| 20 | 20 | }); |
| 21 | 21 | |
| 22 | 22 | const state = service.getState(); |
| 23 | - | |
| 23 | + | |
| 24 | 24 | // Check that the service is in headless mode |
| 25 | 25 | expect(state.isHeadless).toBe(true); |
| 26 | 26 | |
| 27 | 27 | // Check permission for Edit tool |
| 28 | 28 | const result = checkToolPermission( |
| 29 | - { name: 'Edit', arguments: {} }, | |
| 30 | - state.permissions | |
| 29 | + { name: "Edit", arguments: {} }, | |
| 30 | + state.permissions, | |
| 31 | 31 | ); |
| 32 | 32 | |
| 33 | 33 | // Should be allowed because --allow Edit is specified |
| 34 | - expect(result.permission).toBe('allow'); | |
| 34 | + expect(result.permission).toBe("allow"); | |
| 35 | 35 | }); |
| 36 | 36 | |
| 37 | - it('should allow multiple tools with --allow in headless mode', () => { | |
| 37 | + it("should allow multiple tools with --allow in headless mode", () => { | |
| 38 | 38 | // Initialize service with headless mode and multiple --allow flags |
| 39 | 39 | service.initializeSync({ |
| 40 | - allow: ['Edit', 'Write', 'Bash'], | |
| 41 | - isHeadless: true | |
| 40 | + allow: ["Edit", "Write", "Bash"], | |
| 41 | + isHeadless: true, | |
| 42 | 42 | }); |
| 43 | 43 | |
| 44 | 44 | const state = service.getState(); |
| 45 | 45 | |
| 46 | 46 | // Check Edit |
| 47 | 47 | const editResult = checkToolPermission( |
| 48 | - { name: 'Edit', arguments: {} }, | |
| 49 | - state.permissions | |
| 48 | + { name: "Edit", arguments: {} }, | |
| 49 | + state.permissions, | |
| 50 | 50 | ); |
| 51 | - expect(editResult.permission).toBe('allow'); | |
| 51 | + expect(editResult.permission).toBe("allow"); | |
| 52 | 52 | |
| 53 | 53 | // Check Write |
| 54 | 54 | const writeResult = checkToolPermission( |
| 55 | - { name: 'Write', arguments: {} }, | |
| 56 | - state.permissions | |
| 55 | + { name: "Write", arguments: {} }, | |
| 56 | + state.permissions, | |
| 57 | 57 | ); |
| 58 | - expect(writeResult.permission).toBe('allow'); | |
| 58 | + expect(writeResult.permission).toBe("allow"); | |
| 59 | 59 | |
| 60 | 60 | // Check Bash |
| 61 | 61 | const bashResult = checkToolPermission( |
| 62 | - { name: 'Bash', arguments: {} }, | |
| 63 | - state.permissions | |
| 62 | + { name: "Bash", arguments: {} }, | |
| 63 | + state.permissions, | |
| 64 | 64 | ); |
| 65 | - expect(bashResult.permission).toBe('allow'); | |
| 65 | + expect(bashResult.permission).toBe("allow"); | |
| 66 | 66 | }); |
| 67 | 67 | |
| 68 | - it('should respect --exclude in headless mode', () => { | |
| 68 | + it("should respect --exclude in headless mode", () => { | |
| 69 | 69 | service.initializeSync({ |
| 70 | - allow: ['Read'], | |
| 71 | - exclude: ['Edit'], | |
| 72 | - isHeadless: true | |
| 70 | + allow: ["Read"], | |
| 71 | + exclude: ["Edit"], | |
| 72 | + isHeadless: true, | |
| 73 | 73 | }); |
| 74 | 74 | |
| 75 | 75 | const state = service.getState(); |
| 76 | 76 | |
| 77 | 77 | // Check that Read is allowed |
| 78 | 78 | const readResult = checkToolPermission( |
| 79 | - { name: 'Read', arguments: {} }, | |
| 80 | - state.permissions | |
| 79 | + { name: "Read", arguments: {} }, | |
| 80 | + state.permissions, | |
| 81 | 81 | ); |
| 82 | - expect(readResult.permission).toBe('allow'); | |
| 82 | + expect(readResult.permission).toBe("allow"); | |
| 83 | 83 | |
| 84 | 84 | // Check that Edit is excluded |
| 85 | 85 | const editResult = checkToolPermission( |
| 86 | - { name: 'Edit', arguments: {} }, | |
| 87 | - state.permissions | |
| 86 | + { name: "Edit", arguments: {} }, | |
| 87 | + state.permissions, | |
| 88 | 88 | ); |
| 89 | - expect(editResult.permission).toBe('exclude'); | |
| 89 | + expect(editResult.permission).toBe("exclude"); | |
| 90 | 90 | }); |
| 91 | 91 | |
| 92 | - it('should work with plan mode and --allow overrides', () => { | |
| 92 | + it("should work with plan mode and --allow overrides", () => { | |
| 93 | 93 | // Plan mode normally excludes write operations |
| 94 | 94 | 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, | |
| 98 | 98 | }); |
| 99 | 99 | |
| 100 | 100 | const state = service.getState(); |
| 101 | 101 | |
| 102 | 102 | // In plan mode with --allow Edit override |
| 103 | 103 | const editResult = checkToolPermission( |
| 104 | - { name: 'Edit', arguments: {} }, | |
| 105 | - state.permissions | |
| 104 | + { name: "Edit", arguments: {} }, | |
| 105 | + state.permissions, | |
| 106 | 106 | ); |
| 107 | - | |
| 107 | + | |
| 108 | 108 | // Currently this fails because plan mode ignores --allow flags |
| 109 | 109 | // After fix, this should be 'allow' |
| 110 | - expect(editResult.permission).toBe('exclude'); // Current behavior | |
| 110 | + expect(editResult.permission).toBe("exclude"); // Current behavior | |
| 111 | 111 | // TODO: After fix, change to: expect(editResult.permission).toBe('allow'); |
| 112 | 112 | }); |
| 113 | 113 | }); |
| 114 | -}); | |
| No newline at the end of the file | ||
| 114 | +}); |
modified extensions/cli/src/permissions/permissionChecker.test.ts +40 −38
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | |
| 22 | 22 | it("should match prefix wildcards", () => { |
| 23 | 23 | expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe( |
| 24 | - true | |
| 24 | + true, | |
| 25 | 25 | ); |
| 26 | 26 | expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true); |
| 27 | 27 | expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false); |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true); |
| 59 | 59 | expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true); |
| 60 | 60 | expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe( |
| 61 | - true | |
| 61 | + true, | |
| 62 | 62 | ); |
| 63 | 63 | }); |
| 64 | 64 | |
| @@ -74,64 +74,66 @@ | ||
| 74 | 74 | describe("Bash command patterns", () => { |
| 75 | 75 | it("should match Bash command patterns with Bash tool", () => { |
| 76 | 76 | expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe( |
| 77 | - true | |
| 77 | + true, | |
| 78 | 78 | ); |
| 79 | 79 | expect( |
| 80 | - matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" }) | |
| 80 | + matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" }), | |
| 81 | 81 | ).toBe(true); |
| 82 | 82 | expect( |
| 83 | - matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" }) | |
| 83 | + matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" }), | |
| 84 | 84 | ).toBe(false); |
| 85 | 85 | }); |
| 86 | 86 | |
| 87 | 87 | it("should match Bash command patterns with Bash display name", () => { |
| 88 | 88 | expect( |
| 89 | - matchesToolPattern("Bash", "Bash(git*)", { command: "git status" }) | |
| 89 | + matchesToolPattern("Bash", "Bash(git*)", { command: "git status" }), | |
| 90 | 90 | ).toBe(true); |
| 91 | 91 | expect( |
| 92 | - matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" }) | |
| 92 | + matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" }), | |
| 93 | 93 | ).toBe(true); |
| 94 | 94 | expect( |
| 95 | - matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" }) | |
| 95 | + matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" }), | |
| 96 | 96 | ).toBe(false); |
| 97 | 97 | }); |
| 98 | 98 | |
| 99 | 99 | it("should match exact Bash commands", () => { |
| 100 | 100 | expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe( |
| 101 | - true | |
| 101 | + true, | |
| 102 | 102 | ); |
| 103 | 103 | expect( |
| 104 | - matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" }) | |
| 104 | + matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" }), | |
| 105 | 105 | ).toBe(false); |
| 106 | 106 | }); |
| 107 | 107 | |
| 108 | 108 | it("should not match Bash patterns for non-bash tools", () => { |
| 109 | 109 | expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe( |
| 110 | - false | |
| 110 | + false, | |
| 111 | 111 | ); |
| 112 | 112 | expect( |
| 113 | - matchesToolPattern("Write", "Bash(git*)", { command: "git status" }) | |
| 113 | + matchesToolPattern("Write", "Bash(git*)", { command: "git status" }), | |
| 114 | 114 | ).toBe(false); |
| 115 | 115 | }); |
| 116 | 116 | |
| 117 | 117 | it("should not match Bash patterns without command argument", () => { |
| 118 | 118 | expect(matchesToolPattern("Bash", "Bash(ls*)", {})).toBe(false); |
| 119 | 119 | expect( |
| 120 | - matchesToolPattern("Bash", "Bash(ls*)", { other: "value" }) | |
| 120 | + matchesToolPattern("Bash", "Bash(ls*)", { other: "value" }), | |
| 121 | 121 | ).toBe(false); |
| 122 | 122 | }); |
| 123 | 123 | |
| 124 | 124 | it("should handle complex Bash command patterns", () => { |
| 125 | 125 | expect( |
| 126 | - matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" }) | |
| 126 | + matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" }), | |
| 127 | 127 | ).toBe(true); |
| 128 | 128 | expect( |
| 129 | - matchesToolPattern("Bash", "Bash(npm*)", { command: "npm run build" }) | |
| 129 | + matchesToolPattern("Bash", "Bash(npm*)", { | |
| 130 | + command: "npm run build", | |
| 131 | + }), | |
| 130 | 132 | ).toBe(true); |
| 131 | 133 | expect( |
| 132 | 134 | matchesToolPattern("Bash", "Bash(git*commit*)", { |
| 133 | 135 | command: "git commit -m 'test'", |
| 134 | - }) | |
| 136 | + }), | |
| 135 | 137 | ).toBe(true); |
| 136 | 138 | }); |
| 137 | 139 | }); |
| @@ -209,7 +211,7 @@ | ||
| 209 | 211 | config: { host: "localhost", port: 3000 }, // Different reference, same content |
| 210 | 212 | }; |
| 211 | 213 | expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe( |
| 212 | - false | |
| 214 | + false, | |
| 213 | 215 | ); |
| 214 | 216 | }); |
| 215 | 217 | |
| @@ -250,11 +252,11 @@ | ||
| 250 | 252 | |
| 251 | 253 | expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true); |
| 252 | 254 | expect(matchesArguments(args, { command: "npm run *:unit" })).toBe( |
| 253 | - true | |
| 255 | + true, | |
| 254 | 256 | ); |
| 255 | 257 | expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true); |
| 256 | 258 | expect( |
| 257 | - matchesArguments(args, { path: "/home/*/projects/*/src/**" }) | |
| 259 | + matchesArguments(args, { path: "/home/*/projects/*/src/**" }), | |
| 258 | 260 | ).toBe(true); |
| 259 | 261 | expect(matchesArguments(args, { command: "yarn *" })).toBe(false); |
| 260 | 262 | }); |
| @@ -268,7 +270,7 @@ | ||
| 268 | 270 | |
| 269 | 271 | // Literal dots, brackets, parentheses should match exactly |
| 270 | 272 | expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe( |
| 271 | - true | |
| 273 | + true, | |
| 272 | 274 | ); |
| 273 | 275 | expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true); |
| 274 | 276 | expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true); |
| @@ -276,7 +278,7 @@ | ||
| 276 | 278 | |
| 277 | 279 | // These should not match due to regex escaping |
| 278 | 280 | expect(matchesArguments(args, { command: "*test_pattern*" })).toBe( |
| 279 | - false | |
| 281 | + false, | |
| 280 | 282 | ); |
| 281 | 283 | expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal |
| 282 | 284 | }); |
| @@ -294,7 +296,7 @@ | ||
| 294 | 296 | tool: "bash", // exact match |
| 295 | 297 | command: "cd*install", // glob match |
| 296 | 298 | flag: "--verbose", // exact match |
| 297 | - }) | |
| 299 | + }), | |
| 298 | 300 | ).toBe(true); |
| 299 | 301 | |
| 300 | 302 | expect( |
| @@ -302,7 +304,7 @@ | ||
| 302 | 304 | tool: "bash", // exact match |
| 303 | 305 | command: "cd*test", // glob no match |
| 304 | 306 | flag: "--verbose", // exact match |
| 305 | - }) | |
| 307 | + }), | |
| 306 | 308 | ).toBe(false); |
| 307 | 309 | }); |
| 308 | 310 | |
| @@ -350,7 +352,7 @@ | ||
| 350 | 352 | |
| 351 | 353 | const result = checkToolPermission( |
| 352 | 354 | { name: "readFile", arguments: { path: "/test.txt" } }, |
| 353 | - permissions | |
| 355 | + permissions, | |
| 354 | 356 | ); |
| 355 | 357 | |
| 356 | 358 | expect(result.permission).toBe("allow"); |
| @@ -367,7 +369,7 @@ | ||
| 367 | 369 | name: "writeFile", |
| 368 | 370 | arguments: { path: "/test.txt", content: "hello" }, |
| 369 | 371 | }, |
| 370 | - permissions | |
| 372 | + permissions, | |
| 371 | 373 | ); |
| 372 | 374 | |
| 373 | 375 | expect(result.permission).toBe("ask"); |
| @@ -381,7 +383,7 @@ | ||
| 381 | 383 | |
| 382 | 384 | const result = checkToolPermission( |
| 383 | 385 | { name: "runTerminalCommand", arguments: { command: "rm -rf /" } }, |
| 384 | - permissions | |
| 386 | + permissions, | |
| 385 | 387 | ); |
| 386 | 388 | |
| 387 | 389 | expect(result.permission).toBe("exclude"); |
| @@ -398,14 +400,14 @@ | ||
| 398 | 400 | |
| 399 | 401 | const mcpResult = checkToolPermission( |
| 400 | 402 | { name: "mcp__ide__getDiagnostics", arguments: {} }, |
| 401 | - permissions | |
| 403 | + permissions, | |
| 402 | 404 | ); |
| 403 | 405 | expect(mcpResult.permission).toBe("ask"); |
| 404 | 406 | expect(mcpResult.matchedPolicy?.tool).toBe("mcp__*"); |
| 405 | 407 | |
| 406 | 408 | const builtinResult = checkToolPermission( |
| 407 | 409 | { name: "readFile", arguments: { path: "/test.txt" } }, |
| 408 | - permissions | |
| 410 | + permissions, | |
| 409 | 411 | ); |
| 410 | 412 | expect(builtinResult.permission).toBe("allow"); |
| 411 | 413 | expect(builtinResult.matchedPolicy?.tool).toBe("*"); |
| @@ -428,7 +430,7 @@ | ||
| 428 | 430 | name: "writeFile", |
| 429 | 431 | arguments: { path: "/sensitive.txt", content: "data" }, |
| 430 | 432 | }, |
| 431 | - permissions | |
| 433 | + permissions, | |
| 432 | 434 | ); |
| 433 | 435 | expect(sensitiveResult.permission).toBe("exclude"); |
| 434 | 436 | |
| @@ -437,7 +439,7 @@ | ||
| 437 | 439 | name: "writeFile", |
| 438 | 440 | arguments: { path: "/normal.txt", content: "data" }, |
| 439 | 441 | }, |
| 440 | - permissions | |
| 442 | + permissions, | |
| 441 | 443 | ); |
| 442 | 444 | expect(normalResult.permission).toBe("allow"); |
| 443 | 445 | }); |
| @@ -459,7 +461,7 @@ | ||
| 459 | 461 | |
| 460 | 462 | const result = checkToolPermission( |
| 461 | 463 | { name: "unknownTool", arguments: {} }, |
| 462 | - permissions | |
| 464 | + permissions, | |
| 463 | 465 | ); |
| 464 | 466 | |
| 465 | 467 | expect(result.permission).toBe("ask"); |
| @@ -477,7 +479,7 @@ | ||
| 477 | 479 | // Should match "Bash(ls*)" pattern and allow |
| 478 | 480 | const lsResult = checkToolPermission( |
| 479 | 481 | { name: "Bash", arguments: { command: "ls -la" } }, |
| 480 | - permissions | |
| 482 | + permissions, | |
| 481 | 483 | ); |
| 482 | 484 | expect(lsResult.permission).toBe("allow"); |
| 483 | 485 | expect(lsResult.matchedPolicy?.tool).toBe("Bash(ls*)"); |
| @@ -485,7 +487,7 @@ | ||
| 485 | 487 | // Should match "Bash(git*)" pattern and ask |
| 486 | 488 | const gitResult = checkToolPermission( |
| 487 | 489 | { name: "Bash", arguments: { command: "git status" } }, |
| 488 | - permissions | |
| 490 | + permissions, | |
| 489 | 491 | ); |
| 490 | 492 | expect(gitResult.permission).toBe("ask"); |
| 491 | 493 | expect(gitResult.matchedPolicy?.tool).toBe("Bash(git*)"); |
| @@ -493,7 +495,7 @@ | ||
| 493 | 495 | // Should match general fallback for other commands |
| 494 | 496 | const npmResult = checkToolPermission( |
| 495 | 497 | { name: "Bash", arguments: { command: "npm install" } }, |
| 496 | - permissions | |
| 498 | + permissions, | |
| 497 | 499 | ); |
| 498 | 500 | expect(npmResult.permission).toBe("ask"); |
| 499 | 501 | expect(npmResult.matchedPolicy?.tool).toBe("Bash"); |
| @@ -522,7 +524,7 @@ | ||
| 522 | 524 | // Should exclude dangerous rm commands |
| 523 | 525 | const rmResult = checkToolPermission( |
| 524 | 526 | { name: "Bash", arguments: { command: "rm -rf /" } }, |
| 525 | - permissions | |
| 527 | + permissions, | |
| 526 | 528 | ); |
| 527 | 529 | expect(rmResult.permission).toBe("exclude"); |
| 528 | 530 | expect(rmResult.matchedPolicy?.argumentMatches?.command).toBe("rm*"); |
| @@ -533,17 +535,17 @@ | ||
| 533 | 535 | name: "Write", |
| 534 | 536 | arguments: { file_path: "/src/components/Button.ts" }, |
| 535 | 537 | }, |
| 536 | - permissions | |
| 538 | + permissions, | |
| 537 | 539 | ); |
| 538 | 540 | expect(tsResult.permission).toBe("ask"); |
| 539 | 541 | expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe( |
| 540 | - "**/*.ts" | |
| 542 | + "**/*.ts", | |
| 541 | 543 | ); |
| 542 | 544 | |
| 543 | 545 | // Should allow other file writes |
| 544 | 546 | const jsResult = checkToolPermission( |
| 545 | 547 | { name: "Write", arguments: { file_path: "/src/utils/helper.js" } }, |
| 546 | - permissions | |
| 548 | + permissions, | |
| 547 | 549 | ); |
| 548 | 550 | expect(jsResult.permission).toBe("allow"); |
| 549 | 551 | expect(jsResult.matchedPolicy?.argumentMatches).toBeUndefined(); |
modified extensions/cli/src/permissions/permissionManager.test.ts +2 −2
| @@ -206,7 +206,7 @@ | ||
| 206 | 206 | |
| 207 | 207 | // Start all requests |
| 208 | 208 | const promises = toolCalls.map((toolCall) => |
| 209 | - manager.requestPermission(toolCall) | |
| 209 | + manager.requestPermission(toolCall), | |
| 210 | 210 | ); |
| 211 | 211 | |
| 212 | 212 | // Get all pending request IDs |
| @@ -255,7 +255,7 @@ | ||
| 255 | 255 | |
| 256 | 256 | const promise = manager.requestPermission(toolCall); |
| 257 | 257 | const requestDetails = manager.getPendingRequest( |
| 258 | - manager.getPendingRequestIds()[0] | |
| 258 | + manager.getPendingRequestIds()[0], | |
| 259 | 259 | ); |
| 260 | 260 | |
| 261 | 261 | 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"; | |
| 2 | 5 | |
| 3 | 6 | describe("permissionsYamlLoader", () => { |
| 4 | 7 | describe("yamlConfigToPolicies", () => { |
| @@ -89,34 +92,34 @@ | ||
| 89 | 92 | describe("parseToolPattern", () => { |
| 90 | 93 | it("should parse tool name without arguments", () => { |
| 91 | 94 | const policy = parseToolPattern("Write", "allow"); |
| 92 | - | |
| 95 | + | |
| 93 | 96 | expect(policy).toEqual({ |
| 94 | 97 | tool: "Write", |
| 95 | - permission: "allow" | |
| 98 | + permission: "allow", | |
| 96 | 99 | }); |
| 97 | 100 | }); |
| 98 | 101 | |
| 99 | 102 | it("should parse tool name with file path pattern", () => { |
| 100 | 103 | const policy = parseToolPattern("Write(**/*.ts)", "exclude"); |
| 101 | - | |
| 104 | + | |
| 102 | 105 | expect(policy).toEqual({ |
| 103 | 106 | tool: "Write", |
| 104 | 107 | permission: "exclude", |
| 105 | 108 | argumentMatches: { |
| 106 | - file_path: "**/*.ts" | |
| 107 | - } | |
| 109 | + file_path: "**/*.ts", | |
| 110 | + }, | |
| 108 | 111 | }); |
| 109 | 112 | }); |
| 110 | 113 | |
| 111 | 114 | it("should parse bash command with argument", () => { |
| 112 | 115 | const policy = parseToolPattern("Bash(npm install)", "ask"); |
| 113 | - | |
| 116 | + | |
| 114 | 117 | expect(policy).toEqual({ |
| 115 | 118 | tool: "Bash", |
| 116 | 119 | permission: "ask", |
| 117 | 120 | argumentMatches: { |
| 118 | - command: "npm install" | |
| 119 | - } | |
| 121 | + command: "npm install", | |
| 122 | + }, | |
| 120 | 123 | }); |
| 121 | 124 | }); |
| 122 | 125 | |
| @@ -124,20 +127,36 @@ | ||
| 124 | 127 | const testCases = [ |
| 125 | 128 | { |
| 126 | 129 | 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 | + }, | |
| 128 | 135 | }, |
| 129 | 136 | { |
| 130 | 137 | 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 | + }, | |
| 132 | 143 | }, |
| 133 | 144 | { |
| 134 | 145 | 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 | + }, | |
| 136 | 151 | }, |
| 137 | 152 | { |
| 138 | 153 | 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 | + }, | |
| 141 | 160 | ]; |
| 142 | 161 | |
| 143 | 162 | testCases.forEach(({ pattern, expected }) => { |
| @@ -148,50 +167,52 @@ | ||
| 148 | 167 | |
| 149 | 168 | it("should handle empty arguments", () => { |
| 150 | 169 | const policy = parseToolPattern("Write()", "allow"); |
| 151 | - | |
| 170 | + | |
| 152 | 171 | expect(policy).toEqual({ |
| 153 | 172 | tool: "Write", |
| 154 | - permission: "allow" | |
| 173 | + permission: "allow", | |
| 155 | 174 | }); |
| 156 | 175 | }); |
| 157 | 176 | |
| 158 | 177 | it("should handle whitespace in arguments", () => { |
| 159 | 178 | const policy = parseToolPattern("Bash( npm run test )", "ask"); |
| 160 | - | |
| 179 | + | |
| 161 | 180 | expect(policy).toEqual({ |
| 162 | 181 | tool: "Bash", |
| 163 | 182 | permission: "ask", |
| 164 | 183 | argumentMatches: { |
| 165 | - command: "npm run test" | |
| 166 | - } | |
| 184 | + command: "npm run test", | |
| 185 | + }, | |
| 167 | 186 | }); |
| 168 | 187 | }); |
| 169 | 188 | |
| 170 | 189 | it("should handle unknown tools with default argument key", () => { |
| 171 | 190 | const policy = parseToolPattern("CustomTool(some-pattern)", "allow"); |
| 172 | - | |
| 191 | + | |
| 173 | 192 | expect(policy).toEqual({ |
| 174 | 193 | tool: "CustomTool", |
| 175 | 194 | permission: "allow", |
| 176 | 195 | argumentMatches: { |
| 177 | - pattern: "some-pattern" | |
| 178 | - } | |
| 196 | + pattern: "some-pattern", | |
| 197 | + }, | |
| 179 | 198 | }); |
| 180 | 199 | }); |
| 181 | 200 | |
| 182 | 201 | 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 | + ); | |
| 184 | 205 | }); |
| 185 | 206 | |
| 186 | 207 | it("should use exact tool names in patterns", () => { |
| 187 | 208 | const policy = parseToolPattern("write(**/*.ts)", "allow"); |
| 188 | - | |
| 209 | + | |
| 189 | 210 | expect(policy).toEqual({ |
| 190 | 211 | tool: "write", |
| 191 | 212 | permission: "allow", |
| 192 | 213 | argumentMatches: { |
| 193 | - pattern: "**/*.ts" | |
| 194 | - } | |
| 214 | + pattern: "**/*.ts", | |
| 215 | + }, | |
| 195 | 216 | }); |
| 196 | 217 | }); |
| 197 | 218 | }); |
modified extensions/cli/src/permissions/policyWriter.test.ts +27 −9
| @@ -4,22 +4,38 @@ | ||
| 4 | 4 | describe("generatePolicyRule", () => { |
| 5 | 5 | it("should return display name for regular tools", () => { |
| 6 | 6 | 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"); | |
| 8 | 10 | expect(generatePolicyRule("List", { path: "/test" })).toBe("List"); |
| 9 | 11 | expect(generatePolicyRule("Search", { pattern: "test" })).toBe("Search"); |
| 10 | 12 | expect(generatePolicyRule("Grep", { pattern: "test" })).toBe("Grep"); // Unknown tool, passes through |
| 11 | 13 | }); |
| 12 | 14 | |
| 13 | 15 | 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 | + ); | |
| 17 | 25 | }); |
| 18 | 26 | |
| 19 | 27 | 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*)"); | |
| 23 | 39 | }); |
| 24 | 40 | |
| 25 | 41 | it("should fallback to display name for bash tools without command", () => { |
| @@ -32,7 +48,9 @@ | ||
| 32 | 48 | expect(generatePolicyRule("bash", { command: "ls" })).toBe("bash"); |
| 33 | 49 | expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("BASH"); |
| 34 | 50 | 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"); | |
| 36 | 54 | }); |
| 37 | 55 | }); |
| 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 @@ | ||
| 20 | 20 | expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("EDIT"); |
| 21 | 21 | expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit"); |
| 22 | 22 | }); |
| 23 | -}); | |
| No newline at the end of the file | ||
| 23 | +}); |
modified extensions/cli/src/permissions/precedenceResolver.test.ts +5 −5
| @@ -128,15 +128,15 @@ | ||
| 128 | 128 | }); |
| 129 | 129 | |
| 130 | 130 | // 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"); | |
| 132 | 132 | expect(writePolicy?.permission).toBe("allow"); |
| 133 | 133 | |
| 134 | 134 | // 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"); | |
| 136 | 136 | expect(searchPolicy?.permission).toBe("ask"); |
| 137 | 137 | |
| 138 | 138 | // Should still have default policies |
| 139 | - const readPolicy = policies.find(p => p.tool === "Read"); | |
| 139 | + const readPolicy = policies.find((p) => p.tool === "Read"); | |
| 140 | 140 | expect(readPolicy).toBeDefined(); |
| 141 | 141 | }); |
| 142 | 142 | |
| @@ -178,9 +178,9 @@ | ||
| 178 | 178 | |
| 179 | 179 | // Config policy should override default |
| 180 | 180 | expect(policies[0]).toEqual({ tool: "Bash", permission: "allow" }); |
| 181 | - // Default policies should follow | |
| 181 | + // Default policies should follow | |
| 182 | 182 | expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES); |
| 183 | 183 | }); |
| 184 | 184 | }); |
| 185 | 185 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { checkToolPermission } from './permissionChecker.js'; | |
| 4 | -import { yamlConfigToPolicies } from './permissionsYamlLoader.js'; | |
| 3 | +import { checkToolPermission } from "./permissionChecker.js"; | |
| 4 | +import { yamlConfigToPolicies } from "./permissionsYamlLoader.js"; | |
| 5 | 5 | |
| 6 | 6 | // Mock fs module |
| 7 | -vi.mock('fs'); | |
| 7 | +vi.mock("fs"); | |
| 8 | 8 | |
| 9 | -describe('YAML Permissions - Edit Tool Bug', () => { | |
| 9 | +describe("YAML Permissions - Edit Tool Bug", () => { | |
| 10 | 10 | beforeEach(() => { |
| 11 | 11 | vi.clearAllMocks(); |
| 12 | 12 | }); |
| 13 | 13 | |
| 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", () => { | |
| 15 | 15 | // Test the exact YAML content from the user |
| 16 | 16 | const yamlContent = `allow: |
| 17 | 17 | - Edit |
| @@ -20,54 +20,52 @@ | ||
| 20 | 20 | |
| 21 | 21 | // Parse the YAML config |
| 22 | 22 | const config = { |
| 23 | - allow: ['Edit'], | |
| 23 | + allow: ["Edit"], | |
| 24 | 24 | ask: [], |
| 25 | - exclude: [] | |
| 25 | + exclude: [], | |
| 26 | 26 | }; |
| 27 | 27 | |
| 28 | 28 | // Convert to policies |
| 29 | 29 | const policies = yamlConfigToPolicies(config); |
| 30 | - console.log('Converted policies:', policies); | |
| 30 | + console.log("Converted policies:", policies); | |
| 31 | 31 | |
| 32 | 32 | // 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" }]); | |
| 36 | 34 | |
| 37 | 35 | // Test permission check with tool call named "Edit" |
| 38 | 36 | const toolCall1 = { |
| 39 | - name: 'Edit', | |
| 40 | - arguments: { filepath: 'test.txt' } | |
| 37 | + name: "Edit", | |
| 38 | + arguments: { filepath: "test.txt" }, | |
| 41 | 39 | }; |
| 42 | 40 | const result1 = checkToolPermission(toolCall1, { policies }); |
| 43 | 41 | console.log('Permission check for "Edit":', result1); |
| 44 | - expect(result1.permission).toBe('allow'); | |
| 42 | + expect(result1.permission).toBe("allow"); | |
| 45 | 43 | |
| 46 | 44 | // Legacy names should NOT work anymore |
| 47 | 45 | 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" }, | |
| 50 | 48 | }; |
| 51 | 49 | const result2 = checkToolPermission(toolCall2, { policies }); |
| 52 | 50 | 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 | |
| 54 | 52 | |
| 55 | 53 | // Legacy names should NOT work anymore |
| 56 | 54 | const toolCall3 = { |
| 57 | - name: 'edit_file', | |
| 58 | - arguments: { filepath: 'test.txt' } | |
| 55 | + name: "edit_file", | |
| 56 | + arguments: { filepath: "test.txt" }, | |
| 59 | 57 | }; |
| 60 | 58 | const result3 = checkToolPermission(toolCall3, { policies }); |
| 61 | 59 | 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 | |
| 63 | 61 | }); |
| 64 | 62 | |
| 65 | -it('should use exact tool names without normalization', () => { | |
| 63 | + it("should use exact tool names without normalization", () => { | |
| 66 | 64 | // Tools are now used exactly as they are named, no normalization |
| 67 | 65 | const editName = "Edit"; |
| 68 | 66 | const multiEditName = "MultiEdit"; |
| 69 | - | |
| 67 | + | |
| 70 | 68 | expect(editName).toBe("Edit"); |
| 71 | 69 | expect(multiEditName).toBe("MultiEdit"); |
| 72 | 70 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | 3 | // 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"; | |
| 6 | 6 | |
| 7 | -import { ApiClientService } from './ApiClientService.js'; | |
| 7 | +import { ApiClientService } from "./ApiClientService.js"; | |
| 8 | 8 | |
| 9 | -describe('ApiClientService', () => { | |
| 9 | +describe("ApiClientService", () => { | |
| 10 | 10 | let service: ApiClientService; |
| 11 | 11 | const mockApiClient = { |
| 12 | 12 | get: vi.fn(), |
| 13 | 13 | post: vi.fn(), |
| 14 | 14 | put: vi.fn(), |
| 15 | - delete: vi.fn() | |
| 15 | + delete: vi.fn(), | |
| 16 | 16 | }; |
| 17 | 17 | |
| 18 | 18 | beforeEach(() => { |
| @@ -20,114 +20,118 @@ | ||
| 20 | 20 | service = new ApiClientService(); |
| 21 | 21 | }); |
| 22 | 22 | |
| 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 () => { | |
| 25 | 25 | vi.mocked(config.getApiClient).mockReturnValue(null as any); |
| 26 | 26 | |
| 27 | 27 | const state = await service.initialize({ accessToken: null } as any); |
| 28 | 28 | |
| 29 | 29 | expect(state).toEqual({ |
| 30 | - apiClient: null | |
| 30 | + apiClient: null, | |
| 31 | 31 | }); |
| 32 | 32 | }); |
| 33 | 33 | |
| 34 | - test('should initialize with api client when token provided', async () => { | |
| 34 | + test("should initialize with api client when token provided", async () => { | |
| 35 | 35 | vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any); |
| 36 | 36 | |
| 37 | - const state = await service.initialize({ accessToken: 'test-token' } as any); | |
| 37 | + const state = await service.initialize({ | |
| 38 | + accessToken: "test-token", | |
| 39 | + } as any); | |
| 38 | 40 | |
| 39 | 41 | expect(state).toEqual({ |
| 40 | - apiClient: mockApiClient | |
| 42 | + apiClient: mockApiClient, | |
| 41 | 43 | }); |
| 42 | - expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith('test-token'); | |
| 44 | + expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith("test-token"); | |
| 43 | 45 | }); |
| 44 | 46 | }); |
| 45 | 47 | |
| 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 () => { | |
| 48 | 50 | // Initialize first |
| 49 | 51 | vi.mocked(config.getApiClient).mockReturnValue(null as any); |
| 50 | 52 | await service.initialize({ accessToken: null } as any); |
| 51 | 53 | |
| 52 | 54 | // Update with new token |
| 53 | 55 | 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); | |
| 55 | 57 | |
| 56 | 58 | expect(state).toEqual({ |
| 57 | - apiClient: mockApiClient | |
| 59 | + apiClient: mockApiClient, | |
| 58 | 60 | }); |
| 59 | 61 | expect(service.getState()).toEqual(state); |
| 60 | 62 | }); |
| 61 | 63 | |
| 62 | - test('should handle update errors', async () => { | |
| 64 | + test("should handle update errors", async () => { | |
| 63 | 65 | await service.initialize({ accessToken: null } as any); |
| 64 | - | |
| 66 | + | |
| 65 | 67 | vi.mocked(config.getApiClient).mockImplementation(() => { |
| 66 | - throw new Error('Failed to create client'); | |
| 68 | + throw new Error("Failed to create client"); | |
| 67 | 69 | }); |
| 68 | 70 | |
| 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"); | |
| 72 | 74 | }); |
| 73 | 75 | }); |
| 74 | 76 | |
| 75 | - describe('isReady()', () => { | |
| 76 | - test('should return false when not initialized', () => { | |
| 77 | + describe("isReady()", () => { | |
| 78 | + test("should return false when not initialized", () => { | |
| 77 | 79 | expect(service.isReady()).toBe(false); |
| 78 | 80 | }); |
| 79 | 81 | |
| 80 | - test('should return false when api client is null', async () => { | |
| 82 | + test("should return false when api client is null", async () => { | |
| 81 | 83 | vi.mocked(config.getApiClient).mockReturnValue(null as any); |
| 82 | 84 | await service.initialize({ accessToken: null } as any); |
| 83 | 85 | |
| 84 | 86 | expect(service.isReady()).toBe(false); |
| 85 | 87 | }); |
| 86 | 88 | |
| 87 | - test('should return true when api client exists', async () => { | |
| 89 | + test("should return true when api client exists", async () => { | |
| 88 | 90 | vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any); |
| 89 | - await service.initialize({ accessToken: 'token' } as any); | |
| 91 | + await service.initialize({ accessToken: "token" } as any); | |
| 90 | 92 | |
| 91 | 93 | expect(service.isReady()).toBe(true); |
| 92 | 94 | }); |
| 93 | 95 | }); |
| 94 | 96 | |
| 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"]); | |
| 98 | 100 | }); |
| 99 | 101 | }); |
| 100 | 102 | |
| 101 | - describe('Event Emission', () => { | |
| 102 | - test('should emit stateChanged on update', async () => { | |
| 103 | + describe("Event Emission", () => { | |
| 104 | + test("should emit stateChanged on update", async () => { | |
| 103 | 105 | vi.mocked(config.getApiClient).mockReturnValue(null as any); |
| 104 | 106 | await service.initialize({ accessToken: null } as any); |
| 105 | 107 | |
| 106 | 108 | const listener = vi.fn(); |
| 107 | - service.on('stateChanged', listener); | |
| 109 | + service.on("stateChanged", listener); | |
| 108 | 110 | |
| 109 | 111 | 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); | |
| 111 | 113 | |
| 112 | 114 | expect(listener).toHaveBeenCalledWith( |
| 113 | 115 | expect.objectContaining({ apiClient: mockApiClient }), |
| 114 | - expect.objectContaining({ apiClient: null }) | |
| 116 | + expect.objectContaining({ apiClient: null }), | |
| 115 | 117 | ); |
| 116 | 118 | }); |
| 117 | 119 | |
| 118 | - test('should emit error on update failure', async () => { | |
| 120 | + test("should emit error on update failure", async () => { | |
| 119 | 121 | await service.initialize({ accessToken: null } as any); |
| 120 | - | |
| 122 | + | |
| 121 | 123 | const errorListener = vi.fn(); |
| 122 | - service.on('error', errorListener); | |
| 124 | + service.on("error", errorListener); | |
| 123 | 125 | |
| 124 | - const error = new Error('Update failed'); | |
| 126 | + const error = new Error("Update failed"); | |
| 125 | 127 | vi.mocked(config.getApiClient).mockImplementation(() => { |
| 126 | 128 | throw error; |
| 127 | 129 | }); |
| 128 | 130 | |
| 129 | - await expect(service.update({ accessToken: 'bad' } as any)).rejects.toThrow(); | |
| 131 | + await expect( | |
| 132 | + service.update({ accessToken: "bad" } as any), | |
| 133 | + ).rejects.toThrow(); | |
| 130 | 134 | expect(errorListener).toHaveBeenCalledWith(error); |
| 131 | 135 | }); |
| 132 | 136 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | 3 | // Mock the workos module |
| 4 | -vi.mock('../auth/workos.js'); | |
| 4 | +vi.mock("../auth/workos.js"); | |
| 5 | 5 | |
| 6 | 6 | // Import the workos functions we need to mock |
| 7 | -import { | |
| 7 | +import { | |
| 8 | 8 | loadAuthConfig, |
| 9 | 9 | isAuthenticated, |
| 10 | 10 | login, |
| 11 | 11 | logout, |
| 12 | 12 | ensureOrganization, |
| 13 | 13 | saveAuthConfig, |
| 14 | - listUserOrganizations | |
| 15 | -} from '../auth/workos.js'; | |
| 14 | + listUserOrganizations, | |
| 15 | +} from "../auth/workos.js"; | |
| 16 | 16 | |
| 17 | -import { AuthService } from './AuthService.js'; | |
| 17 | +import { AuthService } from "./AuthService.js"; | |
| 18 | 18 | |
| 19 | -describe('AuthService', () => { | |
| 19 | +describe("AuthService", () => { | |
| 20 | 20 | let service: AuthService; |
| 21 | 21 | 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, | |
| 28 | 28 | }; |
| 29 | 29 | |
| 30 | 30 | beforeEach(() => { |
| @@ -32,8 +32,8 @@ | ||
| 32 | 32 | service = new AuthService(); |
| 33 | 33 | }); |
| 34 | 34 | |
| 35 | - describe('State Management', () => { | |
| 36 | - test('should initialize with unauthenticated state', async () => { | |
| 35 | + describe("State Management", () => { | |
| 36 | + test("should initialize with unauthenticated state", async () => { | |
| 37 | 37 | vi.mocked(loadAuthConfig).mockReturnValue(null); |
| 38 | 38 | vi.mocked(isAuthenticated).mockReturnValue(false); |
| 39 | 39 | |
| @@ -42,11 +42,11 @@ | ||
| 42 | 42 | expect(state).toEqual({ |
| 43 | 43 | authConfig: null, |
| 44 | 44 | isAuthenticated: false, |
| 45 | - organizationId: undefined | |
| 45 | + organizationId: undefined, | |
| 46 | 46 | }); |
| 47 | 47 | }); |
| 48 | 48 | |
| 49 | - test('should initialize with authenticated state', async () => { | |
| 49 | + test("should initialize with authenticated state", async () => { | |
| 50 | 50 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 51 | 51 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 52 | 52 | |
| @@ -55,13 +55,13 @@ | ||
| 55 | 55 | expect(state).toEqual({ |
| 56 | 56 | authConfig: mockAuthConfig, |
| 57 | 57 | isAuthenticated: true, |
| 58 | - organizationId: 'org-123' | |
| 58 | + organizationId: "org-123", | |
| 59 | 59 | }); |
| 60 | 60 | }); |
| 61 | 61 | }); |
| 62 | 62 | |
| 63 | - describe('login()', () => { | |
| 64 | - test('should update state after successful login', async () => { | |
| 63 | + describe("login()", () => { | |
| 64 | + test("should update state after successful login", async () => { | |
| 65 | 65 | // Initialize first |
| 66 | 66 | vi.mocked(loadAuthConfig).mockReturnValue(null); |
| 67 | 67 | vi.mocked(isAuthenticated).mockReturnValue(false); |
| @@ -75,22 +75,22 @@ | ||
| 75 | 75 | expect(state).toEqual({ |
| 76 | 76 | authConfig: mockAuthConfig, |
| 77 | 77 | isAuthenticated: true, |
| 78 | - organizationId: 'org-123' | |
| 78 | + organizationId: "org-123", | |
| 79 | 79 | }); |
| 80 | 80 | expect(service.getState()).toEqual(state); |
| 81 | 81 | }); |
| 82 | 82 | |
| 83 | - test('should handle login failure', async () => { | |
| 83 | + test("should handle login failure", async () => { | |
| 84 | 84 | await service.initialize(); |
| 85 | - const loginError = new Error('Login failed'); | |
| 85 | + const loginError = new Error("Login failed"); | |
| 86 | 86 | vi.mocked(login).mockRejectedValue(loginError); |
| 87 | 87 | |
| 88 | - await expect(service.login()).rejects.toThrow('Login failed'); | |
| 88 | + await expect(service.login()).rejects.toThrow("Login failed"); | |
| 89 | 89 | }); |
| 90 | 90 | }); |
| 91 | 91 | |
| 92 | - describe('logout()', () => { | |
| 93 | - test('should clear state after logout', async () => { | |
| 92 | + describe("logout()", () => { | |
| 93 | + test("should clear state after logout", async () => { | |
| 94 | 94 | // Initialize with authenticated state |
| 95 | 95 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 96 | 96 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| @@ -101,14 +101,14 @@ | ||
| 101 | 101 | expect(state).toEqual({ |
| 102 | 102 | authConfig: null, |
| 103 | 103 | isAuthenticated: false, |
| 104 | - organizationId: undefined | |
| 104 | + organizationId: undefined, | |
| 105 | 105 | }); |
| 106 | 106 | expect(logout).toHaveBeenCalled(); |
| 107 | 107 | }); |
| 108 | 108 | }); |
| 109 | 109 | |
| 110 | - describe('ensureOrganization()', () => { | |
| 111 | - test('should update organization after ensuring', async () => { | |
| 110 | + describe("ensureOrganization()", () => { | |
| 111 | + test("should update organization after ensuring", async () => { | |
| 112 | 112 | // Initialize with auth but no org |
| 113 | 113 | const authWithoutOrg = { ...mockAuthConfig, organizationId: null }; |
| 114 | 114 | vi.mocked(loadAuthConfig).mockReturnValue(authWithoutOrg); |
| @@ -123,39 +123,43 @@ | ||
| 123 | 123 | expect(state).toEqual({ |
| 124 | 124 | authConfig: mockAuthConfig, |
| 125 | 125 | isAuthenticated: true, |
| 126 | - organizationId: 'org-123' | |
| 126 | + organizationId: "org-123", | |
| 127 | 127 | }); |
| 128 | 128 | }); |
| 129 | 129 | |
| 130 | - test('should throw error if not authenticated', async () => { | |
| 130 | + test("should throw error if not authenticated", async () => { | |
| 131 | 131 | vi.mocked(loadAuthConfig).mockReturnValue(null); |
| 132 | 132 | vi.mocked(isAuthenticated).mockReturnValue(false); |
| 133 | 133 | await service.initialize(); |
| 134 | 134 | |
| 135 | 135 | await expect(service.ensureOrganization()).rejects.toThrow( |
| 136 | - 'Not authenticated - cannot ensure organization' | |
| 136 | + "Not authenticated - cannot ensure organization", | |
| 137 | 137 | ); |
| 138 | 138 | }); |
| 139 | 139 | |
| 140 | - test('should pass organization slug to ensureOrganization in headless mode', async () => { | |
| 140 | + test("should pass organization slug to ensureOrganization in headless mode", async () => { | |
| 141 | 141 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 142 | 142 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 143 | 143 | await service.initialize(); |
| 144 | 144 | |
| 145 | - const updatedConfig = { ...mockAuthConfig, organizationId: 'org-456' }; | |
| 145 | + const updatedConfig = { ...mockAuthConfig, organizationId: "org-456" }; | |
| 146 | 146 | vi.mocked(ensureOrganization).mockResolvedValue(updatedConfig); |
| 147 | 147 | |
| 148 | - const state = await service.ensureOrganization(true, 'org-slug'); | |
| 148 | + const state = await service.ensureOrganization(true, "org-slug"); | |
| 149 | 149 | |
| 150 | - expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'org-slug'); | |
| 150 | + expect(ensureOrganization).toHaveBeenCalledWith( | |
| 151 | + mockAuthConfig, | |
| 152 | + true, | |
| 153 | + "org-slug", | |
| 154 | + ); | |
| 151 | 155 | expect(state).toEqual({ |
| 152 | 156 | authConfig: updatedConfig, |
| 153 | 157 | isAuthenticated: true, |
| 154 | - organizationId: 'org-456' | |
| 158 | + organizationId: "org-456", | |
| 155 | 159 | }); |
| 156 | 160 | }); |
| 157 | 161 | |
| 158 | - test('should handle personal organization slug', async () => { | |
| 162 | + test("should handle personal organization slug", async () => { | |
| 159 | 163 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 160 | 164 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 161 | 165 | await service.initialize(); |
| @@ -163,17 +167,21 @@ | ||
| 163 | 167 | const personalConfig = { ...mockAuthConfig, organizationId: null }; |
| 164 | 168 | vi.mocked(ensureOrganization).mockResolvedValue(personalConfig); |
| 165 | 169 | |
| 166 | - const state = await service.ensureOrganization(true, 'personal'); | |
| 170 | + const state = await service.ensureOrganization(true, "personal"); | |
| 167 | 171 | |
| 168 | - expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'personal'); | |
| 172 | + expect(ensureOrganization).toHaveBeenCalledWith( | |
| 173 | + mockAuthConfig, | |
| 174 | + true, | |
| 175 | + "personal", | |
| 176 | + ); | |
| 169 | 177 | expect(state).toEqual({ |
| 170 | 178 | authConfig: personalConfig, |
| 171 | 179 | isAuthenticated: true, |
| 172 | - organizationId: undefined | |
| 180 | + organizationId: undefined, | |
| 173 | 181 | }); |
| 174 | 182 | }); |
| 175 | 183 | |
| 176 | - test('should work without organization slug parameter', async () => { | |
| 184 | + test("should work without organization slug parameter", async () => { | |
| 177 | 185 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 178 | 186 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 179 | 187 | await service.initialize(); |
| @@ -182,38 +190,42 @@ | ||
| 182 | 190 | |
| 183 | 191 | const state = await service.ensureOrganization(false); |
| 184 | 192 | |
| 185 | - expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, false, undefined); | |
| 193 | + expect(ensureOrganization).toHaveBeenCalledWith( | |
| 194 | + mockAuthConfig, | |
| 195 | + false, | |
| 196 | + undefined, | |
| 197 | + ); | |
| 186 | 198 | expect(state).toEqual({ |
| 187 | 199 | authConfig: mockAuthConfig, |
| 188 | 200 | isAuthenticated: true, |
| 189 | - organizationId: 'org-123' | |
| 201 | + organizationId: "org-123", | |
| 190 | 202 | }); |
| 191 | 203 | }); |
| 192 | 204 | }); |
| 193 | 205 | |
| 194 | - describe('switchOrganization()', () => { | |
| 195 | - test('should update state with new organization', async () => { | |
| 206 | + describe("switchOrganization()", () => { | |
| 207 | + test("should update state with new organization", async () => { | |
| 196 | 208 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 197 | 209 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 198 | 210 | await service.initialize(); |
| 199 | 211 | |
| 200 | - const state = await service.switchOrganization('org-456'); | |
| 212 | + const state = await service.switchOrganization("org-456"); | |
| 201 | 213 | |
| 202 | 214 | expect(state).toEqual({ |
| 203 | 215 | authConfig: { |
| 204 | 216 | ...mockAuthConfig, |
| 205 | - organizationId: 'org-456' | |
| 217 | + organizationId: "org-456", | |
| 206 | 218 | }, |
| 207 | 219 | isAuthenticated: true, |
| 208 | - organizationId: 'org-456' | |
| 220 | + organizationId: "org-456", | |
| 209 | 221 | }); |
| 210 | 222 | expect(saveAuthConfig).toHaveBeenCalledWith({ |
| 211 | 223 | ...mockAuthConfig, |
| 212 | - organizationId: 'org-456' | |
| 224 | + organizationId: "org-456", | |
| 213 | 225 | }); |
| 214 | 226 | }); |
| 215 | 227 | |
| 216 | - test('should handle null organization', async () => { | |
| 228 | + test("should handle null organization", async () => { | |
| 217 | 229 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 218 | 230 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 219 | 231 | await service.initialize(); |
| @@ -223,27 +235,27 @@ | ||
| 223 | 235 | expect(state.organizationId).toBeUndefined(); |
| 224 | 236 | }); |
| 225 | 237 | |
| 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; | |
| 228 | 240 | vi.mocked(loadAuthConfig).mockReturnValue(tokenOnlyAuth); |
| 229 | 241 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 230 | 242 | await service.initialize(); |
| 231 | 243 | |
| 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", | |
| 234 | 246 | ); |
| 235 | 247 | }); |
| 236 | 248 | }); |
| 237 | 249 | |
| 238 | - describe('getAvailableOrganizations()', () => { | |
| 239 | - test('should return organizations when authenticated', async () => { | |
| 250 | + describe("getAvailableOrganizations()", () => { | |
| 251 | + test("should return organizations when authenticated", async () => { | |
| 240 | 252 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 241 | 253 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 242 | 254 | await service.initialize(); |
| 243 | 255 | |
| 244 | 256 | 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" }, | |
| 247 | 259 | ]; |
| 248 | 260 | vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs); |
| 249 | 261 | |
| @@ -251,7 +263,7 @@ | ||
| 251 | 263 | expect(orgs).toEqual(mockOrgs); |
| 252 | 264 | }); |
| 253 | 265 | |
| 254 | - test('should return null when not authenticated', async () => { | |
| 266 | + test("should return null when not authenticated", async () => { | |
| 255 | 267 | vi.mocked(loadAuthConfig).mockReturnValue(null); |
| 256 | 268 | vi.mocked(isAuthenticated).mockReturnValue(false); |
| 257 | 269 | await service.initialize(); |
| @@ -260,42 +272,44 @@ | ||
| 260 | 272 | expect(orgs).toBeNull(); |
| 261 | 273 | }); |
| 262 | 274 | |
| 263 | - test('should handle errors gracefully', async () => { | |
| 275 | + test("should handle errors gracefully", async () => { | |
| 264 | 276 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 265 | 277 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 266 | 278 | await service.initialize(); |
| 267 | 279 | |
| 268 | - vi.mocked(listUserOrganizations).mockRejectedValue(new Error('API error')); | |
| 280 | + vi.mocked(listUserOrganizations).mockRejectedValue( | |
| 281 | + new Error("API error"), | |
| 282 | + ); | |
| 269 | 283 | |
| 270 | 284 | // Add error event listener to prevent unhandled rejection |
| 271 | 285 | const errorHandler = vi.fn(); |
| 272 | - service.on('error', errorHandler); | |
| 286 | + service.on("error", errorHandler); | |
| 273 | 287 | |
| 274 | 288 | const orgs = await service.getAvailableOrganizations(); |
| 275 | 289 | expect(orgs).toBeNull(); |
| 276 | 290 | expect(errorHandler).toHaveBeenCalledWith(expect.any(Error)); |
| 277 | 291 | |
| 278 | 292 | // Clean up |
| 279 | - service.off('error', errorHandler); | |
| 293 | + service.off("error", errorHandler); | |
| 280 | 294 | }); |
| 281 | 295 | }); |
| 282 | 296 | |
| 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 () => { | |
| 285 | 299 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 286 | 300 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 287 | 301 | await service.initialize(); |
| 288 | 302 | |
| 289 | 303 | 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" }, | |
| 292 | 306 | ]); |
| 293 | 307 | |
| 294 | 308 | const hasMultiple = await service.hasMultipleOrganizations(); |
| 295 | 309 | expect(hasMultiple).toBe(true); |
| 296 | 310 | }); |
| 297 | 311 | |
| 298 | - test('should return false when no orgs available', async () => { | |
| 312 | + test("should return false when no orgs available", async () => { | |
| 299 | 313 | vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig); |
| 300 | 314 | vi.mocked(isAuthenticated).mockReturnValue(true); |
| 301 | 315 | await service.initialize(); |
| @@ -307,8 +321,8 @@ | ||
| 307 | 321 | }); |
| 308 | 322 | }); |
| 309 | 323 | |
| 310 | - describe('refresh()', () => { | |
| 311 | - test('should reload auth state from disk', async () => { | |
| 324 | + describe("refresh()", () => { | |
| 325 | + test("should reload auth state from disk", async () => { | |
| 312 | 326 | vi.mocked(loadAuthConfig).mockReturnValue(null); |
| 313 | 327 | vi.mocked(isAuthenticated).mockReturnValue(false); |
| 314 | 328 | await service.initialize(); |
| @@ -322,20 +336,20 @@ | ||
| 322 | 336 | expect(state).toEqual({ |
| 323 | 337 | authConfig: mockAuthConfig, |
| 324 | 338 | isAuthenticated: true, |
| 325 | - organizationId: 'org-123' | |
| 339 | + organizationId: "org-123", | |
| 326 | 340 | }); |
| 327 | 341 | }); |
| 328 | 342 | }); |
| 329 | 343 | |
| 330 | - describe('Event Emission', () => { | |
| 331 | - test('should emit stateChanged on login', async () => { | |
| 344 | + describe("Event Emission", () => { | |
| 345 | + test("should emit stateChanged on login", async () => { | |
| 332 | 346 | // Initialize with no auth config to simulate logged out state |
| 333 | 347 | vi.mocked(loadAuthConfig).mockReturnValue(null); |
| 334 | 348 | vi.mocked(isAuthenticated).mockReturnValue(false); |
| 335 | 349 | await service.initialize(); |
| 336 | - | |
| 350 | + | |
| 337 | 351 | const listener = vi.fn(); |
| 338 | - service.on('stateChanged', listener); | |
| 352 | + service.on("stateChanged", listener); | |
| 339 | 353 | |
| 340 | 354 | vi.mocked(login).mockResolvedValue(mockAuthConfig); |
| 341 | 355 | await service.login(); |
| @@ -344,25 +358,25 @@ | ||
| 344 | 358 | expect.objectContaining({ |
| 345 | 359 | isAuthenticated: true, |
| 346 | 360 | authConfig: mockAuthConfig, |
| 347 | - organizationId: 'org-123' | |
| 361 | + organizationId: "org-123", | |
| 348 | 362 | }), |
| 349 | 363 | expect.objectContaining({ |
| 350 | 364 | isAuthenticated: false, |
| 351 | - authConfig: null | |
| 352 | - }) | |
| 365 | + authConfig: null, | |
| 366 | + }), | |
| 353 | 367 | ); |
| 354 | 368 | }); |
| 355 | 369 | |
| 356 | - test('should emit error on login failure', async () => { | |
| 370 | + test("should emit error on login failure", async () => { | |
| 357 | 371 | await service.initialize(); |
| 358 | 372 | const errorListener = vi.fn(); |
| 359 | - service.on('error', errorListener); | |
| 373 | + service.on("error", errorListener); | |
| 360 | 374 | |
| 361 | - const error = new Error('Login failed'); | |
| 375 | + const error = new Error("Login failed"); | |
| 362 | 376 | vi.mocked(login).mockRejectedValue(error); |
| 363 | 377 | |
| 364 | 378 | await expect(service.login()).rejects.toThrow(); |
| 365 | 379 | expect(errorListener).toHaveBeenCalledWith(error); |
| 366 | 380 | }); |
| 367 | 381 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { BaseService, hasDependencies, ServiceWithDependencies } from './BaseService.js'; | |
| 3 | +import { | |
| 4 | + BaseService, | |
| 5 | + hasDependencies, | |
| 6 | + ServiceWithDependencies, | |
| 7 | +} from "./BaseService.js"; | |
| 4 | 8 | |
| 5 | 9 | // Test implementation of BaseService |
| 6 | 10 | interface TestState { |
| @@ -11,16 +15,16 @@ | ||
| 11 | 15 | |
| 12 | 16 | class TestService extends BaseService<TestState> { |
| 13 | 17 | constructor() { |
| 14 | - super('TestService', { | |
| 18 | + super("TestService", { | |
| 15 | 19 | value: 0, |
| 16 | - message: 'initial' | |
| 20 | + message: "initial", | |
| 17 | 21 | }); |
| 18 | 22 | } |
| 19 | 23 | |
| 20 | 24 | async doInitialize(value: number, message: string): Promise<TestState> { |
| 21 | 25 | return { |
| 22 | 26 | value, |
| 23 | - message | |
| 27 | + message, | |
| 24 | 28 | }; |
| 25 | 29 | } |
| 26 | 30 | |
| @@ -31,175 +35,180 @@ | ||
| 31 | 35 | } |
| 32 | 36 | |
| 33 | 37 | // Test service with dependencies |
| 34 | -class DependentTestService extends TestService implements ServiceWithDependencies { | |
| 38 | +class DependentTestService | |
| 39 | + extends TestService | |
| 40 | + implements ServiceWithDependencies | |
| 41 | +{ | |
| 35 | 42 | getDependencies(): string[] { |
| 36 | - return ['auth', 'config']; | |
| 43 | + return ["auth", "config"]; | |
| 37 | 44 | } |
| 38 | 45 | } |
| 39 | 46 | |
| 40 | 47 | // Test service that throws during initialization |
| 41 | 48 | class FailingTestService extends BaseService<TestState> { |
| 42 | 49 | constructor() { |
| 43 | - super('FailingService', { | |
| 50 | + super("FailingService", { | |
| 44 | 51 | value: 0, |
| 45 | - message: 'initial' | |
| 52 | + message: "initial", | |
| 46 | 53 | }); |
| 47 | 54 | } |
| 48 | 55 | |
| 49 | 56 | async doInitialize(): Promise<TestState> { |
| 50 | - throw new Error('Initialization failed'); | |
| 57 | + throw new Error("Initialization failed"); | |
| 51 | 58 | } |
| 52 | 59 | } |
| 53 | 60 | |
| 54 | -describe('BaseService', () => { | |
| 55 | - describe('Basic Functionality', () => { | |
| 61 | +describe("BaseService", () => { | |
| 62 | + describe("Basic Functionality", () => { | |
| 56 | 63 | let service: TestService; |
| 57 | 64 | |
| 58 | 65 | beforeEach(() => { |
| 59 | 66 | service = new TestService(); |
| 60 | 67 | }); |
| 61 | 68 | |
| 62 | - test('should have correct initial state', () => { | |
| 69 | + test("should have correct initial state", () => { | |
| 63 | 70 | const state = service.getState(); |
| 64 | 71 | expect(state).toEqual({ |
| 65 | 72 | value: 0, |
| 66 | - message: 'initial' | |
| 73 | + message: "initial", | |
| 67 | 74 | }); |
| 68 | 75 | expect(service.isReady()).toBe(false); |
| 69 | 76 | }); |
| 70 | 77 | |
| 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 | + | |
| 74 | 81 | expect(state).toEqual({ |
| 75 | 82 | value: 42, |
| 76 | - message: 'initialized' | |
| 83 | + message: "initialized", | |
| 77 | 84 | }); |
| 78 | 85 | expect(service.isReady()).toBe(true); |
| 79 | 86 | }); |
| 80 | 87 | |
| 81 | - test('should emit initialization events', async () => { | |
| 88 | + test("should emit initialization events", async () => { | |
| 82 | 89 | const initializingListener = vi.fn(); |
| 83 | 90 | 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 | + | |
| 90 | 97 | expect(initializingListener).toHaveBeenCalledTimes(1); |
| 91 | 98 | expect(initializedListener).toHaveBeenCalledTimes(1); |
| 92 | 99 | expect(initializedListener).toHaveBeenCalledWith({ |
| 93 | 100 | value: 42, |
| 94 | - message: 'initialized' | |
| 101 | + message: "initialized", | |
| 95 | 102 | }); |
| 96 | 103 | }); |
| 97 | 104 | |
| 98 | - test('should handle initialization failure', async () => { | |
| 105 | + test("should handle initialization failure", async () => { | |
| 99 | 106 | const failingService = new FailingTestService(); |
| 100 | 107 | 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 | + ); | |
| 105 | 114 | expect(errorListener).toHaveBeenCalledTimes(1); |
| 106 | 115 | expect(failingService.isReady()).toBe(false); |
| 107 | 116 | }); |
| 108 | 117 | }); |
| 109 | 118 | |
| 110 | - describe('State Management', () => { | |
| 119 | + describe("State Management", () => { | |
| 111 | 120 | let service: TestService; |
| 112 | 121 | |
| 113 | 122 | beforeEach(() => { |
| 114 | 123 | service = new TestService(); |
| 115 | 124 | }); |
| 116 | 125 | |
| 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 | + | |
| 120 | 129 | const state1 = service.getState(); |
| 121 | 130 | const state2 = service.getState(); |
| 122 | - | |
| 131 | + | |
| 123 | 132 | expect(state1).toEqual(state2); |
| 124 | 133 | expect(state1).not.toBe(state2); // Different object references |
| 125 | 134 | }); |
| 126 | 135 | |
| 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"); | |
| 129 | 138 | service.updateState({ data: [{ id: 1 }, { id: 2 }] }); |
| 130 | - | |
| 139 | + | |
| 131 | 140 | const state = service.getState(); |
| 132 | 141 | const originalData = state.data; |
| 133 | - | |
| 142 | + | |
| 134 | 143 | // Modify the returned state's nested object |
| 135 | 144 | if (state.data) { |
| 136 | 145 | state.data[0].id = 999; |
| 137 | 146 | } |
| 138 | - | |
| 147 | + | |
| 139 | 148 | // With shallow copy, nested objects are shared |
| 140 | 149 | const newState = service.getState(); |
| 141 | 150 | expect(newState.data).toEqual([{ id: 999 }, { id: 2 }]); |
| 142 | 151 | expect(newState.data).toBe(originalData); // Same reference for nested objects |
| 143 | 152 | }); |
| 144 | 153 | |
| 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 | + | |
| 148 | 157 | const stateChangeListener = vi.fn(); |
| 149 | - service.on('stateChanged', stateChangeListener); | |
| 150 | - | |
| 158 | + service.on("stateChanged", stateChangeListener); | |
| 159 | + | |
| 151 | 160 | service.updateState({ value: 100 }); |
| 152 | - | |
| 161 | + | |
| 153 | 162 | expect(stateChangeListener).toHaveBeenCalledTimes(1); |
| 154 | 163 | 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 | |
| 157 | 166 | ); |
| 158 | 167 | }); |
| 159 | 168 | |
| 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 | + | |
| 163 | 172 | service.updateState({ value: 100 }); |
| 164 | 173 | expect(service.getState()).toEqual({ |
| 165 | 174 | value: 100, |
| 166 | - message: 'test' | |
| 175 | + message: "test", | |
| 167 | 176 | }); |
| 168 | - | |
| 169 | - service.updateState({ message: 'updated' }); | |
| 177 | + | |
| 178 | + service.updateState({ message: "updated" }); | |
| 170 | 179 | expect(service.getState()).toEqual({ |
| 171 | 180 | value: 100, |
| 172 | - message: 'updated' | |
| 181 | + message: "updated", | |
| 173 | 182 | }); |
| 174 | 183 | }); |
| 175 | 184 | }); |
| 176 | 185 | |
| 177 | - describe('Reload Functionality', () => { | |
| 186 | + describe("Reload Functionality", () => { | |
| 178 | 187 | let service: TestService; |
| 179 | 188 | |
| 180 | 189 | beforeEach(() => { |
| 181 | 190 | service = new TestService(); |
| 182 | 191 | }); |
| 183 | 192 | |
| 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"); | |
| 186 | 195 | expect(service.getState()).toEqual({ |
| 187 | 196 | value: 42, |
| 188 | - message: 'first' | |
| 197 | + message: "first", | |
| 189 | 198 | }); |
| 190 | - | |
| 191 | - await service.reload(100, 'second'); | |
| 199 | + | |
| 200 | + await service.reload(100, "second"); | |
| 192 | 201 | expect(service.getState()).toEqual({ |
| 193 | 202 | value: 100, |
| 194 | - message: 'second' | |
| 203 | + message: "second", | |
| 195 | 204 | }); |
| 196 | 205 | expect(service.isReady()).toBe(true); |
| 197 | 206 | }); |
| 198 | 207 | |
| 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"); | |
| 201 | 210 | expect(service.isReady()).toBe(true); |
| 202 | - | |
| 211 | + | |
| 203 | 212 | // Create a promise to check intermediate state |
| 204 | 213 | let wasNotReady = false; |
| 205 | 214 | const originalInit = service.initialize.bind(service); |
| @@ -207,100 +216,104 @@ | ||
| 207 | 216 | wasNotReady = !service.isReady(); |
| 208 | 217 | return originalInit(value, message); |
| 209 | 218 | }) as any; |
| 210 | - | |
| 211 | - await service.reload(100, 'reloaded'); | |
| 212 | - | |
| 219 | + | |
| 220 | + await service.reload(100, "reloaded"); | |
| 221 | + | |
| 213 | 222 | expect(wasNotReady).toBe(true); |
| 214 | 223 | expect(service.isReady()).toBe(true); |
| 215 | 224 | }); |
| 216 | 225 | }); |
| 217 | 226 | |
| 218 | - describe('Cleanup', () => { | |
| 227 | + describe("Cleanup", () => { | |
| 219 | 228 | let service: TestService; |
| 220 | 229 | |
| 221 | 230 | beforeEach(() => { |
| 222 | 231 | service = new TestService(); |
| 223 | 232 | }); |
| 224 | 233 | |
| 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 | + | |
| 228 | 237 | const listener = vi.fn(); |
| 229 | - service.on('test-event', listener); | |
| 230 | - | |
| 238 | + service.on("test-event", listener); | |
| 239 | + | |
| 231 | 240 | await service.cleanup(); |
| 232 | - | |
| 241 | + | |
| 233 | 242 | expect(service.isReady()).toBe(false); |
| 234 | - | |
| 243 | + | |
| 235 | 244 | // Verify listeners are removed |
| 236 | - service.emit('test-event'); | |
| 245 | + service.emit("test-event"); | |
| 237 | 246 | expect(listener).not.toHaveBeenCalled(); |
| 238 | 247 | }); |
| 239 | 248 | }); |
| 240 | 249 | |
| 241 | - describe('ServiceWithDependencies', () => { | |
| 242 | - test('should correctly identify services with dependencies', () => { | |
| 250 | + describe("ServiceWithDependencies", () => { | |
| 251 | + test("should correctly identify services with dependencies", () => { | |
| 243 | 252 | const regularService = new TestService(); |
| 244 | 253 | const dependentService = new DependentTestService(); |
| 245 | - | |
| 254 | + | |
| 246 | 255 | expect(hasDependencies(regularService)).toBe(false); |
| 247 | 256 | expect(hasDependencies(dependentService)).toBe(true); |
| 248 | - | |
| 257 | + | |
| 249 | 258 | if (hasDependencies(dependentService)) { |
| 250 | - expect(dependentService.getDependencies()).toEqual(['auth', 'config']); | |
| 259 | + expect(dependentService.getDependencies()).toEqual(["auth", "config"]); | |
| 251 | 260 | } |
| 252 | 261 | }); |
| 253 | 262 | }); |
| 254 | 263 | |
| 255 | - describe('Shallow Copy Functionality', () => { | |
| 264 | + describe("Shallow Copy Functionality", () => { | |
| 256 | 265 | let service: TestService; |
| 257 | 266 | |
| 258 | 267 | beforeEach(() => { |
| 259 | 268 | service = new TestService(); |
| 260 | 269 | }); |
| 261 | 270 | |
| 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, | |
| 266 | 275 | }); |
| 267 | - | |
| 276 | + | |
| 268 | 277 | const state = service.getState(); |
| 269 | - expect(state.data).toEqual([null, undefined, 'string', 123]); | |
| 278 | + expect(state.data).toEqual([null, undefined, "string", 123]); | |
| 270 | 279 | }); |
| 271 | 280 | |
| 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, | |
| 277 | 286 | }); |
| 278 | - | |
| 287 | + | |
| 279 | 288 | const state = service.getState(); |
| 280 | 289 | expect(state.data?.[0]).toEqual(date); |
| 281 | 290 | expect(state.data?.[0]).toBe(date); // Same instance with shallow copy |
| 282 | 291 | expect(state.data?.[0]).toBeInstanceOf(Date); |
| 283 | 292 | }); |
| 284 | 293 | |
| 285 | - test('should handle complex nested structures', async () => { | |
| 294 | + test("should handle complex nested structures", async () => { | |
| 286 | 295 | const complexData = { |
| 287 | 296 | nested: { |
| 288 | - array: [1, 2, { deep: 'value' }], | |
| 297 | + array: [1, 2, { deep: "value" }], | |
| 289 | 298 | date: new Date(), |
| 290 | 299 | bool: true, |
| 291 | - null: null | |
| 292 | - } | |
| 300 | + null: null, | |
| 301 | + }, | |
| 293 | 302 | }; |
| 294 | - | |
| 295 | - await service.initialize(42, 'test'); | |
| 303 | + | |
| 304 | + await service.initialize(42, "test"); | |
| 296 | 305 | service.updateState({ data: complexData as any }); |
| 297 | - | |
| 306 | + | |
| 298 | 307 | const state = service.getState(); |
| 299 | 308 | expect(state.data).toEqual(complexData); |
| 300 | 309 | expect(state.data).toBe(complexData); // Same reference with shallow copy |
| 301 | - | |
| 310 | + | |
| 302 | 311 | // 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 | + ) { | |
| 304 | 317 | const data = state.data as any; |
| 305 | 318 | expect(data.nested.array).toBe(complexData.nested.array); |
| 306 | 319 | expect(data.nested.array[2]).toBe(complexData.nested.array[2]); |
| @@ -308,79 +321,81 @@ | ||
| 308 | 321 | }); |
| 309 | 322 | }); |
| 310 | 323 | |
| 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", () => { | |
| 313 | 326 | const service = new TestService(); |
| 314 | - | |
| 327 | + | |
| 315 | 328 | // Override setState to throw |
| 316 | 329 | const originalSetState = Object.getOwnPropertyDescriptor( |
| 317 | - Object.getPrototypeOf(service), | |
| 318 | - 'setState' | |
| 330 | + Object.getPrototypeOf(service), | |
| 331 | + "setState", | |
| 319 | 332 | ); |
| 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 | + }, | |
| 325 | 338 | }); |
| 326 | - | |
| 327 | - expect(() => service.updateState({ value: 100 })).toThrow('setState failed'); | |
| 328 | - | |
| 339 | + | |
| 340 | + expect(() => service.updateState({ value: 100 })).toThrow( | |
| 341 | + "setState failed", | |
| 342 | + ); | |
| 343 | + | |
| 329 | 344 | // Restore original |
| 330 | 345 | if (originalSetState) { |
| 331 | 346 | Object.defineProperty( |
| 332 | - Object.getPrototypeOf(service), | |
| 333 | - 'setState', | |
| 334 | - originalSetState | |
| 347 | + Object.getPrototypeOf(service), | |
| 348 | + "setState", | |
| 349 | + originalSetState, | |
| 335 | 350 | ); |
| 336 | 351 | } |
| 337 | 352 | }); |
| 338 | 353 | }); |
| 339 | 354 | |
| 340 | - describe('Event Emitter Integration', () => { | |
| 355 | + describe("Event Emitter Integration", () => { | |
| 341 | 356 | let service: TestService; |
| 342 | 357 | |
| 343 | 358 | beforeEach(() => { |
| 344 | 359 | service = new TestService(); |
| 345 | 360 | }); |
| 346 | 361 | |
| 347 | - test('should support multiple listeners', async () => { | |
| 362 | + test("should support multiple listeners", async () => { | |
| 348 | 363 | const listener1 = vi.fn(); |
| 349 | 364 | 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 | + | |
| 356 | 371 | expect(listener1).toHaveBeenCalledTimes(1); |
| 357 | 372 | expect(listener2).toHaveBeenCalledTimes(1); |
| 358 | 373 | }); |
| 359 | 374 | |
| 360 | - test('should support once listeners', async () => { | |
| 375 | + test("should support once listeners", async () => { | |
| 361 | 376 | 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"); | |
| 366 | 381 | service.updateState({ value: 100 }); |
| 367 | 382 | service.updateState({ value: 200 }); |
| 368 | - | |
| 383 | + | |
| 369 | 384 | expect(listener).toHaveBeenCalledTimes(1); |
| 370 | 385 | }); |
| 371 | 386 | |
| 372 | - test('should allow removing specific listeners', async () => { | |
| 387 | + test("should allow removing specific listeners", async () => { | |
| 373 | 388 | 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 | + | |
| 378 | 393 | service.updateState({ value: 100 }); |
| 379 | 394 | expect(listener).toHaveBeenCalledTimes(1); |
| 380 | - | |
| 381 | - service.off('stateChanged', listener); | |
| 395 | + | |
| 396 | + service.off("stateChanged", listener); | |
| 382 | 397 | service.updateState({ value: 200 }); |
| 383 | 398 | expect(listener).toHaveBeenCalledTimes(1); // Not called again |
| 384 | 399 | }); |
| 385 | 400 | }); |
| 386 | -}); | |
| No newline at the end of the file | ||
| 401 | +}); |
modified extensions/cli/src/services/ConfigService.test.ts +43 −41
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | { accessToken: "token" } as any, |
| 41 | 41 | "/path/to/config.yaml", |
| 42 | 42 | "org-123", |
| 43 | - mockApiClient as any | |
| 43 | + mockApiClient as any, | |
| 44 | 44 | ); |
| 45 | 45 | |
| 46 | 46 | expect(state).toEqual({ |
| @@ -59,7 +59,7 @@ | ||
| 59 | 59 | { accessToken: "token" } as any, |
| 60 | 60 | undefined, |
| 61 | 61 | "org-123", |
| 62 | - mockApiClient as any | |
| 62 | + mockApiClient as any, | |
| 63 | 63 | ); |
| 64 | 64 | |
| 65 | 65 | expect(state).toEqual({ |
| @@ -69,20 +69,20 @@ | ||
| 69 | 69 | }); |
| 70 | 70 | |
| 71 | 71 | test("should inject rules into config", async () => { |
| 72 | - | |
| 73 | 72 | vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ |
| 74 | 73 | config: mockConfig as any, |
| 75 | 74 | source: { type: "cli-flag", path: "/config.yaml" } as any, |
| 76 | 75 | }); |
| 77 | - vi.mocked(args.processRule) | |
| 78 | - .mockImplementation(async (rule) => `Processed: ${rule}`); | |
| 76 | + vi.mocked(args.processRule).mockImplementation( | |
| 77 | + async (rule) => `Processed: ${rule}`, | |
| 78 | + ); | |
| 79 | 79 | |
| 80 | 80 | const state = await service.initialize( |
| 81 | 81 | { accessToken: "token" } as any, |
| 82 | 82 | "/config.yaml", |
| 83 | 83 | "org-123", |
| 84 | 84 | mockApiClient as any, |
| 85 | - ["rule1", "rule2"] | |
| 85 | + ["rule1", "rule2"], | |
| 86 | 86 | ); |
| 87 | 87 | |
| 88 | 88 | expect(state.config).toEqual({ |
| @@ -95,7 +95,6 @@ | ||
| 95 | 95 | |
| 96 | 96 | describe("switchConfig()", () => { |
| 97 | 97 | test("should switch to new configuration", async () => { |
| 98 | - | |
| 99 | 98 | // Initialize first |
| 100 | 99 | vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ |
| 101 | 100 | config: mockConfig as any, |
| @@ -105,7 +104,7 @@ | ||
| 105 | 104 | { accessToken: "token" } as any, |
| 106 | 105 | "/old.yaml", |
| 107 | 106 | "org-123", |
| 108 | - mockApiClient as any | |
| 107 | + mockApiClient as any, | |
| 109 | 108 | ); |
| 110 | 109 | |
| 111 | 110 | // Switch to new config |
| @@ -119,7 +118,7 @@ | ||
| 119 | 118 | "/new.yaml", |
| 120 | 119 | { accessToken: "token" } as any, |
| 121 | 120 | "org-123", |
| 122 | - mockApiClient as any | |
| 121 | + mockApiClient as any, | |
| 123 | 122 | ); |
| 124 | 123 | |
| 125 | 124 | expect(state).toEqual({ |
| @@ -130,31 +129,30 @@ | ||
| 130 | 129 | }); |
| 131 | 130 | |
| 132 | 131 | test("should handle switch config errors", async () => { |
| 133 | - | |
| 134 | 132 | await service.initialize( |
| 135 | 133 | { accessToken: "token" } as any, |
| 136 | 134 | "/old.yaml", |
| 137 | 135 | "org-123", |
| 138 | - mockApiClient as any | |
| 136 | + mockApiClient as any, | |
| 139 | 137 | ); |
| 140 | 138 | |
| 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 | + ); | |
| 143 | 142 | |
| 144 | 143 | await expect( |
| 145 | 144 | service.switchConfig( |
| 146 | 145 | "/bad.yaml", |
| 147 | 146 | { accessToken: "token" } as any, |
| 148 | 147 | "org-123", |
| 149 | - mockApiClient as any | |
| 150 | - ) | |
| 148 | + mockApiClient as any, | |
| 149 | + ), | |
| 151 | 150 | ).rejects.toThrow("Config not found"); |
| 152 | 151 | }); |
| 153 | 152 | }); |
| 154 | 153 | |
| 155 | 154 | describe("reload()", () => { |
| 156 | 155 | test("should reload current configuration", async () => { |
| 157 | - | |
| 158 | 156 | // Initialize with a config |
| 159 | 157 | vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ |
| 160 | 158 | config: mockConfig as any, |
| @@ -164,7 +162,7 @@ | ||
| 164 | 162 | { accessToken: "token" } as any, |
| 165 | 163 | "/config.yaml", |
| 166 | 164 | "org-123", |
| 167 | - mockApiClient as any | |
| 165 | + mockApiClient as any, | |
| 168 | 166 | ); |
| 169 | 167 | |
| 170 | 168 | // Modify mock to return updated config |
| @@ -177,7 +175,7 @@ | ||
| 177 | 175 | const state = await service.reload( |
| 178 | 176 | { accessToken: "token" } as any, |
| 179 | 177 | "org-123", |
| 180 | - mockApiClient as any | |
| 178 | + mockApiClient as any, | |
| 181 | 179 | ); |
| 182 | 180 | |
| 183 | 181 | expect(state).toEqual({ |
| @@ -196,22 +194,21 @@ | ||
| 196 | 194 | { accessToken: "token" } as any, |
| 197 | 195 | undefined, |
| 198 | 196 | "org-123", |
| 199 | - mockApiClient as any | |
| 197 | + mockApiClient as any, | |
| 200 | 198 | ); |
| 201 | 199 | |
| 202 | 200 | await expect( |
| 203 | 201 | service.reload( |
| 204 | 202 | { accessToken: "token" } as any, |
| 205 | 203 | "org-123", |
| 206 | - mockApiClient as any | |
| 207 | - ) | |
| 204 | + mockApiClient as any, | |
| 205 | + ), | |
| 208 | 206 | ).rejects.toThrow("No configuration path available for reload"); |
| 209 | 207 | }); |
| 210 | 208 | }); |
| 211 | 209 | |
| 212 | 210 | describe("updateConfigPath()", () => { |
| 213 | 211 | test("should update config path and reload dependent services", async () => { |
| 214 | - | |
| 215 | 212 | // Initialize service first |
| 216 | 213 | vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ |
| 217 | 214 | config: mockConfig as any, |
| @@ -221,12 +218,14 @@ | ||
| 221 | 218 | { accessToken: "token" } as any, |
| 222 | 219 | "/old.yaml", |
| 223 | 220 | "org-123", |
| 224 | - mockApiClient as any | |
| 221 | + mockApiClient as any, | |
| 225 | 222 | ); |
| 226 | 223 | |
| 227 | 224 | // 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); | |
| 230 | 229 | vi.mocked(serviceContainer.get).mockResolvedValue({ |
| 231 | 230 | apiClient: mockApiClient, |
| 232 | 231 | }); |
| @@ -246,13 +245,13 @@ | ||
| 246 | 245 | }); |
| 247 | 246 | expect(vi.mocked(serviceContainer.set)).toHaveBeenCalledWith( |
| 248 | 247 | SERVICE_NAMES.CONFIG, |
| 249 | - expect.objectContaining({ config: newConfig }) | |
| 248 | + expect.objectContaining({ config: newConfig }), | |
| 250 | 249 | ); |
| 251 | 250 | expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith( |
| 252 | - SERVICE_NAMES.MODEL | |
| 251 | + SERVICE_NAMES.MODEL, | |
| 253 | 252 | ); |
| 254 | 253 | expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith( |
| 255 | - SERVICE_NAMES.MCP | |
| 254 | + SERVICE_NAMES.MCP, | |
| 256 | 255 | ); |
| 257 | 256 | }); |
| 258 | 257 | |
| @@ -261,17 +260,19 @@ | ||
| 261 | 260 | { accessToken: "token" } as any, |
| 262 | 261 | "/old.yaml", |
| 263 | 262 | "org-123", |
| 264 | - mockApiClient as any | |
| 263 | + mockApiClient as any, | |
| 265 | 264 | ); |
| 266 | 265 | |
| 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); | |
| 269 | 270 | vi.mocked(serviceContainer.get).mockResolvedValue({ |
| 270 | 271 | apiClient: null, |
| 271 | 272 | }); |
| 272 | 273 | |
| 273 | 274 | await expect(service.updateConfigPath("/new.yaml")).rejects.toThrow( |
| 274 | - "API client not available" | |
| 275 | + "API client not available", | |
| 275 | 276 | ); |
| 276 | 277 | }); |
| 277 | 278 | }); |
| @@ -284,7 +285,6 @@ | ||
| 284 | 285 | |
| 285 | 286 | describe("Event Emission", () => { |
| 286 | 287 | test("should emit stateChanged when switching config", async () => { |
| 287 | - | |
| 288 | 288 | vi.mocked(configLoader.loadConfiguration).mockResolvedValue({ |
| 289 | 289 | config: mockConfig as any, |
| 290 | 290 | source: { type: "cli-flag", path: "/old.yaml" } as any, |
| @@ -293,7 +293,7 @@ | ||
| 293 | 293 | { accessToken: "token" } as any, |
| 294 | 294 | "/old.yaml", |
| 295 | 295 | "org-123", |
| 296 | - mockApiClient as any | |
| 296 | + mockApiClient as any, | |
| 297 | 297 | ); |
| 298 | 298 | |
| 299 | 299 | const listener = vi.fn(); |
| @@ -309,22 +309,24 @@ | ||
| 309 | 309 | "/new.yaml", |
| 310 | 310 | { accessToken: "token" } as any, |
| 311 | 311 | "org-123", |
| 312 | - mockApiClient as any | |
| 312 | + mockApiClient as any, | |
| 313 | 313 | ); |
| 314 | 314 | |
| 315 | 315 | expect(listener).toHaveBeenCalledWith( |
| 316 | 316 | 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 | + }), | |
| 318 | 321 | ); |
| 319 | 322 | }); |
| 320 | 323 | |
| 321 | 324 | test("should emit error on switch failure", async () => { |
| 322 | - | |
| 323 | 325 | await service.initialize( |
| 324 | 326 | { accessToken: "token" } as any, |
| 325 | 327 | "/old.yaml", |
| 326 | 328 | "org-123", |
| 327 | - mockApiClient as any | |
| 329 | + mockApiClient as any, | |
| 328 | 330 | ); |
| 329 | 331 | |
| 330 | 332 | const errorListener = vi.fn(); |
| @@ -338,8 +340,8 @@ | ||
| 338 | 340 | "/bad.yaml", |
| 339 | 341 | { accessToken: "token" } as any, |
| 340 | 342 | "org-123", |
| 341 | - mockApiClient as any | |
| 342 | - ) | |
| 343 | + mockApiClient as any, | |
| 344 | + ), | |
| 343 | 345 | ).rejects.toThrow(); |
| 344 | 346 | expect(errorListener).toHaveBeenCalledWith(error); |
| 345 | 347 | }); |
| @@ -367,4 +369,4 @@ | ||
| 367 | 369 | expect(service.updateConfigPath.length).toBe(1); |
| 368 | 370 | }); |
| 369 | 371 | }); |
| 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"; | |
| 3 | 3 | |
| 4 | -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | |
| 4 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 5 | 5 | |
| 6 | -import { FileIndexService } from './FileIndexService.js'; | |
| 6 | +import { FileIndexService } from "./FileIndexService.js"; | |
| 7 | 7 | |
| 8 | 8 | // Mock the file watcher |
| 9 | -vi.mock('../util/fileWatcher.js', () => ({ | |
| 9 | +vi.mock("../util/fileWatcher.js", () => ({ | |
| 10 | 10 | getFileWatcher: () => ({ |
| 11 | 11 | startWatching: vi.fn(), |
| 12 | 12 | stopWatching: vi.fn(), |
| @@ -15,18 +15,18 @@ | ||
| 15 | 15 | })); |
| 16 | 16 | |
| 17 | 17 | // Mock git detection |
| 18 | -vi.mock('../util/git.js', () => ({ | |
| 18 | +vi.mock("../util/git.js", () => ({ | |
| 19 | 19 | isGitRepo: vi.fn(() => false), |
| 20 | 20 | })); |
| 21 | 21 | |
| 22 | -describe('FileIndexService', () => { | |
| 22 | +describe("FileIndexService", () => { | |
| 23 | 23 | let service: FileIndexService; |
| 24 | 24 | let tempDir: string; |
| 25 | 25 | let originalCwd: string; |
| 26 | 26 | |
| 27 | 27 | beforeEach(() => { |
| 28 | 28 | originalCwd = process.cwd(); |
| 29 | - tempDir = fs.mkdtempSync(path.join(process.cwd(), 'test-fileindex-')); | |
| 29 | + tempDir = fs.mkdtempSync(path.join(process.cwd(), "test-fileindex-")); | |
| 30 | 30 | process.chdir(tempDir); |
| 31 | 31 | |
| 32 | 32 | service = new FileIndexService(); |
| @@ -40,11 +40,11 @@ | ||
| 40 | 40 | } |
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | - it('should initialize and index files', async () => { | |
| 43 | + it("should initialize and index files", async () => { | |
| 44 | 44 | // 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"); | |
| 48 | 48 | |
| 49 | 49 | // Initialize the service |
| 50 | 50 | await service.initialize(); |
| @@ -52,99 +52,102 @@ | ||
| 52 | 52 | // Should have indexed the files |
| 53 | 53 | const files = service.getFiles(); |
| 54 | 54 | 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"); | |
| 60 | 60 | }); |
| 61 | 61 | |
| 62 | - it('should filter files correctly', async () => { | |
| 62 | + it("should filter files correctly", async () => { | |
| 63 | 63 | // 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; }"); | |
| 67 | 67 | |
| 68 | 68 | await service.initialize(); |
| 69 | 69 | |
| 70 | 70 | // 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); | |
| 75 | 75 | |
| 76 | 76 | // 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); | |
| 80 | 80 | }); |
| 81 | 81 | |
| 82 | - it('should handle empty directory', async () => { | |
| 82 | + it("should handle empty directory", async () => { | |
| 83 | 83 | await service.initialize(); |
| 84 | - | |
| 84 | + | |
| 85 | 85 | const files = service.getFiles(); |
| 86 | 86 | expect(files).toEqual([]); |
| 87 | 87 | expect(service.isIndexing()).toBe(false); |
| 88 | 88 | expect(service.getError()).toBeNull(); |
| 89 | 89 | }); |
| 90 | 90 | |
| 91 | - it('should ignore specified patterns', async () => { | |
| 91 | + it("should ignore specified patterns", async () => { | |
| 92 | 92 | // 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")'); | |
| 98 | 101 | |
| 99 | 102 | // Create files that should be included |
| 100 | - fs.writeFileSync('src.js', 'console.log("src")'); | |
| 103 | + fs.writeFileSync("src.js", 'console.log("src")'); | |
| 101 | 104 | |
| 102 | 105 | await service.initialize(); |
| 103 | 106 | |
| 104 | 107 | const files = service.getFiles(); |
| 105 | - const filePaths = files.map(f => f.path); | |
| 106 | - | |
| 108 | + const filePaths = files.map((f) => f.path); | |
| 109 | + | |
| 107 | 110 | // Should include src.js |
| 108 | - expect(filePaths).toContain('src.js'); | |
| 109 | - | |
| 111 | + expect(filePaths).toContain("src.js"); | |
| 112 | + | |
| 110 | 113 | // 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); | |
| 113 | 116 | }); |
| 114 | 117 | |
| 115 | - it('should sort files correctly with no filter', async () => { | |
| 118 | + it("should sort files correctly with no filter", async () => { | |
| 116 | 119 | // 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")'); | |
| 120 | 123 | |
| 121 | 124 | await service.initialize(); |
| 122 | 125 | |
| 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"); | |
| 127 | 130 | }); |
| 128 | 131 | |
| 129 | - it('should include files with matching names and paths', async () => { | |
| 132 | + it("should include files with matching names and paths", async () => { | |
| 130 | 133 | // 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"); | |
| 134 | 137 | |
| 135 | 138 | await service.initialize(); |
| 136 | 139 | |
| 137 | - const filtered = service.filterFiles('test'); | |
| 138 | - | |
| 140 | + const filtered = service.filterFiles("test"); | |
| 141 | + | |
| 139 | 142 | // Should include both files that match the filter |
| 140 | 143 | 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"); | |
| 143 | 146 | // 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")); | |
| 145 | 148 | }); |
| 146 | 149 | |
| 147 | - it('should respect limit parameter', async () => { | |
| 150 | + it("should respect limit parameter", async () => { | |
| 148 | 151 | // Create many files |
| 149 | 152 | for (let i = 0; i < 20; i++) { |
| 150 | 153 | fs.writeFileSync(`file${i}.js`, `console.log("file${i}")`); |
| @@ -152,22 +155,22 @@ | ||
| 152 | 155 | |
| 153 | 156 | await service.initialize(); |
| 154 | 157 | |
| 155 | - const files = service.filterFiles('', 5); | |
| 158 | + const files = service.filterFiles("", 5); | |
| 156 | 159 | expect(files.length).toBe(5); |
| 157 | 160 | }); |
| 158 | 161 | |
| 159 | - it('should handle refresh correctly', async () => { | |
| 162 | + it("should handle refresh correctly", async () => { | |
| 160 | 163 | // Create initial file |
| 161 | - fs.writeFileSync('initial.js', 'console.log("initial")'); | |
| 162 | - | |
| 164 | + fs.writeFileSync("initial.js", 'console.log("initial")'); | |
| 165 | + | |
| 163 | 166 | await service.initialize(); |
| 164 | 167 | expect(service.getFiles().length).toBe(1); |
| 165 | 168 | |
| 166 | 169 | // Add another file |
| 167 | - fs.writeFileSync('added.js', 'console.log("added")'); | |
| 168 | - | |
| 170 | + fs.writeFileSync("added.js", 'console.log("added")'); | |
| 171 | + | |
| 169 | 172 | // Refresh should pick up the new file |
| 170 | 173 | await service.refreshIndex(); |
| 171 | 174 | expect(service.getFiles().length).toBe(2); |
| 172 | 175 | }); |
| 173 | -}); | |
| No newline at the end of the file | ||
| 176 | +}); |
modified extensions/cli/src/services/MCPService.test.ts +10 −7
| @@ -43,7 +43,7 @@ | ||
| 43 | 43 | |
| 44 | 44 | afterEach(async () => { |
| 45 | 45 | vi.clearAllMocks(); |
| 46 | - await mcpService.cleanup() | |
| 46 | + await mcpService.cleanup(); | |
| 47 | 47 | }); |
| 48 | 48 | |
| 49 | 49 | describe("initialization", () => { |
| @@ -86,7 +86,7 @@ | ||
| 86 | 86 | const firstStatus = mcpService.getOverallStatus(); |
| 87 | 87 | expect(firstStatus.status).toBe("connected"); |
| 88 | 88 | expect(firstStatus.hasWarnings).toBe(false); |
| 89 | - await mcpService.cleanup() | |
| 89 | + await mcpService.cleanup(); | |
| 90 | 90 | const secondStatus = mcpService.getOverallStatus(); |
| 91 | 91 | expect(secondStatus.status).toBe("idle"); |
| 92 | 92 | }); |
| @@ -107,14 +107,13 @@ | ||
| 107 | 107 | |
| 108 | 108 | it("should handle server not found error", async () => { |
| 109 | 109 | await expect(mcpService.restartServer("nonexistent")).rejects.toThrow( |
| 110 | - "Server nonexistent not found in configuration" | |
| 110 | + "Server nonexistent not found in configuration", | |
| 111 | 111 | ); |
| 112 | 112 | }); |
| 113 | 113 | |
| 114 | 114 | it("should handle stop individual server", async () => { |
| 115 | 115 | await expect(mcpService.stopServer("test-server")).resolves.not.toThrow(); |
| 116 | 116 | }); |
| 117 | - | |
| 118 | 117 | }); |
| 119 | 118 | |
| 120 | 119 | describe("tools and prompts", () => { |
| @@ -129,7 +128,7 @@ | ||
| 129 | 128 | |
| 130 | 129 | it("should throw error for unknown tool", async () => { |
| 131 | 130 | await expect(mcpService.runTool("unknown-tool", {})).rejects.toThrow( |
| 132 | - "Tool unknown-tool not found" | |
| 131 | + "Tool unknown-tool not found", | |
| 133 | 132 | ); |
| 134 | 133 | }); |
| 135 | 134 | }); |
| @@ -137,10 +136,14 @@ | ||
| 137 | 136 | describe("shutdown", () => { |
| 138 | 137 | it("should handle shutdown gracefully", async () => { |
| 139 | 138 | await mcpService.initialize(mockAssistant); |
| 140 | - await mcpService.cleanup() | |
| 139 | + await mcpService.cleanup(); | |
| 141 | 140 | |
| 142 | 141 | 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); | |
| 144 | 147 | }); |
| 145 | 148 | |
| 146 | 149 | 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"; | |
| 2 | 2 | |
| 3 | -import { ModeService } from './ModeService.js'; | |
| 3 | +import { ModeService } from "./ModeService.js"; | |
| 4 | 4 | |
| 5 | -describe('ModeService', () => { | |
| 5 | +describe("ModeService", () => { | |
| 6 | 6 | let modeService: ModeService; |
| 7 | 7 | |
| 8 | 8 | beforeEach(() => { |
| @@ -16,166 +16,166 @@ | ||
| 16 | 16 | (ModeService as any).instance = undefined; |
| 17 | 17 | }); |
| 18 | 18 | |
| 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 () => { | |
| 21 | 21 | const state = await modeService.initialize({}); |
| 22 | - | |
| 22 | + | |
| 23 | 23 | expect(state).toEqual({ |
| 24 | - mode: 'normal', | |
| 25 | - toolPermissionService: expect.any(Object) | |
| 24 | + mode: "normal", | |
| 25 | + toolPermissionService: expect.any(Object), | |
| 26 | 26 | }); |
| 27 | - expect(modeService.getCurrentMode()).toBe('normal'); | |
| 27 | + expect(modeService.getCurrentMode()).toBe("normal"); | |
| 28 | 28 | }); |
| 29 | 29 | |
| 30 | - test('should convert readonly flag to plan mode', async () => { | |
| 30 | + test("should convert readonly flag to plan mode", async () => { | |
| 31 | 31 | 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"); | |
| 35 | 35 | }); |
| 36 | 36 | |
| 37 | - test('should convert auto flag to auto mode', async () => { | |
| 37 | + test("should convert auto flag to auto mode", async () => { | |
| 38 | 38 | 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"], | |
| 48 | 48 | }); |
| 49 | - | |
| 49 | + | |
| 50 | 50 | const toolPermissionService = state.toolPermissionService; |
| 51 | 51 | expect(toolPermissionService).toBeDefined(); |
| 52 | 52 | expect(toolPermissionService.getState()).toBeDefined(); |
| 53 | - expect(toolPermissionService.getCurrentMode()).toBe('normal'); | |
| 53 | + expect(toolPermissionService.getCurrentMode()).toBe("normal"); | |
| 54 | 54 | }); |
| 55 | 55 | }); |
| 56 | 56 | |
| 57 | - describe('switchMode()', () => { | |
| 57 | + describe("switchMode()", () => { | |
| 58 | 58 | beforeEach(async () => { |
| 59 | 59 | await modeService.initialize({}); |
| 60 | 60 | }); |
| 61 | 61 | |
| 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"); | |
| 69 | 69 | }); |
| 70 | 70 | |
| 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"); | |
| 79 | 79 | }); |
| 80 | 80 | |
| 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"); | |
| 87 | 87 | }); |
| 88 | 88 | |
| 89 | - test('should update tool permission service when switching modes', () => { | |
| 89 | + test("should update tool permission service when switching modes", () => { | |
| 90 | 90 | const toolPermissionService = modeService.getToolPermissionService(); |
| 91 | 91 | const initialState = toolPermissionService.getState(); |
| 92 | - | |
| 93 | - modeService.switchMode('auto'); | |
| 92 | + | |
| 93 | + modeService.switchMode("auto"); | |
| 94 | 94 | const newState = toolPermissionService.getState(); |
| 95 | - | |
| 96 | - expect(newState.currentMode).toBe('auto'); | |
| 95 | + | |
| 96 | + expect(newState.currentMode).toBe("auto"); | |
| 97 | 97 | expect(newState.permissions.policies.length).toBeGreaterThan(0); |
| 98 | 98 | expect(newState.permissions.policies[0]).toEqual({ |
| 99 | - tool: '*', | |
| 100 | - permission: 'allow' | |
| 99 | + tool: "*", | |
| 100 | + permission: "allow", | |
| 101 | 101 | }); |
| 102 | 102 | }); |
| 103 | 103 | |
| 104 | - test('should handle multiple mode switches correctly', () => { | |
| 104 | + test("should handle multiple mode switches correctly", () => { | |
| 105 | 105 | // Start in normal |
| 106 | - expect(modeService.getCurrentMode()).toBe('normal'); | |
| 107 | - | |
| 106 | + expect(modeService.getCurrentMode()).toBe("normal"); | |
| 107 | + | |
| 108 | 108 | // Switch to plan |
| 109 | - modeService.switchMode('plan'); | |
| 109 | + modeService.switchMode("plan"); | |
| 110 | 110 | const planState = modeService.getToolPermissionService().getState(); |
| 111 | 111 | expect(planState.permissions.policies).toContainEqual({ |
| 112 | - tool: 'Write', | |
| 113 | - permission: 'exclude' | |
| 112 | + tool: "Write", | |
| 113 | + permission: "exclude", | |
| 114 | 114 | }); |
| 115 | - | |
| 115 | + | |
| 116 | 116 | // Switch to auto |
| 117 | - modeService.switchMode('auto'); | |
| 117 | + modeService.switchMode("auto"); | |
| 118 | 118 | const autoState = modeService.getToolPermissionService().getState(); |
| 119 | 119 | expect(autoState.permissions.policies).toHaveLength(1); |
| 120 | 120 | expect(autoState.permissions.policies[0]).toEqual({ |
| 121 | - tool: '*', | |
| 122 | - permission: 'allow' | |
| 121 | + tool: "*", | |
| 122 | + permission: "allow", | |
| 123 | 123 | }); |
| 124 | - | |
| 124 | + | |
| 125 | 125 | // Back to normal |
| 126 | - modeService.switchMode('normal'); | |
| 126 | + modeService.switchMode("normal"); | |
| 127 | 127 | const normalState = modeService.getToolPermissionService().getState(); |
| 128 | - expect(normalState.currentMode).toBe('normal'); | |
| 128 | + expect(normalState.currentMode).toBe("normal"); | |
| 129 | 129 | }); |
| 130 | 130 | }); |
| 131 | 131 | |
| 132 | - describe('getAvailableModes()', () => { | |
| 132 | + describe("getAvailableModes()", () => { | |
| 133 | 133 | beforeEach(async () => { |
| 134 | 134 | await modeService.initialize({}); |
| 135 | 135 | }); |
| 136 | 136 | |
| 137 | - test('should return all available modes with descriptions', () => { | |
| 137 | + test("should return all available modes with descriptions", () => { | |
| 138 | 138 | const modes = modeService.getAvailableModes(); |
| 139 | 139 | 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 | + | |
| 146 | 146 | // Check that all modes have descriptions |
| 147 | - modes.forEach(mode => { | |
| 147 | + modes.forEach((mode) => { | |
| 148 | 148 | expect(mode.description).toBeDefined(); |
| 149 | 149 | expect(mode.description.length).toBeGreaterThan(0); |
| 150 | 150 | }); |
| 151 | 151 | }); |
| 152 | 152 | }); |
| 153 | 153 | |
| 154 | - describe('Singleton Behavior', () => { | |
| 155 | - test('should return the same instance', () => { | |
| 154 | + describe("Singleton Behavior", () => { | |
| 155 | + test("should return the same instance", () => { | |
| 156 | 156 | const instance1 = ModeService.getInstance(); |
| 157 | 157 | const instance2 = ModeService.getInstance(); |
| 158 | 158 | expect(instance1).toBe(instance2); |
| 159 | 159 | }); |
| 160 | 160 | |
| 161 | - test('should maintain state across getInstance calls', async () => { | |
| 161 | + test("should maintain state across getInstance calls", async () => { | |
| 162 | 162 | const instance1 = ModeService.getInstance(); |
| 163 | 163 | await instance1.initialize({}); |
| 164 | - instance1.switchMode('plan'); | |
| 165 | - | |
| 164 | + instance1.switchMode("plan"); | |
| 165 | + | |
| 166 | 166 | const instance2 = ModeService.getInstance(); |
| 167 | - expect(instance2.getCurrentMode()).toBe('plan'); | |
| 167 | + expect(instance2.getCurrentMode()).toBe("plan"); | |
| 168 | 168 | }); |
| 169 | 169 | }); |
| 170 | 170 | |
| 171 | - describe('isReady()', () => { | |
| 172 | - test('should always return true for ModeService', () => { | |
| 171 | + describe("isReady()", () => { | |
| 172 | + test("should always return true for ModeService", () => { | |
| 173 | 173 | // ModeService is always ready since it's a singleton |
| 174 | 174 | expect(modeService.isReady()).toBe(true); |
| 175 | 175 | }); |
| 176 | 176 | }); |
| 177 | 177 | |
| 178 | - describe('Event Emission', () => { | |
| 178 | + describe("Event Emission", () => { | |
| 179 | 179 | let modeChangeListener: ReturnType<typeof vi.fn>; |
| 180 | 180 | let stateChangeListener: ReturnType<typeof vi.fn>; |
| 181 | 181 | |
| @@ -183,77 +183,77 @@ | ||
| 183 | 183 | await modeService.initialize({}); |
| 184 | 184 | modeChangeListener = vi.fn(); |
| 185 | 185 | stateChangeListener = vi.fn(); |
| 186 | - modeService.on('modeChanged', modeChangeListener); | |
| 187 | - modeService.on('stateChanged', stateChangeListener); | |
| 186 | + modeService.on("modeChanged", modeChangeListener); | |
| 187 | + modeService.on("stateChanged", stateChangeListener); | |
| 188 | 188 | }); |
| 189 | 189 | |
| 190 | 190 | afterEach(() => { |
| 191 | - modeService.off('modeChanged', modeChangeListener); | |
| 192 | - modeService.off('stateChanged', stateChangeListener); | |
| 191 | + modeService.off("modeChanged", modeChangeListener); | |
| 192 | + modeService.off("stateChanged", stateChangeListener); | |
| 193 | 193 | }); |
| 194 | 194 | |
| 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"); | |
| 199 | 199 | expect(modeChangeListener).toHaveBeenCalledTimes(1); |
| 200 | 200 | }); |
| 201 | 201 | |
| 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 | + | |
| 205 | 205 | expect(stateChangeListener).toHaveBeenCalledWith( |
| 206 | - expect.objectContaining({ mode: 'plan' }), | |
| 207 | - expect.objectContaining({ mode: 'normal' }) | |
| 206 | + expect.objectContaining({ mode: "plan" }), | |
| 207 | + expect.objectContaining({ mode: "normal" }), | |
| 208 | 208 | ); |
| 209 | 209 | }); |
| 210 | 210 | |
| 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"); | |
| 213 | 213 | modeChangeListener.mockClear(); |
| 214 | 214 | 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"); | |
| 219 | 219 | expect(modeChangeListener).toHaveBeenCalledTimes(1); |
| 220 | 220 | expect(stateChangeListener).toHaveBeenCalledTimes(1); |
| 221 | 221 | }); |
| 222 | 222 | |
| 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"); | |
| 225 | 225 | modeChangeListener.mockClear(); |
| 226 | 226 | stateChangeListener.mockClear(); |
| 227 | - | |
| 228 | - modeService.switchMode('plan'); | |
| 229 | - | |
| 227 | + | |
| 228 | + modeService.switchMode("plan"); | |
| 229 | + | |
| 230 | 230 | expect(modeChangeListener).not.toHaveBeenCalled(); |
| 231 | 231 | // stateChanged might still be called due to setState, but modeChanged should not |
| 232 | 232 | }); |
| 233 | 233 | }); |
| 234 | 234 | |
| 235 | - describe('Integration with ToolPermissionService', () => { | |
| 235 | + describe("Integration with ToolPermissionService", () => { | |
| 236 | 236 | beforeEach(async () => { |
| 237 | 237 | await modeService.initialize({ |
| 238 | - allow: ['Read'], | |
| 239 | - exclude: ['dangerous_tool'] | |
| 238 | + allow: ["Read"], | |
| 239 | + exclude: ["dangerous_tool"], | |
| 240 | 240 | }); |
| 241 | 241 | }); |
| 242 | 242 | |
| 243 | - test('should pass initialization args to ToolPermissionService', () => { | |
| 243 | + test("should pass initialization args to ToolPermissionService", () => { | |
| 244 | 244 | const toolService = modeService.getToolPermissionService(); |
| 245 | 245 | const state = toolService.getState(); |
| 246 | - | |
| 246 | + | |
| 247 | 247 | // The state should have processed the allow/exclude rules |
| 248 | 248 | expect(state.permissions.policies).toBeDefined(); |
| 249 | - expect(state.currentMode).toBe('normal'); | |
| 249 | + expect(state.currentMode).toBe("normal"); | |
| 250 | 250 | }); |
| 251 | 251 | |
| 252 | - test('should maintain ToolPermissionService reference', () => { | |
| 252 | + test("should maintain ToolPermissionService reference", () => { | |
| 253 | 253 | const toolService1 = modeService.getToolPermissionService(); |
| 254 | 254 | const toolService2 = modeService.getToolPermissionService(); |
| 255 | - | |
| 255 | + | |
| 256 | 256 | expect(toolService1).toBe(toolService2); |
| 257 | 257 | }); |
| 258 | 258 | }); |
| 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"; | |
| 4 | 4 | |
| 5 | 5 | // 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"); | |
| 9 | 9 | |
| 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"; | |
| 13 | 13 | |
| 14 | -import { ModelService } from './ModelService.js'; | |
| 14 | +import { ModelService } from "./ModelService.js"; | |
| 15 | 15 | |
| 16 | -describe('ModelService', () => { | |
| 16 | +describe("ModelService", () => { | |
| 17 | 17 | let service: ModelService; |
| 18 | 18 | let mockAssistant: AssistantUnrolled; |
| 19 | 19 | let mockAuthConfig: AuthConfig; |
| @@ -24,69 +24,77 @@ | ||
| 24 | 24 | service = new ModelService(); |
| 25 | 25 | |
| 26 | 26 | mockAssistant = { |
| 27 | - name: 'test-assistant', | |
| 28 | - version: '1.0.0', | |
| 27 | + name: "test-assistant", | |
| 28 | + version: "1.0.0", | |
| 29 | 29 | models: [ |
| 30 | 30 | { |
| 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"], | |
| 36 | 36 | } as ModelConfig, |
| 37 | 37 | { |
| 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"], | |
| 43 | 43 | } as ModelConfig, |
| 44 | 44 | { |
| 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"], | |
| 50 | 50 | } as ModelConfig, |
| 51 | 51 | ], |
| 52 | 52 | } as AssistantUnrolled; |
| 53 | 53 | |
| 54 | 54 | 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", | |
| 60 | 60 | expiresAt: Date.now() + 3600000, // 1 hour from now |
| 61 | 61 | }; |
| 62 | 62 | }); |
| 63 | 63 | |
| 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 | + ]); | |
| 67 | 70 | vi.mocked(workos.getModelName).mockReturnValue(null); |
| 68 | 71 | |
| 69 | 72 | const state = await service.initialize(mockAssistant, mockAuthConfig); |
| 70 | 73 | |
| 71 | 74 | expect(state).toEqual({ |
| 72 | 75 | llmApi: mockLlmApi, |
| 73 | - model: mockAssistant.models![0] | |
| 76 | + model: mockAssistant.models![0], | |
| 74 | 77 | }); |
| 75 | 78 | }); |
| 76 | 79 | |
| 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 | + ); | |
| 80 | 85 | |
| 81 | 86 | const state = await service.initialize(mockAssistant, mockAuthConfig); |
| 82 | 87 | |
| 83 | - expect(state.model?.name).toBe('Claude 3'); | |
| 88 | + expect(state.model?.name).toBe("Claude 3"); | |
| 84 | 89 | expect(state.llmApi).toStrictEqual(mockLlmApi); |
| 85 | 90 | }); |
| 86 | 91 | |
| 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 | + ]); | |
| 90 | 98 | |
| 91 | 99 | const state = await service.initialize(mockAssistant, mockAuthConfig); |
| 92 | 100 | |
| @@ -94,10 +102,13 @@ | ||
| 94 | 102 | }); |
| 95 | 103 | }); |
| 96 | 104 | |
| 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 () => { | |
| 99 | 107 | // 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 | + ]); | |
| 101 | 112 | await service.initialize(mockAssistant, mockAuthConfig); |
| 102 | 113 | |
| 103 | 114 | // Update with new assistant |
| @@ -105,124 +116,152 @@ | ||
| 105 | 116 | ...mockAssistant, |
| 106 | 117 | models: [ |
| 107 | 118 | { |
| 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"], | |
| 113 | 124 | } as ModelConfig, |
| 114 | 125 | ], |
| 115 | 126 | }; |
| 116 | 127 | 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 | + ]); | |
| 118 | 132 | |
| 119 | 133 | const state = await service.update(newAssistant, mockAuthConfig); |
| 120 | 134 | |
| 121 | 135 | expect(state).toEqual({ |
| 122 | 136 | llmApi: newLlmApi, |
| 123 | - model: newAssistant.models![0] | |
| 137 | + model: newAssistant.models![0], | |
| 124 | 138 | }); |
| 125 | 139 | }); |
| 126 | 140 | }); |
| 127 | 141 | |
| 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 | + ]); | |
| 131 | 148 | await service.initialize(mockAssistant, mockAuthConfig); |
| 132 | 149 | |
| 133 | 150 | 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 | + ); | |
| 135 | 154 | |
| 136 | 155 | const state = await service.switchModel(1); |
| 137 | 156 | |
| 138 | 157 | expect(state).toEqual({ |
| 139 | 158 | llmApi: newLlmApi, |
| 140 | - model: mockAssistant.models![1] | |
| 159 | + model: mockAssistant.models![1], | |
| 141 | 160 | }); |
| 142 | 161 | expect(service.getState()).toEqual(state); |
| 143 | 162 | }); |
| 144 | 163 | |
| 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 | + ]); | |
| 147 | 169 | await service.initialize(mockAssistant, mockAuthConfig); |
| 148 | 170 | |
| 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 | + ); | |
| 151 | 177 | }); |
| 152 | 178 | |
| 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 | + ); | |
| 155 | 183 | }); |
| 156 | 184 | |
| 157 | - test('should handle continue-proxy provider specially', async () => { | |
| 185 | + test("should handle continue-proxy provider specially", async () => { | |
| 158 | 186 | 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"], | |
| 164 | 192 | } as ModelConfig; |
| 165 | 193 | |
| 166 | 194 | 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 | + ]); | |
| 168 | 199 | await service.initialize(mockAssistant, mockAuthConfig); |
| 169 | 200 | |
| 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 | + ); | |
| 173 | 206 | |
| 174 | 207 | await service.switchModel(0); |
| 175 | 208 | |
| 176 | 209 | 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", | |
| 180 | 213 | env: { |
| 181 | - apiKeyLocation: 'env.PROXY_KEY', | |
| 182 | - orgScopeId: 'org-123', | |
| 214 | + apiKeyLocation: "env.PROXY_KEY", | |
| 215 | + orgScopeId: "org-123", | |
| 183 | 216 | proxyUrl: undefined, |
| 184 | 217 | }, |
| 185 | 218 | }); |
| 186 | 219 | }); |
| 187 | 220 | }); |
| 188 | 221 | |
| 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 | + ]); | |
| 192 | 228 | await service.initialize(mockAssistant, mockAuthConfig); |
| 193 | 229 | |
| 194 | 230 | const models = service.getAvailableChatModels(); |
| 195 | 231 | |
| 196 | 232 | expect(models).toHaveLength(2); |
| 197 | 233 | expect(models[0]).toEqual({ |
| 198 | - provider: 'openai', | |
| 199 | - name: 'GPT-4', | |
| 234 | + provider: "openai", | |
| 235 | + name: "GPT-4", | |
| 200 | 236 | index: 0, |
| 201 | 237 | }); |
| 202 | 238 | expect(models[1]).toEqual({ |
| 203 | - provider: 'anthropic', | |
| 204 | - name: 'Claude 3', | |
| 239 | + provider: "anthropic", | |
| 240 | + name: "Claude 3", | |
| 205 | 241 | index: 1, |
| 206 | 242 | }); |
| 207 | 243 | }); |
| 208 | 244 | |
| 209 | - test('should include models with undefined roles', async () => { | |
| 245 | + test("should include models with undefined roles", async () => { | |
| 210 | 246 | // Add a model with undefined roles to the assistant |
| 211 | 247 | const assistantWithUndefinedRoles = { |
| 212 | 248 | ...mockAssistant, |
| 213 | 249 | models: [ |
| 214 | 250 | ...mockAssistant.models!, |
| 215 | 251 | { |
| 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", | |
| 220 | 256 | // roles is undefined |
| 221 | 257 | } as ModelConfig, |
| 222 | 258 | ], |
| 223 | 259 | }; |
| 224 | 260 | |
| 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 | + ]); | |
| 226 | 265 | await service.initialize(assistantWithUndefinedRoles, mockAuthConfig); |
| 227 | 266 | |
| 228 | 267 | const models = service.getAvailableChatModels(); |
| @@ -230,126 +269,156 @@ | ||
| 230 | 269 | // Should include the two chat models and the model with undefined roles |
| 231 | 270 | expect(models).toHaveLength(3); |
| 232 | 271 | expect(models[2]).toEqual({ |
| 233 | - provider: 'local', | |
| 234 | - name: 'Llama 2', | |
| 272 | + provider: "local", | |
| 273 | + name: "Llama 2", | |
| 235 | 274 | index: 2, |
| 236 | 275 | }); |
| 237 | 276 | }); |
| 238 | 277 | }); |
| 239 | 278 | |
| 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 | + ]); | |
| 243 | 285 | await service.initialize(mockAssistant, mockAuthConfig); |
| 244 | 286 | |
| 245 | 287 | expect(service.getCurrentModelIndex()).toBe(0); |
| 246 | 288 | |
| 247 | - vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any); | |
| 289 | + vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue( | |
| 290 | + mockLlmApi as any, | |
| 291 | + ); | |
| 248 | 292 | await service.switchModel(1); |
| 249 | 293 | expect(service.getCurrentModelIndex()).toBe(1); |
| 250 | 294 | }); |
| 251 | 295 | |
| 252 | - test('should return -1 when no model is set', () => { | |
| 296 | + test("should return -1 when no model is set", () => { | |
| 253 | 297 | expect(service.getCurrentModelIndex()).toBe(-1); |
| 254 | 298 | }); |
| 255 | 299 | }); |
| 256 | 300 | |
| 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 | + ]); | |
| 260 | 307 | await service.initialize(mockAssistant, mockAuthConfig); |
| 261 | 308 | |
| 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); | |
| 265 | 312 | }); |
| 266 | 313 | |
| 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 | + ]); | |
| 269 | 319 | await service.initialize(mockAssistant, mockAuthConfig); |
| 270 | 320 | |
| 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); | |
| 273 | 323 | }); |
| 274 | 324 | }); |
| 275 | 325 | |
| 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 | + ]); | |
| 279 | 332 | await service.initialize(mockAssistant, mockAuthConfig); |
| 280 | 333 | |
| 281 | 334 | expect(service.getModelInfo()).toEqual({ |
| 282 | - provider: 'openai', | |
| 283 | - name: 'GPT-4' | |
| 335 | + provider: "openai", | |
| 336 | + name: "GPT-4", | |
| 284 | 337 | }); |
| 285 | 338 | }); |
| 286 | 339 | |
| 287 | - test('should return null when no model set', () => { | |
| 340 | + test("should return null when no model set", () => { | |
| 288 | 341 | expect(service.getModelInfo()).toBeNull(); |
| 289 | 342 | }); |
| 290 | 343 | }); |
| 291 | 344 | |
| 292 | - describe('isReady()', () => { | |
| 293 | - test('should return false when not initialized', () => { | |
| 345 | + describe("isReady()", () => { | |
| 346 | + test("should return false when not initialized", () => { | |
| 294 | 347 | expect(service.isReady()).toBe(false); |
| 295 | 348 | }); |
| 296 | 349 | |
| 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 | + ]); | |
| 299 | 355 | await service.initialize(mockAssistant, mockAuthConfig); |
| 300 | 356 | |
| 301 | 357 | expect(service.isReady()).toBe(true); |
| 302 | 358 | }); |
| 303 | 359 | |
| 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 | + ]); | |
| 306 | 365 | await service.initialize(mockAssistant, mockAuthConfig); |
| 307 | 366 | |
| 308 | 367 | expect(service.isReady()).toBe(false); |
| 309 | 368 | }); |
| 310 | 369 | }); |
| 311 | 370 | |
| 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"]); | |
| 315 | 374 | }); |
| 316 | 375 | }); |
| 317 | 376 | |
| 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 | + ]); | |
| 321 | 383 | await service.initialize(mockAssistant, mockAuthConfig); |
| 322 | 384 | |
| 323 | 385 | const listener = vi.fn(); |
| 324 | - service.on('stateChanged', listener); | |
| 386 | + service.on("stateChanged", listener); | |
| 325 | 387 | |
| 326 | 388 | 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 | + ); | |
| 328 | 392 | await service.switchModel(1); |
| 329 | 393 | |
| 330 | 394 | expect(listener).toHaveBeenCalledWith( |
| 331 | 395 | expect.objectContaining({ |
| 332 | 396 | model: mockAssistant.models![1], |
| 333 | - llmApi: newLlmApi | |
| 397 | + llmApi: newLlmApi, | |
| 334 | 398 | }), |
| 335 | 399 | expect.objectContaining({ |
| 336 | 400 | model: mockAssistant.models![0], |
| 337 | - llmApi: mockLlmApi | |
| 338 | - }) | |
| 401 | + llmApi: mockLlmApi, | |
| 402 | + }), | |
| 339 | 403 | ); |
| 340 | 404 | }); |
| 341 | 405 | |
| 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 | + ]); | |
| 344 | 411 | await service.initialize(mockAssistant, mockAuthConfig); |
| 345 | 412 | |
| 346 | 413 | const errorListener = vi.fn(); |
| 347 | - service.on('error', errorListener); | |
| 414 | + service.on("error", errorListener); | |
| 348 | 415 | |
| 349 | 416 | vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any); |
| 350 | 417 | |
| 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 | + ); | |
| 352 | 421 | expect(errorListener).toHaveBeenCalledWith(expect.any(Error)); |
| 353 | 422 | }); |
| 354 | 423 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { ServiceContainer } from './ServiceContainer.js'; | |
| 3 | +import { ServiceContainer } from "./ServiceContainer.js"; | |
| 4 | 4 | |
| 5 | -describe('ServiceContainer', () => { | |
| 5 | +describe("ServiceContainer", () => { | |
| 6 | 6 | let container: ServiceContainer; |
| 7 | 7 | |
| 8 | 8 | beforeEach(() => { |
| @@ -10,13 +10,13 @@ | ||
| 10 | 10 | vi.clearAllMocks(); |
| 11 | 11 | }); |
| 12 | 12 | |
| 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 () => { | |
| 15 | 15 | // 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" }; | |
| 20 | 20 | |
| 21 | 21 | let authReloadCount = 0; |
| 22 | 22 | let apiClientReloadCount = 0; |
| @@ -25,43 +25,43 @@ | ||
| 25 | 25 | |
| 26 | 26 | // Register services with mock factories that track reload count |
| 27 | 27 | container.register( |
| 28 | - 'auth', | |
| 28 | + "auth", | |
| 29 | 29 | async () => { |
| 30 | 30 | authReloadCount++; |
| 31 | 31 | return authValue; |
| 32 | 32 | }, |
| 33 | - [] | |
| 33 | + [], | |
| 34 | 34 | ); |
| 35 | 35 | |
| 36 | 36 | container.register( |
| 37 | - 'apiClient', | |
| 37 | + "apiClient", | |
| 38 | 38 | async () => { |
| 39 | 39 | apiClientReloadCount++; |
| 40 | 40 | return apiClientValue; |
| 41 | 41 | }, |
| 42 | - ['auth'] | |
| 42 | + ["auth"], | |
| 43 | 43 | ); |
| 44 | 44 | |
| 45 | 45 | container.register( |
| 46 | - 'config', | |
| 46 | + "config", | |
| 47 | 47 | async () => { |
| 48 | 48 | configReloadCount++; |
| 49 | 49 | return configValue; |
| 50 | 50 | }, |
| 51 | - ['auth', 'apiClient'] | |
| 51 | + ["auth", "apiClient"], | |
| 52 | 52 | ); |
| 53 | 53 | |
| 54 | 54 | container.register( |
| 55 | - 'model', | |
| 55 | + "model", | |
| 56 | 56 | async () => { |
| 57 | 57 | modelReloadCount++; |
| 58 | 58 | return modelValue; |
| 59 | 59 | }, |
| 60 | - ['config'] | |
| 60 | + ["config"], | |
| 61 | 61 | ); |
| 62 | 62 | |
| 63 | 63 | // Initial load of all services |
| 64 | - await container.get('model'); | |
| 64 | + await container.get("model"); | |
| 65 | 65 | |
| 66 | 66 | // Verify initial load counts |
| 67 | 67 | expect(authReloadCount).toBe(1); |
| @@ -70,95 +70,111 @@ | ||
| 70 | 70 | expect(modelReloadCount).toBe(1); |
| 71 | 71 | |
| 72 | 72 | // Reload auth service - should cascade to all dependents |
| 73 | - await container.reload('auth'); | |
| 73 | + await container.reload("auth"); | |
| 74 | 74 | |
| 75 | 75 | // Verify cascade reload occurred - all dependent services should reload |
| 76 | 76 | expect(authReloadCount).toBe(2); // auth reloaded |
| 77 | 77 | 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 | |
| 79 | 79 | expect(modelReloadCount).toBe(2); // model depends on config |
| 80 | 80 | }); |
| 81 | 81 | |
| 82 | - test('should find all transitive dependents correctly', async () => { | |
| 82 | + test("should find all transitive dependents correctly", async () => { | |
| 83 | 83 | // 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"]); | |
| 89 | 92 | |
| 90 | 93 | // 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 | + | |
| 95 | 100 | // 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 | + ]); | |
| 97 | 107 | }); |
| 98 | 108 | |
| 99 | - test('should handle circular dependencies gracefully', async () => { | |
| 109 | + test("should handle circular dependencies gracefully", async () => { | |
| 100 | 110 | // This test ensures the findAllDependents doesn't get stuck in infinite loops |
| 101 | - | |
| 111 | + | |
| 102 | 112 | // 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 | + | |
| 106 | 116 | // 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 | + | |
| 109 | 121 | // 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 | + | |
| 113 | 125 | // 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"); | |
| 116 | 128 | }); |
| 117 | 129 | |
| 118 | - test('should emit events during cascade reload', async () => { | |
| 130 | + test("should emit events during cascade reload", async () => { | |
| 119 | 131 | 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"]); | |
| 123 | 135 | |
| 124 | 136 | // 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")); | |
| 129 | 141 | |
| 130 | 142 | // Initial load |
| 131 | - await container.get('child'); | |
| 143 | + await container.get("child"); | |
| 132 | 144 | events.length = 0; // Clear events |
| 133 | 145 | |
| 134 | 146 | // Reload parent - should cascade to child |
| 135 | - await container.reload('parent'); | |
| 147 | + await container.reload("parent"); | |
| 136 | 148 | |
| 137 | 149 | // 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"); | |
| 142 | 154 | }); |
| 143 | 155 | |
| 144 | - test('should preserve service state when no dependents exist', async () => { | |
| 156 | + test("should preserve service state when no dependents exist", async () => { | |
| 145 | 157 | 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 | + ); | |
| 151 | 167 | |
| 152 | 168 | // Load initially |
| 153 | - await container.get('standalone'); | |
| 169 | + await container.get("standalone"); | |
| 154 | 170 | expect(reloadCount).toBe(1); |
| 155 | 171 | |
| 156 | 172 | // Reload - only this service should reload |
| 157 | - await container.reload('standalone'); | |
| 173 | + await container.reload("standalone"); | |
| 158 | 174 | expect(reloadCount).toBe(2); |
| 159 | 175 | |
| 160 | 176 | // Should still be ready |
| 161 | - expect(container.isReady('standalone')).toBe(true); | |
| 177 | + expect(container.isReady("standalone")).toBe(true); | |
| 162 | 178 | }); |
| 163 | 179 | }); |
| 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 @@ | ||
| 40 | 40 | } else { |
| 41 | 41 | // Normal mode behavior depends on user config |
| 42 | 42 | console.log( |
| 43 | - `Normal mode - Write policy: ${ | |
| 44 | - writePolicy?.permission || "none" | |
| 45 | - }` | |
| 43 | + `Normal mode - Write policy: ${writePolicy?.permission || "none"}`, | |
| 46 | 44 | ); |
| 47 | 45 | } |
| 48 | 46 | }); |
| @@ -52,17 +50,17 @@ | ||
| 52 | 50 | |
| 53 | 51 | // Find all policies that could affect Write tool |
| 54 | 52 | const writeRelevantPolicies = policies.filter( |
| 55 | - (p) => p.tool === "Write" || p.tool === "*" | |
| 53 | + (p) => p.tool === "Write" || p.tool === "*", | |
| 56 | 54 | ); |
| 57 | 55 | |
| 58 | 56 | console.log( |
| 59 | - `\n=== WRITE-RELEVANT POLICIES IN ${mode.toUpperCase()} MODE ===` | |
| 57 | + `\n=== WRITE-RELEVANT POLICIES IN ${mode.toUpperCase()} MODE ===`, | |
| 60 | 58 | ); |
| 61 | 59 | writeRelevantPolicies.forEach((policy, index) => { |
| 62 | 60 | console.log( |
| 63 | 61 | `${index + 1}. tool: "${policy.tool}", permission: "${ |
| 64 | 62 | policy.permission |
| 65 | - }"` | |
| 63 | + }"`, | |
| 66 | 64 | ); |
| 67 | 65 | }); |
| 68 | 66 | |
| @@ -94,7 +92,7 @@ | ||
| 94 | 92 | console.log( |
| 95 | 93 | `${index + 1}. tool: "${policy.tool}", permission: "${ |
| 96 | 94 | policy.permission |
| 97 | - }"` | |
| 95 | + }"`, | |
| 98 | 96 | ); |
| 99 | 97 | }); |
| 100 | 98 | |
| @@ -107,7 +105,7 @@ | ||
| 107 | 105 | console.log( |
| 108 | 106 | `${index + 1}. tool: "${policy.tool}", permission: "${ |
| 109 | 107 | policy.permission |
| 110 | - }"` | |
| 108 | + }"`, | |
| 111 | 109 | ); |
| 112 | 110 | }); |
| 113 | 111 |
modified extensions/cli/src/services/ToolPermissionService.integration.test.ts +42 −27
| @@ -14,30 +14,40 @@ | ||
| 14 | 14 | const overrides = { |
| 15 | 15 | allow: ["dangerous_tool"], |
| 16 | 16 | ask: ["sensitive_tool"], |
| 17 | - exclude: ["forbidden_tool", "write_*"] | |
| 17 | + exclude: ["forbidden_tool", "write_*"], | |
| 18 | 18 | }; |
| 19 | 19 | |
| 20 | 20 | const state = await service.initialize(overrides); |
| 21 | 21 | |
| 22 | 22 | // Verify the compiled policies |
| 23 | 23 | const policies = state.permissions.policies; |
| 24 | - | |
| 24 | + | |
| 25 | 25 | // 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 | + | |
| 31 | 39 | // Verify runtime overrides are present |
| 32 | 40 | expect(excludePolicy1).toBeDefined(); |
| 33 | 41 | expect(excludePolicy2).toBeDefined(); |
| 34 | 42 | expect(askPolicy).toBeDefined(); |
| 35 | 43 | expect(allowPolicy).toBeDefined(); |
| 36 | - | |
| 44 | + | |
| 37 | 45 | // Verify all default policies are present |
| 38 | 46 | 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, | |
| 41 | 51 | ); |
| 42 | 52 | expect(foundPolicy).toBeDefined(); |
| 43 | 53 | } |
| @@ -46,24 +56,26 @@ | ||
| 46 | 56 | it("should allow dynamic updates after initialization", async () => { |
| 47 | 57 | // Start with defaults (may include additional policies from permissions.yaml) |
| 48 | 58 | await service.initialize(); |
| 49 | - | |
| 59 | + | |
| 50 | 60 | let permissions = service.getPermissions(); |
| 51 | - | |
| 61 | + | |
| 52 | 62 | // Verify all default policies are present (may have additional ones) |
| 53 | 63 | 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, | |
| 56 | 68 | ); |
| 57 | 69 | expect(foundPolicy).toBeDefined(); |
| 58 | 70 | } |
| 59 | 71 | |
| 60 | 72 | // Update with new policies (this replaces ALL policies) |
| 61 | 73 | const newPolicies = [ |
| 62 | - { tool: "*", permission: "ask" as const } // Ask for everything | |
| 74 | + { tool: "*", permission: "ask" as const }, // Ask for everything | |
| 63 | 75 | ]; |
| 64 | - | |
| 76 | + | |
| 65 | 77 | service.updatePermissions(newPolicies); |
| 66 | - | |
| 78 | + | |
| 67 | 79 | permissions = service.getPermissions(); |
| 68 | 80 | expect(permissions.policies).toEqual(newPolicies); |
| 69 | 81 | expect(permissions.policies.length).toBe(1); |
| @@ -71,19 +83,22 @@ | ||
| 71 | 83 | |
| 72 | 84 | it("should maintain state consistency", async () => { |
| 73 | 85 | const overrides = { |
| 74 | - exclude: ["test_tool"] | |
| 86 | + exclude: ["test_tool"], | |
| 75 | 87 | }; |
| 76 | 88 | |
| 77 | 89 | await service.initialize(overrides); |
| 78 | - | |
| 90 | + | |
| 79 | 91 | // Both getState and getPermissions should return same data |
| 80 | 92 | const state = service.getState(); |
| 81 | 93 | const permissions = service.getPermissions(); |
| 82 | - | |
| 94 | + | |
| 83 | 95 | // getState() returns a shallow copy, so nested objects are the same reference |
| 84 | 96 | expect(state.permissions).toEqual(permissions); |
| 85 | 97 | 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 | + }); | |
| 87 | 102 | }); |
| 88 | 103 | |
| 89 | 104 | it("should handle concurrent access correctly", async () => { |
| @@ -91,16 +106,16 @@ | ||
| 91 | 106 | await service.initialize({ allow: ["tool1"] }); |
| 92 | 107 | |
| 93 | 108 | // 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())); | |
| 97 | 112 | |
| 98 | 113 | const results = await Promise.all(promises); |
| 99 | - | |
| 114 | + | |
| 100 | 115 | // All should return the same value |
| 101 | 116 | const firstResult = results[0]; |
| 102 | - results.forEach(result => { | |
| 117 | + results.forEach((result) => { | |
| 103 | 118 | expect(result).toStrictEqual(firstResult); |
| 104 | 119 | }); |
| 105 | 120 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { ToolPermissionService } from './ToolPermissionService.js'; | |
| 3 | +import { ToolPermissionService } from "./ToolPermissionService.js"; | |
| 4 | 4 | |
| 5 | -describe('ToolPermissionService - Mode Functionality', () => { | |
| 5 | +describe("ToolPermissionService - Mode Functionality", () => { | |
| 6 | 6 | let service: ToolPermissionService; |
| 7 | 7 | |
| 8 | 8 | beforeEach(() => { |
| 9 | 9 | service = new ToolPermissionService(); |
| 10 | 10 | }); |
| 11 | 11 | |
| 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", () => { | |
| 14 | 14 | const state = service.initializeSync(); |
| 15 | - expect(state.currentMode).toBe('normal'); | |
| 15 | + expect(state.currentMode).toBe("normal"); | |
| 16 | 16 | }); |
| 17 | 17 | |
| 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"); | |
| 21 | 21 | }); |
| 22 | 22 | |
| 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" }); | |
| 25 | 25 | const policies = state.permissions.policies; |
| 26 | - | |
| 26 | + | |
| 27 | 27 | // 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 | + | |
| 32 | 38 | // 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 | + | |
| 37 | 49 | // 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 | + | |
| 40 | 54 | // 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); | |
| 42 | 58 | }); |
| 43 | 59 | |
| 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" }); | |
| 47 | 62 | const policies = state.permissions.policies; |
| 48 | - | |
| 63 | + | |
| 49 | 64 | // First policy should be the mode policy (allow all) |
| 50 | 65 | expect(policies[0]).toEqual({ |
| 51 | - tool: '*', | |
| 52 | - permission: 'allow' | |
| 66 | + tool: "*", | |
| 67 | + permission: "allow", | |
| 53 | 68 | }); |
| 54 | 69 | }); |
| 55 | 70 | |
| 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 | + | |
| 60 | 75 | // Normal mode may have default policies but no mode-specific wildcard at the start |
| 61 | 76 | 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 | + | |
| 64 | 82 | // Plan mode should have write exclusions and read allowances |
| 65 | 83 | 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); | |
| 68 | 92 | }); |
| 69 | 93 | }); |
| 70 | 94 | |
| 71 | - describe('mode switching', () => { | |
| 95 | + describe("mode switching", () => { | |
| 72 | 96 | beforeEach(() => { |
| 73 | 97 | service.initializeSync(); |
| 74 | 98 | }); |
| 75 | 99 | |
| 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"); | |
| 83 | 107 | }); |
| 84 | 108 | |
| 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" }); | |
| 87 | 111 | const normalPolicies = service.getPermissions().policies; |
| 88 | - | |
| 89 | - service.switchMode('plan'); | |
| 112 | + | |
| 113 | + service.switchMode("plan"); | |
| 90 | 114 | const planPolicies = service.getPermissions().policies; |
| 91 | - | |
| 115 | + | |
| 92 | 116 | 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); | |
| 94 | 122 | }); |
| 95 | 123 | |
| 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)", () => { | |
| 97 | 125 | // Initialize with some existing policies |
| 98 | 126 | service.initializeSync({ |
| 99 | - allow: ['allowedTool'], | |
| 100 | - exclude: ['excludedTool'] | |
| 127 | + allow: ["allowedTool"], | |
| 128 | + exclude: ["excludedTool"], | |
| 101 | 129 | }); |
| 102 | - | |
| 130 | + | |
| 103 | 131 | const initialPolicies = service.getPermissions().policies; |
| 104 | 132 | const nonModePolicyCount = initialPolicies.length; |
| 105 | - | |
| 106 | - service.switchMode('plan'); | |
| 133 | + | |
| 134 | + service.switchMode("plan"); | |
| 107 | 135 | const newPolicies = service.getPermissions().policies; |
| 108 | - | |
| 136 | + | |
| 109 | 137 | // Plan mode should use ONLY mode policies (absolute override) |
| 110 | 138 | // 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 | + | |
| 114 | 142 | // 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 | + ); | |
| 117 | 147 | expect(userAllowPolicy).toBeUndefined(); |
| 118 | 148 | expect(userExcludePolicy).toBeUndefined(); |
| 119 | 149 | }); |
| 120 | 150 | |
| 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"); | |
| 130 | 160 | }); |
| 131 | 161 | |
| 132 | - it('should preserve original user policies when switching modes', () => { | |
| 162 | + it("should preserve original user policies when switching modes", () => { | |
| 133 | 163 | // Initialize with user-defined policies |
| 134 | 164 | service.initializeSync({ |
| 135 | - allow: ['customAllowedTool'], | |
| 136 | - exclude: ['customExcludedTool'], | |
| 137 | - ask: ['customAskTool'] | |
| 165 | + allow: ["customAllowedTool"], | |
| 166 | + exclude: ["customExcludedTool"], | |
| 167 | + ask: ["customAskTool"], | |
| 138 | 168 | }); |
| 139 | - | |
| 169 | + | |
| 140 | 170 | 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", | |
| 145 | 176 | ).length; |
| 146 | 177 | expect(userPolicyCount).toBe(3); |
| 147 | - | |
| 178 | + | |
| 148 | 179 | // Switch to plan mode (should store original policies) |
| 149 | - service.switchMode('plan'); | |
| 180 | + service.switchMode("plan"); | |
| 150 | 181 | const planPolicies = service.getPermissions().policies; |
| 151 | - | |
| 182 | + | |
| 152 | 183 | // 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", | |
| 157 | 189 | ).length; |
| 158 | 190 | expect(planUserPolicyCount).toBe(0); |
| 159 | - | |
| 191 | + | |
| 160 | 192 | // Switch back to normal mode (should restore original policies) |
| 161 | - service.switchMode('normal'); | |
| 193 | + service.switchMode("normal"); | |
| 162 | 194 | const restoredPolicies = service.getPermissions().policies; |
| 163 | - | |
| 195 | + | |
| 164 | 196 | // 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", | |
| 169 | 202 | ).length; |
| 170 | 203 | 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 | - }); | |
| 177 | 204 | |
| 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", () => { | |
| 179 | 224 | // Initialize with user config that allows write tools |
| 180 | 225 | service.initializeSync({ |
| 181 | - allow: ['Write', 'Edit', 'Bash'], | |
| 182 | - mode: 'plan' | |
| 226 | + allow: ["Write", "Edit", "Bash"], | |
| 227 | + mode: "plan", | |
| 183 | 228 | }); |
| 184 | - | |
| 229 | + | |
| 185 | 230 | const policies = service.getPermissions().policies; |
| 186 | - | |
| 231 | + | |
| 187 | 232 | // 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 | + | |
| 192 | 243 | // 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); | |
| 194 | 247 | }); |
| 195 | 248 | |
| 196 | - it('should override user permissions in auto mode', () => { | |
| 249 | + it("should override user permissions in auto mode", () => { | |
| 197 | 250 | // Initialize with user config that excludes tools |
| 198 | 251 | service.initializeSync({ |
| 199 | - exclude: ['Write', 'Edit', 'Bash'], | |
| 200 | - mode: 'auto' | |
| 252 | + exclude: ["Write", "Edit", "Bash"], | |
| 253 | + mode: "auto", | |
| 201 | 254 | }); |
| 202 | - | |
| 255 | + | |
| 203 | 256 | const policies = service.getPermissions().policies; |
| 204 | - | |
| 257 | + | |
| 205 | 258 | // 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" }); | |
| 207 | 260 | }); |
| 208 | 261 | }); |
| 209 | 262 | |
| 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)", () => { | |
| 212 | 265 | const state = service.initializeSync({ |
| 213 | - mode: 'plan', | |
| 214 | - allow: ['customTool'] | |
| 266 | + mode: "plan", | |
| 267 | + allow: ["customTool"], | |
| 215 | 268 | }); |
| 216 | 269 | const policies = state.permissions.policies; |
| 217 | - | |
| 270 | + | |
| 218 | 271 | // Mode policies should come first, and there should be policies |
| 219 | 272 | expect(policies.length).toBeGreaterThan(0); |
| 220 | - | |
| 273 | + | |
| 221 | 274 | // 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); | |
| 224 | 279 | }); |
| 225 | 280 | }); |
| 226 | 281 | |
| 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"); | |
| 234 | 289 | }); |
| 235 | 290 | }); |
| 236 | 291 | |
| 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 | + | |
| 241 | 296 | const state = service.getState(); |
| 242 | 297 | const currentMode = service.getCurrentMode(); |
| 243 | - | |
| 298 | + | |
| 244 | 299 | expect(state.currentMode).toBe(currentMode); |
| 245 | - expect(currentMode).toBe('plan'); | |
| 300 | + expect(currentMode).toBe("plan"); | |
| 246 | 301 | }); |
| 247 | 302 | |
| 248 | - it('should update state when switching modes', () => { | |
| 303 | + it("should update state when switching modes", () => { | |
| 249 | 304 | service.initializeSync(); |
| 250 | - | |
| 305 | + | |
| 251 | 306 | 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 | + | |
| 256 | 311 | const newState = service.getState(); |
| 257 | - expect(newState.currentMode).toBe('plan'); | |
| 312 | + expect(newState.currentMode).toBe("plan"); | |
| 258 | 313 | expect(newState).not.toEqual(initialState); |
| 259 | 314 | }); |
| 260 | 315 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { checkToolPermission } from '../permissions/permissionChecker.js'; | |
| 3 | +import { checkToolPermission } from "../permissions/permissionChecker.js"; | |
| 4 | 4 | |
| 5 | -import { ToolPermissionService } from './ToolPermissionService.js'; | |
| 5 | +import { ToolPermissionService } from "./ToolPermissionService.js"; | |
| 6 | 6 | |
| 7 | -describe('ToolPermissionService - Real Tool Permission Test', () => { | |
| 7 | +describe("ToolPermissionService - Real Tool Permission Test", () => { | |
| 8 | 8 | let service: ToolPermissionService; |
| 9 | 9 | |
| 10 | 10 | beforeEach(() => { |
| 11 | 11 | service = new ToolPermissionService(); |
| 12 | 12 | }); |
| 13 | 13 | |
| 14 | - describe('Plan Mode Real Tool Tests', () => { | |
| 14 | + describe("Plan Mode Real Tool Tests", () => { | |
| 15 | 15 | beforeEach(() => { |
| 16 | - service.initializeSync({ mode: 'plan' }); | |
| 16 | + service.initializeSync({ mode: "plan" }); | |
| 17 | 17 | }); |
| 18 | 18 | |
| 19 | - it('should deny Write tool in plan mode', () => { | |
| 19 | + it("should deny Write tool in plan mode", () => { | |
| 20 | 20 | const permissions = service.getPermissions(); |
| 21 | 21 | const toolCall = { |
| 22 | - name: 'Write', | |
| 23 | - arguments: { path: 'test.txt', content: 'test' } | |
| 22 | + name: "Write", | |
| 23 | + arguments: { path: "test.txt", content: "test" }, | |
| 24 | 24 | }; |
| 25 | 25 | const result = checkToolPermission(toolCall, permissions); |
| 26 | - | |
| 26 | + | |
| 27 | 27 | console.log(`Write permission check result:`, result); |
| 28 | - expect(result.permission).toBe('exclude'); | |
| 28 | + expect(result.permission).toBe("exclude"); | |
| 29 | 29 | }); |
| 30 | 30 | |
| 31 | - it('should deny Edit tool in plan mode', () => { | |
| 31 | + it("should deny Edit tool in plan mode", () => { | |
| 32 | 32 | const permissions = service.getPermissions(); |
| 33 | 33 | 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" }, | |
| 36 | 36 | }; |
| 37 | 37 | const result = checkToolPermission(toolCall, permissions); |
| 38 | - | |
| 38 | + | |
| 39 | 39 | console.log(`Edit permission check result:`, result); |
| 40 | - expect(result.permission).toBe('exclude'); | |
| 40 | + expect(result.permission).toBe("exclude"); | |
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | - it('should allow Bash tool in plan mode', () => { | |
| 43 | + it("should allow Bash tool in plan mode", () => { | |
| 44 | 44 | const permissions = service.getPermissions(); |
| 45 | 45 | const toolCall = { |
| 46 | - name: 'Bash', | |
| 47 | - arguments: { command: 'ls' } | |
| 46 | + name: "Bash", | |
| 47 | + arguments: { command: "ls" }, | |
| 48 | 48 | }; |
| 49 | 49 | const result = checkToolPermission(toolCall, permissions); |
| 50 | - | |
| 50 | + | |
| 51 | 51 | console.log(`Bash permission check result:`, result); |
| 52 | - expect(result.permission).toBe('allow'); | |
| 52 | + expect(result.permission).toBe("allow"); | |
| 53 | 53 | }); |
| 54 | 54 | |
| 55 | - it('should allow Read tool in plan mode', () => { | |
| 55 | + it("should allow Read tool in plan mode", () => { | |
| 56 | 56 | const permissions = service.getPermissions(); |
| 57 | 57 | const toolCall = { |
| 58 | - name: 'Read', | |
| 59 | - arguments: { path: 'test.txt' } | |
| 58 | + name: "Read", | |
| 59 | + arguments: { path: "test.txt" }, | |
| 60 | 60 | }; |
| 61 | 61 | const result = checkToolPermission(toolCall, permissions); |
| 62 | - | |
| 62 | + | |
| 63 | 63 | console.log(`Read permission check result:`, result); |
| 64 | - expect(result.permission).toBe('allow'); | |
| 64 | + expect(result.permission).toBe("allow"); | |
| 65 | 65 | }); |
| 66 | 66 | |
| 67 | - it('should allow List tool in plan mode', () => { | |
| 67 | + it("should allow List tool in plan mode", () => { | |
| 68 | 68 | const permissions = service.getPermissions(); |
| 69 | 69 | const toolCall = { |
| 70 | - name: 'List', | |
| 71 | - arguments: { path: '.' } | |
| 70 | + name: "List", | |
| 71 | + arguments: { path: "." }, | |
| 72 | 72 | }; |
| 73 | 73 | const result = checkToolPermission(toolCall, permissions); |
| 74 | - | |
| 74 | + | |
| 75 | 75 | console.log(`List permission check result:`, result); |
| 76 | - expect(result.permission).toBe('allow'); | |
| 76 | + expect(result.permission).toBe("allow"); | |
| 77 | 77 | }); |
| 78 | 78 | |
| 79 | - it('should deny unknown tools in plan mode (wildcard exclude)', () => { | |
| 79 | + it("should deny unknown tools in plan mode (wildcard exclude)", () => { | |
| 80 | 80 | const permissions = service.getPermissions(); |
| 81 | 81 | const toolCall = { |
| 82 | - name: 'unknown_write_tool', | |
| 83 | - arguments: {} | |
| 82 | + name: "unknown_write_tool", | |
| 83 | + arguments: {}, | |
| 84 | 84 | }; |
| 85 | 85 | const result = checkToolPermission(toolCall, permissions); |
| 86 | - | |
| 86 | + | |
| 87 | 87 | console.log(`unknown_write_tool permission check result:`, result); |
| 88 | - expect(result.permission).toBe('exclude'); | |
| 88 | + expect(result.permission).toBe("exclude"); | |
| 89 | 89 | }); |
| 90 | 90 | }); |
| 91 | 91 | |
| 92 | - describe('Auto Mode Real Tool Tests', () => { | |
| 92 | + describe("Auto Mode Real Tool Tests", () => { | |
| 93 | 93 | beforeEach(() => { |
| 94 | - service.initializeSync({ mode: 'auto' }); | |
| 94 | + service.initializeSync({ mode: "auto" }); | |
| 95 | 95 | }); |
| 96 | 96 | |
| 97 | - it('should allow Write tool in auto mode', () => { | |
| 97 | + it("should allow Write tool in auto mode", () => { | |
| 98 | 98 | const permissions = service.getPermissions(); |
| 99 | 99 | const toolCall = { |
| 100 | - name: 'Write', | |
| 101 | - arguments: { path: 'test.txt', content: 'test' } | |
| 100 | + name: "Write", | |
| 101 | + arguments: { path: "test.txt", content: "test" }, | |
| 102 | 102 | }; |
| 103 | 103 | const result = checkToolPermission(toolCall, permissions); |
| 104 | - | |
| 104 | + | |
| 105 | 105 | console.log(`Auto mode Write permission check result:`, result); |
| 106 | - expect(result.permission).toBe('allow'); | |
| 106 | + expect(result.permission).toBe("allow"); | |
| 107 | 107 | }); |
| 108 | 108 | |
| 109 | - it('should allow Bash tool in auto mode', () => { | |
| 109 | + it("should allow Bash tool in auto mode", () => { | |
| 110 | 110 | const permissions = service.getPermissions(); |
| 111 | 111 | const toolCall = { |
| 112 | - name: 'Bash', | |
| 113 | - arguments: { command: 'ls' } | |
| 112 | + name: "Bash", | |
| 113 | + arguments: { command: "ls" }, | |
| 114 | 114 | }; |
| 115 | 115 | const result = checkToolPermission(toolCall, permissions); |
| 116 | - | |
| 116 | + | |
| 117 | 117 | console.log(`Auto mode Bash permission check result:`, result); |
| 118 | - expect(result.permission).toBe('allow'); | |
| 118 | + expect(result.permission).toBe("allow"); | |
| 119 | 119 | }); |
| 120 | 120 | |
| 121 | - it('should allow unknown tools in auto mode (wildcard allow)', () => { | |
| 121 | + it("should allow unknown tools in auto mode (wildcard allow)", () => { | |
| 122 | 122 | const permissions = service.getPermissions(); |
| 123 | 123 | const toolCall = { |
| 124 | - name: 'unknown_tool', | |
| 125 | - arguments: {} | |
| 124 | + name: "unknown_tool", | |
| 125 | + arguments: {}, | |
| 126 | 126 | }; |
| 127 | 127 | const result = checkToolPermission(toolCall, permissions); |
| 128 | - | |
| 128 | + | |
| 129 | 129 | console.log(`Auto mode unknown_tool permission check result:`, result); |
| 130 | - expect(result.permission).toBe('allow'); | |
| 130 | + expect(result.permission).toBe("allow"); | |
| 131 | 131 | }); |
| 132 | 132 | }); |
| 133 | 133 | |
| 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", () => { | |
| 136 | 136 | // Start with user explicitly allowing Write |
| 137 | 137 | service.initializeSync({ |
| 138 | - allow: ['Write'], | |
| 139 | - mode: 'normal' | |
| 138 | + allow: ["Write"], | |
| 139 | + mode: "normal", | |
| 140 | 140 | }); |
| 141 | 141 | |
| 142 | 142 | // Verify Write is allowed in normal mode |
| 143 | 143 | let permissions = service.getPermissions(); |
| 144 | 144 | const toolCall = { |
| 145 | - name: 'Write', | |
| 146 | - arguments: { path: 'test.txt', content: 'test' } | |
| 145 | + name: "Write", | |
| 146 | + arguments: { path: "test.txt", content: "test" }, | |
| 147 | 147 | }; |
| 148 | 148 | let result = checkToolPermission(toolCall, permissions); |
| 149 | 149 | console.log(`Normal mode with user allow - Write result:`, result); |
| 150 | - expect(result.permission).toBe('allow'); | |
| 150 | + expect(result.permission).toBe("allow"); | |
| 151 | 151 | |
| 152 | 152 | // Switch to plan mode - should OVERRIDE user config completely |
| 153 | - service.switchMode('plan'); | |
| 153 | + service.switchMode("plan"); | |
| 154 | 154 | permissions = service.getPermissions(); |
| 155 | 155 | result = checkToolPermission(toolCall, permissions); |
| 156 | - | |
| 156 | + | |
| 157 | 157 | 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"); | |
| 160 | 163 | }); |
| 161 | 164 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | 3 | // 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"); | |
| 6 | 6 | |
| 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"; | |
| 9 | 9 | |
| 10 | 10 | import { ToolPermissionService } from "./ToolPermissionService.js"; |
| 11 | 11 | |
| @@ -17,29 +17,33 @@ | ||
| 17 | 17 | service = new ToolPermissionService(); |
| 18 | 18 | }); |
| 19 | 19 | |
| 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 | + | |
| 24 | 26 | const state = await service.initialize(); |
| 25 | - | |
| 27 | + | |
| 26 | 28 | expect(state).toEqual({ |
| 27 | 29 | permissions: { policies: [] }, |
| 28 | - currentMode: 'normal', | |
| 30 | + currentMode: "normal", | |
| 29 | 31 | isHeadless: false, |
| 30 | - modePolicyCount: 0 | |
| 32 | + modePolicyCount: 0, | |
| 31 | 33 | }); |
| 32 | 34 | }); |
| 33 | 35 | |
| 34 | - test('should initialize with runtime overrides', async () => { | |
| 36 | + test("should initialize with runtime overrides", async () => { | |
| 35 | 37 | 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" }, | |
| 39 | 41 | ]; |
| 40 | - | |
| 41 | - vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(mockPolicies); | |
| 42 | - | |
| 42 | + | |
| 43 | + vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue( | |
| 44 | + mockPolicies, | |
| 45 | + ); | |
| 46 | + | |
| 43 | 47 | const overrides = { |
| 44 | 48 | allow: ["TestTool1"], |
| 45 | 49 | ask: ["TestTool2"], |
| @@ -49,48 +53,52 @@ | ||
| 49 | 53 | const state = await service.initialize(overrides); |
| 50 | 54 | |
| 51 | 55 | expect(state.permissions.policies).toEqual(mockPolicies); |
| 52 | - expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({ | |
| 56 | + expect( | |
| 57 | + precedenceResolver.resolvePermissionPrecedence, | |
| 58 | + ).toHaveBeenCalledWith({ | |
| 53 | 59 | commandLineFlags: overrides, |
| 54 | 60 | personalSettings: true, |
| 55 | - useDefaults: true | |
| 61 | + useDefaults: true, | |
| 56 | 62 | }); |
| 57 | 63 | }); |
| 58 | 64 | |
| 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"); | |
| 65 | 73 | // Plan mode should have mode-specific policies |
| 66 | 74 | expect(state.permissions.policies.length).toBeGreaterThan(0); |
| 67 | 75 | expect(state.permissions.policies).toContainEqual({ |
| 68 | - tool: 'Write', | |
| 69 | - permission: 'exclude' | |
| 76 | + tool: "Write", | |
| 77 | + permission: "exclude", | |
| 70 | 78 | }); |
| 71 | 79 | }); |
| 72 | 80 | }); |
| 73 | 81 | |
| 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 | + | |
| 82 | 90 | expect(state).toBeDefined(); |
| 83 | 91 | expect(state.permissions.policies).toContainEqual({ |
| 84 | - tool: 'Tool1', | |
| 85 | - permission: 'allow' | |
| 92 | + tool: "Tool1", | |
| 93 | + permission: "allow", | |
| 86 | 94 | }); |
| 87 | 95 | }); |
| 88 | 96 | |
| 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 | + | |
| 94 | 102 | const state = service.initializeSync({ |
| 95 | 103 | allow: [], |
| 96 | 104 | ask: [], |
| @@ -98,129 +106,136 @@ | ||
| 98 | 106 | }); |
| 99 | 107 | |
| 100 | 108 | expect(state.permissions.policies).toEqual([ |
| 101 | - { tool: '*', permission: 'ask' } | |
| 109 | + { tool: "*", permission: "ask" }, | |
| 102 | 110 | ]); |
| 103 | 111 | }); |
| 104 | 112 | }); |
| 105 | 113 | |
| 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" }); | |
| 109 | 117 | const policies = state.permissions.policies; |
| 110 | - | |
| 118 | + | |
| 111 | 119 | // 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 | + | |
| 115 | 123 | // 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 | + | |
| 121 | 129 | // 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 | + }); | |
| 123 | 134 | }); |
| 124 | 135 | |
| 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 | + | |
| 128 | 139 | expect(state.permissions.policies).toEqual([ |
| 129 | - { tool: '*', permission: 'allow' } | |
| 140 | + { tool: "*", permission: "allow" }, | |
| 130 | 141 | ]); |
| 131 | 142 | }); |
| 132 | 143 | |
| 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 | + | |
| 141 | 154 | // Normal mode should use user configuration |
| 142 | 155 | 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" }, | |
| 145 | 158 | ]); |
| 146 | 159 | expect(state.modePolicyCount).toBe(0); |
| 147 | 160 | }); |
| 148 | 161 | }); |
| 149 | 162 | |
| 150 | - describe('switchMode()', () => { | |
| 163 | + describe("switchMode()", () => { | |
| 151 | 164 | 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 | + ); | |
| 156 | 171 | }); |
| 157 | 172 | |
| 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"); | |
| 164 | 179 | // Should only have plan mode policies |
| 165 | 180 | expect(state.permissions.policies).toContainEqual({ |
| 166 | - tool: 'Write', | |
| 167 | - permission: 'exclude' | |
| 181 | + tool: "Write", | |
| 182 | + permission: "exclude", | |
| 168 | 183 | }); |
| 169 | 184 | // Should not have user policies |
| 170 | 185 | expect(state.permissions.policies).not.toContainEqual({ |
| 171 | - tool: 'UserTool1', | |
| 172 | - permission: 'allow' | |
| 186 | + tool: "UserTool1", | |
| 187 | + permission: "allow", | |
| 173 | 188 | }); |
| 174 | 189 | }); |
| 175 | 190 | |
| 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" }); | |
| 178 | 193 | const originalState = service.getState(); |
| 179 | - | |
| 180 | - service.switchMode('plan'); | |
| 194 | + | |
| 195 | + service.switchMode("plan"); | |
| 181 | 196 | const planState = service.getState(); |
| 182 | - | |
| 197 | + | |
| 183 | 198 | // Should have stored original policies |
| 184 | 199 | expect(planState.originalPolicies).toEqual({ |
| 185 | - policies: originalState.permissions.policies | |
| 200 | + policies: originalState.permissions.policies, | |
| 186 | 201 | }); |
| 187 | 202 | }); |
| 188 | 203 | |
| 189 | - test('should restore original policies when switching back to normal', () => { | |
| 204 | + test("should restore original policies when switching back to normal", () => { | |
| 190 | 205 | // Start in normal with user policies |
| 191 | - service.initializeSync({ mode: 'normal' }); | |
| 206 | + service.initializeSync({ mode: "normal" }); | |
| 192 | 207 | const originalPolicies = service.getState().permissions.policies; |
| 193 | - | |
| 208 | + | |
| 194 | 209 | // Switch to plan |
| 195 | - service.switchMode('plan'); | |
| 196 | - | |
| 210 | + service.switchMode("plan"); | |
| 211 | + | |
| 197 | 212 | // Switch back to normal |
| 198 | - const state = service.switchMode('normal'); | |
| 199 | - | |
| 213 | + const state = service.switchMode("normal"); | |
| 214 | + | |
| 200 | 215 | // Should restore original user policies |
| 201 | 216 | expect(state.permissions.policies).toEqual(originalPolicies); |
| 202 | 217 | }); |
| 203 | 218 | |
| 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 | + | |
| 207 | 222 | // 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"); | |
| 213 | 228 | expect(service.getState().permissions.policies).toEqual([ |
| 214 | - { tool: '*', permission: 'allow' } | |
| 229 | + { tool: "*", permission: "allow" }, | |
| 215 | 230 | ]); |
| 216 | - | |
| 217 | - service.switchMode('normal'); | |
| 218 | - expect(service.getCurrentMode()).toBe('normal'); | |
| 231 | + | |
| 232 | + service.switchMode("normal"); | |
| 233 | + expect(service.getCurrentMode()).toBe("normal"); | |
| 219 | 234 | }); |
| 220 | 235 | }); |
| 221 | 236 | |
| 222 | - describe('updatePermissions()', () => { | |
| 223 | - test('should replace all policies', () => { | |
| 237 | + describe("updatePermissions()", () => { | |
| 238 | + test("should replace all policies", () => { | |
| 224 | 239 | service.initializeSync(); |
| 225 | 240 | |
| 226 | 241 | const newPolicies: ToolPermissionPolicy[] = [ |
| @@ -236,8 +251,8 @@ | ||
| 236 | 251 | }); |
| 237 | 252 | }); |
| 238 | 253 | |
| 239 | - describe('getPermissions()', () => { | |
| 240 | - test('should return current permissions', () => { | |
| 254 | + describe("getPermissions()", () => { | |
| 255 | + test("should return current permissions", () => { | |
| 241 | 256 | service.initializeSync({ allow: ["TestTool"] }); |
| 242 | 257 | |
| 243 | 258 | const permissions = service.getPermissions(); |
| @@ -249,97 +264,99 @@ | ||
| 249 | 264 | }); |
| 250 | 265 | }); |
| 251 | 266 | |
| 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"); | |
| 259 | 274 | }); |
| 260 | 275 | }); |
| 261 | 276 | |
| 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)", () => { | |
| 264 | 279 | // ToolPermissionService is designed to be always ready since it uses synchronous initialization |
| 265 | 280 | expect(service.isReady()).toBe(true); |
| 266 | 281 | }); |
| 267 | 282 | |
| 268 | - test('should return true after initialization', async () => { | |
| 283 | + test("should return true after initialization", async () => { | |
| 269 | 284 | await service.initialize(); |
| 270 | 285 | expect(service.isReady()).toBe(true); |
| 271 | 286 | }); |
| 272 | 287 | }); |
| 273 | 288 | |
| 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 | + | |
| 278 | 293 | 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 | + | |
| 283 | 298 | expect(listener).toHaveBeenCalledWith( |
| 284 | - expect.objectContaining({ currentMode: 'plan' }), | |
| 285 | - expect.objectContaining({ currentMode: 'normal' }) | |
| 299 | + expect.objectContaining({ currentMode: "plan" }), | |
| 300 | + expect.objectContaining({ currentMode: "normal" }), | |
| 286 | 301 | ); |
| 287 | 302 | }); |
| 288 | 303 | |
| 289 | - test('should emit stateChanged when updating permissions', () => { | |
| 304 | + test("should emit stateChanged when updating permissions", () => { | |
| 290 | 305 | service.initializeSync(); |
| 291 | - | |
| 306 | + | |
| 292 | 307 | const listener = vi.fn(); |
| 293 | - service.on('stateChanged', listener); | |
| 294 | - | |
| 308 | + service.on("stateChanged", listener); | |
| 309 | + | |
| 295 | 310 | const newPolicies: ToolPermissionPolicy[] = [ |
| 296 | - { tool: 'NewTool', permission: 'allow' } | |
| 311 | + { tool: "NewTool", permission: "allow" }, | |
| 297 | 312 | ]; |
| 298 | 313 | service.updatePermissions(newPolicies); |
| 299 | - | |
| 314 | + | |
| 300 | 315 | expect(listener).toHaveBeenCalledWith( |
| 301 | - expect.objectContaining({ | |
| 302 | - permissions: { policies: newPolicies } | |
| 316 | + expect.objectContaining({ | |
| 317 | + permissions: { policies: newPolicies }, | |
| 303 | 318 | }), |
| 304 | - expect.any(Object) | |
| 319 | + expect.any(Object), | |
| 305 | 320 | ); |
| 306 | 321 | }); |
| 307 | 322 | }); |
| 308 | 323 | |
| 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", () => { | |
| 311 | 326 | // 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"], | |
| 320 | 337 | }); |
| 321 | - | |
| 338 | + | |
| 322 | 339 | // Plan mode should override and exclude these tools |
| 323 | 340 | expect(state.permissions.policies).toContainEqual({ |
| 324 | - tool: 'Write', | |
| 325 | - permission: 'exclude' | |
| 341 | + tool: "Write", | |
| 342 | + permission: "exclude", | |
| 326 | 343 | }); |
| 327 | 344 | expect(state.permissions.policies).toContainEqual({ |
| 328 | - tool: 'Edit', | |
| 329 | - permission: 'exclude' | |
| 345 | + tool: "Edit", | |
| 346 | + permission: "exclude", | |
| 330 | 347 | }); |
| 331 | 348 | }); |
| 332 | 349 | |
| 333 | - test('auto mode should completely override user policies', () => { | |
| 350 | + test("auto mode should completely override user policies", () => { | |
| 334 | 351 | // 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"], | |
| 338 | 355 | }); |
| 339 | - | |
| 356 | + | |
| 340 | 357 | // Auto mode should override and allow everything |
| 341 | 358 | expect(state.permissions.policies).toEqual([ |
| 342 | - { tool: '*', permission: 'allow' } | |
| 359 | + { tool: "*", permission: "allow" }, | |
| 343 | 360 | ]); |
| 344 | 361 | }); |
| 345 | 362 | }); |
| @@ -350,49 +367,57 @@ | ||
| 350 | 367 | { tool: "Edit", permission: "allow" as const }, |
| 351 | 368 | { tool: "Write", permission: "ask" as const }, |
| 352 | 369 | ]; |
| 353 | - | |
| 370 | + | |
| 354 | 371 | // 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 | + | |
| 357 | 376 | const service = new ToolPermissionService(); |
| 358 | 377 | service.initializeSync({ mode: "normal" }); |
| 359 | - | |
| 378 | + | |
| 360 | 379 | // Verify initial state |
| 361 | 380 | expect(service.getPermissions().policies).toEqual(mockPolicies); |
| 362 | - | |
| 381 | + | |
| 363 | 382 | // Simulate new policies being added to the file |
| 364 | 383 | const newMockPolicies = [ |
| 365 | 384 | ...mockPolicies, |
| 366 | 385 | { tool: "Read", permission: "allow" as const }, |
| 367 | 386 | ]; |
| 368 | - vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(newMockPolicies); | |
| 369 | - | |
| 387 | + vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue( | |
| 388 | + newMockPolicies, | |
| 389 | + ); | |
| 390 | + | |
| 370 | 391 | // Reload permissions |
| 371 | 392 | await service.reloadPermissions(); |
| 372 | - | |
| 393 | + | |
| 373 | 394 | // Verify policies were reloaded |
| 374 | 395 | expect(service.getPermissions().policies).toEqual(newMockPolicies); |
| 375 | - expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({ | |
| 396 | + expect( | |
| 397 | + precedenceResolver.resolvePermissionPrecedence, | |
| 398 | + ).toHaveBeenCalledWith({ | |
| 376 | 399 | personalSettings: true, |
| 377 | 400 | useDefaults: true, |
| 378 | 401 | }); |
| 379 | 402 | }); |
| 380 | - | |
| 403 | + | |
| 381 | 404 | test("should skip reload in non-normal modes", async () => { |
| 382 | 405 | const service = new ToolPermissionService(); |
| 383 | 406 | service.initializeSync({ mode: "plan" }); |
| 384 | - | |
| 407 | + | |
| 385 | 408 | const initialPolicies = service.getPermissions().policies; |
| 386 | - | |
| 409 | + | |
| 387 | 410 | // Clear the mock call count |
| 388 | 411 | vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockClear(); |
| 389 | - | |
| 412 | + | |
| 390 | 413 | // Try to reload |
| 391 | 414 | await service.reloadPermissions(); |
| 392 | - | |
| 415 | + | |
| 393 | 416 | // Verify no reload happened |
| 394 | 417 | expect(service.getPermissions().policies).toEqual(initialPolicies); |
| 395 | - expect(precedenceResolver.resolvePermissionPrecedence).not.toHaveBeenCalled(); | |
| 418 | + expect( | |
| 419 | + precedenceResolver.resolvePermissionPrecedence, | |
| 420 | + ).not.toHaveBeenCalled(); | |
| 396 | 421 | }); |
| 397 | 422 | }); |
| 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 @@ | ||
| 56 | 56 | // getState() returns a shallow copy, getPermissions() returns the same permissions object |
| 57 | 57 | expect(state.permissions).toEqual(permissions); |
| 58 | 58 | expect(state.permissions).toBe(permissions); // Same reference with shallow copy |
| 59 | - | |
| 59 | + | |
| 60 | 60 | // Multiple calls to getPermissions() should return the same reference |
| 61 | 61 | const permissions2 = service.getPermissions(); |
| 62 | 62 | 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"; | |
| 2 | 2 | |
| 3 | -import { initializeServices } from './index.js'; | |
| 3 | +import { initializeServices } from "./index.js"; | |
| 4 | 4 | |
| 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 () => { | |
| 7 | 7 | // Create a fresh container and initialize services to get real dependencies |
| 8 | 8 | const testContainer = new ServiceContainer(); |
| 9 | - | |
| 9 | + | |
| 10 | 10 | // Monkey patch the global serviceContainer to capture registrations |
| 11 | 11 | const originalRegister = testContainer.register.bind(testContainer); |
| 12 | 12 | 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 | + ) { | |
| 15 | 19 | serviceDependencies[serviceName] = [...deps]; // Capture actual dependencies |
| 16 | 20 | return originalRegister(serviceName, factory, deps); |
| 17 | 21 | }; |
| 18 | 22 | |
| 19 | 23 | // Import and run the real service initialization to capture dependencies |
| 20 | - const { serviceContainer } = await import('./index.js'); | |
| 24 | + const { serviceContainer } = await import("./index.js"); | |
| 21 | 25 | const originalContainer = serviceContainer; |
| 22 | - | |
| 26 | + | |
| 23 | 27 | // Temporarily replace the global container |
| 24 | 28 | (global as any).serviceContainer = testContainer; |
| 25 | - | |
| 29 | + | |
| 26 | 30 | try { |
| 27 | 31 | // This will register services with their real dependencies |
| 28 | 32 | await initializeServices({ headless: true }); |
| @@ -34,7 +38,9 @@ | ||
| 34 | 38 | } |
| 35 | 39 | |
| 36 | 40 | // Detect circular dependencies using topological sort |
| 37 | - const detectCircularDependencies = (dependencies: Record<string, string[]>): string[] => { | |
| 41 | + const detectCircularDependencies = ( | |
| 42 | + dependencies: Record<string, string[]>, | |
| 43 | + ): string[] => { | |
| 38 | 44 | const visited = new Set<string>(); |
| 39 | 45 | const recStack = new Set<string>(); |
| 40 | 46 | const cycle: string[] = []; |
| @@ -78,9 +84,11 @@ | ||
| 78 | 84 | }; |
| 79 | 85 | |
| 80 | 86 | const circularDeps = detectCircularDependencies(serviceDependencies); |
| 81 | - | |
| 87 | + | |
| 82 | 88 | if (circularDeps.length > 0) { |
| 83 | - throw new Error(`Circular dependency detected: ${circularDeps.join(' -> ')}`); | |
| 89 | + throw new Error( | |
| 90 | + `Circular dependency detected: ${circularDeps.join(" -> ")}`, | |
| 91 | + ); | |
| 84 | 92 | } |
| 85 | 93 | |
| 86 | 94 | // Also verify that all services can be theoretically loaded without circular issues |
| @@ -89,9 +97,15 @@ | ||
| 89 | 97 | const maxIterations = Object.keys(serviceDependencies).length * 2; |
| 90 | 98 | let iterations = 0; |
| 91 | 99 | |
| 92 | - while (resolved.size < Object.keys(serviceDependencies).length && iterations < maxIterations) { | |
| 100 | + while ( | |
| 101 | + resolved.size < Object.keys(serviceDependencies).length && | |
| 102 | + iterations < maxIterations | |
| 103 | + ) { | |
| 93 | 104 | 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 | + ) { | |
| 95 | 109 | resolved.add(service); |
| 96 | 110 | } |
| 97 | 111 | } |
| @@ -103,4 +117,4 @@ | ||
| 103 | 117 | |
| 104 | 118 | expect(canResolveAll()).toBe(true); |
| 105 | 119 | }); |
| 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"; | |
| 2 | 2 | |
| 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"; | |
| 5 | 5 | |
| 6 | -import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js'; | |
| 6 | +import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js"; | |
| 7 | 7 | |
| 8 | -describe('Service Initialization', () => { | |
| 8 | +describe("Service Initialization", () => { | |
| 9 | 9 | beforeEach(() => { |
| 10 | 10 | // Clean up service container state |
| 11 | 11 | const services = [ |
| @@ -14,10 +14,10 @@ | ||
| 14 | 14 | SERVICE_NAMES.API_CLIENT, |
| 15 | 15 | SERVICE_NAMES.CONFIG, |
| 16 | 16 | SERVICE_NAMES.MODEL, |
| 17 | - SERVICE_NAMES.MCP | |
| 17 | + SERVICE_NAMES.MCP, | |
| 18 | 18 | ]; |
| 19 | - | |
| 20 | - services.forEach(service => { | |
| 19 | + | |
| 20 | + services.forEach((service) => { | |
| 21 | 21 | // Reset service state |
| 22 | 22 | (serviceContainer as any).services.delete(service); |
| 23 | 23 | (serviceContainer as any).factories.delete(service); |
| @@ -25,37 +25,41 @@ | ||
| 25 | 25 | }); |
| 26 | 26 | }); |
| 27 | 27 | |
| 28 | - it('should have TOOL_PERMISSIONS service ready after initialization', async () => { | |
| 28 | + it("should have TOOL_PERMISSIONS service ready after initialization", async () => { | |
| 29 | 29 | // Before initialization, service should not be ready |
| 30 | 30 | 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 | + | |
| 33 | 33 | // Initialize services |
| 34 | 34 | await initializeServices({ |
| 35 | 35 | headless: true, |
| 36 | 36 | toolPermissionOverrides: { |
| 37 | - mode: 'normal' | |
| 38 | - } | |
| 37 | + mode: "normal", | |
| 38 | + }, | |
| 39 | 39 | }); |
| 40 | - | |
| 40 | + | |
| 41 | 41 | // 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"); | |
| 44 | 46 | expect(afterInit.value).toBeDefined(); |
| 45 | - expect(afterInit.value?.currentMode).toBe('normal'); | |
| 47 | + expect(afterInit.value?.currentMode).toBe("normal"); | |
| 46 | 48 | expect(afterInit.value?.isHeadless).toBe(true); |
| 47 | 49 | }); |
| 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 () => { | |
| 50 | 52 | await initializeServices({ |
| 51 | - headless: true | |
| 53 | + headless: true, | |
| 52 | 54 | }); |
| 53 | - | |
| 55 | + | |
| 54 | 56 | // 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 | + | |
| 57 | 61 | // Service should be ready, not idle |
| 58 | - expect(serviceResult.state).toBe('ready'); | |
| 62 | + expect(serviceResult.state).toBe("ready"); | |
| 59 | 63 | expect(serviceResult.value).toBeDefined(); |
| 60 | 64 | }); |
| 61 | -}); | |
| No newline at the end of the file | ||
| 65 | +}); |
modified extensions/cli/src/services/index.test.ts +8 −5
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | createOrUpdateConfig: vi.fn().mockResolvedValue(undefined), |
| 12 | 12 | })); |
| 13 | 13 | |
| 14 | -// Mock auth module | |
| 14 | +// Mock auth module | |
| 15 | 15 | vi.mock("../auth/workos.js", () => ({ |
| 16 | 16 | loadAuthConfig: vi.fn().mockReturnValue({}), |
| 17 | 17 | })); |
| @@ -47,12 +47,15 @@ | ||
| 47 | 47 | // Set up mocks |
| 48 | 48 | (modeService as any).initialize = mockModeService.initialize; |
| 49 | 49 | (modeService as any).getCurrentMode = mockModeService.getCurrentMode; |
| 50 | - (modeService as any).getToolPermissionService = mockModeService.getToolPermissionService; | |
| 51 | - | |
| 50 | + (modeService as any).getToolPermissionService = | |
| 51 | + mockModeService.getToolPermissionService; | |
| 52 | + | |
| 52 | 53 | // Mock serviceContainer methods |
| 53 | - (serviceContainer as any).registerValue = mockServiceContainer.registerValue; | |
| 54 | + (serviceContainer as any).registerValue = | |
| 55 | + mockServiceContainer.registerValue; | |
| 54 | 56 | (serviceContainer as any).register = mockServiceContainer.register; |
| 55 | - (serviceContainer as any).initializeAll = mockServiceContainer.initializeAll; | |
| 57 | + (serviceContainer as any).initializeAll = | |
| 58 | + mockServiceContainer.initializeAll; | |
| 56 | 59 | }); |
| 57 | 60 | |
| 58 | 61 | afterEach(() => { |
modified extensions/cli/src/session.test.ts +15 −15
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | |
| 6 | 6 | beforeEach(() => { |
| 7 | 7 | originalEnv = { ...process.env }; |
| 8 | - | |
| 8 | + | |
| 9 | 9 | // Clear session-related environment variables |
| 10 | 10 | delete process.env.TMUX_PANE; |
| 11 | 11 | delete process.env.TERM_SESSION_ID; |
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | |
| 42 | 42 | it("should use TERM_SESSION_ID when TMUX_PANE is not available", () => { |
| 43 | 43 | process.env.TERM_SESSION_ID = "w1t0s0:0.0"; |
| 44 | - | |
| 44 | + | |
| 45 | 45 | saveSession([{ role: "user", content: "test" }]); |
| 46 | 46 | expect(hasSession()).toBe(true); |
| 47 | 47 | clearSession(); |
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | |
| 50 | 50 | it("should use SSH_TTY when other env vars are not available", () => { |
| 51 | 51 | process.env.SSH_TTY = "/dev/pts/0"; |
| 52 | - | |
| 52 | + | |
| 53 | 53 | saveSession([{ role: "user", content: "test" }]); |
| 54 | 54 | expect(hasSession()).toBe(true); |
| 55 | 55 | clearSession(); |
| @@ -57,12 +57,12 @@ | ||
| 57 | 57 | |
| 58 | 58 | it("should clean special characters from session IDs", () => { |
| 59 | 59 | process.env.TMUX_PANE = "%1:0.0/special#chars@test!"; |
| 60 | - | |
| 60 | + | |
| 61 | 61 | // Should not throw error despite special characters |
| 62 | 62 | expect(() => { |
| 63 | 63 | saveSession([{ role: "user", content: "test" }]); |
| 64 | 64 | }).not.toThrow(); |
| 65 | - | |
| 65 | + | |
| 66 | 66 | expect(hasSession()).toBe(true); |
| 67 | 67 | clearSession(); |
| 68 | 68 | }); |
| @@ -71,7 +71,7 @@ | ||
| 71 | 71 | describe("Test Mode", () => { |
| 72 | 72 | it("should use test session ID when provided", () => { |
| 73 | 73 | process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123"; |
| 74 | - | |
| 74 | + | |
| 75 | 75 | saveSession([{ role: "user", content: "test" }]); |
| 76 | 76 | expect(hasSession()).toBe(true); |
| 77 | 77 | clearSession(); |
| @@ -81,28 +81,28 @@ | ||
| 81 | 81 | describe("Fallback Mechanisms", () => { |
| 82 | 82 | it("should create a session even when no environment variables are available", () => { |
| 83 | 83 | // No environment variables set |
| 84 | - | |
| 84 | + | |
| 85 | 85 | // Should fall back to TTY path, process tree, or PID |
| 86 | 86 | expect(() => { |
| 87 | 87 | saveSession([{ role: "user", content: "fallback test" }]); |
| 88 | 88 | }).not.toThrow(); |
| 89 | - | |
| 89 | + | |
| 90 | 90 | expect(hasSession()).toBe(true); |
| 91 | 91 | clearSession(); |
| 92 | 92 | }); |
| 93 | 93 | |
| 94 | 94 | it("should handle session persistence correctly", () => { |
| 95 | 95 | process.env.TMUX_PANE = "%test"; |
| 96 | - | |
| 96 | + | |
| 97 | 97 | const testHistory = [ |
| 98 | 98 | { role: "user" as const, content: "Hello" }, |
| 99 | - { role: "assistant" as const, content: "Hi there!" } | |
| 99 | + { role: "assistant" as const, content: "Hi there!" }, | |
| 100 | 100 | ]; |
| 101 | - | |
| 101 | + | |
| 102 | 102 | // Save session |
| 103 | 103 | saveSession(testHistory); |
| 104 | 104 | expect(hasSession()).toBe(true); |
| 105 | - | |
| 105 | + | |
| 106 | 106 | // Clear and verify it's gone |
| 107 | 107 | clearSession(); |
| 108 | 108 | expect(hasSession()).toBe(false); |
| @@ -113,12 +113,12 @@ | ||
| 113 | 113 | it("should handle filesystem errors gracefully", () => { |
| 114 | 114 | // Try to save to invalid session ID that might cause filesystem issues |
| 115 | 115 | process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-with-various-chars"; |
| 116 | - | |
| 116 | + | |
| 117 | 117 | expect(() => { |
| 118 | 118 | saveSession([{ role: "user", content: "test" }]); |
| 119 | 119 | }).not.toThrow(); |
| 120 | - | |
| 120 | + | |
| 121 | 121 | clearSession(); |
| 122 | 122 | }); |
| 123 | 123 | }); |
| 124 | -}); | |
| No newline at the end of the file | ||
| 124 | +}); |
modified extensions/cli/src/slashCommands.modes.test.ts +4 −4
| @@ -1,10 +1,10 @@ | ||
| 1 | 1 | // Mode-related slash commands have been removed per user request |
| 2 | 2 | // This test file is no longer needed but needs a dummy test for Vitest |
| 3 | 3 | |
| 4 | -import { describe, it, expect } from 'vitest'; | |
| 4 | +import { describe, it, expect } from "vitest"; | |
| 5 | 5 | |
| 6 | -describe('Mode slash commands (removed)', () => { | |
| 7 | - it('should pass (dummy test)', () => { | |
| 6 | +describe("Mode slash commands (removed)", () => { | |
| 7 | + it("should pass (dummy test)", () => { | |
| 8 | 8 | expect(true).toBe(true); |
| 9 | 9 | }); |
| 10 | -}); | |
| No newline at the end of the file | ||
| 10 | +}); |
modified extensions/cli/src/slashCommands.test.ts +2 −6
| @@ -35,7 +35,7 @@ | ||
| 35 | 35 | expect.arrayContaining([ |
| 36 | 36 | expect.objectContaining({ name: "help" }), |
| 37 | 37 | expect.objectContaining({ name: "login" }), |
| 38 | - ]) | |
| 38 | + ]), | |
| 39 | 39 | ); |
| 40 | 40 | }); |
| 41 | 41 | |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | |
| 59 | 59 | expect(result).not.toBeNull(); |
| 60 | 60 | expect(result?.output).toContain( |
| 61 | - "Login successful! All services updated automatically." | |
| 61 | + "Login successful! All services updated automatically.", | |
| 62 | 62 | ); |
| 63 | 63 | |
| 64 | 64 | // Verify auth service login was called |
| @@ -73,8 +73,6 @@ | ||
| 73 | 73 | expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG); |
| 74 | 74 | }); |
| 75 | 75 | |
| 76 | - | |
| 77 | - | |
| 78 | 76 | test.skip("login failure should not trigger any reloads", async () => { |
| 79 | 77 | const loginError = new Error("Login failed"); |
| 80 | 78 | (services.auth.login as any).mockRejectedValue(loginError); |
| @@ -87,8 +85,6 @@ | ||
| 87 | 85 | // Verify NO reload was triggered on failure |
| 88 | 86 | expect(reloadService).not.toHaveBeenCalled(); |
| 89 | 87 | }); |
| 90 | - | |
| 91 | - | |
| 92 | 88 | }); |
| 93 | 89 | |
| 94 | 90 | 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", () => { | |
| 8 | 13 | beforeEach(() => { |
| 9 | 14 | // Clean up service container state before each test |
| 10 | 15 | const services = [ |
| @@ -13,10 +18,10 @@ | ||
| 13 | 18 | SERVICE_NAMES.API_CLIENT, |
| 14 | 19 | SERVICE_NAMES.CONFIG, |
| 15 | 20 | SERVICE_NAMES.MODEL, |
| 16 | - SERVICE_NAMES.MCP | |
| 21 | + SERVICE_NAMES.MCP, | |
| 17 | 22 | ]; |
| 18 | - | |
| 19 | - services.forEach(service => { | |
| 23 | + | |
| 24 | + services.forEach((service) => { | |
| 20 | 25 | // Reset service state |
| 21 | 26 | (serviceContainer as any).services.delete(service); |
| 22 | 27 | (serviceContainer as any).factories.delete(service); |
| @@ -24,137 +29,143 @@ | ||
| 24 | 29 | }); |
| 25 | 30 | }); |
| 26 | 31 | |
| 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 () => { | |
| 28 | 33 | // Initialize services in plan mode (simulating `cn -p`) |
| 29 | 34 | await initializeServices({ |
| 30 | 35 | headless: true, |
| 31 | 36 | toolPermissionOverrides: { |
| 32 | - mode: 'plan' | |
| 33 | - } | |
| 37 | + mode: "plan", | |
| 38 | + }, | |
| 34 | 39 | }); |
| 35 | 40 | |
| 36 | 41 | // 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"); | |
| 40 | 47 | |
| 41 | 48 | // Get available tools - this should include Bash in plan mode |
| 42 | 49 | const tools = await getAllTools(); |
| 43 | - const toolNames = tools.map(t => t.function.name); | |
| 50 | + const toolNames = tools.map((t) => t.function.name); | |
| 44 | 51 | |
| 45 | 52 | // Bash should be allowed in plan mode |
| 46 | - expect(toolNames).toContain('Bash'); | |
| 47 | - | |
| 53 | + expect(toolNames).toContain("Bash"); | |
| 54 | + | |
| 48 | 55 | // 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 | + | |
| 55 | 62 | // 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"); | |
| 58 | 65 | }); |
| 59 | 66 | |
| 60 | - test('should include Bash tool in normal mode', async () => { | |
| 67 | + test("should include Bash tool in normal mode", async () => { | |
| 61 | 68 | // Initialize services in normal mode |
| 62 | 69 | await initializeServices({ |
| 63 | 70 | headless: true, |
| 64 | 71 | toolPermissionOverrides: { |
| 65 | - mode: 'normal' | |
| 66 | - } | |
| 72 | + mode: "normal", | |
| 73 | + }, | |
| 67 | 74 | }); |
| 68 | 75 | |
| 69 | 76 | // 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"); | |
| 73 | 82 | |
| 74 | 83 | // Get available tools - Bash should be available in normal mode |
| 75 | 84 | const tools = await getAllTools(); |
| 76 | - const toolNames = tools.map(t => t.function.name); | |
| 85 | + const toolNames = tools.map((t) => t.function.name); | |
| 77 | 86 | |
| 78 | 87 | // 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"); | |
| 83 | 92 | }); |
| 84 | 93 | |
| 85 | - test('should include all tools in auto mode', async () => { | |
| 94 | + test("should include all tools in auto mode", async () => { | |
| 86 | 95 | // Initialize services in auto mode |
| 87 | 96 | await initializeServices({ |
| 88 | 97 | headless: true, |
| 89 | 98 | toolPermissionOverrides: { |
| 90 | - mode: 'auto' | |
| 91 | - } | |
| 99 | + mode: "auto", | |
| 100 | + }, | |
| 92 | 101 | }); |
| 93 | 102 | |
| 94 | 103 | // 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"); | |
| 98 | 109 | |
| 99 | 110 | // Get available tools - all tools should be available in auto mode |
| 100 | 111 | const tools = await getAllTools(); |
| 101 | - const toolNames = tools.map(t => t.function.name); | |
| 112 | + const toolNames = tools.map((t) => t.function.name); | |
| 102 | 113 | |
| 103 | 114 | // 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"); | |
| 108 | 119 | }); |
| 109 | 120 | |
| 110 | - test('should respect explicit exclude in normal mode', async () => { | |
| 121 | + test("should respect explicit exclude in normal mode", async () => { | |
| 111 | 122 | // Initialize services in normal mode with Read tool explicitly excluded |
| 112 | 123 | await initializeServices({ |
| 113 | 124 | headless: true, |
| 114 | 125 | toolPermissionOverrides: { |
| 115 | - mode: 'normal', | |
| 116 | - exclude: ['Read'] | |
| 117 | - } | |
| 126 | + mode: "normal", | |
| 127 | + exclude: ["Read"], | |
| 128 | + }, | |
| 118 | 129 | }); |
| 119 | 130 | |
| 120 | 131 | const tools = await getAllTools(); |
| 121 | - const toolNames = tools.map(t => t.function.name); | |
| 132 | + const toolNames = tools.map((t) => t.function.name); | |
| 122 | 133 | |
| 123 | 134 | // Read should be excluded due to explicit exclude |
| 124 | - expect(toolNames).not.toContain('Read'); | |
| 125 | - | |
| 135 | + expect(toolNames).not.toContain("Read"); | |
| 136 | + | |
| 126 | 137 | // 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"); | |
| 131 | 142 | }); |
| 132 | 143 | |
| 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 () => { | |
| 134 | 145 | // This test specifically addresses the original issue where plan mode |
| 135 | 146 | // wasn't properly excluding tools despite being in plan mode |
| 136 | 147 | await initializeServices({ |
| 137 | 148 | headless: true, |
| 138 | 149 | 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 | + }, | |
| 142 | 153 | }); |
| 143 | 154 | |
| 144 | 155 | const tools = await getAllTools(); |
| 145 | - const toolNames = tools.map(t => t.function.name); | |
| 156 | + const toolNames = tools.map((t) => t.function.name); | |
| 146 | 157 | |
| 147 | 158 | // Plan mode should still exclude write tools despite --allow flags |
| 148 | 159 | // 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 | + | |
| 152 | 163 | // Bash should be available in plan mode |
| 153 | - expect(toolNames).toContain('Bash'); | |
| 154 | - | |
| 164 | + expect(toolNames).toContain("Bash"); | |
| 165 | + | |
| 155 | 166 | // 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"); | |
| 159 | 170 | }); |
| 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"; | |
| 2 | 2 | |
| 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"; | |
| 6 | 10 | |
| 7 | -describe('streamChatResponse - Mode Switch During Streaming', () => { | |
| 11 | +describe("streamChatResponse - Mode Switch During Streaming", () => { | |
| 8 | 12 | beforeEach(async () => { |
| 9 | 13 | // Clean up service container state before each test |
| 10 | 14 | const services = [ |
| @@ -13,10 +17,10 @@ | ||
| 13 | 17 | SERVICE_NAMES.API_CLIENT, |
| 14 | 18 | SERVICE_NAMES.CONFIG, |
| 15 | 19 | SERVICE_NAMES.MODEL, |
| 16 | - SERVICE_NAMES.MCP | |
| 20 | + SERVICE_NAMES.MCP, | |
| 17 | 21 | ]; |
| 18 | - | |
| 19 | - services.forEach(service => { | |
| 22 | + | |
| 23 | + services.forEach((service) => { | |
| 20 | 24 | (serviceContainer as any).services.delete(service); |
| 21 | 25 | (serviceContainer as any).factories.delete(service); |
| 22 | 26 | (serviceContainer as any).dependencies.delete(service); |
| @@ -26,73 +30,73 @@ | ||
| 26 | 30 | await initializeServices({ |
| 27 | 31 | headless: true, |
| 28 | 32 | toolPermissionOverrides: { |
| 29 | - mode: 'normal' | |
| 30 | - } | |
| 33 | + mode: "normal", | |
| 34 | + }, | |
| 31 | 35 | }); |
| 32 | 36 | }); |
| 33 | 37 | |
| 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 () => { | |
| 35 | 39 | // Start in normal mode |
| 36 | 40 | let tools = await getAllTools(); |
| 37 | - let toolNames = tools.map(t => t.function.name); | |
| 38 | - | |
| 41 | + let toolNames = tools.map((t) => t.function.name); | |
| 42 | + | |
| 39 | 43 | // 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"); | |
| 42 | 46 | |
| 43 | 47 | // Switch to plan mode (simulating Shift+Tab during streaming) |
| 44 | - modeService.switchMode('plan'); | |
| 45 | - | |
| 48 | + modeService.switchMode("plan"); | |
| 49 | + | |
| 46 | 50 | // Update the service container (this is what UserInput.tsx does) |
| 47 | 51 | const updatedState = modeService.getToolPermissionService().getState(); |
| 48 | 52 | serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); |
| 49 | 53 | |
| 50 | 54 | // Recompute tools - should now exclude write tools |
| 51 | 55 | tools = await getAllTools(); |
| 52 | - toolNames = tools.map(t => t.function.name); | |
| 53 | - | |
| 56 | + toolNames = tools.map((t) => t.function.name); | |
| 57 | + | |
| 54 | 58 | // 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 | + | |
| 58 | 62 | // 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"); | |
| 62 | 66 | }); |
| 63 | 67 | |
| 64 | - test('getAllTools reflects current mode immediately', async () => { | |
| 68 | + test("getAllTools reflects current mode immediately", async () => { | |
| 65 | 69 | // Start in normal mode |
| 66 | - expect(modeService.getCurrentMode()).toBe('normal'); | |
| 70 | + expect(modeService.getCurrentMode()).toBe("normal"); | |
| 67 | 71 | let tools = await getAllTools(); |
| 68 | - expect(tools.map(t => t.function.name)).toContain('Write'); | |
| 72 | + expect(tools.map((t) => t.function.name)).toContain("Write"); | |
| 69 | 73 | |
| 70 | 74 | // Switch to plan mode |
| 71 | - modeService.switchMode('plan'); | |
| 75 | + modeService.switchMode("plan"); | |
| 72 | 76 | let updatedState = modeService.getToolPermissionService().getState(); |
| 73 | 77 | serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); |
| 74 | - expect(modeService.getCurrentMode()).toBe('plan'); | |
| 75 | - | |
| 78 | + expect(modeService.getCurrentMode()).toBe("plan"); | |
| 79 | + | |
| 76 | 80 | // getAllTools should immediately reflect the new mode |
| 77 | 81 | 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"); | |
| 79 | 83 | |
| 80 | 84 | // Switch to auto mode |
| 81 | - modeService.switchMode('auto'); | |
| 85 | + modeService.switchMode("auto"); | |
| 82 | 86 | updatedState = modeService.getToolPermissionService().getState(); |
| 83 | 87 | serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); |
| 84 | - expect(modeService.getCurrentMode()).toBe('auto'); | |
| 85 | - | |
| 88 | + expect(modeService.getCurrentMode()).toBe("auto"); | |
| 89 | + | |
| 86 | 90 | // getAllTools should immediately reflect auto mode (all tools allowed) |
| 87 | 91 | 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"); | |
| 91 | 95 | }); |
| 92 | 96 | |
| 93 | - test('demonstrates the fix: no more stale tool lists', async () => { | |
| 97 | + test("demonstrates the fix: no more stale tool lists", async () => { | |
| 94 | 98 | // This test demonstrates that the fix prevents the original race condition |
| 95 | - | |
| 99 | + | |
| 96 | 100 | // Mock a multi-turn conversation scenario |
| 97 | 101 | const mockLlmApi = { |
| 98 | 102 | chatCompletions: { |
| @@ -102,52 +106,65 @@ | ||
| 102 | 106 | [Symbol.asyncIterator]: async function* () { |
| 103 | 107 | // First response - content only |
| 104 | 108 | 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 | + ], | |
| 109 | 115 | }; |
| 110 | - | |
| 116 | + | |
| 111 | 117 | // Second response - indicates tool calls coming |
| 112 | 118 | 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 | + ], | |
| 121 | 136 | }; |
| 122 | 137 | |
| 123 | 138 | // Final response |
| 124 | 139 | yield { |
| 125 | - choices: [{ | |
| 126 | - delta: {}, | |
| 127 | - finish_reason: "tool_calls" | |
| 128 | - }] | |
| 140 | + choices: [ | |
| 141 | + { | |
| 142 | + delta: {}, | |
| 143 | + finish_reason: "tool_calls", | |
| 144 | + }, | |
| 145 | + ], | |
| 129 | 146 | }; |
| 130 | - } | |
| 147 | + }, | |
| 131 | 148 | }; |
| 132 | - }) | |
| 133 | - } | |
| 149 | + }), | |
| 150 | + }, | |
| 134 | 151 | }; |
| 135 | 152 | |
| 136 | 153 | const mockModel = { |
| 137 | 154 | model: "gpt-4", |
| 138 | - defaultCompletionOptions: {} | |
| 155 | + defaultCompletionOptions: {}, | |
| 139 | 156 | }; |
| 140 | 157 | |
| 141 | 158 | const abortController = new AbortController(); |
| 142 | - | |
| 159 | + | |
| 143 | 160 | // Start in normal mode - tools should include Write |
| 144 | 161 | const initialTools = await getAllTools(); |
| 145 | - expect(initialTools.map(t => t.function.name)).toContain('Write'); | |
| 162 | + expect(initialTools.map((t) => t.function.name)).toContain("Write"); | |
| 146 | 163 | |
| 147 | 164 | // During streaming, if mode switches, subsequent iterations should use new tools |
| 148 | 165 | // This is now handled by recomputing tools on each iteration |
| 149 | - | |
| 166 | + | |
| 150 | 167 | // The fix ensures that each call to processStreamingResponse gets fresh tools |
| 151 | 168 | // based on the current mode, preventing the race condition |
| 152 | 169 | }); |
| 153 | -}); | |
| No newline at the end of the file | ||
| 170 | +}); |
modified extensions/cli/src/streamChatResponse.test.ts +36 −37
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | ChatCompletionChunk, |
| 5 | 5 | ChatCompletionMessageParam, |
| 6 | 6 | } from "openai/resources/chat/completions.mjs"; |
| 7 | -import { vi } from 'vitest'; | |
| 7 | +import { vi } from "vitest"; | |
| 8 | 8 | |
| 9 | 9 | import { toolPermissionManager } from "./permissions/permissionManager.js"; |
| 10 | 10 | import { |
| @@ -18,7 +18,6 @@ | ||
| 18 | 18 | import { PreprocessedToolCall } from "./tools/types.js"; |
| 19 | 19 | import { writeFileTool } from "./tools/writeFile.js"; |
| 20 | 20 | |
| 21 | - | |
| 22 | 21 | // Test the chunk processing logic that was identified as buggy |
| 23 | 22 | describe("processStreamingResponse - content preservation", () => { |
| 24 | 23 | // Mock dependencies |
| @@ -49,7 +48,7 @@ | ||
| 49 | 48 | function toolCallChunk( |
| 50 | 49 | id: string, |
| 51 | 50 | name?: string, |
| 52 | - args?: string | |
| 51 | + args?: string, | |
| 53 | 52 | ): ChatCompletionChunk { |
| 54 | 53 | return { |
| 55 | 54 | id: "test", |
| @@ -83,7 +82,7 @@ | ||
| 83 | 82 | index: number, |
| 84 | 83 | id?: string, |
| 85 | 84 | name?: string, |
| 86 | - args?: string | |
| 85 | + args?: string, | |
| 87 | 86 | ): ChatCompletionChunk { |
| 88 | 87 | const toolCall: any = { |
| 89 | 88 | index, |
| @@ -185,27 +184,27 @@ | ||
| 185 | 184 | toolCallChunk( |
| 186 | 185 | "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", |
| 187 | 186 | undefined, |
| 188 | - '{"filepath' | |
| 187 | + '{"filepath', | |
| 189 | 188 | ), |
| 190 | 189 | toolCallChunk( |
| 191 | 190 | "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", |
| 192 | 191 | undefined, |
| 193 | - '": "/Use' | |
| 192 | + '": "/Use', | |
| 194 | 193 | ), |
| 195 | 194 | toolCallChunk( |
| 196 | 195 | "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", |
| 197 | 196 | undefined, |
| 198 | - "rs/nate/gh/c" | |
| 197 | + "rs/nate/gh/c", | |
| 199 | 198 | ), |
| 200 | 199 | toolCallChunk( |
| 201 | 200 | "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", |
| 202 | 201 | undefined, |
| 203 | - "ontinuede" | |
| 202 | + "ontinuede", | |
| 204 | 203 | ), |
| 205 | 204 | toolCallChunk( |
| 206 | 205 | "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", |
| 207 | 206 | undefined, |
| 208 | - "v/cli/README" | |
| 207 | + "v/cli/README", | |
| 209 | 208 | ), |
| 210 | 209 | toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'), |
| 211 | 210 | contentChunk(""), |
| @@ -228,7 +227,7 @@ | ||
| 228 | 227 | // Verify the tool call was assembled correctly |
| 229 | 228 | expect(result.toolCalls[0].name).toBe("Read"); |
| 230 | 229 | expect(result.toolCalls[0].argumentsStr).toBe( |
| 231 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' | |
| 230 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 232 | 231 | ); |
| 233 | 232 | }); |
| 234 | 233 | |
| @@ -257,14 +256,14 @@ | ||
| 257 | 256 | 0, |
| 258 | 257 | "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", |
| 259 | 258 | "Read", |
| 260 | - "" | |
| 259 | + "", | |
| 261 | 260 | ), |
| 262 | 261 | // Subsequent chunks only have index, no ID |
| 263 | 262 | toolCallChunkWithIndex( |
| 264 | 263 | 0, |
| 265 | 264 | undefined, |
| 266 | 265 | undefined, |
| 267 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' | |
| 266 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 268 | 267 | ), |
| 269 | 268 | ]; |
| 270 | 269 | |
| @@ -277,19 +276,19 @@ | ||
| 277 | 276 | |
| 278 | 277 | // Content is captured correctly |
| 279 | 278 | 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!", | |
| 281 | 280 | ); |
| 282 | 281 | expect(result.toolCalls.length).toBe(1); |
| 283 | 282 | |
| 284 | 283 | // Fixed: finalContent preserves content |
| 285 | 284 | 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!", | |
| 287 | 286 | ); |
| 288 | 287 | |
| 289 | 288 | // Tool call arguments are preserved using index mapping |
| 290 | 289 | expect(result.toolCalls[0].name).toBe("Read"); |
| 291 | 290 | expect(result.toolCalls[0].argumentsStr).toBe( |
| 292 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' | |
| 291 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 293 | 292 | ); |
| 294 | 293 | }); |
| 295 | 294 | |
| @@ -302,7 +301,7 @@ | ||
| 302 | 301 | 0, |
| 303 | 302 | "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", |
| 304 | 303 | "Read", |
| 305 | - "" | |
| 304 | + "", | |
| 306 | 305 | ), |
| 307 | 306 | // Subsequent chunks fragment the JSON arguments |
| 308 | 307 | toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'), |
| @@ -328,13 +327,13 @@ | ||
| 328 | 327 | // Fixed: Both issues are resolved |
| 329 | 328 | // 1. Content is preserved |
| 330 | 329 | 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!", | |
| 332 | 331 | ); |
| 333 | 332 | |
| 334 | 333 | // 2. Tool call arguments are assembled correctly |
| 335 | 334 | expect(result.toolCalls[0].name).toBe("Read"); |
| 336 | 335 | expect(result.toolCalls[0].argumentsStr).toBe( |
| 337 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' | |
| 336 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 338 | 337 | ); |
| 339 | 338 | }); |
| 340 | 339 | |
| @@ -352,15 +351,15 @@ | ||
| 352 | 351 | prompt_tokens: 711, |
| 353 | 352 | total_tokens: 807, |
| 354 | 353 | prompt_tokens_details: { |
| 355 | - cached_tokens: 3353 | |
| 356 | - } | |
| 357 | - } | |
| 354 | + cached_tokens: 3353, | |
| 355 | + }, | |
| 356 | + }, | |
| 358 | 357 | }; |
| 359 | 358 | |
| 360 | 359 | chunks = [ |
| 361 | 360 | malformedChunk, // Put malformed chunk first to trigger the bug more clearly |
| 362 | 361 | contentChunk("Hello "), |
| 363 | - contentChunk("world!") | |
| 362 | + contentChunk("world!"), | |
| 364 | 363 | ]; |
| 365 | 364 | |
| 366 | 365 | // This should not throw an error: "Cannot read properties of undefined (reading 'delta')" |
| @@ -440,7 +439,7 @@ | ||
| 440 | 439 | vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce( |
| 441 | 440 | () => { |
| 442 | 441 | throw new Error("Missing required argument"); |
| 443 | - } | |
| 442 | + }, | |
| 444 | 443 | ); |
| 445 | 444 | |
| 446 | 445 | const toolCalls: ToolCall[] = [ |
| @@ -470,7 +469,7 @@ | ||
| 470 | 469 | expect(callbacks.onToolStart).toHaveBeenCalledWith("Read", {}); |
| 471 | 470 | expect(callbacks.onToolError).toHaveBeenCalledWith( |
| 472 | 471 | expect.stringContaining("Missing required argument"), |
| 473 | - "Read" | |
| 472 | + "Read", | |
| 474 | 473 | ); |
| 475 | 474 | }); |
| 476 | 475 | |
| @@ -492,7 +491,7 @@ | ||
| 492 | 491 | expect(preprocessedCalls).toHaveLength(0); |
| 493 | 492 | expect(errorChatEntries).toHaveLength(1); |
| 494 | 493 | expect(errorChatEntries[0].content).toContain( |
| 495 | - "Tool nonexistent_tool not found" | |
| 494 | + "Tool nonexistent_tool not found", | |
| 496 | 495 | ); |
| 497 | 496 | }); |
| 498 | 497 | }); |
| @@ -538,7 +537,7 @@ | ||
| 538 | 537 | |
| 539 | 538 | const { chatHistoryEntries } = await executeStreamedToolCalls( |
| 540 | 539 | preprocessedCalls, |
| 541 | - callbacks | |
| 540 | + callbacks, | |
| 542 | 541 | ); |
| 543 | 542 | |
| 544 | 543 | // Verify results |
| @@ -549,7 +548,7 @@ | ||
| 549 | 548 | }); |
| 550 | 549 | expect(callbacks.onToolResult).toHaveBeenCalledWith( |
| 551 | 550 | "Tool execution successful", |
| 552 | - "Read" | |
| 551 | + "Read", | |
| 553 | 552 | ); |
| 554 | 553 | expect(mockedExecuteToolCall).toHaveBeenCalledWith(preprocessedCalls[0]); |
| 555 | 554 | }); |
| @@ -583,7 +582,7 @@ | ||
| 583 | 582 | }); |
| 584 | 583 | } |
| 585 | 584 | return toolPermissionManager; |
| 586 | - } | |
| 585 | + }, | |
| 587 | 586 | ); |
| 588 | 587 | |
| 589 | 588 | // Create preprocessed tool call |
| @@ -614,7 +613,7 @@ | ||
| 614 | 613 | |
| 615 | 614 | const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls( |
| 616 | 615 | preprocessedCalls, |
| 617 | - callbacks | |
| 616 | + callbacks, | |
| 618 | 617 | ); |
| 619 | 618 | |
| 620 | 619 | // Verify results |
| @@ -622,7 +621,7 @@ | ||
| 622 | 621 | expect(chatHistoryEntries).toHaveLength(2); |
| 623 | 622 | expect(chatHistoryEntries[0].content).toBe("Permission denied by user"); |
| 624 | 623 | expect(chatHistoryEntries[1].content).toBe( |
| 625 | - "Cancelled due to previous tool rejection" | |
| 624 | + "Cancelled due to previous tool rejection", | |
| 626 | 625 | ); |
| 627 | 626 | expect(callbacks.onToolStart).toHaveBeenCalledWith("Write", { |
| 628 | 627 | filepath: "/test.txt", |
| @@ -630,13 +629,13 @@ | ||
| 630 | 629 | }); |
| 631 | 630 | expect(callbacks.onToolResult).toHaveBeenCalledWith( |
| 632 | 631 | "Permission denied by user", |
| 633 | - "Write" | |
| 632 | + "Write", | |
| 634 | 633 | ); |
| 635 | 634 | expect(callbacks.onToolPermissionRequest).toHaveBeenCalledWith( |
| 636 | 635 | "Write", |
| 637 | 636 | { filepath: "/test.txt", content: "data" }, |
| 638 | 637 | "req_123", |
| 639 | - undefined | |
| 638 | + undefined, | |
| 640 | 639 | ); |
| 641 | 640 | }); |
| 642 | 641 | |
| @@ -649,7 +648,7 @@ | ||
| 649 | 648 | |
| 650 | 649 | const toolsModule = await import("./tools/index.js"); |
| 651 | 650 | vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue( |
| 652 | - new Error("Execution failed") | |
| 651 | + new Error("Execution failed"), | |
| 653 | 652 | ); |
| 654 | 653 | |
| 655 | 654 | // Create preprocessed tool call |
| @@ -671,13 +670,13 @@ | ||
| 671 | 670 | |
| 672 | 671 | const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls( |
| 673 | 672 | preprocessedCalls, |
| 674 | - callbacks | |
| 673 | + callbacks, | |
| 675 | 674 | ); |
| 676 | 675 | |
| 677 | 676 | // Verify results |
| 678 | 677 | expect(chatHistoryEntries).toHaveLength(1); |
| 679 | 678 | expect(chatHistoryEntries[0].content).toContain( |
| 680 | - "Error executing tool search_code" | |
| 679 | + "Error executing tool search_code", | |
| 681 | 680 | ); |
| 682 | 681 | expect(chatHistoryEntries[0].content).toContain("Execution failed"); |
| 683 | 682 | expect(callbacks.onToolStart).toHaveBeenCalledWith("search_code", { |
| @@ -685,9 +684,9 @@ | ||
| 685 | 684 | }); |
| 686 | 685 | expect(callbacks.onToolError).toHaveBeenCalledWith( |
| 687 | 686 | expect.stringContaining( |
| 688 | - "Error executing tool search_code: Execution failed" | |
| 687 | + "Error executing tool search_code: Execution failed", | |
| 689 | 688 | ), |
| 690 | - "search_code" | |
| 689 | + "search_code", | |
| 691 | 690 | ); |
| 692 | 691 | }); |
| 693 | 692 | }); |
modified extensions/cli/src/systemMessage.test.ts +8 −4
| @@ -7,13 +7,15 @@ | ||
| 7 | 7 | // Mock the service container to avoid "No factory registered for service 'config'" error |
| 8 | 8 | vi.mock("./services/ServiceContainer.js", () => ({ |
| 9 | 9 | serviceContainer: { |
| 10 | - get: vi.fn().mockResolvedValue({ config: { rules: [] } }) | |
| 11 | - } | |
| 10 | + get: vi.fn().mockResolvedValue({ config: { rules: [] } }), | |
| 11 | + }, | |
| 12 | 12 | })); |
| 13 | 13 | |
| 14 | 14 | // Mock processRule to avoid file system operations in tests |
| 15 | 15 | 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)), | |
| 17 | 19 | })); |
| 18 | 20 | |
| 19 | 21 | describe("constructSystemMessage", () => { |
| @@ -124,7 +126,9 @@ | ||
| 124 | 126 | expect(result).toContain("You are an agent in the Continue CLI"); |
| 125 | 127 | expect(result).toContain("IMPORTANT: You are running in headless mode"); |
| 126 | 128 | 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 | + ); | |
| 128 | 132 | }); |
| 129 | 133 | |
| 130 | 134 | 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 @@ | ||
| 29 | 29 | |
| 30 | 30 | // This should not throw an error |
| 31 | 31 | await expect( |
| 32 | - posthogService.capture("test_event", { test: "data" }) | |
| 32 | + posthogService.capture("test_event", { test: "data" }), | |
| 33 | 33 | ).resolves.toBeUndefined(); |
| 34 | 34 | |
| 35 | 35 | // Verify the client capture was called |
| @@ -68,12 +68,12 @@ | ||
| 68 | 68 | it("should handle getClient errors gracefully", async () => { |
| 69 | 69 | // Mock the getClient method to throw an error |
| 70 | 70 | vi.spyOn(posthogService as any, "getClient").mockRejectedValue( |
| 71 | - new Error("Failed to initialize PostHog client") | |
| 71 | + new Error("Failed to initialize PostHog client"), | |
| 72 | 72 | ); |
| 73 | 73 | |
| 74 | 74 | // This should not throw an error |
| 75 | 75 | await expect( |
| 76 | - posthogService.capture("test_event", { test: "data" }) | |
| 76 | + posthogService.capture("test_event", { test: "data" }), | |
| 77 | 77 | ).resolves.toBeUndefined(); |
| 78 | 78 | }); |
| 79 | 79 | |
| @@ -100,4 +100,4 @@ | ||
| 100 | 100 | process.env.CONTINUE_CLI_ENABLE_TELEMETRY = originalEnv; |
| 101 | 101 | } |
| 102 | 102 | }); |
| 103 | -}); | |
| No newline at the end of the file | ||
| 103 | +}); |
modified extensions/cli/src/telemetry/posthogService.test.ts +4 −3
| @@ -26,7 +26,6 @@ | ||
| 26 | 26 | |
| 27 | 27 | import { PosthogService } from "./posthogService.js"; |
| 28 | 28 | |
| 29 | - | |
| 30 | 29 | describe("PosthogService", () => { |
| 31 | 30 | let tempDir: string; |
| 32 | 31 | |
| @@ -90,7 +89,9 @@ | ||
| 90 | 89 | it("should use machine id when auth config is environment-based", () => { |
| 91 | 90 | const mockMachineId = "test-machine-id"; |
| 92 | 91 | |
| 93 | - vi.mocked(loadAuthConfig).mockReturnValue({ accessToken: "token" } as any); | |
| 92 | + vi.mocked(loadAuthConfig).mockReturnValue({ | |
| 93 | + accessToken: "token", | |
| 94 | + } as any); | |
| 94 | 95 | vi.mocked(isAuthenticatedConfig).mockReturnValue(false); |
| 95 | 96 | vi.mocked(machineIdSync).mockReturnValue(mockMachineId); |
| 96 | 97 | |
| @@ -116,4 +117,4 @@ | ||
| 116 | 117 | expect(service.isEnabled).toBe(false); |
| 117 | 118 | }); |
| 118 | 119 | }); |
| 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", () => { | |
| 3 | 3 | // This utility is tested through its usage in real component tests |
| 4 | 4 | // rather than in isolation due to module mocking complexities |
| 5 | 5 | expect(true).toBe(true); |
| 6 | 6 | }); |
| 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 @@ | ||
| 1 | 1 | import { vi } from "vitest"; |
| 2 | 2 | |
| 3 | -import { createTestServiceContainer } from '../testServiceContainer.js'; | |
| 3 | +import { createTestServiceContainer } from "../testServiceContainer.js"; | |
| 4 | 4 | |
| 5 | -describe('TestServiceContainer', () => { | |
| 5 | +describe("TestServiceContainer", () => { | |
| 6 | 6 | afterEach(() => { |
| 7 | 7 | vi.clearAllTimers(); |
| 8 | 8 | }); |
| 9 | - it('should create a container with extended methods', () => { | |
| 9 | + it("should create a container with extended methods", () => { | |
| 10 | 10 | const container = createTestServiceContainer(); |
| 11 | - | |
| 11 | + | |
| 12 | 12 | expect(container).toBeDefined(); |
| 13 | 13 | expect(container.resolveService).toBeDefined(); |
| 14 | 14 | expect(container.rejectService).toBeDefined(); |
| @@ -16,108 +16,108 @@ | ||
| 16 | 16 | expect(container.waitForService).toBeDefined(); |
| 17 | 17 | }); |
| 18 | 18 | |
| 19 | - it('should allow controlled service resolution', async () => { | |
| 19 | + it("should allow controlled service resolution", async () => { | |
| 20 | 20 | const container = createTestServiceContainer(); |
| 21 | - | |
| 21 | + | |
| 22 | 22 | // Register a service |
| 23 | - container.register('test', () => Promise.resolve('should not resolve')); | |
| 24 | - | |
| 23 | + container.register("test", () => Promise.resolve("should not resolve")); | |
| 24 | + | |
| 25 | 25 | // Load the service - this will create a pending promise |
| 26 | - const loadPromise = container.load('test'); | |
| 27 | - | |
| 26 | + const loadPromise = container.load("test"); | |
| 27 | + | |
| 28 | 28 | // 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 | + | |
| 32 | 32 | // Resolve the service with our controlled value |
| 33 | - container.resolveService('test', 'controlled value'); | |
| 34 | - | |
| 33 | + container.resolveService("test", "controlled value"); | |
| 34 | + | |
| 35 | 35 | // Wait for the load promise to complete |
| 36 | 36 | const loadedValue = await loadPromise; |
| 37 | - expect(loadedValue).toBe('controlled value'); | |
| 38 | - | |
| 37 | + expect(loadedValue).toBe("controlled value"); | |
| 38 | + | |
| 39 | 39 | // 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"); | |
| 43 | 43 | }); |
| 44 | 44 | |
| 45 | - it('should allow controlled service rejection', async () => { | |
| 45 | + it("should allow controlled service rejection", async () => { | |
| 46 | 46 | const container = createTestServiceContainer(); |
| 47 | - | |
| 47 | + | |
| 48 | 48 | // Register a service |
| 49 | - container.register('failing', () => Promise.resolve('should not resolve')); | |
| 50 | - | |
| 49 | + container.register("failing", () => Promise.resolve("should not resolve")); | |
| 50 | + | |
| 51 | 51 | // Load the service and handle the rejection |
| 52 | - const loadPromise = container.load('failing'); | |
| 53 | - | |
| 52 | + const loadPromise = container.load("failing"); | |
| 53 | + | |
| 54 | 54 | // 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 | + | |
| 58 | 58 | // Expect the load promise to reject |
| 59 | - await expect(loadPromise).rejects.toThrow('Controlled failure'); | |
| 60 | - | |
| 59 | + await expect(loadPromise).rejects.toThrow("Controlled failure"); | |
| 60 | + | |
| 61 | 61 | // 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"); | |
| 64 | 64 | expect(result.error).toBe(error); |
| 65 | 65 | }); |
| 66 | 66 | |
| 67 | - it('should wait for multiple services', async () => { | |
| 67 | + it("should wait for multiple services", async () => { | |
| 68 | 68 | const container = createTestServiceContainer(); |
| 69 | - | |
| 69 | + | |
| 70 | 70 | // 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 | + | |
| 75 | 75 | // 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 | + | |
| 80 | 80 | // 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 | + | |
| 85 | 85 | // Wait for all to be ready |
| 86 | - await container.waitForReady('service1', 'service2', 'service3'); | |
| 87 | - | |
| 86 | + await container.waitForReady("service1", "service2", "service3"); | |
| 87 | + | |
| 88 | 88 | // 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); | |
| 92 | 92 | }); |
| 93 | 93 | |
| 94 | - it('should handle pre-resolved services', () => { | |
| 94 | + it("should handle pre-resolved services", () => { | |
| 95 | 95 | const container = createTestServiceContainer(); |
| 96 | - | |
| 96 | + | |
| 97 | 97 | // Register a service that resolves immediately |
| 98 | - container.register('immediate', () => Promise.resolve('immediate value')); | |
| 99 | - | |
| 98 | + container.register("immediate", () => Promise.resolve("immediate value")); | |
| 99 | + | |
| 100 | 100 | // The factory should be replaced with our controlled factory |
| 101 | 101 | // 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"); | |
| 104 | 104 | }); |
| 105 | 105 | |
| 106 | - it('should support waitForService helper', async () => { | |
| 106 | + it("should support waitForService helper", async () => { | |
| 107 | 107 | const container = createTestServiceContainer(); |
| 108 | - | |
| 108 | + | |
| 109 | 109 | // 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 | + | |
| 113 | 113 | // Set up the wait before resolving |
| 114 | - const waitPromise = container.waitForService('async'); | |
| 115 | - | |
| 114 | + const waitPromise = container.waitForService("async"); | |
| 115 | + | |
| 116 | 116 | // Resolve the service |
| 117 | - container.resolveService('async', 'async value'); | |
| 118 | - | |
| 117 | + container.resolveService("async", "async value"); | |
| 118 | + | |
| 119 | 119 | // Wait should resolve with the value |
| 120 | 120 | const value = await waitPromise; |
| 121 | - expect(value).toBe('async value'); | |
| 121 | + expect(value).toBe("async value"); | |
| 122 | 122 | }); |
| 123 | -}); | |
| No newline at the end of the file | ||
| 123 | +}); |
modified extensions/cli/src/tools/edit.test.ts +16 −10
| @@ -50,7 +50,7 @@ | ||
| 50 | 50 | }; |
| 51 | 51 | |
| 52 | 52 | 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.`, | |
| 54 | 54 | ); |
| 55 | 55 | }); |
| 56 | 56 | |
| @@ -66,7 +66,7 @@ | ||
| 66 | 66 | }; |
| 67 | 67 | |
| 68 | 68 | await expect(editTool.preprocess!(args)).rejects.toThrow( |
| 69 | - `File ${nonExistentFile} does not exist` | |
| 69 | + `File ${nonExistentFile} does not exist`, | |
| 70 | 70 | ); |
| 71 | 71 | }); |
| 72 | 72 | |
| @@ -81,7 +81,7 @@ | ||
| 81 | 81 | }; |
| 82 | 82 | |
| 83 | 83 | await expect(editTool.preprocess!(args)).rejects.toThrow( |
| 84 | - "String not found in file: Not found" | |
| 84 | + "String not found in file: Not found", | |
| 85 | 85 | ); |
| 86 | 86 | }); |
| 87 | 87 | |
| @@ -96,7 +96,7 @@ | ||
| 96 | 96 | }; |
| 97 | 97 | |
| 98 | 98 | 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.', | |
| 100 | 100 | ); |
| 101 | 101 | }); |
| 102 | 102 | |
| @@ -110,7 +110,7 @@ | ||
| 110 | 110 | }; |
| 111 | 111 | |
| 112 | 112 | 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", | |
| 114 | 114 | ); |
| 115 | 115 | }); |
| 116 | 116 | |
| @@ -154,7 +154,7 @@ | ||
| 154 | 154 | const result = await editTool.preprocess!(args); |
| 155 | 155 | |
| 156 | 156 | 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", | |
| 158 | 158 | ); |
| 159 | 159 | }); |
| 160 | 160 | }); |
| @@ -170,8 +170,14 @@ | ||
| 170 | 170 | |
| 171 | 171 | const result = await editTool.run(args); |
| 172 | 172 | |
| 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 | + ); | |
| 175 | 181 | }); |
| 176 | 182 | |
| 177 | 183 | it("should throw error if file write fails", async () => { |
| @@ -186,7 +192,7 @@ | ||
| 186 | 192 | }; |
| 187 | 193 | |
| 188 | 194 | await expect(editTool.run(args)).rejects.toThrow( |
| 189 | - `Error: failed to edit ${testFilePath}: Write failed` | |
| 195 | + `Error: failed to edit ${testFilePath}: Write failed`, | |
| 190 | 196 | ); |
| 191 | 197 | }); |
| 192 | 198 | }); |
| @@ -205,4 +211,4 @@ | ||
| 205 | 211 | expect(result.args.newContent).toContain("Hi there"); |
| 206 | 212 | }); |
| 207 | 213 | }); |
| 208 | -}); | |
| No newline at the end of the file | ||
| 214 | +}); |
modified extensions/cli/src/tools/formatters.test.ts +11 −13
| @@ -22,10 +22,10 @@ | ||
| 22 | 22 | |
| 23 | 23 | it("should format tool name with relative path argument", () => { |
| 24 | 24 | expect(formatToolCall("Write", { filepath: "README.md" })).toBe( |
| 25 | - "Write(README.md)" | |
| 25 | + "Write(README.md)", | |
| 26 | 26 | ); |
| 27 | 27 | expect(formatToolCall("Read", { filepath: "src/index.ts" })).toBe( |
| 28 | - "Read(src/index.ts)" | |
| 28 | + "Read(src/index.ts)", | |
| 29 | 29 | ); |
| 30 | 30 | }); |
| 31 | 31 | |
| @@ -33,26 +33,24 @@ | ||
| 33 | 33 | expect( |
| 34 | 34 | formatToolCall("Write", { |
| 35 | 35 | filepath: "/Users/test/project/README.md", |
| 36 | - }) | |
| 36 | + }), | |
| 37 | 37 | ).toBe("Write(README.md)"); |
| 38 | 38 | |
| 39 | 39 | expect( |
| 40 | 40 | formatToolCall("Read", { |
| 41 | 41 | filepath: "/Users/test/project/src/components/App.tsx", |
| 42 | - }) | |
| 42 | + }), | |
| 43 | 43 | ).toBe("Read(src/components/App.tsx)"); |
| 44 | 44 | }); |
| 45 | 45 | |
| 46 | 46 | 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 | + ); | |
| 50 | 50 | }); |
| 51 | 51 | |
| 52 | 52 | 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)"); | |
| 56 | 54 | expect(formatToolCall("Search", { pattern: 123 })).toBe("Search(123)"); |
| 57 | 55 | }); |
| 58 | 56 | |
| @@ -61,7 +59,7 @@ | ||
| 61 | 59 | formatToolCall("Write", { |
| 62 | 60 | filepath: "test.txt", |
| 63 | 61 | content: "Hello world", |
| 64 | - }) | |
| 62 | + }), | |
| 65 | 63 | ).toBe("Write(test.txt)"); |
| 66 | 64 | }); |
| 67 | 65 | }); |
| @@ -82,10 +80,10 @@ | ||
| 82 | 80 | |
| 83 | 81 | it("should convert absolute paths to relative", () => { |
| 84 | 82 | expect(formatToolArgument("/Users/test/project/README.md")).toBe( |
| 85 | - "README.md" | |
| 83 | + "README.md", | |
| 86 | 84 | ); |
| 87 | 85 | expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe( |
| 88 | - "src/index.ts" | |
| 86 | + "src/index.ts", | |
| 89 | 87 | ); |
| 90 | 88 | }); |
| 91 | 89 |
modified extensions/cli/src/tools/multiEdit.test.ts +31 −19
| @@ -54,7 +54,7 @@ | ||
| 54 | 54 | }; |
| 55 | 55 | |
| 56 | 56 | 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.`, | |
| 58 | 58 | ); |
| 59 | 59 | }); |
| 60 | 60 | |
| @@ -74,7 +74,7 @@ | ||
| 74 | 74 | }; |
| 75 | 75 | |
| 76 | 76 | await expect(multiEditTool.preprocess!(args)).rejects.toThrow( |
| 77 | - `File ${nonExistentFile} does not exist` | |
| 77 | + `File ${nonExistentFile} does not exist`, | |
| 78 | 78 | ); |
| 79 | 79 | }); |
| 80 | 80 | |
| @@ -87,7 +87,7 @@ | ||
| 87 | 87 | }; |
| 88 | 88 | |
| 89 | 89 | 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", | |
| 91 | 91 | ); |
| 92 | 92 | }); |
| 93 | 93 | |
| @@ -105,7 +105,7 @@ | ||
| 105 | 105 | }; |
| 106 | 106 | |
| 107 | 107 | await expect(multiEditTool.preprocess!(args)).rejects.toThrow( |
| 108 | - "Edit 1: old_string is required" | |
| 108 | + "Edit 1: old_string is required", | |
| 109 | 109 | ); |
| 110 | 110 | }); |
| 111 | 111 | |
| @@ -123,7 +123,7 @@ | ||
| 123 | 123 | }; |
| 124 | 124 | |
| 125 | 125 | await expect(multiEditTool.preprocess!(args)).rejects.toThrow( |
| 126 | - "Edit 1: new_string is required" | |
| 126 | + "Edit 1: new_string is required", | |
| 127 | 127 | ); |
| 128 | 128 | }); |
| 129 | 129 | |
| @@ -141,7 +141,7 @@ | ||
| 141 | 141 | }; |
| 142 | 142 | |
| 143 | 143 | 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", | |
| 145 | 145 | ); |
| 146 | 146 | }); |
| 147 | 147 | |
| @@ -160,7 +160,7 @@ | ||
| 160 | 160 | }; |
| 161 | 161 | |
| 162 | 162 | 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"', | |
| 164 | 164 | ); |
| 165 | 165 | }); |
| 166 | 166 | |
| @@ -179,7 +179,7 @@ | ||
| 179 | 179 | }; |
| 180 | 180 | |
| 181 | 181 | 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.', | |
| 183 | 183 | ); |
| 184 | 184 | }); |
| 185 | 185 | |
| @@ -236,7 +236,7 @@ | ||
| 236 | 236 | const result = await multiEditTool.preprocess!(args); |
| 237 | 237 | |
| 238 | 238 | 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", | |
| 240 | 240 | ); |
| 241 | 241 | expect(result.args.editCount).toBe(2); |
| 242 | 242 | expect(result.preview?.[0]?.content).toContain("Will apply 2 edits"); |
| @@ -259,7 +259,7 @@ | ||
| 259 | 259 | const result = await multiEditTool.preprocess!(args); |
| 260 | 260 | |
| 261 | 261 | 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", | |
| 263 | 263 | ); |
| 264 | 264 | }); |
| 265 | 265 | |
| @@ -309,7 +309,7 @@ | ||
| 309 | 309 | const result = await multiEditTool.preprocess!(args); |
| 310 | 310 | |
| 311 | 311 | 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", | |
| 313 | 313 | ); |
| 314 | 314 | }); |
| 315 | 315 | }); |
| @@ -327,8 +327,14 @@ | ||
| 327 | 327 | |
| 328 | 328 | const result = await multiEditTool.run(args); |
| 329 | 329 | |
| 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 | + ); | |
| 332 | 338 | }); |
| 333 | 339 | |
| 334 | 340 | it("should return correct message for multiple edits", async () => { |
| @@ -342,7 +348,9 @@ | ||
| 342 | 348 | |
| 343 | 349 | const result = await multiEditTool.run(args); |
| 344 | 350 | |
| 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 | + ); | |
| 346 | 354 | }); |
| 347 | 355 | |
| 348 | 356 | it("should return correct message for new file creation", async () => { |
| @@ -356,7 +364,9 @@ | ||
| 356 | 364 | |
| 357 | 365 | const result = await multiEditTool.run(args); |
| 358 | 366 | |
| 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 | + ); | |
| 360 | 370 | }); |
| 361 | 371 | |
| 362 | 372 | it("should throw error if file write fails", async () => { |
| @@ -373,7 +383,7 @@ | ||
| 373 | 383 | }; |
| 374 | 384 | |
| 375 | 385 | await expect(multiEditTool.run(args)).rejects.toThrow( |
| 376 | - `Error: failed to edit ${testFilePath}: Write failed` | |
| 386 | + `Error: failed to edit ${testFilePath}: Write failed`, | |
| 377 | 387 | ); |
| 378 | 388 | }); |
| 379 | 389 | }); |
| @@ -397,7 +407,9 @@ | ||
| 397 | 407 | const result = await multiEditTool.preprocess!(args); |
| 398 | 408 | |
| 399 | 409 | 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 | + ); | |
| 401 | 413 | }); |
| 402 | 414 | |
| 403 | 415 | it("should handle relative paths with subdirectories", async () => { |
| @@ -462,7 +474,7 @@ | ||
| 462 | 474 | it("should handle relative path for new file creation", async () => { |
| 463 | 475 | const relativePath = "new-file.txt"; |
| 464 | 476 | const absolutePath = path.resolve(process.cwd(), relativePath); |
| 465 | - | |
| 477 | + | |
| 466 | 478 | vi.mocked(fs.existsSync).mockImplementation((path) => { |
| 467 | 479 | // Parent directory (cwd) exists, but file doesn't |
| 468 | 480 | if (path === process.cwd()) return true; |
| @@ -506,4 +518,4 @@ | ||
| 506 | 518 | expect(result.args.newContent).toContain("Hi there"); |
| 507 | 519 | }); |
| 508 | 520 | }); |
| 509 | -}); | |
| No newline at the end of the file | ||
| 521 | +}); |
modified extensions/cli/src/tools/preprocess.test.ts +6 −6
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import * as fs from "fs"; |
| 2 | 2 | |
| 3 | 3 | import * as diff from "diff"; |
| 4 | -import { describe, it, expect, beforeEach, vi } from 'vitest'; | |
| 4 | +import { describe, it, expect, beforeEach, vi } from "vitest"; | |
| 5 | 5 | |
| 6 | 6 | // Mock fs module |
| 7 | 7 | vi.mock("fs", async () => { |
| @@ -397,7 +397,7 @@ | ||
| 397 | 397 | }; |
| 398 | 398 | |
| 399 | 399 | await expect( |
| 400 | - searchAndReplaceInFileTool.preprocess!(args) | |
| 400 | + searchAndReplaceInFileTool.preprocess!(args), | |
| 401 | 401 | ).rejects.toThrowError(/file .* does not exist/); |
| 402 | 402 | }); |
| 403 | 403 | |
| @@ -411,9 +411,9 @@ | ||
| 411 | 411 | }; |
| 412 | 412 | |
| 413 | 413 | await expect( |
| 414 | - searchAndReplaceInFileTool.preprocess!(args) | |
| 414 | + searchAndReplaceInFileTool.preprocess!(args), | |
| 415 | 415 | ).rejects.toThrowError( |
| 416 | - "No complete search/replace blocks found in any diffs" | |
| 416 | + "No complete search/replace blocks found in any diffs", | |
| 417 | 417 | ); |
| 418 | 418 | }); |
| 419 | 419 | |
| @@ -433,7 +433,7 @@ | ||
| 433 | 433 | }; |
| 434 | 434 | |
| 435 | 435 | await expect( |
| 436 | - searchAndReplaceInFileTool.preprocess!(args) | |
| 436 | + searchAndReplaceInFileTool.preprocess!(args), | |
| 437 | 437 | ).rejects.toThrowError(/Search content not found in block 1:/); |
| 438 | 438 | }); |
| 439 | 439 | |
| @@ -461,7 +461,7 @@ | ||
| 461 | 461 | const result = await searchAndReplaceInFileTool.preprocess!(args); |
| 462 | 462 | |
| 463 | 463 | 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", | |
| 465 | 465 | ); |
| 466 | 466 | }); |
| 467 | 467 | }); |
modified extensions/cli/src/tools/runTerminalCommand.test.ts +118 −83
| @@ -2,9 +2,9 @@ | ||
| 2 | 2 | |
| 3 | 3 | describe("runTerminalCommandTool", () => { |
| 4 | 4 | const TEST_TIMEOUT_MS = 1000; // 1 second for tests |
| 5 | - | |
| 5 | + | |
| 6 | 6 | beforeAll(() => { |
| 7 | - process.env.NODE_ENV = 'test'; | |
| 7 | + process.env.NODE_ENV = "test"; | |
| 8 | 8 | process.env.TEST_TERMINAL_TIMEOUT = String(TEST_TIMEOUT_MS); |
| 9 | 9 | }); |
| 10 | 10 | |
| @@ -13,7 +13,9 @@ | ||
| 13 | 13 | }); |
| 14 | 14 | describe("basic command execution", () => { |
| 15 | 15 | 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 | + }); | |
| 17 | 19 | expect(result.trim()).toBe("hello world"); |
| 18 | 20 | }); |
| 19 | 21 | |
| @@ -24,11 +26,11 @@ | ||
| 24 | 26 | |
| 25 | 27 | it("should execute directory listing command and return file listings", async () => { |
| 26 | 28 | // 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 ."; | |
| 28 | 30 | const result = await runTerminalCommandTool.run({ command }); |
| 29 | - | |
| 31 | + | |
| 30 | 32 | // On Windows, look for <DIR> entries, on Unix look for . and .. |
| 31 | - if (process.platform === 'win32') { | |
| 33 | + if (process.platform === "win32") { | |
| 32 | 34 | expect(result).toContain("."); |
| 33 | 35 | } else { |
| 34 | 36 | expect(result).toContain("."); |
| @@ -37,99 +39,131 @@ | ||
| 37 | 39 | }); |
| 38 | 40 | |
| 39 | 41 | 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 | + }); | |
| 41 | 45 | expect(result.trim()).toBe("arg1 arg2 arg3"); |
| 42 | 46 | }); |
| 43 | 47 | }); |
| 44 | 48 | |
| 45 | 49 | describe("error handling", () => { |
| 46 | 50 | 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\):/); | |
| 49 | 54 | }); |
| 50 | 55 | |
| 51 | 56 | 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/); | |
| 54 | 62 | }); |
| 55 | 63 | |
| 56 | 64 | 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 | + }); | |
| 58 | 68 | expect(result).toBe(""); |
| 59 | 69 | }); |
| 60 | 70 | |
| 61 | 71 | 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 | + }); | |
| 63 | 75 | expect(result).toContain("success"); |
| 64 | 76 | expect(result).toContain("Stderr: error message"); |
| 65 | 77 | }); |
| 66 | 78 | }); |
| 67 | 79 | |
| 68 | 80 | 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 | |
| 127 | 161 | }); |
| 128 | 162 | |
| 129 | 163 | describe("output handling", () => { |
| 130 | 164 | 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'", | |
| 133 | 167 | }); |
| 134 | 168 | expect(result).toContain("line1\nline2\nline3"); |
| 135 | 169 | }); |
| @@ -141,13 +175,13 @@ | ||
| 141 | 175 | |
| 142 | 176 | it("should handle large output", async () => { |
| 143 | 177 | // 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", | |
| 146 | 180 | }); |
| 147 | 181 | expect(result).toContain("1\n"); |
| 148 | 182 | expect(result).toContain("1000"); |
| 149 | 183 | // Count lines to ensure all output is captured |
| 150 | - const lines = result.trim().split('\n'); | |
| 184 | + const lines = result.trim().split("\n"); | |
| 151 | 185 | expect(lines).toHaveLength(1000); |
| 152 | 186 | }); |
| 153 | 187 | }); |
| @@ -159,24 +193,25 @@ | ||
| 159 | 193 | }); |
| 160 | 194 | |
| 161 | 195 | 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", | |
| 164 | 198 | }); |
| 165 | 199 | expect(result.trim()).toBe("2"); |
| 166 | 200 | }); |
| 167 | 201 | |
| 168 | 202 | 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", | |
| 171 | 206 | }); |
| 172 | 207 | expect(result.trim()).toBe("test"); |
| 173 | 208 | }); |
| 174 | 209 | |
| 175 | 210 | 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'", | |
| 178 | 213 | }); |
| 179 | 214 | expect(result.trim()).toBe("hello"); |
| 180 | 215 | }); |
| 181 | 216 | }); |
| 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 | - | |
| 2 | 1 | // Since we want to test just the interface and not the internals, |
| 3 | 2 | // let's create a simplified version of the run function to test the truncation logic |
| 4 | 3 | describe("searchCodeTool", () => { |
| 5 | 4 | // 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 | |
| 7 | 6 | // if truncation happens with large outputs |
| 8 | 7 | |
| 9 | 8 | it("should include truncation message when output exceeds limit", () => { |
| 10 | 9 | // 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';`, | |
| 13 | 13 | ).join("\n"); |
| 14 | - | |
| 14 | + | |
| 15 | 15 | // 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 | + | |
| 18 | 18 | // 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 | + | |
| 22 | 22 | // Count the content lines (excluding header and truncation message) |
| 23 | 23 | const contentLines = nonEmptyLines.slice(1, -1); |
| 24 | - | |
| 24 | + | |
| 25 | 25 | // Check that we have exactly 100 content lines |
| 26 | 26 | expect(contentLines.length).toBe(100); |
| 27 | - | |
| 27 | + | |
| 28 | 28 | // 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 | + ); | |
| 30 | 32 | }); |
| 31 | 33 | |
| 32 | 34 | it("should not include truncation message when output is within limit", () => { |
| 33 | 35 | // 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';`, | |
| 36 | 39 | ).join("\n"); |
| 37 | - | |
| 40 | + | |
| 38 | 41 | // Format the output as the function would |
| 39 | 42 | const output = `Search results for pattern "foo":\n\n${smallOutput}`; |
| 40 | - | |
| 43 | + | |
| 41 | 44 | // Verify no truncation message is included |
| 42 | 45 | expect(output).not.toContain("[Results truncated:"); |
| 43 | - | |
| 46 | + | |
| 44 | 47 | // 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 | + | |
| 48 | 51 | // Check that we have the expected number of lines (header + 50 content lines) |
| 49 | 52 | expect(nonEmptyLines.length).toBe(51); |
| 50 | 53 | }); |
| 51 | -}); | |
| No newline at the end of the file | ||
| 54 | +}); |
modified extensions/cli/src/ui/ColoredDiff.test.ts +52 −28
| @@ -11,10 +11,12 @@ | ||
| 11 | 11 | return "world"; |
| 12 | 12 | }`; |
| 13 | 13 | |
| 14 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 14 | + const { lastFrame } = render( | |
| 15 | + React.createElement(ColoredDiff, { diffContent }), | |
| 16 | + ); | |
| 15 | 17 | const frame = lastFrame(); |
| 16 | 18 | |
| 17 | - expect(frame).toContain("console.log(\"added line\")"); | |
| 19 | + expect(frame).toContain('console.log("added line")'); | |
| 18 | 20 | expect(frame).toContain("+"); |
| 19 | 21 | }); |
| 20 | 22 | |
| @@ -25,10 +27,12 @@ | ||
| 25 | 27 | return "world"; |
| 26 | 28 | }`; |
| 27 | 29 | |
| 28 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 30 | + const { lastFrame } = render( | |
| 31 | + React.createElement(ColoredDiff, { diffContent }), | |
| 32 | + ); | |
| 29 | 33 | const frame = lastFrame(); |
| 30 | 34 | |
| 31 | - expect(frame).toContain("console.log(\"removed line\")"); | |
| 35 | + expect(frame).toContain('console.log("removed line")'); | |
| 32 | 36 | expect(frame).toContain("-"); |
| 33 | 37 | }); |
| 34 | 38 | |
| @@ -40,11 +44,13 @@ | ||
| 40 | 44 | return "world"; |
| 41 | 45 | }`; |
| 42 | 46 | |
| 43 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 47 | + const { lastFrame } = render( | |
| 48 | + React.createElement(ColoredDiff, { diffContent }), | |
| 49 | + ); | |
| 44 | 50 | const frame = lastFrame(); |
| 45 | 51 | |
| 46 | 52 | expect(frame).toContain("function hello()"); |
| 47 | - expect(frame).toContain("return \"world\""); | |
| 53 | + expect(frame).toContain('return "world"'); | |
| 48 | 54 | }); |
| 49 | 55 | |
| 50 | 56 | it("renders word-level diffs for modified lines", () => { |
| @@ -54,18 +60,22 @@ | ||
| 54 | 60 | + return "new text"; |
| 55 | 61 | }`; |
| 56 | 62 | |
| 57 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 63 | + const { lastFrame } = render( | |
| 64 | + React.createElement(ColoredDiff, { diffContent }), | |
| 65 | + ); | |
| 58 | 66 | const frame = lastFrame(); |
| 59 | 67 | |
| 60 | - expect(frame).toContain("return \""); | |
| 61 | - expect(frame).toContain("text\""); | |
| 68 | + expect(frame).toContain('return "'); | |
| 69 | + expect(frame).toContain('text"'); | |
| 62 | 70 | // Should show both old and new versions for word-level diff |
| 63 | 71 | expect(frame).toContain("-"); |
| 64 | 72 | expect(frame).toContain("+"); |
| 65 | 73 | }); |
| 66 | 74 | |
| 67 | 75 | it("handles empty diff content", () => { |
| 68 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent: "" })); | |
| 76 | + const { lastFrame } = render( | |
| 77 | + React.createElement(ColoredDiff, { diffContent: "" }), | |
| 78 | + ); | |
| 69 | 79 | const frame = lastFrame(); |
| 70 | 80 | |
| 71 | 81 | expect(frame).toContain("No changes detected"); |
| @@ -73,13 +83,17 @@ | ||
| 73 | 83 | |
| 74 | 84 | it("truncates long diffs", () => { |
| 75 | 85 | // 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 | + ); | |
| 77 | 89 | const diffContent = `@@ -1,1 +1,20 @@ |
| 78 | 90 | function hello() { |
| 79 | 91 | ${lines} |
| 80 | 92 | }`; |
| 81 | 93 | |
| 82 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 94 | + const { lastFrame } = render( | |
| 95 | + React.createElement(ColoredDiff, { diffContent }), | |
| 96 | + ); | |
| 83 | 97 | const frame = lastFrame(); |
| 84 | 98 | |
| 85 | 99 | expect(frame).toContain("more lines"); |
| @@ -95,13 +109,15 @@ | ||
| 95 | 109 | return x + y; |
| 96 | 110 | }`; |
| 97 | 111 | |
| 98 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 112 | + const { lastFrame } = render( | |
| 113 | + React.createElement(ColoredDiff, { diffContent }), | |
| 114 | + ); | |
| 99 | 115 | const frame = lastFrame(); |
| 100 | 116 | |
| 101 | 117 | // 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'); | |
| 105 | 121 | }); |
| 106 | 122 | |
| 107 | 123 | it("handles single-type changes without word-level diffing", () => { |
| @@ -112,12 +128,14 @@ | ||
| 112 | 128 | return "world"; |
| 113 | 129 | }`; |
| 114 | 130 | |
| 115 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 131 | + const { lastFrame } = render( | |
| 132 | + React.createElement(ColoredDiff, { diffContent }), | |
| 133 | + ); | |
| 116 | 134 | const frame = lastFrame(); |
| 117 | 135 | |
| 118 | 136 | // 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")'); | |
| 121 | 139 | expect(frame).toContain("+"); |
| 122 | 140 | }); |
| 123 | 141 | |
| @@ -128,7 +146,9 @@ | ||
| 128 | 146 | + return "new text"; |
| 129 | 147 | }`; |
| 130 | 148 | |
| 131 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 149 | + const { lastFrame } = render( | |
| 150 | + React.createElement(ColoredDiff, { diffContent }), | |
| 151 | + ); | |
| 132 | 152 | const frame = lastFrame(); |
| 133 | 153 | |
| 134 | 154 | // Extract just the line numbers and content, ignoring colors/styling |
| @@ -136,8 +156,8 @@ | ||
| 136 | 156 | expect(frame).toContain("function hello()"); |
| 137 | 157 | expect(frame).toContain("- "); |
| 138 | 158 | expect(frame).toContain("+ "); |
| 139 | - expect(frame).toContain("return \""); | |
| 140 | - expect(frame).toContain("text\""); | |
| 159 | + expect(frame).toContain('return "'); | |
| 160 | + expect(frame).toContain('text"'); | |
| 141 | 161 | |
| 142 | 162 | // Verify we have both old and new text content |
| 143 | 163 | // Word-level diff splits these into separate words |
| @@ -156,20 +176,22 @@ | ||
| 156 | 176 | +const y = "hello universe"; |
| 157 | 177 | const z = 3;`; |
| 158 | 178 | |
| 159 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 179 | + const { lastFrame } = render( | |
| 180 | + React.createElement(ColoredDiff, { diffContent }), | |
| 181 | + ); | |
| 160 | 182 | const frame = lastFrame(); |
| 161 | 183 | |
| 162 | 184 | // All original text should be preserved |
| 163 | 185 | expect(frame).toContain("const x = 1"); |
| 164 | 186 | expect(frame).toContain("const z = 3"); |
| 165 | - | |
| 187 | + | |
| 166 | 188 | // Both old and new versions should be shown |
| 167 | 189 | // Word-level diff splits these into separate words |
| 168 | 190 | expect(frame).toContain("hello"); |
| 169 | 191 | expect(frame).toContain("world"); |
| 170 | 192 | expect(frame).toContain("universe"); |
| 171 | - expect(frame).toContain("const y = \""); | |
| 172 | - | |
| 193 | + expect(frame).toContain('const y = "'); | |
| 194 | + | |
| 173 | 195 | // Should have proper line prefixes |
| 174 | 196 | expect(frame).toContain("- "); |
| 175 | 197 | expect(frame).toContain("+ "); |
| @@ -184,7 +206,9 @@ | ||
| 184 | 206 | + return result.data; |
| 185 | 207 | }`; |
| 186 | 208 | |
| 187 | - const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); | |
| 209 | + const { lastFrame } = render( | |
| 210 | + React.createElement(ColoredDiff, { diffContent }), | |
| 211 | + ); | |
| 188 | 212 | const frame = lastFrame(); |
| 189 | 213 | |
| 190 | 214 | // Check that all unique content appears |
| @@ -204,4 +228,4 @@ | ||
| 204 | 228 | expect(frame).toContain("- "); |
| 205 | 229 | expect(frame).toContain("+ "); |
| 206 | 230 | }); |
| 207 | -}); | |
| No newline at the end of the file | ||
| 231 | +}); |
modified extensions/cli/src/ui/MarkdownRenderer.test.tsx +3 −3
| @@ -132,13 +132,13 @@ | ||
| 132 | 132 | |
| 133 | 133 | it("handles headings with multiple words", () => { |
| 134 | 134 | const result = renderMarkdown( |
| 135 | - "# This is a long heading with multiple words" | |
| 135 | + "# This is a long heading with multiple words", | |
| 136 | 136 | ); |
| 137 | 137 | expect(result.length).toBe(1); |
| 138 | 138 | expect(React.isValidElement(result[0])).toBe(true); |
| 139 | 139 | expect((result[0] as any).props.bold).toBe(true); |
| 140 | 140 | 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", | |
| 142 | 142 | ); |
| 143 | 143 | }); |
| 144 | 144 | |
| @@ -183,7 +183,7 @@ | ||
| 183 | 183 | |
| 184 | 184 | it("handles code blocks mixed with other formatting", () => { |
| 185 | 185 | 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", | |
| 187 | 187 | ); |
| 188 | 188 | expect(result.length).toBe(5); |
| 189 | 189 | 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"; | |
| 4 | 4 | |
| 5 | -import { ModelCapabilityWarning } from './ModelCapabilityWarning.js'; | |
| 5 | +import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js"; | |
| 6 | 6 | |
| 7 | -describe('ModelCapabilityWarning', () => { | |
| 8 | - test('should render warning message with model name', () => { | |
| 7 | +describe("ModelCapabilityWarning", () => { | |
| 8 | + test("should render warning message with model name", () => { | |
| 9 | 9 | const { lastFrame } = render( |
| 10 | - React.createElement(ModelCapabilityWarning, { modelName: 'gpt-3-davinci' }) | |
| 10 | + React.createElement(ModelCapabilityWarning, { | |
| 11 | + modelName: "gpt-3-davinci", | |
| 12 | + }), | |
| 11 | 13 | ); |
| 12 | - | |
| 14 | + | |
| 13 | 15 | const frame = lastFrame(); |
| 14 | 16 | 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"); | |
| 19 | 23 | } |
| 20 | 24 | }); |
| 21 | 25 | |
| 22 | - test('should handle model names with slashes', () => { | |
| 26 | + test("should handle model names with slashes", () => { | |
| 23 | 27 | const { lastFrame } = render( |
| 24 | - React.createElement(ModelCapabilityWarning, { modelName: 'local/mistral-7b' }) | |
| 28 | + React.createElement(ModelCapabilityWarning, { | |
| 29 | + modelName: "local/mistral-7b", | |
| 30 | + }), | |
| 25 | 31 | ); |
| 26 | - | |
| 32 | + | |
| 27 | 33 | const frame = lastFrame(); |
| 28 | 34 | if (frame) { |
| 29 | - expect(frame).toContain('local/mistral-7b'); | |
| 35 | + expect(frame).toContain("local/mistral-7b"); | |
| 30 | 36 | } |
| 31 | 37 | }); |
| 32 | 38 | |
| 33 | - test('should display warning icon', () => { | |
| 39 | + test("should display warning icon", () => { | |
| 34 | 40 | const { lastFrame } = render( |
| 35 | - React.createElement(ModelCapabilityWarning, { modelName: 'test-model' }) | |
| 41 | + React.createElement(ModelCapabilityWarning, { modelName: "test-model" }), | |
| 36 | 42 | ); |
| 37 | - | |
| 43 | + | |
| 38 | 44 | const frame = lastFrame(); |
| 39 | 45 | if (frame) { |
| 40 | - expect(frame).toContain('⚠️'); | |
| 46 | + expect(frame).toContain("⚠️"); | |
| 41 | 47 | } |
| 42 | 48 | }); |
| 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"; | |
| 8 | 2 | import { render } from "ink-testing-library"; |
| 9 | 3 | import React from "react"; |
| 10 | 4 | import { describe, expect, it, vi, beforeEach } from "vitest"; |
| @@ -38,7 +32,7 @@ | ||
| 38 | 32 | firstUserMessage: "Today's session", |
| 39 | 33 | }, |
| 40 | 34 | { |
| 41 | - id: "session-2", | |
| 35 | + id: "session-2", | |
| 42 | 36 | path: "/test/session-2.json", |
| 43 | 37 | timestamp: yesterday, |
| 44 | 38 | messageCount: 5, |
| @@ -47,7 +41,7 @@ | ||
| 47 | 41 | { |
| 48 | 42 | id: "session-3", |
| 49 | 43 | path: "/test/session-3.json", |
| 50 | - timestamp: thisWeek, | |
| 44 | + timestamp: thisWeek, | |
| 51 | 45 | messageCount: 8, |
| 52 | 46 | firstUserMessage: "This week's session", |
| 53 | 47 | }, |
| @@ -56,7 +50,7 @@ | ||
| 56 | 50 | path: "/test/session-4.json", |
| 57 | 51 | timestamp: thisYear, |
| 58 | 52 | messageCount: 12, |
| 59 | - firstUserMessage: "This year's session", | |
| 53 | + firstUserMessage: "This year's session", | |
| 60 | 54 | }, |
| 61 | 55 | { |
| 62 | 56 | id: "session-5", |
| @@ -68,35 +62,35 @@ | ||
| 68 | 62 | ]; |
| 69 | 63 | |
| 70 | 64 | const { lastFrame } = render( |
| 71 | - <SessionSelector | |
| 65 | + <SessionSelector | |
| 72 | 66 | sessions={sessions} |
| 73 | 67 | onSelect={mockOnSelect} |
| 74 | 68 | onExit={mockOnExit} |
| 75 | - /> | |
| 69 | + />, | |
| 76 | 70 | ); |
| 77 | 71 | |
| 78 | 72 | // Check that the output contains expected date formats |
| 79 | 73 | expect(lastFrame()).toContain("2:00 PM"); // Today should show time |
| 80 | 74 | expect(lastFrame()).toContain("yesterday"); // Yesterday should show "yesterday" |
| 81 | - | |
| 75 | + | |
| 82 | 76 | // This week should show day name (we can't predict exact day without knowing when test runs) |
| 83 | 77 | // but we can check it doesn't contain "ago" which was the old format |
| 84 | 78 | expect(lastFrame()).not.toContain("days ago"); |
| 85 | - | |
| 79 | + | |
| 86 | 80 | // This year should show month/day format like "Oct 18" (no "ago") |
| 87 | 81 | expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}/); // MMM d format |
| 88 | - | |
| 82 | + | |
| 89 | 83 | // Last year should include the year |
| 90 | 84 | expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}, \d{4}/); // MMM d, yyyy format |
| 91 | 85 | }); |
| 92 | 86 | |
| 93 | 87 | it("handles empty sessions gracefully", () => { |
| 94 | 88 | const { lastFrame } = render( |
| 95 | - <SessionSelector | |
| 89 | + <SessionSelector | |
| 96 | 90 | sessions={[]} |
| 97 | 91 | onSelect={mockOnSelect} |
| 98 | 92 | onExit={mockOnExit} |
| 99 | - /> | |
| 93 | + />, | |
| 100 | 94 | ); |
| 101 | 95 | |
| 102 | 96 | expect(lastFrame()).toContain("No previous sessions found"); |
| @@ -115,13 +109,13 @@ | ||
| 115 | 109 | ]; |
| 116 | 110 | |
| 117 | 111 | const { lastFrame } = render( |
| 118 | - <SessionSelector | |
| 112 | + <SessionSelector | |
| 119 | 113 | sessions={sessions} |
| 120 | 114 | onSelect={mockOnSelect} |
| 121 | 115 | onExit={mockOnExit} |
| 122 | - /> | |
| 116 | + />, | |
| 123 | 117 | ); |
| 124 | 118 | |
| 125 | 119 | expect(lastFrame()).toContain("(no messages)"); |
| 126 | 120 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -describe('detectLanguage', () => { | |
| 4 | - it('should detect JavaScript from import statements', () => { | |
| 3 | +describe("detectLanguage", () => { | |
| 4 | + it("should detect JavaScript from import statements", () => { | |
| 5 | 5 | const code = `import React from 'react';`; |
| 6 | - expect(detectLanguage(code)).toBe('javascript'); | |
| 6 | + expect(detectLanguage(code)).toBe("javascript"); | |
| 7 | 7 | }); |
| 8 | 8 | |
| 9 | - it('should detect JavaScript from require statements', () => { | |
| 9 | + it("should detect JavaScript from require statements", () => { | |
| 10 | 10 | const code = `const fs = require('fs');`; |
| 11 | - expect(detectLanguage(code)).toBe('javascript'); | |
| 11 | + expect(detectLanguage(code)).toBe("javascript"); | |
| 12 | 12 | }); |
| 13 | 13 | |
| 14 | - it('should detect JavaScript from function declarations', () => { | |
| 14 | + it("should detect JavaScript from function declarations", () => { | |
| 15 | 15 | const code = `function myFunction() { return true; }`; |
| 16 | - expect(detectLanguage(code)).toBe('javascript'); | |
| 16 | + expect(detectLanguage(code)).toBe("javascript"); | |
| 17 | 17 | }); |
| 18 | 18 | |
| 19 | - it('should detect TypeScript from interface declarations', () => { | |
| 19 | + it("should detect TypeScript from interface declarations", () => { | |
| 20 | 20 | const code = `interface User { name: string; }`; |
| 21 | - expect(detectLanguage(code)).toBe('typescript'); | |
| 21 | + expect(detectLanguage(code)).toBe("typescript"); | |
| 22 | 22 | }); |
| 23 | 23 | |
| 24 | - it('should detect TypeScript from type declarations', () => { | |
| 24 | + it("should detect TypeScript from type declarations", () => { | |
| 25 | 25 | const code = `type UserType = { name: string; };`; |
| 26 | - expect(detectLanguage(code)).toBe('typescript'); | |
| 26 | + expect(detectLanguage(code)).toBe("typescript"); | |
| 27 | 27 | }); |
| 28 | 28 | |
| 29 | - it('should detect Python from function definitions', () => { | |
| 29 | + it("should detect Python from function definitions", () => { | |
| 30 | 30 | const code = `def my_function(): |
| 31 | 31 | return True`; |
| 32 | - expect(detectLanguage(code)).toBe('python'); | |
| 32 | + expect(detectLanguage(code)).toBe("python"); | |
| 33 | 33 | }); |
| 34 | 34 | |
| 35 | - it('should detect Python from class definitions', () => { | |
| 35 | + it("should detect Python from class definitions", () => { | |
| 36 | 36 | const code = `class MyClass: |
| 37 | 37 | def __init__(self): |
| 38 | 38 | pass`; |
| 39 | - expect(detectLanguage(code)).toBe('python'); | |
| 39 | + expect(detectLanguage(code)).toBe("python"); | |
| 40 | 40 | }); |
| 41 | 41 | |
| 42 | - it('should detect Java from public class declarations', () => { | |
| 42 | + it("should detect Java from public class declarations", () => { | |
| 43 | 43 | const code = `public class MyClass { |
| 44 | 44 | public static void main(String[] args) { |
| 45 | 45 | } |
| 46 | 46 | }`; |
| 47 | - expect(detectLanguage(code)).toBe('java'); | |
| 47 | + expect(detectLanguage(code)).toBe("java"); | |
| 48 | 48 | }); |
| 49 | 49 | |
| 50 | - it('should detect C from include statements', () => { | |
| 50 | + it("should detect C from include statements", () => { | |
| 51 | 51 | const code = `#include <stdio.h> |
| 52 | 52 | int main() { |
| 53 | 53 | return 0; |
| 54 | 54 | }`; |
| 55 | - expect(detectLanguage(code)).toBe('c'); | |
| 55 | + expect(detectLanguage(code)).toBe("c"); | |
| 56 | 56 | }); |
| 57 | 57 | |
| 58 | - it('should detect C++ from using namespace', () => { | |
| 58 | + it("should detect C++ from using namespace", () => { | |
| 59 | 59 | const code = `using namespace std; |
| 60 | 60 | int main() { |
| 61 | 61 | return 0; |
| 62 | 62 | }`; |
| 63 | - expect(detectLanguage(code)).toBe('cpp'); | |
| 63 | + expect(detectLanguage(code)).toBe("cpp"); | |
| 64 | 64 | }); |
| 65 | 65 | |
| 66 | - it('should detect C# from using System', () => { | |
| 66 | + it("should detect C# from using System", () => { | |
| 67 | 67 | const code = `using System; |
| 68 | 68 | public class Program { |
| 69 | 69 | public static void Main() { |
| 70 | 70 | } |
| 71 | 71 | }`; |
| 72 | - expect(detectLanguage(code)).toBe('csharp'); | |
| 72 | + expect(detectLanguage(code)).toBe("csharp"); | |
| 73 | 73 | }); |
| 74 | 74 | |
| 75 | - it('should detect Go from package main', () => { | |
| 75 | + it("should detect Go from package main", () => { | |
| 76 | 76 | const code = `package main |
| 77 | 77 | import "fmt" |
| 78 | 78 | func main() { |
| 79 | 79 | fmt.Println("Hello, World!") |
| 80 | 80 | }`; |
| 81 | - expect(detectLanguage(code)).toBe('go'); | |
| 81 | + expect(detectLanguage(code)).toBe("go"); | |
| 82 | 82 | }); |
| 83 | 83 | |
| 84 | - it('should detect Rust from function syntax', () => { | |
| 84 | + it("should detect Rust from function syntax", () => { | |
| 85 | 85 | const code = `fn main() { |
| 86 | 86 | println!("Hello, World!"); |
| 87 | 87 | }`; |
| 88 | - expect(detectLanguage(code)).toBe('rust'); | |
| 88 | + expect(detectLanguage(code)).toBe("rust"); | |
| 89 | 89 | }); |
| 90 | 90 | |
| 91 | - it('should detect PHP from opening tag', () => { | |
| 91 | + it("should detect PHP from opening tag", () => { | |
| 92 | 92 | const code = `<?php |
| 93 | 93 | echo "Hello, World!"; |
| 94 | 94 | ?>`; |
| 95 | - expect(detectLanguage(code)).toBe('php'); | |
| 95 | + expect(detectLanguage(code)).toBe("php"); | |
| 96 | 96 | }); |
| 97 | 97 | |
| 98 | - it('should detect SQL from SELECT statements', () => { | |
| 98 | + it("should detect SQL from SELECT statements", () => { | |
| 99 | 99 | const code = `SELECT * FROM users WHERE id = 1;`; |
| 100 | - expect(detectLanguage(code)).toBe('sql'); | |
| 100 | + expect(detectLanguage(code)).toBe("sql"); | |
| 101 | 101 | }); |
| 102 | 102 | |
| 103 | - it('should detect SQL with case insensitive matching', () => { | |
| 103 | + it("should detect SQL with case insensitive matching", () => { | |
| 104 | 104 | const code = `select name from users where active = true;`; |
| 105 | - expect(detectLanguage(code)).toBe('sql'); | |
| 105 | + expect(detectLanguage(code)).toBe("sql"); | |
| 106 | 106 | }); |
| 107 | 107 | |
| 108 | - it('should detect JSON from object syntax', () => { | |
| 108 | + it("should detect JSON from object syntax", () => { | |
| 109 | 109 | const code = `{ |
| 110 | 110 | "name": "John", |
| 111 | 111 | "age": 30 |
| 112 | 112 | }`; |
| 113 | - expect(detectLanguage(code)).toBe('json'); | |
| 113 | + expect(detectLanguage(code)).toBe("json"); | |
| 114 | 114 | }); |
| 115 | 115 | |
| 116 | - it('should detect bash from shebang', () => { | |
| 116 | + it("should detect bash from shebang", () => { | |
| 117 | 117 | const code = `#!/bin/bash |
| 118 | 118 | echo "Hello, World!"`; |
| 119 | - expect(detectLanguage(code)).toBe('bash'); | |
| 119 | + expect(detectLanguage(code)).toBe("bash"); | |
| 120 | 120 | }); |
| 121 | 121 | |
| 122 | - it('should detect HTML from DOCTYPE', () => { | |
| 122 | + it("should detect HTML from DOCTYPE", () => { | |
| 123 | 123 | const code = `<!DOCTYPE html> |
| 124 | 124 | <html> |
| 125 | 125 | <head> |
| 126 | 126 | <title>Test</title> |
| 127 | 127 | </head> |
| 128 | 128 | </html>`; |
| 129 | - expect(detectLanguage(code)).toBe('html'); | |
| 129 | + expect(detectLanguage(code)).toBe("html"); | |
| 130 | 130 | }); |
| 131 | 131 | |
| 132 | - it('should detect HTML from html tag', () => { | |
| 132 | + it("should detect HTML from html tag", () => { | |
| 133 | 133 | const code = `<html> |
| 134 | 134 | <body> |
| 135 | 135 | <h1>Hello</h1> |
| 136 | 136 | </body> |
| 137 | 137 | </html>`; |
| 138 | - expect(detectLanguage(code)).toBe('html'); | |
| 138 | + expect(detectLanguage(code)).toBe("html"); | |
| 139 | 139 | }); |
| 140 | 140 | |
| 141 | - it('should detect CSS from media queries', () => { | |
| 141 | + it("should detect CSS from media queries", () => { | |
| 142 | 142 | const code = `@media screen and (max-width: 600px) { |
| 143 | 143 | body { |
| 144 | 144 | font-size: 14px; |
| 145 | 145 | } |
| 146 | 146 | }`; |
| 147 | - expect(detectLanguage(code)).toBe('css'); | |
| 147 | + expect(detectLanguage(code)).toBe("css"); | |
| 148 | 148 | }); |
| 149 | 149 | |
| 150 | - it('should detect Markdown from headers', () => { | |
| 150 | + it("should detect Markdown from headers", () => { | |
| 151 | 151 | const code = `# Main Title |
| 152 | 152 | ## Subtitle |
| 153 | 153 | This is some content.`; |
| 154 | - expect(detectLanguage(code)).toBe('markdown'); | |
| 154 | + expect(detectLanguage(code)).toBe("markdown"); | |
| 155 | 155 | }); |
| 156 | 156 | |
| 157 | - it('should default to javascript for unknown patterns', () => { | |
| 157 | + it("should default to javascript for unknown patterns", () => { | |
| 158 | 158 | const code = `some random code that doesn't match any pattern`; |
| 159 | - expect(detectLanguage(code)).toBe('javascript'); | |
| 159 | + expect(detectLanguage(code)).toBe("javascript"); | |
| 160 | 160 | }); |
| 161 | 161 | |
| 162 | - it('should handle empty string', () => { | |
| 162 | + it("should handle empty string", () => { | |
| 163 | 163 | const code = ``; |
| 164 | - expect(detectLanguage(code)).toBe('javascript'); | |
| 164 | + expect(detectLanguage(code)).toBe("javascript"); | |
| 165 | 165 | }); |
| 166 | 166 | |
| 167 | - it('should handle whitespace-only code', () => { | |
| 167 | + it("should handle whitespace-only code", () => { | |
| 168 | 168 | const code = ` |
| 169 | 169 | |
| 170 | 170 | `; |
| 171 | - expect(detectLanguage(code)).toBe('javascript'); | |
| 171 | + expect(detectLanguage(code)).toBe("javascript"); | |
| 172 | 172 | }); |
| 173 | 173 | |
| 174 | - it('should match first pattern when multiple patterns could match', () => { | |
| 174 | + it("should match first pattern when multiple patterns could match", () => { | |
| 175 | 175 | // This code has both import (JavaScript) and interface (TypeScript) patterns |
| 176 | 176 | const code = `import { Component } from 'react'; |
| 177 | 177 | interface Props { |
| 178 | 178 | name: string; |
| 179 | 179 | }`; |
| 180 | - expect(detectLanguage(code)).toBe('javascript'); // JavaScript pattern comes first | |
| 180 | + expect(detectLanguage(code)).toBe("javascript"); // JavaScript pattern comes first | |
| 181 | 181 | }); |
| 182 | 182 | |
| 183 | - it('should handle multiline code correctly', () => { | |
| 183 | + it("should handle multiline code correctly", () => { | |
| 184 | 184 | const code = ` |
| 185 | 185 | import React from 'react'; |
| 186 | 186 | |
| @@ -188,20 +188,20 @@ | ||
| 188 | 188 | return <div>Hello</div>; |
| 189 | 189 | }; |
| 190 | 190 | `; |
| 191 | - expect(detectLanguage(code)).toBe('javascript'); | |
| 191 | + expect(detectLanguage(code)).toBe("javascript"); | |
| 192 | 192 | }); |
| 193 | 193 | |
| 194 | - it('should detect patterns with leading whitespace', () => { | |
| 194 | + it("should detect patterns with leading whitespace", () => { | |
| 195 | 195 | const code = ` def my_function(): |
| 196 | 196 | return True`; |
| 197 | - expect(detectLanguage(code)).toBe('python'); | |
| 197 | + expect(detectLanguage(code)).toBe("python"); | |
| 198 | 198 | }); |
| 199 | - | |
| 200 | - it('should handle YAML-like content but default to javascript', () => { | |
| 199 | + | |
| 200 | + it("should handle YAML-like content but default to javascript", () => { | |
| 201 | 201 | // The actual implementation doesn't detect YAML from document separator |
| 202 | 202 | const code = `--- |
| 203 | 203 | name: John |
| 204 | 204 | age: 30`; |
| 205 | - expect(detectLanguage(code)).toBe('yaml'); | |
| 205 | + expect(detectLanguage(code)).toBe("yaml"); | |
| 206 | 206 | }); |
| 207 | -}); | |
| No newline at the end of the file | ||
| 207 | +}); |
modified extensions/cli/src/ui/TUIChat.test.tsx +1 −1
| @@ -10,4 +10,4 @@ | ||
| 10 | 10 | it("should import all test modules", () => { |
| 11 | 11 | expect(true).toBe(true); |
| 12 | 12 | }); |
| 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", () => { | |
| 4 | 8 | let buffer: TextBuffer; |
| 5 | 9 | |
| 6 | 10 | beforeEach(() => { |
| 7 | 11 | buffer = new TextBuffer(); |
| 8 | 12 | }); |
| 9 | 13 | |
| 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(""); | |
| 13 | 17 | expect(buffer.cursor).toBe(0); |
| 14 | 18 | }); |
| 15 | 19 | |
| 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"); | |
| 19 | 23 | expect(buffer.cursor).toBe(5); |
| 20 | 24 | }); |
| 21 | 25 | }); |
| 22 | 26 | |
| 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"); | |
| 27 | 31 | expect(buffer.cursor).toBe(0); |
| 28 | 32 | }); |
| 29 | 33 | |
| 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"); | |
| 32 | 36 | buffer.setCursor(5); |
| 33 | - buffer.setText('hi'); | |
| 34 | - expect(buffer.text).toBe('hi'); | |
| 37 | + buffer.setText("hi"); | |
| 38 | + expect(buffer.text).toBe("hi"); | |
| 35 | 39 | expect(buffer.cursor).toBe(2); |
| 36 | 40 | }); |
| 37 | 41 | }); |
| 38 | 42 | |
| 39 | - describe('setCursor', () => { | |
| 43 | + describe("setCursor", () => { | |
| 40 | 44 | beforeEach(() => { |
| 41 | - buffer.setText('hello'); | |
| 45 | + buffer.setText("hello"); | |
| 42 | 46 | }); |
| 43 | 47 | |
| 44 | - it('should set cursor to valid position', () => { | |
| 48 | + it("should set cursor to valid position", () => { | |
| 45 | 49 | buffer.setCursor(3); |
| 46 | 50 | expect(buffer.cursor).toBe(3); |
| 47 | 51 | }); |
| 48 | 52 | |
| 49 | - it('should clamp cursor to minimum of 0', () => { | |
| 53 | + it("should clamp cursor to minimum of 0", () => { | |
| 50 | 54 | buffer.setCursor(-5); |
| 51 | 55 | expect(buffer.cursor).toBe(0); |
| 52 | 56 | }); |
| 53 | 57 | |
| 54 | - it('should clamp cursor to maximum of text length', () => { | |
| 58 | + it("should clamp cursor to maximum of text length", () => { | |
| 55 | 59 | buffer.setCursor(10); |
| 56 | 60 | expect(buffer.cursor).toBe(5); |
| 57 | 61 | }); |
| 58 | 62 | }); |
| 59 | 63 | |
| 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"); | |
| 63 | 67 | buffer.setCursor(2); |
| 64 | - buffer.insertText('XX'); | |
| 65 | - expect(buffer.text).toBe('heXXllo'); | |
| 68 | + buffer.insertText("XX"); | |
| 69 | + expect(buffer.text).toBe("heXXllo"); | |
| 66 | 70 | expect(buffer.cursor).toBe(4); |
| 67 | 71 | }); |
| 68 | 72 | |
| 69 | - it('should insert text at beginning', () => { | |
| 70 | - buffer.setText('world'); | |
| 73 | + it("should insert text at beginning", () => { | |
| 74 | + buffer.setText("world"); | |
| 71 | 75 | 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"); | |
| 74 | 78 | expect(buffer.cursor).toBe(6); |
| 75 | 79 | }); |
| 76 | 80 | |
| 77 | - it('should insert text at end', () => { | |
| 78 | - buffer.setText('hello'); | |
| 81 | + it("should insert text at end", () => { | |
| 82 | + buffer.setText("hello"); | |
| 79 | 83 | 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"); | |
| 82 | 86 | expect(buffer.cursor).toBe(11); |
| 83 | 87 | }); |
| 84 | 88 | }); |
| 85 | 89 | |
| 86 | - describe('deleteCharAt', () => { | |
| 90 | + describe("deleteCharAt", () => { | |
| 87 | 91 | beforeEach(() => { |
| 88 | - buffer.setText('hello'); | |
| 92 | + buffer.setText("hello"); | |
| 89 | 93 | buffer.setCursor(3); |
| 90 | 94 | }); |
| 91 | 95 | |
| 92 | - it('should delete character at specified position', () => { | |
| 96 | + it("should delete character at specified position", () => { | |
| 93 | 97 | buffer.deleteCharAt(2); |
| 94 | - expect(buffer.text).toBe('helo'); | |
| 98 | + expect(buffer.text).toBe("helo"); | |
| 95 | 99 | expect(buffer.cursor).toBe(2); |
| 96 | 100 | }); |
| 97 | 101 | |
| 98 | - it('should not adjust cursor if deleting before cursor', () => { | |
| 102 | + it("should not adjust cursor if deleting before cursor", () => { | |
| 99 | 103 | buffer.deleteCharAt(1); |
| 100 | - expect(buffer.text).toBe('hllo'); | |
| 104 | + expect(buffer.text).toBe("hllo"); | |
| 101 | 105 | expect(buffer.cursor).toBe(2); |
| 102 | 106 | }); |
| 103 | 107 | |
| 104 | - it('should not delete if position is out of bounds', () => { | |
| 108 | + it("should not delete if position is out of bounds", () => { | |
| 105 | 109 | buffer.deleteCharAt(10); |
| 106 | - expect(buffer.text).toBe('hello'); | |
| 110 | + expect(buffer.text).toBe("hello"); | |
| 107 | 111 | expect(buffer.cursor).toBe(3); |
| 108 | 112 | }); |
| 109 | 113 | |
| 110 | - it('should not delete if position is negative', () => { | |
| 114 | + it("should not delete if position is negative", () => { | |
| 111 | 115 | buffer.deleteCharAt(-1); |
| 112 | - expect(buffer.text).toBe('hello'); | |
| 116 | + expect(buffer.text).toBe("hello"); | |
| 113 | 117 | expect(buffer.cursor).toBe(3); |
| 114 | 118 | }); |
| 115 | 119 | }); |
| 116 | 120 | |
| 117 | - describe('deleteBackward', () => { | |
| 121 | + describe("deleteBackward", () => { | |
| 118 | 122 | beforeEach(() => { |
| 119 | - buffer.setText('hello'); | |
| 123 | + buffer.setText("hello"); | |
| 120 | 124 | buffer.setCursor(3); |
| 121 | 125 | }); |
| 122 | 126 | |
| 123 | - it('should delete character before cursor', () => { | |
| 127 | + it("should delete character before cursor", () => { | |
| 124 | 128 | buffer.deleteBackward(); |
| 125 | - expect(buffer.text).toBe('helo'); | |
| 129 | + expect(buffer.text).toBe("helo"); | |
| 126 | 130 | expect(buffer.cursor).toBe(2); |
| 127 | 131 | }); |
| 128 | 132 | |
| 129 | - it('should not delete if cursor is at beginning', () => { | |
| 133 | + it("should not delete if cursor is at beginning", () => { | |
| 130 | 134 | buffer.setCursor(0); |
| 131 | 135 | buffer.deleteBackward(); |
| 132 | - expect(buffer.text).toBe('hello'); | |
| 136 | + expect(buffer.text).toBe("hello"); | |
| 133 | 137 | expect(buffer.cursor).toBe(0); |
| 134 | 138 | }); |
| 135 | 139 | }); |
| 136 | 140 | |
| 137 | - describe('deleteForward', () => { | |
| 141 | + describe("deleteForward", () => { | |
| 138 | 142 | beforeEach(() => { |
| 139 | - buffer.setText('hello'); | |
| 143 | + buffer.setText("hello"); | |
| 140 | 144 | buffer.setCursor(2); |
| 141 | 145 | }); |
| 142 | 146 | |
| 143 | - it('should delete character at cursor position', () => { | |
| 147 | + it("should delete character at cursor position", () => { | |
| 144 | 148 | buffer.deleteForward(); |
| 145 | - expect(buffer.text).toBe('helo'); | |
| 149 | + expect(buffer.text).toBe("helo"); | |
| 146 | 150 | expect(buffer.cursor).toBe(2); |
| 147 | 151 | }); |
| 148 | 152 | |
| 149 | - it('should not delete if cursor is at end', () => { | |
| 153 | + it("should not delete if cursor is at end", () => { | |
| 150 | 154 | buffer.setCursor(5); |
| 151 | 155 | buffer.deleteForward(); |
| 152 | - expect(buffer.text).toBe('hello'); | |
| 156 | + expect(buffer.text).toBe("hello"); | |
| 153 | 157 | expect(buffer.cursor).toBe(5); |
| 154 | 158 | }); |
| 155 | 159 | }); |
| 156 | 160 | |
| 157 | - describe('moveWordLeft', () => { | |
| 161 | + describe("moveWordLeft", () => { | |
| 158 | 162 | beforeEach(() => { |
| 159 | - buffer.setText('hello world test'); | |
| 163 | + buffer.setText("hello world test"); | |
| 160 | 164 | }); |
| 161 | 165 | |
| 162 | - it('should move to start of current word', () => { | |
| 166 | + it("should move to start of current word", () => { | |
| 163 | 167 | buffer.setCursor(8); // middle of "world" |
| 164 | 168 | buffer.moveWordLeft(); |
| 165 | 169 | expect(buffer.cursor).toBe(6); // start of "world" |
| 166 | 170 | }); |
| 167 | 171 | |
| 168 | - it('should move to start of previous word', () => { | |
| 172 | + it("should move to start of previous word", () => { | |
| 169 | 173 | buffer.setCursor(6); // start of "world" |
| 170 | 174 | buffer.moveWordLeft(); |
| 171 | 175 | expect(buffer.cursor).toBe(0); // start of "hello" |
| 172 | 176 | }); |
| 173 | 177 | |
| 174 | - it('should skip whitespace', () => { | |
| 178 | + it("should skip whitespace", () => { | |
| 175 | 179 | buffer.setCursor(11); // space after "world" |
| 176 | 180 | buffer.moveWordLeft(); |
| 177 | 181 | expect(buffer.cursor).toBe(6); // start of "world" |
| 178 | 182 | }); |
| 179 | 183 | |
| 180 | - it('should not move beyond beginning', () => { | |
| 184 | + it("should not move beyond beginning", () => { | |
| 181 | 185 | buffer.setCursor(0); |
| 182 | 186 | buffer.moveWordLeft(); |
| 183 | 187 | expect(buffer.cursor).toBe(0); |
| 184 | 188 | }); |
| 185 | 189 | }); |
| 186 | 190 | |
| 187 | - describe('moveWordRight', () => { | |
| 191 | + describe("moveWordRight", () => { | |
| 188 | 192 | beforeEach(() => { |
| 189 | - buffer.setText('hello world test'); | |
| 193 | + buffer.setText("hello world test"); | |
| 190 | 194 | }); |
| 191 | 195 | |
| 192 | - it('should move to end of current word', () => { | |
| 196 | + it("should move to end of current word", () => { | |
| 193 | 197 | buffer.setCursor(2); // middle of "hello" |
| 194 | 198 | buffer.moveWordRight(); |
| 195 | 199 | expect(buffer.cursor).toBe(5); // end of "hello" |
| 196 | 200 | }); |
| 197 | 201 | |
| 198 | - it('should skip whitespace to next word', () => { | |
| 202 | + it("should skip whitespace to next word", () => { | |
| 199 | 203 | buffer.setCursor(5); // end of "hello" |
| 200 | 204 | buffer.moveWordRight(); |
| 201 | 205 | expect(buffer.cursor).toBe(11); // end of "world" |
| 202 | 206 | }); |
| 203 | 207 | |
| 204 | - it('should not move beyond end', () => { | |
| 208 | + it("should not move beyond end", () => { | |
| 205 | 209 | buffer.setCursor(16); |
| 206 | 210 | buffer.moveWordRight(); |
| 207 | 211 | expect(buffer.cursor).toBe(16); |
| 208 | 212 | }); |
| 209 | 213 | }); |
| 210 | 214 | |
| 211 | - describe('deleteWordBackward', () => { | |
| 215 | + describe("deleteWordBackward", () => { | |
| 212 | 216 | beforeEach(() => { |
| 213 | - buffer.setText('hello world test'); | |
| 217 | + buffer.setText("hello world test"); | |
| 214 | 218 | }); |
| 215 | 219 | |
| 216 | - it('should delete from cursor to start of word', () => { | |
| 220 | + it("should delete from cursor to start of word", () => { | |
| 217 | 221 | buffer.setCursor(8); // middle of "world" |
| 218 | 222 | buffer.deleteWordBackward(); |
| 219 | - expect(buffer.text).toBe('hello rld test'); | |
| 223 | + expect(buffer.text).toBe("hello rld test"); | |
| 220 | 224 | expect(buffer.cursor).toBe(6); |
| 221 | 225 | }); |
| 222 | 226 | |
| 223 | - it('should delete entire previous word', () => { | |
| 227 | + it("should delete entire previous word", () => { | |
| 224 | 228 | buffer.setCursor(6); // start of "world" |
| 225 | 229 | buffer.deleteWordBackward(); |
| 226 | - expect(buffer.text).toBe('world test'); | |
| 230 | + expect(buffer.text).toBe("world test"); | |
| 227 | 231 | expect(buffer.cursor).toBe(0); |
| 228 | 232 | }); |
| 229 | 233 | }); |
| 230 | 234 | |
| 231 | - describe('deleteWordForward', () => { | |
| 235 | + describe("deleteWordForward", () => { | |
| 232 | 236 | beforeEach(() => { |
| 233 | - buffer.setText('hello world test'); | |
| 237 | + buffer.setText("hello world test"); | |
| 234 | 238 | }); |
| 235 | 239 | |
| 236 | - it('should delete from cursor to end of word', () => { | |
| 240 | + it("should delete from cursor to end of word", () => { | |
| 237 | 241 | buffer.setCursor(2); // middle of "hello" |
| 238 | 242 | buffer.deleteWordForward(); |
| 239 | - expect(buffer.text).toBe('he world test'); | |
| 243 | + expect(buffer.text).toBe("he world test"); | |
| 240 | 244 | expect(buffer.cursor).toBe(2); |
| 241 | 245 | }); |
| 242 | 246 | |
| 243 | - it('should delete to next word boundary', () => { | |
| 247 | + it("should delete to next word boundary", () => { | |
| 244 | 248 | buffer.setCursor(5); // end of "hello" |
| 245 | 249 | buffer.deleteWordForward(); |
| 246 | - expect(buffer.text).toBe('hello test'); | |
| 250 | + expect(buffer.text).toBe("hello test"); | |
| 247 | 251 | expect(buffer.cursor).toBe(5); |
| 248 | 252 | }); |
| 249 | 253 | }); |
| 250 | 254 | |
| 251 | - describe('movement methods', () => { | |
| 255 | + describe("movement methods", () => { | |
| 252 | 256 | beforeEach(() => { |
| 253 | - buffer.setText('hello'); | |
| 257 | + buffer.setText("hello"); | |
| 254 | 258 | buffer.setCursor(2); |
| 255 | 259 | }); |
| 256 | 260 | |
| 257 | - it('should move to start', () => { | |
| 261 | + it("should move to start", () => { | |
| 258 | 262 | buffer.moveToStart(); |
| 259 | 263 | expect(buffer.cursor).toBe(0); |
| 260 | 264 | }); |
| 261 | 265 | |
| 262 | - it('should move to end', () => { | |
| 266 | + it("should move to end", () => { | |
| 263 | 267 | buffer.moveToEnd(); |
| 264 | 268 | expect(buffer.cursor).toBe(5); |
| 265 | 269 | }); |
| 266 | 270 | |
| 267 | - it('should move left', () => { | |
| 271 | + it("should move left", () => { | |
| 268 | 272 | buffer.moveLeft(); |
| 269 | 273 | expect(buffer.cursor).toBe(1); |
| 270 | 274 | }); |
| 271 | 275 | |
| 272 | - it('should not move left beyond start', () => { | |
| 276 | + it("should not move left beyond start", () => { | |
| 273 | 277 | buffer.setCursor(0); |
| 274 | 278 | buffer.moveLeft(); |
| 275 | 279 | expect(buffer.cursor).toBe(0); |
| 276 | 280 | }); |
| 277 | 281 | |
| 278 | - it('should move right', () => { | |
| 282 | + it("should move right", () => { | |
| 279 | 283 | buffer.moveRight(); |
| 280 | 284 | expect(buffer.cursor).toBe(3); |
| 281 | 285 | }); |
| 282 | 286 | |
| 283 | - it('should not move right beyond end', () => { | |
| 287 | + it("should not move right beyond end", () => { | |
| 284 | 288 | buffer.setCursor(5); |
| 285 | 289 | buffer.moveRight(); |
| 286 | 290 | expect(buffer.cursor).toBe(5); |
| 287 | 291 | }); |
| 288 | 292 | }); |
| 289 | 293 | |
| 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"); | |
| 293 | 297 | buffer.setCursor(5); |
| 294 | 298 | buffer.clear(); |
| 295 | - expect(buffer.text).toBe(''); | |
| 299 | + expect(buffer.text).toBe(""); | |
| 296 | 300 | expect(buffer.cursor).toBe(0); |
| 297 | 301 | }); |
| 298 | 302 | |
| 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); | |
| 301 | 305 | buffer.handleInput(longText, { ctrl: false, meta: false } as any); |
| 302 | 306 | buffer.flushPendingInput(); |
| 303 | 307 | |
| 304 | - expect(buffer.text).toBe('[Paste #1]'); | |
| 308 | + expect(buffer.text).toBe("[Paste #1]"); | |
| 305 | 309 | |
| 306 | 310 | buffer.clear(); |
| 307 | - expect(buffer.text).toBe(''); | |
| 311 | + expect(buffer.text).toBe(""); | |
| 308 | 312 | expect(buffer.cursor).toBe(0); |
| 309 | 313 | }); |
| 310 | 314 | }); |
| 311 | 315 | |
| 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"; | |
| 315 | 319 | buffer.handleInput(shortText, { ctrl: false, meta: false } as any); |
| 316 | 320 | |
| 317 | - expect(buffer.text).toBe('hello world'); | |
| 321 | + expect(buffer.text).toBe("hello world"); | |
| 318 | 322 | }); |
| 319 | 323 | |
| 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); | |
| 322 | 326 | buffer.handleInput(longText, { ctrl: false, meta: false } as any); |
| 323 | 327 | buffer.flushPendingInput(); |
| 324 | 328 | |
| 325 | - expect(buffer.text).toBe('[Paste #1]'); | |
| 329 | + expect(buffer.text).toBe("[Paste #1]"); | |
| 326 | 330 | }); |
| 327 | 331 | |
| 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); | |
| 330 | 334 | buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any); |
| 331 | 335 | buffer.flushPendingInput(); |
| 332 | 336 | |
| 333 | - expect(buffer.text).toBe('[Paste #1, 4 lines]'); | |
| 337 | + expect(buffer.text).toBe("[Paste #1, 4 lines]"); | |
| 334 | 338 | }); |
| 335 | 339 | |
| 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); | |
| 338 | 342 | buffer.handleInput(longText, { ctrl: false, meta: false } as any); |
| 339 | 343 | buffer.flushPendingInput(); |
| 340 | 344 | |
| 341 | 345 | // Verify it was collapsed |
| 342 | - expect(buffer.text).toBe('[Paste #1]'); | |
| 346 | + expect(buffer.text).toBe("[Paste #1]"); | |
| 343 | 347 | |
| 344 | 348 | // Expand it |
| 345 | 349 | buffer.expandAllPasteBlocks(); |
| @@ -348,37 +352,37 @@ | ||
| 348 | 352 | expect(buffer.text).toBe(longText); |
| 349 | 353 | }); |
| 350 | 354 | |
| 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 "); | |
| 353 | 357 | buffer.setCursor(7); |
| 354 | 358 | |
| 355 | - const longText = 'a'.repeat(COLLAPSE_SIZE + 1); | |
| 359 | + const longText = "a".repeat(COLLAPSE_SIZE + 1); | |
| 356 | 360 | buffer.handleInput(longText, { ctrl: false, meta: false } as any); |
| 357 | 361 | buffer.flushPendingInput(); |
| 358 | 362 | |
| 359 | - expect(buffer.text).toBe('before [Paste #1]'); | |
| 363 | + expect(buffer.text).toBe("before [Paste #1]"); | |
| 360 | 364 | |
| 361 | 365 | // 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"); | |
| 364 | 368 | |
| 365 | 369 | // Move cursor to beginning and type |
| 366 | 370 | 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"); | |
| 369 | 373 | }); |
| 370 | 374 | |
| 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 | |
| 373 | 377 | buffer.handleInput(exactText, { ctrl: false, meta: false } as any); |
| 374 | 378 | buffer.flushPendingInput(); // This will go into rapid input mode due to size |
| 375 | 379 | |
| 376 | 380 | expect(buffer.text).toBe(exactText); // Should not be collapsed |
| 377 | 381 | }); |
| 378 | 382 | |
| 379 | - it('should handle paste operations as single large inputs', () => { | |
| 383 | + it("should handle paste operations as single large inputs", () => { | |
| 380 | 384 | // 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); | |
| 382 | 386 | |
| 383 | 387 | expect(longText.length).toBeGreaterThan(COLLAPSE_SIZE); |
| 384 | 388 | |
| @@ -386,87 +390,95 @@ | ||
| 386 | 390 | buffer.flushPendingInput(); |
| 387 | 391 | |
| 388 | 392 | // Should be collapsed |
| 389 | - expect(buffer.text).toBe('[Paste #1]'); | |
| 393 | + expect(buffer.text).toBe("[Paste #1]"); | |
| 390 | 394 | }); |
| 391 | 395 | |
| 392 | - it('should handle bracketed paste mode', () => { | |
| 396 | + it("should handle bracketed paste mode", () => { | |
| 393 | 397 | // Simulate bracketed paste: start sequence, content, end sequence |
| 394 | 398 | |
| 395 | 399 | // Start paste mode |
| 396 | - buffer.handleInput('\u001b[200~', {} as any); | |
| 400 | + buffer.handleInput("\u001b[200~", {} as any); | |
| 397 | 401 | expect(buffer.isInPasteMode()).toBe(true); |
| 398 | 402 | |
| 399 | 403 | // 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) => { | |
| 404 | 412 | buffer.handleInput(chunk, { ctrl: false, meta: false } as any); |
| 405 | 413 | }); |
| 406 | 414 | |
| 407 | 415 | // Text should NOT be visible during paste mode (to avoid visual bugs) |
| 408 | - expect(buffer.text).toBe(''); | |
| 416 | + expect(buffer.text).toBe(""); | |
| 409 | 417 | |
| 410 | 418 | // End paste mode |
| 411 | - buffer.handleInput('\u001b[201~', {} as any); | |
| 419 | + buffer.handleInput("\u001b[201~", {} as any); | |
| 412 | 420 | expect(buffer.isInPasteMode()).toBe(false); |
| 413 | 421 | |
| 414 | 422 | // Now should be collapsed if > COLLAPSE_SIZE |
| 415 | 423 | if (totalContent.length > COLLAPSE_SIZE) { |
| 416 | - expect(buffer.text).toBe('[Paste #1]'); | |
| 424 | + expect(buffer.text).toBe("[Paste #1]"); | |
| 417 | 425 | } |
| 418 | 426 | }); |
| 419 | 427 | |
| 420 | - it('should not collapse short bracketed paste content', () => { | |
| 428 | + it("should not collapse short bracketed paste content", () => { | |
| 421 | 429 | // Start paste mode |
| 422 | - buffer.handleInput('\u001b[200~', {} as any); | |
| 430 | + buffer.handleInput("\u001b[200~", {} as any); | |
| 423 | 431 | |
| 424 | 432 | // Add short content |
| 425 | - const shortContent = 'Hello world!'; | |
| 433 | + const shortContent = "Hello world!"; | |
| 426 | 434 | buffer.handleInput(shortContent, { ctrl: false, meta: false } as any); |
| 427 | 435 | |
| 428 | 436 | // End paste mode |
| 429 | - buffer.handleInput('\u001b[201~', {} as any); | |
| 437 | + buffer.handleInput("\u001b[201~", {} as any); | |
| 430 | 438 | |
| 431 | 439 | // Should not be collapsed |
| 432 | 440 | expect(buffer.text).toBe(shortContent); |
| 433 | 441 | }); |
| 434 | 442 | |
| 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); | |
| 438 | 450 | buffer.flushPendingInput(); |
| 439 | 451 | |
| 440 | - expect(buffer.text).toBe('[Paste #1, 4 lines]'); | |
| 452 | + expect(buffer.text).toBe("[Paste #1, 4 lines]"); | |
| 441 | 453 | |
| 442 | 454 | buffer.expandAllPasteBlocks(); |
| 443 | 455 | |
| 444 | 456 | // 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); | |
| 446 | 458 | expect(buffer.text).toBe(expected); |
| 447 | 459 | }); |
| 448 | 460 | |
| 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); | |
| 452 | 464 | |
| 453 | 465 | buffer.handleInput(longText1, { ctrl: false, meta: false } as any); |
| 454 | 466 | buffer.flushPendingInput(); |
| 455 | - expect(buffer.text).toBe('[Paste #1]'); | |
| 467 | + expect(buffer.text).toBe("[Paste #1]"); | |
| 456 | 468 | |
| 457 | - buffer.insertText(' '); | |
| 469 | + buffer.insertText(" "); | |
| 458 | 470 | buffer.handleInput(longText2, { ctrl: false, meta: false } as any); |
| 459 | 471 | buffer.flushPendingInput(); |
| 460 | - expect(buffer.text).toBe('[Paste #1] [Paste #2]'); | |
| 472 | + expect(buffer.text).toBe("[Paste #1] [Paste #2]"); | |
| 461 | 473 | }); |
| 462 | 474 | |
| 463 | - it('should detect rapid input above threshold', () => { | |
| 475 | + it("should detect rapid input above threshold", () => { | |
| 464 | 476 | // 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); | |
| 466 | 478 | buffer.handleInput(rapidText, { ctrl: false, meta: false } as any); |
| 467 | 479 | |
| 468 | 480 | // Should go into rapid input buffer (not displayed yet) |
| 469 | - expect(buffer.text).toBe(''); | |
| 481 | + expect(buffer.text).toBe(""); | |
| 470 | 482 | expect(buffer.isInRapidInputMode()).toBe(true); |
| 471 | 483 | |
| 472 | 484 | // Flush to finalize |
| @@ -476,23 +488,23 @@ | ||
| 476 | 488 | expect(buffer.text).toBe(rapidText); |
| 477 | 489 | }); |
| 478 | 490 | |
| 479 | - it('should combine split paste chunks', () => { | |
| 491 | + it("should combine split paste chunks", () => { | |
| 480 | 492 | // 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 | |
| 482 | 494 | buffer.handleInput(firstChunk, { ctrl: false, meta: false } as any); |
| 483 | 495 | |
| 484 | 496 | // First chunk goes into rapid input mode - no placeholder yet |
| 485 | - expect(buffer.text).toBe(''); | |
| 497 | + expect(buffer.text).toBe(""); | |
| 486 | 498 | |
| 487 | 499 | // 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 | |
| 489 | 501 | buffer.handleInput(secondChunk, { ctrl: false, meta: false } as any); |
| 490 | 502 | |
| 491 | 503 | // Flush to finalize the rapid input synchronously |
| 492 | 504 | buffer.flushPendingInput(); |
| 493 | 505 | |
| 494 | 506 | // Should show only one placeholder with combined content |
| 495 | - expect(buffer.text).toBe('[Paste #1]'); | |
| 507 | + expect(buffer.text).toBe("[Paste #1]"); | |
| 496 | 508 | |
| 497 | 509 | // Verify the combined content is stored correctly |
| 498 | 510 | buffer.expandAllPasteBlocks(); |
| @@ -500,148 +512,155 @@ | ||
| 500 | 512 | expect(buffer.text).toBe(expectedContent); |
| 501 | 513 | }); |
| 502 | 514 | |
| 503 | - it('should expand paste blocks on submission (simulating Enter key behavior)', () => { | |
| 515 | + it("should expand paste blocks on submission (simulating Enter key behavior)", () => { | |
| 504 | 516 | // Add some text before the paste |
| 505 | - buffer.insertText('Command: '); | |
| 506 | - | |
| 517 | + buffer.insertText("Command: "); | |
| 518 | + | |
| 507 | 519 | // 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); | |
| 509 | 523 | buffer.handleInput(pastedCode, { ctrl: false, meta: false } as any); |
| 510 | 524 | buffer.flushPendingInput(); |
| 511 | - | |
| 525 | + | |
| 512 | 526 | // 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 | + | |
| 515 | 529 | // Simulate what happens when user presses Enter - UserInput calls expandAllPasteBlocks() |
| 516 | 530 | buffer.expandAllPasteBlocks(); |
| 517 | - | |
| 531 | + | |
| 518 | 532 | // 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); | |
| 520 | 536 | expect(buffer.text).toBe(expectedFullText); |
| 521 | - | |
| 537 | + | |
| 522 | 538 | // Verify paste map is cleared after expansion |
| 523 | 539 | buffer.expandAllPasteBlocks(); // Should be no-op now |
| 524 | 540 | expect(buffer.text).toBe(expectedFullText); // Should remain the same |
| 525 | 541 | }); |
| 526 | 542 | }); |
| 527 | 543 | |
| 528 | - describe('handleInput', () => { | |
| 544 | + describe("handleInput", () => { | |
| 529 | 545 | beforeEach(() => { |
| 530 | - buffer.setText('hello'); | |
| 546 | + buffer.setText("hello"); | |
| 531 | 547 | buffer.setCursor(2); |
| 532 | 548 | }); |
| 533 | 549 | |
| 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); | |
| 536 | 552 | expect(result).toBe(true); |
| 537 | - expect(buffer.text).toBe('heXllo'); | |
| 553 | + expect(buffer.text).toBe("heXllo"); | |
| 538 | 554 | expect(buffer.cursor).toBe(3); |
| 539 | 555 | }); |
| 540 | 556 | |
| 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); | |
| 543 | 559 | expect(result).toBe(true); |
| 544 | - expect(buffer.text).toBe('heXYZllo'); | |
| 560 | + expect(buffer.text).toBe("heXYZllo"); | |
| 545 | 561 | expect(buffer.cursor).toBe(5); |
| 546 | 562 | }); |
| 547 | 563 | |
| 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); | |
| 550 | 566 | expect(result).toBe(true); |
| 551 | 567 | expect(buffer.cursor).toBe(0); |
| 552 | 568 | }); |
| 553 | 569 | |
| 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); | |
| 556 | 572 | expect(result).toBe(true); |
| 557 | 573 | expect(buffer.cursor).toBe(5); |
| 558 | 574 | }); |
| 559 | 575 | |
| 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); | |
| 562 | 578 | expect(result).toBe(true); |
| 563 | - expect(buffer.text).toBe('llo'); | |
| 579 | + expect(buffer.text).toBe("llo"); | |
| 564 | 580 | expect(buffer.cursor).toBe(0); |
| 565 | 581 | }); |
| 566 | 582 | |
| 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); | |
| 569 | 585 | expect(result).toBe(true); |
| 570 | - expect(buffer.text).toBe('he'); | |
| 586 | + expect(buffer.text).toBe("he"); | |
| 571 | 587 | expect(buffer.cursor).toBe(2); |
| 572 | 588 | }); |
| 573 | 589 | |
| 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); | |
| 576 | 592 | expect(result).toBe(true); |
| 577 | 593 | expect(buffer.cursor).toBe(1); |
| 578 | 594 | |
| 579 | - result = buffer.handleInput('', { rightArrow: true } as any); | |
| 595 | + result = buffer.handleInput("", { rightArrow: true } as any); | |
| 580 | 596 | expect(result).toBe(true); |
| 581 | 597 | expect(buffer.cursor).toBe(2); |
| 582 | 598 | }); |
| 583 | 599 | |
| 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); | |
| 586 | 602 | expect(result).toBe(true); |
| 587 | - expect(buffer.text).toBe('hllo'); | |
| 603 | + expect(buffer.text).toBe("hllo"); | |
| 588 | 604 | expect(buffer.cursor).toBe(1); |
| 589 | 605 | }); |
| 590 | 606 | |
| 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); | |
| 593 | 609 | expect(result).toBe(true); |
| 594 | - expect(buffer.text).toBe('hllo'); | |
| 610 | + expect(buffer.text).toBe("hllo"); | |
| 595 | 611 | expect(buffer.cursor).toBe(1); |
| 596 | 612 | }); |
| 597 | 613 | |
| 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); | |
| 600 | 619 | expect(result).toBe(true); |
| 601 | 620 | expect(buffer.cursor).toBe(0); |
| 602 | 621 | }); |
| 603 | 622 | |
| 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); | |
| 606 | 625 | expect(result).toBe(true); |
| 607 | 626 | // Should delete word backward |
| 608 | - expect(buffer.text).toBe('llo'); | |
| 627 | + expect(buffer.text).toBe("llo"); | |
| 609 | 628 | expect(buffer.cursor).toBe(0); |
| 610 | 629 | }); |
| 611 | 630 | |
| 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); | |
| 614 | 633 | expect(result).toBe(false); |
| 615 | 634 | }); |
| 616 | 635 | }); |
| 617 | 636 | |
| 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"); | |
| 621 | 640 | buffer.setCursor(2); |
| 622 | 641 | const result = buffer.renderWithCursor(); |
| 623 | 642 | expect(result).toEqual({ |
| 624 | - text: 'hello', | |
| 625 | - cursorPosition: 2 | |
| 643 | + text: "hello", | |
| 644 | + cursorPosition: 2, | |
| 626 | 645 | }); |
| 627 | 646 | }); |
| 628 | 647 | |
| 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..."); | |
| 631 | 650 | expect(result).toEqual({ |
| 632 | - text: 'Enter text...', | |
| 633 | - cursorPosition: 0 | |
| 651 | + text: "Enter text...", | |
| 652 | + cursorPosition: 0, | |
| 634 | 653 | }); |
| 635 | 654 | }); |
| 636 | 655 | |
| 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"); | |
| 639 | 658 | buffer.setCursor(2); |
| 640 | - const result = buffer.renderWithCursor('Enter text...'); | |
| 659 | + const result = buffer.renderWithCursor("Enter text..."); | |
| 641 | 660 | expect(result).toEqual({ |
| 642 | - text: 'hello', | |
| 643 | - cursorPosition: 2 | |
| 661 | + text: "hello", | |
| 662 | + cursorPosition: 2, | |
| 644 | 663 | }); |
| 645 | 664 | }); |
| 646 | 665 | }); |
| 647 | -}); | |
| No newline at the end of the file | ||
| 666 | +}); |
modified extensions/cli/src/ui/UpdateNotification.test.tsx +1 −1
| @@ -119,4 +119,4 @@ | ||
| 119 | 119 | expect(mockVersionModule.getLatestVersion).toHaveBeenCalled(); |
| 120 | 120 | } |
| 121 | 121 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { modeService } from '../services/ModeService.js'; | |
| 3 | +import { modeService } from "../services/ModeService.js"; | |
| 4 | 4 | |
| 5 | -describe('UserInput Keyboard Shortcuts', () => { | |
| 5 | +describe("UserInput Keyboard Shortcuts", () => { | |
| 6 | 6 | beforeEach(() => { |
| 7 | 7 | // Reset to normal mode for each test |
| 8 | 8 | modeService.initialize({}); |
| 9 | 9 | }); |
| 10 | 10 | |
| 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", () => { | |
| 13 | 13 | // Initially should be normal mode |
| 14 | - expect(modeService.getCurrentMode()).toBe('normal'); | |
| 14 | + expect(modeService.getCurrentMode()).toBe("normal"); | |
| 15 | 15 | |
| 16 | 16 | // Cycle to plan |
| 17 | - modeService.switchMode('plan'); | |
| 18 | - expect(modeService.getCurrentMode()).toBe('plan'); | |
| 17 | + modeService.switchMode("plan"); | |
| 18 | + expect(modeService.getCurrentMode()).toBe("plan"); | |
| 19 | 19 | |
| 20 | 20 | // Cycle to auto |
| 21 | - modeService.switchMode('auto'); | |
| 22 | - expect(modeService.getCurrentMode()).toBe('auto'); | |
| 21 | + modeService.switchMode("auto"); | |
| 22 | + expect(modeService.getCurrentMode()).toBe("auto"); | |
| 23 | 23 | |
| 24 | 24 | // Cycle back to normal |
| 25 | - modeService.switchMode('normal'); | |
| 26 | - expect(modeService.getCurrentMode()).toBe('normal'); | |
| 25 | + modeService.switchMode("normal"); | |
| 26 | + expect(modeService.getCurrentMode()).toBe("normal"); | |
| 27 | 27 | }); |
| 28 | 28 | |
| 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 | + | |
| 32 | 32 | // Test cycling through all modes |
| 33 | 33 | for (let i = 0; i < modes.length * 2; i++) { |
| 34 | 34 | const expectedMode = modes[i % modes.length]; |
| @@ -37,4 +37,4 @@ | ||
| 37 | 37 | } |
| 38 | 38 | }); |
| 39 | 39 | }); |
| 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 @@ | ||
| 6 | 6 | |
| 7 | 7 | // Mock the 'open' module to prevent actual URL opening during tests |
| 8 | 8 | vi.mock("open", () => ({ |
| 9 | - default: vi.fn() | |
| 9 | + default: vi.fn(), | |
| 10 | 10 | })); |
| 11 | 11 | |
| 12 | 12 | // Mock the NavigationContext |
| @@ -15,8 +15,8 @@ | ||
| 15 | 15 | navigateTo: vi.fn(), |
| 16 | 16 | closeCurrentScreen: vi.fn(), |
| 17 | 17 | isScreenActive: vi.fn(() => false), |
| 18 | - state: { currentScreen: 'free-trial', screenData: null } | |
| 19 | - }) | |
| 18 | + state: { currentScreen: "free-trial", screenData: null }, | |
| 19 | + }), | |
| 20 | 20 | })); |
| 21 | 21 | |
| 22 | 22 | describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { |
| @@ -29,9 +29,7 @@ | ||
| 29 | 29 | describe("Initial Choice Screen Rendering", () => { |
| 30 | 30 | it("displays all three options with proper formatting", () => { |
| 31 | 31 | const { lastFrame } = render( |
| 32 | - <FreeTrialTransitionUI | |
| 33 | - onReload={mockOnReload} | |
| 34 | - /> | |
| 32 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 35 | 33 | ); |
| 36 | 34 | |
| 37 | 35 | const frame = lastFrame(); |
| @@ -44,22 +42,20 @@ | ||
| 44 | 42 | |
| 45 | 43 | it("highlights first option by default", () => { |
| 46 | 44 | const { lastFrame } = render( |
| 47 | - <FreeTrialTransitionUI | |
| 48 | - onReload={mockOnReload} | |
| 49 | - /> | |
| 45 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 50 | 46 | ); |
| 51 | 47 | |
| 52 | 48 | const frame = lastFrame(); |
| 53 | 49 | expect(frame).toContain("▶ 1. 💳 Sign up for models add-on"); |
| 54 | 50 | 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 | + ); | |
| 56 | 54 | }); |
| 57 | 55 | |
| 58 | 56 | it("renders without crashing when all props are provided", () => { |
| 59 | 57 | const { lastFrame } = render( |
| 60 | - <FreeTrialTransitionUI | |
| 61 | - onReload={mockOnReload} | |
| 62 | - /> | |
| 58 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 63 | 59 | ); |
| 64 | 60 | |
| 65 | 61 | const frame = lastFrame(); |
| @@ -72,7 +68,7 @@ | ||
| 72 | 68 | <FreeTrialTransitionUI |
| 73 | 69 | onReload={mockOnReload} |
| 74 | 70 | // onShowConfigSelector not provided |
| 75 | - /> | |
| 71 | + />, | |
| 76 | 72 | ); |
| 77 | 73 | |
| 78 | 74 | const frame = lastFrame(); |
| @@ -83,21 +79,19 @@ | ||
| 83 | 79 | |
| 84 | 80 | it("includes proper user instructions", () => { |
| 85 | 81 | const { lastFrame } = render( |
| 86 | - <FreeTrialTransitionUI | |
| 87 | - onReload={mockOnReload} | |
| 88 | - /> | |
| 82 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 89 | 83 | ); |
| 90 | 84 | |
| 91 | 85 | const frame = lastFrame(); |
| 92 | 86 | 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 | + ); | |
| 94 | 90 | }); |
| 95 | 91 | |
| 96 | 92 | it("shows all options with proper descriptions", () => { |
| 97 | 93 | const { lastFrame } = render( |
| 98 | - <FreeTrialTransitionUI | |
| 99 | - onReload={mockOnReload} | |
| 100 | - /> | |
| 94 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 101 | 95 | ); |
| 102 | 96 | |
| 103 | 97 | const frame = lastFrame(); |
| @@ -111,22 +105,14 @@ | ||
| 111 | 105 | it("accepts all required callback props", () => { |
| 112 | 106 | // Test that component accepts and renders with all props |
| 113 | 107 | expect(() => { |
| 114 | - render( | |
| 115 | - <FreeTrialTransitionUI | |
| 116 | - onReload={mockOnReload} | |
| 117 | - /> | |
| 118 | - ); | |
| 108 | + render(<FreeTrialTransitionUI onReload={mockOnReload} />); | |
| 119 | 109 | }).not.toThrow(); |
| 120 | 110 | }); |
| 121 | 111 | |
| 122 | 112 | it("accepts optional onShowConfigSelector prop", () => { |
| 123 | 113 | // Test that component works without onShowConfigSelector |
| 124 | 114 | expect(() => { |
| 125 | - render( | |
| 126 | - <FreeTrialTransitionUI | |
| 127 | - onReload={mockOnReload} | |
| 128 | - /> | |
| 129 | - ); | |
| 115 | + render(<FreeTrialTransitionUI onReload={mockOnReload} />); | |
| 130 | 116 | }).not.toThrow(); |
| 131 | 117 | }); |
| 132 | 118 | }); |
| @@ -134,9 +120,7 @@ | ||
| 134 | 120 | describe("Visual Styling and Layout", () => { |
| 135 | 121 | it("renders with proper border styling", () => { |
| 136 | 122 | const { lastFrame } = render( |
| 137 | - <FreeTrialTransitionUI | |
| 138 | - onReload={mockOnReload} | |
| 139 | - /> | |
| 123 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 140 | 124 | ); |
| 141 | 125 | |
| 142 | 126 | const frame = lastFrame(); |
| @@ -146,32 +130,34 @@ | ||
| 146 | 130 | |
| 147 | 131 | it("displays with proper spacing and formatting", () => { |
| 148 | 132 | const { lastFrame } = render( |
| 149 | - <FreeTrialTransitionUI | |
| 150 | - onReload={mockOnReload} | |
| 151 | - /> | |
| 133 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 152 | 134 | ); |
| 153 | 135 | |
| 154 | 136 | const frame = lastFrame(); |
| 155 | 137 | // Should have proper spacing between lines |
| 156 | - expect(frame?.split('\n').length).toBeGreaterThan(5); | |
| 138 | + expect(frame?.split("\n").length).toBeGreaterThan(5); | |
| 157 | 139 | }); |
| 158 | 140 | |
| 159 | 141 | it("shows selection indicator on first option by default", () => { |
| 160 | 142 | const { lastFrame } = render( |
| 161 | - <FreeTrialTransitionUI | |
| 162 | - onReload={mockOnReload} | |
| 163 | - /> | |
| 143 | + <FreeTrialTransitionUI onReload={mockOnReload} />, | |
| 164 | 144 | ); |
| 165 | 145 | |
| 166 | 146 | 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("▶"); | |
| 175 | 161 | }); |
| 176 | 162 | }); |
| 177 | 163 | |
| @@ -184,4 +170,4 @@ | ||
| 184 | 170 | expect(typeof openModule.default).toBe("function"); |
| 185 | 171 | }); |
| 186 | 172 | }); |
| 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 @@ | ||
| 5 | 5 | it("should mock URL opening to prevent actual browser launches during tests", () => { |
| 6 | 6 | // This test verifies that we properly mock the 'open' module |
| 7 | 7 | // to prevent actual URLs from being opened during test runs |
| 8 | - | |
| 8 | + | |
| 9 | 9 | // Import and check that open is mocked |
| 10 | 10 | const mockOpen = vi.fn(); |
| 11 | 11 | vi.mock("open", () => mockOpen); |
| 12 | - | |
| 12 | + | |
| 13 | 13 | // Verify the mock is properly set up |
| 14 | 14 | expect(mockOpen).toBeDefined(); |
| 15 | 15 | expect(typeof mockOpen).toBe("function"); |
| @@ -19,16 +19,25 @@ | ||
| 19 | 19 | // Test the URL construction logic without actually opening URLs |
| 20 | 20 | const baseUrl = "https://test.continue.dev"; |
| 21 | 21 | const expectedUrl = new URL("setup-models", baseUrl).toString(); |
| 22 | - | |
| 22 | + | |
| 23 | 23 | expect(expectedUrl).toBe("https://test.continue.dev/setup-models"); |
| 24 | 24 | }); |
| 25 | 25 | |
| 26 | 26 | it("should handle URL construction with different base URLs", () => { |
| 27 | 27 | // Test URL construction with various base URLs |
| 28 | 28 | 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 | + }, | |
| 32 | 41 | ]; |
| 33 | 42 | |
| 34 | 43 | testCases.forEach(({ base, expected }) => { |
| @@ -41,16 +50,16 @@ | ||
| 41 | 50 | // This test documents the security consideration: |
| 42 | 51 | // Without proper mocking, tests could open arbitrary URLs in the user's browser |
| 43 | 52 | // The mock ensures this doesn't happen during automated test runs |
| 44 | - | |
| 53 | + | |
| 45 | 54 | const openFunction = vi.fn(); |
| 46 | - | |
| 55 | + | |
| 47 | 56 | // Simulate what would happen if URL opening was called |
| 48 | 57 | openFunction("https://malicious-site.com"); |
| 49 | - | |
| 58 | + | |
| 50 | 59 | // Verify the mock was called instead of actual URL opening |
| 51 | 60 | expect(openFunction).toHaveBeenCalledWith("https://malicious-site.com"); |
| 52 | 61 | expect(openFunction).toHaveBeenCalledTimes(1); |
| 53 | - | |
| 62 | + | |
| 54 | 63 | // In real usage, this would have opened a browser tab, but with mocking it's safe |
| 55 | 64 | }); |
| 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 @@ | ||
| 50 | 50 | |
| 51 | 51 | it("handles remote URL prop", () => { |
| 52 | 52 | const { lastFrame } = render( |
| 53 | - React.createElement(AppRoot, { remoteUrl: "http://localhost:3000" }) | |
| 53 | + React.createElement(AppRoot, { remoteUrl: "http://localhost:3000" }), | |
| 54 | 54 | ); |
| 55 | 55 | const frame = lastFrame(); |
| 56 | 56 | |
| @@ -59,4 +59,4 @@ | ||
| 59 | 59 | expect(frame.length).toBeGreaterThan(0); |
| 60 | 60 | } |
| 61 | 61 | }); |
| 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 @@ | ||
| 21 | 21 | expect(hasAtSymbol).toBe(true); |
| 22 | 22 | |
| 23 | 23 | // Mode-specific UI |
| 24 | - if (mode === 'remote') { | |
| 24 | + if (mode === "remote") { | |
| 25 | 25 | expect(frame).toContain("Remote Mode"); |
| 26 | 26 | } else { |
| 27 | 27 | expect(frame).not.toContain("Remote Mode"); |
| @@ -44,15 +44,16 @@ | ||
| 44 | 44 | expect(frame).toContain("@READ"); |
| 45 | 45 | |
| 46 | 46 | // In local mode, should show either navigation hints or files |
| 47 | - if (mode === 'local') { | |
| 47 | + if (mode === "local") { | |
| 48 | 48 | // Should show either navigation hints or at least indicate file search is working |
| 49 | 49 | 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"); | |
| 51 | 52 | expect(hasNavigationHints || hasFileSearch).toBe(true); |
| 52 | 53 | } |
| 53 | 54 | |
| 54 | 55 | // Mode-specific checks |
| 55 | - if (mode === 'remote') { | |
| 56 | + if (mode === "remote") { | |
| 56 | 57 | expect(frame).toContain("Remote Mode"); |
| 57 | 58 | } else { |
| 58 | 59 | expect(frame).not.toContain("Remote Mode"); |
| @@ -75,7 +76,7 @@ | ||
| 75 | 76 | expect(frame).toContain("@@test"); |
| 76 | 77 | |
| 77 | 78 | // Mode-specific UI elements |
| 78 | - if (mode === 'remote') { | |
| 79 | + if (mode === "remote") { | |
| 79 | 80 | expect(frame).toContain("Remote Mode"); |
| 80 | 81 | } else { |
| 81 | 82 | expect(frame).toContain("Continue CLI"); |
| @@ -98,11 +99,12 @@ | ||
| 98 | 99 | expect(frame.length).toBeGreaterThan(0); |
| 99 | 100 | |
| 100 | 101 | // In local mode, should show either navigation hints or file search UI |
| 101 | - if (mode === 'local') { | |
| 102 | + if (mode === "local") { | |
| 102 | 103 | // Should show either navigation hints or at least the @ character in file search |
| 103 | 104 | 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"); | |
| 105 | 107 | expect(hasNavigationHints || hasFileSearchUI).toBe(true); |
| 106 | 108 | } |
| 107 | 109 | }); |
| 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 @@ | ||
| 5 | 5 | // This test verifies that the integration points exist |
| 6 | 6 | // More comprehensive integration tests would require complex mocking |
| 7 | 7 | // that is difficult to maintain and test reliably. |
| 8 | - | |
| 8 | + | |
| 9 | 9 | // The key integration points are: |
| 10 | 10 | // 1. FreeTrialTransitionUI receives onShowConfigSelector callback |
| 11 | 11 | // 2. TUIChat provides handleFreeTrialShowConfigSelector function |
| 12 | 12 | // 3. Config selector is shown when option 3 is selected |
| 13 | - | |
| 13 | + | |
| 14 | 14 | // These integration points are tested via: |
| 15 | 15 | // - Type checking (ensures interfaces match) |
| 16 | 16 | // - Manual testing during development |
| 17 | 17 | // - E2E tests that exercise the full flow |
| 18 | - | |
| 18 | + | |
| 19 | 19 | expect(true).toBe(true); // Placeholder test |
| 20 | 20 | }); |
| 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 @@ | ||
| 9 | 9 | const frame = lastFrame(); |
| 10 | 10 | // The input might be in a different format, let's be more flexible |
| 11 | 11 | expect(frame ? frame.toLowerCase() : "").toMatch( |
| 12 | - /testing|123|ask anything/ | |
| 12 | + /testing|123|ask anything/, | |
| 13 | 13 | ); |
| 14 | - | |
| 14 | + | |
| 15 | 15 | // Mode-specific assertions |
| 16 | - if (mode === 'remote') { | |
| 16 | + if (mode === "remote") { | |
| 17 | 17 | expect(frame).toContain("Remote Mode"); |
| 18 | 18 | } else { |
| 19 | 19 | expect(frame).not.toContain("Remote Mode"); |
| @@ -36,34 +36,37 @@ | ||
| 36 | 36 | // The UI should remain stable after Enter (no crash) |
| 37 | 37 | expect(afterEnter).toBeDefined(); |
| 38 | 38 | expect(afterEnter).toContain("Ask anything"); |
| 39 | - | |
| 39 | + | |
| 40 | 40 | // Local mode specific features |
| 41 | - if (mode === 'local') { | |
| 41 | + if (mode === "local") { | |
| 42 | 42 | expect(afterEnter).toContain("@ for context"); |
| 43 | 43 | expect(afterEnter).toContain("/ for slash commands"); |
| 44 | 44 | } |
| 45 | 45 | }); |
| 46 | 46 | |
| 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 @@ | ||
| 15 | 15 | expect(frame).toContain("│"); |
| 16 | 16 | |
| 17 | 17 | // Mode-specific assertions |
| 18 | - if (mode === 'remote') { | |
| 18 | + if (mode === "remote") { | |
| 19 | 19 | expect(frame).toContain("Remote Mode"); |
| 20 | 20 | } else { |
| 21 | 21 | expect(frame).not.toContain("Remote Mode"); |
| @@ -35,12 +35,12 @@ | ||
| 35 | 35 | expect(frame).toContain("/ for slash commands"); |
| 36 | 36 | |
| 37 | 37 | // In local mode, also shows context hint |
| 38 | - if (mode === 'local') { | |
| 38 | + if (mode === "local") { | |
| 39 | 39 | expect(frame).toContain("@ for context"); |
| 40 | 40 | } |
| 41 | 41 | |
| 42 | 42 | // Verify mode-specific UI |
| 43 | - if (mode === 'remote') { | |
| 43 | + if (mode === "remote") { | |
| 44 | 44 | expect(frame).toContain("Remote Mode"); |
| 45 | 45 | } else { |
| 46 | 46 | expect(frame).toContain("Continue CLI"); |
| @@ -65,13 +65,13 @@ | ||
| 65 | 65 | // Verify the component renders |
| 66 | 66 | const frame = lastFrame(); |
| 67 | 67 | expect(frame).toContain("Ask anything"); |
| 68 | - | |
| 68 | + | |
| 69 | 69 | // In local mode, we have access to more UI elements |
| 70 | - if (mode === 'local') { | |
| 70 | + if (mode === "local") { | |
| 71 | 71 | expect(frame).toContain("@ for context"); |
| 72 | 72 | expect(frame).toContain("/ for slash commands"); |
| 73 | 73 | } |
| 74 | 74 | |
| 75 | 75 | context.cleanup(); |
| 76 | 76 | }); |
| 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 @@ | ||
| 30 | 30 | |
| 31 | 31 | it("should call reloadPermissions after creating a policy", async () => { |
| 32 | 32 | // 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 | + ); | |
| 35 | 39 | vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); |
| 36 | 40 | |
| 37 | 41 | // Test the workflow that should happen in useChat.handleToolPermissionResponse |
| @@ -42,7 +46,7 @@ | ||
| 42 | 46 | |
| 43 | 47 | const approved = true; |
| 44 | 48 | const createPolicy = true; |
| 45 | - | |
| 49 | + | |
| 46 | 50 | // Simulate the policy creation flow from useChat |
| 47 | 51 | if (approved && createPolicy && mockActiveRequest) { |
| 48 | 52 | try { |
| @@ -57,29 +61,38 @@ | ||
| 57 | 61 | ); |
| 58 | 62 | |
| 59 | 63 | await addPolicyToYaml(policyRule); |
| 60 | - | |
| 64 | + | |
| 61 | 65 | // This is the key part we're testing - reload should be called |
| 62 | 66 | await services.mode.getToolPermissionService().reloadPermissions(); |
| 63 | - | |
| 64 | 67 | } catch (error) { |
| 65 | 68 | // Handle errors gracefully |
| 66 | 69 | } |
| 67 | 70 | } |
| 68 | 71 | |
| 69 | 72 | // 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 | + ); | |
| 72 | 79 | expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); |
| 73 | 80 | }); |
| 74 | 81 | |
| 75 | 82 | it("should handle permission reload failure gracefully", async () => { |
| 76 | 83 | // 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 | + ); | |
| 79 | 90 | vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); |
| 80 | 91 | |
| 81 | 92 | // Mock reloadPermissions to fail |
| 82 | - mockToolPermissionService.reloadPermissions.mockRejectedValue(new Error("Reload failed")); | |
| 93 | + mockToolPermissionService.reloadPermissions.mockRejectedValue( | |
| 94 | + new Error("Reload failed"), | |
| 95 | + ); | |
| 83 | 96 | |
| 84 | 97 | const mockActiveRequest = { |
| 85 | 98 | toolName: "Write", |
| @@ -88,7 +101,7 @@ | ||
| 88 | 101 | |
| 89 | 102 | const approved = true; |
| 90 | 103 | const createPolicy = true; |
| 91 | - | |
| 104 | + | |
| 92 | 105 | // Test that error handling works correctly - this should not throw |
| 93 | 106 | let errorCaught = false; |
| 94 | 107 | try { |
| @@ -101,12 +114,11 @@ | ||
| 101 | 114 | mockActiveRequest.toolName, |
| 102 | 115 | mockActiveRequest.toolArgs, |
| 103 | 116 | ); |
| 104 | - | |
| 117 | + | |
| 105 | 118 | await addPolicyToYaml(policyRule); |
| 106 | - | |
| 119 | + | |
| 107 | 120 | // This should fail but not break the flow |
| 108 | 121 | await services.mode.getToolPermissionService().reloadPermissions(); |
| 109 | - | |
| 110 | 122 | } catch (error) { |
| 111 | 123 | // Error should be caught and handled gracefully |
| 112 | 124 | errorCaught = true; |
| @@ -121,8 +133,12 @@ | ||
| 121 | 133 | |
| 122 | 134 | it("verifies the expected improvement: policy takes effect immediately", async () => { |
| 123 | 135 | // 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 | + ); | |
| 126 | 142 | vi.mocked(addPolicyToYaml).mockResolvedValue(undefined); |
| 127 | 143 | |
| 128 | 144 | // Mock successful reload |
| @@ -137,7 +153,7 @@ | ||
| 137 | 153 | // Simulate user choosing "Continue + don't ask again" |
| 138 | 154 | const approved = true; |
| 139 | 155 | const createPolicy = true; |
| 140 | - | |
| 156 | + | |
| 141 | 157 | // The workflow should complete successfully |
| 142 | 158 | if (approved && createPolicy && mockActiveRequest) { |
| 143 | 159 | const { generatePolicyRule, addPolicyToYaml } = await import( |
| @@ -156,10 +172,10 @@ | ||
| 156 | 172 | |
| 157 | 173 | // AFTER: Policy is now active without restart |
| 158 | 174 | // Next time user tries to edit a file, it should be automatically allowed |
| 159 | - | |
| 175 | + | |
| 160 | 176 | expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled(); |
| 161 | - | |
| 177 | + | |
| 162 | 178 | // This represents the improvement: the new policy takes effect immediately |
| 163 | 179 | // without requiring the user to restart the Continue CLI |
| 164 | 180 | }); |
| 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 @@ | ||
| 14 | 14 | beforeEach(async () => { |
| 15 | 15 | context = createUITestContext({ |
| 16 | 16 | allServicesReady: true, |
| 17 | - serviceState: "ready", | |
| 17 | + serviceState: "ready", | |
| 18 | 18 | serviceValue: { some: "data" }, |
| 19 | 19 | }); |
| 20 | - | |
| 20 | + | |
| 21 | 21 | // Ensure mode service is properly initialized in normal mode |
| 22 | 22 | await modeService.initialize({}); |
| 23 | 23 | }); |
| @@ -37,30 +37,30 @@ | ||
| 37 | 37 | |
| 38 | 38 | // b) Shift+Tab to switch into plan mode |
| 39 | 39 | stdin.write("\x1b[Z"); |
| 40 | - await new Promise(resolve => setTimeout(resolve, 200)); | |
| 41 | - | |
| 40 | + await new Promise((resolve) => setTimeout(resolve, 200)); | |
| 41 | + | |
| 42 | 42 | frame = lastFrame(); |
| 43 | - | |
| 43 | + | |
| 44 | 44 | // c) Make sure the string "[plan]" is on the screen |
| 45 | 45 | expect(frame!).toContain("[plan]"); |
| 46 | - | |
| 46 | + | |
| 47 | 47 | // d) Successfully send a message without error |
| 48 | 48 | const testMessage = "Can you help me analyze this code?"; |
| 49 | 49 | stdin.write(testMessage); |
| 50 | 50 | stdin.write("\r"); |
| 51 | - | |
| 51 | + | |
| 52 | 52 | // Wait for message processing |
| 53 | - await new Promise(resolve => setTimeout(resolve, 300)); | |
| 54 | - | |
| 53 | + await new Promise((resolve) => setTimeout(resolve, 300)); | |
| 54 | + | |
| 55 | 55 | frame = lastFrame(); |
| 56 | - | |
| 56 | + | |
| 57 | 57 | // Verify no crash occurred and UI is still functional |
| 58 | 58 | expect(frame).toBeDefined(); |
| 59 | 59 | expect(frame!.length).toBeGreaterThan(0); |
| 60 | - | |
| 60 | + | |
| 61 | 61 | // Should still be in plan mode after sending message |
| 62 | 62 | expect(frame!).toContain("[plan]"); |
| 63 | - | |
| 63 | + | |
| 64 | 64 | // Should still show the input prompt |
| 65 | 65 | expect(frame!).toContain("Ask anything"); |
| 66 | 66 | } finally { |
| @@ -79,62 +79,58 @@ | ||
| 79 | 79 | |
| 80 | 80 | // Switch to plan mode |
| 81 | 81 | stdin.write("\x1b[Z"); |
| 82 | - await new Promise(resolve => setTimeout(resolve, 100)); | |
| 83 | - | |
| 82 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 83 | + | |
| 84 | 84 | frame = lastFrame(); |
| 85 | 85 | expect(frame!).toContain("[plan]"); |
| 86 | 86 | |
| 87 | 87 | // Switch to auto mode |
| 88 | 88 | stdin.write("\x1b[Z"); |
| 89 | - await new Promise(resolve => setTimeout(resolve, 100)); | |
| 90 | - | |
| 89 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 90 | + | |
| 91 | 91 | frame = lastFrame(); |
| 92 | 92 | expect(frame!).toContain("[auto]"); |
| 93 | 93 | expect(frame!).not.toContain("[plan]"); |
| 94 | 94 | |
| 95 | 95 | // Switch back to normal mode |
| 96 | 96 | stdin.write("\x1b[Z"); |
| 97 | - await new Promise(resolve => setTimeout(resolve, 100)); | |
| 98 | - | |
| 97 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 98 | + | |
| 99 | 99 | frame = lastFrame(); |
| 100 | 100 | expect(frame!).not.toContain("[plan]"); |
| 101 | 101 | expect(frame!).not.toContain("[auto]"); |
| 102 | - | |
| 103 | - | |
| 104 | 102 | } finally { |
| 105 | 103 | unmount(); |
| 106 | 104 | } |
| 107 | 105 | }); |
| 108 | 106 | |
| 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 () => { | |
| 110 | 108 | const { lastFrame, stdin, unmount } = render(React.createElement(AppRoot)); |
| 111 | 109 | |
| 112 | 110 | try { |
| 113 | 111 | // Switch to plan mode |
| 114 | 112 | stdin.write("\x1b[Z"); |
| 115 | - await new Promise(resolve => setTimeout(resolve, 100)); | |
| 116 | - | |
| 113 | + await new Promise((resolve) => setTimeout(resolve, 100)); | |
| 114 | + | |
| 117 | 115 | let frame = lastFrame(); |
| 118 | 116 | expect(frame!).toContain("[plan]"); |
| 119 | 117 | |
| 120 | 118 | // Send a message while in plan mode |
| 121 | 119 | stdin.write("Test message"); |
| 122 | 120 | stdin.write("\r"); |
| 123 | - await new Promise(resolve => setTimeout(resolve, 200)); | |
| 124 | - | |
| 121 | + await new Promise((resolve) => setTimeout(resolve, 200)); | |
| 122 | + | |
| 125 | 123 | frame = lastFrame(); |
| 126 | 124 | |
| 127 | 125 | // Try to switch to another mode - this is where the bug might occur |
| 128 | 126 | 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 | + | |
| 131 | 129 | frame = lastFrame(); |
| 132 | - | |
| 130 | + | |
| 133 | 131 | // This should work - if it fails, we've reproduced the "can't switch back" bug |
| 134 | 132 | expect(frame!).toContain("[auto]"); |
| 135 | 133 | expect(frame!).not.toContain("[plan]"); |
| 136 | - | |
| 137 | - | |
| 138 | 134 | } finally { |
| 139 | 135 | unmount(); |
| 140 | 136 | } |
| @@ -143,39 +139,41 @@ | ||
| 143 | 139 | it.skip("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => { |
| 144 | 140 | // This test specifically tests the service container interaction |
| 145 | 141 | // that causes the actual bug in production |
| 146 | - | |
| 142 | + | |
| 147 | 143 | // First, set up a realistic service state (not mocked) |
| 148 | 144 | await modeService.initialize({ isHeadless: false }); |
| 149 | - | |
| 145 | + | |
| 150 | 146 | // Register the tool permissions service like the real app does |
| 151 | 147 | 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 | + | |
| 154 | 153 | // Verify initial state works |
| 155 | 154 | expect(() => getAllTools()).not.toThrow(); |
| 156 | - | |
| 155 | + | |
| 157 | 156 | // Switch modes WITHOUT updating the service container (this simulates the bug) |
| 158 | 157 | modeService.switchMode("plan"); |
| 159 | - | |
| 158 | + | |
| 160 | 159 | // The service container still has the old state, so getAllTools() should not find |
| 161 | 160 | // the updated state with plan mode permissions. However, since the ToolPermissionService |
| 162 | 161 | // overrides isReady() to always return true, getAllTools() will actually work. |
| 163 | 162 | // 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 | |
| 166 | 165 | // container has a stale state that doesn't match the ToolPermissionService |
| 167 | 166 | const staleState = { ...initialState, currentMode: "normal" as const }; |
| 168 | 167 | serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, staleState); |
| 169 | - | |
| 170 | - | |
| 168 | + | |
| 171 | 169 | // Now getAllTools() should work because it gets the service state from the container |
| 172 | 170 | // and the container has a valid state (even if it's stale) |
| 173 | 171 | const tools = getAllTools(); |
| 174 | 172 | expect(tools).toBeDefined(); |
| 175 | 173 | expect(Array.isArray(tools)).toBe(true); |
| 176 | - | |
| 174 | + | |
| 177 | 175 | // But the tools returned will be for "normal" mode, not "plan" mode |
| 178 | 176 | // In plan mode, many tools should be excluded, but with stale normal state, all tools are available |
| 179 | 177 | const planModeState = modeService.getToolPermissionService().getState(); |
| 180 | 178 | }); |
| 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 @@ | ||
| 19 | 19 | }); |
| 20 | 20 | |
| 21 | 21 | 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" />); | |
| 25 | 23 | const frame = lastFrame(); |
| 26 | 24 | |
| 27 | 25 | expect(frame).toBeDefined(); |
| @@ -30,9 +28,7 @@ | ||
| 30 | 28 | }); |
| 31 | 29 | |
| 32 | 30 | 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" />); | |
| 36 | 32 | const frame = lastFrame(); |
| 37 | 33 | |
| 38 | 34 | // Should show remote mode in the UI |
| @@ -40,9 +36,7 @@ | ||
| 40 | 36 | }); |
| 41 | 37 | |
| 42 | 38 | 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" />); | |
| 46 | 40 | const frame = lastFrame(); |
| 47 | 41 | |
| 48 | 42 | // Should not show loading services message |
| @@ -54,7 +48,7 @@ | ||
| 54 | 48 | |
| 55 | 49 | it("handles different remote URLs", () => { |
| 56 | 50 | const { lastFrame } = render( |
| 57 | - <AppRoot remoteUrl="https://api.example.com:8080" /> | |
| 51 | + <AppRoot remoteUrl="https://api.example.com:8080" />, | |
| 58 | 52 | ); |
| 59 | 53 | const frame = lastFrame(); |
| 60 | 54 | |
| @@ -65,7 +59,7 @@ | ||
| 65 | 59 | |
| 66 | 60 | it("shows slash commands in remote mode", async () => { |
| 67 | 61 | const { lastFrame, stdin } = render( |
| 68 | - <AppRoot remoteUrl="http://localhost:3000" /> | |
| 62 | + <AppRoot remoteUrl="http://localhost:3000" />, | |
| 69 | 63 | ); |
| 70 | 64 | |
| 71 | 65 | // Wait for initial render |
| @@ -84,13 +78,13 @@ | ||
| 84 | 78 | |
| 85 | 79 | // The slash command menu might show /exit or navigation instructions |
| 86 | 80 | // 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; | |
| 93 | 87 | |
| 94 | 88 | expect(hasSlashCommandUI).toBe(true); |
| 95 | 89 | }); |
| 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 @@ | ||
| 14 | 14 | |
| 15 | 15 | // Should show the slash character |
| 16 | 16 | expect(frame).toContain("/"); |
| 17 | - | |
| 17 | + | |
| 18 | 18 | // Mode-specific assertions |
| 19 | - if (mode === 'remote') { | |
| 19 | + if (mode === "remote") { | |
| 20 | 20 | expect(frame).toContain("Remote Mode"); |
| 21 | 21 | } else { |
| 22 | 22 | expect(frame).not.toContain("Remote Mode"); |
| @@ -37,9 +37,9 @@ | ||
| 37 | 37 | |
| 38 | 38 | // Should show the typed command |
| 39 | 39 | expect(frame).toContain("/log"); |
| 40 | - | |
| 40 | + | |
| 41 | 41 | // Mode-specific UI elements |
| 42 | - if (mode === 'remote') { | |
| 42 | + if (mode === "remote") { | |
| 43 | 43 | expect(frame).toContain("Remote Mode"); |
| 44 | 44 | } else { |
| 45 | 45 | expect(frame).not.toContain("Remote Mode"); |
| @@ -52,9 +52,9 @@ | ||
| 52 | 52 | |
| 53 | 53 | // Type /log and then tab |
| 54 | 54 | stdin.write("/log"); |
| 55 | - | |
| 55 | + | |
| 56 | 56 | await new Promise((resolve) => setTimeout(resolve, 50)); |
| 57 | - | |
| 57 | + | |
| 58 | 58 | stdin.write("\t"); |
| 59 | 59 | |
| 60 | 60 | await new Promise((resolve) => setTimeout(resolve, 50)); |
| @@ -65,9 +65,9 @@ | ||
| 65 | 65 | expect(frameAfterTab).toBeDefined(); |
| 66 | 66 | if (frameAfterTab) { |
| 67 | 67 | expect(frameAfterTab.length).toBeGreaterThan(0); |
| 68 | - | |
| 68 | + | |
| 69 | 69 | // Mode-specific checks |
| 70 | - if (mode === 'remote') { | |
| 70 | + if (mode === "remote") { | |
| 71 | 71 | expect(frameAfterTab).toContain("Remote Mode"); |
| 72 | 72 | } else { |
| 73 | 73 | expect(frameAfterTab).not.toContain("Remote Mode"); |
| @@ -87,9 +87,9 @@ | ||
| 87 | 87 | |
| 88 | 88 | // Should show the slash |
| 89 | 89 | expect(frame).toContain("/"); |
| 90 | - | |
| 90 | + | |
| 91 | 91 | // In remote mode, slash command menu shows immediately |
| 92 | - if (mode === 'remote') { | |
| 92 | + if (mode === "remote") { | |
| 93 | 93 | expect(frame).toContain("/exit"); |
| 94 | 94 | expect(frame).toContain("Remote Mode"); |
| 95 | 95 | } else { |
| @@ -101,4 +101,4 @@ | ||
| 101 | 101 | expect(hasSlash).toBe(true); |
| 102 | 102 | } |
| 103 | 103 | }); |
| 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 @@ | ||
| 27 | 27 | }} |
| 28 | 28 | requestId="test-request-123" |
| 29 | 29 | onResponse={handleResponse} |
| 30 | - /> | |
| 30 | + />, | |
| 31 | 31 | ); |
| 32 | 32 | |
| 33 | 33 | await vi.advanceTimersByTimeAsync(50); |
| @@ -42,7 +42,7 @@ | ||
| 42 | 42 | "test-request-123", |
| 43 | 43 | false, // approved = false |
| 44 | 44 | false, // createPolicy = false |
| 45 | - true // stopStream = true | |
| 45 | + true, // stopStream = true | |
| 46 | 46 | ); |
| 47 | 47 | }); |
| 48 | 48 | |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | }} |
| 59 | 59 | requestId="dangerous-request" |
| 60 | 60 | onResponse={handleResponse} |
| 61 | - /> | |
| 61 | + />, | |
| 62 | 62 | ); |
| 63 | 63 | |
| 64 | 64 | await vi.advanceTimersByTimeAsync(50); |
| @@ -73,14 +73,14 @@ | ||
| 73 | 73 | "dangerous-request", |
| 74 | 74 | false, // rejected |
| 75 | 75 | false, // createPolicy = false |
| 76 | - true // stopStream = true | |
| 76 | + true, // stopStream = true | |
| 77 | 77 | ); |
| 78 | 78 | }); |
| 79 | 79 | |
| 80 | 80 | it("tests that rejection response leads to stream stopping behavior", () => { |
| 81 | 81 | // This test validates the key behavior - when onResponse is called with approved=false, |
| 82 | 82 | // it should lead to the streamChatResponse function stopping and returning early |
| 83 | - | |
| 83 | + | |
| 84 | 84 | const mockStreamingFunction = vi.fn().mockImplementation((approved) => { |
| 85 | 85 | if (!approved) { |
| 86 | 86 | // Simulate early return when tool is rejected |
| @@ -104,10 +104,12 @@ | ||
| 104 | 104 | |
| 105 | 105 | it("validates permission manager handles rejection correctly", async () => { |
| 106 | 106 | // 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 | + ); | |
| 108 | 110 | |
| 109 | 111 | const mockResolve = vi.fn(); |
| 110 | - | |
| 112 | + | |
| 111 | 113 | // Simulate a pending request |
| 112 | 114 | const requestId = "test-request-456"; |
| 113 | 115 | (toolPermissionManager as any).pendingRequests.set(requestId, { |
| @@ -121,15 +123,17 @@ | ||
| 121 | 123 | // Verify the request was properly rejected |
| 122 | 124 | expect(result).toBe(true); |
| 123 | 125 | expect(mockResolve).toHaveBeenCalledWith({ approved: false }); |
| 124 | - | |
| 126 | + | |
| 125 | 127 | // 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 | + ); | |
| 127 | 131 | }); |
| 128 | 132 | |
| 129 | 133 | it("handles multiple tool calls correctly when first is rejected", () => { |
| 130 | 134 | // Test the bug fix: when multiple tool calls are present and the first is rejected, |
| 131 | 135 | // remaining tool calls should be marked as cancelled to maintain chat history consistency |
| 132 | - | |
| 136 | + | |
| 133 | 137 | const mockMultipleToolCalls = [ |
| 134 | 138 | { id: "call_1", name: "Edit", arguments: {} }, |
| 135 | 139 | { id: "call_2", name: "Write", arguments: {} }, |
| @@ -143,10 +147,10 @@ | ||
| 143 | 147 | // Simulate the rejection handling logic |
| 144 | 148 | const deniedMessage = "Permission denied by user"; |
| 145 | 149 | const rejectedToolCall = mockMultipleToolCalls[0]; |
| 146 | - | |
| 150 | + | |
| 147 | 151 | // First tool call gets denied |
| 148 | 152 | mockCallbacks.onToolResult(deniedMessage, rejectedToolCall.name); |
| 149 | - | |
| 153 | + | |
| 150 | 154 | // Remaining tool calls should be cancelled |
| 151 | 155 | for (let i = 1; i < mockMultipleToolCalls.length; i++) { |
| 152 | 156 | const remainingToolCall = mockMultipleToolCalls[i]; |
| @@ -156,30 +160,62 @@ | ||
| 156 | 160 | |
| 157 | 161 | // Verify all tool calls got results |
| 158 | 162 | 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 | + ); | |
| 162 | 178 | }); |
| 163 | 179 | |
| 164 | 180 | it("ensures proper response content in headless mode", () => { |
| 165 | 181 | // 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 | + ) => { | |
| 168 | 189 | // Simulate the fixed return logic |
| 169 | - const responseToReturn = isHeadless ? (finalResponse || content) : fullResponse; | |
| 190 | + const responseToReturn = isHeadless | |
| 191 | + ? finalResponse || content | |
| 192 | + : fullResponse; | |
| 170 | 193 | return responseToReturn; |
| 171 | 194 | }; |
| 172 | 195 | |
| 173 | 196 | // 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"); | |
| 176 | 205 | |
| 177 | 206 | // 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"); | |
| 180 | 210 | |
| 181 | 211 | // 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"); | |
| 184 | 220 | }); |
| 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 @@ | ||
| 19 | 19 | }); |
| 20 | 20 | |
| 21 | 21 | 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" />); | |
| 25 | 23 | const frame = lastFrame(); |
| 26 | 24 | |
| 27 | 25 | expect(frame).toBeDefined(); |
| @@ -29,9 +27,7 @@ | ||
| 29 | 27 | }); |
| 30 | 28 | |
| 31 | 29 | 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" />); | |
| 35 | 31 | const frame = lastFrame(); |
| 36 | 32 | |
| 37 | 33 | // Should render normally even without tools |
| @@ -41,7 +37,7 @@ | ||
| 41 | 37 | |
| 42 | 38 | it("maintains UI stability during tool operations", async () => { |
| 43 | 39 | const { lastFrame, stdin } = render( |
| 44 | - <AppRoot remoteUrl="http://localhost:3000" /> | |
| 40 | + <AppRoot remoteUrl="http://localhost:3000" />, | |
| 45 | 41 | ); |
| 46 | 42 | |
| 47 | 43 | // Type a message that might trigger tool use |
| @@ -60,7 +56,7 @@ | ||
| 60 | 56 | |
| 61 | 57 | it("shows tool-related slash commands", async () => { |
| 62 | 58 | const { lastFrame, stdin } = render( |
| 63 | - <AppRoot remoteUrl="http://localhost:3000" /> | |
| 59 | + <AppRoot remoteUrl="http://localhost:3000" />, | |
| 64 | 60 | ); |
| 65 | 61 | |
| 66 | 62 | // Wait for initial render |
| @@ -79,13 +75,13 @@ | ||
| 79 | 75 | |
| 80 | 76 | // The slash command menu might show different UI states |
| 81 | 77 | // 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; | |
| 88 | 84 | |
| 89 | 85 | expect(hasSlashCommandIndicator).toBe(true); |
| 90 | 86 | }); |
| 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 @@ | ||
| 26 | 26 | }} |
| 27 | 27 | requestId="test-request-123" |
| 28 | 28 | onResponse={handleResponse} |
| 29 | - /> | |
| 29 | + />, | |
| 30 | 30 | ); |
| 31 | 31 | |
| 32 | 32 | await vi.advanceTimersByTimeAsync(50); |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | }} |
| 59 | 59 | requestId="test-request-123" |
| 60 | 60 | onResponse={handleResponse} |
| 61 | - /> | |
| 61 | + />, | |
| 62 | 62 | ); |
| 63 | 63 | |
| 64 | 64 | await vi.advanceTimersByTimeAsync(50); |
| @@ -72,7 +72,7 @@ | ||
| 72 | 72 | "test-request-123", |
| 73 | 73 | true, |
| 74 | 74 | false, |
| 75 | - false | |
| 75 | + false, | |
| 76 | 76 | ); |
| 77 | 77 | }); |
| 78 | 78 | |
| @@ -87,7 +87,7 @@ | ||
| 87 | 87 | }} |
| 88 | 88 | requestId="test-request-456" |
| 89 | 89 | onResponse={handleResponse} |
| 90 | - /> | |
| 90 | + />, | |
| 91 | 91 | ); |
| 92 | 92 | |
| 93 | 93 | await vi.advanceTimersByTimeAsync(50); |
| @@ -101,7 +101,7 @@ | ||
| 101 | 101 | "test-request-456", |
| 102 | 102 | false, |
| 103 | 103 | false, |
| 104 | - true | |
| 104 | + true, | |
| 105 | 105 | ); |
| 106 | 106 | }); |
| 107 | 107 | |
| @@ -116,7 +116,7 @@ | ||
| 116 | 116 | }} |
| 117 | 117 | requestId="test-request-789" |
| 118 | 118 | onResponse={handleResponse} |
| 119 | - /> | |
| 119 | + />, | |
| 120 | 120 | ); |
| 121 | 121 | |
| 122 | 122 | await vi.advanceTimersByTimeAsync(50); |
| @@ -130,7 +130,7 @@ | ||
| 130 | 130 | "test-request-789", |
| 131 | 131 | false, |
| 132 | 132 | false, |
| 133 | - true | |
| 133 | + true, | |
| 134 | 134 | ); |
| 135 | 135 | }); |
| 136 | 136 | |
| @@ -145,7 +145,7 @@ | ||
| 145 | 145 | }} |
| 146 | 146 | requestId="test-request-123" |
| 147 | 147 | onResponse={handleResponse} |
| 148 | - /> | |
| 148 | + />, | |
| 149 | 149 | ); |
| 150 | 150 | |
| 151 | 151 | await vi.advanceTimersByTimeAsync(50); |
| @@ -162,7 +162,7 @@ | ||
| 162 | 162 | "test-request-123", |
| 163 | 163 | true, |
| 164 | 164 | undefined, |
| 165 | - undefined | |
| 165 | + undefined, | |
| 166 | 166 | ); |
| 167 | 167 | }); |
| 168 | 168 | |
| @@ -177,7 +177,7 @@ | ||
| 177 | 177 | }} |
| 178 | 178 | requestId="test-request-policy" |
| 179 | 179 | onResponse={handleResponse} |
| 180 | - /> | |
| 180 | + />, | |
| 181 | 181 | ); |
| 182 | 182 | |
| 183 | 183 | await vi.advanceTimersByTimeAsync(50); |
| @@ -192,7 +192,7 @@ | ||
| 192 | 192 | "test-request-policy", |
| 193 | 193 | true, |
| 194 | 194 | true, |
| 195 | - false | |
| 195 | + false, | |
| 196 | 196 | ); |
| 197 | 197 | }); |
| 198 | 198 | |
| @@ -209,7 +209,7 @@ | ||
| 209 | 209 | }} |
| 210 | 210 | requestId="test-request-stop" |
| 211 | 211 | onResponse={handleResponse} |
| 212 | - /> | |
| 212 | + />, | |
| 213 | 213 | ); |
| 214 | 214 | |
| 215 | 215 | await vi.advanceTimersByTimeAsync(50); |
| @@ -217,7 +217,7 @@ | ||
| 217 | 217 | // Verify the new option exists in the rendered output |
| 218 | 218 | const frame = lastFrame(); |
| 219 | 219 | expect(frame).toContain("No, and tell Continue what to do differently"); |
| 220 | - | |
| 220 | + | |
| 221 | 221 | // Verify all 3 options are present |
| 222 | 222 | expect(frame).toContain("Continue"); |
| 223 | 223 | expect(frame).toContain("Continue + don't ask again"); |
| @@ -240,7 +240,7 @@ | ||
| 240 | 240 | }} |
| 241 | 241 | requestId="test-request-escape" |
| 242 | 242 | onResponse={handleResponse} |
| 243 | - /> | |
| 243 | + />, | |
| 244 | 244 | ); |
| 245 | 245 | |
| 246 | 246 | await vi.advanceTimersByTimeAsync(50); |
| @@ -253,9 +253,9 @@ | ||
| 253 | 253 | // Verify the escape key triggers the stopStream behavior |
| 254 | 254 | expect(handleResponse).toHaveBeenCalledWith( |
| 255 | 255 | "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) | |
| 259 | 259 | ); |
| 260 | 260 | }); |
| 261 | 261 | |
| @@ -272,7 +272,7 @@ | ||
| 272 | 272 | }} |
| 273 | 273 | requestId="test-request-n-key" |
| 274 | 274 | onResponse={handleResponse} |
| 275 | - /> | |
| 275 | + />, | |
| 276 | 276 | ); |
| 277 | 277 | |
| 278 | 278 | await vi.advanceTimersByTimeAsync(50); |
| @@ -285,24 +285,22 @@ | ||
| 285 | 285 | // Verify the 'n' key triggers the stopStream behavior |
| 286 | 286 | expect(handleResponse).toHaveBeenCalledWith( |
| 287 | 287 | "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) | |
| 291 | 291 | ); |
| 292 | 292 | }); |
| 293 | 293 | |
| 294 | 294 | it("shows tool result with red dot and 'Cancelled by user' message", async () => { |
| 295 | 295 | // Import the components we need for this test |
| 296 | - const { ToolResultSummary } = await import( | |
| 297 | - "../ToolResultSummary.js" | |
| 298 | - ); | |
| 296 | + const { ToolResultSummary } = await import("../ToolResultSummary.js"); | |
| 299 | 297 | const { MemoizedMessage } = await import( |
| 300 | 298 | "../components/MemoizedMessage.js" |
| 301 | 299 | ); |
| 302 | 300 | |
| 303 | 301 | // Test the ToolResultSummary component directly |
| 304 | 302 | const { lastFrame: summaryFrame } = render( |
| 305 | - <ToolResultSummary toolName="Edit" content="Permission denied by user" /> | |
| 303 | + <ToolResultSummary toolName="Edit" content="Permission denied by user" />, | |
| 306 | 304 | ); |
| 307 | 305 | |
| 308 | 306 | const summary = summaryFrame(); |
| @@ -318,7 +316,7 @@ | ||
| 318 | 316 | }; |
| 319 | 317 | |
| 320 | 318 | const { lastFrame: messageFrame } = render( |
| 321 | - <MemoizedMessage message={message} index={0} /> | |
| 319 | + <MemoizedMessage message={message} index={0} />, | |
| 322 | 320 | ); |
| 323 | 321 | |
| 324 | 322 | 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"; | |
| 4 | 4 | |
| 5 | -import { modeService } from '../../services/ModeService.js'; | |
| 5 | +import { modeService } from "../../services/ModeService.js"; | |
| 6 | 6 | |
| 7 | -import { ModeIndicator } from './ModeIndicator.js'; | |
| 7 | +import { ModeIndicator } from "./ModeIndicator.js"; | |
| 8 | 8 | |
| 9 | - | |
| 10 | -describe('ModeIndicator', () => { | |
| 9 | +describe("ModeIndicator", () => { | |
| 11 | 10 | beforeEach(() => { |
| 12 | 11 | // Reset to normal mode for each test |
| 13 | 12 | modeService.initialize({}); |
| 14 | 13 | }); |
| 15 | 14 | |
| 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", () => { | |
| 18 | 17 | const { lastFrame } = render(<ModeIndicator />); |
| 19 | - expect(lastFrame()).toBe(''); | |
| 18 | + expect(lastFrame()).toBe(""); | |
| 20 | 19 | }); |
| 21 | 20 | |
| 22 | - it('should display plan mode with blue color', () => { | |
| 21 | + it("should display plan mode with blue color", () => { | |
| 23 | 22 | const { lastFrame } = render(<ModeIndicator mode="plan" />); |
| 24 | - expect(lastFrame()).toContain('[plan]'); | |
| 23 | + expect(lastFrame()).toContain("[plan]"); | |
| 25 | 24 | }); |
| 26 | 25 | |
| 27 | - it('should display auto mode with green color', () => { | |
| 26 | + it("should display auto mode with green color", () => { | |
| 28 | 27 | const { lastFrame } = render(<ModeIndicator mode="auto" />); |
| 29 | - expect(lastFrame()).toContain('[auto]'); | |
| 28 | + expect(lastFrame()).toContain("[auto]"); | |
| 30 | 29 | }); |
| 31 | 30 | |
| 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"); | |
| 34 | 33 | const { lastFrame } = render(<ModeIndicator />); |
| 35 | - expect(lastFrame()).toContain('[plan]'); | |
| 34 | + expect(lastFrame()).toContain("[plan]"); | |
| 36 | 35 | }); |
| 37 | 36 | |
| 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"); | |
| 40 | 39 | const { lastFrame } = render(<ModeIndicator mode="auto" />); |
| 41 | - expect(lastFrame()).toContain('[auto]'); | |
| 40 | + expect(lastFrame()).toContain("[auto]"); | |
| 42 | 41 | }); |
| 43 | 42 | }); |
| 44 | 43 | |
| 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", () => { | |
| 47 | 46 | const { lastFrame, rerender } = render(<ModeIndicator />); |
| 48 | - | |
| 47 | + | |
| 49 | 48 | // Initially normal (no display) |
| 50 | - expect(lastFrame()).toBe(''); | |
| 51 | - | |
| 49 | + expect(lastFrame()).toBe(""); | |
| 50 | + | |
| 52 | 51 | // Switch to plan |
| 53 | - modeService.switchMode('plan'); | |
| 52 | + modeService.switchMode("plan"); | |
| 54 | 53 | rerender(<ModeIndicator />); |
| 55 | - expect(lastFrame()).toContain('[plan]'); | |
| 56 | - | |
| 54 | + expect(lastFrame()).toContain("[plan]"); | |
| 55 | + | |
| 57 | 56 | // Switch to auto |
| 58 | - modeService.switchMode('auto'); | |
| 57 | + modeService.switchMode("auto"); | |
| 59 | 58 | rerender(<ModeIndicator />); |
| 60 | - expect(lastFrame()).toContain('[auto]'); | |
| 61 | - | |
| 59 | + expect(lastFrame()).toContain("[auto]"); | |
| 60 | + | |
| 62 | 61 | // Switch back to normal |
| 63 | - modeService.switchMode('normal'); | |
| 62 | + modeService.switchMode("normal"); | |
| 64 | 63 | rerender(<ModeIndicator />); |
| 65 | - expect(lastFrame()).toBe(''); | |
| 64 | + expect(lastFrame()).toBe(""); | |
| 66 | 65 | }); |
| 67 | 66 | }); |
| 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 @@ | ||
| 71 | 71 | }); |
| 72 | 72 | |
| 73 | 73 | 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 | + ); | |
| 75 | 77 | expect(formatArgs({ emoji: "🎉🎊✨" })).toBe("🎉🎊✨"); |
| 76 | 78 | }); |
| 77 | 79 | }); |
| 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 @@ | ||
| 5 | 5 | import React from "react"; |
| 6 | 6 | import { describe, it, expect, vi } from "vitest"; |
| 7 | 7 | |
| 8 | -import { NavigationProvider, useNavigation, NavigationScreen } from "../NavigationContext.js"; | |
| 8 | +import { | |
| 9 | + NavigationProvider, | |
| 10 | + useNavigation, | |
| 11 | + NavigationScreen, | |
| 12 | +} from "../NavigationContext.js"; | |
| 9 | 13 | |
| 10 | 14 | describe("NavigationContext", () => { |
| 11 | 15 | // Helper to create wrapper |
| @@ -163,13 +167,9 @@ | ||
| 163 | 167 | |
| 164 | 168 | it("closes from any screen back to chat", () => { |
| 165 | 169 | 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"]; | |
| 173 | 173 | |
| 174 | 174 | screens.forEach((screen) => { |
| 175 | 175 | act(() => { |
| @@ -257,8 +257,12 @@ | ||
| 257 | 257 | result.current.navigateTo("login", { different: "data" }); |
| 258 | 258 | }); |
| 259 | 259 | |
| 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 | + ); | |
| 262 | 266 | }); |
| 263 | 267 | }); |
| 264 | 268 | |
| @@ -269,9 +273,9 @@ | ||
| 269 | 273 | |
| 270 | 274 | // Navigate to login with resolve callback |
| 271 | 275 | 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, | |
| 275 | 279 | }); |
| 276 | 280 | }); |
| 277 | 281 | |
| @@ -344,4 +348,4 @@ | ||
| 344 | 348 | }); |
| 345 | 349 | }); |
| 346 | 350 | }); |
| 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"; | |
| 9 | 2 | |
| 10 | 3 | import { createMinimalTestContext } from "../../test-helpers/ui-test-context.js"; |
| 11 | 4 | |
| @@ -54,4 +47,4 @@ | ||
| 54 | 47 | cleanup(); |
| 55 | 48 | expect(pollInterval).toBeUndefined(); |
| 56 | 49 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -describe('useConfigSelector', () => { | |
| 4 | - test('hook updated to use reactive service pattern', () => { | |
| 3 | +describe("useConfigSelector", () => { | |
| 4 | + test("hook updated to use reactive service pattern", () => { | |
| 5 | 5 | // This test documents that useConfigSelector has been updated |
| 6 | - | |
| 6 | + | |
| 7 | 7 | // Changes made: |
| 8 | 8 | // 1. Removed manual onAssistantChange callback |
| 9 | - // 2. Now calls services.config.updateConfigPath() | |
| 9 | + // 2. Now calls services.config.updateConfigPath() | |
| 10 | 10 | // 3. Lets ServiceContainer handle dependency management |
| 11 | 11 | // 4. Allows automatic UI updates via reactive system |
| 12 | - | |
| 12 | + | |
| 13 | 13 | // The hook now properly: |
| 14 | 14 | // - Handles local config selection |
| 15 | 15 | // - Handles assistant config selection |
| 16 | 16 | // - Handles create config option |
| 17 | 17 | // - Provides error handling |
| 18 | 18 | // - Triggers reactive updates |
| 19 | - | |
| 20 | - expect('hook').toBe('hook'); | |
| 19 | + | |
| 20 | + expect("hook").toBe("hook"); | |
| 21 | 21 | }); |
| 22 | 22 | |
| 23 | - test('integrates with reactive service system', () => { | |
| 23 | + test("integrates with reactive service system", () => { | |
| 24 | 24 | // The hook integration follows the correct pattern: |
| 25 | 25 | // - User interaction → service method call |
| 26 | - // - Service handles state update and notification | |
| 26 | + // - Service handles state update and notification | |
| 27 | 27 | // - ServiceContainer manages dependency cascade |
| 28 | 28 | // - UI components re-render automatically |
| 29 | - | |
| 30 | - expect('integration').toBe('integration'); | |
| 29 | + | |
| 30 | + expect("integration").toBe("integration"); | |
| 31 | 31 | }); |
| 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"; | |
| 2 | 5 | |
| 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); | |
| 9 | 14 | }); |
| 10 | 15 | |
| 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); | |
| 18 | 23 | }); |
| 19 | 24 | |
| 20 | - it('should return false for null or undefined', () => { | |
| 25 | + it("should return false for null or undefined", () => { | |
| 21 | 26 | expect(isValidAnthropicApiKey(null)).toBe(false); |
| 22 | 27 | expect(isValidAnthropicApiKey(undefined)).toBe(false); |
| 23 | 28 | }); |
| 24 | 29 | |
| 25 | - it('should return false for non-string values', () => { | |
| 30 | + it("should return false for non-string values", () => { | |
| 26 | 31 | expect(isValidAnthropicApiKey(123 as any)).toBe(false); |
| 27 | 32 | expect(isValidAnthropicApiKey({} as any)).toBe(false); |
| 28 | 33 | expect(isValidAnthropicApiKey([] as any)).toBe(false); |
| 29 | 34 | }); |
| 30 | 35 | }); |
| 31 | 36 | |
| 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 | + ); | |
| 41 | 52 | }); |
| 42 | -}); | |
| No newline at the end of the file | ||
| 53 | +}); |
modified extensions/cli/src/util/exponentialBackoff.test.ts +9 −7
| @@ -39,11 +39,13 @@ | ||
| 39 | 39 | } |
| 40 | 40 | |
| 41 | 41 | // 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 | + ) { | |
| 47 | 49 | return true; |
| 48 | 50 | } |
| 49 | 51 | |
| @@ -52,7 +54,7 @@ | ||
| 52 | 54 | |
| 53 | 55 | function calculateDelay( |
| 54 | 56 | attempt: number, |
| 55 | - options: Required<ExponentialBackoffOptions> | |
| 57 | + options: Required<ExponentialBackoffOptions>, | |
| 56 | 58 | ): number { |
| 57 | 59 | const baseDelay = |
| 58 | 60 | options.initialDelay * Math.pow(options.backoffMultiplier, attempt); |
| @@ -270,7 +272,7 @@ | ||
| 270 | 272 | |
| 271 | 273 | // Mock Math.random to return 0.5 (middle of jitter range) |
| 272 | 274 | const originalRandom = Math.random; |
| 273 | - vi.spyOn(Math, 'random').mockReturnValue(0.5); | |
| 275 | + vi.spyOn(Math, "random").mockReturnValue(0.5); | |
| 274 | 276 | |
| 275 | 277 | // With jitter factor of 0.5 + 0.5 * 0.5 = 0.75 |
| 276 | 278 | 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"; | |
| 4 | 4 | |
| 5 | -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | |
| 5 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 6 | 6 | |
| 7 | -import { FileWatcher } from './fileWatcher.js'; | |
| 7 | +import { FileWatcher } from "./fileWatcher.js"; | |
| 8 | 8 | |
| 9 | -describe('FileWatcher', () => { | |
| 9 | +describe("FileWatcher", () => { | |
| 10 | 10 | let tempDir: string; |
| 11 | 11 | let watcher: FileWatcher; |
| 12 | 12 | |
| 13 | 13 | beforeEach(() => { |
| 14 | 14 | // 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-")); | |
| 16 | 16 | watcher = new FileWatcher({ |
| 17 | 17 | debounceMs: 100, // Shorter debounce for tests |
| 18 | - maxDepth: 2 | |
| 18 | + maxDepth: 2, | |
| 19 | 19 | }); |
| 20 | 20 | }); |
| 21 | 21 | |
| @@ -27,25 +27,25 @@ | ||
| 27 | 27 | } |
| 28 | 28 | }); |
| 29 | 29 | |
| 30 | - it.skip('should detect when new files are created', async () => { | |
| 30 | + it.skip("should detect when new files are created", async () => { | |
| 31 | 31 | const callback = vi.fn(); |
| 32 | 32 | watcher.onChange(callback); |
| 33 | 33 | watcher.startWatching(tempDir); |
| 34 | 34 | |
| 35 | 35 | // 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"); | |
| 38 | 38 | |
| 39 | 39 | // Wait for debounce |
| 40 | - await new Promise(resolve => setTimeout(resolve, 150)); | |
| 40 | + await new Promise((resolve) => setTimeout(resolve, 150)); | |
| 41 | 41 | |
| 42 | 42 | expect(callback).toHaveBeenCalled(); |
| 43 | 43 | }); |
| 44 | 44 | |
| 45 | - it.skip('should detect when files are deleted', async () => { | |
| 45 | + it.skip("should detect when files are deleted", async () => { | |
| 46 | 46 | // 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"); | |
| 49 | 49 | |
| 50 | 50 | const callback = vi.fn(); |
| 51 | 51 | watcher.onChange(callback); |
| @@ -55,16 +55,16 @@ | ||
| 55 | 55 | fs.unlinkSync(testFile); |
| 56 | 56 | |
| 57 | 57 | // Wait for debounce |
| 58 | - await new Promise(resolve => setTimeout(resolve, 150)); | |
| 58 | + await new Promise((resolve) => setTimeout(resolve, 150)); | |
| 59 | 59 | |
| 60 | 60 | expect(callback).toHaveBeenCalled(); |
| 61 | 61 | }); |
| 62 | 62 | |
| 63 | - it('should ignore paths that match ignore patterns', async () => { | |
| 63 | + it("should ignore paths that match ignore patterns", async () => { | |
| 64 | 64 | // 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"); | |
| 66 | 66 | fs.mkdirSync(nodeModulesDir); |
| 67 | - | |
| 67 | + | |
| 68 | 68 | const callback = vi.fn(); |
| 69 | 69 | watcher.onChange(callback); |
| 70 | 70 | watcher.startWatching(tempDir); |
| @@ -72,94 +72,94 @@ | ||
| 72 | 72 | // Wait longer to ensure watcher is fully initialized and settled |
| 73 | 73 | // Increase timeout for CI environments where file system events may be slower |
| 74 | 74 | // 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)); | |
| 76 | 76 | |
| 77 | 77 | // Reset the callback mock to ignore any initialization events |
| 78 | 78 | callback.mockClear(); |
| 79 | 79 | |
| 80 | 80 | // 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"); | |
| 83 | 83 | |
| 84 | 84 | // 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)); | |
| 86 | 86 | |
| 87 | 87 | // Should not have been called because node_modules is ignored |
| 88 | 88 | expect(callback).not.toHaveBeenCalled(); |
| 89 | 89 | }); |
| 90 | 90 | |
| 91 | - it('should ignore files matching wildcard patterns like **/*.tmp', async () => { | |
| 91 | + it("should ignore files matching wildcard patterns like **/*.tmp", async () => { | |
| 92 | 92 | const callback = vi.fn(); |
| 93 | 93 | watcher.onChange(callback); |
| 94 | 94 | watcher.startWatching(tempDir); |
| 95 | 95 | |
| 96 | 96 | // Wait for watcher to initialize with longer timeout for CI |
| 97 | 97 | // 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)); | |
| 99 | 99 | callback.mockClear(); |
| 100 | 100 | |
| 101 | 101 | // 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"); | |
| 104 | 104 | |
| 105 | 105 | // 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"); | |
| 108 | 108 | |
| 109 | 109 | // 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"); | |
| 112 | 112 | |
| 113 | 113 | // Wait for debounce with longer timeout for CI |
| 114 | - await new Promise(resolve => setTimeout(resolve, 500)); | |
| 114 | + await new Promise((resolve) => setTimeout(resolve, 500)); | |
| 115 | 115 | |
| 116 | 116 | // Should not have been called because all files match ignore patterns |
| 117 | 117 | expect(callback).not.toHaveBeenCalled(); |
| 118 | 118 | }); |
| 119 | 119 | |
| 120 | - it('should ignore specific files like .DS_Store', async () => { | |
| 120 | + it("should ignore specific files like .DS_Store", async () => { | |
| 121 | 121 | const callback = vi.fn(); |
| 122 | 122 | watcher.onChange(callback); |
| 123 | 123 | watcher.startWatching(tempDir); |
| 124 | 124 | |
| 125 | 125 | // Wait for watcher to initialize with longer timeout for CI |
| 126 | 126 | // 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)); | |
| 128 | 128 | callback.mockClear(); |
| 129 | 129 | |
| 130 | 130 | // 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"); | |
| 133 | 133 | |
| 134 | 134 | // Wait for debounce with longer timeout for CI |
| 135 | - await new Promise(resolve => setTimeout(resolve, 500)); | |
| 135 | + await new Promise((resolve) => setTimeout(resolve, 500)); | |
| 136 | 136 | |
| 137 | 137 | // Should not have been called because .DS_Store matches ignore pattern |
| 138 | 138 | expect(callback).not.toHaveBeenCalled(); |
| 139 | 139 | }); |
| 140 | 140 | |
| 141 | - it('should detect files that do not match ignore patterns', async () => { | |
| 141 | + it("should detect files that do not match ignore patterns", async () => { | |
| 142 | 142 | const callback = vi.fn(); |
| 143 | 143 | watcher.onChange(callback); |
| 144 | 144 | watcher.startWatching(tempDir); |
| 145 | 145 | |
| 146 | 146 | // Wait for watcher to initialize with longer timeout for CI |
| 147 | 147 | // 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)); | |
| 149 | 149 | callback.mockClear(); |
| 150 | 150 | |
| 151 | 151 | // Create a .js file (should NOT be ignored) |
| 152 | - const jsFile = path.join(tempDir, 'test.js'); | |
| 152 | + const jsFile = path.join(tempDir, "test.js"); | |
| 153 | 153 | fs.writeFileSync(jsFile, 'console.log("hello");'); |
| 154 | 154 | |
| 155 | 155 | // Wait for debounce with longer timeout for CI |
| 156 | - await new Promise(resolve => setTimeout(resolve, 500)); | |
| 156 | + await new Promise((resolve) => setTimeout(resolve, 500)); | |
| 157 | 157 | |
| 158 | 158 | // Should have been called because .js files are not in ignore patterns |
| 159 | 159 | expect(callback).toHaveBeenCalled(); |
| 160 | 160 | }); |
| 161 | 161 | |
| 162 | - it('should allow unsubscribing from callbacks', async () => { | |
| 162 | + it("should allow unsubscribing from callbacks", async () => { | |
| 163 | 163 | const callback = vi.fn(); |
| 164 | 164 | const unsubscribe = watcher.onChange(callback); |
| 165 | 165 | watcher.startWatching(tempDir); |
| @@ -168,43 +168,43 @@ | ||
| 168 | 168 | unsubscribe(); |
| 169 | 169 | |
| 170 | 170 | // 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"); | |
| 173 | 173 | |
| 174 | 174 | // Wait for debounce |
| 175 | - await new Promise(resolve => setTimeout(resolve, 150)); | |
| 175 | + await new Promise((resolve) => setTimeout(resolve, 150)); | |
| 176 | 176 | |
| 177 | 177 | // Should not have been called because we unsubscribed |
| 178 | 178 | expect(callback).not.toHaveBeenCalled(); |
| 179 | 179 | }); |
| 180 | 180 | |
| 181 | - describe('shouldIgnorePath method', () => { | |
| 182 | - it('should correctly ignore wildcard file patterns', () => { | |
| 181 | + describe("shouldIgnorePath method", () => { | |
| 182 | + it("should correctly ignore wildcard file patterns", () => { | |
| 183 | 183 | const watcher = new FileWatcher(); |
| 184 | - | |
| 184 | + | |
| 185 | 185 | // Test the private method by accessing it through prototype |
| 186 | 186 | const shouldIgnorePath = (watcher as any).shouldIgnorePath.bind(watcher); |
| 187 | - | |
| 187 | + | |
| 188 | 188 | // 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 | + | |
| 194 | 194 | // 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 | + | |
| 199 | 199 | // 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 | + | |
| 203 | 203 | // 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); | |
| 208 | 208 | }); |
| 209 | 209 | }); |
| 210 | 210 | }); |
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"; | |
| 2 | 2 | |
| 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"); | |
| 7 | 7 | }); |
| 8 | 8 | |
| 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"); | |
| 12 | 12 | }); |
| 13 | 13 | |
| 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"); | |
| 17 | 17 | }); |
| 18 | 18 | |
| 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"); | |
| 22 | 22 | }); |
| 23 | 23 | |
| 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"); | |
| 27 | 27 | }); |
| 28 | 28 | |
| 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"); | |
| 32 | 32 | }); |
| 33 | 33 | |
| 34 | - it('should format API errors with status and message', () => { | |
| 34 | + it("should format API errors with status and message", () => { | |
| 35 | 35 | const error = { |
| 36 | 36 | status: 404, |
| 37 | - error: { message: 'Not found' } | |
| 37 | + error: { message: "Not found" }, | |
| 38 | 38 | }; |
| 39 | 39 | // The actual implementation prioritizes nested error.message over status formatting |
| 40 | - expect(formatError(error)).toBe('Not found'); | |
| 40 | + expect(formatError(error)).toBe("Not found"); | |
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | - it('should format network errors with code and syscall', () => { | |
| 43 | + it("should format network errors with code and syscall", () => { | |
| 44 | 44 | const error = { |
| 45 | - code: 'ECONNREFUSED', | |
| 46 | - syscall: 'connect' | |
| 45 | + code: "ECONNREFUSED", | |
| 46 | + syscall: "connect", | |
| 47 | 47 | }; |
| 48 | - expect(formatError(error)).toBe('Network error: ECONNREFUSED in connect'); | |
| 48 | + expect(formatError(error)).toBe("Network error: ECONNREFUSED in connect"); | |
| 49 | 49 | }); |
| 50 | 50 | |
| 51 | - it('should join error arrays', () => { | |
| 51 | + it("should join error arrays", () => { | |
| 52 | 52 | const error = { |
| 53 | - errors: ['First error', 'Second error', 'Third error'] | |
| 53 | + errors: ["First error", "Second error", "Third error"], | |
| 54 | 54 | }; |
| 55 | - expect(formatError(error)).toBe('First error, Second error, Third error'); | |
| 55 | + expect(formatError(error)).toBe("First error, Second error, Third error"); | |
| 56 | 56 | }); |
| 57 | 57 | |
| 58 | - it('should JSON stringify complex objects', () => { | |
| 58 | + it("should JSON stringify complex objects", () => { | |
| 59 | 59 | const error = { |
| 60 | - code: 'CUSTOM_ERROR', | |
| 61 | - data: { id: 123, name: 'test' } | |
| 60 | + code: "CUSTOM_ERROR", | |
| 61 | + data: { id: 123, name: "test" }, | |
| 62 | 62 | }; |
| 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 | + ); | |
| 64 | 66 | }); |
| 65 | 67 | |
| 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" }; | |
| 68 | 70 | circular.self = circular; |
| 69 | 71 | |
| 70 | 72 | const result = formatError(circular); |
| 71 | - expect(result).toBe('An error occurred: [object Object]'); | |
| 73 | + expect(result).toBe("An error occurred: [object Object]"); | |
| 72 | 74 | }); |
| 73 | 75 | |
| 74 | - it('should handle null values', () => { | |
| 75 | - expect(formatError(null)).toBe('null'); | |
| 76 | + it("should handle null values", () => { | |
| 77 | + expect(formatError(null)).toBe("null"); | |
| 76 | 78 | }); |
| 77 | 79 | |
| 78 | - it('should handle undefined values', () => { | |
| 79 | - expect(formatError(undefined)).toBe('undefined'); | |
| 80 | + it("should handle undefined values", () => { | |
| 81 | + expect(formatError(undefined)).toBe("undefined"); | |
| 80 | 82 | }); |
| 81 | 83 | |
| 82 | - it('should handle numbers', () => { | |
| 83 | - expect(formatError(42)).toBe('42'); | |
| 84 | + it("should handle numbers", () => { | |
| 85 | + expect(formatError(42)).toBe("42"); | |
| 84 | 86 | }); |
| 85 | 87 | |
| 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"); | |
| 89 | 91 | }); |
| 90 | 92 | |
| 91 | - it('should handle empty objects', () => { | |
| 92 | - expect(formatError({})).toBe('{}'); | |
| 93 | + it("should handle empty objects", () => { | |
| 94 | + expect(formatError({})).toBe("{}"); | |
| 93 | 95 | }); |
| 94 | 96 | |
| 95 | - it('should handle empty arrays', () => { | |
| 96 | - expect(formatError([])).toBe('[]'); | |
| 97 | + it("should handle empty arrays", () => { | |
| 98 | + expect(formatError([])).toBe("[]"); | |
| 97 | 99 | }); |
| 98 | 100 | |
| 99 | - it('should prioritize message over other properties', () => { | |
| 101 | + it("should prioritize message over other properties", () => { | |
| 100 | 102 | 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", | |
| 104 | 106 | }; |
| 105 | - expect(formatError(error)).toBe('Primary message'); | |
| 107 | + expect(formatError(error)).toBe("Primary message"); | |
| 106 | 108 | }); |
| 107 | 109 | |
| 108 | - it('should prioritize error property over details', () => { | |
| 110 | + it("should prioritize error property over details", () => { | |
| 109 | 111 | const error = { |
| 110 | - error: 'Nested error', | |
| 111 | - details: 'Error details' | |
| 112 | + error: "Nested error", | |
| 113 | + details: "Error details", | |
| 112 | 114 | }; |
| 113 | - expect(formatError(error)).toBe('Nested error'); | |
| 115 | + expect(formatError(error)).toBe("Nested error"); | |
| 114 | 116 | }); |
| 115 | 117 | |
| 116 | - it('should handle deeply nested error structures', () => { | |
| 118 | + it("should handle deeply nested error structures", () => { | |
| 117 | 119 | const error = { |
| 118 | 120 | error: { |
| 119 | 121 | error: { |
| 120 | - message: 'Deep nested error' | |
| 121 | - } | |
| 122 | - } | |
| 122 | + message: "Deep nested error", | |
| 123 | + }, | |
| 124 | + }, | |
| 123 | 125 | }; |
| 124 | - expect(formatError(error)).toBe('Deep nested error'); | |
| 126 | + expect(formatError(error)).toBe("Deep nested error"); | |
| 125 | 127 | }); |
| 126 | 128 | |
| 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", () => { | |
| 128 | 130 | const error = { |
| 129 | 131 | status: 404, |
| 130 | - error: { code: 'NOT_FOUND' } | |
| 132 | + error: { code: "NOT_FOUND" }, | |
| 131 | 133 | }; |
| 132 | 134 | expect(formatError(error)).toBe('{"code":"NOT_FOUND"}'); |
| 133 | 135 | }); |
| 134 | 136 | }); |
| 135 | 137 | |
| 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"); | |
| 140 | 144 | }); |
| 141 | 145 | |
| 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"); | |
| 146 | 150 | }); |
| 147 | 151 | |
| 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"); | |
| 150 | 154 | }); |
| 151 | 155 | }); |
modified extensions/cli/src/util/git.test.ts +9 −10
| @@ -1,9 +1,6 @@ | ||
| 1 | 1 | import { beforeEach, describe, expect, it } from "vitest"; |
| 2 | 2 | |
| 3 | -import { | |
| 4 | - getGitHubActionsRepoUrl, | |
| 5 | - isGitHubActions, | |
| 6 | -} from "./git.js"; | |
| 3 | +import { getGitHubActionsRepoUrl, isGitHubActions } from "./git.js"; | |
| 7 | 4 | |
| 8 | 5 | describe("git utilities - GitHub Actions detection", () => { |
| 9 | 6 | beforeEach(() => { |
| @@ -42,7 +39,7 @@ | ||
| 42 | 39 | it("should return GitHub URL with default server", () => { |
| 43 | 40 | process.env.GITHUB_ACTIONS = "true"; |
| 44 | 41 | process.env.GITHUB_REPOSITORY = "owner/repo"; |
| 45 | - | |
| 42 | + | |
| 46 | 43 | expect(getGitHubActionsRepoUrl()).toBe("https://github.com/owner/repo"); |
| 47 | 44 | }); |
| 48 | 45 | |
| @@ -50,8 +47,10 @@ | ||
| 50 | 47 | process.env.GITHUB_ACTIONS = "true"; |
| 51 | 48 | process.env.GITHUB_REPOSITORY = "owner/repo"; |
| 52 | 49 | 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 | + ); | |
| 55 | 54 | }); |
| 56 | 55 | }); |
| 57 | 56 | |
| @@ -59,7 +58,7 @@ | ||
| 59 | 58 | it("should prioritize GitHub Actions environment variables", () => { |
| 60 | 59 | process.env.GITHUB_ACTIONS = "true"; |
| 61 | 60 | process.env.GITHUB_REPOSITORY = "owner/repo"; |
| 62 | - | |
| 61 | + | |
| 63 | 62 | // Since we can't easily mock git commands, we'll rely on the fact that |
| 64 | 63 | // GitHub Actions detection should take priority and return immediately |
| 65 | 64 | const result = getGitHubActionsRepoUrl(); |
| @@ -70,9 +69,9 @@ | ||
| 70 | 69 | process.env.GITHUB_ACTIONS = "true"; |
| 71 | 70 | process.env.GITHUB_REPOSITORY = "enterprise/repo"; |
| 72 | 71 | process.env.GITHUB_SERVER_URL = "https://git.company.com"; |
| 73 | - | |
| 72 | + | |
| 74 | 73 | const result = getGitHubActionsRepoUrl(); |
| 75 | 74 | expect(result).toBe("https://git.company.com/enterprise/repo"); |
| 76 | 75 | }); |
| 77 | 76 | }); |
| 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"; | |
| 2 | 2 | |
| 3 | -import { InputHistory } from './inputHistory.js'; | |
| 3 | +import { InputHistory } from "./inputHistory.js"; | |
| 4 | 4 | |
| 5 | 5 | // Mock fs to avoid creating actual files during tests |
| 6 | -vi.mock('fs', () => ({ | |
| 6 | +vi.mock("fs", () => ({ | |
| 7 | 7 | default: { |
| 8 | 8 | existsSync: vi.fn(), |
| 9 | 9 | readFileSync: vi.fn(), |
| 10 | 10 | writeFileSync: vi.fn(), |
| 11 | - mkdirSync: vi.fn() | |
| 11 | + mkdirSync: vi.fn(), | |
| 12 | 12 | }, |
| 13 | 13 | existsSync: vi.fn(), |
| 14 | 14 | readFileSync: vi.fn(), |
| 15 | 15 | writeFileSync: vi.fn(), |
| 16 | - mkdirSync: vi.fn() | |
| 16 | + mkdirSync: vi.fn(), | |
| 17 | 17 | })); |
| 18 | 18 | |
| 19 | -describe('InputHistory', () => { | |
| 19 | +describe("InputHistory", () => { | |
| 20 | 20 | let inputHistory: InputHistory; |
| 21 | 21 | |
| 22 | 22 | beforeEach(async () => { |
| 23 | 23 | // Reset mocks and set up default behavior |
| 24 | 24 | vi.clearAllMocks(); |
| 25 | - const fs = await import('fs'); | |
| 25 | + const fs = await import("fs"); | |
| 26 | 26 | vi.mocked(fs.existsSync).mockReturnValue(false); |
| 27 | - vi.mocked(fs.readFileSync).mockReturnValue('[]'); | |
| 27 | + vi.mocked(fs.readFileSync).mockReturnValue("[]"); | |
| 28 | 28 | |
| 29 | 29 | inputHistory = new InputHistory(); |
| 30 | 30 | }); |
| 31 | 31 | |
| 32 | - describe('navigation with typed input preservation', () => { | |
| 32 | + describe("navigation with typed input preservation", () => { | |
| 33 | 33 | beforeEach(() => { |
| 34 | 34 | // Add some history entries |
| 35 | - inputHistory.addEntry('first command'); | |
| 36 | - inputHistory.addEntry('second command'); | |
| 35 | + inputHistory.addEntry("first command"); | |
| 36 | + inputHistory.addEntry("second command"); | |
| 37 | 37 | }); |
| 38 | 38 | |
| 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"; | |
| 41 | 41 | |
| 42 | 42 | // User types something then presses up arrow |
| 43 | 43 | const historyEntry1 = inputHistory.navigateUp(typedInput); |
| 44 | - expect(historyEntry1).toBe('second command'); | |
| 44 | + expect(historyEntry1).toBe("second command"); | |
| 45 | 45 | |
| 46 | 46 | // Then presses down arrow - should get back their typed input |
| 47 | 47 | const returnedInput = inputHistory.navigateDown(); |
| 48 | - expect(returnedInput).toBe('user typed this'); | |
| 48 | + expect(returnedInput).toBe("user typed this"); | |
| 49 | 49 | }); |
| 50 | 50 | |
| 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"; | |
| 53 | 53 | |
| 54 | 54 | // Navigate up twice, then back down twice |
| 55 | 55 | inputHistory.navigateUp(typedInput); |
| @@ -57,32 +57,32 @@ | ||
| 57 | 57 | inputHistory.navigateDown(); // Go back one in history |
| 58 | 58 | const result = inputHistory.navigateDown(); // Go back to original |
| 59 | 59 | |
| 60 | - expect(result).toBe('hello world'); | |
| 60 | + expect(result).toBe("hello world"); | |
| 61 | 61 | }); |
| 62 | 62 | }); |
| 63 | 63 | |
| 64 | - describe('basic navigation functionality', () => { | |
| 64 | + describe("basic navigation functionality", () => { | |
| 65 | 65 | 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"); | |
| 69 | 69 | }); |
| 70 | 70 | |
| 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 | |
| 74 | 74 | |
| 75 | - const result2 = inputHistory.navigateUp('current'); | |
| 76 | - expect(result2).toBe('command2'); | |
| 75 | + const result2 = inputHistory.navigateUp("current"); | |
| 76 | + expect(result2).toBe("command2"); | |
| 77 | 77 | |
| 78 | - const result3 = inputHistory.navigateUp('current'); | |
| 79 | - expect(result3).toBe('command1'); | |
| 78 | + const result3 = inputHistory.navigateUp("current"); | |
| 79 | + expect(result3).toBe("command1"); | |
| 80 | 80 | }); |
| 81 | 81 | |
| 82 | - it('should handle navigation with no history', () => { | |
| 82 | + it("should handle navigation with no history", () => { | |
| 83 | 83 | const emptyHistory = new InputHistory(); |
| 84 | - const result = emptyHistory.navigateUp('test'); | |
| 84 | + const result = emptyHistory.navigateUp("test"); | |
| 85 | 85 | expect(result).toBe(null); |
| 86 | 86 | }); |
| 87 | 87 | }); |
| 88 | -}); | |
| No newline at the end of the file | ||
| 88 | +}); |
modified extensions/cli/src/util/stdin.test.ts +34 −34
| @@ -24,28 +24,28 @@ | ||
| 24 | 24 | it("should return null in test environments", async () => { |
| 25 | 25 | // Test that the function respects test environment variables |
| 26 | 26 | process.env.NODE_ENV = "test"; |
| 27 | - | |
| 27 | + | |
| 28 | 28 | const { readStdinSync } = await import("./stdin.js"); |
| 29 | 29 | const result = readStdinSync(); |
| 30 | - | |
| 30 | + | |
| 31 | 31 | expect(result).toBe(null); |
| 32 | 32 | }); |
| 33 | 33 | |
| 34 | 34 | it("should return null when CONTINUE_CLI_TEST is set", async () => { |
| 35 | 35 | process.env.CONTINUE_CLI_TEST = "true"; |
| 36 | - | |
| 36 | + | |
| 37 | 37 | const { readStdinSync } = await import("./stdin.js"); |
| 38 | 38 | const result = readStdinSync(); |
| 39 | - | |
| 39 | + | |
| 40 | 40 | expect(result).toBe(null); |
| 41 | 41 | }); |
| 42 | 42 | |
| 43 | 43 | it("should return null when VITEST is set", async () => { |
| 44 | 44 | process.env.VITEST = "true"; |
| 45 | - | |
| 45 | + | |
| 46 | 46 | const { readStdinSync } = await import("./stdin.js"); |
| 47 | 47 | const result = readStdinSync(); |
| 48 | - | |
| 48 | + | |
| 49 | 49 | expect(result).toBe(null); |
| 50 | 50 | }); |
| 51 | 51 | |
| @@ -55,13 +55,13 @@ | ||
| 55 | 55 | delete process.env.VITEST; |
| 56 | 56 | delete process.env.CONTINUE_CLI_TEST; |
| 57 | 57 | delete process.env.JEST_WORKER_ID; |
| 58 | - | |
| 58 | + | |
| 59 | 59 | // Mock stdin as TTY |
| 60 | 60 | (process.stdin as any).isTTY = true; |
| 61 | - | |
| 61 | + | |
| 62 | 62 | const { readStdinSync } = await import("./stdin.js"); |
| 63 | 63 | const result = readStdinSync(); |
| 64 | - | |
| 64 | + | |
| 65 | 65 | expect(result).toBe(null); |
| 66 | 66 | }); |
| 67 | 67 | |
| @@ -71,17 +71,17 @@ | ||
| 71 | 71 | delete process.env.VITEST; |
| 72 | 72 | delete process.env.CONTINUE_CLI_TEST; |
| 73 | 73 | delete process.env.JEST_WORKER_ID; |
| 74 | - | |
| 74 | + | |
| 75 | 75 | // Mock stdin as not TTY (piped) |
| 76 | 76 | (process.stdin as any).isTTY = false; |
| 77 | - | |
| 77 | + | |
| 78 | 78 | // Mock fs.readFileSync to return test data |
| 79 | 79 | const mockReadFileSync = vi.mocked(fs.readFileSync); |
| 80 | 80 | mockReadFileSync.mockReturnValue("test input data"); |
| 81 | - | |
| 81 | + | |
| 82 | 82 | const { readStdinSync } = await import("./stdin.js"); |
| 83 | 83 | const result = readStdinSync(); |
| 84 | - | |
| 84 | + | |
| 85 | 85 | expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8"); |
| 86 | 86 | expect(result).toBe("test input data"); |
| 87 | 87 | }); |
| @@ -92,19 +92,19 @@ | ||
| 92 | 92 | delete process.env.VITEST; |
| 93 | 93 | delete process.env.CONTINUE_CLI_TEST; |
| 94 | 94 | delete process.env.JEST_WORKER_ID; |
| 95 | - | |
| 95 | + | |
| 96 | 96 | // Mock stdin as not TTY |
| 97 | 97 | (process.stdin as any).isTTY = false; |
| 98 | - | |
| 98 | + | |
| 99 | 99 | // Mock fs.readFileSync to throw an error |
| 100 | 100 | const mockReadFileSync = vi.mocked(fs.readFileSync); |
| 101 | 101 | mockReadFileSync.mockImplementation(() => { |
| 102 | 102 | throw new Error("EAGAIN: resource temporarily unavailable"); |
| 103 | 103 | }); |
| 104 | - | |
| 104 | + | |
| 105 | 105 | const { readStdinSync } = await import("./stdin.js"); |
| 106 | 106 | const result = readStdinSync(); |
| 107 | - | |
| 107 | + | |
| 108 | 108 | expect(result).toBe(null); |
| 109 | 109 | }); |
| 110 | 110 | |
| @@ -114,17 +114,17 @@ | ||
| 114 | 114 | delete process.env.VITEST; |
| 115 | 115 | delete process.env.CONTINUE_CLI_TEST; |
| 116 | 116 | delete process.env.JEST_WORKER_ID; |
| 117 | - | |
| 117 | + | |
| 118 | 118 | // Mock stdin as not TTY |
| 119 | 119 | (process.stdin as any).isTTY = false; |
| 120 | - | |
| 120 | + | |
| 121 | 121 | // Mock fs.readFileSync to return data with whitespace |
| 122 | 122 | const mockReadFileSync = vi.mocked(fs.readFileSync); |
| 123 | 123 | mockReadFileSync.mockReturnValue(" test input with whitespace \n"); |
| 124 | - | |
| 124 | + | |
| 125 | 125 | const { readStdinSync } = await import("./stdin.js"); |
| 126 | 126 | const result = readStdinSync(); |
| 127 | - | |
| 127 | + | |
| 128 | 128 | expect(result).toBe("test input with whitespace"); |
| 129 | 129 | }); |
| 130 | 130 | |
| @@ -134,17 +134,17 @@ | ||
| 134 | 134 | delete process.env.VITEST; |
| 135 | 135 | delete process.env.CONTINUE_CLI_TEST; |
| 136 | 136 | delete process.env.JEST_WORKER_ID; |
| 137 | - | |
| 137 | + | |
| 138 | 138 | // Mock stdin with undefined isTTY (some environments) |
| 139 | 139 | (process.stdin as any).isTTY = undefined; |
| 140 | - | |
| 140 | + | |
| 141 | 141 | // Mock fs.readFileSync to return test data |
| 142 | 142 | const mockReadFileSync = vi.mocked(fs.readFileSync); |
| 143 | 143 | mockReadFileSync.mockReturnValue("undefined tty test"); |
| 144 | - | |
| 144 | + | |
| 145 | 145 | const { readStdinSync } = await import("./stdin.js"); |
| 146 | 146 | const result = readStdinSync(); |
| 147 | - | |
| 147 | + | |
| 148 | 148 | expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8"); |
| 149 | 149 | expect(result).toBe("undefined tty test"); |
| 150 | 150 | }); |
| @@ -156,13 +156,13 @@ | ||
| 156 | 156 | delete process.env.CONTINUE_CLI_TEST; |
| 157 | 157 | delete process.env.JEST_WORKER_ID; |
| 158 | 158 | process.env.CI = "true"; |
| 159 | - | |
| 159 | + | |
| 160 | 160 | // Mock stdin as TTY in CI |
| 161 | 161 | (process.stdin as any).isTTY = true; |
| 162 | - | |
| 162 | + | |
| 163 | 163 | const { readStdinSync } = await import("./stdin.js"); |
| 164 | 164 | const result = readStdinSync(); |
| 165 | - | |
| 165 | + | |
| 166 | 166 | // Should return null in CI when stdin is a TTY |
| 167 | 167 | expect(result).toBe(null); |
| 168 | 168 | }); |
| @@ -172,7 +172,7 @@ | ||
| 172 | 172 | it("should work on different Node.js versions", async () => { |
| 173 | 173 | // Test that the function doesn't rely on Node.js version-specific features |
| 174 | 174 | const { readStdinSync } = await import("./stdin.js"); |
| 175 | - | |
| 175 | + | |
| 176 | 176 | // Should not throw errors regardless of environment |
| 177 | 177 | expect(() => readStdinSync()).not.toThrow(); |
| 178 | 178 | }); |
| @@ -183,20 +183,20 @@ | ||
| 183 | 183 | delete process.env.VITEST; |
| 184 | 184 | delete process.env.CONTINUE_CLI_TEST; |
| 185 | 185 | delete process.env.JEST_WORKER_ID; |
| 186 | - | |
| 186 | + | |
| 187 | 187 | (process.stdin as any).isTTY = false; |
| 188 | - | |
| 188 | + | |
| 189 | 189 | // Mock fs.readFileSync to simulate fd 0 not available |
| 190 | 190 | const mockReadFileSync = vi.mocked(fs.readFileSync); |
| 191 | 191 | mockReadFileSync.mockImplementation(() => { |
| 192 | 192 | throw new Error("EBADF: bad file descriptor"); |
| 193 | 193 | }); |
| 194 | - | |
| 194 | + | |
| 195 | 195 | const { readStdinSync } = await import("./stdin.js"); |
| 196 | 196 | const result = readStdinSync(); |
| 197 | - | |
| 197 | + | |
| 198 | 198 | // Should handle the error gracefully |
| 199 | 199 | expect(result).toBe(null); |
| 200 | 200 | }); |
| 201 | 201 | }); |
| 202 | -}); | |
| No newline at the end of the file | ||
| 202 | +}); |
modified extensions/cli/src/util/withExponentialBackoff.test.ts +5 −5
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | const results: string[] = []; |
| 32 | 32 | const generator = withExponentialBackoff( |
| 33 | 33 | generatorFactory, |
| 34 | - abortController.signal | |
| 34 | + abortController.signal, | |
| 35 | 35 | ); |
| 36 | 36 | |
| 37 | 37 | for await (const chunk of generator) { |
| @@ -63,7 +63,7 @@ | ||
| 63 | 63 | { |
| 64 | 64 | maxRetries: 2, |
| 65 | 65 | initialDelay: 10, // Short delay for testing |
| 66 | - } | |
| 66 | + }, | |
| 67 | 67 | ); |
| 68 | 68 | |
| 69 | 69 | for await (const chunk of generator) { |
| @@ -83,7 +83,7 @@ | ||
| 83 | 83 | |
| 84 | 84 | const generator = withExponentialBackoff( |
| 85 | 85 | generatorFactory, |
| 86 | - abortController.signal | |
| 86 | + abortController.signal, | |
| 87 | 87 | ); |
| 88 | 88 | |
| 89 | 89 | await expect(async () => { |
| @@ -107,7 +107,7 @@ | ||
| 107 | 107 | |
| 108 | 108 | const generator = withExponentialBackoff( |
| 109 | 109 | generatorFactory, |
| 110 | - abortController.signal | |
| 110 | + abortController.signal, | |
| 111 | 111 | ); |
| 112 | 112 | |
| 113 | 113 | await expect(async () => { |
| @@ -118,4 +118,4 @@ | ||
| 118 | 118 | |
| 119 | 119 | expect(generatorFactory).toHaveBeenCalledTimes(0); |
| 120 | 120 | }); |
| 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"); | |
| 17 | 17 | }); |
| 18 | 18 | |
| 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"; | |
| 21 | 21 | 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"); | |
| 26 | 26 | }); |
| 27 | 27 | }); |
| 28 | 28 | |
| 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", () => { | |
| 31 | 31 | const yamlWithComments = `# My Continue config |
| 32 | 32 | name: Local Config |
| 33 | 33 | version: 1.0.0 |
| @@ -40,15 +40,15 @@ | ||
| 40 | 40 | `; |
| 41 | 41 | |
| 42 | 42 | 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"); | |
| 49 | 49 | }); |
| 50 | 50 | |
| 51 | - it('should preserve comments when updating existing model', () => { | |
| 51 | + it("should preserve comments when updating existing model", () => { | |
| 52 | 52 | const yamlWithComments = `# My Continue config |
| 53 | 53 | name: Local Config |
| 54 | 54 | version: 1.0.0 |
| @@ -61,17 +61,17 @@ | ||
| 61 | 61 | `; |
| 62 | 62 | |
| 63 | 63 | 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"); | |
| 70 | 70 | }); |
| 71 | 71 | }); |
| 72 | 72 | |
| 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", () => { | |
| 75 | 75 | const existingConfig = `name: Local Config |
| 76 | 76 | version: 1.0.0 |
| 77 | 77 | schema: v1 |
| @@ -82,14 +82,14 @@ | ||
| 82 | 82 | `; |
| 83 | 83 | |
| 84 | 84 | 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"); | |
| 90 | 90 | }); |
| 91 | 91 | |
| 92 | - it('should update existing anthropic model', () => { | |
| 92 | + it("should update existing anthropic model", () => { | |
| 93 | 93 | const existingConfig = `name: Local Config |
| 94 | 94 | version: 1.0.0 |
| 95 | 95 | schema: v1 |
| @@ -103,49 +103,57 @@ | ||
| 103 | 103 | `; |
| 104 | 104 | |
| 105 | 105 | 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 | + | |
| 113 | 113 | // 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 | + ); | |
| 115 | 117 | expect(anthropicMatches).toHaveLength(1); |
| 116 | 118 | }); |
| 117 | 119 | |
| 118 | - it('should handle config with no models array', () => { | |
| 120 | + it("should handle config with no models array", () => { | |
| 119 | 121 | const configWithoutModels = `name: Local Config |
| 120 | 122 | version: 1.0.0 |
| 121 | 123 | schema: v1 |
| 122 | 124 | `; |
| 123 | 125 | |
| 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"); | |
| 130 | 135 | }); |
| 131 | 136 | |
| 132 | - it('should handle config with empty models array', () => { | |
| 137 | + it("should handle config with empty models array", () => { | |
| 133 | 138 | const configWithEmptyModels = `name: Local Config |
| 134 | 139 | version: 1.0.0 |
| 135 | 140 | schema: v1 |
| 136 | 141 | models: [] |
| 137 | 142 | `; |
| 138 | 143 | |
| 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"); | |
| 144 | 152 | }); |
| 145 | 153 | }); |
| 146 | 154 | |
| 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", () => { | |
| 149 | 157 | const input = `# Test config |
| 150 | 158 | name: Test |
| 151 | 159 | models: |
| @@ -153,16 +161,16 @@ | ||
| 153 | 161 | `; |
| 154 | 162 | |
| 155 | 163 | const result = updateAnthropicModelInYaml(input, testApiKey); |
| 156 | - | |
| 164 | + | |
| 157 | 165 | // Should not throw when parsing |
| 158 | 166 | expect(() => { |
| 159 | 167 | parse(result); |
| 160 | 168 | }).not.toThrow(); |
| 161 | 169 | }); |
| 162 | 170 | |
| 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 | + | |
| 166 | 174 | expect(result).toMatch(/^name: /m); |
| 167 | 175 | expect(result).toMatch(/^version: /m); |
| 168 | 176 | expect(result).toMatch(/^schema: /m); |
| @@ -173,29 +181,29 @@ | ||
| 173 | 181 | }); |
| 174 | 182 | }); |
| 175 | 183 | |
| 176 | - describe('edge cases', () => { | |
| 177 | - it('should handle malformed models array gracefully', () => { | |
| 184 | + describe("edge cases", () => { | |
| 185 | + it("should handle malformed models array gracefully", () => { | |
| 178 | 186 | const malformedConfig = `name: Local Config |
| 179 | 187 | models: "not an array" |
| 180 | 188 | `; |
| 181 | 189 | |
| 182 | 190 | 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"); | |
| 186 | 194 | }); |
| 187 | 195 | |
| 188 | - it('should handle different API key formats', () => { | |
| 196 | + it("should handle different API key formats", () => { | |
| 189 | 197 | 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", | |
| 193 | 201 | ]; |
| 194 | 202 | |
| 195 | - differentKeys.forEach(key => { | |
| 196 | - const result = updateAnthropicModelInYaml('', key); | |
| 203 | + differentKeys.forEach((key) => { | |
| 204 | + const result = updateAnthropicModelInYaml("", key); | |
| 197 | 205 | expect(result).toContain(`ANTHROPIC_API_KEY: ${key}`); |
| 198 | 206 | }); |
| 199 | 207 | }); |
| 200 | 208 | }); |
| 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"; | |
| 2 | 2 | |
| 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); | |
| 9 | 9 | }); |
| 10 | 10 | |
| 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); | |
| 14 | 14 | }); |
| 15 | 15 | |
| 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); | |
| 20 | 20 | }); |
| 21 | 21 | |
| 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); | |
| 25 | 25 | }); |
| 26 | 26 | }); |
| 27 | 27 | |
| 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); | |
| 32 | 32 | }); |
| 33 | 33 | |
| 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); | |
| 37 | 37 | }); |
| 38 | 38 | |
| 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); | |
| 41 | 41 | }); |
| 42 | 42 | }); |
| 43 | 43 | |
| 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); | |
| 48 | 48 | }); |
| 49 | 49 | |
| 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); | |
| 52 | 52 | }); |
| 53 | 53 | }); |
| 54 | 54 | |
| 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); | |
| 59 | 59 | }); |
| 60 | 60 | |
| 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); | |
| 64 | 64 | }); |
| 65 | 65 | }); |
| 66 | 66 | |
| 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); | |
| 71 | 71 | }); |
| 72 | 72 | |
| 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); | |
| 76 | 76 | }); |
| 77 | 77 | }); |
| 78 | 78 | |
| 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); | |
| 82 | 82 | }); |
| 83 | 83 | }); |
| 84 | 84 | |
| 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); | |
| 89 | 89 | }); |
| 90 | 90 | |
| 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); | |
| 93 | 93 | }); |
| 94 | 94 | }); |
| 95 | 95 | |
| 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); | |
| 99 | 99 | }); |
| 100 | 100 | }); |
| 101 | 101 | |
| 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); | |
| 106 | 106 | }); |
| 107 | 107 | |
| 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); | |
| 111 | 111 | }); |
| 112 | 112 | }); |
| 113 | 113 | |
| 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); | |
| 119 | 119 | }); |
| 120 | 120 | }); |
| 121 | 121 | |
| 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", () => { | |
| 124 | 124 | // 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); | |
| 128 | 130 | }); |
| 129 | 131 | |
| 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", () => { | |
| 131 | 133 | // 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); | |
| 135 | 137 | }); |
| 136 | 138 | |
| 137 | - test('should consider models capable when both name and model match', () => { | |
| 139 | + test("should consider models capable when both name and model match", () => { | |
| 138 | 140 | // 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 | + ); | |
| 141 | 145 | }); |
| 142 | 146 | |
| 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", () => { | |
| 144 | 148 | // 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); | |
| 147 | 151 | }); |
| 148 | 152 | }); |
| 149 | -}); | |
| No newline at the end of the file | ||
| 153 | +}); |