test: dynamic policy evaluation
This commit is contained in:
parent
940031917c
commit
a7ceb4e033
4 changed files with 624 additions and 51 deletions
|
|
@ -1,4 +1,4 @@
|
|||
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 +6,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 +28,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 +74,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
// Helper function to create a ToolExtras object
|
||||
const createMockExtras = (
|
||||
overrides: Partial<{
|
||||
onPartialOutput?: jest.Mock;
|
||||
onPartialOutput?: any;
|
||||
remoteName?: string;
|
||||
}> = {},
|
||||
): ToolExtras => {
|
||||
|
|
@ -90,16 +91,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 +148,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 +192,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 +356,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 +403,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 +414,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 +473,116 @@ describe("runTerminalCommandImpl", () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTerminalCommandTool.evaluateToolCallPolicy", () => {
|
||||
|
||||
it("should require permission for echo commands regardless of base policy", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "echo hello world" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(basePolicy, args);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
|
||||
it("should require permission for ECHO commands (case insensitive)", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "ECHO HELLO" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(basePolicy, args);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
|
||||
it("should require permission for echo commands with leading spaces", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: " echo test" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(basePolicy, args);
|
||||
|
||||
expect(result).toBe("allowedWithPermission");
|
||||
});
|
||||
|
||||
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 echo 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 not match echo in middle of command", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "npm run echo-test" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(basePolicy, args);
|
||||
|
||||
// Should use base policy since "echo" is not at the start
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
|
||||
it("should handle commands that contain echo but don't start with it", () => {
|
||||
const basePolicy = "allowedWithoutPermission";
|
||||
const args = { command: "grep echo file.txt" };
|
||||
|
||||
const result = runTerminalCommandTool.evaluateToolCallPolicy!(basePolicy, args);
|
||||
|
||||
// Should use base policy since command doesn't start with echo
|
||||
expect(result).toBe("allowedWithoutPermission");
|
||||
});
|
||||
});
|
||||
|
|
@ -663,6 +663,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({
|
||||
|
|
@ -751,7 +757,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: [
|
||||
|
|
@ -2939,4 +2955,431 @@ 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),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -39,6 +39,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