merge main

This commit is contained in:
Dallin Romney 2025-07-31 09:21:45 -07:00
commit 51b01c6205
15 changed files with 1140 additions and 235 deletions

View file

@ -82,3 +82,25 @@ 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 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`) - user is prompted
- **Headless mode**: Same default policies, but tools requiring confirmation (`ask`) will cause the process to exit with an error message
To use tools that normally require confirmation in headless mode, you must explicitly allow them:
```bash
# 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 run_terminal_command "Clean up the codebase"
```
This approach ensures that headless mode is secure by default while providing clear guidance on how to enable the needed permissions.

View file

@ -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<void> {
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);
}
/**

View file

@ -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<void> {
const configDir = path.dirname(CONFIG_PATH);
@ -46,60 +46,12 @@ export async function createOrUpdateConfig(apiKey: string): Promise<void> {
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(

View file

@ -26,3 +26,4 @@ export const DEFAULT_TOOL_POLICIES: ToolPermissionPolicy[] = [
// Default fallback - ask for any unmatched tools
{ tool: "*", permission: "ask" },
];

View file

@ -0,0 +1,117 @@
import { resolvePermissionPrecedence } from "./precedenceResolver.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import { checkToolPermission } from "./permissionChecker.js";
describe("Headless Permissions Integration", () => {
describe("precedence resolution", () => {
it("should use default policies", () => {
const policies = resolvePermissionPrecedence({
useDefaults: true,
personalSettings: false, // Disable to avoid file system dependencies
});
expect(policies).toEqual(DEFAULT_TOOL_POLICIES);
});
it("should allow CLI overrides to supersede defaults", () => {
const policies = resolvePermissionPrecedence({
commandLineFlags: {
exclude: ["dangerous_tool"],
},
useDefaults: true,
personalSettings: false,
});
// CLI exclusion should come first
expect(policies[0]).toEqual({ tool: "dangerous_tool", permission: "exclude" });
// Default policies should follow
expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
});
});
describe("permission checking with default policies", () => {
it("should follow default permission rules", () => {
const permissions = { policies: DEFAULT_TOOL_POLICIES };
// 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");
// 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 },
...DEFAULT_TOOL_POLICIES,
];
const permissions = { policies };
// Excluded tool should be blocked
const excludedResult = checkToolPermission(
{ name: "dangerous_tool", arguments: {} },
permissions
);
expect(excludedResult.permission).toBe("exclude");
// 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 with permission overrides", () => {
// Simulate CLI with some overrides
const policies = resolvePermissionPrecedence({
commandLineFlags: {
// Still exclude truly dangerous operations
exclude: ["rm", "sudo"],
// Allow specific tools that would normally require confirmation
allow: ["write_file", "run_terminal_command"],
},
useDefaults: true,
personalSettings: false,
});
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: "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,
});
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");
});
});
});

View file

@ -140,5 +140,48 @@ describe("precedenceResolver", () => {
const readPolicy = policies.find(p => p.tool === "read_file");
expect(readPolicy).toBeDefined();
});
describe("precedence rules", () => {
it("should use default policies when no other sources provided", () => {
const policies = resolvePermissionPrecedence({
useDefaults: true,
personalSettings: false,
});
expect(policies).toEqual(DEFAULT_TOOL_POLICIES);
});
it("should allow CLI flags to override default policies", () => {
const policies = resolvePermissionPrecedence({
commandLineFlags: {
exclude: ["write_file"],
},
useDefaults: true,
personalSettings: false,
});
// CLI exclusion should come first
expect(policies[0]).toEqual({ tool: "write_file", permission: "exclude" });
// Default policies should follow
expect(policies.slice(1)).toEqual(DEFAULT_TOOL_POLICIES);
});
it("should allow config policies to override defaults", () => {
const configPolicies: ToolPermissionPolicy[] = [
{ tool: "run_terminal_command", permission: "allow" },
];
const policies = resolvePermissionPrecedence({
configPermissions: configPolicies,
useDefaults: true,
personalSettings: false,
});
// 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);
});
});
});
});

View file

@ -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
});

View file

@ -22,6 +22,7 @@ import {
BUILTIN_TOOLS,
executeToolCall,
getAvailableTools,
getToolDisplayName,
Tool,
ToolCall,
validateToolCallArgsPresent,
@ -473,7 +474,8 @@ export async function preprocessStreamedToolCalls(
*/
export async function executeStreamedToolCalls(
preprocessedCalls: PreprocessedToolCall[],
callbacks?: StreamCallbacks
callbacks?: StreamCallbacks,
isHeadless?: boolean
): Promise<{
hasRejection: boolean;
chatHistoryEntries: ChatCompletionToolMessageParam[];
@ -513,6 +515,23 @@ export async function executeStreamedToolCalls(
if (permissionCheck.permission === "allow") {
approved = true;
} else if (permissionCheck.permission === "ask") {
if (isHeadless) {
// In headless mode, exit immediately with instructions
const tool = BUILTIN_TOOLS.find((t) => t.name === toolCall.name);
const toolName = tool?.displayName || toolCall.name;
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
@ -711,7 +730,11 @@ export async function streamChatResponse(
// Execute the valid preprocessed tool calls
const { chatHistoryEntries: toolResults, hasRejection } =
await executeStreamedToolCalls(preprocessedCalls, callbacks);
await executeStreamedToolCalls(
preprocessedCalls,
callbacks,
isHeadless
);
if (isHeadless && hasRejection) {
logger.debug(

View file

@ -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");
});
});
});

View file

@ -1,4 +1,4 @@
import { exec } from "child_process";
import { spawn } from "child_process";
import telemetryService from "../telemetry/telemetryService.js";
import {
isGitCommitCommand,
@ -38,27 +38,84 @@ export const runTerminalCommandTool: Tool = {
},
run: async ({ command }: { command: string }): Promise<string> => {
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;
let isResolved = false;
if (error) {
reject(`Error: ${error.message}`);
const TIMEOUT_MS = 30000; // 30 seconds
const resetTimeout = () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
if (isResolved) return;
isResolved = true;
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 (isResolved) return;
isResolved = true;
if (timeoutId) {
clearTimeout(timeoutId);
}
// 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
if (isGitCommitCommand(command)) {
telemetryService.recordCommitCreated();
} else if (isPullRequestCommand(command)) {
telemetryService.recordPullRequestCreated();
// 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(`Stderr: ${stderr}`);
resolve(stdout + `\nStderr: ${stderr}`);
return;
}
resolve(stdout);
});
child.on("error", (error) => {
if (isResolved) return;
isResolved = true;
if (timeoutId) {
clearTimeout(timeoutId);
}
reject(`Error: ${error.message}`);
});
});
},
};

199
src/ui/ColoredDiff.test.ts Normal file
View file

@ -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("+ ");
});
});

View file

@ -1,15 +1,25 @@
import { diffWordsWithSpace, Change } from "diff";
import { Box, Text } from "ink";
import React from "react";
import React, { useMemo } 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';
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;
@ -22,105 +32,236 @@ 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;
}
export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent }) => {
function useWordLevelDiff(oldContent: string, newContent: string) {
return useMemo(() => {
return diffWordsWithSpace(oldContent, newContent);
}, [oldContent, newContent]);
}
function renderWordLevelContent(
changes: Change[],
showType: "removed" | "added"
): React.ReactNode {
const segments: React.ReactNode[] = [];
changes.forEach((change, index) => {
if (showType === "removed") {
if (change.removed) {
// Highlight removed words with darker red
segments.push(
<Text key={index} backgroundColor={COLORS.DELETION_HIGHLIGHT}>
{change.value}
</Text>
);
} else if (!change.added) {
// Unchanged text - no special styling
segments.push(change.value);
}
} else {
if (change.added) {
// Highlight added words with darker green
segments.push(
<Text key={index} backgroundColor={COLORS.ADDITION_HIGHLIGHT}>
{change.value}
</Text>
);
} else if (!change.removed) {
// Unchanged text - no special styling
segments.push(change.value);
}
}
});
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 (
<Box key={`group-${groupIndex}`} flexDirection="column">
<Box flexDirection="row">
<Text color={COLORS.LINE_NUMBER}>
{(delLines[0]?.oldLine ?? "").toString().padEnd(4)}{" "}
</Text>
<Text backgroundColor={COLORS.DELETION_BG}>- </Text>
<Text backgroundColor={COLORS.DELETION_BG}>
{renderWordLevelContent(changes, "removed")}
</Text>
</Box>
<Box flexDirection="row">
<Text color={COLORS.LINE_NUMBER}>
{(addLines[0]?.newLine ?? "").toString().padEnd(4)}{" "}
</Text>
<Text backgroundColor={COLORS.ADDITION_BG}>+ </Text>
<Text backgroundColor={COLORS.ADDITION_BG}>
{renderWordLevelContent(changes, "added")}
</Text>
</Box>
</Box>
);
};
export const ColoredDiff: React.FC<{ diffContent: string }> = ({
diffContent,
}) => {
const parsedLines = parseDiffWithLineNumbers(diffContent);
if (parsedLines.length === 0) {
return <Text color="gray">No changes detected.</Text>;
}
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;
// 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 (
<Box flexDirection="column">
{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 = COLORS.ADDITION_BG;
prefixSymbol = "+";
break;
case "del":
gutterNumStr = (line.oldLine ?? "").toString();
backgroundColor = COLORS.DELETION_BG;
prefixSymbol = "-";
break;
case "context":
gutterNumStr = (line.newLine ?? "").toString();
dim = true;
prefixSymbol = " ";
break;
default:
return null;
}
return (
<Box key={lineKey} flexDirection="row">
<Text color={COLORS.LINE_NUMBER}>{gutterNumStr.padEnd(4)} </Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{prefixSymbol}{" "}
</Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{line.content}
</Text>
</Box>
);
} else {
// Word-level diff group
const delLines = group.lines.filter((l) => l.type === "del");
const addLines = group.lines.filter((l) => l.type === "add");
return (
<WordLevelDiffGroup
key={`group-${groupIndex}`}
groupIndex={groupIndex}
delLines={delLines}
addLines={addLines}
/>
);
}
return (
<Box key={lineKey} flexDirection="row">
<Text color="gray">{gutterNumStr.padEnd(4)} </Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{prefixSymbol}{' '}
</Text>
<Text backgroundColor={backgroundColor} dimColor={dim}>
{line.content}
</Text>
</Box>
);
})}
{isTruncated && (
<Text color="gray" dimColor>
@ -129,4 +270,4 @@ export const ColoredDiff: React.FC<{ diffContent: string }> = ({ diffContent })
)}
</Box>
);
};
};

View file

@ -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<void> {
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<FreeTrialTransitionUIProps> = ({

View file

@ -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}`);
});
});
});
});

View file

@ -0,0 +1,87 @@
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);
// Update the models array while preserving comments and structure
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();
}
}