Merge pull request #7421 from continuedev/tomasz/con-3680
Create dynamic tool policies and implement dynamic policy for terminal tool
This commit is contained in:
commit
259cbc25f8
26 changed files with 4277 additions and 181 deletions
|
|
@ -23,5 +23,5 @@ CHANGELOG.md
|
|||
**/CODEOWNERS
|
||||
core/vendor
|
||||
coverage
|
||||
e2e
|
||||
# e2e
|
||||
packages/continue-sdk
|
||||
2
binary/package-lock.json
generated
2
binary/package-lock.json
generated
|
|
@ -106,6 +106,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -140,6 +141,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
|
|||
31
core/core.ts
31
core/core.ts
|
|
@ -1009,6 +1009,37 @@ export class Core {
|
|||
this.handleToolCall(toolCall),
|
||||
);
|
||||
|
||||
on(
|
||||
"tools/evaluatePolicy",
|
||||
async ({ data: { toolName, basePolicy, args } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
|
||||
const tool = config.tools.find((t) => t.function.name === toolName);
|
||||
if (!tool) {
|
||||
// Tool not found, return base policy
|
||||
return { policy: basePolicy };
|
||||
}
|
||||
|
||||
// Extract display value for specific tools
|
||||
let displayValue: string | undefined;
|
||||
if (toolName === "runTerminalCommand" && args.command) {
|
||||
displayValue = args.command as string;
|
||||
}
|
||||
|
||||
// If tool has evaluateToolCallPolicy function, use it
|
||||
if (tool.evaluateToolCallPolicy) {
|
||||
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
|
||||
return { policy: evaluatedPolicy, displayValue };
|
||||
}
|
||||
|
||||
// Otherwise return base policy unchanged
|
||||
return { policy: basePolicy, displayValue };
|
||||
},
|
||||
);
|
||||
|
||||
on("isItemTooBig", async ({ data: { item } }) => {
|
||||
return this.isItemTooBig(item);
|
||||
});
|
||||
|
|
|
|||
4
core/index.d.ts
vendored
4
core/index.d.ts
vendored
|
|
@ -1099,6 +1099,10 @@ export interface Tool {
|
|||
exampleArgs?: Array<[string, string | number]>;
|
||||
};
|
||||
defaultToolPolicy?: ToolPolicy;
|
||||
evaluateToolCallPolicy?: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
) => ToolPolicy;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
|
|
|
|||
21
core/package-lock.json
generated
21
core/package-lock.json
generated
|
|
@ -67,6 +67,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -101,6 +102,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
@ -6892,6 +6894,13 @@
|
|||
"node": ">= 0.12"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/shell-quote": {
|
||||
"version": "1.7.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz",
|
||||
"integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/shimmer": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz",
|
||||
|
|
@ -17459,6 +17468,18 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/shell-quote": {
|
||||
"version": "1.8.3",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
|
||||
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/shiki": {
|
||||
"version": "3.7.0",
|
||||
"resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz",
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
@ -111,6 +112,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ import {
|
|||
SlashCommandDescWithSource,
|
||||
StreamDiffLinesPayload,
|
||||
ToolCall,
|
||||
ToolPolicy,
|
||||
} from "../";
|
||||
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
|
||||
import { GetLspDefinitionsFunction } from "../autocomplete/types";
|
||||
|
|
@ -293,6 +294,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
{ toolCall: ToolCall },
|
||||
{ contextItems: ContextItem[]; errorMessage?: string },
|
||||
];
|
||||
"tools/evaluatePolicy": [
|
||||
{ toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
|
||||
{ policy: ToolPolicy; displayValue?: string },
|
||||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
|
||||
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"didChangeSelectedProfile",
|
||||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"tools/evaluatePolicy",
|
||||
"controlPlane/getEnvironment",
|
||||
"controlPlane/getFreeTrialStatus",
|
||||
"controlPlane/getModelsAddOnUpgradeUrl",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import os from "os";
|
||||
import { Tool } from "../..";
|
||||
import { Tool, ToolPolicy } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { evaluateTerminalCommandSecurity } from "../security/terminalCommandSecurity";
|
||||
|
||||
/**
|
||||
* Get the preferred shell for the current platform
|
||||
|
|
@ -56,6 +57,15 @@ export const runTerminalCommandTool: Tool = {
|
|||
},
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
return evaluateTerminalCommandSecurity(
|
||||
basePolicy,
|
||||
parsedArgs.command as string,
|
||||
);
|
||||
},
|
||||
systemMessageDescription: {
|
||||
prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
|
||||
${RUN_COMMAND_NOTES}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,12 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
afterAll,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import * as childProcess from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
|
|
@ -6,17 +14,18 @@ import * as path from "node:path";
|
|||
import { IDE, ToolExtras } from "../..";
|
||||
import * as processBackgroundStates from "../../util/processTerminalBackgroundStates";
|
||||
import { runTerminalCommandImpl } from "./runTerminalCommand";
|
||||
import { runTerminalCommandTool } from "../definitions/runTerminalCommand";
|
||||
|
||||
// We're using real child processes, so ensure these aren't mocked
|
||||
jest.unmock("node:child_process");
|
||||
jest.unmock("node:util");
|
||||
vi.unmock("node:child_process");
|
||||
vi.unmock("node:util");
|
||||
|
||||
describe("runTerminalCommandImpl", () => {
|
||||
// Setup mocks and spies
|
||||
const mockGetIdeInfo = jest.fn();
|
||||
const mockGetWorkspaceDirs = jest.fn();
|
||||
const mockOnPartialOutput = jest.fn();
|
||||
const mockRunCommand = jest.fn();
|
||||
const mockGetIdeInfo = vi.fn();
|
||||
const mockGetWorkspaceDirs = vi.fn();
|
||||
const mockOnPartialOutput = vi.fn();
|
||||
const mockRunCommand = vi.fn();
|
||||
|
||||
// Use a simple approach to ensure background processes are terminated
|
||||
let testPid: number | null = null;
|
||||
|
|
@ -27,7 +36,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
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
|
||||
|
|
@ -73,7 +82,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
// Helper function to create a ToolExtras object
|
||||
const createMockExtras = (
|
||||
overrides: Partial<{
|
||||
onPartialOutput?: jest.Mock;
|
||||
onPartialOutput?: any;
|
||||
remoteName?: string;
|
||||
}> = {},
|
||||
): ToolExtras => {
|
||||
|
|
@ -90,16 +99,16 @@ describe("runTerminalCommandImpl", () => {
|
|||
getWorkspaceDirs: mockGetWorkspaceDirs,
|
||||
runCommand: mockRunCommand,
|
||||
// Add stubs for other required IDE methods
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
// Create a base ToolExtras object with required properties
|
||||
|
|
@ -147,7 +156,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: true };
|
||||
const mockOutputFn = jest.fn();
|
||||
const mockOutputFn = vi.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
// Execute the command with streaming
|
||||
|
|
@ -191,7 +200,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
"`;
|
||||
|
||||
const args = { command, waitForCompletion: false };
|
||||
const mockOutputFn = jest.fn();
|
||||
const mockOutputFn = vi.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
|
@ -355,25 +364,25 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
it("should handle missing workspace directory gracefully", async () => {
|
||||
// Mock IDE to return empty workspace directories
|
||||
const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
|
||||
const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
|
||||
|
||||
// Create IDE mock with empty workspace
|
||||
const mockIde = {
|
||||
getIdeInfo: jest
|
||||
getIdeInfo: vi
|
||||
.fn()
|
||||
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
|
||||
getWorkspaceDirs: mockEmptyWorkspace,
|
||||
runCommand: jest.fn(),
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
runCommand: vi.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
const extras = {
|
||||
|
|
@ -402,7 +411,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
it("should handle case where cwd fallbacks all fail", async () => {
|
||||
// Mock IDE to return empty workspace directories
|
||||
const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([]));
|
||||
const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([]));
|
||||
|
||||
// Save original environment variables and process.cwd
|
||||
const originalHome = process.env.HOME;
|
||||
|
|
@ -413,27 +422,27 @@ describe("runTerminalCommandImpl", () => {
|
|||
// Mock all fallbacks to fail
|
||||
delete process.env.HOME;
|
||||
delete process.env.USERPROFILE;
|
||||
process.cwd = jest.fn().mockImplementation(() => {
|
||||
process.cwd = vi.fn().mockImplementation(() => {
|
||||
throw new Error("Current directory unavailable");
|
||||
}) as jest.MockedFunction<() => string>;
|
||||
}) as any;
|
||||
|
||||
// Create IDE mock with empty workspace
|
||||
const mockIde = {
|
||||
getIdeInfo: jest
|
||||
getIdeInfo: vi
|
||||
.fn()
|
||||
.mockReturnValue(Promise.resolve({ remoteName: "local" })),
|
||||
getWorkspaceDirs: mockEmptyWorkspace,
|
||||
runCommand: jest.fn(),
|
||||
getIdeSettings: jest.fn(),
|
||||
getDiff: jest.fn(),
|
||||
getClipboardContent: jest.fn(),
|
||||
isTelemetryEnabled: jest.fn(),
|
||||
readFile: jest.fn(),
|
||||
writeFile: jest.fn(),
|
||||
renameFile: jest.fn(),
|
||||
deleteFile: jest.fn(),
|
||||
globFiles: jest.fn(),
|
||||
ls: jest.fn(),
|
||||
runCommand: vi.fn(),
|
||||
getIdeSettings: vi.fn(),
|
||||
getDiff: vi.fn(),
|
||||
getClipboardContent: vi.fn(),
|
||||
isTelemetryEnabled: vi.fn(),
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
renameFile: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
globFiles: vi.fn(),
|
||||
ls: vi.fn(),
|
||||
};
|
||||
|
||||
const extras = {
|
||||
|
|
@ -472,3 +481,125 @@ describe("runTerminalCommandImpl", () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTerminalCommandTool.evaluateToolCallPolicy", () => {
|
||||
it("should return base policy for safe commands like echo", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "echo hello world" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should respect disabled policy even for non-echo commands", () => {
|
||||
const basePolicy = "disabled";
|
||||
const args = { command: "ls -la" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should respect disabled policy even for safe commands", () => {
|
||||
const basePolicy = "disabled";
|
||||
const args = { command: "echo test" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should return base policy for non-echo commands", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "ls -la" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should return base policy for git commands", () => {
|
||||
const basePolicy = "allowedWithPermission";
|
||||
const args = { command: "git status" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
|
||||
it("should handle undefined command gracefully", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: undefined };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should handle null command gracefully", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: null };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should handle empty command string", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should disable dangerous commands like rm -rf /", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "rm -rf /" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("disabled");
|
||||
});
|
||||
|
||||
it("should require permission for high-risk network commands", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "curl http://example.com" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(
|
||||
basePolicy,
|
||||
args,
|
||||
);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
});
|
||||
1626
core/tools/implementations/terminalCommandSecurity.vitest.ts
Normal file
1626
core/tools/implementations/terminalCommandSecurity.vitest.ts
Normal file
File diff suppressed because it is too large
Load diff
1202
core/tools/security/terminalCommandSecurity.ts
Normal file
1202
core/tools/security/terminalCommandSecurity.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -142,6 +142,7 @@ class MessageTypes {
|
|||
"didChangeSelectedProfile",
|
||||
"didChangeSelectedOrg",
|
||||
"tools/call",
|
||||
"tools/evaluatePolicy",
|
||||
"controlPlane/openUrl",
|
||||
"isItemTooBig",
|
||||
"process/markAsBackgrounded",
|
||||
|
|
|
|||
|
|
@ -134,7 +134,7 @@ export class GUIActions {
|
|||
public static async toggleToolPolicy(
|
||||
view: WebView,
|
||||
toolName: string,
|
||||
n: number,
|
||||
desiredState: number | string,
|
||||
) {
|
||||
const toolButton = await TestUtils.waitForSuccess(() =>
|
||||
GUISelectors.getToolButton(view),
|
||||
|
|
@ -145,9 +145,41 @@ export class GUIActions {
|
|||
);
|
||||
await TestUtils.waitForTimeout(500);
|
||||
|
||||
// Enabled -> Excluded -> Ask first
|
||||
for (let i = 0; i < n; i++) {
|
||||
await TestUtils.waitForSuccess(() => toolPolicyButton.click());
|
||||
// Map old number format to state names for backward compatibility
|
||||
// 0 = Automatic/Auto, 1 = Excluded/Off, 2 = Ask First/Ask
|
||||
let targetStates: string[];
|
||||
if (typeof desiredState === "number") {
|
||||
const stateMap = [
|
||||
["Automatic", "Auto"], // 0
|
||||
["Excluded", "Off"], // 1
|
||||
["Ask First", "Ask"], // 2
|
||||
];
|
||||
targetStates = stateMap[desiredState] || ["Ask First", "Ask"];
|
||||
} else {
|
||||
targetStates = [desiredState];
|
||||
}
|
||||
|
||||
// Keep clicking until we reach the desired state
|
||||
let maxAttempts = 5; // Safety limit to prevent infinite loops
|
||||
while (maxAttempts > 0) {
|
||||
const currentText = await toolPolicyButton.getText();
|
||||
|
||||
// Check if we've reached any of the target states
|
||||
if (targetStates.some((state) => currentText.includes(state))) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Click to move to next state
|
||||
await toolPolicyButton.click();
|
||||
await TestUtils.waitForTimeout(200); // Small delay for UI update
|
||||
|
||||
maxAttempts--;
|
||||
}
|
||||
|
||||
if (maxAttempts === 0) {
|
||||
throw new Error(
|
||||
`Failed to set tool policy to ${targetStates.join(" or ")} after 5 attempts`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import {
|
|||
InputBox,
|
||||
TextEditor,
|
||||
VSBrowser,
|
||||
Workbench
|
||||
Workbench,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { DEFAULT_TIMEOUT } from "../constants";
|
||||
|
|
@ -86,76 +86,69 @@ export class GlobalActions {
|
|||
|
||||
static async setNextEditEnabled(enabled: boolean) {
|
||||
const workbench = new Workbench();
|
||||
|
||||
await workbench.openCommandPrompt();
|
||||
process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = 'true';
|
||||
|
||||
|
||||
await workbench.openCommandPrompt();
|
||||
process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = "true";
|
||||
|
||||
// Initial wait and clear
|
||||
await TestUtils.waitForTimeout(1000);
|
||||
await GlobalActions.clearAllNotifications();
|
||||
|
||||
|
||||
const statusBar = await workbench.getStatusBar();
|
||||
|
||||
|
||||
// Robust element finding with text validation
|
||||
const continueItem = await TestUtils.waitForSuccess(
|
||||
async () => {
|
||||
// Clear any new notifications
|
||||
try {
|
||||
await GlobalActions.clearAllNotifications();
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
const continueItem = await TestUtils.waitForSuccess(async () => {
|
||||
// Clear any new notifications
|
||||
try {
|
||||
await GlobalActions.clearAllNotifications();
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
const element = await statusBar.findElement(
|
||||
By.xpath("//*[contains(text(), 'Continue')]"),
|
||||
);
|
||||
|
||||
// Validate we can get text
|
||||
const text = await element.getText();
|
||||
if (!text || text.trim() === "") {
|
||||
// Try alternative methods
|
||||
const textContent = await element.getAttribute("textContent");
|
||||
if (!textContent || textContent.trim() === "") {
|
||||
throw new Error("Text not yet available");
|
||||
}
|
||||
|
||||
const element = await statusBar.findElement(
|
||||
By.xpath("//*[contains(text(), 'Continue')]")
|
||||
);
|
||||
|
||||
// Validate we can get text
|
||||
const text = await element.getText();
|
||||
if (!text || text.trim() === '') {
|
||||
// Try alternative methods
|
||||
const textContent = await element.getAttribute('textContent');
|
||||
if (!textContent || textContent.trim() === '') {
|
||||
throw new Error('Text not yet available');
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
},
|
||||
DEFAULT_TIMEOUT.MD
|
||||
);
|
||||
}
|
||||
|
||||
return element;
|
||||
}, DEFAULT_TIMEOUT.MD);
|
||||
|
||||
// Get text with retry
|
||||
const text = await TestUtils.waitForSuccess(
|
||||
async () => {
|
||||
const itemText = await continueItem.getText();
|
||||
if (!itemText || itemText.trim() === '') {
|
||||
// Fallback to textContent
|
||||
const textContent = await continueItem.getAttribute('textContent');
|
||||
if (textContent && textContent.trim() !== '') {
|
||||
return textContent;
|
||||
}
|
||||
throw new Error('Text content not yet available');
|
||||
const text = await TestUtils.waitForSuccess(async () => {
|
||||
const itemText = await continueItem.getText();
|
||||
if (!itemText || itemText.trim() === "") {
|
||||
// Fallback to textContent
|
||||
const textContent = await continueItem.getAttribute("textContent");
|
||||
if (textContent && textContent.trim() !== "") {
|
||||
return textContent;
|
||||
}
|
||||
return itemText;
|
||||
},
|
||||
DEFAULT_TIMEOUT.MD
|
||||
);
|
||||
|
||||
throw new Error("Text content not yet available");
|
||||
}
|
||||
return itemText;
|
||||
}, DEFAULT_TIMEOUT.MD);
|
||||
|
||||
console.log("Final text:", text);
|
||||
|
||||
const hasNE = text.includes('(NE)');
|
||||
|
||||
const hasNE = text.includes("(NE)");
|
||||
console.log("hasNE:", hasNE);
|
||||
|
||||
|
||||
if (hasNE !== enabled) {
|
||||
await workbench.executeCommand('Continue: Toggle Next Edit');
|
||||
await workbench.executeCommand("Continue: Toggle Next Edit");
|
||||
// Clear any resulting notifications
|
||||
await TestUtils.waitForTimeout(500);
|
||||
await GlobalActions.clearAllNotifications();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static async disableNextEdit() {
|
||||
await this.setNextEditEnabled(false);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import {
|
|||
WebDriver,
|
||||
WebElement,
|
||||
WebView,
|
||||
until
|
||||
until,
|
||||
} from "vscode-extension-tester";
|
||||
|
||||
import { GlobalActions } from "../actions/Global.actions";
|
||||
|
|
|
|||
2
extensions/vscode/package-lock.json
generated
2
extensions/vscode/package-lock.json
generated
|
|
@ -158,6 +158,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -192,6 +193,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
|
|||
2
gui/package-lock.json
generated
2
gui/package-lock.json
generated
|
|
@ -173,6 +173,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -207,6 +208,7 @@
|
|||
"@types/pg": "^8.11.6",
|
||||
"@types/plist": "^3.0.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/tar": "^6.1.13",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"@types/win-ca": "^3.5.4",
|
||||
|
|
|
|||
276
gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.test.tsx
Normal file
276
gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.test.tsx
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
import { describe, expect, it, vi } from "vitest";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { RunTerminalCommand } from "./RunTerminalCommand";
|
||||
import { ToolCallState } from "core";
|
||||
|
||||
// Mock the UnifiedTerminalCommand component since it requires Redux
|
||||
vi.mock("../../../components/UnifiedTerminal/UnifiedTerminal", () => ({
|
||||
UnifiedTerminalCommand: ({
|
||||
command,
|
||||
output,
|
||||
status,
|
||||
statusMessage,
|
||||
toolCallState,
|
||||
toolCallId,
|
||||
}: any) => (
|
||||
<div data-testid="unified-terminal">
|
||||
<div data-testid="command">{command}</div>
|
||||
<div data-testid="output">{output}</div>
|
||||
<div data-testid="status">{status}</div>
|
||||
<div data-testid="status-message">{statusMessage}</div>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe("RunTerminalCommand", () => {
|
||||
it("should display error message when tool call is errored", () => {
|
||||
const erroredToolCallState: ToolCallState = {
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
arguments: JSON.stringify({ command: 'eval "echo hello"' }),
|
||||
},
|
||||
},
|
||||
status: "errored",
|
||||
parsedArgs: { command: 'eval "echo hello"' },
|
||||
output: [
|
||||
{
|
||||
name: "Security Policy Violation",
|
||||
description: "Command Disabled",
|
||||
content:
|
||||
'This command has been disabled by security policy:\n\neval "echo hello"\n\nThis command cannot be executed as it may pose a security risk.',
|
||||
icon: "problems",
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
render(
|
||||
<RunTerminalCommand
|
||||
command='eval "echo hello"'
|
||||
toolCallState={erroredToolCallState}
|
||||
toolCallId="test-id"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Check that the error message is displayed in the output
|
||||
const outputElement = screen.getByTestId("output");
|
||||
expect(outputElement.textContent).toContain(
|
||||
"This command has been disabled by security policy",
|
||||
);
|
||||
expect(outputElement.textContent).toContain('eval "echo hello"');
|
||||
expect(outputElement.textContent).toContain(
|
||||
"cannot be executed as it may pose a security risk",
|
||||
);
|
||||
|
||||
// Check that status is set to failed
|
||||
const statusElement = screen.getByTestId("status");
|
||||
expect(statusElement.textContent).toBe("failed");
|
||||
});
|
||||
|
||||
it("should display terminal output for successful commands", () => {
|
||||
const successfulToolCallState: ToolCallState = {
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
arguments: JSON.stringify({ command: "ls -la" }),
|
||||
},
|
||||
},
|
||||
status: "done",
|
||||
parsedArgs: { command: "ls -la" },
|
||||
output: [
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Command executed successfully",
|
||||
content:
|
||||
"total 64\ndrwxr-xr-x 10 user staff 320 Jan 1 12:00 .\ndrwxr-xr-x 20 user staff 640 Jan 1 11:00 ..",
|
||||
icon: "terminal",
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
render(
|
||||
<RunTerminalCommand
|
||||
command="ls -la"
|
||||
toolCallState={successfulToolCallState}
|
||||
toolCallId="test-id"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Check that the terminal output is displayed
|
||||
const outputElement = screen.getByTestId("output");
|
||||
expect(outputElement.textContent).toContain("total 64");
|
||||
expect(outputElement.textContent).toContain("drwxr-xr-x");
|
||||
|
||||
// Check that status is completed
|
||||
const statusElement = screen.getByTestId("status");
|
||||
expect(statusElement.textContent).toBe("completed");
|
||||
});
|
||||
|
||||
it("should handle running status correctly", () => {
|
||||
const runningToolCallState: ToolCallState = {
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
arguments: JSON.stringify({ command: "npm install" }),
|
||||
},
|
||||
},
|
||||
status: "calling",
|
||||
parsedArgs: { command: "npm install" },
|
||||
output: [],
|
||||
};
|
||||
|
||||
render(
|
||||
<RunTerminalCommand
|
||||
command="npm install"
|
||||
toolCallState={runningToolCallState}
|
||||
toolCallId="test-id"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Check that status is set to running
|
||||
const statusElement = screen.getByTestId("status");
|
||||
expect(statusElement.textContent).toBe("running");
|
||||
|
||||
// Check that command is displayed
|
||||
const commandElement = screen.getByTestId("command");
|
||||
expect(commandElement.textContent).toBe("npm install");
|
||||
});
|
||||
|
||||
it("should detect failed status from error state", () => {
|
||||
const failedToolCallState: ToolCallState = {
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
arguments: JSON.stringify({ command: "invalid-command" }),
|
||||
},
|
||||
},
|
||||
status: "errored",
|
||||
parsedArgs: { command: "invalid-command" },
|
||||
output: [
|
||||
{
|
||||
name: "Tool Call Error",
|
||||
description: "Command Failed",
|
||||
content: "Command 'invalid-command' not found",
|
||||
icon: "problems",
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
render(
|
||||
<RunTerminalCommand
|
||||
command="invalid-command"
|
||||
toolCallState={failedToolCallState}
|
||||
toolCallId="test-id"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Check that error content is displayed
|
||||
const outputElement = screen.getByTestId("output");
|
||||
expect(outputElement.textContent).toContain(
|
||||
"Command 'invalid-command' not found",
|
||||
);
|
||||
|
||||
// Check that status is failed
|
||||
const statusElement = screen.getByTestId("status");
|
||||
expect(statusElement.textContent).toBe("failed");
|
||||
});
|
||||
|
||||
it("should handle empty output gracefully", () => {
|
||||
const emptyOutputState: ToolCallState = {
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
arguments: JSON.stringify({ command: "echo" }),
|
||||
},
|
||||
},
|
||||
status: "done",
|
||||
parsedArgs: { command: "echo" },
|
||||
output: [],
|
||||
};
|
||||
|
||||
render(
|
||||
<RunTerminalCommand
|
||||
command="echo"
|
||||
toolCallState={emptyOutputState}
|
||||
toolCallId="test-id"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should render with empty output
|
||||
const outputElement = screen.getByTestId("output");
|
||||
expect(outputElement.textContent).toBe("");
|
||||
|
||||
// Status should still be completed
|
||||
const statusElement = screen.getByTestId("status");
|
||||
expect(statusElement.textContent).toBe("completed");
|
||||
});
|
||||
|
||||
it("should prioritize first output item for errored status", () => {
|
||||
const multiOutputErrorState: ToolCallState = {
|
||||
toolCallId: "test-id",
|
||||
toolCall: {
|
||||
id: "test-id",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
arguments: JSON.stringify({ command: "sudo rm -rf /" }),
|
||||
},
|
||||
},
|
||||
status: "errored",
|
||||
parsedArgs: { command: "sudo rm -rf /" },
|
||||
output: [
|
||||
{
|
||||
name: "Security Policy Violation",
|
||||
description: "Dangerous Command Blocked",
|
||||
content: "This command is extremely dangerous and has been blocked.",
|
||||
icon: "problems",
|
||||
hidden: false,
|
||||
},
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Should not be shown",
|
||||
content: "This should not appear for errored status",
|
||||
icon: "terminal",
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
render(
|
||||
<RunTerminalCommand
|
||||
command="sudo rm -rf /"
|
||||
toolCallState={multiOutputErrorState}
|
||||
toolCallId="test-id"
|
||||
/>,
|
||||
);
|
||||
|
||||
// Should show the security error, not the terminal output
|
||||
const outputElement = screen.getByTestId("output");
|
||||
expect(outputElement.textContent).toContain(
|
||||
"extremely dangerous and has been blocked",
|
||||
);
|
||||
expect(outputElement.textContent).not.toContain("This should not appear");
|
||||
|
||||
// Status should be failed for errored state
|
||||
const statusElement = screen.getByTestId("status");
|
||||
expect(statusElement.textContent).toBe("failed");
|
||||
});
|
||||
});
|
||||
|
|
@ -8,13 +8,15 @@ interface RunTerminalCommandToolCallProps {
|
|||
}
|
||||
|
||||
export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
|
||||
// Find the terminal output from context items if available
|
||||
const terminalItem = props.toolCallState.output?.find(
|
||||
(item) => item.name === "Terminal",
|
||||
);
|
||||
// For errored status, show any output (error messages)
|
||||
// Otherwise look for terminal output specifically
|
||||
const isErrored = props.toolCallState.status === "errored";
|
||||
const outputItem = isErrored
|
||||
? props.toolCallState.output?.[0] // Get first output item for errors
|
||||
: props.toolCallState.output?.find((item) => item.name === "Terminal");
|
||||
|
||||
const terminalContent = terminalItem?.content || "";
|
||||
const statusMessage = terminalItem?.status || "";
|
||||
const terminalContent = outputItem?.content || "";
|
||||
const statusMessage = outputItem?.status || "";
|
||||
const isRunning = props.toolCallState.status === "calling";
|
||||
|
||||
// Determine status type
|
||||
|
|
@ -22,7 +24,7 @@ export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
|
|||
"completed";
|
||||
if (isRunning) {
|
||||
statusType = "running";
|
||||
} else if (statusMessage?.includes("failed")) {
|
||||
} else if (isErrored || statusMessage?.includes("failed")) {
|
||||
statusType = "failed";
|
||||
} else if (statusMessage?.includes("background")) {
|
||||
statusType = "background";
|
||||
|
|
|
|||
|
|
@ -59,6 +59,9 @@ test(
|
|||
const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
|
||||
|
||||
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
|
||||
ideMessenger.responses["tools/evaluatePolicy"] = {
|
||||
policy: "allowedWithPermission",
|
||||
};
|
||||
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
|
||||
const messengerRequestSpy = vi.spyOn(ideMessenger, "request");
|
||||
|
||||
|
|
@ -169,6 +172,9 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => {
|
|||
const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
|
||||
|
||||
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
|
||||
ideMessenger.responses["tools/evaluatePolicy"] = {
|
||||
policy: "allowedWithoutPermission",
|
||||
};
|
||||
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
|
||||
const messengerRequestSpy = vi.spyOn(ideMessenger, "request");
|
||||
|
||||
|
|
@ -213,7 +219,7 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => {
|
|||
await getElementByText(EDIT_CHANGES);
|
||||
|
||||
// Make sure there's no pending tool call
|
||||
verifyNotPresentByTestId(
|
||||
await verifyNotPresentByTestId(
|
||||
generateToolCallButtonTestId("accept", EDIT_TOOL_CALL_ID),
|
||||
);
|
||||
// Tool call, check that applyToFile was called for edit
|
||||
|
|
|
|||
|
|
@ -41,6 +41,11 @@ describe("Parallel Tool Calls", () => {
|
|||
test("should handle assistant message with multiple tool calls", async () => {
|
||||
const { ideMessenger, store } = await renderWithProviders(<Chat />);
|
||||
|
||||
// Mock the tools/evaluatePolicy response to allow tools without permission
|
||||
ideMessenger.responses["tools/evaluatePolicy"] = {
|
||||
policy: "allowedWithPermission",
|
||||
};
|
||||
|
||||
await act(async () => {
|
||||
addAndSelectMockLlm(store, ideMessenger);
|
||||
});
|
||||
|
|
@ -77,6 +82,11 @@ describe("Parallel Tool Calls", () => {
|
|||
test("should handle individual tool call actions without breaking other calls", async () => {
|
||||
const { ideMessenger, store } = await renderWithProviders(<Chat />);
|
||||
|
||||
// Mock the tools/evaluatePolicy response to allow tools without permission
|
||||
ideMessenger.responses["tools/evaluatePolicy"] = {
|
||||
policy: "allowedWithPermission",
|
||||
};
|
||||
|
||||
await act(async () => {
|
||||
addAndSelectMockLlm(store, ideMessenger);
|
||||
});
|
||||
|
|
@ -133,6 +143,11 @@ describe("Parallel Tool Calls", () => {
|
|||
test("should handle streaming deltas for multiple tool calls", async () => {
|
||||
const { ideMessenger, store } = await renderWithProviders(<Chat />);
|
||||
|
||||
// Mock the tools/evaluatePolicy response to allow tools without permission
|
||||
ideMessenger.responses["tools/evaluatePolicy"] = {
|
||||
policy: "allowedWithPermission",
|
||||
};
|
||||
|
||||
await act(async () => {
|
||||
addAndSelectMockLlm(store, ideMessenger);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { LLMFullCompletionOptions, Tool } from "core";
|
||||
import {
|
||||
ContextItem,
|
||||
LLMFullCompletionOptions,
|
||||
Tool,
|
||||
ToolCallState,
|
||||
ToolPolicy,
|
||||
} from "core";
|
||||
import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
|
||||
import { ToCoreProtocol } from "core/protocol";
|
||||
import { selectActiveTools } from "../selectors/selectActiveTools";
|
||||
|
|
@ -7,6 +13,7 @@ import { selectSelectedChatModel } from "../slices/configSlice";
|
|||
import {
|
||||
abortStream,
|
||||
addPromptCompletionPair,
|
||||
errorToolCall,
|
||||
setActive,
|
||||
setAppliedRulesAtIndex,
|
||||
setContextPercentage,
|
||||
|
|
@ -15,8 +22,10 @@ import {
|
|||
setIsPruned,
|
||||
setToolGenerated,
|
||||
streamUpdate,
|
||||
updateToolCallOutput,
|
||||
} from "../slices/sessionSlice";
|
||||
import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
|
||||
import { IIdeMessenger } from "../../context/IdeMessenger";
|
||||
import { constructMessages } from "../util/constructMessages";
|
||||
|
||||
import { modelSupportsNativeTools } from "core/llm/toolSupport";
|
||||
|
|
@ -28,6 +37,62 @@ import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
|
|||
import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
|
||||
import { callToolById } from "./callToolById";
|
||||
import { enhanceParsedArgs } from "./enhanceParsedArgs";
|
||||
|
||||
/**
|
||||
* Evaluates the tool policy for a tool call, including dynamic policy evaluation
|
||||
*/
|
||||
async function evaluateToolPolicy(
|
||||
toolCallState: ToolCallState,
|
||||
toolSettings: Record<string, ToolPolicy>,
|
||||
activeTools: Tool[],
|
||||
ideMessenger: IIdeMessenger,
|
||||
): Promise<{ policy: ToolPolicy; displayValue?: string }> {
|
||||
const basePolicy =
|
||||
toolSettings[toolCallState.toolCall.function.name] ??
|
||||
activeTools.find(
|
||||
(tool) => tool.function.name === toolCallState.toolCall.function.name,
|
||||
)?.defaultToolPolicy ??
|
||||
DEFAULT_TOOL_SETTING;
|
||||
|
||||
// Use already parsed arguments
|
||||
const parsedArgs = toolCallState.parsedArgs || {};
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await ideMessenger.request("tools/evaluatePolicy", {
|
||||
toolName: toolCallState.toolCall.function.name,
|
||||
basePolicy,
|
||||
args: parsedArgs,
|
||||
});
|
||||
} catch (error) {
|
||||
// If request fails, return disabled
|
||||
return { policy: "disabled" };
|
||||
}
|
||||
|
||||
// Evaluate the policy dynamically
|
||||
if (!result || result.status === "error") {
|
||||
// If evaluation fails, treat as disabled
|
||||
return { policy: "disabled" };
|
||||
}
|
||||
|
||||
const dynamicPolicy = result.content.policy;
|
||||
const displayValue = result.content.displayValue;
|
||||
|
||||
// Ensure dynamic policy cannot be more lenient than base policy
|
||||
// Policy hierarchy (most restrictive to least): disabled > allowedWithPermission > allowedWithoutPermission
|
||||
if (basePolicy === "disabled") {
|
||||
return { policy: "disabled", displayValue }; // Cannot override disabled
|
||||
}
|
||||
if (
|
||||
basePolicy === "allowedWithPermission" &&
|
||||
dynamicPolicy === "allowedWithoutPermission"
|
||||
) {
|
||||
return { policy: "allowedWithPermission", displayValue }; // Cannot make more lenient
|
||||
}
|
||||
|
||||
return { policy: dynamicPolicy, displayValue };
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the execution of tool calls that may be automatically accepted.
|
||||
* Sets all tools as generated first, then executes auto-approved tool calls.
|
||||
|
|
@ -36,7 +101,9 @@ async function handleToolCallExecution(
|
|||
dispatch: AppThunkDispatch,
|
||||
getState: () => RootState,
|
||||
activeTools: Tool[],
|
||||
): Promise<void> {
|
||||
ideMessenger: IIdeMessenger,
|
||||
): Promise<boolean> {
|
||||
// Return whether all tools were auto-approved
|
||||
const newState = getState();
|
||||
const toolSettings = newState.ui.toolSettings;
|
||||
const allToolCallStates = selectCurrentToolCalls(newState);
|
||||
|
|
@ -48,33 +115,71 @@ async function handleToolCallExecution(
|
|||
|
||||
// If no generating tool calls, nothing to process
|
||||
if (toolCallStates.length === 0) {
|
||||
return;
|
||||
return false; // No tools to process, need to set inactive
|
||||
}
|
||||
|
||||
// Check if ALL tool calls are auto-approved - if not, wait for user approval
|
||||
const allAutoApproved = toolCallStates.every((toolCallState) => {
|
||||
const toolPolicy =
|
||||
toolSettings[toolCallState.toolCall.function.name] ??
|
||||
activeTools.find(
|
||||
(tool) => tool.function.name === toolCallState.toolCall.function.name,
|
||||
)?.defaultToolPolicy ??
|
||||
DEFAULT_TOOL_SETTING;
|
||||
return toolPolicy == "allowedWithoutPermission";
|
||||
});
|
||||
// Check if ALL tool calls are auto-approved using dynamic evaluation
|
||||
const policyResults = await Promise.all(
|
||||
toolCallStates.map((toolCallState) =>
|
||||
evaluateToolPolicy(
|
||||
toolCallState,
|
||||
toolSettings,
|
||||
activeTools,
|
||||
ideMessenger,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Set all tools as generated first
|
||||
toolCallStates.forEach((toolCallState) => {
|
||||
dispatch(
|
||||
setToolGenerated({
|
||||
toolCallId: toolCallState.toolCallId,
|
||||
tools: newState.config.config.tools,
|
||||
}),
|
||||
);
|
||||
});
|
||||
// Handle disabled tool calls and set others as generated
|
||||
const autoApprovedResults = await Promise.all(
|
||||
toolCallStates.map(async (toolCallState, index) => {
|
||||
const { policy, displayValue } = policyResults[index];
|
||||
|
||||
// Only run if we have auto-approve for all
|
||||
if (policy === "disabled") {
|
||||
// Mark as errored instead of generated
|
||||
dispatch(errorToolCall({ toolCallId: toolCallState.toolCallId }));
|
||||
|
||||
// Use the displayValue from the policy evaluation, or fallback to function name
|
||||
const command = displayValue || toolCallState.toolCall.function.name;
|
||||
|
||||
// Add error message explaining why it's disabled
|
||||
dispatch(
|
||||
updateToolCallOutput({
|
||||
toolCallId: toolCallState.toolCallId,
|
||||
contextItems: [
|
||||
{
|
||||
icon: "problems",
|
||||
name: "Security Policy Violation",
|
||||
description: "Command Disabled",
|
||||
content: `This command has been disabled by security policy:\n\n${command}\n\nThis command cannot be executed as it may pose a security risk.`,
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
return false;
|
||||
} else {
|
||||
// Set as generated for non-disabled tools
|
||||
dispatch(
|
||||
setToolGenerated({
|
||||
toolCallId: toolCallState.toolCallId,
|
||||
tools: newState.config.config.tools,
|
||||
}),
|
||||
);
|
||||
return policy === "allowedWithoutPermission";
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const allAutoApproved = autoApprovedResults.every(Boolean);
|
||||
|
||||
// Only run if we have auto-approve for all non-disabled tools
|
||||
if (allAutoApproved && toolCallStates.length > 0) {
|
||||
const toolCallPromises = toolCallStates.map(async (toolCallState) => {
|
||||
const nonDisabledToolCalls = toolCallStates.filter(
|
||||
(_, index) => policyResults[index].policy !== "disabled",
|
||||
);
|
||||
|
||||
const toolCallPromises = nonDisabledToolCalls.map(async (toolCallState) => {
|
||||
const response = await dispatch(
|
||||
callToolById({ toolCallId: toolCallState.toolCallId }),
|
||||
);
|
||||
|
|
@ -83,6 +188,8 @@ async function handleToolCallExecution(
|
|||
|
||||
await Promise.all(toolCallPromises);
|
||||
}
|
||||
|
||||
return allAutoApproved;
|
||||
}
|
||||
|
||||
export const streamNormalInput = createAsyncThunk<
|
||||
|
|
@ -266,32 +373,18 @@ export const streamNormalInput = createAsyncThunk<
|
|||
),
|
||||
);
|
||||
|
||||
const generatingToolCalls = allToolCallStates.filter(
|
||||
(toolCallState) => toolCallState.status === "generating",
|
||||
// Handle tool call execution if there are any generating tool calls
|
||||
const allAutoApproved = await handleToolCallExecution(
|
||||
dispatch,
|
||||
getState,
|
||||
activeTools,
|
||||
extra.ideMessenger,
|
||||
);
|
||||
|
||||
// Check if ALL generating tool calls are auto-approved
|
||||
const allAutoApproved =
|
||||
generatingToolCalls.length > 0 &&
|
||||
generatingToolCalls.every((toolCallState) => {
|
||||
const toolPolicy =
|
||||
toolSettings[toolCallState.toolCall.function.name] ??
|
||||
activeTools.find(
|
||||
(tool) =>
|
||||
tool.function.name === toolCallState.toolCall.function.name,
|
||||
)?.defaultToolPolicy ??
|
||||
DEFAULT_TOOL_SETTING;
|
||||
return toolPolicy == "allowedWithoutPermission";
|
||||
});
|
||||
|
||||
// Only set inactive if:
|
||||
// 1. There are no tool calls, OR
|
||||
// 2. There are tool calls but they require manual approval
|
||||
// This prevents UI flashing for auto-approved tools while still showing approval UI for others
|
||||
if (generatingToolCalls.length === 0 || !allAutoApproved) {
|
||||
// Only set inactive if not all tools were auto-approved
|
||||
// This prevents UI flashing for auto-approved tools
|
||||
if (!allAutoApproved) {
|
||||
dispatch(setInactive());
|
||||
}
|
||||
|
||||
await handleToolCallExecution(dispatch, getState, activeTools);
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -671,6 +671,12 @@ describe("streamResponseThunk", () => {
|
|||
contextPercentage: 0.9,
|
||||
},
|
||||
});
|
||||
} else if (endpoint === "tools/evaluatePolicy") {
|
||||
// Mock dynamic policy evaluation - return auto-approve for this test
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: { policy: "allowedWithoutPermission" },
|
||||
});
|
||||
} else if (endpoint === "tools/call") {
|
||||
// Mock server-side tool call response
|
||||
return Promise.resolve({
|
||||
|
|
@ -759,7 +765,7 @@ describe("streamResponseThunk", () => {
|
|||
// Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist)
|
||||
const dispatchedActions = (mockStoreWithToolSettings as any).getActions();
|
||||
|
||||
// Verify exact action sequence by comparing action types
|
||||
// Verify exact action sequence
|
||||
const actionTypes = dispatchedActions.map((action: any) => action.type);
|
||||
expect(actionTypes).toEqual([
|
||||
"chat/streamResponse/pending",
|
||||
|
|
|
|||
|
|
@ -237,6 +237,12 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
contextPercentage: 0.9,
|
||||
},
|
||||
});
|
||||
} else if (endpoint === "tools/evaluatePolicy") {
|
||||
// Mock dynamic policy evaluation - return auto-approve for this test
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: { policy: "allowedWithoutPermission" },
|
||||
});
|
||||
} else if (endpoint === "tools/call") {
|
||||
// Mock server-side tool call response
|
||||
return Promise.resolve({
|
||||
|
|
@ -376,7 +382,7 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
// Verify key actions are dispatched (tool calls trigger a complex cascade, so we verify key actions exist)
|
||||
const dispatchedActions = (mockStoreWithToolSettings as any).getActions();
|
||||
|
||||
// Verify exact action sequence by comparing action types
|
||||
// Verify exact action sequence
|
||||
const actionTypes = dispatchedActions.map((action: any) => action.type);
|
||||
expect(actionTypes).toEqual([
|
||||
"chat/streamResponse/pending",
|
||||
|
|
@ -572,6 +578,16 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
|
||||
// Verify final state after tool call execution
|
||||
const finalState = mockStoreWithToolSettings.getState();
|
||||
|
||||
// Check that the tool was executed (status should be 'done' if auto-approved and executed)
|
||||
const toolCallState = finalState.session.history.find(
|
||||
(item) => item.toolCallStates && item.toolCallStates.length > 0,
|
||||
)?.toolCallStates?.[0];
|
||||
|
||||
// With proper mocking, the tool should be auto-executed
|
||||
expect(toolCallState?.status).toBe("done");
|
||||
expect(toolCallState?.output).toBeDefined();
|
||||
|
||||
expect(finalState).toEqual({
|
||||
session: {
|
||||
history: [
|
||||
|
|
@ -1012,16 +1028,30 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
],
|
||||
},
|
||||
{
|
||||
type: "session/setInactive",
|
||||
payload: undefined,
|
||||
},
|
||||
{
|
||||
type: "session/setToolGenerated",
|
||||
type: "session/errorToolCall",
|
||||
payload: {
|
||||
toolCallId: "tool-reject-1",
|
||||
tools: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session/updateToolCallOutput",
|
||||
payload: {
|
||||
toolCallId: "tool-reject-1",
|
||||
contextItems: [
|
||||
{
|
||||
icon: "problems",
|
||||
name: "Security Policy Violation",
|
||||
description: "Command Disabled",
|
||||
content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`,
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session/setInactive",
|
||||
payload: undefined,
|
||||
},
|
||||
{
|
||||
type: "chat/streamNormalInput/fulfilled",
|
||||
meta: {
|
||||
|
|
@ -1288,7 +1318,16 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
filepath: "test.js",
|
||||
changes: "const x = 1;",
|
||||
},
|
||||
status: "generated", // Tool call exists but isn't executed due to settings
|
||||
status: "errored", // Tool call is marked as errored due to being disabled
|
||||
output: [
|
||||
{
|
||||
icon: "problems",
|
||||
name: "Security Policy Violation",
|
||||
description: "Command Disabled",
|
||||
content: `This command has been disabled by security policy:\n\nedit_existing_file\n\nThis command cannot be executed as it may pose a security risk.`,
|
||||
hidden: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
|
@ -1662,10 +1701,6 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "session/setInactive",
|
||||
payload: undefined,
|
||||
},
|
||||
{
|
||||
type: "session/setToolGenerated",
|
||||
payload: {
|
||||
|
|
@ -1673,6 +1708,10 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
tools: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session/setInactive",
|
||||
payload: undefined,
|
||||
},
|
||||
{
|
||||
type: "chat/streamNormalInput/fulfilled",
|
||||
meta: {
|
||||
|
|
@ -2363,10 +2402,6 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "session/setInactive",
|
||||
payload: undefined,
|
||||
},
|
||||
{
|
||||
type: "session/setToolGenerated",
|
||||
payload: {
|
||||
|
|
@ -2374,6 +2409,10 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
tools: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "session/setInactive",
|
||||
payload: undefined,
|
||||
},
|
||||
{
|
||||
type: "chat/streamNormalInput/fulfilled",
|
||||
meta: {
|
||||
|
|
@ -2971,4 +3010,588 @@ describe("streamResponseThunk - tool calls", () => {
|
|||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("dynamic policy evaluation", () => {
|
||||
it("should call tools/evaluatePolicy with correct parameters", async () => {
|
||||
const mockStore = createMockStore({
|
||||
session: {
|
||||
history: [
|
||||
{
|
||||
message: { id: "1", role: "user", content: "Run echo hello" },
|
||||
contextItems: [],
|
||||
},
|
||||
],
|
||||
hasReasoningEnabled: false,
|
||||
isStreaming: true,
|
||||
id: "session-123",
|
||||
mode: "chat",
|
||||
streamAborter: new AbortController(),
|
||||
contextPercentage: 0,
|
||||
isPruned: false,
|
||||
isInEdit: false,
|
||||
title: "",
|
||||
lastSessionId: undefined,
|
||||
isSessionMetadataLoading: false,
|
||||
allSessionMetadata: [],
|
||||
symbols: {},
|
||||
codeBlockApplyStates: {
|
||||
states: [],
|
||||
curIndex: 0,
|
||||
},
|
||||
newestToolbarPreviewForInput: {},
|
||||
compactionLoading: {},
|
||||
inlineErrorMessage: undefined,
|
||||
},
|
||||
config: {
|
||||
config: {
|
||||
tools: [],
|
||||
rules: [],
|
||||
tabAutocompleteModel: undefined,
|
||||
selectedModelByRole: {
|
||||
chat: mockClaudeModel,
|
||||
apply: null,
|
||||
edit: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
experimental: {
|
||||
onlyUseSystemMessageTools: false,
|
||||
},
|
||||
} as any,
|
||||
lastSelectedModelByRole: {
|
||||
chat: mockClaudeModel.title,
|
||||
},
|
||||
} as any,
|
||||
ui: {
|
||||
toolSettings: {
|
||||
run_terminal_command: "allowedWithoutPermission",
|
||||
},
|
||||
ruleSettings: {},
|
||||
showDialog: false,
|
||||
dialogMessage: undefined,
|
||||
} as any,
|
||||
} as any);
|
||||
|
||||
const mockIdeMessenger = mockStore.mockIdeMessenger;
|
||||
|
||||
// Simple mock - just return a different policy for testing
|
||||
mockIdeMessenger.request.mockImplementation(
|
||||
(endpoint: string, data: any) => {
|
||||
if (endpoint === "tools/evaluatePolicy") {
|
||||
// For this test, simulate that echo commands require permission
|
||||
if (data.args.command?.toLowerCase().startsWith("echo")) {
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: { policy: "allowedWithPermission" },
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: { policy: data.basePolicy },
|
||||
});
|
||||
} else if (endpoint === "llm/compileChat") {
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: {
|
||||
compiledChatMessages: [
|
||||
{ role: "user", content: "Run echo hello" },
|
||||
],
|
||||
didPrune: false,
|
||||
contextPercentage: 0.5,
|
||||
},
|
||||
});
|
||||
} else if (endpoint === "history/save") {
|
||||
return Promise.resolve({ status: "success" });
|
||||
} else if (endpoint === "history/list") {
|
||||
return Promise.resolve({ status: "success", content: [] });
|
||||
}
|
||||
return Promise.resolve({ status: "success", content: {} });
|
||||
},
|
||||
);
|
||||
|
||||
// Setup streaming with echo command (should require permission despite auto-approve base)
|
||||
async function* mockStreamWithEcho() {
|
||||
yield [{ role: "assistant", content: "I'll run the echo command." }];
|
||||
yield [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-echo-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "run_terminal_command",
|
||||
arguments: JSON.stringify({ command: "echo hello" }),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
return {
|
||||
prompt: "Run echo hello",
|
||||
completion: "I'll run the echo command.",
|
||||
modelProvider: "anthropic",
|
||||
};
|
||||
}
|
||||
|
||||
mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithEcho());
|
||||
|
||||
// Execute thunk
|
||||
await mockStore.dispatch(
|
||||
streamResponseThunk({
|
||||
editorState: mockEditorState,
|
||||
modifiers: mockModifiers,
|
||||
}) as any,
|
||||
);
|
||||
|
||||
// Just verify the call was made with correct params
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith(
|
||||
"tools/evaluatePolicy",
|
||||
expect.objectContaining({
|
||||
toolName: "run_terminal_command",
|
||||
basePolicy: "allowedWithoutPermission",
|
||||
args: { command: "echo hello" },
|
||||
}),
|
||||
);
|
||||
|
||||
// Verify tool wasn't auto-executed (policy changed to require permission)
|
||||
expect(mockIdeMessenger.request).not.toHaveBeenCalledWith(
|
||||
"tools/call",
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
|
||||
it("should respect disabled policy", async () => {
|
||||
const mockStore = createMockStore({
|
||||
session: {
|
||||
history: [
|
||||
{
|
||||
message: { id: "1", role: "user", content: "Run ls" },
|
||||
contextItems: [],
|
||||
},
|
||||
],
|
||||
hasReasoningEnabled: false,
|
||||
isStreaming: true,
|
||||
id: "session-123",
|
||||
mode: "chat",
|
||||
streamAborter: new AbortController(),
|
||||
contextPercentage: 0,
|
||||
isPruned: false,
|
||||
isInEdit: false,
|
||||
title: "",
|
||||
lastSessionId: undefined,
|
||||
isSessionMetadataLoading: false,
|
||||
allSessionMetadata: [],
|
||||
symbols: {},
|
||||
codeBlockApplyStates: {
|
||||
states: [],
|
||||
curIndex: 0,
|
||||
},
|
||||
newestToolbarPreviewForInput: {},
|
||||
compactionLoading: {},
|
||||
inlineErrorMessage: undefined,
|
||||
},
|
||||
config: {
|
||||
config: {
|
||||
tools: [],
|
||||
rules: [],
|
||||
tabAutocompleteModel: undefined,
|
||||
selectedModelByRole: {
|
||||
chat: mockClaudeModel,
|
||||
apply: null,
|
||||
edit: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
experimental: {
|
||||
onlyUseSystemMessageTools: false,
|
||||
},
|
||||
} as any,
|
||||
lastSelectedModelByRole: {
|
||||
chat: mockClaudeModel.title,
|
||||
},
|
||||
} as any,
|
||||
ui: {
|
||||
toolSettings: {
|
||||
run_terminal_command: "disabled", // Tool is disabled
|
||||
},
|
||||
ruleSettings: {},
|
||||
showDialog: false,
|
||||
dialogMessage: undefined,
|
||||
} as any,
|
||||
} as any);
|
||||
|
||||
const mockIdeMessenger = mockStore.mockIdeMessenger;
|
||||
|
||||
// Simple mock - just return disabled policy
|
||||
mockIdeMessenger.request.mockImplementation(
|
||||
(endpoint: string, data: any) => {
|
||||
if (endpoint === "tools/evaluatePolicy") {
|
||||
// Backend should respect disabled state
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: { policy: "disabled" },
|
||||
});
|
||||
} else if (endpoint === "llm/compileChat") {
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: {
|
||||
compiledChatMessages: [{ role: "user", content: "Run ls" }],
|
||||
didPrune: false,
|
||||
contextPercentage: 0.5,
|
||||
},
|
||||
});
|
||||
} else if (endpoint === "history/save") {
|
||||
return Promise.resolve({ status: "success" });
|
||||
} else if (endpoint === "history/list") {
|
||||
return Promise.resolve({ status: "success", content: [] });
|
||||
}
|
||||
return Promise.resolve({ status: "success", content: {} });
|
||||
},
|
||||
);
|
||||
|
||||
// Setup streaming with regular command
|
||||
async function* mockStreamWithLs() {
|
||||
yield [{ role: "assistant", content: "I'll list the files." }];
|
||||
yield [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-ls-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "run_terminal_command",
|
||||
arguments: JSON.stringify({ command: "ls" }),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
return {
|
||||
prompt: "Run ls",
|
||||
completion: "I'll list the files.",
|
||||
modelProvider: "anthropic",
|
||||
};
|
||||
}
|
||||
|
||||
mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithLs());
|
||||
|
||||
// Execute thunk
|
||||
await mockStore.dispatch(
|
||||
streamResponseThunk({
|
||||
editorState: mockEditorState,
|
||||
modifiers: mockModifiers,
|
||||
}) as any,
|
||||
);
|
||||
|
||||
// Verify tools/evaluatePolicy was called
|
||||
expect(mockIdeMessenger.request).toHaveBeenCalledWith(
|
||||
"tools/evaluatePolicy",
|
||||
expect.objectContaining({
|
||||
toolName: "run_terminal_command",
|
||||
basePolicy: "disabled",
|
||||
args: { command: "ls" },
|
||||
}),
|
||||
);
|
||||
|
||||
// Tool should NOT be executed since it's disabled
|
||||
expect(mockIdeMessenger.request).not.toHaveBeenCalledWith(
|
||||
"tools/call",
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle evaluation errors gracefully", async () => {
|
||||
const mockStore = createMockStore({
|
||||
session: {
|
||||
history: [
|
||||
{
|
||||
message: { id: "1", role: "user", content: "Do something" },
|
||||
contextItems: [],
|
||||
},
|
||||
],
|
||||
hasReasoningEnabled: false,
|
||||
isStreaming: true,
|
||||
id: "session-123",
|
||||
mode: "chat",
|
||||
streamAborter: new AbortController(),
|
||||
contextPercentage: 0,
|
||||
isPruned: false,
|
||||
isInEdit: false,
|
||||
title: "",
|
||||
lastSessionId: undefined,
|
||||
isSessionMetadataLoading: false,
|
||||
allSessionMetadata: [],
|
||||
symbols: {},
|
||||
codeBlockApplyStates: {
|
||||
states: [],
|
||||
curIndex: 0,
|
||||
},
|
||||
newestToolbarPreviewForInput: {},
|
||||
compactionLoading: {},
|
||||
inlineErrorMessage: undefined,
|
||||
},
|
||||
config: {
|
||||
config: {
|
||||
tools: [],
|
||||
rules: [],
|
||||
tabAutocompleteModel: undefined,
|
||||
selectedModelByRole: {
|
||||
chat: mockClaudeModel,
|
||||
apply: null,
|
||||
edit: null,
|
||||
summarize: null,
|
||||
autocomplete: null,
|
||||
rerank: null,
|
||||
embed: null,
|
||||
},
|
||||
experimental: {
|
||||
onlyUseSystemMessageTools: false,
|
||||
},
|
||||
} as any,
|
||||
lastSelectedModelByRole: {
|
||||
chat: mockClaudeModel.title,
|
||||
},
|
||||
} as any,
|
||||
ui: {
|
||||
toolSettings: {
|
||||
some_tool: "allowedWithoutPermission",
|
||||
},
|
||||
ruleSettings: {},
|
||||
showDialog: false,
|
||||
dialogMessage: undefined,
|
||||
} as any,
|
||||
} as any);
|
||||
|
||||
const mockIdeMessenger = mockStore.mockIdeMessenger;
|
||||
|
||||
// Mock evaluation failure
|
||||
mockIdeMessenger.request.mockImplementation((endpoint: string) => {
|
||||
if (endpoint === "tools/evaluatePolicy") {
|
||||
// Simulate evaluation error
|
||||
return Promise.resolve({
|
||||
status: "error",
|
||||
error: "Failed to evaluate policy",
|
||||
});
|
||||
} else if (endpoint === "llm/compileChat") {
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: {
|
||||
compiledChatMessages: [{ role: "user", content: "Do something" }],
|
||||
didPrune: false,
|
||||
contextPercentage: 0.5,
|
||||
},
|
||||
});
|
||||
} else if (endpoint === "history/save") {
|
||||
return Promise.resolve({ status: "success" });
|
||||
} else if (endpoint === "history/list") {
|
||||
return Promise.resolve({ status: "success", content: [] });
|
||||
}
|
||||
return Promise.resolve({ status: "success", content: {} });
|
||||
});
|
||||
|
||||
// Setup streaming with tool call
|
||||
async function* mockStreamWithTool() {
|
||||
yield [{ role: "assistant", content: "I'll help you." }];
|
||||
yield [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "some_tool",
|
||||
arguments: JSON.stringify({ arg: "value" }),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
return {
|
||||
prompt: "Do something",
|
||||
completion: "I'll help you.",
|
||||
modelProvider: "anthropic",
|
||||
};
|
||||
}
|
||||
|
||||
mockIdeMessenger.llmStreamChat.mockReturnValue(mockStreamWithTool());
|
||||
|
||||
// Execute thunk - should handle error gracefully
|
||||
const result = await mockStore.dispatch(
|
||||
streamResponseThunk({
|
||||
editorState: mockEditorState,
|
||||
modifiers: mockModifiers,
|
||||
}) as any,
|
||||
);
|
||||
|
||||
// Should complete successfully despite evaluation error
|
||||
expect(result.type).toBe("chat/streamResponse/fulfilled");
|
||||
|
||||
// Tool should be treated as disabled due to evaluation error
|
||||
expect(mockIdeMessenger.request).not.toHaveBeenCalledWith(
|
||||
"tools/call",
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
|
||||
it("should properly handle disabled commands and show error status", async () => {
|
||||
const { mockStore, mockIdeMessenger } = setupTest();
|
||||
|
||||
// Setup store with runTerminalCommand tool
|
||||
const mockStoreWithTerminalTool = createMockStore({
|
||||
...mockStore.getState(),
|
||||
config: {
|
||||
...mockStore.getState().config,
|
||||
config: {
|
||||
...mockStore.getState().config.config,
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
displayTitle: "Run Terminal Command",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
description: "Execute a terminal command",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description: "The command to execute",
|
||||
},
|
||||
},
|
||||
required: ["command"],
|
||||
},
|
||||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
readonly: false,
|
||||
group: "code",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
ui: {
|
||||
...mockStore.getState().ui,
|
||||
toolSettings: {
|
||||
runTerminalCommand: "allowedWithPermission",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const mockTerminalIdeMessenger =
|
||||
mockStoreWithTerminalTool.mockIdeMessenger;
|
||||
|
||||
// Setup compilation and policy evaluation responses
|
||||
mockTerminalIdeMessenger.request.mockImplementation(
|
||||
(endpoint: string, data: any) => {
|
||||
if (endpoint === "llm/compileChat") {
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: {
|
||||
compiledChatMessages: [
|
||||
{ role: "user", content: "Run eval command" },
|
||||
],
|
||||
didPrune: false,
|
||||
contextPercentage: 0.9,
|
||||
},
|
||||
});
|
||||
} else if (endpoint === "tools/evaluatePolicy") {
|
||||
// Return disabled for eval command
|
||||
const args = data.args || {};
|
||||
if (args.command && args.command.includes("eval")) {
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: { policy: "disabled" },
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
status: "success",
|
||||
content: { policy: "allowedWithPermission" },
|
||||
});
|
||||
} else if (endpoint === "history/save") {
|
||||
return Promise.resolve({ status: "success" });
|
||||
} else if (endpoint === "history/list") {
|
||||
return Promise.resolve({ status: "success", content: [] });
|
||||
}
|
||||
return Promise.resolve({ status: "success", content: {} });
|
||||
},
|
||||
);
|
||||
|
||||
// Setup streaming with eval command tool call
|
||||
async function* mockStreamWithEvalCommand() {
|
||||
yield [
|
||||
{ role: "assistant", content: "I'll run the eval command for you." },
|
||||
];
|
||||
yield [
|
||||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-call-eval",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "runTerminalCommand",
|
||||
arguments: JSON.stringify({ command: 'eval "echo hello"' }),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
return {
|
||||
prompt: "Run eval command",
|
||||
completion: "I'll run the eval command for you.",
|
||||
modelProvider: "anthropic",
|
||||
};
|
||||
}
|
||||
|
||||
mockTerminalIdeMessenger.llmStreamChat.mockReturnValue(
|
||||
mockStreamWithEvalCommand(),
|
||||
);
|
||||
|
||||
// Execute thunk
|
||||
await mockStoreWithTerminalTool.dispatch(
|
||||
streamResponseThunk({
|
||||
editorState: mockEditorState,
|
||||
modifiers: mockModifiers,
|
||||
}) as any,
|
||||
);
|
||||
|
||||
// Get final state
|
||||
const finalState = mockStoreWithTerminalTool.getState();
|
||||
const toolCallStates = finalState.session.history.flatMap(
|
||||
(item) => item.toolCallStates || [],
|
||||
);
|
||||
|
||||
// Find the eval command tool call
|
||||
const evalToolCall = toolCallStates.find(
|
||||
(t) => t.toolCallId === "tool-call-eval",
|
||||
);
|
||||
|
||||
expect(evalToolCall).toBeDefined();
|
||||
|
||||
// The tool call should have an errored status (not "generated")
|
||||
expect(evalToolCall?.status).toBe("errored");
|
||||
|
||||
// The tool call should have an error message explaining it's disabled
|
||||
// Errors are stored as ContextItems with the error in the content
|
||||
const errorOutput = evalToolCall?.output?.[0];
|
||||
expect(errorOutput?.content).toContain("disabled");
|
||||
|
||||
// Verify the command was NOT executed (no tool/call request)
|
||||
const toolCallRequests =
|
||||
mockTerminalIdeMessenger.request.mock.calls.filter(
|
||||
(call) => call[0] === "tools/call",
|
||||
);
|
||||
expect(toolCallRequests).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -42,6 +42,16 @@ export const createMockStore = (initialState?: Partial<RootState>) => {
|
|||
contextPercentage: 0,
|
||||
isPruned: false,
|
||||
isInEdit: false,
|
||||
isSessionMetadataLoading: false,
|
||||
allSessionMetadata: [],
|
||||
symbols: {},
|
||||
codeBlockApplyStates: {
|
||||
states: [],
|
||||
curIndex: 0,
|
||||
},
|
||||
newestToolbarPreviewForInput: {},
|
||||
compactionLoading: {},
|
||||
inlineErrorMessage: undefined,
|
||||
...initialState?.session,
|
||||
},
|
||||
ui: {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue