Merge branch 'main' of https://github.com/continuedev/continue into dallin/con-3885-no-any-rule
This commit is contained in:
commit
b67e476ccb
40 changed files with 1714 additions and 240 deletions
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Detailed PR Review
|
||||
uses: continuedev/continue/actions/detailed-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
|
||||
uses: continuedev/continue/actions/detailed-review@5dc7a050db441934c26eb910b8433291f627db7f
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: continuedev
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Continue PR Review Action
|
||||
uses: continuedev/continue/actions/general-review@b3f4b82600f603ca28c65a319b80ec36c4644ed7
|
||||
uses: continuedev/continue/actions/general-review@5dc7a050db441934c26eb910b8433291f627db7f
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "continuedev"
|
||||
|
|
|
|||
15
core/commands/slash/ruleBlockSlashCommand.ts
Normal file
15
core/commands/slash/ruleBlockSlashCommand.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { RuleWithSource, SlashCommandWithSource } from "../..";
|
||||
|
||||
export function convertRuleBlockToSlashCommand(
|
||||
rule: RuleWithSource,
|
||||
): SlashCommandWithSource {
|
||||
return {
|
||||
name:
|
||||
rule.name ||
|
||||
(rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule),
|
||||
description: rule.description ?? "",
|
||||
prompt: rule.rule,
|
||||
source: "invokable-rule",
|
||||
promptFile: rule.ruleFile,
|
||||
};
|
||||
}
|
||||
93
core/commands/slash/ruleBlockSlashCommand.vitest.ts
Normal file
93
core/commands/slash/ruleBlockSlashCommand.vitest.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { RuleWithSource } from "../..";
|
||||
import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand";
|
||||
|
||||
describe("convertRuleBlockToSlashCommand", () => {
|
||||
it("should convert a rule with all properties to a slash command", () => {
|
||||
const rule: RuleWithSource = {
|
||||
name: "Code Review",
|
||||
rule: "Review this code for best practices",
|
||||
description: "Performs a code review",
|
||||
source: "rules-block",
|
||||
ruleFile: "/path/to/rules.yaml",
|
||||
invokable: true,
|
||||
};
|
||||
|
||||
const result = convertRuleBlockToSlashCommand(rule);
|
||||
|
||||
expect(result).toEqual({
|
||||
name: "Code Review",
|
||||
description: "Performs a code review",
|
||||
prompt: "Review this code for best practices",
|
||||
source: "invokable-rule",
|
||||
promptFile: "/path/to/rules.yaml",
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle a rule without name", () => {
|
||||
const rule: RuleWithSource = {
|
||||
rule: "Review this code",
|
||||
source: "rules-block",
|
||||
invokable: true,
|
||||
};
|
||||
|
||||
const result = convertRuleBlockToSlashCommand(rule);
|
||||
|
||||
expect(result.name).toBe("Review this code");
|
||||
expect(result.prompt).toBe("Review this code");
|
||||
});
|
||||
|
||||
it("should truncate long rule text when used as name", () => {
|
||||
const rule: RuleWithSource = {
|
||||
rule: "This is a very long rule text that should be truncated",
|
||||
source: "rules-block",
|
||||
invokable: true,
|
||||
};
|
||||
|
||||
const result = convertRuleBlockToSlashCommand(rule);
|
||||
|
||||
expect(result.name).toBe("This is a very long ...");
|
||||
expect(result.prompt).toBe(
|
||||
"This is a very long rule text that should be truncated",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle a rule without description", () => {
|
||||
const rule: RuleWithSource = {
|
||||
name: "Test Rule",
|
||||
rule: "Test rule content",
|
||||
source: "rules-block",
|
||||
invokable: true,
|
||||
};
|
||||
|
||||
const result = convertRuleBlockToSlashCommand(rule);
|
||||
|
||||
expect(result.description).toBe("");
|
||||
});
|
||||
|
||||
it("should use rule text as the prompt", () => {
|
||||
const rule: RuleWithSource = {
|
||||
name: "Explain Code",
|
||||
rule: "Explain what this code does in simple terms",
|
||||
source: "rules-block",
|
||||
invokable: true,
|
||||
};
|
||||
|
||||
const result = convertRuleBlockToSlashCommand(rule);
|
||||
|
||||
expect(result.prompt).toBe("Explain what this code does in simple terms");
|
||||
});
|
||||
|
||||
it("should always set source to 'invokable-rule'", () => {
|
||||
const rule: RuleWithSource = {
|
||||
name: "Test",
|
||||
rule: "Test",
|
||||
source: "default-chat",
|
||||
invokable: true,
|
||||
};
|
||||
|
||||
const result = convertRuleBlockToSlashCommand(rule);
|
||||
|
||||
expect(result.source).toBe("invokable-rule");
|
||||
});
|
||||
});
|
||||
|
|
@ -1061,6 +1061,7 @@ declare global {
|
|||
filepath?: string;
|
||||
fileContent?: string;
|
||||
originalFileContent?: string;
|
||||
autoFormattingDiff?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
|
||||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
|
|
@ -208,7 +209,21 @@ async function configYamlToContinueConfig(options: {
|
|||
}
|
||||
|
||||
for (const rule of config.rules ?? []) {
|
||||
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
|
||||
const convertedRule = convertYamlRuleToContinueRule(rule);
|
||||
continueConfig.rules.push(convertedRule);
|
||||
|
||||
// Convert invokable rules to slash commands
|
||||
if (convertedRule.invokable) {
|
||||
try {
|
||||
const slashCommand = convertRuleBlockToSlashCommand(convertedRule);
|
||||
continueConfig.slashCommands?.push(slashCommand);
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`,
|
||||
fatal: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
continueConfig.data = config.data;
|
||||
|
|
|
|||
|
|
@ -13,8 +13,10 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
rule: rule.rule,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
description: rule.description,
|
||||
ruleFile: rule.sourceFile,
|
||||
alwaysApply: rule.alwaysApply,
|
||||
invokable: rule.invokable,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
2
core/index.d.ts
vendored
2
core/index.d.ts
vendored
|
|
@ -1387,6 +1387,7 @@ export interface ApplyState {
|
|||
fileContent?: string;
|
||||
originalFileContent?: string;
|
||||
toolCallId?: string;
|
||||
autoFormattingDiff?: string;
|
||||
}
|
||||
|
||||
export interface StreamDiffLinesPayload {
|
||||
|
|
@ -1807,6 +1808,7 @@ export interface RuleWithSource {
|
|||
description?: string;
|
||||
ruleFile?: string;
|
||||
alwaysApply?: boolean;
|
||||
invokable?: boolean;
|
||||
}
|
||||
export interface CompleteOnboardingPayload {
|
||||
mode: OnboardingModes;
|
||||
|
|
|
|||
|
|
@ -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];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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" }));
|
||||
|
|
|
|||
|
|
@ -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":
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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);
|
||||
}
|
||||
367
core/util/processTerminalStates.test.ts
Normal file
367
core/util/processTerminalStates.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
119
core/util/processTerminalStates.ts
Normal file
119
core/util/processTerminalStates.ts
Normal 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();
|
||||
}
|
||||
62
extensions/cli/src/stream/messageQueue.test.ts
Normal file
62
extensions/cli/src/stream/messageQueue.test.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../util/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
setLevel: vi.fn(),
|
||||
configureHeadlessMode: vi.fn(),
|
||||
getLogPath: vi.fn(),
|
||||
getSessionId: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { messageQueue } from "./messageQueue.js";
|
||||
|
||||
describe("messageQueue", () => {
|
||||
beforeEach(() => {
|
||||
// Drain any leftover items from previous tests
|
||||
while (messageQueue.getAllQueuedMessages()) {}
|
||||
});
|
||||
|
||||
it("enqueues and emits messageQueued", async () => {
|
||||
const event = new Promise<any>((resolve) =>
|
||||
messageQueue.once("messageQueued", resolve),
|
||||
);
|
||||
|
||||
const ok = await messageQueue.enqueueMessage("hello world");
|
||||
expect(ok).toBe(true);
|
||||
expect(messageQueue.getQueueLength()).toBe(1);
|
||||
|
||||
const queued = await event;
|
||||
expect(queued.message).toBe("hello world");
|
||||
});
|
||||
|
||||
it("combines messages, merges image maps, writes history, and clears queue", async () => {
|
||||
const bufA = Buffer.from("A");
|
||||
const bufB = Buffer.from("B");
|
||||
|
||||
const img1 = new Map<string, Buffer>([["a", bufA]]);
|
||||
const img2 = new Map<string, Buffer>([["b", bufB]]);
|
||||
|
||||
const history = { addEntry: vi.fn() } as any;
|
||||
|
||||
await messageQueue.enqueueMessage("one", img1);
|
||||
await messageQueue.enqueueMessage("two", img2, history);
|
||||
|
||||
const combined = messageQueue.getAllQueuedMessages();
|
||||
expect(combined).toBeTruthy();
|
||||
expect(combined!.message).toBe("one\ntwo");
|
||||
expect(combined!.imageMap).toBeDefined();
|
||||
expect(combined!.imageMap!.get("a")).toEqual(bufA);
|
||||
expect(combined!.imageMap!.get("b")).toEqual(bufB);
|
||||
|
||||
// queue should be cleared
|
||||
expect(messageQueue.getQueueLength()).toBe(0);
|
||||
|
||||
// input history should receive the combined message
|
||||
expect(history.addEntry).toHaveBeenCalledWith("one\ntwo");
|
||||
});
|
||||
});
|
||||
94
extensions/cli/src/stream/messageQueue.ts
Normal file
94
extensions/cli/src/stream/messageQueue.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { EventEmitter } from "events";
|
||||
|
||||
import { InputHistory } from "../util/inputHistory.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
export interface QueuedMessage {
|
||||
message: string;
|
||||
imageMap?: Map<string, Buffer>;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface MessageProcessor {
|
||||
(message: string, imageMap?: Map<string, Buffer>): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A queue to store messages that need to be processed later
|
||||
*/
|
||||
class MessageQueue extends EventEmitter {
|
||||
private queue: QueuedMessage[] = [];
|
||||
private inputHistory: InputHistory | undefined;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
async enqueueMessage(
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
inputHistory?: InputHistory,
|
||||
): Promise<boolean> {
|
||||
this.inputHistory = inputHistory;
|
||||
|
||||
const queuedMessage: QueuedMessage = {
|
||||
message,
|
||||
imageMap,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
this.queue.push(queuedMessage);
|
||||
logger.debug("MessageQueue: Message queued", {
|
||||
queueLength: this.queue.length,
|
||||
});
|
||||
|
||||
// Emit event for UI to show the queued message
|
||||
this.emit("messageQueued", queuedMessage);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public getAllQueuedMessages() {
|
||||
if (this.queue.length === 0) return undefined;
|
||||
|
||||
// Combine all queued messages into one
|
||||
const combinedMessage = this.queue.map((msg) => msg.message).join("\n");
|
||||
const combinedImageMap = new Map<string, Buffer>();
|
||||
|
||||
// Merge all image maps
|
||||
for (const queuedMsg of this.queue) {
|
||||
if (queuedMsg.imageMap) {
|
||||
for (const [key, value] of queuedMsg.imageMap) {
|
||||
combinedImageMap.set(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
message: combinedMessage,
|
||||
imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
// Add to input history and clear the queue
|
||||
this.inputHistory?.addEntry(combinedMessage);
|
||||
this.queue = [];
|
||||
|
||||
logger.debug("MessageQueue: All messages dequeued and combined", {
|
||||
combinedLength: combinedMessage.length,
|
||||
queueLength: this.queue.length,
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public getLatestMessage() {
|
||||
return this.getAllQueuedMessages();
|
||||
}
|
||||
|
||||
getQueueLength(): number {
|
||||
return this.queue.length;
|
||||
}
|
||||
}
|
||||
|
||||
export const messageQueue = new MessageQueue();
|
||||
|
|
@ -188,6 +188,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
inputMode,
|
||||
activePermissionRequest,
|
||||
wasInterrupted,
|
||||
queuedMessages,
|
||||
handleUserMessage,
|
||||
handleInterrupt,
|
||||
handleFileAttached,
|
||||
|
|
@ -282,6 +283,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
model={services.model?.model || undefined}
|
||||
mcpService={services.mcp?.mcpService || undefined}
|
||||
chatHistory={chatHistory}
|
||||
queuedMessages={queuedMessages}
|
||||
renderMessage={renderMessage}
|
||||
refreshTrigger={staticRefreshTrigger}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import type { PermissionMode } from "../permissions/types.js";
|
|||
import type { FileIndexServiceState } from "../services/FileIndexService.js";
|
||||
import { SERVICE_NAMES, serviceContainer } from "../services/index.js";
|
||||
import { modeService } from "../services/ModeService.js";
|
||||
import { messageQueue } from "../stream/messageQueue.js";
|
||||
import { InputHistory } from "../util/inputHistory.js";
|
||||
|
||||
import { FileSearchUI } from "./FileSearchUI.js";
|
||||
|
|
@ -515,7 +516,7 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
}
|
||||
|
||||
// Normal Enter behavior - submit if there's content
|
||||
if ((textBuffer.text.trim() || wasInterrupted) && !isWaitingForResponse) {
|
||||
if (textBuffer.text.trim() || wasInterrupted) {
|
||||
// Get images before expanding paste blocks
|
||||
const imageMap = textBuffer.getAllImages();
|
||||
|
||||
|
|
@ -523,14 +524,19 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
textBuffer.expandAllPasteBlocks();
|
||||
const submittedText = textBuffer.text.trim();
|
||||
|
||||
// Only add to history if there's actual text (not when resuming)
|
||||
if (submittedText) {
|
||||
if (isWaitingForResponse) {
|
||||
// Process message later when LLM has responded
|
||||
void messageQueue.enqueueMessage(
|
||||
submittedText,
|
||||
imageMap,
|
||||
inputHistory,
|
||||
);
|
||||
} else {
|
||||
// Submit with images
|
||||
inputHistory.addEntry(submittedText);
|
||||
onSubmit(submittedText, imageMap);
|
||||
}
|
||||
|
||||
// Submit with images
|
||||
onSubmit(submittedText, imageMap);
|
||||
|
||||
textBuffer.clear();
|
||||
setInputText("");
|
||||
setCursorPosition(0);
|
||||
|
|
@ -647,15 +653,6 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
// Allow typing during streaming, but block submission
|
||||
if (!inputMode) {
|
||||
// Block only Enter key submission during streaming
|
||||
if (key.return && !key.shift) {
|
||||
return;
|
||||
}
|
||||
// Allow all other input (typing, navigation, etc.)
|
||||
}
|
||||
|
||||
// Handle slash command navigation
|
||||
if (showSlashCommands) {
|
||||
if (handleSlashCommandNavigation(key)) {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import type { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { Box, Static, useStdout } from "ink";
|
||||
import { Box, Static, Text, useStdout } from "ink";
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import type { ChatHistoryItem } from "../../../../../core/index.js";
|
||||
import type { MCPService } from "../../services/MCPService.js";
|
||||
import type { QueuedMessage } from "../../stream/messageQueue.js";
|
||||
import { useTerminalSize } from "../hooks/useTerminalSize.js";
|
||||
import { IntroMessage } from "../IntroMessage.js";
|
||||
|
||||
|
|
@ -13,6 +14,7 @@ interface StaticChatContentProps {
|
|||
model?: ModelConfig;
|
||||
mcpService?: MCPService;
|
||||
chatHistory: ChatHistoryItem[];
|
||||
queuedMessages?: QueuedMessage[];
|
||||
renderMessage: (item: ChatHistoryItem, index: number) => React.ReactElement;
|
||||
refreshTrigger?: number; // Add a prop to trigger refresh from parent
|
||||
}
|
||||
|
|
@ -23,6 +25,7 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
|
|||
model,
|
||||
mcpService,
|
||||
chatHistory,
|
||||
queuedMessages = [],
|
||||
renderMessage,
|
||||
refreshTrigger,
|
||||
}) => {
|
||||
|
|
@ -140,6 +143,15 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
|
|||
<React.Fragment key={`pending-${index}`}>{item}</React.Fragment>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
{/* Queued messages - show at bottom with queue indicators */}
|
||||
{queuedMessages.length > 0 && (
|
||||
<Box paddingLeft={2} paddingBottom={1}>
|
||||
<Text color="gray" italic>
|
||||
{queuedMessages.map((msg) => msg.message).join("\n")}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
/* eslint-disable max-lines */
|
||||
import type { ChatHistoryItem, Session } from "core/index.js";
|
||||
import { useApp } from "ink";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
|
@ -11,6 +12,7 @@ import {
|
|||
updateSessionHistory,
|
||||
} from "../../session.js";
|
||||
import { handleSlashCommands } from "../../slashCommands.js";
|
||||
import { messageQueue, QueuedMessage } from "../../stream/messageQueue.js";
|
||||
import { telemetryService } from "../../telemetry/telemetryService.js";
|
||||
import { formatError } from "../../util/formatError.js";
|
||||
import { logger } from "../../util/logger.js";
|
||||
|
|
@ -166,6 +168,22 @@ export function useChat({
|
|||
// Track interrupted state for resume functionality
|
||||
const [wasInterrupted, setWasInterrupted] = useState(false);
|
||||
|
||||
// Track queued messages for immediate display
|
||||
const [queuedMessages, setQueuedMessages] = useState<QueuedMessage[]>([]);
|
||||
|
||||
// Set up message queue listeners
|
||||
useEffect(() => {
|
||||
const onMessageQueued = (queuedMessage: QueuedMessage) => {
|
||||
setQueuedMessages((prev) => [...prev, queuedMessage]);
|
||||
};
|
||||
|
||||
messageQueue.on("messageQueued", onMessageQueued);
|
||||
|
||||
return () => {
|
||||
messageQueue.off("messageQueued", onMessageQueued);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Clean up abort controller on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
|
|
@ -306,6 +324,30 @@ export function useChat({
|
|||
setIsWaitingForResponse(false);
|
||||
setResponseStartTime(null);
|
||||
setInputMode(true);
|
||||
|
||||
// Check if there are queued messages and process them after a microtask delay
|
||||
// This ensures the GUI state has been updated before processing the next message
|
||||
const queuedMessageData = messageQueue.getLatestMessage();
|
||||
if (queuedMessageData) {
|
||||
const { message: latestQueuedMessage, imageMap } = queuedMessageData;
|
||||
logger.debug("processing queued message", { latestQueuedMessage });
|
||||
|
||||
// Clear all queued messages from display since we're processing them all together
|
||||
setQueuedMessages([]);
|
||||
|
||||
// Add the queued message to chat history so it shows in the GUI
|
||||
const formattedQueuedMessage = await formatMessageWithFiles(
|
||||
latestQueuedMessage,
|
||||
[], // No attached files for queued messages
|
||||
imageMap,
|
||||
);
|
||||
setChatHistory((prev) => [...prev, formattedQueuedMessage]);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui
|
||||
|
||||
// Process the queued message using the internal processing logic without re-adding to history
|
||||
await processQueuedMessage(latestQueuedMessage, imageMap);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -398,20 +440,11 @@ export function useChat({
|
|||
.join("");
|
||||
};
|
||||
|
||||
const handleUserMessage = async (
|
||||
const processMessage = async (
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
isQueuedMessage: boolean = false,
|
||||
) => {
|
||||
// Check if this is a resume request (empty message after interruption)
|
||||
if (await handleResumeRequest(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear interrupted state if user types a new message
|
||||
if (wasInterrupted && message !== "") {
|
||||
setWasInterrupted(false);
|
||||
}
|
||||
|
||||
// Handle special commands
|
||||
const handled = await handleSpecialCommands({
|
||||
message,
|
||||
|
|
@ -440,27 +473,9 @@ export function useChat({
|
|||
// Track telemetry
|
||||
trackUserMessage(message, model);
|
||||
|
||||
// Format message with attached files and images
|
||||
logger.debug("Processing message with images", {
|
||||
hasImages: !!(imageMap && imageMap.size > 0),
|
||||
imageCount: imageMap?.size || 0,
|
||||
});
|
||||
const newUserMessage = await formatMessageWithFiles(
|
||||
message,
|
||||
attachedFiles,
|
||||
imageMap,
|
||||
);
|
||||
logger.debug("Message formatted successfully");
|
||||
|
||||
if (attachedFiles.length > 0) {
|
||||
setAttachedFiles([]);
|
||||
}
|
||||
|
||||
// In remote mode, send message to server instead of processing locally
|
||||
if (isRemoteMode && remoteUrl) {
|
||||
const messageContentString = convertMessageContentToString(
|
||||
newUserMessage.message.content,
|
||||
);
|
||||
const messageContentString = convertMessageContentToString(message);
|
||||
|
||||
await handleRemoteMessage({
|
||||
remoteUrl,
|
||||
|
|
@ -469,23 +484,87 @@ export function useChat({
|
|||
return;
|
||||
}
|
||||
|
||||
// Check if auto-compacting is needed BEFORE adding user message
|
||||
const { currentChatHistory, currentCompactionIndex } =
|
||||
await handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex,
|
||||
setChatHistory: setChatHistory,
|
||||
setCompactionIndex,
|
||||
// For non-queued messages, format and add to chat history
|
||||
if (isQueuedMessage) {
|
||||
// For queued messages, chat history is already updated
|
||||
// Check if auto-compacting is needed with current history
|
||||
const { currentChatHistory, currentCompactionIndex } =
|
||||
await handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex,
|
||||
setChatHistory: setChatHistory,
|
||||
setCompactionIndex,
|
||||
});
|
||||
|
||||
// Execute the streaming response with the current history (which already includes the queued message)
|
||||
await executeStreamingResponse(
|
||||
currentChatHistory,
|
||||
currentCompactionIndex,
|
||||
);
|
||||
} else {
|
||||
// Format message with attached files and images
|
||||
logger.debug("Processing message with images", {
|
||||
hasImages: !!(imageMap && imageMap.size > 0),
|
||||
imageCount: imageMap?.size || 0,
|
||||
});
|
||||
const newUserMessage = await formatMessageWithFiles(
|
||||
message,
|
||||
attachedFiles,
|
||||
imageMap,
|
||||
);
|
||||
logger.debug("Message formatted successfully");
|
||||
|
||||
// Add the formatted user message to history
|
||||
const newHistory = [...currentChatHistory, newUserMessage];
|
||||
setChatHistory(newHistory);
|
||||
if (attachedFiles.length > 0) {
|
||||
setAttachedFiles([]);
|
||||
}
|
||||
|
||||
// Execute the streaming response
|
||||
await executeStreamingResponse(newHistory, currentCompactionIndex);
|
||||
// Check if auto-compacting is needed BEFORE adding user message
|
||||
const { currentChatHistory, currentCompactionIndex } =
|
||||
await handleAutoCompaction({
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
compactionIndex,
|
||||
setChatHistory: setChatHistory,
|
||||
setCompactionIndex,
|
||||
});
|
||||
|
||||
// Add the formatted user message to history
|
||||
const newHistory = [...currentChatHistory, newUserMessage];
|
||||
setChatHistory(newHistory);
|
||||
|
||||
// Execute the streaming response
|
||||
await executeStreamingResponse(newHistory, currentCompactionIndex);
|
||||
}
|
||||
};
|
||||
|
||||
const processQueuedMessage = async (
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
) => {
|
||||
// For queued messages, we can reuse the core message processing logic
|
||||
// by calling the internal processing function directly
|
||||
await processMessage(message, imageMap, true);
|
||||
};
|
||||
|
||||
const handleUserMessage = async (
|
||||
message: string,
|
||||
imageMap?: Map<string, Buffer>,
|
||||
) => {
|
||||
// Check if this is a resume request (empty message after interruption)
|
||||
if (await handleResumeRequest(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear interrupted state if user types a new message
|
||||
if (wasInterrupted && message !== "") {
|
||||
setWasInterrupted(false);
|
||||
}
|
||||
|
||||
// Use the common message processing logic
|
||||
await processMessage(message, imageMap, false);
|
||||
};
|
||||
|
||||
const handleInterrupt = () => {
|
||||
|
|
@ -537,6 +616,8 @@ export function useChat({
|
|||
additionalRules,
|
||||
);
|
||||
setChatHistory(newHistory);
|
||||
// Clear any queued messages when resetting chat
|
||||
setQueuedMessages([]);
|
||||
};
|
||||
|
||||
const handleToolPermissionResponse = async (
|
||||
|
|
@ -614,6 +695,7 @@ export function useChat({
|
|||
attachedFiles,
|
||||
activePermissionRequest,
|
||||
wasInterrupted,
|
||||
queuedMessages,
|
||||
handleUserMessage,
|
||||
handleInterrupt,
|
||||
handleFileAttached,
|
||||
|
|
|
|||
|
|
@ -146,6 +146,7 @@ class MessageTypes {
|
|||
"isItemTooBig",
|
||||
"process/markAsBackgrounded",
|
||||
"process/isBackgrounded",
|
||||
"process/killTerminalProcess"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,12 +4,12 @@ import {
|
|||
InputBox,
|
||||
Key,
|
||||
TextEditor,
|
||||
until,
|
||||
VSBrowser,
|
||||
WebDriver,
|
||||
WebElement,
|
||||
WebView,
|
||||
Workbench,
|
||||
until,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { GlobalActions } from "../actions/Global.actions";
|
||||
|
|
@ -47,11 +47,31 @@ describe("Keyboard Shortcuts", () => {
|
|||
|
||||
afterEach(async function () {
|
||||
this.timeout(DEFAULT_TIMEOUT.XL * 1000);
|
||||
await cleanupChat();
|
||||
await view.switchBack();
|
||||
await editor.clearText();
|
||||
await new EditorView().closeAllEditors();
|
||||
});
|
||||
|
||||
async function cleanupChat(chatInput?: WebElement) {
|
||||
try {
|
||||
if (!chatInput) {
|
||||
chatInput = await TestUtils.waitForSuccess(async () => {
|
||||
return GUISelectors.getMessageInputFieldAtIndex(view, 0);
|
||||
});
|
||||
}
|
||||
if (
|
||||
chatInput &&
|
||||
(await chatInput.isDisplayed()) &&
|
||||
(await chatInput.isEnabled())
|
||||
) {
|
||||
await chatInput.clear();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`Failed to clear chat: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
it("Should correctly undo and redo using keyboard shortcuts when writing a chat message", async () => {
|
||||
await GUIActions.executeFocusContinueInputShortcut(driver);
|
||||
({ view } = await GUIActions.switchToReactIframe());
|
||||
|
|
@ -105,10 +125,8 @@ describe("Keyboard Shortcuts", () => {
|
|||
);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
it("Should not create a code block when Cmd+L is pressed without text highlighted", async () => {
|
||||
const text = "Hello, world!";
|
||||
|
||||
await editor.setText(text);
|
||||
it("Should not create a code block when Cmd+L is pressed on an empty document", async () => {
|
||||
expect((await editor.getText()).trim()).to.equal("");
|
||||
|
||||
await GUIActions.executeFocusContinueInputShortcut(driver);
|
||||
|
||||
|
|
@ -174,6 +192,9 @@ describe("Keyboard Shortcuts", () => {
|
|||
|
||||
await driver.wait(until.elementIsNotVisible(textInput), DEFAULT_TIMEOUT.XS);
|
||||
expect(await textInput.isDisplayed()).to.equal(false);
|
||||
|
||||
// Make sure the view is visible again, so it can be cleared in afterEach()
|
||||
await GUIActions.executeFocusContinueInputShortcut(driver);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
it("Should create a code block when Cmd+L is pressed with text highlighted", async () => {
|
||||
|
|
@ -197,4 +218,44 @@ describe("Keyboard Shortcuts", () => {
|
|||
|
||||
await GUIActions.executeFocusContinueInputShortcut(driver);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
|
||||
it("Should create a code block with the whole file when Cmd+L is pressed on an empty line", async () => {
|
||||
const text = "Hello,\n\n\nworld!";
|
||||
|
||||
await editor.setText(text);
|
||||
await editor.moveCursor(2, 1); //Move cursor to an empty line
|
||||
|
||||
await GUIActions.executeFocusContinueInputShortcut(driver);
|
||||
|
||||
({ view } = await GUIActions.switchToReactIframe());
|
||||
|
||||
const codeBlock = await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getInputBoxCodeBlockAtIndex(view, 0),
|
||||
);
|
||||
const codeblockContent = await codeBlock.getAttribute(
|
||||
"data-codeblockcontent",
|
||||
);
|
||||
|
||||
expect(codeblockContent).to.equal(text);
|
||||
});
|
||||
|
||||
it("Should create a code block when Cmd+L is pressed on a non-empty line", async () => {
|
||||
const text = "Hello, world!";
|
||||
|
||||
await editor.setText(text);
|
||||
await editor.moveCursor(1, 7); //Move cursor to the 1st space
|
||||
|
||||
await GUIActions.executeFocusContinueInputShortcut(driver);
|
||||
|
||||
({ view } = await GUIActions.switchToReactIframe());
|
||||
|
||||
const codeBlock = await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getInputBoxCodeBlockAtIndex(view, 0),
|
||||
);
|
||||
const codeblockContent = await codeBlock.getAttribute(
|
||||
"data-codeblockcontent",
|
||||
);
|
||||
|
||||
expect(codeblockContent).to.equal(text);
|
||||
}).timeout(DEFAULT_TIMEOUT.XL);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -524,13 +524,12 @@
|
|||
"continue.continueSubMenu": [
|
||||
{
|
||||
"command": "continue.focusContinueInputWithoutClear",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection"
|
||||
"group": "Continue"
|
||||
},
|
||||
{
|
||||
"command": "continue.focusEdit",
|
||||
"group": "Continue",
|
||||
"when": "editorHasSelection && !editorReadonly"
|
||||
"when": "!editorReadonly"
|
||||
}
|
||||
],
|
||||
"explorer/context": [
|
||||
|
|
|
|||
|
|
@ -1,8 +1,11 @@
|
|||
import { Core } from "core/core";
|
||||
import { DataLogger } from "core/data/log";
|
||||
import { myersDiff } from "core/diff/myers";
|
||||
|
||||
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
|
||||
import { editOutcomeTracker } from "../extension/EditOutcomeTracker";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
|
||||
import { VerticalDiffManager } from "./vertical/manager";
|
||||
|
||||
export async function processDiff(
|
||||
|
|
@ -42,7 +45,8 @@ export async function processDiff(
|
|||
}
|
||||
|
||||
if (streamId) {
|
||||
const fileContent = await ide.readFile(newOrCurrentUri);
|
||||
// Capture file content before save to detect autoformatting
|
||||
const preSaveContent = await ide.readFile(newOrCurrentUri);
|
||||
|
||||
// Record the edit outcome before updating the apply state
|
||||
await editOutcomeTracker.recordEditOutcome(
|
||||
|
|
@ -51,16 +55,45 @@ export async function processDiff(
|
|||
DataLogger.getInstance(),
|
||||
);
|
||||
|
||||
// Save the file
|
||||
await ide.saveFile(newOrCurrentUri);
|
||||
|
||||
// Capture file content after save to detect autoformatting
|
||||
const postSaveContent = await ide.readFile(newOrCurrentUri);
|
||||
|
||||
// Detect autoformatting by comparing normalized content
|
||||
let autoFormattingDiff: string | undefined;
|
||||
const normalizedPreSave = preSaveContent.trim();
|
||||
const normalizedPostSave = postSaveContent.trim();
|
||||
|
||||
if (normalizedPreSave !== normalizedPostSave) {
|
||||
// Auto-formatting was applied by the editor
|
||||
const diffLines = myersDiff(preSaveContent, postSaveContent);
|
||||
autoFormattingDiff = diffLines
|
||||
.map((line) => {
|
||||
switch (line.type) {
|
||||
case "old":
|
||||
return `-${line.line}`;
|
||||
case "new":
|
||||
return `+${line.line}`;
|
||||
case "same":
|
||||
return ` ${line.line}`;
|
||||
}
|
||||
})
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
await sidebar.webviewProtocol.request("updateApplyState", {
|
||||
fileContent,
|
||||
fileContent: postSaveContent, // Use post-save content
|
||||
filepath: newOrCurrentUri,
|
||||
streamId,
|
||||
status: "closed",
|
||||
numDiffs: 0,
|
||||
toolCallId,
|
||||
autoFormattingDiff, // Include autoformatting diff
|
||||
});
|
||||
} else {
|
||||
// Save the file even if no streamId
|
||||
await ide.saveFile(newOrCurrentUri);
|
||||
}
|
||||
|
||||
// Save the file
|
||||
await ide.saveFile(newOrCurrentUri);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,22 +36,38 @@ export function getRangeInFileWithContents(
|
|||
};
|
||||
}
|
||||
|
||||
if (selection.isEmpty && !allowEmpty) {
|
||||
if ((selection.isEmpty && !allowEmpty) || isEmptyFile(editor.document)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let selectionRange = new vscode.Range(selection.start, selection.end);
|
||||
const document = editor.document;
|
||||
// Select the context from the beginning of the selection start line to the selection start position
|
||||
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
|
||||
const textBeforeSelectionStart = document.getText(
|
||||
new vscode.Range(beginningOfSelectionStartLine, selection.start),
|
||||
);
|
||||
// If there are only whitespace before the start of the selection, include the indentation
|
||||
if (textBeforeSelectionStart.trim().length === 0) {
|
||||
selectionRange = selectionRange.with({
|
||||
start: beginningOfSelectionStartLine,
|
||||
});
|
||||
let selectionRange: vscode.Range | undefined;
|
||||
// if the selection is empty and document is not empty, select the whole document
|
||||
if (selection.isEmpty) {
|
||||
selectionRange = new vscode.Range(
|
||||
new vscode.Position(0, 0),
|
||||
new vscode.Position(
|
||||
editor.document.lineCount - 1,
|
||||
editor.document.lineAt(
|
||||
editor.document.lineCount - 1,
|
||||
).range.end.character,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (!selectionRange) {
|
||||
selectionRange = new vscode.Range(selection.start, selection.end);
|
||||
const document = editor.document;
|
||||
// Select the context from the beginning of the selection start line to the selection start position
|
||||
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
|
||||
const textBeforeSelectionStart = document.getText(
|
||||
new vscode.Range(beginningOfSelectionStartLine, selection.start),
|
||||
);
|
||||
// If there are only whitespace before the start of the selection, include the indentation
|
||||
if (textBeforeSelectionStart.trim().length === 0) {
|
||||
selectionRange = selectionRange.with({
|
||||
start: beginningOfSelectionStartLine,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const contents = editor.document.getText(selectionRange);
|
||||
|
|
@ -61,12 +77,12 @@ export function getRangeInFileWithContents(
|
|||
contents,
|
||||
range: {
|
||||
start: {
|
||||
line: selection.start.line,
|
||||
character: selection.start.character,
|
||||
line: selectionRange.start.line,
|
||||
character: selectionRange.start.character,
|
||||
},
|
||||
end: {
|
||||
line: selection.end.line,
|
||||
character: selection.end.character,
|
||||
line: selectionRange.end.line,
|
||||
character: selectionRange.end.character,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -78,7 +94,7 @@ export function getRangeInFileWithContents(
|
|||
export async function addHighlightedCodeToContext(
|
||||
webviewProtocol: VsCodeWebviewProtocol | undefined,
|
||||
) {
|
||||
const rangeInFileWithContents = getRangeInFileWithContents();
|
||||
const rangeInFileWithContents = getRangeInFileWithContents(true);
|
||||
if (rangeInFileWithContents) {
|
||||
webviewProtocol?.request("highlightedCode", {
|
||||
rangeInFileWithContents,
|
||||
|
|
@ -129,6 +145,10 @@ export async function addEntireFileToContext(
|
|||
});
|
||||
}
|
||||
|
||||
export function isEmptyFile(document: vscode.TextDocument) {
|
||||
return document.lineCount === 1 && document.lineAt(0).range.isEmpty;
|
||||
}
|
||||
|
||||
export function addCodeToContextFromRange(
|
||||
range: vscode.Range,
|
||||
webviewProtocol: VsCodeWebviewProtocol,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { useMemo, useRef } from "react";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { saveCurrentSession } from "../../redux/thunks/session";
|
||||
import { useCompactConversation } from "../../util/compactConversation";
|
||||
|
|
@ -8,15 +9,36 @@ const ContextStatus = () => {
|
|||
const contextPercentage = useAppSelector(
|
||||
(state) => state.session.contextPercentage,
|
||||
);
|
||||
const selectedChatModel = useAppSelector(
|
||||
(state) => state.config.config.selectedModelByRole.chat?.model,
|
||||
);
|
||||
const previousHistoryLength = useRef<number | null>(null);
|
||||
const previousSelectedChatModel = useRef<string | null>(null);
|
||||
const history = useAppSelector((state) => state.session.history);
|
||||
const percent = Math.round((contextPercentage ?? 0) * 100);
|
||||
const isPruned = useAppSelector((state) => state.session.isPruned);
|
||||
|
||||
const isDifferentModelAndSameHistory = useMemo(() => {
|
||||
if (!selectedChatModel) return false;
|
||||
// only reset if history changes
|
||||
if (previousHistoryLength.current !== history.length) {
|
||||
previousHistoryLength.current = history.length;
|
||||
previousSelectedChatModel.current = selectedChatModel;
|
||||
return false;
|
||||
}
|
||||
return previousSelectedChatModel.current !== selectedChatModel;
|
||||
}, [history.length, selectedChatModel]);
|
||||
|
||||
const compactConversation = useCompactConversation();
|
||||
if (!isPruned && percent < 60) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// if user changed to a different model, we shouldn't show the context status until the user sends a new message
|
||||
if (isDifferentModelAndSameHistory) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const barColorClass = isPruned ? "bg-error" : "bg-description";
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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()}⌫
|
||||
|
|
|
|||
|
|
@ -83,12 +83,57 @@ export const handleApplyStateUpdate = createAsyncThunk<
|
|||
}
|
||||
|
||||
if (accepted) {
|
||||
// Add autoformatting diff to tool output if present
|
||||
if (applyState.autoFormattingDiff) {
|
||||
dispatch(
|
||||
updateToolCallOutput({
|
||||
toolCallId: applyState.toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
icon: "info",
|
||||
name: "Auto-formatting Applied",
|
||||
description: "Editor auto-formatting changes",
|
||||
content: `Along with your edits, the editor applied the following auto-formatting:\n\n${applyState.autoFormattingDiff}\n\n(Note: Pay close attention to changes such as single quotes being converted to double quotes, semicolons being removed or added, long lines being broken into multiple lines, adjusting indentation style, adding/removing trailing commas, etc. This will help you ensure future SEARCH/REPLACE operations to this file are accurate.)`,
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (toolCallState.status !== "errored") {
|
||||
dispatch(
|
||||
acceptToolCall({
|
||||
toolCallId: applyState.toolCallId,
|
||||
}),
|
||||
);
|
||||
dispatch(
|
||||
updateToolCallOutput({
|
||||
toolCallId: applyState.toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Edit Success",
|
||||
content: `Successfully edited ${applyState.filepath}`,
|
||||
description: "",
|
||||
hidden: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
dispatch(
|
||||
updateToolCallOutput({
|
||||
toolCallId: applyState.toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
name: "Edit Failed",
|
||||
content: `Failed to edit ${applyState.filepath}. To continue working with the file, read it again to see the most up-to-date contents`,
|
||||
description: "",
|
||||
hidden: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
void dispatch(
|
||||
|
|
@ -98,7 +143,6 @@ export const handleApplyStateUpdate = createAsyncThunk<
|
|||
);
|
||||
}
|
||||
}
|
||||
// TODO return output from edit tools so the model knows the result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ export const moveTerminalProcessToBackground = createAsyncThunk<
|
|||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: existingContent + (existingContent ? "\n\n" : "") + status,
|
||||
content: existingContent,
|
||||
status: status,
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -17,13 +17,13 @@ export const editToolImpl: ClientToolImpl = async (
|
|||
filepath = filepath.slice(2);
|
||||
}
|
||||
|
||||
const openFiles = await extras.ideMessenger.ide.getOpenFiles();
|
||||
let firstUriMatch = await resolveRelativePathInDir(
|
||||
filepath,
|
||||
extras.ideMessenger.ide,
|
||||
);
|
||||
|
||||
if (!firstUriMatch) {
|
||||
const openFiles = await extras.ideMessenger.ide.getOpenFiles();
|
||||
for (const uri of openFiles) {
|
||||
if (uri.endsWith(filepath)) {
|
||||
firstUriMatch = uri;
|
||||
|
|
@ -46,13 +46,7 @@ export const editToolImpl: ClientToolImpl = async (
|
|||
);
|
||||
|
||||
return {
|
||||
respondImmediately: true,
|
||||
output: [
|
||||
{
|
||||
name: "File edited successfully",
|
||||
content: `Successfully initiated edit for ${firstUriMatch}`,
|
||||
description: "File edit operation started",
|
||||
},
|
||||
],
|
||||
respondImmediately: false,
|
||||
output: undefined, // no immediate output - output for edit tools should be added based on apply state coming in
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
name: Test Invokable Rules
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
|
||||
rules:
|
||||
- name: "Code Review"
|
||||
rule: "Review this code for best practices and potential issues"
|
||||
invokable: true
|
||||
description: "Performs a code review"
|
||||
|
||||
- name: "Explain Code"
|
||||
rule: "Explain what this code does in simple terms"
|
||||
invokable: true
|
||||
|
||||
- name: "Regular Rule"
|
||||
rule: "This is a non-invokable rule"
|
||||
invokable: false
|
||||
|
||||
- name: "Default Rule"
|
||||
rule: "This rule has no invokable property"
|
||||
description: "Should default to non-invokable"
|
||||
|
||||
- "Simple string rule"
|
||||
|
|
@ -57,6 +57,7 @@ const ruleObjectSchema = z.object({
|
|||
globs: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
regex: z.union([z.string(), z.array(z.string())]).optional(),
|
||||
alwaysApply: z.boolean().optional(),
|
||||
invokable: z.boolean().optional(),
|
||||
sourceFile: z.string().optional(), //TODO refactor RuleWithSource.ruleFile to align with sourceFile
|
||||
});
|
||||
const ruleSchema = z.union([z.string(), ruleObjectSchema]);
|
||||
|
|
|
|||
18
packages/terminal-security/package-lock.json
generated
18
packages/terminal-security/package-lock.json
generated
|
|
@ -1322,14 +1322,14 @@
|
|||
"license": "MIT"
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.14",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fdir": "^6.4.4",
|
||||
"picomatch": "^4.0.2"
|
||||
"fdir": "^6.5.0",
|
||||
"picomatch": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.0.0"
|
||||
|
|
@ -1390,9 +1390,9 @@
|
|||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "7.1.4",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.4.tgz",
|
||||
"integrity": "sha512-X5QFK4SGynAeeIt+A7ZWnApdUyHYm+pzv/8/A57LqSGcI88U6R6ipOs3uCesdc6yl7nl+zNO0t8LmqAdXcQihw==",
|
||||
"version": "7.1.5",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.5.tgz",
|
||||
"integrity": "sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
|
@ -1401,7 +1401,7 @@
|
|||
"picomatch": "^4.0.3",
|
||||
"postcss": "^8.5.6",
|
||||
"rollup": "^4.43.0",
|
||||
"tinyglobby": "^0.2.14"
|
||||
"tinyglobby": "^0.2.15"
|
||||
},
|
||||
"bin": {
|
||||
"vite": "bin/vite.js"
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue