Merge pull request #7368 from chezsmithy/feat-stop-terminal

feat: ✨ Add ability to stop foreground terminal commands
This commit is contained in:
Dallin Romney 2025-09-10 18:39:24 -07:00 • committed by GitHub
commit 5dc7a050db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 1027 additions and 127 deletions

View file

@ -29,8 +29,9 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
killTerminalProcess,
markProcessAsBackgrounded,
} from "./util/processTerminalBackgroundStates";
} from "./util/processTerminalStates";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -1062,6 +1063,10 @@ export class Core {
},
);
on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
await killTerminalProcess(toolCallId);
});
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;

View file

@ -313,5 +313,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
"process/killTerminalProcess": [{ toolCallId: string }, void];
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
};

View file

@ -86,6 +86,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
"process/killTerminalProcess",
];
// Message types to pass through from core to webview

View file

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

View file

@ -12,7 +12,7 @@ import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { IDE, ToolExtras } from "../..";
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
import * as processTerminalStates from "../../util/processTerminalStates";
import { runTerminalCommandImpl } from "./runTerminalCommand";
import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
@ -39,12 +39,8 @@ describe("runTerminalCommandImpl", () => {
vi.resetAllMocks();
// Setup backgrounded processes handling - don't mock, just make sure it's empty
// Get any processes that might be already tracked and clear them
const processMap = (processBackgroundStates as any)
.processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === "function") {
processMap.clear();
}
// Clear any processes that might be already tracked
processTerminalStates.clearAllBackgroundProcesses();
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));

View file

@ -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":

View file

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

View file

@ -1,17 +0,0 @@
// Track which processes have been backgrounded
const processTerminalBackgroundStates = new Map<string, boolean>();
// 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);
}

View file

@ -0,0 +1,367 @@
import { ChildProcess } from "child_process";
import {
clearAllBackgroundProcesses,
getAllBackgroundedProcessIds,
getAllRunningProcessIds,
getRunningProcess,
isProcessBackgrounded,
isProcessRunning,
killAllRunningTerminalProcesses,
killMultipleTerminalProcesses,
killTerminalProcess,
markProcessAsBackgrounded,
markProcessAsRunning,
removeBackgroundedProcess,
removeRunningProcess,
updateProcessOutput,
} from "./processTerminalStates";
// Mock ChildProcess
const createMockProcess = (
pid: number = 123,
killed: boolean = false,
): jest.Mocked<ChildProcess> => {
const mockProcess = {
pid,
killed,
kill: jest.fn(),
} as unknown as jest.Mocked<ChildProcess>;
// Make kill() update the killed property
mockProcess.kill.mockImplementation(() => {
(mockProcess as any).killed = true;
return true;
});
return mockProcess;
};
describe("processTerminalStates", () => {
beforeEach(() => {
// Clear all running processes
const runningIds = getAllRunningProcessIds();
runningIds.forEach((id) => removeRunningProcess(id));
// Clear all backgrounded processes
const backgroundedIds = getAllBackgroundedProcessIds();
backgroundedIds.forEach((id) => removeBackgroundedProcess(id));
// Clear all timers
jest.clearAllTimers();
});
test("should mark a process as backgrounded", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
});
test("should correctly identify non-backgrounded processes", () => {
const toolCallId = "test-123";
const anotherToolCallId = "test-456";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
});
test("should remove a process from backgrounded state", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test("should handle removing non-existent processes", () => {
const toolCallId = "test-123";
// Should not throw an error
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test("should handle multiple processes", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const toolCallId3 = "test-789";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
expect(isProcessBackgrounded(toolCallId1)).toBe(true);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
expect(isProcessBackgrounded(toolCallId3)).toBe(false);
removeBackgroundedProcess(toolCallId1);
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
});
describe("foreground process functions", () => {
test("should mark a process as running", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
const mockCallback = jest.fn();
const initialOutput = "initial output";
markProcessAsRunning(
toolCallId,
mockProcess,
mockCallback,
initialOutput,
);
expect(isProcessRunning(toolCallId)).toBe(true);
expect(getRunningProcess(toolCallId)).toBe(mockProcess);
});
test("should handle process without callback or initial output", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
expect(getRunningProcess(toolCallId)).toBe(mockProcess);
});
test("should correctly identify non-running processes", () => {
const toolCallId = "test-123";
const anotherToolCallId = "test-456";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
expect(isProcessRunning(anotherToolCallId)).toBe(false);
});
test("should update process output", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
const initialOutput = "initial";
const updatedOutput = "updated output";
markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput);
updateProcessOutput(toolCallId, updatedOutput);
// We can't directly test the output value, but we can ensure the function doesn't throw
expect(() =>
updateProcessOutput(toolCallId, updatedOutput),
).not.toThrow();
});
test("should handle updating output for non-existent process", () => {
const toolCallId = "non-existent";
expect(() =>
updateProcessOutput(toolCallId, "some output"),
).not.toThrow();
});
test("should remove a process from running state", () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
removeRunningProcess(toolCallId);
expect(isProcessRunning(toolCallId)).toBe(false);
expect(getRunningProcess(toolCallId)).toBeUndefined();
});
test("should handle removing non-existent running processes", () => {
const toolCallId = "test-123";
expect(() => removeRunningProcess(toolCallId)).not.toThrow();
expect(isProcessRunning(toolCallId)).toBe(false);
});
test("should return undefined for non-existent running process", () => {
const toolCallId = "non-existent";
expect(getRunningProcess(toolCallId)).toBeUndefined();
});
});
describe("terminal command cancellation", () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test("should cancel a running terminal command", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
expect(isProcessRunning(toolCallId)).toBe(true);
await killTerminalProcess(toolCallId);
expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
expect(isProcessRunning(toolCallId)).toBe(false);
});
test("should handle cancelling non-existent process", async () => {
const toolCallId = "non-existent";
await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow();
});
test("should handle cancelling already killed process", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess(123, true); // Already killed
markProcessAsRunning(toolCallId, mockProcess);
await killTerminalProcess(toolCallId);
expect(mockProcess.kill).not.toHaveBeenCalled();
});
test("should send SIGKILL after timeout if process not killed", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
// Mock kill to not actually set killed=true for SIGTERM
mockProcess.kill.mockImplementation((signal) => {
if (signal === "SIGKILL") {
(mockProcess as any).killed = true;
}
return true;
});
markProcessAsRunning(toolCallId, mockProcess);
const cancelPromise = killTerminalProcess(toolCallId);
// Fast-forward time to trigger the timeout
jest.advanceTimersByTime(5000);
await cancelPromise;
expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL");
});
test("should not send SIGKILL if process was already killed", async () => {
const toolCallId = "test-123";
const mockProcess = createMockProcess();
markProcessAsRunning(toolCallId, mockProcess);
const cancelPromise = killTerminalProcess(toolCallId);
// Fast-forward time to trigger the timeout
jest.advanceTimersByTime(5000);
await cancelPromise;
expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL
});
});
describe("utility functions", () => {
test("should get all running process IDs", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const mockProcess1 = createMockProcess(123);
const mockProcess2 = createMockProcess(456);
markProcessAsRunning(toolCallId1, mockProcess1);
markProcessAsRunning(toolCallId2, mockProcess2);
const runningIds = getAllRunningProcessIds();
expect(runningIds).toContain(toolCallId1);
expect(runningIds).toContain(toolCallId2);
expect(runningIds).toHaveLength(2);
});
test("should get all backgrounded process IDs", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
const backgroundedIds = getAllBackgroundedProcessIds();
expect(backgroundedIds).toContain(toolCallId1);
expect(backgroundedIds).toContain(toolCallId2);
expect(backgroundedIds).toHaveLength(2);
});
test("should return empty arrays when no processes", () => {
expect(getAllRunningProcessIds()).toEqual([]);
expect(getAllBackgroundedProcessIds()).toEqual([]);
});
test("should cancel multiple terminal commands", async () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const mockProcess1 = createMockProcess(123);
const mockProcess2 = createMockProcess(456);
markProcessAsRunning(toolCallId1, mockProcess1);
markProcessAsRunning(toolCallId2, mockProcess2);
await killMultipleTerminalProcesses([toolCallId1, toolCallId2]);
expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
expect(isProcessRunning(toolCallId1)).toBe(false);
expect(isProcessRunning(toolCallId2)).toBe(false);
});
test("should cancel all running terminal commands", async () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const mockProcess1 = createMockProcess(123);
const mockProcess2 = createMockProcess(456);
markProcessAsRunning(toolCallId1, mockProcess1);
markProcessAsRunning(toolCallId2, mockProcess2);
const cancelledIds = await killAllRunningTerminalProcesses();
expect(cancelledIds).toContain(toolCallId1);
expect(cancelledIds).toContain(toolCallId2);
expect(cancelledIds).toHaveLength(2);
expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
expect(isProcessRunning(toolCallId1)).toBe(false);
expect(isProcessRunning(toolCallId2)).toBe(false);
});
test("should return empty array when no running commands to cancel", async () => {
const cancelledIds = await killAllRunningTerminalProcesses();
expect(cancelledIds).toEqual([]);
});
test("should clear all background processes", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
expect(getAllBackgroundedProcessIds()).toHaveLength(2);
clearAllBackgroundProcesses();
expect(getAllBackgroundedProcessIds()).toEqual([]);
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
expect(isProcessBackgrounded(toolCallId2)).toBe(false);
});
});
});

View file

@ -0,0 +1,119 @@
import { ChildProcess } from "child_process";
// Track which processes have been backgrounded
const processTerminalBackgroundStates = new Map<string, boolean>();
// Track which foreground processes are currently running
interface RunningProcessInfo {
process: ChildProcess;
onPartialOutput?: (params: {
toolCallId: string;
contextItems: any[];
}) => void;
currentOutput: string;
}
const processTerminalForegroundStates = new Map<string, RunningProcessInfo>();
// Background process functions (existing)
export function markProcessAsBackgrounded(toolCallId: string): void {
processTerminalBackgroundStates.set(toolCallId, true);
}
export function isProcessBackgrounded(toolCallId: string): boolean {
return processTerminalBackgroundStates.has(toolCallId);
}
export function removeBackgroundedProcess(toolCallId: string): void {
processTerminalBackgroundStates.delete(toolCallId);
}
// Foreground process functions (new)
export function markProcessAsRunning(
toolCallId: string,
process: ChildProcess,
onPartialOutput?: (params: {
toolCallId: string;
contextItems: any[];
}) => void,
currentOutput: string = "",
): void {
processTerminalForegroundStates.set(toolCallId, {
process,
onPartialOutput,
currentOutput,
});
}
export function isProcessRunning(toolCallId: string): boolean {
return processTerminalForegroundStates.has(toolCallId);
}
export function getRunningProcess(
toolCallId: string,
): ChildProcess | undefined {
const info = processTerminalForegroundStates.get(toolCallId);
return info?.process;
}
export function updateProcessOutput(toolCallId: string, output: string): void {
const info = processTerminalForegroundStates.get(toolCallId);
if (info) {
info.currentOutput = output;
}
}
export function removeRunningProcess(toolCallId: string): void {
processTerminalForegroundStates.delete(toolCallId);
}
export async function killTerminalProcess(toolCallId: string): Promise<void> {
const processInfo = processTerminalForegroundStates.get(toolCallId);
if (processInfo && !processInfo.process.killed) {
const { process } = processInfo;
process.kill("SIGTERM");
// Force kill after 5 seconds if still running
setTimeout(() => {
if (!process.killed) {
process.kill("SIGKILL");
}
}, 5000);
processTerminalForegroundStates.delete(toolCallId);
}
}
// Function to cancel multiple terminal commands at once
export async function killMultipleTerminalProcesses(
toolCallIds: string[],
): Promise<void> {
const cancelPromises = toolCallIds.map((toolCallId) =>
killTerminalProcess(toolCallId),
);
await Promise.all(cancelPromises);
}
// Function to cancel ALL currently running terminal commands
export async function killAllRunningTerminalProcesses(): Promise<string[]> {
const runningIds = getAllRunningProcessIds();
if (runningIds.length > 0) {
await killMultipleTerminalProcesses(runningIds);
}
return runningIds; // Return the IDs that were cancelled
}
// Utility functions
export function getAllRunningProcessIds(): string[] {
return Array.from(processTerminalForegroundStates.keys());
}
export function getAllBackgroundedProcessIds(): string[] {
return Array.from(processTerminalBackgroundStates.keys());
}
// Utility function for testing - clears all background process states
export function clearAllBackgroundProcesses(): void {
processTerminalBackgroundStates.clear();
}

View file

@ -146,6 +146,7 @@ class MessageTypes {
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
"process/killTerminalProcess"
)
}
}

View file

@ -1,13 +1,15 @@
import { BuiltInToolNames } from "core/tools/builtIn";
import { useContext, useEffect } from "react";
import { useSelector } from "react-redux";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import {
selectFirstPendingToolCall,
selectPendingToolCalls,
selectToolCallsByStatus,
} from "../../../../redux/selectors/selectToolCalls";
import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
import { callToolById } from "../../../../redux/thunks/callToolById";
import { cancelStream } from "../../../../redux/thunks/cancelStream";
import { logToolUsage } from "../../../../redux/util";
import { isJetBrains } from "../../../../util";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
@ -35,6 +37,14 @@ const isCancelToolCallShortcut = (
return modifierKey && event.key === "Backspace";
};
// Check if a tool call is a terminal command
const isTerminalCommand = (toolCallState: any) => {
return (
toolCallState?.toolCall?.function?.name ===
BuiltInToolNames.RunTerminalCommand
);
};
export function LumpToolbar() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
@ -55,13 +65,67 @@ export function LumpToolbar() {
);
const isApplying = applyStates.some((state) => state.status === "streaming");
// Get ALL running terminal commands
const runningToolCalls = useAppSelector((state) =>
selectToolCallsByStatus(state, "calling"),
);
const runningTerminalCalls = runningToolCalls.filter(isTerminalCommand);
const hasRunningTerminalCommand = runningTerminalCalls.length > 0;
// Simple handler: stop ALL running terminal commands
const handleStopAllTerminalCommands = async () => {
if (runningTerminalCalls.length === 0) {
return;
}
// Stop all terminal commands concurrently
const stopPromises = runningTerminalCalls.map(async (terminalCall) => {
try {
// Cancel the process on the backend
await ideMessenger.request("process/killTerminalProcess", {
toolCallId: terminalCall.toolCallId,
});
// Cancel the tool call in the UI
dispatch(
cancelToolCall({
toolCallId: terminalCall.toolCallId,
}),
);
logToolUsage(terminalCall, false, true, ideMessenger);
} catch (error) {
console.error(
`Failed to cancel terminal command ${terminalCall.toolCallId}:`,
error,
);
}
});
// Wait for all cancellations to complete
await Promise.all(stopPromises);
};
// Combined stop handler
const handleStopAction = async () => {
// Stop all terminal commands if any are running
if (hasRunningTerminalCommand) {
await handleStopAllTerminalCommands();
}
// Also stop regular streaming if it's happening
if (isStreaming) {
dispatch(cancelStream());
}
};
useEffect(() => {
if (!firstPendingToolCall) {
if (!firstPendingToolCall && !hasRunningTerminalCommand) {
return;
}
const handleToolCallKeyboardShortcuts = (event: KeyboardEvent) => {
if (isExecuteToolCallShortcut(event)) {
if (isExecuteToolCallShortcut(event) && firstPendingToolCall) {
event.preventDefault();
event.stopPropagation();
@ -71,13 +135,19 @@ export function LumpToolbar() {
} else if (isCancelToolCallShortcut(event, jetbrains)) {
event.preventDefault();
event.stopPropagation();
void dispatch(
cancelToolCall({
toolCallId: firstPendingToolCall.toolCallId,
}),
);
logToolUsage(firstPendingToolCall, false, true, ideMessenger);
if (hasRunningTerminalCommand) {
// Stop running terminal commands
void handleStopAction();
} else if (firstPendingToolCall) {
// Cancel pending tool call
void dispatch(
cancelToolCall({
toolCallId: firstPendingToolCall.toolCallId,
}),
);
logToolUsage(firstPendingToolCall, false, true, ideMessenger);
}
}
};
@ -85,7 +155,7 @@ export function LumpToolbar() {
return () => {
document.removeEventListener("keydown", handleToolCallKeyboardShortcuts);
};
}, [firstPendingToolCall]);
}, [firstPendingToolCall, hasRunningTerminalCommand, runningTerminalCalls]);
if (isApplying) {
return <IsApplyingToolbar />;
@ -103,8 +173,18 @@ export function LumpToolbar() {
return <TtsActiveToolbar />;
}
// Only show terminal streaming for actual terminal commands
if (hasRunningTerminalCommand) {
const count = runningTerminalCalls.length;
const stopText = `Stop Terminal${count > 1 ? ` (${count})` : ""}`;
return (
<StreamingToolbar onStop={handleStopAction} displayText={stopText} />
);
}
// Regular streaming (non-terminal)
if (isStreaming) {
return <StreamingToolbar />;
return <StreamingToolbar onStop={() => dispatch(cancelStream())} />;
}
if (pendingToolCalls.length > 0) {

View file

@ -1,20 +1,25 @@
import { useAppDispatch } from "../../../../redux/hooks";
import { cancelStream } from "../../../../redux/thunks/cancelStream";
import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util";
import { GeneratingIndicator } from "./GeneratingIndicator";
export function StreamingToolbar() {
interface StreamingToolbarProps {
onStop: () => void;
displayText?: string;
}
export function StreamingToolbar({
onStop,
displayText = "Stop",
}: StreamingToolbarProps) {
const jetbrains = isJetBrains();
const dispatch = useAppDispatch();
return (
<div className="flex w-full items-center justify-between">
<GeneratingIndicator />
<div
onClick={() => void dispatch(cancelStream())}
onClick={onStop}
className="text-2xs cursor-pointer px-1.5 py-0.5 hover:brightness-125"
>
<span className="text-description">Stop</span>
<span className="text-description">{displayText}</span>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
<span className="text-description-muted ml-1 opacity-75">
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()}⌫

View file

@ -46,7 +46,7 @@ export const moveTerminalProcessToBackground = createAsyncThunk<
{
name: "Terminal",
description: "Terminal command output",
content: existingContent + (existingContent ? "\n\n" : "") + status,
content: existingContent,
status: status,
},
];

View file

@ -8,6 +8,7 @@ import {
ToolResultChatMessage,
UserChatMessage,
} from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
@ -712,4 +713,346 @@ describe("constructMessages", () => {
expect(messages[0].content).toContain("Base System Message");
expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule);
});
// Tests for the specific block in lines 135-142 handling toolCallState.output
describe("toolCallState.output handling (lines 135-142)", () => {
test("should use CANCELLED_TOOL_CALL_MESSAGE for cancelled tool calls", () => {
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I'll run a command",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "some_tool",
arguments: '{"command": "ls"}',
},
},
],
};
mockHistory = [
{
message: assistantWithToolCall,
contextItems: [],
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "some_tool",
arguments: '{"command": "ls"}',
},
},
status: "canceled",
parsedArgs: { command: "ls" },
output: [
createContextItem(
"result",
"This should be ignored due to cancelled status",
),
],
},
],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
const toolMessage = messages[2] as ToolResultChatMessage;
expect(toolMessage.role).toBe("tool");
expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE);
expect(toolMessage.content).not.toContain("This should be ignored");
});
test("should use renderContextItemsWithStatus for RunTerminalCommand with output", () => {
const assistantWithTerminalCall: AssistantChatMessage = {
role: "assistant",
content: "I'll run a terminal command",
toolCalls: [
{
id: "terminal-call-1",
type: "function",
function: {
name: BuiltInToolNames.RunTerminalCommand,
arguments: '{"command": "ls -la"}',
},
},
],
};
const terminalOutputWithStatus = [
{
...createContextItem("terminal-output", "file1.txt\nfile2.txt"),
status: "completed",
},
{
...createContextItem("terminal-error", "Warning: deprecated flag"),
status: "warning",
},
];
mockHistory = [
{
message: assistantWithTerminalCall,
contextItems: [],
toolCallStates: [
{
toolCallId: "terminal-call-1",
toolCall: {
id: "terminal-call-1",
type: "function",
function: {
name: BuiltInToolNames.RunTerminalCommand,
arguments: '{"command": "ls -la"}',
},
},
status: "done",
parsedArgs: { command: "ls -la" },
output: terminalOutputWithStatus,
},
],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
const toolMessage = messages[2] as ToolResultChatMessage;
expect(toolMessage.role).toBe("tool");
expect(toolMessage.toolCallId).toBe("terminal-call-1");
// Should contain content with status appended
expect(toolMessage.content).toContain("file1.txt\nfile2.txt");
expect(toolMessage.content).toContain("[Status: completed]");
expect(toolMessage.content).toContain("Warning: deprecated flag");
expect(toolMessage.content).toContain("[Status: warning]");
// Should use renderContextItemsWithStatus format with double newlines between items
expect(toolMessage.content).toMatch(
/file1\.txt\nfile2\.txt\n\[Status: completed\]\n\nWarning: deprecated flag\n\[Status: warning\]/,
);
});
test("should use renderContextItems for non-RunTerminalCommand tools with output", () => {
const assistantWithSearchCall: AssistantChatMessage = {
role: "assistant",
content: "I'll search for that",
toolCalls: [
{
id: "search-call-1",
type: "function",
function: {
name: "search", // Not RunTerminalCommand
arguments: '{"query": "test"}',
},
},
],
};
const searchOutput = [
createContextItem("result1", "First search result"),
createContextItem("result2", "Second search result"),
];
mockHistory = [
{
message: assistantWithSearchCall,
contextItems: [],
toolCallStates: [
{
toolCallId: "search-call-1",
toolCall: {
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "done",
parsedArgs: { query: "test" },
output: searchOutput,
},
],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
const toolMessage = messages[2] as ToolResultChatMessage;
expect(toolMessage.role).toBe("tool");
expect(toolMessage.toolCallId).toBe("search-call-1");
// Should use renderContextItems format (no status, double newlines between items)
expect(toolMessage.content).toBe(
"First search result\n\nSecond search result",
);
expect(toolMessage.content).not.toContain("[Status:");
});
test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when no output exists", () => {
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I'll search for that",
toolCalls: [
{
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
};
mockHistory = [
{
message: assistantWithToolCall,
contextItems: [],
toolCallStates: [
{
toolCallId: "search-call-1",
toolCall: {
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "generating",
parsedArgs: { query: "test" },
// No output field
},
],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
const toolMessage = messages[2] as ToolResultChatMessage;
expect(toolMessage.role).toBe("tool");
expect(toolMessage.toolCallId).toBe("search-call-1");
expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
});
test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState is undefined", () => {
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I'll search for that",
toolCalls: [
{
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
};
mockHistory = [
{
message: assistantWithToolCall,
contextItems: [],
// No toolCallStates array
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
const toolMessage = messages[2] as ToolResultChatMessage;
expect(toolMessage.role).toBe("tool");
expect(toolMessage.toolCallId).toBe("search-call-1");
expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
});
test("should prioritize cancelled status over output content", () => {
const assistantWithTerminalCall: AssistantChatMessage = {
role: "assistant",
content: "I'll run a command",
toolCalls: [
{
id: "terminal-call-1",
type: "function",
function: {
name: BuiltInToolNames.RunTerminalCommand,
arguments: '{"command": "ls"}',
},
},
],
};
mockHistory = [
{
message: assistantWithTerminalCall,
contextItems: [],
toolCallStates: [
{
toolCallId: "terminal-call-1",
toolCall: {
id: "terminal-call-1",
type: "function",
function: {
name: BuiltInToolNames.RunTerminalCommand,
arguments: '{"command": "ls"}',
},
},
status: "canceled", // Cancelled status
parsedArgs: { command: "ls" },
output: [
createContextItem(
"terminal-output",
"This output should be ignored",
),
], // Has output but is cancelled
},
],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
const toolMessage = messages[2] as ToolResultChatMessage;
expect(toolMessage.role).toBe("tool");
expect(toolMessage.toolCallId).toBe("terminal-call-1");
// Should use cancelled message, not the output content
expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE);
expect(toolMessage.content).not.toContain(
"This output should be ignored",
);
});
});
});

View file

@ -10,6 +10,7 @@ import {
import { chatMessageIsEmpty } from "core/llm/messages";
import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules";
import { RulePolicies } from "core/llm/rules/types";
import { BuiltInToolNames } from "core/tools/builtIn";
import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
@ -20,8 +21,13 @@ import { findLast, findLastIndex } from "core/util/findLast";
import {
normalizeToMessageParts,
renderContextItems,
renderContextItemsWithStatus,
} from "core/util/messageContent";
import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/utils";
// Helper function to render context items and append status information
// Helper function to render context items and append status information
interface MessageWithContextItems {
ctxItems: ContextItemWithId[];
message: ChatMessage;
@ -132,8 +138,14 @@ export function constructMessages(
if (toolCallState?.status === "canceled") {
content = CANCELLED_TOOL_CALL_MESSAGE;
} else if (
toolCallState?.output &&
toolCall.function?.name == BuiltInToolNames.RunTerminalCommand
) {
// Add status for tools containing detailed status outcomes per context item
content = renderContextItemsWithStatus(toolCallState.output);
} else if (toolCallState?.output) {
content = renderContextItems(toolCallState.output);
content = renderContextItems(toolCallState?.output);
}
msgs.push({