From 58cb7815ca9f85fed632c77e6be8944973a4b04c Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sat, 23 Aug 2025 20:07:59 -0700 Subject: [PATCH 1/5] 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 2/5] 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 3/5] 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 066068765341fa02b927336052455ab782a13900 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Tue, 9 Sep 2025 23:38:44 -0700 Subject: [PATCH 4/5] 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 5/5] 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\]/, ); });