Elffuss BraidHub

kikocis/continue public

Merge branch 'main' of https://github.com/continuedev/continue into dallin/con-3885-no-any-rule
Changeset7cf73afcccb78cd0f95dd782772cbe027f81bde66a606f6783f386d0e7f38c92
AuthorDallin Romney <dallinromney@gmail.com> · 2025-09-11 12:47 -07:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-09-11 12:47 -07:00
Parentsee03d604eeb7, a9be1ad64add

Browse the files at this changeset

40 files changed

modified .github/workflows/continue-detailed-review.yaml +1 −1
@@ -18,7 +18,7 @@
1818 timeout-minutes: 10
1919 steps:
2020 - name: Run Detailed PR Review
21- uses: continuedev/continue/actions/detailed-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
21+ uses: continuedev/continue/actions/detailed-review@5dc7a050db441934c26eb910b8433291f627db7f
2222 with:
2323 continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
2424 continue-org: continuedev
modified .github/workflows/continue-general-review.yaml +1 −1
@@ -18,7 +18,7 @@
1818 timeout-minutes: 10
1919 steps:
2020 - name: Run Continue PR Review Action
21- uses: continuedev/continue/actions/general-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
21+ uses: continuedev/continue/actions/general-review@5dc7a050db441934c26eb910b8433291f627db7f
2222 with:
2323 continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
2424 continue-org: "continuedev"
added core/commands/slash/ruleBlockSlashCommand.ts +15 −0
@@ -0,0 +1,15 @@
1+import { RuleWithSource, SlashCommandWithSource } from "../..";
2+
3+export function convertRuleBlockToSlashCommand(
4+ rule: RuleWithSource,
5+): SlashCommandWithSource {
6+ return {
7+ name:
8+ rule.name ||
9+ (rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule),
10+ description: rule.description ?? "",
11+ prompt: rule.rule,
12+ source: "invokable-rule",
13+ promptFile: rule.ruleFile,
14+ };
15+}
added core/commands/slash/ruleBlockSlashCommand.vitest.ts +93 −0
@@ -0,0 +1,93 @@
1+import { describe, expect, it } from "vitest";
2+import { RuleWithSource } from "../..";
3+import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand";
4+
5+describe("convertRuleBlockToSlashCommand", () => {
6+ it("should convert a rule with all properties to a slash command", () => {
7+ const rule: RuleWithSource = {
8+ name: "Code Review",
9+ rule: "Review this code for best practices",
10+ description: "Performs a code review",
11+ source: "rules-block",
12+ ruleFile: "/path/to/rules.yaml",
13+ invokable: true,
14+ };
15+
16+ const result = convertRuleBlockToSlashCommand(rule);
17+
18+ expect(result).toEqual({
19+ name: "Code Review",
20+ description: "Performs a code review",
21+ prompt: "Review this code for best practices",
22+ source: "invokable-rule",
23+ promptFile: "/path/to/rules.yaml",
24+ });
25+ });
26+
27+ it("should handle a rule without name", () => {
28+ const rule: RuleWithSource = {
29+ rule: "Review this code",
30+ source: "rules-block",
31+ invokable: true,
32+ };
33+
34+ const result = convertRuleBlockToSlashCommand(rule);
35+
36+ expect(result.name).toBe("Review this code");
37+ expect(result.prompt).toBe("Review this code");
38+ });
39+
40+ it("should truncate long rule text when used as name", () => {
41+ const rule: RuleWithSource = {
42+ rule: "This is a very long rule text that should be truncated",
43+ source: "rules-block",
44+ invokable: true,
45+ };
46+
47+ const result = convertRuleBlockToSlashCommand(rule);
48+
49+ expect(result.name).toBe("This is a very long ...");
50+ expect(result.prompt).toBe(
51+ "This is a very long rule text that should be truncated",
52+ );
53+ });
54+
55+ it("should handle a rule without description", () => {
56+ const rule: RuleWithSource = {
57+ name: "Test Rule",
58+ rule: "Test rule content",
59+ source: "rules-block",
60+ invokable: true,
61+ };
62+
63+ const result = convertRuleBlockToSlashCommand(rule);
64+
65+ expect(result.description).toBe("");
66+ });
67+
68+ it("should use rule text as the prompt", () => {
69+ const rule: RuleWithSource = {
70+ name: "Explain Code",
71+ rule: "Explain what this code does in simple terms",
72+ source: "rules-block",
73+ invokable: true,
74+ };
75+
76+ const result = convertRuleBlockToSlashCommand(rule);
77+
78+ expect(result.prompt).toBe("Explain what this code does in simple terms");
79+ });
80+
81+ it("should always set source to 'invokable-rule'", () => {
82+ const rule: RuleWithSource = {
83+ name: "Test",
84+ rule: "Test",
85+ source: "default-chat",
86+ invokable: true,
87+ };
88+
89+ const result = convertRuleBlockToSlashCommand(rule);
90+
91+ expect(result.source).toBe("invokable-rule");
92+ });
93+});
modified core/config/types.ts +1 −0
@@ -1061,6 +1061,7 @@
10611061 filepath?: string;
10621062 fileContent?: string;
10631063 originalFileContent?: string;
1064+ autoFormattingDiff?: string;
10641065 }
10651066
10661067 export interface RangeInFileWithContents {
modified core/config/yaml/loadYaml.ts +16 −1
@@ -24,6 +24,7 @@
2424
2525 import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
2626 import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
27+import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
2728 import { getControlPlaneEnvSync } from "../../control-plane/env";
2829 import { PolicySingleton } from "../../control-plane/PolicySingleton";
2930 import { getBaseToolDefinitions } from "../../tools";
@@ -208,7 +209,21 @@
208209 }
209210
210211 for (const rule of config.rules ?? []) {
211- continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
212+ const convertedRule = convertYamlRuleToContinueRule(rule);
213+ continueConfig.rules.push(convertedRule);
214+
215+ // Convert invokable rules to slash commands
216+ if (convertedRule.invokable) {
217+ try {
218+ const slashCommand = convertRuleBlockToSlashCommand(convertedRule);
219+ continueConfig.slashCommands?.push(slashCommand);
220+ } catch (e) {
221+ localErrors.push({
222+ message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`,
223+ fatal: false,
224+ });
225+ }
226+ }
212227 }
213228
214229 continueConfig.data = config.data;
modified core/config/yaml/yamlToContinueConfig.ts +2 −0
@@ -13,8 +13,10 @@
1313 rule: rule.rule,
1414 globs: rule.globs,
1515 name: rule.name,
16+ description: rule.description,
1617 ruleFile: rule.sourceFile,
1718 alwaysApply: rule.alwaysApply,
19+ invokable: rule.invokable,
1820 };
1921 }
2022 }
modified core/core.ts +6 −1
@@ -29,8 +29,9 @@
2929 import { Telemetry } from "./util/posthog";
3030 import {
3131 isProcessBackgrounded,
32+ killTerminalProcess,
3233 markProcessAsBackgrounded,
33-} from "./util/processTerminalBackgroundStates";
34+} from "./util/processTerminalStates";
3435 import { getSymbolsForManyFiles } from "./util/treeSitter";
3536 import { TTS } from "./util/tts";
3637
@@ -1062,6 +1063,10 @@
10621063 },
10631064 );
10641065
1066+ on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
1067+ await killTerminalProcess(toolCallId);
1068+ });
1069+
10651070 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
10661071 const isValid = setMdmLicenseKey(licenseKey);
10671072 return isValid;
modified core/index.d.ts +2 −0
@@ -1387,6 +1387,7 @@
13871387 fileContent?: string;
13881388 originalFileContent?: string;
13891389 toolCallId?: string;
1390+ autoFormattingDiff?: string;
13901391 }
13911392
13921393 export interface StreamDiffLinesPayload {
@@ -1807,6 +1808,7 @@
18071808 description?: string;
18081809 ruleFile?: string;
18091810 alwaysApply?: boolean;
1811+ invokable?: boolean;
18101812 }
18111813 export interface CompleteOnboardingPayload {
18121814 mode: OnboardingModes;
modified core/protocol/core.ts +1 −0
@@ -313,5 +313,6 @@
313313 ];
314314 "process/markAsBackgrounded": [{ toolCallId: string }, void];
315315 "process/isBackgrounded": [{ toolCallId: string }, boolean];
316+ "process/killTerminalProcess": [{ toolCallId: string }, void];
316317 "mdm/setLicenseKey": [{ licenseKey: string }, boolean];
317318 };
modified core/protocol/passThrough.ts +1 −0
@@ -86,6 +86,7 @@
8686 "isItemTooBig",
8787 "process/markAsBackgrounded",
8888 "process/isBackgrounded",
89+ "process/killTerminalProcess",
8990 ];
9091
9192 // Message types to pass through from core to webview
modified core/tools/implementations/runTerminalCommand.ts +55 −10
@@ -36,8 +36,11 @@
3636 import { ToolImpl } from ".";
3737 import {
3838 isProcessBackgrounded,
39+ markProcessAsRunning,
3940 removeBackgroundedProcess,
40-} from "../../util/processTerminalBackgroundStates";
41+ removeRunningProcess,
42+ updateProcessOutput,
43+} from "../../util/processTerminalStates";
4144 import { getBooleanArg, getStringArg } from "../parseArgs";
4245
4346 const asyncExec = util.promisify(childProcess.exec);
@@ -120,6 +123,16 @@
120123 env: getColorEnv(), // Add enhanced environment for colors
121124 });
122125
126+ // Track this process for foreground cancellation
127+ if (toolCallId && waitForCompletion) {
128+ markProcessAsRunning(
129+ toolCallId,
130+ childProc,
131+ extras.onPartialOutput,
132+ terminalOutput,
133+ );
134+ }
135+
123136 childProc.stdout?.on("data", (data) => {
124137 // Skip if this process has been backgrounded
125138 if (isProcessBackgrounded(toolCallId)) return;
@@ -127,6 +140,11 @@
127140 const newOutput = getDecodedOutput(data);
128141 terminalOutput += newOutput;
129142
143+ // Update the tracked output for potential cancellation notifications
144+ if (toolCallId && waitForCompletion) {
145+ updateProcessOutput(toolCallId, terminalOutput);
146+ }
147+
130148 // Send partial output to UI
131149 if (extras.onPartialOutput) {
132150 const status = waitForCompletion
@@ -153,6 +171,11 @@
153171 const newOutput = getDecodedOutput(data);
154172 terminalOutput += newOutput;
155173
174+ // Update the tracked output for potential cancellation notifications
175+ if (toolCallId && waitForCompletion) {
176+ updateProcessOutput(toolCallId, terminalOutput);
177+ }
178+
156179 // Send partial output to UI, status is not required
157180 if (extras.onPartialOutput) {
158181 extras.onPartialOutput({
@@ -182,15 +205,19 @@
182205 }
183206
184207 childProc.on("close", (code) => {
185- // If this process has been backgrounded, clean it up from the map and return
186- if (isProcessBackgrounded(toolCallId)) {
187- removeBackgroundedProcess(toolCallId);
188- return;
208+ // Clean up process tracking
209+ if (toolCallId) {
210+ if (isProcessBackgrounded(toolCallId)) {
211+ removeBackgroundedProcess(toolCallId);
212+ return;
213+ }
214+ // Remove from foreground tracking if it was tracked
215+ removeRunningProcess(toolCallId);
189216 }
190217
191218 if (waitForCompletion) {
192219 // Normal completion, resolve now
193- if (code === 0) {
220+ if (!code || code === 0) {
194221 const status = "Command completed";
195222 resolve([
196223 {
@@ -234,10 +261,14 @@
234261 });
235262
236263 childProc.on("error", (error) => {
237- // If this process has been backgrounded, clean it up from the map and return
238- if (isProcessBackgrounded(toolCallId)) {
239- removeBackgroundedProcess(toolCallId);
240- return;
264+ // Clean up process tracking
265+ if (toolCallId) {
266+ if (isProcessBackgrounded(toolCallId)) {
267+ removeBackgroundedProcess(toolCallId);
268+ return;
269+ }
270+ // Remove from foreground tracking if it was tracked
271+ removeRunningProcess(toolCallId);
241272 }
242273
243274 reject(error);
@@ -281,6 +312,11 @@
281312 },
282313 );
283314
315+ // Track this process for foreground cancellation
316+ if (toolCallId) {
317+ markProcessAsRunning(toolCallId, childProc, undefined, "");
318+ }
319+
284320 let stdout = "";
285321 let stderr = "";
286322
@@ -293,6 +329,11 @@
293329 });
294330
295331 childProc.on("close", (code) => {
332+ // Clean up process tracking
333+ if (toolCallId) {
334+ removeRunningProcess(toolCallId);
335+ }
336+
296337 if (code === 0) {
297338 resolve({ stdout, stderr });
298339 } else {
@@ -305,6 +346,10 @@
305346 });
306347
307348 childProc.on("error", (error) => {
349+ // Clean up process tracking
350+ if (toolCallId) {
351+ removeRunningProcess(toolCallId);
352+ }
308353 reject(error);
309354 });
310355 },
modified core/tools/implementations/runTerminalCommand.vitest.ts +3 −7
@@ -12,7 +12,7 @@
1212 import * as os from "node:os";
1313 import * as path from "node:path";
1414 import { IDE, ToolExtras } from "../..";
15-import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
15+import * as processTerminalStates from "../../util/processTerminalStates";
1616 import { runTerminalCommandImpl } from "./runTerminalCommand";
1717 import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
1818
@@ -39,12 +39,8 @@
3939 vi.resetAllMocks();
4040
4141 // Setup backgrounded processes handling - don't mock, just make sure it's empty
42- // Get any processes that might be already tracked and clear them
43- const processMap = (processBackgroundStates as any)
44- .processTerminalBackgroundStates;
45- if (processMap && typeof processMap.clear === "function") {
46- processMap.clear();
47- }
42+ // Clear any processes that might be already tracked
43+ processTerminalStates.clearAllBackgroundProcesses();
4844
4945 // Setup IDE mocks
5046 mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
modified core/util/messageContent.ts +15 −0
@@ -35,6 +35,21 @@
3535 return contextItems.map((item) => item.content).join("\n\n");
3636 }
3737
38+export function renderContextItemsWithStatus(contextItems: any[]): string {
39+ return contextItems
40+ .map((item) => {
41+ let result = item.content;
42+
43+ // If this item has a status, append it directly after the content
44+ if (item.status) {
45+ result += `\n[Status: ${item.status}]`;
46+ }
47+
48+ return result;
49+ })
50+ .join("\n\n");
51+}
52+
3853 export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
3954 switch (message.role) {
4055 case "user":
deleted core/util/processTerminalBackgroundStates.test.ts +0 −73
@@ -1,73 +0,0 @@
1-import {
2- markProcessAsBackgrounded,
3- isProcessBackgrounded,
4- removeBackgroundedProcess,
5-} from "./processTerminalBackgroundStates";
6-
7-describe("processTerminalBackgroundStates", () => {
8- beforeEach(() => {
9- // Clear any backgrounded processes before each test
10- const backgroundedProcesses = Array.from(
11- Object.getOwnPropertySymbols(global),
12- ).find(
13- (symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)",
14- );
15-
16- if (backgroundedProcesses) {
17- // Reset the map by reimporting the module
18- jest.resetModules();
19- }
20- });
21-
22- test("should mark a process as backgrounded", () => {
23- const toolCallId = "test-123";
24- markProcessAsBackgrounded(toolCallId);
25- expect(isProcessBackgrounded(toolCallId)).toBe(true);
26- });
27-
28- test("should correctly identify non-backgrounded processes", () => {
29- const toolCallId = "test-123";
30- const anotherToolCallId = "test-456";
31-
32- markProcessAsBackgrounded(toolCallId);
33-
34- expect(isProcessBackgrounded(toolCallId)).toBe(true);
35- expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
36- });
37-
38- test("should remove a process from backgrounded state", () => {
39- const toolCallId = "test-123";
40-
41- markProcessAsBackgrounded(toolCallId);
42- expect(isProcessBackgrounded(toolCallId)).toBe(true);
43-
44- removeBackgroundedProcess(toolCallId);
45- expect(isProcessBackgrounded(toolCallId)).toBe(false);
46- });
47-
48- test("should handle removing non-existent processes", () => {
49- const toolCallId = "test-123";
50-
51- // Should not throw an error
52- removeBackgroundedProcess(toolCallId);
53- expect(isProcessBackgrounded(toolCallId)).toBe(false);
54- });
55-
56- test("should handle multiple processes", () => {
57- const toolCallId1 = "test-123";
58- const toolCallId2 = "test-456";
59- const toolCallId3 = "test-789";
60-
61- markProcessAsBackgrounded(toolCallId1);
62- markProcessAsBackgrounded(toolCallId2);
63-
64- expect(isProcessBackgrounded(toolCallId1)).toBe(true);
65- expect(isProcessBackgrounded(toolCallId2)).toBe(true);
66- expect(isProcessBackgrounded(toolCallId3)).toBe(false);
67-
68- removeBackgroundedProcess(toolCallId1);
69-
70- expect(isProcessBackgrounded(toolCallId1)).toBe(false);
71- expect(isProcessBackgrounded(toolCallId2)).toBe(true);
72- });
73-});
deleted core/util/processTerminalBackgroundStates.ts +0 −17
@@ -1,17 +0,0 @@
1-// Track which processes have been backgrounded
2-const processTerminalBackgroundStates = new Map<string, boolean>();
3-
4-// Function to mark a process as backgrounded
5-export function markProcessAsBackgrounded(toolCallId: string): void {
6- processTerminalBackgroundStates.set(toolCallId, true);
7-}
8-
9-// Function to check if a process is backgrounded
10-export function isProcessBackgrounded(toolCallId: string): boolean {
11- return processTerminalBackgroundStates.has(toolCallId);
12-}
13-
14-// Function to remove a process from the backgrounded processes map
15-export function removeBackgroundedProcess(toolCallId: string): void {
16- processTerminalBackgroundStates.delete(toolCallId);
17-}
added core/util/processTerminalStates.test.ts +367 −0
@@ -0,0 +1,367 @@
1+import { ChildProcess } from "child_process";
2+import {
3+ clearAllBackgroundProcesses,
4+ getAllBackgroundedProcessIds,
5+ getAllRunningProcessIds,
6+ getRunningProcess,
7+ isProcessBackgrounded,
8+ isProcessRunning,
9+ killAllRunningTerminalProcesses,
10+ killMultipleTerminalProcesses,
11+ killTerminalProcess,
12+ markProcessAsBackgrounded,
13+ markProcessAsRunning,
14+ removeBackgroundedProcess,
15+ removeRunningProcess,
16+ updateProcessOutput,
17+} from "./processTerminalStates";
18+
19+// Mock ChildProcess
20+const createMockProcess = (
21+ pid: number = 123,
22+ killed: boolean = false,
23+): jest.Mocked<ChildProcess> => {
24+ const mockProcess = {
25+ pid,
26+ killed,
27+ kill: jest.fn(),
28+ } as unknown as jest.Mocked<ChildProcess>;
29+
30+ // Make kill() update the killed property
31+ mockProcess.kill.mockImplementation(() => {
32+ (mockProcess as any).killed = true;
33+ return true;
34+ });
35+
36+ return mockProcess;
37+};
38+
39+describe("processTerminalStates", () => {
40+ beforeEach(() => {
41+ // Clear all running processes
42+ const runningIds = getAllRunningProcessIds();
43+ runningIds.forEach((id) => removeRunningProcess(id));
44+
45+ // Clear all backgrounded processes
46+ const backgroundedIds = getAllBackgroundedProcessIds();
47+ backgroundedIds.forEach((id) => removeBackgroundedProcess(id));
48+
49+ // Clear all timers
50+ jest.clearAllTimers();
51+ });
52+
53+ test("should mark a process as backgrounded", () => {
54+ const toolCallId = "test-123";
55+ markProcessAsBackgrounded(toolCallId);
56+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
57+ });
58+
59+ test("should correctly identify non-backgrounded processes", () => {
60+ const toolCallId = "test-123";
61+ const anotherToolCallId = "test-456";
62+
63+ markProcessAsBackgrounded(toolCallId);
64+
65+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
66+ expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
67+ });
68+
69+ test("should remove a process from backgrounded state", () => {
70+ const toolCallId = "test-123";
71+
72+ markProcessAsBackgrounded(toolCallId);
73+ expect(isProcessBackgrounded(toolCallId)).toBe(true);
74+
75+ removeBackgroundedProcess(toolCallId);
76+ expect(isProcessBackgrounded(toolCallId)).toBe(false);
77+ });
78+
79+ test("should handle removing non-existent processes", () => {
80+ const toolCallId = "test-123";
81+
82+ // Should not throw an error
83+ removeBackgroundedProcess(toolCallId);
84+ expect(isProcessBackgrounded(toolCallId)).toBe(false);
85+ });
86+
87+ test("should handle multiple processes", () => {
88+ const toolCallId1 = "test-123";
89+ const toolCallId2 = "test-456";
90+ const toolCallId3 = "test-789";
91+
92+ markProcessAsBackgrounded(toolCallId1);
93+ markProcessAsBackgrounded(toolCallId2);
94+
95+ expect(isProcessBackgrounded(toolCallId1)).toBe(true);
96+ expect(isProcessBackgrounded(toolCallId2)).toBe(true);
97+ expect(isProcessBackgrounded(toolCallId3)).toBe(false);
98+
99+ removeBackgroundedProcess(toolCallId1);
100+
101+ expect(isProcessBackgrounded(toolCallId1)).toBe(false);
102+ expect(isProcessBackgrounded(toolCallId2)).toBe(true);
103+ });
104+
105+ describe("foreground process functions", () => {
106+ test("should mark a process as running", () => {
107+ const toolCallId = "test-123";
108+ const mockProcess = createMockProcess();
109+ const mockCallback = jest.fn();
110+ const initialOutput = "initial output";
111+
112+ markProcessAsRunning(
113+ toolCallId,
114+ mockProcess,
115+ mockCallback,
116+ initialOutput,
117+ );
118+
119+ expect(isProcessRunning(toolCallId)).toBe(true);
120+ expect(getRunningProcess(toolCallId)).toBe(mockProcess);
121+ });
122+
123+ test("should handle process without callback or initial output", () => {
124+ const toolCallId = "test-123";
125+ const mockProcess = createMockProcess();
126+
127+ markProcessAsRunning(toolCallId, mockProcess);
128+
129+ expect(isProcessRunning(toolCallId)).toBe(true);
130+ expect(getRunningProcess(toolCallId)).toBe(mockProcess);
131+ });
132+
133+ test("should correctly identify non-running processes", () => {
134+ const toolCallId = "test-123";
135+ const anotherToolCallId = "test-456";
136+ const mockProcess = createMockProcess();
137+
138+ markProcessAsRunning(toolCallId, mockProcess);
139+
140+ expect(isProcessRunning(toolCallId)).toBe(true);
141+ expect(isProcessRunning(anotherToolCallId)).toBe(false);
142+ });
143+
144+ test("should update process output", () => {
145+ const toolCallId = "test-123";
146+ const mockProcess = createMockProcess();
147+ const initialOutput = "initial";
148+ const updatedOutput = "updated output";
149+
150+ markProcessAsRunning(toolCallId, mockProcess, undefined, initialOutput);
151+ updateProcessOutput(toolCallId, updatedOutput);
152+
153+ // We can't directly test the output value, but we can ensure the function doesn't throw
154+ expect(() =>
155+ updateProcessOutput(toolCallId, updatedOutput),
156+ ).not.toThrow();
157+ });
158+
159+ test("should handle updating output for non-existent process", () => {
160+ const toolCallId = "non-existent";
161+
162+ expect(() =>
163+ updateProcessOutput(toolCallId, "some output"),
164+ ).not.toThrow();
165+ });
166+
167+ test("should remove a process from running state", () => {
168+ const toolCallId = "test-123";
169+ const mockProcess = createMockProcess();
170+
171+ markProcessAsRunning(toolCallId, mockProcess);
172+ expect(isProcessRunning(toolCallId)).toBe(true);
173+
174+ removeRunningProcess(toolCallId);
175+ expect(isProcessRunning(toolCallId)).toBe(false);
176+ expect(getRunningProcess(toolCallId)).toBeUndefined();
177+ });
178+
179+ test("should handle removing non-existent running processes", () => {
180+ const toolCallId = "test-123";
181+
182+ expect(() => removeRunningProcess(toolCallId)).not.toThrow();
183+ expect(isProcessRunning(toolCallId)).toBe(false);
184+ });
185+
186+ test("should return undefined for non-existent running process", () => {
187+ const toolCallId = "non-existent";
188+
189+ expect(getRunningProcess(toolCallId)).toBeUndefined();
190+ });
191+ });
192+
193+ describe("terminal command cancellation", () => {
194+ beforeEach(() => {
195+ jest.useFakeTimers();
196+ });
197+
198+ afterEach(() => {
199+ jest.useRealTimers();
200+ });
201+
202+ test("should cancel a running terminal command", async () => {
203+ const toolCallId = "test-123";
204+ const mockProcess = createMockProcess();
205+
206+ markProcessAsRunning(toolCallId, mockProcess);
207+ expect(isProcessRunning(toolCallId)).toBe(true);
208+
209+ await killTerminalProcess(toolCallId);
210+
211+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
212+ expect(isProcessRunning(toolCallId)).toBe(false);
213+ });
214+
215+ test("should handle cancelling non-existent process", async () => {
216+ const toolCallId = "non-existent";
217+
218+ await expect(killTerminalProcess(toolCallId)).resolves.not.toThrow();
219+ });
220+
221+ test("should handle cancelling already killed process", async () => {
222+ const toolCallId = "test-123";
223+ const mockProcess = createMockProcess(123, true); // Already killed
224+
225+ markProcessAsRunning(toolCallId, mockProcess);
226+
227+ await killTerminalProcess(toolCallId);
228+
229+ expect(mockProcess.kill).not.toHaveBeenCalled();
230+ });
231+
232+ test("should send SIGKILL after timeout if process not killed", async () => {
233+ const toolCallId = "test-123";
234+ const mockProcess = createMockProcess();
235+
236+ // Mock kill to not actually set killed=true for SIGTERM
237+ mockProcess.kill.mockImplementation((signal) => {
238+ if (signal === "SIGKILL") {
239+ (mockProcess as any).killed = true;
240+ }
241+ return true;
242+ });
243+
244+ markProcessAsRunning(toolCallId, mockProcess);
245+
246+ const cancelPromise = killTerminalProcess(toolCallId);
247+
248+ // Fast-forward time to trigger the timeout
249+ jest.advanceTimersByTime(5000);
250+
251+ await cancelPromise;
252+
253+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
254+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGKILL");
255+ });
256+
257+ test("should not send SIGKILL if process was already killed", async () => {
258+ const toolCallId = "test-123";
259+ const mockProcess = createMockProcess();
260+
261+ markProcessAsRunning(toolCallId, mockProcess);
262+
263+ const cancelPromise = killTerminalProcess(toolCallId);
264+
265+ // Fast-forward time to trigger the timeout
266+ jest.advanceTimersByTime(5000);
267+
268+ await cancelPromise;
269+
270+ expect(mockProcess.kill).toHaveBeenCalledWith("SIGTERM");
271+ expect(mockProcess.kill).toHaveBeenCalledTimes(1); // Only SIGTERM, no SIGKILL
272+ });
273+ });
274+
275+ describe("utility functions", () => {
276+ test("should get all running process IDs", () => {
277+ const toolCallId1 = "test-123";
278+ const toolCallId2 = "test-456";
279+ const mockProcess1 = createMockProcess(123);
280+ const mockProcess2 = createMockProcess(456);
281+
282+ markProcessAsRunning(toolCallId1, mockProcess1);
283+ markProcessAsRunning(toolCallId2, mockProcess2);
284+
285+ const runningIds = getAllRunningProcessIds();
286+ expect(runningIds).toContain(toolCallId1);
287+ expect(runningIds).toContain(toolCallId2);
288+ expect(runningIds).toHaveLength(2);
289+ });
290+
291+ test("should get all backgrounded process IDs", () => {
292+ const toolCallId1 = "test-123";
293+ const toolCallId2 = "test-456";
294+
295+ markProcessAsBackgrounded(toolCallId1);
296+ markProcessAsBackgrounded(toolCallId2);
297+
298+ const backgroundedIds = getAllBackgroundedProcessIds();
299+ expect(backgroundedIds).toContain(toolCallId1);
300+ expect(backgroundedIds).toContain(toolCallId2);
301+ expect(backgroundedIds).toHaveLength(2);
302+ });
303+
304+ test("should return empty arrays when no processes", () => {
305+ expect(getAllRunningProcessIds()).toEqual([]);
306+ expect(getAllBackgroundedProcessIds()).toEqual([]);
307+ });
308+
309+ test("should cancel multiple terminal commands", async () => {
310+ const toolCallId1 = "test-123";
311+ const toolCallId2 = "test-456";
312+ const mockProcess1 = createMockProcess(123);
313+ const mockProcess2 = createMockProcess(456);
314+
315+ markProcessAsRunning(toolCallId1, mockProcess1);
316+ markProcessAsRunning(toolCallId2, mockProcess2);
317+
318+ await killMultipleTerminalProcesses([toolCallId1, toolCallId2]);
319+
320+ expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
321+ expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
322+ expect(isProcessRunning(toolCallId1)).toBe(false);
323+ expect(isProcessRunning(toolCallId2)).toBe(false);
324+ });
325+
326+ test("should cancel all running terminal commands", async () => {
327+ const toolCallId1 = "test-123";
328+ const toolCallId2 = "test-456";
329+ const mockProcess1 = createMockProcess(123);
330+ const mockProcess2 = createMockProcess(456);
331+
332+ markProcessAsRunning(toolCallId1, mockProcess1);
333+ markProcessAsRunning(toolCallId2, mockProcess2);
334+
335+ const cancelledIds = await killAllRunningTerminalProcesses();
336+
337+ expect(cancelledIds).toContain(toolCallId1);
338+ expect(cancelledIds).toContain(toolCallId2);
339+ expect(cancelledIds).toHaveLength(2);
340+ expect(mockProcess1.kill).toHaveBeenCalledWith("SIGTERM");
341+ expect(mockProcess2.kill).toHaveBeenCalledWith("SIGTERM");
342+ expect(isProcessRunning(toolCallId1)).toBe(false);
343+ expect(isProcessRunning(toolCallId2)).toBe(false);
344+ });
345+
346+ test("should return empty array when no running commands to cancel", async () => {
347+ const cancelledIds = await killAllRunningTerminalProcesses();
348+ expect(cancelledIds).toEqual([]);
349+ });
350+
351+ test("should clear all background processes", () => {
352+ const toolCallId1 = "test-123";
353+ const toolCallId2 = "test-456";
354+
355+ markProcessAsBackgrounded(toolCallId1);
356+ markProcessAsBackgrounded(toolCallId2);
357+
358+ expect(getAllBackgroundedProcessIds()).toHaveLength(2);
359+
360+ clearAllBackgroundProcesses();
361+
362+ expect(getAllBackgroundedProcessIds()).toEqual([]);
363+ expect(isProcessBackgrounded(toolCallId1)).toBe(false);
364+ expect(isProcessBackgrounded(toolCallId2)).toBe(false);
365+ });
366+ });
367+});
added core/util/processTerminalStates.ts +119 −0
@@ -0,0 +1,119 @@
1+import { ChildProcess } from "child_process";
2+
3+// Track which processes have been backgrounded
4+const processTerminalBackgroundStates = new Map<string, boolean>();
5+
6+// Track which foreground processes are currently running
7+interface RunningProcessInfo {
8+ process: ChildProcess;
9+ onPartialOutput?: (params: {
10+ toolCallId: string;
11+ contextItems: any[];
12+ }) => void;
13+ currentOutput: string;
14+}
15+
16+const processTerminalForegroundStates = new Map<string, RunningProcessInfo>();
17+
18+// Background process functions (existing)
19+export function markProcessAsBackgrounded(toolCallId: string): void {
20+ processTerminalBackgroundStates.set(toolCallId, true);
21+}
22+
23+export function isProcessBackgrounded(toolCallId: string): boolean {
24+ return processTerminalBackgroundStates.has(toolCallId);
25+}
26+
27+export function removeBackgroundedProcess(toolCallId: string): void {
28+ processTerminalBackgroundStates.delete(toolCallId);
29+}
30+
31+// Foreground process functions (new)
32+export function markProcessAsRunning(
33+ toolCallId: string,
34+ process: ChildProcess,
35+ onPartialOutput?: (params: {
36+ toolCallId: string;
37+ contextItems: any[];
38+ }) => void,
39+ currentOutput: string = "",
40+): void {
41+ processTerminalForegroundStates.set(toolCallId, {
42+ process,
43+ onPartialOutput,
44+ currentOutput,
45+ });
46+}
47+
48+export function isProcessRunning(toolCallId: string): boolean {
49+ return processTerminalForegroundStates.has(toolCallId);
50+}
51+
52+export function getRunningProcess(
53+ toolCallId: string,
54+): ChildProcess | undefined {
55+ const info = processTerminalForegroundStates.get(toolCallId);
56+ return info?.process;
57+}
58+
59+export function updateProcessOutput(toolCallId: string, output: string): void {
60+ const info = processTerminalForegroundStates.get(toolCallId);
61+ if (info) {
62+ info.currentOutput = output;
63+ }
64+}
65+
66+export function removeRunningProcess(toolCallId: string): void {
67+ processTerminalForegroundStates.delete(toolCallId);
68+}
69+
70+export async function killTerminalProcess(toolCallId: string): Promise<void> {
71+ const processInfo = processTerminalForegroundStates.get(toolCallId);
72+ if (processInfo && !processInfo.process.killed) {
73+ const { process } = processInfo;
74+
75+ process.kill("SIGTERM");
76+
77+ // Force kill after 5 seconds if still running
78+ setTimeout(() => {
79+ if (!process.killed) {
80+ process.kill("SIGKILL");
81+ }
82+ }, 5000);
83+
84+ processTerminalForegroundStates.delete(toolCallId);
85+ }
86+}
87+
88+// Function to cancel multiple terminal commands at once
89+export async function killMultipleTerminalProcesses(
90+ toolCallIds: string[],
91+): Promise<void> {
92+ const cancelPromises = toolCallIds.map((toolCallId) =>
93+ killTerminalProcess(toolCallId),
94+ );
95+ await Promise.all(cancelPromises);
96+}
97+
98+// Function to cancel ALL currently running terminal commands
99+export async function killAllRunningTerminalProcesses(): Promise<string[]> {
100+ const runningIds = getAllRunningProcessIds();
101+ if (runningIds.length > 0) {
102+ await killMultipleTerminalProcesses(runningIds);
103+ }
104+ return runningIds; // Return the IDs that were cancelled
105+}
106+
107+// Utility functions
108+export function getAllRunningProcessIds(): string[] {
109+ return Array.from(processTerminalForegroundStates.keys());
110+}
111+
112+export function getAllBackgroundedProcessIds(): string[] {
113+ return Array.from(processTerminalBackgroundStates.keys());
114+}
115+
116+// Utility function for testing - clears all background process states
117+export function clearAllBackgroundProcesses(): void {
118+ processTerminalBackgroundStates.clear();
119+}
added extensions/cli/src/stream/messageQueue.test.ts +62 −0
@@ -0,0 +1,62 @@
1+import { beforeEach, describe, expect, it, vi } from "vitest";
2+
3+vi.mock("../util/logger.js", () => ({
4+ logger: {
5+ debug: vi.fn(),
6+ info: vi.fn(),
7+ warn: vi.fn(),
8+ error: vi.fn(),
9+ setLevel: vi.fn(),
10+ configureHeadlessMode: vi.fn(),
11+ getLogPath: vi.fn(),
12+ getSessionId: vi.fn(),
13+ },
14+}));
15+
16+import { messageQueue } from "./messageQueue.js";
17+
18+describe("messageQueue", () => {
19+ beforeEach(() => {
20+ // Drain any leftover items from previous tests
21+ while (messageQueue.getAllQueuedMessages()) {}
22+ });
23+
24+ it("enqueues and emits messageQueued", async () => {
25+ const event = new Promise<any>((resolve) =>
26+ messageQueue.once("messageQueued", resolve),
27+ );
28+
29+ const ok = await messageQueue.enqueueMessage("hello world");
30+ expect(ok).toBe(true);
31+ expect(messageQueue.getQueueLength()).toBe(1);
32+
33+ const queued = await event;
34+ expect(queued.message).toBe("hello world");
35+ });
36+
37+ it("combines messages, merges image maps, writes history, and clears queue", async () => {
38+ const bufA = Buffer.from("A");
39+ const bufB = Buffer.from("B");
40+
41+ const img1 = new Map<string, Buffer>([["a", bufA]]);
42+ const img2 = new Map<string, Buffer>([["b", bufB]]);
43+
44+ const history = { addEntry: vi.fn() } as any;
45+
46+ await messageQueue.enqueueMessage("one", img1);
47+ await messageQueue.enqueueMessage("two", img2, history);
48+
49+ const combined = messageQueue.getAllQueuedMessages();
50+ expect(combined).toBeTruthy();
51+ expect(combined!.message).toBe("one\ntwo");
52+ expect(combined!.imageMap).toBeDefined();
53+ expect(combined!.imageMap!.get("a")).toEqual(bufA);
54+ expect(combined!.imageMap!.get("b")).toEqual(bufB);
55+
56+ // queue should be cleared
57+ expect(messageQueue.getQueueLength()).toBe(0);
58+
59+ // input history should receive the combined message
60+ expect(history.addEntry).toHaveBeenCalledWith("one\ntwo");
61+ });
62+});
added extensions/cli/src/stream/messageQueue.ts +94 −0
@@ -0,0 +1,94 @@
1+import { EventEmitter } from "events";
2+
3+import { InputHistory } from "../util/inputHistory.js";
4+import { logger } from "../util/logger.js";
5+
6+export interface QueuedMessage {
7+ message: string;
8+ imageMap?: Map<string, Buffer>;
9+ timestamp: number;
10+}
11+
12+export interface MessageProcessor {
13+ (message: string, imageMap?: Map<string, Buffer>): Promise<void>;
14+}
15+
16+/**
17+ * A queue to store messages that need to be processed later
18+ */
19+class MessageQueue extends EventEmitter {
20+ private queue: QueuedMessage[] = [];
21+ private inputHistory: InputHistory | undefined;
22+
23+ constructor() {
24+ super();
25+ }
26+
27+ async enqueueMessage(
28+ message: string,
29+ imageMap?: Map<string, Buffer>,
30+ inputHistory?: InputHistory,
31+ ): Promise<boolean> {
32+ this.inputHistory = inputHistory;
33+
34+ const queuedMessage: QueuedMessage = {
35+ message,
36+ imageMap,
37+ timestamp: Date.now(),
38+ };
39+
40+ this.queue.push(queuedMessage);
41+ logger.debug("MessageQueue: Message queued", {
42+ queueLength: this.queue.length,
43+ });
44+
45+ // Emit event for UI to show the queued message
46+ this.emit("messageQueued", queuedMessage);
47+
48+ return true;
49+ }
50+
51+ public getAllQueuedMessages() {
52+ if (this.queue.length === 0) return undefined;
53+
54+ // Combine all queued messages into one
55+ const combinedMessage = this.queue.map((msg) => msg.message).join("\n");
56+ const combinedImageMap = new Map<string, Buffer>();
57+
58+ // Merge all image maps
59+ for (const queuedMsg of this.queue) {
60+ if (queuedMsg.imageMap) {
61+ for (const [key, value] of queuedMsg.imageMap) {
62+ combinedImageMap.set(key, value);
63+ }
64+ }
65+ }
66+
67+ const result = {
68+ message: combinedMessage,
69+ imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined,
70+ timestamp: Date.now(),
71+ };
72+
73+ // Add to input history and clear the queue
74+ this.inputHistory?.addEntry(combinedMessage);
75+ this.queue = [];
76+
77+ logger.debug("MessageQueue: All messages dequeued and combined", {
78+ combinedLength: combinedMessage.length,
79+ queueLength: this.queue.length,
80+ });
81+
82+ return result;
83+ }
84+
85+ public getLatestMessage() {
86+ return this.getAllQueuedMessages();
87+ }
88+
89+ getQueueLength(): number {
90+ return this.queue.length;
91+ }
92+}
93+
94+export const messageQueue = new MessageQueue();
modified extensions/cli/src/ui/TUIChat.tsx +2 −0
@@ -188,6 +188,7 @@
188188 inputMode,
189189 activePermissionRequest,
190190 wasInterrupted,
191+ queuedMessages,
191192 handleUserMessage,
192193 handleInterrupt,
193194 handleFileAttached,
@@ -282,6 +283,7 @@
282283 model={services.model?.model || undefined}
283284 mcpService={services.mcp?.mcpService || undefined}
284285 chatHistory={chatHistory}
286+ queuedMessages={queuedMessages}
285287 renderMessage={renderMessage}
286288 refreshTrigger={staticRefreshTrigger}
287289 />
modified extensions/cli/src/ui/UserInput.tsx +12 −15
@@ -9,6 +9,7 @@
99 import type { FileIndexServiceState } from "../services/FileIndexService.js";
1010 import { SERVICE_NAMES, serviceContainer } from "../services/index.js";
1111 import { modeService } from "../services/ModeService.js";
12+import { messageQueue } from "../stream/messageQueue.js";
1213 import { InputHistory } from "../util/inputHistory.js";
1314
1415 import { FileSearchUI } from "./FileSearchUI.js";
@@ -515,7 +516,7 @@
515516 }
516517
517518 // Normal Enter behavior - submit if there's content
518- if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) {
519+ if (textBuffer.text.trim() || wasInterrupted) {
519520 // Get images before expanding paste blocks
520521 const imageMap = textBuffer.getAllImages();
521522
@@ -523,14 +524,19 @@
523524 textBuffer.expandAllPasteBlocks();
524525 const submittedText = textBuffer.text.trim();
525526
526- // Only add to history if there's actual text (not when resuming)
527- if (submittedText) {
527+ if (isWaitingForResponse) {
528+ // Process message later when LLM has responded
529+ void messageQueue.enqueueMessage(
530+ submittedText,
531+ imageMap,
532+ inputHistory,
533+ );
534+ } else {
535+ // Submit with images
528536 inputHistory.addEntry(submittedText);
537+ onSubmit(submittedText, imageMap);
529538 }
530539
531- // Submit with images
532- onSubmit(submittedText, imageMap);
533-
534540 textBuffer.clear();
535541 setInputText("");
536542 setCursorPosition(0);
@@ -647,15 +653,6 @@
647653 return;
648654 }
649655
650- // Allow typing during streaming, but block submission
651- if (!inputMode) {
652- // Block only Enter key submission during streaming
653- if (key.return && !key.shift) {
654- return;
655- }
656- // Allow all other input (typing, navigation, etc.)
657- }
658-
659656 // Handle slash command navigation
660657 if (showSlashCommands) {
661658 if (handleSlashCommandNavigation(key)) {
modified extensions/cli/src/ui/components/StaticChatContent.tsx +13 −1
@@ -1,9 +1,10 @@
11 import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
2-import { Box, Static, useStdout } from "ink";
2+import { Box, Static, Text, useStdout } from "ink";
33 import React, { useCallback, useEffect, useRef, useState } from "react";
44
55 import type { ChatHistoryItem } from "../../../../../core/index.js";
66 import type { MCPService } from "../../services/MCPService.js";
7+import type { QueuedMessage } from "../../stream/messageQueue.js";
78 import { useTerminalSize } from "../hooks/useTerminalSize.js";
89 import { IntroMessage } from "../IntroMessage.js";
910
@@ -13,6 +14,7 @@
1314 model?: ModelConfig;
1415 mcpService?: MCPService;
1516 chatHistory: ChatHistoryItem[];
17+ queuedMessages?: QueuedMessage[];
1618 renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
1719 refreshTrigger?: number; // Add a prop to trigger refresh from parent
1820 }
@@ -23,6 +25,7 @@
2325 model,
2426 mcpService,
2527 chatHistory,
28+ queuedMessages = [],
2629 renderMessage,
2730 refreshTrigger,
2831 }) => {
@@ -140,6 +143,15 @@
140143 <React.Fragment key={`pending-${index}`}>{item}</React.Fragment>
141144 ))}
142145 </Box>
146+
147+ {/* Queued messages - show at bottom with queue indicators */}
148+ {queuedMessages.length > 0 && (
149+ <Box paddingLeft={2} paddingBottom={1}>
150+ <Text color="gray" italic>
151+ {queuedMessages.map((msg) => msg.message).join("\n")}
152+ </Text>
153+ </Box>
154+ )}
143155 </Box>
144156 );
145157 };
modified extensions/cli/src/ui/hooks/useChat.ts +126 −44
@@ -1,3 +1,4 @@
1+/* eslint-disable max-lines */
12 import type { ChatHistoryItem, Session } from "core/index.js";
23 import { useApp } from "ink";
34 import { useEffect, useRef, useState } from "react";
@@ -11,6 +12,7 @@
1112 updateSessionHistory,
1213 } from "../../session.js";
1314 import { handleSlashCommands } from "../../slashCommands.js";
15+import { messageQueue, QueuedMessage } from "../../stream/messageQueue.js";
1416 import { telemetryService } from "../../telemetry/telemetryService.js";
1517 import { formatError } from "../../util/formatError.js";
1618 import { logger } from "../../util/logger.js";
@@ -166,6 +168,22 @@
166168 // Track interrupted state for resume functionality
167169 const [wasInterrupted, setWasInterrupted] = useState(false);
168170
171+ // Track queued messages for immediate display
172+ const [queuedMessages, setQueuedMessages] = useState<QueuedMessage[]>([]);
173+
174+ // Set up message queue listeners
175+ useEffect(() => {
176+ const onMessageQueued = (queuedMessage: QueuedMessage) => {
177+ setQueuedMessages((prev) => [...prev, queuedMessage]);
178+ };
179+
180+ messageQueue.on("messageQueued", onMessageQueued);
181+
182+ return () => {
183+ messageQueue.off("messageQueued", onMessageQueued);
184+ };
185+ }, []);
186+
169187 // Clean up abort controller on unmount
170188 useEffect(() => {
171189 return () => {
@@ -306,6 +324,30 @@
306324 setIsWaitingForResponse(false);
307325 setResponseStartTime(null);
308326 setInputMode(true);
327+
328+ // Check if there are queued messages and process them after a microtask delay
329+ // This ensures the GUI state has been updated before processing the next message
330+ const queuedMessageData = messageQueue.getLatestMessage();
331+ if (queuedMessageData) {
332+ const { message: latestQueuedMessage, imageMap } = queuedMessageData;
333+ logger.debug("processing queued message", { latestQueuedMessage });
334+
335+ // Clear all queued messages from display since we're processing them all together
336+ setQueuedMessages([]);
337+
338+ // Add the queued message to chat history so it shows in the GUI
339+ const formattedQueuedMessage = await formatMessageWithFiles(
340+ latestQueuedMessage,
341+ [], // No attached files for queued messages
342+ imageMap,
343+ );
344+ setChatHistory((prev) => [...prev, formattedQueuedMessage]);
345+
346+ await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui
347+
348+ // Process the queued message using the internal processing logic without re-adding to history
349+ await processQueuedMessage(latestQueuedMessage, imageMap);
350+ }
309351 }
310352 };
311353
@@ -398,20 +440,11 @@
398440 .join("");
399441 };
400442
401- const handleUserMessage = async (
443+ const processMessage = async (
402444 message: string,
403445 imageMap?: Map<string, Buffer>,
446+ isQueuedMessage: boolean = false,
404447 ) => {
405- // Check if this is a resume request (empty message after interruption)
406- if (await handleResumeRequest(message)) {
407- return;
408- }
409-
410- // Clear interrupted state if user types a new message
411- if (wasInterrupted && message !== "") {
412- setWasInterrupted(false);
413- }
414-
415448 // Handle special commands
416449 const handled = await handleSpecialCommands({
417450 message,
@@ -440,27 +473,9 @@
440473 // Track telemetry
441474 trackUserMessage(message, model);
442475
443- // Format message with attached files and images
444- logger.debug("Processing message with images", {
445- hasImages: !!(imageMap && imageMap.size > 0),
446- imageCount: imageMap?.size || 0,
447- });
448- const newUserMessage = await formatMessageWithFiles(
449- message,
450- attachedFiles,
451- imageMap,
452- );
453- logger.debug("Message formatted successfully");
454-
455- if (attachedFiles.length > 0) {
456- setAttachedFiles([]);
457- }
458-
459476 // In remote mode, send message to server instead of processing locally
460477 if (isRemoteMode && remoteUrl) {
461- const messageContentString = convertMessageContentToString(
462- newUserMessage.message.content,
463- );
478+ const messageContentString = convertMessageContentToString(message);
464479
465480 await handleRemoteMessage({
466481 remoteUrl,
@@ -469,23 +484,87 @@
469484 return;
470485 }
471486
472- // Check if auto-compacting is needed BEFORE adding user message
473- const { currentChatHistory, currentCompactionIndex } =
474- await handleAutoCompaction({
475- chatHistory,
476- model,
477- llmApi,
478- compactionIndex,
479- setChatHistory: setChatHistory,
480- setCompactionIndex,
487+ // For non-queued messages, format and add to chat history
488+ if (isQueuedMessage) {
489+ // For queued messages, chat history is already updated
490+ // Check if auto-compacting is needed with current history
491+ const { currentChatHistory, currentCompactionIndex } =
492+ await handleAutoCompaction({
493+ chatHistory,
494+ model,
495+ llmApi,
496+ compactionIndex,
497+ setChatHistory: setChatHistory,
498+ setCompactionIndex,
499+ });
500+
501+ // Execute the streaming response with the current history (which already includes the queued message)
502+ await executeStreamingResponse(
503+ currentChatHistory,
504+ currentCompactionIndex,
505+ );
506+ } else {
507+ // Format message with attached files and images
508+ logger.debug("Processing message with images", {
509+ hasImages: !!(imageMap && imageMap.size > 0),
510+ imageCount: imageMap?.size || 0,
481511 });
512+ const newUserMessage = await formatMessageWithFiles(
513+ message,
514+ attachedFiles,
515+ imageMap,
516+ );
517+ logger.debug("Message formatted successfully");
482518
483- // Add the formatted user message to history
484- const newHistory = [...currentChatHistory, newUserMessage];
485- setChatHistory(newHistory);
519+ if (attachedFiles.length > 0) {
520+ setAttachedFiles([]);
521+ }
522+
523+ // Check if auto-compacting is needed BEFORE adding user message
524+ const { currentChatHistory, currentCompactionIndex } =
525+ await handleAutoCompaction({
526+ chatHistory,
527+ model,
528+ llmApi,
529+ compactionIndex,
530+ setChatHistory: setChatHistory,
531+ setCompactionIndex,
532+ });
533+
534+ // Add the formatted user message to history
535+ const newHistory = [...currentChatHistory, newUserMessage];
536+ setChatHistory(newHistory);
537+
538+ // Execute the streaming response
539+ await executeStreamingResponse(newHistory, currentCompactionIndex);
540+ }
541+ };
542+
543+ const processQueuedMessage = async (
544+ message: string,
545+ imageMap?: Map<string, Buffer>,
546+ ) => {
547+ // For queued messages, we can reuse the core message processing logic
548+ // by calling the internal processing function directly
549+ await processMessage(message, imageMap, true);
550+ };
551+
552+ const handleUserMessage = async (
553+ message: string,
554+ imageMap?: Map<string, Buffer>,
555+ ) => {
556+ // Check if this is a resume request (empty message after interruption)
557+ if (await handleResumeRequest(message)) {
558+ return;
559+ }
560+
561+ // Clear interrupted state if user types a new message
562+ if (wasInterrupted && message !== "") {
563+ setWasInterrupted(false);
564+ }
486565
487- // Execute the streaming response
488- await executeStreamingResponse(newHistory, currentCompactionIndex);
566+ // Use the common message processing logic
567+ await processMessage(message, imageMap, false);
489568 };
490569
491570 const handleInterrupt = () => {
@@ -537,6 +616,8 @@
537616 additionalRules,
538617 );
539618 setChatHistory(newHistory);
619+ // Clear any queued messages when resetting chat
620+ setQueuedMessages([]);
540621 };
541622
542623 const handleToolPermissionResponse = async (
@@ -614,6 +695,7 @@
614695 attachedFiles,
615696 activePermissionRequest,
616697 wasInterrupted,
698+ queuedMessages,
617699 handleUserMessage,
618700 handleInterrupt,
619701 handleFileAttached,
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +1 −0
@@ -146,6 +146,7 @@
146146 "isItemTooBig",
147147 "process/markAsBackgrounded",
148148 "process/isBackgrounded",
149+ "process/killTerminalProcess"
149150 )
150151 }
151152 }
modified extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +66 −5
@@ -4,12 +4,12 @@
44 InputBox,
55 Key,
66 TextEditor,
7+ until,
78 VSBrowser,
89 WebDriver,
910 WebElement,
1011 WebView,
1112 Workbench,
12- until,
1313 } from "vscode-extension-tester";
1414
1515 import { GlobalActions } from "../actions/Global.actions";
@@ -47,11 +47,31 @@
4747
4848 afterEach(async function () {
4949 this.timeout(DEFAULT_TIMEOUT.XL * 1000);
50+ await cleanupChat();
5051 await view.switchBack();
5152 await editor.clearText();
5253 await new EditorView().closeAllEditors();
5354 });
5455
56+ async function cleanupChat(chatInput?: WebElement) {
57+ try {
58+ if (!chatInput) {
59+ chatInput = await TestUtils.waitForSuccess(async () => {
60+ return GUISelectors.getMessageInputFieldAtIndex(view, 0);
61+ });
62+ }
63+ if (
64+ chatInput &&
65+ (await chatInput.isDisplayed()) &&
66+ (await chatInput.isEnabled())
67+ ) {
68+ await chatInput.clear();
69+ }
70+ } catch (e) {
71+ console.error(`Failed to clear chat: ${e}`);
72+ }
73+ }
74+
5575 it("Should correctly undo and redo using keyboard shortcuts when writing a chat message", async () => {
5676 await GUIActions.executeFocusContinueInputShortcut(driver);
5777 ({ view } = await GUIActions.switchToReactIframe());
@@ -105,10 +125,8 @@
105125 );
106126 }).timeout(DEFAULT_TIMEOUT.XL);
107127
108- it("Should not create a code block when Cmd+L is pressed without text highlighted", async () => {
109- const text = "Hello, world!";
110-
111- await editor.setText(text);
128+ it("Should not create a code block when Cmd+L is pressed on an empty document", async () => {
129+ expect((await editor.getText()).trim()).to.equal("");
112130
113131 await GUIActions.executeFocusContinueInputShortcut(driver);
114132
@@ -174,6 +192,9 @@
174192
175193 await driver.wait(until.elementIsNotVisible(textInput), DEFAULT_TIMEOUT.XS);
176194 expect(await textInput.isDisplayed()).to.equal(false);
195+
196+ // Make sure the view is visible again, so it can be cleared in afterEach()
197+ await GUIActions.executeFocusContinueInputShortcut(driver);
177198 }).timeout(DEFAULT_TIMEOUT.XL);
178199
179200 it("Should create a code block when Cmd+L is pressed with text highlighted", async () => {
@@ -197,4 +218,44 @@
197218
198219 await GUIActions.executeFocusContinueInputShortcut(driver);
199220 }).timeout(DEFAULT_TIMEOUT.XL);
221+
222+ it("Should create a code block with the whole file when Cmd+L is pressed on an empty line", async () => {
223+ const text = "Hello,\n\n\nworld!";
224+
225+ await editor.setText(text);
226+ await editor.moveCursor(2, 1); //Move cursor to an empty line
227+
228+ await GUIActions.executeFocusContinueInputShortcut(driver);
229+
230+ ({ view } = await GUIActions.switchToReactIframe());
231+
232+ const codeBlock = await TestUtils.waitForSuccess(() =>
233+ GUISelectors.getInputBoxCodeBlockAtIndex(view, 0),
234+ );
235+ const codeblockContent = await codeBlock.getAttribute(
236+ "data-codeblockcontent",
237+ );
238+
239+ expect(codeblockContent).to.equal(text);
240+ });
241+
242+ it("Should create a code block when Cmd+L is pressed on a non-empty line", async () => {
243+ const text = "Hello, world!";
244+
245+ await editor.setText(text);
246+ await editor.moveCursor(1, 7); //Move cursor to the 1st space
247+
248+ await GUIActions.executeFocusContinueInputShortcut(driver);
249+
250+ ({ view } = await GUIActions.switchToReactIframe());
251+
252+ const codeBlock = await TestUtils.waitForSuccess(() =>
253+ GUISelectors.getInputBoxCodeBlockAtIndex(view, 0),
254+ );
255+ const codeblockContent = await codeBlock.getAttribute(
256+ "data-codeblockcontent",
257+ );
258+
259+ expect(codeblockContent).to.equal(text);
260+ }).timeout(DEFAULT_TIMEOUT.XL);
200261 });
modified extensions/vscode/package.json +2 −3
@@ -524,13 +524,12 @@
524524 "continue.continueSubMenu": [
525525 {
526526 "command": "continue.focusContinueInputWithoutClear",
527- "group": "Continue",
528- "when": "editorHasSelection"
527+ "group": "Continue"
529528 },
530529 {
531530 "command": "continue.focusEdit",
532531 "group": "Continue",
533- "when": "editorHasSelection && !editorReadonly"
532+ "when": "!editorReadonly"
534533 }
535534 ],
536535 "explorer/context": [
modified extensions/vscode/src/diff/processDiff.ts +38 −5
@@ -1,8 +1,11 @@
11 import { Core } from "core/core";
22 import { DataLogger } from "core/data/log";
3+import { myersDiff } from "core/diff/myers";
4+
35 import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
46 import { editOutcomeTracker } from "../extension/EditOutcomeTracker";
57 import { VsCodeIde } from "../VsCodeIde";
8+
69 import { VerticalDiffManager } from "./vertical/manager";
710
811 export async function processDiff(
@@ -42,7 +45,8 @@
4245 }
4346
4447 if (streamId) {
45- const fileContent = await ide.readFile(newOrCurrentUri);
48+ // Capture file content before save to detect autoformatting
49+ const preSaveContent = await ide.readFile(newOrCurrentUri);
4650
4751 // Record the edit outcome before updating the apply state
4852 await editOutcomeTracker.recordEditOutcome(
@@ -51,16 +55,45 @@
5155 DataLogger.getInstance(),
5256 );
5357
58+ // Save the file
59+ await ide.saveFile(newOrCurrentUri);
60+
61+ // Capture file content after save to detect autoformatting
62+ const postSaveContent = await ide.readFile(newOrCurrentUri);
63+
64+ // Detect autoformatting by comparing normalized content
65+ let autoFormattingDiff: string | undefined;
66+ const normalizedPreSave = preSaveContent.trim();
67+ const normalizedPostSave = postSaveContent.trim();
68+
69+ if (normalizedPreSave !== normalizedPostSave) {
70+ // Auto-formatting was applied by the editor
71+ const diffLines = myersDiff(preSaveContent, postSaveContent);
72+ autoFormattingDiff = diffLines
73+ .map((line) => {
74+ switch (line.type) {
75+ case "old":
76+ return `-${line.line}`;
77+ case "new":
78+ return `+${line.line}`;
79+ case "same":
80+ return ` ${line.line}`;
81+ }
82+ })
83+ .join("\n");
84+ }
85+
5486 await sidebar.webviewProtocol.request("updateApplyState", {
55- fileContent,
87+ fileContent: postSaveContent, // Use post-save content
5688 filepath: newOrCurrentUri,
5789 streamId,
5890 status: "closed",
5991 numDiffs: 0,
6092 toolCallId,
93+ autoFormattingDiff, // Include autoformatting diff
6194 });
95+ } else {
96+ // Save the file even if no streamId
97+ await ide.saveFile(newOrCurrentUri);
6298 }
63-
64- // Save the file
65- await ide.saveFile(newOrCurrentUri);
6699 }
modified extensions/vscode/src/util/addCode.ts +38 −18
@@ -36,22 +36,38 @@
3636 };
3737 }
3838
39- if (selection.isEmpty && !allowEmpty) {
39+ if ((selection.isEmpty && !allowEmpty) || isEmptyFile(editor.document)) {
4040 return null;
4141 }
4242
43- let selectionRange = new vscode.Range(selection.start, selection.end);
44- const document = editor.document;
45- // Select the context from the beginning of the selection start line to the selection start position
46- const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
47- const textBeforeSelectionStart = document.getText(
48- new vscode.Range(beginningOfSelectionStartLine, selection.start),
49- );
50- // If there are only whitespace before the start of the selection, include the indentation
51- if (textBeforeSelectionStart.trim().length === 0) {
52- selectionRange = selectionRange.with({
53- start: beginningOfSelectionStartLine,
54- });
43+ let selectionRange: vscode.Range | undefined;
44+ // if the selection is empty and document is not empty, select the whole document
45+ if (selection.isEmpty) {
46+ selectionRange = new vscode.Range(
47+ new vscode.Position(0, 0),
48+ new vscode.Position(
49+ editor.document.lineCount - 1,
50+ editor.document.lineAt(
51+ editor.document.lineCount - 1,
52+ ).range.end.character,
53+ ),
54+ );
55+ }
56+
57+ if (!selectionRange) {
58+ selectionRange = new vscode.Range(selection.start, selection.end);
59+ const document = editor.document;
60+ // Select the context from the beginning of the selection start line to the selection start position
61+ const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
62+ const textBeforeSelectionStart = document.getText(
63+ new vscode.Range(beginningOfSelectionStartLine, selection.start),
64+ );
65+ // If there are only whitespace before the start of the selection, include the indentation
66+ if (textBeforeSelectionStart.trim().length === 0) {
67+ selectionRange = selectionRange.with({
68+ start: beginningOfSelectionStartLine,
69+ });
70+ }
5571 }
5672
5773 const contents = editor.document.getText(selectionRange);
@@ -61,12 +77,12 @@
6177 contents,
6278 range: {
6379 start: {
64- line: selection.start.line,
65- character: selection.start.character,
80+ line: selectionRange.start.line,
81+ character: selectionRange.start.character,
6682 },
6783 end: {
68- line: selection.end.line,
69- character: selection.end.character,
84+ line: selectionRange.end.line,
85+ character: selectionRange.end.character,
7086 },
7187 },
7288 };
@@ -78,7 +94,7 @@
7894 export async function addHighlightedCodeToContext(
7995 webviewProtocol: VsCodeWebviewProtocol | undefined,
8096 ) {
81- const rangeInFileWithContents = getRangeInFileWithContents();
97+ const rangeInFileWithContents = getRangeInFileWithContents(true);
8298 if (rangeInFileWithContents) {
8399 webviewProtocol?.request("highlightedCode", {
84100 rangeInFileWithContents,
@@ -129,6 +145,10 @@
129145 });
130146 }
131147
148+export function isEmptyFile(document: vscode.TextDocument) {
149+ return document.lineCount === 1 && document.lineAt(0).range.isEmpty;
150+}
151+
132152 export function addCodeToContextFromRange(
133153 range: vscode.Range,
134154 webviewProtocol: VsCodeWebviewProtocol,
modified gui/src/components/mainInput/ContextStatus.tsx +22 −0
@@ -1,3 +1,4 @@
1+import { useMemo, useRef } from "react";
12 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
23 import { saveCurrentSession } from "../../redux/thunks/session";
34 import { useCompactConversation } from "../../util/compactConversation";
@@ -8,15 +9,36 @@
89 const contextPercentage = useAppSelector(
910 (state) => state.session.contextPercentage,
1011 );
12+ const selectedChatModel = useAppSelector(
13+ (state) => state.config.config.selectedModelByRole.chat?.model,
14+ );
15+ const previousHistoryLength = useRef<number | null>(null);
16+ const previousSelectedChatModel = useRef<string | null>(null);
1117 const history = useAppSelector((state) => state.session.history);
1218 const percent = Math.round((contextPercentage ?? 0) * 100);
1319 const isPruned = useAppSelector((state) => state.session.isPruned);
1420
21+ const isDifferentModelAndSameHistory = useMemo(() => {
22+ if (!selectedChatModel) return false;
23+ // only reset if history changes
24+ if (previousHistoryLength.current !== history.length) {
25+ previousHistoryLength.current = history.length;
26+ previousSelectedChatModel.current = selectedChatModel;
27+ return false;
28+ }
29+ return previousSelectedChatModel.current !== selectedChatModel;
30+ }, [history.length, selectedChatModel]);
31+
1532 const compactConversation = useCompactConversation();
1633 if (!isPruned && percent < 60) {
1734 return null;
1835 }
1936
37+ // if user changed to a different model, we shouldn't show the context status until the user sends a new message
38+ if (isDifferentModelAndSameHistory) {
39+ return null;
40+ }
41+
2042 const barColorClass = isPruned ? "bg-error" : "bg-description";
2143
2244 return (
modified gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +91 −11
@@ -1,13 +1,15 @@
1+import { BuiltInToolNames } from "core/tools/builtIn";
12 import { useContext, useEffect } from "react";
2-import { useSelector } from "react-redux";
33 import { IdeMessengerContext } from "../../../../context/IdeMessenger";
44 import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
55 import {
66 selectFirstPendingToolCall,
77 selectPendingToolCalls,
8+ selectToolCallsByStatus,
89 } from "../../../../redux/selectors/selectToolCalls";
910 import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
1011 import { callToolById } from "../../../../redux/thunks/callToolById";
12+import { cancelStream } from "../../../../redux/thunks/cancelStream";
1113 import { logToolUsage } from "../../../../redux/util";
1214 import { isJetBrains } from "../../../../util";
1315 import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
@@ -35,6 +37,14 @@
3537 return modifierKey && event.key === "Backspace";
3638 };
3739
40+// Check if a tool call is a terminal command
41+const isTerminalCommand = (toolCallState: any) => {
42+ return (
43+ toolCallState?.toolCall?.function?.name ===
44+ BuiltInToolNames.RunTerminalCommand
45+ );
46+};
47+
3848 export function LumpToolbar() {
3949 const dispatch = useAppDispatch();
4050 const ideMessenger = useContext(IdeMessengerContext);
@@ -55,13 +65,67 @@
5565 );
5666 const isApplying = applyStates.some((state) => state.status === "streaming");
5767
68+ // Get ALL running terminal commands
69+ const runningToolCalls = useAppSelector((state) =>
70+ selectToolCallsByStatus(state, "calling"),
71+ );
72+ const runningTerminalCalls = runningToolCalls.filter(isTerminalCommand);
73+ const hasRunningTerminalCommand = runningTerminalCalls.length > 0;
74+
75+ // Simple handler: stop ALL running terminal commands
76+ const handleStopAllTerminalCommands = async () => {
77+ if (runningTerminalCalls.length === 0) {
78+ return;
79+ }
80+
81+ // Stop all terminal commands concurrently
82+ const stopPromises = runningTerminalCalls.map(async (terminalCall) => {
83+ try {
84+ // Cancel the process on the backend
85+ await ideMessenger.request("process/killTerminalProcess", {
86+ toolCallId: terminalCall.toolCallId,
87+ });
88+
89+ // Cancel the tool call in the UI
90+ dispatch(
91+ cancelToolCall({
92+ toolCallId: terminalCall.toolCallId,
93+ }),
94+ );
95+
96+ logToolUsage(terminalCall, false, true, ideMessenger);
97+ } catch (error) {
98+ console.error(
99+ `Failed to cancel terminal command ${terminalCall.toolCallId}:`,
100+ error,
101+ );
102+ }
103+ });
104+
105+ // Wait for all cancellations to complete
106+ await Promise.all(stopPromises);
107+ };
108+
109+ // Combined stop handler
110+ const handleStopAction = async () => {
111+ // Stop all terminal commands if any are running
112+ if (hasRunningTerminalCommand) {
113+ await handleStopAllTerminalCommands();
114+ }
115+
116+ // Also stop regular streaming if it's happening
117+ if (isStreaming) {
118+ dispatch(cancelStream());
119+ }
120+ };
121+
58122 useEffect(() => {
59- if (!firstPendingToolCall) {
123+ if (!firstPendingToolCall && !hasRunningTerminalCommand) {
60124 return;
61125 }
62126
63127 const handleToolCallKeyboardShortcuts = (event: KeyboardEvent) => {
64- if (isExecuteToolCallShortcut(event)) {
128+ if (isExecuteToolCallShortcut(event) && firstPendingToolCall) {
65129 event.preventDefault();
66130 event.stopPropagation();
67131
@@ -71,13 +135,19 @@
71135 } else if (isCancelToolCallShortcut(event, jetbrains)) {
72136 event.preventDefault();
73137 event.stopPropagation();
74- void dispatch(
75- cancelToolCall({
76- toolCallId: firstPendingToolCall.toolCallId,
77- }),
78- );
79138
80- logToolUsage(firstPendingToolCall, false, true, ideMessenger);
139+ if (hasRunningTerminalCommand) {
140+ // Stop running terminal commands
141+ void handleStopAction();
142+ } else if (firstPendingToolCall) {
143+ // Cancel pending tool call
144+ void dispatch(
145+ cancelToolCall({
146+ toolCallId: firstPendingToolCall.toolCallId,
147+ }),
148+ );
149+ logToolUsage(firstPendingToolCall, false, true, ideMessenger);
150+ }
81151 }
82152 };
83153
@@ -85,7 +155,7 @@
85155 return () => {
86156 document.removeEventListener("keydown", handleToolCallKeyboardShortcuts);
87157 };
88- }, [firstPendingToolCall]);
158+ }, [firstPendingToolCall, hasRunningTerminalCommand, runningTerminalCalls]);
89159
90160 if (isApplying) {
91161 return <IsApplyingToolbar />;
@@ -103,8 +173,18 @@
103173 return <TtsActiveToolbar />;
104174 }
105175
176+ // Only show terminal streaming for actual terminal commands
177+ if (hasRunningTerminalCommand) {
178+ const count = runningTerminalCalls.length;
179+ const stopText = `Stop Terminal${count > 1 ? ` (${count})` : ""}`;
180+ return (
181+ <StreamingToolbar onStop={handleStopAction} displayText={stopText} />
182+ );
183+ }
184+
185+ // Regular streaming (non-terminal)
106186 if (isStreaming) {
107- return <StreamingToolbar />;
187+ return <StreamingToolbar onStop={() => dispatch(cancelStream())} />;
108188 }
109189
110190 if (pendingToolCalls.length > 0) {
modified gui/src/components/mainInput/Lump/LumpToolbar/StreamingToolbar.tsx +11 −6
@@ -1,20 +1,25 @@
1-import { useAppDispatch } from "../../../../redux/hooks";
2-import { cancelStream } from "../../../../redux/thunks/cancelStream";
31 import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util";
42 import { GeneratingIndicator } from "./GeneratingIndicator";
53
6-export function StreamingToolbar() {
4+interface StreamingToolbarProps {
5+ onStop: () => void;
6+ displayText?: string;
7+}
8+
9+export function StreamingToolbar({
10+ onStop,
11+ displayText = "Stop",
12+}: StreamingToolbarProps) {
713 const jetbrains = isJetBrains();
8- const dispatch = useAppDispatch();
914
1015 return (
1116 <div className="flex w-full items-center justify-between">
1217 <GeneratingIndicator />
1318 <div
14- onClick={() => void dispatch(cancelStream())}
19+ onClick={onStop}
1520 className="text-2xs cursor-pointer px-1.5 py-0.5 hover:brightness-125"
1621 >
17- <span className="text-description">Stop</span>
22+ <span className="text-description">{displayText}</span>
1823 {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
1924 <span className="text-description-muted ml-1 opacity-75">
2025 {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()}⌫
modified gui/src/redux/thunks/handleApplyStateUpdate.ts +45 −1
@@ -83,12 +83,57 @@
8383 }
8484
8585 if (accepted) {
86+ // Add autoformatting diff to tool output if present
87+ if (applyState.autoFormattingDiff) {
88+ dispatch(
89+ updateToolCallOutput({
90+ toolCallId: applyState.toolCallId,
91+ contextItems: [
92+ {
93+ icon: "info",
94+ name: "Auto-formatting Applied",
95+ description: "Editor auto-formatting changes",
96+ content: `Along with your edits, the editor applied the following auto-formatting:\n\n${applyState.autoFormattingDiff}\n\n(Note: Pay close attention to changes such as single quotes being converted to double quotes, semicolons being removed or added, long lines being broken into multiple lines, adjusting indentation style, adding/removing trailing commas, etc. This will help you ensure future SEARCH/REPLACE operations to this file are accurate.)`,
97+ hidden: false,
98+ },
99+ ],
100+ }),
101+ );
102+ }
103+
86104 if (toolCallState.status !== "errored") {
87105 dispatch(
88106 acceptToolCall({
89107 toolCallId: applyState.toolCallId,
90108 }),
91109 );
110+ dispatch(
111+ updateToolCallOutput({
112+ toolCallId: applyState.toolCallId,
113+ contextItems: [
114+ {
115+ name: "Edit Success",
116+ content: `Successfully edited ${applyState.filepath}`,
117+ description: "",
118+ hidden: true,
119+ },
120+ ],
121+ }),
122+ );
123+ } else {
124+ dispatch(
125+ updateToolCallOutput({
126+ toolCallId: applyState.toolCallId,
127+ contextItems: [
128+ {
129+ name: "Edit Failed",
130+ content: `Failed to edit ${applyState.filepath}. To continue working with the file, read it again to see the most up-to-date contents`,
131+ description: "",
132+ hidden: true,
133+ },
134+ ],
135+ }),
136+ );
92137 }
93138
94139 void dispatch(
@@ -98,7 +143,6 @@
98143 );
99144 }
100145 }
101- // TODO return output from edit tools so the model knows the result
102146 }
103147 }
104148 }
modified gui/src/redux/thunks/moveTerminalProcessToBackground.ts +1 −1
@@ -46,7 +46,7 @@
4646 {
4747 name: "Terminal",
4848 description: "Terminal command output",
49- content: existingContent + (existingContent ? "\n\n" : "") + status,
49+ content: existingContent,
5050 status: status,
5151 },
5252 ];
modified gui/src/redux/util/constructMessages.test.ts +343 −0
@@ -8,6 +8,7 @@
88 ToolResultChatMessage,
99 UserChatMessage,
1010 } from "core";
11+import { BuiltInToolNames } from "core/tools/builtIn";
1112 import {
1213 CANCELLED_TOOL_CALL_MESSAGE,
1314 NO_TOOL_CALL_OUTPUT_MESSAGE,
@@ -712,4 +713,346 @@
712713 expect(messages[0].content).toContain("Base System Message");
713714 expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule);
714715 });
716+
717+ // Tests for the specific block in lines 135-142 handling toolCallState.output
718+ describe("toolCallState.output handling (lines 135-142)", () => {
719+ test("should use CANCELLED_TOOL_CALL_MESSAGE for cancelled tool calls", () => {
720+ const assistantWithToolCall: AssistantChatMessage = {
721+ role: "assistant",
722+ content: "I'll run a command",
723+ toolCalls: [
724+ {
725+ id: "tool-call-1",
726+ type: "function",
727+ function: {
728+ name: "some_tool",
729+ arguments: '{"command": "ls"}',
730+ },
731+ },
732+ ],
733+ };
734+
735+ mockHistory = [
736+ {
737+ message: assistantWithToolCall,
738+ contextItems: [],
739+ toolCallStates: [
740+ {
741+ toolCallId: "tool-call-1",
742+ toolCall: {
743+ id: "tool-call-1",
744+ type: "function",
745+ function: {
746+ name: "some_tool",
747+ arguments: '{"command": "ls"}',
748+ },
749+ },
750+ status: "canceled",
751+ parsedArgs: { command: "ls" },
752+ output: [
753+ createContextItem(
754+ "result",
755+ "This should be ignored due to cancelled status",
756+ ),
757+ ],
758+ },
759+ ],
760+ },
761+ ];
762+
763+ const { messages } = constructMessages(
764+ mockHistory,
765+ "Base System Message",
766+ mockRules,
767+ {},
768+ );
769+
770+ const toolMessage = messages[2] as ToolResultChatMessage;
771+ expect(toolMessage.role).toBe("tool");
772+ expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE);
773+ expect(toolMessage.content).not.toContain("This should be ignored");
774+ });
775+
776+ test("should use renderContextItemsWithStatus for RunTerminalCommand with output", () => {
777+ const assistantWithTerminalCall: AssistantChatMessage = {
778+ role: "assistant",
779+ content: "I'll run a terminal command",
780+ toolCalls: [
781+ {
782+ id: "terminal-call-1",
783+ type: "function",
784+ function: {
785+ name: BuiltInToolNames.RunTerminalCommand,
786+ arguments: '{"command": "ls -la"}',
787+ },
788+ },
789+ ],
790+ };
791+
792+ const terminalOutputWithStatus = [
793+ {
794+ ...createContextItem("terminal-output", "file1.txt\nfile2.txt"),
795+ status: "completed",
796+ },
797+ {
798+ ...createContextItem("terminal-error", "Warning: deprecated flag"),
799+ status: "warning",
800+ },
801+ ];
802+
803+ mockHistory = [
804+ {
805+ message: assistantWithTerminalCall,
806+ contextItems: [],
807+ toolCallStates: [
808+ {
809+ toolCallId: "terminal-call-1",
810+ toolCall: {
811+ id: "terminal-call-1",
812+ type: "function",
813+ function: {
814+ name: BuiltInToolNames.RunTerminalCommand,
815+ arguments: '{"command": "ls -la"}',
816+ },
817+ },
818+ status: "done",
819+ parsedArgs: { command: "ls -la" },
820+ output: terminalOutputWithStatus,
821+ },
822+ ],
823+ },
824+ ];
825+
826+ const { messages } = constructMessages(
827+ mockHistory,
828+ "Base System Message",
829+ mockRules,
830+ {},
831+ );
832+
833+ const toolMessage = messages[2] as ToolResultChatMessage;
834+ expect(toolMessage.role).toBe("tool");
835+ expect(toolMessage.toolCallId).toBe("terminal-call-1");
836+ // Should contain content with status appended
837+ expect(toolMessage.content).toContain("file1.txt\nfile2.txt");
838+ expect(toolMessage.content).toContain("[Status: completed]");
839+ expect(toolMessage.content).toContain("Warning: deprecated flag");
840+ expect(toolMessage.content).toContain("[Status: warning]");
841+ // Should use renderContextItemsWithStatus format with double newlines between items
842+ expect(toolMessage.content).toMatch(
843+ /file1\.txt\nfile2\.txt\n\[Status: completed\]\n\nWarning: deprecated flag\n\[Status: warning\]/,
844+ );
845+ });
846+
847+ test("should use renderContextItems for non-RunTerminalCommand tools with output", () => {
848+ const assistantWithSearchCall: AssistantChatMessage = {
849+ role: "assistant",
850+ content: "I'll search for that",
851+ toolCalls: [
852+ {
853+ id: "search-call-1",
854+ type: "function",
855+ function: {
856+ name: "search", // Not RunTerminalCommand
857+ arguments: '{"query": "test"}',
858+ },
859+ },
860+ ],
861+ };
862+
863+ const searchOutput = [
864+ createContextItem("result1", "First search result"),
865+ createContextItem("result2", "Second search result"),
866+ ];
867+
868+ mockHistory = [
869+ {
870+ message: assistantWithSearchCall,
871+ contextItems: [],
872+ toolCallStates: [
873+ {
874+ toolCallId: "search-call-1",
875+ toolCall: {
876+ id: "search-call-1",
877+ type: "function",
878+ function: {
879+ name: "search",
880+ arguments: '{"query": "test"}',
881+ },
882+ },
883+ status: "done",
884+ parsedArgs: { query: "test" },
885+ output: searchOutput,
886+ },
887+ ],
888+ },
889+ ];
890+
891+ const { messages } = constructMessages(
892+ mockHistory,
893+ "Base System Message",
894+ mockRules,
895+ {},
896+ );
897+
898+ const toolMessage = messages[2] as ToolResultChatMessage;
899+ expect(toolMessage.role).toBe("tool");
900+ expect(toolMessage.toolCallId).toBe("search-call-1");
901+ // Should use renderContextItems format (no status, double newlines between items)
902+ expect(toolMessage.content).toBe(
903+ "First search result\n\nSecond search result",
904+ );
905+ expect(toolMessage.content).not.toContain("[Status:");
906+ });
907+
908+ test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when no output exists", () => {
909+ const assistantWithToolCall: AssistantChatMessage = {
910+ role: "assistant",
911+ content: "I'll search for that",
912+ toolCalls: [
913+ {
914+ id: "search-call-1",
915+ type: "function",
916+ function: {
917+ name: "search",
918+ arguments: '{"query": "test"}',
919+ },
920+ },
921+ ],
922+ };
923+
924+ mockHistory = [
925+ {
926+ message: assistantWithToolCall,
927+ contextItems: [],
928+ toolCallStates: [
929+ {
930+ toolCallId: "search-call-1",
931+ toolCall: {
932+ id: "search-call-1",
933+ type: "function",
934+ function: {
935+ name: "search",
936+ arguments: '{"query": "test"}',
937+ },
938+ },
939+ status: "generating",
940+ parsedArgs: { query: "test" },
941+ // No output field
942+ },
943+ ],
944+ },
945+ ];
946+
947+ const { messages } = constructMessages(
948+ mockHistory,
949+ "Base System Message",
950+ mockRules,
951+ {},
952+ );
953+
954+ const toolMessage = messages[2] as ToolResultChatMessage;
955+ expect(toolMessage.role).toBe("tool");
956+ expect(toolMessage.toolCallId).toBe("search-call-1");
957+ expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
958+ });
959+
960+ test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState is undefined", () => {
961+ const assistantWithToolCall: AssistantChatMessage = {
962+ role: "assistant",
963+ content: "I'll search for that",
964+ toolCalls: [
965+ {
966+ id: "search-call-1",
967+ type: "function",
968+ function: {
969+ name: "search",
970+ arguments: '{"query": "test"}',
971+ },
972+ },
973+ ],
974+ };
975+
976+ mockHistory = [
977+ {
978+ message: assistantWithToolCall,
979+ contextItems: [],
980+ // No toolCallStates array
981+ },
982+ ];
983+
984+ const { messages } = constructMessages(
985+ mockHistory,
986+ "Base System Message",
987+ mockRules,
988+ {},
989+ );
990+
991+ const toolMessage = messages[2] as ToolResultChatMessage;
992+ expect(toolMessage.role).toBe("tool");
993+ expect(toolMessage.toolCallId).toBe("search-call-1");
994+ expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
995+ });
996+
997+ test("should prioritize cancelled status over output content", () => {
998+ const assistantWithTerminalCall: AssistantChatMessage = {
999+ role: "assistant",
1000+ content: "I'll run a command",
1001+ toolCalls: [
1002+ {
1003+ id: "terminal-call-1",
1004+ type: "function",
1005+ function: {
1006+ name: BuiltInToolNames.RunTerminalCommand,
1007+ arguments: '{"command": "ls"}',
1008+ },
1009+ },
1010+ ],
1011+ };
1012+
1013+ mockHistory = [
1014+ {
1015+ message: assistantWithTerminalCall,
1016+ contextItems: [],
1017+ toolCallStates: [
1018+ {
1019+ toolCallId: "terminal-call-1",
1020+ toolCall: {
1021+ id: "terminal-call-1",
1022+ type: "function",
1023+ function: {
1024+ name: BuiltInToolNames.RunTerminalCommand,
1025+ arguments: '{"command": "ls"}',
1026+ },
1027+ },
1028+ status: "canceled", // Cancelled status
1029+ parsedArgs: { command: "ls" },
1030+ output: [
1031+ createContextItem(
1032+ "terminal-output",
1033+ "This output should be ignored",
1034+ ),
1035+ ], // Has output but is cancelled
1036+ },
1037+ ],
1038+ },
1039+ ];
1040+
1041+ const { messages } = constructMessages(
1042+ mockHistory,
1043+ "Base System Message",
1044+ mockRules,
1045+ {},
1046+ );
1047+
1048+ const toolMessage = messages[2] as ToolResultChatMessage;
1049+ expect(toolMessage.role).toBe("tool");
1050+ expect(toolMessage.toolCallId).toBe("terminal-call-1");
1051+ // Should use cancelled message, not the output content
1052+ expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE);
1053+ expect(toolMessage.content).not.toContain(
1054+ "This output should be ignored",
1055+ );
1056+ });
1057+ });
7151058 });
modified gui/src/redux/util/constructMessages.ts +13 −1
@@ -10,6 +10,7 @@
1010 import { chatMessageIsEmpty } from "core/llm/messages";
1111 import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules";
1212 import { RulePolicies } from "core/llm/rules/types";
13+import { BuiltInToolNames } from "core/tools/builtIn";
1314 import {
1415 CANCELLED_TOOL_CALL_MESSAGE,
1516 NO_TOOL_CALL_OUTPUT_MESSAGE,
@@ -20,8 +21,13 @@
2021 import {
2122 normalizeToMessageParts,
2223 renderContextItems,
24+ renderContextItemsWithStatus,
2325 } from "core/util/messageContent";
2426 import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/utils";
27+
28+// Helper function to render context items and append status information
29+// Helper function to render context items and append status information
30+
2531 interface MessageWithContextItems {
2632 ctxItems: ContextItemWithId[];
2733 message: ChatMessage;
@@ -132,8 +138,14 @@
132138
133139 if (toolCallState?.status === "canceled") {
134140 content = CANCELLED_TOOL_CALL_MESSAGE;
141+ } else if (
142+ toolCallState?.output &&
143+ toolCall.function?.name == BuiltInToolNames.RunTerminalCommand
144+ ) {
145+ // Add status for tools containing detailed status outcomes per context item
146+ content = renderContextItemsWithStatus(toolCallState.output);
135147 } else if (toolCallState?.output) {
136- content = renderContextItems(toolCallState.output);
148+ content = renderContextItems(toolCallState?.output);
137149 }
138150
139151 msgs.push({
modified gui/src/util/clientTools/editImpl.ts +3 −9
@@ -17,13 +17,13 @@
1717 filepath = filepath.slice(2);
1818 }
1919
20- const openFiles = await extras.ideMessenger.ide.getOpenFiles();
2120 let firstUriMatch = await resolveRelativePathInDir(
2221 filepath,
2322 extras.ideMessenger.ide,
2423 );
2524
2625 if (!firstUriMatch) {
26+ const openFiles = await extras.ideMessenger.ide.getOpenFiles();
2727 for (const uri of openFiles) {
2828 if (uri.endsWith(filepath)) {
2929 firstUriMatch = uri;
@@ -46,13 +46,7 @@
4646 );
4747
4848 return {
49- respondImmediately: true,
50- output: [
51- {
52- name: "File edited successfully",
53- content: `Successfully initiated edit for ${firstUriMatch}`,
54- description: "File edit operation started",
55- },
56- ],
49+ respondImmediately: false,
50+ output: undefined, // no immediate output - output for edit tools should be added based on apply state coming in
5751 };
5852 };
added packages/config-yaml/src/__tests__/test-files/invokable-rules.yaml +23 −0
@@ -0,0 +1,23 @@
1+name: Test Invokable Rules
2+version: 0.0.1
3+schema: v1
4+
5+rules:
6+ - name: "Code Review"
7+ rule: "Review this code for best practices and potential issues"
8+ invokable: true
9+ description: "Performs a code review"
10+
11+ - name: "Explain Code"
12+ rule: "Explain what this code does in simple terms"
13+ invokable: true
14+
15+ - name: "Regular Rule"
16+ rule: "This is a non-invokable rule"
17+ invokable: false
18+
19+ - name: "Default Rule"
20+ rule: "This rule has no invokable property"
21+ description: "Should default to non-invokable"
22+
23+ - "Simple string rule"
No newline at the end of the file
modified packages/config-yaml/src/schemas/index.ts +1 −0
@@ -57,6 +57,7 @@
5757 globs: z.union([z.string(), z.array(z.string())]).optional(),
5858 regex: z.union([z.string(), z.array(z.string())]).optional(),
5959 alwaysApply: z.boolean().optional(),
60+ invokable: z.boolean().optional(),
6061 sourceFile: z.string().optional(), //TODO refactor RuleWithSource.ruleFile to align with sourceFile
6162 });
6263 const ruleSchema = z.union([z.string(), ruleObjectSchema]);
modified packages/terminal-security/package-lock.json +9 −9
@@ -1322,14 +1322,14 @@
13221322 "license": "MIT"
13231323 },
13241324 "node_modules/tinyglobby": {
1325- "version": "0.2.14",
1326- "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
1327- "integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
1325+ "version": "0.2.15",
1326+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
1327+ "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
13281328 "dev": true,
13291329 "license": "MIT",
13301330 "dependencies": {
1331- "fdir": "^6.4.4",
1332- "picomatch": "^4.0.2"
1331+ "fdir": "^6.5.0",
1332+ "picomatch": "^4.0.3"
13331333 },
13341334 "engines": {
13351335 "node": ">=12.0.0"
@@ -1390,9 +1390,9 @@
13901390 "license": "MIT"
13911391 },
13921392 "node_modules/vite": {
1393- "version": "7.1.4",
1394- "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.4.tgz",
1395- "integrity": "sha512-X5QFK4SGynAeeIt+A7ZWnApdUyHYm+pzv/8/A57LqSGcI88U6R6ipOs3uCesdc6yl7nl+zNO0t8LmqAdXcQihw==",
1393+ "version": "7.1.5",
1394+ "resolved": "https://registry.npmjs.org/vite/-/vite-7.1.5.tgz",
1395+ "integrity": "sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==",
13961396 "dev": true,
13971397 "license": "MIT",
13981398 "dependencies": {
@@ -1401,7 +1401,7 @@
14011401 "picomatch": "^4.0.3",
14021402 "postcss": "^8.5.6",
14031403 "rollup": "^4.43.0",
1404- "tinyglobby": "^0.2.14"
1404+ "tinyglobby": "^0.2.15"
14051405 },
14061406 "bin": {
14071407 "vite": "bin/vite.js"