merge: main and fix conflicts/tests

This commit is contained in:
Dallin Romney 2025-07-30 14:39:40 -07:00
commit 613dd0f751
23 changed files with 778 additions and 132 deletions

View file

@ -2,6 +2,8 @@
The Continue CLI (`cn`) is a customizable command line coding agent.
![Continue CLI Demo](./media/demo.gif)
## Installation
```bash

View file

@ -31,4 +31,48 @@ export default {
__filename: path.resolve(fileURLToPath(import.meta.url)),
},
resolver: "<rootDir>/jest.resolver.cjs",
// Force E2E tests to run sequentially to avoid console override conflicts
projects: [
{
displayName: "e2e",
testMatch: ["<rootDir>/src/e2e/**/*.test.ts"],
maxWorkers: 1,
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
},
moduleNameMapper: {
"^(\\.{1,2}/.+)\\.js$": "$1",
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
preset: "ts-jest/presets/default-esm",
testEnvironment: "node",
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
resolver: "<rootDir>/jest.resolver.cjs",
},
{
displayName: "unit",
testMatch: ["<rootDir>/src/**/*.test.ts", "<rootDir>/src/**/*.test.tsx"],
testPathIgnorePatterns: ["<rootDir>/src/e2e/"],
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
},
moduleNameMapper: {
"^(\\.{1,2}/.+)\\.js$": "$1",
"^highlight\\.js/lib/languages/(.+)$":
"<rootDir>/src/ui/__mocks__/highlightLanguage.js",
"^lowlight$": "<rootDir>/src/ui/__mocks__/lowlight.js",
"^ink-testing-library$":
"<rootDir>/node_modules/ink-testing-library/build/index.js",
"^./SyntaxHighlighter\\.js$":
"<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
"^./FreeTrialStatus\\.js$":
"<rootDir>/src/ui/__mocks__/FreeTrialStatus.tsx",
},
extensionsToTreatAsEsm: [".ts", ".tsx"],
preset: "ts-jest/presets/default-esm",
testEnvironment: "node",
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
resolver: "<rootDir>/jest.resolver.cjs",
},
],
};

View file

@ -1,4 +1,5 @@
import { jest } from "@jest/globals";
import { resetConsoleOverrides } from "./src/util/consoleOverride.js";
// Disable telemetry for tests
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0";
@ -15,7 +16,7 @@ jest.mock("./src/commands/commands.js");
jest.mock("./src/services/index.js");
jest.mock("./src/services/ServiceContainerContext.js");
// Set up global afterEach hook to clear all timers
// Set up global afterEach hook to clear all timers and reset console
afterEach(() => {
// Clear jest timers only if they're available
if (typeof jest !== "undefined" && jest.clearAllTimers) {
@ -25,4 +26,11 @@ afterEach(() => {
// Ignore errors when clearing timers
}
}
// Reset console overrides to ensure clean state for each test
try {
resetConsoleOverrides();
} catch (e) {
// Ignore errors when resetting console
}
});

BIN
media/demo.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

View file

@ -11,6 +11,7 @@ export interface CommandLineArgs {
readonly?: boolean; // Only allow readonly tools
noTools?: boolean; // Disable all tools
rules?: string[]; // Array of rule specifications
format?: 'json'; // Output format for headless mode
}
/**
@ -136,6 +137,15 @@ export function parseArgs(): CommandLineArgs {
result.noTools = true;
}
// Get format from --format flag
const formatIndex = args.indexOf("--format");
if (formatIndex !== -1 && formatIndex + 1 < args.length) {
const formatValue = args[formatIndex + 1];
if (formatValue === 'json') {
result.format = 'json';
}
}
// Get config path from --config flag
const configIndex = args.indexOf("--config");
if (configIndex !== -1 && configIndex + 1 < args.length) {
@ -160,7 +170,7 @@ export function parseArgs(): CommandLineArgs {
}
// Find the last argument that's not a flag or a flag value
const flagsWithValues = ["--config", "--rule"];
const flagsWithValues = ["--config", "--rule", "--format"];
const nonFlagArgs = args.filter((arg, index) => {
// Skip flags (starting with --)
if (arg.startsWith("--") || arg === "-p") return false;

View file

@ -12,17 +12,42 @@ import { ModelServiceState, SERVICE_NAMES } from "../services/types.js";
import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import { posthogService } from "../telemetry/posthogService.js";
import telemetryService from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { BaseCommandOptions } from "./BaseCommandOptions.js";
import { posthogService } from "../telemetry/posthogService.js";
/**
* Processes and validates JSON output for headless mode
* @param response - The raw response from the LLM
* @returns Valid JSON string
*/
function processJsonOutput(response: string): string {
const trimmedResponse = response.trim();
try {
// Try to parse the response as JSON to validate it
JSON.parse(trimmedResponse);
// If it parses successfully, return as-is
return trimmedResponse;
} catch (error) {
// If it's not valid JSON, wrap it in a JSON object
return JSON.stringify({
response: trimmedResponse,
status: "success",
note: "Response was not valid JSON, so it was wrapped in a JSON object",
});
}
}
export interface ChatOptions extends BaseCommandOptions {
headless?: boolean;
resume?: boolean;
rule?: string[]; // Array of rule specifications
format?: "json"; // Output format for headless mode
}
export async function initializeChatHistory(
@ -46,7 +71,9 @@ export async function initializeChatHistory(
const rulesSystemMessage = ""; // TODO //assistant.systemMessage;
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
options.rule
options.rule,
options.format,
options.headless
);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
@ -61,7 +88,8 @@ async function processMessage(
chatHistory: ChatCompletionMessageParam[],
model: any,
llmApi: any,
isHeadless: boolean
isHeadless: boolean,
format?: "json"
): Promise<void> {
// Track user prompt
telemetryService.logUserPrompt(userInput.length, userInput);
@ -84,8 +112,12 @@ async function processMessage(
);
// In headless mode, only print the final response using safe stdout
if (isHeadless && finalResponse.trim()) {
safeStdout(finalResponse + "\n");
if (isHeadless && finalResponse && finalResponse.trim()) {
// Process output based on format
const outputResponse =
format === "json" ? processJsonOutput(finalResponse) : finalResponse;
safeStdout(outputResponse + "\n");
}
// Save session after each successful response
@ -140,7 +172,14 @@ async function runHeadlessMode(
isFirstMessage = false;
await processMessage(userInput, chatHistory, model, llmApi, true);
await processMessage(
userInput,
chatHistory,
model,
llmApi,
true,
options.format
);
}
}

View file

@ -119,7 +119,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// Initialize chat history
let chatHistory: ChatCompletionMessageParam[] = [];
const systemMessage = await constructSystemMessage("", options.rule);
const systemMessage = await constructSystemMessage("", options.rule, undefined, true);
if (systemMessage) {
chatHistory.push({ role: "system", content: systemMessage });
}
@ -584,7 +584,7 @@ async function streamChatResponseWithInterruption(
abortController,
callbacks
);
return response;
return response || "";
} finally {
clearInterval(interruptionChecker);
// Ensure any streaming message is finalized

View file

@ -0,0 +1,112 @@
import {
cleanupTestContext,
createTestContext,
runCLI,
} from "../test-helpers/cli-helpers.js";
import {
setupMockLLMTest,
cleanupMockLLMServer,
type MockLLMServer,
} from "../test-helpers/mock-llm-server.js";
describe("E2E: Headless Mode with JSON Format", () => {
let context: any;
let mockServer: MockLLMServer;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
if (mockServer) {
await cleanupMockLLMServer(mockServer);
}
await cleanupTestContext(context);
});
it("should output valid JSON when LLM returns valid JSON", async () => {
const validJsonResponse = {
response: "This is a JSON response",
status: "success",
files: ["test.ts"]
};
mockServer = await setupMockLLMTest(context, {
response: JSON.stringify(validJsonResponse),
streaming: false, // Use non-streaming to avoid JSON escaping issues
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify the output is valid JSON
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
const parsedOutput = JSON.parse(result.stdout.trim());
expect(parsedOutput).toEqual(validJsonResponse);
expect(result.exitCode).toBe(0);
}, 20000);
it("should wrap non-JSON response in JSON object", async () => {
const nonJsonResponse = "This is just plain text response";
mockServer = await setupMockLLMTest(context, {
response: nonJsonResponse,
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Test prompt"],
timeout: 15000,
});
// Verify the output is valid JSON
expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
const parsedOutput = JSON.parse(result.stdout.trim());
expect(parsedOutput.response).toBe(nonJsonResponse);
expect(parsedOutput.status).toBe("success");
expect(parsedOutput.note).toBe("Response was not valid JSON, so it was wrapped in a JSON object");
expect(result.exitCode).toBe(0);
}, 20000);
it("should include JSON formatting instructions in system message", async () => {
mockServer = await setupMockLLMTest(context, {
response: '{"response": "I understand JSON format"}',
});
const result = await runCLI(context, {
args: ["-p", "--format", "json", "--config", context.configPath, "Hello"],
timeout: 15000,
});
expect(result.exitCode).toBe(0);
expect(mockServer.requests).toHaveLength(1);
// Find the system message
const systemMessage = mockServer.requests[0].body.messages.find((m: any) => m.role === "system");
expect(systemMessage.content).toContain("JSON output mode");
expect(systemMessage.content).toContain("valid JSON that can be parsed by JSON.parse()");
}, 20000);
it("should fail validation when --format is used without -p flag", async () => {
const result = await runCLI(context, {
args: ["--format", "json", "Test prompt"],
timeout: 5000,
expectError: true,
});
expect(result.stderr).toContain("--format flag can only be used with -p/--print flag");
expect(result.exitCode).toBe(1);
}, 10000);
it("should fail validation with invalid format value", async () => {
const result = await runCLI(context, {
args: ["-p", "--format", "xml", "Test prompt"],
timeout: 5000,
expectError: true,
});
expect(result.stderr).toContain("--format currently only supports 'json'");
expect(result.exitCode).toBe(1);
}, 10000);
});

View file

@ -17,25 +17,6 @@ describe("E2E: Headless Mode (Minimal)", () => {
await cleanupTestContext(context);
});
it("should show version with --version flag", async () => {
const result = await runCLI(context, {
args: ["--version"],
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toMatch(/\d+\.\d+\.\d+/); // Matches version pattern
});
it("should show help with --help flag", async () => {
const result = await runCLI(context, {
args: ["--help"],
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("Continue CLI");
expect(result.stdout).toContain("-p, --print");
});
it("should accept a config file path", async () => {
// Create a minimal YAML config
const configPath = path.join(context.testDir, "test-config.yaml");

View file

@ -0,0 +1,122 @@
import { createTestContext, cleanupTestContext, runCLI, createTestConfig } from "../test-helpers/cli-helpers.js";
describe("E2E: Headless Mode - Missing Prompt", () => {
let context: any;
beforeEach(async () => {
context = await createTestContext();
});
afterEach(async () => {
await cleanupTestContext(context);
});
it("should exit with helpful error message when no prompt is provided with -p flag", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath],
env: { OPENAI_API_KEY: "test-key" },
expectError: true,
timeout: 5000, // Short timeout to avoid hanging
});
// Should exit with non-zero exit code
expect(result.exitCode).toBe(1);
// Should provide helpful error message
const output = result.stderr + result.stdout;
expect(output).toContain("A prompt is required when using the -p/--print flag");
expect(output).toContain('cn -p "please review my current git diff"');
expect(output).toContain('echo "hello" | cn -p');
expect(output).toContain('cn -p "analyze the code in src/"');
});
it("should work correctly when prompt is provided with -p flag", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Hello assistant"],
env: { OPENAI_API_KEY: "test-key" },
expectError: true, // Will fail due to invalid API key, but should process the prompt
timeout: 5000,
});
// Should attempt to process the prompt (will fail due to invalid API key)
expect(result.exitCode).not.toBe(0);
// Should NOT show the "prompt required" error message
const output = result.stderr + result.stdout;
expect(output).not.toContain("A prompt is required when using the -p/--print flag");
});
it("should work correctly when prompt is provided via stdin with -p flag", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath],
env: { OPENAI_API_KEY: "test-key" },
input: "Hello from stdin",
expectError: true, // Will fail due to invalid API key, but should process the stdin
timeout: 5000,
});
// Should attempt to process the stdin input (will fail due to invalid API key)
expect(result.exitCode).not.toBe(0);
// Should NOT show the "prompt required" error message
const output = result.stderr + result.stdout;
expect(output).not.toContain("A prompt is required when using the -p/--print flag");
});
it("should prioritize command line prompt over stdin when both are provided", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Command line prompt"],
env: { OPENAI_API_KEY: "test-key" },
input: "Stdin input that should be ignored",
expectError: true, // Will fail due to invalid API key
timeout: 5000,
});
// Should use command line prompt over stdin
expect(result.exitCode).not.toBe(0);
// Should NOT show the "prompt required" error message
const output = result.stderr + result.stdout;
expect(output).not.toContain("A prompt is required when using the -p/--print flag");
});
});

View file

@ -3,6 +3,18 @@ import { createTestContext, cleanupTestContext, runCLI, createTestConfig } from
describe("E2E: Headless Mode (Simple)", () => {
let context: any;
const testConfig = `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`;
const testEnv = { OPENAI_API_KEY: "test-key" };
beforeEach(async () => {
context = await createTestContext();
});
@ -39,72 +51,56 @@ no models here`);
});
it("should handle missing prompt in headless mode", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
await createTestConfig(context, testConfig);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath],
env: { OPENAI_API_KEY: "test-key" },
env: testEnv,
expectError: true,
});
// Should error when no prompt provided in headless mode
expect(result.exitCode).not.toBe(0);
});
it("should accept piped input with -p flag", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
await createTestConfig(context, testConfig);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath],
env: { OPENAI_API_KEY: "test-key" },
env: testEnv,
input: "Hello from piped input",
expectError: true,
});
// Should not show "You: " prompt when input is piped
expect(result.stderr).not.toContain("You:");
expect(result.stdout).not.toContain("You:");
// Will fail because of missing API key but should consume the piped input
expect(result.exitCode).not.toBe(0);
});
it("should not interfere with normal prompt argument", async () => {
await createTestConfig(context, `name: Test Assistant
version: 1.0.0
schema: v1
models:
- model: gpt-4
provider: openai
apiKey: test-key
roles:
- chat`);
it("should combine piped input with prompt argument", async () => {
await createTestConfig(context, testConfig);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Command line argument"],
env: { OPENAI_API_KEY: "test-key" },
input: "Piped input that should be ignored",
env: testEnv,
input: "Piped input to be combined",
expectError: true,
});
expect(result.stderr).not.toContain("You:");
expect(result.stdout).not.toContain("You:");
expect(result.exitCode).not.toBe(0);
});
it("should work with only prompt argument", async () => {
await createTestConfig(context, testConfig);
const result = await runCLI(context, {
args: ["-p", "--config", context.configPath, "Only command line argument"],
env: testEnv,
expectError: true,
});
// Should use command line argument over piped input
// Will fail because of missing API key but should not show "You:" prompt
expect(result.stderr).not.toContain("You:");
expect(result.stdout).not.toContain("You:");
expect(result.exitCode).not.toBe(0);

View file

@ -38,12 +38,30 @@ program
addCommonOptions(program)
.argument("[prompt]", "Optional prompt to send to the assistant")
.option("-p, --print", "Print response and exit (useful for pipes)")
.option(
"--format <format>",
"Output format for headless mode (json). Only works with -p/--print flag."
)
.option("--resume", "Resume from last session")
.action(async (prompt, options) => {
// Configure console overrides FIRST, before any other logging
const isHeadless = options.print;
configureConsoleForHeadless(isHeadless);
// Validate --format flag only works with -p/--print
if (options.format && !options.print) {
console.error(
"Error: --format flag can only be used with -p/--print flag"
);
process.exit(1);
}
// Validate format value
if (options.format && options.format !== "json") {
console.error("Error: --format currently only supports 'json'");
process.exit(1);
}
if (options.verbose) {
logger.setLevel("debug");
const logPath = logger.getLogPath();
@ -60,13 +78,29 @@ addCommonOptions(program)
}
// Check for piped input when using -p flag
if (options.print && !prompt) {
if (options.print) {
const stdinInput = readStdinSync();
if (stdinInput) {
prompt = stdinInput;
if (prompt) {
// Combine stdin and prompt argument - stdin comes first in XML block
prompt = `<stdin>\n${stdinInput}\n</stdin>\n\n${prompt}`;
} else {
// Only stdin input, use as-is
prompt = stdinInput;
}
}
}
// In headless mode, ensure we have a prompt
if (options.print && !prompt) {
console.error("Error: A prompt is required when using the -p/--print flag.\n");
console.error("Usage examples:");
console.error(' cn -p "please review my current git diff"');
console.error(' echo "hello" | cn -p');
console.error(' cn -p "analyze the code in src/"');
process.exit(1);
}
// Map --print to headless mode
options.headless = options.print;
options.print = undefined;
@ -102,7 +136,7 @@ program
});
// Serve subcommand
const serveCommand = program
program
.command("serve [prompt]")
.description("Start an HTTP server with /state and /message endpoints")
.option(
@ -114,12 +148,12 @@ const serveCommand = program
.action(async (prompt, options) => {
// Merge parent options with subcommand options
const mergedOptions = mergeParentOptions(program, options);
if (mergedOptions.verbose) {
logger.setLevel("debug");
logger.debug("Verbose logging enabled");
}
await serve(prompt, mergedOptions);
});
@ -145,4 +179,4 @@ try {
} catch (error) {
console.error(error);
process.exit(1);
}
}

View file

@ -395,14 +395,10 @@ export async function preprocessStreamedToolCalls(
callbacks?: StreamCallbacks
): Promise<{
preprocessedCalls: PreprocessedToolCall[];
chatHistoryEntries: { role: "tool"; tool_call_id: string; content: string }[];
errorChatEntries: ChatCompletionToolMessageParam[];
}> {
const preprocessedCalls: PreprocessedToolCall[] = [];
const chatHistoryEntries: {
role: "tool";
tool_call_id: string;
content: string;
}[] = [];
const errorChatEntries: ChatCompletionToolMessageParam[] = [];
// Get all available tools
const availableTools: Tool[] = await getAvailableTools();
@ -435,9 +431,7 @@ export async function preprocessStreamedToolCalls(
preprocessedCalls.push(preprocessedCall);
} catch (error) {
// Notify the UI about the tool start, even though it failed
if (callbacks?.onToolStart) {
callbacks.onToolStart(toolCall.name, toolCall.arguments);
}
callbacks?.onToolStart?.(toolCall.name, toolCall.arguments);
const errorMessage = `Error processing tool call: ${
error instanceof Error ? error.message : String(error)
@ -457,20 +451,18 @@ export async function preprocessStreamedToolCalls(
);
// Add error to chat history
chatHistoryEntries.push({
errorChatEntries.push({
role: "tool",
tool_call_id: toolCall.id,
content: errorMessage,
});
// Notify about the error
if (callbacks?.onToolError) {
callbacks.onToolError(errorMessage, toolCall.name);
}
callbacks?.onToolError?.(errorMessage, toolCall.name);
}
}
return { preprocessedCalls, chatHistoryEntries };
return { preprocessedCalls, errorChatEntries };
}
/**
@ -484,9 +476,23 @@ export async function executeStreamedToolCalls(
callbacks?: StreamCallbacks
): Promise<ChatCompletionToolMessageParam[]> {
const chatHistoryEntries: ChatCompletionToolMessageParam[] = [];
let remainingCanceled = false;
// Execute each preprocessed tool call
for (const toolCall of preprocessedCalls) {
if (remainingCanceled) {
const cancelledMessage = `Cancelled due to previous tool rejection`;
chatHistoryEntries.push({
role: "tool",
tool_call_id: toolCall.id,
content: cancelledMessage,
});
callbacks?.onToolResult?.(cancelledMessage, toolCall.name);
continue;
}
// Handle remaining tool calls in this batch to maintain chat history consistency
try {
logger.debug("Checking tool permissions", {
name: toolCall.name,
@ -495,9 +501,7 @@ export async function executeStreamedToolCalls(
// Notify tool start - before permission check
// This ensures the UI shows the tool call even if it's rejected
if (callbacks?.onToolStart) {
callbacks.onToolStart(toolCall.name, toolCall.arguments);
}
callbacks?.onToolStart?.(toolCall.name, toolCall.arguments);
// Check tool permissions
const permissionCheck = checkToolPermission(toolCall);
@ -549,6 +553,9 @@ export async function executeStreamedToolCalls(
// Fallback: deny if no UI callback available
approved = false;
}
} else if (permissionCheck.permission === "exclude") {
// This shouldn't happen as excluded tools are filtered out earlier
approved = false;
}
if (!approved) {
@ -564,9 +571,10 @@ export async function executeStreamedToolCalls(
content: deniedMessage,
});
if (callbacks?.onToolResult) {
callbacks.onToolResult(deniedMessage, toolCall.name);
}
callbacks?.onToolResult?.(deniedMessage, toolCall.name);
logger.debug("Tool call rejected - stopping stream");
remainingCanceled = true;
continue;
}
@ -583,9 +591,7 @@ export async function executeStreamedToolCalls(
content: toolResult,
});
if (callbacks?.onToolResult) {
callbacks.onToolResult(toolResult, toolCall.name);
}
callbacks?.onToolResult?.(toolResult, toolCall.name);
} catch (error) {
const errorMessage = `Error executing tool ${toolCall.name}: ${
error instanceof Error ? error.message : String(error)
@ -602,9 +608,7 @@ export async function executeStreamedToolCalls(
content: errorMessage,
});
if (callbacks?.onToolError) {
callbacks.onToolError(errorMessage, toolCall.name);
}
callbacks?.onToolError?.(errorMessage, toolCall.name);
}
}
@ -693,13 +697,11 @@ export async function streamChatResponse(
});
// First preprocess the tool calls
const { preprocessedCalls, chatHistoryEntries: preprocessErrors } =
const { preprocessedCalls, errorChatEntries } =
await preprocessStreamedToolCalls(toolCalls, callbacks);
// Add any preprocessing errors to chat history
for (const entry of preprocessErrors) {
chatHistory.push(entry);
}
chatHistory.push(...errorChatEntries);
// Execute the valid preprocessed tool calls
const toolResults = await executeStreamedToolCalls(
@ -707,10 +709,7 @@ export async function streamChatResponse(
callbacks
);
// Add tool results to chat history
for (const entry of toolResults) {
chatHistory.push(entry);
}
chatHistory.push(...toolResults);
} else if (content) {
// Just content, no tools
chatHistory.push({ role: "assistant", content });
@ -718,7 +717,6 @@ export async function streamChatResponse(
// Check if we should continue
if (!shouldContinue) {
logger.debug("Conversation complete - no more tool calls");
break;
}
}

View file

@ -375,12 +375,12 @@ describe("preprocessStreamedToolCalls", () => {
onToolError: vi.fn(),
};
const { preprocessedCalls, chatHistoryEntries } =
const { preprocessedCalls, errorChatEntries } =
await preprocessStreamedToolCalls(toolCalls, callbacks);
// Should have one preprocessed call and no errors
expect(preprocessedCalls).toHaveLength(1);
expect(chatHistoryEntries).toHaveLength(0);
expect(errorChatEntries).toHaveLength(0);
expect(preprocessedCalls[0].name).toBe("read_file");
expect(preprocessedCalls[0].tool).toBeDefined();
expect(preprocessedCalls[0].preprocessResult).toBeDefined();
@ -414,15 +414,13 @@ describe("preprocessStreamedToolCalls", () => {
onToolError: vi.fn(),
};
const { preprocessedCalls, chatHistoryEntries } =
const { preprocessedCalls, errorChatEntries } =
await preprocessStreamedToolCalls(toolCalls, callbacks);
// Should have no preprocessed calls and one error
expect(preprocessedCalls).toHaveLength(0);
expect(chatHistoryEntries).toHaveLength(1);
expect(chatHistoryEntries[0].content).toContain(
"Missing required argument"
);
expect(errorChatEntries).toHaveLength(1);
expect(errorChatEntries[0].content).toContain("Missing required argument");
// Callbacks should be called for errors
expect(callbacks.onToolStart).toHaveBeenCalledWith("read_file", {});
@ -443,13 +441,13 @@ describe("preprocessStreamedToolCalls", () => {
},
];
const { preprocessedCalls, chatHistoryEntries } =
const { preprocessedCalls, errorChatEntries } =
await preprocessStreamedToolCalls(toolCalls);
// Should have no preprocessed calls and one error
expect(preprocessedCalls).toHaveLength(0);
expect(chatHistoryEntries).toHaveLength(1);
expect(chatHistoryEntries[0].content).toContain(
expect(errorChatEntries).toHaveLength(1);
expect(errorChatEntries[0].content).toContain(
"Tool nonexistent_tool not found"
);
});
@ -554,6 +552,14 @@ describe("executeStreamedToolCalls", () => {
startNotified: false,
tool: writeFileTool,
},
{
id: "call_457",
name: "write_file",
arguments: { filepath: "/test.txt", content: "data" },
argumentsStr: '{"filepath": "/test.txt", "content": "data"}',
startNotified: false,
tool: writeFileTool,
},
];
const callbacks = {
@ -568,8 +574,11 @@ describe("executeStreamedToolCalls", () => {
);
// Verify results
expect(chatHistoryEntries).toHaveLength(1);
expect(chatHistoryEntries).toHaveLength(2);
expect(chatHistoryEntries[0].content).toBe("Permission denied by user");
expect(chatHistoryEntries[1].content).toBe(
"Cancelled due to previous tool rejection"
);
expect(callbacks.onToolStart).toHaveBeenCalledWith("write_file", {
filepath: "/test.txt",
content: "data",

View file

@ -101,4 +101,29 @@ Rule 3: Third rule`;
expect(result).toContain("AGENTS.md");
expect(result).toContain("</context>");
});
it("should add headless mode instructions when headless is true", async () => {
const result = await constructSystemMessage("", undefined, undefined, true);
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).toContain("IMPORTANT: You are running in headless mode");
expect(result).toContain("Provide ONLY your final answer");
expect(result).toContain("Do not include explanations, reasoning, or additional commentary");
});
it("should not add headless mode instructions when headless is false", async () => {
const result = await constructSystemMessage("", undefined, undefined, false);
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).not.toContain("IMPORTANT: You are running in headless mode");
expect(result).not.toContain("Provide ONLY your final answer");
});
it("should not add headless mode instructions when headless is undefined", async () => {
const result = await constructSystemMessage("");
expect(result).toContain("You are an agent in the Continue CLI");
expect(result).not.toContain("IMPORTANT: You are running in headless mode");
expect(result).not.toContain("Provide ONLY your final answer");
});
});

View file

@ -97,11 +97,15 @@ ${getGitStatus()}
* Load and construct a comprehensive system message with base message and rules section
* @param rulesSystemMessage - The rules system message from the assistant
* @param additionalRules - Additional rules from --rule flags
* @param format - Output format for headless mode
* @param headless - Whether running in headless mode
* @returns The comprehensive system message with base message and rules section
*/
export async function constructSystemMessage(
rulesSystemMessage: string,
additionalRules?: string[]
additionalRules?: string[],
format?: "json",
headless?: boolean
): Promise<string> {
const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
@ -139,6 +143,25 @@ export async function constructSystemMessage(
// Construct the comprehensive system message
let systemMessage = baseSystemMessage;
// In headless mode, add instructions to be concise and only provide final answers
if (headless) {
systemMessage += `
IMPORTANT: You are running in headless mode. Provide ONLY your final answer to the user's question. Do not include explanations, reasoning, or additional commentary unless specifically requested. Be direct and concise.`;
}
// Add JSON formatting instructions if format is json
if (format === "json") {
systemMessage += `
IMPORTANT: You are operating in JSON output mode. Your final response MUST be valid JSON that can be parsed by JSON.parse(). The JSON should contain properties relevant to answer the user's question. You don't need to include any general "response" or "answer" field. Do not include any text before or after the JSON - the entire response must be parseable JSON.
Example response format:
{
"property": "value"
}`;
}
// Add rules section if we have any rules or agent content
if (rulesSystemMessage || agentContent || processedRules.length > 0) {
systemMessage += '\n\n<context name="userRules">';

View file

@ -32,6 +32,13 @@ export async function createTestContext(): Promise<CLITestContext> {
const cliPath = path.resolve("dist/index.js");
const testDir = await fs.mkdtemp(path.join(os.tmpdir(), "cn-test-"));
// Ensure the CLI file exists before returning the context
try {
await fs.access(cliPath);
} catch (error) {
throw new Error(`CLI file not found at ${cliPath}. Please run 'npm run build' first.`);
}
return {
cliPath,
testDir,

View file

@ -111,14 +111,18 @@ export async function createMockLLMServer(
const words = responseText.split(" ");
words.forEach((word, index) => {
const content = index === 0 ? word : " " + word;
// Properly escape JSON content
const escapedContent = JSON.stringify(content).slice(1, -1);
res.write(
`data: {"choices":[{"delta":{"content":"${content}"},"index":0}]}\n\n`
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`
);
});
} else {
// Send entire response in one chunk for non-streaming mode
// Properly escape JSON content
const escapedContent = JSON.stringify(responseText).slice(1, -1);
res.write(
`data: {"choices":[{"delta":{"content":"${responseText}"},"index":0}]}\n\n`
`data: {"choices":[{"delta":{"content":"${escapedContent}"},"index":0}]}\n\n`
);
}

View file

@ -34,8 +34,8 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
const allRules = [...commandLineRules, ...configRules];
// Check if model is capable
const modelCapable = isModelCapable(model.provider, model.name);
// Check if model is capable - now checking both name and model properties
const modelCapable = isModelCapable(model.provider, model.name, model.model);
return (
<Box flexDirection="column" paddingX={1} paddingY={1}>

View file

@ -0,0 +1,182 @@
import { jest } from "@jest/globals";
import { render } from "ink-testing-library";
import React from "react";
import { ToolPermissionSelector } from "../components/ToolPermissionSelector.js";
describe("TUIChat - Stream Stopping on Tool Rejection", () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
jest.useRealTimers();
});
it("verifies tool permission rejection flow", async () => {
const handleResponse = jest.fn();
const { stdin } = render(
<ToolPermissionSelector
toolName="Edit"
toolArgs={{
file_path: "/test.txt",
old_string: "old content",
new_string: "new content",
}}
requestId="test-request-123"
onResponse={handleResponse}
/>
);
await jest.advanceTimersByTimeAsync(50);
// Simulate user rejecting the tool call (press escape)
stdin.write("\x1b"); // ESC key
await jest.advanceTimersByTimeAsync(50);
// Verify that the tool was rejected
expect(handleResponse).toHaveBeenCalledWith(
"test-request-123",
false, // approved = false
false // createPolicy = false
);
});
it("verifies rejection with 'n' key triggers proper response", async () => {
const handleResponse = jest.fn();
const { stdin } = render(
<ToolPermissionSelector
toolName="Write"
toolArgs={{
file_path: "/dangerous-file.sh",
content: "rm -rf /",
}}
requestId="dangerous-request"
onResponse={handleResponse}
/>
);
await jest.advanceTimersByTimeAsync(50);
// Press 'n' to reject
stdin.write("n");
await jest.advanceTimersByTimeAsync(50);
// Verify rejection
expect(handleResponse).toHaveBeenCalledWith(
"dangerous-request",
false, // rejected
false
);
});
it("tests that rejection response leads to stream stopping behavior", () => {
// This test validates the key behavior - when onResponse is called with approved=false,
// it should lead to the streamChatResponse function stopping and returning early
const mockStreamingFunction = jest.fn().mockImplementation((approved) => {
if (!approved) {
// Simulate early return when tool is rejected
return "Partial content before rejection";
}
// If approved, would continue with full processing
return "Full content with tool results";
});
// Test rejection path
const rejectedResult = mockStreamingFunction(false);
expect(rejectedResult).toBe("Partial content before rejection");
// Test approval path for comparison
const approvedResult = mockStreamingFunction(true);
expect(approvedResult).toBe("Full content with tool results");
// The key insight: when tools are rejected, processing stops early
expect(rejectedResult).not.toBe(approvedResult);
});
it("validates permission manager handles rejection correctly", async () => {
// Import the permission manager to test its behavior
const { toolPermissionManager } = await import("../../permissions/permissionManager.js");
const mockResolve = jest.fn();
// Simulate a pending request
const requestId = "test-request-456";
(toolPermissionManager as any).pendingRequests.set(requestId, {
toolCall: { name: "Edit", arguments: {} },
resolve: mockResolve,
});
// Reject the request (this is what happens when user presses escape/n)
const result = toolPermissionManager.rejectRequest(requestId);
// Verify the request was properly rejected
expect(result).toBe(true);
expect(mockResolve).toHaveBeenCalledWith({ approved: false });
// Verify the request was removed from pending requests
expect((toolPermissionManager as any).pendingRequests.has(requestId)).toBe(false);
});
it("handles multiple tool calls correctly when first is rejected", () => {
// Test the bug fix: when multiple tool calls are present and the first is rejected,
// remaining tool calls should be marked as cancelled to maintain chat history consistency
const mockMultipleToolCalls = [
{ id: "call_1", name: "Edit", arguments: {} },
{ id: "call_2", name: "Write", arguments: {} },
{ id: "call_3", name: "Read", arguments: {} },
];
const mockCallbacks = {
onToolResult: jest.fn(),
};
// Simulate the rejection handling logic
const deniedMessage = "Permission denied by user";
const rejectedToolCall = mockMultipleToolCalls[0];
// First tool call gets denied
mockCallbacks.onToolResult(deniedMessage, rejectedToolCall.name);
// Remaining tool calls should be cancelled
for (let i = 1; i < mockMultipleToolCalls.length; i++) {
const remainingToolCall = mockMultipleToolCalls[i];
const cancelledMessage = "Cancelled due to previous tool rejection";
mockCallbacks.onToolResult(cancelledMessage, remainingToolCall.name);
}
// Verify all tool calls got results
expect(mockCallbacks.onToolResult).toHaveBeenCalledTimes(3);
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(1, "Permission denied by user", "Edit");
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(2, "Cancelled due to previous tool rejection", "Write");
expect(mockCallbacks.onToolResult).toHaveBeenNthCalledWith(3, "Cancelled due to previous tool rejection", "Read");
});
it("ensures proper response content in headless mode", () => {
// Test the bug fix: ensure finalResponse fallback works properly in headless mode
const mockStreamingBehavior = (isHeadless: boolean, finalResponse: string, content: string, fullResponse: string) => {
// Simulate the fixed return logic
const responseToReturn = isHeadless ? (finalResponse || content) : fullResponse;
return responseToReturn;
};
// Test headless mode with initialized finalResponse
expect(mockStreamingBehavior(true, "final content", "current content", "full content"))
.toBe("final content");
// Test headless mode with uninitialized finalResponse (empty string)
expect(mockStreamingBehavior(true, "", "current content", "full content"))
.toBe("current content");
// Test non-headless mode
expect(mockStreamingBehavior(false, "final content", "current content", "full content"))
.toBe("full content");
});
});

View file

@ -95,4 +95,21 @@ export function withOriginalConsole<T>(fn: () => T): T {
*/
export function isInHeadlessMode(): boolean {
return isHeadlessMode;
}
/**
* Reset console overrides to original state
* Useful for testing to ensure clean state
*/
export function resetConsoleOverrides(): void {
if (originalConsole) {
console.log = originalConsole.log;
console.info = originalConsole.info;
console.warn = originalConsole.warn;
console.error = originalConsole.error;
console.debug = originalConsole.debug;
originalConsole = null;
}
isHeadlessMode = false;
}

View file

@ -118,4 +118,32 @@ describe('isModelCapable', () => {
expect(isModelCapable('anthropic', 'CLAUDE-3-OPUS')).toBe(true);
});
});
describe('Model property matching', () => {
test('should consider models capable when model property matches even if name does not', () => {
// Case where name doesn't match but model property does
expect(isModelCapable('custom', 'some-custom-name', 'gpt-4')).toBe(true);
expect(isModelCapable('custom', 'random-name', 'claude-3-opus')).toBe(true);
expect(isModelCapable('custom', 'xyz', 'gemini-pro')).toBe(true);
});
test('should consider models capable when name matches even if model property does not', () => {
// Case where name matches but model property doesn't
expect(isModelCapable('custom', 'gpt-4', 'some-internal-id')).toBe(true);
expect(isModelCapable('custom', 'claude-3-opus', 'xyz')).toBe(true);
expect(isModelCapable('custom', 'gemini-pro', 'random')).toBe(true);
});
test('should consider models capable when both name and model match', () => {
// Case where both match
expect(isModelCapable('openai', 'gpt-4', 'gpt-4-turbo')).toBe(true);
expect(isModelCapable('anthropic', 'claude-3', 'claude-3-opus')).toBe(true);
});
test('should consider models not capable when neither name nor model match', () => {
// Case where neither matches
expect(isModelCapable('custom', 'llama-7b', 'local-model')).toBe(false);
expect(isModelCapable('custom', 'falcon-7b', 'random-model')).toBe(false);
});
});
});

View file

@ -1,16 +1,21 @@
/**
* Determines if a model is recommended for use with `cn`
*/
export function isModelCapable(provider: string, model: string): boolean {
const normalizedModel = model.toLowerCase();
export function isModelCapable(provider: string, name: string, model?: string): boolean {
// Check both name and model properties
const normalizedName = name.toLowerCase();
const normalizedModel = model ? model.toLowerCase() : '';
if (
[/gemini/, /claude/, /gpt/, /o\d/g, /kimi/, /qwen/].some((pattern) =>
pattern.test(normalizedModel)
)
) {
const patterns = [/gemini/, /claude/, /gpt/, /o\d/, /kimi/, /qwen/];
// If either name OR model matches any of the patterns, consider it capable
if (patterns.some((pattern) => pattern.test(normalizedName))) {
return true;
}
if (model && patterns.some((pattern) => pattern.test(normalizedModel))) {
return true;
}
return false;
}
}