From a2b3206c4a5b3fcebafc9458fbb7745e01e087ba Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 08:16:21 -0700 Subject: [PATCH 01/16] Add timeout handling and comprehensive tests for terminal command execution --- src/tools/runTerminalCommand.test.ts | 157 +++++++++++++++++++++++++++ src/tools/runTerminalCommand.ts | 59 ++++++++-- 2 files changed, 209 insertions(+), 7 deletions(-) create mode 100644 src/tools/runTerminalCommand.test.ts diff --git a/src/tools/runTerminalCommand.test.ts b/src/tools/runTerminalCommand.test.ts new file mode 100644 index 000000000..88a3295af --- /dev/null +++ b/src/tools/runTerminalCommand.test.ts @@ -0,0 +1,157 @@ +import { runTerminalCommandTool } from "./runTerminalCommand.js"; + +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'" }); + expect(result.trim()).toBe("hello world"); + }); + + it("should execute pwd command and return current directory", async () => { + const result = await runTerminalCommandTool.run({ command: "pwd" }); + expect(result.trim()).toMatch(/^\/.*$/); // Should be an absolute path + }); + + it("should execute ls command and return file listings", async () => { + const result = await runTerminalCommandTool.run({ command: "ls -la ." }); + expect(result).toContain("."); + expect(result).toContain(".."); + }); + + it("should handle commands with multiple arguments", async () => { + 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\):/); + }); + + 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/); + }); + + it("should resolve when commands have non-zero exit codes but no stderr", async () => { + 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\"'" }); + expect(result).toContain("success"); + expect(result).toContain("Stderr: error message"); + }); + }); + + describe("timeout functionality", () => { + it("should timeout commands that produce no output for 30+ seconds", async () => { + // Create a command that sleeps for 35 seconds without producing output + const startTime = Date.now(); + const result = await runTerminalCommandTool.run({ command: "sleep 35" }); + const endTime = Date.now(); + + // Should timeout in roughly 30 seconds, not 35 + expect(endTime - startTime).toBeLessThan(32000); + expect(endTime - startTime).toBeGreaterThan(29000); + expect(result).toContain("[Command timed out after 30 seconds of no output]"); + }, 35000); // Set Jest timeout to 35 seconds for this test + + it("should not timeout commands that continuously produce output", async () => { + // Create a command that produces output every second for 5 seconds + const startTime = Date.now(); + const result = await runTerminalCommandTool.run({ + command: "for i in 1 2 3 4 5; do echo \"output $i\"; sleep 1; done" + }); + const endTime = Date.now(); + + // Should complete normally in about 5 seconds + expect(endTime - startTime).toBeLessThan(10000); + expect(result).toContain("output 1"); + expect(result).toContain("output 5"); + expect(result).not.toContain("[Command timed out"); + }, 15000); // Set Jest timeout to 15 seconds for this test + + it("should reset timeout when command produces stderr output", async () => { + // Create a command that produces stderr output periodically + const startTime = Date.now(); + const result = await runTerminalCommandTool.run({ + command: "for i in 1 2 3; do echo \"error $i\" >&2; sleep 1; done; echo 'done'" + }); + const endTime = Date.now(); + + // Should complete normally in about 3 seconds + expect(endTime - startTime).toBeLessThan(8000); + expect(result).toContain("done"); + expect(result).toContain("Stderr: error 1"); + expect(result).not.toContain("[Command timed out"); + }, 12000); // Set Jest timeout to 12 seconds for this test + + it("should include partial output when timing out", async () => { + // Create a command that produces some output then stops + const result = await runTerminalCommandTool.run({ + command: "echo 'initial output'; sleep 35" + }); + + expect(result).toContain("initial output"); + expect(result).toContain("[Command timed out after 30 seconds of no output]"); + }, 35000); // Set Jest timeout to 35 seconds for this test + }); + + describe("output handling", () => { + it("should preserve line breaks in output", async () => { + const result = await runTerminalCommandTool.run({ + command: "printf 'line1\\nline2\\nline3'" + }); + expect(result).toContain("line1\nline2\nline3"); + }); + + it("should handle empty output", async () => { + const result = await runTerminalCommandTool.run({ command: "true" }); + expect(result).toBe(""); + }); + + it("should handle large output", async () => { + // Generate a command that produces substantial output + 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'); + expect(lines).toHaveLength(1000); + }); + }); + + describe("command types", () => { + it("should handle shell built-ins", async () => { + const result = await runTerminalCommandTool.run({ command: "echo $PWD" }); + expect(result.trim()).toMatch(/^\/.*$/); + }); + + it("should handle commands with pipes", async () => { + 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" + }); + 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'" + }); + expect(result.trim()).toBe("hello"); + }); + }); +}); \ No newline at end of file diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index a98898bf8..70ee0a639 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -1,4 +1,4 @@ -import { exec } from "child_process"; +import { spawn } from "child_process"; import telemetryService from "../telemetry/telemetryService.js"; import { isGitCommitCommand, @@ -20,12 +20,45 @@ export const runTerminalCommandTool: Tool = { readonly: false, run: async ({ command }: { command: string }): Promise => { return new Promise((resolve, reject) => { - exec(command, (error, stdout, stderr) => { - const exitCode = error?.code || 0; + const child = spawn("sh", ["-c", command]); + let stdout = ""; + let stderr = ""; + let lastOutputTime = Date.now(); + let timeoutId: NodeJS.Timeout; - if (error) { - reject(`Error: ${error.message}`); - return; + const TIMEOUT_MS = 30000; // 30 seconds + + const resetTimeout = () => { + if (timeoutId) { + clearTimeout(timeoutId); + } + timeoutId = setTimeout(() => { + child.kill(); + const output = stdout + (stderr ? `\nStderr: ${stderr}` : ""); + resolve( + output + "\n\n[Command timed out after 30 seconds of no output]" + ); + }, TIMEOUT_MS); + }; + + // Start the initial timeout + resetTimeout(); + + child.stdout.on("data", (data) => { + stdout += data.toString(); + lastOutputTime = Date.now(); + resetTimeout(); + }); + + child.stderr.on("data", (data) => { + stderr += data.toString(); + lastOutputTime = Date.now(); + resetTimeout(); + }); + + child.on("close", (code) => { + if (timeoutId) { + clearTimeout(timeoutId); } // Track specific git operations @@ -35,12 +68,24 @@ export const runTerminalCommandTool: Tool = { telemetryService.recordPullRequestCreated(); } + if (code !== 0 && stderr) { + reject(`Error (exit code ${code}): ${stderr}`); + return; + } + if (stderr) { - resolve(`Stderr: ${stderr}`); + resolve(stdout + `\nStderr: ${stderr}`); return; } resolve(stdout); }); + + child.on("error", (error) => { + if (timeoutId) { + clearTimeout(timeoutId); + } + reject(`Error: ${error.message}`); + }); }); }, }; From fe16776d516fa939c9c10ba55a6e09e840e4b198 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 09:15:58 -0700 Subject: [PATCH 02/16] Refactor YAML config updates to use centralized yamlConfigUpdater utility --- src/freeTrialTransition.ts | 62 +-------- src/onboarding.ts | 62 +-------- src/ui/FreeTrialTransitionUI.tsx | 62 +-------- src/util/yamlConfigUpdater.test.ts | 200 +++++++++++++++++++++++++++++ src/util/yamlConfigUpdater.ts | 92 +++++++++++++ 5 files changed, 313 insertions(+), 165 deletions(-) create mode 100644 src/util/yamlConfigUpdater.test.ts create mode 100644 src/util/yamlConfigUpdater.ts diff --git a/src/freeTrialTransition.ts b/src/freeTrialTransition.ts index 1a8910a3d..3c3792135 100644 --- a/src/freeTrialTransition.ts +++ b/src/freeTrialTransition.ts @@ -5,7 +5,7 @@ import open from "open"; import * as os from "os"; import * as path from "path"; import * as readlineSync from "readline-sync"; -import * as YAML from "yaml"; +import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; import { env } from "./env.js"; const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); @@ -20,60 +20,12 @@ async function createOrUpdateConfig(apiKey: string): Promise { fs.mkdirSync(configDir, { recursive: true }); } - const newModel = { - uses: "anthropic/claude-4-sonnet", - with: { - ANTHROPIC_API_KEY: apiKey, - }, - }; - - if (fs.existsSync(CONFIG_PATH)) { - const existingContent = fs.readFileSync(CONFIG_PATH, "utf8"); - let config; - - try { - config = YAML.parse(existingContent); - - // Make sure models array exists - if (!config.models) { - config.models = []; - } - - // Check if model already exists - const existingModelIndex = config.models.findIndex( - (model: any) => model.uses === "anthropic/claude-4-sonnet" - ); - - if (existingModelIndex >= 0) { - // Update existing model - config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey; - } else { - // Add new model - config.models.push(newModel); - } - } catch (error) { - // If parsing fails, create a new config - config = { - name: "Local Config", - version: "1.0.0", - schema: "v1", - models: [newModel], - }; - } - - // Write back to file - fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); - } else { - // Create new config file - const config = { - name: "Local Config", - version: "1.0.0", - schema: "v1", - models: [newModel], - }; - - fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); - } + const existingContent = fs.existsSync(CONFIG_PATH) + ? fs.readFileSync(CONFIG_PATH, "utf8") + : ""; + + const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); + fs.writeFileSync(CONFIG_PATH, updatedContent); } /** diff --git a/src/onboarding.ts b/src/onboarding.ts index 53ff8c558..156242c6c 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -37,7 +37,7 @@ export async function checkHasAcceptableModel( } } -import * as YAML from "yaml"; +import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; export async function createOrUpdateConfig(apiKey: string): Promise { const configDir = path.dirname(CONFIG_PATH); @@ -46,60 +46,12 @@ export async function createOrUpdateConfig(apiKey: string): Promise { fs.mkdirSync(configDir, { recursive: true }); } - const newModel = { - uses: "anthropic/claude-4-sonnet", - with: { - ANTHROPIC_API_KEY: apiKey, - }, - }; - - if (fs.existsSync(CONFIG_PATH)) { - const existingContent = fs.readFileSync(CONFIG_PATH, "utf8"); - let config; - - try { - config = YAML.parse(existingContent); - - // Make sure models array exists - if (!config.models) { - config.models = []; - } - - // Check if model already exists - const existingModelIndex = config.models.findIndex( - (model: any) => model.uses === "anthropic/claude-4-sonnet" - ); - - if (existingModelIndex >= 0) { - // Update existing model - config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey; - } else { - // Add new model - config.models.push(newModel); - } - } catch (error) { - // If parsing fails, create a new config - config = { - name: "Local Config", - version: "1.0.0", - schema: "v1", - models: [newModel], - }; - } - - // Write back to file - fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); - } else { - // Create new config file - const config = { - name: "Local Config", - version: "1.0.0", - schema: "v1", - models: [newModel], - }; - - fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); - } + const existingContent = fs.existsSync(CONFIG_PATH) + ? fs.readFileSync(CONFIG_PATH, "utf8") + : ""; + + const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); + fs.writeFileSync(CONFIG_PATH, updatedContent); } export async function runOnboardingFlow( diff --git a/src/ui/FreeTrialTransitionUI.tsx b/src/ui/FreeTrialTransitionUI.tsx index 1f4584951..d75cdad2e 100644 --- a/src/ui/FreeTrialTransitionUI.tsx +++ b/src/ui/FreeTrialTransitionUI.tsx @@ -4,7 +4,7 @@ import open from "open"; import * as os from "os"; import * as path from "path"; import React, { useState } from "react"; -import * as YAML from "yaml"; +import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; import { env } from "../env.js"; const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); @@ -25,60 +25,12 @@ async function createOrUpdateConfig(apiKey: string): Promise { fs.mkdirSync(configDir, { recursive: true }); } - const newModel = { - uses: "anthropic/claude-4-sonnet", - with: { - ANTHROPIC_API_KEY: apiKey, - }, - }; - - if (fs.existsSync(CONFIG_PATH)) { - const existingContent = fs.readFileSync(CONFIG_PATH, "utf8"); - let config; - - try { - config = YAML.parse(existingContent); - - // Make sure models array exists - if (!config.models) { - config.models = []; - } - - // Check if model already exists - const existingModelIndex = config.models.findIndex( - (model: any) => model.uses === "anthropic/claude-4-sonnet" - ); - - if (existingModelIndex >= 0) { - // Update existing model - config.models[existingModelIndex].with.ANTHROPIC_API_KEY = apiKey; - } else { - // Add new model - config.models.push(newModel); - } - } catch (error) { - // If parsing fails, create a new config - config = { - name: "Local Config", - version: "1.0.0", - schema: "v1", - models: [newModel], - }; - } - - // Write back to file - fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); - } else { - // Create new config file - const config = { - name: "Local Config", - version: "1.0.0", - schema: "v1", - models: [newModel], - }; - - fs.writeFileSync(CONFIG_PATH, YAML.stringify(config)); - } + const existingContent = fs.existsSync(CONFIG_PATH) + ? fs.readFileSync(CONFIG_PATH, "utf8") + : ""; + + const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); + fs.writeFileSync(CONFIG_PATH, updatedContent); } const FreeTrialTransitionUI: React.FC = ({ diff --git a/src/util/yamlConfigUpdater.test.ts b/src/util/yamlConfigUpdater.test.ts new file mode 100644 index 000000000..838d5d600 --- /dev/null +++ b/src/util/yamlConfigUpdater.test.ts @@ -0,0 +1,200 @@ +import { updateAnthropicModelInYaml } from './yamlConfigUpdater.js'; +import { parse } from 'yaml'; + +describe('updateAnthropicModelInYaml', () => { + const testApiKey = 'sk-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: sk-ant-test123456789'); + }); + + 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: sk-ant-test123456789'); + }); + }); + + describe('comment preservation', () => { + it('should preserve comments when adding new model', () => { + const yamlWithComments = `# My Continue config +name: Local Config +version: 1.0.0 +schema: v1 +# List of available models +models: + - uses: openai/gpt-4 + with: + OPENAI_API_KEY: sk-test +`; + + 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: sk-ant-test123456789'); + }); + + it('should preserve comments when updating existing model', () => { + const yamlWithComments = `# My Continue config +name: Local Config +version: 1.0.0 +schema: v1 +# List of available models +models: + - uses: anthropic/claude-4-sonnet + with: + ANTHROPIC_API_KEY: old-key +`; + + 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: sk-ant-test123456789'); + expect(result).not.toContain('old-key'); + }); + }); + + describe('model management', () => { + it('should add new anthropic model when none exists', () => { + const existingConfig = `name: Local Config +version: 1.0.0 +schema: v1 +models: + - uses: openai/gpt-4 + with: + OPENAI_API_KEY: sk-openai-test +`; + + 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: sk-ant-test123456789'); + expect(result).toContain('OPENAI_API_KEY: sk-openai-test'); + }); + + it('should update existing anthropic model', () => { + const existingConfig = `name: Local Config +version: 1.0.0 +schema: v1 +models: + - uses: anthropic/claude-4-sonnet + with: + ANTHROPIC_API_KEY: old-anthropic-key + - uses: openai/gpt-4 + with: + OPENAI_API_KEY: sk-openai-test +`; + + 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: sk-ant-test123456789'); + expect(result).toContain('OPENAI_API_KEY: sk-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); + expect(anthropicMatches).toHaveLength(1); + }); + + 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: sk-ant-test123456789'); + }); + + 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: sk-ant-test123456789'); + }); + }); + + describe('structure validation', () => { + it('should produce valid YAML that can be parsed', () => { + const input = `# Test config +name: Test +models: + - uses: existing/model +`; + + 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); + + expect(result).toMatch(/^name: /m); + expect(result).toMatch(/^version: /m); + expect(result).toMatch(/^schema: /m); + expect(result).toMatch(/^models:/m); + expect(result).toMatch(/^\s+- uses: /m); + expect(result).toMatch(/^\s+with:/m); + expect(result).toMatch(/^\s+ANTHROPIC_API_KEY: /m); + }); + }); + + 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: sk-ant-test123456789'); + }); + + it('should handle different API key formats', () => { + const differentKeys = [ + 'sk-ant-1234567890', + 'sk-ant-abcdefghijklmnop', + 'sk-ant-test-key-with-dashes' + ]; + + differentKeys.forEach(key => { + const result = updateAnthropicModelInYaml('', key); + expect(result).toContain(`ANTHROPIC_API_KEY: ${key}`); + }); + }); + }); +}); \ No newline at end of file diff --git a/src/util/yamlConfigUpdater.ts b/src/util/yamlConfigUpdater.ts new file mode 100644 index 000000000..da6799dde --- /dev/null +++ b/src/util/yamlConfigUpdater.ts @@ -0,0 +1,92 @@ +import { parseDocument } from "yaml"; + +export interface ModelConfig { + uses: string; + with: { + ANTHROPIC_API_KEY: string; + }; +} + +export interface ConfigStructure { + name: string; + version: string; + schema: string; + models: ModelConfig[]; +} + +/** + * Updates or adds an Anthropic Claude model configuration in a YAML string while preserving comments and formatting. + * This is a pure function that takes a YAML string and returns a modified YAML string. + * + * @param yamlContent - The original YAML content as a string (can be empty) + * @param apiKey - The Anthropic API key to set + * @returns The updated YAML content as a string with comments preserved + */ +export function updateAnthropicModelInYaml(yamlContent: string, apiKey: string): string { + const newModel: ModelConfig = { + uses: "anthropic/claude-4-sonnet", + with: { + ANTHROPIC_API_KEY: apiKey, + }, + }; + + try { + const doc = parseDocument(yamlContent); + + // If document is empty or has no content, create a new config + if (!doc.contents || doc.contents === null) { + const defaultConfig: ConfigStructure = { + name: "Local Config", + version: "1.0.0", + schema: "v1", + models: [newModel], + }; + + const newDoc = parseDocument(''); + Object.keys(defaultConfig).forEach(key => + newDoc.set(key, (defaultConfig as any)[key]) + ); + return newDoc.toString(); + } + + // Convert to JS, filter models, and recreate + const config = doc.toJS() as any; + + // Make sure models array exists + if (!config.models) { + config.models = []; + } + + // Filter out existing anthropic models + config.models = config.models.filter((model: any) => + !model || model.uses !== "anthropic/claude-4-sonnet" + ); + + // Add the new anthropic model + config.models.push(newModel); + + // Preserve comments by manually reconstructing the document + // Get all the top-level comments and structure + if (doc.has('models')) { + doc.set('models', config.models); + } else { + doc.set('models', config.models); + } + + return doc.toString(); + } catch (error) { + // If parsing fails completely, create a new config + const defaultConfig: ConfigStructure = { + name: "Local Config", + version: "1.0.0", + schema: "v1", + models: [newModel], + }; + + const doc = parseDocument(''); + Object.keys(defaultConfig).forEach(key => + doc.set(key, (defaultConfig as any)[key]) + ); + return doc.toString(); + } +} \ No newline at end of file From bac423c117c0a01adb6d0ddae3ef4da91d2d9640 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 09:28:24 -0700 Subject: [PATCH 03/16] Add headless mode permissions with full tool access by default --- spec/permissions.md | 19 +++ src/permissions/defaultPolicies.ts | 9 ++ .../headlessPermissions.integration.test.ts | 129 ++++++++++++++++++ src/permissions/index.ts | 2 +- src/permissions/precedenceResolver.test.ts | 67 ++++++++- src/permissions/precedenceResolver.ts | 9 +- src/services/ToolPermissionService.ts | 12 +- .../ToolPermissionService.unit.test.ts | 4 +- src/services/index.ts | 4 +- 9 files changed, 242 insertions(+), 13 deletions(-) create mode 100644 src/permissions/headlessPermissions.integration.test.ts diff --git a/spec/permissions.md b/spec/permissions.md index 380c7bfba..51b828359 100644 --- a/spec/permissions.md +++ b/spec/permissions.md @@ -82,3 +82,22 @@ exclude: Except that it's important to understand that this file is _not_ intended to be edited by the user. It is only for persistence, and users should interact with their permissions by using the TUI. This file should be created the first time that the CLI starts. + +## Headless mode permissions + +When running in headless mode (using the `-p` or `--print` flag), the CLI uses different default policies designed for non-interactive usage: + +- **Normal mode**: Write operations and terminal commands require confirmation (`ask`) +- **Headless mode**: All tools are allowed by default (`*: allow`) + +This behavior can still be overridden using the standard precedence rules. For example: + +```bash +# Headless mode with full access (default) +cn -p "Write a hello world script" + +# Headless mode with specific restrictions +cn -p --exclude Write "Clean up the codebase" +``` + +The headless default policies are defined in [`src/permissions/defaultPolicies.ts`](../src/permissions/defaultPolicies.ts) as `HEADLESS_TOOL_POLICIES`. diff --git a/src/permissions/defaultPolicies.ts b/src/permissions/defaultPolicies.ts index d08c5f375..4af884496 100644 --- a/src/permissions/defaultPolicies.ts +++ b/src/permissions/defaultPolicies.ts @@ -26,3 +26,12 @@ export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [ // Default fallback - ask for any unmatched tools { tool: "*", permission: "ask" }, ]; + +/** + * Headless mode permission policies where all tools are allowed by default. + * Used when running with the "-p" flag for full access without prompts. + */ +export const HEADLESS_TOOL_POLICIES: ToolPermissionPolicy[] = [ + // Allow all tools by default in headless mode + { tool: "*", permission: "allow" }, +]; diff --git a/src/permissions/headlessPermissions.integration.test.ts b/src/permissions/headlessPermissions.integration.test.ts new file mode 100644 index 000000000..31ba6da71 --- /dev/null +++ b/src/permissions/headlessPermissions.integration.test.ts @@ -0,0 +1,129 @@ +import { resolvePermissionPrecedence } from "./precedenceResolver.js"; +import { HEADLESS_TOOL_POLICIES, DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +import { checkToolPermission } from "./permissionChecker.js"; + +describe("Headless Permissions Integration", () => { + describe("precedence resolution with headless mode", () => { + it("should use headless policies when headless: true", () => { + const policies = resolvePermissionPrecedence({ + useDefaults: true, + personalSettings: false, // Disable to avoid file system dependencies + headless: true, + }); + + expect(policies).toEqual(HEADLESS_TOOL_POLICIES); + expect(policies.length).toBe(1); + expect(policies[0]).toEqual({ tool: "*", permission: "allow" }); + }); + + it("should use normal policies when headless: false", () => { + const policies = resolvePermissionPrecedence({ + useDefaults: true, + personalSettings: false, + headless: false, + }); + + expect(policies).toEqual(DEFAULT_TOOL_POLICIES); + expect(policies.length).toBeGreaterThan(1); + + // Check that write operations require confirmation in normal mode + const writePolicy = policies.find(p => p.tool === "write_file"); + expect(writePolicy?.permission).toBe("ask"); + }); + + it("should allow CLI overrides to supersede headless defaults", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + exclude: ["dangerous_tool"], + }, + useDefaults: true, + personalSettings: false, + headless: true, + }); + + // CLI exclusion should come first + expect(policies[0]).toEqual({ tool: "dangerous_tool", permission: "exclude" }); + // Headless wildcard should still be present + expect(policies[1]).toEqual({ tool: "*", permission: "allow" }); + }); + }); + + describe("permission checking with headless policies", () => { + it("should allow all tools with headless policies", () => { + const permissions = { policies: HEADLESS_TOOL_POLICIES }; + + // Test various tool types + const toolsToTest = [ + "write_file", + "run_terminal_command", + "read_file", + "search_code", + "some_unknown_tool", + "mcp__custom_tool" + ]; + + for (const toolName of toolsToTest) { + const result = checkToolPermission( + { name: toolName, arguments: {} }, + permissions + ); + + expect(result.permission).toBe("allow"); + expect(result.matchedPolicy).toEqual({ tool: "*", permission: "allow" }); + } + }); + + it("should respect CLI overrides even in headless mode", () => { + const policies = [ + { tool: "dangerous_tool", permission: "exclude" as const }, + { tool: "*", permission: "allow" as const }, + ]; + const permissions = { policies }; + + // Excluded tool should be blocked + const excludedResult = checkToolPermission( + { name: "dangerous_tool", arguments: {} }, + permissions + ); + expect(excludedResult.permission).toBe("exclude"); + + // Other tools should be allowed + const allowedResult = checkToolPermission( + { name: "safe_tool", arguments: {} }, + permissions + ); + expect(allowedResult.permission).toBe("allow"); + }); + }); + + describe("real-world headless scenarios", () => { + it("should handle typical CLI workflow in headless mode", () => { + // Simulate headless mode with some CLI overrides + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + // Still exclude truly dangerous operations + exclude: ["rm", "sudo"], + // Allow specific tools that might normally require confirmation + allow: ["git", "npm"], + }, + useDefaults: true, + personalSettings: false, + headless: true, + }); + + 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"); + + // Explicitly allowed tools should be allowed + expect(checkToolPermission({ name: "git", arguments: {} }, permissions).permission).toBe("allow"); + expect(checkToolPermission({ name: "npm", arguments: {} }, permissions).permission).toBe("allow"); + + // Other tools should fall back to headless wildcard (allow) + expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("allow"); + expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("allow"); + }); + }); +}); \ No newline at end of file diff --git a/src/permissions/index.ts b/src/permissions/index.ts index 7e5fca074..9327dafb9 100644 --- a/src/permissions/index.ts +++ b/src/permissions/index.ts @@ -6,7 +6,7 @@ export type { ToolPermissions, } from "./types.js"; -export { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +export { DEFAULT_TOOL_POLICIES, HEADLESS_TOOL_POLICIES } from "./defaultPolicies.js"; export { checkToolPermission, filterExcludedTools, diff --git a/src/permissions/precedenceResolver.test.ts b/src/permissions/precedenceResolver.test.ts index 7e69810fe..7c4bb9dcf 100644 --- a/src/permissions/precedenceResolver.test.ts +++ b/src/permissions/precedenceResolver.test.ts @@ -1,5 +1,5 @@ import { jest } from "@jest/globals"; -import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +import { DEFAULT_TOOL_POLICIES, HEADLESS_TOOL_POLICIES } from "./defaultPolicies.js"; import { resolvePermissionPrecedence } from "./precedenceResolver.js"; import { ToolPermissionPolicy } from "./types.js"; @@ -140,5 +140,70 @@ describe("precedenceResolver", () => { const readPolicy = policies.find(p => p.tool === "read_file"); expect(readPolicy).toBeDefined(); }); + + describe("headless mode", () => { + it("should use headless policies when headless: true", () => { + const policies = resolvePermissionPrecedence({ + useDefaults: true, + personalSettings: false, + headless: true, + }); + + expect(policies).toEqual(HEADLESS_TOOL_POLICIES); + }); + + it("should use normal policies when headless: false", () => { + const policies = resolvePermissionPrecedence({ + useDefaults: true, + personalSettings: false, + headless: false, + }); + + expect(policies).toEqual(DEFAULT_TOOL_POLICIES); + }); + + it("should use normal policies when headless is undefined", () => { + const policies = resolvePermissionPrecedence({ + useDefaults: true, + personalSettings: false, + }); + + expect(policies).toEqual(DEFAULT_TOOL_POLICIES); + }); + + it("should allow CLI flags to override headless policies", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + exclude: ["write_file"], + }, + useDefaults: true, + personalSettings: false, + headless: true, + }); + + // CLI exclusion should come first, overriding headless allow-all + expect(policies[0]).toEqual({ tool: "write_file", permission: "exclude" }); + // Headless wildcard should still be present + expect(policies[1]).toEqual({ tool: "*", permission: "allow" }); + }); + + it("should allow config policies to override headless defaults", () => { + const configPolicies: ToolPermissionPolicy[] = [ + { tool: "run_terminal_command", permission: "ask" }, + ]; + + const policies = resolvePermissionPrecedence({ + configPermissions: configPolicies, + useDefaults: true, + personalSettings: false, + headless: true, + }); + + // Config policy should override headless default + expect(policies[0]).toEqual({ tool: "run_terminal_command", permission: "ask" }); + // Headless wildcard should still be present + expect(policies[1]).toEqual({ tool: "*", permission: "allow" }); + }); + }); }); }); \ No newline at end of file diff --git a/src/permissions/precedenceResolver.ts b/src/permissions/precedenceResolver.ts index b3a6da6e9..b7a4dc967 100644 --- a/src/permissions/precedenceResolver.ts +++ b/src/permissions/precedenceResolver.ts @@ -1,4 +1,4 @@ -import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +import { DEFAULT_TOOL_POLICIES, HEADLESS_TOOL_POLICIES } from "./defaultPolicies.js"; import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js"; import { normalizeToolName } from "./toolNameMapping.js"; import { ToolPermissionPolicy } from "./types.js"; @@ -17,6 +17,8 @@ export interface PermissionSources { personalSettings?: boolean; // Whether to load from permissions.yaml /** Default policies - lowest precedence */ useDefaults?: boolean; + /** Whether running in headless mode - affects default policies */ + headless?: boolean; } /** @@ -38,9 +40,10 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer // Layer 4: Default policies (lowest precedence) if (sources.useDefaults !== false) { + const defaultPolicies = sources.headless ? HEADLESS_TOOL_POLICIES : DEFAULT_TOOL_POLICIES; layers.push({ - name: "defaults", - policies: [...DEFAULT_TOOL_POLICIES] + name: sources.headless ? "headless-defaults" : "defaults", + policies: [...defaultPolicies] }); } diff --git a/src/services/ToolPermissionService.ts b/src/services/ToolPermissionService.ts index b599fcc60..a80d1b03c 100644 --- a/src/services/ToolPermissionService.ts +++ b/src/services/ToolPermissionService.ts @@ -23,16 +23,18 @@ export class ToolPermissionService { allow?: string[]; ask?: string[]; exclude?: string[]; - }): ToolPermissionServiceState { + }, headless?: boolean): ToolPermissionServiceState { logger.debug("Synchronously initializing ToolPermissionService", { - hasOverrides: !!runtimeOverrides + hasOverrides: !!runtimeOverrides, + headless: !!headless }); // Use the precedence resolver to get properly ordered policies const compiledPolicies = resolvePermissionPrecedence({ commandLineFlags: runtimeOverrides, personalSettings: true, // Enable loading from ~/.continue/permissions.yaml - useDefaults: true + useDefaults: true, + headless: headless }); this.state = { @@ -49,12 +51,12 @@ export class ToolPermissionService { allow?: string[]; ask?: string[]; exclude?: string[]; - }): Promise { + }, headless?: boolean): Promise { // Ensure permissions.yaml exists before loading await ensurePermissionsYamlExists(); // Use the synchronous version after ensuring the file exists - return this.initializeSync(runtimeOverrides); + return this.initializeSync(runtimeOverrides, headless); } /** diff --git a/src/services/ToolPermissionService.unit.test.ts b/src/services/ToolPermissionService.unit.test.ts index 71793ca81..dbb48b61b 100644 --- a/src/services/ToolPermissionService.unit.test.ts +++ b/src/services/ToolPermissionService.unit.test.ts @@ -23,7 +23,7 @@ describe("ToolPermissionService unit tests", () => { expect(state.permissions.policies).toBeDefined(); expect(state.permissions.policies.length).toBeGreaterThan(0); - // Verify the overrides are in the policies + // Verify the overrides are in the policies (they should be at the beginning due to precedence) const toolNames = state.permissions.policies.map((p) => p.tool); expect(toolNames).toContain("TestTool3"); expect(toolNames).toContain("TestTool2"); @@ -74,4 +74,6 @@ describe("ToolPermissionService unit tests", () => { expect(state.permissions.policies.length).toBe(2); }); }); + + // Headless mode functionality is tested in precedenceResolver.test.ts and integration tests }); diff --git a/src/services/index.ts b/src/services/index.ts index f9b03ed0d..210c56dee 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -31,13 +31,13 @@ export async function initializeServices(options: ServiceInitOptions = {}) { // Handle tool permissions specially for immediate availability if (options.toolPermissionOverrides) { // Initialize synchronously and register the value immediately - const permissionState = toolPermissionService.initializeSync(options.toolPermissionOverrides); + const permissionState = toolPermissionService.initializeSync(options.toolPermissionOverrides, options.headless); serviceContainer.registerValue(SERVICE_NAMES.TOOL_PERMISSIONS, permissionState); } else { // Register normal factory for lazy initialization serviceContainer.register( SERVICE_NAMES.TOOL_PERMISSIONS, - () => toolPermissionService.initialize(), + () => toolPermissionService.initialize(undefined, options.headless), [] ); } From 191b5ea63bc77ca0910a1542497dd689b13de911 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 10:54:51 -0700 Subject: [PATCH 04/16] feat: word-level diff --- src/ui/ColoredDiff.test.ts | 199 +++++++++++++++++++++++++++++++++++++ src/ui/ColoredDiff.tsx | 148 ++++++++++++++++++++------- 2 files changed, 311 insertions(+), 36 deletions(-) create mode 100644 src/ui/ColoredDiff.test.ts diff --git a/src/ui/ColoredDiff.test.ts b/src/ui/ColoredDiff.test.ts new file mode 100644 index 000000000..2d7093eaf --- /dev/null +++ b/src/ui/ColoredDiff.test.ts @@ -0,0 +1,199 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { ColoredDiff } from "./ColoredDiff.js"; + +describe("ColoredDiff", () => { + it("renders simple line additions", () => { + const diffContent = `@@ -1,3 +1,4 @@ + function hello() { ++ console.log("added line"); + return "world"; + }`; + + const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); + const frame = lastFrame(); + + expect(frame).toContain("console.log(\"added line\")"); + expect(frame).toContain("+"); + }); + + it("renders simple line deletions", () => { + const diffContent = `@@ -1,4 +1,3 @@ + function hello() { +- console.log("removed line"); + return "world"; + }`; + + const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); + const frame = lastFrame(); + + expect(frame).toContain("console.log(\"removed line\")"); + expect(frame).toContain("-"); + }); + + it("renders context lines", () => { + const diffContent = `@@ -1,4 +1,4 @@ + function hello() { +- console.log("old"); ++ console.log("new"); + return "world"; + }`; + + const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); + const frame = lastFrame(); + + expect(frame).toContain("function hello()"); + expect(frame).toContain("return \"world\""); + }); + + it("renders word-level diffs for modified lines", () => { + const diffContent = `@@ -1,3 +1,3 @@ + function hello() { +- return "old text"; ++ return "new text"; + }`; + + const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); + const frame = lastFrame(); + + 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 frame = lastFrame(); + + expect(frame).toContain("No changes detected"); + }); + + 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 diffContent = `@@ -1,1 +1,20 @@ + function hello() { +${lines} + }`; + + const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); + const frame = lastFrame(); + + expect(frame).toContain("more lines"); + }); + + it("handles mixed add/delete groups for word-level diffing", () => { + const diffContent = `@@ -1,4 +1,4 @@ + function hello() { +- const x = "old value"; +- const y = "another old"; ++ const x = "new value"; ++ const y = "another new"; + return x + y; + }`; + + 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"); + }); + + it("handles single-type changes without word-level diffing", () => { + const diffContent = `@@ -1,3 +1,4 @@ + function hello() { ++ console.log("new line 1"); ++ console.log("new line 2"); + return "world"; + }`; + + 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("+"); + }); + + it("text content matches expected diff output ignoring styling", () => { + const diffContent = `@@ -1,4 +1,4 @@ + function hello() { +- return "old text"; ++ return "new text"; + }`; + + const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); + const frame = lastFrame(); + + // Extract just the line numbers and content, ignoring colors/styling + // The output should contain these essential elements: + expect(frame).toContain("function hello()"); + expect(frame).toContain("- "); + expect(frame).toContain("+ "); + expect(frame).toContain("return \""); + expect(frame).toContain("text\""); + + // Verify we have both old and new text content + expect(frame).toContain("old text"); + expect(frame).toContain("new text"); + + // Verify we don't have corrupted or missing content + const lineMatches = frame?.match(/return "/g) || []; + expect(lineMatches.length).toBeGreaterThanOrEqual(2); // Should appear in both - and + lines + }); + + it("word-level diff preserves all original content", () => { + const diffContent = `@@ -1,3 +1,3 @@ + const x = 1; +-const y = "hello world"; ++const y = "hello universe"; + const z = 3;`; + + 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 + expect(frame).toContain("hello world"); + expect(frame).toContain("hello universe"); + expect(frame).toContain("const y = \"hello"); + + // Should have proper line prefixes + expect(frame).toContain("- "); + expect(frame).toContain("+ "); + }); + + it("complex word-level diff maintains content integrity", () => { + const diffContent = `@@ -1,5 +1,5 @@ + function calculate() { +- const result = oldFunction(a, b); +- return result.value; ++ const result = newFunction(a, b, c); ++ return result.data; + }`; + + const { lastFrame } = render(React.createElement(ColoredDiff, { diffContent })); + const frame = lastFrame(); + + // Check that all unique content appears + expect(frame).toContain("function calculate()"); + expect(frame).toContain("const result ="); + expect(frame).toContain("oldFunction(a, b)"); + expect(frame).toContain("newFunction(a, b, c)"); + expect(frame).toContain("return result."); + expect(frame).toContain("value"); + expect(frame).toContain("data"); + + // Verify structure is maintained + expect(frame).toContain("- "); + expect(frame).toContain("+ "); + }); +}); \ No newline at end of file diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index 1dcae6de5..c3ceefb5d 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -1,5 +1,6 @@ import { Box, Text } from "ink"; import React from "react"; +import { diffWordsWithSpace } from "diff"; interface DiffLine { type: 'add' | 'del' | 'context' | 'hunk' | 'other'; @@ -67,6 +68,25 @@ function parseDiffWithLineNumbers(diffContent: string): DiffLine[] { return result; } +function getWordLevelContent(oldContent: string, newContent: string, showType: 'removed' | 'added'): string { + const changes = diffWordsWithSpace(oldContent, newContent); + let result = ''; + + changes.forEach((change) => { + if (showType === 'removed') { + if (change.removed || !change.added) { + result += change.value; + } + } else { + if (change.added || !change.removed) { + result += change.value; + } + } + }); + + return result; +} + export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) => { const parsedLines = parseDiffWithLineNumbers(diffContent); @@ -81,46 +101,102 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) const truncatedLines = displayableLines.slice(0, 16); const isTruncated = displayableLines.length > 16; + // Group consecutive add/delete lines for word-level diffing + const groupedLines: Array<{ type: 'group' | 'single', lines: DiffLine[] }> = []; + let currentGroup: DiffLine[] = []; + + for (let i = 0; i < truncatedLines.length; i++) { + const line = truncatedLines[i]; + const nextLine = truncatedLines[i + 1]; + + if (line.type === 'add' || line.type === 'del') { + currentGroup.push(line); + + // If next line is different type or end of array, finalize the group + if (!nextLine || (nextLine.type !== 'add' && nextLine.type !== 'del')) { + if (currentGroup.length > 1) { + const delLines = currentGroup.filter(l => l.type === 'del'); + const addLines = currentGroup.filter(l => l.type === 'add'); + + // Only do word-level diff if we have both deletions and additions + if (delLines.length > 0 && addLines.length > 0) { + groupedLines.push({ type: 'group', lines: currentGroup }); + } else { + // Single type, treat as individual lines + currentGroup.forEach(l => groupedLines.push({ type: 'single', lines: [l] })); + } + } else { + groupedLines.push({ type: 'single', lines: currentGroup }); + } + currentGroup = []; + } + } else { + groupedLines.push({ type: 'single', lines: [line] }); + } + } + return ( - {truncatedLines.map((line, index) => { - const lineKey = `diff-line-${index}`; - let gutterNumStr = ''; - let prefixSymbol = ' '; - let dim = false; - let backgroundColor: string | undefined = undefined; + {groupedLines.map((group, groupIndex) => { + if (group.type === 'single') { + const line = group.lines[0]; + const lineKey = `diff-line-${groupIndex}`; + let gutterNumStr = ''; + let prefixSymbol = ' '; + let dim = false; + let backgroundColor: string | undefined = undefined; - switch (line.type) { - case 'add': - gutterNumStr = (line.newLine ?? '').toString(); - backgroundColor = '#1a4a1a'; - prefixSymbol = '+'; - break; - case 'del': - gutterNumStr = (line.oldLine ?? '').toString(); - backgroundColor = '#4a1a1a'; - prefixSymbol = '-'; - break; - case 'context': - gutterNumStr = (line.newLine ?? '').toString(); - dim = true; - prefixSymbol = ' '; - break; - default: - return null; + switch (line.type) { + case 'add': + gutterNumStr = (line.newLine ?? '').toString(); + backgroundColor = '#1a4a1a'; + prefixSymbol = '+'; + break; + case 'del': + gutterNumStr = (line.oldLine ?? '').toString(); + backgroundColor = '#4a1a1a'; + prefixSymbol = '-'; + break; + case 'context': + gutterNumStr = (line.newLine ?? '').toString(); + dim = true; + prefixSymbol = ' '; + break; + default: + return null; + } + + return ( + + {gutterNumStr.padEnd(4)} + + {prefixSymbol}{' '} + + + {line.content} + + + ); + } else { + // Word-level diff group + const delLines = group.lines.filter(l => l.type === 'del'); + const addLines = group.lines.filter(l => l.type === 'add'); + const oldContent = delLines.map(l => l.content).join('\n'); + const newContent = addLines.map(l => l.content).join('\n'); + + return ( + + + {(delLines[0]?.oldLine ?? '').toString().padEnd(4)} + - {getWordLevelContent(oldContent, newContent, 'removed')} + + + {(addLines[0]?.newLine ?? '').toString().padEnd(4)} + + {getWordLevelContent(oldContent, newContent, 'added')} + + + ); } - - return ( - - {gutterNumStr.padEnd(4)} - - {prefixSymbol}{' '} - - - {line.content} - - - ); })} {isTruncated && ( From 186b5b62a2f7bde590cd79819067998b02523da1 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 11:16:02 -0700 Subject: [PATCH 05/16] fix: coloring of word level diff --- src/ui/ColoredDiff.tsx | 175 ++++++++++++++++++++++++----------------- 1 file changed, 105 insertions(+), 70 deletions(-) diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index c3ceefb5d..991d2576f 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -1,16 +1,16 @@ +import { diffWordsWithSpace } from "diff"; import { Box, Text } from "ink"; import React from "react"; -import { diffWordsWithSpace } from "diff"; interface DiffLine { - type: 'add' | 'del' | 'context' | 'hunk' | 'other'; + type: "add" | "del" | "context" | "hunk" | "other"; oldLine?: number; newLine?: number; content: string; } function parseDiffWithLineNumbers(diffContent: string): DiffLine[] { - const lines = diffContent.split('\n'); + const lines = diffContent.split("\n"); const result: DiffLine[] = []; let currentOldLine = 0; let currentNewLine = 0; @@ -23,144 +23,169 @@ function parseDiffWithLineNumbers(diffContent: string): DiffLine[] { currentOldLine = parseInt(hunkMatch[1], 10); currentNewLine = parseInt(hunkMatch[2], 10); inHunk = true; - result.push({ type: 'hunk', content: line }); + result.push({ type: "hunk", content: line }); currentOldLine--; currentNewLine--; continue; } if (!inHunk) { if ( - line.startsWith('--- ') || - line.startsWith('+++ ') || - line.startsWith('diff --git') || - line.startsWith('index ') + line.startsWith("--- ") || + line.startsWith("+++ ") || + line.startsWith("diff --git") || + line.startsWith("index ") ) continue; continue; } - if (line.startsWith('+')) { + if (line.startsWith("+")) { currentNewLine++; result.push({ - type: 'add', + type: "add", newLine: currentNewLine, content: line.substring(1), }); - } else if (line.startsWith('-')) { + } else if (line.startsWith("-")) { currentOldLine++; result.push({ - type: 'del', + type: "del", oldLine: currentOldLine, content: line.substring(1), }); - } else if (line.startsWith(' ')) { + } else if (line.startsWith(" ")) { currentOldLine++; currentNewLine++; result.push({ - type: 'context', + type: "context", oldLine: currentOldLine, newLine: currentNewLine, content: line.substring(1), }); - } else if (line.startsWith('\\')) { - result.push({ type: 'other', content: line }); + } else if (line.startsWith("\\")) { + result.push({ type: "other", content: line }); } } return result; } -function getWordLevelContent(oldContent: string, newContent: string, showType: 'removed' | 'added'): string { +function renderWordLevelContent( + oldContent: string, + newContent: string, + showType: "removed" | "added" +): React.ReactNode { const changes = diffWordsWithSpace(oldContent, newContent); - let result = ''; - - changes.forEach((change) => { - if (showType === 'removed') { - if (change.removed || !change.added) { - result += change.value; + const segments: React.ReactNode[] = []; + + changes.forEach((change, index) => { + if (showType === "removed") { + if (change.removed) { + // Highlight removed words with darker red + segments.push( + + {change.value} + + ); + } else if (!change.added) { + // Unchanged text - no special styling + segments.push(change.value); } } else { - if (change.added || !change.removed) { - result += change.value; + if (change.added) { + // Highlight added words with darker green + segments.push( + + {change.value} + + ); + } else if (!change.removed) { + // Unchanged text - no special styling + segments.push(change.value); } } }); - - return result; + + return <>{segments}; } -export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) => { +export const ColoredDiff: React.FC<{ diffContent: string }> = ({ + diffContent, +}) => { const parsedLines = parseDiffWithLineNumbers(diffContent); - + if (parsedLines.length === 0) { return No changes detected.; } const displayableLines = parsedLines.filter( - (l) => l.type !== 'hunk' && l.type !== 'other', + (l) => l.type !== "hunk" && l.type !== "other" ); - const truncatedLines = displayableLines.slice(0, 16); - const isTruncated = displayableLines.length > 16; + const truncatedLines = displayableLines; + const isTruncated = false; // Group consecutive add/delete lines for word-level diffing - const groupedLines: Array<{ type: 'group' | 'single', lines: DiffLine[] }> = []; + const groupedLines: Array<{ type: "group" | "single"; lines: DiffLine[] }> = + []; let currentGroup: DiffLine[] = []; - + for (let i = 0; i < truncatedLines.length; i++) { const line = truncatedLines[i]; const nextLine = truncatedLines[i + 1]; - - if (line.type === 'add' || line.type === 'del') { + + if (line.type === "add" || line.type === "del") { currentGroup.push(line); - + // If next line is different type or end of array, finalize the group - if (!nextLine || (nextLine.type !== 'add' && nextLine.type !== 'del')) { + if (!nextLine || (nextLine.type !== "add" && nextLine.type !== "del")) { if (currentGroup.length > 1) { - const delLines = currentGroup.filter(l => l.type === 'del'); - const addLines = currentGroup.filter(l => l.type === 'add'); - + const delLines = currentGroup.filter((l) => l.type === "del"); + const addLines = currentGroup.filter((l) => l.type === "add"); + // Only do word-level diff if we have both deletions and additions if (delLines.length > 0 && addLines.length > 0) { - groupedLines.push({ type: 'group', lines: currentGroup }); + groupedLines.push({ type: "group", lines: currentGroup }); } else { // Single type, treat as individual lines - currentGroup.forEach(l => groupedLines.push({ type: 'single', lines: [l] })); + currentGroup.forEach((l) => + groupedLines.push({ type: "single", lines: [l] }) + ); } } else { - groupedLines.push({ type: 'single', lines: currentGroup }); + groupedLines.push({ type: "single", lines: currentGroup }); } currentGroup = []; } } else { - groupedLines.push({ type: 'single', lines: [line] }); + groupedLines.push({ type: "single", lines: [line] }); } } return ( {groupedLines.map((group, groupIndex) => { - if (group.type === 'single') { + if (group.type === "single") { const line = group.lines[0]; const lineKey = `diff-line-${groupIndex}`; - let gutterNumStr = ''; - let prefixSymbol = ' '; + let gutterNumStr = ""; + let prefixSymbol = " "; let dim = false; let backgroundColor: string | undefined = undefined; switch (line.type) { - case 'add': - gutterNumStr = (line.newLine ?? '').toString(); - backgroundColor = '#1a4a1a'; - prefixSymbol = '+'; + case "add": + gutterNumStr = (line.newLine ?? "").toString(); + backgroundColor = "green"; + prefixSymbol = "+"; break; - case 'del': - gutterNumStr = (line.oldLine ?? '').toString(); - backgroundColor = '#4a1a1a'; - prefixSymbol = '-'; + case "del": + gutterNumStr = (line.oldLine ?? "").toString(); + backgroundColor = "red"; + prefixSymbol = "-"; break; - case 'context': - gutterNumStr = (line.newLine ?? '').toString(); + case "context": + gutterNumStr = (line.newLine ?? "").toString(); dim = true; - prefixSymbol = ' '; + prefixSymbol = " "; break; default: return null; @@ -170,7 +195,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) {gutterNumStr.padEnd(4)} - {prefixSymbol}{' '} + {prefixSymbol}{" "} {line.content} @@ -179,20 +204,30 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) ); } else { // Word-level diff group - const delLines = group.lines.filter(l => l.type === 'del'); - const addLines = group.lines.filter(l => l.type === 'add'); - const oldContent = delLines.map(l => l.content).join('\n'); - const newContent = addLines.map(l => l.content).join('\n'); - + const delLines = group.lines.filter((l) => l.type === "del"); + const addLines = group.lines.filter((l) => l.type === "add"); + const oldContent = delLines.map((l) => l.content).join("\n"); + const newContent = addLines.map((l) => l.content).join("\n"); + return ( - {(delLines[0]?.oldLine ?? '').toString().padEnd(4)} - - {getWordLevelContent(oldContent, newContent, 'removed')} + + {(delLines[0]?.oldLine ?? "").toString().padEnd(4)}{" "} + + - + + {renderWordLevelContent(oldContent, newContent, "removed")} + - {(addLines[0]?.newLine ?? '').toString().padEnd(4)} - + {getWordLevelContent(oldContent, newContent, 'added')} + + {(addLines[0]?.newLine ?? "").toString().padEnd(4)}{" "} + + + + + {renderWordLevelContent(oldContent, newContent, "added")} + ); @@ -205,4 +240,4 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) )} ); -}; \ No newline at end of file +}; From 4db1cd9fcd013af2a2e3ceaa54ad7dd33eba568b Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 13:36:20 -0700 Subject: [PATCH 06/16] update diff colors --- src/ui/ColoredDiff.tsx | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index 991d2576f..803225f71 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -2,6 +2,15 @@ import { diffWordsWithSpace } from "diff"; import { Box, Text } from "ink"; import React from "react"; +// Color constants for diff display +const COLORS = { + ADDITION_BG: "#325b30", + DELETION_BG: "#712f37", + ADDITION_HIGHLIGHT: "#59a467", + DELETION_HIGHLIGHT: "#a75e6d", + LINE_NUMBER: "gray", +} as const; + interface DiffLine { type: "add" | "del" | "context" | "hunk" | "other"; oldLine?: number; @@ -81,7 +90,7 @@ function renderWordLevelContent( if (change.removed) { // Highlight removed words with darker red segments.push( - + {change.value} ); @@ -93,7 +102,7 @@ function renderWordLevelContent( if (change.added) { // Highlight added words with darker green segments.push( - + {change.value} ); @@ -174,12 +183,12 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ switch (line.type) { case "add": gutterNumStr = (line.newLine ?? "").toString(); - backgroundColor = "green"; + backgroundColor = COLORS.ADDITION_BG; prefixSymbol = "+"; break; case "del": gutterNumStr = (line.oldLine ?? "").toString(); - backgroundColor = "red"; + backgroundColor = COLORS.DELETION_BG; prefixSymbol = "-"; break; case "context": @@ -193,7 +202,7 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ return ( - {gutterNumStr.padEnd(4)} + {gutterNumStr.padEnd(4)} {prefixSymbol}{" "} @@ -212,20 +221,20 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ return ( - + {(delLines[0]?.oldLine ?? "").toString().padEnd(4)}{" "} - - - + - + {renderWordLevelContent(oldContent, newContent, "removed")} - + {(addLines[0]?.newLine ?? "").toString().padEnd(4)}{" "} - + - + + + {renderWordLevelContent(oldContent, newContent, "added")} From 706eb6e234c91347da32e5a4d46591f0c74e639f Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Wed, 30 Jul 2025 13:42:17 -0700 Subject: [PATCH 07/16] Update src/util/yamlConfigUpdater.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- src/util/yamlConfigUpdater.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/util/yamlConfigUpdater.ts b/src/util/yamlConfigUpdater.ts index da6799dde..9112696d3 100644 --- a/src/util/yamlConfigUpdater.ts +++ b/src/util/yamlConfigUpdater.ts @@ -58,7 +58,7 @@ export function updateAnthropicModelInYaml(yamlContent: string, apiKey: string): } // Filter out existing anthropic models - config.models = config.models.filter((model: any) => + config.models = config.models.filter((model: any) => model && model.uses !== "anthropic/claude-4-sonnet") !model || model.uses !== "anthropic/claude-4-sonnet" ); From d21bd215fa48e7674c2dcff3107f7e57191be3d3 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Wed, 30 Jul 2025 13:44:21 -0700 Subject: [PATCH 08/16] Update src/tools/runTerminalCommand.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- src/tools/runTerminalCommand.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index 70ee0a639..02c7d5568 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -68,7 +68,7 @@ export const runTerminalCommandTool: Tool = { telemetryService.recordPullRequestCreated(); } - if (code !== 0 && stderr) { + if (code !== 0) { reject(`Error (exit code ${code}): ${stderr}`); return; } From ed7bb0a8e5c70165a1d6fe25a8f574cd9f0be709 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 13:45:22 -0700 Subject: [PATCH 09/16] fix: address feedback --- src/util/yamlConfigUpdater.ts | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/util/yamlConfigUpdater.ts b/src/util/yamlConfigUpdater.ts index da6799dde..059bdf8f7 100644 --- a/src/util/yamlConfigUpdater.ts +++ b/src/util/yamlConfigUpdater.ts @@ -65,13 +65,8 @@ export function updateAnthropicModelInYaml(yamlContent: string, apiKey: string): // Add the new anthropic model config.models.push(newModel); - // Preserve comments by manually reconstructing the document - // Get all the top-level comments and structure - if (doc.has('models')) { - doc.set('models', config.models); - } else { - doc.set('models', config.models); - } + // Update the models array while preserving comments and structure + doc.set('models', config.models); return doc.toString(); } catch (error) { From 276afde4abd1b817b43aa2e3b8bdaf395c3621f3 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 13:49:58 -0700 Subject: [PATCH 10/16] fix: lint errs --- src/util/yamlConfigUpdater.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/util/yamlConfigUpdater.ts b/src/util/yamlConfigUpdater.ts index fdf96f86d..059bdf8f7 100644 --- a/src/util/yamlConfigUpdater.ts +++ b/src/util/yamlConfigUpdater.ts @@ -58,7 +58,7 @@ export function updateAnthropicModelInYaml(yamlContent: string, apiKey: string): } // Filter out existing anthropic models - config.models = config.models.filter((model: any) => model && model.uses !== "anthropic/claude-4-sonnet") + config.models = config.models.filter((model: any) => !model || model.uses !== "anthropic/claude-4-sonnet" ); From c498b67fd65eb64d1fb1ffdf45e6366d84056ff1 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 13:51:50 -0700 Subject: [PATCH 11/16] fix tests --- src/ui/ColoredDiff.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index 803225f71..dd74a4d4f 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -129,8 +129,8 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ (l) => l.type !== "hunk" && l.type !== "other" ); - const truncatedLines = displayableLines; - const isTruncated = false; + const truncatedLines = displayableLines.slice(0, 16); + const isTruncated = displayableLines.length > 16; // Group consecutive add/delete lines for word-level diffing const groupedLines: Array<{ type: "group" | "single"; lines: DiffLine[] }> = From 500e64084391b88058dfa10d67770af48d1a63d9 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 13:52:54 -0700 Subject: [PATCH 12/16] fix: address feedback --- src/tools/runTerminalCommand.ts | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index 02c7d5568..0269bf592 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -25,6 +25,7 @@ export const runTerminalCommandTool: Tool = { let stderr = ""; let lastOutputTime = Date.now(); let timeoutId: NodeJS.Timeout; + let isResolved = false; const TIMEOUT_MS = 30000; // 30 seconds @@ -33,6 +34,8 @@ export const runTerminalCommandTool: Tool = { clearTimeout(timeoutId); } timeoutId = setTimeout(() => { + if (isResolved) return; + isResolved = true; child.kill(); const output = stdout + (stderr ? `\nStderr: ${stderr}` : ""); resolve( @@ -57,22 +60,28 @@ export const runTerminalCommandTool: Tool = { }); child.on("close", (code) => { + if (isResolved) return; + isResolved = true; + if (timeoutId) { clearTimeout(timeoutId); } - // Track specific git operations - if (isGitCommitCommand(command)) { - telemetryService.recordCommitCreated(); - } else if (isPullRequestCommand(command)) { - telemetryService.recordPullRequestCreated(); - } - - if (code !== 0) { + // Only reject on non-zero exit code if there's also stderr + if (code !== 0 && stderr) { reject(`Error (exit code ${code}): ${stderr}`); return; } + // Track specific git operations only after successful execution + if (code === 0) { + if (isGitCommitCommand(command)) { + telemetryService.recordCommitCreated(); + } else if (isPullRequestCommand(command)) { + telemetryService.recordPullRequestCreated(); + } + } + if (stderr) { resolve(stdout + `\nStderr: ${stderr}`); return; @@ -81,6 +90,9 @@ export const runTerminalCommandTool: Tool = { }); child.on("error", (error) => { + if (isResolved) return; + isResolved = true; + if (timeoutId) { clearTimeout(timeoutId); } From 8a15233bc9d7e332953137dd26dae7ff328b9007 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 22:29:42 -0700 Subject: [PATCH 13/16] address feedback about memo --- src/ui/ColoredDiff.tsx | 73 +++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 26 deletions(-) diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index dd74a4d4f..d266484de 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -1,6 +1,6 @@ import { diffWordsWithSpace } from "diff"; import { Box, Text } from "ink"; -import React from "react"; +import React, { useMemo } from "react"; // Color constants for diff display const COLORS = { @@ -77,12 +77,16 @@ function parseDiffWithLineNumbers(diffContent: string): DiffLine[] { return result; } +function useWordLevelDiff(oldContent: string, newContent: string) { + return useMemo(() => { + return diffWordsWithSpace(oldContent, newContent); + }, [oldContent, newContent]); +} + function renderWordLevelContent( - oldContent: string, - newContent: string, + changes: ReturnType, showType: "removed" | "added" ): React.ReactNode { - const changes = diffWordsWithSpace(oldContent, newContent); const segments: React.ReactNode[] = []; changes.forEach((change, index) => { @@ -116,6 +120,39 @@ function renderWordLevelContent( return <>{segments}; } +const WordLevelDiffGroup: React.FC<{ + groupIndex: number; + delLines: DiffLine[]; + addLines: DiffLine[]; +}> = ({ groupIndex, delLines, addLines }) => { + const oldContent = delLines.map(l => l.content).join('\n'); + const newContent = addLines.map(l => l.content).join('\n'); + const changes = useWordLevelDiff(oldContent, newContent); + + return ( + + + + {(delLines[0]?.oldLine ?? "").toString().padEnd(4)}{" "} + + - + + {renderWordLevelContent(changes, "removed")} + + + + + {(addLines[0]?.newLine ?? "").toString().padEnd(4)}{" "} + + + + + {renderWordLevelContent(changes, "added")} + + + + ); +}; + export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent, }) => { @@ -215,30 +252,14 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ // Word-level diff group const delLines = group.lines.filter((l) => l.type === "del"); const addLines = group.lines.filter((l) => l.type === "add"); - const oldContent = delLines.map((l) => l.content).join("\n"); - const newContent = addLines.map((l) => l.content).join("\n"); return ( - - - - {(delLines[0]?.oldLine ?? "").toString().padEnd(4)}{" "} - - - - - {renderWordLevelContent(oldContent, newContent, "removed")} - - - - - {(addLines[0]?.newLine ?? "").toString().padEnd(4)}{" "} - - + - - {renderWordLevelContent(oldContent, newContent, "added")} - - - + ); } })} From 328ff12e65e6a6022528b4091b951d6cfc3fdae8 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 22:34:20 -0700 Subject: [PATCH 14/16] headless tool call permissions error msg --- spec/permissions.md | 19 +-- src/permissions/defaultPolicies.ts | 8 -- .../headlessPermissions.integration.test.ts | 108 +++++++++--------- src/permissions/index.ts | 2 +- src/permissions/precedenceResolver.test.ts | 38 +++--- src/permissions/precedenceResolver.ts | 7 +- src/streamChatResponse.ts | 41 +++++-- 7 files changed, 116 insertions(+), 107 deletions(-) diff --git a/spec/permissions.md b/spec/permissions.md index 51b828359..0e47c056c 100644 --- a/spec/permissions.md +++ b/spec/permissions.md @@ -85,19 +85,22 @@ This file should be created the first time that the CLI starts. ## Headless mode permissions -When running in headless mode (using the `-p` or `--print` flag), the CLI uses different default policies designed for non-interactive usage: +When running in headless mode (using the `-p` or `--print` flag), the CLI uses the same default policies as normal mode, but with different behavior for tools that require confirmation: -- **Normal mode**: Write operations and terminal commands require confirmation (`ask`) -- **Headless mode**: All tools are allowed by default (`*: allow`) +- **Normal mode**: Write operations and terminal commands require confirmation (`ask`) - user is prompted +- **Headless mode**: Same default policies, but tools requiring confirmation (`ask`) will cause the process to exit with an error message -This behavior can still be overridden using the standard precedence rules. For example: +To use tools that normally require confirmation in headless mode, you must explicitly allow them: ```bash -# Headless mode with full access (default) -cn -p "Write a hello world script" +# Headless mode with explicit permissions for write operations +cn -p --allow write_file "Write a hello world script" + +# Headless mode with wildcard permission (allow all tools) +cn -p --allow "*" "Write and run a script" # Headless mode with specific restrictions -cn -p --exclude Write "Clean up the codebase" +cn -p --exclude run_terminal_command "Clean up the codebase" ``` -The headless default policies are defined in [`src/permissions/defaultPolicies.ts`](../src/permissions/defaultPolicies.ts) as `HEADLESS_TOOL_POLICIES`. +This approach ensures that headless mode is secure by default while providing clear guidance on how to enable the needed permissions. diff --git a/src/permissions/defaultPolicies.ts b/src/permissions/defaultPolicies.ts index 4af884496..6b5693e5b 100644 --- a/src/permissions/defaultPolicies.ts +++ b/src/permissions/defaultPolicies.ts @@ -27,11 +27,3 @@ export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [ { tool: "*", permission: "ask" }, ]; -/** - * Headless mode permission policies where all tools are allowed by default. - * Used when running with the "-p" flag for full access without prompts. - */ -export const HEADLESS_TOOL_POLICIES: ToolPermissionPolicy[] = [ - // Allow all tools by default in headless mode - { tool: "*", permission: "allow" }, -]; diff --git a/src/permissions/headlessPermissions.integration.test.ts b/src/permissions/headlessPermissions.integration.test.ts index 31ba6da71..7ca1e7dbf 100644 --- a/src/permissions/headlessPermissions.integration.test.ts +++ b/src/permissions/headlessPermissions.integration.test.ts @@ -1,37 +1,28 @@ import { resolvePermissionPrecedence } from "./precedenceResolver.js"; -import { HEADLESS_TOOL_POLICIES, DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; +import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { checkToolPermission } from "./permissionChecker.js"; describe("Headless Permissions Integration", () => { describe("precedence resolution with headless mode", () => { - it("should use headless policies when headless: true", () => { - const policies = resolvePermissionPrecedence({ + it("should use same default policies for both headless and normal modes", () => { + const headlessPolicies = resolvePermissionPrecedence({ useDefaults: true, personalSettings: false, // Disable to avoid file system dependencies headless: true, }); - expect(policies).toEqual(HEADLESS_TOOL_POLICIES); - expect(policies.length).toBe(1); - expect(policies[0]).toEqual({ tool: "*", permission: "allow" }); - }); - - it("should use normal policies when headless: false", () => { - const policies = resolvePermissionPrecedence({ + const normalPolicies = resolvePermissionPrecedence({ useDefaults: true, personalSettings: false, headless: false, }); - expect(policies).toEqual(DEFAULT_TOOL_POLICIES); - expect(policies.length).toBeGreaterThan(1); - - // Check that write operations require confirmation in normal mode - const writePolicy = policies.find(p => p.tool === "write_file"); - expect(writePolicy?.permission).toBe("ask"); + expect(headlessPolicies).toEqual(DEFAULT_TOOL_POLICIES); + expect(normalPolicies).toEqual(DEFAULT_TOOL_POLICIES); + expect(headlessPolicies).toEqual(normalPolicies); }); - it("should allow CLI overrides to supersede headless defaults", () => { + it("should allow CLI overrides to supersede defaults in headless mode", () => { const policies = resolvePermissionPrecedence({ commandLineFlags: { exclude: ["dangerous_tool"], @@ -43,40 +34,32 @@ describe("Headless Permissions Integration", () => { // CLI exclusion should come first expect(policies[0]).toEqual({ tool: "dangerous_tool", permission: "exclude" }); - // Headless wildcard should still be present - expect(policies[1]).toEqual({ tool: "*", permission: "allow" }); + // Default policies should follow + expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES); }); }); - describe("permission checking with headless policies", () => { - it("should allow all tools with headless policies", () => { - const permissions = { policies: HEADLESS_TOOL_POLICIES }; + describe("permission checking with default policies", () => { + it("should follow default permission rules", () => { + const permissions = { policies: DEFAULT_TOOL_POLICIES }; - // Test various tool types - const toolsToTest = [ - "write_file", - "run_terminal_command", - "read_file", - "search_code", - "some_unknown_tool", - "mcp__custom_tool" - ]; + // Read-only tools should be allowed + expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow"); + expect(checkToolPermission({ name: "list_files", arguments: {} }, permissions).permission).toBe("allow"); + expect(checkToolPermission({ name: "search_code", arguments: {} }, permissions).permission).toBe("allow"); - for (const toolName of toolsToTest) { - const result = checkToolPermission( - { name: toolName, arguments: {} }, - permissions - ); - - expect(result.permission).toBe("allow"); - expect(result.matchedPolicy).toEqual({ tool: "*", permission: "allow" }); - } + // Write operations should require permission + expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("ask"); + expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("ask"); + + // Unknown tools should default to ask + expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("ask"); }); it("should respect CLI overrides even in headless mode", () => { const policies = [ { tool: "dangerous_tool", permission: "exclude" as const }, - { tool: "*", permission: "allow" as const }, + ...DEFAULT_TOOL_POLICIES, ]; const permissions = { policies }; @@ -87,24 +70,21 @@ describe("Headless Permissions Integration", () => { ); expect(excludedResult.permission).toBe("exclude"); - // Other tools should be allowed - const allowedResult = checkToolPermission( - { name: "safe_tool", arguments: {} }, - permissions - ); - expect(allowedResult.permission).toBe("allow"); + // Default tools should follow their normal rules + expect(checkToolPermission({ name: "read_file", arguments: {} }, permissions).permission).toBe("allow"); + expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("ask"); }); }); describe("real-world headless scenarios", () => { - it("should handle typical CLI workflow in headless mode", () => { + it("should handle typical CLI workflow with permission overrides", () => { // Simulate headless mode with some CLI overrides const policies = resolvePermissionPrecedence({ commandLineFlags: { // Still exclude truly dangerous operations exclude: ["rm", "sudo"], - // Allow specific tools that might normally require confirmation - allow: ["git", "npm"], + // Allow specific tools that would normally require confirmation + allow: ["write_file", "run_terminal_command"], }, useDefaults: true, personalSettings: false, @@ -118,11 +98,31 @@ describe("Headless Permissions Integration", () => { expect(checkToolPermission({ name: "sudo", arguments: {} }, permissions).permission).toBe("exclude"); // Explicitly allowed tools should be allowed - expect(checkToolPermission({ name: "git", arguments: {} }, permissions).permission).toBe("allow"); - expect(checkToolPermission({ name: "npm", arguments: {} }, permissions).permission).toBe("allow"); - - // Other tools should fall back to headless wildcard (allow) expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("allow"); + expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("allow"); + + // Read-only tools should still be allowed by default + expect(checkToolPermission({ name: "read_file", 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"); + }); + + it("should handle workflow with wildcard allow override", () => { + const policies = resolvePermissionPrecedence({ + commandLineFlags: { + allow: ["*"], // Allow all tools + }, + useDefaults: true, + personalSettings: false, + headless: true, + }); + + const permissions = { policies }; + + // All tools should be allowed due to wildcard override + expect(checkToolPermission({ name: "write_file", arguments: {} }, permissions).permission).toBe("allow"); + expect(checkToolPermission({ name: "run_terminal_command", arguments: {} }, permissions).permission).toBe("allow"); expect(checkToolPermission({ name: "unknown_tool", arguments: {} }, permissions).permission).toBe("allow"); }); }); diff --git a/src/permissions/index.ts b/src/permissions/index.ts index 9327dafb9..7e5fca074 100644 --- a/src/permissions/index.ts +++ b/src/permissions/index.ts @@ -6,7 +6,7 @@ export type { ToolPermissions, } from "./types.js"; -export { DEFAULT_TOOL_POLICIES, HEADLESS_TOOL_POLICIES } from "./defaultPolicies.js"; +export { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; export { checkToolPermission, filterExcludedTools, diff --git a/src/permissions/precedenceResolver.test.ts b/src/permissions/precedenceResolver.test.ts index 7c4bb9dcf..de0ab10f6 100644 --- a/src/permissions/precedenceResolver.test.ts +++ b/src/permissions/precedenceResolver.test.ts @@ -1,5 +1,5 @@ import { jest } from "@jest/globals"; -import { DEFAULT_TOOL_POLICIES, HEADLESS_TOOL_POLICIES } from "./defaultPolicies.js"; +import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { resolvePermissionPrecedence } from "./precedenceResolver.js"; import { ToolPermissionPolicy } from "./types.js"; @@ -142,27 +142,25 @@ describe("precedenceResolver", () => { }); describe("headless mode", () => { - it("should use headless policies when headless: true", () => { - const policies = resolvePermissionPrecedence({ + it("should use same policies for headless and normal modes", () => { + const headlessPolicies = resolvePermissionPrecedence({ useDefaults: true, personalSettings: false, headless: true, }); - expect(policies).toEqual(HEADLESS_TOOL_POLICIES); - }); - - it("should use normal policies when headless: false", () => { - const policies = resolvePermissionPrecedence({ + const normalPolicies = resolvePermissionPrecedence({ useDefaults: true, personalSettings: false, headless: false, }); - expect(policies).toEqual(DEFAULT_TOOL_POLICIES); + expect(headlessPolicies).toEqual(DEFAULT_TOOL_POLICIES); + expect(normalPolicies).toEqual(DEFAULT_TOOL_POLICIES); + expect(headlessPolicies).toEqual(normalPolicies); }); - it("should use normal policies when headless is undefined", () => { + it("should use default policies when headless is undefined", () => { const policies = resolvePermissionPrecedence({ useDefaults: true, personalSettings: false, @@ -171,7 +169,7 @@ describe("precedenceResolver", () => { expect(policies).toEqual(DEFAULT_TOOL_POLICIES); }); - it("should allow CLI flags to override headless policies", () => { + it("should allow CLI flags to override default policies in headless mode", () => { const policies = resolvePermissionPrecedence({ commandLineFlags: { exclude: ["write_file"], @@ -181,15 +179,15 @@ describe("precedenceResolver", () => { headless: true, }); - // CLI exclusion should come first, overriding headless allow-all + // CLI exclusion should come first expect(policies[0]).toEqual({ tool: "write_file", permission: "exclude" }); - // Headless wildcard should still be present - expect(policies[1]).toEqual({ tool: "*", permission: "allow" }); + // Default policies should follow + expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES); }); - it("should allow config policies to override headless defaults", () => { + it("should allow config policies to override defaults in headless mode", () => { const configPolicies: ToolPermissionPolicy[] = [ - { tool: "run_terminal_command", permission: "ask" }, + { tool: "run_terminal_command", permission: "allow" }, ]; const policies = resolvePermissionPrecedence({ @@ -199,10 +197,10 @@ describe("precedenceResolver", () => { headless: true, }); - // Config policy should override headless default - expect(policies[0]).toEqual({ tool: "run_terminal_command", permission: "ask" }); - // Headless wildcard should still be present - expect(policies[1]).toEqual({ tool: "*", permission: "allow" }); + // Config policy should override default + expect(policies[0]).toEqual({ tool: "run_terminal_command", permission: "allow" }); + // Default policies should follow + expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES); }); }); }); diff --git a/src/permissions/precedenceResolver.ts b/src/permissions/precedenceResolver.ts index b7a4dc967..22ad131c2 100644 --- a/src/permissions/precedenceResolver.ts +++ b/src/permissions/precedenceResolver.ts @@ -1,4 +1,4 @@ -import { DEFAULT_TOOL_POLICIES, HEADLESS_TOOL_POLICIES } from "./defaultPolicies.js"; +import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { loadPermissionsYaml, yamlConfigToPolicies } from "./permissionsYamlLoader.js"; import { normalizeToolName } from "./toolNameMapping.js"; import { ToolPermissionPolicy } from "./types.js"; @@ -40,10 +40,9 @@ export function resolvePermissionPrecedence(sources: PermissionSources): ToolPer // Layer 4: Default policies (lowest precedence) if (sources.useDefaults !== false) { - const defaultPolicies = sources.headless ? HEADLESS_TOOL_POLICIES : DEFAULT_TOOL_POLICIES; layers.push({ - name: sources.headless ? "headless-defaults" : "defaults", - policies: [...defaultPolicies] + name: "defaults", + policies: [...DEFAULT_TOOL_POLICIES] }); } diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 242e30d83..4b379241a 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -239,7 +239,7 @@ async function processStreamingResponse( hasToolCalls = true; for (const toolCallDelta of choice.delta.tool_calls) { let toolCallId: string | undefined; - + // If we have an ID, use it and map the index if (toolCallDelta.id) { toolCallId = toolCallDelta.id; @@ -250,12 +250,14 @@ async function processStreamingResponse( // No ID, but we have an index - look up the ID from our map toolCallId = indexToIdMap.get(toolCallDelta.index); } - + if (!toolCallId) { - logger.warn("Tool call delta without ID or valid index mapping", { toolCallDelta }); + logger.warn("Tool call delta without ID or valid index mapping", { + toolCallDelta, + }); continue; } - + // Create tool call entry if it doesn't exist if (!toolCallsMap.has(toolCallId)) { toolCallsMap.set(toolCallId, { @@ -478,7 +480,6 @@ export async function streamChatResponse( arguments: toolCall.arguments, }); - // Notify tool start immediately - before permission check // This ensures the UI shows the tool call even if it's rejected if (callbacks?.onToolStart) { @@ -490,6 +491,23 @@ export async function streamChatResponse( if (permissionCheck.permission === "allow") { approved = true; } else if (permissionCheck.permission === "ask") { + // In headless mode, exit immediately with instructions + const tool = BUILTIN_TOOLS.find((t) => t.name === toolCall.name); + const toolName = tool?.displayName || toolCall.name; + if (isHeadless) { + console.error( + `Error: Tool '${toolName}' requires permission but cn is running in headless mode.` + ); + console.error( + `If you want to allow this tool, use --allow ${toolName}.` + ); + console.error( + `If you don't want the tool to be included, use --exclude ${toolName}.` + ); + + process.exit(1); + } + // Request permission from user if (callbacks?.onToolPermissionRequest) { // Use the proper toolPermissionManager API @@ -497,7 +515,7 @@ export async function streamChatResponse( name: toolCall.name, arguments: toolCall.arguments, }; - + // Set up listener for permissionRequested event const handlePermissionRequested = (event: { requestId: string; @@ -516,17 +534,16 @@ export async function streamChatResponse( ); } }; - + toolPermissionManager.on( "permissionRequested", handlePermissionRequested ); - + // Request permission using the proper API - const permissionResult = await toolPermissionManager.requestPermission( - toolCallRequest - ); - + const permissionResult = + await toolPermissionManager.requestPermission(toolCallRequest); + approved = permissionResult.approved; } else { // Fallback: deny if no UI callback available From 447f4d7e9e9a8d8609ece748e7e552a645fc92e3 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 22:36:11 -0700 Subject: [PATCH 15/16] fix errors --- src/ui/ColoredDiff.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/ColoredDiff.tsx b/src/ui/ColoredDiff.tsx index d266484de..40b13c239 100644 --- a/src/ui/ColoredDiff.tsx +++ b/src/ui/ColoredDiff.tsx @@ -1,4 +1,4 @@ -import { diffWordsWithSpace } from "diff"; +import { diffWordsWithSpace, Change } from "diff"; import { Box, Text } from "ink"; import React, { useMemo } from "react"; @@ -84,7 +84,7 @@ function useWordLevelDiff(oldContent: string, newContent: string) { } function renderWordLevelContent( - changes: ReturnType, + changes: Change[], showType: "removed" | "added" ): React.ReactNode { const segments: React.ReactNode[] = []; From e614792d31cc06cdc98c53a88774137cbb924d70 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Jul 2025 23:02:51 -0700 Subject: [PATCH 16/16] fix feedback --- .../headlessPermissions.integration.test.ts | 24 ++++------------ src/permissions/precedenceResolver.test.ts | 28 +++---------------- src/permissions/precedenceResolver.ts | 2 -- src/services/ToolPermissionService.ts | 12 ++++---- src/services/index.ts | 4 +-- 5 files changed, 17 insertions(+), 53 deletions(-) diff --git a/src/permissions/headlessPermissions.integration.test.ts b/src/permissions/headlessPermissions.integration.test.ts index 7ca1e7dbf..791c6cb25 100644 --- a/src/permissions/headlessPermissions.integration.test.ts +++ b/src/permissions/headlessPermissions.integration.test.ts @@ -3,33 +3,23 @@ import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js"; import { checkToolPermission } from "./permissionChecker.js"; describe("Headless Permissions Integration", () => { - describe("precedence resolution with headless mode", () => { - it("should use same default policies for both headless and normal modes", () => { - const headlessPolicies = resolvePermissionPrecedence({ + describe("precedence resolution", () => { + it("should use default policies", () => { + const policies = resolvePermissionPrecedence({ useDefaults: true, personalSettings: false, // Disable to avoid file system dependencies - headless: true, }); - const normalPolicies = resolvePermissionPrecedence({ - useDefaults: true, - personalSettings: false, - headless: false, - }); - - expect(headlessPolicies).toEqual(DEFAULT_TOOL_POLICIES); - expect(normalPolicies).toEqual(DEFAULT_TOOL_POLICIES); - expect(headlessPolicies).toEqual(normalPolicies); + expect(policies).toEqual(DEFAULT_TOOL_POLICIES); }); - it("should allow CLI overrides to supersede defaults in headless mode", () => { + it("should allow CLI overrides to supersede defaults", () => { const policies = resolvePermissionPrecedence({ commandLineFlags: { exclude: ["dangerous_tool"], }, useDefaults: true, personalSettings: false, - headless: true, }); // CLI exclusion should come first @@ -78,7 +68,7 @@ describe("Headless Permissions Integration", () => { describe("real-world headless scenarios", () => { it("should handle typical CLI workflow with permission overrides", () => { - // Simulate headless mode with some CLI overrides + // Simulate CLI with some overrides const policies = resolvePermissionPrecedence({ commandLineFlags: { // Still exclude truly dangerous operations @@ -88,7 +78,6 @@ describe("Headless Permissions Integration", () => { }, useDefaults: true, personalSettings: false, - headless: true, }); const permissions = { policies }; @@ -115,7 +104,6 @@ describe("Headless Permissions Integration", () => { }, useDefaults: true, personalSettings: false, - headless: true, }); const permissions = { policies }; diff --git a/src/permissions/precedenceResolver.test.ts b/src/permissions/precedenceResolver.test.ts index de0ab10f6..b16317587 100644 --- a/src/permissions/precedenceResolver.test.ts +++ b/src/permissions/precedenceResolver.test.ts @@ -141,26 +141,8 @@ describe("precedenceResolver", () => { expect(readPolicy).toBeDefined(); }); - describe("headless mode", () => { - it("should use same policies for headless and normal modes", () => { - const headlessPolicies = resolvePermissionPrecedence({ - useDefaults: true, - personalSettings: false, - headless: true, - }); - - const normalPolicies = resolvePermissionPrecedence({ - useDefaults: true, - personalSettings: false, - headless: false, - }); - - expect(headlessPolicies).toEqual(DEFAULT_TOOL_POLICIES); - expect(normalPolicies).toEqual(DEFAULT_TOOL_POLICIES); - expect(headlessPolicies).toEqual(normalPolicies); - }); - - it("should use default policies when headless is undefined", () => { + describe("precedence rules", () => { + it("should use default policies when no other sources provided", () => { const policies = resolvePermissionPrecedence({ useDefaults: true, personalSettings: false, @@ -169,14 +151,13 @@ describe("precedenceResolver", () => { expect(policies).toEqual(DEFAULT_TOOL_POLICIES); }); - it("should allow CLI flags to override default policies in headless mode", () => { + it("should allow CLI flags to override default policies", () => { const policies = resolvePermissionPrecedence({ commandLineFlags: { exclude: ["write_file"], }, useDefaults: true, personalSettings: false, - headless: true, }); // CLI exclusion should come first @@ -185,7 +166,7 @@ describe("precedenceResolver", () => { expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES); }); - it("should allow config policies to override defaults in headless mode", () => { + it("should allow config policies to override defaults", () => { const configPolicies: ToolPermissionPolicy[] = [ { tool: "run_terminal_command", permission: "allow" }, ]; @@ -194,7 +175,6 @@ describe("precedenceResolver", () => { configPermissions: configPolicies, useDefaults: true, personalSettings: false, - headless: true, }); // Config policy should override default diff --git a/src/permissions/precedenceResolver.ts b/src/permissions/precedenceResolver.ts index 22ad131c2..b3a6da6e9 100644 --- a/src/permissions/precedenceResolver.ts +++ b/src/permissions/precedenceResolver.ts @@ -17,8 +17,6 @@ export interface PermissionSources { personalSettings?: boolean; // Whether to load from permissions.yaml /** Default policies - lowest precedence */ useDefaults?: boolean; - /** Whether running in headless mode - affects default policies */ - headless?: boolean; } /** diff --git a/src/services/ToolPermissionService.ts b/src/services/ToolPermissionService.ts index a80d1b03c..b599fcc60 100644 --- a/src/services/ToolPermissionService.ts +++ b/src/services/ToolPermissionService.ts @@ -23,18 +23,16 @@ export class ToolPermissionService { allow?: string[]; ask?: string[]; exclude?: string[]; - }, headless?: boolean): ToolPermissionServiceState { + }): ToolPermissionServiceState { logger.debug("Synchronously initializing ToolPermissionService", { - hasOverrides: !!runtimeOverrides, - headless: !!headless + hasOverrides: !!runtimeOverrides }); // Use the precedence resolver to get properly ordered policies const compiledPolicies = resolvePermissionPrecedence({ commandLineFlags: runtimeOverrides, personalSettings: true, // Enable loading from ~/.continue/permissions.yaml - useDefaults: true, - headless: headless + useDefaults: true }); this.state = { @@ -51,12 +49,12 @@ export class ToolPermissionService { allow?: string[]; ask?: string[]; exclude?: string[]; - }, headless?: boolean): Promise { + }): Promise { // Ensure permissions.yaml exists before loading await ensurePermissionsYamlExists(); // Use the synchronous version after ensuring the file exists - return this.initializeSync(runtimeOverrides, headless); + return this.initializeSync(runtimeOverrides); } /** diff --git a/src/services/index.ts b/src/services/index.ts index 210c56dee..f9b03ed0d 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -31,13 +31,13 @@ export async function initializeServices(options: ServiceInitOptions = {}) { // Handle tool permissions specially for immediate availability if (options.toolPermissionOverrides) { // Initialize synchronously and register the value immediately - const permissionState = toolPermissionService.initializeSync(options.toolPermissionOverrides, options.headless); + const permissionState = toolPermissionService.initializeSync(options.toolPermissionOverrides); serviceContainer.registerValue(SERVICE_NAMES.TOOL_PERMISSIONS, permissionState); } else { // Register normal factory for lazy initialization serviceContainer.register( SERVICE_NAMES.TOOL_PERMISSIONS, - () => toolPermissionService.initialize(undefined, options.headless), + () => toolPermissionService.initialize(), [] ); }