diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml index f718deeca..45ad818d1 100644 --- a/.github/workflows/continue-detailed-review.yaml +++ b/.github/workflows/continue-detailed-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Detailed PR Review - uses: continuedev/continue/actions/detailed-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7 + uses: continuedev/continue/actions/detailed-review@5dc7a050db441934c26eb910b8433291f627db7f with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: continuedev diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 01fffa316..16a5af935 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Continue PR Review Action - uses: continuedev/continue/actions/general-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7 + uses: continuedev/continue/actions/general-review@5dc7a050db441934c26eb910b8433291f627db7f with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "continuedev" diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts new file mode 100644 index 000000000..d907768cb --- /dev/null +++ b/core/commands/slash/ruleBlockSlashCommand.ts @@ -0,0 +1,15 @@ +import { RuleWithSource, SlashCommandWithSource } from "../.."; + +export function convertRuleBlockToSlashCommand( + rule: RuleWithSource, +): SlashCommandWithSource { + return { + name: + rule.name || + (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule), + description: rule.description ?? "", + prompt: rule.rule, + source: "invokable-rule", + promptFile: rule.ruleFile, + }; +} diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts new file mode 100644 index 000000000..ccbc2df4f --- /dev/null +++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vitest"; +import { RuleWithSource } from "../.."; +import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand"; + +describe("convertRuleBlockToSlashCommand", () => { + it("should convert a rule with all properties to a slash command", () => { + const rule: RuleWithSource = { + name: "Code Review", + rule: "Review this code for best practices", + description: "Performs a code review", + source: "rules-block", + ruleFile: "/path/to/rules.yaml", + invokable: true, + }; + + const result = convertRuleBlockToSlashCommand(rule); + + expect(result).toEqual({ + name: "Code Review", + description: "Performs a code review", + prompt: "Review this code for best practices", + source: "invokable-rule", + promptFile: "/path/to/rules.yaml", + }); + }); + + it("should handle a rule without name", () => { + const rule: RuleWithSource = { + rule: "Review this code", + source: "rules-block", + invokable: true, + }; + + const result = convertRuleBlockToSlashCommand(rule); + + expect(result.name).toBe("Review this code"); + expect(result.prompt).toBe("Review this code"); + }); + + it("should truncate long rule text when used as name", () => { + const rule: RuleWithSource = { + rule: "This is a very long rule text that should be truncated", + source: "rules-block", + invokable: true, + }; + + const result = convertRuleBlockToSlashCommand(rule); + + expect(result.name).toBe("This is a very long ..."); + expect(result.prompt).toBe( + "This is a very long rule text that should be truncated", + ); + }); + + it("should handle a rule without description", () => { + const rule: RuleWithSource = { + name: "Test Rule", + rule: "Test rule content", + source: "rules-block", + invokable: true, + }; + + const result = convertRuleBlockToSlashCommand(rule); + + expect(result.description).toBe(""); + }); + + it("should use rule text as the prompt", () => { + const rule: RuleWithSource = { + name: "Explain Code", + rule: "Explain what this code does in simple terms", + source: "rules-block", + invokable: true, + }; + + const result = convertRuleBlockToSlashCommand(rule); + + expect(result.prompt).toBe("Explain what this code does in simple terms"); + }); + + it("should always set source to 'invokable-rule'", () => { + const rule: RuleWithSource = { + name: "Test", + rule: "Test", + source: "default-chat", + invokable: true, + }; + + const result = convertRuleBlockToSlashCommand(rule); + + expect(result.source).toBe("invokable-rule"); + }); +}); diff --git a/core/config/types.ts b/core/config/types.ts index 6048cf4d3..0b76419df 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -1061,6 +1061,7 @@ declare global { filepath?: string; fileContent?: string; originalFileContent?: string; + autoFormattingDiff?: string; } export interface RangeInFileWithContents { diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 65cb5e0ff..19202e7fd 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -24,6 +24,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; +import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand"; import { getControlPlaneEnvSync } from "../../control-plane/env"; import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { getBaseToolDefinitions } from "../../tools"; @@ -208,7 +209,21 @@ async function configYamlToContinueConfig(options: { } for (const rule of config.rules ?? []) { - continueConfig.rules.push(convertYamlRuleToContinueRule(rule)); + const convertedRule = convertYamlRuleToContinueRule(rule); + continueConfig.rules.push(convertedRule); + + // Convert invokable rules to slash commands + if (convertedRule.invokable) { + try { + const slashCommand = convertRuleBlockToSlashCommand(convertedRule); + continueConfig.slashCommands?.push(slashCommand); + } catch (e) { + localErrors.push({ + message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`, + fatal: false, + }); + } + } } continueConfig.data = config.data; diff --git a/core/config/yaml/yamlToContinueConfig.ts b/core/config/yaml/yamlToContinueConfig.ts index 8d61e06bc..f775646ef 100644 --- a/core/config/yaml/yamlToContinueConfig.ts +++ b/core/config/yaml/yamlToContinueConfig.ts @@ -13,8 +13,10 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { rule: rule.rule, globs: rule.globs, name: rule.name, + description: rule.description, ruleFile: rule.sourceFile, alwaysApply: rule.alwaysApply, + invokable: rule.invokable, }; } } diff --git a/core/core.ts b/core/core.ts index b824624a6..c340fb624 100644 --- a/core/core.ts +++ b/core/core.ts @@ -29,8 +29,9 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { isProcessBackgrounded, + killTerminalProcess, markProcessAsBackgrounded, -} from "./util/processTerminalBackgroundStates"; +} from "./util/processTerminalStates"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -1062,6 +1063,10 @@ export class Core { }, ); + on("process/killTerminalProcess", async ({ data: { toolCallId } }) => { + await killTerminalProcess(toolCallId); + }); + on("mdm/setLicenseKey", ({ data: { licenseKey } }) => { const isValid = setMdmLicenseKey(licenseKey); return isValid; diff --git a/core/index.d.ts b/core/index.d.ts index 6e80bc5d3..6b0844d02 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1387,6 +1387,7 @@ export interface ApplyState { fileContent?: string; originalFileContent?: string; toolCallId?: string; + autoFormattingDiff?: string; } export interface StreamDiffLinesPayload { @@ -1807,6 +1808,7 @@ export interface RuleWithSource { description?: string; ruleFile?: string; alwaysApply?: boolean; + invokable?: boolean; } export interface CompleteOnboardingPayload { mode: OnboardingModes; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 5add878be..74243f195 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -313,5 +313,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "process/markAsBackgrounded": [{ toolCallId: string }, void]; "process/isBackgrounded": [{ toolCallId: string }, boolean]; + "process/killTerminalProcess": [{ toolCallId: string }, void]; "mdm/setLicenseKey": [{ licenseKey: string }, boolean]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 91819a33d..8f109f46f 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -86,6 +86,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "isItemTooBig", "process/markAsBackgrounded", "process/isBackgrounded", + "process/killTerminalProcess", ]; // Message types to pass through from core to webview diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index b106396af..cccf3353b 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -36,8 +36,11 @@ import { fileURLToPath } from "node:url"; import { ToolImpl } from "."; import { isProcessBackgrounded, + markProcessAsRunning, removeBackgroundedProcess, -} from "../../util/processTerminalBackgroundStates"; + removeRunningProcess, + updateProcessOutput, +} from "../../util/processTerminalStates"; import { getBooleanArg, getStringArg } from "../parseArgs"; const asyncExec = util.promisify(childProcess.exec); @@ -120,6 +123,16 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { env: getColorEnv(), // Add enhanced environment for colors }); + // Track this process for foreground cancellation + if (toolCallId && waitForCompletion) { + markProcessAsRunning( + toolCallId, + childProc, + extras.onPartialOutput, + terminalOutput, + ); + } + childProc.stdout?.on("data", (data) => { // Skip if this process has been backgrounded if (isProcessBackgrounded(toolCallId)) return; @@ -127,6 +140,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { const newOutput = getDecodedOutput(data); terminalOutput += newOutput; + // Update the tracked output for potential cancellation notifications + if (toolCallId && waitForCompletion) { + updateProcessOutput(toolCallId, terminalOutput); + } + // Send partial output to UI if (extras.onPartialOutput) { const status = waitForCompletion @@ -153,6 +171,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { const newOutput = getDecodedOutput(data); terminalOutput += newOutput; + // Update the tracked output for potential cancellation notifications + if (toolCallId && waitForCompletion) { + updateProcessOutput(toolCallId, terminalOutput); + } + // Send partial output to UI, status is not required if (extras.onPartialOutput) { extras.onPartialOutput({ @@ -182,15 +205,19 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { } childProc.on("close", (code) => { - // If this process has been backgrounded, clean it up from the map and return - if (isProcessBackgrounded(toolCallId)) { - removeBackgroundedProcess(toolCallId); - return; + // Clean up process tracking + if (toolCallId) { + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } + // Remove from foreground tracking if it was tracked + removeRunningProcess(toolCallId); } if (waitForCompletion) { // Normal completion, resolve now - if (code === 0) { + if (!code || code === 0) { const status = "Command completed"; resolve([ { @@ -234,10 +261,14 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }); childProc.on("error", (error) => { - // If this process has been backgrounded, clean it up from the map and return - if (isProcessBackgrounded(toolCallId)) { - removeBackgroundedProcess(toolCallId); - return; + // Clean up process tracking + if (toolCallId) { + if (isProcessBackgrounded(toolCallId)) { + removeBackgroundedProcess(toolCallId); + return; + } + // Remove from foreground tracking if it was tracked + removeRunningProcess(toolCallId); } reject(error); @@ -281,6 +312,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }, ); + // Track this process for foreground cancellation + if (toolCallId) { + markProcessAsRunning(toolCallId, childProc, undefined, ""); + } + let stdout = ""; let stderr = ""; @@ -293,6 +329,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }); childProc.on("close", (code) => { + // Clean up process tracking + if (toolCallId) { + removeRunningProcess(toolCallId); + } + if (code === 0) { resolve({ stdout, stderr }); } else { @@ -305,6 +346,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }); childProc.on("error", (error) => { + // Clean up process tracking + if (toolCallId) { + removeRunningProcess(toolCallId); + } reject(error); }); }, diff --git a/core/tools/implementations/runTerminalCommand.vitest.ts b/core/tools/implementations/runTerminalCommand.vitest.ts index 659163eb8..230d482f7 100644 --- a/core/tools/implementations/runTerminalCommand.vitest.ts +++ b/core/tools/implementations/runTerminalCommand.vitest.ts @@ -12,7 +12,7 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import { IDE, ToolExtras } from "../.."; -import * as processBackgroundStates from "../../util/processTerminalBackgroundStates"; +import * as processTerminalStates from "../../util/processTerminalStates"; import { runTerminalCommandImpl } from "./runTerminalCommand"; import { runTerminalCommandTool } from "../definitions/runTerminalCommand"; @@ -39,12 +39,8 @@ describe("runTerminalCommandImpl", () => { vi.resetAllMocks(); // Setup backgrounded processes handling - don't mock, just make sure it's empty - // Get any processes that might be already tracked and clear them - const processMap = (processBackgroundStates as any) - .processTerminalBackgroundStates; - if (processMap && typeof processMap.clear === "function") { - processMap.clear(); - } + // Clear any processes that might be already tracked + processTerminalStates.clearAllBackgroundProcesses(); // Setup IDE mocks mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" })); diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts index 31c447389..5a0bc95bf 100644 --- a/core/util/messageContent.ts +++ b/core/util/messageContent.ts @@ -35,6 +35,21 @@ export function renderContextItems(contextItems: ContextItem[]): string { return contextItems.map((item) => item.content).join("\n\n"); } +export function renderContextItemsWithStatus(contextItems: any[]): string { + return contextItems + .map((item) => { + let result = item.content; + + // If this item has a status, append it directly after the content + if (item.status) { + result += `\n[Status: ${item.status}]`; + } + + return result; + }) + .join("\n\n"); +} + export function normalizeToMessageParts(message: ChatMessage): MessagePart[] { switch (message.role) { case "user": diff --git a/core/util/processTerminalBackgroundStates.test.ts b/core/util/processTerminalBackgroundStates.test.ts deleted file mode 100644 index 03a6e3de5..000000000 --- a/core/util/processTerminalBackgroundStates.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { - markProcessAsBackgrounded, - isProcessBackgrounded, - removeBackgroundedProcess, -} from "./processTerminalBackgroundStates"; - -describe("processTerminalBackgroundStates", () => { - beforeEach(() => { - // Clear any backgrounded processes before each test - const backgroundedProcesses = Array.from( - Object.getOwnPropertySymbols(global), - ).find( - (symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)", - ); - - if (backgroundedProcesses) { - // Reset the map by reimporting the module - jest.resetModules(); - } - }); - - test("should mark a process as backgrounded", () => { - const toolCallId = "test-123"; - markProcessAsBackgrounded(toolCallId); - expect(isProcessBackgrounded(toolCallId)).toBe(true); - }); - - test("should correctly identify non-backgrounded processes", () => { - const toolCallId = "test-123"; - const anotherToolCallId = "test-456"; - - markProcessAsBackgrounded(toolCallId); - - expect(isProcessBackgrounded(toolCallId)).toBe(true); - expect(isProcessBackgrounded(anotherToolCallId)).toBe(false); - }); - - test("should remove a process from backgrounded state", () => { - const toolCallId = "test-123"; - - markProcessAsBackgrounded(toolCallId); - expect(isProcessBackgrounded(toolCallId)).toBe(true); - - removeBackgroundedProcess(toolCallId); - expect(isProcessBackgrounded(toolCallId)).toBe(false); - }); - - test("should handle removing non-existent processes", () => { - const toolCallId = "test-123"; - - // Should not throw an error - removeBackgroundedProcess(toolCallId); - expect(isProcessBackgrounded(toolCallId)).toBe(false); - }); - - test("should handle multiple processes", () => { - const toolCallId1 = "test-123"; - const toolCallId2 = "test-456"; - const toolCallId3 = "test-789"; - - markProcessAsBackgrounded(toolCallId1); - markProcessAsBackgrounded(toolCallId2); - - expect(isProcessBackgrounded(toolCallId1)).toBe(true); - expect(isProcessBackgrounded(toolCallId2)).toBe(true); - expect(isProcessBackgrounded(toolCallId3)).toBe(false); - - removeBackgroundedProcess(toolCallId1); - - expect(isProcessBackgrounded(toolCallId1)).toBe(false); - expect(isProcessBackgrounded(toolCallId2)).toBe(true); - }); -}); diff --git a/core/util/processTerminalBackgroundStates.ts b/core/util/processTerminalBackgroundStates.ts deleted file mode 100644 index 437b90925..000000000 --- a/core/util/processTerminalBackgroundStates.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Track which processes have been backgrounded -const processTerminalBackgroundStates = new Map(); - -// Function to mark a process as backgrounded -export function markProcessAsBackgrounded(toolCallId: string): void { - processTerminalBackgroundStates.set(toolCallId, true); -} - -// Function to check if a process is backgrounded -export function isProcessBackgrounded(toolCallId: string): boolean { - return processTerminalBackgroundStates.has(toolCallId); -} - -// Function to remove a process from the backgrounded processes map -export function removeBackgroundedProcess(toolCallId: string): void { - processTerminalBackgroundStates.delete(toolCallId); -} diff --git a/core/util/processTerminalStates.test.ts b/core/util/processTerminalStates.test.ts new file mode 100644 index 000000000..6b9e39f00 --- /dev/null +++ b/core/util/processTerminalStates.test.ts @@ -0,0 +1,367 @@ +import { ChildProcess } from "child_process"; +import { + clearAllBackgroundProcesses, + getAllBackgroundedProcessIds, + getAllRunningProcessIds, + getRunningProcess, + isProcessBackgrounded, + isProcessRunning, + killAllRunningTerminalProcesses, + killMultipleTerminalProcesses, + killTerminalProcess, + markProcessAsBackgrounded, + markProcessAsRunning, + removeBackgroundedProcess, + removeRunningProcess, + updateProcessOutput, +} from "./processTerminalStates"; + +// Mock ChildProcess +const createMockProcess = ( + pid: number = 123, + killed: boolean = false, +): jest.Mocked => { + const mockProcess = { + pid, + killed, + kill: jest.fn(), + } as unknown as jest.Mocked; + + // Make kill() update the killed property + mockProcess.kill.mockImplementation(() => { + (mockProcess as any).killed = true; + return true; + }); + + return mockProcess; +}; + +describe("processTerminalStates", () => { + beforeEach(() => { + // Clear all running processes + const runningIds = getAllRunningProcessIds(); + runningIds.forEach((id) => removeRunningProcess(id)); + + // Clear all backgrounded processes + const backgroundedIds = getAllBackgroundedProcessIds(); + backgroundedIds.forEach((id) => removeBackgroundedProcess(id)); + + // Clear all timers + jest.clearAllTimers(); + }); + + test("should mark a process as backgrounded", () => { + const toolCallId = "test-123"; + markProcessAsBackgrounded(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(true); + }); + + test("should correctly identify non-backgrounded processes", () => { + const toolCallId = "test-123"; + const anotherToolCallId = "test-456"; + + markProcessAsBackgrounded(toolCallId); + + expect(isProcessBackgrounded(toolCallId)).toBe(true); + expect(isProcessBackgrounded(anotherToolCallId)).toBe(false); + }); + + test("should remove a process from backgrounded state", () => { + const toolCallId = "test-123"; + + markProcessAsBackgrounded(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(true); + + removeBackgroundedProcess(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(false); + }); + + test("should handle removing non-existent processes", () => { + const toolCallId = "test-123"; + + // Should not throw an error + removeBackgroundedProcess(toolCallId); + expect(isProcessBackgrounded(toolCallId)).toBe(false); + }); + + test("should handle multiple processes", () => { + const toolCallId1 = "test-123"; + const toolCallId2 = "test-456"; + const toolCallId3 = "test-789"; + + markProcessAsBackgrounded(toolCallId1); + markProcessAsBackgrounded(toolCallId2); + + expect(isProcessBackgrounded(toolCallId1)).toBe(true); + expect(isProcessBackgrounded(toolCallId2)).toBe(true); + expect(isProcessBackgrounded(toolCallId3)).toBe(false); + + removeBackgroundedProcess(toolCallId1); + + expect(isProcessBackgrounded(toolCallId1)).toBe(false); + expect(isProcessBackgrounded(toolCallId2)).toBe(true); + }); + + describe("foreground process functions", () => { + test("should mark a process as running", () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(); + const mockCallback = jest.fn(); + const initialOutput = "initial output"; + + markProcessAsRunning( + toolCallId, + mockProcess, + mockCallback, + initialOutput, + ); + + expect(isProcessRunning(toolCallId)).toBe(true); + expect(getRunningProcess(toolCallId)).toBe(mockProcess); + }); + + test("should handle process without callback or initial output", () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(); + + markProcessAsRunning(toolCallId, mockProcess); + + expect(isProcessRunning(toolCallId)).toBe(true); + expect(getRunningProcess(toolCallId)).toBe(mockProcess); + }); + + test("should correctly identify non-running processes", () => { + const toolCallId = "test-123"; + const anotherToolCallId = "test-456"; + const mockProcess = createMockProcess(); + + markProcessAsRunning(toolCallId, mockProcess); + + expect(isProcessRunning(toolCallId)).toBe(true); + expect(isProcessRunning(anotherToolCallId)).toBe(false); + }); + + test("should update process output", () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(); + const initialOutput = "initial"; + const updatedOutput = "updated output"; + + markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput); + updateProcessOutput(toolCallId, updatedOutput); + + // We can't directly test the output value, but we can ensure the function doesn't throw + expect(() => + updateProcessOutput(toolCallId, updatedOutput), + ).not.toThrow(); + }); + + test("should handle updating output for non-existent process", () => { + const toolCallId = "non-existent"; + + expect(() => + updateProcessOutput(toolCallId, "some output"), + ).not.toThrow(); + }); + + test("should remove a process from running state", () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(); + + markProcessAsRunning(toolCallId, mockProcess); + expect(isProcessRunning(toolCallId)).toBe(true); + + removeRunningProcess(toolCallId); + expect(isProcessRunning(toolCallId)).toBe(false); + expect(getRunningProcess(toolCallId)).toBeUndefined(); + }); + + test("should handle removing non-existent running processes", () => { + const toolCallId = "test-123"; + + expect(() => removeRunningProcess(toolCallId)).not.toThrow(); + expect(isProcessRunning(toolCallId)).toBe(false); + }); + + test("should return undefined for non-existent running process", () => { + const toolCallId = "non-existent"; + + expect(getRunningProcess(toolCallId)).toBeUndefined(); + }); + }); + + describe("terminal command cancellation", () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + test("should cancel a running terminal command", async () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(); + + markProcessAsRunning(toolCallId, mockProcess); + expect(isProcessRunning(toolCallId)).toBe(true); + + await killTerminalProcess(toolCallId); + + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); + expect(isProcessRunning(toolCallId)).toBe(false); + }); + + test("should handle cancelling non-existent process", async () => { + const toolCallId = "non-existent"; + + await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow(); + }); + + test("should handle cancelling already killed process", async () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(123, true); // Already killed + + markProcessAsRunning(toolCallId, mockProcess); + + await killTerminalProcess(toolCallId); + + expect(mockProcess.kill).not.toHaveBeenCalled(); + }); + + test("should send SIGKILL after timeout if process not killed", async () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(); + + // Mock kill to not actually set killed=true for SIGTERM + mockProcess.kill.mockImplementation((signal) => { + if (signal === "SIGKILL") { + (mockProcess as any).killed = true; + } + return true; + }); + + markProcessAsRunning(toolCallId, mockProcess); + + const cancelPromise = killTerminalProcess(toolCallId); + + // Fast-forward time to trigger the timeout + jest.advanceTimersByTime(5000); + + await cancelPromise; + + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); + expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL"); + }); + + test("should not send SIGKILL if process was already killed", async () => { + const toolCallId = "test-123"; + const mockProcess = createMockProcess(); + + markProcessAsRunning(toolCallId, mockProcess); + + const cancelPromise = killTerminalProcess(toolCallId); + + // Fast-forward time to trigger the timeout + jest.advanceTimersByTime(5000); + + await cancelPromise; + + expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); + expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL + }); + }); + + describe("utility functions", () => { + test("should get all running process IDs", () => { + const toolCallId1 = "test-123"; + const toolCallId2 = "test-456"; + const mockProcess1 = createMockProcess(123); + const mockProcess2 = createMockProcess(456); + + markProcessAsRunning(toolCallId1, mockProcess1); + markProcessAsRunning(toolCallId2, mockProcess2); + + const runningIds = getAllRunningProcessIds(); + expect(runningIds).toContain(toolCallId1); + expect(runningIds).toContain(toolCallId2); + expect(runningIds).toHaveLength(2); + }); + + test("should get all backgrounded process IDs", () => { + const toolCallId1 = "test-123"; + const toolCallId2 = "test-456"; + + markProcessAsBackgrounded(toolCallId1); + markProcessAsBackgrounded(toolCallId2); + + const backgroundedIds = getAllBackgroundedProcessIds(); + expect(backgroundedIds).toContain(toolCallId1); + expect(backgroundedIds).toContain(toolCallId2); + expect(backgroundedIds).toHaveLength(2); + }); + + test("should return empty arrays when no processes", () => { + expect(getAllRunningProcessIds()).toEqual([]); + expect(getAllBackgroundedProcessIds()).toEqual([]); + }); + + test("should cancel multiple terminal commands", async () => { + const toolCallId1 = "test-123"; + const toolCallId2 = "test-456"; + const mockProcess1 = createMockProcess(123); + const mockProcess2 = createMockProcess(456); + + markProcessAsRunning(toolCallId1, mockProcess1); + markProcessAsRunning(toolCallId2, mockProcess2); + + await killMultipleTerminalProcesses([toolCallId1, toolCallId2]); + + expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM"); + expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM"); + expect(isProcessRunning(toolCallId1)).toBe(false); + expect(isProcessRunning(toolCallId2)).toBe(false); + }); + + test("should cancel all running terminal commands", async () => { + const toolCallId1 = "test-123"; + const toolCallId2 = "test-456"; + const mockProcess1 = createMockProcess(123); + const mockProcess2 = createMockProcess(456); + + markProcessAsRunning(toolCallId1, mockProcess1); + markProcessAsRunning(toolCallId2, mockProcess2); + + const cancelledIds = await killAllRunningTerminalProcesses(); + + expect(cancelledIds).toContain(toolCallId1); + expect(cancelledIds).toContain(toolCallId2); + expect(cancelledIds).toHaveLength(2); + expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM"); + expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM"); + expect(isProcessRunning(toolCallId1)).toBe(false); + expect(isProcessRunning(toolCallId2)).toBe(false); + }); + + test("should return empty array when no running commands to cancel", async () => { + const cancelledIds = await killAllRunningTerminalProcesses(); + expect(cancelledIds).toEqual([]); + }); + + test("should clear all background processes", () => { + const toolCallId1 = "test-123"; + const toolCallId2 = "test-456"; + + markProcessAsBackgrounded(toolCallId1); + markProcessAsBackgrounded(toolCallId2); + + expect(getAllBackgroundedProcessIds()).toHaveLength(2); + + clearAllBackgroundProcesses(); + + expect(getAllBackgroundedProcessIds()).toEqual([]); + expect(isProcessBackgrounded(toolCallId1)).toBe(false); + expect(isProcessBackgrounded(toolCallId2)).toBe(false); + }); + }); +}); diff --git a/core/util/processTerminalStates.ts b/core/util/processTerminalStates.ts new file mode 100644 index 000000000..cad243a82 --- /dev/null +++ b/core/util/processTerminalStates.ts @@ -0,0 +1,119 @@ +import { ChildProcess } from "child_process"; + +// Track which processes have been backgrounded +const processTerminalBackgroundStates = new Map(); + +// Track which foreground processes are currently running +interface RunningProcessInfo { + process: ChildProcess; + onPartialOutput?: (params: { + toolCallId: string; + contextItems: any[]; + }) => void; + currentOutput: string; +} + +const processTerminalForegroundStates = new Map(); + +// Background process functions (existing) +export function markProcessAsBackgrounded(toolCallId: string): void { + processTerminalBackgroundStates.set(toolCallId, true); +} + +export function isProcessBackgrounded(toolCallId: string): boolean { + return processTerminalBackgroundStates.has(toolCallId); +} + +export function removeBackgroundedProcess(toolCallId: string): void { + processTerminalBackgroundStates.delete(toolCallId); +} + +// Foreground process functions (new) +export function markProcessAsRunning( + toolCallId: string, + process: ChildProcess, + onPartialOutput?: (params: { + toolCallId: string; + contextItems: any[]; + }) => void, + currentOutput: string = "", +): void { + processTerminalForegroundStates.set(toolCallId, { + process, + onPartialOutput, + currentOutput, + }); +} + +export function isProcessRunning(toolCallId: string): boolean { + return processTerminalForegroundStates.has(toolCallId); +} + +export function getRunningProcess( + toolCallId: string, +): ChildProcess | undefined { + const info = processTerminalForegroundStates.get(toolCallId); + return info?.process; +} + +export function updateProcessOutput(toolCallId: string, output: string): void { + const info = processTerminalForegroundStates.get(toolCallId); + if (info) { + info.currentOutput = output; + } +} + +export function removeRunningProcess(toolCallId: string): void { + processTerminalForegroundStates.delete(toolCallId); +} + +export async function killTerminalProcess(toolCallId: string): Promise { + const processInfo = processTerminalForegroundStates.get(toolCallId); + if (processInfo && !processInfo.process.killed) { + const { process } = processInfo; + + process.kill("SIGTERM"); + + // Force kill after 5 seconds if still running + setTimeout(() => { + if (!process.killed) { + process.kill("SIGKILL"); + } + }, 5000); + + processTerminalForegroundStates.delete(toolCallId); + } +} + +// Function to cancel multiple terminal commands at once +export async function killMultipleTerminalProcesses( + toolCallIds: string[], +): Promise { + const cancelPromises = toolCallIds.map((toolCallId) => + killTerminalProcess(toolCallId), + ); + await Promise.all(cancelPromises); +} + +// Function to cancel ALL currently running terminal commands +export async function killAllRunningTerminalProcesses(): Promise { + const runningIds = getAllRunningProcessIds(); + if (runningIds.length > 0) { + await killMultipleTerminalProcesses(runningIds); + } + return runningIds; // Return the IDs that were cancelled +} + +// Utility functions +export function getAllRunningProcessIds(): string[] { + return Array.from(processTerminalForegroundStates.keys()); +} + +export function getAllBackgroundedProcessIds(): string[] { + return Array.from(processTerminalBackgroundStates.keys()); +} + +// Utility function for testing - clears all background process states +export function clearAllBackgroundProcesses(): void { + processTerminalBackgroundStates.clear(); +} diff --git a/docs/docs.json b/docs/docs.json index e57798880..d6469ae2f 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -233,6 +233,7 @@ "guides/codebase-documentation-awareness", "guides/cli", "guides/continuous-ai", + "guides/continuous-ai-readiness-assessment", "guides/plan-mode-guide", "guides/ollama-guide", "guides/instinct", diff --git a/docs/guides/codebase-documentation-awareness.mdx b/docs/guides/codebase-documentation-awareness.mdx index a79805a34..d061bce98 100644 --- a/docs/guides/codebase-documentation-awareness.mdx +++ b/docs/guides/codebase-documentation-awareness.mdx @@ -1,11 +1,10 @@ --- -title: How to make your agent aware of codebases and documentation +title: How to Make Your Agent Aware of Codebases and Documentation description: Learn how to give your AI agent access to codebases and documentation for more context-aware assistance keywords: [agent, codebase, documentation, MCP, context, RAG, tools] +sidebarTitle: Codebase and Documentation Awareness --- -# How to make your agent aware of codebases and documentation - AI coding agents work best when they understand the context of your project. This guide shows you how to give your agent access to codebases and documentation, making it more helpful and accurate. ## Make your agent aware of your open codebase @@ -28,18 +27,21 @@ Rules guide your agent's behavior and understanding. Place markdown files in `.c # Project Architecture This is a React application with: + - Components in `/src/components` - API routes in `/src/api` - State management using Redux in `/src/store` ## Coding Standards + - Use TypeScript for all new files - Follow the existing naming conventions - Write tests for all new features ``` - Place rules files at different levels of your project hierarchy to scope when they trigger + Place rules files at different levels of your project hierarchy to scope when + they trigger Learn more about [rules configuration](/customize/deep-dives/rules). @@ -60,6 +62,7 @@ Create rules that point to external codebases: # External Dependencies Our authentication system is based on: + - [Auth.js documentation](https://authjs.dev/) - [Example implementation](https://github.com/nextauthjs/next-auth-example) @@ -76,6 +79,7 @@ Add rules to guide CLI usage: # Repository Access You can use the `gh` CLI to: + - Search for issues: `gh issue list --repo owner/repo` - View pull requests: `gh pr list --repo owner/repo` - Clone repositories: `gh repo clone owner/repo` @@ -86,6 +90,7 @@ You can use the `gh` CLI to: [DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository. Once configured, your agent can explore repositories like: + - "Explore the React repository structure" - "Find how authentication is implemented in NextAuth.js" @@ -115,6 +120,7 @@ Guide your agent to relevant documentation: # Documentation Resources For framework-specific questions, refer to: + - React: https://react.dev/reference/react - Next.js: https://nextjs.org/docs - Tailwind CSS: https://tailwindcss.com/docs @@ -127,6 +133,7 @@ Always cite documentation when explaining concepts. [Context7 MCP](https://hub.continue.dev/upstash/context7-mcp) enables your agent to search and retrieve information from public documentation: Your agent can then answer questions like: + - "How do I use React hooks?" - "What's the syntax for Tailwind CSS animations?" @@ -142,6 +149,7 @@ Create rules that reference internal resources: # Internal Documentation Our team documentation is available at: + - API Documentation: https://internal.docs/api - Architecture Guide: https://internal.docs/architecture - Deployment Process: https://internal.docs/deployment diff --git a/docs/guides/continuous-ai-readiness-assessment.mdx b/docs/guides/continuous-ai-readiness-assessment.mdx new file mode 100644 index 000000000..f72e5dd85 --- /dev/null +++ b/docs/guides/continuous-ai-readiness-assessment.mdx @@ -0,0 +1,309 @@ +--- +title: Assessing Your Team's Readiness for Continuous AI +description: Complete framework to evaluate team readiness for Continuous AI adoption with maturity levels, assessment criteria, and implementation roadmap. +sidebarTitle: Continuous AI Readiness Assessment +--- + + + **TL;DR:** Use this assessment framework to determine if your team is ready to + move from individual AI tool usage to automated Continuous AI workflows. + Covers technical infrastructure, processes, culture, and organizational + support. + + +## Assessing Continuous AI Readiness + +Continuous AI can dramatically improve development velocity and code quality, but successful implementation requires careful evaluation across four key dimensions. + + + Rushing into Continuous AI without proper foundations leads to frustration and + failed initiatives. Use this framework to identify gaps before scaling. + + +### 1. Identify Your Current Maturity Level + +Determine where your team falls on the Continuous AI maturity spectrum: + + + + Developers use AI tools inconsistently with highly variable results. + + **Characteristics:** + - High rejection rates of AI-generated code (>50%) + - No shared standards or prompting rules + - AI tools lack context about your codebase + - Ad-hoc usage without team coordination + + + + + AI is systematically integrated into team workflows and CI/CD pipelines. + +**Characteristics:** + +- Consistent adoption across 80%+ of team members +- AI integrated into code reviews and deployment processes +- Documented standards for prompts and tool usage +- Basic metrics tracking AI impact + + + + + Certain development processes run autonomously with minimal human oversight. + + **Characteristics:** + - Human intervention rates below 15% + - Robust monitoring and automated rollback systems + - Measurable ROI from automation initiatives + - Advanced context awareness and learning loops + + + + +### 2. Evaluate Readiness Across Four Key Dimensions + +Assess your team's strengths and potential risks across these critical areas: + + + + **Key Questions:** + - Do our development tools integrate reliably? + - Can we measure AI effectiveness and impact? + - Are security policies compatible with AI workflows? + + **🟢 Green Flags:** + - Stable tool integrations with >99.5% uptime + - Comprehensive monitoring and observability + - Security policies that support AI tool usage + - Automated testing and deployment pipelines + + **🔴 Red Flags:** + - Frequent integration breakdowns + - No performance tracking or metrics + - Restrictive security policies blocking AI tools + - Manual deployment processes + + + + + **Key Questions:** + - Are our development workflows consistent and documented? + - Do we have quality gates and review processes? + - Can we reproduce builds and deployments reliably? + + **🟢 Green Flags:** + - Clear coding standards and style guides + - Automated CI/CD with quality gates + - Documented, repeatable processes + - Consistent code review practices + + **🔴 Red Flags:** + - Inconsistent code reviews + - Ad-hoc deployment processes + - "Works on my machine" culture + - Undocumented tribal knowledge + + + + + **Key Questions:** + - Are developers open to adopting new AI-powered workflows? + - How does the team handle experimentation and failure? + - Do team members collaborate effectively on new initiatives? + + **🟢 Green Flags:** + - High curiosity and willingness to experiment + - Collaborative problem-solving culture + - Constructive feedback and learning mindset + - Active knowledge sharing practices + +**🔴 Red Flags:** + +- Strong resistance to workflow changes +- Blame culture around mistakes +- Perfectionism blocking experimentation +- Siloed work with minimal collaboration + + + + + **Key Questions:** + - Does leadership provide budget and resources for AI initiatives? + - Is there tolerance for experimentation and learning? + - Are expectations realistic for ROI timelines? + + **🟢 Green Flags:** + - Executive buy-in and strategic alignment + - Dedicated budget for training and tools + - 3-6 month ROI expectations + - Support for calculated risk-taking + + **🔴 Red Flags:** + - Pressure for immediate ROI (weeks) + - No allocated budget for AI initiatives + - High risk aversion culture + - Lack of leadership engagement + + + + +### 3. Critical Warning Signs + + + **Stop and address these issues before scaling Continuous AI:** + + + + + - Builds breaking regularly (>5% failure rate) + - Unstable deployments or rollback frequency >10% + - No monitoring or observability systems + - Critical security policy conflicts + + + + + - More than 30% of team opposed to AI tools + - No established feedback or learning culture + - History of failed automation initiatives + - Resistance to changing existing workflows + + + + + - Inconsistent development workflows + - No quality gates or review processes + - Manual deployment and testing processes + - Lack of documentation and standards + + + + + - Leadership expecting ROI in weeks vs months + - No allocated budget for AI initiatives + - High pressure, low experimentation tolerance + - Lack of strategic alignment on AI adoption + + + + +### 4. Implementation Roadmap + +Based on your assessment results, follow this step-by-step approach: + + + + Document current performance across key areas: + + - Development velocity (story + points, cycle time) + - Code quality metrics (bug rates, technical debt) + - Review times and approval rates + - Developer satisfaction and productivity + scores + + + + + Choose one high-impact, low-risk workflow to automate first: + + - **Code Review:** Automated analysis and suggestions + - **Documentation:** Auto-generated API docs and README updates + - **Testing:** Automated test generation and maintenance + - **Refactoring:** Systematic code improvement suggestions + + + + + Create and document consistent practices: + - AI tool selection and configuration guidelines + + - Prompting standards and best practices + + - Quality gates and review processes + + - Security and compliance requirements + + + + + Run controlled experiments with success criteria: + - Start with 2-3 team members for 2-4 weeks + - Track metrics against baseline performance + - Gather qualitative feedback on developer experience + - Document lessons learned and optimization opportunities + + + + + Expand successful pilots across the organization: + - Roll out to additional team members gradually + - Implement monitoring and alerting systems + - Establish feedback loops for continuous improvement + - Plan next automation targets based on results + + + + + + + Comprehensive explanation of maturity levels and organizational readiness + factors + + + + Technical implementation details and best practices for Continuous AI + workflows + + + +## Quick Assessment Checklist + + + **Ready to get started?** Use this quick checklist to gauge your immediate + readiness: + + +**Technical Foundation (Score: \_\_\_/4)** + +- Stable CI/CD pipelines with \<5% failure rate +- Monitoring and observability systems in place +- Security policies support AI tool integration +- Development environment standardization + +**Process Maturity (Score: \_\_\_/4)** + +- Documented coding standards and review processes +- Consistent deployment and rollback procedures +- Quality gates and automated testing +- Regular retrospectives and process improvement + +**Team Culture (Score: \_\_\_/4)** + +- \<30% resistance to AI tool adoption +- Active experimentation and learning culture +- Collaborative problem-solving approach +- Constructive feedback and knowledge sharing + +**Organizational Support (Score: \_\_\_/4)** + +- Leadership buy-in and strategic alignment +- Dedicated budget for AI initiatives and training +- 3-6 month ROI expectations (not weeks) +- Support for calculated risk-taking + +--- + +**Overall Readiness Score: \_\_\_/16** + +- **12-16:** Ready to begin Continuous AI implementation +- **8-11:** Address gaps in 1-2 areas before scaling +- **\<8:** Focus on foundational improvements first diff --git a/docs/guides/overview.mdx b/docs/guides/overview.mdx index 3a609ac15..19b639758 100644 --- a/docs/guides/overview.mdx +++ b/docs/guides/overview.mdx @@ -13,6 +13,7 @@ description: "Comprehensive collection of practical guides for Continue includin - [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows - [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue +- [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption ## What Advanced Tutorials Are Available diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 8513b1405..2205e7976 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -28,6 +28,7 @@ export interface CompactionCallbacks { * @param model The model configuration * @param llmApi The LLM API instance * @param callbacks Optional callbacks for streaming updates + * @param abortController Optional abort controller for cancellation * @returns The compacted history with compaction index */ export async function compactChatHistory( @@ -35,6 +36,7 @@ export async function compactChatHistory( model: ModelConfig, llmApi: BaseLlmApi, callbacks?: CompactionCallbacks, + abortController?: AbortController, ): Promise { // Create a prompt to summarize the conversation const compactionPrompt: ChatHistoryItem = { @@ -81,7 +83,7 @@ export async function compactChatHistory( } // Stream the compaction response (service drives updates; this collects content locally) - const controller = new AbortController(); + const controller = abortController || new AbortController(); let compactionContent = ""; const streamCallbacks: StreamCallbacks = { diff --git a/extensions/cli/src/stream/messageQueue.test.ts b/extensions/cli/src/stream/messageQueue.test.ts new file mode 100644 index 000000000..8646258aa --- /dev/null +++ b/extensions/cli/src/stream/messageQueue.test.ts @@ -0,0 +1,62 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + setLevel: vi.fn(), + configureHeadlessMode: vi.fn(), + getLogPath: vi.fn(), + getSessionId: vi.fn(), + }, +})); + +import { messageQueue } from "./messageQueue.js"; + +describe("messageQueue", () => { + beforeEach(() => { + // Drain any leftover items from previous tests + while (messageQueue.getAllQueuedMessages()) {} + }); + + it("enqueues and emits messageQueued", async () => { + const event = new Promise((resolve) => + messageQueue.once("messageQueued", resolve), + ); + + const ok = await messageQueue.enqueueMessage("hello world"); + expect(ok).toBe(true); + expect(messageQueue.getQueueLength()).toBe(1); + + const queued = await event; + expect(queued.message).toBe("hello world"); + }); + + it("combines messages, merges image maps, writes history, and clears queue", async () => { + const bufA = Buffer.from("A"); + const bufB = Buffer.from("B"); + + const img1 = new Map([["a", bufA]]); + const img2 = new Map([["b", bufB]]); + + const history = { addEntry: vi.fn() } as any; + + await messageQueue.enqueueMessage("one", img1); + await messageQueue.enqueueMessage("two", img2, history); + + const combined = messageQueue.getAllQueuedMessages(); + expect(combined).toBeTruthy(); + expect(combined!.message).toBe("one\ntwo"); + expect(combined!.imageMap).toBeDefined(); + expect(combined!.imageMap!.get("a")).toEqual(bufA); + expect(combined!.imageMap!.get("b")).toEqual(bufB); + + // queue should be cleared + expect(messageQueue.getQueueLength()).toBe(0); + + // input history should receive the combined message + expect(history.addEntry).toHaveBeenCalledWith("one\ntwo"); + }); +}); diff --git a/extensions/cli/src/stream/messageQueue.ts b/extensions/cli/src/stream/messageQueue.ts new file mode 100644 index 000000000..3703a4644 --- /dev/null +++ b/extensions/cli/src/stream/messageQueue.ts @@ -0,0 +1,94 @@ +import { EventEmitter } from "events"; + +import { InputHistory } from "../util/inputHistory.js"; +import { logger } from "../util/logger.js"; + +export interface QueuedMessage { + message: string; + imageMap?: Map; + timestamp: number; +} + +export interface MessageProcessor { + (message: string, imageMap?: Map): Promise; +} + +/** + * A queue to store messages that need to be processed later + */ +class MessageQueue extends EventEmitter { + private queue: QueuedMessage[] = []; + private inputHistory: InputHistory | undefined; + + constructor() { + super(); + } + + async enqueueMessage( + message: string, + imageMap?: Map, + inputHistory?: InputHistory, + ): Promise { + this.inputHistory = inputHistory; + + const queuedMessage: QueuedMessage = { + message, + imageMap, + timestamp: Date.now(), + }; + + this.queue.push(queuedMessage); + logger.debug("MessageQueue: Message queued", { + queueLength: this.queue.length, + }); + + // Emit event for UI to show the queued message + this.emit("messageQueued", queuedMessage); + + return true; + } + + public getAllQueuedMessages() { + if (this.queue.length === 0) return undefined; + + // Combine all queued messages into one + const combinedMessage = this.queue.map((msg) => msg.message).join("\n"); + const combinedImageMap = new Map(); + + // Merge all image maps + for (const queuedMsg of this.queue) { + if (queuedMsg.imageMap) { + for (const [key, value] of queuedMsg.imageMap) { + combinedImageMap.set(key, value); + } + } + } + + const result = { + message: combinedMessage, + imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined, + timestamp: Date.now(), + }; + + // Add to input history and clear the queue + this.inputHistory?.addEntry(combinedMessage); + this.queue = []; + + logger.debug("MessageQueue: All messages dequeued and combined", { + combinedLength: combinedMessage.length, + queueLength: this.queue.length, + }); + + return result; + } + + public getLatestMessage() { + return this.getAllQueuedMessages(); + } + + getQueueLength(): number { + return this.queue.length; + } +} + +export const messageQueue = new MessageQueue(); diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts index 5960a952a..528e28be2 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts @@ -147,7 +147,7 @@ describe("handleAutoCompaction", () => { "Auto-compacting...", ); expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( - "✓ Chat history auto-compacted successfully.", + "Chat history auto-compacted successfully.", ); expect(result).toEqual({ diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts index 4e55a2cd5..797cfba2b 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts @@ -55,7 +55,7 @@ function handleCompactionSuccess( ) { if (isHeadless) return; - const successMessage = "✓ Chat history auto-compacted successfully."; + const successMessage = "Chat history auto-compacted successfully."; if (callbacks?.onSystemMessage) { callbacks.onSystemMessage(successMessage); diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index a60ec85b4..4efede92b 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -1,4 +1,4 @@ -import { Box, Text } from "ink"; +import { Box } from "ink"; import React, { useCallback, useEffect, @@ -17,6 +17,7 @@ import { } from "../services/types.js"; import { logger } from "../util/logger.js"; +import { ActionStatus } from "./components/ActionStatus.js"; import { BottomStatusBar } from "./components/BottomStatusBar.js"; import { ResourceDebugBar } from "./components/ResourceDebugBar.js"; import { ScreenContent } from "./components/ScreenContent.js"; @@ -31,8 +32,6 @@ import { useLoginHandlers, useSelectors, } from "./hooks/useTUIChatHooks.js"; -import { LoadingAnimation } from "./LoadingAnimation.js"; -import { Timer } from "./Timer.js"; interface TUIChatProps { // Remote mode props @@ -185,9 +184,12 @@ const TUIChat: React.FC = ({ setChatHistory, isWaitingForResponse, responseStartTime, + isCompacting, + compactionStartTime, inputMode, activePermissionRequest, wasInterrupted, + queuedMessages, handleUserMessage, handleInterrupt, handleFileAttached, @@ -282,6 +284,7 @@ const TUIChat: React.FC = ({ model={services.model?.model || undefined} mcpService={services.mcp?.mcpService || undefined} chatHistory={chatHistory} + queuedMessages={queuedMessages} renderMessage={renderMessage} refreshTrigger={staticRefreshTrigger} /> @@ -290,18 +293,21 @@ const TUIChat: React.FC = ({ {/* Fixed bottom section */} {/* Status */} - {isWaitingForResponse && responseStartTime && ( - - - - ( - - - - • esc to interrupt ) - - - )} + + + {/* Compaction Status */} + {/* All screen-specific content */} = ({ handleToolPermissionResponse={handleToolPermissionResponse} handleUserMessage={handleUserMessage} isWaitingForResponse={isWaitingForResponse} + isCompacting={isCompacting} inputMode={inputMode} handleInterrupt={handleInterrupt} handleFileAttached={handleFileAttached} diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 4b5deb5bc..199e18fb2 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -9,6 +9,7 @@ import type { PermissionMode } from "../permissions/types.js"; import type { FileIndexServiceState } from "../services/FileIndexService.js"; import { SERVICE_NAMES, serviceContainer } from "../services/index.js"; import { modeService } from "../services/ModeService.js"; +import { messageQueue } from "../stream/messageQueue.js"; import { InputHistory } from "../util/inputHistory.js"; import { FileSearchUI } from "./FileSearchUI.js"; @@ -94,6 +95,7 @@ const FileSearchMaybe: React.FC<{ interface UserInputProps { onSubmit: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; + isCompacting?: boolean; inputMode: boolean; onInterrupt?: () => void; assistant?: AssistantConfig; @@ -109,6 +111,7 @@ interface UserInputProps { const UserInput: React.FC = ({ onSubmit, isWaitingForResponse, + isCompacting = false, inputMode, onInterrupt, assistant, @@ -515,7 +518,7 @@ const UserInput: React.FC = ({ } // Normal Enter behavior - submit if there's content - if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) { + if (textBuffer.text.trim() || wasInterrupted) { // Get images before expanding paste blocks const imageMap = textBuffer.getAllImages(); @@ -523,14 +526,19 @@ const UserInput: React.FC = ({ textBuffer.expandAllPasteBlocks(); const submittedText = textBuffer.text.trim(); - // Only add to history if there's actual text (not when resuming) - if (submittedText) { + if (isWaitingForResponse || isCompacting) { + // Process message later when LLM has responded or compaction is complete + void messageQueue.enqueueMessage( + submittedText, + imageMap, + inputHistory, + ); + } else { + // Submit with images inputHistory.addEntry(submittedText); + onSubmit(submittedText, imageMap); } - // Submit with images - onSubmit(submittedText, imageMap); - textBuffer.clear(); setInputText(""); setCursorPosition(0); @@ -570,6 +578,12 @@ const UserInput: React.FC = ({ return true; } + // Handle escape key to interrupt compaction (higher priority) + if (isCompacting && onInterrupt) { + onInterrupt(); + return true; + } + // Handle escape key to interrupt streaming if (isWaitingForResponse && onInterrupt) { onInterrupt(); @@ -647,15 +661,6 @@ const UserInput: React.FC = ({ return; } - // Allow typing during streaming, but block submission - if (!inputMode) { - // Block only Enter key submission during streaming - if (key.return && !key.shift) { - return; - } - // Allow all other input (typing, navigation, etc.) - } - // Handle slash command navigation if (showSlashCommands) { if (handleSlashCommandNavigation(key)) { diff --git a/extensions/cli/src/ui/__tests__/TUIChat.actionStatus.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.actionStatus.test.tsx new file mode 100644 index 000000000..59152b7e0 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/TUIChat.actionStatus.test.tsx @@ -0,0 +1,214 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createUITestContext } from "../../test-helpers/ui-test-context.js"; +import { AppRoot } from "../AppRoot.js"; + +// Mock the useChat hook to control state +const mockUseChat = vi.fn(); + +vi.mock("../hooks/useChat.js", () => ({ + useChat: () => mockUseChat(), +})); + +describe("TUIChat - ActionStatus", () => { + let context: any; + + beforeEach(() => { + context = createUITestContext({ + allServicesReady: true, + serviceState: "ready", + }); + + // Default mock return value + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: false, + responseStartTime: null, + isCompacting: false, + compactionStartTime: null, + inputMode: true, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: vi.fn(), + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + }); + + afterEach(() => { + context.cleanup(); + vi.clearAllMocks(); + }); + + it("shows only response status when waiting for response", () => { + const responseStartTime = Date.now(); + + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: true, + responseStartTime, + isCompacting: false, + compactionStartTime: null, + inputMode: false, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: vi.fn(), + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + const { lastFrame, unmount } = render(React.createElement(AppRoot, {})); + + try { + const frame = lastFrame(); + expect(frame).toBeDefined(); + + // Should show spinner/response indicator but not compaction message + expect(frame).toContain("esc to interrupt"); + expect(frame).not.toContain("Compacting history"); + } finally { + unmount(); + } + }); + + it("shows only compaction status when compacting", () => { + const compactionStartTime = Date.now(); + + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: false, + responseStartTime: null, + isCompacting: true, + compactionStartTime, + inputMode: true, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: vi.fn(), + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + const { lastFrame, unmount } = render(React.createElement(AppRoot, {})); + + try { + const frame = lastFrame(); + expect(frame).toBeDefined(); + + // Should show compaction message but not spinner + expect(frame).toContain("Compacting history"); + expect(frame).toContain("esc to interrupt"); + } finally { + unmount(); + } + }); + + it("shows neither status when both states are false", () => { + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: false, + responseStartTime: null, + isCompacting: false, + compactionStartTime: null, + inputMode: true, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: vi.fn(), + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + const { lastFrame, unmount } = render(React.createElement(AppRoot, {})); + + try { + const frame = lastFrame(); + expect(frame).toBeDefined(); + + // Should not show any status messages + expect(frame).not.toContain("Compacting history"); + // The basic UI should still be there + expect(frame).toContain("Ask anything"); + } finally { + unmount(); + } + }); + + it("handles state transitions correctly", () => { + const { lastFrame, rerender, unmount } = render( + React.createElement(AppRoot, {}), + ); + + // Start with compaction + const compactionStartTime = Date.now(); + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: false, + responseStartTime: null, + isCompacting: true, + compactionStartTime, + inputMode: true, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: vi.fn(), + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + try { + rerender(React.createElement(AppRoot, {})); + + let frame = lastFrame(); + expect(frame).toContain("Compacting history"); + expect(frame).not.toContain("⠀⠁⠃⠇⠏⠟⠿⣿"); // No spinner chars when only compacting + + // Transition to response waiting + const responseStartTime = Date.now(); + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: true, + responseStartTime, + isCompacting: false, + compactionStartTime: null, + inputMode: false, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: vi.fn(), + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + rerender(React.createElement(AppRoot, {})); + + frame = lastFrame(); + expect(frame).not.toContain("Compacting history"); + expect(frame).toContain("esc to interrupt"); + } finally { + unmount(); + } + }); +}); diff --git a/extensions/cli/src/ui/__tests__/TUIChat.compactionCancellation.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.compactionCancellation.test.tsx new file mode 100644 index 000000000..81d0843da --- /dev/null +++ b/extensions/cli/src/ui/__tests__/TUIChat.compactionCancellation.test.tsx @@ -0,0 +1,141 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createUITestContext } from "../../test-helpers/ui-test-context.js"; +import { AppRoot } from "../AppRoot.js"; + +// Mock the useChat hook to control state +const mockUseChat = vi.fn(); +const mockHandleInterrupt = vi.fn(); + +vi.mock("../hooks/useChat.js", () => ({ + useChat: () => mockUseChat(), +})); + +describe("TUIChat - Compaction Cancellation", () => { + let context: any; + + beforeEach(() => { + context = createUITestContext({ + allServicesReady: true, + serviceState: "ready", + }); + + // Reset the mock + mockHandleInterrupt.mockClear(); + }); + + afterEach(() => { + context.cleanup(); + vi.clearAllMocks(); + }); + + it("calls handleInterrupt when ESC is pressed during compaction", () => { + const compactionStartTime = Date.now(); + + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: false, + responseStartTime: null, + isCompacting: true, + compactionStartTime, + inputMode: true, // Changed to true so ESC handling is active + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: mockHandleInterrupt, + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + const { stdin, unmount } = render(React.createElement(AppRoot, {})); + + try { + // Give some time for the component to render and set up input handling + setTimeout(() => { + // Simulate ESC key press during compaction + stdin.write("\x1b"); // ESC key + + // The handleInterrupt should be called + expect(mockHandleInterrupt).toHaveBeenCalledTimes(1); + }, 100); + } finally { + unmount(); + } + }); + + it("shows compaction status with esc to interrupt message", () => { + const compactionStartTime = Date.now(); + + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: false, + responseStartTime: null, + isCompacting: true, + compactionStartTime, + inputMode: false, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: mockHandleInterrupt, + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + const { lastFrame, unmount } = render(React.createElement(AppRoot, {})); + + try { + const frame = lastFrame(); + expect(frame).toBeDefined(); + + // Should show compaction message with interrupt option + expect(frame).toContain("Compacting history"); + expect(frame).toContain("esc to interrupt"); + } finally { + unmount(); + } + }); + + it("prioritizes compaction cancellation over response cancellation", () => { + // This tests the case where both might be true (theoretical edge case) + const compactionStartTime = Date.now(); + const responseStartTime = Date.now(); + + mockUseChat.mockReturnValue({ + chatHistory: [], + setChatHistory: vi.fn(), + isWaitingForResponse: true, + responseStartTime, + isCompacting: true, + compactionStartTime, + inputMode: false, + attachedFiles: [], + activePermissionRequest: null, + wasInterrupted: false, + handleUserMessage: vi.fn(), + handleInterrupt: mockHandleInterrupt, + handleFileAttached: vi.fn(), + resetChatHistory: vi.fn(), + handleToolPermissionResponse: vi.fn(), + }); + + const { stdin, unmount } = render(React.createElement(AppRoot, {})); + + try { + // Simulate ESC key press when both states are active + stdin.write("\x1b"); // ESC key + + // Should still call handleInterrupt (which will prioritize compaction) + expect(mockHandleInterrupt).toHaveBeenCalledTimes(1); + } finally { + unmount(); + } + }); +}); diff --git a/extensions/cli/src/ui/components/ActionStatus.tsx b/extensions/cli/src/ui/components/ActionStatus.tsx new file mode 100644 index 000000000..ce4542cb6 --- /dev/null +++ b/extensions/cli/src/ui/components/ActionStatus.tsx @@ -0,0 +1,37 @@ +import { Box, Text } from "ink"; +import React from "react"; + +import { LoadingAnimation } from "../LoadingAnimation.js"; +import { Timer } from "../Timer.js"; + +interface ActionStatusProps { + visible: boolean; + startTime: number; + message: string; + showSpinner?: boolean; + color?: string; + loadingColor?: string; +} + +const ActionStatus: React.FC = ({ + visible, + startTime, + message, + showSpinner = false, + color = "gray", + loadingColor = "green", +}) => { + if (!visible) return null; + + return ( + + {showSpinner && } + {message} + ( + + • esc to interrupt ) + + ); +}; + +export { ActionStatus }; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 1af22c91a..0cbd602ac 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -32,6 +32,7 @@ interface ScreenContentProps { ) => void; handleUserMessage: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; + isCompacting: boolean; inputMode: boolean; handleInterrupt: () => void; handleFileAttached: (filePath: string, content: string) => void; @@ -55,6 +56,7 @@ export const ScreenContent: React.FC = ({ handleToolPermissionResponse, handleUserMessage, isWaitingForResponse, + isCompacting, inputMode, handleInterrupt, handleFileAttached, @@ -149,6 +151,7 @@ export const ScreenContent: React.FC = ({ React.ReactElement; refreshTrigger?: number; // Add a prop to trigger refresh from parent } @@ -23,6 +25,7 @@ export const StaticChatContent: React.FC = ({ model, mcpService, chatHistory, + queuedMessages = [], renderMessage, refreshTrigger, }) => { @@ -140,6 +143,15 @@ export const StaticChatContent: React.FC = ({ {item} ))} + + {/* Queued messages - show at bottom with queue indicators */} + {queuedMessages.length > 0 && ( + + + {queuedMessages.map((msg) => msg.message).join("\n")} + + + )} ); }; diff --git a/extensions/cli/src/ui/hooks/useChat.compaction.ts b/extensions/cli/src/ui/hooks/useChat.compaction.ts index 8952f7643..df0132246 100644 --- a/extensions/cli/src/ui/hooks/useChat.compaction.ts +++ b/extensions/cli/src/ui/hooks/useChat.compaction.ts @@ -14,6 +14,9 @@ interface HandleCompactCommandOptions { setCompactionIndex: React.Dispatch>; currentSession: Session; setCurrentSession: React.Dispatch>; + setIsCompacting: (value: boolean) => void; + setCompactionStartTime: (time: number | null) => void; + setCompactionAbortController: (controller: AbortController | null) => void; } /** @@ -27,22 +30,32 @@ export async function handleCompactCommand({ setCompactionIndex, currentSession, setCurrentSession, + setIsCompacting, + setCompactionStartTime, + setCompactionAbortController, }: HandleCompactCommandOptions): Promise { - // Add compacting message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Compacting chat history...", - }, - contextItems: [], - }, - ]); + // Create abort controller for cancellation support + const compactionController = new AbortController(); + setCompactionAbortController(compactionController); + + // Start compaction status display + setIsCompacting(true); + setCompactionStartTime(Date.now()); try { - // Compact the chat history directly (already in unified format) - const result = await compactChatHistory(chatHistory, model, llmApi); + // Compact the chat history directly (already in unified format) with abort controller + const result = await compactChatHistory( + chatHistory, + model, + llmApi, + undefined, + compactionController, + ); + + // Check if operation was aborted before proceeding with success actions + if (compactionController.signal.aborted) { + return; + } // Replace chat history with compacted version setChatHistory(result.compactedHistory); @@ -56,6 +69,7 @@ export async function handleCompactCommand({ updateSessionHistory(result.compactedHistory); setCurrentSession(updatedSession); + // Add success message to chat setChatHistory((prev) => [ ...prev, { @@ -67,17 +81,37 @@ export async function handleCompactCommand({ }, ]); } catch (error) { - logger.error("Compaction failed:", error); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Compaction failed: ${formatError(error)}`, + // Check if the error was due to abortion + if (compactionController.signal.aborted) { + logger.info("Manual compaction was cancelled by user"); + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: "Compaction cancelled.", + }, + contextItems: [], }, - contextItems: [], - }, - ]); + ]); + } else { + logger.error("Compaction failed:", error); + setChatHistory((prev) => [ + ...prev, + { + message: { + role: "system", + content: `Compaction failed: ${formatError(error)}`, + }, + contextItems: [], + }, + ]); + } + } finally { + // Stop compaction status display + setIsCompacting(false); + setCompactionStartTime(null); + setCompactionAbortController(null); } } @@ -88,6 +122,7 @@ interface HandleAutoCompactionOptions { compactionIndex: number | null; setChatHistory: React.Dispatch>; setCompactionIndex: React.Dispatch>; + abortController?: AbortController; } /** @@ -100,6 +135,7 @@ export async function handleAutoCompaction({ compactionIndex: _compactionIndex, setChatHistory, setCompactionIndex, + abortController, }: HandleAutoCompactionOptions): Promise<{ currentChatHistory: ChatHistoryItem[]; currentCompactionIndex: number | null; @@ -116,20 +152,14 @@ export async function handleAutoCompaction({ logger.info("Auto-compaction triggered for TUI mode"); - // Add compacting message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Auto-compacting chat history...", - }, - contextItems: [], - }, - ]); - // Compact the unified history - const result = await compactChatHistory(chatHistory, model, llmApi); + const result = await compactChatHistory( + chatHistory, + model, + llmApi, + undefined, + abortController, + ); // Keep the system message and append the compaction summary // This replaces the old messages with a summary to reduce context size @@ -151,23 +181,22 @@ export async function handleAutoCompaction({ ? [systemMessage, compactedMessage] : [compactedMessage]; - setChatHistory(updatedHistory); + // Add success message to the history that will be returned + const successMessage: ChatHistoryItem = { + message: { + role: "system", + content: "Chat history auto-compacted successfully.", + }, + contextItems: [], + }; + + const finalHistory = [...updatedHistory, successMessage]; + + setChatHistory(finalHistory); setCompactionIndex(updatedHistory.length - 1); - // Add success message - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "✓ Chat history auto-compacted successfully.", - }, - contextItems: [], - }, - ]); - return { - currentChatHistory: updatedHistory, + currentChatHistory: finalHistory, currentCompactionIndex: updatedHistory.length - 1, }; } catch (error) { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 9b9cc5871..1bb2cd10e 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -1,3 +1,5 @@ +/* eslint-disable max-lines */ +/* eslint-disable max-statements */ import type { ChatHistoryItem, Session } from "core/index.js"; import { useApp } from "ink"; import { useEffect, useRef, useState } from "react"; @@ -11,6 +13,7 @@ import { updateSessionHistory, } from "../../session.js"; import { handleSlashCommands } from "../../slashCommands.js"; +import { messageQueue, QueuedMessage } from "../../stream/messageQueue.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; import { formatError } from "../../util/formatError.js"; import { logger } from "../../util/logger.js"; @@ -138,9 +141,15 @@ export function useChat({ const [responseStartTime, setResponseStartTime] = useState( null, ); + const [isCompacting, setIsCompacting] = useState(false); + const [compactionStartTime, setCompactionStartTime] = useState( + null, + ); const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); + const [compactionAbortController, setCompactionAbortController] = + useState(null); const [isChatHistoryInitialized, setIsChatHistoryInitialized] = useState( // If we're resuming and found a saved session, we're already initialized // If we're forking and found a session to fork from, we're already initialized @@ -166,6 +175,22 @@ export function useChat({ // Track interrupted state for resume functionality const [wasInterrupted, setWasInterrupted] = useState(false); + // Track queued messages for immediate display + const [queuedMessages, setQueuedMessages] = useState([]); + + // Set up message queue listeners + useEffect(() => { + const onMessageQueued = (queuedMessage: QueuedMessage) => { + setQueuedMessages((prev) => [...prev, queuedMessage]); + }; + + messageQueue.on("messageQueued", onMessageQueued); + + return () => { + messageQueue.off("messageQueued", onMessageQueued); + }; + }, []); + // Clean up abort controller on unmount useEffect(() => { return () => { @@ -306,6 +331,23 @@ export function useChat({ setIsWaitingForResponse(false); setResponseStartTime(null); setInputMode(true); + + // Check if there are queued messages and process them after a microtask delay + // This ensures the GUI state has been updated before processing the next message + const queuedMessageData = messageQueue.getLatestMessage(); + if (queuedMessageData) { + const { message: latestQueuedMessage, imageMap } = queuedMessageData; + logger.debug("processing queued message", { latestQueuedMessage }); + + // Clear queued messages from display since they're about to be processed + // Note: messageQueue.getLatestMessage() already cleared the actual queue + setQueuedMessages([]); + + await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui + + // Process the queued message - it will handle adding to history and compaction display + await processQueuedMessage(latestQueuedMessage, imageMap); + } } }; @@ -362,6 +404,9 @@ export function useChat({ setCompactionIndex, currentSession, setCurrentSession, + setIsCompacting, + setCompactionStartTime, + setCompactionAbortController, }); return null; } @@ -398,20 +443,11 @@ export function useChat({ .join(""); }; - const handleUserMessage = async ( + const processMessage = async ( message: string, imageMap?: Map, + isQueuedMessage: boolean = false, ) => { - // Check if this is a resume request (empty message after interruption) - if (await handleResumeRequest(message)) { - return; - } - - // Clear interrupted state if user types a new message - if (wasInterrupted && message !== "") { - setWasInterrupted(false); - } - // Handle special commands const handled = await handleSpecialCommands({ message, @@ -440,27 +476,9 @@ export function useChat({ // Track telemetry trackUserMessage(message, model); - // Format message with attached files and images - logger.debug("Processing message with images", { - hasImages: !!(imageMap && imageMap.size > 0), - imageCount: imageMap?.size || 0, - }); - const newUserMessage = await formatMessageWithFiles( - message, - attachedFiles, - imageMap, - ); - logger.debug("Message formatted successfully"); - - if (attachedFiles.length > 0) { - setAttachedFiles([]); - } - // In remote mode, send message to server instead of processing locally if (isRemoteMode && remoteUrl) { - const messageContentString = convertMessageContentToString( - newUserMessage.message.content, - ); + const messageContentString = convertMessageContentToString(message); await handleRemoteMessage({ remoteUrl, @@ -469,23 +487,161 @@ export function useChat({ return; } - // Check if auto-compacting is needed BEFORE adding user message - const { currentChatHistory, currentCompactionIndex } = - await handleAutoCompaction({ - chatHistory, - model, - llmApi, - compactionIndex, - setChatHistory: setChatHistory, - setCompactionIndex, + // For non-queued messages, format and add to chat history + if (isQueuedMessage) { + // For queued messages, we need to format and add to history after compaction + // First, format the message + const formattedQueuedMessage = await formatMessageWithFiles( + message, + [], // No attached files for queued messages + imageMap, + ); + + // Check if auto-compacting is needed with current history + const compactionController = new AbortController(); + setCompactionAbortController(compactionController); + setIsCompacting(true); + setCompactionStartTime(Date.now()); + + // Add the queued message to queue display during compaction + const queuedMessageForDisplay: QueuedMessage = { + message, + imageMap, + timestamp: Date.now(), + }; + setQueuedMessages((prev) => [...prev, queuedMessageForDisplay]); + + let currentChatHistory, currentCompactionIndex; + try { + const result = await handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex, + setChatHistory: setChatHistory, + setCompactionIndex, + abortController: compactionController, + }); + currentChatHistory = result.currentChatHistory; + currentCompactionIndex = result.currentCompactionIndex; + } catch (error) { + // If compaction fails, remove the queued message from display + setQueuedMessages((prev) => + prev.filter((msg) => msg !== queuedMessageForDisplay), + ); + throw error; // Re-throw to maintain error handling + } finally { + setIsCompacting(false); + setCompactionStartTime(null); + setCompactionAbortController(null); + } + + // Add the formatted queued message to history after compaction completes + const newHistory = [...currentChatHistory, formattedQueuedMessage]; + setChatHistory(newHistory); + + // Remove the queued message from display since it's now in chat history + setQueuedMessages((prev) => + prev.filter((msg) => msg !== queuedMessageForDisplay), + ); + + // Execute the streaming response with the updated history + await executeStreamingResponse(newHistory, currentCompactionIndex); + } else { + // Format message with attached files and images + logger.debug("Processing message with images", { + hasImages: !!(imageMap && imageMap.size > 0), + imageCount: imageMap?.size || 0, }); + const newUserMessage = await formatMessageWithFiles( + message, + attachedFiles, + imageMap, + ); + logger.debug("Message formatted successfully"); - // Add the formatted user message to history - const newHistory = [...currentChatHistory, newUserMessage]; - setChatHistory(newHistory); + if (attachedFiles.length > 0) { + setAttachedFiles([]); + } - // Execute the streaming response - await executeStreamingResponse(newHistory, currentCompactionIndex); + // Check if auto-compacting is needed BEFORE adding user message + const compactionController = new AbortController(); + setCompactionAbortController(compactionController); + setIsCompacting(true); + setCompactionStartTime(Date.now()); + + // Add the triggering message to queue display during compaction + const compactionQueuedMessage: QueuedMessage = { + message, + imageMap, + timestamp: Date.now(), + }; + setQueuedMessages((prev) => [...prev, compactionQueuedMessage]); + + let currentChatHistory, currentCompactionIndex; + try { + const result = await handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex, + setChatHistory: setChatHistory, + setCompactionIndex, + abortController: compactionController, + }); + currentChatHistory = result.currentChatHistory; + currentCompactionIndex = result.currentCompactionIndex; + } catch (error) { + // If compaction fails, remove the triggering message from queue display + setQueuedMessages((prev) => + prev.filter((msg) => msg !== compactionQueuedMessage), + ); + throw error; // Re-throw to maintain error handling + } finally { + setIsCompacting(false); + setCompactionStartTime(null); + setCompactionAbortController(null); + } + + // Add the formatted user message to history + const newHistory = [...currentChatHistory, newUserMessage]; + setChatHistory(newHistory); + + // Remove the triggering message from queue display since it's now in chat history + setQueuedMessages((prev) => + prev.filter((msg) => msg !== compactionQueuedMessage), + ); + + // Execute the streaming response + await executeStreamingResponse(newHistory, currentCompactionIndex); + } + }; + + const processQueuedMessage = async ( + message: string, + imageMap?: Map, + ) => { + // For queued messages, we can reuse the core message processing logic + // by calling the internal processing function directly + await processMessage(message, imageMap, true); + }; + + const handleUserMessage = async ( + message: string, + imageMap?: Map, + ) => { + // Check if this is a resume request (empty message after interruption) + if (await handleResumeRequest(message)) { + return; + } + + // Clear interrupted state if user types a new message + if (wasInterrupted && message !== "") { + setWasInterrupted(false); + } + + // Use the common message processing logic + await processMessage(message, imageMap, false); }; const handleInterrupt = () => { @@ -504,7 +660,21 @@ export function useChat({ return; } - // Local mode: abort the controller + // Local mode: abort the appropriate controller + + // If compaction is running, abort compaction + if (compactionAbortController && isCompacting) { + compactionAbortController.abort(); + setIsCompacting(false); + setCompactionStartTime(null); + setCompactionAbortController(null); + setInputMode(true); + // Clear any queued messages (including the triggering message) when compaction is interrupted + setQueuedMessages([]); + return; + } + + // If response is running, abort response if (abortController && isWaitingForResponse) { abortController.abort(); @@ -537,6 +707,8 @@ export function useChat({ additionalRules, ); setChatHistory(newHistory); + // Clear any queued messages when resetting chat + setQueuedMessages([]); }; const handleToolPermissionResponse = async ( @@ -610,10 +782,13 @@ export function useChat({ setChatHistory: setChatHistory, isWaitingForResponse, responseStartTime, + isCompacting, + compactionStartTime, inputMode, attachedFiles, activePermissionRequest, wasInterrupted, + queuedMessages, handleUserMessage, handleInterrupt, handleFileAttached, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 15d131f92..63484d9eb 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -146,6 +146,7 @@ class MessageTypes { "isItemTooBig", "process/markAsBackgrounded", "process/isBackgrounded", + "process/killTerminalProcess" ) } } diff --git a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts index 5dff86d5e..c557708ef 100644 --- a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +++ b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts @@ -4,12 +4,12 @@ import { InputBox, Key, TextEditor, + until, VSBrowser, WebDriver, WebElement, WebView, Workbench, - until, } from "vscode-extension-tester"; import { GlobalActions } from "../actions/Global.actions"; @@ -47,11 +47,31 @@ describe("Keyboard Shortcuts", () => { afterEach(async function () { this.timeout(DEFAULT_TIMEOUT.XL * 1000); + await cleanupChat(); await view.switchBack(); await editor.clearText(); await new EditorView().closeAllEditors(); }); + async function cleanupChat(chatInput?: WebElement) { + try { + if (!chatInput) { + chatInput = await TestUtils.waitForSuccess(async () => { + return GUISelectors.getMessageInputFieldAtIndex(view, 0); + }); + } + if ( + chatInput && + (await chatInput.isDisplayed()) && + (await chatInput.isEnabled()) + ) { + await chatInput.clear(); + } + } catch (e) { + console.error(`Failed to clear chat: ${e}`); + } + } + it("Should correctly undo and redo using keyboard shortcuts when writing a chat message", async () => { await GUIActions.executeFocusContinueInputShortcut(driver); ({ view } = await GUIActions.switchToReactIframe()); @@ -105,10 +125,8 @@ describe("Keyboard Shortcuts", () => { ); }).timeout(DEFAULT_TIMEOUT.XL); - it("Should not create a code block when Cmd+L is pressed without text highlighted", async () => { - const text = "Hello, world!"; - - await editor.setText(text); + it("Should not create a code block when Cmd+L is pressed on an empty document", async () => { + expect((await editor.getText()).trim()).to.equal(""); await GUIActions.executeFocusContinueInputShortcut(driver); @@ -174,6 +192,9 @@ describe("Keyboard Shortcuts", () => { await driver.wait(until.elementIsNotVisible(textInput), DEFAULT_TIMEOUT.XS); expect(await textInput.isDisplayed()).to.equal(false); + + // Make sure the view is visible again, so it can be cleared in afterEach() + await GUIActions.executeFocusContinueInputShortcut(driver); }).timeout(DEFAULT_TIMEOUT.XL); it("Should create a code block when Cmd+L is pressed with text highlighted", async () => { @@ -197,4 +218,44 @@ describe("Keyboard Shortcuts", () => { await GUIActions.executeFocusContinueInputShortcut(driver); }).timeout(DEFAULT_TIMEOUT.XL); + + it("Should create a code block with the whole file when Cmd+L is pressed on an empty line", async () => { + const text = "Hello,\n\n\nworld!"; + + await editor.setText(text); + await editor.moveCursor(2, 1); //Move cursor to an empty line + + await GUIActions.executeFocusContinueInputShortcut(driver); + + ({ view } = await GUIActions.switchToReactIframe()); + + const codeBlock = await TestUtils.waitForSuccess(() => + GUISelectors.getInputBoxCodeBlockAtIndex(view, 0), + ); + const codeblockContent = await codeBlock.getAttribute( + "data-codeblockcontent", + ); + + expect(codeblockContent).to.equal(text); + }); + + it("Should create a code block when Cmd+L is pressed on a non-empty line", async () => { + const text = "Hello, world!"; + + await editor.setText(text); + await editor.moveCursor(1, 7); //Move cursor to the 1st space + + await GUIActions.executeFocusContinueInputShortcut(driver); + + ({ view } = await GUIActions.switchToReactIframe()); + + const codeBlock = await TestUtils.waitForSuccess(() => + GUISelectors.getInputBoxCodeBlockAtIndex(view, 0), + ); + const codeblockContent = await codeBlock.getAttribute( + "data-codeblockcontent", + ); + + expect(codeblockContent).to.equal(text); + }).timeout(DEFAULT_TIMEOUT.XL); }); diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 4993063cf..15587e699 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -524,13 +524,12 @@ "continue.continueSubMenu": [ { "command": "continue.focusContinueInputWithoutClear", - "group": "Continue", - "when": "editorHasSelection" + "group": "Continue" }, { "command": "continue.focusEdit", "group": "Continue", - "when": "editorHasSelection && !editorReadonly" + "when": "!editorReadonly" } ], "explorer/context": [ diff --git a/extensions/vscode/src/diff/processDiff.ts b/extensions/vscode/src/diff/processDiff.ts index f350e12b4..cbff6f4a3 100644 --- a/extensions/vscode/src/diff/processDiff.ts +++ b/extensions/vscode/src/diff/processDiff.ts @@ -1,8 +1,11 @@ import { Core } from "core/core"; import { DataLogger } from "core/data/log"; +import { myersDiff } from "core/diff/myers"; + import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; import { editOutcomeTracker } from "../extension/EditOutcomeTracker"; import { VsCodeIde } from "../VsCodeIde"; + import { VerticalDiffManager } from "./vertical/manager"; export async function processDiff( @@ -42,7 +45,8 @@ export async function processDiff( } if (streamId) { - const fileContent = await ide.readFile(newOrCurrentUri); + // Capture file content before save to detect autoformatting + const preSaveContent = await ide.readFile(newOrCurrentUri); // Record the edit outcome before updating the apply state await editOutcomeTracker.recordEditOutcome( @@ -51,16 +55,45 @@ export async function processDiff( DataLogger.getInstance(), ); + // Save the file + await ide.saveFile(newOrCurrentUri); + + // Capture file content after save to detect autoformatting + const postSaveContent = await ide.readFile(newOrCurrentUri); + + // Detect autoformatting by comparing normalized content + let autoFormattingDiff: string | undefined; + const normalizedPreSave = preSaveContent.trim(); + const normalizedPostSave = postSaveContent.trim(); + + if (normalizedPreSave !== normalizedPostSave) { + // Auto-formatting was applied by the editor + const diffLines = myersDiff(preSaveContent, postSaveContent); + autoFormattingDiff = diffLines + .map((line) => { + switch (line.type) { + case "old": + return `-${line.line}`; + case "new": + return `+${line.line}`; + case "same": + return ` ${line.line}`; + } + }) + .join("\n"); + } + await sidebar.webviewProtocol.request("updateApplyState", { - fileContent, + fileContent: postSaveContent, // Use post-save content filepath: newOrCurrentUri, streamId, status: "closed", numDiffs: 0, toolCallId, + autoFormattingDiff, // Include autoformatting diff }); + } else { + // Save the file even if no streamId + await ide.saveFile(newOrCurrentUri); } - - // Save the file - await ide.saveFile(newOrCurrentUri); } diff --git a/extensions/vscode/src/util/addCode.ts b/extensions/vscode/src/util/addCode.ts index 524d77e88..05d9c3afe 100644 --- a/extensions/vscode/src/util/addCode.ts +++ b/extensions/vscode/src/util/addCode.ts @@ -36,22 +36,38 @@ export function getRangeInFileWithContents( }; } - if (selection.isEmpty && !allowEmpty) { + if ((selection.isEmpty && !allowEmpty) || isEmptyFile(editor.document)) { return null; } - let selectionRange = new vscode.Range(selection.start, selection.end); - const document = editor.document; - // Select the context from the beginning of the selection start line to the selection start position - const beginningOfSelectionStartLine = selection.start.with(undefined, 0); - const textBeforeSelectionStart = document.getText( - new vscode.Range(beginningOfSelectionStartLine, selection.start), - ); - // If there are only whitespace before the start of the selection, include the indentation - if (textBeforeSelectionStart.trim().length === 0) { - selectionRange = selectionRange.with({ - start: beginningOfSelectionStartLine, - }); + let selectionRange: vscode.Range | undefined; + // if the selection is empty and document is not empty, select the whole document + if (selection.isEmpty) { + selectionRange = new vscode.Range( + new vscode.Position(0, 0), + new vscode.Position( + editor.document.lineCount - 1, + editor.document.lineAt( + editor.document.lineCount - 1, + ).range.end.character, + ), + ); + } + + if (!selectionRange) { + selectionRange = new vscode.Range(selection.start, selection.end); + const document = editor.document; + // Select the context from the beginning of the selection start line to the selection start position + const beginningOfSelectionStartLine = selection.start.with(undefined, 0); + const textBeforeSelectionStart = document.getText( + new vscode.Range(beginningOfSelectionStartLine, selection.start), + ); + // If there are only whitespace before the start of the selection, include the indentation + if (textBeforeSelectionStart.trim().length === 0) { + selectionRange = selectionRange.with({ + start: beginningOfSelectionStartLine, + }); + } } const contents = editor.document.getText(selectionRange); @@ -61,12 +77,12 @@ export function getRangeInFileWithContents( contents, range: { start: { - line: selection.start.line, - character: selection.start.character, + line: selectionRange.start.line, + character: selectionRange.start.character, }, end: { - line: selection.end.line, - character: selection.end.character, + line: selectionRange.end.line, + character: selectionRange.end.character, }, }, }; @@ -78,7 +94,7 @@ export function getRangeInFileWithContents( export async function addHighlightedCodeToContext( webviewProtocol: VsCodeWebviewProtocol | undefined, ) { - const rangeInFileWithContents = getRangeInFileWithContents(); + const rangeInFileWithContents = getRangeInFileWithContents(true); if (rangeInFileWithContents) { webviewProtocol?.request("highlightedCode", { rangeInFileWithContents, @@ -129,6 +145,10 @@ export async function addEntireFileToContext( }); } +export function isEmptyFile(document: vscode.TextDocument) { + return document.lineCount === 1 && document.lineAt(0).range.isEmpty; +} + export function addCodeToContextFromRange( range: vscode.Range, webviewProtocol: VsCodeWebviewProtocol, diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx index b6dc7bca6..63be8f180 100644 --- a/gui/src/components/mainInput/ContextStatus.tsx +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -1,3 +1,4 @@ +import { useMemo, useRef } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { saveCurrentSession } from "../../redux/thunks/session"; import { useCompactConversation } from "../../util/compactConversation"; @@ -8,15 +9,36 @@ const ContextStatus = () => { const contextPercentage = useAppSelector( (state) => state.session.contextPercentage, ); + const selectedChatModel = useAppSelector( + (state) => state.config.config.selectedModelByRole.chat?.model, + ); + const previousHistoryLength = useRef(null); + const previousSelectedChatModel = useRef(null); const history = useAppSelector((state) => state.session.history); const percent = Math.round((contextPercentage ?? 0) * 100); const isPruned = useAppSelector((state) => state.session.isPruned); + const isDifferentModelAndSameHistory = useMemo(() => { + if (!selectedChatModel) return false; + // only reset if history changes + if (previousHistoryLength.current !== history.length) { + previousHistoryLength.current = history.length; + previousSelectedChatModel.current = selectedChatModel; + return false; + } + return previousSelectedChatModel.current !== selectedChatModel; + }, [history.length, selectedChatModel]); + const compactConversation = useCompactConversation(); if (!isPruned && percent < 60) { return null; } + // if user changed to a different model, we shouldn't show the context status until the user sends a new message + if (isDifferentModelAndSameHistory) { + return null; + } + const barColorClass = isPruned ? "bg-error" : "bg-description"; return ( diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 6b68d40af..09c85c3a2 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -1,13 +1,15 @@ +import { BuiltInToolNames } from "core/tools/builtIn"; import { useContext, useEffect } from "react"; -import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { selectFirstPendingToolCall, selectPendingToolCalls, + selectToolCallsByStatus, } from "../../../../redux/selectors/selectToolCalls"; import { cancelToolCall } from "../../../../redux/slices/sessionSlice"; import { callToolById } from "../../../../redux/thunks/callToolById"; +import { cancelStream } from "../../../../redux/thunks/cancelStream"; import { logToolUsage } from "../../../../redux/util"; import { isJetBrains } from "../../../../util"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; @@ -35,6 +37,14 @@ const isCancelToolCallShortcut = ( return modifierKey && event.key === "Backspace"; }; +// Check if a tool call is a terminal command +const isTerminalCommand = (toolCallState: any) => { + return ( + toolCallState?.toolCall?.function?.name === + BuiltInToolNames.RunTerminalCommand + ); +}; + export function LumpToolbar() { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); @@ -55,13 +65,67 @@ export function LumpToolbar() { ); const isApplying = applyStates.some((state) => state.status === "streaming"); + // Get ALL running terminal commands + const runningToolCalls = useAppSelector((state) => + selectToolCallsByStatus(state, "calling"), + ); + const runningTerminalCalls = runningToolCalls.filter(isTerminalCommand); + const hasRunningTerminalCommand = runningTerminalCalls.length > 0; + + // Simple handler: stop ALL running terminal commands + const handleStopAllTerminalCommands = async () => { + if (runningTerminalCalls.length === 0) { + return; + } + + // Stop all terminal commands concurrently + const stopPromises = runningTerminalCalls.map(async (terminalCall) => { + try { + // Cancel the process on the backend + await ideMessenger.request("process/killTerminalProcess", { + toolCallId: terminalCall.toolCallId, + }); + + // Cancel the tool call in the UI + dispatch( + cancelToolCall({ + toolCallId: terminalCall.toolCallId, + }), + ); + + logToolUsage(terminalCall, false, true, ideMessenger); + } catch (error) { + console.error( + `Failed to cancel terminal command ${terminalCall.toolCallId}:`, + error, + ); + } + }); + + // Wait for all cancellations to complete + await Promise.all(stopPromises); + }; + + // Combined stop handler + const handleStopAction = async () => { + // Stop all terminal commands if any are running + if (hasRunningTerminalCommand) { + await handleStopAllTerminalCommands(); + } + + // Also stop regular streaming if it's happening + if (isStreaming) { + dispatch(cancelStream()); + } + }; + useEffect(() => { - if (!firstPendingToolCall) { + if (!firstPendingToolCall && !hasRunningTerminalCommand) { return; } const handleToolCallKeyboardShortcuts = (event: KeyboardEvent) => { - if (isExecuteToolCallShortcut(event)) { + if (isExecuteToolCallShortcut(event) && firstPendingToolCall) { event.preventDefault(); event.stopPropagation(); @@ -71,13 +135,19 @@ export function LumpToolbar() { } else if (isCancelToolCallShortcut(event, jetbrains)) { event.preventDefault(); event.stopPropagation(); - void dispatch( - cancelToolCall({ - toolCallId: firstPendingToolCall.toolCallId, - }), - ); - logToolUsage(firstPendingToolCall, false, true, ideMessenger); + if (hasRunningTerminalCommand) { + // Stop running terminal commands + void handleStopAction(); + } else if (firstPendingToolCall) { + // Cancel pending tool call + void dispatch( + cancelToolCall({ + toolCallId: firstPendingToolCall.toolCallId, + }), + ); + logToolUsage(firstPendingToolCall, false, true, ideMessenger); + } } }; @@ -85,7 +155,7 @@ export function LumpToolbar() { return () => { document.removeEventListener("keydown", handleToolCallKeyboardShortcuts); }; - }, [firstPendingToolCall]); + }, [firstPendingToolCall, hasRunningTerminalCommand, runningTerminalCalls]); if (isApplying) { return ; @@ -103,8 +173,18 @@ export function LumpToolbar() { return ; } + // Only show terminal streaming for actual terminal commands + if (hasRunningTerminalCommand) { + const count = runningTerminalCalls.length; + const stopText = `Stop Terminal${count > 1 ? ` (${count})` : ""}`; + return ( + + ); + } + + // Regular streaming (non-terminal) if (isStreaming) { - return ; + return dispatch(cancelStream())} />; } if (pendingToolCalls.length > 0) { diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx index 4acfd6334..d67187161 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx @@ -1,20 +1,25 @@ -import { useAppDispatch } from "../../../../redux/hooks"; -import { cancelStream } from "../../../../redux/thunks/cancelStream"; import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util"; import { GeneratingIndicator } from "./GeneratingIndicator"; -export function StreamingToolbar() { +interface StreamingToolbarProps { + onStop: () => void; + displayText?: string; +} + +export function StreamingToolbar({ + onStop, + displayText = "Stop", +}: StreamingToolbarProps) { const jetbrains = isJetBrains(); - const dispatch = useAppDispatch(); return (
void dispatch(cancelStream())} + onClick={onStop} className="text-2xs cursor-pointer px-1.5 py-0.5 hover:brightness-125" > - Stop + {displayText} {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()}⌫ diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts index 25532e750..f5f5adc71 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -83,12 +83,57 @@ export const handleApplyStateUpdate = createAsyncThunk< } if (accepted) { + // Add autoformatting diff to tool output if present + if (applyState.autoFormattingDiff) { + dispatch( + updateToolCallOutput({ + toolCallId: applyState.toolCallId, + contextItems: [ + { + icon: "info", + name: "Auto-formatting Applied", + description: "Editor auto-formatting changes", + content: `Along with your edits, the editor applied the following auto-formatting:\n\n${applyState.autoFormattingDiff}\n\n(Note: Pay close attention to changes such as single quotes being converted to double quotes, semicolons being removed or added, long lines being broken into multiple lines, adjusting indentation style, adding/removing trailing commas, etc. This will help you ensure future SEARCH/REPLACE operations to this file are accurate.)`, + hidden: false, + }, + ], + }), + ); + } + if (toolCallState.status !== "errored") { dispatch( acceptToolCall({ toolCallId: applyState.toolCallId, }), ); + dispatch( + updateToolCallOutput({ + toolCallId: applyState.toolCallId, + contextItems: [ + { + name: "Edit Success", + content: `Successfully edited ${applyState.filepath}`, + description: "", + hidden: true, + }, + ], + }), + ); + } else { + dispatch( + updateToolCallOutput({ + toolCallId: applyState.toolCallId, + contextItems: [ + { + name: "Edit Failed", + content: `Failed to edit ${applyState.filepath}. To continue working with the file, read it again to see the most up-to-date contents`, + description: "", + hidden: true, + }, + ], + }), + ); } void dispatch( @@ -98,7 +143,6 @@ export const handleApplyStateUpdate = createAsyncThunk< ); } } - // TODO return output from edit tools so the model knows the result } } } diff --git a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts index 07c43bf53..8563e858c 100644 --- a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts +++ b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts @@ -46,7 +46,7 @@ export const moveTerminalProcessToBackground = createAsyncThunk< { name: "Terminal", description: "Terminal command output", - content: existingContent + (existingContent ? "\n\n" : "") + status, + content: existingContent, status: status, }, ]; diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts index d4c5e572e..6fd213a75 100644 --- a/gui/src/redux/util/constructMessages.test.ts +++ b/gui/src/redux/util/constructMessages.test.ts @@ -8,6 +8,7 @@ import { ToolResultChatMessage, UserChatMessage, } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { CANCELLED_TOOL_CALL_MESSAGE, NO_TOOL_CALL_OUTPUT_MESSAGE, @@ -712,4 +713,346 @@ describe("constructMessages", () => { expect(messages[0].content).toContain("Base System Message"); expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule); }); + + // Tests for the specific block in lines 135-142 handling toolCallState.output + describe("toolCallState.output handling (lines 135-142)", () => { + test("should use CANCELLED_TOOL_CALL_MESSAGE for cancelled tool calls", () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I'll run a command", + toolCalls: [ + { + id: "tool-call-1", + type: "function", + function: { + name: "some_tool", + arguments: '{"command": "ls"}', + }, + }, + ], + }; + + mockHistory = [ + { + message: assistantWithToolCall, + contextItems: [], + toolCallStates: [ + { + toolCallId: "tool-call-1", + toolCall: { + id: "tool-call-1", + type: "function", + function: { + name: "some_tool", + arguments: '{"command": "ls"}', + }, + }, + status: "canceled", + parsedArgs: { command: "ls" }, + output: [ + createContextItem( + "result", + "This should be ignored due to cancelled status", + ), + ], + }, + ], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.role).toBe("tool"); + expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE); + expect(toolMessage.content).not.toContain("This should be ignored"); + }); + + test("should use renderContextItemsWithStatus for RunTerminalCommand with output", () => { + const assistantWithTerminalCall: AssistantChatMessage = { + role: "assistant", + content: "I'll run a terminal command", + toolCalls: [ + { + id: "terminal-call-1", + type: "function", + function: { + name: BuiltInToolNames.RunTerminalCommand, + arguments: '{"command": "ls -la"}', + }, + }, + ], + }; + + const terminalOutputWithStatus = [ + { + ...createContextItem("terminal-output", "file1.txt\nfile2.txt"), + status: "completed", + }, + { + ...createContextItem("terminal-error", "Warning: deprecated flag"), + status: "warning", + }, + ]; + + mockHistory = [ + { + message: assistantWithTerminalCall, + contextItems: [], + toolCallStates: [ + { + toolCallId: "terminal-call-1", + toolCall: { + id: "terminal-call-1", + type: "function", + function: { + name: BuiltInToolNames.RunTerminalCommand, + arguments: '{"command": "ls -la"}', + }, + }, + status: "done", + parsedArgs: { command: "ls -la" }, + output: terminalOutputWithStatus, + }, + ], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.role).toBe("tool"); + expect(toolMessage.toolCallId).toBe("terminal-call-1"); + // Should contain content with status appended + expect(toolMessage.content).toContain("file1.txt\nfile2.txt"); + expect(toolMessage.content).toContain("[Status: completed]"); + expect(toolMessage.content).toContain("Warning: deprecated flag"); + expect(toolMessage.content).toContain("[Status: warning]"); + // Should use renderContextItemsWithStatus format with double newlines between items + expect(toolMessage.content).toMatch( + /file1\.txt\nfile2\.txt\n\[Status: completed\]\n\nWarning: deprecated flag\n\[Status: warning\]/, + ); + }); + + test("should use renderContextItems for non-RunTerminalCommand tools with output", () => { + const assistantWithSearchCall: AssistantChatMessage = { + role: "assistant", + content: "I'll search for that", + toolCalls: [ + { + id: "search-call-1", + type: "function", + function: { + name: "search", // Not RunTerminalCommand + arguments: '{"query": "test"}', + }, + }, + ], + }; + + const searchOutput = [ + createContextItem("result1", "First search result"), + createContextItem("result2", "Second search result"), + ]; + + mockHistory = [ + { + message: assistantWithSearchCall, + contextItems: [], + toolCallStates: [ + { + toolCallId: "search-call-1", + toolCall: { + id: "search-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "done", + parsedArgs: { query: "test" }, + output: searchOutput, + }, + ], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.role).toBe("tool"); + expect(toolMessage.toolCallId).toBe("search-call-1"); + // Should use renderContextItems format (no status, double newlines between items) + expect(toolMessage.content).toBe( + "First search result\n\nSecond search result", + ); + expect(toolMessage.content).not.toContain("[Status:"); + }); + + test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when no output exists", () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I'll search for that", + toolCalls: [ + { + id: "search-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + mockHistory = [ + { + message: assistantWithToolCall, + contextItems: [], + toolCallStates: [ + { + toolCallId: "search-call-1", + toolCall: { + id: "search-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + status: "generating", + parsedArgs: { query: "test" }, + // No output field + }, + ], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.role).toBe("tool"); + expect(toolMessage.toolCallId).toBe("search-call-1"); + expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); + }); + + test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState is undefined", () => { + const assistantWithToolCall: AssistantChatMessage = { + role: "assistant", + content: "I'll search for that", + toolCalls: [ + { + id: "search-call-1", + type: "function", + function: { + name: "search", + arguments: '{"query": "test"}', + }, + }, + ], + }; + + mockHistory = [ + { + message: assistantWithToolCall, + contextItems: [], + // No toolCallStates array + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.role).toBe("tool"); + expect(toolMessage.toolCallId).toBe("search-call-1"); + expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE); + }); + + test("should prioritize cancelled status over output content", () => { + const assistantWithTerminalCall: AssistantChatMessage = { + role: "assistant", + content: "I'll run a command", + toolCalls: [ + { + id: "terminal-call-1", + type: "function", + function: { + name: BuiltInToolNames.RunTerminalCommand, + arguments: '{"command": "ls"}', + }, + }, + ], + }; + + mockHistory = [ + { + message: assistantWithTerminalCall, + contextItems: [], + toolCallStates: [ + { + toolCallId: "terminal-call-1", + toolCall: { + id: "terminal-call-1", + type: "function", + function: { + name: BuiltInToolNames.RunTerminalCommand, + arguments: '{"command": "ls"}', + }, + }, + status: "canceled", // Cancelled status + parsedArgs: { command: "ls" }, + output: [ + createContextItem( + "terminal-output", + "This output should be ignored", + ), + ], // Has output but is cancelled + }, + ], + }, + ]; + + const { messages } = constructMessages( + mockHistory, + "Base System Message", + mockRules, + {}, + ); + + const toolMessage = messages[2] as ToolResultChatMessage; + expect(toolMessage.role).toBe("tool"); + expect(toolMessage.toolCallId).toBe("terminal-call-1"); + // Should use cancelled message, not the output content + expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE); + expect(toolMessage.content).not.toContain( + "This output should be ignored", + ); + }); + }); }); diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index f75eb8b49..9b3593082 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -10,6 +10,7 @@ import { import { chatMessageIsEmpty } from "core/llm/messages"; import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; import { RulePolicies } from "core/llm/rules/types"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { CANCELLED_TOOL_CALL_MESSAGE, NO_TOOL_CALL_OUTPUT_MESSAGE, @@ -20,8 +21,13 @@ import { findLast, findLastIndex } from "core/util/findLast"; import { normalizeToMessageParts, renderContextItems, + renderContextItemsWithStatus, } from "core/util/messageContent"; import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/utils"; + +// Helper function to render context items and append status information +// Helper function to render context items and append status information + interface MessageWithContextItems { ctxItems: ContextItemWithId[]; message: ChatMessage; @@ -132,8 +138,14 @@ export function constructMessages( if (toolCallState?.status === "canceled") { content = CANCELLED_TOOL_CALL_MESSAGE; + } else if ( + toolCallState?.output && + toolCall.function?.name == BuiltInToolNames.RunTerminalCommand + ) { + // Add status for tools containing detailed status outcomes per context item + content = renderContextItemsWithStatus(toolCallState.output); } else if (toolCallState?.output) { - content = renderContextItems(toolCallState.output); + content = renderContextItems(toolCallState?.output); } msgs.push({ diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index cefc6832f..ccc7cc3fa 100644 --- a/gui/src/util/clientTools/editImpl.ts +++ b/gui/src/util/clientTools/editImpl.ts @@ -17,13 +17,13 @@ export const editToolImpl: ClientToolImpl = async ( filepath = filepath.slice(2); } - const openFiles = await extras.ideMessenger.ide.getOpenFiles(); let firstUriMatch = await resolveRelativePathInDir( filepath, extras.ideMessenger.ide, ); if (!firstUriMatch) { + const openFiles = await extras.ideMessenger.ide.getOpenFiles(); for (const uri of openFiles) { if (uri.endsWith(filepath)) { firstUriMatch = uri; @@ -46,13 +46,7 @@ export const editToolImpl: ClientToolImpl = async ( ); return { - respondImmediately: true, - output: [ - { - name: "File edited successfully", - content: `Successfully initiated edit for ${firstUriMatch}`, - description: "File edit operation started", - }, - ], + respondImmediately: false, + output: undefined, // no immediate output - output for edit tools should be added based on apply state coming in }; }; diff --git a/packages/config-yaml/src/__tests__/test-files/invokable-rules.yaml b/packages/config-yaml/src/__tests__/test-files/invokable-rules.yaml new file mode 100644 index 000000000..cccd39457 --- /dev/null +++ b/packages/config-yaml/src/__tests__/test-files/invokable-rules.yaml @@ -0,0 +1,23 @@ +name: Test Invokable Rules +version: 0.0.1 +schema: v1 + +rules: + - name: "Code Review" + rule: "Review this code for best practices and potential issues" + invokable: true + description: "Performs a code review" + + - name: "Explain Code" + rule: "Explain what this code does in simple terms" + invokable: true + + - name: "Regular Rule" + rule: "This is a non-invokable rule" + invokable: false + + - name: "Default Rule" + rule: "This rule has no invokable property" + description: "Should default to non-invokable" + + - "Simple string rule" \ No newline at end of file diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 8e1c73224..e4a15d7bb 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -57,6 +57,7 @@ const ruleObjectSchema = z.object({ globs: z.union([z.string(), z.array(z.string())]).optional(), regex: z.union([z.string(), z.array(z.string())]).optional(), alwaysApply: z.boolean().optional(), + invokable: z.boolean().optional(), sourceFile: z.string().optional(), //TODO refactor RuleWithSource.ruleFile to align with sourceFile }); const ruleSchema = z.union([z.string(), ruleObjectSchema]); diff --git a/packages/terminal-security/package-lock.json b/packages/terminal-security/package-lock.json index 62d1f9b79..640f76919 100644 --- a/packages/terminal-security/package-lock.json +++ b/packages/terminal-security/package-lock.json @@ -1322,14 +1322,14 @@ "license": "MIT" }, "node_modules/tinyglobby": { - "version": "0.2.14", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz", - "integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==", + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", "dev": true, "license": "MIT", "dependencies": { - "fdir": "^6.4.4", - "picomatch": "^4.0.2" + "fdir": "^6.5.0", + "picomatch": "^4.0.3" }, "engines": { "node": ">=12.0.0" @@ -1390,9 +1390,9 @@ "license": "MIT" }, "node_modules/vite": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.4.tgz", - "integrity": "sha512-X5QFK4SGynAeeIt+A7ZWnApdUyHYm+pzv/8/A57LqSGcI88U6R6ipOs3uCesdc6yl7nl+zNO0t8LmqAdXcQihw==", + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.5.tgz", + "integrity": "sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1401,7 +1401,7 @@ "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", - "tinyglobby": "^0.2.14" + "tinyglobby": "^0.2.15" }, "bin": { "vite": "bin/vite.js" diff --git a/scripts/install-dependencies.sh b/scripts/install-dependencies.sh index 836b8e11b..8832fc44b 100755 --- a/scripts/install-dependencies.sh +++ b/scripts/install-dependencies.sh @@ -45,7 +45,7 @@ echo "Installing GUI extension dependencies..." pushd gui npm install npm link @continuedev/core -npm run build +NODE_OPTIONS="--max-old-space-size=4096" npm run build popd # VSCode Extension (will also package GUI)