From fe8eb5dcbc23abd65f18fec54e9206246876d720 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Fri, 18 Jul 2025 19:08:16 +0200 Subject: [PATCH 01/26] feat: allow Cmd+L / Cmd+I on empty selection to select the entire file Signed-off-by: Fred Bricon --- .../e2e/tests/KeyboardShortcuts.test.ts | 71 +++++++++++++++++-- extensions/vscode/package.json | 5 +- extensions/vscode/src/util/addCode.ts | 56 ++++++++++----- 3 files changed, 106 insertions(+), 26 deletions(-) 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 3eaf44c21..63b7f00d6 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -540,13 +540,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/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, From 58cb7815ca9f85fed632c77e6be8944973a4b04c Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sat, 23 Aug 2025 20:07:59 -0700 Subject: [PATCH 02/26] feat: Add ability to stop foreground terminal commands --- core/core.ts | 9 +- core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 1 + .../implementations/runTerminalCommand.ts | 65 +++- .../runTerminalCommand.vitest.ts | 4 +- .../processTerminalBackgroundStates.test.ts | 73 ---- core/util/processTerminalBackgroundStates.ts | 17 - core/util/processTerminalStates.test.ts | 350 ++++++++++++++++++ core/util/processTerminalStates.ts | 114 ++++++ .../constants/MessageTypes.kt | 2 + .../Lump/LumpToolbar/LumpToolbar.tsx | 102 ++++- .../Lump/LumpToolbar/StreamingToolbar.tsx | 22 +- .../thunks/moveTerminalProcessToBackground.ts | 2 +- gui/src/redux/util/constructMessages.ts | 18 +- 14 files changed, 660 insertions(+), 120 deletions(-) delete mode 100644 core/util/processTerminalBackgroundStates.test.ts delete mode 100644 core/util/processTerminalBackgroundStates.ts create mode 100644 core/util/processTerminalStates.test.ts create mode 100644 core/util/processTerminalStates.ts diff --git a/core/core.ts b/core/core.ts index 30dcd7a41..f26dc1b6a 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,7 +30,7 @@ import { Telemetry } from "./util/posthog"; import { isProcessBackgrounded, markProcessAsBackgrounded, -} from "./util/processTerminalBackgroundStates"; +} from "./util/processTerminalStates"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -1056,6 +1056,13 @@ export class Core { }, ); + on("process/cancelTerminalCommand", async ({ data: { toolCallId } }) => { + const { cancelTerminalCommand } = await import( + "./util/processTerminalStates.js" + ); + await cancelTerminalCommand(toolCallId); + }); + on("mdm/setLicenseKey", ({ data: { licenseKey } }) => { const isValid = setMdmLicenseKey(licenseKey); return isValid; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 5add878be..2bd22c830 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/cancelTerminalCommand": [{ toolCallId: string }, void]; "mdm/setLicenseKey": [{ licenseKey: string }, boolean]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 91819a33d..ff0717244 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/cancelTerminalCommand", ]; // 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..c26e5b64d 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"; @@ -40,7 +40,7 @@ describe("runTerminalCommandImpl", () => { // 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) + const processMap = (processTerminalStates as any) .processTerminalBackgroundStates; if (processMap && typeof processMap.clear === "function") { processMap.clear(); 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..00f64ab4e --- /dev/null +++ b/core/util/processTerminalStates.test.ts @@ -0,0 +1,350 @@ +import { ChildProcess } from "child_process"; +import { + cancelAllRunningTerminalCommands, + cancelMultipleTerminalCommands, + cancelTerminalCommand, + getAllBackgroundedProcessIds, + getAllRunningProcessIds, + getRunningProcess, + isProcessBackgrounded, + isProcessRunning, + 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 cancelTerminalCommand(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(cancelTerminalCommand(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 cancelTerminalCommand(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 = cancelTerminalCommand(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 = cancelTerminalCommand(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 cancelMultipleTerminalCommands([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 cancelAllRunningTerminalCommands(); + + 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 cancelAllRunningTerminalCommands(); + expect(cancelledIds).toEqual([]); + }); + }); +}); diff --git a/core/util/processTerminalStates.ts b/core/util/processTerminalStates.ts new file mode 100644 index 000000000..922b9d7dc --- /dev/null +++ b/core/util/processTerminalStates.ts @@ -0,0 +1,114 @@ +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 cancelTerminalCommand(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 cancelMultipleTerminalCommands( + toolCallIds: string[], +): Promise { + const cancelPromises = toolCallIds.map((toolCallId) => + cancelTerminalCommand(toolCallId), + ); + await Promise.all(cancelPromises); +} + +// Function to cancel ALL currently running terminal commands +export async function cancelAllRunningTerminalCommands(): Promise { + const runningIds = getAllRunningProcessIds(); + if (runningIds.length > 0) { + await cancelMultipleTerminalCommands(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()); +} 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..a400adb0a 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 @@ -144,8 +144,10 @@ class MessageTypes { "tools/evaluatePolicy", "controlPlane/openUrl", "isItemTooBig", + "controlPlane/openUrl", "process/markAsBackgrounded", "process/isBackgrounded", + "process/cancelTerminalCommand", ) } } diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 6b68d40af..245076d74 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -1,13 +1,14 @@ 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 +36,15 @@ 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 === "run_terminal_command" || + toolCallState?.toolCall?.function?.name === "Bash" || + toolCallState?.toolCall?.function?.name === "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/cancelTerminalCommand", { + 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,16 @@ export function LumpToolbar() { return ; } - if (isStreaming) { - return ; + // Show streaming toolbar for any streaming activity + if (isStreaming || hasRunningTerminalCommand) { + const count = runningTerminalCalls.length; + const stopText = hasRunningTerminalCommand + ? `Stop Terminal${count > 1 ? ` (${count})` : ""}` + : "Stop"; + + return ( + + ); } 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..15e7334ab 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx @@ -3,18 +3,34 @@ 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(); + const handleStop = () => { + if (onStop) { + onStop(); + } else { + void dispatch(cancelStream()); + } + }; + return (
void dispatch(cancelStream())} + onClick={handleStop} 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/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.ts b/gui/src/redux/util/constructMessages.ts index f75eb8b49..c36e1ccad 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -22,6 +22,22 @@ import { renderContextItems, } from "core/util/messageContent"; import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/utils"; + +// Helper function to render context items and append status information +function renderContextItemsWithStatus(contextItems: any[]): string { + const content = renderContextItems(contextItems); + + // Check if any context items have status information + const statusItems = contextItems + .filter((item) => item.status) + .map((item) => `Status: ${item.status}`); + + if (statusItems.length > 0) { + return `${content}\n\n${statusItems.join("\n")}`; + } + + return content; +} interface MessageWithContextItems { ctxItems: ContextItemWithId[]; message: ChatMessage; @@ -133,7 +149,7 @@ export function constructMessages( if (toolCallState?.status === "canceled") { content = CANCELLED_TOOL_CALL_MESSAGE; } else if (toolCallState?.output) { - content = renderContextItems(toolCallState.output); + content = renderContextItemsWithStatus(toolCallState.output); } msgs.push({ From acbba9b7d084e83dced1dbdb28ee6f4b90ed8814 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 27 Aug 2025 23:48:05 -0700 Subject: [PATCH 03/26] fix: :bug: Fixes based on reviewer comments --- core/core.ts | 6 +-- core/protocol/core.ts | 2 +- core/protocol/passThrough.ts | 2 +- .../runTerminalCommand.vitest.ts | 8 +--- core/util/processTerminalStates.test.ts | 39 +++++++++++++------ core/util/processTerminalStates.ts | 15 ++++--- .../constants/MessageTypes.kt | 3 +- .../Lump/LumpToolbar/LumpToolbar.tsx | 9 ++--- .../Lump/LumpToolbar/StreamingToolbar.tsx | 13 ++----- gui/src/redux/util/constructMessages.ts | 26 ++++++------- 10 files changed, 64 insertions(+), 59 deletions(-) diff --git a/core/core.ts b/core/core.ts index f26dc1b6a..2357d8687 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1056,11 +1056,11 @@ export class Core { }, ); - on("process/cancelTerminalCommand", async ({ data: { toolCallId } }) => { - const { cancelTerminalCommand } = await import( + on("process/killTerminalProcess", async ({ data: { toolCallId } }) => { + const { killTerminalProcess } = await import( "./util/processTerminalStates.js" ); - await cancelTerminalCommand(toolCallId); + await killTerminalProcess(toolCallId); }); on("mdm/setLicenseKey", ({ data: { licenseKey } }) => { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 2bd22c830..74243f195 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -313,6 +313,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "process/markAsBackgrounded": [{ toolCallId: string }, void]; "process/isBackgrounded": [{ toolCallId: string }, boolean]; - "process/cancelTerminalCommand": [{ toolCallId: string }, void]; + "process/killTerminalProcess": [{ toolCallId: string }, void]; "mdm/setLicenseKey": [{ licenseKey: string }, boolean]; }; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index ff0717244..8f109f46f 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -86,7 +86,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "isItemTooBig", "process/markAsBackgrounded", "process/isBackgrounded", - "process/cancelTerminalCommand", + "process/killTerminalProcess", ]; // Message types to pass through from core to webview diff --git a/core/tools/implementations/runTerminalCommand.vitest.ts b/core/tools/implementations/runTerminalCommand.vitest.ts index c26e5b64d..230d482f7 100644 --- a/core/tools/implementations/runTerminalCommand.vitest.ts +++ b/core/tools/implementations/runTerminalCommand.vitest.ts @@ -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 = (processTerminalStates 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/processTerminalStates.test.ts b/core/util/processTerminalStates.test.ts index 00f64ab4e..6b9e39f00 100644 --- a/core/util/processTerminalStates.test.ts +++ b/core/util/processTerminalStates.test.ts @@ -1,13 +1,14 @@ import { ChildProcess } from "child_process"; import { - cancelAllRunningTerminalCommands, - cancelMultipleTerminalCommands, - cancelTerminalCommand, + clearAllBackgroundProcesses, getAllBackgroundedProcessIds, getAllRunningProcessIds, getRunningProcess, isProcessBackgrounded, isProcessRunning, + killAllRunningTerminalProcesses, + killMultipleTerminalProcesses, + killTerminalProcess, markProcessAsBackgrounded, markProcessAsRunning, removeBackgroundedProcess, @@ -205,7 +206,7 @@ describe("processTerminalStates", () => { markProcessAsRunning(toolCallId, mockProcess); expect(isProcessRunning(toolCallId)).toBe(true); - await cancelTerminalCommand(toolCallId); + await killTerminalProcess(toolCallId); expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM"); expect(isProcessRunning(toolCallId)).toBe(false); @@ -214,7 +215,7 @@ describe("processTerminalStates", () => { test("should handle cancelling non-existent process", async () => { const toolCallId = "non-existent"; - await expect(cancelTerminalCommand(toolCallId)).resolves.not.toThrow(); + await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow(); }); test("should handle cancelling already killed process", async () => { @@ -223,7 +224,7 @@ describe("processTerminalStates", () => { markProcessAsRunning(toolCallId, mockProcess); - await cancelTerminalCommand(toolCallId); + await killTerminalProcess(toolCallId); expect(mockProcess.kill).not.toHaveBeenCalled(); }); @@ -242,7 +243,7 @@ describe("processTerminalStates", () => { markProcessAsRunning(toolCallId, mockProcess); - const cancelPromise = cancelTerminalCommand(toolCallId); + const cancelPromise = killTerminalProcess(toolCallId); // Fast-forward time to trigger the timeout jest.advanceTimersByTime(5000); @@ -259,7 +260,7 @@ describe("processTerminalStates", () => { markProcessAsRunning(toolCallId, mockProcess); - const cancelPromise = cancelTerminalCommand(toolCallId); + const cancelPromise = killTerminalProcess(toolCallId); // Fast-forward time to trigger the timeout jest.advanceTimersByTime(5000); @@ -314,7 +315,7 @@ describe("processTerminalStates", () => { markProcessAsRunning(toolCallId1, mockProcess1); markProcessAsRunning(toolCallId2, mockProcess2); - await cancelMultipleTerminalCommands([toolCallId1, toolCallId2]); + await killMultipleTerminalProcesses([toolCallId1, toolCallId2]); expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM"); expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM"); @@ -331,7 +332,7 @@ describe("processTerminalStates", () => { markProcessAsRunning(toolCallId1, mockProcess1); markProcessAsRunning(toolCallId2, mockProcess2); - const cancelledIds = await cancelAllRunningTerminalCommands(); + const cancelledIds = await killAllRunningTerminalProcesses(); expect(cancelledIds).toContain(toolCallId1); expect(cancelledIds).toContain(toolCallId2); @@ -343,8 +344,24 @@ describe("processTerminalStates", () => { }); test("should return empty array when no running commands to cancel", async () => { - const cancelledIds = await cancelAllRunningTerminalCommands(); + 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 index 922b9d7dc..cad243a82 100644 --- a/core/util/processTerminalStates.ts +++ b/core/util/processTerminalStates.ts @@ -67,7 +67,7 @@ export function removeRunningProcess(toolCallId: string): void { processTerminalForegroundStates.delete(toolCallId); } -export async function cancelTerminalCommand(toolCallId: string): Promise { +export async function killTerminalProcess(toolCallId: string): Promise { const processInfo = processTerminalForegroundStates.get(toolCallId); if (processInfo && !processInfo.process.killed) { const { process } = processInfo; @@ -86,20 +86,20 @@ export async function cancelTerminalCommand(toolCallId: string): Promise { } // Function to cancel multiple terminal commands at once -export async function cancelMultipleTerminalCommands( +export async function killMultipleTerminalProcesses( toolCallIds: string[], ): Promise { const cancelPromises = toolCallIds.map((toolCallId) => - cancelTerminalCommand(toolCallId), + killTerminalProcess(toolCallId), ); await Promise.all(cancelPromises); } // Function to cancel ALL currently running terminal commands -export async function cancelAllRunningTerminalCommands(): Promise { +export async function killAllRunningTerminalProcesses(): Promise { const runningIds = getAllRunningProcessIds(); if (runningIds.length > 0) { - await cancelMultipleTerminalCommands(runningIds); + await killMultipleTerminalProcesses(runningIds); } return runningIds; // Return the IDs that were cancelled } @@ -112,3 +112,8 @@ export function getAllRunningProcessIds(): string[] { 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/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 a400adb0a..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 @@ -144,10 +144,9 @@ class MessageTypes { "tools/evaluatePolicy", "controlPlane/openUrl", "isItemTooBig", - "controlPlane/openUrl", "process/markAsBackgrounded", "process/isBackgrounded", - "process/cancelTerminalCommand", + "process/killTerminalProcess" ) } } diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 245076d74..3127dd0a8 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -19,6 +19,7 @@ import { PendingApplyStatesToolbar } from "./PendingApplyStatesToolbar"; import { PendingToolCallToolbar } from "./PendingToolCallToolbar"; import { StreamingToolbar } from "./StreamingToolbar"; import { TtsActiveToolbar } from "./TtsActiveToolbar"; +import { BuiltInToolNames } from "core/tools/builtIn"; // Keyboard shortcut detection utilities const isExecuteToolCallShortcut = (event: KeyboardEvent) => { @@ -38,11 +39,7 @@ const isCancelToolCallShortcut = ( // Check if a tool call is a terminal command const isTerminalCommand = (toolCallState: any) => { - return ( - toolCallState?.toolCall?.function?.name === "run_terminal_command" || - toolCallState?.toolCall?.function?.name === "Bash" || - toolCallState?.toolCall?.function?.name === "runTerminalCommand" - ); + return BuiltInToolNames.RunTerminalCommand; }; export function LumpToolbar() { @@ -82,7 +79,7 @@ export function LumpToolbar() { const stopPromises = runningTerminalCalls.map(async (terminalCall) => { try { // Cancel the process on the backend - await ideMessenger.request("process/cancelTerminalCommand", { + await ideMessenger.request("process/killTerminalProcess", { toolCallId: terminalCall.toolCallId, }); diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx index 15e7334ab..66d35f3cb 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx @@ -1,26 +1,19 @@ -import { useAppDispatch } from "../../../../redux/hooks"; -import { cancelStream } from "../../../../redux/thunks/cancelStream"; import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util"; import { GeneratingIndicator } from "./GeneratingIndicator"; interface StreamingToolbarProps { - onStop?: () => void; + onStop: () => void; displayText?: string; } export function StreamingToolbar({ onStop, displayText = "Stop", -}: StreamingToolbarProps = {}) { +}: StreamingToolbarProps) { const jetbrains = isJetBrains(); - const dispatch = useAppDispatch(); const handleStop = () => { - if (onStop) { - onStop(); - } else { - void dispatch(cancelStream()); - } + onStop(); }; return ( diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index c36e1ccad..666a1bfd9 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -17,26 +17,24 @@ import { import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools"; import { SystemMessageToolsFramework } from "core/tools/systemMessageTools/types"; import { findLast, findLastIndex } from "core/util/findLast"; -import { - normalizeToMessageParts, - renderContextItems, -} from "core/util/messageContent"; +import { normalizeToMessageParts } 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 function renderContextItemsWithStatus(contextItems: any[]): string { - const content = renderContextItems(contextItems); + return contextItems + .map((item) => { + let result = item.content; - // Check if any context items have status information - const statusItems = contextItems - .filter((item) => item.status) - .map((item) => `Status: ${item.status}`); + // If this item has a status, append it directly after the content + if (item.status) { + result += `\n[Status: ${item.status}]`; + } - if (statusItems.length > 0) { - return `${content}\n\n${statusItems.join("\n")}`; - } - - return content; + return result; + }) + .join("\n\n"); } interface MessageWithContextItems { ctxItems: ContextItemWithId[]; From 3ca38974631330356841d721fa583334131bf559 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Thu, 28 Aug 2025 00:12:13 -0700 Subject: [PATCH 04/26] fix: :bug: Fix issue with streaming toolbar --- .../Lump/LumpToolbar/LumpToolbar.tsx | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx index 3127dd0a8..09c85c3a2 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx @@ -1,3 +1,4 @@ +import { BuiltInToolNames } from "core/tools/builtIn"; import { useContext, useEffect } from "react"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; @@ -19,7 +20,6 @@ import { PendingApplyStatesToolbar } from "./PendingApplyStatesToolbar"; import { PendingToolCallToolbar } from "./PendingToolCallToolbar"; import { StreamingToolbar } from "./StreamingToolbar"; import { TtsActiveToolbar } from "./TtsActiveToolbar"; -import { BuiltInToolNames } from "core/tools/builtIn"; // Keyboard shortcut detection utilities const isExecuteToolCallShortcut = (event: KeyboardEvent) => { @@ -39,7 +39,10 @@ const isCancelToolCallShortcut = ( // Check if a tool call is a terminal command const isTerminalCommand = (toolCallState: any) => { - return BuiltInToolNames.RunTerminalCommand; + return ( + toolCallState?.toolCall?.function?.name === + BuiltInToolNames.RunTerminalCommand + ); }; export function LumpToolbar() { @@ -170,18 +173,20 @@ export function LumpToolbar() { return ; } - // Show streaming toolbar for any streaming activity - if (isStreaming || hasRunningTerminalCommand) { + // Only show terminal streaming for actual terminal commands + if (hasRunningTerminalCommand) { const count = runningTerminalCalls.length; - const stopText = hasRunningTerminalCommand - ? `Stop Terminal${count > 1 ? ` (${count})` : ""}` - : "Stop"; - + const stopText = `Stop Terminal${count > 1 ? ` (${count})` : ""}`; return ( ); } + // Regular streaming (non-terminal) + if (isStreaming) { + return dispatch(cancelStream())} />; + } + if (pendingToolCalls.length > 0) { return ; } From ebded1fc6710a9d07090efcd7a2857dadf26e63b Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 9 Sep 2025 11:11:04 -0700 Subject: [PATCH 05/26] Add autoformatting detection for edit tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement autoformatting detection similar to Cline's approach to improve reliability of edit operations. When edit tools (multiEdit/editFile) are executed, the system now captures file content before and after save operations to detect editor autoformatting changes. Key changes: - Add `createPrettyPatch` utility using existing `myersDiff` function - Capture pre/post save content in `processDiff.ts` - Add `autoFormattingDiff` field to `ApplyState` protocol - Include autoformatting diff in tool responses with guidance for language model - Help prevent future edit failures due to undetected formatting changes 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- core/config/types.ts | 1 + core/index.d.ts | 1 + extensions/vscode/src/diff/processDiff.ts | 34 ++++++++++++--- extensions/vscode/src/util/diffUtils.ts | 41 +++++++++++++++++++ .../redux/thunks/handleApplyStateUpdate.ts | 19 ++++++++- 5 files changed, 90 insertions(+), 6 deletions(-) create mode 100644 extensions/vscode/src/util/diffUtils.ts 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/index.d.ts b/core/index.d.ts index a31e02c67..815fd9448 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1382,6 +1382,7 @@ export interface ApplyState { fileContent?: string; originalFileContent?: string; toolCallId?: string; + autoFormattingDiff?: string; } export interface StreamDiffLinesPayload { diff --git a/extensions/vscode/src/diff/processDiff.ts b/extensions/vscode/src/diff/processDiff.ts index f350e12b4..d46b4ef9d 100644 --- a/extensions/vscode/src/diff/processDiff.ts +++ b/extensions/vscode/src/diff/processDiff.ts @@ -1,7 +1,9 @@ import { Core } from "core/core"; import { DataLogger } from "core/data/log"; + import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; import { editOutcomeTracker } from "../extension/EditOutcomeTracker"; +import { createPrettyPatch, normalizeContent } from "../util/diffUtils"; import { VsCodeIde } from "../VsCodeIde"; import { VerticalDiffManager } from "./vertical/manager"; @@ -42,7 +44,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 +54,37 @@ 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 = normalizeContent(preSaveContent); + const normalizedPostSave = normalizeContent(postSaveContent); + + if (normalizedPreSave !== normalizedPostSave) { + // Auto-formatting was applied by the editor + autoFormattingDiff = createPrettyPatch( + newOrCurrentUri, + preSaveContent, + postSaveContent, + ); + } + 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/diffUtils.ts b/extensions/vscode/src/util/diffUtils.ts new file mode 100644 index 000000000..4e53fb8c6 --- /dev/null +++ b/extensions/vscode/src/util/diffUtils.ts @@ -0,0 +1,41 @@ +import { myersDiff } from "core/diff/myers"; + +/** + * Creates a pretty patch diff string similar to unified diff format + * Uses Continue's existing myersDiff function for diff calculation + */ +export function createPrettyPatch( + filename: string = "file", + oldStr: string = "", + newStr: string = "", +): string { + if (oldStr === newStr) { + return ""; + } + + const diffLines = myersDiff(oldStr, newStr); + const patchLines: string[] = []; + + for (const diffLine of diffLines) { + switch (diffLine.type) { + case "old": + patchLines.push(`-${diffLine.line}`); + break; + case "new": + patchLines.push(`+${diffLine.line}`); + break; + case "same": + patchLines.push(` ${diffLine.line}`); + break; + } + } + + return patchLines.join("\n"); +} + +/** + * Normalizes content by trimming whitespace for comparison + */ +export function normalizeContent(content: string): string { + return content.trim(); +} \ No newline at end of file diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts index 25532e750..8d7c1bec0 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -83,6 +83,24 @@ 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({ @@ -98,7 +116,6 @@ export const handleApplyStateUpdate = createAsyncThunk< ); } } - // TODO return output from edit tools so the model knows the result } } } From 1f5389f070bb368badf3ed99a8ba02449078f181 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 9 Sep 2025 14:14:35 -0700 Subject: [PATCH 06/26] updates --- extensions/vscode/src/diff/processDiff.ts | 25 +++++++++----- extensions/vscode/src/util/diffUtils.ts | 41 ----------------------- 2 files changed, 17 insertions(+), 49 deletions(-) delete mode 100644 extensions/vscode/src/util/diffUtils.ts diff --git a/extensions/vscode/src/diff/processDiff.ts b/extensions/vscode/src/diff/processDiff.ts index d46b4ef9d..eda40e162 100644 --- a/extensions/vscode/src/diff/processDiff.ts +++ b/extensions/vscode/src/diff/processDiff.ts @@ -1,10 +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 { createPrettyPatch, normalizeContent } from "../util/diffUtils"; import { VsCodeIde } from "../VsCodeIde"; + import { VerticalDiffManager } from "./vertical/manager"; export async function processDiff( @@ -62,16 +63,24 @@ export async function processDiff( // Detect autoformatting by comparing normalized content let autoFormattingDiff: string | undefined; - const normalizedPreSave = normalizeContent(preSaveContent); - const normalizedPostSave = normalizeContent(postSaveContent); + const normalizedPreSave = preSaveContent.trim(); + const normalizedPostSave = postSaveContent.trim(); if (normalizedPreSave !== normalizedPostSave) { // Auto-formatting was applied by the editor - autoFormattingDiff = createPrettyPatch( - newOrCurrentUri, - preSaveContent, - postSaveContent, - ); + 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", { diff --git a/extensions/vscode/src/util/diffUtils.ts b/extensions/vscode/src/util/diffUtils.ts deleted file mode 100644 index 4e53fb8c6..000000000 --- a/extensions/vscode/src/util/diffUtils.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { myersDiff } from "core/diff/myers"; - -/** - * Creates a pretty patch diff string similar to unified diff format - * Uses Continue's existing myersDiff function for diff calculation - */ -export function createPrettyPatch( - filename: string = "file", - oldStr: string = "", - newStr: string = "", -): string { - if (oldStr === newStr) { - return ""; - } - - const diffLines = myersDiff(oldStr, newStr); - const patchLines: string[] = []; - - for (const diffLine of diffLines) { - switch (diffLine.type) { - case "old": - patchLines.push(`-${diffLine.line}`); - break; - case "new": - patchLines.push(`+${diffLine.line}`); - break; - case "same": - patchLines.push(` ${diffLine.line}`); - break; - } - } - - return patchLines.join("\n"); -} - -/** - * Normalizes content by trimming whitespace for comparison - */ -export function normalizeContent(content: string): string { - return content.trim(); -} \ No newline at end of file From f7e91eccc11b21bc42bc4a6aac8946938d8ff416 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 8 Sep 2025 22:01:14 +0530 Subject: [PATCH 07/26] feat(cli): message queing --- extensions/cli/src/stream/messageQueue.ts | 57 +++++++++++++++++++++++ extensions/cli/src/ui/UserInput.tsx | 27 +++++------ extensions/cli/src/ui/hooks/useChat.ts | 13 ++++++ 3 files changed, 82 insertions(+), 15 deletions(-) create mode 100644 extensions/cli/src/stream/messageQueue.ts diff --git a/extensions/cli/src/stream/messageQueue.ts b/extensions/cli/src/stream/messageQueue.ts new file mode 100644 index 000000000..d91f2d398 --- /dev/null +++ b/extensions/cli/src/stream/messageQueue.ts @@ -0,0 +1,57 @@ +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 { + private queue: QueuedMessage[] = []; + private inputHistory: InputHistory | undefined; + + 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, + }); + + return true; + } + + public getLatestMessage() { + if (this.queue.length === 0) return undefined; + const latestMessage = this.queue.shift(); + logger.debug("MessageQueue: Message dequeued", { + queueLength: this.queue.length, + }); + this.inputHistory?.addEntry(latestMessage!.message); + return latestMessage; + } + + getQueueLength(): number { + return this.queue.length; + } +} + +export const messageQueue = new MessageQueue(); diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 4b5deb5bc..97b04949a 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"; @@ -515,7 +516,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 +524,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) { + // Process message later when LLM has responded + 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); @@ -647,15 +653,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/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 9b9cc5871..ed8fa2cd4 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -11,6 +11,7 @@ import { updateSessionHistory, } from "../../session.js"; import { handleSlashCommands } from "../../slashCommands.js"; +import { messageQueue } from "../../stream/messageQueue.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; import { formatError } from "../../util/formatError.js"; import { logger } from "../../util/logger.js"; @@ -306,6 +307,16 @@ 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 latestQueuedMessage = messageQueue.getLatestMessage()?.message; + if (latestQueuedMessage) { + logger.debug("processing queued message", { latestQueuedMessage }); + await new Promise((resolve) => setTimeout(resolve, 100)); + // Note: InputHistory entry was already added when the message was first submitted + await handleUserMessage(latestQueuedMessage); + } } }; @@ -484,6 +495,8 @@ export function useChat({ const newHistory = [...currentChatHistory, newUserMessage]; setChatHistory(newHistory); + logger.debug("debug1 streaming started again"); + // Execute the streaming response await executeStreamingResponse(newHistory, currentCompactionIndex); }; From 04d680ac006188cc2080d784c46164946c1790aa Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Mon, 8 Sep 2025 22:06:43 +0530 Subject: [PATCH 08/26] comment --- extensions/cli/src/ui/hooks/useChat.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index ed8fa2cd4..72467fbf4 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -313,8 +313,7 @@ export function useChat({ const latestQueuedMessage = messageQueue.getLatestMessage()?.message; if (latestQueuedMessage) { logger.debug("processing queued message", { latestQueuedMessage }); - await new Promise((resolve) => setTimeout(resolve, 100)); - // Note: InputHistory entry was already added when the message was first submitted + await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui await handleUserMessage(latestQueuedMessage); } } From 4c7c2954333592cb6ddfd6b63e05c16f0ada9642 Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Mon, 8 Sep 2025 15:55:03 -0700 Subject: [PATCH 09/26] queued messages show up in chat --- extensions/cli/src/stream/messageQueue.ts | 48 ++++- extensions/cli/src/ui/TUIChat.tsx | 2 + .../src/ui/components/StaticChatContent.tsx | 14 +- extensions/cli/src/ui/hooks/useChat.ts | 169 +++++++++++++----- 4 files changed, 177 insertions(+), 56 deletions(-) diff --git a/extensions/cli/src/stream/messageQueue.ts b/extensions/cli/src/stream/messageQueue.ts index d91f2d398..50e4fb12e 100644 --- a/extensions/cli/src/stream/messageQueue.ts +++ b/extensions/cli/src/stream/messageQueue.ts @@ -1,3 +1,4 @@ +import { EventEmitter } from "events"; import { InputHistory } from "../util/inputHistory.js"; import { logger } from "../util/logger.js"; @@ -14,10 +15,14 @@ export interface MessageProcessor { /** * A queue to store messages that need to be processed later */ -class MessageQueue { +class MessageQueue extends EventEmitter { private queue: QueuedMessage[] = []; private inputHistory: InputHistory | undefined; + constructor() { + super(); + } + async enqueueMessage( message: string, imageMap?: Map, @@ -36,17 +41,48 @@ class MessageQueue { queueLength: this.queue.length, }); + // Emit event for UI to show the queued message + this.emit("messageQueued", queuedMessage); + return true; } - public getLatestMessage() { + public getAllQueuedMessages() { if (this.queue.length === 0) return undefined; - const latestMessage = this.queue.shift(); - logger.debug("MessageQueue: Message dequeued", { + + // 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, }); - this.inputHistory?.addEntry(latestMessage!.message); - return latestMessage; + + return result; + } + + public getLatestMessage() { + return this.getAllQueuedMessages(); } getQueueLength(): number { diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index a60ec85b4..554e36513 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -188,6 +188,7 @@ const TUIChat: React.FC = ({ inputMode, activePermissionRequest, wasInterrupted, + queuedMessages, handleUserMessage, handleInterrupt, handleFileAttached, @@ -282,6 +283,7 @@ const TUIChat: React.FC = ({ model={services.model?.model || undefined} mcpService={services.mcp?.mcpService || undefined} chatHistory={chatHistory} + queuedMessages={queuedMessages} renderMessage={renderMessage} refreshTrigger={staticRefreshTrigger} /> diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index 4c1c9f133..ee0012a46 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -1,9 +1,10 @@ import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; -import { Box, Static, useStdout } from "ink"; +import { Box, Static, Text, useStdout } from "ink"; import React, { useCallback, useEffect, useRef, useState } from "react"; import type { ChatHistoryItem } from "../../../../../core/index.js"; import type { MCPService } from "../../services/MCPService.js"; +import type { QueuedMessage } from "../../stream/messageQueue.js"; import { useTerminalSize } from "../hooks/useTerminalSize.js"; import { IntroMessage } from "../IntroMessage.js"; @@ -13,6 +14,7 @@ interface StaticChatContentProps { model?: ModelConfig; mcpService?: MCPService; chatHistory: ChatHistoryItem[]; + queuedMessages?: QueuedMessage[]; renderMessage: (item: ChatHistoryItem, index: number) => 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.ts b/extensions/cli/src/ui/hooks/useChat.ts index 72467fbf4..83748d3dd 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -11,7 +11,7 @@ import { updateSessionHistory, } from "../../session.js"; import { handleSlashCommands } from "../../slashCommands.js"; -import { messageQueue } from "../../stream/messageQueue.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"; @@ -167,6 +167,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 () => { @@ -310,11 +326,26 @@ export function useChat({ // 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 latestQueuedMessage = messageQueue.getLatestMessage()?.message; - if (latestQueuedMessage) { + const queuedMessageData = messageQueue.getLatestMessage(); + if (queuedMessageData) { + const { message: latestQueuedMessage, imageMap } = queuedMessageData; logger.debug("processing queued message", { latestQueuedMessage }); + + // Clear all queued messages from display since we're processing them all together + setQueuedMessages([]); + + // Add the queued message to chat history so it shows in the GUI + const formattedQueuedMessage = await formatMessageWithFiles( + latestQueuedMessage, + [], // No attached files for queued messages + imageMap, + ); + setChatHistory((prev) => [...prev, formattedQueuedMessage]); + await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui - await handleUserMessage(latestQueuedMessage); + + // Process the queued message using the internal processing logic without re-adding to history + await processQueuedMessage(latestQueuedMessage, imageMap); } } }; @@ -408,20 +439,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, @@ -450,27 +472,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, @@ -479,25 +483,89 @@ 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) { + // 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([]); + } - logger.debug("debug1 streaming started again"); + // Check if auto-compacting is needed BEFORE adding user message + const { currentChatHistory, currentCompactionIndex } = + await handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex, + setChatHistory: setChatHistory, + setCompactionIndex, + }); - // Execute the streaming response - await executeStreamingResponse(newHistory, currentCompactionIndex); + // Add the formatted user message to history + const newHistory = [...currentChatHistory, newUserMessage]; + setChatHistory(newHistory); + + logger.debug("debug1 streaming started again"); + + // Execute the streaming response + await executeStreamingResponse(newHistory, currentCompactionIndex); + } else { + // For queued messages, chat history is already updated + // Check if auto-compacting is needed with current history + const { currentChatHistory, currentCompactionIndex } = + await handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex, + setChatHistory: setChatHistory, + setCompactionIndex, + }); + + // Execute the streaming response with the current history (which already includes the queued message) + await executeStreamingResponse( + currentChatHistory, + 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 = () => { @@ -549,6 +617,8 @@ export function useChat({ additionalRules, ); setChatHistory(newHistory); + // Clear any queued messages when resetting chat + setQueuedMessages([]); }; const handleToolPermissionResponse = async ( @@ -626,6 +696,7 @@ export function useChat({ attachedFiles, activePermissionRequest, wasInterrupted, + queuedMessages, handleUserMessage, handleInterrupt, handleFileAttached, From 066068765341fa02b927336052455ab782a13900 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Tue, 9 Sep 2025 23:38:44 -0700 Subject: [PATCH 10/26] fix: :bug: Resolve comments from review --- core/core.ts | 4 +- core/util/messageContent.ts | 15 + .../Lump/LumpToolbar/StreamingToolbar.tsx | 6 +- gui/src/redux/util/constructMessages.test.ts | 343 ++++++++++++++++++ gui/src/redux/util/constructMessages.ts | 28 +- 5 files changed, 373 insertions(+), 23 deletions(-) diff --git a/core/core.ts b/core/core.ts index 2357d8687..8aa6a55ae 100644 --- a/core/core.ts +++ b/core/core.ts @@ -29,6 +29,7 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { isProcessBackgrounded, + killTerminalProcess, markProcessAsBackgrounded, } from "./util/processTerminalStates"; import { getSymbolsForManyFiles } from "./util/treeSitter"; @@ -1057,9 +1058,6 @@ export class Core { ); on("process/killTerminalProcess", async ({ data: { toolCallId } }) => { - const { killTerminalProcess } = await import( - "./util/processTerminalStates.js" - ); await killTerminalProcess(toolCallId); }); 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/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx index 66d35f3cb..d67187161 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx @@ -12,15 +12,11 @@ export function StreamingToolbar({ }: StreamingToolbarProps) { const jetbrains = isJetBrains(); - const handleStop = () => { - onStop(); - }; - return (
{displayText} diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts index d4c5e572e..b79d8da14 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[\s\S]*\[Status: completed\][\s\S]*\n\n[\s\S]*Warning.*\[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 666a1bfd9..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, @@ -17,25 +18,16 @@ import { import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools"; import { SystemMessageToolsFramework } from "core/tools/systemMessageTools/types"; import { findLast, findLastIndex } from "core/util/findLast"; -import { normalizeToMessageParts } from "core/util/messageContent"; +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 -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"); -} interface MessageWithContextItems { ctxItems: ContextItemWithId[]; message: ChatMessage; @@ -146,8 +138,14 @@ export function constructMessages( if (toolCallState?.status === "canceled") { content = CANCELLED_TOOL_CALL_MESSAGE; - } else if (toolCallState?.output) { + } 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); } msgs.push({ From ab8babbb097281efed01746e2ebc4291bb32d82a Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Tue, 9 Sep 2025 23:47:18 -0700 Subject: [PATCH 11/26] fix: :bug: Fix failing test --- gui/src/redux/util/constructMessages.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/redux/util/constructMessages.test.ts b/gui/src/redux/util/constructMessages.test.ts index b79d8da14..6fd213a75 100644 --- a/gui/src/redux/util/constructMessages.test.ts +++ b/gui/src/redux/util/constructMessages.test.ts @@ -840,7 +840,7 @@ describe("constructMessages", () => { expect(toolMessage.content).toContain("[Status: warning]"); // Should use renderContextItemsWithStatus format with double newlines between items expect(toolMessage.content).toMatch( - /file1\.txt[\s\S]*\[Status: completed\][\s\S]*\n\n[\s\S]*Warning.*\[Status: warning\]/, + /file1\.txt\nfile2\.txt\n\[Status: completed\]\n\nWarning: deprecated flag\n\[Status: warning\]/, ); }); From 2377a791d0d68d95144351a4c534310edacebf9c Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 10 Sep 2025 18:31:32 +0530 Subject: [PATCH 12/26] remove log and fix eslint --- extensions/cli/src/ui/hooks/useChat.ts | 40 ++++++++++++-------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 83748d3dd..6d2c98ad1 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -484,7 +484,25 @@ export function useChat({ } // For non-queued messages, format and add to chat history - if (!isQueuedMessage) { + if (isQueuedMessage) { + // For queued messages, chat history is already updated + // Check if auto-compacting is needed with current history + const { currentChatHistory, currentCompactionIndex } = + await handleAutoCompaction({ + chatHistory, + model, + llmApi, + compactionIndex, + setChatHistory: setChatHistory, + setCompactionIndex, + }); + + // Execute the streaming response with the current history (which already includes the queued message) + await executeStreamingResponse( + currentChatHistory, + currentCompactionIndex, + ); + } else { // Format message with attached files and images logger.debug("Processing message with images", { hasImages: !!(imageMap && imageMap.size > 0), @@ -516,28 +534,8 @@ export function useChat({ const newHistory = [...currentChatHistory, newUserMessage]; setChatHistory(newHistory); - logger.debug("debug1 streaming started again"); - // Execute the streaming response await executeStreamingResponse(newHistory, currentCompactionIndex); - } else { - // For queued messages, chat history is already updated - // Check if auto-compacting is needed with current history - const { currentChatHistory, currentCompactionIndex } = - await handleAutoCompaction({ - chatHistory, - model, - llmApi, - compactionIndex, - setChatHistory: setChatHistory, - setCompactionIndex, - }); - - // Execute the streaming response with the current history (which already includes the queued message) - await executeStreamingResponse( - currentChatHistory, - currentCompactionIndex, - ); } }; From 9cc3d69e4dfc467fefd9cd98b90ed9be64df8468 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 10 Sep 2025 18:15:23 -0700 Subject: [PATCH 13/26] fix: edit impl --- .../redux/thunks/handleApplyStateUpdate.ts | 27 +++++++++++++++++++ gui/src/util/clientTools/editImpl.ts | 14 +++------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts index 25532e750..1a28cc3d4 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -89,6 +89,33 @@ export const handleApplyStateUpdate = createAsyncThunk< 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 edited ${applyState.filepath}. To continue working with the file, read it again to see the most up-to-date contents`, + description: "", + hidden: true, + }, + ], + }), + ); } void dispatch( diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index cefc6832f..967b3cc8d 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 }; }; From 0136215913e572bbd4ee3ffa81b93bf4456a946e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 10 Sep 2025 18:20:12 -0700 Subject: [PATCH 14/26] fix: prettier --- gui/src/util/clientTools/editImpl.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index 967b3cc8d..ccc7cc3fa 100644 --- a/gui/src/util/clientTools/editImpl.ts +++ b/gui/src/util/clientTools/editImpl.ts @@ -21,7 +21,7 @@ export const editToolImpl: ClientToolImpl = async ( filepath, extras.ideMessenger.ide, ); - + if (!firstUriMatch) { const openFiles = await extras.ideMessenger.ide.getOpenFiles(); for (const uri of openFiles) { From 602a8e9f11c7164a835ba61f84e460564e05ba79 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 11 Sep 2025 01:41:52 +0000 Subject: [PATCH 15/26] build(deps-dev): bump vite in /packages/terminal-security Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 7.1.4 to 7.1.5. - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v7.1.5/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 7.1.5 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- packages/terminal-security/package-lock.json | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) 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" From d9dbbe636af8c3b756443c0681af5849b652f94d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 10 Sep 2025 19:05:05 -0700 Subject: [PATCH 16/26] Update gui/src/redux/thunks/handleApplyStateUpdate.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- gui/src/redux/thunks/handleApplyStateUpdate.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts index 1a28cc3d4..5080b13c2 100644 --- a/gui/src/redux/thunks/handleApplyStateUpdate.ts +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -109,7 +109,7 @@ export const handleApplyStateUpdate = createAsyncThunk< contextItems: [ { name: "Edit Failed", - content: `Failed to edited ${applyState.filepath}. To continue working with the file, read it again to see the most up-to-date contents`, + 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, }, From a3e6b9b136f5b25e1b0de0a471ca8315d531ad1b Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 10 Sep 2025 21:44:11 -0700 Subject: [PATCH 17/26] chore: format --- extensions/vscode/src/diff/processDiff.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/diff/processDiff.ts b/extensions/vscode/src/diff/processDiff.ts index eda40e162..cbff6f4a3 100644 --- a/extensions/vscode/src/diff/processDiff.ts +++ b/extensions/vscode/src/diff/processDiff.ts @@ -70,7 +70,7 @@ export async function processDiff( // Auto-formatting was applied by the editor const diffLines = myersDiff(preSaveContent, postSaveContent); autoFormattingDiff = diffLines - .map(line => { + .map((line) => { switch (line.type) { case "old": return `-${line.line}`; From fc3e72dfe1c624ef5f2776e4cf83a6d2c54b578e Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Sep 2025 12:50:05 +0530 Subject: [PATCH 18/26] feat: do not show context fill display when model changes --- .../components/mainInput/ContextStatus.tsx | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx index 4ed048d86..abf06c19c 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 ( From cda58d24678031b8def0a38305b112c9585ec52c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 11 Sep 2025 09:09:21 +0000 Subject: [PATCH 19/26] build(deps): bump continuedev/continue from 1.4.38 to 1.4.39 Bumps [continuedev/continue](https://github.com/continuedev/continue) from 1.4.38 to 1.4.39. - [Release notes](https://github.com/continuedev/continue/releases) - [Commits](https://github.com/continuedev/continue/compare/b3f4b82600f603ca28c65a319b80ec36c4644ed7...5dc7a050db441934c26eb910b8433291f627db7f) --- updated-dependencies: - dependency-name: continuedev/continue dependency-version: 1.4.39 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .github/workflows/continue-detailed-review.yaml | 2 +- .github/workflows/continue-general-review.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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" From 49655ef7d9511ac0eddff97ffc1ee664c0d634d3 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Sep 2025 19:09:52 +0530 Subject: [PATCH 20/26] fix lint --- extensions/cli/src/stream/messageQueue.ts | 1 + extensions/cli/src/ui/hooks/useChat.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/extensions/cli/src/stream/messageQueue.ts b/extensions/cli/src/stream/messageQueue.ts index 50e4fb12e..3703a4644 100644 --- a/extensions/cli/src/stream/messageQueue.ts +++ b/extensions/cli/src/stream/messageQueue.ts @@ -1,4 +1,5 @@ import { EventEmitter } from "events"; + import { InputHistory } from "../util/inputHistory.js"; import { logger } from "../util/logger.js"; diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 6d2c98ad1..37ce38266 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines */ import type { ChatHistoryItem, Session } from "core/index.js"; import { useApp } from "ink"; import { useEffect, useRef, useState } from "react"; From 878464fcacf79defb55a175ea02b79f3c0968e4a Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 11 Sep 2025 19:36:30 +0530 Subject: [PATCH 21/26] add tests --- .../cli/src/stream/messageQueue.test.ts | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 extensions/cli/src/stream/messageQueue.test.ts 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"); + }); +}); From 21f78907c357c7a8e817c84ced2b54196b2ec0c7 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 11 Sep 2025 10:12:20 -0700 Subject: [PATCH 22/26] feat: invokable rule --- core/commands/slash/ruleBlockSlashCommand.ts | 13 +++++++++++++ core/config/yaml/loadYaml.ts | 17 ++++++++++++++++- core/config/yaml/yamlToContinueConfig.ts | 2 ++ core/index.d.ts | 1 + packages/config-yaml/src/schemas/index.ts | 1 + 5 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 core/commands/slash/ruleBlockSlashCommand.ts diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts new file mode 100644 index 000000000..82670e022 --- /dev/null +++ b/core/commands/slash/ruleBlockSlashCommand.ts @@ -0,0 +1,13 @@ +import { RuleWithSource, SlashCommandWithSource } from "../.."; + +export function convertRuleBlockToSlashCommand( + rule: RuleWithSource, +): SlashCommandWithSource { + return { + name: rule.name || "Unnamed Rule", + description: rule.description ?? "", + prompt: rule.rule, + source: "invokable-rule", + promptFile: rule.ruleFile, + }; +} \ No newline at end of file diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 65cb5e0ff..3a634ddcb 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/index.d.ts b/core/index.d.ts index 6e80bc5d3..073a55ae5 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1807,6 +1807,7 @@ export interface RuleWithSource { description?: string; ruleFile?: string; alwaysApply?: boolean; + invokable?: boolean; } export interface CompleteOnboardingPayload { mode: OnboardingModes; 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]); From 91a475a2906787aba9fa93241f5e978d72ba415e Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 11 Sep 2025 10:34:00 -0700 Subject: [PATCH 23/26] test: invokable rules --- .../slash/ruleBlockSlashCommand.vitest.ts | 78 +++++++++++++++++++ .../__tests__/test-files/invokable-rules.yaml | 23 ++++++ 2 files changed, 101 insertions(+) create mode 100644 core/commands/slash/ruleBlockSlashCommand.vitest.ts create mode 100644 packages/config-yaml/src/__tests__/test-files/invokable-rules.yaml diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts new file mode 100644 index 000000000..2d63e7046 --- /dev/null +++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts @@ -0,0 +1,78 @@ +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("Unnamed Rule"); + expect(result.prompt).toBe("Review this code"); + }); + + 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"); + }); +}); \ No newline at end of file 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 From e569e3a0c6f63cbc0bf14abff55e5a22c728ff54 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 11 Sep 2025 10:34:37 -0700 Subject: [PATCH 24/26] fix: formatting --- core/commands/slash/ruleBlockSlashCommand.ts | 2 +- core/commands/slash/ruleBlockSlashCommand.vitest.ts | 2 +- core/config/yaml/loadYaml.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts index 82670e022..9484f0761 100644 --- a/core/commands/slash/ruleBlockSlashCommand.ts +++ b/core/commands/slash/ruleBlockSlashCommand.ts @@ -10,4 +10,4 @@ export function convertRuleBlockToSlashCommand( source: "invokable-rule", promptFile: rule.ruleFile, }; -} \ No newline at end of file +} diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts index 2d63e7046..ebaafb5e2 100644 --- a/core/commands/slash/ruleBlockSlashCommand.vitest.ts +++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts @@ -75,4 +75,4 @@ describe("convertRuleBlockToSlashCommand", () => { expect(result.source).toBe("invokable-rule"); }); -}); \ No newline at end of file +}); diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 3a634ddcb..19202e7fd 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -211,7 +211,7 @@ async function configYamlToContinueConfig(options: { for (const rule of config.rules ?? []) { const convertedRule = convertYamlRuleToContinueRule(rule); continueConfig.rules.push(convertedRule); - + // Convert invokable rules to slash commands if (convertedRule.invokable) { try { From 2d518abf2b46832af4ff1907a974564177b3c617 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 11 Sep 2025 12:33:46 -0700 Subject: [PATCH 25/26] improv: naming and truncation --- core/commands/slash/ruleBlockSlashCommand.ts | 2 +- .../slash/ruleBlockSlashCommand.vitest.ts | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts index 9484f0761..852d131a8 100644 --- a/core/commands/slash/ruleBlockSlashCommand.ts +++ b/core/commands/slash/ruleBlockSlashCommand.ts @@ -4,7 +4,7 @@ export function convertRuleBlockToSlashCommand( rule: RuleWithSource, ): SlashCommandWithSource { return { - name: rule.name || "Unnamed Rule", + name: rule.name || (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule), description: rule.description ?? "", prompt: rule.rule, source: "invokable-rule", diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts index ebaafb5e2..45e9ae316 100644 --- a/core/commands/slash/ruleBlockSlashCommand.vitest.ts +++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts @@ -33,10 +33,23 @@ describe("convertRuleBlockToSlashCommand", () => { const result = convertRuleBlockToSlashCommand(rule); - expect(result.name).toBe("Unnamed 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", From ae9f87418da80c297de3f757b8755bb5e539d69a Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 11 Sep 2025 12:37:48 -0700 Subject: [PATCH 26/26] fix: formatting --- core/commands/slash/ruleBlockSlashCommand.ts | 4 +++- core/commands/slash/ruleBlockSlashCommand.vitest.ts | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/core/commands/slash/ruleBlockSlashCommand.ts b/core/commands/slash/ruleBlockSlashCommand.ts index 852d131a8..d907768cb 100644 --- a/core/commands/slash/ruleBlockSlashCommand.ts +++ b/core/commands/slash/ruleBlockSlashCommand.ts @@ -4,7 +4,9 @@ export function convertRuleBlockToSlashCommand( rule: RuleWithSource, ): SlashCommandWithSource { return { - name: rule.name || (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule), + name: + rule.name || + (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule), description: rule.description ?? "", prompt: rule.rule, source: "invokable-rule", diff --git a/core/commands/slash/ruleBlockSlashCommand.vitest.ts b/core/commands/slash/ruleBlockSlashCommand.vitest.ts index 45e9ae316..ccbc2df4f 100644 --- a/core/commands/slash/ruleBlockSlashCommand.vitest.ts +++ b/core/commands/slash/ruleBlockSlashCommand.vitest.ts @@ -47,7 +47,9 @@ describe("convertRuleBlockToSlashCommand", () => { 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"); + expect(result.prompt).toBe( + "This is a very long rule text that should be truncated", + ); }); it("should handle a rule without description", () => {