chore: run prettier --write on cli
This commit is contained in:
parent
a54c14f42b
commit
2bde569370
101 changed files with 4227 additions and 3547 deletions
|
|
@ -18,25 +18,30 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev
|
|||
### Core Components
|
||||
|
||||
1. **Entry Point** (`src/index.ts`): Main CLI logic with two modes:
|
||||
|
||||
- **Headless mode**: Non-interactive mode for automation/CI
|
||||
- **TUI mode**: Terminal User Interface using Ink/React
|
||||
- **Standard mode**: Traditional readline-based chat interface
|
||||
|
||||
2. **Authentication** (`src/auth/`): WorkOS-based authentication system
|
||||
|
||||
- `ensureAuth.ts`: Handles authentication flow
|
||||
- `workos.ts`: WorkOS configuration and token management
|
||||
|
||||
3. **Continue SDK Integration** (`src/continueSDK.ts`): Initializes the Continue SDK client with:
|
||||
|
||||
- API key authentication
|
||||
- Assistant configuration (slug-based)
|
||||
- Organization support
|
||||
|
||||
4. **Terminal UI** (`src/ui/`): React/Ink-based TUI components
|
||||
|
||||
- `TUIChat.tsx`: Main chat interface component
|
||||
- `UserInput.tsx`: Input handling with multi-line support
|
||||
- `TextBuffer.ts`: Text display utilities
|
||||
|
||||
5. **Tools System** (`src/tools/`): Built-in development tools including:
|
||||
|
||||
- File operations (read, write, list)
|
||||
- Code search functionality
|
||||
- Terminal command execution
|
||||
|
|
|
|||
|
|
@ -23,11 +23,13 @@ This document specifies the behavior of the CLI's configuration loading system,
|
|||
**When CLI is invoked, config source is determined in this order:**
|
||||
|
||||
1. **CLI `--config` Flag** (highest priority)
|
||||
|
||||
- File path (starts with `.`, `/`, `~`): Loads local YAML file
|
||||
- Assistant slug (`owner/package`): Fetches from Continue platform
|
||||
- Overrides any saved preferences
|
||||
|
||||
2. **Saved Config URI** (if no `--config` flag)
|
||||
|
||||
- Retrieved from authentication config
|
||||
- Converts `file://` URIs back to file paths
|
||||
- Converts `slug://` URIs back to assistant slugs
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb
|
|||
|
||||
1. If the --config flag is provided, load this config
|
||||
2. Otherwise, we will present the user with two options:
|
||||
|
||||
- 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
|
||||
- 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
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { parseArgs, processRule } from "./args.js";
|
||||
|
||||
|
|
@ -20,7 +20,6 @@ describe("parseArgs", () => {
|
|||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
|
||||
it("should set resume to true when --resume flag is present", () => {
|
||||
process.argv = ["node", "script.js", "--resume"];
|
||||
const result = parseArgs();
|
||||
|
|
@ -33,7 +32,6 @@ describe("parseArgs", () => {
|
|||
expect(result.readonly).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
it("should parse config path from --config flag", () => {
|
||||
process.argv = ["node", "script.js", "--config", "/path/to/config.yaml"];
|
||||
const result = parseArgs();
|
||||
|
|
@ -189,8 +187,7 @@ describe("parseArgs", () => {
|
|||
it("should handle empty arguments array", () => {
|
||||
process.argv = ["node", "script.js"];
|
||||
const result = parseArgs();
|
||||
expect(result).toEqual({
|
||||
});
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it("should handle multiple boolean flags", () => {
|
||||
|
|
@ -224,7 +221,7 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
// Mock fetch for hub tests
|
||||
const originalFetch = global.fetch;
|
||||
const mockFetch = vi.fn() as any;
|
||||
|
||||
|
||||
beforeAll(() => {
|
||||
global.fetch = mockFetch;
|
||||
});
|
||||
|
|
@ -232,7 +229,7 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
afterAll(() => {
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch.mockClear();
|
||||
});
|
||||
|
|
@ -242,11 +239,12 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
// Create a mock zip file containing a markdown rule
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
const ruleContent = "# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications.";
|
||||
const ruleContent =
|
||||
"# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications.";
|
||||
zip.file("rule.md", ruleContent);
|
||||
|
||||
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
|
||||
// Mock successful fetch response
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
|
|
@ -254,10 +252,13 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
} as Response);
|
||||
|
||||
const result = await processRule("continuedev/sentry-nextjs");
|
||||
|
||||
|
||||
expect(result).toBe(ruleContent);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("v0/continuedev/sentry-nextjs/latest/download", "https://api.continue.dev/")
|
||||
new URL(
|
||||
"v0/continuedev/sentry-nextjs/latest/download",
|
||||
"https://api.continue.dev/",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -269,7 +270,7 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
} as Response);
|
||||
|
||||
await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found'
|
||||
'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -277,7 +278,7 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
mockFetch.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/sentry-nextjs": Network error'
|
||||
'Failed to load rule from hub "continuedev/sentry-nextjs": Network error',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -285,7 +286,7 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
// "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug
|
||||
// Let's test with a slug that has wrong format but contains "/"
|
||||
await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow(
|
||||
'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts'
|
||||
'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -293,14 +294,14 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
await expect(processRule("continuedev/empty-rule")).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file'
|
||||
'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -309,14 +310,14 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
const zip = new JSZip();
|
||||
zip.folder("docs"); // Create a directory but no files
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
await expect(processRule("continuedev/directory-only")).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file'
|
||||
'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -325,20 +326,20 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
const zip = new JSZip();
|
||||
const mdContent = "# Main Rule\n\nThis is the markdown rule content.";
|
||||
const txtContent = "This is just a text file.";
|
||||
|
||||
|
||||
zip.file("README.txt", txtContent);
|
||||
zip.file("rule.md", mdContent);
|
||||
zip.file("package.json", '{"name": "test"}');
|
||||
|
||||
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
const result = await processRule("continuedev/mixed-files");
|
||||
|
||||
|
||||
expect(result).toBe(mdContent);
|
||||
});
|
||||
|
||||
|
|
@ -347,33 +348,33 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
const zip = new JSZip();
|
||||
const rule1Content = "# First Rule\n\nThis is the first rule.";
|
||||
const rule2Content = "# Second Rule\n\nThis is the second rule.";
|
||||
|
||||
|
||||
zip.file("rule1.md", rule1Content);
|
||||
zip.file("rule2.md", rule2Content);
|
||||
|
||||
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
} as Response);
|
||||
|
||||
const result = await processRule("continuedev/multiple-rules");
|
||||
|
||||
|
||||
// Should use the first markdown file found (alphabetically)
|
||||
expect(result).toBe(rule1Content);
|
||||
});
|
||||
|
||||
it("should handle malformed zip files", async () => {
|
||||
const invalidZipBuffer = new ArrayBuffer(10);
|
||||
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(invalidZipBuffer),
|
||||
} as Response);
|
||||
|
||||
await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow(
|
||||
'Failed to load rule from hub "continuedev/corrupted-zip"'
|
||||
'Failed to load rule from hub "continuedev/corrupted-zip"',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -384,7 +385,7 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
const zip = new JSZip();
|
||||
zip.file("rule.md", "# Hub Rule");
|
||||
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
|
||||
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(zipBuffer),
|
||||
|
|
@ -406,9 +407,9 @@ describe("processRule (loadRuleFromHub integration)", () => {
|
|||
// This would be treated as a file path, not a hub slug
|
||||
// since it starts with "."
|
||||
await expect(processRule("./owner/package")).rejects.toThrow(
|
||||
'Failed to read rule file "./owner/package": Rule file not found'
|
||||
'Failed to read rule file "./owner/package": Rule file not found',
|
||||
);
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { getDisplayableAsciiArt, CONTINUE_ASCII_ART } from "./asciiArt.js";
|
|||
|
||||
describe("asciiArt", () => {
|
||||
let originalColumns: number | undefined;
|
||||
|
||||
|
||||
beforeEach(() => {
|
||||
originalColumns = process.stdout.columns;
|
||||
});
|
||||
|
|
@ -23,7 +23,7 @@ describe("asciiArt", () => {
|
|||
process.stdout.columns = 80;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
|
||||
expect(result).toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
|
||||
|
|
@ -32,7 +32,7 @@ describe("asciiArt", () => {
|
|||
process.stdout.columns = 60;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
|
||||
expect(result).toContain("CONTINUE");
|
||||
expect(result).toContain("v0.0.0-dev");
|
||||
expect(result).not.toBe(CONTINUE_ASCII_ART);
|
||||
|
|
@ -45,7 +45,7 @@ describe("asciiArt", () => {
|
|||
process.stdout.columns = 74;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
|
||||
expect(result).toContain("CONTINUE");
|
||||
expect(result).not.toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
|
|
@ -55,7 +55,7 @@ describe("asciiArt", () => {
|
|||
process.stdout.columns = 75;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
|
||||
expect(result).toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
|
||||
|
|
@ -64,8 +64,8 @@ describe("asciiArt", () => {
|
|||
delete (process.stdout as any).columns;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
|
||||
expect(result).toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -79,12 +79,12 @@ describe("ensureOrganization with CLI organization slug", () => {
|
|||
const consoleInfoSpy = vi.spyOn(console, "info");
|
||||
|
||||
await expect(
|
||||
ensureOrganization(mockAuthConfig, true, "invalid-org")
|
||||
ensureOrganization(mockAuthConfig, true, "invalid-org"),
|
||||
).rejects.toThrow('Organization "invalid-org" not found');
|
||||
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(
|
||||
chalk.yellow("Available organizations:"),
|
||||
expect.stringContaining("personal")
|
||||
expect.stringContaining("personal"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -99,13 +99,13 @@ describe("ensureOrganization with CLI organization slug", () => {
|
|||
});
|
||||
|
||||
await expect(
|
||||
ensureOrganization(mockAuthConfig, false, "org-one")
|
||||
ensureOrganization(mockAuthConfig, false, "org-one"),
|
||||
).rejects.toThrow("Process exit");
|
||||
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
chalk.red(
|
||||
"The --org flag is only supported in headless mode (with -p/--print flag)"
|
||||
)
|
||||
"The --org flag is only supported in headless mode (with -p/--print flag)",
|
||||
),
|
||||
);
|
||||
expect(processExitSpy).toHaveBeenCalledWith(1);
|
||||
|
||||
|
|
@ -141,7 +141,7 @@ describe("ensureOrganization with CLI organization slug", () => {
|
|||
const result = await ensureOrganization(
|
||||
mockEnvAuthConfig,
|
||||
true,
|
||||
"org-two"
|
||||
"org-two",
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
|
|
@ -192,7 +192,7 @@ describe("ensureOrganization with CLI organization slug", () => {
|
|||
vi.mocked(getApiClient).mockReturnValue(apiClient as any);
|
||||
|
||||
await expect(
|
||||
ensureOrganization(mockAuthConfig, true, "org-one")
|
||||
ensureOrganization(mockAuthConfig, true, "org-one"),
|
||||
).rejects.toThrow("API Error");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,68 +1,85 @@
|
|||
import type { AssistantConfig } from '@continuedev/sdk';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { AssistantConfig } from "@continuedev/sdk";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAllSlashCommands } from './commands.js';
|
||||
import { getAllSlashCommands } from "./commands.js";
|
||||
|
||||
describe('Slash Commands Integration', () => {
|
||||
describe("Slash Commands Integration", () => {
|
||||
const mockAssistant: AssistantConfig = {
|
||||
name: 'test-assistant',
|
||||
version: '1.0.0',
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
prompts: [
|
||||
{ name: 'test-prompt', prompt: 'Test prompt', description: 'Test prompt description' }
|
||||
]
|
||||
{
|
||||
name: "test-prompt",
|
||||
prompt: "Test prompt",
|
||||
description: "Test prompt description",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe('System Commands Registration', () => {
|
||||
it('should include all system commands in the commands list', () => {
|
||||
describe("System Commands Registration", () => {
|
||||
it("should include all system commands in the commands list", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
const commandNames = commands.map(cmd => cmd.name);
|
||||
|
||||
const commandNames = commands.map((cmd) => cmd.name);
|
||||
|
||||
// Check that system commands are present (mode commands have been removed)
|
||||
expect(commandNames).toContain('help');
|
||||
expect(commandNames).toContain('clear');
|
||||
expect(commandNames).toContain('exit');
|
||||
expect(commandNames).toContain('login');
|
||||
expect(commandNames).toContain('logout');
|
||||
expect(commandNames).toContain('whoami');
|
||||
expect(commandNames).toContain("help");
|
||||
expect(commandNames).toContain("clear");
|
||||
expect(commandNames).toContain("exit");
|
||||
expect(commandNames).toContain("login");
|
||||
expect(commandNames).toContain("logout");
|
||||
expect(commandNames).toContain("whoami");
|
||||
|
||||
expect(commandNames).toContain('model');
|
||||
expect(commandNames).toContain('config');
|
||||
expect(commandNames).toContain("model");
|
||||
expect(commandNames).toContain("config");
|
||||
});
|
||||
|
||||
it('should include assistant prompt commands', () => {
|
||||
it("should include assistant prompt commands", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
const commandNames = commands.map(cmd => cmd.name);
|
||||
|
||||
expect(commandNames).toContain('test-prompt');
|
||||
const commandNames = commands.map((cmd) => cmd.name);
|
||||
|
||||
expect(commandNames).toContain("test-prompt");
|
||||
});
|
||||
|
||||
it('should categorize system commands correctly', () => {
|
||||
it("should categorize system commands correctly", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
const systemCommands = commands.filter(cmd =>
|
||||
['help', 'clear', 'exit', 'login', 'logout', 'whoami', 'model', 'config'].includes(cmd.name)
|
||||
const systemCommands = commands.filter((cmd) =>
|
||||
[
|
||||
"help",
|
||||
"clear",
|
||||
"exit",
|
||||
"login",
|
||||
"logout",
|
||||
"whoami",
|
||||
"model",
|
||||
"config",
|
||||
].includes(cmd.name),
|
||||
);
|
||||
|
||||
systemCommands.forEach(cmd => {
|
||||
expect(cmd.category).toBe('system');
|
||||
|
||||
systemCommands.forEach((cmd) => {
|
||||
expect(cmd.category).toBe("system");
|
||||
});
|
||||
});
|
||||
|
||||
it('should categorize assistant commands correctly', () => {
|
||||
it("should categorize assistant commands correctly", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant);
|
||||
const assistantCommands = commands.filter(cmd => cmd.name === 'test-prompt');
|
||||
|
||||
assistantCommands.forEach(cmd => {
|
||||
expect(cmd.category).toBe('assistant');
|
||||
const assistantCommands = commands.filter(
|
||||
(cmd) => cmd.name === "test-prompt",
|
||||
);
|
||||
|
||||
assistantCommands.forEach((cmd) => {
|
||||
expect(cmd.category).toBe("assistant");
|
||||
});
|
||||
});
|
||||
|
||||
it('should only show exit command in remote mode', () => {
|
||||
const commands = getAllSlashCommands(mockAssistant, { isRemoteMode: true });
|
||||
const commandNames = commands.map(cmd => cmd.name);
|
||||
|
||||
it("should only show exit command in remote mode", () => {
|
||||
const commands = getAllSlashCommands(mockAssistant, {
|
||||
isRemoteMode: true,
|
||||
});
|
||||
const commandNames = commands.map((cmd) => cmd.name);
|
||||
|
||||
// In remote mode, only exit command should be available
|
||||
expect(commandNames).toContain('exit');
|
||||
expect(commandNames).toContain("exit");
|
||||
expect(commandNames).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ vi.mock("./chat.js", () => ({
|
|||
|
||||
describe("listSessionsCommand", () => {
|
||||
const mockListSessions = vi.mocked(sessionModule.listSessions);
|
||||
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
|
@ -51,7 +51,7 @@ describe("listSessionsCommand", () => {
|
|||
firstUserMessage: "Hello world",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
id: "session-2",
|
||||
path: "/path/to/session2.json",
|
||||
timestamp: new Date("2023-01-01T09:00:00Z"),
|
||||
messageCount: 3,
|
||||
|
|
@ -66,22 +66,26 @@ describe("listSessionsCommand", () => {
|
|||
await listSessionsCommand({ format: "json" });
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
JSON.stringify({
|
||||
sessions: [
|
||||
{
|
||||
id: "session-1",
|
||||
timestamp: "2023-01-01T10:00:00.000Z",
|
||||
messageCount: 5,
|
||||
firstUserMessage: "Hello world",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
timestamp: "2023-01-01T09:00:00.000Z",
|
||||
messageCount: 3,
|
||||
firstUserMessage: "Test message",
|
||||
},
|
||||
],
|
||||
}, null, 2)
|
||||
JSON.stringify(
|
||||
{
|
||||
sessions: [
|
||||
{
|
||||
id: "session-1",
|
||||
timestamp: "2023-01-01T10:00:00.000Z",
|
||||
messageCount: 5,
|
||||
firstUserMessage: "Hello world",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
timestamp: "2023-01-01T09:00:00.000Z",
|
||||
messageCount: 3,
|
||||
firstUserMessage: "Test message",
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
|
|
@ -107,7 +111,7 @@ describe("listSessionsCommand", () => {
|
|||
await listSessionsCommand({ format: "json" });
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
JSON.stringify({ sessions: [] }, null, 2)
|
||||
JSON.stringify({ sessions: [] }, null, 2),
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
|
|
@ -121,9 +125,9 @@ describe("listSessionsCommand", () => {
|
|||
await listSessionsCommand({});
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"No previous sessions found. Start a new conversation with: cn"
|
||||
"No previous sessions found. Start a new conversation with: cn",
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -9,14 +9,10 @@ vi.mock("../telemetry/telemetryService.js");
|
|||
vi.mock("../ui/index.js");
|
||||
vi.mock("../util/git.js");
|
||||
|
||||
const mockWorkos = vi.mocked(
|
||||
await import("../auth/workos.js")
|
||||
);
|
||||
const mockWorkos = vi.mocked(await import("../auth/workos.js"));
|
||||
const mockEnv = vi.mocked(await import("../env.js"));
|
||||
const mockGit = vi.mocked(await import("../util/git.js"));
|
||||
const mockStartRemoteTUIChat = vi.mocked(
|
||||
await import("../ui/index.js")
|
||||
);
|
||||
const mockStartRemoteTUIChat = vi.mocked(await import("../ui/index.js"));
|
||||
|
||||
// Mock fetch globally
|
||||
const mockFetch = vi.fn();
|
||||
|
|
@ -36,12 +32,12 @@ global.console = {
|
|||
describe("remote command", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
|
||||
// Clear GitHub Actions environment variables
|
||||
delete process.env.GITHUB_ACTIONS;
|
||||
delete process.env.GITHUB_REPOSITORY;
|
||||
delete process.env.GITHUB_SERVER_URL;
|
||||
|
||||
|
||||
// Setup default mocks
|
||||
mockWorkos.loadAuthConfig.mockReturnValue({
|
||||
userId: "test-user-id",
|
||||
|
|
@ -51,19 +47,19 @@ describe("remote command", () => {
|
|||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: null,
|
||||
});
|
||||
|
||||
|
||||
mockWorkos.isAuthenticatedConfig.mockReturnValue(true);
|
||||
mockWorkos.getAccessToken.mockReturnValue("test-token");
|
||||
|
||||
|
||||
mockEnv.env = {
|
||||
apiBase: "https://api.example.com",
|
||||
workOsClientId: "test-client-id",
|
||||
appUrl: "https://test.example.com",
|
||||
continueHome: "/tmp/test-continue-home",
|
||||
};
|
||||
|
||||
|
||||
mockGit.getRepoUrl.mockReturnValue("https://github.com/user/test-repo.git");
|
||||
|
||||
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
|
|
@ -72,15 +68,15 @@ describe("remote command", () => {
|
|||
port: 8080,
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
mockStartRemoteTUIChat.startRemoteTUIChat.mockResolvedValue({} as any);
|
||||
});
|
||||
|
||||
it("should include idempotency key in request body when provided", async () => {
|
||||
const testIdempotencyKey = "test-idempotency-key-123";
|
||||
|
||||
|
||||
await remote("test prompt", { idempotencyKey: testIdempotencyKey });
|
||||
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents/devboxes", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
|
|
@ -89,14 +85,16 @@ describe("remote command", () => {
|
|||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.stringContaining(`"idempotencyKey":"${testIdempotencyKey}"`),
|
||||
})
|
||||
body: expect.stringContaining(
|
||||
`"idempotencyKey":"${testIdempotencyKey}"`,
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should not include idempotency key in request body when not provided", async () => {
|
||||
await remote("test prompt", {});
|
||||
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents/devboxes", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
|
|
@ -106,57 +104,55 @@ describe("remote command", () => {
|
|||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.not.stringContaining("idempotencyKey"),
|
||||
})
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
|
||||
it("should work with direct URL connection and idempotency key", async () => {
|
||||
const testUrl = "ws://direct-url.com";
|
||||
const testIdempotencyKey = "direct-key-789";
|
||||
|
||||
await remote("test prompt", {
|
||||
url: testUrl,
|
||||
idempotencyKey: testIdempotencyKey
|
||||
|
||||
await remote("test prompt", {
|
||||
url: testUrl,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
|
||||
// Should not make POST request when connecting directly to URL
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
// Should connect directly to the provided URL
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
|
||||
testUrl,
|
||||
"test prompt"
|
||||
"test prompt",
|
||||
);
|
||||
});
|
||||
|
||||
it("should ignore --start flag when --url is provided without --start", async () => {
|
||||
const testUrl = "ws://direct-url.com";
|
||||
|
||||
|
||||
await remote("test prompt", { url: testUrl });
|
||||
|
||||
|
||||
// Should not make POST request when connecting directly to URL
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
// Should connect directly to the provided URL and start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
|
||||
testUrl,
|
||||
"test prompt"
|
||||
"test prompt",
|
||||
);
|
||||
|
||||
|
||||
// Should not output JSON
|
||||
expect(mockConsoleLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle proper request body structure with all fields", async () => {
|
||||
const testIdempotencyKey = "structured-test-key";
|
||||
|
||||
|
||||
await remote("test prompt", { idempotencyKey: testIdempotencyKey });
|
||||
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
|
||||
expect(requestBody).toEqual({
|
||||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
|
|
@ -167,7 +163,7 @@ describe("remote command", () => {
|
|||
|
||||
it("should call getRepoUrl to get the current repository URL", async () => {
|
||||
await remote("test prompt", {});
|
||||
|
||||
|
||||
expect(mockGit.getRepoUrl).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
|
@ -175,24 +171,24 @@ describe("remote command", () => {
|
|||
// Simulate GitHub Actions environment
|
||||
process.env.GITHUB_ACTIONS = "true";
|
||||
process.env.GITHUB_REPOSITORY = "myorg/myrepo";
|
||||
|
||||
|
||||
// Mock getRepoUrl to return the GitHub Actions URL
|
||||
mockGit.getRepoUrl.mockReturnValue("https://github.com/myorg/myrepo.git");
|
||||
|
||||
|
||||
await remote("test prompt", { idempotencyKey: "github-actions-key" });
|
||||
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
|
||||
expect(requestBody.repoUrl).toBe("https://github.com/myorg/myrepo.git");
|
||||
expect(requestBody.idempotencyKey).toBe("github-actions-key");
|
||||
});
|
||||
|
||||
it("should include branchName in request body when branch option is provided", async () => {
|
||||
const testBranch = "feature/new-feature";
|
||||
|
||||
|
||||
await remote("test prompt", { branch: testBranch });
|
||||
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents/devboxes", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
|
|
@ -202,13 +198,13 @@ describe("remote command", () => {
|
|||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.stringContaining(`"branchName":"${testBranch}"`),
|
||||
})
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should not include branchName in request body when branch option is not provided", async () => {
|
||||
await remote("test prompt", {});
|
||||
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents/devboxes", mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
|
|
@ -218,22 +214,22 @@ describe("remote command", () => {
|
|||
Authorization: "Bearer test-token",
|
||||
},
|
||||
body: expect.not.stringContaining("branchName"),
|
||||
})
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle proper request body structure with branch field", async () => {
|
||||
const testBranch = "main";
|
||||
const testIdempotencyKey = "test-with-branch";
|
||||
|
||||
await remote("test prompt", {
|
||||
branch: testBranch,
|
||||
idempotencyKey: testIdempotencyKey
|
||||
|
||||
await remote("test prompt", {
|
||||
branch: testBranch,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
|
||||
|
||||
expect(requestBody).toEqual({
|
||||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
|
|
@ -246,29 +242,29 @@ describe("remote command", () => {
|
|||
describe("start mode (-s / --start flag)", () => {
|
||||
it("should output JSON and exit without starting TUI when using --start with direct URL", async () => {
|
||||
const testUrl = "ws://test-url.com";
|
||||
|
||||
|
||||
await remote("test prompt", { url: testUrl, start: true });
|
||||
|
||||
|
||||
// Should not start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
// Should not make POST request
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
// Should output JSON
|
||||
expect(mockConsoleLog).toHaveBeenCalledWith(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Remote environment connection details",
|
||||
url: testUrl,
|
||||
mode: "direct_url"
|
||||
})
|
||||
mode: "direct_url",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should create remote environment, output JSON, and exit without starting TUI when using --start", async () => {
|
||||
await remote("test prompt", { start: true });
|
||||
|
||||
|
||||
// Should make POST request to create environment
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL("agents/devboxes", mockEnv.env.apiBase),
|
||||
|
|
@ -278,16 +274,16 @@ describe("remote command", () => {
|
|||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
// Should not start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
// Should output JSON with environment details
|
||||
const consoleLogCall = mockConsoleLog.mock.calls[0][0];
|
||||
const outputJson = JSON.parse(consoleLogCall);
|
||||
|
||||
|
||||
expect(outputJson).toEqual({
|
||||
status: "success",
|
||||
message: "Remote development environment created successfully",
|
||||
|
|
@ -295,27 +291,30 @@ describe("remote command", () => {
|
|||
containerUrl: "ws://test-url.com",
|
||||
containerPort: 8080,
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
mode: "new_environment"
|
||||
mode: "new_environment",
|
||||
});
|
||||
});
|
||||
|
||||
it("should work with start mode and idempotency key", async () => {
|
||||
const testIdempotencyKey = "start-mode-key";
|
||||
|
||||
await remote("test prompt", { start: true, idempotencyKey: testIdempotencyKey });
|
||||
|
||||
|
||||
await remote("test prompt", {
|
||||
start: true,
|
||||
idempotencyKey: testIdempotencyKey,
|
||||
});
|
||||
|
||||
// Should include idempotency key in request
|
||||
const fetchCall = mockFetch.mock.calls[0];
|
||||
const requestBody = JSON.parse(fetchCall[1].body);
|
||||
expect(requestBody.idempotencyKey).toBe(testIdempotencyKey);
|
||||
|
||||
|
||||
// Should not start TUI
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
// Should output JSON
|
||||
expect(mockConsoleLog).toHaveBeenCalledWith(
|
||||
expect.stringContaining('"status":"success"')
|
||||
expect.stringContaining('"status":"success"'),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,13 +1,6 @@
|
|||
import type { Server } from "http";
|
||||
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createMinimalTestContext } from "../test-helpers/ui-test-context.js";
|
||||
|
||||
|
|
@ -40,7 +33,7 @@ describe("serve command", () => {
|
|||
config: { models: [] },
|
||||
llmApi: { chat: vi.fn() },
|
||||
model: { name: "test-model" },
|
||||
})
|
||||
}),
|
||||
),
|
||||
}));
|
||||
|
||||
|
|
@ -73,7 +66,7 @@ describe("serve command", () => {
|
|||
|
||||
afterEach(async () => {
|
||||
context.cleanup();
|
||||
|
||||
|
||||
// Restore original process.exit
|
||||
process.exit = originalProcessExit;
|
||||
|
||||
|
|
@ -100,26 +93,28 @@ describe("serve command", () => {
|
|||
it("should pass the --org flag through to initializeServices", async () => {
|
||||
// Import the services module to spy on
|
||||
const servicesModule = await import("../services/index.js");
|
||||
|
||||
|
||||
// Create spy on initializeServices
|
||||
const initializeServicesSpy = vi.spyOn(servicesModule, "initializeServices")
|
||||
const initializeServicesSpy = vi
|
||||
.spyOn(servicesModule, "initializeServices")
|
||||
.mockResolvedValue({
|
||||
config: { models: [] },
|
||||
llmApi: { chat: vi.fn() },
|
||||
model: { name: "test-model" }
|
||||
model: { name: "test-model" },
|
||||
} as any);
|
||||
|
||||
// Create spy on getService
|
||||
const getServiceSpy = vi.spyOn(servicesModule, "getService")
|
||||
// Create spy on getService
|
||||
const getServiceSpy = vi
|
||||
.spyOn(servicesModule, "getService")
|
||||
.mockResolvedValueOnce({
|
||||
config: { name: "test" },
|
||||
llmApi: { chat: vi.fn() },
|
||||
model: { provider: "test", model: "test" }
|
||||
model: { provider: "test", model: "test" },
|
||||
} as any)
|
||||
.mockResolvedValueOnce({
|
||||
config: { name: "test" },
|
||||
llmApi: { chat: vi.fn() },
|
||||
model: { provider: "test", model: "test" }
|
||||
model: { provider: "test", model: "test" },
|
||||
} as any);
|
||||
|
||||
// Import serve after setting up spies
|
||||
|
|
@ -129,7 +124,7 @@ describe("serve command", () => {
|
|||
const testOptions = {
|
||||
org: "test-organization-slug",
|
||||
timeout: "60",
|
||||
port: "9000"
|
||||
port: "9000",
|
||||
};
|
||||
|
||||
try {
|
||||
|
|
@ -142,12 +137,12 @@ describe("serve command", () => {
|
|||
expect(initializeServicesSpy).toHaveBeenCalled();
|
||||
expect(initializeServicesSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
organizationSlug: "test-organization-slug"
|
||||
})
|
||||
organizationSlug: "test-organization-slug",
|
||||
}),
|
||||
);
|
||||
|
||||
// Clean up spies
|
||||
initializeServicesSpy.mockRestore();
|
||||
getServiceSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -11,14 +11,14 @@
|
|||
*/
|
||||
function stripThinkTags(response: string): string {
|
||||
// Remove <think></think> tags and their content
|
||||
let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, '');
|
||||
|
||||
let cleaned = response.replace(/<think>[\s\S]*?<\/think>/g, "");
|
||||
|
||||
// Remove excess whitespace: multiple consecutive newlines become single newlines
|
||||
cleaned = cleaned.replace(/\n\s*\n\s*\n/g, '\n\n');
|
||||
|
||||
cleaned = cleaned.replace(/\n\s*\n\s*\n/g, "\n\n");
|
||||
|
||||
// Trim leading and trailing whitespace
|
||||
cleaned = cleaned.trim();
|
||||
|
||||
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
|
|
@ -157,4 +157,4 @@ Content should remain`;
|
|||
expect(stripThinkTags(input)).toContain("<think>Unclosed think tag");
|
||||
expect(stripThinkTags(input)).toContain("Content should remain");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,13 +3,17 @@ import { BaseLlmApi } from "@continuedev/openai-adapters";
|
|||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import { compactChatHistory, findCompactionIndex, getHistoryForLLM, COMPACTION_MARKER } from "./compaction.js";
|
||||
import {
|
||||
compactChatHistory,
|
||||
findCompactionIndex,
|
||||
getHistoryForLLM,
|
||||
COMPACTION_MARKER,
|
||||
} from "./compaction.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
|
||||
|
||||
// Mock the streamChatResponse function
|
||||
vi.mock("./streamChatResponse.js", () => ({
|
||||
streamChatResponse: vi.fn()
|
||||
streamChatResponse: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("compaction", () => {
|
||||
|
|
@ -27,7 +31,10 @@ describe("compaction", () => {
|
|||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
|
||||
|
|
@ -67,7 +74,10 @@ describe("compaction", () => {
|
|||
it("should not match marker in middle of content", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: `Some text ${COMPACTION_MARKER} in the middle` },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `Some text ${COMPACTION_MARKER} in the middle`,
|
||||
},
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
|
|
@ -116,21 +126,30 @@ describe("compaction", () => {
|
|||
{ role: "system", content: "System message" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
|
||||
const result = getHistoryForLLM(history, 3);
|
||||
expect(result).toEqual([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should return compacted history without system message when compaction is at index 0", () => {
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nThis is a summary` },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
];
|
||||
|
||||
|
|
@ -157,9 +176,7 @@ describe("compaction", () => {
|
|||
const result = getHistoryForLLM(history, -1);
|
||||
// Negative index with slice means "from the end", so -1 gives us only the last message
|
||||
// Since compactionIndex is not > 0, system message is not included
|
||||
expect(result).toEqual([
|
||||
{ role: "user", content: "Hello" },
|
||||
]);
|
||||
expect(result).toEqual([{ role: "user", content: "Hello" }]);
|
||||
});
|
||||
|
||||
it("should handle empty history", () => {
|
||||
|
|
@ -233,12 +250,14 @@ describe("compaction", () => {
|
|||
it("should compact chat history successfully", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "This is a summary of the conversation";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System message" },
|
||||
|
|
@ -247,12 +266,15 @@ describe("compaction", () => {
|
|||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2);
|
||||
expect(result.compactedHistory[0]).toEqual({ role: "system", content: "System message" });
|
||||
expect(result.compactedHistory[0]).toEqual({
|
||||
role: "system",
|
||||
content: "System message",
|
||||
});
|
||||
expect(result.compactedHistory[1]).toEqual({
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\n${mockContent}`
|
||||
content: `${COMPACTION_MARKER}\n${mockContent}`,
|
||||
});
|
||||
expect(result.compactionIndex).toBe(1);
|
||||
expect(result.compactionContent).toBe(mockContent);
|
||||
|
|
@ -263,13 +285,15 @@ describe("compaction", () => {
|
|||
const mockContent = "Summary content";
|
||||
const onStreamContent = vi.fn();
|
||||
const onStreamComplete = vi.fn();
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary ");
|
||||
callbacks?.onContent?.("content");
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary ");
|
||||
callbacks?.onContent?.("content");
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
|
|
@ -277,9 +301,9 @@ describe("compaction", () => {
|
|||
|
||||
await compactChatHistory(history, mockModel, mockLlmApi, {
|
||||
onStreamContent,
|
||||
onStreamComplete
|
||||
onStreamComplete,
|
||||
});
|
||||
|
||||
|
||||
expect(onStreamContent).toHaveBeenCalledWith("Summary ");
|
||||
expect(onStreamContent).toHaveBeenCalledWith("content");
|
||||
expect(onStreamComplete).toHaveBeenCalled();
|
||||
|
|
@ -289,7 +313,7 @@ describe("compaction", () => {
|
|||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockError = new Error("Stream failed");
|
||||
const onError = vi.fn();
|
||||
|
||||
|
||||
mockStreamResponse.mockRejectedValue(mockError);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
|
|
@ -297,48 +321,55 @@ describe("compaction", () => {
|
|||
];
|
||||
|
||||
await expect(
|
||||
compactChatHistory(history, mockModel, mockLlmApi, { onError })
|
||||
compactChatHistory(history, mockModel, mockLlmApi, { onError }),
|
||||
).rejects.toThrow("Stream failed");
|
||||
|
||||
|
||||
expect(onError).toHaveBeenCalledWith(mockError);
|
||||
});
|
||||
|
||||
it("should handle history with only system message", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "Summary of system setup";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "You are a helpful assistant" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2);
|
||||
expect(result.compactedHistory[0]).toEqual({ role: "system", content: "You are a helpful assistant" });
|
||||
expect(result.compactedHistory[0]).toEqual({
|
||||
role: "system",
|
||||
content: "You are a helpful assistant",
|
||||
});
|
||||
expect(result.compactedHistory[1].content).toContain(COMPACTION_MARKER);
|
||||
});
|
||||
|
||||
it("should handle empty content from stream", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("");
|
||||
callbacks?.onContentComplete?.("");
|
||||
return "";
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("");
|
||||
callbacks?.onContentComplete?.("");
|
||||
return "";
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
expect(result.compactionContent).toBe("");
|
||||
expect(result.compactedHistory[0].content).toBe(`${COMPACTION_MARKER}\n`);
|
||||
});
|
||||
|
|
@ -346,13 +377,15 @@ describe("compaction", () => {
|
|||
it("should correctly construct prompt for compaction", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
let capturedHistory: ChatCompletionMessageParam[] = [];
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
capturedHistory = [...history];
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
capturedHistory = [...history];
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System" },
|
||||
|
|
@ -361,24 +394,26 @@ describe("compaction", () => {
|
|||
];
|
||||
|
||||
await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
// Should have original history plus the compaction prompt
|
||||
expect(capturedHistory).toHaveLength(4);
|
||||
expect(capturedHistory[3]).toEqual({
|
||||
role: "user",
|
||||
content: expect.stringContaining("provide a concise summary")
|
||||
content: expect.stringContaining("provide a concise summary"),
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle history with tool calls and mixed message types", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "Summary including tool usage";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System" },
|
||||
|
|
@ -389,32 +424,34 @@ describe("compaction", () => {
|
|||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2);
|
||||
expect(result.compactionContent).toBe(mockContent);
|
||||
});
|
||||
|
||||
it("should handle very long chat histories", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Long summary");
|
||||
callbacks?.onContentComplete?.("Long summary");
|
||||
return "Long summary";
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Long summary");
|
||||
callbacks?.onContentComplete?.("Long summary");
|
||||
return "Long summary";
|
||||
},
|
||||
);
|
||||
|
||||
// Create a very long history
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "System" },
|
||||
];
|
||||
|
||||
|
||||
for (let i = 0; i < 100; i++) {
|
||||
history.push({ role: "user", content: `User message ${i}` });
|
||||
history.push({ role: "assistant", content: `Assistant response ${i}` });
|
||||
}
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(2); // System + compaction
|
||||
expect(result.compactionIndex).toBe(1);
|
||||
});
|
||||
|
|
@ -422,12 +459,14 @@ describe("compaction", () => {
|
|||
it("should handle history without system message", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
const mockContent = "Summary without system";
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.(mockContent);
|
||||
callbacks?.onContentComplete?.(mockContent);
|
||||
return mockContent;
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
|
|
@ -435,7 +474,7 @@ describe("compaction", () => {
|
|||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
expect(result.compactedHistory).toHaveLength(1); // Only compaction
|
||||
expect(result.compactedHistory[0].role).toBe("assistant");
|
||||
expect(result.compactionIndex).toBe(0);
|
||||
|
|
@ -444,14 +483,17 @@ describe("compaction", () => {
|
|||
|
||||
describe("property-based tests", () => {
|
||||
it("getHistoryForLLM should always return a subset of the original history", () => {
|
||||
const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
|
||||
const testCases: Array<{
|
||||
history: ChatCompletionMessageParam[];
|
||||
compactionIndex: number | null;
|
||||
}> = [
|
||||
{
|
||||
history: [
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
],
|
||||
compactionIndex: 1
|
||||
compactionIndex: 1,
|
||||
},
|
||||
{
|
||||
history: [
|
||||
|
|
@ -459,51 +501,61 @@ describe("compaction", () => {
|
|||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
],
|
||||
compactionIndex: 2
|
||||
compactionIndex: 2,
|
||||
},
|
||||
{
|
||||
history: [],
|
||||
compactionIndex: null
|
||||
}
|
||||
compactionIndex: null,
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ history, compactionIndex }) => {
|
||||
const result = getHistoryForLLM(history, compactionIndex);
|
||||
|
||||
|
||||
// Every message in result should exist in original history
|
||||
result.forEach(msg => {
|
||||
result.forEach((msg) => {
|
||||
expect(history).toContainEqual(msg);
|
||||
});
|
||||
|
||||
|
||||
// Result length should be <= original length
|
||||
expect(result.length).toBeLessThanOrEqual(history.length);
|
||||
});
|
||||
});
|
||||
|
||||
it("getHistoryForLLM should always include system message if it exists at index 0", () => {
|
||||
const systemMessage: ChatCompletionMessageParam = { role: "system", content: "System" };
|
||||
const testCases: Array<{ history: ChatCompletionMessageParam[], compactionIndex: number | null }> = [
|
||||
const systemMessage: ChatCompletionMessageParam = {
|
||||
role: "system",
|
||||
content: "System",
|
||||
};
|
||||
const testCases: Array<{
|
||||
history: ChatCompletionMessageParam[];
|
||||
compactionIndex: number | null;
|
||||
}> = [
|
||||
{
|
||||
history: [
|
||||
systemMessage,
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
],
|
||||
compactionIndex: 2
|
||||
compactionIndex: 2,
|
||||
},
|
||||
{
|
||||
history: [
|
||||
systemMessage,
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
],
|
||||
compactionIndex: 1
|
||||
}
|
||||
compactionIndex: 1,
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ history, compactionIndex }) => {
|
||||
const result = getHistoryForLLM(history, compactionIndex);
|
||||
|
||||
if (history[0]?.role === "system" && compactionIndex !== null && compactionIndex > 0) {
|
||||
|
||||
if (
|
||||
history[0]?.role === "system" &&
|
||||
compactionIndex !== null &&
|
||||
compactionIndex > 0
|
||||
) {
|
||||
expect(result[0]).toEqual(systemMessage);
|
||||
}
|
||||
});
|
||||
|
|
@ -511,12 +563,14 @@ describe("compaction", () => {
|
|||
|
||||
it("compaction should always reduce message count for non-trivial histories", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
},
|
||||
);
|
||||
|
||||
const testHistories: ChatCompletionMessageParam[][] = [
|
||||
[
|
||||
|
|
@ -530,12 +584,12 @@ describe("compaction", () => {
|
|||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: "Assistant 1" },
|
||||
{ role: "user", content: "User 2" },
|
||||
]
|
||||
],
|
||||
];
|
||||
|
||||
for (const history of testHistories) {
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
// Compacted history should be shorter than original
|
||||
// (system + compaction) or just compaction
|
||||
expect(result.compactedHistory.length).toBeLessThanOrEqual(2);
|
||||
|
|
@ -547,39 +601,56 @@ describe("compaction", () => {
|
|||
describe("invariant tests", () => {
|
||||
it("compactionIndex should always point to a message with COMPACTION_MARKER", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary content");
|
||||
callbacks?.onContentComplete?.("Summary content");
|
||||
return "Summary content";
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary content");
|
||||
callbacks?.onContentComplete?.("Summary content");
|
||||
return "Summary content";
|
||||
},
|
||||
);
|
||||
|
||||
const histories: ChatCompletionMessageParam[][] = [
|
||||
[{ role: "system", content: "System" }, { role: "user", content: "Hello" }],
|
||||
[{ role: "user", content: "Hello" }, { role: "assistant", content: "Hi" }],
|
||||
[
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Hello" },
|
||||
],
|
||||
[
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi" },
|
||||
],
|
||||
[{ role: "system", content: "System" }],
|
||||
];
|
||||
|
||||
for (const history of histories) {
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
// The message at compactionIndex should contain the marker
|
||||
const compactionMessage = result.compactedHistory[result.compactionIndex];
|
||||
const compactionMessage =
|
||||
result.compactedHistory[result.compactionIndex];
|
||||
expect(compactionMessage.role).toBe("assistant");
|
||||
expect(typeof compactionMessage.content === "string" && compactionMessage.content.startsWith(COMPACTION_MARKER)).toBe(true);
|
||||
expect(
|
||||
typeof compactionMessage.content === "string" &&
|
||||
compactionMessage.content.startsWith(COMPACTION_MARKER),
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("system message should always be preserved in the same position", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
const systemMessage: ChatCompletionMessageParam = { role: "system", content: "You are helpful" };
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
},
|
||||
);
|
||||
|
||||
const systemMessage: ChatCompletionMessageParam = {
|
||||
role: "system",
|
||||
content: "You are helpful",
|
||||
};
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
systemMessage,
|
||||
{ role: "user", content: "Hello" },
|
||||
|
|
@ -587,19 +658,21 @@ describe("compaction", () => {
|
|||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
// System message should still be at index 0
|
||||
expect(result.compactedHistory[0]).toEqual(systemMessage);
|
||||
});
|
||||
|
||||
it("findCompactionIndex should be consistent with compactChatHistory result", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
});
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
async (history, model, api, controller, callbacks) => {
|
||||
callbacks?.onContent?.("Summary");
|
||||
callbacks?.onContentComplete?.("Summary");
|
||||
return "Summary";
|
||||
},
|
||||
);
|
||||
|
||||
const history: ChatCompletionMessageParam[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
|
|
@ -607,10 +680,10 @@ describe("compaction", () => {
|
|||
];
|
||||
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
|
||||
// findCompactionIndex should find the same index
|
||||
const foundIndex = findCompactionIndex(result.compactedHistory);
|
||||
expect(foundIndex).toBe(result.compactionIndex);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,56 +1,58 @@
|
|||
import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest';
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock('./auth/workos.js');
|
||||
vi.mock("./auth/workos.js");
|
||||
|
||||
import type { AuthConfig } from './auth/workos.js';
|
||||
import { getLlmApi } from './config.js';
|
||||
import type { AuthConfig } from "./auth/workos.js";
|
||||
import { getLlmApi } from "./config.js";
|
||||
|
||||
describe('config', () => {
|
||||
describe("config", () => {
|
||||
let mockAuthConfig: AuthConfig;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockAuthConfig = {
|
||||
accessToken: 'test-token',
|
||||
refreshToken: 'test-refresh',
|
||||
userEmail: 'test@example.com',
|
||||
userId: 'test-user',
|
||||
organizationId: 'test-org',
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
userEmail: "test@example.com",
|
||||
userId: "test-user",
|
||||
organizationId: "test-org",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
};
|
||||
});
|
||||
|
||||
describe('getLlmApi()', () => {
|
||||
test('should throw error when models array is empty', () => {
|
||||
describe("getLlmApi()", () => {
|
||||
test("should throw error when models array is empty", () => {
|
||||
const assistant: AssistantUnrolled = {
|
||||
name: 'test-assistant',
|
||||
version: '1.0.0',
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
};
|
||||
|
||||
expect(() => getLlmApi(assistant, mockAuthConfig))
|
||||
.toThrow('No models found in the configured assistant');
|
||||
expect(() => getLlmApi(assistant, mockAuthConfig)).toThrow(
|
||||
"No models found in the configured assistant",
|
||||
);
|
||||
});
|
||||
|
||||
test('should throw error when no chat models available', () => {
|
||||
test("should throw error when no chat models available", () => {
|
||||
const assistant: AssistantUnrolled = {
|
||||
name: 'test-assistant',
|
||||
version: '1.0.0',
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
provider: 'openai',
|
||||
model: 'text-embedding-ada-002',
|
||||
name: 'Ada Embeddings',
|
||||
roles: ['embed'],
|
||||
provider: "openai",
|
||||
model: "text-embedding-ada-002",
|
||||
name: "Ada Embeddings",
|
||||
roles: ["embed"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
};
|
||||
|
||||
expect(() => getLlmApi(assistant, mockAuthConfig))
|
||||
.toThrow('No models with the chat role found in the configured assistant');
|
||||
expect(() => getLlmApi(assistant, mockAuthConfig)).toThrow(
|
||||
"No models with the chat role found in the configured assistant",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ describe("convertLegacyModeFlags", () => {
|
|||
|
||||
test("should throw error when both readonly and auto are true", () => {
|
||||
expect(() => convertLegacyModeFlags(true, true)).toThrow(
|
||||
"Cannot use both --readonly and --auto flags together"
|
||||
"Cannot use both --readonly and --auto flags together",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -34,7 +34,7 @@ describe("buildPermissionOverrides", () => {
|
|||
["readFile"],
|
||||
["writeFile"],
|
||||
["runTerminalCommand"],
|
||||
"plan"
|
||||
"plan",
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
|
|
@ -125,7 +125,7 @@ describe("processCommandFlags", () => {
|
|||
processCommandFlags({
|
||||
readonly: true,
|
||||
auto: true,
|
||||
})
|
||||
}),
|
||||
).toThrow("Cannot use both --readonly and --auto flags together");
|
||||
});
|
||||
|
||||
|
|
@ -142,4 +142,4 @@ describe("processCommandFlags", () => {
|
|||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,209 +1,221 @@
|
|||
import { validateFlags, handleValidationErrors } from './flagValidator.js';
|
||||
import { validateFlags, handleValidationErrors } from "./flagValidator.js";
|
||||
|
||||
describe('validateFlags', () => {
|
||||
describe('format flag validation', () => {
|
||||
test('should pass when format is used with print', () => {
|
||||
describe("validateFlags", () => {
|
||||
describe("format flag validation", () => {
|
||||
test("should pass when format is used with print", () => {
|
||||
const result = validateFlags({
|
||||
format: 'json',
|
||||
format: "json",
|
||||
print: true,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail when format is used without print', () => {
|
||||
test("should fail when format is used without print", () => {
|
||||
const result = validateFlags({
|
||||
format: 'json',
|
||||
format: "json",
|
||||
print: false,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('FORMAT_REQUIRES_PRINT');
|
||||
expect(result.errors[0].message).toContain('--format flag can only be used with -p/--print');
|
||||
expect(result.errors[0].code).toBe("FORMAT_REQUIRES_PRINT");
|
||||
expect(result.errors[0].message).toContain(
|
||||
"--format flag can only be used with -p/--print",
|
||||
);
|
||||
});
|
||||
|
||||
test('should fail when format value is invalid', () => {
|
||||
test("should fail when format value is invalid", () => {
|
||||
const result = validateFlags({
|
||||
format: 'xml',
|
||||
format: "xml",
|
||||
print: true,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('INVALID_FORMAT_VALUE');
|
||||
expect(result.errors[0].message).toContain("--format currently only supports 'json'");
|
||||
expect(result.errors[0].code).toBe("INVALID_FORMAT_VALUE");
|
||||
expect(result.errors[0].message).toContain(
|
||||
"--format currently only supports 'json'",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('silent flag validation', () => {
|
||||
test('should pass when silent is used with print', () => {
|
||||
describe("silent flag validation", () => {
|
||||
test("should pass when silent is used with print", () => {
|
||||
const result = validateFlags({
|
||||
silent: true,
|
||||
print: true,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail when silent is used without print', () => {
|
||||
test("should fail when silent is used without print", () => {
|
||||
const result = validateFlags({
|
||||
silent: true,
|
||||
print: false,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('SILENT_REQUIRES_PRINT');
|
||||
expect(result.errors[0].message).toContain('--silent flag can only be used with -p/--print');
|
||||
expect(result.errors[0].code).toBe("SILENT_REQUIRES_PRINT");
|
||||
expect(result.errors[0].message).toContain(
|
||||
"--silent flag can only be used with -p/--print",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mode flags validation', () => {
|
||||
test('should pass with readonly only', () => {
|
||||
describe("mode flags validation", () => {
|
||||
test("should pass with readonly only", () => {
|
||||
const result = validateFlags({
|
||||
readonly: true,
|
||||
auto: false,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should pass with auto only', () => {
|
||||
test("should pass with auto only", () => {
|
||||
const result = validateFlags({
|
||||
readonly: false,
|
||||
auto: true,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail when both readonly and auto are used', () => {
|
||||
test("should fail when both readonly and auto are used", () => {
|
||||
const result = validateFlags({
|
||||
readonly: true,
|
||||
auto: true,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('CONFLICTING_MODE_FLAGS');
|
||||
expect(result.errors[0].message).toContain('Cannot use both --readonly and --auto');
|
||||
expect(result.errors[0].code).toBe("CONFLICTING_MODE_FLAGS");
|
||||
expect(result.errors[0].message).toContain(
|
||||
"Cannot use both --readonly and --auto",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('permission flags validation', () => {
|
||||
test('should pass with valid permission flags', () => {
|
||||
describe("permission flags validation", () => {
|
||||
test("should pass with valid permission flags", () => {
|
||||
const result = validateFlags({
|
||||
allow: ['readFile', 'searchCode'],
|
||||
ask: ['writeFile'],
|
||||
exclude: ['Write', 'Bash'],
|
||||
allow: ["readFile", "searchCode"],
|
||||
ask: ["writeFile"],
|
||||
exclude: ["Write", "Bash"],
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should fail with empty tool names in allow', () => {
|
||||
test("should fail with empty tool names in allow", () => {
|
||||
const result = validateFlags({
|
||||
allow: ['readFile', '', 'searchCode'],
|
||||
allow: ["readFile", "", "searchCode"],
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('EMPTY_ALLOW_TOOL');
|
||||
expect(result.errors[0].message).toContain('--allow requires a tool name');
|
||||
expect(result.errors[0].code).toBe("EMPTY_ALLOW_TOOL");
|
||||
expect(result.errors[0].message).toContain(
|
||||
"--allow requires a tool name",
|
||||
);
|
||||
});
|
||||
|
||||
test('should fail with empty tool names in ask', () => {
|
||||
test("should fail with empty tool names in ask", () => {
|
||||
const result = validateFlags({
|
||||
ask: ['writeFile', ' ', 'editFile'],
|
||||
ask: ["writeFile", " ", "editFile"],
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('EMPTY_ASK_TOOL');
|
||||
expect(result.errors[0].message).toContain('--ask requires a tool name');
|
||||
expect(result.errors[0].code).toBe("EMPTY_ASK_TOOL");
|
||||
expect(result.errors[0].message).toContain("--ask requires a tool name");
|
||||
});
|
||||
|
||||
test('should fail with empty tool names in exclude', () => {
|
||||
test("should fail with empty tool names in exclude", () => {
|
||||
const result = validateFlags({
|
||||
exclude: ['Write', '', 'Bash'],
|
||||
exclude: ["Write", "", "Bash"],
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0].code).toBe('EMPTY_EXCLUDE_TOOL');
|
||||
expect(result.errors[0].message).toContain('--exclude requires a tool name');
|
||||
expect(result.errors[0].code).toBe("EMPTY_EXCLUDE_TOOL");
|
||||
expect(result.errors[0].message).toContain(
|
||||
"--exclude requires a tool name",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('multiple errors', () => {
|
||||
test('should return all validation errors', () => {
|
||||
describe("multiple errors", () => {
|
||||
test("should return all validation errors", () => {
|
||||
const result = validateFlags({
|
||||
format: 'xml',
|
||||
format: "xml",
|
||||
print: false,
|
||||
silent: true,
|
||||
readonly: true,
|
||||
auto: true,
|
||||
allow: ['readFile', ''],
|
||||
allow: ["readFile", ""],
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.errors.length).toBeGreaterThan(1);
|
||||
|
||||
const errorCodes = result.errors.map(e => e.code);
|
||||
expect(errorCodes).toContain('FORMAT_REQUIRES_PRINT');
|
||||
expect(errorCodes).toContain('INVALID_FORMAT_VALUE');
|
||||
expect(errorCodes).toContain('SILENT_REQUIRES_PRINT');
|
||||
expect(errorCodes).toContain('CONFLICTING_MODE_FLAGS');
|
||||
expect(errorCodes).toContain('EMPTY_ALLOW_TOOL');
|
||||
|
||||
const errorCodes = result.errors.map((e) => e.code);
|
||||
expect(errorCodes).toContain("FORMAT_REQUIRES_PRINT");
|
||||
expect(errorCodes).toContain("INVALID_FORMAT_VALUE");
|
||||
expect(errorCodes).toContain("SILENT_REQUIRES_PRINT");
|
||||
expect(errorCodes).toContain("CONFLICTING_MODE_FLAGS");
|
||||
expect(errorCodes).toContain("EMPTY_ALLOW_TOOL");
|
||||
});
|
||||
});
|
||||
|
||||
describe('config path validation', () => {
|
||||
test('should pass with valid config path', () => {
|
||||
describe("config path validation", () => {
|
||||
test("should pass with valid config path", () => {
|
||||
const result = validateFlags({
|
||||
config: './my-config.yaml',
|
||||
config: "./my-config.yaml",
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('should pass with undefined config', () => {
|
||||
test("should pass with undefined config", () => {
|
||||
const result = validateFlags({
|
||||
config: undefined,
|
||||
});
|
||||
|
||||
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleValidationErrors', () => {
|
||||
test('should be a function that accepts validation errors', () => {
|
||||
describe("handleValidationErrors", () => {
|
||||
test("should be a function that accepts validation errors", () => {
|
||||
// Test function signature without calling it (since it calls process.exit)
|
||||
expect(typeof handleValidationErrors).toBe('function');
|
||||
expect(typeof handleValidationErrors).toBe("function");
|
||||
expect(handleValidationErrors.length).toBe(1);
|
||||
});
|
||||
|
||||
test('should accept proper error format', () => {
|
||||
test("should accept proper error format", () => {
|
||||
const validErrors = [
|
||||
{ code: 'TEST_ERROR', message: 'Test message' },
|
||||
{ code: 'ANOTHER_ERROR', message: 'Another message' }
|
||||
{ code: "TEST_ERROR", message: "Test message" },
|
||||
{ code: "ANOTHER_ERROR", message: "Another message" },
|
||||
];
|
||||
|
||||
|
||||
// Verify the function exists and would accept this format
|
||||
// We don't call it since it would exit the process
|
||||
expect(() => {
|
||||
const errorArray = validErrors;
|
||||
expect(Array.isArray(errorArray)).toBe(true);
|
||||
expect(errorArray.every(e => e.code && e.message)).toBe(true);
|
||||
expect(errorArray.every((e) => e.code && e.message)).toBe(true);
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,27 +1,38 @@
|
|||
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
|
||||
import {
|
||||
isValidAnthropicApiKey,
|
||||
getApiKeyValidationError,
|
||||
} from "./util/apiKeyValidation.js";
|
||||
|
||||
describe('Free Trial Transition API Key Validation', () => {
|
||||
it('should validate API keys properly for free trial transition', () => {
|
||||
describe("Free Trial Transition API Key Validation", () => {
|
||||
it("should validate API keys properly for free trial transition", () => {
|
||||
// Valid API keys
|
||||
expect(isValidAnthropicApiKey('TEST-ant-1234567890')).toBe(true);
|
||||
expect(isValidAnthropicApiKey('TEST-ant-api03_T3BlbkFJ1234567890abcdef')).toBe(true);
|
||||
|
||||
expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
|
||||
expect(
|
||||
isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
|
||||
).toBe(true);
|
||||
|
||||
// Invalid API keys
|
||||
expect(isValidAnthropicApiKey('TEST-')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('TEST-ant-')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('TEST-openai-1234')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('')).toBe(false);
|
||||
expect(isValidAnthropicApiKey("TEST-")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("TEST-openai-1234")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("")).toBe(false);
|
||||
expect(isValidAnthropicApiKey(null)).toBe(false);
|
||||
expect(isValidAnthropicApiKey(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('should provide helpful error messages for invalid API keys', () => {
|
||||
expect(getApiKeyValidationError('')).toBe('API key is required');
|
||||
expect(getApiKeyValidationError(null)).toBe('API key is required');
|
||||
expect(getApiKeyValidationError(undefined)).toBe('API key is required');
|
||||
expect(getApiKeyValidationError('TEST-')).toBe('API key must start with "TEST-ant-"');
|
||||
expect(getApiKeyValidationError('TEST-openai-1234')).toBe('API key must start with "TEST-ant-"');
|
||||
expect(getApiKeyValidationError('TEST-ant-')).toBe('API key is too short');
|
||||
expect(getApiKeyValidationError('invalid')).toBe('API key must start with "TEST-ant-"');
|
||||
it("should provide helpful error messages for invalid API keys", () => {
|
||||
expect(getApiKeyValidationError("")).toBe("API key is required");
|
||||
expect(getApiKeyValidationError(null)).toBe("API key is required");
|
||||
expect(getApiKeyValidationError(undefined)).toBe("API key is required");
|
||||
expect(getApiKeyValidationError("TEST-")).toBe(
|
||||
'API key must start with "TEST-ant-"',
|
||||
);
|
||||
expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
|
||||
'API key must start with "TEST-ant-"',
|
||||
);
|
||||
expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
|
||||
expect(getApiKeyValidationError("invalid")).toBe(
|
||||
'API key must start with "TEST-ant-"',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import chalk from 'chalk';
|
||||
import { vi } from 'vitest';
|
||||
import chalk from "chalk";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import {
|
||||
configureLogger,
|
||||
isLoggingEnabled,
|
||||
log,
|
||||
error,
|
||||
info,
|
||||
warn,
|
||||
loggers
|
||||
} from './logging.js';
|
||||
import {
|
||||
configureLogger,
|
||||
isLoggingEnabled,
|
||||
log,
|
||||
error,
|
||||
info,
|
||||
warn,
|
||||
loggers,
|
||||
} from "./logging.js";
|
||||
|
||||
describe('logging utilities', () => {
|
||||
describe("logging utilities", () => {
|
||||
let consoleInfoSpy: ReturnType<typeof vi.spyOn>;
|
||||
let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
|
||||
let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
|
@ -19,227 +19,233 @@ describe('logging utilities', () => {
|
|||
beforeEach(() => {
|
||||
// Reset logger state
|
||||
configureLogger({ headless: false });
|
||||
|
||||
|
||||
// Mock console methods
|
||||
consoleInfoSpy = vi.spyOn(console, 'info').mockImplementation(() => {});
|
||||
consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
consoleInfoSpy = vi.spyOn(console, "info").mockImplementation(() => {});
|
||||
consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('configureLogger', () => {
|
||||
it('should configure logger for non-headless mode', () => {
|
||||
describe("configureLogger", () => {
|
||||
it("should configure logger for non-headless mode", () => {
|
||||
configureLogger({ headless: false });
|
||||
expect(isLoggingEnabled()).toBe(true);
|
||||
});
|
||||
|
||||
it('should configure logger for headless mode', () => {
|
||||
it("should configure logger for headless mode", () => {
|
||||
configureLogger({ headless: true });
|
||||
expect(isLoggingEnabled()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isLoggingEnabled', () => {
|
||||
it('should return true in non-headless mode', () => {
|
||||
describe("isLoggingEnabled", () => {
|
||||
it("should return true in non-headless mode", () => {
|
||||
configureLogger({ headless: false });
|
||||
expect(isLoggingEnabled()).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false in headless mode', () => {
|
||||
it("should return false in headless mode", () => {
|
||||
configureLogger({ headless: true });
|
||||
expect(isLoggingEnabled()).toBe(false);
|
||||
});
|
||||
|
||||
it('should return true when forceEnable is true, even in headless mode', () => {
|
||||
it("should return true when forceEnable is true, even in headless mode", () => {
|
||||
configureLogger({ headless: true });
|
||||
expect(isLoggingEnabled(true)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return true when forceEnable is true in non-headless mode', () => {
|
||||
it("should return true when forceEnable is true in non-headless mode", () => {
|
||||
configureLogger({ headless: false });
|
||||
expect(isLoggingEnabled(true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('log', () => {
|
||||
it('should log in non-headless mode', () => {
|
||||
describe("log", () => {
|
||||
it("should log in non-headless mode", () => {
|
||||
configureLogger({ headless: false });
|
||||
log('test message');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith('test message');
|
||||
log("test message");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith("test message");
|
||||
});
|
||||
|
||||
it('should not log in headless mode', () => {
|
||||
it("should not log in headless mode", () => {
|
||||
configureLogger({ headless: true });
|
||||
log('test message');
|
||||
log("test message");
|
||||
expect(consoleInfoSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should log in headless mode when forceLog is true', () => {
|
||||
it("should log in headless mode when forceLog is true", () => {
|
||||
configureLogger({ headless: true });
|
||||
log('test message', true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith('test message');
|
||||
log("test message", true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith("test message");
|
||||
});
|
||||
|
||||
it('should log in non-headless mode when forceLog is true', () => {
|
||||
it("should log in non-headless mode when forceLog is true", () => {
|
||||
configureLogger({ headless: false });
|
||||
log('test message', true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith('test message');
|
||||
log("test message", true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith("test message");
|
||||
});
|
||||
});
|
||||
|
||||
describe('error', () => {
|
||||
it('should log errors in non-headless mode', () => {
|
||||
describe("error", () => {
|
||||
it("should log errors in non-headless mode", () => {
|
||||
configureLogger({ headless: false });
|
||||
error('error message');
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('error message');
|
||||
error("error message");
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith("error message");
|
||||
});
|
||||
|
||||
it('should log errors in headless mode by default (forceLog defaults to true)', () => {
|
||||
it("should log errors in headless mode by default (forceLog defaults to true)", () => {
|
||||
configureLogger({ headless: true });
|
||||
error('error message');
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('error message');
|
||||
error("error message");
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith("error message");
|
||||
});
|
||||
|
||||
it('should not log errors in headless mode when forceLog is false', () => {
|
||||
it("should not log errors in headless mode when forceLog is false", () => {
|
||||
configureLogger({ headless: true });
|
||||
error('error message', false);
|
||||
error("error message", false);
|
||||
expect(consoleErrorSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should log errors when forceLog is explicitly true', () => {
|
||||
it("should log errors when forceLog is explicitly true", () => {
|
||||
configureLogger({ headless: true });
|
||||
error('error message', true);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith('error message');
|
||||
error("error message", true);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith("error message");
|
||||
});
|
||||
});
|
||||
|
||||
describe('info', () => {
|
||||
it('should log info in non-headless mode', () => {
|
||||
describe("info", () => {
|
||||
it("should log info in non-headless mode", () => {
|
||||
configureLogger({ headless: false });
|
||||
info('info message');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith('info message');
|
||||
info("info message");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith("info message");
|
||||
});
|
||||
|
||||
it('should not log info in headless mode', () => {
|
||||
it("should not log info in headless mode", () => {
|
||||
configureLogger({ headless: true });
|
||||
info('info message');
|
||||
info("info message");
|
||||
expect(consoleInfoSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should log info in headless mode when forceLog is true', () => {
|
||||
it("should log info in headless mode when forceLog is true", () => {
|
||||
configureLogger({ headless: true });
|
||||
info('info message', true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith('info message');
|
||||
info("info message", true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith("info message");
|
||||
});
|
||||
});
|
||||
|
||||
describe('warn', () => {
|
||||
it('should log warnings in non-headless mode', () => {
|
||||
describe("warn", () => {
|
||||
it("should log warnings in non-headless mode", () => {
|
||||
configureLogger({ headless: false });
|
||||
warn('warning message');
|
||||
expect(consoleWarnSpy).toHaveBeenCalledWith('warning message');
|
||||
warn("warning message");
|
||||
expect(consoleWarnSpy).toHaveBeenCalledWith("warning message");
|
||||
});
|
||||
|
||||
it('should not log warnings in headless mode', () => {
|
||||
it("should not log warnings in headless mode", () => {
|
||||
configureLogger({ headless: true });
|
||||
warn('warning message');
|
||||
warn("warning message");
|
||||
expect(consoleWarnSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should log warnings in headless mode when forceLog is true', () => {
|
||||
it("should log warnings in headless mode when forceLog is true", () => {
|
||||
configureLogger({ headless: true });
|
||||
warn('warning message', true);
|
||||
expect(consoleWarnSpy).toHaveBeenCalledWith('warning message');
|
||||
warn("warning message", true);
|
||||
expect(consoleWarnSpy).toHaveBeenCalledWith("warning message");
|
||||
});
|
||||
});
|
||||
|
||||
describe('loggers object', () => {
|
||||
describe("loggers object", () => {
|
||||
beforeEach(() => {
|
||||
configureLogger({ headless: false });
|
||||
});
|
||||
|
||||
it('should provide colored success logger', () => {
|
||||
loggers.success('success message');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.green('success message'));
|
||||
it("should provide colored success logger", () => {
|
||||
loggers.success("success message");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(
|
||||
chalk.green("success message"),
|
||||
);
|
||||
});
|
||||
|
||||
it('should provide colored info logger', () => {
|
||||
loggers.info('info message');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.blue('info message'));
|
||||
it("should provide colored info logger", () => {
|
||||
loggers.info("info message");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.blue("info message"));
|
||||
});
|
||||
|
||||
it('should provide colored warning logger', () => {
|
||||
loggers.warning('warning message');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.yellow('warning message'));
|
||||
it("should provide colored warning logger", () => {
|
||||
loggers.warning("warning message");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(
|
||||
chalk.yellow("warning message"),
|
||||
);
|
||||
});
|
||||
|
||||
it('should provide colored error logger', () => {
|
||||
loggers.error('error message');
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red('error message'));
|
||||
it("should provide colored error logger", () => {
|
||||
loggers.error("error message");
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red("error message"));
|
||||
});
|
||||
|
||||
it('should provide colored debug logger', () => {
|
||||
loggers.debug('debug message');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.gray('debug message'));
|
||||
it("should provide colored debug logger", () => {
|
||||
loggers.debug("debug message");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.gray("debug message"));
|
||||
});
|
||||
|
||||
it('should provide command logger that always logs', () => {
|
||||
it("should provide command logger that always logs", () => {
|
||||
configureLogger({ headless: true });
|
||||
loggers.command('command output');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith('command output');
|
||||
loggers.command("command output");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith("command output");
|
||||
});
|
||||
|
||||
it('should respect forceLog parameter in colored loggers', () => {
|
||||
it("should respect forceLog parameter in colored loggers", () => {
|
||||
configureLogger({ headless: true });
|
||||
|
||||
loggers.success('success message', false);
|
||||
|
||||
loggers.success("success message", false);
|
||||
expect(consoleInfoSpy).not.toHaveBeenCalled();
|
||||
|
||||
loggers.success('success message', true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(chalk.green('success message'));
|
||||
|
||||
loggers.success("success message", true);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(
|
||||
chalk.green("success message"),
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle error logger with default forceLog behavior', () => {
|
||||
it("should handle error logger with default forceLog behavior", () => {
|
||||
configureLogger({ headless: true });
|
||||
|
||||
loggers.error('error message');
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red('error message'));
|
||||
|
||||
loggers.error('error message', false);
|
||||
|
||||
loggers.error("error message");
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(chalk.red("error message"));
|
||||
|
||||
loggers.error("error message", false);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledTimes(1); // Should not be called again
|
||||
});
|
||||
});
|
||||
|
||||
describe('complex logging scenarios', () => {
|
||||
it('should handle different message types', () => {
|
||||
describe("complex logging scenarios", () => {
|
||||
it("should handle different message types", () => {
|
||||
configureLogger({ headless: false });
|
||||
|
||||
log('string message');
|
||||
|
||||
log("string message");
|
||||
log(123);
|
||||
log({ key: 'value' });
|
||||
log({ key: "value" });
|
||||
log(null);
|
||||
log(undefined);
|
||||
|
||||
|
||||
expect(consoleInfoSpy).toHaveBeenCalledTimes(5);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith('string message');
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith("string message");
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(123);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith({ key: 'value' });
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith({ key: "value" });
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(null);
|
||||
expect(consoleInfoSpy).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('should maintain state across multiple configure calls', () => {
|
||||
it("should maintain state across multiple configure calls", () => {
|
||||
configureLogger({ headless: false });
|
||||
expect(isLoggingEnabled()).toBe(true);
|
||||
|
||||
|
||||
configureLogger({ headless: true });
|
||||
expect(isLoggingEnabled()).toBe(false);
|
||||
|
||||
|
||||
configureLogger({ headless: false });
|
||||
expect(isLoggingEnabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,28 +1,28 @@
|
|||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import { describe, expect, test, beforeEach, afterEach } from 'vitest';
|
||||
import { describe, expect, test, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import type { AuthConfig } from './auth/workos.js';
|
||||
import { runNormalFlow } from './onboarding.js';
|
||||
import type { AuthConfig } from "./auth/workos.js";
|
||||
import { runNormalFlow } from "./onboarding.js";
|
||||
|
||||
describe('onboarding config flag handling', () => {
|
||||
describe("onboarding config flag handling", () => {
|
||||
let tempDir: string;
|
||||
let mockAuthConfig: AuthConfig;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create a temporary directory for test config files
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'continue-test-'));
|
||||
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "continue-test-"));
|
||||
|
||||
// Create a minimal auth config for testing
|
||||
mockAuthConfig = {
|
||||
userId: 'test-user',
|
||||
userEmail: 'test@example.com',
|
||||
accessToken: 'test-token',
|
||||
refreshToken: 'test-refresh',
|
||||
userId: "test-user",
|
||||
userEmail: "test@example.com",
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
organizationId: 'test-org',
|
||||
organizationId: "test-org",
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -33,123 +33,130 @@ describe('onboarding config flag handling', () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('should fail loudly when --config points to non-existent file', async () => {
|
||||
const configPath = path.join(tempDir, 'non-existent.yaml');
|
||||
|
||||
test("should fail loudly when --config points to non-existent file", async () => {
|
||||
const configPath = path.join(tempDir, "non-existent.yaml");
|
||||
|
||||
// Verify the file doesn't exist
|
||||
expect(fs.existsSync(configPath)).toBe(false);
|
||||
|
||||
|
||||
// Should throw an error that mentions both the path and the failure
|
||||
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
|
||||
/Failed to load config from ".*non-existent\.yaml": .*ENOENT/
|
||||
/Failed to load config from ".*non-existent\.yaml": .*ENOENT/,
|
||||
);
|
||||
});
|
||||
|
||||
test('should fail loudly when --config points to malformed YAML file', async () => {
|
||||
const configPath = path.join(tempDir, 'malformed.yaml');
|
||||
|
||||
// Create a malformed YAML file
|
||||
fs.writeFileSync(configPath, `
|
||||
test("should fail loudly when --config points to malformed YAML file", async () => {
|
||||
const configPath = path.join(tempDir, "malformed.yaml");
|
||||
|
||||
// Create a malformed YAML file
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
`
|
||||
name: "Test Config"
|
||||
models:
|
||||
- name: "GPT-4"
|
||||
provider: "openai"
|
||||
invalid_yaml_syntax: [unclosed array
|
||||
`);
|
||||
|
||||
`,
|
||||
);
|
||||
|
||||
// Verify the file exists
|
||||
expect(fs.existsSync(configPath)).toBe(true);
|
||||
|
||||
|
||||
// Should throw an error mentioning the path and failure to load
|
||||
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
|
||||
/Failed to load config from ".*malformed\.yaml": .+/
|
||||
/Failed to load config from ".*malformed\.yaml": .+/,
|
||||
);
|
||||
});
|
||||
|
||||
test('should fail loudly when --config points to file with missing required fields', async () => {
|
||||
const configPath = path.join(tempDir, 'incomplete.yaml');
|
||||
|
||||
test("should fail loudly when --config points to file with missing required fields", async () => {
|
||||
const configPath = path.join(tempDir, "incomplete.yaml");
|
||||
|
||||
// Create a config file missing required fields
|
||||
fs.writeFileSync(configPath, `
|
||||
fs.writeFileSync(
|
||||
configPath,
|
||||
`
|
||||
name: "Incomplete Config"
|
||||
# Missing models array and other required fields
|
||||
`);
|
||||
|
||||
`,
|
||||
);
|
||||
|
||||
// Verify the file exists
|
||||
expect(fs.existsSync(configPath)).toBe(true);
|
||||
|
||||
|
||||
// Should throw with our specific error format and include path
|
||||
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
|
||||
/^Failed to load config from ".*": .+/
|
||||
/^Failed to load config from ".*": .+/,
|
||||
);
|
||||
});
|
||||
|
||||
test('should handle different config path formats with proper error messages', async () => {
|
||||
test("should handle different config path formats with proper error messages", async () => {
|
||||
const testPaths = [
|
||||
'./non-existent.yaml',
|
||||
'/absolute/path/config.yaml',
|
||||
'../relative/config.yaml',
|
||||
'simple-name.yaml'
|
||||
"./non-existent.yaml",
|
||||
"/absolute/path/config.yaml",
|
||||
"../relative/config.yaml",
|
||||
"simple-name.yaml",
|
||||
];
|
||||
|
||||
|
||||
for (const configPath of testPaths) {
|
||||
await expect(runNormalFlow(mockAuthConfig, configPath)).rejects.toThrow(
|
||||
/Failed to load config from ".*": .+/
|
||||
/Failed to load config from ".*": .+/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('should handle empty string config path', async () => {
|
||||
test("should handle empty string config path", async () => {
|
||||
// Empty string should be treated differently from undefined
|
||||
// Note: empty string triggers onboarding flow, but should still fail in our error format
|
||||
await expect(runNormalFlow(mockAuthConfig, "")).rejects.toThrow();
|
||||
});
|
||||
|
||||
test('should not fall back to default config when explicit config fails', async () => {
|
||||
const configPath = path.join(tempDir, 'bad-config.yaml');
|
||||
|
||||
test("should not fall back to default config when explicit config fails", async () => {
|
||||
const configPath = path.join(tempDir, "bad-config.yaml");
|
||||
|
||||
// Create a bad config file
|
||||
fs.writeFileSync(configPath, 'invalid: yaml: content: [');
|
||||
|
||||
fs.writeFileSync(configPath, "invalid: yaml: content: [");
|
||||
|
||||
const promise = runNormalFlow(mockAuthConfig, configPath);
|
||||
|
||||
|
||||
await expect(promise).rejects.toThrow();
|
||||
|
||||
|
||||
try {
|
||||
await promise;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
|
||||
|
||||
// CRITICAL: Must have our specific error format from the fix
|
||||
expect(message).toMatch(/^Failed to load config from ".*": .+/);
|
||||
|
||||
|
||||
// Error should be about the specific config file we provided
|
||||
expect(message).toContain(configPath);
|
||||
|
||||
|
||||
// Should NOT mention falling back to default config (this was the bug!)
|
||||
expect(message).not.toContain('~/.continue/config.yaml');
|
||||
expect(message).not.toContain('default config');
|
||||
expect(message).not.toContain('fallback');
|
||||
expect(message).not.toContain("~/.continue/config.yaml");
|
||||
expect(message).not.toContain("default config");
|
||||
expect(message).not.toContain("fallback");
|
||||
}
|
||||
});
|
||||
|
||||
test('demonstrates the fix: explicit config failure vs no config provided', async () => {
|
||||
const badConfigPath = path.join(tempDir, 'bad.yaml');
|
||||
fs.writeFileSync(badConfigPath, 'invalid yaml [');
|
||||
|
||||
test("demonstrates the fix: explicit config failure vs no config provided", async () => {
|
||||
const badConfigPath = path.join(tempDir, "bad.yaml");
|
||||
fs.writeFileSync(badConfigPath, "invalid yaml [");
|
||||
|
||||
// Case 1: Explicit --config that fails should throw our specific error
|
||||
await expect(runNormalFlow(mockAuthConfig, badConfigPath)).rejects.toThrow(
|
||||
/^Failed to load config from "/
|
||||
/^Failed to load config from "/,
|
||||
);
|
||||
|
||||
|
||||
// Case 2: No explicit config should follow different logic
|
||||
try {
|
||||
await runNormalFlow(mockAuthConfig, undefined);
|
||||
// If it succeeds, that's fine - the point is it's different behavior
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : String(error);
|
||||
// This should NOT have our "Failed to load config from" prefix
|
||||
expect(errorMessage).not.toMatch(/^Failed to load config from "/);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,10 +4,18 @@ import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
|
|||
|
||||
describe("defaultPolicies", () => {
|
||||
it("should have correct permissions for read-only tools", () => {
|
||||
const readOnlyTools = ["Read", "List", "Search", "Fetch", "Exit", "Diff", "Checklist"];
|
||||
|
||||
const readOnlyTools = [
|
||||
"Read",
|
||||
"List",
|
||||
"Search",
|
||||
"Fetch",
|
||||
"Exit",
|
||||
"Diff",
|
||||
"Checklist",
|
||||
];
|
||||
|
||||
for (const tool of readOnlyTools) {
|
||||
const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool);
|
||||
const policy = DEFAULT_TOOL_POLICIES.find((p) => p.tool === tool);
|
||||
expect(policy, `Policy should exist for ${tool}`).toBeDefined();
|
||||
expect(policy?.permission, `${tool} should be allowed`).toBe("allow");
|
||||
}
|
||||
|
|
@ -15,29 +23,35 @@ describe("defaultPolicies", () => {
|
|||
|
||||
it("should have correct permissions for write tools", () => {
|
||||
const writeTools = ["Write", "Edit", "MultiEdit", "Bash"];
|
||||
|
||||
|
||||
for (const tool of writeTools) {
|
||||
const policy = DEFAULT_TOOL_POLICIES.find(p => p.tool === tool);
|
||||
const policy = DEFAULT_TOOL_POLICIES.find((p) => p.tool === tool);
|
||||
expect(policy, `Policy should exist for ${tool}`).toBeDefined();
|
||||
expect(policy?.permission, `${tool} should require confirmation`).toBe("ask");
|
||||
expect(policy?.permission, `${tool} should require confirmation`).toBe(
|
||||
"ask",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("should have a catch-all policy", () => {
|
||||
const catchAllPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "*");
|
||||
const catchAllPolicy = DEFAULT_TOOL_POLICIES.find((p) => p.tool === "*");
|
||||
expect(catchAllPolicy).toBeDefined();
|
||||
expect(catchAllPolicy?.permission).toBe("ask");
|
||||
});
|
||||
|
||||
it("should include MultiEdit policy", () => {
|
||||
const multiEditPolicy = DEFAULT_TOOL_POLICIES.find(p => p.tool === "MultiEdit");
|
||||
const multiEditPolicy = DEFAULT_TOOL_POLICIES.find(
|
||||
(p) => p.tool === "MultiEdit",
|
||||
);
|
||||
expect(multiEditPolicy).toBeDefined();
|
||||
expect(multiEditPolicy?.permission).toBe("ask");
|
||||
});
|
||||
|
||||
it("should have policies in correct order", () => {
|
||||
// The catch-all policy should be last
|
||||
const catchAllIndex = DEFAULT_TOOL_POLICIES.findIndex(p => p.tool === "*");
|
||||
const catchAllIndex = DEFAULT_TOOL_POLICIES.findIndex(
|
||||
(p) => p.tool === "*",
|
||||
);
|
||||
expect(catchAllIndex).toBe(DEFAULT_TOOL_POLICIES.length - 1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,7 +23,10 @@ describe("Headless Permissions Integration", () => {
|
|||
});
|
||||
|
||||
// CLI exclusion should come first
|
||||
expect(policies[0]).toEqual({ tool: "dangerous_tool", permission: "exclude" });
|
||||
expect(policies[0]).toEqual({
|
||||
tool: "dangerous_tool",
|
||||
permission: "exclude",
|
||||
});
|
||||
// Default policies should follow
|
||||
expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
|
|
@ -34,16 +37,36 @@ describe("Headless Permissions Integration", () => {
|
|||
const permissions = { policies: DEFAULT_TOOL_POLICIES };
|
||||
|
||||
// Read-only tools should be allowed
|
||||
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "List", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Search", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "Read", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "List", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "Search", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
|
||||
// Write operations should require permission
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("ask");
|
||||
// Write operations should require permission
|
||||
expect(
|
||||
checkToolPermission({ name: "Write", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("ask");
|
||||
expect(
|
||||
checkToolPermission({ name: "Bash", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("ask");
|
||||
|
||||
// Unknown tools should default to ask
|
||||
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(
|
||||
checkToolPermission(
|
||||
{ name: "unknown_tool", arguments: {} },
|
||||
permissions,
|
||||
).permission,
|
||||
).toBe("ask");
|
||||
});
|
||||
|
||||
it("should respect CLI overrides even in headless mode", () => {
|
||||
|
|
@ -56,13 +79,19 @@ describe("Headless Permissions Integration", () => {
|
|||
// Excluded tool should be blocked
|
||||
const excludedResult = checkToolPermission(
|
||||
{ name: "dangerous_tool", arguments: {} },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(excludedResult.permission).toBe("exclude");
|
||||
|
||||
// Default tools should follow their normal rules
|
||||
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(
|
||||
checkToolPermission({ name: "Read", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "Write", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("ask");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -83,18 +112,38 @@ describe("Headless Permissions Integration", () => {
|
|||
const permissions = { policies };
|
||||
|
||||
// Excluded tools should be blocked
|
||||
expect(checkToolPermission({ name: "rm", arguments: {} }, permissions).permission).toBe("exclude");
|
||||
expect(checkToolPermission({ name: "sudo", arguments: {} }, permissions).permission).toBe("exclude");
|
||||
expect(
|
||||
checkToolPermission({ name: "rm", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("exclude");
|
||||
expect(
|
||||
checkToolPermission({ name: "sudo", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("exclude");
|
||||
|
||||
// Explicitly allowed tools should be allowed
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "Write", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "Bash", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
|
||||
// Read-only tools should still be allowed by default
|
||||
expect(checkToolPermission({ name: "Read", arguments: {} }, permissions).permission).toBe("allow");
|
||||
|
||||
expect(
|
||||
checkToolPermission({ name: "Read", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
|
||||
// Unknown tools should default to ask (since no wildcard allow override was provided)
|
||||
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask");
|
||||
expect(
|
||||
checkToolPermission(
|
||||
{ name: "unknown_tool", arguments: {} },
|
||||
permissions,
|
||||
).permission,
|
||||
).toBe("ask");
|
||||
});
|
||||
|
||||
it("should handle workflow with wildcard allow override", () => {
|
||||
|
|
@ -109,9 +158,20 @@ describe("Headless Permissions Integration", () => {
|
|||
const permissions = { policies };
|
||||
|
||||
// All tools should be allowed due to wildcard override
|
||||
expect(checkToolPermission({ name: "Write", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "Bash", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "Write", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission({ name: "Bash", arguments: {} }, permissions)
|
||||
.permission,
|
||||
).toBe("allow");
|
||||
expect(
|
||||
checkToolPermission(
|
||||
{ name: "unknown_tool", arguments: {} },
|
||||
permissions,
|
||||
).permission,
|
||||
).toBe("allow");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,114 +1,114 @@
|
|||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
import { ToolPermissionService } from '../services/ToolPermissionService.js';
|
||||
import { ToolPermissionService } from "../services/ToolPermissionService.js";
|
||||
|
||||
import { checkToolPermission } from './permissionChecker.js';
|
||||
import { checkToolPermission } from "./permissionChecker.js";
|
||||
|
||||
describe('Permission Integration Tests', () => {
|
||||
describe("Permission Integration Tests", () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
describe('Headless mode with --allow flags', () => {
|
||||
it('should allow Edit tool when --allow Edit is specified in headless mode', () => {
|
||||
describe("Headless mode with --allow flags", () => {
|
||||
it("should allow Edit tool when --allow Edit is specified in headless mode", () => {
|
||||
// Initialize service with headless mode and --allow Edit
|
||||
service.initializeSync({
|
||||
allow: ['Edit'],
|
||||
isHeadless: true
|
||||
allow: ["Edit"],
|
||||
isHeadless: true,
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
|
||||
// Check that the service is in headless mode
|
||||
expect(state.isHeadless).toBe(true);
|
||||
|
||||
// Check permission for Edit tool
|
||||
const result = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
{ name: "Edit", arguments: {} },
|
||||
state.permissions,
|
||||
);
|
||||
|
||||
// Should be allowed because --allow Edit is specified
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
it('should allow multiple tools with --allow in headless mode', () => {
|
||||
it("should allow multiple tools with --allow in headless mode", () => {
|
||||
// Initialize service with headless mode and multiple --allow flags
|
||||
service.initializeSync({
|
||||
allow: ['Edit', 'Write', 'Bash'],
|
||||
isHeadless: true
|
||||
allow: ["Edit", "Write", "Bash"],
|
||||
isHeadless: true,
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
// Check Edit
|
||||
const editResult = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
{ name: "Edit", arguments: {} },
|
||||
state.permissions,
|
||||
);
|
||||
expect(editResult.permission).toBe('allow');
|
||||
expect(editResult.permission).toBe("allow");
|
||||
|
||||
// Check Write
|
||||
const writeResult = checkToolPermission(
|
||||
{ name: 'Write', arguments: {} },
|
||||
state.permissions
|
||||
{ name: "Write", arguments: {} },
|
||||
state.permissions,
|
||||
);
|
||||
expect(writeResult.permission).toBe('allow');
|
||||
expect(writeResult.permission).toBe("allow");
|
||||
|
||||
// Check Bash
|
||||
const bashResult = checkToolPermission(
|
||||
{ name: 'Bash', arguments: {} },
|
||||
state.permissions
|
||||
{ name: "Bash", arguments: {} },
|
||||
state.permissions,
|
||||
);
|
||||
expect(bashResult.permission).toBe('allow');
|
||||
expect(bashResult.permission).toBe("allow");
|
||||
});
|
||||
|
||||
it('should respect --exclude in headless mode', () => {
|
||||
it("should respect --exclude in headless mode", () => {
|
||||
service.initializeSync({
|
||||
allow: ['Read'],
|
||||
exclude: ['Edit'],
|
||||
isHeadless: true
|
||||
allow: ["Read"],
|
||||
exclude: ["Edit"],
|
||||
isHeadless: true,
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
// Check that Read is allowed
|
||||
const readResult = checkToolPermission(
|
||||
{ name: 'Read', arguments: {} },
|
||||
state.permissions
|
||||
{ name: "Read", arguments: {} },
|
||||
state.permissions,
|
||||
);
|
||||
expect(readResult.permission).toBe('allow');
|
||||
expect(readResult.permission).toBe("allow");
|
||||
|
||||
// Check that Edit is excluded
|
||||
const editResult = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
{ name: "Edit", arguments: {} },
|
||||
state.permissions,
|
||||
);
|
||||
expect(editResult.permission).toBe('exclude');
|
||||
expect(editResult.permission).toBe("exclude");
|
||||
});
|
||||
|
||||
it('should work with plan mode and --allow overrides', () => {
|
||||
it("should work with plan mode and --allow overrides", () => {
|
||||
// Plan mode normally excludes write operations
|
||||
service.initializeSync({
|
||||
mode: 'plan',
|
||||
allow: ['Edit'], // But we explicitly allow Edit
|
||||
isHeadless: true
|
||||
mode: "plan",
|
||||
allow: ["Edit"], // But we explicitly allow Edit
|
||||
isHeadless: true,
|
||||
});
|
||||
|
||||
const state = service.getState();
|
||||
|
||||
// In plan mode with --allow Edit override
|
||||
const editResult = checkToolPermission(
|
||||
{ name: 'Edit', arguments: {} },
|
||||
state.permissions
|
||||
{ name: "Edit", arguments: {} },
|
||||
state.permissions,
|
||||
);
|
||||
|
||||
|
||||
// Currently this fails because plan mode ignores --allow flags
|
||||
// After fix, this should be 'allow'
|
||||
expect(editResult.permission).toBe('exclude'); // Current behavior
|
||||
expect(editResult.permission).toBe("exclude"); // Current behavior
|
||||
// TODO: After fix, change to: expect(editResult.permission).toBe('allow');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
it("should match prefix wildcards", () => {
|
||||
expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(
|
||||
true
|
||||
true,
|
||||
);
|
||||
expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true);
|
||||
expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false);
|
||||
|
|
@ -58,7 +58,7 @@ describe("Permission Checker", () => {
|
|||
expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true);
|
||||
expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true);
|
||||
expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(
|
||||
true
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -74,64 +74,66 @@ describe("Permission Checker", () => {
|
|||
describe("Bash command patterns", () => {
|
||||
it("should match Bash command patterns with Bash tool", () => {
|
||||
expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe(
|
||||
true
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" })
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" })
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should match Bash command patterns with Bash display name", () => {
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "git status" })
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "git status" }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" })
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" })
|
||||
matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should match exact Bash commands", () => {
|
||||
expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe(
|
||||
true
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" })
|
||||
matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should not match Bash patterns for non-bash tools", () => {
|
||||
expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe(
|
||||
false
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
matchesToolPattern("Write", "Bash(git*)", { command: "git status" })
|
||||
matchesToolPattern("Write", "Bash(git*)", { command: "git status" }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should not match Bash patterns without command argument", () => {
|
||||
expect(matchesToolPattern("Bash", "Bash(ls*)", {})).toBe(false);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { other: "value" })
|
||||
matchesToolPattern("Bash", "Bash(ls*)", { other: "value" }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle complex Bash command patterns", () => {
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" })
|
||||
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" }),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(npm*)", { command: "npm run build" })
|
||||
matchesToolPattern("Bash", "Bash(npm*)", {
|
||||
command: "npm run build",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesToolPattern("Bash", "Bash(git*commit*)", {
|
||||
command: "git commit -m 'test'",
|
||||
})
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -209,7 +211,7 @@ describe("Permission Checker", () => {
|
|||
config: { host: "localhost", port: 3000 }, // Different reference, same content
|
||||
};
|
||||
expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(
|
||||
false
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -250,11 +252,11 @@ describe("Permission Checker", () => {
|
|||
|
||||
expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true);
|
||||
expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(
|
||||
true
|
||||
true,
|
||||
);
|
||||
expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true);
|
||||
expect(
|
||||
matchesArguments(args, { path: "/home/*/projects/*/src/**" })
|
||||
matchesArguments(args, { path: "/home/*/projects/*/src/**" }),
|
||||
).toBe(true);
|
||||
expect(matchesArguments(args, { command: "yarn *" })).toBe(false);
|
||||
});
|
||||
|
|
@ -268,7 +270,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
// Literal dots, brackets, parentheses should match exactly
|
||||
expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(
|
||||
true
|
||||
true,
|
||||
);
|
||||
expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true);
|
||||
expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true);
|
||||
|
|
@ -276,7 +278,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
// These should not match due to regex escaping
|
||||
expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(
|
||||
false
|
||||
false,
|
||||
);
|
||||
expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal
|
||||
});
|
||||
|
|
@ -294,7 +296,7 @@ describe("Permission Checker", () => {
|
|||
tool: "bash", // exact match
|
||||
command: "cd*install", // glob match
|
||||
flag: "--verbose", // exact match
|
||||
})
|
||||
}),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
|
|
@ -302,7 +304,7 @@ describe("Permission Checker", () => {
|
|||
tool: "bash", // exact match
|
||||
command: "cd*test", // glob no match
|
||||
flag: "--verbose", // exact match
|
||||
})
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
|
|
@ -350,7 +352,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
const result = checkToolPermission(
|
||||
{ name: "readFile", arguments: { path: "/test.txt" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("allow");
|
||||
|
|
@ -367,7 +369,7 @@ describe("Permission Checker", () => {
|
|||
name: "writeFile",
|
||||
arguments: { path: "/test.txt", content: "hello" },
|
||||
},
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("ask");
|
||||
|
|
@ -381,7 +383,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
const result = checkToolPermission(
|
||||
{ name: "runTerminalCommand", arguments: { command: "rm -rf /" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("exclude");
|
||||
|
|
@ -398,14 +400,14 @@ describe("Permission Checker", () => {
|
|||
|
||||
const mcpResult = checkToolPermission(
|
||||
{ name: "mcp__ide__getDiagnostics", arguments: {} },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(mcpResult.permission).toBe("ask");
|
||||
expect(mcpResult.matchedPolicy?.tool).toBe("mcp__*");
|
||||
|
||||
const builtinResult = checkToolPermission(
|
||||
{ name: "readFile", arguments: { path: "/test.txt" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(builtinResult.permission).toBe("allow");
|
||||
expect(builtinResult.matchedPolicy?.tool).toBe("*");
|
||||
|
|
@ -428,7 +430,7 @@ describe("Permission Checker", () => {
|
|||
name: "writeFile",
|
||||
arguments: { path: "/sensitive.txt", content: "data" },
|
||||
},
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(sensitiveResult.permission).toBe("exclude");
|
||||
|
||||
|
|
@ -437,7 +439,7 @@ describe("Permission Checker", () => {
|
|||
name: "writeFile",
|
||||
arguments: { path: "/normal.txt", content: "data" },
|
||||
},
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(normalResult.permission).toBe("allow");
|
||||
});
|
||||
|
|
@ -459,7 +461,7 @@ describe("Permission Checker", () => {
|
|||
|
||||
const result = checkToolPermission(
|
||||
{ name: "unknownTool", arguments: {} },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
|
||||
expect(result.permission).toBe("ask");
|
||||
|
|
@ -477,7 +479,7 @@ describe("Permission Checker", () => {
|
|||
// Should match "Bash(ls*)" pattern and allow
|
||||
const lsResult = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "ls -la" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(lsResult.permission).toBe("allow");
|
||||
expect(lsResult.matchedPolicy?.tool).toBe("Bash(ls*)");
|
||||
|
|
@ -485,7 +487,7 @@ describe("Permission Checker", () => {
|
|||
// Should match "Bash(git*)" pattern and ask
|
||||
const gitResult = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "git status" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(gitResult.permission).toBe("ask");
|
||||
expect(gitResult.matchedPolicy?.tool).toBe("Bash(git*)");
|
||||
|
|
@ -493,7 +495,7 @@ describe("Permission Checker", () => {
|
|||
// Should match general fallback for other commands
|
||||
const npmResult = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "npm install" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(npmResult.permission).toBe("ask");
|
||||
expect(npmResult.matchedPolicy?.tool).toBe("Bash");
|
||||
|
|
@ -522,7 +524,7 @@ describe("Permission Checker", () => {
|
|||
// Should exclude dangerous rm commands
|
||||
const rmResult = checkToolPermission(
|
||||
{ name: "Bash", arguments: { command: "rm -rf /" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(rmResult.permission).toBe("exclude");
|
||||
expect(rmResult.matchedPolicy?.argumentMatches?.command).toBe("rm*");
|
||||
|
|
@ -533,17 +535,17 @@ describe("Permission Checker", () => {
|
|||
name: "Write",
|
||||
arguments: { file_path: "/src/components/Button.ts" },
|
||||
},
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(tsResult.permission).toBe("ask");
|
||||
expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe(
|
||||
"**/*.ts"
|
||||
"**/*.ts",
|
||||
);
|
||||
|
||||
// Should allow other file writes
|
||||
const jsResult = checkToolPermission(
|
||||
{ name: "Write", arguments: { file_path: "/src/utils/helper.js" } },
|
||||
permissions
|
||||
permissions,
|
||||
);
|
||||
expect(jsResult.permission).toBe("allow");
|
||||
expect(jsResult.matchedPolicy?.argumentMatches).toBeUndefined();
|
||||
|
|
|
|||
|
|
@ -206,7 +206,7 @@ describe("ToolPermissionManager", () => {
|
|||
|
||||
// Start all requests
|
||||
const promises = toolCalls.map((toolCall) =>
|
||||
manager.requestPermission(toolCall)
|
||||
manager.requestPermission(toolCall),
|
||||
);
|
||||
|
||||
// Get all pending request IDs
|
||||
|
|
@ -255,7 +255,7 @@ describe("ToolPermissionManager", () => {
|
|||
|
||||
const promise = manager.requestPermission(toolCall);
|
||||
const requestDetails = manager.getPendingRequest(
|
||||
manager.getPendingRequestIds()[0]
|
||||
manager.getPendingRequestIds()[0],
|
||||
);
|
||||
|
||||
expect(requestDetails?.toolCall.arguments).toEqual(toolCall.arguments);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
import { yamlConfigToPolicies, parseToolPattern } from "./permissionsYamlLoader.js";
|
||||
import {
|
||||
yamlConfigToPolicies,
|
||||
parseToolPattern,
|
||||
} from "./permissionsYamlLoader.js";
|
||||
|
||||
describe("permissionsYamlLoader", () => {
|
||||
describe("yamlConfigToPolicies", () => {
|
||||
|
|
@ -89,34 +92,34 @@ describe("permissionsYamlLoader", () => {
|
|||
describe("parseToolPattern", () => {
|
||||
it("should parse tool name without arguments", () => {
|
||||
const policy = parseToolPattern("Write", "allow");
|
||||
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "Write",
|
||||
permission: "allow"
|
||||
permission: "allow",
|
||||
});
|
||||
});
|
||||
|
||||
it("should parse tool name with file path pattern", () => {
|
||||
const policy = parseToolPattern("Write(**/*.ts)", "exclude");
|
||||
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "Write",
|
||||
permission: "exclude",
|
||||
argumentMatches: {
|
||||
file_path: "**/*.ts"
|
||||
}
|
||||
file_path: "**/*.ts",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should parse bash command with argument", () => {
|
||||
const policy = parseToolPattern("Bash(npm install)", "ask");
|
||||
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "Bash",
|
||||
permission: "ask",
|
||||
argumentMatches: {
|
||||
command: "npm install"
|
||||
}
|
||||
command: "npm install",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -124,20 +127,36 @@ describe("permissionsYamlLoader", () => {
|
|||
const testCases = [
|
||||
{
|
||||
pattern: "Read(src/**/*.js)",
|
||||
expected: { tool: "Read", permission: "allow", argumentMatches: { file_path: "src/**/*.js" } }
|
||||
expected: {
|
||||
tool: "Read",
|
||||
permission: "allow",
|
||||
argumentMatches: { file_path: "src/**/*.js" },
|
||||
},
|
||||
},
|
||||
{
|
||||
pattern: "List(/home/user)",
|
||||
expected: { tool: "List", permission: "allow", argumentMatches: { path: "/home/user" } }
|
||||
expected: {
|
||||
tool: "List",
|
||||
permission: "allow",
|
||||
argumentMatches: { path: "/home/user" },
|
||||
},
|
||||
},
|
||||
{
|
||||
pattern: "Search(TODO)",
|
||||
expected: { tool: "Search", permission: "allow", argumentMatches: { query: "TODO" } }
|
||||
expected: {
|
||||
tool: "Search",
|
||||
permission: "allow",
|
||||
argumentMatches: { query: "TODO" },
|
||||
},
|
||||
},
|
||||
{
|
||||
pattern: "Fetch(https://api.example.com)",
|
||||
expected: { tool: "Fetch", permission: "allow", argumentMatches: { url: "https://api.example.com" } }
|
||||
}
|
||||
expected: {
|
||||
tool: "Fetch",
|
||||
permission: "allow",
|
||||
argumentMatches: { url: "https://api.example.com" },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ pattern, expected }) => {
|
||||
|
|
@ -148,50 +167,52 @@ describe("permissionsYamlLoader", () => {
|
|||
|
||||
it("should handle empty arguments", () => {
|
||||
const policy = parseToolPattern("Write()", "allow");
|
||||
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "Write",
|
||||
permission: "allow"
|
||||
permission: "allow",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle whitespace in arguments", () => {
|
||||
const policy = parseToolPattern("Bash( npm run test )", "ask");
|
||||
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "Bash",
|
||||
permission: "ask",
|
||||
argumentMatches: {
|
||||
command: "npm run test"
|
||||
}
|
||||
command: "npm run test",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle unknown tools with default argument key", () => {
|
||||
const policy = parseToolPattern("CustomTool(some-pattern)", "allow");
|
||||
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "CustomTool",
|
||||
permission: "allow",
|
||||
argumentMatches: {
|
||||
pattern: "some-pattern"
|
||||
}
|
||||
pattern: "some-pattern",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error for invalid pattern", () => {
|
||||
expect(() => parseToolPattern("Write(unclosed", "allow")).toThrow("Invalid tool pattern: Write(unclosed");
|
||||
expect(() => parseToolPattern("Write(unclosed", "allow")).toThrow(
|
||||
"Invalid tool pattern: Write(unclosed",
|
||||
);
|
||||
});
|
||||
|
||||
it("should use exact tool names in patterns", () => {
|
||||
const policy = parseToolPattern("write(**/*.ts)", "allow");
|
||||
|
||||
|
||||
expect(policy).toEqual({
|
||||
tool: "write",
|
||||
permission: "allow",
|
||||
argumentMatches: {
|
||||
pattern: "**/*.ts"
|
||||
}
|
||||
pattern: "**/*.ts",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,22 +4,38 @@ describe("policyWriter", () => {
|
|||
describe("generatePolicyRule", () => {
|
||||
it("should return display name for regular tools", () => {
|
||||
expect(generatePolicyRule("Read", { file_path: "/test" })).toBe("Read");
|
||||
expect(generatePolicyRule("Write", { file_path: "/test", content: "test" })).toBe("Write");
|
||||
expect(
|
||||
generatePolicyRule("Write", { file_path: "/test", content: "test" }),
|
||||
).toBe("Write");
|
||||
expect(generatePolicyRule("List", { path: "/test" })).toBe("List");
|
||||
expect(generatePolicyRule("Search", { pattern: "test" })).toBe("Search");
|
||||
expect(generatePolicyRule("Grep", { pattern: "test" })).toBe("Grep"); // Unknown tool, passes through
|
||||
});
|
||||
|
||||
it("should generate command-specific patterns for Bash tool", () => {
|
||||
expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe("Bash(ls*)");
|
||||
expect(generatePolicyRule("Bash", { command: "git status" })).toBe("Bash(git*)");
|
||||
expect(generatePolicyRule("Bash", { command: "npm install" })).toBe("Bash(npm*)");
|
||||
expect(generatePolicyRule("Bash", { command: "ls -la" })).toBe(
|
||||
"Bash(ls*)",
|
||||
);
|
||||
expect(generatePolicyRule("Bash", { command: "git status" })).toBe(
|
||||
"Bash(git*)",
|
||||
);
|
||||
expect(generatePolicyRule("Bash", { command: "npm install" })).toBe(
|
||||
"Bash(npm*)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle complex bash commands", () => {
|
||||
expect(generatePolicyRule("Bash", { command: "ls -la && echo test" })).toBe("Bash(ls*)");
|
||||
expect(generatePolicyRule("Bash", { command: "find . -name '*.ts' | head -10" })).toBe("Bash(find*)");
|
||||
expect(generatePolicyRule("Bash", { command: " grep -r test . " })).toBe("Bash(grep*)");
|
||||
expect(
|
||||
generatePolicyRule("Bash", { command: "ls -la && echo test" }),
|
||||
).toBe("Bash(ls*)");
|
||||
expect(
|
||||
generatePolicyRule("Bash", {
|
||||
command: "find . -name '*.ts' | head -10",
|
||||
}),
|
||||
).toBe("Bash(find*)");
|
||||
expect(
|
||||
generatePolicyRule("Bash", { command: " grep -r test . " }),
|
||||
).toBe("Bash(grep*)");
|
||||
});
|
||||
|
||||
it("should fallback to display name for bash tools without command", () => {
|
||||
|
|
@ -32,7 +48,9 @@ describe("policyWriter", () => {
|
|||
expect(generatePolicyRule("bash", { command: "ls" })).toBe("bash");
|
||||
expect(generatePolicyRule("BASH", { command: "pwd" })).toBe("BASH");
|
||||
expect(generatePolicyRule("read", { file_path: "/test" })).toBe("read");
|
||||
expect(generatePolicyRule("write", { file_path: "/test", content: "test" })).toBe("write");
|
||||
expect(
|
||||
generatePolicyRule("write", { file_path: "/test", content: "test" }),
|
||||
).toBe("write");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -20,4 +20,4 @@ describe("policyWriter verification", () => {
|
|||
expect(generatePolicyRule("EDIT", { filepath: "test.txt" })).toBe("EDIT");
|
||||
expect(generatePolicyRule("Edit", { filepath: "test.txt" })).toBe("Edit");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -128,15 +128,15 @@ describe("precedenceResolver", () => {
|
|||
});
|
||||
|
||||
// Find the Write policy - should be from CLI (allow)
|
||||
const writePolicy = policies.find(p => p.tool === "Write");
|
||||
const writePolicy = policies.find((p) => p.tool === "Write");
|
||||
expect(writePolicy?.permission).toBe("allow");
|
||||
|
||||
// Find the Search policy - should be from config
|
||||
const searchPolicy = policies.find(p => p.tool === "Search");
|
||||
const searchPolicy = policies.find((p) => p.tool === "Search");
|
||||
expect(searchPolicy?.permission).toBe("ask");
|
||||
|
||||
// Should still have default policies
|
||||
const readPolicy = policies.find(p => p.tool === "Read");
|
||||
const readPolicy = policies.find((p) => p.tool === "Read");
|
||||
expect(readPolicy).toBeDefined();
|
||||
});
|
||||
|
||||
|
|
@ -178,9 +178,9 @@ describe("precedenceResolver", () => {
|
|||
|
||||
// Config policy should override default
|
||||
expect(policies[0]).toEqual({ tool: "Bash", permission: "allow" });
|
||||
// Default policies should follow
|
||||
// Default policies should follow
|
||||
expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
import { checkToolPermission } from './permissionChecker.js';
|
||||
import { yamlConfigToPolicies } from './permissionsYamlLoader.js';
|
||||
import { checkToolPermission } from "./permissionChecker.js";
|
||||
import { yamlConfigToPolicies } from "./permissionsYamlLoader.js";
|
||||
|
||||
// Mock fs module
|
||||
vi.mock('fs');
|
||||
vi.mock("fs");
|
||||
|
||||
describe('YAML Permissions - Edit Tool Bug', () => {
|
||||
describe("YAML Permissions - Edit Tool Bug", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('should allow Edit tool when it is in the allow list', () => {
|
||||
it("should allow Edit tool when it is in the allow list", () => {
|
||||
// Test the exact YAML content from the user
|
||||
const yamlContent = `allow:
|
||||
- Edit
|
||||
|
|
@ -20,54 +20,52 @@ exclude: []`;
|
|||
|
||||
// Parse the YAML config
|
||||
const config = {
|
||||
allow: ['Edit'],
|
||||
allow: ["Edit"],
|
||||
ask: [],
|
||||
exclude: []
|
||||
exclude: [],
|
||||
};
|
||||
|
||||
// Convert to policies
|
||||
const policies = yamlConfigToPolicies(config);
|
||||
console.log('Converted policies:', policies);
|
||||
console.log("Converted policies:", policies);
|
||||
|
||||
// The policies should have Edit as allowed
|
||||
expect(policies).toEqual([
|
||||
{ tool: 'Edit', permission: 'allow' }
|
||||
]);
|
||||
expect(policies).toEqual([{ tool: "Edit", permission: "allow" }]);
|
||||
|
||||
// Test permission check with tool call named "Edit"
|
||||
const toolCall1 = {
|
||||
name: 'Edit',
|
||||
arguments: { filepath: 'test.txt' }
|
||||
name: "Edit",
|
||||
arguments: { filepath: "test.txt" },
|
||||
};
|
||||
const result1 = checkToolPermission(toolCall1, { policies });
|
||||
console.log('Permission check for "Edit":', result1);
|
||||
expect(result1.permission).toBe('allow');
|
||||
expect(result1.permission).toBe("allow");
|
||||
|
||||
// Legacy names should NOT work anymore
|
||||
const toolCall2 = {
|
||||
name: 'search_and_replace_in_file',
|
||||
arguments: { filepath: 'test.txt' }
|
||||
name: "search_and_replace_in_file",
|
||||
arguments: { filepath: "test.txt" },
|
||||
};
|
||||
const result2 = checkToolPermission(toolCall2, { policies });
|
||||
console.log('Permission check for "search_and_replace_in_file":', result2);
|
||||
expect(result2.permission).toBe('ask'); // Should not match, falls back to ask
|
||||
expect(result2.permission).toBe("ask"); // Should not match, falls back to ask
|
||||
|
||||
// Legacy names should NOT work anymore
|
||||
const toolCall3 = {
|
||||
name: 'edit_file',
|
||||
arguments: { filepath: 'test.txt' }
|
||||
name: "edit_file",
|
||||
arguments: { filepath: "test.txt" },
|
||||
};
|
||||
const result3 = checkToolPermission(toolCall3, { policies });
|
||||
console.log('Permission check for "edit_file":', result3);
|
||||
expect(result3.permission).toBe('ask'); // Should not match, falls back to ask
|
||||
expect(result3.permission).toBe("ask"); // Should not match, falls back to ask
|
||||
});
|
||||
|
||||
it('should use exact tool names without normalization', () => {
|
||||
it("should use exact tool names without normalization", () => {
|
||||
// Tools are now used exactly as they are named, no normalization
|
||||
const editName = "Edit";
|
||||
const multiEditName = "MultiEdit";
|
||||
|
||||
|
||||
expect(editName).toBe("Edit");
|
||||
expect(multiEditName).toBe("MultiEdit");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
import { describe, expect, test, beforeEach, vi } from "vitest";
|
||||
|
||||
// Mock the config module
|
||||
vi.mock('../config.js');
|
||||
import * as config from '../config.js';
|
||||
vi.mock("../config.js");
|
||||
import * as config from "../config.js";
|
||||
|
||||
import { ApiClientService } from './ApiClientService.js';
|
||||
import { ApiClientService } from "./ApiClientService.js";
|
||||
|
||||
describe('ApiClientService', () => {
|
||||
describe("ApiClientService", () => {
|
||||
let service: ApiClientService;
|
||||
const mockApiClient = {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
delete: vi.fn()
|
||||
delete: vi.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -20,114 +20,118 @@ describe('ApiClientService', () => {
|
|||
service = new ApiClientService();
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with null api client', async () => {
|
||||
describe("State Management", () => {
|
||||
test("should initialize with null api client", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
|
||||
const state = await service.initialize({ accessToken: null } as any);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: null
|
||||
apiClient: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with api client when token provided', async () => {
|
||||
test("should initialize with api client when token provided", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
|
||||
const state = await service.initialize({ accessToken: 'test-token' } as any);
|
||||
const state = await service.initialize({
|
||||
accessToken: "test-token",
|
||||
} as any);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: mockApiClient
|
||||
apiClient: mockApiClient,
|
||||
});
|
||||
expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith('test-token');
|
||||
expect(vi.mocked(config.getApiClient)).toHaveBeenCalledWith("test-token");
|
||||
});
|
||||
});
|
||||
|
||||
describe('update()', () => {
|
||||
test('should update api client with new auth config', async () => {
|
||||
describe("update()", () => {
|
||||
test("should update api client with new auth config", async () => {
|
||||
// Initialize first
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
// Update with new token
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
const state = await service.update({ accessToken: 'new-token' } as any);
|
||||
const state = await service.update({ accessToken: "new-token" } as any);
|
||||
|
||||
expect(state).toEqual({
|
||||
apiClient: mockApiClient
|
||||
apiClient: mockApiClient,
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test('should handle update errors', async () => {
|
||||
test("should handle update errors", async () => {
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
|
||||
vi.mocked(config.getApiClient).mockImplementation(() => {
|
||||
throw new Error('Failed to create client');
|
||||
throw new Error("Failed to create client");
|
||||
});
|
||||
|
||||
await expect(service.update({ accessToken: 'bad-token' } as any)).rejects.toThrow(
|
||||
'Failed to create client'
|
||||
);
|
||||
await expect(
|
||||
service.update({ accessToken: "bad-token" } as any),
|
||||
).rejects.toThrow("Failed to create client");
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReady()', () => {
|
||||
test('should return false when not initialized', () => {
|
||||
describe("isReady()", () => {
|
||||
test("should return false when not initialized", () => {
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should return false when api client is null', async () => {
|
||||
test("should return false when api client is null", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should return true when api client exists', async () => {
|
||||
test("should return true when api client exists", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.initialize({ accessToken: 'token' } as any);
|
||||
await service.initialize({ accessToken: "token" } as any);
|
||||
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDependencies()', () => {
|
||||
test('should declare auth dependency', () => {
|
||||
expect(service.getDependencies()).toEqual(['auth']);
|
||||
describe("getDependencies()", () => {
|
||||
test("should declare auth dependency", () => {
|
||||
expect(service.getDependencies()).toEqual(["auth"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged on update', async () => {
|
||||
describe("Event Emission", () => {
|
||||
test("should emit stateChanged on update", async () => {
|
||||
vi.mocked(config.getApiClient).mockReturnValue(null as any);
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
service.on("stateChanged", listener);
|
||||
|
||||
vi.mocked(config.getApiClient).mockReturnValue(mockApiClient as any);
|
||||
await service.update({ accessToken: 'new-token' } as any);
|
||||
await service.update({ accessToken: "new-token" } as any);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ apiClient: mockApiClient }),
|
||||
expect.objectContaining({ apiClient: null })
|
||||
expect.objectContaining({ apiClient: null }),
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit error on update failure', async () => {
|
||||
test("should emit error on update failure", async () => {
|
||||
await service.initialize({ accessToken: null } as any);
|
||||
|
||||
const errorListener = vi.fn();
|
||||
service.on('error', errorListener);
|
||||
|
||||
const error = new Error('Update failed');
|
||||
const errorListener = vi.fn();
|
||||
service.on("error", errorListener);
|
||||
|
||||
const error = new Error("Update failed");
|
||||
vi.mocked(config.getApiClient).mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
|
||||
await expect(service.update({ accessToken: 'bad' } as any)).rejects.toThrow();
|
||||
await expect(
|
||||
service.update({ accessToken: "bad" } as any),
|
||||
).rejects.toThrow();
|
||||
expect(errorListener).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,30 +1,30 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
import { describe, expect, test, beforeEach, vi } from "vitest";
|
||||
|
||||
// Mock the workos module
|
||||
vi.mock('../auth/workos.js');
|
||||
vi.mock("../auth/workos.js");
|
||||
|
||||
// Import the workos functions we need to mock
|
||||
import {
|
||||
import {
|
||||
loadAuthConfig,
|
||||
isAuthenticated,
|
||||
login,
|
||||
logout,
|
||||
ensureOrganization,
|
||||
saveAuthConfig,
|
||||
listUserOrganizations
|
||||
} from '../auth/workos.js';
|
||||
listUserOrganizations,
|
||||
} from "../auth/workos.js";
|
||||
|
||||
import { AuthService } from './AuthService.js';
|
||||
import { AuthService } from "./AuthService.js";
|
||||
|
||||
describe('AuthService', () => {
|
||||
describe("AuthService", () => {
|
||||
let service: AuthService;
|
||||
const mockAuthConfig = {
|
||||
accessToken: 'test-token',
|
||||
organizationId: 'org-123',
|
||||
userId: 'user-123',
|
||||
userEmail: 'test@example.com',
|
||||
refreshToken: 'refresh-token',
|
||||
expiresAt: Date.now() + 3600000
|
||||
accessToken: "test-token",
|
||||
organizationId: "org-123",
|
||||
userId: "user-123",
|
||||
userEmail: "test@example.com",
|
||||
refreshToken: "refresh-token",
|
||||
expiresAt: Date.now() + 3600000,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -32,8 +32,8 @@ describe('AuthService', () => {
|
|||
service = new AuthService();
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with unauthenticated state', async () => {
|
||||
describe("State Management", () => {
|
||||
test("should initialize with unauthenticated state", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
|
||||
|
|
@ -42,11 +42,11 @@ describe('AuthService', () => {
|
|||
expect(state).toEqual({
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
organizationId: undefined
|
||||
organizationId: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with authenticated state', async () => {
|
||||
test("should initialize with authenticated state", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
|
||||
|
|
@ -55,13 +55,13 @@ describe('AuthService', () => {
|
|||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
organizationId: "org-123",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('login()', () => {
|
||||
test('should update state after successful login', async () => {
|
||||
describe("login()", () => {
|
||||
test("should update state after successful login", async () => {
|
||||
// Initialize first
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
|
|
@ -75,22 +75,22 @@ describe('AuthService', () => {
|
|||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
organizationId: "org-123",
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test('should handle login failure', async () => {
|
||||
test("should handle login failure", async () => {
|
||||
await service.initialize();
|
||||
const loginError = new Error('Login failed');
|
||||
const loginError = new Error("Login failed");
|
||||
vi.mocked(login).mockRejectedValue(loginError);
|
||||
|
||||
await expect(service.login()).rejects.toThrow('Login failed');
|
||||
await expect(service.login()).rejects.toThrow("Login failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe('logout()', () => {
|
||||
test('should clear state after logout', async () => {
|
||||
describe("logout()", () => {
|
||||
test("should clear state after logout", async () => {
|
||||
// Initialize with authenticated state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
|
|
@ -101,14 +101,14 @@ describe('AuthService', () => {
|
|||
expect(state).toEqual({
|
||||
authConfig: null,
|
||||
isAuthenticated: false,
|
||||
organizationId: undefined
|
||||
organizationId: undefined,
|
||||
});
|
||||
expect(logout).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ensureOrganization()', () => {
|
||||
test('should update organization after ensuring', async () => {
|
||||
describe("ensureOrganization()", () => {
|
||||
test("should update organization after ensuring", async () => {
|
||||
// Initialize with auth but no org
|
||||
const authWithoutOrg = { ...mockAuthConfig, organizationId: null };
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(authWithoutOrg);
|
||||
|
|
@ -123,39 +123,43 @@ describe('AuthService', () => {
|
|||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
organizationId: "org-123",
|
||||
});
|
||||
});
|
||||
|
||||
test('should throw error if not authenticated', async () => {
|
||||
test("should throw error if not authenticated", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
||||
await expect(service.ensureOrganization()).rejects.toThrow(
|
||||
'Not authenticated - cannot ensure organization'
|
||||
"Not authenticated - cannot ensure organization",
|
||||
);
|
||||
});
|
||||
|
||||
test('should pass organization slug to ensureOrganization in headless mode', async () => {
|
||||
test("should pass organization slug to ensureOrganization in headless mode", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const updatedConfig = { ...mockAuthConfig, organizationId: 'org-456' };
|
||||
const updatedConfig = { ...mockAuthConfig, organizationId: "org-456" };
|
||||
vi.mocked(ensureOrganization).mockResolvedValue(updatedConfig);
|
||||
|
||||
const state = await service.ensureOrganization(true, 'org-slug');
|
||||
const state = await service.ensureOrganization(true, "org-slug");
|
||||
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'org-slug');
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(
|
||||
mockAuthConfig,
|
||||
true,
|
||||
"org-slug",
|
||||
);
|
||||
expect(state).toEqual({
|
||||
authConfig: updatedConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-456'
|
||||
organizationId: "org-456",
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle personal organization slug', async () => {
|
||||
test("should handle personal organization slug", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
|
@ -163,17 +167,21 @@ describe('AuthService', () => {
|
|||
const personalConfig = { ...mockAuthConfig, organizationId: null };
|
||||
vi.mocked(ensureOrganization).mockResolvedValue(personalConfig);
|
||||
|
||||
const state = await service.ensureOrganization(true, 'personal');
|
||||
const state = await service.ensureOrganization(true, "personal");
|
||||
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, true, 'personal');
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(
|
||||
mockAuthConfig,
|
||||
true,
|
||||
"personal",
|
||||
);
|
||||
expect(state).toEqual({
|
||||
authConfig: personalConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: undefined
|
||||
organizationId: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test('should work without organization slug parameter', async () => {
|
||||
test("should work without organization slug parameter", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
|
@ -182,38 +190,42 @@ describe('AuthService', () => {
|
|||
|
||||
const state = await service.ensureOrganization(false);
|
||||
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(mockAuthConfig, false, undefined);
|
||||
expect(ensureOrganization).toHaveBeenCalledWith(
|
||||
mockAuthConfig,
|
||||
false,
|
||||
undefined,
|
||||
);
|
||||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
organizationId: "org-123",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchOrganization()', () => {
|
||||
test('should update state with new organization', async () => {
|
||||
describe("switchOrganization()", () => {
|
||||
test("should update state with new organization", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const state = await service.switchOrganization('org-456');
|
||||
const state = await service.switchOrganization("org-456");
|
||||
|
||||
expect(state).toEqual({
|
||||
authConfig: {
|
||||
...mockAuthConfig,
|
||||
organizationId: 'org-456'
|
||||
organizationId: "org-456",
|
||||
},
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-456'
|
||||
organizationId: "org-456",
|
||||
});
|
||||
expect(saveAuthConfig).toHaveBeenCalledWith({
|
||||
...mockAuthConfig,
|
||||
organizationId: 'org-456'
|
||||
organizationId: "org-456",
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle null organization', async () => {
|
||||
test("should handle null organization", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
|
@ -223,27 +235,27 @@ describe('AuthService', () => {
|
|||
expect(state.organizationId).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should throw error if not file-based auth', async () => {
|
||||
const tokenOnlyAuth = { accessToken: 'token' } as any;
|
||||
test("should throw error if not file-based auth", async () => {
|
||||
const tokenOnlyAuth = { accessToken: "token" } as any;
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(tokenOnlyAuth);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
await expect(service.switchOrganization('org-456')).rejects.toThrow(
|
||||
'Not authenticated with file-based auth'
|
||||
await expect(service.switchOrganization("org-456")).rejects.toThrow(
|
||||
"Not authenticated with file-based auth",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableOrganizations()', () => {
|
||||
test('should return organizations when authenticated', async () => {
|
||||
describe("getAvailableOrganizations()", () => {
|
||||
test("should return organizations when authenticated", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const mockOrgs = [
|
||||
{ id: 'org-1', name: 'Org 1', slug: 'org-1' },
|
||||
{ id: 'org-2', name: 'Org 2', slug: 'org-2' }
|
||||
{ id: "org-1", name: "Org 1", slug: "org-1" },
|
||||
{ id: "org-2", name: "Org 2", slug: "org-2" },
|
||||
];
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue(mockOrgs);
|
||||
|
||||
|
|
@ -251,7 +263,7 @@ describe('AuthService', () => {
|
|||
expect(orgs).toEqual(mockOrgs);
|
||||
});
|
||||
|
||||
test('should return null when not authenticated', async () => {
|
||||
test("should return null when not authenticated", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
|
@ -260,42 +272,44 @@ describe('AuthService', () => {
|
|||
expect(orgs).toBeNull();
|
||||
});
|
||||
|
||||
test('should handle errors gracefully', async () => {
|
||||
test("should handle errors gracefully", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockRejectedValue(new Error('API error'));
|
||||
vi.mocked(listUserOrganizations).mockRejectedValue(
|
||||
new Error("API error"),
|
||||
);
|
||||
|
||||
// Add error event listener to prevent unhandled rejection
|
||||
const errorHandler = vi.fn();
|
||||
service.on('error', errorHandler);
|
||||
service.on("error", errorHandler);
|
||||
|
||||
const orgs = await service.getAvailableOrganizations();
|
||||
expect(orgs).toBeNull();
|
||||
expect(errorHandler).toHaveBeenCalledWith(expect.any(Error));
|
||||
|
||||
// Clean up
|
||||
service.off('error', errorHandler);
|
||||
service.off("error", errorHandler);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasMultipleOrganizations()', () => {
|
||||
test('should return true when multiple orgs available', async () => {
|
||||
describe("hasMultipleOrganizations()", () => {
|
||||
test("should return true when multiple orgs available", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue([
|
||||
{ id: 'org-1', name: 'Org 1', slug: 'org-1' },
|
||||
{ id: 'org-2', name: 'Org 2', slug: 'org-2' }
|
||||
{ id: "org-1", name: "Org 1", slug: "org-1" },
|
||||
{ id: "org-2", name: "Org 2", slug: "org-2" },
|
||||
]);
|
||||
|
||||
const hasMultiple = await service.hasMultipleOrganizations();
|
||||
expect(hasMultiple).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false when no orgs available', async () => {
|
||||
test("should return false when no orgs available", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
await service.initialize();
|
||||
|
|
@ -307,8 +321,8 @@ describe('AuthService', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('refresh()', () => {
|
||||
test('should reload auth state from disk', async () => {
|
||||
describe("refresh()", () => {
|
||||
test("should reload auth state from disk", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
|
@ -322,20 +336,20 @@ describe('AuthService', () => {
|
|||
expect(state).toEqual({
|
||||
authConfig: mockAuthConfig,
|
||||
isAuthenticated: true,
|
||||
organizationId: 'org-123'
|
||||
organizationId: "org-123",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged on login', async () => {
|
||||
describe("Event Emission", () => {
|
||||
test("should emit stateChanged on login", async () => {
|
||||
// Initialize with no auth config to simulate logged out state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
await service.initialize();
|
||||
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
service.on("stateChanged", listener);
|
||||
|
||||
vi.mocked(login).mockResolvedValue(mockAuthConfig);
|
||||
await service.login();
|
||||
|
|
@ -344,25 +358,25 @@ describe('AuthService', () => {
|
|||
expect.objectContaining({
|
||||
isAuthenticated: true,
|
||||
authConfig: mockAuthConfig,
|
||||
organizationId: 'org-123'
|
||||
organizationId: "org-123",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
isAuthenticated: false,
|
||||
authConfig: null
|
||||
})
|
||||
authConfig: null,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit error on login failure', async () => {
|
||||
test("should emit error on login failure", async () => {
|
||||
await service.initialize();
|
||||
const errorListener = vi.fn();
|
||||
service.on('error', errorListener);
|
||||
service.on("error", errorListener);
|
||||
|
||||
const error = new Error('Login failed');
|
||||
const error = new Error("Login failed");
|
||||
vi.mocked(login).mockRejectedValue(error);
|
||||
|
||||
await expect(service.login()).rejects.toThrow();
|
||||
expect(errorListener).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
import { describe, expect, test, beforeEach, vi } from "vitest";
|
||||
|
||||
import { BaseService, hasDependencies, ServiceWithDependencies } from './BaseService.js';
|
||||
import {
|
||||
BaseService,
|
||||
hasDependencies,
|
||||
ServiceWithDependencies,
|
||||
} from "./BaseService.js";
|
||||
|
||||
// Test implementation of BaseService
|
||||
interface TestState {
|
||||
|
|
@ -11,16 +15,16 @@ interface TestState {
|
|||
|
||||
class TestService extends BaseService<TestState> {
|
||||
constructor() {
|
||||
super('TestService', {
|
||||
super("TestService", {
|
||||
value: 0,
|
||||
message: 'initial'
|
||||
message: "initial",
|
||||
});
|
||||
}
|
||||
|
||||
async doInitialize(value: number, message: string): Promise<TestState> {
|
||||
return {
|
||||
value,
|
||||
message
|
||||
message,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -31,175 +35,180 @@ class TestService extends BaseService<TestState> {
|
|||
}
|
||||
|
||||
// Test service with dependencies
|
||||
class DependentTestService extends TestService implements ServiceWithDependencies {
|
||||
class DependentTestService
|
||||
extends TestService
|
||||
implements ServiceWithDependencies
|
||||
{
|
||||
getDependencies(): string[] {
|
||||
return ['auth', 'config'];
|
||||
return ["auth", "config"];
|
||||
}
|
||||
}
|
||||
|
||||
// Test service that throws during initialization
|
||||
class FailingTestService extends BaseService<TestState> {
|
||||
constructor() {
|
||||
super('FailingService', {
|
||||
super("FailingService", {
|
||||
value: 0,
|
||||
message: 'initial'
|
||||
message: "initial",
|
||||
});
|
||||
}
|
||||
|
||||
async doInitialize(): Promise<TestState> {
|
||||
throw new Error('Initialization failed');
|
||||
throw new Error("Initialization failed");
|
||||
}
|
||||
}
|
||||
|
||||
describe('BaseService', () => {
|
||||
describe('Basic Functionality', () => {
|
||||
describe("BaseService", () => {
|
||||
describe("Basic Functionality", () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should have correct initial state', () => {
|
||||
test("should have correct initial state", () => {
|
||||
const state = service.getState();
|
||||
expect(state).toEqual({
|
||||
value: 0,
|
||||
message: 'initial'
|
||||
message: "initial",
|
||||
});
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should initialize successfully', async () => {
|
||||
const state = await service.initialize(42, 'initialized');
|
||||
|
||||
test("should initialize successfully", async () => {
|
||||
const state = await service.initialize(42, "initialized");
|
||||
|
||||
expect(state).toEqual({
|
||||
value: 42,
|
||||
message: 'initialized'
|
||||
message: "initialized",
|
||||
});
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should emit initialization events', async () => {
|
||||
test("should emit initialization events", async () => {
|
||||
const initializingListener = vi.fn();
|
||||
const initializedListener = vi.fn();
|
||||
|
||||
service.on('initializing', initializingListener);
|
||||
service.on('initialized', initializedListener);
|
||||
|
||||
await service.initialize(42, 'initialized');
|
||||
|
||||
|
||||
service.on("initializing", initializingListener);
|
||||
service.on("initialized", initializedListener);
|
||||
|
||||
await service.initialize(42, "initialized");
|
||||
|
||||
expect(initializingListener).toHaveBeenCalledTimes(1);
|
||||
expect(initializedListener).toHaveBeenCalledTimes(1);
|
||||
expect(initializedListener).toHaveBeenCalledWith({
|
||||
value: 42,
|
||||
message: 'initialized'
|
||||
message: "initialized",
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle initialization failure', async () => {
|
||||
test("should handle initialization failure", async () => {
|
||||
const failingService = new FailingTestService();
|
||||
const errorListener = vi.fn();
|
||||
|
||||
failingService.on('error', errorListener);
|
||||
|
||||
await expect(failingService.initialize()).rejects.toThrow('Initialization failed');
|
||||
|
||||
failingService.on("error", errorListener);
|
||||
|
||||
await expect(failingService.initialize()).rejects.toThrow(
|
||||
"Initialization failed",
|
||||
);
|
||||
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||
expect(failingService.isReady()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
describe("State Management", () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should return immutable state copy', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
test("should return immutable state copy", async () => {
|
||||
await service.initialize(42, "test");
|
||||
|
||||
const state1 = service.getState();
|
||||
const state2 = service.getState();
|
||||
|
||||
|
||||
expect(state1).toEqual(state2);
|
||||
expect(state1).not.toBe(state2); // Different object references
|
||||
});
|
||||
|
||||
test('should return shallow copy of state', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
test("should return shallow copy of state", async () => {
|
||||
await service.initialize(42, "test");
|
||||
service.updateState({ data: [{ id: 1 }, { id: 2 }] });
|
||||
|
||||
|
||||
const state = service.getState();
|
||||
const originalData = state.data;
|
||||
|
||||
|
||||
// Modify the returned state's nested object
|
||||
if (state.data) {
|
||||
state.data[0].id = 999;
|
||||
}
|
||||
|
||||
|
||||
// With shallow copy, nested objects are shared
|
||||
const newState = service.getState();
|
||||
expect(newState.data).toEqual([{ id: 999 }, { id: 2 }]);
|
||||
expect(newState.data).toBe(originalData); // Same reference for nested objects
|
||||
});
|
||||
|
||||
test('should emit state change events', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
test("should emit state change events", async () => {
|
||||
await service.initialize(42, "test");
|
||||
|
||||
const stateChangeListener = vi.fn();
|
||||
service.on('stateChanged', stateChangeListener);
|
||||
|
||||
service.on("stateChanged", stateChangeListener);
|
||||
|
||||
service.updateState({ value: 100 });
|
||||
|
||||
|
||||
expect(stateChangeListener).toHaveBeenCalledTimes(1);
|
||||
expect(stateChangeListener).toHaveBeenCalledWith(
|
||||
{ value: 100, message: 'test' }, // new state
|
||||
{ value: 42, message: 'test' } // previous state
|
||||
{ value: 100, message: "test" }, // new state
|
||||
{ value: 42, message: "test" }, // previous state
|
||||
);
|
||||
});
|
||||
|
||||
test('should merge partial state updates', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
test("should merge partial state updates", async () => {
|
||||
await service.initialize(42, "test");
|
||||
|
||||
service.updateState({ value: 100 });
|
||||
expect(service.getState()).toEqual({
|
||||
value: 100,
|
||||
message: 'test'
|
||||
message: "test",
|
||||
});
|
||||
|
||||
service.updateState({ message: 'updated' });
|
||||
|
||||
service.updateState({ message: "updated" });
|
||||
expect(service.getState()).toEqual({
|
||||
value: 100,
|
||||
message: 'updated'
|
||||
message: "updated",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Reload Functionality', () => {
|
||||
describe("Reload Functionality", () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should reload service with new parameters', async () => {
|
||||
await service.initialize(42, 'first');
|
||||
test("should reload service with new parameters", async () => {
|
||||
await service.initialize(42, "first");
|
||||
expect(service.getState()).toEqual({
|
||||
value: 42,
|
||||
message: 'first'
|
||||
message: "first",
|
||||
});
|
||||
|
||||
await service.reload(100, 'second');
|
||||
|
||||
await service.reload(100, "second");
|
||||
expect(service.getState()).toEqual({
|
||||
value: 100,
|
||||
message: 'second'
|
||||
message: "second",
|
||||
});
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should reset isInitialized during reload', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
test("should reset isInitialized during reload", async () => {
|
||||
await service.initialize(42, "test");
|
||||
expect(service.isReady()).toBe(true);
|
||||
|
||||
|
||||
// Create a promise to check intermediate state
|
||||
let wasNotReady = false;
|
||||
const originalInit = service.initialize.bind(service);
|
||||
|
|
@ -207,100 +216,104 @@ describe('BaseService', () => {
|
|||
wasNotReady = !service.isReady();
|
||||
return originalInit(value, message);
|
||||
}) as any;
|
||||
|
||||
await service.reload(100, 'reloaded');
|
||||
|
||||
|
||||
await service.reload(100, "reloaded");
|
||||
|
||||
expect(wasNotReady).toBe(true);
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Cleanup', () => {
|
||||
describe("Cleanup", () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should cleanup resources', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
test("should cleanup resources", async () => {
|
||||
await service.initialize(42, "test");
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('test-event', listener);
|
||||
|
||||
service.on("test-event", listener);
|
||||
|
||||
await service.cleanup();
|
||||
|
||||
|
||||
expect(service.isReady()).toBe(false);
|
||||
|
||||
|
||||
// Verify listeners are removed
|
||||
service.emit('test-event');
|
||||
service.emit("test-event");
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ServiceWithDependencies', () => {
|
||||
test('should correctly identify services with dependencies', () => {
|
||||
describe("ServiceWithDependencies", () => {
|
||||
test("should correctly identify services with dependencies", () => {
|
||||
const regularService = new TestService();
|
||||
const dependentService = new DependentTestService();
|
||||
|
||||
|
||||
expect(hasDependencies(regularService)).toBe(false);
|
||||
expect(hasDependencies(dependentService)).toBe(true);
|
||||
|
||||
|
||||
if (hasDependencies(dependentService)) {
|
||||
expect(dependentService.getDependencies()).toEqual(['auth', 'config']);
|
||||
expect(dependentService.getDependencies()).toEqual(["auth", "config"]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Shallow Copy Functionality', () => {
|
||||
describe("Shallow Copy Functionality", () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should handle null and undefined values', async () => {
|
||||
await service.initialize(42, 'test');
|
||||
service.updateState({
|
||||
data: [null, undefined, 'string', 123] as any
|
||||
test("should handle null and undefined values", async () => {
|
||||
await service.initialize(42, "test");
|
||||
service.updateState({
|
||||
data: [null, undefined, "string", 123] as any,
|
||||
});
|
||||
|
||||
|
||||
const state = service.getState();
|
||||
expect(state.data).toEqual([null, undefined, 'string', 123]);
|
||||
expect(state.data).toEqual([null, undefined, "string", 123]);
|
||||
});
|
||||
|
||||
test('should handle Date objects', async () => {
|
||||
const date = new Date('2024-01-01');
|
||||
await service.initialize(42, 'test');
|
||||
service.updateState({
|
||||
data: [date] as any
|
||||
test("should handle Date objects", async () => {
|
||||
const date = new Date("2024-01-01");
|
||||
await service.initialize(42, "test");
|
||||
service.updateState({
|
||||
data: [date] as any,
|
||||
});
|
||||
|
||||
|
||||
const state = service.getState();
|
||||
expect(state.data?.[0]).toEqual(date);
|
||||
expect(state.data?.[0]).toBe(date); // Same instance with shallow copy
|
||||
expect(state.data?.[0]).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
test('should handle complex nested structures', async () => {
|
||||
test("should handle complex nested structures", async () => {
|
||||
const complexData = {
|
||||
nested: {
|
||||
array: [1, 2, { deep: 'value' }],
|
||||
array: [1, 2, { deep: "value" }],
|
||||
date: new Date(),
|
||||
bool: true,
|
||||
null: null
|
||||
}
|
||||
null: null,
|
||||
},
|
||||
};
|
||||
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
await service.initialize(42, "test");
|
||||
service.updateState({ data: complexData as any });
|
||||
|
||||
|
||||
const state = service.getState();
|
||||
expect(state.data).toEqual(complexData);
|
||||
expect(state.data).toBe(complexData); // Same reference with shallow copy
|
||||
|
||||
|
||||
// Verify nested objects are shared (not deep copied)
|
||||
if (state.data && typeof state.data === 'object' && 'nested' in state.data) {
|
||||
if (
|
||||
state.data &&
|
||||
typeof state.data === "object" &&
|
||||
"nested" in state.data
|
||||
) {
|
||||
const data = state.data as any;
|
||||
expect(data.nested.array).toBe(complexData.nested.array);
|
||||
expect(data.nested.array[2]).toBe(complexData.nested.array[2]);
|
||||
|
|
@ -308,79 +321,81 @@ describe('BaseService', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
test('should emit error events on setState failures', () => {
|
||||
describe("Error Handling", () => {
|
||||
test("should emit error events on setState failures", () => {
|
||||
const service = new TestService();
|
||||
|
||||
|
||||
// Override setState to throw
|
||||
const originalSetState = Object.getOwnPropertyDescriptor(
|
||||
Object.getPrototypeOf(service),
|
||||
'setState'
|
||||
Object.getPrototypeOf(service),
|
||||
"setState",
|
||||
);
|
||||
|
||||
Object.defineProperty(service, 'setState', {
|
||||
value: function() {
|
||||
throw new Error('setState failed');
|
||||
}
|
||||
|
||||
Object.defineProperty(service, "setState", {
|
||||
value: function () {
|
||||
throw new Error("setState failed");
|
||||
},
|
||||
});
|
||||
|
||||
expect(() => service.updateState({ value: 100 })).toThrow('setState failed');
|
||||
|
||||
|
||||
expect(() => service.updateState({ value: 100 })).toThrow(
|
||||
"setState failed",
|
||||
);
|
||||
|
||||
// Restore original
|
||||
if (originalSetState) {
|
||||
Object.defineProperty(
|
||||
Object.getPrototypeOf(service),
|
||||
'setState',
|
||||
originalSetState
|
||||
Object.getPrototypeOf(service),
|
||||
"setState",
|
||||
originalSetState,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emitter Integration', () => {
|
||||
describe("Event Emitter Integration", () => {
|
||||
let service: TestService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new TestService();
|
||||
});
|
||||
|
||||
test('should support multiple listeners', async () => {
|
||||
test("should support multiple listeners", async () => {
|
||||
const listener1 = vi.fn();
|
||||
const listener2 = vi.fn();
|
||||
|
||||
service.on('initialized', listener1);
|
||||
service.on('initialized', listener2);
|
||||
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
|
||||
service.on("initialized", listener1);
|
||||
service.on("initialized", listener2);
|
||||
|
||||
await service.initialize(42, "test");
|
||||
|
||||
expect(listener1).toHaveBeenCalledTimes(1);
|
||||
expect(listener2).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('should support once listeners', async () => {
|
||||
test("should support once listeners", async () => {
|
||||
const listener = vi.fn();
|
||||
|
||||
service.once('stateChanged', listener);
|
||||
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
service.once("stateChanged", listener);
|
||||
|
||||
await service.initialize(42, "test");
|
||||
service.updateState({ value: 100 });
|
||||
service.updateState({ value: 200 });
|
||||
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('should allow removing specific listeners', async () => {
|
||||
test("should allow removing specific listeners", async () => {
|
||||
const listener = vi.fn();
|
||||
|
||||
service.on('stateChanged', listener);
|
||||
await service.initialize(42, 'test');
|
||||
|
||||
|
||||
service.on("stateChanged", listener);
|
||||
await service.initialize(42, "test");
|
||||
|
||||
service.updateState({ value: 100 });
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
|
||||
service.off('stateChanged', listener);
|
||||
|
||||
service.off("stateChanged", listener);
|
||||
service.updateState({ value: 200 });
|
||||
expect(listener).toHaveBeenCalledTimes(1); // Not called again
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
"/path/to/config.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
|
|
@ -59,7 +59,7 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
undefined,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
|
|
@ -69,20 +69,20 @@ describe("ConfigService", () => {
|
|||
});
|
||||
|
||||
test("should inject rules into config", async () => {
|
||||
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/config.yaml" } as any,
|
||||
});
|
||||
vi.mocked(args.processRule)
|
||||
.mockImplementation(async (rule) => `Processed: ${rule}`);
|
||||
vi.mocked(args.processRule).mockImplementation(
|
||||
async (rule) => `Processed: ${rule}`,
|
||||
);
|
||||
|
||||
const state = await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/config.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any,
|
||||
["rule1", "rule2"]
|
||||
["rule1", "rule2"],
|
||||
);
|
||||
|
||||
expect(state.config).toEqual({
|
||||
|
|
@ -95,7 +95,6 @@ describe("ConfigService", () => {
|
|||
|
||||
describe("switchConfig()", () => {
|
||||
test("should switch to new configuration", async () => {
|
||||
|
||||
// Initialize first
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
|
|
@ -105,7 +104,7 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
// Switch to new config
|
||||
|
|
@ -119,7 +118,7 @@ describe("ConfigService", () => {
|
|||
"/new.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
|
|
@ -130,31 +129,30 @@ describe("ConfigService", () => {
|
|||
});
|
||||
|
||||
test("should handle switch config errors", async () => {
|
||||
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
vi.mocked(configLoader.loadConfiguration)
|
||||
.mockRejectedValue(new Error("Config not found"));
|
||||
vi.mocked(configLoader.loadConfiguration).mockRejectedValue(
|
||||
new Error("Config not found"),
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.switchConfig(
|
||||
"/bad.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
)
|
||||
mockApiClient as any,
|
||||
),
|
||||
).rejects.toThrow("Config not found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reload()", () => {
|
||||
test("should reload current configuration", async () => {
|
||||
|
||||
// Initialize with a config
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
|
|
@ -164,7 +162,7 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
"/config.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
// Modify mock to return updated config
|
||||
|
|
@ -177,7 +175,7 @@ describe("ConfigService", () => {
|
|||
const state = await service.reload(
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
expect(state).toEqual({
|
||||
|
|
@ -196,22 +194,21 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
undefined,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.reload(
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
)
|
||||
mockApiClient as any,
|
||||
),
|
||||
).rejects.toThrow("No configuration path available for reload");
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateConfigPath()", () => {
|
||||
test("should update config path and reload dependent services", async () => {
|
||||
|
||||
// Initialize service first
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
|
|
@ -221,12 +218,14 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
// Mock service container
|
||||
vi.mocked(workos.loadAuthConfig)
|
||||
.mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
|
||||
vi.mocked(workos.loadAuthConfig).mockReturnValue({
|
||||
accessToken: "token",
|
||||
organizationId: "org-123",
|
||||
} as any);
|
||||
vi.mocked(serviceContainer.get).mockResolvedValue({
|
||||
apiClient: mockApiClient,
|
||||
});
|
||||
|
|
@ -246,13 +245,13 @@ describe("ConfigService", () => {
|
|||
});
|
||||
expect(vi.mocked(serviceContainer.set)).toHaveBeenCalledWith(
|
||||
SERVICE_NAMES.CONFIG,
|
||||
expect.objectContaining({ config: newConfig })
|
||||
expect.objectContaining({ config: newConfig }),
|
||||
);
|
||||
expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith(
|
||||
SERVICE_NAMES.MODEL
|
||||
SERVICE_NAMES.MODEL,
|
||||
);
|
||||
expect(vi.mocked(serviceContainer.reload)).toHaveBeenCalledWith(
|
||||
SERVICE_NAMES.MCP
|
||||
SERVICE_NAMES.MCP,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -261,17 +260,19 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
vi.mocked(workos.loadAuthConfig)
|
||||
.mockReturnValue({ accessToken: "token", organizationId: "org-123" } as any);
|
||||
vi.mocked(workos.loadAuthConfig).mockReturnValue({
|
||||
accessToken: "token",
|
||||
organizationId: "org-123",
|
||||
} as any);
|
||||
vi.mocked(serviceContainer.get).mockResolvedValue({
|
||||
apiClient: null,
|
||||
});
|
||||
|
||||
await expect(service.updateConfigPath("/new.yaml")).rejects.toThrow(
|
||||
"API client not available"
|
||||
"API client not available",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -284,7 +285,6 @@ describe("ConfigService", () => {
|
|||
|
||||
describe("Event Emission", () => {
|
||||
test("should emit stateChanged when switching config", async () => {
|
||||
|
||||
vi.mocked(configLoader.loadConfiguration).mockResolvedValue({
|
||||
config: mockConfig as any,
|
||||
source: { type: "cli-flag", path: "/old.yaml" } as any,
|
||||
|
|
@ -293,7 +293,7 @@ describe("ConfigService", () => {
|
|||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
const listener = vi.fn();
|
||||
|
|
@ -309,22 +309,24 @@ describe("ConfigService", () => {
|
|||
"/new.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ config: newConfig, configPath: "/new.yaml" }),
|
||||
expect.objectContaining({ config: mockConfig, configPath: "/old.yaml" })
|
||||
expect.objectContaining({
|
||||
config: mockConfig,
|
||||
configPath: "/old.yaml",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("should emit error on switch failure", async () => {
|
||||
|
||||
await service.initialize(
|
||||
{ accessToken: "token" } as any,
|
||||
"/old.yaml",
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
mockApiClient as any,
|
||||
);
|
||||
|
||||
const errorListener = vi.fn();
|
||||
|
|
@ -338,8 +340,8 @@ describe("ConfigService", () => {
|
|||
"/bad.yaml",
|
||||
{ accessToken: "token" } as any,
|
||||
"org-123",
|
||||
mockApiClient as any
|
||||
)
|
||||
mockApiClient as any,
|
||||
),
|
||||
).rejects.toThrow();
|
||||
expect(errorListener).toHaveBeenCalledWith(error);
|
||||
});
|
||||
|
|
@ -367,4 +369,4 @@ describe("ConfigService", () => {
|
|||
expect(service.updateConfigPath.length).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as fs from "fs";
|
||||
import * as path from "path";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { FileIndexService } from './FileIndexService.js';
|
||||
import { FileIndexService } from "./FileIndexService.js";
|
||||
|
||||
// Mock the file watcher
|
||||
vi.mock('../util/fileWatcher.js', () => ({
|
||||
vi.mock("../util/fileWatcher.js", () => ({
|
||||
getFileWatcher: () => ({
|
||||
startWatching: vi.fn(),
|
||||
stopWatching: vi.fn(),
|
||||
|
|
@ -15,18 +15,18 @@ vi.mock('../util/fileWatcher.js', () => ({
|
|||
}));
|
||||
|
||||
// Mock git detection
|
||||
vi.mock('../util/git.js', () => ({
|
||||
vi.mock("../util/git.js", () => ({
|
||||
isGitRepo: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
describe('FileIndexService', () => {
|
||||
describe("FileIndexService", () => {
|
||||
let service: FileIndexService;
|
||||
let tempDir: string;
|
||||
let originalCwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
tempDir = fs.mkdtempSync(path.join(process.cwd(), 'test-fileindex-'));
|
||||
tempDir = fs.mkdtempSync(path.join(process.cwd(), "test-fileindex-"));
|
||||
process.chdir(tempDir);
|
||||
|
||||
service = new FileIndexService();
|
||||
|
|
@ -40,11 +40,11 @@ describe('FileIndexService', () => {
|
|||
}
|
||||
});
|
||||
|
||||
it('should initialize and index files', async () => {
|
||||
it("should initialize and index files", async () => {
|
||||
// Create test files
|
||||
fs.writeFileSync('test.js', 'console.log("test");');
|
||||
fs.writeFileSync('test.ts', 'console.log("test");');
|
||||
fs.writeFileSync('README.md', '# Test');
|
||||
fs.writeFileSync("test.js", 'console.log("test");');
|
||||
fs.writeFileSync("test.ts", 'console.log("test");');
|
||||
fs.writeFileSync("README.md", "# Test");
|
||||
|
||||
// Initialize the service
|
||||
await service.initialize();
|
||||
|
|
@ -52,99 +52,102 @@ describe('FileIndexService', () => {
|
|||
// Should have indexed the files
|
||||
const files = service.getFiles();
|
||||
expect(files.length).toBeGreaterThan(0);
|
||||
|
||||
const filePaths = files.map(f => f.path);
|
||||
expect(filePaths).toContain('test.js');
|
||||
expect(filePaths).toContain('test.ts');
|
||||
expect(filePaths).toContain('README.md');
|
||||
|
||||
const filePaths = files.map((f) => f.path);
|
||||
expect(filePaths).toContain("test.js");
|
||||
expect(filePaths).toContain("test.ts");
|
||||
expect(filePaths).toContain("README.md");
|
||||
});
|
||||
|
||||
it('should filter files correctly', async () => {
|
||||
it("should filter files correctly", async () => {
|
||||
// Create test files
|
||||
fs.writeFileSync('component.tsx', 'export default () => <div></div>');
|
||||
fs.writeFileSync('utils.ts', 'export const util = () => {}');
|
||||
fs.writeFileSync('styles.css', '.test { color: red; }');
|
||||
fs.writeFileSync("component.tsx", "export default () => <div></div>");
|
||||
fs.writeFileSync("utils.ts", "export const util = () => {}");
|
||||
fs.writeFileSync("styles.css", ".test { color: red; }");
|
||||
|
||||
await service.initialize();
|
||||
|
||||
// Test filtering by extension
|
||||
const tsFiles = service.filterFiles('ts');
|
||||
expect(tsFiles.some(f => f.path === 'component.tsx')).toBe(true);
|
||||
expect(tsFiles.some(f => f.path === 'utils.ts')).toBe(true);
|
||||
expect(tsFiles.some(f => f.path === 'styles.css')).toBe(false);
|
||||
const tsFiles = service.filterFiles("ts");
|
||||
expect(tsFiles.some((f) => f.path === "component.tsx")).toBe(true);
|
||||
expect(tsFiles.some((f) => f.path === "utils.ts")).toBe(true);
|
||||
expect(tsFiles.some((f) => f.path === "styles.css")).toBe(false);
|
||||
|
||||
// Test filtering by name
|
||||
const componentFiles = service.filterFiles('component');
|
||||
expect(componentFiles.some(f => f.path === 'component.tsx')).toBe(true);
|
||||
expect(componentFiles.some(f => f.path === 'utils.ts')).toBe(false);
|
||||
const componentFiles = service.filterFiles("component");
|
||||
expect(componentFiles.some((f) => f.path === "component.tsx")).toBe(true);
|
||||
expect(componentFiles.some((f) => f.path === "utils.ts")).toBe(false);
|
||||
});
|
||||
|
||||
it('should handle empty directory', async () => {
|
||||
it("should handle empty directory", async () => {
|
||||
await service.initialize();
|
||||
|
||||
|
||||
const files = service.getFiles();
|
||||
expect(files).toEqual([]);
|
||||
expect(service.isIndexing()).toBe(false);
|
||||
expect(service.getError()).toBeNull();
|
||||
});
|
||||
|
||||
it('should ignore specified patterns', async () => {
|
||||
it("should ignore specified patterns", async () => {
|
||||
// Create files that should be ignored
|
||||
fs.mkdirSync('node_modules');
|
||||
fs.writeFileSync(path.join('node_modules', 'package.js'), 'module.exports = {}');
|
||||
|
||||
fs.mkdirSync('dist');
|
||||
fs.writeFileSync(path.join('dist', 'bundle.js'), 'console.log("bundle")');
|
||||
fs.mkdirSync("node_modules");
|
||||
fs.writeFileSync(
|
||||
path.join("node_modules", "package.js"),
|
||||
"module.exports = {}",
|
||||
);
|
||||
|
||||
fs.mkdirSync("dist");
|
||||
fs.writeFileSync(path.join("dist", "bundle.js"), 'console.log("bundle")');
|
||||
|
||||
// Create files that should be included
|
||||
fs.writeFileSync('src.js', 'console.log("src")');
|
||||
fs.writeFileSync("src.js", 'console.log("src")');
|
||||
|
||||
await service.initialize();
|
||||
|
||||
const files = service.getFiles();
|
||||
const filePaths = files.map(f => f.path);
|
||||
|
||||
const filePaths = files.map((f) => f.path);
|
||||
|
||||
// Should include src.js
|
||||
expect(filePaths).toContain('src.js');
|
||||
|
||||
expect(filePaths).toContain("src.js");
|
||||
|
||||
// Should not include ignored files
|
||||
expect(filePaths.some(p => p.includes('node_modules'))).toBe(false);
|
||||
expect(filePaths.some(p => p.includes('dist'))).toBe(false);
|
||||
expect(filePaths.some((p) => p.includes("node_modules"))).toBe(false);
|
||||
expect(filePaths.some((p) => p.includes("dist"))).toBe(false);
|
||||
});
|
||||
|
||||
it('should sort files correctly with no filter', async () => {
|
||||
it("should sort files correctly with no filter", async () => {
|
||||
// Create files in non-alphabetical order
|
||||
fs.writeFileSync('zebra.js', 'console.log("zebra")');
|
||||
fs.writeFileSync('alpha.js', 'console.log("alpha")');
|
||||
fs.writeFileSync('beta.js', 'console.log("beta")');
|
||||
fs.writeFileSync("zebra.js", 'console.log("zebra")');
|
||||
fs.writeFileSync("alpha.js", 'console.log("alpha")');
|
||||
fs.writeFileSync("beta.js", 'console.log("beta")');
|
||||
|
||||
await service.initialize();
|
||||
|
||||
const files = service.filterFiles('');
|
||||
expect(files[0].path).toBe('alpha.js');
|
||||
expect(files[1].path).toBe('beta.js');
|
||||
expect(files[2].path).toBe('zebra.js');
|
||||
const files = service.filterFiles("");
|
||||
expect(files[0].path).toBe("alpha.js");
|
||||
expect(files[1].path).toBe("beta.js");
|
||||
expect(files[2].path).toBe("zebra.js");
|
||||
});
|
||||
|
||||
it('should include files with matching names and paths', async () => {
|
||||
it("should include files with matching names and paths", async () => {
|
||||
// Create nested structure
|
||||
fs.mkdirSync('src');
|
||||
fs.writeFileSync(path.join('src', 'test-helper.js'), 'helper');
|
||||
fs.writeFileSync('test.js', 'test file');
|
||||
fs.mkdirSync("src");
|
||||
fs.writeFileSync(path.join("src", "test-helper.js"), "helper");
|
||||
fs.writeFileSync("test.js", "test file");
|
||||
|
||||
await service.initialize();
|
||||
|
||||
const filtered = service.filterFiles('test');
|
||||
|
||||
const filtered = service.filterFiles("test");
|
||||
|
||||
// Should include both files that match the filter
|
||||
expect(filtered.length).toBeGreaterThanOrEqual(2);
|
||||
const filePaths = filtered.map(f => f.path);
|
||||
expect(filePaths).toContain('test.js');
|
||||
const filePaths = filtered.map((f) => f.path);
|
||||
expect(filePaths).toContain("test.js");
|
||||
// Normalize path separators for cross-platform compatibility
|
||||
expect(filePaths).toContain(path.join('src', 'test-helper.js'));
|
||||
expect(filePaths).toContain(path.join("src", "test-helper.js"));
|
||||
});
|
||||
|
||||
it('should respect limit parameter', async () => {
|
||||
it("should respect limit parameter", async () => {
|
||||
// Create many files
|
||||
for (let i = 0; i < 20; i++) {
|
||||
fs.writeFileSync(`file${i}.js`, `console.log("file${i}")`);
|
||||
|
|
@ -152,22 +155,22 @@ describe('FileIndexService', () => {
|
|||
|
||||
await service.initialize();
|
||||
|
||||
const files = service.filterFiles('', 5);
|
||||
const files = service.filterFiles("", 5);
|
||||
expect(files.length).toBe(5);
|
||||
});
|
||||
|
||||
it('should handle refresh correctly', async () => {
|
||||
it("should handle refresh correctly", async () => {
|
||||
// Create initial file
|
||||
fs.writeFileSync('initial.js', 'console.log("initial")');
|
||||
|
||||
fs.writeFileSync("initial.js", 'console.log("initial")');
|
||||
|
||||
await service.initialize();
|
||||
expect(service.getFiles().length).toBe(1);
|
||||
|
||||
// Add another file
|
||||
fs.writeFileSync('added.js', 'console.log("added")');
|
||||
|
||||
fs.writeFileSync("added.js", 'console.log("added")');
|
||||
|
||||
// Refresh should pick up the new file
|
||||
await service.refreshIndex();
|
||||
expect(service.getFiles().length).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ describe("MCPService", () => {
|
|||
|
||||
afterEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
await mcpService.cleanup()
|
||||
await mcpService.cleanup();
|
||||
});
|
||||
|
||||
describe("initialization", () => {
|
||||
|
|
@ -86,7 +86,7 @@ describe("MCPService", () => {
|
|||
const firstStatus = mcpService.getOverallStatus();
|
||||
expect(firstStatus.status).toBe("connected");
|
||||
expect(firstStatus.hasWarnings).toBe(false);
|
||||
await mcpService.cleanup()
|
||||
await mcpService.cleanup();
|
||||
const secondStatus = mcpService.getOverallStatus();
|
||||
expect(secondStatus.status).toBe("idle");
|
||||
});
|
||||
|
|
@ -107,14 +107,13 @@ describe("MCPService", () => {
|
|||
|
||||
it("should handle server not found error", async () => {
|
||||
await expect(mcpService.restartServer("nonexistent")).rejects.toThrow(
|
||||
"Server nonexistent not found in configuration"
|
||||
"Server nonexistent not found in configuration",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle stop individual server", async () => {
|
||||
await expect(mcpService.stopServer("test-server")).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("tools and prompts", () => {
|
||||
|
|
@ -129,7 +128,7 @@ describe("MCPService", () => {
|
|||
|
||||
it("should throw error for unknown tool", async () => {
|
||||
await expect(mcpService.runTool("unknown-tool", {})).rejects.toThrow(
|
||||
"Tool unknown-tool not found"
|
||||
"Tool unknown-tool not found",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -137,10 +136,14 @@ describe("MCPService", () => {
|
|||
describe("shutdown", () => {
|
||||
it("should handle shutdown gracefully", async () => {
|
||||
await mcpService.initialize(mockAssistant);
|
||||
await mcpService.cleanup()
|
||||
await mcpService.cleanup();
|
||||
|
||||
const state = mcpService.getState();
|
||||
expect(state.mcpService?.getState().connections.filter(c => c.status === "connected")).toHaveLength(0)
|
||||
expect(
|
||||
state.mcpService
|
||||
?.getState()
|
||||
.connections.filter((c) => c.status === "connected"),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle multiple shutdown calls", async () => {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { beforeEach, afterEach, describe, expect, vi, test } from 'vitest';
|
||||
import { beforeEach, afterEach, describe, expect, vi, test } from "vitest";
|
||||
|
||||
import { ModeService } from './ModeService.js';
|
||||
import { ModeService } from "./ModeService.js";
|
||||
|
||||
describe('ModeService', () => {
|
||||
describe("ModeService", () => {
|
||||
let modeService: ModeService;
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -16,166 +16,166 @@ describe('ModeService', () => {
|
|||
(ModeService as any).instance = undefined;
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with normal mode by default', async () => {
|
||||
describe("State Management", () => {
|
||||
test("should initialize with normal mode by default", async () => {
|
||||
const state = await modeService.initialize({});
|
||||
|
||||
|
||||
expect(state).toEqual({
|
||||
mode: 'normal',
|
||||
toolPermissionService: expect.any(Object)
|
||||
mode: "normal",
|
||||
toolPermissionService: expect.any(Object),
|
||||
});
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
expect(modeService.getCurrentMode()).toBe("normal");
|
||||
});
|
||||
|
||||
test('should convert readonly flag to plan mode', async () => {
|
||||
test("should convert readonly flag to plan mode", async () => {
|
||||
const state = await modeService.initialize({ readonly: true });
|
||||
|
||||
expect(state.mode).toBe('plan');
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
|
||||
expect(state.mode).toBe("plan");
|
||||
expect(modeService.getCurrentMode()).toBe("plan");
|
||||
});
|
||||
|
||||
test('should convert auto flag to auto mode', async () => {
|
||||
test("should convert auto flag to auto mode", async () => {
|
||||
const state = await modeService.initialize({ auto: true });
|
||||
|
||||
expect(state.mode).toBe('auto');
|
||||
expect(modeService.getCurrentMode()).toBe('auto');
|
||||
|
||||
expect(state.mode).toBe("auto");
|
||||
expect(modeService.getCurrentMode()).toBe("auto");
|
||||
});
|
||||
|
||||
test('should initialize tool permission service with flags', async () => {
|
||||
const state = await modeService.initialize({
|
||||
allow: ['testTool'],
|
||||
exclude: ['badTool']
|
||||
test("should initialize tool permission service with flags", async () => {
|
||||
const state = await modeService.initialize({
|
||||
allow: ["testTool"],
|
||||
exclude: ["badTool"],
|
||||
});
|
||||
|
||||
|
||||
const toolPermissionService = state.toolPermissionService;
|
||||
expect(toolPermissionService).toBeDefined();
|
||||
expect(toolPermissionService.getState()).toBeDefined();
|
||||
expect(toolPermissionService.getCurrentMode()).toBe('normal');
|
||||
expect(toolPermissionService.getCurrentMode()).toBe("normal");
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchMode()', () => {
|
||||
describe("switchMode()", () => {
|
||||
beforeEach(async () => {
|
||||
await modeService.initialize({});
|
||||
});
|
||||
|
||||
test('should switch from normal to plan mode', () => {
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
|
||||
modeService.switchMode('plan');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
expect(modeService.getState().mode).toBe('plan');
|
||||
test("should switch from normal to plan mode", () => {
|
||||
expect(modeService.getCurrentMode()).toBe("normal");
|
||||
|
||||
modeService.switchMode("plan");
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe("plan");
|
||||
expect(modeService.getState().mode).toBe("plan");
|
||||
});
|
||||
|
||||
test('should switch from plan to auto mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
|
||||
modeService.switchMode('auto');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe('auto');
|
||||
expect(modeService.getState().mode).toBe('auto');
|
||||
test("should switch from plan to auto mode", () => {
|
||||
modeService.switchMode("plan");
|
||||
expect(modeService.getCurrentMode()).toBe("plan");
|
||||
|
||||
modeService.switchMode("auto");
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe("auto");
|
||||
expect(modeService.getState().mode).toBe("auto");
|
||||
});
|
||||
|
||||
test('should switch back to normal mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
modeService.switchMode('normal');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
expect(modeService.getState().mode).toBe('normal');
|
||||
test("should switch back to normal mode", () => {
|
||||
modeService.switchMode("plan");
|
||||
modeService.switchMode("normal");
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe("normal");
|
||||
expect(modeService.getState().mode).toBe("normal");
|
||||
});
|
||||
|
||||
test('should update tool permission service when switching modes', () => {
|
||||
test("should update tool permission service when switching modes", () => {
|
||||
const toolPermissionService = modeService.getToolPermissionService();
|
||||
const initialState = toolPermissionService.getState();
|
||||
|
||||
modeService.switchMode('auto');
|
||||
|
||||
modeService.switchMode("auto");
|
||||
const newState = toolPermissionService.getState();
|
||||
|
||||
expect(newState.currentMode).toBe('auto');
|
||||
|
||||
expect(newState.currentMode).toBe("auto");
|
||||
expect(newState.permissions.policies.length).toBeGreaterThan(0);
|
||||
expect(newState.permissions.policies[0]).toEqual({
|
||||
tool: '*',
|
||||
permission: 'allow'
|
||||
tool: "*",
|
||||
permission: "allow",
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle multiple mode switches correctly', () => {
|
||||
test("should handle multiple mode switches correctly", () => {
|
||||
// Start in normal
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe("normal");
|
||||
|
||||
// Switch to plan
|
||||
modeService.switchMode('plan');
|
||||
modeService.switchMode("plan");
|
||||
const planState = modeService.getToolPermissionService().getState();
|
||||
expect(planState.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
tool: "Write",
|
||||
permission: "exclude",
|
||||
});
|
||||
|
||||
|
||||
// Switch to auto
|
||||
modeService.switchMode('auto');
|
||||
modeService.switchMode("auto");
|
||||
const autoState = modeService.getToolPermissionService().getState();
|
||||
expect(autoState.permissions.policies).toHaveLength(1);
|
||||
expect(autoState.permissions.policies[0]).toEqual({
|
||||
tool: '*',
|
||||
permission: 'allow'
|
||||
tool: "*",
|
||||
permission: "allow",
|
||||
});
|
||||
|
||||
|
||||
// Back to normal
|
||||
modeService.switchMode('normal');
|
||||
modeService.switchMode("normal");
|
||||
const normalState = modeService.getToolPermissionService().getState();
|
||||
expect(normalState.currentMode).toBe('normal');
|
||||
expect(normalState.currentMode).toBe("normal");
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableModes()', () => {
|
||||
describe("getAvailableModes()", () => {
|
||||
beforeEach(async () => {
|
||||
await modeService.initialize({});
|
||||
});
|
||||
|
||||
test('should return all available modes with descriptions', () => {
|
||||
test("should return all available modes with descriptions", () => {
|
||||
const modes = modeService.getAvailableModes();
|
||||
expect(modes).toHaveLength(3);
|
||||
|
||||
const modeNames = modes.map(m => m.mode);
|
||||
expect(modeNames).toContain('normal');
|
||||
expect(modeNames).toContain('plan');
|
||||
expect(modeNames).toContain('auto');
|
||||
|
||||
|
||||
const modeNames = modes.map((m) => m.mode);
|
||||
expect(modeNames).toContain("normal");
|
||||
expect(modeNames).toContain("plan");
|
||||
expect(modeNames).toContain("auto");
|
||||
|
||||
// Check that all modes have descriptions
|
||||
modes.forEach(mode => {
|
||||
modes.forEach((mode) => {
|
||||
expect(mode.description).toBeDefined();
|
||||
expect(mode.description.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Singleton Behavior', () => {
|
||||
test('should return the same instance', () => {
|
||||
describe("Singleton Behavior", () => {
|
||||
test("should return the same instance", () => {
|
||||
const instance1 = ModeService.getInstance();
|
||||
const instance2 = ModeService.getInstance();
|
||||
expect(instance1).toBe(instance2);
|
||||
});
|
||||
|
||||
test('should maintain state across getInstance calls', async () => {
|
||||
test("should maintain state across getInstance calls", async () => {
|
||||
const instance1 = ModeService.getInstance();
|
||||
await instance1.initialize({});
|
||||
instance1.switchMode('plan');
|
||||
|
||||
instance1.switchMode("plan");
|
||||
|
||||
const instance2 = ModeService.getInstance();
|
||||
expect(instance2.getCurrentMode()).toBe('plan');
|
||||
expect(instance2.getCurrentMode()).toBe("plan");
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReady()', () => {
|
||||
test('should always return true for ModeService', () => {
|
||||
describe("isReady()", () => {
|
||||
test("should always return true for ModeService", () => {
|
||||
// ModeService is always ready since it's a singleton
|
||||
expect(modeService.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
describe("Event Emission", () => {
|
||||
let modeChangeListener: ReturnType<typeof vi.fn>;
|
||||
let stateChangeListener: ReturnType<typeof vi.fn>;
|
||||
|
||||
|
|
@ -183,77 +183,77 @@ describe('ModeService', () => {
|
|||
await modeService.initialize({});
|
||||
modeChangeListener = vi.fn();
|
||||
stateChangeListener = vi.fn();
|
||||
modeService.on('modeChanged', modeChangeListener);
|
||||
modeService.on('stateChanged', stateChangeListener);
|
||||
modeService.on("modeChanged", modeChangeListener);
|
||||
modeService.on("stateChanged", stateChangeListener);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
modeService.off('modeChanged', modeChangeListener);
|
||||
modeService.off('stateChanged', stateChangeListener);
|
||||
modeService.off("modeChanged", modeChangeListener);
|
||||
modeService.off("stateChanged", stateChangeListener);
|
||||
});
|
||||
|
||||
test('should emit modeChanged event when mode switches', () => {
|
||||
modeService.switchMode('plan');
|
||||
|
||||
expect(modeChangeListener).toHaveBeenCalledWith('plan', 'normal');
|
||||
test("should emit modeChanged event when mode switches", () => {
|
||||
modeService.switchMode("plan");
|
||||
|
||||
expect(modeChangeListener).toHaveBeenCalledWith("plan", "normal");
|
||||
expect(modeChangeListener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('should emit stateChanged event when mode switches', () => {
|
||||
modeService.switchMode('plan');
|
||||
|
||||
test("should emit stateChanged event when mode switches", () => {
|
||||
modeService.switchMode("plan");
|
||||
|
||||
expect(stateChangeListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ mode: 'plan' }),
|
||||
expect.objectContaining({ mode: 'normal' })
|
||||
expect.objectContaining({ mode: "plan" }),
|
||||
expect.objectContaining({ mode: "normal" }),
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit event with correct previous and new modes', () => {
|
||||
modeService.switchMode('plan');
|
||||
test("should emit event with correct previous and new modes", () => {
|
||||
modeService.switchMode("plan");
|
||||
modeChangeListener.mockClear();
|
||||
stateChangeListener.mockClear();
|
||||
|
||||
modeService.switchMode('auto');
|
||||
|
||||
expect(modeChangeListener).toHaveBeenCalledWith('auto', 'plan');
|
||||
|
||||
modeService.switchMode("auto");
|
||||
|
||||
expect(modeChangeListener).toHaveBeenCalledWith("auto", "plan");
|
||||
expect(modeChangeListener).toHaveBeenCalledTimes(1);
|
||||
expect(stateChangeListener).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('should not emit event when switching to same mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
test("should not emit event when switching to same mode", () => {
|
||||
modeService.switchMode("plan");
|
||||
modeChangeListener.mockClear();
|
||||
stateChangeListener.mockClear();
|
||||
|
||||
modeService.switchMode('plan');
|
||||
|
||||
|
||||
modeService.switchMode("plan");
|
||||
|
||||
expect(modeChangeListener).not.toHaveBeenCalled();
|
||||
// stateChanged might still be called due to setState, but modeChanged should not
|
||||
});
|
||||
});
|
||||
|
||||
describe('Integration with ToolPermissionService', () => {
|
||||
describe("Integration with ToolPermissionService", () => {
|
||||
beforeEach(async () => {
|
||||
await modeService.initialize({
|
||||
allow: ['Read'],
|
||||
exclude: ['dangerous_tool']
|
||||
allow: ["Read"],
|
||||
exclude: ["dangerous_tool"],
|
||||
});
|
||||
});
|
||||
|
||||
test('should pass initialization args to ToolPermissionService', () => {
|
||||
test("should pass initialization args to ToolPermissionService", () => {
|
||||
const toolService = modeService.getToolPermissionService();
|
||||
const state = toolService.getState();
|
||||
|
||||
|
||||
// The state should have processed the allow/exclude rules
|
||||
expect(state.permissions.policies).toBeDefined();
|
||||
expect(state.currentMode).toBe('normal');
|
||||
expect(state.currentMode).toBe("normal");
|
||||
});
|
||||
|
||||
test('should maintain ToolPermissionService reference', () => {
|
||||
test("should maintain ToolPermissionService reference", () => {
|
||||
const toolService1 = modeService.getToolPermissionService();
|
||||
const toolService2 = modeService.getToolPermissionService();
|
||||
|
||||
|
||||
expect(toolService1).toBe(toolService2);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,19 +1,19 @@
|
|||
import { AssistantUnrolled, ModelConfig } from '@continuedev/config-yaml';
|
||||
import * as openaiAdapters from '@continuedev/openai-adapters';
|
||||
import { describe, expect, beforeEach, vi, test } from 'vitest';
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import * as openaiAdapters from "@continuedev/openai-adapters";
|
||||
import { describe, expect, beforeEach, vi, test } from "vitest";
|
||||
|
||||
// Mock dependencies before imports
|
||||
vi.mock('@continuedev/openai-adapters');
|
||||
vi.mock('../config.js');
|
||||
vi.mock('../auth/workos.js');
|
||||
vi.mock("@continuedev/openai-adapters");
|
||||
vi.mock("../config.js");
|
||||
vi.mock("../auth/workos.js");
|
||||
|
||||
import { AuthConfig } from '../auth/workos.js';
|
||||
import * as workos from '../auth/workos.js';
|
||||
import * as config from '../config.js';
|
||||
import { AuthConfig } from "../auth/workos.js";
|
||||
import * as workos from "../auth/workos.js";
|
||||
import * as config from "../config.js";
|
||||
|
||||
import { ModelService } from './ModelService.js';
|
||||
import { ModelService } from "./ModelService.js";
|
||||
|
||||
describe('ModelService', () => {
|
||||
describe("ModelService", () => {
|
||||
let service: ModelService;
|
||||
let mockAssistant: AssistantUnrolled;
|
||||
let mockAuthConfig: AuthConfig;
|
||||
|
|
@ -24,69 +24,77 @@ describe('ModelService', () => {
|
|||
service = new ModelService();
|
||||
|
||||
mockAssistant = {
|
||||
name: 'test-assistant',
|
||||
version: '1.0.0',
|
||||
name: "test-assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
{
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
name: 'GPT-4',
|
||||
apiKey: 'test-key',
|
||||
roles: ['chat'],
|
||||
provider: "openai",
|
||||
model: "gpt-4",
|
||||
name: "GPT-4",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: 'anthropic',
|
||||
model: 'claude-3',
|
||||
name: 'Claude 3',
|
||||
apiKey: 'test-key',
|
||||
roles: ['chat'],
|
||||
provider: "anthropic",
|
||||
model: "claude-3",
|
||||
name: "Claude 3",
|
||||
apiKey: "test-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
{
|
||||
provider: 'openai',
|
||||
model: 'gpt-3.5',
|
||||
name: 'GPT-3.5',
|
||||
apiKey: 'test-key',
|
||||
roles: ['embed'],
|
||||
provider: "openai",
|
||||
model: "gpt-3.5",
|
||||
name: "GPT-3.5",
|
||||
apiKey: "test-key",
|
||||
roles: ["embed"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
} as AssistantUnrolled;
|
||||
|
||||
mockAuthConfig = {
|
||||
accessToken: 'test-token',
|
||||
refreshToken: 'test-refresh',
|
||||
userEmail: 'test@example.com',
|
||||
userId: 'test-user',
|
||||
organizationId: 'test-org',
|
||||
accessToken: "test-token",
|
||||
refreshToken: "test-refresh",
|
||||
userEmail: "test@example.com",
|
||||
userId: "test-user",
|
||||
organizationId: "test-org",
|
||||
expiresAt: Date.now() + 3600000, // 1 hour from now
|
||||
};
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with default model', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
describe("State Management", () => {
|
||||
test("should initialize with default model", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
vi.mocked(workos.getModelName).mockReturnValue(null);
|
||||
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(state).toEqual({
|
||||
llmApi: mockLlmApi,
|
||||
model: mockAssistant.models![0]
|
||||
model: mockAssistant.models![0],
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with persisted model if valid', async () => {
|
||||
vi.mocked(workos.getModelName).mockReturnValue('Claude 3');
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
test("should initialize with persisted model if valid", async () => {
|
||||
vi.mocked(workos.getModelName).mockReturnValue("Claude 3");
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
|
||||
mockLlmApi as any,
|
||||
);
|
||||
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(state.model?.name).toBe('Claude 3');
|
||||
expect(state.model?.name).toBe("Claude 3");
|
||||
expect(state.llmApi).toStrictEqual(mockLlmApi);
|
||||
});
|
||||
|
||||
test('should fall back to default if persisted model not found', async () => {
|
||||
vi.mocked(workos.getModelName).mockReturnValue('Non-existent Model');
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
test("should fall back to default if persisted model not found", async () => {
|
||||
vi.mocked(workos.getModelName).mockReturnValue("Non-existent Model");
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
|
||||
const state = await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
|
|
@ -94,10 +102,13 @@ describe('ModelService', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('update()', () => {
|
||||
test('should update model with new assistant config', async () => {
|
||||
describe("update()", () => {
|
||||
test("should update model with new assistant config", async () => {
|
||||
// Initialize first
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
// Update with new assistant
|
||||
|
|
@ -105,124 +116,152 @@ describe('ModelService', () => {
|
|||
...mockAssistant,
|
||||
models: [
|
||||
{
|
||||
provider: 'openai',
|
||||
model: 'gpt-4-turbo',
|
||||
name: 'GPT-4 Turbo',
|
||||
apiKey: 'new-key',
|
||||
roles: ['chat'],
|
||||
provider: "openai",
|
||||
model: "gpt-4-turbo",
|
||||
name: "GPT-4 Turbo",
|
||||
apiKey: "new-key",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig,
|
||||
],
|
||||
};
|
||||
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([newLlmApi as any, newAssistant.models![0] as ModelConfig]);
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
newLlmApi as any,
|
||||
newAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
|
||||
const state = await service.update(newAssistant, mockAuthConfig);
|
||||
|
||||
expect(state).toEqual({
|
||||
llmApi: newLlmApi,
|
||||
model: newAssistant.models![0]
|
||||
model: newAssistant.models![0],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchModel()', () => {
|
||||
test('should switch to a different model by index', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
describe("switchModel()", () => {
|
||||
test("should switch to a different model by index", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(newLlmApi as any);
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
|
||||
newLlmApi as any,
|
||||
);
|
||||
|
||||
const state = await service.switchModel(1);
|
||||
|
||||
expect(state).toEqual({
|
||||
llmApi: newLlmApi,
|
||||
model: mockAssistant.models![1]
|
||||
model: mockAssistant.models![1],
|
||||
});
|
||||
expect(service.getState()).toEqual(state);
|
||||
});
|
||||
|
||||
test('should throw error for invalid model index', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
test("should throw error for invalid model index", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
await expect(service.switchModel(5)).rejects.toThrow('Invalid model index: 5. Available models: 0-1');
|
||||
await expect(service.switchModel(-1)).rejects.toThrow('Invalid model index: -1. Available models: 0-1');
|
||||
await expect(service.switchModel(5)).rejects.toThrow(
|
||||
"Invalid model index: 5. Available models: 0-1",
|
||||
);
|
||||
await expect(service.switchModel(-1)).rejects.toThrow(
|
||||
"Invalid model index: -1. Available models: 0-1",
|
||||
);
|
||||
});
|
||||
|
||||
test('should throw error when service not initialized', async () => {
|
||||
await expect(service.switchModel(0)).rejects.toThrow('ModelService not initialized');
|
||||
test("should throw error when service not initialized", async () => {
|
||||
await expect(service.switchModel(0)).rejects.toThrow(
|
||||
"ModelService not initialized",
|
||||
);
|
||||
});
|
||||
|
||||
test('should handle continue-proxy provider specially', async () => {
|
||||
test("should handle continue-proxy provider specially", async () => {
|
||||
const proxyModel = {
|
||||
provider: 'continue-proxy',
|
||||
name: 'Proxy Model',
|
||||
apiBase: 'https://proxy.continue.dev',
|
||||
apiKeyLocation: 'env.PROXY_KEY',
|
||||
roles: ['chat'],
|
||||
provider: "continue-proxy",
|
||||
name: "Proxy Model",
|
||||
apiBase: "https://proxy.continue.dev",
|
||||
apiKeyLocation: "env.PROXY_KEY",
|
||||
roles: ["chat"],
|
||||
} as ModelConfig;
|
||||
|
||||
mockAssistant.models = [proxyModel];
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, proxyModel]);
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
proxyModel,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
vi.mocked(workos.getAccessToken).mockReturnValue('proxy-token');
|
||||
vi.mocked(workos.getOrganizationId).mockReturnValue('org-123');
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
vi.mocked(workos.getAccessToken).mockReturnValue("proxy-token");
|
||||
vi.mocked(workos.getOrganizationId).mockReturnValue("org-123");
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
|
||||
mockLlmApi as any,
|
||||
);
|
||||
|
||||
await service.switchModel(0);
|
||||
|
||||
expect(vi.mocked(openaiAdapters.constructLlmApi)).toHaveBeenCalledWith({
|
||||
provider: 'continue-proxy',
|
||||
apiBase: 'https://proxy.continue.dev',
|
||||
apiKey: 'proxy-token',
|
||||
provider: "continue-proxy",
|
||||
apiBase: "https://proxy.continue.dev",
|
||||
apiKey: "proxy-token",
|
||||
env: {
|
||||
apiKeyLocation: 'env.PROXY_KEY',
|
||||
orgScopeId: 'org-123',
|
||||
apiKeyLocation: "env.PROXY_KEY",
|
||||
orgScopeId: "org-123",
|
||||
proxyUrl: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableChatModels()', () => {
|
||||
test('should return only models with chat role', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
describe("getAvailableChatModels()", () => {
|
||||
test("should return only models with chat role", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const models = service.getAvailableChatModels();
|
||||
|
||||
expect(models).toHaveLength(2);
|
||||
expect(models[0]).toEqual({
|
||||
provider: 'openai',
|
||||
name: 'GPT-4',
|
||||
provider: "openai",
|
||||
name: "GPT-4",
|
||||
index: 0,
|
||||
});
|
||||
expect(models[1]).toEqual({
|
||||
provider: 'anthropic',
|
||||
name: 'Claude 3',
|
||||
provider: "anthropic",
|
||||
name: "Claude 3",
|
||||
index: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test('should include models with undefined roles', async () => {
|
||||
test("should include models with undefined roles", async () => {
|
||||
// Add a model with undefined roles to the assistant
|
||||
const assistantWithUndefinedRoles = {
|
||||
...mockAssistant,
|
||||
models: [
|
||||
...mockAssistant.models!,
|
||||
{
|
||||
provider: 'local',
|
||||
model: 'llama-2',
|
||||
name: 'Llama 2',
|
||||
apiKey: 'test-key',
|
||||
provider: "local",
|
||||
model: "llama-2",
|
||||
name: "Llama 2",
|
||||
apiKey: "test-key",
|
||||
// roles is undefined
|
||||
} as ModelConfig,
|
||||
],
|
||||
};
|
||||
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, assistantWithUndefinedRoles.models![0] as ModelConfig]);
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
assistantWithUndefinedRoles.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(assistantWithUndefinedRoles, mockAuthConfig);
|
||||
|
||||
const models = service.getAvailableChatModels();
|
||||
|
|
@ -230,126 +269,156 @@ describe('ModelService', () => {
|
|||
// Should include the two chat models and the model with undefined roles
|
||||
expect(models).toHaveLength(3);
|
||||
expect(models[2]).toEqual({
|
||||
provider: 'local',
|
||||
name: 'Llama 2',
|
||||
provider: "local",
|
||||
name: "Llama 2",
|
||||
index: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentModelIndex()', () => {
|
||||
test('should return correct index of current model', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
describe("getCurrentModelIndex()", () => {
|
||||
test("should return correct index of current model", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.getCurrentModelIndex()).toBe(0);
|
||||
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(mockLlmApi as any);
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
|
||||
mockLlmApi as any,
|
||||
);
|
||||
await service.switchModel(1);
|
||||
expect(service.getCurrentModelIndex()).toBe(1);
|
||||
});
|
||||
|
||||
test('should return -1 when no model is set', () => {
|
||||
test("should return -1 when no model is set", () => {
|
||||
expect(service.getCurrentModelIndex()).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getModelIndexByName()', () => {
|
||||
test('should find model by name', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
describe("getModelIndexByName()", () => {
|
||||
test("should find model by name", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.getModelIndexByName('GPT-4')).toBe(0);
|
||||
expect(service.getModelIndexByName('Claude 3')).toBe(1);
|
||||
expect(service.getModelIndexByName('Non-existent')).toBe(-1);
|
||||
expect(service.getModelIndexByName("GPT-4")).toBe(0);
|
||||
expect(service.getModelIndexByName("Claude 3")).toBe(1);
|
||||
expect(service.getModelIndexByName("Non-existent")).toBe(-1);
|
||||
});
|
||||
|
||||
test('should find model by name and provider', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
test("should find model by name and provider", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.getModelIndexByName('GPT-4', 'openai')).toBe(0);
|
||||
expect(service.getModelIndexByName('GPT-4', 'anthropic')).toBe(-1);
|
||||
expect(service.getModelIndexByName("GPT-4", "openai")).toBe(0);
|
||||
expect(service.getModelIndexByName("GPT-4", "anthropic")).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getModelInfo()', () => {
|
||||
test('should return current model info', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
describe("getModelInfo()", () => {
|
||||
test("should return current model info", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.getModelInfo()).toEqual({
|
||||
provider: 'openai',
|
||||
name: 'GPT-4'
|
||||
provider: "openai",
|
||||
name: "GPT-4",
|
||||
});
|
||||
});
|
||||
|
||||
test('should return null when no model set', () => {
|
||||
test("should return null when no model set", () => {
|
||||
expect(service.getModelInfo()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReady()', () => {
|
||||
test('should return false when not initialized', () => {
|
||||
describe("isReady()", () => {
|
||||
test("should return false when not initialized", () => {
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
|
||||
test('should return true when initialized with model and llmApi', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
test("should return true when initialized with model and llmApi", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false if llmApi is null', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([null as any, mockAssistant.models![0] as ModelConfig]);
|
||||
test("should return false if llmApi is null", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
null as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
expect(service.isReady()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDependencies()', () => {
|
||||
test('should declare auth and config dependencies', () => {
|
||||
expect(service.getDependencies()).toEqual(['auth', 'config']);
|
||||
describe("getDependencies()", () => {
|
||||
test("should declare auth and config dependencies", () => {
|
||||
expect(service.getDependencies()).toEqual(["auth", "config"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged on model switch', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
describe("Event Emission", () => {
|
||||
test("should emit stateChanged on model switch", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
service.on("stateChanged", listener);
|
||||
|
||||
const newLlmApi = { complete: vi.fn(), stream: vi.fn() };
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(newLlmApi as any);
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(
|
||||
newLlmApi as any,
|
||||
);
|
||||
await service.switchModel(1);
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
model: mockAssistant.models![1],
|
||||
llmApi: newLlmApi
|
||||
llmApi: newLlmApi,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
model: mockAssistant.models![0],
|
||||
llmApi: mockLlmApi
|
||||
})
|
||||
llmApi: mockLlmApi,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit error on switch failure', async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([mockLlmApi as any, mockAssistant.models![0] as ModelConfig]);
|
||||
test("should emit error on switch failure", async () => {
|
||||
vi.mocked(config.getLlmApi).mockReturnValue([
|
||||
mockLlmApi as any,
|
||||
mockAssistant.models![0] as ModelConfig,
|
||||
]);
|
||||
await service.initialize(mockAssistant, mockAuthConfig);
|
||||
|
||||
const errorListener = vi.fn();
|
||||
service.on('error', errorListener);
|
||||
service.on("error", errorListener);
|
||||
|
||||
vi.mocked(openaiAdapters.constructLlmApi).mockReturnValue(null as any);
|
||||
|
||||
await expect(service.switchModel(1)).rejects.toThrow('Failed to initialize LLM');
|
||||
await expect(service.switchModel(1)).rejects.toThrow(
|
||||
"Failed to initialize LLM",
|
||||
);
|
||||
expect(errorListener).toHaveBeenCalledWith(expect.any(Error));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
import { describe, expect, test, beforeEach, vi } from "vitest";
|
||||
|
||||
import { ServiceContainer } from './ServiceContainer.js';
|
||||
import { ServiceContainer } from "./ServiceContainer.js";
|
||||
|
||||
describe('ServiceContainer', () => {
|
||||
describe("ServiceContainer", () => {
|
||||
let container: ServiceContainer;
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -10,13 +10,13 @@ describe('ServiceContainer', () => {
|
|||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Dependency Cascade Reloading', () => {
|
||||
test('should automatically reload all transitive dependents', async () => {
|
||||
describe("Dependency Cascade Reloading", () => {
|
||||
test("should automatically reload all transitive dependents", async () => {
|
||||
// Setup service dependency chain: auth -> apiClient -> config -> model
|
||||
const authValue = { auth: 'auth-value' };
|
||||
const apiClientValue = { apiClient: 'api-client-value' };
|
||||
const configValue = { config: 'config-value' };
|
||||
const modelValue = { model: 'model-value' };
|
||||
const authValue = { auth: "auth-value" };
|
||||
const apiClientValue = { apiClient: "api-client-value" };
|
||||
const configValue = { config: "config-value" };
|
||||
const modelValue = { model: "model-value" };
|
||||
|
||||
let authReloadCount = 0;
|
||||
let apiClientReloadCount = 0;
|
||||
|
|
@ -25,43 +25,43 @@ describe('ServiceContainer', () => {
|
|||
|
||||
// Register services with mock factories that track reload count
|
||||
container.register(
|
||||
'auth',
|
||||
"auth",
|
||||
async () => {
|
||||
authReloadCount++;
|
||||
return authValue;
|
||||
},
|
||||
[]
|
||||
[],
|
||||
);
|
||||
|
||||
container.register(
|
||||
'apiClient',
|
||||
"apiClient",
|
||||
async () => {
|
||||
apiClientReloadCount++;
|
||||
return apiClientValue;
|
||||
},
|
||||
['auth']
|
||||
["auth"],
|
||||
);
|
||||
|
||||
container.register(
|
||||
'config',
|
||||
"config",
|
||||
async () => {
|
||||
configReloadCount++;
|
||||
return configValue;
|
||||
},
|
||||
['auth', 'apiClient']
|
||||
["auth", "apiClient"],
|
||||
);
|
||||
|
||||
container.register(
|
||||
'model',
|
||||
"model",
|
||||
async () => {
|
||||
modelReloadCount++;
|
||||
return modelValue;
|
||||
},
|
||||
['config']
|
||||
["config"],
|
||||
);
|
||||
|
||||
// Initial load of all services
|
||||
await container.get('model');
|
||||
await container.get("model");
|
||||
|
||||
// Verify initial load counts
|
||||
expect(authReloadCount).toBe(1);
|
||||
|
|
@ -70,95 +70,111 @@ describe('ServiceContainer', () => {
|
|||
expect(modelReloadCount).toBe(1);
|
||||
|
||||
// Reload auth service - should cascade to all dependents
|
||||
await container.reload('auth');
|
||||
await container.reload("auth");
|
||||
|
||||
// Verify cascade reload occurred - all dependent services should reload
|
||||
expect(authReloadCount).toBe(2); // auth reloaded
|
||||
expect(apiClientReloadCount).toBe(2); // apiClient depends on auth
|
||||
expect(configReloadCount).toBe(2); // config depends on auth and apiClient
|
||||
expect(configReloadCount).toBe(2); // config depends on auth and apiClient
|
||||
expect(modelReloadCount).toBe(2); // model depends on config
|
||||
});
|
||||
|
||||
test('should find all transitive dependents correctly', async () => {
|
||||
test("should find all transitive dependents correctly", async () => {
|
||||
// Setup complex dependency graph
|
||||
container.register('serviceA', async () => ({}), []);
|
||||
container.register('serviceB', async () => ({}), ['serviceA']);
|
||||
container.register('serviceC', async () => ({}), ['serviceA']);
|
||||
container.register('serviceD', async () => ({}), ['serviceB', 'serviceC']);
|
||||
container.register('serviceE', async () => ({}), ['serviceD']);
|
||||
container.register("serviceA", async () => ({}), []);
|
||||
container.register("serviceB", async () => ({}), ["serviceA"]);
|
||||
container.register("serviceC", async () => ({}), ["serviceA"]);
|
||||
container.register("serviceD", async () => ({}), [
|
||||
"serviceB",
|
||||
"serviceC",
|
||||
]);
|
||||
container.register("serviceE", async () => ({}), ["serviceD"]);
|
||||
|
||||
// Use reflection to access private method for testing
|
||||
const findAllDependents = (container as any).findAllDependents.bind(container);
|
||||
|
||||
const dependentsOfA = findAllDependents('serviceA');
|
||||
|
||||
const findAllDependents = (container as any).findAllDependents.bind(
|
||||
container,
|
||||
);
|
||||
|
||||
const dependentsOfA = findAllDependents("serviceA");
|
||||
|
||||
// serviceA should have all others as transitive dependents
|
||||
expect(dependentsOfA.sort()).toEqual(['serviceB', 'serviceC', 'serviceD', 'serviceE']);
|
||||
expect(dependentsOfA.sort()).toEqual([
|
||||
"serviceB",
|
||||
"serviceC",
|
||||
"serviceD",
|
||||
"serviceE",
|
||||
]);
|
||||
});
|
||||
|
||||
test('should handle circular dependencies gracefully', async () => {
|
||||
test("should handle circular dependencies gracefully", async () => {
|
||||
// This test ensures the findAllDependents doesn't get stuck in infinite loops
|
||||
|
||||
|
||||
// Setup a circular dependency (which shouldn't happen in practice but we handle it)
|
||||
container.register('serviceX', async () => ({}), ['serviceY']);
|
||||
container.register('serviceY', async () => ({}), ['serviceX']);
|
||||
|
||||
container.register("serviceX", async () => ({}), ["serviceY"]);
|
||||
container.register("serviceY", async () => ({}), ["serviceX"]);
|
||||
|
||||
// Use reflection to access private method for testing
|
||||
const findAllDependents = (container as any).findAllDependents.bind(container);
|
||||
|
||||
const findAllDependents = (container as any).findAllDependents.bind(
|
||||
container,
|
||||
);
|
||||
|
||||
// Should not hang and should return both services as circular dependents
|
||||
const dependentsOfX = findAllDependents('serviceX');
|
||||
const dependentsOfY = findAllDependents('serviceY');
|
||||
|
||||
const dependentsOfX = findAllDependents("serviceX");
|
||||
const dependentsOfY = findAllDependents("serviceY");
|
||||
|
||||
// Both should contain each other due to circular dependency
|
||||
expect(dependentsOfX).toContain('serviceY');
|
||||
expect(dependentsOfY).toContain('serviceX');
|
||||
expect(dependentsOfX).toContain("serviceY");
|
||||
expect(dependentsOfY).toContain("serviceX");
|
||||
});
|
||||
|
||||
test('should emit events during cascade reload', async () => {
|
||||
test("should emit events during cascade reload", async () => {
|
||||
const events: string[] = [];
|
||||
|
||||
container.register('parent', async () => ({ parent: true }), []);
|
||||
container.register('child', async () => ({ child: true }), ['parent']);
|
||||
|
||||
container.register("parent", async () => ({ parent: true }), []);
|
||||
container.register("child", async () => ({ child: true }), ["parent"]);
|
||||
|
||||
// Listen for events
|
||||
container.on('parent:loading', () => events.push('parent:loading'));
|
||||
container.on('parent:ready', () => events.push('parent:ready'));
|
||||
container.on('child:loading', () => events.push('child:loading'));
|
||||
container.on('child:ready', () => events.push('child:ready'));
|
||||
container.on("parent:loading", () => events.push("parent:loading"));
|
||||
container.on("parent:ready", () => events.push("parent:ready"));
|
||||
container.on("child:loading", () => events.push("child:loading"));
|
||||
container.on("child:ready", () => events.push("child:ready"));
|
||||
|
||||
// Initial load
|
||||
await container.get('child');
|
||||
await container.get("child");
|
||||
events.length = 0; // Clear events
|
||||
|
||||
// Reload parent - should cascade to child
|
||||
await container.reload('parent');
|
||||
await container.reload("parent");
|
||||
|
||||
// Verify both services went through loading cycle
|
||||
expect(events).toContain('parent:loading');
|
||||
expect(events).toContain('parent:ready');
|
||||
expect(events).toContain('child:loading');
|
||||
expect(events).toContain('child:ready');
|
||||
expect(events).toContain("parent:loading");
|
||||
expect(events).toContain("parent:ready");
|
||||
expect(events).toContain("child:loading");
|
||||
expect(events).toContain("child:ready");
|
||||
});
|
||||
|
||||
test('should preserve service state when no dependents exist', async () => {
|
||||
test("should preserve service state when no dependents exist", async () => {
|
||||
let reloadCount = 0;
|
||||
|
||||
container.register('standalone', async () => {
|
||||
reloadCount++;
|
||||
return { standalone: true };
|
||||
}, []);
|
||||
|
||||
container.register(
|
||||
"standalone",
|
||||
async () => {
|
||||
reloadCount++;
|
||||
return { standalone: true };
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Load initially
|
||||
await container.get('standalone');
|
||||
await container.get("standalone");
|
||||
expect(reloadCount).toBe(1);
|
||||
|
||||
// Reload - only this service should reload
|
||||
await container.reload('standalone');
|
||||
await container.reload("standalone");
|
||||
expect(reloadCount).toBe(2);
|
||||
|
||||
// Should still be ready
|
||||
expect(container.isReady('standalone')).toBe(true);
|
||||
expect(container.isReady("standalone")).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -40,9 +40,7 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
} else {
|
||||
// Normal mode behavior depends on user config
|
||||
console.log(
|
||||
`Normal mode - Write policy: ${
|
||||
writePolicy?.permission || "none"
|
||||
}`
|
||||
`Normal mode - Write policy: ${writePolicy?.permission || "none"}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
|
@ -52,17 +50,17 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
|
||||
// Find all policies that could affect Write tool
|
||||
const writeRelevantPolicies = policies.filter(
|
||||
(p) => p.tool === "Write" || p.tool === "*"
|
||||
(p) => p.tool === "Write" || p.tool === "*",
|
||||
);
|
||||
|
||||
console.log(
|
||||
`\n=== WRITE-RELEVANT POLICIES IN ${mode.toUpperCase()} MODE ===`
|
||||
`\n=== WRITE-RELEVANT POLICIES IN ${mode.toUpperCase()} MODE ===`,
|
||||
);
|
||||
writeRelevantPolicies.forEach((policy, index) => {
|
||||
console.log(
|
||||
`${index + 1}. tool: "${policy.tool}", permission: "${
|
||||
policy.permission
|
||||
}"`
|
||||
}"`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -94,7 +92,7 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
console.log(
|
||||
`${index + 1}. tool: "${policy.tool}", permission: "${
|
||||
policy.permission
|
||||
}"`
|
||||
}"`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -107,7 +105,7 @@ describe("ToolPermissionService - Debug Tool Permissions", () => {
|
|||
console.log(
|
||||
`${index + 1}. tool: "${policy.tool}", permission: "${
|
||||
policy.permission
|
||||
}"`
|
||||
}"`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -14,30 +14,40 @@ describe("ToolPermissionService E2E", () => {
|
|||
const overrides = {
|
||||
allow: ["dangerous_tool"],
|
||||
ask: ["sensitive_tool"],
|
||||
exclude: ["forbidden_tool", "write_*"]
|
||||
exclude: ["forbidden_tool", "write_*"],
|
||||
};
|
||||
|
||||
const state = await service.initialize(overrides);
|
||||
|
||||
// Verify the compiled policies
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
|
||||
// Find the runtime override policies (they should be at the beginning)
|
||||
const excludePolicy1 = policies.find(p => p.tool === "forbidden_tool" && p.permission === "exclude");
|
||||
const excludePolicy2 = policies.find(p => p.tool === "write_*" && p.permission === "exclude");
|
||||
const askPolicy = policies.find(p => p.tool === "sensitive_tool" && p.permission === "ask");
|
||||
const allowPolicy = policies.find(p => p.tool === "dangerous_tool" && p.permission === "allow");
|
||||
|
||||
const excludePolicy1 = policies.find(
|
||||
(p) => p.tool === "forbidden_tool" && p.permission === "exclude",
|
||||
);
|
||||
const excludePolicy2 = policies.find(
|
||||
(p) => p.tool === "write_*" && p.permission === "exclude",
|
||||
);
|
||||
const askPolicy = policies.find(
|
||||
(p) => p.tool === "sensitive_tool" && p.permission === "ask",
|
||||
);
|
||||
const allowPolicy = policies.find(
|
||||
(p) => p.tool === "dangerous_tool" && p.permission === "allow",
|
||||
);
|
||||
|
||||
// Verify runtime overrides are present
|
||||
expect(excludePolicy1).toBeDefined();
|
||||
expect(excludePolicy2).toBeDefined();
|
||||
expect(askPolicy).toBeDefined();
|
||||
expect(allowPolicy).toBeDefined();
|
||||
|
||||
|
||||
// Verify all default policies are present
|
||||
for (const defaultPolicy of DEFAULT_TOOL_POLICIES) {
|
||||
const foundPolicy = policies.find(p =>
|
||||
p.tool === defaultPolicy.tool && p.permission === defaultPolicy.permission
|
||||
const foundPolicy = policies.find(
|
||||
(p) =>
|
||||
p.tool === defaultPolicy.tool &&
|
||||
p.permission === defaultPolicy.permission,
|
||||
);
|
||||
expect(foundPolicy).toBeDefined();
|
||||
}
|
||||
|
|
@ -46,24 +56,26 @@ describe("ToolPermissionService E2E", () => {
|
|||
it("should allow dynamic updates after initialization", async () => {
|
||||
// Start with defaults (may include additional policies from permissions.yaml)
|
||||
await service.initialize();
|
||||
|
||||
|
||||
let permissions = service.getPermissions();
|
||||
|
||||
|
||||
// Verify all default policies are present (may have additional ones)
|
||||
for (const defaultPolicy of DEFAULT_TOOL_POLICIES) {
|
||||
const foundPolicy = permissions.policies.find(p =>
|
||||
p.tool === defaultPolicy.tool && p.permission === defaultPolicy.permission
|
||||
const foundPolicy = permissions.policies.find(
|
||||
(p) =>
|
||||
p.tool === defaultPolicy.tool &&
|
||||
p.permission === defaultPolicy.permission,
|
||||
);
|
||||
expect(foundPolicy).toBeDefined();
|
||||
}
|
||||
|
||||
// Update with new policies (this replaces ALL policies)
|
||||
const newPolicies = [
|
||||
{ tool: "*", permission: "ask" as const } // Ask for everything
|
||||
{ tool: "*", permission: "ask" as const }, // Ask for everything
|
||||
];
|
||||
|
||||
|
||||
service.updatePermissions(newPolicies);
|
||||
|
||||
|
||||
permissions = service.getPermissions();
|
||||
expect(permissions.policies).toEqual(newPolicies);
|
||||
expect(permissions.policies.length).toBe(1);
|
||||
|
|
@ -71,19 +83,22 @@ describe("ToolPermissionService E2E", () => {
|
|||
|
||||
it("should maintain state consistency", async () => {
|
||||
const overrides = {
|
||||
exclude: ["test_tool"]
|
||||
exclude: ["test_tool"],
|
||||
};
|
||||
|
||||
await service.initialize(overrides);
|
||||
|
||||
|
||||
// Both getState and getPermissions should return same data
|
||||
const state = service.getState();
|
||||
const permissions = service.getPermissions();
|
||||
|
||||
|
||||
// getState() returns a shallow copy, so nested objects are the same reference
|
||||
expect(state.permissions).toEqual(permissions);
|
||||
expect(state.permissions).toBe(permissions); // Same reference for nested objects
|
||||
expect(state.permissions.policies[0]).toEqual({ tool: "test_tool", permission: "exclude" });
|
||||
expect(state.permissions.policies[0]).toEqual({
|
||||
tool: "test_tool",
|
||||
permission: "exclude",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle concurrent access correctly", async () => {
|
||||
|
|
@ -91,16 +106,16 @@ describe("ToolPermissionService E2E", () => {
|
|||
await service.initialize({ allow: ["tool1"] });
|
||||
|
||||
// Simulate concurrent reads
|
||||
const promises = Array(10).fill(null).map(() =>
|
||||
Promise.resolve(service.getPermissions())
|
||||
);
|
||||
const promises = Array(10)
|
||||
.fill(null)
|
||||
.map(() => Promise.resolve(service.getPermissions()));
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
|
||||
// All should return the same value
|
||||
const firstResult = results[0];
|
||||
results.forEach(result => {
|
||||
results.forEach((result) => {
|
||||
expect(result).toStrictEqual(firstResult);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,261 +1,316 @@
|
|||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ToolPermissionService } from './ToolPermissionService.js';
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
describe('ToolPermissionService - Mode Functionality', () => {
|
||||
describe("ToolPermissionService - Mode Functionality", () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
describe('mode initialization', () => {
|
||||
it('should initialize with normal mode by default', () => {
|
||||
describe("mode initialization", () => {
|
||||
it("should initialize with normal mode by default", () => {
|
||||
const state = service.initializeSync();
|
||||
expect(state.currentMode).toBe('normal');
|
||||
expect(state.currentMode).toBe("normal");
|
||||
});
|
||||
|
||||
it('should initialize with specified mode', () => {
|
||||
const state = service.initializeSync({ mode: 'plan' });
|
||||
expect(state.currentMode).toBe('plan');
|
||||
it("should initialize with specified mode", () => {
|
||||
const state = service.initializeSync({ mode: "plan" });
|
||||
expect(state.currentMode).toBe("plan");
|
||||
});
|
||||
|
||||
it('should generate correct policies for plan mode', () => {
|
||||
const state = service.initializeSync({ mode: 'plan' });
|
||||
it("should generate correct policies for plan mode", () => {
|
||||
const state = service.initializeSync({ mode: "plan" });
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
|
||||
// Should have specific policies for write tools (excluded)
|
||||
expect(policies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
|
||||
expect(policies.some(p => p.tool === 'Edit' && p.permission === 'exclude')).toBe(true);
|
||||
expect(policies.some(p => p.tool === 'Bash' && p.permission === 'allow')).toBe(true);
|
||||
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Write" && p.permission === "exclude"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Edit" && p.permission === "exclude"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Bash" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
|
||||
// Should have specific policies for read tools (allowed)
|
||||
expect(policies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true);
|
||||
expect(policies.some(p => p.tool === 'Grep' && p.permission === 'allow')).toBe(true);
|
||||
expect(policies.some(p => p.tool === 'LS' && p.permission === 'allow')).toBe(true);
|
||||
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Read" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Grep" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "LS" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
|
||||
// Should allow MCP tools
|
||||
expect(policies.some(p => p.tool === 'mcp:*' && p.permission === 'allow')).toBe(true);
|
||||
|
||||
expect(
|
||||
policies.some((p) => p.tool === "mcp:*" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
|
||||
// Should have an exclusion policy for all other tools as fallback
|
||||
expect(policies.some(p => p.tool === '*' && p.permission === 'exclude')).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "*" && p.permission === "exclude"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
it('should generate correct policies for auto mode', () => {
|
||||
const state = service.initializeSync({ mode: 'auto' });
|
||||
it("should generate correct policies for auto mode", () => {
|
||||
const state = service.initializeSync({ mode: "auto" });
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
|
||||
// First policy should be the mode policy (allow all)
|
||||
expect(policies[0]).toEqual({
|
||||
tool: '*',
|
||||
permission: 'allow'
|
||||
tool: "*",
|
||||
permission: "allow",
|
||||
});
|
||||
});
|
||||
|
||||
it('should have mode-specific policy positioning', () => {
|
||||
const normalState = service.initializeSync({ mode: 'normal' });
|
||||
const planState = service.initializeSync({ mode: 'plan' });
|
||||
|
||||
it("should have mode-specific policy positioning", () => {
|
||||
const normalState = service.initializeSync({ mode: "normal" });
|
||||
const planState = service.initializeSync({ mode: "plan" });
|
||||
|
||||
// Normal mode may have default policies but no mode-specific wildcard at the start
|
||||
const normalFirstPolicy = normalState.permissions.policies[0];
|
||||
expect(normalFirstPolicy?.tool !== '*' || normalFirstPolicy?.permission !== 'exclude').toBe(true);
|
||||
|
||||
expect(
|
||||
normalFirstPolicy?.tool !== "*" ||
|
||||
normalFirstPolicy?.permission !== "exclude",
|
||||
).toBe(true);
|
||||
|
||||
// Plan mode should have write exclusions and read allowances
|
||||
const planPolicies = planState.permissions.policies;
|
||||
expect(planPolicies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
|
||||
expect(planPolicies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true);
|
||||
expect(
|
||||
planPolicies.some(
|
||||
(p) => p.tool === "Write" && p.permission === "exclude",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
planPolicies.some((p) => p.tool === "Read" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mode switching', () => {
|
||||
describe("mode switching", () => {
|
||||
beforeEach(() => {
|
||||
service.initializeSync();
|
||||
});
|
||||
|
||||
it('should switch from normal to plan mode', () => {
|
||||
expect(service.getCurrentMode()).toBe('normal');
|
||||
|
||||
const newState = service.switchMode('plan');
|
||||
|
||||
expect(newState.currentMode).toBe('plan');
|
||||
expect(service.getCurrentMode()).toBe('plan');
|
||||
it("should switch from normal to plan mode", () => {
|
||||
expect(service.getCurrentMode()).toBe("normal");
|
||||
|
||||
const newState = service.switchMode("plan");
|
||||
|
||||
expect(newState.currentMode).toBe("plan");
|
||||
expect(service.getCurrentMode()).toBe("plan");
|
||||
});
|
||||
|
||||
it('should update policies when switching modes', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
it("should update policies when switching modes", () => {
|
||||
service.initializeSync({ mode: "normal" });
|
||||
const normalPolicies = service.getPermissions().policies;
|
||||
|
||||
service.switchMode('plan');
|
||||
|
||||
service.switchMode("plan");
|
||||
const planPolicies = service.getPermissions().policies;
|
||||
|
||||
|
||||
expect(planPolicies).not.toEqual(normalPolicies);
|
||||
expect(planPolicies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
|
||||
expect(
|
||||
planPolicies.some(
|
||||
(p) => p.tool === "Write" && p.permission === "exclude",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should use absolute override for plan mode (ignore non-mode policies)', () => {
|
||||
it("should use absolute override for plan mode (ignore non-mode policies)", () => {
|
||||
// Initialize with some existing policies
|
||||
service.initializeSync({
|
||||
allow: ['allowedTool'],
|
||||
exclude: ['excludedTool']
|
||||
allow: ["allowedTool"],
|
||||
exclude: ["excludedTool"],
|
||||
});
|
||||
|
||||
|
||||
const initialPolicies = service.getPermissions().policies;
|
||||
const nonModePolicyCount = initialPolicies.length;
|
||||
|
||||
service.switchMode('plan');
|
||||
|
||||
service.switchMode("plan");
|
||||
const newPolicies = service.getPermissions().policies;
|
||||
|
||||
|
||||
// Plan mode should use ONLY mode policies (absolute override)
|
||||
// Should contain Write exclude policy for plan mode
|
||||
const writePolicy = newPolicies.find(p => p.tool === 'Write');
|
||||
expect(writePolicy?.permission).toBe('exclude');
|
||||
|
||||
const writePolicy = newPolicies.find((p) => p.tool === "Write");
|
||||
expect(writePolicy?.permission).toBe("exclude");
|
||||
|
||||
// Should not contain any user-defined policies from the initial setup
|
||||
const userAllowPolicy = newPolicies.find(p => p.tool === 'allowedTool');
|
||||
const userExcludePolicy = newPolicies.find(p => p.tool === 'excludedTool');
|
||||
const userAllowPolicy = newPolicies.find((p) => p.tool === "allowedTool");
|
||||
const userExcludePolicy = newPolicies.find(
|
||||
(p) => p.tool === "excludedTool",
|
||||
);
|
||||
expect(userAllowPolicy).toBeUndefined();
|
||||
expect(userExcludePolicy).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle switching between different modes', () => {
|
||||
service.switchMode('plan');
|
||||
expect(service.getCurrentMode()).toBe('plan');
|
||||
|
||||
service.switchMode('auto');
|
||||
expect(service.getCurrentMode()).toBe('auto');
|
||||
|
||||
service.switchMode('normal');
|
||||
expect(service.getCurrentMode()).toBe('normal');
|
||||
it("should handle switching between different modes", () => {
|
||||
service.switchMode("plan");
|
||||
expect(service.getCurrentMode()).toBe("plan");
|
||||
|
||||
service.switchMode("auto");
|
||||
expect(service.getCurrentMode()).toBe("auto");
|
||||
|
||||
service.switchMode("normal");
|
||||
expect(service.getCurrentMode()).toBe("normal");
|
||||
});
|
||||
|
||||
it('should preserve original user policies when switching modes', () => {
|
||||
it("should preserve original user policies when switching modes", () => {
|
||||
// Initialize with user-defined policies
|
||||
service.initializeSync({
|
||||
allow: ['customAllowedTool'],
|
||||
exclude: ['customExcludedTool'],
|
||||
ask: ['customAskTool']
|
||||
allow: ["customAllowedTool"],
|
||||
exclude: ["customExcludedTool"],
|
||||
ask: ["customAskTool"],
|
||||
});
|
||||
|
||||
|
||||
const originalPolicies = service.getPermissions().policies;
|
||||
const userPolicyCount = originalPolicies.filter(p =>
|
||||
p.tool === 'customAllowedTool' ||
|
||||
p.tool === 'customExcludedTool' ||
|
||||
p.tool === 'customAskTool'
|
||||
const userPolicyCount = originalPolicies.filter(
|
||||
(p) =>
|
||||
p.tool === "customAllowedTool" ||
|
||||
p.tool === "customExcludedTool" ||
|
||||
p.tool === "customAskTool",
|
||||
).length;
|
||||
expect(userPolicyCount).toBe(3);
|
||||
|
||||
|
||||
// Switch to plan mode (should store original policies)
|
||||
service.switchMode('plan');
|
||||
service.switchMode("plan");
|
||||
const planPolicies = service.getPermissions().policies;
|
||||
|
||||
|
||||
// Plan mode should not have user policies
|
||||
const planUserPolicyCount = planPolicies.filter(p =>
|
||||
p.tool === 'customAllowedTool' ||
|
||||
p.tool === 'customExcludedTool' ||
|
||||
p.tool === 'customAskTool'
|
||||
const planUserPolicyCount = planPolicies.filter(
|
||||
(p) =>
|
||||
p.tool === "customAllowedTool" ||
|
||||
p.tool === "customExcludedTool" ||
|
||||
p.tool === "customAskTool",
|
||||
).length;
|
||||
expect(planUserPolicyCount).toBe(0);
|
||||
|
||||
|
||||
// Switch back to normal mode (should restore original policies)
|
||||
service.switchMode('normal');
|
||||
service.switchMode("normal");
|
||||
const restoredPolicies = service.getPermissions().policies;
|
||||
|
||||
|
||||
// Should have user policies restored
|
||||
const restoredUserPolicyCount = restoredPolicies.filter(p =>
|
||||
p.tool === 'customAllowedTool' ||
|
||||
p.tool === 'customExcludedTool' ||
|
||||
p.tool === 'customAskTool'
|
||||
const restoredUserPolicyCount = restoredPolicies.filter(
|
||||
(p) =>
|
||||
p.tool === "customAllowedTool" ||
|
||||
p.tool === "customExcludedTool" ||
|
||||
p.tool === "customAskTool",
|
||||
).length;
|
||||
expect(restoredUserPolicyCount).toBe(3);
|
||||
|
||||
|
||||
// Verify specific policies are restored correctly
|
||||
expect(restoredPolicies.some(p => p.tool === 'customAllowedTool' && p.permission === 'allow')).toBe(true);
|
||||
expect(restoredPolicies.some(p => p.tool === 'customExcludedTool' && p.permission === 'exclude')).toBe(true);
|
||||
expect(restoredPolicies.some(p => p.tool === 'customAskTool' && p.permission === 'ask')).toBe(true);
|
||||
expect(
|
||||
restoredPolicies.some(
|
||||
(p) => p.tool === "customAllowedTool" && p.permission === "allow",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
restoredPolicies.some(
|
||||
(p) => p.tool === "customExcludedTool" && p.permission === "exclude",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
restoredPolicies.some(
|
||||
(p) => p.tool === "customAskTool" && p.permission === "ask",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should override user permissions in plan mode', () => {
|
||||
it("should override user permissions in plan mode", () => {
|
||||
// Initialize with user config that allows write tools
|
||||
service.initializeSync({
|
||||
allow: ['Write', 'Edit', 'Bash'],
|
||||
mode: 'plan'
|
||||
allow: ["Write", "Edit", "Bash"],
|
||||
mode: "plan",
|
||||
});
|
||||
|
||||
|
||||
const policies = service.getPermissions().policies;
|
||||
|
||||
|
||||
// Mode policies should override user config - Write should be excluded despite being in allow list
|
||||
expect(policies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true);
|
||||
expect(policies.some(p => p.tool === 'Edit' && p.permission === 'exclude')).toBe(true);
|
||||
expect(policies.some(p => p.tool === 'Bash' && p.permission === 'allow')).toBe(true);
|
||||
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Write" && p.permission === "exclude"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Edit" && p.permission === "exclude"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Bash" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
|
||||
// Read tools should be allowed
|
||||
expect(policies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "Read" && p.permission === "allow"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should override user permissions in auto mode', () => {
|
||||
it("should override user permissions in auto mode", () => {
|
||||
// Initialize with user config that excludes tools
|
||||
service.initializeSync({
|
||||
exclude: ['Write', 'Edit', 'Bash'],
|
||||
mode: 'auto'
|
||||
exclude: ["Write", "Edit", "Bash"],
|
||||
mode: "auto",
|
||||
});
|
||||
|
||||
|
||||
const policies = service.getPermissions().policies;
|
||||
|
||||
|
||||
// Mode policies should override user config - everything should be allowed
|
||||
expect(policies[0]).toEqual({ tool: '*', permission: 'allow' });
|
||||
expect(policies[0]).toEqual({ tool: "*", permission: "allow" });
|
||||
});
|
||||
});
|
||||
|
||||
describe('mode policy generation', () => {
|
||||
it('should generate policies in correct order (mode policies first)', () => {
|
||||
describe("mode policy generation", () => {
|
||||
it("should generate policies in correct order (mode policies first)", () => {
|
||||
const state = service.initializeSync({
|
||||
mode: 'plan',
|
||||
allow: ['customTool']
|
||||
mode: "plan",
|
||||
allow: ["customTool"],
|
||||
});
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
|
||||
// Mode policies should come first, and there should be policies
|
||||
expect(policies.length).toBeGreaterThan(0);
|
||||
|
||||
|
||||
// Should have MCP and wildcard exclusion policies
|
||||
expect(policies.some(p => p.tool === 'mcp:*')).toBe(true);
|
||||
expect(policies.some(p => p.tool === '*' && p.permission === 'exclude')).toBe(true);
|
||||
expect(policies.some((p) => p.tool === "mcp:*")).toBe(true);
|
||||
expect(
|
||||
policies.some((p) => p.tool === "*" && p.permission === "exclude"),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentMode', () => {
|
||||
it('should return the current mode', () => {
|
||||
service.initializeSync({ mode: 'plan' });
|
||||
expect(service.getCurrentMode()).toBe('plan');
|
||||
|
||||
service.switchMode('auto');
|
||||
expect(service.getCurrentMode()).toBe('auto');
|
||||
describe("getCurrentMode", () => {
|
||||
it("should return the current mode", () => {
|
||||
service.initializeSync({ mode: "plan" });
|
||||
expect(service.getCurrentMode()).toBe("plan");
|
||||
|
||||
service.switchMode("auto");
|
||||
expect(service.getCurrentMode()).toBe("auto");
|
||||
});
|
||||
});
|
||||
|
||||
describe('state consistency', () => {
|
||||
it('should maintain consistent state between getState and getCurrentMode', () => {
|
||||
service.initializeSync({ mode: 'plan' });
|
||||
|
||||
describe("state consistency", () => {
|
||||
it("should maintain consistent state between getState and getCurrentMode", () => {
|
||||
service.initializeSync({ mode: "plan" });
|
||||
|
||||
const state = service.getState();
|
||||
const currentMode = service.getCurrentMode();
|
||||
|
||||
|
||||
expect(state.currentMode).toBe(currentMode);
|
||||
expect(currentMode).toBe('plan');
|
||||
expect(currentMode).toBe("plan");
|
||||
});
|
||||
|
||||
it('should update state when switching modes', () => {
|
||||
it("should update state when switching modes", () => {
|
||||
service.initializeSync();
|
||||
|
||||
|
||||
const initialState = service.getState();
|
||||
expect(initialState.currentMode).toBe('normal');
|
||||
|
||||
service.switchMode('plan');
|
||||
|
||||
expect(initialState.currentMode).toBe("normal");
|
||||
|
||||
service.switchMode("plan");
|
||||
|
||||
const newState = service.getState();
|
||||
expect(newState.currentMode).toBe('plan');
|
||||
expect(newState.currentMode).toBe("plan");
|
||||
expect(newState).not.toEqual(initialState);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,162 +1,165 @@
|
|||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
import { checkToolPermission } from '../permissions/permissionChecker.js';
|
||||
import { checkToolPermission } from "../permissions/permissionChecker.js";
|
||||
|
||||
import { ToolPermissionService } from './ToolPermissionService.js';
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
describe('ToolPermissionService - Real Tool Permission Test', () => {
|
||||
describe("ToolPermissionService - Real Tool Permission Test", () => {
|
||||
let service: ToolPermissionService;
|
||||
|
||||
beforeEach(() => {
|
||||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
describe('Plan Mode Real Tool Tests', () => {
|
||||
describe("Plan Mode Real Tool Tests", () => {
|
||||
beforeEach(() => {
|
||||
service.initializeSync({ mode: 'plan' });
|
||||
service.initializeSync({ mode: "plan" });
|
||||
});
|
||||
|
||||
it('should deny Write tool in plan mode', () => {
|
||||
it("should deny Write tool in plan mode", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'Write',
|
||||
arguments: { path: 'test.txt', content: 'test' }
|
||||
name: "Write",
|
||||
arguments: { path: "test.txt", content: "test" },
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`Write permission check result:`, result);
|
||||
expect(result.permission).toBe('exclude');
|
||||
expect(result.permission).toBe("exclude");
|
||||
});
|
||||
|
||||
it('should deny Edit tool in plan mode', () => {
|
||||
it("should deny Edit tool in plan mode", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'Edit',
|
||||
arguments: { path: 'test.txt', old_str: 'old', new_str: 'new' }
|
||||
name: "Edit",
|
||||
arguments: { path: "test.txt", old_str: "old", new_str: "new" },
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`Edit permission check result:`, result);
|
||||
expect(result.permission).toBe('exclude');
|
||||
expect(result.permission).toBe("exclude");
|
||||
});
|
||||
|
||||
it('should allow Bash tool in plan mode', () => {
|
||||
it("should allow Bash tool in plan mode", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'Bash',
|
||||
arguments: { command: 'ls' }
|
||||
name: "Bash",
|
||||
arguments: { command: "ls" },
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`Bash permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
it('should allow Read tool in plan mode', () => {
|
||||
it("should allow Read tool in plan mode", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'Read',
|
||||
arguments: { path: 'test.txt' }
|
||||
name: "Read",
|
||||
arguments: { path: "test.txt" },
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`Read permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
it('should allow List tool in plan mode', () => {
|
||||
it("should allow List tool in plan mode", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'List',
|
||||
arguments: { path: '.' }
|
||||
name: "List",
|
||||
arguments: { path: "." },
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`List permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
it('should deny unknown tools in plan mode (wildcard exclude)', () => {
|
||||
it("should deny unknown tools in plan mode (wildcard exclude)", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'unknown_write_tool',
|
||||
arguments: {}
|
||||
name: "unknown_write_tool",
|
||||
arguments: {},
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`unknown_write_tool permission check result:`, result);
|
||||
expect(result.permission).toBe('exclude');
|
||||
expect(result.permission).toBe("exclude");
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auto Mode Real Tool Tests', () => {
|
||||
describe("Auto Mode Real Tool Tests", () => {
|
||||
beforeEach(() => {
|
||||
service.initializeSync({ mode: 'auto' });
|
||||
service.initializeSync({ mode: "auto" });
|
||||
});
|
||||
|
||||
it('should allow Write tool in auto mode', () => {
|
||||
it("should allow Write tool in auto mode", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'Write',
|
||||
arguments: { path: 'test.txt', content: 'test' }
|
||||
name: "Write",
|
||||
arguments: { path: "test.txt", content: "test" },
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`Auto mode Write permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
it('should allow Bash tool in auto mode', () => {
|
||||
it("should allow Bash tool in auto mode", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'Bash',
|
||||
arguments: { command: 'ls' }
|
||||
name: "Bash",
|
||||
arguments: { command: "ls" },
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`Auto mode Bash permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
|
||||
it('should allow unknown tools in auto mode (wildcard allow)', () => {
|
||||
it("should allow unknown tools in auto mode (wildcard allow)", () => {
|
||||
const permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'unknown_tool',
|
||||
arguments: {}
|
||||
name: "unknown_tool",
|
||||
arguments: {},
|
||||
};
|
||||
const result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`Auto mode unknown_tool permission check result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
});
|
||||
});
|
||||
|
||||
describe('Mode Override Test', () => {
|
||||
it('should override user permissions when switching to plan mode', () => {
|
||||
describe("Mode Override Test", () => {
|
||||
it("should override user permissions when switching to plan mode", () => {
|
||||
// Start with user explicitly allowing Write
|
||||
service.initializeSync({
|
||||
allow: ['Write'],
|
||||
mode: 'normal'
|
||||
allow: ["Write"],
|
||||
mode: "normal",
|
||||
});
|
||||
|
||||
// Verify Write is allowed in normal mode
|
||||
let permissions = service.getPermissions();
|
||||
const toolCall = {
|
||||
name: 'Write',
|
||||
arguments: { path: 'test.txt', content: 'test' }
|
||||
name: "Write",
|
||||
arguments: { path: "test.txt", content: "test" },
|
||||
};
|
||||
let result = checkToolPermission(toolCall, permissions);
|
||||
console.log(`Normal mode with user allow - Write result:`, result);
|
||||
expect(result.permission).toBe('allow');
|
||||
expect(result.permission).toBe("allow");
|
||||
|
||||
// Switch to plan mode - should OVERRIDE user config completely
|
||||
service.switchMode('plan');
|
||||
service.switchMode("plan");
|
||||
permissions = service.getPermissions();
|
||||
result = checkToolPermission(toolCall, permissions);
|
||||
|
||||
|
||||
console.log(`After switching to plan mode - write_file result:`, result);
|
||||
console.log(`Plan mode policies:`, permissions.policies.map(p => `${p.tool}:${p.permission}`));
|
||||
expect(result.permission).toBe('exclude');
|
||||
console.log(
|
||||
`Plan mode policies:`,
|
||||
permissions.policies.map((p) => `${p.tool}:${p.permission}`),
|
||||
);
|
||||
expect(result.permission).toBe("exclude");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { describe, expect, test, beforeEach, vi } from 'vitest';
|
||||
import { describe, expect, test, beforeEach, vi } from "vitest";
|
||||
|
||||
// Mock modules
|
||||
vi.mock('../permissions/permissionsYamlLoader.js');
|
||||
vi.mock('../permissions/precedenceResolver.js');
|
||||
vi.mock("../permissions/permissionsYamlLoader.js");
|
||||
vi.mock("../permissions/precedenceResolver.js");
|
||||
|
||||
import * as precedenceResolver from '../permissions/precedenceResolver.js';
|
||||
import { ToolPermissionPolicy } from '../permissions/types.js';
|
||||
import * as precedenceResolver from "../permissions/precedenceResolver.js";
|
||||
import { ToolPermissionPolicy } from "../permissions/types.js";
|
||||
|
||||
import { ToolPermissionService } from "./ToolPermissionService.js";
|
||||
|
||||
|
|
@ -17,29 +17,33 @@ describe("ToolPermissionService", () => {
|
|||
service = new ToolPermissionService();
|
||||
});
|
||||
|
||||
describe('State Management', () => {
|
||||
test('should initialize with default state', async () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([]);
|
||||
|
||||
describe("State Management", () => {
|
||||
test("should initialize with default state", async () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
[],
|
||||
);
|
||||
|
||||
const state = await service.initialize();
|
||||
|
||||
|
||||
expect(state).toEqual({
|
||||
permissions: { policies: [] },
|
||||
currentMode: 'normal',
|
||||
currentMode: "normal",
|
||||
isHeadless: false,
|
||||
modePolicyCount: 0
|
||||
modePolicyCount: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with runtime overrides', async () => {
|
||||
test("should initialize with runtime overrides", async () => {
|
||||
const mockPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: 'TestTool3', permission: 'exclude' },
|
||||
{ tool: 'TestTool2', permission: 'ask' },
|
||||
{ tool: 'TestTool1', permission: 'allow' }
|
||||
{ tool: "TestTool3", permission: "exclude" },
|
||||
{ tool: "TestTool2", permission: "ask" },
|
||||
{ tool: "TestTool1", permission: "allow" },
|
||||
];
|
||||
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(mockPolicies);
|
||||
|
||||
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
mockPolicies,
|
||||
);
|
||||
|
||||
const overrides = {
|
||||
allow: ["TestTool1"],
|
||||
ask: ["TestTool2"],
|
||||
|
|
@ -49,48 +53,52 @@ describe("ToolPermissionService", () => {
|
|||
const state = await service.initialize(overrides);
|
||||
|
||||
expect(state.permissions.policies).toEqual(mockPolicies);
|
||||
expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({
|
||||
expect(
|
||||
precedenceResolver.resolvePermissionPrecedence,
|
||||
).toHaveBeenCalledWith({
|
||||
commandLineFlags: overrides,
|
||||
personalSettings: true,
|
||||
useDefaults: true
|
||||
useDefaults: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('should initialize with specific mode', async () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([]);
|
||||
|
||||
const state = await service.initialize({ mode: 'plan' });
|
||||
|
||||
expect(state.currentMode).toBe('plan');
|
||||
test("should initialize with specific mode", async () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
[],
|
||||
);
|
||||
|
||||
const state = await service.initialize({ mode: "plan" });
|
||||
|
||||
expect(state.currentMode).toBe("plan");
|
||||
// Plan mode should have mode-specific policies
|
||||
expect(state.permissions.policies.length).toBeGreaterThan(0);
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
tool: "Write",
|
||||
permission: "exclude",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeSync()', () => {
|
||||
test('should work synchronously for immediate availability', () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'Tool1', permission: 'allow' }
|
||||
]);
|
||||
|
||||
const state = service.initializeSync({ allow: ['Tool1'] });
|
||||
|
||||
describe("initializeSync()", () => {
|
||||
test("should work synchronously for immediate availability", () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
[{ tool: "Tool1", permission: "allow" }],
|
||||
);
|
||||
|
||||
const state = service.initializeSync({ allow: ["Tool1"] });
|
||||
|
||||
expect(state).toBeDefined();
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Tool1',
|
||||
permission: 'allow'
|
||||
tool: "Tool1",
|
||||
permission: "allow",
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle empty overrides', () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: '*', permission: 'ask' }
|
||||
]);
|
||||
|
||||
test("should handle empty overrides", () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
[{ tool: "*", permission: "ask" }],
|
||||
);
|
||||
|
||||
const state = service.initializeSync({
|
||||
allow: [],
|
||||
ask: [],
|
||||
|
|
@ -98,129 +106,136 @@ describe("ToolPermissionService", () => {
|
|||
});
|
||||
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'ask' }
|
||||
{ tool: "*", permission: "ask" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Mode-specific policies', () => {
|
||||
test('should generate plan mode policies', () => {
|
||||
const state = service.initializeSync({ mode: 'plan' });
|
||||
describe("Mode-specific policies", () => {
|
||||
test("should generate plan mode policies", () => {
|
||||
const state = service.initializeSync({ mode: "plan" });
|
||||
const policies = state.permissions.policies;
|
||||
|
||||
|
||||
// Should exclude write tools
|
||||
expect(policies).toContainEqual({ tool: 'Write', permission: 'exclude' });
|
||||
expect(policies).toContainEqual({ tool: 'Edit', permission: 'exclude' });
|
||||
|
||||
expect(policies).toContainEqual({ tool: "Write", permission: "exclude" });
|
||||
expect(policies).toContainEqual({ tool: "Edit", permission: "exclude" });
|
||||
|
||||
// Should allow read tools and bash
|
||||
expect(policies).toContainEqual({ tool: 'Bash', permission: 'allow' });
|
||||
expect(policies).toContainEqual({ tool: 'Read', permission: 'allow' });
|
||||
expect(policies).toContainEqual({ tool: 'Grep', permission: 'allow' });
|
||||
expect(policies).toContainEqual({ tool: 'LS', permission: 'allow' });
|
||||
|
||||
expect(policies).toContainEqual({ tool: "Bash", permission: "allow" });
|
||||
expect(policies).toContainEqual({ tool: "Read", permission: "allow" });
|
||||
expect(policies).toContainEqual({ tool: "Grep", permission: "allow" });
|
||||
expect(policies).toContainEqual({ tool: "LS", permission: "allow" });
|
||||
|
||||
// Should have wildcard exclusion at the end
|
||||
expect(policies[policies.length - 1]).toEqual({ tool: '*', permission: 'exclude' });
|
||||
expect(policies[policies.length - 1]).toEqual({
|
||||
tool: "*",
|
||||
permission: "exclude",
|
||||
});
|
||||
});
|
||||
|
||||
test('should generate auto mode policies', () => {
|
||||
const state = service.initializeSync({ mode: 'auto' });
|
||||
|
||||
test("should generate auto mode policies", () => {
|
||||
const state = service.initializeSync({ mode: "auto" });
|
||||
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'allow' }
|
||||
{ tool: "*", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
|
||||
test('should generate normal mode policies', () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'Tool1', permission: 'allow' },
|
||||
{ tool: 'Tool2', permission: 'ask' }
|
||||
]);
|
||||
|
||||
const state = service.initializeSync({ mode: 'normal' });
|
||||
|
||||
test("should generate normal mode policies", () => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
[
|
||||
{ tool: "Tool1", permission: "allow" },
|
||||
{ tool: "Tool2", permission: "ask" },
|
||||
],
|
||||
);
|
||||
|
||||
const state = service.initializeSync({ mode: "normal" });
|
||||
|
||||
// Normal mode should use user configuration
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: 'Tool1', permission: 'allow' },
|
||||
{ tool: 'Tool2', permission: 'ask' }
|
||||
{ tool: "Tool1", permission: "allow" },
|
||||
{ tool: "Tool2", permission: "ask" },
|
||||
]);
|
||||
expect(state.modePolicyCount).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('switchMode()', () => {
|
||||
describe("switchMode()", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'UserTool1', permission: 'allow' },
|
||||
{ tool: 'UserTool2', permission: 'exclude' }
|
||||
]);
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
[
|
||||
{ tool: "UserTool1", permission: "allow" },
|
||||
{ tool: "UserTool2", permission: "exclude" },
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('should switch from normal to plan mode', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
|
||||
const state = service.switchMode('plan');
|
||||
|
||||
expect(state.currentMode).toBe('plan');
|
||||
test("should switch from normal to plan mode", () => {
|
||||
service.initializeSync({ mode: "normal" });
|
||||
|
||||
const state = service.switchMode("plan");
|
||||
|
||||
expect(state.currentMode).toBe("plan");
|
||||
// Should only have plan mode policies
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
tool: "Write",
|
||||
permission: "exclude",
|
||||
});
|
||||
// Should not have user policies
|
||||
expect(state.permissions.policies).not.toContainEqual({
|
||||
tool: 'UserTool1',
|
||||
permission: 'allow'
|
||||
tool: "UserTool1",
|
||||
permission: "allow",
|
||||
});
|
||||
});
|
||||
|
||||
test('should store original policies when leaving normal mode', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
test("should store original policies when leaving normal mode", () => {
|
||||
service.initializeSync({ mode: "normal" });
|
||||
const originalState = service.getState();
|
||||
|
||||
service.switchMode('plan');
|
||||
|
||||
service.switchMode("plan");
|
||||
const planState = service.getState();
|
||||
|
||||
|
||||
// Should have stored original policies
|
||||
expect(planState.originalPolicies).toEqual({
|
||||
policies: originalState.permissions.policies
|
||||
policies: originalState.permissions.policies,
|
||||
});
|
||||
});
|
||||
|
||||
test('should restore original policies when switching back to normal', () => {
|
||||
test("should restore original policies when switching back to normal", () => {
|
||||
// Start in normal with user policies
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
service.initializeSync({ mode: "normal" });
|
||||
const originalPolicies = service.getState().permissions.policies;
|
||||
|
||||
|
||||
// Switch to plan
|
||||
service.switchMode('plan');
|
||||
|
||||
service.switchMode("plan");
|
||||
|
||||
// Switch back to normal
|
||||
const state = service.switchMode('normal');
|
||||
|
||||
const state = service.switchMode("normal");
|
||||
|
||||
// Should restore original user policies
|
||||
expect(state.permissions.policies).toEqual(originalPolicies);
|
||||
});
|
||||
|
||||
test('should handle multiple mode switches', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
|
||||
test("should handle multiple mode switches", () => {
|
||||
service.initializeSync({ mode: "normal" });
|
||||
|
||||
// Switch through all modes
|
||||
service.switchMode('plan');
|
||||
expect(service.getCurrentMode()).toBe('plan');
|
||||
|
||||
service.switchMode('auto');
|
||||
expect(service.getCurrentMode()).toBe('auto');
|
||||
service.switchMode("plan");
|
||||
expect(service.getCurrentMode()).toBe("plan");
|
||||
|
||||
service.switchMode("auto");
|
||||
expect(service.getCurrentMode()).toBe("auto");
|
||||
expect(service.getState().permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'allow' }
|
||||
{ tool: "*", permission: "allow" },
|
||||
]);
|
||||
|
||||
service.switchMode('normal');
|
||||
expect(service.getCurrentMode()).toBe('normal');
|
||||
|
||||
service.switchMode("normal");
|
||||
expect(service.getCurrentMode()).toBe("normal");
|
||||
});
|
||||
});
|
||||
|
||||
describe('updatePermissions()', () => {
|
||||
test('should replace all policies', () => {
|
||||
describe("updatePermissions()", () => {
|
||||
test("should replace all policies", () => {
|
||||
service.initializeSync();
|
||||
|
||||
const newPolicies: ToolPermissionPolicy[] = [
|
||||
|
|
@ -236,8 +251,8 @@ describe("ToolPermissionService", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('getPermissions()', () => {
|
||||
test('should return current permissions', () => {
|
||||
describe("getPermissions()", () => {
|
||||
test("should return current permissions", () => {
|
||||
service.initializeSync({ allow: ["TestTool"] });
|
||||
|
||||
const permissions = service.getPermissions();
|
||||
|
|
@ -249,97 +264,99 @@ describe("ToolPermissionService", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('getCurrentMode()', () => {
|
||||
test('should return current mode', () => {
|
||||
service.initializeSync({ mode: 'plan' });
|
||||
expect(service.getCurrentMode()).toBe('plan');
|
||||
|
||||
service.switchMode('auto');
|
||||
expect(service.getCurrentMode()).toBe('auto');
|
||||
describe("getCurrentMode()", () => {
|
||||
test("should return current mode", () => {
|
||||
service.initializeSync({ mode: "plan" });
|
||||
expect(service.getCurrentMode()).toBe("plan");
|
||||
|
||||
service.switchMode("auto");
|
||||
expect(service.getCurrentMode()).toBe("auto");
|
||||
});
|
||||
});
|
||||
|
||||
describe('isReady()', () => {
|
||||
test('should always return true (service is always ready)', () => {
|
||||
describe("isReady()", () => {
|
||||
test("should always return true (service is always ready)", () => {
|
||||
// ToolPermissionService is designed to be always ready since it uses synchronous initialization
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
|
||||
test('should return true after initialization', async () => {
|
||||
test("should return true after initialization", async () => {
|
||||
await service.initialize();
|
||||
expect(service.isReady()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Event Emission', () => {
|
||||
test('should emit stateChanged when switching modes', () => {
|
||||
service.initializeSync({ mode: 'normal' });
|
||||
|
||||
describe("Event Emission", () => {
|
||||
test("should emit stateChanged when switching modes", () => {
|
||||
service.initializeSync({ mode: "normal" });
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
|
||||
service.switchMode('plan');
|
||||
|
||||
service.on("stateChanged", listener);
|
||||
|
||||
service.switchMode("plan");
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ currentMode: 'plan' }),
|
||||
expect.objectContaining({ currentMode: 'normal' })
|
||||
expect.objectContaining({ currentMode: "plan" }),
|
||||
expect.objectContaining({ currentMode: "normal" }),
|
||||
);
|
||||
});
|
||||
|
||||
test('should emit stateChanged when updating permissions', () => {
|
||||
test("should emit stateChanged when updating permissions", () => {
|
||||
service.initializeSync();
|
||||
|
||||
|
||||
const listener = vi.fn();
|
||||
service.on('stateChanged', listener);
|
||||
|
||||
service.on("stateChanged", listener);
|
||||
|
||||
const newPolicies: ToolPermissionPolicy[] = [
|
||||
{ tool: 'NewTool', permission: 'allow' }
|
||||
{ tool: "NewTool", permission: "allow" },
|
||||
];
|
||||
service.updatePermissions(newPolicies);
|
||||
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permissions: { policies: newPolicies }
|
||||
expect.objectContaining({
|
||||
permissions: { policies: newPolicies },
|
||||
}),
|
||||
expect.any(Object)
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Mode Override Behavior', () => {
|
||||
test('plan mode should completely override user policies', () => {
|
||||
describe("Mode Override Behavior", () => {
|
||||
test("plan mode should completely override user policies", () => {
|
||||
// Initialize with user policies that would allow writes
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue([
|
||||
{ tool: 'Write', permission: 'allow' },
|
||||
{ tool: 'Edit', permission: 'allow' }
|
||||
]);
|
||||
|
||||
const state = service.initializeSync({
|
||||
mode: 'plan',
|
||||
allow: ['Write', 'Edit']
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
[
|
||||
{ tool: "Write", permission: "allow" },
|
||||
{ tool: "Edit", permission: "allow" },
|
||||
],
|
||||
);
|
||||
|
||||
const state = service.initializeSync({
|
||||
mode: "plan",
|
||||
allow: ["Write", "Edit"],
|
||||
});
|
||||
|
||||
|
||||
// Plan mode should override and exclude these tools
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Write',
|
||||
permission: 'exclude'
|
||||
tool: "Write",
|
||||
permission: "exclude",
|
||||
});
|
||||
expect(state.permissions.policies).toContainEqual({
|
||||
tool: 'Edit',
|
||||
permission: 'exclude'
|
||||
tool: "Edit",
|
||||
permission: "exclude",
|
||||
});
|
||||
});
|
||||
|
||||
test('auto mode should completely override user policies', () => {
|
||||
test("auto mode should completely override user policies", () => {
|
||||
// Initialize with user policies that would exclude tools
|
||||
const state = service.initializeSync({
|
||||
mode: 'auto',
|
||||
exclude: ['DangerousTool']
|
||||
const state = service.initializeSync({
|
||||
mode: "auto",
|
||||
exclude: ["DangerousTool"],
|
||||
});
|
||||
|
||||
|
||||
// Auto mode should override and allow everything
|
||||
expect(state.permissions.policies).toEqual([
|
||||
{ tool: '*', permission: 'allow' }
|
||||
{ tool: "*", permission: "allow" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
@ -350,49 +367,57 @@ describe("ToolPermissionService", () => {
|
|||
{ tool: "Edit", permission: "allow" as const },
|
||||
{ tool: "Write", permission: "ask" as const },
|
||||
];
|
||||
|
||||
|
||||
// Mock the precedence resolver to return fresh policies
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(mockPolicies);
|
||||
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
mockPolicies,
|
||||
);
|
||||
|
||||
const service = new ToolPermissionService();
|
||||
service.initializeSync({ mode: "normal" });
|
||||
|
||||
|
||||
// Verify initial state
|
||||
expect(service.getPermissions().policies).toEqual(mockPolicies);
|
||||
|
||||
|
||||
// Simulate new policies being added to the file
|
||||
const newMockPolicies = [
|
||||
...mockPolicies,
|
||||
{ tool: "Read", permission: "allow" as const },
|
||||
];
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(newMockPolicies);
|
||||
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockReturnValue(
|
||||
newMockPolicies,
|
||||
);
|
||||
|
||||
// Reload permissions
|
||||
await service.reloadPermissions();
|
||||
|
||||
|
||||
// Verify policies were reloaded
|
||||
expect(service.getPermissions().policies).toEqual(newMockPolicies);
|
||||
expect(precedenceResolver.resolvePermissionPrecedence).toHaveBeenCalledWith({
|
||||
expect(
|
||||
precedenceResolver.resolvePermissionPrecedence,
|
||||
).toHaveBeenCalledWith({
|
||||
personalSettings: true,
|
||||
useDefaults: true,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
test("should skip reload in non-normal modes", async () => {
|
||||
const service = new ToolPermissionService();
|
||||
service.initializeSync({ mode: "plan" });
|
||||
|
||||
|
||||
const initialPolicies = service.getPermissions().policies;
|
||||
|
||||
|
||||
// Clear the mock call count
|
||||
vi.mocked(precedenceResolver.resolvePermissionPrecedence).mockClear();
|
||||
|
||||
|
||||
// Try to reload
|
||||
await service.reloadPermissions();
|
||||
|
||||
|
||||
// Verify no reload happened
|
||||
expect(service.getPermissions().policies).toEqual(initialPolicies);
|
||||
expect(precedenceResolver.resolvePermissionPrecedence).not.toHaveBeenCalled();
|
||||
expect(
|
||||
precedenceResolver.resolvePermissionPrecedence,
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ describe("ToolPermissionService unit tests", () => {
|
|||
// getState() returns a shallow copy, getPermissions() returns the same permissions object
|
||||
expect(state.permissions).toEqual(permissions);
|
||||
expect(state.permissions).toBe(permissions); // Same reference with shallow copy
|
||||
|
||||
|
||||
// Multiple calls to getPermissions() should return the same reference
|
||||
const permissions2 = service.getPermissions();
|
||||
expect(permissions).toEqual(permissions2);
|
||||
|
|
|
|||
|
|
@ -1,28 +1,32 @@
|
|||
import { ServiceContainer } from './ServiceContainer.js';
|
||||
import { ServiceContainer } from "./ServiceContainer.js";
|
||||
|
||||
import { initializeServices } from './index.js';
|
||||
import { initializeServices } from "./index.js";
|
||||
|
||||
describe('Service Circular Dependencies', () => {
|
||||
it('should not have circular dependencies in service setup', async () => {
|
||||
describe("Service Circular Dependencies", () => {
|
||||
it("should not have circular dependencies in service setup", async () => {
|
||||
// Create a fresh container and initialize services to get real dependencies
|
||||
const testContainer = new ServiceContainer();
|
||||
|
||||
|
||||
// Monkey patch the global serviceContainer to capture registrations
|
||||
const originalRegister = testContainer.register.bind(testContainer);
|
||||
const serviceDependencies: Record<string, string[]> = {};
|
||||
|
||||
testContainer.register = function<T>(serviceName: string, factory: () => Promise<T>, deps: string[] = []) {
|
||||
|
||||
testContainer.register = function <T>(
|
||||
serviceName: string,
|
||||
factory: () => Promise<T>,
|
||||
deps: string[] = [],
|
||||
) {
|
||||
serviceDependencies[serviceName] = [...deps]; // Capture actual dependencies
|
||||
return originalRegister(serviceName, factory, deps);
|
||||
};
|
||||
|
||||
// Import and run the real service initialization to capture dependencies
|
||||
const { serviceContainer } = await import('./index.js');
|
||||
const { serviceContainer } = await import("./index.js");
|
||||
const originalContainer = serviceContainer;
|
||||
|
||||
|
||||
// Temporarily replace the global container
|
||||
(global as any).serviceContainer = testContainer;
|
||||
|
||||
|
||||
try {
|
||||
// This will register services with their real dependencies
|
||||
await initializeServices({ headless: true });
|
||||
|
|
@ -34,7 +38,9 @@ describe('Service Circular Dependencies', () => {
|
|||
}
|
||||
|
||||
// Detect circular dependencies using topological sort
|
||||
const detectCircularDependencies = (dependencies: Record<string, string[]>): string[] => {
|
||||
const detectCircularDependencies = (
|
||||
dependencies: Record<string, string[]>,
|
||||
): string[] => {
|
||||
const visited = new Set<string>();
|
||||
const recStack = new Set<string>();
|
||||
const cycle: string[] = [];
|
||||
|
|
@ -78,9 +84,11 @@ describe('Service Circular Dependencies', () => {
|
|||
};
|
||||
|
||||
const circularDeps = detectCircularDependencies(serviceDependencies);
|
||||
|
||||
|
||||
if (circularDeps.length > 0) {
|
||||
throw new Error(`Circular dependency detected: ${circularDeps.join(' -> ')}`);
|
||||
throw new Error(
|
||||
`Circular dependency detected: ${circularDeps.join(" -> ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Also verify that all services can be theoretically loaded without circular issues
|
||||
|
|
@ -89,9 +97,15 @@ describe('Service Circular Dependencies', () => {
|
|||
const maxIterations = Object.keys(serviceDependencies).length * 2;
|
||||
let iterations = 0;
|
||||
|
||||
while (resolved.size < Object.keys(serviceDependencies).length && iterations < maxIterations) {
|
||||
while (
|
||||
resolved.size < Object.keys(serviceDependencies).length &&
|
||||
iterations < maxIterations
|
||||
) {
|
||||
for (const [service, deps] of Object.entries(serviceDependencies)) {
|
||||
if (!resolved.has(service) && deps.every(dep => resolved.has(dep))) {
|
||||
if (
|
||||
!resolved.has(service) &&
|
||||
deps.every((dep) => resolved.has(dep))
|
||||
) {
|
||||
resolved.add(service);
|
||||
}
|
||||
}
|
||||
|
|
@ -103,4 +117,4 @@ describe('Service Circular Dependencies', () => {
|
|||
|
||||
expect(canResolveAll()).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { serviceContainer } from './ServiceContainer.js';
|
||||
import type { ToolPermissionServiceState } from './ToolPermissionService.js';
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import type { ToolPermissionServiceState } from "./ToolPermissionService.js";
|
||||
|
||||
import { initializeServices, getServiceSync, SERVICE_NAMES } from './index.js';
|
||||
import { initializeServices, getServiceSync, SERVICE_NAMES } from "./index.js";
|
||||
|
||||
describe('Service Initialization', () => {
|
||||
describe("Service Initialization", () => {
|
||||
beforeEach(() => {
|
||||
// Clean up service container state
|
||||
const services = [
|
||||
|
|
@ -14,10 +14,10 @@ describe('Service Initialization', () => {
|
|||
SERVICE_NAMES.API_CLIENT,
|
||||
SERVICE_NAMES.CONFIG,
|
||||
SERVICE_NAMES.MODEL,
|
||||
SERVICE_NAMES.MCP
|
||||
SERVICE_NAMES.MCP,
|
||||
];
|
||||
|
||||
services.forEach(service => {
|
||||
|
||||
services.forEach((service) => {
|
||||
// Reset service state
|
||||
(serviceContainer as any).services.delete(service);
|
||||
(serviceContainer as any).factories.delete(service);
|
||||
|
|
@ -25,37 +25,41 @@ describe('Service Initialization', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('should have TOOL_PERMISSIONS service ready after initialization', async () => {
|
||||
it("should have TOOL_PERMISSIONS service ready after initialization", async () => {
|
||||
// Before initialization, service should not be ready
|
||||
const beforeInit = getServiceSync(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
expect(beforeInit.state).toBe('error'); // Not registered yet
|
||||
|
||||
expect(beforeInit.state).toBe("error"); // Not registered yet
|
||||
|
||||
// Initialize services
|
||||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'normal'
|
||||
}
|
||||
mode: "normal",
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
// After initialization, service should be ready
|
||||
const afterInit = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
expect(afterInit.state).toBe('ready');
|
||||
const afterInit = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
expect(afterInit.state).toBe("ready");
|
||||
expect(afterInit.value).toBeDefined();
|
||||
expect(afterInit.value?.currentMode).toBe('normal');
|
||||
expect(afterInit.value?.currentMode).toBe("normal");
|
||||
expect(afterInit.value?.isHeadless).toBe(true);
|
||||
});
|
||||
|
||||
it('should have TOOL_PERMISSIONS service ready immediately when accessed early', async () => {
|
||||
|
||||
it("should have TOOL_PERMISSIONS service ready immediately when accessed early", async () => {
|
||||
await initializeServices({
|
||||
headless: true
|
||||
headless: true,
|
||||
});
|
||||
|
||||
|
||||
// Simulate early access like in streamChatResponse
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
|
||||
// Service should be ready, not idle
|
||||
expect(serviceResult.state).toBe('ready');
|
||||
expect(serviceResult.state).toBe("ready");
|
||||
expect(serviceResult.value).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ vi.mock("../onboarding.js", () => ({
|
|||
createOrUpdateConfig: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
// Mock auth module
|
||||
// Mock auth module
|
||||
vi.mock("../auth/workos.js", () => ({
|
||||
loadAuthConfig: vi.fn().mockReturnValue({}),
|
||||
}));
|
||||
|
|
@ -47,12 +47,15 @@ describe("initializeServices", () => {
|
|||
// Set up mocks
|
||||
(modeService as any).initialize = mockModeService.initialize;
|
||||
(modeService as any).getCurrentMode = mockModeService.getCurrentMode;
|
||||
(modeService as any).getToolPermissionService = mockModeService.getToolPermissionService;
|
||||
|
||||
(modeService as any).getToolPermissionService =
|
||||
mockModeService.getToolPermissionService;
|
||||
|
||||
// Mock serviceContainer methods
|
||||
(serviceContainer as any).registerValue = mockServiceContainer.registerValue;
|
||||
(serviceContainer as any).registerValue =
|
||||
mockServiceContainer.registerValue;
|
||||
(serviceContainer as any).register = mockServiceContainer.register;
|
||||
(serviceContainer as any).initializeAll = mockServiceContainer.initializeAll;
|
||||
(serviceContainer as any).initializeAll =
|
||||
mockServiceContainer.initializeAll;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ describe("Session Management", () => {
|
|||
|
||||
beforeEach(() => {
|
||||
originalEnv = { ...process.env };
|
||||
|
||||
|
||||
// Clear session-related environment variables
|
||||
delete process.env.TMUX_PANE;
|
||||
delete process.env.TERM_SESSION_ID;
|
||||
|
|
@ -41,7 +41,7 @@ describe("Session Management", () => {
|
|||
|
||||
it("should use TERM_SESSION_ID when TMUX_PANE is not available", () => {
|
||||
process.env.TERM_SESSION_ID = "w1t0s0:0.0";
|
||||
|
||||
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
|
|
@ -49,7 +49,7 @@ describe("Session Management", () => {
|
|||
|
||||
it("should use SSH_TTY when other env vars are not available", () => {
|
||||
process.env.SSH_TTY = "/dev/pts/0";
|
||||
|
||||
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
|
|
@ -57,12 +57,12 @@ describe("Session Management", () => {
|
|||
|
||||
it("should clean special characters from session IDs", () => {
|
||||
process.env.TMUX_PANE = "%1:0.0/special#chars@test!";
|
||||
|
||||
|
||||
// Should not throw error despite special characters
|
||||
expect(() => {
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
}).not.toThrow();
|
||||
|
||||
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
});
|
||||
|
|
@ -71,7 +71,7 @@ describe("Session Management", () => {
|
|||
describe("Test Mode", () => {
|
||||
it("should use test session ID when provided", () => {
|
||||
process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-123";
|
||||
|
||||
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
|
|
@ -81,28 +81,28 @@ describe("Session Management", () => {
|
|||
describe("Fallback Mechanisms", () => {
|
||||
it("should create a session even when no environment variables are available", () => {
|
||||
// No environment variables set
|
||||
|
||||
|
||||
// Should fall back to TTY path, process tree, or PID
|
||||
expect(() => {
|
||||
saveSession([{ role: "user", content: "fallback test" }]);
|
||||
}).not.toThrow();
|
||||
|
||||
|
||||
expect(hasSession()).toBe(true);
|
||||
clearSession();
|
||||
});
|
||||
|
||||
it("should handle session persistence correctly", () => {
|
||||
process.env.TMUX_PANE = "%test";
|
||||
|
||||
|
||||
const testHistory = [
|
||||
{ role: "user" as const, content: "Hello" },
|
||||
{ role: "assistant" as const, content: "Hi there!" }
|
||||
{ role: "assistant" as const, content: "Hi there!" },
|
||||
];
|
||||
|
||||
|
||||
// Save session
|
||||
saveSession(testHistory);
|
||||
expect(hasSession()).toBe(true);
|
||||
|
||||
|
||||
// Clear and verify it's gone
|
||||
clearSession();
|
||||
expect(hasSession()).toBe(false);
|
||||
|
|
@ -113,12 +113,12 @@ describe("Session Management", () => {
|
|||
it("should handle filesystem errors gracefully", () => {
|
||||
// Try to save to invalid session ID that might cause filesystem issues
|
||||
process.env.CONTINUE_CLI_TEST_SESSION_ID = "test-with-various-chars";
|
||||
|
||||
|
||||
expect(() => {
|
||||
saveSession([{ role: "user", content: "test" }]);
|
||||
}).not.toThrow();
|
||||
|
||||
|
||||
clearSession();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
// Mode-related slash commands have been removed per user request
|
||||
// This test file is no longer needed but needs a dummy test for Vitest
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
describe('Mode slash commands (removed)', () => {
|
||||
it('should pass (dummy test)', () => {
|
||||
describe("Mode slash commands (removed)", () => {
|
||||
it("should pass (dummy test)", () => {
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ describe("handleSlashCommands", () => {
|
|||
expect.arrayContaining([
|
||||
expect.objectContaining({ name: "help" }),
|
||||
expect.objectContaining({ name: "login" }),
|
||||
])
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -58,7 +58,7 @@ describe("handleSlashCommands", () => {
|
|||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.output).toContain(
|
||||
"Login successful! All services updated automatically."
|
||||
"Login successful! All services updated automatically.",
|
||||
);
|
||||
|
||||
// Verify auth service login was called
|
||||
|
|
@ -73,8 +73,6 @@ describe("handleSlashCommands", () => {
|
|||
expect(reloadService).not.toHaveBeenCalledWith(SERVICE_NAMES.CONFIG);
|
||||
});
|
||||
|
||||
|
||||
|
||||
test.skip("login failure should not trigger any reloads", async () => {
|
||||
const loginError = new Error("Login failed");
|
||||
(services.auth.login as any).mockRejectedValue(loginError);
|
||||
|
|
@ -87,8 +85,6 @@ describe("handleSlashCommands", () => {
|
|||
// Verify NO reload was triggered on failure
|
||||
expect(reloadService).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
});
|
||||
|
||||
describe("Other Commands (unchanged behavior)", () => {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
import { describe, expect, test } from 'vitest';
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { getServiceSync, initializeServices, SERVICE_NAMES, serviceContainer } from './services/index.js';
|
||||
import type { ToolPermissionServiceState } from './services/ToolPermissionService.js';
|
||||
import { getAllTools } from './streamChatResponse.js';
|
||||
import {
|
||||
getServiceSync,
|
||||
initializeServices,
|
||||
SERVICE_NAMES,
|
||||
serviceContainer,
|
||||
} from "./services/index.js";
|
||||
import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
|
||||
import { getAllTools } from "./streamChatResponse.js";
|
||||
|
||||
describe('getAllTools - Tool Filtering', () => {
|
||||
describe("getAllTools - Tool Filtering", () => {
|
||||
beforeEach(() => {
|
||||
// Clean up service container state before each test
|
||||
const services = [
|
||||
|
|
@ -13,10 +18,10 @@ describe('getAllTools - Tool Filtering', () => {
|
|||
SERVICE_NAMES.API_CLIENT,
|
||||
SERVICE_NAMES.CONFIG,
|
||||
SERVICE_NAMES.MODEL,
|
||||
SERVICE_NAMES.MCP
|
||||
SERVICE_NAMES.MCP,
|
||||
];
|
||||
|
||||
services.forEach(service => {
|
||||
|
||||
services.forEach((service) => {
|
||||
// Reset service state
|
||||
(serviceContainer as any).services.delete(service);
|
||||
(serviceContainer as any).factories.delete(service);
|
||||
|
|
@ -24,137 +29,143 @@ describe('getAllTools - Tool Filtering', () => {
|
|||
});
|
||||
});
|
||||
|
||||
test('should exclude Bash tool in plan mode after service initialization', async () => {
|
||||
test("should exclude Bash tool in plan mode after service initialization", async () => {
|
||||
// Initialize services in plan mode (simulating `cn -p`)
|
||||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'plan'
|
||||
}
|
||||
mode: "plan",
|
||||
},
|
||||
});
|
||||
|
||||
// Verify service is ready
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
expect(serviceResult.state).toBe('ready');
|
||||
expect(serviceResult.value?.currentMode).toBe('plan');
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
expect(serviceResult.state).toBe("ready");
|
||||
expect(serviceResult.value?.currentMode).toBe("plan");
|
||||
|
||||
// Get available tools - this should include Bash in plan mode
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
const toolNames = tools.map((t) => t.function.name);
|
||||
|
||||
// Bash should be allowed in plan mode
|
||||
expect(toolNames).toContain('Bash');
|
||||
|
||||
expect(toolNames).toContain("Bash");
|
||||
|
||||
// Read-only tools should still be available
|
||||
expect(toolNames).toContain('Read');
|
||||
expect(toolNames).toContain('List');
|
||||
expect(toolNames).toContain('Search');
|
||||
expect(toolNames).toContain('Fetch');
|
||||
expect(toolNames).toContain('Checklist');
|
||||
|
||||
expect(toolNames).toContain("Read");
|
||||
expect(toolNames).toContain("List");
|
||||
expect(toolNames).toContain("Search");
|
||||
expect(toolNames).toContain("Fetch");
|
||||
expect(toolNames).toContain("Checklist");
|
||||
|
||||
// Write tools should be excluded
|
||||
expect(toolNames).not.toContain('Write');
|
||||
expect(toolNames).not.toContain('Edit');
|
||||
expect(toolNames).not.toContain("Write");
|
||||
expect(toolNames).not.toContain("Edit");
|
||||
});
|
||||
|
||||
test('should include Bash tool in normal mode', async () => {
|
||||
test("should include Bash tool in normal mode", async () => {
|
||||
// Initialize services in normal mode
|
||||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'normal'
|
||||
}
|
||||
mode: "normal",
|
||||
},
|
||||
});
|
||||
|
||||
// Verify service is ready
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
expect(serviceResult.state).toBe('ready');
|
||||
expect(serviceResult.value?.currentMode).toBe('normal');
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
expect(serviceResult.state).toBe("ready");
|
||||
expect(serviceResult.value?.currentMode).toBe("normal");
|
||||
|
||||
// Get available tools - Bash should be available in normal mode
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
const toolNames = tools.map((t) => t.function.name);
|
||||
|
||||
// All tools should be available in normal mode
|
||||
expect(toolNames).toContain('Bash');
|
||||
expect(toolNames).toContain('Read');
|
||||
expect(toolNames).toContain('Write');
|
||||
expect(toolNames).toContain('Edit');
|
||||
expect(toolNames).toContain("Bash");
|
||||
expect(toolNames).toContain("Read");
|
||||
expect(toolNames).toContain("Write");
|
||||
expect(toolNames).toContain("Edit");
|
||||
});
|
||||
|
||||
test('should include all tools in auto mode', async () => {
|
||||
test("should include all tools in auto mode", async () => {
|
||||
// Initialize services in auto mode
|
||||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'auto'
|
||||
}
|
||||
mode: "auto",
|
||||
},
|
||||
});
|
||||
|
||||
// Verify service is ready
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(SERVICE_NAMES.TOOL_PERMISSIONS);
|
||||
expect(serviceResult.state).toBe('ready');
|
||||
expect(serviceResult.value?.currentMode).toBe('auto');
|
||||
const serviceResult = getServiceSync<ToolPermissionServiceState>(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
);
|
||||
expect(serviceResult.state).toBe("ready");
|
||||
expect(serviceResult.value?.currentMode).toBe("auto");
|
||||
|
||||
// Get available tools - all tools should be available in auto mode
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
const toolNames = tools.map((t) => t.function.name);
|
||||
|
||||
// All tools should be available in auto mode
|
||||
expect(toolNames).toContain('Bash');
|
||||
expect(toolNames).toContain('Read');
|
||||
expect(toolNames).toContain('Write');
|
||||
expect(toolNames).toContain('Edit');
|
||||
expect(toolNames).toContain("Bash");
|
||||
expect(toolNames).toContain("Read");
|
||||
expect(toolNames).toContain("Write");
|
||||
expect(toolNames).toContain("Edit");
|
||||
});
|
||||
|
||||
test('should respect explicit exclude in normal mode', async () => {
|
||||
test("should respect explicit exclude in normal mode", async () => {
|
||||
// Initialize services in normal mode with Read tool explicitly excluded
|
||||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'normal',
|
||||
exclude: ['Read']
|
||||
}
|
||||
mode: "normal",
|
||||
exclude: ["Read"],
|
||||
},
|
||||
});
|
||||
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
const toolNames = tools.map((t) => t.function.name);
|
||||
|
||||
// Read should be excluded due to explicit exclude
|
||||
expect(toolNames).not.toContain('Read');
|
||||
|
||||
expect(toolNames).not.toContain("Read");
|
||||
|
||||
// Other tools should still be available in normal mode
|
||||
expect(toolNames).toContain('Bash');
|
||||
expect(toolNames).toContain('Write');
|
||||
expect(toolNames).toContain('List');
|
||||
expect(toolNames).toContain('Search');
|
||||
expect(toolNames).toContain("Bash");
|
||||
expect(toolNames).toContain("Write");
|
||||
expect(toolNames).toContain("List");
|
||||
expect(toolNames).toContain("Search");
|
||||
});
|
||||
|
||||
test('plan mode should override allow flags (regression test for GitHub Actions issue)', async () => {
|
||||
test("plan mode should override allow flags (regression test for GitHub Actions issue)", async () => {
|
||||
// This test specifically addresses the original issue where plan mode
|
||||
// wasn't properly excluding tools despite being in plan mode
|
||||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'plan',
|
||||
allow: ['Write', 'Edit'] // These should be ignored in plan mode
|
||||
}
|
||||
mode: "plan",
|
||||
allow: ["Write", "Edit"], // These should be ignored in plan mode
|
||||
},
|
||||
});
|
||||
|
||||
const tools = await getAllTools();
|
||||
const toolNames = tools.map(t => t.function.name);
|
||||
const toolNames = tools.map((t) => t.function.name);
|
||||
|
||||
// Plan mode should still exclude write tools despite --allow flags
|
||||
// This tests that plan mode policies have absolute precedence
|
||||
expect(toolNames).not.toContain('Write');
|
||||
expect(toolNames).not.toContain('Edit');
|
||||
|
||||
expect(toolNames).not.toContain("Write");
|
||||
expect(toolNames).not.toContain("Edit");
|
||||
|
||||
// Bash should be available in plan mode
|
||||
expect(toolNames).toContain('Bash');
|
||||
|
||||
expect(toolNames).toContain("Bash");
|
||||
|
||||
// Read-only tools should be available
|
||||
expect(toolNames).toContain('Read');
|
||||
expect(toolNames).toContain('List');
|
||||
expect(toolNames).toContain('Search');
|
||||
expect(toolNames).toContain("Read");
|
||||
expect(toolNames).toContain("List");
|
||||
expect(toolNames).toContain("Search");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,10 +1,14 @@
|
|||
import { describe, expect, test, vi, beforeEach } from 'vitest';
|
||||
import { describe, expect, test, vi, beforeEach } from "vitest";
|
||||
|
||||
import { serviceContainer, SERVICE_NAMES, initializeServices } from './services/index.js';
|
||||
import { modeService } from './services/ModeService.js';
|
||||
import { getAllTools } from './streamChatResponse.js';
|
||||
import {
|
||||
serviceContainer,
|
||||
SERVICE_NAMES,
|
||||
initializeServices,
|
||||
} from "./services/index.js";
|
||||
import { modeService } from "./services/ModeService.js";
|
||||
import { getAllTools } from "./streamChatResponse.js";
|
||||
|
||||
describe('streamChatResponse - Mode Switch During Streaming', () => {
|
||||
describe("streamChatResponse - Mode Switch During Streaming", () => {
|
||||
beforeEach(async () => {
|
||||
// Clean up service container state before each test
|
||||
const services = [
|
||||
|
|
@ -13,10 +17,10 @@ describe('streamChatResponse - Mode Switch During Streaming', () => {
|
|||
SERVICE_NAMES.API_CLIENT,
|
||||
SERVICE_NAMES.CONFIG,
|
||||
SERVICE_NAMES.MODEL,
|
||||
SERVICE_NAMES.MCP
|
||||
SERVICE_NAMES.MCP,
|
||||
];
|
||||
|
||||
services.forEach(service => {
|
||||
|
||||
services.forEach((service) => {
|
||||
(serviceContainer as any).services.delete(service);
|
||||
(serviceContainer as any).factories.delete(service);
|
||||
(serviceContainer as any).dependencies.delete(service);
|
||||
|
|
@ -26,73 +30,73 @@ describe('streamChatResponse - Mode Switch During Streaming', () => {
|
|||
await initializeServices({
|
||||
headless: true,
|
||||
toolPermissionOverrides: {
|
||||
mode: 'normal'
|
||||
}
|
||||
mode: "normal",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('should recompute tools on each iteration to handle mode switches', async () => {
|
||||
test("should recompute tools on each iteration to handle mode switches", async () => {
|
||||
// Start in normal mode
|
||||
let tools = await getAllTools();
|
||||
let toolNames = tools.map(t => t.function.name);
|
||||
|
||||
let toolNames = tools.map((t) => t.function.name);
|
||||
|
||||
// Should include write tools in normal mode
|
||||
expect(toolNames).toContain('Write');
|
||||
expect(toolNames).toContain('Edit');
|
||||
expect(toolNames).toContain("Write");
|
||||
expect(toolNames).toContain("Edit");
|
||||
|
||||
// Switch to plan mode (simulating Shift+Tab during streaming)
|
||||
modeService.switchMode('plan');
|
||||
|
||||
modeService.switchMode("plan");
|
||||
|
||||
// Update the service container (this is what UserInput.tsx does)
|
||||
const updatedState = modeService.getToolPermissionService().getState();
|
||||
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
|
||||
|
||||
// Recompute tools - should now exclude write tools
|
||||
tools = await getAllTools();
|
||||
toolNames = tools.map(t => t.function.name);
|
||||
|
||||
toolNames = tools.map((t) => t.function.name);
|
||||
|
||||
// Should exclude write tools in plan mode
|
||||
expect(toolNames).not.toContain('Write');
|
||||
expect(toolNames).not.toContain('Edit');
|
||||
|
||||
expect(toolNames).not.toContain("Write");
|
||||
expect(toolNames).not.toContain("Edit");
|
||||
|
||||
// Should still include read-only tools
|
||||
expect(toolNames).toContain('Read');
|
||||
expect(toolNames).toContain('Bash');
|
||||
expect(toolNames).toContain('List');
|
||||
expect(toolNames).toContain("Read");
|
||||
expect(toolNames).toContain("Bash");
|
||||
expect(toolNames).toContain("List");
|
||||
});
|
||||
|
||||
test('getAllTools reflects current mode immediately', async () => {
|
||||
test("getAllTools reflects current mode immediately", async () => {
|
||||
// Start in normal mode
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
expect(modeService.getCurrentMode()).toBe("normal");
|
||||
let tools = await getAllTools();
|
||||
expect(tools.map(t => t.function.name)).toContain('Write');
|
||||
expect(tools.map((t) => t.function.name)).toContain("Write");
|
||||
|
||||
// Switch to plan mode
|
||||
modeService.switchMode('plan');
|
||||
modeService.switchMode("plan");
|
||||
let updatedState = modeService.getToolPermissionService().getState();
|
||||
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe("plan");
|
||||
|
||||
// getAllTools should immediately reflect the new mode
|
||||
tools = await getAllTools();
|
||||
expect(tools.map(t => t.function.name)).not.toContain('Write');
|
||||
expect(tools.map((t) => t.function.name)).not.toContain("Write");
|
||||
|
||||
// Switch to auto mode
|
||||
modeService.switchMode('auto');
|
||||
modeService.switchMode("auto");
|
||||
updatedState = modeService.getToolPermissionService().getState();
|
||||
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState);
|
||||
expect(modeService.getCurrentMode()).toBe('auto');
|
||||
|
||||
expect(modeService.getCurrentMode()).toBe("auto");
|
||||
|
||||
// getAllTools should immediately reflect auto mode (all tools allowed)
|
||||
tools = await getAllTools();
|
||||
expect(tools.map(t => t.function.name)).toContain('Write');
|
||||
expect(tools.map(t => t.function.name)).toContain('Edit');
|
||||
expect(tools.map(t => t.function.name)).toContain('Read');
|
||||
expect(tools.map((t) => t.function.name)).toContain("Write");
|
||||
expect(tools.map((t) => t.function.name)).toContain("Edit");
|
||||
expect(tools.map((t) => t.function.name)).toContain("Read");
|
||||
});
|
||||
|
||||
test('demonstrates the fix: no more stale tool lists', async () => {
|
||||
test("demonstrates the fix: no more stale tool lists", async () => {
|
||||
// This test demonstrates that the fix prevents the original race condition
|
||||
|
||||
|
||||
// Mock a multi-turn conversation scenario
|
||||
const mockLlmApi = {
|
||||
chatCompletions: {
|
||||
|
|
@ -102,52 +106,65 @@ describe('streamChatResponse - Mode Switch During Streaming', () => {
|
|||
[Symbol.asyncIterator]: async function* () {
|
||||
// First response - content only
|
||||
yield {
|
||||
choices: [{
|
||||
delta: { content: "I'll help you with that." },
|
||||
finish_reason: null
|
||||
}]
|
||||
choices: [
|
||||
{
|
||||
delta: { content: "I'll help you with that." },
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
// Second response - indicates tool calls coming
|
||||
yield {
|
||||
choices: [{
|
||||
delta: { tool_calls: [{
|
||||
index: 0,
|
||||
id: "call_1",
|
||||
function: { name: "Read", arguments: '{"filepath": "test.txt"}' }
|
||||
}] },
|
||||
finish_reason: null
|
||||
}]
|
||||
choices: [
|
||||
{
|
||||
delta: {
|
||||
tool_calls: [
|
||||
{
|
||||
index: 0,
|
||||
id: "call_1",
|
||||
function: {
|
||||
name: "Read",
|
||||
arguments: '{"filepath": "test.txt"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// Final response
|
||||
yield {
|
||||
choices: [{
|
||||
delta: {},
|
||||
finish_reason: "tool_calls"
|
||||
}]
|
||||
choices: [
|
||||
{
|
||||
delta: {},
|
||||
finish_reason: "tool_calls",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
})
|
||||
}
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const mockModel = {
|
||||
model: "gpt-4",
|
||||
defaultCompletionOptions: {}
|
||||
defaultCompletionOptions: {},
|
||||
};
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
|
||||
// Start in normal mode - tools should include Write
|
||||
const initialTools = await getAllTools();
|
||||
expect(initialTools.map(t => t.function.name)).toContain('Write');
|
||||
expect(initialTools.map((t) => t.function.name)).toContain("Write");
|
||||
|
||||
// During streaming, if mode switches, subsequent iterations should use new tools
|
||||
// This is now handled by recomputing tools on each iteration
|
||||
|
||||
|
||||
// The fix ensures that each call to processStreamingResponse gets fresh tools
|
||||
// based on the current mode, preventing the race condition
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import type {
|
|||
ChatCompletionChunk,
|
||||
ChatCompletionMessageParam,
|
||||
} from "openai/resources/chat/completions.mjs";
|
||||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { toolPermissionManager } from "./permissions/permissionManager.js";
|
||||
import {
|
||||
|
|
@ -18,7 +18,6 @@ import { searchCodeTool } from "./tools/searchCode.js";
|
|||
import { PreprocessedToolCall } from "./tools/types.js";
|
||||
import { writeFileTool } from "./tools/writeFile.js";
|
||||
|
||||
|
||||
// Test the chunk processing logic that was identified as buggy
|
||||
describe("processStreamingResponse - content preservation", () => {
|
||||
// Mock dependencies
|
||||
|
|
@ -49,7 +48,7 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
function toolCallChunk(
|
||||
id: string,
|
||||
name?: string,
|
||||
args?: string
|
||||
args?: string,
|
||||
): ChatCompletionChunk {
|
||||
return {
|
||||
id: "test",
|
||||
|
|
@ -83,7 +82,7 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
index: number,
|
||||
id?: string,
|
||||
name?: string,
|
||||
args?: string
|
||||
args?: string,
|
||||
): ChatCompletionChunk {
|
||||
const toolCall: any = {
|
||||
index,
|
||||
|
|
@ -185,27 +184,27 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
toolCallChunk(
|
||||
"toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
|
||||
undefined,
|
||||
'{"filepath'
|
||||
'{"filepath',
|
||||
),
|
||||
toolCallChunk(
|
||||
"toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
|
||||
undefined,
|
||||
'": "/Use'
|
||||
'": "/Use',
|
||||
),
|
||||
toolCallChunk(
|
||||
"toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
|
||||
undefined,
|
||||
"rs/nate/gh/c"
|
||||
"rs/nate/gh/c",
|
||||
),
|
||||
toolCallChunk(
|
||||
"toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
|
||||
undefined,
|
||||
"ontinuede"
|
||||
"ontinuede",
|
||||
),
|
||||
toolCallChunk(
|
||||
"toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A",
|
||||
undefined,
|
||||
"v/cli/README"
|
||||
"v/cli/README",
|
||||
),
|
||||
toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'),
|
||||
contentChunk(""),
|
||||
|
|
@ -228,7 +227,7 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
// Verify the tool call was assembled correctly
|
||||
expect(result.toolCalls[0].name).toBe("Read");
|
||||
expect(result.toolCalls[0].argumentsStr).toBe(
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -257,14 +256,14 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
0,
|
||||
"toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz",
|
||||
"Read",
|
||||
""
|
||||
"",
|
||||
),
|
||||
// Subsequent chunks only have index, no ID
|
||||
toolCallChunkWithIndex(
|
||||
0,
|
||||
undefined,
|
||||
undefined,
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
|
||||
),
|
||||
];
|
||||
|
||||
|
|
@ -277,19 +276,19 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
|
||||
// Content is captured correctly
|
||||
expect(result.content).toBe(
|
||||
"I'll read the README.md file for you and then say hello!"
|
||||
"I'll read the README.md file for you and then say hello!",
|
||||
);
|
||||
expect(result.toolCalls.length).toBe(1);
|
||||
|
||||
// Fixed: finalContent preserves content
|
||||
expect(result.finalContent).toBe(
|
||||
"I'll read the README.md file for you and then say hello!"
|
||||
"I'll read the README.md file for you and then say hello!",
|
||||
);
|
||||
|
||||
// Tool call arguments are preserved using index mapping
|
||||
expect(result.toolCalls[0].name).toBe("Read");
|
||||
expect(result.toolCalls[0].argumentsStr).toBe(
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -302,7 +301,7 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
0,
|
||||
"toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz",
|
||||
"Read",
|
||||
""
|
||||
"",
|
||||
),
|
||||
// Subsequent chunks fragment the JSON arguments
|
||||
toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'),
|
||||
|
|
@ -328,13 +327,13 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
// Fixed: Both issues are resolved
|
||||
// 1. Content is preserved
|
||||
expect(result.finalContent).toBe(
|
||||
"I'll read the README.md file for you and then say hello!"
|
||||
"I'll read the README.md file for you and then say hello!",
|
||||
);
|
||||
|
||||
// 2. Tool call arguments are assembled correctly
|
||||
expect(result.toolCalls[0].name).toBe("Read");
|
||||
expect(result.toolCalls[0].argumentsStr).toBe(
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'
|
||||
'{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -352,15 +351,15 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
prompt_tokens: 711,
|
||||
total_tokens: 807,
|
||||
prompt_tokens_details: {
|
||||
cached_tokens: 3353
|
||||
}
|
||||
}
|
||||
cached_tokens: 3353,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
chunks = [
|
||||
malformedChunk, // Put malformed chunk first to trigger the bug more clearly
|
||||
contentChunk("Hello "),
|
||||
contentChunk("world!")
|
||||
contentChunk("world!"),
|
||||
];
|
||||
|
||||
// This should not throw an error: "Cannot read properties of undefined (reading 'delta')"
|
||||
|
|
@ -440,7 +439,7 @@ describe.skip("preprocessStreamedToolCalls", () => {
|
|||
vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce(
|
||||
() => {
|
||||
throw new Error("Missing required argument");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const toolCalls: ToolCall[] = [
|
||||
|
|
@ -470,7 +469,7 @@ describe.skip("preprocessStreamedToolCalls", () => {
|
|||
expect(callbacks.onToolStart).toHaveBeenCalledWith("Read", {});
|
||||
expect(callbacks.onToolError).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Missing required argument"),
|
||||
"Read"
|
||||
"Read",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -492,7 +491,7 @@ describe.skip("preprocessStreamedToolCalls", () => {
|
|||
expect(preprocessedCalls).toHaveLength(0);
|
||||
expect(errorChatEntries).toHaveLength(1);
|
||||
expect(errorChatEntries[0].content).toContain(
|
||||
"Tool nonexistent_tool not found"
|
||||
"Tool nonexistent_tool not found",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -538,7 +537,7 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
|
||||
const { chatHistoryEntries } = await executeStreamedToolCalls(
|
||||
preprocessedCalls,
|
||||
callbacks
|
||||
callbacks,
|
||||
);
|
||||
|
||||
// Verify results
|
||||
|
|
@ -549,7 +548,7 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
});
|
||||
expect(callbacks.onToolResult).toHaveBeenCalledWith(
|
||||
"Tool execution successful",
|
||||
"Read"
|
||||
"Read",
|
||||
);
|
||||
expect(mockedExecuteToolCall).toHaveBeenCalledWith(preprocessedCalls[0]);
|
||||
});
|
||||
|
|
@ -583,7 +582,7 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
});
|
||||
}
|
||||
return toolPermissionManager;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Create preprocessed tool call
|
||||
|
|
@ -614,7 +613,7 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
|
||||
const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls(
|
||||
preprocessedCalls,
|
||||
callbacks
|
||||
callbacks,
|
||||
);
|
||||
|
||||
// Verify results
|
||||
|
|
@ -622,7 +621,7 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
expect(chatHistoryEntries).toHaveLength(2);
|
||||
expect(chatHistoryEntries[0].content).toBe("Permission denied by user");
|
||||
expect(chatHistoryEntries[1].content).toBe(
|
||||
"Cancelled due to previous tool rejection"
|
||||
"Cancelled due to previous tool rejection",
|
||||
);
|
||||
expect(callbacks.onToolStart).toHaveBeenCalledWith("Write", {
|
||||
filepath: "/test.txt",
|
||||
|
|
@ -630,13 +629,13 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
});
|
||||
expect(callbacks.onToolResult).toHaveBeenCalledWith(
|
||||
"Permission denied by user",
|
||||
"Write"
|
||||
"Write",
|
||||
);
|
||||
expect(callbacks.onToolPermissionRequest).toHaveBeenCalledWith(
|
||||
"Write",
|
||||
{ filepath: "/test.txt", content: "data" },
|
||||
"req_123",
|
||||
undefined
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -649,7 +648,7 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
|
||||
const toolsModule = await import("./tools/index.js");
|
||||
vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue(
|
||||
new Error("Execution failed")
|
||||
new Error("Execution failed"),
|
||||
);
|
||||
|
||||
// Create preprocessed tool call
|
||||
|
|
@ -671,13 +670,13 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
|
||||
const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls(
|
||||
preprocessedCalls,
|
||||
callbacks
|
||||
callbacks,
|
||||
);
|
||||
|
||||
// Verify results
|
||||
expect(chatHistoryEntries).toHaveLength(1);
|
||||
expect(chatHistoryEntries[0].content).toContain(
|
||||
"Error executing tool search_code"
|
||||
"Error executing tool search_code",
|
||||
);
|
||||
expect(chatHistoryEntries[0].content).toContain("Execution failed");
|
||||
expect(callbacks.onToolStart).toHaveBeenCalledWith("search_code", {
|
||||
|
|
@ -685,9 +684,9 @@ describe.skip("executeStreamedToolCalls", () => {
|
|||
});
|
||||
expect(callbacks.onToolError).toHaveBeenCalledWith(
|
||||
expect.stringContaining(
|
||||
"Error executing tool search_code: Execution failed"
|
||||
"Error executing tool search_code: Execution failed",
|
||||
),
|
||||
"search_code"
|
||||
"search_code",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -7,13 +7,15 @@ const { constructSystemMessage } = await import("./systemMessage.js");
|
|||
// Mock the service container to avoid "No factory registered for service 'config'" error
|
||||
vi.mock("./services/ServiceContainer.js", () => ({
|
||||
serviceContainer: {
|
||||
get: vi.fn().mockResolvedValue({ config: { rules: [] } })
|
||||
}
|
||||
get: vi.fn().mockResolvedValue({ config: { rules: [] } }),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock processRule to avoid file system operations in tests
|
||||
vi.mock("./args.js", () => ({
|
||||
processRule: vi.fn().mockImplementation((rule: string) => Promise.resolve(rule))
|
||||
processRule: vi
|
||||
.fn()
|
||||
.mockImplementation((rule: string) => Promise.resolve(rule)),
|
||||
}));
|
||||
|
||||
describe("constructSystemMessage", () => {
|
||||
|
|
@ -124,7 +126,9 @@ Rule 3: Third rule`;
|
|||
expect(result).toContain("You are an agent in the Continue CLI");
|
||||
expect(result).toContain("IMPORTANT: You are running in headless mode");
|
||||
expect(result).toContain("Provide ONLY your final answer");
|
||||
expect(result).toContain("Do not include explanations, reasoning, or additional commentary");
|
||||
expect(result).toContain(
|
||||
"Do not include explanations, reasoning, or additional commentary",
|
||||
);
|
||||
});
|
||||
|
||||
it("should not add headless mode instructions when headless is false", async () => {
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ describe("PosthogService Error Handling", () => {
|
|||
|
||||
// This should not throw an error
|
||||
await expect(
|
||||
posthogService.capture("test_event", { test: "data" })
|
||||
posthogService.capture("test_event", { test: "data" }),
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
// Verify the client capture was called
|
||||
|
|
@ -68,12 +68,12 @@ describe("PosthogService Error Handling", () => {
|
|||
it("should handle getClient errors gracefully", async () => {
|
||||
// Mock the getClient method to throw an error
|
||||
vi.spyOn(posthogService as any, "getClient").mockRejectedValue(
|
||||
new Error("Failed to initialize PostHog client")
|
||||
new Error("Failed to initialize PostHog client"),
|
||||
);
|
||||
|
||||
// This should not throw an error
|
||||
await expect(
|
||||
posthogService.capture("test_event", { test: "data" })
|
||||
posthogService.capture("test_event", { test: "data" }),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
|
|
@ -100,4 +100,4 @@ describe("PosthogService Error Handling", () => {
|
|||
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = originalEnv;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -26,7 +26,6 @@ import { loadAuthConfig, isAuthenticatedConfig } from "../auth/workos.js";
|
|||
|
||||
import { PosthogService } from "./posthogService.js";
|
||||
|
||||
|
||||
describe("PosthogService", () => {
|
||||
let tempDir: string;
|
||||
|
||||
|
|
@ -90,7 +89,9 @@ describe("PosthogService", () => {
|
|||
it("should use machine id when auth config is environment-based", () => {
|
||||
const mockMachineId = "test-machine-id";
|
||||
|
||||
vi.mocked(loadAuthConfig).mockReturnValue({ accessToken: "token" } as any);
|
||||
vi.mocked(loadAuthConfig).mockReturnValue({
|
||||
accessToken: "token",
|
||||
} as any);
|
||||
vi.mocked(isAuthenticatedConfig).mockReturnValue(false);
|
||||
vi.mocked(machineIdSync).mockReturnValue(mockMachineId);
|
||||
|
||||
|
|
@ -116,4 +117,4 @@ describe("PosthogService", () => {
|
|||
expect(service.isEnabled).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
describe('renderWithServices', () => {
|
||||
it('is tested through actual usage in component tests', () => {
|
||||
describe("renderWithServices", () => {
|
||||
it("is tested through actual usage in component tests", () => {
|
||||
// This utility is tested through its usage in real component tests
|
||||
// rather than in isolation due to module mocking complexities
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
import { createTestServiceContainer } from '../testServiceContainer.js';
|
||||
import { createTestServiceContainer } from "../testServiceContainer.js";
|
||||
|
||||
describe('TestServiceContainer', () => {
|
||||
describe("TestServiceContainer", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers();
|
||||
});
|
||||
it('should create a container with extended methods', () => {
|
||||
it("should create a container with extended methods", () => {
|
||||
const container = createTestServiceContainer();
|
||||
|
||||
|
||||
expect(container).toBeDefined();
|
||||
expect(container.resolveService).toBeDefined();
|
||||
expect(container.rejectService).toBeDefined();
|
||||
|
|
@ -16,108 +16,108 @@ describe('TestServiceContainer', () => {
|
|||
expect(container.waitForService).toBeDefined();
|
||||
});
|
||||
|
||||
it('should allow controlled service resolution', async () => {
|
||||
it("should allow controlled service resolution", async () => {
|
||||
const container = createTestServiceContainer();
|
||||
|
||||
|
||||
// Register a service
|
||||
container.register('test', () => Promise.resolve('should not resolve'));
|
||||
|
||||
container.register("test", () => Promise.resolve("should not resolve"));
|
||||
|
||||
// Load the service - this will create a pending promise
|
||||
const loadPromise = container.load('test');
|
||||
|
||||
const loadPromise = container.load("test");
|
||||
|
||||
// Service should be in loading state
|
||||
const state = container.getSync('test');
|
||||
expect(state.state).toBe('loading');
|
||||
|
||||
const state = container.getSync("test");
|
||||
expect(state.state).toBe("loading");
|
||||
|
||||
// Resolve the service with our controlled value
|
||||
container.resolveService('test', 'controlled value');
|
||||
|
||||
container.resolveService("test", "controlled value");
|
||||
|
||||
// Wait for the load promise to complete
|
||||
const loadedValue = await loadPromise;
|
||||
expect(loadedValue).toBe('controlled value');
|
||||
|
||||
expect(loadedValue).toBe("controlled value");
|
||||
|
||||
// Check the resolved value
|
||||
const result = container.getSync('test');
|
||||
expect(result.state).toBe('ready');
|
||||
expect(result.value).toBe('controlled value');
|
||||
const result = container.getSync("test");
|
||||
expect(result.state).toBe("ready");
|
||||
expect(result.value).toBe("controlled value");
|
||||
});
|
||||
|
||||
it('should allow controlled service rejection', async () => {
|
||||
it("should allow controlled service rejection", async () => {
|
||||
const container = createTestServiceContainer();
|
||||
|
||||
|
||||
// Register a service
|
||||
container.register('failing', () => Promise.resolve('should not resolve'));
|
||||
|
||||
container.register("failing", () => Promise.resolve("should not resolve"));
|
||||
|
||||
// Load the service and handle the rejection
|
||||
const loadPromise = container.load('failing');
|
||||
|
||||
const loadPromise = container.load("failing");
|
||||
|
||||
// Reject the service
|
||||
const error = new Error('Controlled failure');
|
||||
container.rejectService('failing', error);
|
||||
|
||||
const error = new Error("Controlled failure");
|
||||
container.rejectService("failing", error);
|
||||
|
||||
// Expect the load promise to reject
|
||||
await expect(loadPromise).rejects.toThrow('Controlled failure');
|
||||
|
||||
await expect(loadPromise).rejects.toThrow("Controlled failure");
|
||||
|
||||
// Check the error state
|
||||
const result = container.getSync('failing');
|
||||
expect(result.state).toBe('error');
|
||||
const result = container.getSync("failing");
|
||||
expect(result.state).toBe("error");
|
||||
expect(result.error).toBe(error);
|
||||
});
|
||||
|
||||
it('should wait for multiple services', async () => {
|
||||
it("should wait for multiple services", async () => {
|
||||
const container = createTestServiceContainer();
|
||||
|
||||
|
||||
// Register multiple services
|
||||
container.register('service1', () => Promise.resolve());
|
||||
container.register('service2', () => Promise.resolve());
|
||||
container.register('service3', () => Promise.resolve());
|
||||
|
||||
container.register("service1", () => Promise.resolve());
|
||||
container.register("service2", () => Promise.resolve());
|
||||
container.register("service3", () => Promise.resolve());
|
||||
|
||||
// Load all services
|
||||
container.load('service1');
|
||||
container.load('service2');
|
||||
container.load('service3');
|
||||
|
||||
container.load("service1");
|
||||
container.load("service2");
|
||||
container.load("service3");
|
||||
|
||||
// Resolve them in different order
|
||||
setTimeout(() => container.resolveService('service2', 'value2'), 10);
|
||||
setTimeout(() => container.resolveService('service1', 'value1'), 20);
|
||||
setTimeout(() => container.resolveService('service3', 'value3'), 30);
|
||||
|
||||
setTimeout(() => container.resolveService("service2", "value2"), 10);
|
||||
setTimeout(() => container.resolveService("service1", "value1"), 20);
|
||||
setTimeout(() => container.resolveService("service3", "value3"), 30);
|
||||
|
||||
// Wait for all to be ready
|
||||
await container.waitForReady('service1', 'service2', 'service3');
|
||||
|
||||
await container.waitForReady("service1", "service2", "service3");
|
||||
|
||||
// All should be ready
|
||||
expect(container.isReady('service1')).toBe(true);
|
||||
expect(container.isReady('service2')).toBe(true);
|
||||
expect(container.isReady('service3')).toBe(true);
|
||||
expect(container.isReady("service1")).toBe(true);
|
||||
expect(container.isReady("service2")).toBe(true);
|
||||
expect(container.isReady("service3")).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle pre-resolved services', () => {
|
||||
it("should handle pre-resolved services", () => {
|
||||
const container = createTestServiceContainer();
|
||||
|
||||
|
||||
// Register a service that resolves immediately
|
||||
container.register('immediate', () => Promise.resolve('immediate value'));
|
||||
|
||||
container.register("immediate", () => Promise.resolve("immediate value"));
|
||||
|
||||
// The factory should be replaced with our controlled factory
|
||||
// So it should not resolve immediately
|
||||
const state = container.getSync('immediate');
|
||||
expect(state.state).toBe('idle');
|
||||
const state = container.getSync("immediate");
|
||||
expect(state.state).toBe("idle");
|
||||
});
|
||||
|
||||
it('should support waitForService helper', async () => {
|
||||
it("should support waitForService helper", async () => {
|
||||
const container = createTestServiceContainer();
|
||||
|
||||
|
||||
// Register and load a service
|
||||
container.register('async', () => Promise.resolve());
|
||||
container.load('async');
|
||||
|
||||
container.register("async", () => Promise.resolve());
|
||||
container.load("async");
|
||||
|
||||
// Set up the wait before resolving
|
||||
const waitPromise = container.waitForService('async');
|
||||
|
||||
const waitPromise = container.waitForService("async");
|
||||
|
||||
// Resolve the service
|
||||
container.resolveService('async', 'async value');
|
||||
|
||||
container.resolveService("async", "async value");
|
||||
|
||||
// Wait should resolve with the value
|
||||
const value = await waitPromise;
|
||||
expect(value).toBe('async value');
|
||||
expect(value).toBe("async value");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ describe("editTool", () => {
|
|||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
`You must use the Read tool to read ${testFilePath} before editing it.`
|
||||
`You must use the Read tool to read ${testFilePath} before editing it.`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -66,7 +66,7 @@ describe("editTool", () => {
|
|||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
`File ${nonExistentFile} does not exist`
|
||||
`File ${nonExistentFile} does not exist`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -81,7 +81,7 @@ describe("editTool", () => {
|
|||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
"String not found in file: Not found"
|
||||
"String not found in file: Not found",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -96,7 +96,7 @@ describe("editTool", () => {
|
|||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
'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.'
|
||||
'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.',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -110,7 +110,7 @@ describe("editTool", () => {
|
|||
};
|
||||
|
||||
await expect(editTool.preprocess!(args)).rejects.toThrow(
|
||||
"old_string and new_string must be different"
|
||||
"old_string and new_string must be different",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -154,7 +154,7 @@ describe("editTool", () => {
|
|||
const result = await editTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Hello universe\nThis is a test file\nGoodbye universe"
|
||||
"Hello universe\nThis is a test file\nGoodbye universe",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -170,8 +170,14 @@ describe("editTool", () => {
|
|||
|
||||
const result = await editTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully edited ${testFilePath}\nDiff:\nmocked diff`);
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8");
|
||||
expect(result).toBe(
|
||||
`Successfully edited ${testFilePath}\nDiff:\nmocked diff`,
|
||||
);
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
testFilePath,
|
||||
newContent,
|
||||
"utf-8",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if file write fails", async () => {
|
||||
|
|
@ -186,7 +192,7 @@ describe("editTool", () => {
|
|||
};
|
||||
|
||||
await expect(editTool.run(args)).rejects.toThrow(
|
||||
`Error: failed to edit ${testFilePath}: Write failed`
|
||||
`Error: failed to edit ${testFilePath}: Write failed`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -205,4 +211,4 @@ describe("editTool", () => {
|
|||
expect(result.args.newContent).toContain("Hi there");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -22,10 +22,10 @@ describe("formatToolCall", () => {
|
|||
|
||||
it("should format tool name with relative path argument", () => {
|
||||
expect(formatToolCall("Write", { filepath: "README.md" })).toBe(
|
||||
"Write(README.md)"
|
||||
"Write(README.md)",
|
||||
);
|
||||
expect(formatToolCall("Read", { filepath: "src/index.ts" })).toBe(
|
||||
"Read(src/index.ts)"
|
||||
"Read(src/index.ts)",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -33,26 +33,24 @@ describe("formatToolCall", () => {
|
|||
expect(
|
||||
formatToolCall("Write", {
|
||||
filepath: "/Users/test/project/README.md",
|
||||
})
|
||||
}),
|
||||
).toBe("Write(README.md)");
|
||||
|
||||
expect(
|
||||
formatToolCall("Read", {
|
||||
filepath: "/Users/test/project/src/components/App.tsx",
|
||||
})
|
||||
}),
|
||||
).toBe("Read(src/components/App.tsx)");
|
||||
});
|
||||
|
||||
it("should handle absolute paths outside the project", () => {
|
||||
expect(
|
||||
formatToolCall("Write", { filepath: "/Users/other/file.txt" })
|
||||
).toBe("Write(../../other/file.txt)");
|
||||
expect(formatToolCall("Write", { filepath: "/Users/other/file.txt" })).toBe(
|
||||
"Write(../../other/file.txt)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle non-path arguments", () => {
|
||||
expect(formatToolCall("Search", { pattern: "TODO" })).toBe(
|
||||
"Search(TODO)"
|
||||
);
|
||||
expect(formatToolCall("Search", { pattern: "TODO" })).toBe("Search(TODO)");
|
||||
expect(formatToolCall("Search", { pattern: 123 })).toBe("Search(123)");
|
||||
});
|
||||
|
||||
|
|
@ -61,7 +59,7 @@ describe("formatToolCall", () => {
|
|||
formatToolCall("Write", {
|
||||
filepath: "test.txt",
|
||||
content: "Hello world",
|
||||
})
|
||||
}),
|
||||
).toBe("Write(test.txt)");
|
||||
});
|
||||
});
|
||||
|
|
@ -82,10 +80,10 @@ describe("formatToolArgument", () => {
|
|||
|
||||
it("should convert absolute paths to relative", () => {
|
||||
expect(formatToolArgument("/Users/test/project/README.md")).toBe(
|
||||
"README.md"
|
||||
"README.md",
|
||||
);
|
||||
expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe(
|
||||
"src/index.ts"
|
||||
"src/index.ts",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
`You must use the Read tool to read ${testFilePath} before editing it.`
|
||||
`You must use the Read tool to read ${testFilePath} before editing it.`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -74,7 +74,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
`File ${nonExistentFile} does not exist`
|
||||
`File ${nonExistentFile} does not exist`,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -87,7 +87,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"edits array is required and must contain at least one edit"
|
||||
"edits array is required and must contain at least one edit",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -105,7 +105,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"Edit 1: old_string is required"
|
||||
"Edit 1: old_string is required",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -123,7 +123,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"Edit 1: new_string is required"
|
||||
"Edit 1: new_string is required",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -141,7 +141,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
"Edit 1: old_string and new_string must be different"
|
||||
"Edit 1: old_string and new_string must be different",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -160,7 +160,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
'Edit 1: String not found in file: "Not found"'
|
||||
'Edit 1: String not found in file: "Not found"',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -179,7 +179,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
|
||||
'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.'
|
||||
'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.',
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -236,7 +236,7 @@ describe("multiEditTool", () => {
|
|||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Hi there\nThis is a test file\nSee you later"
|
||||
"Hi there\nThis is a test file\nSee you later",
|
||||
);
|
||||
expect(result.args.editCount).toBe(2);
|
||||
expect(result.preview?.[0]?.content).toContain("Will apply 2 edits");
|
||||
|
|
@ -259,7 +259,7 @@ describe("multiEditTool", () => {
|
|||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Hello universe\nThis is a test file\nGoodbye universe"
|
||||
"Hello universe\nThis is a test file\nGoodbye universe",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -309,7 +309,7 @@ describe("multiEditTool", () => {
|
|||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"Greetings cosmos\nThis is a test file\nGoodbye world"
|
||||
"Greetings cosmos\nThis is a test file\nGoodbye world",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -327,8 +327,14 @@ describe("multiEditTool", () => {
|
|||
|
||||
const result = await multiEditTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully edited ${testFilePath} with 1 edit\nDiff:\nmocked diff`);
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8");
|
||||
expect(result).toBe(
|
||||
`Successfully edited ${testFilePath} with 1 edit\nDiff:\nmocked diff`,
|
||||
);
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(
|
||||
testFilePath,
|
||||
newContent,
|
||||
"utf-8",
|
||||
);
|
||||
});
|
||||
|
||||
it("should return correct message for multiple edits", async () => {
|
||||
|
|
@ -342,7 +348,9 @@ describe("multiEditTool", () => {
|
|||
|
||||
const result = await multiEditTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully edited ${testFilePath} with 3 edits\nDiff:\nmocked diff`);
|
||||
expect(result).toBe(
|
||||
`Successfully edited ${testFilePath} with 3 edits\nDiff:\nmocked diff`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return correct message for new file creation", async () => {
|
||||
|
|
@ -356,7 +364,9 @@ describe("multiEditTool", () => {
|
|||
|
||||
const result = await multiEditTool.run(args);
|
||||
|
||||
expect(result).toBe(`Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`);
|
||||
expect(result).toBe(
|
||||
`Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`,
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error if file write fails", async () => {
|
||||
|
|
@ -373,7 +383,7 @@ describe("multiEditTool", () => {
|
|||
};
|
||||
|
||||
await expect(multiEditTool.run(args)).rejects.toThrow(
|
||||
`Error: failed to edit ${testFilePath}: Write failed`
|
||||
`Error: failed to edit ${testFilePath}: Write failed`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -397,7 +407,9 @@ describe("multiEditTool", () => {
|
|||
const result = await multiEditTool.preprocess!(args);
|
||||
|
||||
expect(result.args.file_path).toBe(absolutePath);
|
||||
expect(result.args.newContent).toBe("Hi there\nThis is a test file\nGoodbye world");
|
||||
expect(result.args.newContent).toBe(
|
||||
"Hi there\nThis is a test file\nGoodbye world",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle relative paths with subdirectories", async () => {
|
||||
|
|
@ -462,7 +474,7 @@ describe("multiEditTool", () => {
|
|||
it("should handle relative path for new file creation", async () => {
|
||||
const relativePath = "new-file.txt";
|
||||
const absolutePath = path.resolve(process.cwd(), relativePath);
|
||||
|
||||
|
||||
vi.mocked(fs.existsSync).mockImplementation((path) => {
|
||||
// Parent directory (cwd) exists, but file doesn't
|
||||
if (path === process.cwd()) return true;
|
||||
|
|
@ -506,4 +518,4 @@ describe("multiEditTool", () => {
|
|||
expect(result.args.newContent).toContain("Hi there");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import * as fs from "fs";
|
||||
|
||||
import * as diff from "diff";
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
// Mock fs module
|
||||
vi.mock("fs", async () => {
|
||||
|
|
@ -397,7 +397,7 @@ new line 2
|
|||
};
|
||||
|
||||
await expect(
|
||||
searchAndReplaceInFileTool.preprocess!(args)
|
||||
searchAndReplaceInFileTool.preprocess!(args),
|
||||
).rejects.toThrowError(/file .* does not exist/);
|
||||
});
|
||||
|
||||
|
|
@ -411,9 +411,9 @@ new line 2
|
|||
};
|
||||
|
||||
await expect(
|
||||
searchAndReplaceInFileTool.preprocess!(args)
|
||||
searchAndReplaceInFileTool.preprocess!(args),
|
||||
).rejects.toThrowError(
|
||||
"No complete search/replace blocks found in any diffs"
|
||||
"No complete search/replace blocks found in any diffs",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -433,7 +433,7 @@ replacement
|
|||
};
|
||||
|
||||
await expect(
|
||||
searchAndReplaceInFileTool.preprocess!(args)
|
||||
searchAndReplaceInFileTool.preprocess!(args),
|
||||
).rejects.toThrowError(/Search content not found in block 1:/);
|
||||
});
|
||||
|
||||
|
|
@ -461,7 +461,7 @@ modified line 3
|
|||
const result = await searchAndReplaceInFileTool.preprocess!(args);
|
||||
|
||||
expect(result.args.newContent).toBe(
|
||||
"modified line 1\nline 2\nmodified line 3\nline 4"
|
||||
"modified line 1\nline 2\nmodified line 3\nline 4",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@ import { runTerminalCommandTool } from "./runTerminalCommand.js";
|
|||
|
||||
describe("runTerminalCommandTool", () => {
|
||||
const TEST_TIMEOUT_MS = 1000; // 1 second for tests
|
||||
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.NODE_ENV = "test";
|
||||
process.env.TEST_TERMINAL_TIMEOUT = String(TEST_TIMEOUT_MS);
|
||||
});
|
||||
|
||||
|
|
@ -13,7 +13,9 @@ describe("runTerminalCommandTool", () => {
|
|||
});
|
||||
describe("basic command execution", () => {
|
||||
it("should execute simple echo command and return stdout", async () => {
|
||||
const result = await runTerminalCommandTool.run({ command: "echo 'hello world'" });
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'hello world'",
|
||||
});
|
||||
expect(result.trim()).toBe("hello world");
|
||||
});
|
||||
|
||||
|
|
@ -24,11 +26,11 @@ describe("runTerminalCommandTool", () => {
|
|||
|
||||
it("should execute directory listing command and return file listings", async () => {
|
||||
// Use a cross-platform command that works on both Unix and Windows
|
||||
const command = process.platform === 'win32' ? 'dir' : 'ls -la .';
|
||||
const command = process.platform === "win32" ? "dir" : "ls -la .";
|
||||
const result = await runTerminalCommandTool.run({ command });
|
||||
|
||||
|
||||
// On Windows, look for <DIR> entries, on Unix look for . and ..
|
||||
if (process.platform === 'win32') {
|
||||
if (process.platform === "win32") {
|
||||
expect(result).toContain(".");
|
||||
} else {
|
||||
expect(result).toContain(".");
|
||||
|
|
@ -37,99 +39,131 @@ describe("runTerminalCommandTool", () => {
|
|||
});
|
||||
|
||||
it("should handle commands with multiple arguments", async () => {
|
||||
const result = await runTerminalCommandTool.run({ command: "echo 'arg1' 'arg2' 'arg3'" });
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'arg1' 'arg2' 'arg3'",
|
||||
});
|
||||
expect(result.trim()).toBe("arg1 arg2 arg3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("error handling", () => {
|
||||
it("should reject with error message for non-existent commands", async () => {
|
||||
await expect(runTerminalCommandTool.run({ command: "nonexistentcommand12345" }))
|
||||
.rejects.toMatch(/Error \(exit code 127\):/);
|
||||
await expect(
|
||||
runTerminalCommandTool.run({ command: "nonexistentcommand12345" }),
|
||||
).rejects.toMatch(/Error \(exit code 127\):/);
|
||||
});
|
||||
|
||||
it("should handle commands with non-zero exit codes and stderr", async () => {
|
||||
await expect(runTerminalCommandTool.run({ command: "sh -c 'echo error >&2; exit 1'" }))
|
||||
.rejects.toMatch(/Error \(exit code 1\): error/);
|
||||
await expect(
|
||||
runTerminalCommandTool.run({
|
||||
command: "sh -c 'echo error >&2; exit 1'",
|
||||
}),
|
||||
).rejects.toMatch(/Error \(exit code 1\): error/);
|
||||
});
|
||||
|
||||
it("should resolve when commands have non-zero exit codes but no stderr", async () => {
|
||||
const result = await runTerminalCommandTool.run({ command: "sh -c 'exit 1'" });
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "sh -c 'exit 1'",
|
||||
});
|
||||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
it("should handle commands that write to stderr", async () => {
|
||||
const result = await runTerminalCommandTool.run({ command: "sh -c 'echo \"error message\" >&2; echo \"success\"'" });
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: 'sh -c \'echo "error message" >&2; echo "success"\'',
|
||||
});
|
||||
expect(result).toContain("success");
|
||||
expect(result).toContain("Stderr: error message");
|
||||
});
|
||||
});
|
||||
|
||||
describe("timeout functionality", () => {
|
||||
it("should timeout commands that produce no output for configured duration", async () => {
|
||||
// Create a command that sleeps longer than the timeout
|
||||
const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep 0.5s longer than timeout
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({ command: `sleep ${sleepDuration}` });
|
||||
const endTime = Date.now();
|
||||
const elapsed = endTime - startTime;
|
||||
|
||||
// Should timeout within a reasonable margin of the configured timeout
|
||||
expect(elapsed).toBeLessThan(TEST_TIMEOUT_MS + 200); // Allow 200ms margin
|
||||
expect(elapsed).toBeGreaterThan(TEST_TIMEOUT_MS - 100); // Allow 100ms margin
|
||||
expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`);
|
||||
}, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer
|
||||
it(
|
||||
"should timeout commands that produce no output for configured duration",
|
||||
async () => {
|
||||
// Create a command that sleeps longer than the timeout
|
||||
const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep 0.5s longer than timeout
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `sleep ${sleepDuration}`,
|
||||
});
|
||||
const endTime = Date.now();
|
||||
const elapsed = endTime - startTime;
|
||||
|
||||
it("should not timeout commands that continuously produce output", async () => {
|
||||
// Create a command that produces output at intervals shorter than timeout
|
||||
const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
|
||||
const iterations = 3;
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `for i in $(seq 1 ${iterations}); do echo "output $i"; sleep ${outputInterval}; done`
|
||||
});
|
||||
const endTime = Date.now();
|
||||
|
||||
// Should complete normally
|
||||
expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
|
||||
expect(result).toContain("output 1");
|
||||
expect(result).toContain(`output ${iterations}`);
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
}, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer
|
||||
// Should timeout within a reasonable margin of the configured timeout
|
||||
expect(elapsed).toBeLessThan(TEST_TIMEOUT_MS + 200); // Allow 200ms margin
|
||||
expect(elapsed).toBeGreaterThan(TEST_TIMEOUT_MS - 100); // Allow 100ms margin
|
||||
expect(result).toContain(
|
||||
`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`,
|
||||
);
|
||||
},
|
||||
TEST_TIMEOUT_MS + 2000,
|
||||
); // Set test timeout with buffer
|
||||
|
||||
it("should reset timeout when command produces stderr output", async () => {
|
||||
// Create a command that produces stderr output periodically
|
||||
const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
|
||||
const iterations = 3;
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `for i in $(seq 1 ${iterations}); do echo "error $i" >&2; sleep ${outputInterval}; done; echo 'done'`
|
||||
});
|
||||
const endTime = Date.now();
|
||||
|
||||
// Should complete normally
|
||||
expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
|
||||
expect(result).toContain("done");
|
||||
expect(result).toContain("Stderr: error 1");
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
}, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer
|
||||
it(
|
||||
"should not timeout commands that continuously produce output",
|
||||
async () => {
|
||||
// Create a command that produces output at intervals shorter than timeout
|
||||
const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
|
||||
const iterations = 3;
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `for i in $(seq 1 ${iterations}); do echo "output $i"; sleep ${outputInterval}; done`,
|
||||
});
|
||||
const endTime = Date.now();
|
||||
|
||||
it("should include partial output when timing out", async () => {
|
||||
// Create a command that produces some output then stops
|
||||
const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep longer than timeout
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `echo 'initial output'; sleep ${sleepDuration}`
|
||||
});
|
||||
|
||||
expect(result).toContain("initial output");
|
||||
expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`);
|
||||
}, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer
|
||||
// Should complete normally
|
||||
expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
|
||||
expect(result).toContain("output 1");
|
||||
expect(result).toContain(`output ${iterations}`);
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
},
|
||||
TEST_TIMEOUT_MS * 3,
|
||||
); // Set test timeout with buffer
|
||||
|
||||
it(
|
||||
"should reset timeout when command produces stderr output",
|
||||
async () => {
|
||||
// Create a command that produces stderr output periodically
|
||||
const outputInterval = TEST_TIMEOUT_MS / 1000 / 3; // Output 3 times within timeout period
|
||||
const iterations = 3;
|
||||
const startTime = Date.now();
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `for i in $(seq 1 ${iterations}); do echo "error $i" >&2; sleep ${outputInterval}; done; echo 'done'`,
|
||||
});
|
||||
const endTime = Date.now();
|
||||
|
||||
// Should complete normally
|
||||
expect(endTime - startTime).toBeLessThan(TEST_TIMEOUT_MS * 2);
|
||||
expect(result).toContain("done");
|
||||
expect(result).toContain("Stderr: error 1");
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
},
|
||||
TEST_TIMEOUT_MS * 3,
|
||||
); // Set test timeout with buffer
|
||||
|
||||
it(
|
||||
"should include partial output when timing out",
|
||||
async () => {
|
||||
// Create a command that produces some output then stops
|
||||
const sleepDuration = TEST_TIMEOUT_MS / 1000 + 0.5; // Sleep longer than timeout
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: `echo 'initial output'; sleep ${sleepDuration}`,
|
||||
});
|
||||
|
||||
expect(result).toContain("initial output");
|
||||
expect(result).toContain(
|
||||
`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`,
|
||||
);
|
||||
},
|
||||
TEST_TIMEOUT_MS + 2000,
|
||||
); // Set test timeout with buffer
|
||||
});
|
||||
|
||||
describe("output handling", () => {
|
||||
it("should preserve line breaks in output", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "printf 'line1\\nline2\\nline3'"
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "printf 'line1\\nline2\\nline3'",
|
||||
});
|
||||
expect(result).toContain("line1\nline2\nline3");
|
||||
});
|
||||
|
|
@ -141,13 +175,13 @@ describe("runTerminalCommandTool", () => {
|
|||
|
||||
it("should handle large output", async () => {
|
||||
// Generate a command that produces substantial output
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "seq 1 1000"
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "seq 1 1000",
|
||||
});
|
||||
expect(result).toContain("1\n");
|
||||
expect(result).toContain("1000");
|
||||
// Count lines to ensure all output is captured
|
||||
const lines = result.trim().split('\n');
|
||||
const lines = result.trim().split("\n");
|
||||
expect(lines).toHaveLength(1000);
|
||||
});
|
||||
});
|
||||
|
|
@ -159,24 +193,25 @@ describe("runTerminalCommandTool", () => {
|
|||
});
|
||||
|
||||
it("should handle commands with pipes", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'hello world' | wc -w"
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'hello world' | wc -w",
|
||||
});
|
||||
expect(result.trim()).toBe("2");
|
||||
});
|
||||
|
||||
it("should handle commands with redirections", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "echo 'test' > /tmp/test-file && cat /tmp/test-file && rm /tmp/test-file"
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command:
|
||||
"echo 'test' > /tmp/test-file && cat /tmp/test-file && rm /tmp/test-file",
|
||||
});
|
||||
expect(result.trim()).toBe("test");
|
||||
});
|
||||
|
||||
it("should handle commands with environment variables", async () => {
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "TEST_VAR='hello' sh -c 'echo $TEST_VAR'"
|
||||
const result = await runTerminalCommandTool.run({
|
||||
command: "TEST_VAR='hello' sh -c 'echo $TEST_VAR'",
|
||||
});
|
||||
expect(result.trim()).toBe("hello");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,51 +1,54 @@
|
|||
|
||||
// Since we want to test just the interface and not the internals,
|
||||
// let's create a simplified version of the run function to test the truncation logic
|
||||
describe("searchCodeTool", () => {
|
||||
// We'll test the functionality without mocking the dependencies
|
||||
// Instead, we'll focus on the core truncation logic by directly checking
|
||||
// Instead, we'll focus on the core truncation logic by directly checking
|
||||
// if truncation happens with large outputs
|
||||
|
||||
it("should include truncation message when output exceeds limit", () => {
|
||||
// Create a large sample output (more than 100 lines)
|
||||
const largeOutput = Array.from({ length: 150 }, (_, i) =>
|
||||
`file${i}.ts:${i}:const foo = 'bar';`
|
||||
const largeOutput = Array.from(
|
||||
{ length: 150 },
|
||||
(_, i) => `file${i}.ts:${i}:const foo = 'bar';`,
|
||||
).join("\n");
|
||||
|
||||
|
||||
// Check if the truncation logic is applied by the function
|
||||
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]`;
|
||||
|
||||
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]`;
|
||||
|
||||
// Verify the truncation message is included and only 100 lines are shown
|
||||
const lines = truncatedOutput.split('\n');
|
||||
const nonEmptyLines = lines.filter(line => line.trim() !== '');
|
||||
|
||||
const lines = truncatedOutput.split("\n");
|
||||
const nonEmptyLines = lines.filter((line) => line.trim() !== "");
|
||||
|
||||
// Count the content lines (excluding header and truncation message)
|
||||
const contentLines = nonEmptyLines.slice(1, -1);
|
||||
|
||||
|
||||
// Check that we have exactly 100 content lines
|
||||
expect(contentLines.length).toBe(100);
|
||||
|
||||
|
||||
// Check that the truncation message is present
|
||||
expect(truncatedOutput).toContain("[Results truncated: showing 100 of 150 matches]");
|
||||
expect(truncatedOutput).toContain(
|
||||
"[Results truncated: showing 100 of 150 matches]",
|
||||
);
|
||||
});
|
||||
|
||||
it("should not include truncation message when output is within limit", () => {
|
||||
// Create a sample output (less than 100 lines)
|
||||
const smallOutput = Array.from({ length: 50 }, (_, i) =>
|
||||
`file${i}.ts:${i}:const foo = 'bar';`
|
||||
const smallOutput = Array.from(
|
||||
{ length: 50 },
|
||||
(_, i) => `file${i}.ts:${i}:const foo = 'bar';`,
|
||||
).join("\n");
|
||||
|
||||
|
||||
// Format the output as the function would
|
||||
const output = `Search results for pattern "foo":\n\n${smallOutput}`;
|
||||
|
||||
|
||||
// Verify no truncation message is included
|
||||
expect(output).not.toContain("[Results truncated:");
|
||||
|
||||
|
||||
// Count the lines
|
||||
const lines = output.split('\n');
|
||||
const nonEmptyLines = lines.filter(line => line.trim() !== '');
|
||||
|
||||
const lines = output.split("\n");
|
||||
const nonEmptyLines = lines.filter((line) => line.trim() !== "");
|
||||
|
||||
// Check that we have the expected number of lines (header + 50 content lines)
|
||||
expect(nonEmptyLines.length).toBe(51);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -11,10 +11,12 @@ describe("ColoredDiff", () => {
|
|||
return "world";
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toContain("console.log(\"added line\")");
|
||||
expect(frame).toContain('console.log("added line")');
|
||||
expect(frame).toContain("+");
|
||||
});
|
||||
|
||||
|
|
@ -25,10 +27,12 @@ describe("ColoredDiff", () => {
|
|||
return "world";
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toContain("console.log(\"removed line\")");
|
||||
expect(frame).toContain('console.log("removed line")');
|
||||
expect(frame).toContain("-");
|
||||
});
|
||||
|
||||
|
|
@ -40,11 +44,13 @@ describe("ColoredDiff", () => {
|
|||
return "world";
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toContain("function hello()");
|
||||
expect(frame).toContain("return \"world\"");
|
||||
expect(frame).toContain('return "world"');
|
||||
});
|
||||
|
||||
it("renders word-level diffs for modified lines", () => {
|
||||
|
|
@ -54,18 +60,22 @@ describe("ColoredDiff", () => {
|
|||
+ return "new text";
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toContain("return \"");
|
||||
expect(frame).toContain("text\"");
|
||||
expect(frame).toContain('return "');
|
||||
expect(frame).toContain('text"');
|
||||
// Should show both old and new versions for word-level diff
|
||||
expect(frame).toContain("-");
|
||||
expect(frame).toContain("+");
|
||||
});
|
||||
|
||||
it("handles empty diff content", () => {
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent: "" }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent: "" }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toContain("No changes detected");
|
||||
|
|
@ -73,13 +83,17 @@ describe("ColoredDiff", () => {
|
|||
|
||||
it("truncates long diffs", () => {
|
||||
// Create a diff with more than 16 lines
|
||||
const lines = Array.from({ length: 20 }, (_, i) => `+ line ${i + 1}`).join('\n');
|
||||
const lines = Array.from({ length: 20 }, (_, i) => `+ line ${i + 1}`).join(
|
||||
"\n",
|
||||
);
|
||||
const diffContent = `@@ -1,1 +1,20 @@
|
||||
function hello() {
|
||||
${lines}
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toContain("more lines");
|
||||
|
|
@ -95,13 +109,15 @@ ${lines}
|
|||
return x + y;
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should render word-level diffs
|
||||
expect(frame).toContain("const x = \"");
|
||||
expect(frame).toContain("value\"");
|
||||
expect(frame).toContain("const y = \"another");
|
||||
expect(frame).toContain('const x = "');
|
||||
expect(frame).toContain('value"');
|
||||
expect(frame).toContain('const y = "another');
|
||||
});
|
||||
|
||||
it("handles single-type changes without word-level diffing", () => {
|
||||
|
|
@ -112,12 +128,14 @@ ${lines}
|
|||
return "world";
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should render as normal line additions, not word-level
|
||||
expect(frame).toContain("console.log(\"new line 1\")");
|
||||
expect(frame).toContain("console.log(\"new line 2\")");
|
||||
expect(frame).toContain('console.log("new line 1")');
|
||||
expect(frame).toContain('console.log("new line 2")');
|
||||
expect(frame).toContain("+");
|
||||
});
|
||||
|
||||
|
|
@ -128,7 +146,9 @@ ${lines}
|
|||
+ return "new text";
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Extract just the line numbers and content, ignoring colors/styling
|
||||
|
|
@ -136,8 +156,8 @@ ${lines}
|
|||
expect(frame).toContain("function hello()");
|
||||
expect(frame).toContain("- ");
|
||||
expect(frame).toContain("+ ");
|
||||
expect(frame).toContain("return \"");
|
||||
expect(frame).toContain("text\"");
|
||||
expect(frame).toContain('return "');
|
||||
expect(frame).toContain('text"');
|
||||
|
||||
// Verify we have both old and new text content
|
||||
// Word-level diff splits these into separate words
|
||||
|
|
@ -156,20 +176,22 @@ ${lines}
|
|||
+const y = "hello universe";
|
||||
const z = 3;`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
// All original text should be preserved
|
||||
expect(frame).toContain("const x = 1");
|
||||
expect(frame).toContain("const z = 3");
|
||||
|
||||
|
||||
// Both old and new versions should be shown
|
||||
// Word-level diff splits these into separate words
|
||||
expect(frame).toContain("hello");
|
||||
expect(frame).toContain("world");
|
||||
expect(frame).toContain("universe");
|
||||
expect(frame).toContain("const y = \"");
|
||||
|
||||
expect(frame).toContain('const y = "');
|
||||
|
||||
// Should have proper line prefixes
|
||||
expect(frame).toContain("- ");
|
||||
expect(frame).toContain("+ ");
|
||||
|
|
@ -184,7 +206,9 @@ ${lines}
|
|||
+ return result.data;
|
||||
}`;
|
||||
|
||||
const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent }));
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ColoredDiff, { diffContent }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Check that all unique content appears
|
||||
|
|
@ -204,4 +228,4 @@ ${lines}
|
|||
expect(frame).toContain("- ");
|
||||
expect(frame).toContain("+ ");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -132,13 +132,13 @@ describe("MarkdownRenderer", () => {
|
|||
|
||||
it("handles headings with multiple words", () => {
|
||||
const result = renderMarkdown(
|
||||
"# This is a long heading with multiple words"
|
||||
"# This is a long heading with multiple words",
|
||||
);
|
||||
expect(result.length).toBe(1);
|
||||
expect(React.isValidElement(result[0])).toBe(true);
|
||||
expect((result[0] as any).props.bold).toBe(true);
|
||||
expect((result[0] as any).props.children).toBe(
|
||||
"This is a long heading with multiple words"
|
||||
"This is a long heading with multiple words",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -183,7 +183,7 @@ describe("MarkdownRenderer", () => {
|
|||
|
||||
it("handles code blocks mixed with other formatting", () => {
|
||||
const result = renderMarkdown(
|
||||
"Here's some code:\n```\nfunction test() {\n return 42;\n}\n```\nAnd **bold** text"
|
||||
"Here's some code:\n```\nfunction test() {\n return 42;\n}\n```\nAnd **bold** text",
|
||||
);
|
||||
expect(result.length).toBe(5);
|
||||
expect(result[0]).toBe("Here's some code:\n");
|
||||
|
|
|
|||
|
|
@ -1,43 +1,49 @@
|
|||
import { render } from 'ink-testing-library';
|
||||
import React from 'react';
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { ModelCapabilityWarning } from './ModelCapabilityWarning.js';
|
||||
import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js";
|
||||
|
||||
describe('ModelCapabilityWarning', () => {
|
||||
test('should render warning message with model name', () => {
|
||||
describe("ModelCapabilityWarning", () => {
|
||||
test("should render warning message with model name", () => {
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ModelCapabilityWarning, { modelName: 'gpt-3-davinci' })
|
||||
React.createElement(ModelCapabilityWarning, {
|
||||
modelName: "gpt-3-davinci",
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
const frame = lastFrame();
|
||||
if (frame) {
|
||||
expect(frame).toContain('Model Capability Warning');
|
||||
expect(frame).toContain('gpt-3-davinci');
|
||||
expect(frame).toContain('is not recommended for use with cn due to limited reasoning and tool');
|
||||
expect(frame).toContain('calling capabilities');
|
||||
expect(frame).toContain("Model Capability Warning");
|
||||
expect(frame).toContain("gpt-3-davinci");
|
||||
expect(frame).toContain(
|
||||
"is not recommended for use with cn due to limited reasoning and tool",
|
||||
);
|
||||
expect(frame).toContain("calling capabilities");
|
||||
}
|
||||
});
|
||||
|
||||
test('should handle model names with slashes', () => {
|
||||
test("should handle model names with slashes", () => {
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ModelCapabilityWarning, { modelName: 'local/mistral-7b' })
|
||||
React.createElement(ModelCapabilityWarning, {
|
||||
modelName: "local/mistral-7b",
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
const frame = lastFrame();
|
||||
if (frame) {
|
||||
expect(frame).toContain('local/mistral-7b');
|
||||
expect(frame).toContain("local/mistral-7b");
|
||||
}
|
||||
});
|
||||
|
||||
test('should display warning icon', () => {
|
||||
test("should display warning icon", () => {
|
||||
const { lastFrame } = render(
|
||||
React.createElement(ModelCapabilityWarning, { modelName: 'test-model' })
|
||||
React.createElement(ModelCapabilityWarning, { modelName: "test-model" }),
|
||||
);
|
||||
|
||||
|
||||
const frame = lastFrame();
|
||||
if (frame) {
|
||||
expect(frame).toContain('⚠️');
|
||||
expect(frame).toContain("⚠️");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,10 +1,4 @@
|
|||
import {
|
||||
subDays,
|
||||
subMonths,
|
||||
subYears,
|
||||
startOfDay,
|
||||
addHours
|
||||
} from "date-fns";
|
||||
import { subDays, subMonths, subYears, startOfDay, addHours } from "date-fns";
|
||||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
|
@ -38,7 +32,7 @@ describe("SessionSelector", () => {
|
|||
firstUserMessage: "Today's session",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
id: "session-2",
|
||||
path: "/test/session-2.json",
|
||||
timestamp: yesterday,
|
||||
messageCount: 5,
|
||||
|
|
@ -47,7 +41,7 @@ describe("SessionSelector", () => {
|
|||
{
|
||||
id: "session-3",
|
||||
path: "/test/session-3.json",
|
||||
timestamp: thisWeek,
|
||||
timestamp: thisWeek,
|
||||
messageCount: 8,
|
||||
firstUserMessage: "This week's session",
|
||||
},
|
||||
|
|
@ -56,7 +50,7 @@ describe("SessionSelector", () => {
|
|||
path: "/test/session-4.json",
|
||||
timestamp: thisYear,
|
||||
messageCount: 12,
|
||||
firstUserMessage: "This year's session",
|
||||
firstUserMessage: "This year's session",
|
||||
},
|
||||
{
|
||||
id: "session-5",
|
||||
|
|
@ -68,35 +62,35 @@ describe("SessionSelector", () => {
|
|||
];
|
||||
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
<SessionSelector
|
||||
sessions={sessions}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
// Check that the output contains expected date formats
|
||||
expect(lastFrame()).toContain("2:00 PM"); // Today should show time
|
||||
expect(lastFrame()).toContain("yesterday"); // Yesterday should show "yesterday"
|
||||
|
||||
|
||||
// This week should show day name (we can't predict exact day without knowing when test runs)
|
||||
// but we can check it doesn't contain "ago" which was the old format
|
||||
expect(lastFrame()).not.toContain("days ago");
|
||||
|
||||
|
||||
// This year should show month/day format like "Oct 18" (no "ago")
|
||||
expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}/); // MMM d format
|
||||
|
||||
|
||||
// Last year should include the year
|
||||
expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}, \d{4}/); // MMM d, yyyy format
|
||||
});
|
||||
|
||||
it("handles empty sessions gracefully", () => {
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
<SessionSelector
|
||||
sessions={[]}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("No previous sessions found");
|
||||
|
|
@ -115,13 +109,13 @@ describe("SessionSelector", () => {
|
|||
];
|
||||
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
<SessionSelector
|
||||
sessions={sessions}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("(no messages)");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,186 +1,186 @@
|
|||
import { detectLanguage } from './SyntaxHighlighter.js';
|
||||
import { detectLanguage } from "./SyntaxHighlighter.js";
|
||||
|
||||
describe('detectLanguage', () => {
|
||||
it('should detect JavaScript from import statements', () => {
|
||||
describe("detectLanguage", () => {
|
||||
it("should detect JavaScript from import statements", () => {
|
||||
const code = `import React from 'react';`;
|
||||
expect(detectLanguage(code)).toBe('javascript');
|
||||
expect(detectLanguage(code)).toBe("javascript");
|
||||
});
|
||||
|
||||
it('should detect JavaScript from require statements', () => {
|
||||
it("should detect JavaScript from require statements", () => {
|
||||
const code = `const fs = require('fs');`;
|
||||
expect(detectLanguage(code)).toBe('javascript');
|
||||
expect(detectLanguage(code)).toBe("javascript");
|
||||
});
|
||||
|
||||
it('should detect JavaScript from function declarations', () => {
|
||||
it("should detect JavaScript from function declarations", () => {
|
||||
const code = `function myFunction() { return true; }`;
|
||||
expect(detectLanguage(code)).toBe('javascript');
|
||||
expect(detectLanguage(code)).toBe("javascript");
|
||||
});
|
||||
|
||||
it('should detect TypeScript from interface declarations', () => {
|
||||
it("should detect TypeScript from interface declarations", () => {
|
||||
const code = `interface User { name: string; }`;
|
||||
expect(detectLanguage(code)).toBe('typescript');
|
||||
expect(detectLanguage(code)).toBe("typescript");
|
||||
});
|
||||
|
||||
it('should detect TypeScript from type declarations', () => {
|
||||
it("should detect TypeScript from type declarations", () => {
|
||||
const code = `type UserType = { name: string; };`;
|
||||
expect(detectLanguage(code)).toBe('typescript');
|
||||
expect(detectLanguage(code)).toBe("typescript");
|
||||
});
|
||||
|
||||
it('should detect Python from function definitions', () => {
|
||||
it("should detect Python from function definitions", () => {
|
||||
const code = `def my_function():
|
||||
return True`;
|
||||
expect(detectLanguage(code)).toBe('python');
|
||||
expect(detectLanguage(code)).toBe("python");
|
||||
});
|
||||
|
||||
it('should detect Python from class definitions', () => {
|
||||
it("should detect Python from class definitions", () => {
|
||||
const code = `class MyClass:
|
||||
def __init__(self):
|
||||
pass`;
|
||||
expect(detectLanguage(code)).toBe('python');
|
||||
expect(detectLanguage(code)).toBe("python");
|
||||
});
|
||||
|
||||
it('should detect Java from public class declarations', () => {
|
||||
it("should detect Java from public class declarations", () => {
|
||||
const code = `public class MyClass {
|
||||
public static void main(String[] args) {
|
||||
}
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('java');
|
||||
expect(detectLanguage(code)).toBe("java");
|
||||
});
|
||||
|
||||
it('should detect C from include statements', () => {
|
||||
it("should detect C from include statements", () => {
|
||||
const code = `#include <stdio.h>
|
||||
int main() {
|
||||
return 0;
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('c');
|
||||
expect(detectLanguage(code)).toBe("c");
|
||||
});
|
||||
|
||||
it('should detect C++ from using namespace', () => {
|
||||
it("should detect C++ from using namespace", () => {
|
||||
const code = `using namespace std;
|
||||
int main() {
|
||||
return 0;
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('cpp');
|
||||
expect(detectLanguage(code)).toBe("cpp");
|
||||
});
|
||||
|
||||
it('should detect C# from using System', () => {
|
||||
it("should detect C# from using System", () => {
|
||||
const code = `using System;
|
||||
public class Program {
|
||||
public static void Main() {
|
||||
}
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('csharp');
|
||||
expect(detectLanguage(code)).toBe("csharp");
|
||||
});
|
||||
|
||||
it('should detect Go from package main', () => {
|
||||
it("should detect Go from package main", () => {
|
||||
const code = `package main
|
||||
import "fmt"
|
||||
func main() {
|
||||
fmt.Println("Hello, World!")
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('go');
|
||||
expect(detectLanguage(code)).toBe("go");
|
||||
});
|
||||
|
||||
it('should detect Rust from function syntax', () => {
|
||||
it("should detect Rust from function syntax", () => {
|
||||
const code = `fn main() {
|
||||
println!("Hello, World!");
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('rust');
|
||||
expect(detectLanguage(code)).toBe("rust");
|
||||
});
|
||||
|
||||
it('should detect PHP from opening tag', () => {
|
||||
it("should detect PHP from opening tag", () => {
|
||||
const code = `<?php
|
||||
echo "Hello, World!";
|
||||
?>`;
|
||||
expect(detectLanguage(code)).toBe('php');
|
||||
expect(detectLanguage(code)).toBe("php");
|
||||
});
|
||||
|
||||
it('should detect SQL from SELECT statements', () => {
|
||||
it("should detect SQL from SELECT statements", () => {
|
||||
const code = `SELECT * FROM users WHERE id = 1;`;
|
||||
expect(detectLanguage(code)).toBe('sql');
|
||||
expect(detectLanguage(code)).toBe("sql");
|
||||
});
|
||||
|
||||
it('should detect SQL with case insensitive matching', () => {
|
||||
it("should detect SQL with case insensitive matching", () => {
|
||||
const code = `select name from users where active = true;`;
|
||||
expect(detectLanguage(code)).toBe('sql');
|
||||
expect(detectLanguage(code)).toBe("sql");
|
||||
});
|
||||
|
||||
it('should detect JSON from object syntax', () => {
|
||||
it("should detect JSON from object syntax", () => {
|
||||
const code = `{
|
||||
"name": "John",
|
||||
"age": 30
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('json');
|
||||
expect(detectLanguage(code)).toBe("json");
|
||||
});
|
||||
|
||||
it('should detect bash from shebang', () => {
|
||||
it("should detect bash from shebang", () => {
|
||||
const code = `#!/bin/bash
|
||||
echo "Hello, World!"`;
|
||||
expect(detectLanguage(code)).toBe('bash');
|
||||
expect(detectLanguage(code)).toBe("bash");
|
||||
});
|
||||
|
||||
it('should detect HTML from DOCTYPE', () => {
|
||||
it("should detect HTML from DOCTYPE", () => {
|
||||
const code = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Test</title>
|
||||
</head>
|
||||
</html>`;
|
||||
expect(detectLanguage(code)).toBe('html');
|
||||
expect(detectLanguage(code)).toBe("html");
|
||||
});
|
||||
|
||||
it('should detect HTML from html tag', () => {
|
||||
it("should detect HTML from html tag", () => {
|
||||
const code = `<html>
|
||||
<body>
|
||||
<h1>Hello</h1>
|
||||
</body>
|
||||
</html>`;
|
||||
expect(detectLanguage(code)).toBe('html');
|
||||
expect(detectLanguage(code)).toBe("html");
|
||||
});
|
||||
|
||||
it('should detect CSS from media queries', () => {
|
||||
it("should detect CSS from media queries", () => {
|
||||
const code = `@media screen and (max-width: 600px) {
|
||||
body {
|
||||
font-size: 14px;
|
||||
}
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('css');
|
||||
expect(detectLanguage(code)).toBe("css");
|
||||
});
|
||||
|
||||
it('should detect Markdown from headers', () => {
|
||||
it("should detect Markdown from headers", () => {
|
||||
const code = `# Main Title
|
||||
## Subtitle
|
||||
This is some content.`;
|
||||
expect(detectLanguage(code)).toBe('markdown');
|
||||
expect(detectLanguage(code)).toBe("markdown");
|
||||
});
|
||||
|
||||
it('should default to javascript for unknown patterns', () => {
|
||||
it("should default to javascript for unknown patterns", () => {
|
||||
const code = `some random code that doesn't match any pattern`;
|
||||
expect(detectLanguage(code)).toBe('javascript');
|
||||
expect(detectLanguage(code)).toBe("javascript");
|
||||
});
|
||||
|
||||
it('should handle empty string', () => {
|
||||
it("should handle empty string", () => {
|
||||
const code = ``;
|
||||
expect(detectLanguage(code)).toBe('javascript');
|
||||
expect(detectLanguage(code)).toBe("javascript");
|
||||
});
|
||||
|
||||
it('should handle whitespace-only code', () => {
|
||||
it("should handle whitespace-only code", () => {
|
||||
const code = `
|
||||
|
||||
`;
|
||||
expect(detectLanguage(code)).toBe('javascript');
|
||||
expect(detectLanguage(code)).toBe("javascript");
|
||||
});
|
||||
|
||||
it('should match first pattern when multiple patterns could match', () => {
|
||||
it("should match first pattern when multiple patterns could match", () => {
|
||||
// This code has both import (JavaScript) and interface (TypeScript) patterns
|
||||
const code = `import { Component } from 'react';
|
||||
interface Props {
|
||||
name: string;
|
||||
}`;
|
||||
expect(detectLanguage(code)).toBe('javascript'); // JavaScript pattern comes first
|
||||
expect(detectLanguage(code)).toBe("javascript"); // JavaScript pattern comes first
|
||||
});
|
||||
|
||||
it('should handle multiline code correctly', () => {
|
||||
it("should handle multiline code correctly", () => {
|
||||
const code = `
|
||||
import React from 'react';
|
||||
|
||||
|
|
@ -188,20 +188,20 @@ interface Props {
|
|||
return <div>Hello</div>;
|
||||
};
|
||||
`;
|
||||
expect(detectLanguage(code)).toBe('javascript');
|
||||
expect(detectLanguage(code)).toBe("javascript");
|
||||
});
|
||||
|
||||
it('should detect patterns with leading whitespace', () => {
|
||||
it("should detect patterns with leading whitespace", () => {
|
||||
const code = ` def my_function():
|
||||
return True`;
|
||||
expect(detectLanguage(code)).toBe('python');
|
||||
expect(detectLanguage(code)).toBe("python");
|
||||
});
|
||||
|
||||
it('should handle YAML-like content but default to javascript', () => {
|
||||
|
||||
it("should handle YAML-like content but default to javascript", () => {
|
||||
// The actual implementation doesn't detect YAML from document separator
|
||||
const code = `---
|
||||
name: John
|
||||
age: 30`;
|
||||
expect(detectLanguage(code)).toBe('yaml');
|
||||
expect(detectLanguage(code)).toBe("yaml");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,4 +10,4 @@ describe("TUIChat Test Suite", () => {
|
|||
it("should import all test modules", () => {
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,345 +1,349 @@
|
|||
import { TextBuffer, COLLAPSE_SIZE, RAPID_INPUT_THRESHOLD } from './TextBuffer.js';
|
||||
import {
|
||||
TextBuffer,
|
||||
COLLAPSE_SIZE,
|
||||
RAPID_INPUT_THRESHOLD,
|
||||
} from "./TextBuffer.js";
|
||||
|
||||
describe('TextBuffer', () => {
|
||||
describe("TextBuffer", () => {
|
||||
let buffer: TextBuffer;
|
||||
|
||||
beforeEach(() => {
|
||||
buffer = new TextBuffer();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should initialize with empty text by default', () => {
|
||||
expect(buffer.text).toBe('');
|
||||
describe("constructor", () => {
|
||||
it("should initialize with empty text by default", () => {
|
||||
expect(buffer.text).toBe("");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should initialize with provided text', () => {
|
||||
const buffer = new TextBuffer('hello');
|
||||
expect(buffer.text).toBe('hello');
|
||||
it("should initialize with provided text", () => {
|
||||
const buffer = new TextBuffer("hello");
|
||||
expect(buffer.text).toBe("hello");
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setText', () => {
|
||||
it('should set text and maintain cursor position', () => {
|
||||
buffer.setText('hello');
|
||||
expect(buffer.text).toBe('hello');
|
||||
describe("setText", () => {
|
||||
it("should set text and maintain cursor position", () => {
|
||||
buffer.setText("hello");
|
||||
expect(buffer.text).toBe("hello");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should adjust cursor if it exceeds text length', () => {
|
||||
buffer.setText('hello world');
|
||||
it("should adjust cursor if it exceeds text length", () => {
|
||||
buffer.setText("hello world");
|
||||
buffer.setCursor(5);
|
||||
buffer.setText('hi');
|
||||
expect(buffer.text).toBe('hi');
|
||||
buffer.setText("hi");
|
||||
expect(buffer.text).toBe("hi");
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setCursor', () => {
|
||||
describe("setCursor", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello');
|
||||
buffer.setText("hello");
|
||||
});
|
||||
|
||||
it('should set cursor to valid position', () => {
|
||||
it("should set cursor to valid position", () => {
|
||||
buffer.setCursor(3);
|
||||
expect(buffer.cursor).toBe(3);
|
||||
});
|
||||
|
||||
it('should clamp cursor to minimum of 0', () => {
|
||||
it("should clamp cursor to minimum of 0", () => {
|
||||
buffer.setCursor(-5);
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should clamp cursor to maximum of text length', () => {
|
||||
it("should clamp cursor to maximum of text length", () => {
|
||||
buffer.setCursor(10);
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('insertText', () => {
|
||||
it('should insert text at cursor position', () => {
|
||||
buffer.setText('hello');
|
||||
describe("insertText", () => {
|
||||
it("should insert text at cursor position", () => {
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(2);
|
||||
buffer.insertText('XX');
|
||||
expect(buffer.text).toBe('heXXllo');
|
||||
buffer.insertText("XX");
|
||||
expect(buffer.text).toBe("heXXllo");
|
||||
expect(buffer.cursor).toBe(4);
|
||||
});
|
||||
|
||||
it('should insert text at beginning', () => {
|
||||
buffer.setText('world');
|
||||
it("should insert text at beginning", () => {
|
||||
buffer.setText("world");
|
||||
buffer.setCursor(0);
|
||||
buffer.insertText('hello ');
|
||||
expect(buffer.text).toBe('hello world');
|
||||
buffer.insertText("hello ");
|
||||
expect(buffer.text).toBe("hello world");
|
||||
expect(buffer.cursor).toBe(6);
|
||||
});
|
||||
|
||||
it('should insert text at end', () => {
|
||||
buffer.setText('hello');
|
||||
it("should insert text at end", () => {
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(5);
|
||||
buffer.insertText(' world');
|
||||
expect(buffer.text).toBe('hello world');
|
||||
buffer.insertText(" world");
|
||||
expect(buffer.text).toBe("hello world");
|
||||
expect(buffer.cursor).toBe(11);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteCharAt', () => {
|
||||
describe("deleteCharAt", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello');
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(3);
|
||||
});
|
||||
|
||||
it('should delete character at specified position', () => {
|
||||
it("should delete character at specified position", () => {
|
||||
buffer.deleteCharAt(2);
|
||||
expect(buffer.text).toBe('helo');
|
||||
expect(buffer.text).toBe("helo");
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('should not adjust cursor if deleting before cursor', () => {
|
||||
it("should not adjust cursor if deleting before cursor", () => {
|
||||
buffer.deleteCharAt(1);
|
||||
expect(buffer.text).toBe('hllo');
|
||||
expect(buffer.text).toBe("hllo");
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('should not delete if position is out of bounds', () => {
|
||||
it("should not delete if position is out of bounds", () => {
|
||||
buffer.deleteCharAt(10);
|
||||
expect(buffer.text).toBe('hello');
|
||||
expect(buffer.text).toBe("hello");
|
||||
expect(buffer.cursor).toBe(3);
|
||||
});
|
||||
|
||||
it('should not delete if position is negative', () => {
|
||||
it("should not delete if position is negative", () => {
|
||||
buffer.deleteCharAt(-1);
|
||||
expect(buffer.text).toBe('hello');
|
||||
expect(buffer.text).toBe("hello");
|
||||
expect(buffer.cursor).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteBackward', () => {
|
||||
describe("deleteBackward", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello');
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(3);
|
||||
});
|
||||
|
||||
it('should delete character before cursor', () => {
|
||||
it("should delete character before cursor", () => {
|
||||
buffer.deleteBackward();
|
||||
expect(buffer.text).toBe('helo');
|
||||
expect(buffer.text).toBe("helo");
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('should not delete if cursor is at beginning', () => {
|
||||
it("should not delete if cursor is at beginning", () => {
|
||||
buffer.setCursor(0);
|
||||
buffer.deleteBackward();
|
||||
expect(buffer.text).toBe('hello');
|
||||
expect(buffer.text).toBe("hello");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteForward', () => {
|
||||
describe("deleteForward", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello');
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(2);
|
||||
});
|
||||
|
||||
it('should delete character at cursor position', () => {
|
||||
it("should delete character at cursor position", () => {
|
||||
buffer.deleteForward();
|
||||
expect(buffer.text).toBe('helo');
|
||||
expect(buffer.text).toBe("helo");
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('should not delete if cursor is at end', () => {
|
||||
it("should not delete if cursor is at end", () => {
|
||||
buffer.setCursor(5);
|
||||
buffer.deleteForward();
|
||||
expect(buffer.text).toBe('hello');
|
||||
expect(buffer.text).toBe("hello");
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moveWordLeft', () => {
|
||||
describe("moveWordLeft", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello world test');
|
||||
buffer.setText("hello world test");
|
||||
});
|
||||
|
||||
it('should move to start of current word', () => {
|
||||
it("should move to start of current word", () => {
|
||||
buffer.setCursor(8); // middle of "world"
|
||||
buffer.moveWordLeft();
|
||||
expect(buffer.cursor).toBe(6); // start of "world"
|
||||
});
|
||||
|
||||
it('should move to start of previous word', () => {
|
||||
it("should move to start of previous word", () => {
|
||||
buffer.setCursor(6); // start of "world"
|
||||
buffer.moveWordLeft();
|
||||
expect(buffer.cursor).toBe(0); // start of "hello"
|
||||
});
|
||||
|
||||
it('should skip whitespace', () => {
|
||||
it("should skip whitespace", () => {
|
||||
buffer.setCursor(11); // space after "world"
|
||||
buffer.moveWordLeft();
|
||||
expect(buffer.cursor).toBe(6); // start of "world"
|
||||
});
|
||||
|
||||
it('should not move beyond beginning', () => {
|
||||
it("should not move beyond beginning", () => {
|
||||
buffer.setCursor(0);
|
||||
buffer.moveWordLeft();
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moveWordRight', () => {
|
||||
describe("moveWordRight", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello world test');
|
||||
buffer.setText("hello world test");
|
||||
});
|
||||
|
||||
it('should move to end of current word', () => {
|
||||
it("should move to end of current word", () => {
|
||||
buffer.setCursor(2); // middle of "hello"
|
||||
buffer.moveWordRight();
|
||||
expect(buffer.cursor).toBe(5); // end of "hello"
|
||||
});
|
||||
|
||||
it('should skip whitespace to next word', () => {
|
||||
it("should skip whitespace to next word", () => {
|
||||
buffer.setCursor(5); // end of "hello"
|
||||
buffer.moveWordRight();
|
||||
expect(buffer.cursor).toBe(11); // end of "world"
|
||||
});
|
||||
|
||||
it('should not move beyond end', () => {
|
||||
it("should not move beyond end", () => {
|
||||
buffer.setCursor(16);
|
||||
buffer.moveWordRight();
|
||||
expect(buffer.cursor).toBe(16);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteWordBackward', () => {
|
||||
describe("deleteWordBackward", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello world test');
|
||||
buffer.setText("hello world test");
|
||||
});
|
||||
|
||||
it('should delete from cursor to start of word', () => {
|
||||
it("should delete from cursor to start of word", () => {
|
||||
buffer.setCursor(8); // middle of "world"
|
||||
buffer.deleteWordBackward();
|
||||
expect(buffer.text).toBe('hello rld test');
|
||||
expect(buffer.text).toBe("hello rld test");
|
||||
expect(buffer.cursor).toBe(6);
|
||||
});
|
||||
|
||||
it('should delete entire previous word', () => {
|
||||
it("should delete entire previous word", () => {
|
||||
buffer.setCursor(6); // start of "world"
|
||||
buffer.deleteWordBackward();
|
||||
expect(buffer.text).toBe('world test');
|
||||
expect(buffer.text).toBe("world test");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteWordForward', () => {
|
||||
describe("deleteWordForward", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello world test');
|
||||
buffer.setText("hello world test");
|
||||
});
|
||||
|
||||
it('should delete from cursor to end of word', () => {
|
||||
it("should delete from cursor to end of word", () => {
|
||||
buffer.setCursor(2); // middle of "hello"
|
||||
buffer.deleteWordForward();
|
||||
expect(buffer.text).toBe('he world test');
|
||||
expect(buffer.text).toBe("he world test");
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('should delete to next word boundary', () => {
|
||||
it("should delete to next word boundary", () => {
|
||||
buffer.setCursor(5); // end of "hello"
|
||||
buffer.deleteWordForward();
|
||||
expect(buffer.text).toBe('hello test');
|
||||
expect(buffer.text).toBe("hello test");
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('movement methods', () => {
|
||||
describe("movement methods", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello');
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(2);
|
||||
});
|
||||
|
||||
it('should move to start', () => {
|
||||
it("should move to start", () => {
|
||||
buffer.moveToStart();
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should move to end', () => {
|
||||
it("should move to end", () => {
|
||||
buffer.moveToEnd();
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
|
||||
it('should move left', () => {
|
||||
it("should move left", () => {
|
||||
buffer.moveLeft();
|
||||
expect(buffer.cursor).toBe(1);
|
||||
});
|
||||
|
||||
it('should not move left beyond start', () => {
|
||||
it("should not move left beyond start", () => {
|
||||
buffer.setCursor(0);
|
||||
buffer.moveLeft();
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should move right', () => {
|
||||
it("should move right", () => {
|
||||
buffer.moveRight();
|
||||
expect(buffer.cursor).toBe(3);
|
||||
});
|
||||
|
||||
it('should not move right beyond end', () => {
|
||||
it("should not move right beyond end", () => {
|
||||
buffer.setCursor(5);
|
||||
buffer.moveRight();
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clear', () => {
|
||||
it('should clear text and reset cursor', () => {
|
||||
buffer.setText('hello world');
|
||||
describe("clear", () => {
|
||||
it("should clear text and reset cursor", () => {
|
||||
buffer.setText("hello world");
|
||||
buffer.setCursor(5);
|
||||
buffer.clear();
|
||||
expect(buffer.text).toBe('');
|
||||
expect(buffer.text).toBe("");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should clear paste map when clearing', () => {
|
||||
const longText = 'a'.repeat(COLLAPSE_SIZE + 1);
|
||||
it("should clear paste map when clearing", () => {
|
||||
const longText = "a".repeat(COLLAPSE_SIZE + 1);
|
||||
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
|
||||
expect(buffer.text).toBe('[Paste #1]');
|
||||
expect(buffer.text).toBe("[Paste #1]");
|
||||
|
||||
buffer.clear();
|
||||
expect(buffer.text).toBe('');
|
||||
expect(buffer.text).toBe("");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('paste collapse', () => {
|
||||
it('should not collapse short pasted text', () => {
|
||||
const shortText = 'hello world';
|
||||
describe("paste collapse", () => {
|
||||
it("should not collapse short pasted text", () => {
|
||||
const shortText = "hello world";
|
||||
buffer.handleInput(shortText, { ctrl: false, meta: false } as any);
|
||||
|
||||
expect(buffer.text).toBe('hello world');
|
||||
expect(buffer.text).toBe("hello world");
|
||||
});
|
||||
|
||||
it('should collapse long pasted text exceeding collapse threshold', () => {
|
||||
const longText = 'a'.repeat(COLLAPSE_SIZE + 1);
|
||||
it("should collapse long pasted text exceeding collapse threshold", () => {
|
||||
const longText = "a".repeat(COLLAPSE_SIZE + 1);
|
||||
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
|
||||
expect(buffer.text).toBe('[Paste #1]');
|
||||
expect(buffer.text).toBe("[Paste #1]");
|
||||
});
|
||||
|
||||
it('should count lines correctly in collapsed text', () => {
|
||||
const multiLineText = 'line1\nline2\nline3\n' + 'a'.repeat(COLLAPSE_SIZE);
|
||||
it("should count lines correctly in collapsed text", () => {
|
||||
const multiLineText = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
|
||||
buffer.handleInput(multiLineText, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
|
||||
expect(buffer.text).toBe('[Paste #1, 4 lines]');
|
||||
expect(buffer.text).toBe("[Paste #1, 4 lines]");
|
||||
});
|
||||
|
||||
it('should expand collapsed content on expandAllPasteBlocks', () => {
|
||||
const longText = 'hello ' + 'a'.repeat(COLLAPSE_SIZE);
|
||||
it("should expand collapsed content on expandAllPasteBlocks", () => {
|
||||
const longText = "hello " + "a".repeat(COLLAPSE_SIZE);
|
||||
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
|
||||
// Verify it was collapsed
|
||||
expect(buffer.text).toBe('[Paste #1]');
|
||||
expect(buffer.text).toBe("[Paste #1]");
|
||||
|
||||
// Expand it
|
||||
buffer.expandAllPasteBlocks();
|
||||
|
|
@ -348,37 +352,37 @@ describe('TextBuffer', () => {
|
|||
expect(buffer.text).toBe(longText);
|
||||
});
|
||||
|
||||
it('should handle typing before and after collapsed content', () => {
|
||||
buffer.setText('before ');
|
||||
it("should handle typing before and after collapsed content", () => {
|
||||
buffer.setText("before ");
|
||||
buffer.setCursor(7);
|
||||
|
||||
const longText = 'a'.repeat(COLLAPSE_SIZE + 1);
|
||||
const longText = "a".repeat(COLLAPSE_SIZE + 1);
|
||||
buffer.handleInput(longText, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
|
||||
expect(buffer.text).toBe('before [Paste #1]');
|
||||
expect(buffer.text).toBe("before [Paste #1]");
|
||||
|
||||
// Type after collapsed content
|
||||
buffer.insertText(' after');
|
||||
expect(buffer.text).toBe('before [Paste #1] after');
|
||||
buffer.insertText(" after");
|
||||
expect(buffer.text).toBe("before [Paste #1] after");
|
||||
|
||||
// Move cursor to beginning and type
|
||||
buffer.setCursor(0);
|
||||
buffer.insertText('start ');
|
||||
expect(buffer.text).toBe('start before [Paste #1] after');
|
||||
buffer.insertText("start ");
|
||||
expect(buffer.text).toBe("start before [Paste #1] after");
|
||||
});
|
||||
|
||||
it('should handle exactly collapse threshold without collapsing', () => {
|
||||
const exactText = 'a'.repeat(COLLAPSE_SIZE); // exactly at threshold
|
||||
it("should handle exactly collapse threshold without collapsing", () => {
|
||||
const exactText = "a".repeat(COLLAPSE_SIZE); // exactly at threshold
|
||||
buffer.handleInput(exactText, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput(); // This will go into rapid input mode due to size
|
||||
|
||||
expect(buffer.text).toBe(exactText); // Should not be collapsed
|
||||
});
|
||||
|
||||
it('should handle paste operations as single large inputs', () => {
|
||||
it("should handle paste operations as single large inputs", () => {
|
||||
// This simulates the most common paste scenario: a single large input
|
||||
const longText = 'x'.repeat(COLLAPSE_SIZE + 1);
|
||||
const longText = "x".repeat(COLLAPSE_SIZE + 1);
|
||||
|
||||
expect(longText.length).toBeGreaterThan(COLLAPSE_SIZE);
|
||||
|
||||
|
|
@ -386,87 +390,95 @@ describe('TextBuffer', () => {
|
|||
buffer.flushPendingInput();
|
||||
|
||||
// Should be collapsed
|
||||
expect(buffer.text).toBe('[Paste #1]');
|
||||
expect(buffer.text).toBe("[Paste #1]");
|
||||
});
|
||||
|
||||
it('should handle bracketed paste mode', () => {
|
||||
it("should handle bracketed paste mode", () => {
|
||||
// Simulate bracketed paste: start sequence, content, end sequence
|
||||
|
||||
// Start paste mode
|
||||
buffer.handleInput('\u001b[200~', {} as any);
|
||||
buffer.handleInput("\u001b[200~", {} as any);
|
||||
expect(buffer.isInPasteMode()).toBe(true);
|
||||
|
||||
// Add some content (in chunks like real paste)
|
||||
const chunks = ['Hello ', 'world! ', 'This is a long piece of text. '.repeat(30)];
|
||||
const totalContent = chunks.join('');
|
||||
const chunks = [
|
||||
"Hello ",
|
||||
"world! ",
|
||||
"This is a long piece of text. ".repeat(30),
|
||||
];
|
||||
const totalContent = chunks.join("");
|
||||
|
||||
chunks.forEach(chunk => {
|
||||
chunks.forEach((chunk) => {
|
||||
buffer.handleInput(chunk, { ctrl: false, meta: false } as any);
|
||||
});
|
||||
|
||||
// Text should NOT be visible during paste mode (to avoid visual bugs)
|
||||
expect(buffer.text).toBe('');
|
||||
expect(buffer.text).toBe("");
|
||||
|
||||
// End paste mode
|
||||
buffer.handleInput('\u001b[201~', {} as any);
|
||||
buffer.handleInput("\u001b[201~", {} as any);
|
||||
expect(buffer.isInPasteMode()).toBe(false);
|
||||
|
||||
// Now should be collapsed if > COLLAPSE_SIZE
|
||||
if (totalContent.length > COLLAPSE_SIZE) {
|
||||
expect(buffer.text).toBe('[Paste #1]');
|
||||
expect(buffer.text).toBe("[Paste #1]");
|
||||
}
|
||||
});
|
||||
|
||||
it('should not collapse short bracketed paste content', () => {
|
||||
it("should not collapse short bracketed paste content", () => {
|
||||
// Start paste mode
|
||||
buffer.handleInput('\u001b[200~', {} as any);
|
||||
buffer.handleInput("\u001b[200~", {} as any);
|
||||
|
||||
// Add short content
|
||||
const shortContent = 'Hello world!';
|
||||
const shortContent = "Hello world!";
|
||||
buffer.handleInput(shortContent, { ctrl: false, meta: false } as any);
|
||||
|
||||
// End paste mode
|
||||
buffer.handleInput('\u001b[201~', {} as any);
|
||||
buffer.handleInput("\u001b[201~", {} as any);
|
||||
|
||||
// Should not be collapsed
|
||||
expect(buffer.text).toBe(shortContent);
|
||||
});
|
||||
|
||||
it('should normalize line endings when expanding', () => {
|
||||
const textWithCarriageReturns = 'line1\r\nline2\rline3\n' + 'a'.repeat(COLLAPSE_SIZE);
|
||||
buffer.handleInput(textWithCarriageReturns, { ctrl: false, meta: false } as any);
|
||||
it("should normalize line endings when expanding", () => {
|
||||
const textWithCarriageReturns =
|
||||
"line1\r\nline2\rline3\n" + "a".repeat(COLLAPSE_SIZE);
|
||||
buffer.handleInput(textWithCarriageReturns, {
|
||||
ctrl: false,
|
||||
meta: false,
|
||||
} as any);
|
||||
buffer.flushPendingInput();
|
||||
|
||||
expect(buffer.text).toBe('[Paste #1, 4 lines]');
|
||||
expect(buffer.text).toBe("[Paste #1, 4 lines]");
|
||||
|
||||
buffer.expandAllPasteBlocks();
|
||||
|
||||
// Should have normalized line endings
|
||||
const expected = 'line1\nline2\nline3\n' + 'a'.repeat(COLLAPSE_SIZE);
|
||||
const expected = "line1\nline2\nline3\n" + "a".repeat(COLLAPSE_SIZE);
|
||||
expect(buffer.text).toBe(expected);
|
||||
});
|
||||
|
||||
it('should increment paste counter for multiple pastes', () => {
|
||||
const longText1 = 'a'.repeat(COLLAPSE_SIZE + 1);
|
||||
const longText2 = 'b'.repeat(COLLAPSE_SIZE + 1);
|
||||
it("should increment paste counter for multiple pastes", () => {
|
||||
const longText1 = "a".repeat(COLLAPSE_SIZE + 1);
|
||||
const longText2 = "b".repeat(COLLAPSE_SIZE + 1);
|
||||
|
||||
buffer.handleInput(longText1, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
expect(buffer.text).toBe('[Paste #1]');
|
||||
expect(buffer.text).toBe("[Paste #1]");
|
||||
|
||||
buffer.insertText(' ');
|
||||
buffer.insertText(" ");
|
||||
buffer.handleInput(longText2, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
expect(buffer.text).toBe('[Paste #1] [Paste #2]');
|
||||
expect(buffer.text).toBe("[Paste #1] [Paste #2]");
|
||||
});
|
||||
|
||||
it('should detect rapid input above threshold', () => {
|
||||
it("should detect rapid input above threshold", () => {
|
||||
// Test that input above RAPID_INPUT_THRESHOLD triggers rapid input detection
|
||||
const rapidText = 'x'.repeat(RAPID_INPUT_THRESHOLD + 1);
|
||||
const rapidText = "x".repeat(RAPID_INPUT_THRESHOLD + 1);
|
||||
buffer.handleInput(rapidText, { ctrl: false, meta: false } as any);
|
||||
|
||||
// Should go into rapid input buffer (not displayed yet)
|
||||
expect(buffer.text).toBe('');
|
||||
expect(buffer.text).toBe("");
|
||||
expect(buffer.isInRapidInputMode()).toBe(true);
|
||||
|
||||
// Flush to finalize
|
||||
|
|
@ -476,23 +488,23 @@ describe('TextBuffer', () => {
|
|||
expect(buffer.text).toBe(rapidText);
|
||||
});
|
||||
|
||||
it('should combine split paste chunks', () => {
|
||||
it("should combine split paste chunks", () => {
|
||||
// Simulate macOS Terminal splitting paste
|
||||
const firstChunk = 'a'.repeat(COLLAPSE_SIZE + 200); // Large first chunk
|
||||
const firstChunk = "a".repeat(COLLAPSE_SIZE + 200); // Large first chunk
|
||||
buffer.handleInput(firstChunk, { ctrl: false, meta: false } as any);
|
||||
|
||||
// First chunk goes into rapid input mode - no placeholder yet
|
||||
expect(buffer.text).toBe('');
|
||||
expect(buffer.text).toBe("");
|
||||
|
||||
// Second chunk should be combined with the first (needs to be > 50 chars)
|
||||
const secondChunk = 'b'.repeat(100); // Large enough to trigger split paste detection
|
||||
const secondChunk = "b".repeat(100); // Large enough to trigger split paste detection
|
||||
buffer.handleInput(secondChunk, { ctrl: false, meta: false } as any);
|
||||
|
||||
// Flush to finalize the rapid input synchronously
|
||||
buffer.flushPendingInput();
|
||||
|
||||
// Should show only one placeholder with combined content
|
||||
expect(buffer.text).toBe('[Paste #1]');
|
||||
expect(buffer.text).toBe("[Paste #1]");
|
||||
|
||||
// Verify the combined content is stored correctly
|
||||
buffer.expandAllPasteBlocks();
|
||||
|
|
@ -500,148 +512,155 @@ describe('TextBuffer', () => {
|
|||
expect(buffer.text).toBe(expectedContent);
|
||||
});
|
||||
|
||||
it('should expand paste blocks on submission (simulating Enter key behavior)', () => {
|
||||
it("should expand paste blocks on submission (simulating Enter key behavior)", () => {
|
||||
// Add some text before the paste
|
||||
buffer.insertText('Command: ');
|
||||
|
||||
buffer.insertText("Command: ");
|
||||
|
||||
// Add a large paste that gets collapsed
|
||||
const pastedCode = 'function example() {\n console.log("hello");\n ' + 'x'.repeat(COLLAPSE_SIZE);
|
||||
const pastedCode =
|
||||
'function example() {\n console.log("hello");\n ' +
|
||||
"x".repeat(COLLAPSE_SIZE);
|
||||
buffer.handleInput(pastedCode, { ctrl: false, meta: false } as any);
|
||||
buffer.flushPendingInput();
|
||||
|
||||
|
||||
// Verify it's collapsed
|
||||
expect(buffer.text).toBe('Command: [Paste #1, 3 lines]');
|
||||
|
||||
expect(buffer.text).toBe("Command: [Paste #1, 3 lines]");
|
||||
|
||||
// Simulate what happens when user presses Enter - UserInput calls expandAllPasteBlocks()
|
||||
buffer.expandAllPasteBlocks();
|
||||
|
||||
|
||||
// Should now show the full content with normalized line endings
|
||||
const expectedFullText = 'Command: function example() {\n console.log("hello");\n ' + 'x'.repeat(COLLAPSE_SIZE);
|
||||
const expectedFullText =
|
||||
'Command: function example() {\n console.log("hello");\n ' +
|
||||
"x".repeat(COLLAPSE_SIZE);
|
||||
expect(buffer.text).toBe(expectedFullText);
|
||||
|
||||
|
||||
// Verify paste map is cleared after expansion
|
||||
buffer.expandAllPasteBlocks(); // Should be no-op now
|
||||
expect(buffer.text).toBe(expectedFullText); // Should remain the same
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleInput', () => {
|
||||
describe("handleInput", () => {
|
||||
beforeEach(() => {
|
||||
buffer.setText('hello');
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(2);
|
||||
});
|
||||
|
||||
it('should handle regular character input', () => {
|
||||
const result = buffer.handleInput('X', {} as any);
|
||||
it("should handle regular character input", () => {
|
||||
const result = buffer.handleInput("X", {} as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe('heXllo');
|
||||
expect(buffer.text).toBe("heXllo");
|
||||
expect(buffer.cursor).toBe(3);
|
||||
});
|
||||
|
||||
it('should handle multi-character input (paste)', () => {
|
||||
const result = buffer.handleInput('XYZ', {} as any);
|
||||
it("should handle multi-character input (paste)", () => {
|
||||
const result = buffer.handleInput("XYZ", {} as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe('heXYZllo');
|
||||
expect(buffer.text).toBe("heXYZllo");
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
|
||||
it('should handle ctrl+a (move to start)', () => {
|
||||
const result = buffer.handleInput('a', { ctrl: true } as any);
|
||||
it("should handle ctrl+a (move to start)", () => {
|
||||
const result = buffer.handleInput("a", { ctrl: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle ctrl+e (move to end)', () => {
|
||||
const result = buffer.handleInput('e', { ctrl: true } as any);
|
||||
it("should handle ctrl+e (move to end)", () => {
|
||||
const result = buffer.handleInput("e", { ctrl: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.cursor).toBe(5);
|
||||
});
|
||||
|
||||
it('should handle ctrl+u (delete to start)', () => {
|
||||
const result = buffer.handleInput('u', { ctrl: true } as any);
|
||||
it("should handle ctrl+u (delete to start)", () => {
|
||||
const result = buffer.handleInput("u", { ctrl: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe('llo');
|
||||
expect(buffer.text).toBe("llo");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle ctrl+k (delete to end)', () => {
|
||||
const result = buffer.handleInput('k', { ctrl: true } as any);
|
||||
it("should handle ctrl+k (delete to end)", () => {
|
||||
const result = buffer.handleInput("k", { ctrl: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe('he');
|
||||
expect(buffer.text).toBe("he");
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('should handle arrow keys', () => {
|
||||
let result = buffer.handleInput('', { leftArrow: true } as any);
|
||||
it("should handle arrow keys", () => {
|
||||
let result = buffer.handleInput("", { leftArrow: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.cursor).toBe(1);
|
||||
|
||||
result = buffer.handleInput('', { rightArrow: true } as any);
|
||||
result = buffer.handleInput("", { rightArrow: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('should handle delete key', () => {
|
||||
const result = buffer.handleInput('', { delete: true } as any);
|
||||
it("should handle delete key", () => {
|
||||
const result = buffer.handleInput("", { delete: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe('hllo');
|
||||
expect(buffer.text).toBe("hllo");
|
||||
expect(buffer.cursor).toBe(1);
|
||||
});
|
||||
|
||||
it('should handle backspace key', () => {
|
||||
const result = buffer.handleInput('', { backspace: true } as any);
|
||||
it("should handle backspace key", () => {
|
||||
const result = buffer.handleInput("", { backspace: true } as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.text).toBe('hllo');
|
||||
expect(buffer.text).toBe("hllo");
|
||||
expect(buffer.cursor).toBe(1);
|
||||
});
|
||||
|
||||
it('should handle meta key combinations', () => {
|
||||
const result = buffer.handleInput('', { meta: true, leftArrow: true } as any);
|
||||
it("should handle meta key combinations", () => {
|
||||
const result = buffer.handleInput("", {
|
||||
meta: true,
|
||||
leftArrow: true,
|
||||
} as any);
|
||||
expect(result).toBe(true);
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle option key sequences', () => {
|
||||
const result = buffer.handleInput('\u001b\u007f', {} as any);
|
||||
it("should handle option key sequences", () => {
|
||||
const result = buffer.handleInput("\u001b\u007f", {} as any);
|
||||
expect(result).toBe(true);
|
||||
// Should delete word backward
|
||||
expect(buffer.text).toBe('llo');
|
||||
expect(buffer.text).toBe("llo");
|
||||
expect(buffer.cursor).toBe(0);
|
||||
});
|
||||
|
||||
it('should return false for unhandled input', () => {
|
||||
const result = buffer.handleInput('', { ctrl: true } as any);
|
||||
it("should return false for unhandled input", () => {
|
||||
const result = buffer.handleInput("", { ctrl: true } as any);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderWithCursor', () => {
|
||||
it('should return text and cursor position', () => {
|
||||
buffer.setText('hello');
|
||||
describe("renderWithCursor", () => {
|
||||
it("should return text and cursor position", () => {
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(2);
|
||||
const result = buffer.renderWithCursor();
|
||||
expect(result).toEqual({
|
||||
text: 'hello',
|
||||
cursorPosition: 2
|
||||
text: "hello",
|
||||
cursorPosition: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return placeholder when text is empty', () => {
|
||||
const result = buffer.renderWithCursor('Enter text...');
|
||||
it("should return placeholder when text is empty", () => {
|
||||
const result = buffer.renderWithCursor("Enter text...");
|
||||
expect(result).toEqual({
|
||||
text: 'Enter text...',
|
||||
cursorPosition: 0
|
||||
text: "Enter text...",
|
||||
cursorPosition: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('should return actual text even when placeholder is provided', () => {
|
||||
buffer.setText('hello');
|
||||
it("should return actual text even when placeholder is provided", () => {
|
||||
buffer.setText("hello");
|
||||
buffer.setCursor(2);
|
||||
const result = buffer.renderWithCursor('Enter text...');
|
||||
const result = buffer.renderWithCursor("Enter text...");
|
||||
expect(result).toEqual({
|
||||
text: 'hello',
|
||||
cursorPosition: 2
|
||||
text: "hello",
|
||||
cursorPosition: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -119,4 +119,4 @@ describe("UpdateNotification", () => {
|
|||
expect(mockVersionModule.getLatestVersion).toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,34 +1,34 @@
|
|||
import { describe, expect, it, beforeEach } from 'vitest';
|
||||
import { describe, expect, it, beforeEach } from "vitest";
|
||||
|
||||
import { modeService } from '../services/ModeService.js';
|
||||
import { modeService } from "../services/ModeService.js";
|
||||
|
||||
describe('UserInput Keyboard Shortcuts', () => {
|
||||
describe("UserInput Keyboard Shortcuts", () => {
|
||||
beforeEach(() => {
|
||||
// Reset to normal mode for each test
|
||||
modeService.initialize({});
|
||||
});
|
||||
|
||||
describe('mode cycling logic', () => {
|
||||
it('should cycle through modes in correct order', () => {
|
||||
describe("mode cycling logic", () => {
|
||||
it("should cycle through modes in correct order", () => {
|
||||
// Initially should be normal mode
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
expect(modeService.getCurrentMode()).toBe("normal");
|
||||
|
||||
// Cycle to plan
|
||||
modeService.switchMode('plan');
|
||||
expect(modeService.getCurrentMode()).toBe('plan');
|
||||
modeService.switchMode("plan");
|
||||
expect(modeService.getCurrentMode()).toBe("plan");
|
||||
|
||||
// Cycle to auto
|
||||
modeService.switchMode('auto');
|
||||
expect(modeService.getCurrentMode()).toBe('auto');
|
||||
modeService.switchMode("auto");
|
||||
expect(modeService.getCurrentMode()).toBe("auto");
|
||||
|
||||
// Cycle back to normal
|
||||
modeService.switchMode('normal');
|
||||
expect(modeService.getCurrentMode()).toBe('normal');
|
||||
modeService.switchMode("normal");
|
||||
expect(modeService.getCurrentMode()).toBe("normal");
|
||||
});
|
||||
|
||||
it('should cycle through all modes sequentially', () => {
|
||||
const modes = ['normal', 'plan', 'auto'] as const;
|
||||
|
||||
it("should cycle through all modes sequentially", () => {
|
||||
const modes = ["normal", "plan", "auto"] as const;
|
||||
|
||||
// Test cycling through all modes
|
||||
for (let i = 0; i < modes.length * 2; i++) {
|
||||
const expectedMode = modes[i % modes.length];
|
||||
|
|
@ -37,4 +37,4 @@ describe('UserInput Keyboard Shortcuts', () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js";
|
|||
|
||||
// Mock the 'open' module to prevent actual URL opening during tests
|
||||
vi.mock("open", () => ({
|
||||
default: vi.fn()
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock the NavigationContext
|
||||
|
|
@ -15,8 +15,8 @@ vi.mock("../context/NavigationContext.js", () => ({
|
|||
navigateTo: vi.fn(),
|
||||
closeCurrentScreen: vi.fn(),
|
||||
isScreenActive: vi.fn(() => false),
|
||||
state: { currentScreen: 'free-trial', screenData: null }
|
||||
})
|
||||
state: { currentScreen: "free-trial", screenData: null },
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
||||
|
|
@ -29,9 +29,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
describe("Initial Choice Screen Rendering", () => {
|
||||
it("displays all three options with proper formatting", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
|
|
@ -44,22 +42,20 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
|
||||
it("highlights first option by default", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
expect(frame).toContain("▶ 1. 💳 Sign up for models add-on");
|
||||
expect(frame).not.toContain("▶ 2. 🔑 Enter your Anthropic API key");
|
||||
expect(frame).not.toContain("▶ 3. ⚙️ Switch to a different configuration");
|
||||
expect(frame).not.toContain(
|
||||
"▶ 3. ⚙️ Switch to a different configuration",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders without crashing when all props are provided", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
|
|
@ -72,7 +68,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
// onShowConfigSelector not provided
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
|
|
@ -83,21 +79,19 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
|
||||
it("includes proper user instructions", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
expect(frame).toContain("Choose how you'd like to continue:");
|
||||
expect(frame).toContain("Use ↑↓ arrows or 1/2/3 to select, Enter to confirm");
|
||||
expect(frame).toContain(
|
||||
"Use ↑↓ arrows or 1/2/3 to select, Enter to confirm",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows all options with proper descriptions", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
|
|
@ -111,22 +105,14 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
it("accepts all required callback props", () => {
|
||||
// Test that component accepts and renders with all props
|
||||
expect(() => {
|
||||
render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
);
|
||||
render(<FreeTrialTransitionUI onReload={mockOnReload} />);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it("accepts optional onShowConfigSelector prop", () => {
|
||||
// Test that component works without onShowConfigSelector
|
||||
expect(() => {
|
||||
render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
);
|
||||
render(<FreeTrialTransitionUI onReload={mockOnReload} />);
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
|
@ -134,9 +120,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
describe("Visual Styling and Layout", () => {
|
||||
it("renders with proper border styling", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
|
|
@ -146,32 +130,34 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
|
||||
it("displays with proper spacing and formatting", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
// Should have proper spacing between lines
|
||||
expect(frame?.split('\n').length).toBeGreaterThan(5);
|
||||
expect(frame?.split("\n").length).toBeGreaterThan(5);
|
||||
});
|
||||
|
||||
it("shows selection indicator on first option by default", () => {
|
||||
const { lastFrame } = render(
|
||||
<FreeTrialTransitionUI
|
||||
onReload={mockOnReload}
|
||||
/>
|
||||
<FreeTrialTransitionUI onReload={mockOnReload} />,
|
||||
);
|
||||
|
||||
const frame = lastFrame();
|
||||
const lines = frame?.split('\n') || [];
|
||||
const modelsLine = lines.find(line => line.includes('Sign up for models add-on'));
|
||||
const apiKeyLine = lines.find(line => line.includes('Enter your Anthropic API key'));
|
||||
const configLine = lines.find(line => line.includes('Switch to a different configuration'));
|
||||
const lines = frame?.split("\n") || [];
|
||||
const modelsLine = lines.find((line) =>
|
||||
line.includes("Sign up for models add-on"),
|
||||
);
|
||||
const apiKeyLine = lines.find((line) =>
|
||||
line.includes("Enter your Anthropic API key"),
|
||||
);
|
||||
const configLine = lines.find((line) =>
|
||||
line.includes("Switch to a different configuration"),
|
||||
);
|
||||
|
||||
expect(modelsLine).toContain('▶');
|
||||
expect(apiKeyLine).not.toContain('▶');
|
||||
expect(configLine).not.toContain('▶');
|
||||
expect(modelsLine).toContain("▶");
|
||||
expect(apiKeyLine).not.toContain("▶");
|
||||
expect(configLine).not.toContain("▶");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -184,4 +170,4 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => {
|
|||
expect(typeof openModule.default).toBe("function");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,11 +5,11 @@ describe("FreeTrialTransitionUI - URL Opening Security", () => {
|
|||
it("should mock URL opening to prevent actual browser launches during tests", () => {
|
||||
// This test verifies that we properly mock the 'open' module
|
||||
// to prevent actual URLs from being opened during test runs
|
||||
|
||||
|
||||
// Import and check that open is mocked
|
||||
const mockOpen = vi.fn();
|
||||
vi.mock("open", () => mockOpen);
|
||||
|
||||
|
||||
// Verify the mock is properly set up
|
||||
expect(mockOpen).toBeDefined();
|
||||
expect(typeof mockOpen).toBe("function");
|
||||
|
|
@ -19,16 +19,25 @@ describe("FreeTrialTransitionUI - URL Opening Security", () => {
|
|||
// Test the URL construction logic without actually opening URLs
|
||||
const baseUrl = "https://test.continue.dev";
|
||||
const expectedUrl = new URL("setup-models", baseUrl).toString();
|
||||
|
||||
|
||||
expect(expectedUrl).toBe("https://test.continue.dev/setup-models");
|
||||
});
|
||||
|
||||
it("should handle URL construction with different base URLs", () => {
|
||||
// Test URL construction with various base URLs
|
||||
const testCases = [
|
||||
{ base: "https://continue.dev", expected: "https://continue.dev/setup-models" },
|
||||
{ base: "https://app.continue.dev", expected: "https://app.continue.dev/setup-models" },
|
||||
{ base: "http://localhost:3000", expected: "http://localhost:3000/setup-models" },
|
||||
{
|
||||
base: "https://continue.dev",
|
||||
expected: "https://continue.dev/setup-models",
|
||||
},
|
||||
{
|
||||
base: "https://app.continue.dev",
|
||||
expected: "https://app.continue.dev/setup-models",
|
||||
},
|
||||
{
|
||||
base: "http://localhost:3000",
|
||||
expected: "http://localhost:3000/setup-models",
|
||||
},
|
||||
];
|
||||
|
||||
testCases.forEach(({ base, expected }) => {
|
||||
|
|
@ -41,16 +50,16 @@ describe("FreeTrialTransitionUI - URL Opening Security", () => {
|
|||
// This test documents the security consideration:
|
||||
// Without proper mocking, tests could open arbitrary URLs in the user's browser
|
||||
// The mock ensures this doesn't happen during automated test runs
|
||||
|
||||
|
||||
const openFunction = vi.fn();
|
||||
|
||||
|
||||
// Simulate what would happen if URL opening was called
|
||||
openFunction("https://malicious-site.com");
|
||||
|
||||
|
||||
// Verify the mock was called instead of actual URL opening
|
||||
expect(openFunction).toHaveBeenCalledWith("https://malicious-site.com");
|
||||
expect(openFunction).toHaveBeenCalledTimes(1);
|
||||
|
||||
|
||||
// In real usage, this would have opened a browser tab, but with mocking it's safe
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ describe("TUIChat - Basic UI Tests", () => {
|
|||
|
||||
it("handles remote URL prop", () => {
|
||||
const { lastFrame } = render(
|
||||
React.createElement(AppRoot, { remoteUrl: "http://localhost:3000" })
|
||||
React.createElement(AppRoot, { remoteUrl: "http://localhost:3000" }),
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
|
|
@ -59,4 +59,4 @@ describe("TUIChat - Basic UI Tests", () => {
|
|||
expect(frame.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ describe("TUIChat - @ File Search Tests", () => {
|
|||
expect(hasAtSymbol).toBe(true);
|
||||
|
||||
// Mode-specific UI
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).not.toContain("Remote Mode");
|
||||
|
|
@ -44,15 +44,16 @@ describe("TUIChat - @ File Search Tests", () => {
|
|||
expect(frame).toContain("@READ");
|
||||
|
||||
// In local mode, should show either navigation hints or files
|
||||
if (mode === 'local') {
|
||||
if (mode === "local") {
|
||||
// Should show either navigation hints or at least indicate file search is working
|
||||
const hasNavigationHints = frame.includes("↑/↓ to navigate");
|
||||
const hasFileSearch = frame.includes("@READ") && !frame.includes("Remote Mode");
|
||||
const hasFileSearch =
|
||||
frame.includes("@READ") && !frame.includes("Remote Mode");
|
||||
expect(hasNavigationHints || hasFileSearch).toBe(true);
|
||||
}
|
||||
|
||||
// Mode-specific checks
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).not.toContain("Remote Mode");
|
||||
|
|
@ -75,7 +76,7 @@ describe("TUIChat - @ File Search Tests", () => {
|
|||
expect(frame).toContain("@@test");
|
||||
|
||||
// Mode-specific UI elements
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).toContain("Continue CLI");
|
||||
|
|
@ -98,11 +99,12 @@ describe("TUIChat - @ File Search Tests", () => {
|
|||
expect(frame.length).toBeGreaterThan(0);
|
||||
|
||||
// In local mode, should show either navigation hints or file search UI
|
||||
if (mode === 'local') {
|
||||
if (mode === "local") {
|
||||
// Should show either navigation hints or at least the @ character in file search
|
||||
const hasNavigationHints = frame.includes("↑/↓ to navigate");
|
||||
const hasFileSearchUI = frame.includes("@") && !frame.includes("Remote Mode");
|
||||
const hasFileSearchUI =
|
||||
frame.includes("@") && !frame.includes("Remote Mode");
|
||||
expect(hasNavigationHints || hasFileSearchUI).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,17 +5,17 @@ describe("TUIChat - Free Trial Transition Integration", () => {
|
|||
// This test verifies that the integration points exist
|
||||
// More comprehensive integration tests would require complex mocking
|
||||
// that is difficult to maintain and test reliably.
|
||||
|
||||
|
||||
// The key integration points are:
|
||||
// 1. FreeTrialTransitionUI receives onShowConfigSelector callback
|
||||
// 2. TUIChat provides handleFreeTrialShowConfigSelector function
|
||||
// 3. Config selector is shown when option 3 is selected
|
||||
|
||||
|
||||
// These integration points are tested via:
|
||||
// - Type checking (ensures interfaces match)
|
||||
// - Manual testing during development
|
||||
// - E2E tests that exercise the full flow
|
||||
|
||||
|
||||
expect(true).toBe(true); // Placeholder test
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -9,11 +9,11 @@ describe("TUIChat - User Input Tests", () => {
|
|||
const frame = lastFrame();
|
||||
// The input might be in a different format, let's be more flexible
|
||||
expect(frame ? frame.toLowerCase() : "").toMatch(
|
||||
/testing|123|ask anything/
|
||||
/testing|123|ask anything/,
|
||||
);
|
||||
|
||||
|
||||
// Mode-specific assertions
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).not.toContain("Remote Mode");
|
||||
|
|
@ -36,34 +36,37 @@ describe("TUIChat - User Input Tests", () => {
|
|||
// The UI should remain stable after Enter (no crash)
|
||||
expect(afterEnter).toBeDefined();
|
||||
expect(afterEnter).toContain("Ask anything");
|
||||
|
||||
|
||||
// Local mode specific features
|
||||
if (mode === 'local') {
|
||||
if (mode === "local") {
|
||||
expect(afterEnter).toContain("@ for context");
|
||||
expect(afterEnter).toContain("/ for slash commands");
|
||||
}
|
||||
});
|
||||
|
||||
testBothModes("handles special characters in input without crashing", (mode) => {
|
||||
const { lastFrame, stdin } = renderInMode(mode);
|
||||
testBothModes(
|
||||
"handles special characters in input without crashing",
|
||||
(mode) => {
|
||||
const { lastFrame, stdin } = renderInMode(mode);
|
||||
|
||||
// Try typing various special characters
|
||||
stdin.write("!@#$%^&*()");
|
||||
// Try typing various special characters
|
||||
stdin.write("!@#$%^&*()");
|
||||
|
||||
const frame = lastFrame();
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should handle special characters without crashing
|
||||
expect(frame).toBeDefined();
|
||||
expect(frame).not.toBe("");
|
||||
|
||||
// UI should still be functional
|
||||
expect(frame).toContain("Ask anything");
|
||||
|
||||
// Mode-specific UI elements
|
||||
if (mode === 'remote') {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).toContain("Continue CLI");
|
||||
}
|
||||
});
|
||||
});
|
||||
// Should handle special characters without crashing
|
||||
expect(frame).toBeDefined();
|
||||
expect(frame).not.toBe("");
|
||||
|
||||
// UI should still be functional
|
||||
expect(frame).toContain("Ask anything");
|
||||
|
||||
// Mode-specific UI elements
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).toContain("Continue CLI");
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ describe("TUIChat - Message Display Tests", () => {
|
|||
expect(frame).toContain("│");
|
||||
|
||||
// Mode-specific assertions
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).not.toContain("Remote Mode");
|
||||
|
|
@ -35,12 +35,12 @@ describe("TUIChat - Message Display Tests", () => {
|
|||
expect(frame).toContain("/ for slash commands");
|
||||
|
||||
// In local mode, also shows context hint
|
||||
if (mode === 'local') {
|
||||
if (mode === "local") {
|
||||
expect(frame).toContain("@ for context");
|
||||
}
|
||||
|
||||
// Verify mode-specific UI
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).toContain("Continue CLI");
|
||||
|
|
@ -65,13 +65,13 @@ describe("TUIChat - Message Display Tests", () => {
|
|||
// Verify the component renders
|
||||
const frame = lastFrame();
|
||||
expect(frame).toContain("Ask anything");
|
||||
|
||||
|
||||
// In local mode, we have access to more UI elements
|
||||
if (mode === 'local') {
|
||||
if (mode === "local") {
|
||||
expect(frame).toContain("@ for context");
|
||||
expect(frame).toContain("/ for slash commands");
|
||||
}
|
||||
|
||||
context.cleanup();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -30,8 +30,12 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
|
||||
it("should call reloadPermissions after creating a policy", async () => {
|
||||
// Mock the policy writer
|
||||
const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
|
||||
vi.mocked(generatePolicyRule).mockReturnValue("tool: Edit\npermission: allow");
|
||||
const { generatePolicyRule, addPolicyToYaml } = await import(
|
||||
"../../permissions/policyWriter.js"
|
||||
);
|
||||
vi.mocked(generatePolicyRule).mockReturnValue(
|
||||
"tool: Edit\npermission: allow",
|
||||
);
|
||||
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
|
||||
|
||||
// Test the workflow that should happen in useChat.handleToolPermissionResponse
|
||||
|
|
@ -42,7 +46,7 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
|
||||
const approved = true;
|
||||
const createPolicy = true;
|
||||
|
||||
|
||||
// Simulate the policy creation flow from useChat
|
||||
if (approved && createPolicy && mockActiveRequest) {
|
||||
try {
|
||||
|
|
@ -57,29 +61,38 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
);
|
||||
|
||||
await addPolicyToYaml(policyRule);
|
||||
|
||||
|
||||
// This is the key part we're testing - reload should be called
|
||||
await services.mode.getToolPermissionService().reloadPermissions();
|
||||
|
||||
} catch (error) {
|
||||
// Handle errors gracefully
|
||||
}
|
||||
}
|
||||
|
||||
// Verify the complete workflow executed
|
||||
expect(generatePolicyRule).toHaveBeenCalledWith("Edit", { file_path: "test.txt" });
|
||||
expect(addPolicyToYaml).toHaveBeenCalledWith("tool: Edit\npermission: allow");
|
||||
expect(generatePolicyRule).toHaveBeenCalledWith("Edit", {
|
||||
file_path: "test.txt",
|
||||
});
|
||||
expect(addPolicyToYaml).toHaveBeenCalledWith(
|
||||
"tool: Edit\npermission: allow",
|
||||
);
|
||||
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle permission reload failure gracefully", async () => {
|
||||
// Mock the policy writer
|
||||
const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
|
||||
vi.mocked(generatePolicyRule).mockReturnValue("tool: Write\npermission: allow");
|
||||
const { generatePolicyRule, addPolicyToYaml } = await import(
|
||||
"../../permissions/policyWriter.js"
|
||||
);
|
||||
vi.mocked(generatePolicyRule).mockReturnValue(
|
||||
"tool: Write\npermission: allow",
|
||||
);
|
||||
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
|
||||
|
||||
// Mock reloadPermissions to fail
|
||||
mockToolPermissionService.reloadPermissions.mockRejectedValue(new Error("Reload failed"));
|
||||
mockToolPermissionService.reloadPermissions.mockRejectedValue(
|
||||
new Error("Reload failed"),
|
||||
);
|
||||
|
||||
const mockActiveRequest = {
|
||||
toolName: "Write",
|
||||
|
|
@ -88,7 +101,7 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
|
||||
const approved = true;
|
||||
const createPolicy = true;
|
||||
|
||||
|
||||
// Test that error handling works correctly - this should not throw
|
||||
let errorCaught = false;
|
||||
try {
|
||||
|
|
@ -101,12 +114,11 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
mockActiveRequest.toolName,
|
||||
mockActiveRequest.toolArgs,
|
||||
);
|
||||
|
||||
|
||||
await addPolicyToYaml(policyRule);
|
||||
|
||||
|
||||
// This should fail but not break the flow
|
||||
await services.mode.getToolPermissionService().reloadPermissions();
|
||||
|
||||
} catch (error) {
|
||||
// Error should be caught and handled gracefully
|
||||
errorCaught = true;
|
||||
|
|
@ -121,8 +133,12 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
|
||||
it("verifies the expected improvement: policy takes effect immediately", async () => {
|
||||
// This test documents what the user should experience
|
||||
const { generatePolicyRule, addPolicyToYaml } = await import("../../permissions/policyWriter.js");
|
||||
vi.mocked(generatePolicyRule).mockReturnValue("tool: Edit\npermission: allow");
|
||||
const { generatePolicyRule, addPolicyToYaml } = await import(
|
||||
"../../permissions/policyWriter.js"
|
||||
);
|
||||
vi.mocked(generatePolicyRule).mockReturnValue(
|
||||
"tool: Edit\npermission: allow",
|
||||
);
|
||||
vi.mocked(addPolicyToYaml).mockResolvedValue(undefined);
|
||||
|
||||
// Mock successful reload
|
||||
|
|
@ -137,7 +153,7 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
// Simulate user choosing "Continue + don't ask again"
|
||||
const approved = true;
|
||||
const createPolicy = true;
|
||||
|
||||
|
||||
// The workflow should complete successfully
|
||||
if (approved && createPolicy && mockActiveRequest) {
|
||||
const { generatePolicyRule, addPolicyToYaml } = await import(
|
||||
|
|
@ -156,10 +172,10 @@ describe("Permission Policy Reload Workflow", () => {
|
|||
|
||||
// AFTER: Policy is now active without restart
|
||||
// Next time user tries to edit a file, it should be automatically allowed
|
||||
|
||||
|
||||
expect(mockToolPermissionService.reloadPermissions).toHaveBeenCalled();
|
||||
|
||||
|
||||
// This represents the improvement: the new policy takes effect immediately
|
||||
// without requiring the user to restart the Continue CLI
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,10 +14,10 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
beforeEach(async () => {
|
||||
context = createUITestContext({
|
||||
allServicesReady: true,
|
||||
serviceState: "ready",
|
||||
serviceState: "ready",
|
||||
serviceValue: { some: "data" },
|
||||
});
|
||||
|
||||
|
||||
// Ensure mode service is properly initialized in normal mode
|
||||
await modeService.initialize({});
|
||||
});
|
||||
|
|
@ -37,30 +37,30 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
|
||||
// b) Shift+Tab to switch into plan mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
frame = lastFrame();
|
||||
|
||||
|
||||
// c) Make sure the string "[plan]" is on the screen
|
||||
expect(frame!).toContain("[plan]");
|
||||
|
||||
|
||||
// d) Successfully send a message without error
|
||||
const testMessage = "Can you help me analyze this code?";
|
||||
stdin.write(testMessage);
|
||||
stdin.write("\r");
|
||||
|
||||
|
||||
// Wait for message processing
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
|
||||
frame = lastFrame();
|
||||
|
||||
|
||||
// Verify no crash occurred and UI is still functional
|
||||
expect(frame).toBeDefined();
|
||||
expect(frame!.length).toBeGreaterThan(0);
|
||||
|
||||
|
||||
// Should still be in plan mode after sending message
|
||||
expect(frame!).toContain("[plan]");
|
||||
|
||||
|
||||
// Should still show the input prompt
|
||||
expect(frame!).toContain("Ask anything");
|
||||
} finally {
|
||||
|
|
@ -79,62 +79,58 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
|
||||
// Switch to plan mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
frame = lastFrame();
|
||||
expect(frame!).toContain("[plan]");
|
||||
|
||||
// Switch to auto mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
frame = lastFrame();
|
||||
expect(frame!).toContain("[auto]");
|
||||
expect(frame!).not.toContain("[plan]");
|
||||
|
||||
// Switch back to normal mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
frame = lastFrame();
|
||||
expect(frame!).not.toContain("[plan]");
|
||||
expect(frame!).not.toContain("[auto]");
|
||||
|
||||
|
||||
} finally {
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("tests that you can switch modes after being in plan mode", async () => {
|
||||
it("tests that you can switch modes after being in plan mode", async () => {
|
||||
const { lastFrame, stdin, unmount } = render(React.createElement(AppRoot));
|
||||
|
||||
try {
|
||||
// Switch to plan mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
let frame = lastFrame();
|
||||
expect(frame!).toContain("[plan]");
|
||||
|
||||
// Send a message while in plan mode
|
||||
stdin.write("Test message");
|
||||
stdin.write("\r");
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
frame = lastFrame();
|
||||
|
||||
// Try to switch to another mode - this is where the bug might occur
|
||||
stdin.write("\x1b[Z]"); // Should go to auto mode
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
frame = lastFrame();
|
||||
|
||||
|
||||
// This should work - if it fails, we've reproduced the "can't switch back" bug
|
||||
expect(frame!).toContain("[auto]");
|
||||
expect(frame!).not.toContain("[plan]");
|
||||
|
||||
|
||||
} finally {
|
||||
unmount();
|
||||
}
|
||||
|
|
@ -143,39 +139,41 @@ it("tests that you can switch modes after being in plan mode", async () => {
|
|||
it.skip("reproduces the 'ToolPermissionService not initialized' error when switching modes", async () => {
|
||||
// This test specifically tests the service container interaction
|
||||
// that causes the actual bug in production
|
||||
|
||||
|
||||
// First, set up a realistic service state (not mocked)
|
||||
await modeService.initialize({ isHeadless: false });
|
||||
|
||||
|
||||
// Register the tool permissions service like the real app does
|
||||
const initialState = modeService.getToolPermissionService().getState();
|
||||
serviceContainer.registerValue(SERVICE_NAMES.TOOL_PERMISSIONS, initialState);
|
||||
|
||||
serviceContainer.registerValue(
|
||||
SERVICE_NAMES.TOOL_PERMISSIONS,
|
||||
initialState,
|
||||
);
|
||||
|
||||
// Verify initial state works
|
||||
expect(() => getAllTools()).not.toThrow();
|
||||
|
||||
|
||||
// Switch modes WITHOUT updating the service container (this simulates the bug)
|
||||
modeService.switchMode("plan");
|
||||
|
||||
|
||||
// The service container still has the old state, so getAllTools() should not find
|
||||
// the updated state with plan mode permissions. However, since the ToolPermissionService
|
||||
// overrides isReady() to always return true, getAllTools() will actually work.
|
||||
// The real bug would manifest when the service container has an out-of-sync state.
|
||||
|
||||
// To reproduce the ACTUAL bug, we need to simulate the case where the service
|
||||
|
||||
// To reproduce the ACTUAL bug, we need to simulate the case where the service
|
||||
// container has a stale state that doesn't match the ToolPermissionService
|
||||
const staleState = { ...initialState, currentMode: "normal" as const };
|
||||
serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, staleState);
|
||||
|
||||
|
||||
|
||||
// Now getAllTools() should work because it gets the service state from the container
|
||||
// and the container has a valid state (even if it's stale)
|
||||
const tools = getAllTools();
|
||||
expect(tools).toBeDefined();
|
||||
expect(Array.isArray(tools)).toBe(true);
|
||||
|
||||
|
||||
// But the tools returned will be for "normal" mode, not "plan" mode
|
||||
// In plan mode, many tools should be excluded, but with stale normal state, all tools are available
|
||||
const planModeState = modeService.getToolPermissionService().getState();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -19,9 +19,7 @@ describe("TUIChat - Remote Server Tests", () => {
|
|||
});
|
||||
|
||||
it("renders in remote mode with remote URL", () => {
|
||||
const { lastFrame } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
);
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toBeDefined();
|
||||
|
|
@ -30,9 +28,7 @@ describe("TUIChat - Remote Server Tests", () => {
|
|||
});
|
||||
|
||||
it("shows remote mode indicator", () => {
|
||||
const { lastFrame } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
);
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should show remote mode in the UI
|
||||
|
|
@ -40,9 +36,7 @@ describe("TUIChat - Remote Server Tests", () => {
|
|||
});
|
||||
|
||||
it("does not show service loading in remote mode", () => {
|
||||
const { lastFrame } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
);
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should not show loading services message
|
||||
|
|
@ -54,7 +48,7 @@ describe("TUIChat - Remote Server Tests", () => {
|
|||
|
||||
it("handles different remote URLs", () => {
|
||||
const { lastFrame } = render(
|
||||
<AppRoot remoteUrl="https://api.example.com:8080" />
|
||||
<AppRoot remoteUrl="https://api.example.com:8080" />,
|
||||
);
|
||||
const frame = lastFrame();
|
||||
|
||||
|
|
@ -65,7 +59,7 @@ describe("TUIChat - Remote Server Tests", () => {
|
|||
|
||||
it("shows slash commands in remote mode", async () => {
|
||||
const { lastFrame, stdin } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
<AppRoot remoteUrl="http://localhost:3000" />,
|
||||
);
|
||||
|
||||
// Wait for initial render
|
||||
|
|
@ -84,13 +78,13 @@ describe("TUIChat - Remote Server Tests", () => {
|
|||
|
||||
// The slash command menu might show /exit or navigation instructions
|
||||
// Different timing might show different states
|
||||
const hasSlashCommandUI = frame ? (
|
||||
frame.includes("/exit") ||
|
||||
frame.includes("↑/↓ to navigate") ||
|
||||
frame.includes("◉ /") ||
|
||||
frame.includes("/ for slash commands") // Placeholder text is also valid
|
||||
) : false;
|
||||
const hasSlashCommandUI = frame
|
||||
? frame.includes("/exit") ||
|
||||
frame.includes("↑/↓ to navigate") ||
|
||||
frame.includes("◉ /") ||
|
||||
frame.includes("/ for slash commands") // Placeholder text is also valid
|
||||
: false;
|
||||
|
||||
expect(hasSlashCommandUI).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,9 +14,9 @@ describe("TUIChat - Slash Commands Tests", () => {
|
|||
|
||||
// Should show the slash character
|
||||
expect(frame).toContain("/");
|
||||
|
||||
|
||||
// Mode-specific assertions
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).not.toContain("Remote Mode");
|
||||
|
|
@ -37,9 +37,9 @@ describe("TUIChat - Slash Commands Tests", () => {
|
|||
|
||||
// Should show the typed command
|
||||
expect(frame).toContain("/log");
|
||||
|
||||
|
||||
// Mode-specific UI elements
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frame).not.toContain("Remote Mode");
|
||||
|
|
@ -52,9 +52,9 @@ describe("TUIChat - Slash Commands Tests", () => {
|
|||
|
||||
// Type /log and then tab
|
||||
stdin.write("/log");
|
||||
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
|
||||
stdin.write("\t");
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
|
@ -65,9 +65,9 @@ describe("TUIChat - Slash Commands Tests", () => {
|
|||
expect(frameAfterTab).toBeDefined();
|
||||
if (frameAfterTab) {
|
||||
expect(frameAfterTab.length).toBeGreaterThan(0);
|
||||
|
||||
|
||||
// Mode-specific checks
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frameAfterTab).toContain("Remote Mode");
|
||||
} else {
|
||||
expect(frameAfterTab).not.toContain("Remote Mode");
|
||||
|
|
@ -87,9 +87,9 @@ describe("TUIChat - Slash Commands Tests", () => {
|
|||
|
||||
// Should show the slash
|
||||
expect(frame).toContain("/");
|
||||
|
||||
|
||||
// In remote mode, slash command menu shows immediately
|
||||
if (mode === 'remote') {
|
||||
if (mode === "remote") {
|
||||
expect(frame).toContain("/exit");
|
||||
expect(frame).toContain("Remote Mode");
|
||||
} else {
|
||||
|
|
@ -101,4 +101,4 @@ describe("TUIChat - Slash Commands Tests", () => {
|
|||
expect(hasSlash).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
}}
|
||||
requestId="test-request-123"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -42,7 +42,7 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
"test-request-123",
|
||||
false, // approved = false
|
||||
false, // createPolicy = false
|
||||
true // stopStream = true
|
||||
true, // stopStream = true
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -58,7 +58,7 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
}}
|
||||
requestId="dangerous-request"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -73,14 +73,14 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
"dangerous-request",
|
||||
false, // rejected
|
||||
false, // createPolicy = false
|
||||
true // stopStream = true
|
||||
true, // stopStream = true
|
||||
);
|
||||
});
|
||||
|
||||
it("tests that rejection response leads to stream stopping behavior", () => {
|
||||
// This test validates the key behavior - when onResponse is called with approved=false,
|
||||
// it should lead to the streamChatResponse function stopping and returning early
|
||||
|
||||
|
||||
const mockStreamingFunction = vi.fn().mockImplementation((approved) => {
|
||||
if (!approved) {
|
||||
// Simulate early return when tool is rejected
|
||||
|
|
@ -104,10 +104,12 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
|
||||
it("validates permission manager handles rejection correctly", async () => {
|
||||
// Import the permission manager to test its behavior
|
||||
const { toolPermissionManager } = await import("../../permissions/permissionManager.js");
|
||||
const { toolPermissionManager } = await import(
|
||||
"../../permissions/permissionManager.js"
|
||||
);
|
||||
|
||||
const mockResolve = vi.fn();
|
||||
|
||||
|
||||
// Simulate a pending request
|
||||
const requestId = "test-request-456";
|
||||
(toolPermissionManager as any).pendingRequests.set(requestId, {
|
||||
|
|
@ -121,15 +123,17 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
// Verify the request was properly rejected
|
||||
expect(result).toBe(true);
|
||||
expect(mockResolve).toHaveBeenCalledWith({ approved: false });
|
||||
|
||||
|
||||
// Verify the request was removed from pending requests
|
||||
expect((toolPermissionManager as any).pendingRequests.has(requestId)).toBe(false);
|
||||
expect((toolPermissionManager as any).pendingRequests.has(requestId)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("handles multiple tool calls correctly when first is rejected", () => {
|
||||
// Test the bug fix: when multiple tool calls are present and the first is rejected,
|
||||
// remaining tool calls should be marked as cancelled to maintain chat history consistency
|
||||
|
||||
|
||||
const mockMultipleToolCalls = [
|
||||
{ id: "call_1", name: "Edit", arguments: {} },
|
||||
{ id: "call_2", name: "Write", arguments: {} },
|
||||
|
|
@ -143,10 +147,10 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
// Simulate the rejection handling logic
|
||||
const deniedMessage = "Permission denied by user";
|
||||
const rejectedToolCall = mockMultipleToolCalls[0];
|
||||
|
||||
|
||||
// First tool call gets denied
|
||||
mockCallbacks.onToolResult(deniedMessage, rejectedToolCall.name);
|
||||
|
||||
|
||||
// Remaining tool calls should be cancelled
|
||||
for (let i = 1; i < mockMultipleToolCalls.length; i++) {
|
||||
const remainingToolCall = mockMultipleToolCalls[i];
|
||||
|
|
@ -156,30 +160,62 @@ describe("TUIChat - Stream Stopping on Tool Rejection", () => {
|
|||
|
||||
// Verify all tool calls got results
|
||||
expect(mockCallbacks.onToolResult).toHaveBeenCalledTimes(3);
|
||||
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(1, "Permission denied by user", "Edit");
|
||||
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(2, "Cancelled due to previous tool rejection", "Write");
|
||||
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(3, "Cancelled due to previous tool rejection", "Read");
|
||||
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"Permission denied by user",
|
||||
"Edit",
|
||||
);
|
||||
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"Cancelled due to previous tool rejection",
|
||||
"Write",
|
||||
);
|
||||
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
"Cancelled due to previous tool rejection",
|
||||
"Read",
|
||||
);
|
||||
});
|
||||
|
||||
it("ensures proper response content in headless mode", () => {
|
||||
// Test the bug fix: ensure finalResponse fallback works properly in headless mode
|
||||
|
||||
const mockStreamingBehavior = (isHeadless: boolean, finalResponse: string, content: string, fullResponse: string) => {
|
||||
|
||||
const mockStreamingBehavior = (
|
||||
isHeadless: boolean,
|
||||
finalResponse: string,
|
||||
content: string,
|
||||
fullResponse: string,
|
||||
) => {
|
||||
// Simulate the fixed return logic
|
||||
const responseToReturn = isHeadless ? (finalResponse || content) : fullResponse;
|
||||
const responseToReturn = isHeadless
|
||||
? finalResponse || content
|
||||
: fullResponse;
|
||||
return responseToReturn;
|
||||
};
|
||||
|
||||
// Test headless mode with initialized finalResponse
|
||||
expect(mockStreamingBehavior(true, "final content", "current content", "full content"))
|
||||
.toBe("final content");
|
||||
expect(
|
||||
mockStreamingBehavior(
|
||||
true,
|
||||
"final content",
|
||||
"current content",
|
||||
"full content",
|
||||
),
|
||||
).toBe("final content");
|
||||
|
||||
// Test headless mode with uninitialized finalResponse (empty string)
|
||||
expect(mockStreamingBehavior(true, "", "current content", "full content"))
|
||||
.toBe("current content");
|
||||
expect(
|
||||
mockStreamingBehavior(true, "", "current content", "full content"),
|
||||
).toBe("current content");
|
||||
|
||||
// Test non-headless mode
|
||||
expect(mockStreamingBehavior(false, "final content", "current content", "full content"))
|
||||
.toBe("full content");
|
||||
expect(
|
||||
mockStreamingBehavior(
|
||||
false,
|
||||
"final content",
|
||||
"current content",
|
||||
"full content",
|
||||
),
|
||||
).toBe("full content");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -19,9 +19,7 @@ describe("TUIChat - Tool Display Tests", () => {
|
|||
});
|
||||
|
||||
it("renders without crashing when tools are available", () => {
|
||||
const { lastFrame } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
);
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
expect(frame).toBeDefined();
|
||||
|
|
@ -29,9 +27,7 @@ describe("TUIChat - Tool Display Tests", () => {
|
|||
});
|
||||
|
||||
it("handles UI with no tools configured", () => {
|
||||
const { lastFrame } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
);
|
||||
const { lastFrame } = render(<AppRoot remoteUrl="http://localhost:3000" />);
|
||||
const frame = lastFrame();
|
||||
|
||||
// Should render normally even without tools
|
||||
|
|
@ -41,7 +37,7 @@ describe("TUIChat - Tool Display Tests", () => {
|
|||
|
||||
it("maintains UI stability during tool operations", async () => {
|
||||
const { lastFrame, stdin } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
<AppRoot remoteUrl="http://localhost:3000" />,
|
||||
);
|
||||
|
||||
// Type a message that might trigger tool use
|
||||
|
|
@ -60,7 +56,7 @@ describe("TUIChat - Tool Display Tests", () => {
|
|||
|
||||
it("shows tool-related slash commands", async () => {
|
||||
const { lastFrame, stdin } = render(
|
||||
<AppRoot remoteUrl="http://localhost:3000" />
|
||||
<AppRoot remoteUrl="http://localhost:3000" />,
|
||||
);
|
||||
|
||||
// Wait for initial render
|
||||
|
|
@ -79,13 +75,13 @@ describe("TUIChat - Tool Display Tests", () => {
|
|||
|
||||
// The slash command menu might show different UI states
|
||||
// On Windows, the timing might be different
|
||||
const hasSlashCommandIndicator = frame ? (
|
||||
frame.includes("↑/↓ to navigate") ||
|
||||
frame.includes("/exit") ||
|
||||
frame.includes("◉ /") ||
|
||||
frame.includes("/ for slash commands")
|
||||
) : false;
|
||||
const hasSlashCommandIndicator = frame
|
||||
? frame.includes("↑/↓ to navigate") ||
|
||||
frame.includes("/exit") ||
|
||||
frame.includes("◉ /") ||
|
||||
frame.includes("/ for slash commands")
|
||||
: false;
|
||||
|
||||
expect(hasSlashCommandIndicator).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-123"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -58,7 +58,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-123"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -72,7 +72,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
"test-request-123",
|
||||
true,
|
||||
false,
|
||||
false
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -87,7 +87,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-456"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -101,7 +101,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
"test-request-456",
|
||||
false,
|
||||
false,
|
||||
true
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -116,7 +116,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-789"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -130,7 +130,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
"test-request-789",
|
||||
false,
|
||||
false,
|
||||
true
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -145,7 +145,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-123"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -162,7 +162,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
"test-request-123",
|
||||
true,
|
||||
undefined,
|
||||
undefined
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -177,7 +177,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-policy"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -192,7 +192,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
"test-request-policy",
|
||||
true,
|
||||
true,
|
||||
false
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -209,7 +209,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-stop"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -217,7 +217,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
// Verify the new option exists in the rendered output
|
||||
const frame = lastFrame();
|
||||
expect(frame).toContain("No, and tell Continue what to do differently");
|
||||
|
||||
|
||||
// Verify all 3 options are present
|
||||
expect(frame).toContain("Continue");
|
||||
expect(frame).toContain("Continue + don't ask again");
|
||||
|
|
@ -240,7 +240,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-escape"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -253,9 +253,9 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
// Verify the escape key triggers the stopStream behavior
|
||||
expect(handleResponse).toHaveBeenCalledWith(
|
||||
"test-request-escape",
|
||||
false, // approved = false (rejection)
|
||||
false, // createPolicy = false
|
||||
true // stopStream = true (this is the new behavior)
|
||||
false, // approved = false (rejection)
|
||||
false, // createPolicy = false
|
||||
true, // stopStream = true (this is the new behavior)
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -272,7 +272,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
}}
|
||||
requestId="test-request-n-key"
|
||||
onResponse={handleResponse}
|
||||
/>
|
||||
/>,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
|
|
@ -285,24 +285,22 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
// Verify the 'n' key triggers the stopStream behavior
|
||||
expect(handleResponse).toHaveBeenCalledWith(
|
||||
"test-request-n-key",
|
||||
false, // approved = false (rejection)
|
||||
false, // createPolicy = false
|
||||
true // stopStream = true (this is the new behavior)
|
||||
false, // approved = false (rejection)
|
||||
false, // createPolicy = false
|
||||
true, // stopStream = true (this is the new behavior)
|
||||
);
|
||||
});
|
||||
|
||||
it("shows tool result with red dot and 'Cancelled by user' message", async () => {
|
||||
// Import the components we need for this test
|
||||
const { ToolResultSummary } = await import(
|
||||
"../ToolResultSummary.js"
|
||||
);
|
||||
const { ToolResultSummary } = await import("../ToolResultSummary.js");
|
||||
const { MemoizedMessage } = await import(
|
||||
"../components/MemoizedMessage.js"
|
||||
);
|
||||
|
||||
// Test the ToolResultSummary component directly
|
||||
const { lastFrame: summaryFrame } = render(
|
||||
<ToolResultSummary toolName="Edit" content="Permission denied by user" />
|
||||
<ToolResultSummary toolName="Edit" content="Permission denied by user" />,
|
||||
);
|
||||
|
||||
const summary = summaryFrame();
|
||||
|
|
@ -318,7 +316,7 @@ describe("TUIChat - Tool Permission Tests", () => {
|
|||
};
|
||||
|
||||
const { lastFrame: messageFrame } = render(
|
||||
<MemoizedMessage message={message} index={0} />
|
||||
<MemoizedMessage message={message} index={0} />,
|
||||
);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
|
|
|
|||
|
|
@ -1,68 +1,67 @@
|
|||
import { render } from 'ink-testing-library';
|
||||
import React from 'react';
|
||||
import { describe, expect, it, beforeEach } from 'vitest';
|
||||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it, beforeEach } from "vitest";
|
||||
|
||||
import { modeService } from '../../services/ModeService.js';
|
||||
import { modeService } from "../../services/ModeService.js";
|
||||
|
||||
import { ModeIndicator } from './ModeIndicator.js';
|
||||
import { ModeIndicator } from "./ModeIndicator.js";
|
||||
|
||||
|
||||
describe('ModeIndicator', () => {
|
||||
describe("ModeIndicator", () => {
|
||||
beforeEach(() => {
|
||||
// Reset to normal mode for each test
|
||||
modeService.initialize({});
|
||||
});
|
||||
|
||||
describe('mode display', () => {
|
||||
it('should not render anything for normal mode', () => {
|
||||
describe("mode display", () => {
|
||||
it("should not render anything for normal mode", () => {
|
||||
const { lastFrame } = render(<ModeIndicator />);
|
||||
expect(lastFrame()).toBe('');
|
||||
expect(lastFrame()).toBe("");
|
||||
});
|
||||
|
||||
it('should display plan mode with blue color', () => {
|
||||
it("should display plan mode with blue color", () => {
|
||||
const { lastFrame } = render(<ModeIndicator mode="plan" />);
|
||||
expect(lastFrame()).toContain('[plan]');
|
||||
expect(lastFrame()).toContain("[plan]");
|
||||
});
|
||||
|
||||
it('should display auto mode with green color', () => {
|
||||
it("should display auto mode with green color", () => {
|
||||
const { lastFrame } = render(<ModeIndicator mode="auto" />);
|
||||
expect(lastFrame()).toContain('[auto]');
|
||||
expect(lastFrame()).toContain("[auto]");
|
||||
});
|
||||
|
||||
it('should use current mode from service when no mode prop provided', () => {
|
||||
modeService.switchMode('plan');
|
||||
it("should use current mode from service when no mode prop provided", () => {
|
||||
modeService.switchMode("plan");
|
||||
const { lastFrame } = render(<ModeIndicator />);
|
||||
expect(lastFrame()).toContain('[plan]');
|
||||
expect(lastFrame()).toContain("[plan]");
|
||||
});
|
||||
|
||||
it('should prioritize mode prop over service mode', () => {
|
||||
modeService.switchMode('plan');
|
||||
it("should prioritize mode prop over service mode", () => {
|
||||
modeService.switchMode("plan");
|
||||
const { lastFrame } = render(<ModeIndicator mode="auto" />);
|
||||
expect(lastFrame()).toContain('[auto]');
|
||||
expect(lastFrame()).toContain("[auto]");
|
||||
});
|
||||
});
|
||||
|
||||
describe('mode changes', () => {
|
||||
it('should update when mode changes in service', () => {
|
||||
describe("mode changes", () => {
|
||||
it("should update when mode changes in service", () => {
|
||||
const { lastFrame, rerender } = render(<ModeIndicator />);
|
||||
|
||||
|
||||
// Initially normal (no display)
|
||||
expect(lastFrame()).toBe('');
|
||||
|
||||
expect(lastFrame()).toBe("");
|
||||
|
||||
// Switch to plan
|
||||
modeService.switchMode('plan');
|
||||
modeService.switchMode("plan");
|
||||
rerender(<ModeIndicator />);
|
||||
expect(lastFrame()).toContain('[plan]');
|
||||
|
||||
expect(lastFrame()).toContain("[plan]");
|
||||
|
||||
// Switch to auto
|
||||
modeService.switchMode('auto');
|
||||
modeService.switchMode("auto");
|
||||
rerender(<ModeIndicator />);
|
||||
expect(lastFrame()).toContain('[auto]');
|
||||
|
||||
expect(lastFrame()).toContain("[auto]");
|
||||
|
||||
// Switch back to normal
|
||||
modeService.switchMode('normal');
|
||||
modeService.switchMode("normal");
|
||||
rerender(<ModeIndicator />);
|
||||
expect(lastFrame()).toBe('');
|
||||
expect(lastFrame()).toBe("");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -71,8 +71,10 @@ describe("formatArgs function", () => {
|
|||
});
|
||||
|
||||
it("should handle special characters", () => {
|
||||
expect(formatArgs({ path: "/special/chars!@#$%^&*()_+" })).toBe("/special/chars!@#$%^&*()_+");
|
||||
expect(formatArgs({ path: "/special/chars!@#$%^&*()_+" })).toBe(
|
||||
"/special/chars!@#$%^&*()_+",
|
||||
);
|
||||
expect(formatArgs({ emoji: "🎉🎊✨" })).toBe("🎉🎊✨");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,7 +5,11 @@ import { renderHook, act } from "@testing-library/react";
|
|||
import React from "react";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import { NavigationProvider, useNavigation, NavigationScreen } from "../NavigationContext.js";
|
||||
import {
|
||||
NavigationProvider,
|
||||
useNavigation,
|
||||
NavigationScreen,
|
||||
} from "../NavigationContext.js";
|
||||
|
||||
describe("NavigationContext", () => {
|
||||
// Helper to create wrapper
|
||||
|
|
@ -163,13 +167,9 @@ describe("NavigationContext", () => {
|
|||
|
||||
it("closes from any screen back to chat", () => {
|
||||
const { result } = renderHook(() => useNavigation(), { wrapper });
|
||||
const screens: Array<"config" | "model" | "free-trial" | "login" | "mcp"> = [
|
||||
"config",
|
||||
"model",
|
||||
"free-trial",
|
||||
"login",
|
||||
"mcp",
|
||||
];
|
||||
const screens: Array<
|
||||
"config" | "model" | "free-trial" | "login" | "mcp"
|
||||
> = ["config", "model", "free-trial", "login", "mcp"];
|
||||
|
||||
screens.forEach((screen) => {
|
||||
act(() => {
|
||||
|
|
@ -257,8 +257,12 @@ describe("NavigationContext", () => {
|
|||
result.current.navigateTo("login", { different: "data" });
|
||||
});
|
||||
|
||||
expect(result.current.state.currentScreen).toBe(stateWithData.currentScreen);
|
||||
expect(result.current.state.screenData).not.toBe(stateWithData.screenData);
|
||||
expect(result.current.state.currentScreen).toBe(
|
||||
stateWithData.currentScreen,
|
||||
);
|
||||
expect(result.current.state.screenData).not.toBe(
|
||||
stateWithData.screenData,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -269,9 +273,9 @@ describe("NavigationContext", () => {
|
|||
|
||||
// Navigate to login with resolve callback
|
||||
act(() => {
|
||||
result.current.navigateTo("login", {
|
||||
text: "Please log in",
|
||||
resolve: mockResolve
|
||||
result.current.navigateTo("login", {
|
||||
text: "Please log in",
|
||||
resolve: mockResolve,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -344,4 +348,4 @@ describe("NavigationContext", () => {
|
|||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,4 @@
|
|||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createMinimalTestContext } from "../../test-helpers/ui-test-context.js";
|
||||
|
||||
|
|
@ -54,4 +47,4 @@ describe("useChat", () => {
|
|||
cleanup();
|
||||
expect(pollInterval).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,32 +1,32 @@
|
|||
import { describe, expect, test } from 'vitest';
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
describe('useConfigSelector', () => {
|
||||
test('hook updated to use reactive service pattern', () => {
|
||||
describe("useConfigSelector", () => {
|
||||
test("hook updated to use reactive service pattern", () => {
|
||||
// This test documents that useConfigSelector has been updated
|
||||
|
||||
|
||||
// Changes made:
|
||||
// 1. Removed manual onAssistantChange callback
|
||||
// 2. Now calls services.config.updateConfigPath()
|
||||
// 2. Now calls services.config.updateConfigPath()
|
||||
// 3. Lets ServiceContainer handle dependency management
|
||||
// 4. Allows automatic UI updates via reactive system
|
||||
|
||||
|
||||
// The hook now properly:
|
||||
// - Handles local config selection
|
||||
// - Handles assistant config selection
|
||||
// - Handles create config option
|
||||
// - Provides error handling
|
||||
// - Triggers reactive updates
|
||||
|
||||
expect('hook').toBe('hook');
|
||||
|
||||
expect("hook").toBe("hook");
|
||||
});
|
||||
|
||||
test('integrates with reactive service system', () => {
|
||||
test("integrates with reactive service system", () => {
|
||||
// The hook integration follows the correct pattern:
|
||||
// - User interaction → service method call
|
||||
// - Service handles state update and notification
|
||||
// - Service handles state update and notification
|
||||
// - ServiceContainer manages dependency cascade
|
||||
// - UI components re-render automatically
|
||||
|
||||
expect('integration').toBe('integration');
|
||||
|
||||
expect("integration").toBe("integration");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,42 +1,53 @@
|
|||
import { isValidAnthropicApiKey, getApiKeyValidationError } from './apiKeyValidation.js';
|
||||
import {
|
||||
isValidAnthropicApiKey,
|
||||
getApiKeyValidationError,
|
||||
} from "./apiKeyValidation.js";
|
||||
|
||||
describe('isValidAnthropicApiKey', () => {
|
||||
it('should return true for valid API keys', () => {
|
||||
expect(isValidAnthropicApiKey('TEST-ant-1234567890')).toBe(true);
|
||||
expect(isValidAnthropicApiKey('TEST-ant-abcdefghijklmnop')).toBe(true);
|
||||
expect(isValidAnthropicApiKey('TEST-ant-test-key-with-dashes')).toBe(true);
|
||||
expect(isValidAnthropicApiKey('TEST-ant-api03_T3BlbkFJ1234567890abcdef')).toBe(true);
|
||||
describe("isValidAnthropicApiKey", () => {
|
||||
it("should return true for valid API keys", () => {
|
||||
expect(isValidAnthropicApiKey("TEST-ant-1234567890")).toBe(true);
|
||||
expect(isValidAnthropicApiKey("TEST-ant-abcdefghijklmnop")).toBe(true);
|
||||
expect(isValidAnthropicApiKey("TEST-ant-test-key-with-dashes")).toBe(true);
|
||||
expect(
|
||||
isValidAnthropicApiKey("TEST-ant-api03_T3BlbkFJ1234567890abcdef"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should return false for invalid API keys', () => {
|
||||
expect(isValidAnthropicApiKey('')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('TEST-ant-')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('TEST-')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('TEST-openai-1234567890')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('invalid-key')).toBe(false);
|
||||
expect(isValidAnthropicApiKey('1234567890')).toBe(false);
|
||||
it("should return false for invalid API keys", () => {
|
||||
expect(isValidAnthropicApiKey("")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("TEST-ant-")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("TEST-")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("TEST-openai-1234567890")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("invalid-key")).toBe(false);
|
||||
expect(isValidAnthropicApiKey("1234567890")).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for null or undefined', () => {
|
||||
it("should return false for null or undefined", () => {
|
||||
expect(isValidAnthropicApiKey(null)).toBe(false);
|
||||
expect(isValidAnthropicApiKey(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false for non-string values', () => {
|
||||
it("should return false for non-string values", () => {
|
||||
expect(isValidAnthropicApiKey(123 as any)).toBe(false);
|
||||
expect(isValidAnthropicApiKey({} as any)).toBe(false);
|
||||
expect(isValidAnthropicApiKey([] as any)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getApiKeyValidationError', () => {
|
||||
it('should return appropriate error messages', () => {
|
||||
expect(getApiKeyValidationError('')).toBe('API key is required');
|
||||
expect(getApiKeyValidationError(null)).toBe('API key is required');
|
||||
expect(getApiKeyValidationError(undefined)).toBe('API key is required');
|
||||
expect(getApiKeyValidationError('TEST-')).toBe('API key must start with "TEST-ant-"');
|
||||
expect(getApiKeyValidationError('TEST-openai-1234')).toBe('API key must start with "TEST-ant-"');
|
||||
expect(getApiKeyValidationError('TEST-ant-')).toBe('API key is too short');
|
||||
expect(getApiKeyValidationError('invalid')).toBe('API key must start with "TEST-ant-"');
|
||||
describe("getApiKeyValidationError", () => {
|
||||
it("should return appropriate error messages", () => {
|
||||
expect(getApiKeyValidationError("")).toBe("API key is required");
|
||||
expect(getApiKeyValidationError(null)).toBe("API key is required");
|
||||
expect(getApiKeyValidationError(undefined)).toBe("API key is required");
|
||||
expect(getApiKeyValidationError("TEST-")).toBe(
|
||||
'API key must start with "TEST-ant-"',
|
||||
);
|
||||
expect(getApiKeyValidationError("TEST-openai-1234")).toBe(
|
||||
'API key must start with "TEST-ant-"',
|
||||
);
|
||||
expect(getApiKeyValidationError("TEST-ant-")).toBe("API key is too short");
|
||||
expect(getApiKeyValidationError("invalid")).toBe(
|
||||
'API key must start with "TEST-ant-"',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -39,11 +39,13 @@ function isRetryableError(error: any): boolean {
|
|||
}
|
||||
|
||||
// Check for premature close errors by message content
|
||||
if (lower?.includes("premature close") ||
|
||||
lower?.includes("premature end") ||
|
||||
lower?.includes("connection reset") ||
|
||||
lower?.includes("socket hang up") ||
|
||||
lower?.includes("aborted")) {
|
||||
if (
|
||||
lower?.includes("premature close") ||
|
||||
lower?.includes("premature end") ||
|
||||
lower?.includes("connection reset") ||
|
||||
lower?.includes("socket hang up") ||
|
||||
lower?.includes("aborted")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -52,7 +54,7 @@ function isRetryableError(error: any): boolean {
|
|||
|
||||
function calculateDelay(
|
||||
attempt: number,
|
||||
options: Required<ExponentialBackoffOptions>
|
||||
options: Required<ExponentialBackoffOptions>,
|
||||
): number {
|
||||
const baseDelay =
|
||||
options.initialDelay * Math.pow(options.backoffMultiplier, attempt);
|
||||
|
|
@ -270,7 +272,7 @@ describe("exponentialBackoff utilities", () => {
|
|||
|
||||
// Mock Math.random to return 0.5 (middle of jitter range)
|
||||
const originalRandom = Math.random;
|
||||
vi.spyOn(Math, 'random').mockReturnValue(0.5);
|
||||
vi.spyOn(Math, "random").mockReturnValue(0.5);
|
||||
|
||||
// With jitter factor of 0.5 + 0.5 * 0.5 = 0.75
|
||||
expect(calculateDelay(0, options)).toBe(750); // 1000 * 0.75
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { FileWatcher } from './fileWatcher.js';
|
||||
import { FileWatcher } from "./fileWatcher.js";
|
||||
|
||||
describe('FileWatcher', () => {
|
||||
describe("FileWatcher", () => {
|
||||
let tempDir: string;
|
||||
let watcher: FileWatcher;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create a temporary directory for testing
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filewatcher-test-'));
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "filewatcher-test-"));
|
||||
watcher = new FileWatcher({
|
||||
debounceMs: 100, // Shorter debounce for tests
|
||||
maxDepth: 2
|
||||
maxDepth: 2,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -27,25 +27,25 @@ describe('FileWatcher', () => {
|
|||
}
|
||||
});
|
||||
|
||||
it.skip('should detect when new files are created', async () => {
|
||||
it.skip("should detect when new files are created", async () => {
|
||||
const callback = vi.fn();
|
||||
watcher.onChange(callback);
|
||||
watcher.startWatching(tempDir);
|
||||
|
||||
// Create a new file
|
||||
const testFile = path.join(tempDir, 'test.txt');
|
||||
fs.writeFileSync(testFile, 'test content');
|
||||
const testFile = path.join(tempDir, "test.txt");
|
||||
fs.writeFileSync(testFile, "test content");
|
||||
|
||||
// Wait for debounce
|
||||
await new Promise(resolve => setTimeout(resolve, 150));
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
|
||||
expect(callback).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.skip('should detect when files are deleted', async () => {
|
||||
it.skip("should detect when files are deleted", async () => {
|
||||
// Create a file first
|
||||
const testFile = path.join(tempDir, 'test.txt');
|
||||
fs.writeFileSync(testFile, 'test content');
|
||||
const testFile = path.join(tempDir, "test.txt");
|
||||
fs.writeFileSync(testFile, "test content");
|
||||
|
||||
const callback = vi.fn();
|
||||
watcher.onChange(callback);
|
||||
|
|
@ -55,16 +55,16 @@ describe('FileWatcher', () => {
|
|||
fs.unlinkSync(testFile);
|
||||
|
||||
// Wait for debounce
|
||||
await new Promise(resolve => setTimeout(resolve, 150));
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
|
||||
expect(callback).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore paths that match ignore patterns', async () => {
|
||||
it("should ignore paths that match ignore patterns", async () => {
|
||||
// Pre-create the node_modules directory to avoid directory creation events
|
||||
const nodeModulesDir = path.join(tempDir, 'node_modules');
|
||||
const nodeModulesDir = path.join(tempDir, "node_modules");
|
||||
fs.mkdirSync(nodeModulesDir);
|
||||
|
||||
|
||||
const callback = vi.fn();
|
||||
watcher.onChange(callback);
|
||||
watcher.startWatching(tempDir);
|
||||
|
|
@ -72,94 +72,94 @@ describe('FileWatcher', () => {
|
|||
// Wait longer to ensure watcher is fully initialized and settled
|
||||
// Increase timeout for CI environments where file system events may be slower
|
||||
// Account for the 50ms initialization delay plus extra time for CI
|
||||
await new Promise(resolve => setTimeout(resolve, 600));
|
||||
await new Promise((resolve) => setTimeout(resolve, 600));
|
||||
|
||||
// Reset the callback mock to ignore any initialization events
|
||||
callback.mockClear();
|
||||
|
||||
// Create a file in node_modules (should be ignored)
|
||||
const testFile = path.join(nodeModulesDir, 'test.js');
|
||||
fs.writeFileSync(testFile, 'test content');
|
||||
const testFile = path.join(nodeModulesDir, "test.js");
|
||||
fs.writeFileSync(testFile, "test content");
|
||||
|
||||
// Wait for debounce with longer timeout for CI environments
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
// Should not have been called because node_modules is ignored
|
||||
expect(callback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore files matching wildcard patterns like **/*.tmp', async () => {
|
||||
it("should ignore files matching wildcard patterns like **/*.tmp", async () => {
|
||||
const callback = vi.fn();
|
||||
watcher.onChange(callback);
|
||||
watcher.startWatching(tempDir);
|
||||
|
||||
// Wait for watcher to initialize with longer timeout for CI
|
||||
// Account for the 50ms initialization delay plus extra time for CI
|
||||
await new Promise(resolve => setTimeout(resolve, 600));
|
||||
await new Promise((resolve) => setTimeout(resolve, 600));
|
||||
callback.mockClear();
|
||||
|
||||
// Create a .tmp file (should be ignored by **/*.tmp pattern)
|
||||
const tmpFile = path.join(tempDir, 'test.tmp');
|
||||
fs.writeFileSync(tmpFile, 'temporary content');
|
||||
const tmpFile = path.join(tempDir, "test.tmp");
|
||||
fs.writeFileSync(tmpFile, "temporary content");
|
||||
|
||||
// Create a .log file (should be ignored by **/*.log pattern)
|
||||
const logFile = path.join(tempDir, 'debug.log');
|
||||
fs.writeFileSync(logFile, 'log content');
|
||||
const logFile = path.join(tempDir, "debug.log");
|
||||
fs.writeFileSync(logFile, "log content");
|
||||
|
||||
// Create a .min.js file (should be ignored by **/*.min.js pattern)
|
||||
const minJsFile = path.join(tempDir, 'bundle.min.js');
|
||||
fs.writeFileSync(minJsFile, 'minified js');
|
||||
const minJsFile = path.join(tempDir, "bundle.min.js");
|
||||
fs.writeFileSync(minJsFile, "minified js");
|
||||
|
||||
// Wait for debounce with longer timeout for CI
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
// Should not have been called because all files match ignore patterns
|
||||
expect(callback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore specific files like .DS_Store', async () => {
|
||||
it("should ignore specific files like .DS_Store", async () => {
|
||||
const callback = vi.fn();
|
||||
watcher.onChange(callback);
|
||||
watcher.startWatching(tempDir);
|
||||
|
||||
// Wait for watcher to initialize with longer timeout for CI
|
||||
// Account for the 50ms initialization delay plus extra time for CI
|
||||
await new Promise(resolve => setTimeout(resolve, 600));
|
||||
await new Promise((resolve) => setTimeout(resolve, 600));
|
||||
callback.mockClear();
|
||||
|
||||
// Create .DS_Store file (should be ignored by **/.DS_Store pattern)
|
||||
const dsStoreFile = path.join(tempDir, '.DS_Store');
|
||||
fs.writeFileSync(dsStoreFile, 'ds store content');
|
||||
const dsStoreFile = path.join(tempDir, ".DS_Store");
|
||||
fs.writeFileSync(dsStoreFile, "ds store content");
|
||||
|
||||
// Wait for debounce with longer timeout for CI
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
// Should not have been called because .DS_Store matches ignore pattern
|
||||
expect(callback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should detect files that do not match ignore patterns', async () => {
|
||||
it("should detect files that do not match ignore patterns", async () => {
|
||||
const callback = vi.fn();
|
||||
watcher.onChange(callback);
|
||||
watcher.startWatching(tempDir);
|
||||
|
||||
// Wait for watcher to initialize with longer timeout for CI
|
||||
// Account for the 50ms initialization delay plus extra time for CI
|
||||
await new Promise(resolve => setTimeout(resolve, 600));
|
||||
await new Promise((resolve) => setTimeout(resolve, 600));
|
||||
callback.mockClear();
|
||||
|
||||
// Create a .js file (should NOT be ignored)
|
||||
const jsFile = path.join(tempDir, 'test.js');
|
||||
const jsFile = path.join(tempDir, "test.js");
|
||||
fs.writeFileSync(jsFile, 'console.log("hello");');
|
||||
|
||||
// Wait for debounce with longer timeout for CI
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
// Should have been called because .js files are not in ignore patterns
|
||||
expect(callback).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should allow unsubscribing from callbacks', async () => {
|
||||
it("should allow unsubscribing from callbacks", async () => {
|
||||
const callback = vi.fn();
|
||||
const unsubscribe = watcher.onChange(callback);
|
||||
watcher.startWatching(tempDir);
|
||||
|
|
@ -168,43 +168,43 @@ describe('FileWatcher', () => {
|
|||
unsubscribe();
|
||||
|
||||
// Create a new file
|
||||
const testFile = path.join(tempDir, 'test.txt');
|
||||
fs.writeFileSync(testFile, 'test content');
|
||||
const testFile = path.join(tempDir, "test.txt");
|
||||
fs.writeFileSync(testFile, "test content");
|
||||
|
||||
// Wait for debounce
|
||||
await new Promise(resolve => setTimeout(resolve, 150));
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
|
||||
// Should not have been called because we unsubscribed
|
||||
expect(callback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('shouldIgnorePath method', () => {
|
||||
it('should correctly ignore wildcard file patterns', () => {
|
||||
describe("shouldIgnorePath method", () => {
|
||||
it("should correctly ignore wildcard file patterns", () => {
|
||||
const watcher = new FileWatcher();
|
||||
|
||||
|
||||
// Test the private method by accessing it through prototype
|
||||
const shouldIgnorePath = (watcher as any).shouldIgnorePath.bind(watcher);
|
||||
|
||||
|
||||
// Test wildcard file patterns
|
||||
expect(shouldIgnorePath('/some/path/file.tmp')).toBe(true);
|
||||
expect(shouldIgnorePath('/some/path/file.log')).toBe(true);
|
||||
expect(shouldIgnorePath('/some/path/bundle.min.js')).toBe(true);
|
||||
expect(shouldIgnorePath('/some/path/styles.min.css')).toBe(true);
|
||||
|
||||
expect(shouldIgnorePath("/some/path/file.tmp")).toBe(true);
|
||||
expect(shouldIgnorePath("/some/path/file.log")).toBe(true);
|
||||
expect(shouldIgnorePath("/some/path/bundle.min.js")).toBe(true);
|
||||
expect(shouldIgnorePath("/some/path/styles.min.css")).toBe(true);
|
||||
|
||||
// Test files that should NOT be ignored
|
||||
expect(shouldIgnorePath('/some/path/file.js')).toBe(false);
|
||||
expect(shouldIgnorePath('/some/path/file.ts')).toBe(false);
|
||||
expect(shouldIgnorePath('/some/path/README.md')).toBe(false);
|
||||
|
||||
expect(shouldIgnorePath("/some/path/file.js")).toBe(false);
|
||||
expect(shouldIgnorePath("/some/path/file.ts")).toBe(false);
|
||||
expect(shouldIgnorePath("/some/path/README.md")).toBe(false);
|
||||
|
||||
// Test specific files
|
||||
expect(shouldIgnorePath('/some/path/.DS_Store')).toBe(true);
|
||||
expect(shouldIgnorePath('/some/path/Thumbs.db')).toBe(true);
|
||||
|
||||
expect(shouldIgnorePath("/some/path/.DS_Store")).toBe(true);
|
||||
expect(shouldIgnorePath("/some/path/Thumbs.db")).toBe(true);
|
||||
|
||||
// Test directory patterns
|
||||
expect(shouldIgnorePath('/some/path/node_modules')).toBe(true);
|
||||
expect(shouldIgnorePath('/some/path/node_modules/package')).toBe(true);
|
||||
expect(shouldIgnorePath('/path/dist')).toBe(true);
|
||||
expect(shouldIgnorePath('/path/.git')).toBe(true);
|
||||
expect(shouldIgnorePath("/some/path/node_modules")).toBe(true);
|
||||
expect(shouldIgnorePath("/some/path/node_modules/package")).toBe(true);
|
||||
expect(shouldIgnorePath("/path/dist")).toBe(true);
|
||||
expect(shouldIgnorePath("/path/.git")).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,151 +1,155 @@
|
|||
import { formatError, formatAnthropicError } from './formatError.js';
|
||||
import { formatError, formatAnthropicError } from "./formatError.js";
|
||||
|
||||
describe('formatError', () => {
|
||||
it('should format Error objects correctly', () => {
|
||||
const error = new Error('Test error message');
|
||||
expect(formatError(error)).toBe('Test error message');
|
||||
describe("formatError", () => {
|
||||
it("should format Error objects correctly", () => {
|
||||
const error = new Error("Test error message");
|
||||
expect(formatError(error)).toBe("Test error message");
|
||||
});
|
||||
|
||||
it('should return string errors as-is', () => {
|
||||
const error = 'String error message';
|
||||
expect(formatError(error)).toBe('String error message');
|
||||
it("should return string errors as-is", () => {
|
||||
const error = "String error message";
|
||||
expect(formatError(error)).toBe("String error message");
|
||||
});
|
||||
|
||||
it('should extract message from error objects', () => {
|
||||
const error = { message: 'Object error message' };
|
||||
expect(formatError(error)).toBe('Object error message');
|
||||
it("should extract message from error objects", () => {
|
||||
const error = { message: "Object error message" };
|
||||
expect(formatError(error)).toBe("Object error message");
|
||||
});
|
||||
|
||||
it('should recursively format nested error objects', () => {
|
||||
const error = { error: { message: 'Nested error message' } };
|
||||
expect(formatError(error)).toBe('Nested error message');
|
||||
it("should recursively format nested error objects", () => {
|
||||
const error = { error: { message: "Nested error message" } };
|
||||
expect(formatError(error)).toBe("Nested error message");
|
||||
});
|
||||
|
||||
it('should extract details from error objects', () => {
|
||||
const error = { details: 'Error details' };
|
||||
expect(formatError(error)).toBe('Error details');
|
||||
it("should extract details from error objects", () => {
|
||||
const error = { details: "Error details" };
|
||||
expect(formatError(error)).toBe("Error details");
|
||||
});
|
||||
|
||||
it('should extract description from error objects', () => {
|
||||
const error = { description: 'Error description' };
|
||||
expect(formatError(error)).toBe('Error description');
|
||||
it("should extract description from error objects", () => {
|
||||
const error = { description: "Error description" };
|
||||
expect(formatError(error)).toBe("Error description");
|
||||
});
|
||||
|
||||
it('should format API errors with status and message', () => {
|
||||
it("should format API errors with status and message", () => {
|
||||
const error = {
|
||||
status: 404,
|
||||
error: { message: 'Not found' }
|
||||
error: { message: "Not found" },
|
||||
};
|
||||
// The actual implementation prioritizes nested error.message over status formatting
|
||||
expect(formatError(error)).toBe('Not found');
|
||||
expect(formatError(error)).toBe("Not found");
|
||||
});
|
||||
|
||||
it('should format network errors with code and syscall', () => {
|
||||
it("should format network errors with code and syscall", () => {
|
||||
const error = {
|
||||
code: 'ECONNREFUSED',
|
||||
syscall: 'connect'
|
||||
code: "ECONNREFUSED",
|
||||
syscall: "connect",
|
||||
};
|
||||
expect(formatError(error)).toBe('Network error: ECONNREFUSED in connect');
|
||||
expect(formatError(error)).toBe("Network error: ECONNREFUSED in connect");
|
||||
});
|
||||
|
||||
it('should join error arrays', () => {
|
||||
it("should join error arrays", () => {
|
||||
const error = {
|
||||
errors: ['First error', 'Second error', 'Third error']
|
||||
errors: ["First error", "Second error", "Third error"],
|
||||
};
|
||||
expect(formatError(error)).toBe('First error, Second error, Third error');
|
||||
expect(formatError(error)).toBe("First error, Second error, Third error");
|
||||
});
|
||||
|
||||
it('should JSON stringify complex objects', () => {
|
||||
it("should JSON stringify complex objects", () => {
|
||||
const error = {
|
||||
code: 'CUSTOM_ERROR',
|
||||
data: { id: 123, name: 'test' }
|
||||
code: "CUSTOM_ERROR",
|
||||
data: { id: 123, name: "test" },
|
||||
};
|
||||
expect(formatError(error)).toBe('{"code":"CUSTOM_ERROR","data":{"id":123,"name":"test"}}');
|
||||
expect(formatError(error)).toBe(
|
||||
'{"code":"CUSTOM_ERROR","data":{"id":123,"name":"test"}}',
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle objects that cannot be JSON stringified', () => {
|
||||
const circular: any = { name: 'circular' };
|
||||
it("should handle objects that cannot be JSON stringified", () => {
|
||||
const circular: any = { name: "circular" };
|
||||
circular.self = circular;
|
||||
|
||||
const result = formatError(circular);
|
||||
expect(result).toBe('An error occurred: [object Object]');
|
||||
expect(result).toBe("An error occurred: [object Object]");
|
||||
});
|
||||
|
||||
it('should handle null values', () => {
|
||||
expect(formatError(null)).toBe('null');
|
||||
it("should handle null values", () => {
|
||||
expect(formatError(null)).toBe("null");
|
||||
});
|
||||
|
||||
it('should handle undefined values', () => {
|
||||
expect(formatError(undefined)).toBe('undefined');
|
||||
it("should handle undefined values", () => {
|
||||
expect(formatError(undefined)).toBe("undefined");
|
||||
});
|
||||
|
||||
it('should handle numbers', () => {
|
||||
expect(formatError(42)).toBe('42');
|
||||
it("should handle numbers", () => {
|
||||
expect(formatError(42)).toBe("42");
|
||||
});
|
||||
|
||||
it('should handle boolean values', () => {
|
||||
expect(formatError(true)).toBe('true');
|
||||
expect(formatError(false)).toBe('false');
|
||||
it("should handle boolean values", () => {
|
||||
expect(formatError(true)).toBe("true");
|
||||
expect(formatError(false)).toBe("false");
|
||||
});
|
||||
|
||||
it('should handle empty objects', () => {
|
||||
expect(formatError({})).toBe('{}');
|
||||
it("should handle empty objects", () => {
|
||||
expect(formatError({})).toBe("{}");
|
||||
});
|
||||
|
||||
it('should handle empty arrays', () => {
|
||||
expect(formatError([])).toBe('[]');
|
||||
it("should handle empty arrays", () => {
|
||||
expect(formatError([])).toBe("[]");
|
||||
});
|
||||
|
||||
it('should prioritize message over other properties', () => {
|
||||
it("should prioritize message over other properties", () => {
|
||||
const error = {
|
||||
message: 'Primary message',
|
||||
description: 'Secondary description',
|
||||
details: 'Tertiary details'
|
||||
message: "Primary message",
|
||||
description: "Secondary description",
|
||||
details: "Tertiary details",
|
||||
};
|
||||
expect(formatError(error)).toBe('Primary message');
|
||||
expect(formatError(error)).toBe("Primary message");
|
||||
});
|
||||
|
||||
it('should prioritize error property over details', () => {
|
||||
it("should prioritize error property over details", () => {
|
||||
const error = {
|
||||
error: 'Nested error',
|
||||
details: 'Error details'
|
||||
error: "Nested error",
|
||||
details: "Error details",
|
||||
};
|
||||
expect(formatError(error)).toBe('Nested error');
|
||||
expect(formatError(error)).toBe("Nested error");
|
||||
});
|
||||
|
||||
it('should handle deeply nested error structures', () => {
|
||||
it("should handle deeply nested error structures", () => {
|
||||
const error = {
|
||||
error: {
|
||||
error: {
|
||||
message: 'Deep nested error'
|
||||
}
|
||||
}
|
||||
message: "Deep nested error",
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(formatError(error)).toBe('Deep nested error');
|
||||
expect(formatError(error)).toBe("Deep nested error");
|
||||
});
|
||||
|
||||
it('should format API errors with status only when no nested error message', () => {
|
||||
it("should format API errors with status only when no nested error message", () => {
|
||||
const error = {
|
||||
status: 404,
|
||||
error: { code: 'NOT_FOUND' }
|
||||
error: { code: "NOT_FOUND" },
|
||||
};
|
||||
expect(formatError(error)).toBe('{"code":"NOT_FOUND"}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatAnthropicError', () => {
|
||||
it('should format invalid API key authentication errors', () => {
|
||||
const error = new Error('{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}');
|
||||
expect(formatAnthropicError(error)).toBe('Anthropic: Invalid API key');
|
||||
describe("formatAnthropicError", () => {
|
||||
it("should format invalid API key authentication errors", () => {
|
||||
const error = new Error(
|
||||
'{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}',
|
||||
);
|
||||
expect(formatAnthropicError(error)).toBe("Anthropic: Invalid API key");
|
||||
});
|
||||
|
||||
it('should handle error objects in general', () => {
|
||||
const error = new Error('some error'); // some error we haven't catalogued yet
|
||||
console.log(formatAnthropicError(error))
|
||||
expect(formatAnthropicError(error)).toBe('Anthropic: some error');
|
||||
it("should handle error objects in general", () => {
|
||||
const error = new Error("some error"); // some error we haven't catalogued yet
|
||||
console.log(formatAnthropicError(error));
|
||||
expect(formatAnthropicError(error)).toBe("Anthropic: some error");
|
||||
});
|
||||
|
||||
it('should handle undefined values', () => {
|
||||
expect(formatAnthropicError(undefined)).toBe('Anthropic: undefined');
|
||||
it("should handle undefined values", () => {
|
||||
expect(formatAnthropicError(undefined)).toBe("Anthropic: undefined");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getGitHubActionsRepoUrl,
|
||||
isGitHubActions,
|
||||
} from "./git.js";
|
||||
import { getGitHubActionsRepoUrl, isGitHubActions } from "./git.js";
|
||||
|
||||
describe("git utilities - GitHub Actions detection", () => {
|
||||
beforeEach(() => {
|
||||
|
|
@ -42,7 +39,7 @@ describe("git utilities - GitHub Actions detection", () => {
|
|||
it("should return GitHub URL with default server", () => {
|
||||
process.env.GITHUB_ACTIONS = "true";
|
||||
process.env.GITHUB_REPOSITORY = "owner/repo";
|
||||
|
||||
|
||||
expect(getGitHubActionsRepoUrl()).toBe("https://github.com/owner/repo");
|
||||
});
|
||||
|
||||
|
|
@ -50,8 +47,10 @@ describe("git utilities - GitHub Actions detection", () => {
|
|||
process.env.GITHUB_ACTIONS = "true";
|
||||
process.env.GITHUB_REPOSITORY = "owner/repo";
|
||||
process.env.GITHUB_SERVER_URL = "https://github.enterprise.com";
|
||||
|
||||
expect(getGitHubActionsRepoUrl()).toBe("https://github.enterprise.com/owner/repo");
|
||||
|
||||
expect(getGitHubActionsRepoUrl()).toBe(
|
||||
"https://github.enterprise.com/owner/repo",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -59,7 +58,7 @@ describe("git utilities - GitHub Actions detection", () => {
|
|||
it("should prioritize GitHub Actions environment variables", () => {
|
||||
process.env.GITHUB_ACTIONS = "true";
|
||||
process.env.GITHUB_REPOSITORY = "owner/repo";
|
||||
|
||||
|
||||
// Since we can't easily mock git commands, we'll rely on the fact that
|
||||
// GitHub Actions detection should take priority and return immediately
|
||||
const result = getGitHubActionsRepoUrl();
|
||||
|
|
@ -70,9 +69,9 @@ describe("git utilities - GitHub Actions detection", () => {
|
|||
process.env.GITHUB_ACTIONS = "true";
|
||||
process.env.GITHUB_REPOSITORY = "enterprise/repo";
|
||||
process.env.GITHUB_SERVER_URL = "https://git.company.com";
|
||||
|
||||
|
||||
const result = getGitHubActionsRepoUrl();
|
||||
expect(result).toBe("https://git.company.com/enterprise/repo");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,55 +1,55 @@
|
|||
import { vi } from 'vitest';
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { InputHistory } from './inputHistory.js';
|
||||
import { InputHistory } from "./inputHistory.js";
|
||||
|
||||
// Mock fs to avoid creating actual files during tests
|
||||
vi.mock('fs', () => ({
|
||||
vi.mock("fs", () => ({
|
||||
default: {
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn()
|
||||
mkdirSync: vi.fn(),
|
||||
},
|
||||
existsSync: vi.fn(),
|
||||
readFileSync: vi.fn(),
|
||||
writeFileSync: vi.fn(),
|
||||
mkdirSync: vi.fn()
|
||||
mkdirSync: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('InputHistory', () => {
|
||||
describe("InputHistory", () => {
|
||||
let inputHistory: InputHistory;
|
||||
|
||||
beforeEach(async () => {
|
||||
// Reset mocks and set up default behavior
|
||||
vi.clearAllMocks();
|
||||
const fs = await import('fs');
|
||||
const fs = await import("fs");
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
vi.mocked(fs.readFileSync).mockReturnValue('[]');
|
||||
vi.mocked(fs.readFileSync).mockReturnValue("[]");
|
||||
|
||||
inputHistory = new InputHistory();
|
||||
});
|
||||
|
||||
describe('navigation with typed input preservation', () => {
|
||||
describe("navigation with typed input preservation", () => {
|
||||
beforeEach(() => {
|
||||
// Add some history entries
|
||||
inputHistory.addEntry('first command');
|
||||
inputHistory.addEntry('second command');
|
||||
inputHistory.addEntry("first command");
|
||||
inputHistory.addEntry("second command");
|
||||
});
|
||||
|
||||
it('should preserve typed input when navigating history', () => {
|
||||
const typedInput = 'user typed this';
|
||||
it("should preserve typed input when navigating history", () => {
|
||||
const typedInput = "user typed this";
|
||||
|
||||
// User types something then presses up arrow
|
||||
const historyEntry1 = inputHistory.navigateUp(typedInput);
|
||||
expect(historyEntry1).toBe('second command');
|
||||
expect(historyEntry1).toBe("second command");
|
||||
|
||||
// Then presses down arrow - should get back their typed input
|
||||
const returnedInput = inputHistory.navigateDown();
|
||||
expect(returnedInput).toBe('user typed this');
|
||||
expect(returnedInput).toBe("user typed this");
|
||||
});
|
||||
|
||||
it('should handle multiple up/down navigation cycles', () => {
|
||||
const typedInput = 'hello world';
|
||||
it("should handle multiple up/down navigation cycles", () => {
|
||||
const typedInput = "hello world";
|
||||
|
||||
// Navigate up twice, then back down twice
|
||||
inputHistory.navigateUp(typedInput);
|
||||
|
|
@ -57,32 +57,32 @@ describe('InputHistory', () => {
|
|||
inputHistory.navigateDown(); // Go back one in history
|
||||
const result = inputHistory.navigateDown(); // Go back to original
|
||||
|
||||
expect(result).toBe('hello world');
|
||||
expect(result).toBe("hello world");
|
||||
});
|
||||
});
|
||||
|
||||
describe('basic navigation functionality', () => {
|
||||
describe("basic navigation functionality", () => {
|
||||
beforeEach(() => {
|
||||
inputHistory.addEntry('command1');
|
||||
inputHistory.addEntry('command2');
|
||||
inputHistory.addEntry('command3');
|
||||
inputHistory.addEntry("command1");
|
||||
inputHistory.addEntry("command2");
|
||||
inputHistory.addEntry("command3");
|
||||
});
|
||||
|
||||
it('should navigate up through history in reverse order', () => {
|
||||
const result1 = inputHistory.navigateUp('current');
|
||||
expect(result1).toBe('command3'); // Most recent first
|
||||
it("should navigate up through history in reverse order", () => {
|
||||
const result1 = inputHistory.navigateUp("current");
|
||||
expect(result1).toBe("command3"); // Most recent first
|
||||
|
||||
const result2 = inputHistory.navigateUp('current');
|
||||
expect(result2).toBe('command2');
|
||||
const result2 = inputHistory.navigateUp("current");
|
||||
expect(result2).toBe("command2");
|
||||
|
||||
const result3 = inputHistory.navigateUp('current');
|
||||
expect(result3).toBe('command1');
|
||||
const result3 = inputHistory.navigateUp("current");
|
||||
expect(result3).toBe("command1");
|
||||
});
|
||||
|
||||
it('should handle navigation with no history', () => {
|
||||
it("should handle navigation with no history", () => {
|
||||
const emptyHistory = new InputHistory();
|
||||
const result = emptyHistory.navigateUp('test');
|
||||
const result = emptyHistory.navigateUp("test");
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -24,28 +24,28 @@ describe("stdin handling", () => {
|
|||
it("should return null in test environments", async () => {
|
||||
// Test that the function respects test environment variables
|
||||
process.env.NODE_ENV = "test";
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
|
||||
it("should return null when CONTINUE_CLI_TEST is set", async () => {
|
||||
process.env.CONTINUE_CLI_TEST = "true";
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
|
||||
it("should return null when VITEST is set", async () => {
|
||||
process.env.VITEST = "true";
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
|
||||
|
|
@ -55,13 +55,13 @@ describe("stdin handling", () => {
|
|||
delete process.env.VITEST;
|
||||
delete process.env.CONTINUE_CLI_TEST;
|
||||
delete process.env.JEST_WORKER_ID;
|
||||
|
||||
|
||||
// Mock stdin as TTY
|
||||
(process.stdin as any).isTTY = true;
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
|
||||
|
|
@ -71,17 +71,17 @@ describe("stdin handling", () => {
|
|||
delete process.env.VITEST;
|
||||
delete process.env.CONTINUE_CLI_TEST;
|
||||
delete process.env.JEST_WORKER_ID;
|
||||
|
||||
|
||||
// Mock stdin as not TTY (piped)
|
||||
(process.stdin as any).isTTY = false;
|
||||
|
||||
|
||||
// Mock fs.readFileSync to return test data
|
||||
const mockReadFileSync = vi.mocked(fs.readFileSync);
|
||||
mockReadFileSync.mockReturnValue("test input data");
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8");
|
||||
expect(result).toBe("test input data");
|
||||
});
|
||||
|
|
@ -92,19 +92,19 @@ describe("stdin handling", () => {
|
|||
delete process.env.VITEST;
|
||||
delete process.env.CONTINUE_CLI_TEST;
|
||||
delete process.env.JEST_WORKER_ID;
|
||||
|
||||
|
||||
// Mock stdin as not TTY
|
||||
(process.stdin as any).isTTY = false;
|
||||
|
||||
|
||||
// Mock fs.readFileSync to throw an error
|
||||
const mockReadFileSync = vi.mocked(fs.readFileSync);
|
||||
mockReadFileSync.mockImplementation(() => {
|
||||
throw new Error("EAGAIN: resource temporarily unavailable");
|
||||
});
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
|
||||
|
|
@ -114,17 +114,17 @@ describe("stdin handling", () => {
|
|||
delete process.env.VITEST;
|
||||
delete process.env.CONTINUE_CLI_TEST;
|
||||
delete process.env.JEST_WORKER_ID;
|
||||
|
||||
|
||||
// Mock stdin as not TTY
|
||||
(process.stdin as any).isTTY = false;
|
||||
|
||||
|
||||
// Mock fs.readFileSync to return data with whitespace
|
||||
const mockReadFileSync = vi.mocked(fs.readFileSync);
|
||||
mockReadFileSync.mockReturnValue(" test input with whitespace \n");
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(result).toBe("test input with whitespace");
|
||||
});
|
||||
|
||||
|
|
@ -134,17 +134,17 @@ describe("stdin handling", () => {
|
|||
delete process.env.VITEST;
|
||||
delete process.env.CONTINUE_CLI_TEST;
|
||||
delete process.env.JEST_WORKER_ID;
|
||||
|
||||
|
||||
// Mock stdin with undefined isTTY (some environments)
|
||||
(process.stdin as any).isTTY = undefined;
|
||||
|
||||
|
||||
// Mock fs.readFileSync to return test data
|
||||
const mockReadFileSync = vi.mocked(fs.readFileSync);
|
||||
mockReadFileSync.mockReturnValue("undefined tty test");
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(0, "utf8");
|
||||
expect(result).toBe("undefined tty test");
|
||||
});
|
||||
|
|
@ -156,13 +156,13 @@ describe("stdin handling", () => {
|
|||
delete process.env.CONTINUE_CLI_TEST;
|
||||
delete process.env.JEST_WORKER_ID;
|
||||
process.env.CI = "true";
|
||||
|
||||
|
||||
// Mock stdin as TTY in CI
|
||||
(process.stdin as any).isTTY = true;
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
// Should return null in CI when stdin is a TTY
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
|
|
@ -172,7 +172,7 @@ describe("stdin handling", () => {
|
|||
it("should work on different Node.js versions", async () => {
|
||||
// Test that the function doesn't rely on Node.js version-specific features
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
|
||||
|
||||
// Should not throw errors regardless of environment
|
||||
expect(() => readStdinSync()).not.toThrow();
|
||||
});
|
||||
|
|
@ -183,20 +183,20 @@ describe("stdin handling", () => {
|
|||
delete process.env.VITEST;
|
||||
delete process.env.CONTINUE_CLI_TEST;
|
||||
delete process.env.JEST_WORKER_ID;
|
||||
|
||||
|
||||
(process.stdin as any).isTTY = false;
|
||||
|
||||
|
||||
// Mock fs.readFileSync to simulate fd 0 not available
|
||||
const mockReadFileSync = vi.mocked(fs.readFileSync);
|
||||
mockReadFileSync.mockImplementation(() => {
|
||||
throw new Error("EBADF: bad file descriptor");
|
||||
});
|
||||
|
||||
|
||||
const { readStdinSync } = await import("./stdin.js");
|
||||
const result = readStdinSync();
|
||||
|
||||
|
||||
// Should handle the error gracefully
|
||||
expect(result).toBe(null);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ describe("withExponentialBackoff", () => {
|
|||
const results: string[] = [];
|
||||
const generator = withExponentialBackoff(
|
||||
generatorFactory,
|
||||
abortController.signal
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
for await (const chunk of generator) {
|
||||
|
|
@ -63,7 +63,7 @@ describe("withExponentialBackoff", () => {
|
|||
{
|
||||
maxRetries: 2,
|
||||
initialDelay: 10, // Short delay for testing
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
for await (const chunk of generator) {
|
||||
|
|
@ -83,7 +83,7 @@ describe("withExponentialBackoff", () => {
|
|||
|
||||
const generator = withExponentialBackoff(
|
||||
generatorFactory,
|
||||
abortController.signal
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
await expect(async () => {
|
||||
|
|
@ -107,7 +107,7 @@ describe("withExponentialBackoff", () => {
|
|||
|
||||
const generator = withExponentialBackoff(
|
||||
generatorFactory,
|
||||
abortController.signal
|
||||
abortController.signal,
|
||||
);
|
||||
|
||||
await expect(async () => {
|
||||
|
|
@ -118,4 +118,4 @@ describe("withExponentialBackoff", () => {
|
|||
|
||||
expect(generatorFactory).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,33 +1,33 @@
|
|||
import { parse } from 'yaml';
|
||||
import { parse } from "yaml";
|
||||
|
||||
import { updateAnthropicModelInYaml } from './yamlConfigUpdater.js';
|
||||
import { updateAnthropicModelInYaml } from "./yamlConfigUpdater.js";
|
||||
|
||||
describe('updateAnthropicModelInYaml', () => {
|
||||
const testApiKey = 'TEST-ant-test123456789';
|
||||
describe("updateAnthropicModelInYaml", () => {
|
||||
const testApiKey = "TEST-ant-test123456789";
|
||||
|
||||
describe('empty or invalid input', () => {
|
||||
it('should create new config from empty string', () => {
|
||||
const result = updateAnthropicModelInYaml('', testApiKey);
|
||||
|
||||
expect(result).toContain('name: Local Config');
|
||||
expect(result).toContain('version: 1.0.0');
|
||||
expect(result).toContain('schema: v1');
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
describe("empty or invalid input", () => {
|
||||
it("should create new config from empty string", () => {
|
||||
const result = updateAnthropicModelInYaml("", testApiKey);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("version: 1.0.0");
|
||||
expect(result).toContain("schema: v1");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
});
|
||||
|
||||
it('should create new config from invalid YAML', () => {
|
||||
const invalidYaml = 'invalid: [yaml content';
|
||||
it("should create new config from invalid YAML", () => {
|
||||
const invalidYaml = "invalid: [yaml content";
|
||||
const result = updateAnthropicModelInYaml(invalidYaml, testApiKey);
|
||||
|
||||
expect(result).toContain('name: Local Config');
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
});
|
||||
});
|
||||
|
||||
describe('comment preservation', () => {
|
||||
it('should preserve comments when adding new model', () => {
|
||||
describe("comment preservation", () => {
|
||||
it("should preserve comments when adding new model", () => {
|
||||
const yamlWithComments = `# My Continue config
|
||||
name: Local Config
|
||||
version: 1.0.0
|
||||
|
|
@ -40,15 +40,15 @@ models:
|
|||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(yamlWithComments, testApiKey);
|
||||
|
||||
expect(result).toContain('# My Continue config');
|
||||
expect(result).toContain('# List of available models');
|
||||
expect(result).toContain('uses: openai/gpt-4');
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
|
||||
expect(result).toContain("# My Continue config");
|
||||
expect(result).toContain("# List of available models");
|
||||
expect(result).toContain("uses: openai/gpt-4");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
});
|
||||
|
||||
it('should preserve comments when updating existing model', () => {
|
||||
it("should preserve comments when updating existing model", () => {
|
||||
const yamlWithComments = `# My Continue config
|
||||
name: Local Config
|
||||
version: 1.0.0
|
||||
|
|
@ -61,17 +61,17 @@ models:
|
|||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(yamlWithComments, testApiKey);
|
||||
|
||||
expect(result).toContain('# My Continue config');
|
||||
expect(result).toContain('# List of available models');
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
expect(result).not.toContain('old-key');
|
||||
|
||||
expect(result).toContain("# My Continue config");
|
||||
expect(result).toContain("# List of available models");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
expect(result).not.toContain("old-key");
|
||||
});
|
||||
});
|
||||
|
||||
describe('model management', () => {
|
||||
it('should add new anthropic model when none exists', () => {
|
||||
describe("model management", () => {
|
||||
it("should add new anthropic model when none exists", () => {
|
||||
const existingConfig = `name: Local Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
|
@ -82,14 +82,14 @@ models:
|
|||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
|
||||
|
||||
expect(result).toContain('uses: openai/gpt-4');
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
expect(result).toContain('OPENAI_API_KEY: TEST-openai-test');
|
||||
|
||||
expect(result).toContain("uses: openai/gpt-4");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
|
||||
});
|
||||
|
||||
it('should update existing anthropic model', () => {
|
||||
it("should update existing anthropic model", () => {
|
||||
const existingConfig = `name: Local Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
|
@ -103,49 +103,57 @@ models:
|
|||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(existingConfig, testApiKey);
|
||||
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('uses: openai/gpt-4');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
expect(result).toContain('OPENAI_API_KEY: TEST-openai-test');
|
||||
expect(result).not.toContain('old-anthropic-key');
|
||||
|
||||
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("uses: openai/gpt-4");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
expect(result).toContain("OPENAI_API_KEY: TEST-openai-test");
|
||||
expect(result).not.toContain("old-anthropic-key");
|
||||
|
||||
// Should only have one anthropic model
|
||||
const anthropicMatches = result.match(/uses: anthropic\/claude-4-sonnet/g);
|
||||
const anthropicMatches = result.match(
|
||||
/uses: anthropic\/claude-4-sonnet/g,
|
||||
);
|
||||
expect(anthropicMatches).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should handle config with no models array', () => {
|
||||
it("should handle config with no models array", () => {
|
||||
const configWithoutModels = `name: Local Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(configWithoutModels, testApiKey);
|
||||
|
||||
expect(result).toContain('name: Local Config');
|
||||
expect(result).toContain('models:');
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
const result = updateAnthropicModelInYaml(
|
||||
configWithoutModels,
|
||||
testApiKey,
|
||||
);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("models:");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
});
|
||||
|
||||
it('should handle config with empty models array', () => {
|
||||
it("should handle config with empty models array", () => {
|
||||
const configWithEmptyModels = `name: Local Config
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
models: []
|
||||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(configWithEmptyModels, testApiKey);
|
||||
|
||||
expect(result).toContain('name: Local Config');
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
const result = updateAnthropicModelInYaml(
|
||||
configWithEmptyModels,
|
||||
testApiKey,
|
||||
);
|
||||
|
||||
expect(result).toContain("name: Local Config");
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
});
|
||||
});
|
||||
|
||||
describe('structure validation', () => {
|
||||
it('should produce valid YAML that can be parsed', () => {
|
||||
describe("structure validation", () => {
|
||||
it("should produce valid YAML that can be parsed", () => {
|
||||
const input = `# Test config
|
||||
name: Test
|
||||
models:
|
||||
|
|
@ -153,16 +161,16 @@ models:
|
|||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(input, testApiKey);
|
||||
|
||||
|
||||
// Should not throw when parsing
|
||||
expect(() => {
|
||||
parse(result);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it('should maintain proper YAML structure', () => {
|
||||
const result = updateAnthropicModelInYaml('', testApiKey);
|
||||
|
||||
it("should maintain proper YAML structure", () => {
|
||||
const result = updateAnthropicModelInYaml("", testApiKey);
|
||||
|
||||
expect(result).toMatch(/^name: /m);
|
||||
expect(result).toMatch(/^version: /m);
|
||||
expect(result).toMatch(/^schema: /m);
|
||||
|
|
@ -173,29 +181,29 @@ models:
|
|||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle malformed models array gracefully', () => {
|
||||
describe("edge cases", () => {
|
||||
it("should handle malformed models array gracefully", () => {
|
||||
const malformedConfig = `name: Local Config
|
||||
models: "not an array"
|
||||
`;
|
||||
|
||||
const result = updateAnthropicModelInYaml(malformedConfig, testApiKey);
|
||||
|
||||
expect(result).toContain('uses: anthropic/claude-4-sonnet');
|
||||
expect(result).toContain('ANTHROPIC_API_KEY: TEST-ant-test123456789');
|
||||
|
||||
expect(result).toContain("uses: anthropic/claude-4-sonnet");
|
||||
expect(result).toContain("ANTHROPIC_API_KEY: TEST-ant-test123456789");
|
||||
});
|
||||
|
||||
it('should handle different API key formats', () => {
|
||||
it("should handle different API key formats", () => {
|
||||
const differentKeys = [
|
||||
'TEST-ant-1234567890',
|
||||
'TEST-ant-abcdefghijklmnop',
|
||||
'TEST-ant-test-key-with-dashes'
|
||||
"TEST-ant-1234567890",
|
||||
"TEST-ant-abcdefghijklmnop",
|
||||
"TEST-ant-test-key-with-dashes",
|
||||
];
|
||||
|
||||
differentKeys.forEach(key => {
|
||||
const result = updateAnthropicModelInYaml('', key);
|
||||
differentKeys.forEach((key) => {
|
||||
const result = updateAnthropicModelInYaml("", key);
|
||||
expect(result).toContain(`ANTHROPIC_API_KEY: ${key}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue