fix: properly handle disabled status

This commit is contained in:
Tomasz Stefaniak 2025-08-28 14:19:09 -07:00
parent cea2705406
commit a9bf3aa123
3 changed files with 171 additions and 8 deletions

View file

@ -255,7 +255,7 @@ export class VsCodeMessenger {
});
this.onWebview("tools/evaluatePolicy", async (msg) => {
return this.inProcessMessenger.invoke("tools/evaluatePolicy", msg.data);
return this.inProcessMessenger.externalRequest("tools/evaluatePolicy", msg.data, msg.messageId);
});
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/

View file

@ -1,5 +1,5 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { LLMFullCompletionOptions, Tool, ToolPolicy } from "core";
import { ContextItem, LLMFullCompletionOptions, Tool, ToolPolicy } from "core";
import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
import { ToCoreProtocol } from "core/protocol";
import { selectActiveTools } from "../selectors/selectActiveTools";
@ -8,6 +8,7 @@ import { selectSelectedChatModel } from "../slices/configSlice";
import {
abortStream,
addPromptCompletionPair,
errorToolCall,
setActive,
setAppliedRulesAtIndex,
setContextPercentage,
@ -16,6 +17,7 @@ import {
setIsPruned,
setToolGenerated,
streamUpdate,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
import { constructMessages } from "../util/constructMessages";
@ -54,7 +56,6 @@ async function evaluateToolPolicy(
// If parsing fails, use empty object
}
console.log("HERE HELLO WORLD");
let result;
try {
@ -71,7 +72,6 @@ async function evaluateToolPolicy(
// Evaluate the policy dynamically
console.log("RESULT ZZZ", result);
if (!result || result.status === "error") {
// If evaluation fails, treat as disabled
@ -340,11 +340,25 @@ export const streamNormalInput = createAsyncThunk<
// Check if any are disabled and handle them
policies.forEach((policy, index) => {
if (policy === "disabled") {
// Mark disabled tools as generated but they won't be executed
const toolCallId = generatingToolCalls[index].toolCallId;
const toolName = generatingToolCalls[index].toolCall.function.name;
// Mark as errored instead of generated
dispatch(errorToolCall({ toolCallId }));
// Add error message explaining why it's disabled
dispatch(
setToolGenerated({
toolCallId: generatingToolCalls[index].toolCallId,
tools: newState.config.config.tools,
updateToolCallOutput({
toolCallId,
contextItems: [
{
icon: "problems",
name: "Tool Call Disabled",
description: "Security Policy Violation",
content: `The command '${toolName}' has been disabled by security policy. This command cannot be executed as it may pose a security risk.`,
hidden: false,
},
],
}),
);
}

View file

@ -3419,5 +3419,154 @@ describe("streamResponseThunk - tool calls", () => {
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);
});
});
});