feat: tool call args preprocessing (#7992)

* feat: preprocess tool call args

* fix: broken multi edit impl

* fix: preprocess test failures

* fix: preprocessing tests

* fix: tool calls test progress

* fix: tests using mock store

* fix: thunk tests working

* fix: mock ide messenger tests
This commit is contained in:
Dallin Romney 2025-09-30 18:49:29 -07:00 • committed by GitHub
parent 7e002e879a
commit fac7f5c449
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 1816 additions and 3486 deletions

View file

@ -62,7 +62,7 @@ import { localPathToUri } from "../util/pathToUri";
import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../tools";
import { getBaseToolDefinitions, serializeTool } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
import { loadConfigContextProviders } from "./loadContextProviders";
@ -672,7 +672,7 @@ async function finalToBrowserConfig(
experimental: final.experimental,
rules: final.rules,
docs: final.docs,
tools: final.tools,
tools: final.tools.map(serializeTool),
mcpServerStatuses: final.mcpServerStatuses,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),

View file

@ -1104,7 +1104,6 @@ export class Core {
const tool = config.tools.find((t) => t.function.name === toolName);
if (!tool) {
// Tool not found, return base policy
return { policy: basePolicy };
}
@ -1114,17 +1113,32 @@ export class Core {
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("tools/preprocessArgs", async ({ data: { toolName, 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) {
throw new Error(`Tool ${toolName} not found`);
}
const preprocessedArgs = await tool.preprocessArgs?.(args, {
ide: this.ide,
});
return {
preprocessedArgs,
};
});
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});

View file

@ -7,22 +7,23 @@ export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
* Validates a single edit operation
*/
export function validateSingleEdit(
oldString: string,
newString: string,
oldString: unknown,
newString: unknown,
replaceAll: unknown,
index?: number,
): void {
): { oldString: string; newString: string; replaceAll?: boolean } {
const context = index !== undefined ? `edit at index ${index}: ` : "";
if (!oldString && oldString !== "") {
if (oldString === undefined || typeof oldString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingOldString,
`${context}old_string is required`,
`${context}string old_string is required`,
);
}
if (newString === undefined) {
if (newString === undefined || typeof newString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingNewString,
`${context}new_string is required`,
`${context}string new_string is required`,
);
}
if (oldString === newString) {
@ -31,6 +32,13 @@ export function validateSingleEdit(
`${context}old_string and new_string must be different`,
);
}
if (replaceAll !== undefined && typeof replaceAll !== "boolean") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
`${context}replace_all must be a valid boolean`,
);
}
return { oldString, newString, replaceAll };
}
export function trimEmptyLines({

View file

@ -6,39 +6,69 @@ describe("validateSingleEdit", () => {
describe("valid inputs", () => {
it("should not throw for valid non-empty strings", () => {
expect(() => {
validateSingleEdit("old", "new");
validateSingleEdit("old", "new", undefined);
}).not.toThrow();
});
it("should allow empty old_string for file creation", () => {
expect(() => {
validateSingleEdit("", "new content");
validateSingleEdit("", "new content", undefined);
}).not.toThrow();
});
it("should allow empty new_string for deletion", () => {
expect(() => {
validateSingleEdit("delete me", "");
validateSingleEdit("delete me", "", undefined);
}).not.toThrow();
});
it("should allow multiline strings", () => {
expect(() => {
validateSingleEdit("line1\nline2", "newline1\nnewline2");
validateSingleEdit("line1\nline2", "newline1\nnewline2", undefined);
}).not.toThrow();
});
it("should allow special characters", () => {
expect(() => {
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g");
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g", undefined);
}).not.toThrow();
});
it("should allow replaceAll as true", () => {
expect(() => {
validateSingleEdit("old", "new", true);
}).not.toThrow();
});
it("should allow replaceAll as false", () => {
expect(() => {
validateSingleEdit("old", "new", false);
}).not.toThrow();
});
it("should return validated values including replaceAll", () => {
const result = validateSingleEdit("old", "new", true);
expect(result).toEqual({
oldString: "old",
newString: "new",
replaceAll: true,
});
});
it("should return validated values with replaceAll undefined", () => {
const result = validateSingleEdit("old", "new", undefined);
expect(result).toEqual({
oldString: "old",
newString: "new",
replaceAll: undefined,
});
});
});
describe("invalid inputs", () => {
it("should throw error when old_string is null", () => {
expect(() => {
validateSingleEdit(null as any, "new");
validateSingleEdit(null as any, "new", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -48,7 +78,7 @@ describe("validateSingleEdit", () => {
it("should throw error when old_string is undefined", () => {
expect(() => {
validateSingleEdit(undefined as any, "new");
validateSingleEdit(undefined as any, "new", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -58,7 +88,7 @@ describe("validateSingleEdit", () => {
it("should throw error when new_string is undefined", () => {
expect(() => {
validateSingleEdit("old", undefined as any);
validateSingleEdit("old", undefined as any, undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
@ -68,7 +98,7 @@ describe("validateSingleEdit", () => {
it("should throw error when old_string and new_string are identical", () => {
expect(() => {
validateSingleEdit("same", "same");
validateSingleEdit("same", "same", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
@ -78,19 +108,49 @@ describe("validateSingleEdit", () => {
it("should throw error when both are empty strings", () => {
expect(() => {
validateSingleEdit("", "");
validateSingleEdit("", "", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should throw error when replaceAll is not a boolean", () => {
expect(() => {
validateSingleEdit("old", "new", "invalid" as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should throw error when replaceAll is null", () => {
expect(() => {
validateSingleEdit("old", "new", null as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should throw error when replaceAll is a number", () => {
expect(() => {
validateSingleEdit("old", "new", 1 as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
});
describe("error messages with context", () => {
it("should include edit number in error messages when index provided", () => {
expect(() => {
validateSingleEdit(null as any, "new", 2);
validateSingleEdit(null as any, "new", undefined, 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -100,7 +160,7 @@ describe("validateSingleEdit", () => {
it("should include edit number for new_string errors", () => {
expect(() => {
validateSingleEdit("old", undefined as any, 0);
validateSingleEdit("old", undefined as any, undefined, 0);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
@ -110,7 +170,7 @@ describe("validateSingleEdit", () => {
it("should include edit number for identical strings error", () => {
expect(() => {
validateSingleEdit("same", "same", 4);
validateSingleEdit("same", "same", undefined, 4);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
@ -118,9 +178,19 @@ describe("validateSingleEdit", () => {
);
});
it("should include edit number for replaceAll validation error", () => {
expect(() => {
validateSingleEdit("old", "new", "invalid" as any, 3);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should not include context when index not provided", () => {
expect(() => {
validateSingleEdit("same", "same");
validateSingleEdit("same", "same", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,

View file

@ -2,26 +2,30 @@ import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { validateSingleEdit } from "./findAndReplaceUtils";
export interface MultiEditValidationResult {
edits: EditOperation[];
}
/**
* Validates multi-edit arguments and all edits in a single pass
* @param args - The arguments object containing the edits array
* @returns Validated edits array
* @throws ContinueError if validation fails
*/
export function validateMultiEdit(args: any): MultiEditValidationResult {
const { edits } = args;
export function validateMultiEdit(args: unknown): {
edits: EditOperation[];
} {
if (typeof args !== "object" || !args || !("edits" in args)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"invalid multi-edit args",
);
}
// Validate that edits is a non-empty array
if (!edits || !Array.isArray(edits)) {
if (!Array.isArray(args.edits)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"edits array is required",
);
}
const { edits } = args;
if (edits.length === 0) {
throw new ContinueError(
@ -35,7 +39,7 @@ export function validateMultiEdit(args: any): MultiEditValidationResult {
const edit = edits[i];
// Use existing single edit validation
validateSingleEdit(edit.old_string, edit.new_string, i);
validateSingleEdit(edit.old_string, edit.new_string, edit.replace_all, i);
// Only the first edit can have empty old_string (for insertion at beginning)
if (i > 0 && edit.old_string === "") {

View file

@ -0,0 +1,23 @@
import { IDE } from "../..";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { resolveRelativePathInDir } from "../../util/ideUtils";
export async function validateSearchAndReplaceFilepath(
filepath: unknown,
ide: IDE,
) {
if (!filepath || typeof filepath !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingFilepath,
"filepath (string) is required",
);
}
const resolvedFilepath = await resolveRelativePathInDir(filepath, ide);
if (!resolvedFilepath) {
throw new ContinueError(
ContinueErrorReason.FileNotFound,
`File ${filepath} does not exist`,
);
}
return resolvedFilepath;
}

9
core/index.d.ts vendored
View file

@ -1080,7 +1080,6 @@ export interface Tool {
parameters?: Record<string, any>;
strict?: boolean | null;
};
displayTitle: string;
wouldLikeTo?: string;
isCurrently?: string;
@ -1097,6 +1096,12 @@ export interface Tool {
};
defaultToolPolicy?: ToolPolicy;
toolCallIcon?: string;
preprocessArgs?: (
args: Record<string, unknown>,
extras: {
ide: IDE;
},
) => Promise<Record<string, unknown>>;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
@ -1776,7 +1781,7 @@ export interface BrowserSerializedContinueConfig {
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
tools: Omit<Tool, "preprocessArgs", "evaluatePolicy">[];
mcpServerStatuses: MCPServerStatus[];
rules: RuleWithSource[];
usePlatform: boolean;

View file

@ -318,6 +318,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
{ policy: ToolPolicy; displayValue?: string },
];
"tools/preprocessArgs": [
{ toolName: string; args: Record<string, unknown> },
{ preprocessedArgs?: Record<string, unknown> },
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];

View file

@ -82,6 +82,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"didChangeSelectedOrg",
"tools/call",
"tools/evaluatePolicy",
"tools/preprocessArgs",
"controlPlane/getEnvironment",
"controlPlane/getFreeTrialStatus",
"controlPlane/getModelsAddOnUpgradeUrl",

View file

@ -1,2 +1,4 @@
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
export const ERRORED_TOOL_CALL_OUTPUT_MESSAGE =
"There was an error calling the tool.";

View file

@ -1,4 +1,7 @@
import { Tool } from "../..";
import { validateMultiEdit } from "../../edit/searchAndReplace/multiEditValidation";
import { executeMultiFindAndReplace } from "../../edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
@ -107,4 +110,24 @@ WARNINGS:
],
},
defaultToolPolicy: "allowedWithPermission",
preprocessArgs: async (args, extras) => {
const { edits } = validateMultiEdit(args);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ide,
);
const editingFileContents = await extras.ide.readFile(fileUri);
const newFileContents = executeMultiFindAndReplace(
editingFileContents,
edits,
);
return {
...args,
fileUri,
editingFileContents,
newFileContents,
};
},
};

View file

@ -1,4 +1,7 @@
import { Tool } from "../..";
import { validateSingleEdit } from "../../edit/searchAndReplace/findAndReplaceUtils";
import { executeFindAndReplace } from "../../edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
@ -70,4 +73,31 @@ WARNINGS:
],
},
defaultToolPolicy: "allowedWithPermission",
preprocessArgs: async (args, extras) => {
const { oldString, newString, replaceAll } = validateSingleEdit(
args.old_string,
args.new_string,
args.replace_all,
);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ide,
);
const editingFileContents = await extras.ide.readFile(fileUri);
const newFileContents = executeFindAndReplace(
editingFileContents,
oldString,
newString,
replaceAll ?? false,
0,
);
return {
...args,
fileUri,
editingFileContents,
newFileContents,
};
},
};

View file

@ -51,3 +51,8 @@ export const getConfigDependentToolDefinitions = (
return tools;
};
export function serializeTool(tool: Tool) {
const { preprocessArgs, evaluateToolCallPolicy, ...rest } = tool;
return rest;
}

View file

@ -27,6 +27,7 @@ export enum ContinueErrorReason {
FindAndReplaceMissingOldString = "find_and_replace_missing_old_string",
FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string",
FindAndReplaceMissingNewString = "find_and_replace_missing_new_string",
FindAndReplaceInvalidReplaceAll = "find_and_replace_invalid_replace_all",
FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found",
FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences",
FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath",
@ -48,6 +49,6 @@ export enum ContinueErrorReason {
ParentDirectoryNotFound = "parent_directory_not_found",
// Other
Unspecified = "unspecified",
Unknown = "unknown",
Unspecified = "unspecified", // I.e. a known error but no specific code for it
Unknown = "unknown", // I.e. an unexpected error
}

View file

@ -104,18 +104,22 @@ WARNINGS:
},
},
preprocess: async (args) => {
const { old_string, new_string, replace_all = false } = args as EditArgs;
const { old_string, new_string, replace_all } = args as EditArgs;
const { resolvedPath } = validateAndResolveFilePath(args);
validateSingleEdit(old_string, new_string);
const { oldString, newString, replaceAll } = validateSingleEdit(
old_string,
new_string,
replace_all,
);
const oldContent = fs.readFileSync(resolvedPath, "utf-8");
const newContent = executeFindAndReplace(
oldContent,
old_string,
new_string,
replace_all,
oldString,
newString,
replaceAll ?? false,
0,
);

View file

@ -144,6 +144,7 @@ class MessageTypes {
"didChangeSelectedOrg",
"tools/call",
"tools/evaluatePolicy",
"tools/preprocessArgs",
"controlPlane/openUrl",
"isItemTooBig",
"process/markAsBackgrounded",

View file

@ -44,22 +44,8 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
"file:///Users/user/workspace1",
"file:///Users/user/workspace2",
],
"history/list": [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
{
title: "Remote Agent",
sessionId: "remote-agent-123",
dateCreated: new Date().toString(),
workspaceDirectory: "",
isRemote: true,
remoteId: "agent-123",
},
],
"history/list": [],
"docs/getIndexedPages": [],
"history/save": undefined,
getControlPlaneSessionInfo: {
AUTH_TYPE: AuthType.WorkOsStaging,
@ -92,6 +78,10 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
},
],
},
"context/getSymbolsForFiles": {},
"tools/preprocessArgs": {
preprocessedArgs: undefined,
},
"llm/compileChat": {
compiledChatMessages: [],
didPrune: false,
@ -114,6 +104,15 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
],
};
const DEFAULT_MOCK_CORE_RESPONSE_HANDLERS: MockResponseHandlers = {
"tools/evaluatePolicy": async (data) => {
return {
policy: data.basePolicy,
displayValue: undefined,
};
},
};
const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
{
role: "assistant",
@ -165,7 +164,9 @@ export class MockIdeMessenger implements IIdeMessenger {
}
responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
responseHandlers: MockResponseHandlers = {};
responseHandlers: MockResponseHandlers = {
...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS,
};
chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
chatStreamDelay: number = 0;
setChatResponseText(text: string): void {
@ -253,7 +254,7 @@ export class MockIdeMessenger implements IIdeMessenger {
resetMocks(): void {
this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
this.responseHandlers = {};
this.responseHandlers = { ...DEFAULT_MOCK_CORE_RESPONSE_HANDLERS };
this.chatResponse = DEFAULT_CHAT_RESPONSE;
this.chatStreamDelay = 0;
}

View file

@ -10,6 +10,7 @@ import { Provider } from "react-redux";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AuthProvider } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { MockIdeMessenger } from "../../../../context/MockIdeMessenger";
import { createMockStore } from "../../../../util/test/mockStore";
import DocsIndexingStatus from "./DocsIndexingStatus";
@ -27,19 +28,12 @@ describe("DocsIndexingStatus", () => {
const renderComponent = async (
props: any = {},
storeState = {},
mockIdeMessengerSetup?: (mock: any) => void,
mockMessenger?: MockIdeMessenger,
) => {
const { mockIdeMessenger, ...store } = createMockStore(storeState);
// Configure the mockIdeMessenger for this test
if (mockIdeMessengerSetup) {
mockIdeMessengerSetup(mockIdeMessenger);
} else {
mockIdeMessenger.request.mockResolvedValue({
status: "success",
content: ["page1.html", "page2.html"],
});
}
const { mockIdeMessenger, ...store } = createMockStore(
storeState,
mockMessenger,
);
const result = await act(async () =>
render(
@ -127,11 +121,16 @@ describe("DocsIndexingStatus", () => {
},
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const { mockIdeMessenger } = await renderComponent(
{},
storeState,
new MockIdeMessenger(),
);
const postSpy = vi.spyOn(mockIdeMessenger, "post");
const stopButton = screen.getByTestId("stop-indexing");
fireEvent.click(stopButton);
expect(mockIdeMessenger.post).toHaveBeenCalledWith("indexing/abort", {
expect(postSpy).toHaveBeenCalledWith("indexing/abort", {
type: "docs",
id: "https://example.com",
});
@ -171,10 +170,11 @@ describe("DocsIndexingStatus", () => {
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const postSpy = vi.spyOn(mockIdeMessenger, "post");
const reindexButton = screen.getByTestId("reindex-docs");
fireEvent.click(reindexButton);
expect(mockIdeMessenger.post).toHaveBeenCalledWith("indexing/reindex", {
expect(postSpy).toHaveBeenCalledWith("indexing/reindex", {
type: "docs",
id: "https://example.com",
});
@ -195,13 +195,11 @@ describe("DocsIndexingStatus", () => {
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const postSpy = vi.spyOn(mockIdeMessenger, "post");
const titleElement = screen.getByText("Example Docs");
fireEvent.click(titleElement);
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
"openUrl",
"https://example.com/docs",
);
expect(postSpy).toHaveBeenCalledWith("openUrl", "https://example.com/docs");
});
it("fetches indexed pages when status becomes complete", async () => {
@ -218,15 +216,13 @@ describe("DocsIndexingStatus", () => {
},
};
const { mockIdeMessenger } = await renderComponent({}, storeState);
const mockMessenger = new MockIdeMessenger();
const spy = vi.spyOn(mockMessenger, "request");
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(mockIdeMessenger.request).toHaveBeenCalledWith(
"docs/getIndexedPages",
{
startUrl: "https://example.com",
},
);
expect(spy).toHaveBeenCalledWith("docs/getIndexedPages", {
startUrl: "https://example.com",
});
});
});
@ -244,12 +240,13 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
mockIdeMessenger.request.mockResolvedValue({
status: "success",
content: ["page1.html", "page2.html", "page3.html"],
});
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responses["docs/getIndexedPages"] = [
"page1.html",
"page2.html",
"page3.html",
];
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(screen.getByText("3 pages indexed")).toBeInTheDocument();
@ -270,12 +267,9 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
mockIdeMessenger.request.mockResolvedValue({
status: "success",
content: ["page1.html"],
});
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responses["docs/getIndexedPages"] = ["page1.html"];
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(screen.getByText("1 page indexed")).toBeInTheDocument();
@ -317,12 +311,11 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
mockIdeMessenger.request.mockResolvedValue({
status: "error",
error: "Failed to fetch pages",
});
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responseHandlers["docs/getIndexedPages"] = async (data) => {
throw new Error("Failed to fetch pages");
};
await renderComponent({}, storeState, mockMessenger);
await waitFor(() => {
expect(consoleSpy).toHaveBeenCalledWith(
@ -357,10 +350,12 @@ describe("DocsIndexingStatus", () => {
},
};
await renderComponent({}, storeState, (mockIdeMessenger) => {
// Mock a delayed response to keep in loading state
mockIdeMessenger.request.mockImplementation(() => new Promise(() => {}));
});
const mockMessenger = new MockIdeMessenger();
mockMessenger.responseHandlers["docs/getIndexedPages"] = async (data) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return [];
};
await renderComponent({}, storeState, mockMessenger);
expect(screen.getByText("Loading site info...")).toBeInTheDocument();
});

View file

@ -84,28 +84,23 @@ describe("IndexedPagesTooltip", () => {
it("opens URL when page is clicked", () => {
const { mockIdeMessenger } = renderComponent();
const spy = vi.spyOn(mockIdeMessenger, "post");
const pageLink = screen.getByText("/page1");
fireEvent.click(pageLink);
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
"openUrl",
"https://example.com/page1",
);
expect(spy).toHaveBeenCalledWith("openUrl", "https://example.com/page1");
});
it("opens each page URL correctly when clicked", () => {
const { mockIdeMessenger } = renderComponent();
const spy = vi.spyOn(mockIdeMessenger, "post");
// Click on different pages
fireEvent.click(screen.getByText("/page2"));
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
"openUrl",
"https://example.com/page2",
);
expect(spy).toHaveBeenCalledWith("openUrl", "https://example.com/page2");
fireEvent.click(screen.getByText("/sub/page3"));
expect(mockIdeMessenger.post).toHaveBeenCalledWith(
expect(spy).toHaveBeenCalledWith(
"openUrl",
"https://example.com/sub/page3",
);

View file

@ -19,8 +19,9 @@ import { cn } from "../../../util/cn";
import { getStatusIcon } from "./utils";
interface FindAndReplaceDisplayProps {
fileUri?: string;
editingFileContents?: string;
fileUri?: string; // Added during args preprocessing
newFileContents?: string; // Added during args preprocessing
editingFileContents?: string; // Added args preprocessing
relativeFilePath?: string;
edits: EditOperation[];
toolCallId: string;
@ -84,6 +85,7 @@ function DiffStats({ added, removed }: { added: number; removed: number }) {
export function FindAndReplaceDisplay({
fileUri,
newFileContents,
relativeFilePath,
editingFileContents,
edits,
@ -124,39 +126,37 @@ export function FindAndReplaceDisplay({
}, [editingFileContents, edits]);
const diffResult = useMemo(() => {
if (!currentFileContent) {
return null;
}
try {
// Apply all edits sequentially
let newContent = currentFileContent;
for (let i = 0; i < edits.length; i++) {
const {
old_string: oldString,
new_string: newString,
replace_all: replaceAll,
} = edits[i];
newContent = executeFindAndReplace(
newContent,
oldString,
newString,
!!replaceAll,
i,
);
let contentsAfterReplace = newFileContents;
if (typeof contentsAfterReplace === "undefined") {
// Apply all edits sequentially
contentsAfterReplace = currentFileContent;
for (let i = 0; i < edits.length; i++) {
const {
old_string: oldString,
new_string: newString,
replace_all: replaceAll,
} = edits[i];
contentsAfterReplace = executeFindAndReplace(
contentsAfterReplace,
oldString,
newString,
!!replaceAll,
i,
);
}
}
// Generate diff between original and final content
const diff = diffLines(currentFileContent, newContent);
return { diff, newContent, error: null };
const diff = diffLines(currentFileContent, contentsAfterReplace);
return { diff, error: null };
} catch (error) {
return {
diff: null,
newContent: null,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}, [currentFileContent, edits]);
}, [currentFileContent, newFileContents, edits]);
const diffStats = useMemo(() => {
if (!diffResult?.diff) {

View file

@ -45,7 +45,8 @@ function FunctionSpecificToolCallDiv({
return (
<FindAndReplaceDisplay
editingFileContents={args?.editingFileContents}
fileUri={args?.fileUri}
fileUri={args?.fileUri ?? ""}
newFileContents={args?.newFileContents}
relativeFilePath={args?.filepath ?? ""}
edits={edits}
toolCallId={toolCall.id}
@ -57,7 +58,8 @@ function FunctionSpecificToolCallDiv({
<FindAndReplaceDisplay
editingFileContents={args?.editingFileContents}
relativeFilePath={args?.filepath ?? ""}
fileUri={args?.fileUri}
fileUri={args?.fileUri ?? ""}
newFileContents={args?.newFileContents}
edits={args?.edits ?? []}
toolCallId={toolCall.id}
historyIndex={historyIndex}

View file

@ -1,15 +1,37 @@
import { screen } from "@testing-library/dom";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
import { renderWithProviders } from "../../util/test/render";
import HistoryPage from "./index";
const mockIdeMessenger = new MockIdeMessenger();
mockIdeMessenger.responses["history/list"] = [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
{
title: "Remote Agent",
sessionId: "remote-agent-123",
dateCreated: new Date().toString(),
workspaceDirectory: "",
isRemote: true,
remoteId: "agent-123",
},
];
describe("history Page test", () => {
it("History text is existed after render", async () => {
await renderWithProviders(<HistoryPage />);
await renderWithProviders(<HistoryPage />, {
mockIdeMessenger,
});
expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument();
});
it("History shows the first item in the list", async () => {
await renderWithProviders(<HistoryPage />);
await renderWithProviders(<HistoryPage />, {
mockIdeMessenger,
});
const sessionElement = await screen.findByText(
"Session 1",
{},

View file

@ -36,7 +36,7 @@ export const EMPTY_CONFIG: BrowserSerializedContinueConfig = {
rules: [],
};
const initialState: ConfigState = {
export const INITIAL_CONFIG_SLICE: ConfigState = {
configError: undefined,
config: EMPTY_CONFIG,
loading: false,
@ -44,7 +44,7 @@ const initialState: ConfigState = {
export const configSlice = createSlice({
name: "config",
initialState,
initialState: INITIAL_CONFIG_SLICE,
reducers: {
setConfigResult: (
state,

View file

@ -18,7 +18,7 @@ export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
status: "not-started",
};
const initialState: EditState = {
export const INITIAL_EDIT_STATE: EditState = {
applyState: INITIAL_EDIT_APPLY_STATE,
codeToEdit: [],
returnToMode: "chat",
@ -28,7 +28,7 @@ const initialState: EditState = {
export const editStateSlice = createSlice({
name: "editState",
initialState,
initialState: INITIAL_EDIT_STATE,
reducers: {
setReturnToModeAfterEdit: (
state,

View file

@ -8,7 +8,7 @@ export type IndexingState = {
};
};
const initialState: IndexingState = {
export const INITIAL_INDEXING_STATE: IndexingState = {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
@ -19,7 +19,7 @@ const initialState: IndexingState = {
export const indexingSlice = createSlice({
name: "indexing",
initialState,
initialState: INITIAL_INDEXING_STATE,
reducers: {
updateIndexingStatus: (
state,

View file

@ -19,7 +19,7 @@ export interface ProfilesState {
preferencesByProfileId: Record<string, PreferencesState>;
}
const initialState: ProfilesState = {
export const INITIAL_PROFILES_STATE: ProfilesState = {
preferencesByProfileId: {},
selectedProfileId: null,
selectedOrganizationId: null,
@ -51,7 +51,7 @@ const initialState: ProfilesState = {
export const profilesSlice = createSlice({
name: "profiles",
initialState,
initialState: INITIAL_PROFILES_STATE,
reducers: {
setSelectedProfile: (state, { payload }: PayloadAction<string | null>) => {
state.selectedProfileId = payload;

View file

@ -9,6 +9,7 @@ import { JSONContent } from "@tiptap/react";
import {
ApplyState,
AssistantChatMessage,
BaseSessionMetadata,
ChatHistoryItem,
ChatMessage,
ContextItem,
@ -18,7 +19,6 @@ import {
PromptLog,
RuleWithSource,
Session,
BaseSessionMetadata,
ThinkingChatMessage,
Tool,
ToolCallDelta,
@ -51,7 +51,11 @@ import { findChatHistoryItemByToolCallId, findToolCallById } from "../util";
function filterMultipleEditToolCalls(
toolCalls: ToolCallDelta[],
): ToolCallDelta[] {
const editToolNames = [BuiltInToolNames.EditExistingFile];
const editToolNames = [
BuiltInToolNames.EditExistingFile,
BuiltInToolNames.SingleFindAndReplace,
BuiltInToolNames.MultiEdit,
];
let hasSeenEditTool = false;
return toolCalls.filter((toolCall) => {
@ -228,7 +232,7 @@ type SessionState = {
compactionLoading: Record<number, boolean>; // Track compaction loading by message index
};
const initialState: SessionState = {
export const INITIAL_SESSION_STATE: SessionState = {
isSessionMetadataLoading: false,
allSessionMetadata: [],
history: [],
@ -250,7 +254,7 @@ const initialState: SessionState = {
export const sessionSlice = createSlice({
name: "session",
initialState,
initialState: INITIAL_SESSION_STATE,
reducers: {
addPromptCompletionPair: (
state,
@ -306,7 +310,10 @@ export const sessionSlice = createSlice({
// Cancel any tool calls that are dangling and generated
if (message.toolCallStates) {
message.toolCallStates.forEach((toolCallState) => {
if (toolCallState.status === "generated") {
if (
toolCallState.status === "generated" ||
toolCallState.status === "generating"
) {
toolCallState.status = "canceled";
}
});

View file

@ -11,7 +11,7 @@ interface TabsState {
tabs: Tab[];
}
const initialState: TabsState = {
export const INITIAL_TABS_STATE: TabsState = {
tabs: [
{
id: Date.now().toString(36) + Math.random().toString(36).substring(2),
@ -23,7 +23,7 @@ const initialState: TabsState = {
export const tabsSlice = createSlice({
name: "tabs",
initialState,
initialState: INITIAL_TABS_STATE,
reducers: {
setTabs: (state, action: PayloadAction<Tab[]>) => {
state.tabs = action.payload;

View file

@ -1,7 +1,7 @@
import { ToolPolicy } from "@continuedev/terminal-security";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RuleWithSource, Tool } from "core";
import { ToolPolicy } from "@continuedev/terminal-security";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn";
import { BUILT_IN_GROUP_NAME } from "core/tools/builtIn";
import {
defaultOnboardingCardState,
OnboardingCardState,
@ -18,7 +18,7 @@ export type ToolGroupPolicies = { [toolGroupName: string]: ToolGroupPolicy };
type UIState = {
showDialog: boolean;
dialogMessage: string | JSX.Element | undefined;
dialogMessage: JSX.Element | undefined;
dialogEntryOn: boolean;
onboardingCard: OnboardingCardState;
isExploreDialogOpen: boolean;
@ -32,26 +32,27 @@ type UIState = {
export const DEFAULT_TOOL_SETTING: ToolPolicy = "allowedWithPermission";
export const DEFAULT_RULE_SETTING: RulePolicy = "on";
export const DEFAULT_UI_SLICE: UIState = {
showDialog: false,
dialogMessage: undefined,
dialogEntryOn: false,
onboardingCard: defaultOnboardingCardState,
isExploreDialogOpen:
getLocalStorage(LocalStorageKey.IsExploreDialogOpen) ?? false,
hasDismissedExploreDialog:
getLocalStorage(LocalStorageKey.HasDismissedExploreDialog) ?? false,
shouldAddFileForEditing: false,
ttsActive: false,
toolSettings: {},
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",
},
ruleSettings: {},
};
export const uiSlice = createSlice({
name: "ui",
initialState: {
showDialog: false,
dialogMessage: "",
dialogEntryOn: false,
onboardingCard: defaultOnboardingCardState,
isExploreDialogOpen: getLocalStorage(LocalStorageKey.IsExploreDialogOpen),
hasDismissedExploreDialog: getLocalStorage(
LocalStorageKey.HasDismissedExploreDialog,
),
shouldAddFileForEditing: false,
ttsActive: false,
toolSettings: {},
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",
},
ruleSettings: {},
} as UIState,
initialState: DEFAULT_UI_SLICE,
reducers: {
setOnboardingCard: (
state,

View file

@ -12,16 +12,17 @@ import {
setToolCallCalling,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import { ThunkApiType } from "../store";
import { findToolCallById, logToolUsage } from "../util";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const callToolById = createAsyncThunk<
void,
{ toolCallId: string },
{ toolCallId: string; isAutoApproved?: boolean; depth?: number },
ThunkApiType
>("chat/callTool", async ({ toolCallId }, { dispatch, extra, getState }) => {
>("chat/callTool", async (inputs, { dispatch, extra, getState }) => {
const { toolCallId, isAutoApproved, depth = 0 } = inputs;
const state = getState();
const toolCallState = findToolCallById(state.session.history, toolCallId);
if (!toolCallState) {
@ -36,14 +37,6 @@ export const callToolById = createAsyncThunk<
// Track tool call acceptance and start timing
const startTime = Date.now();
// Check if this is an auto-approved tool
const toolSettings = state.ui.toolSettings;
const toolPolicy =
toolSettings[toolCallState.toolCall.function.name] ??
toolCallState.tool?.defaultToolPolicy ??
DEFAULT_TOOL_SETTING;
const isAutoApproved = toolPolicy === "allowedWithoutPermission";
const selectedChatModel = selectSelectedChatModel(state);
posthog.capture("tool_call_decision", {
@ -164,6 +157,7 @@ export const callToolById = createAsyncThunk<
const wrapped = await dispatch(
streamResponseAfterToolCall({
toolCallId,
depth: depth + 1,
}),
);
unwrapResult(wrapped);

View file

@ -0,0 +1,117 @@
import { ToolPolicy } from "@continuedev/terminal-security";
import { Tool, ToolCallState } from "core";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { errorToolCall, updateToolCallOutput } from "../slices/sessionSlice";
import { DEFAULT_TOOL_SETTING, ToolPolicies } from "../slices/uiSlice";
import { AppThunkDispatch } from "../store";
interface EvaluatedPolicy {
policy: ToolPolicy;
displayValue?: string;
toolCallState: ToolCallState;
}
/**
* Evaluates the tool policy for a tool call, including dynamic policy evaluation
* Note that tool group policies are not considered here because activeTools already excludes disabled groups
*/
async function evaluateToolPolicy(
ideMessenger: IIdeMessenger,
activeTools: Tool[],
toolCallState: ToolCallState,
toolPolicies: ToolPolicies,
): Promise<EvaluatedPolicy> {
const basePolicy =
toolPolicies[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 || {};
const toolName = toolCallState.toolCall.function.name;
const result = await ideMessenger.request("tools/evaluatePolicy", {
toolName,
basePolicy,
args: parsedArgs,
});
// Evaluate the policy dynamically
if (result.status === "error") {
console.error(`Error evaluating tool policy for ${toolName}`, result.error);
return { policy: "disabled", toolCallState };
}
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, toolCallState }; // Cannot override disabled
}
if (
basePolicy === "allowedWithPermission" &&
dynamicPolicy === "allowedWithoutPermission"
) {
return { policy: "allowedWithPermission", displayValue, toolCallState }; // Cannot make more lenient
}
return { policy: dynamicPolicy, displayValue, toolCallState };
}
/*
1. Get arg-dependent tool policies from core
2. Mark any disabled ones as errored
3. Mark others as generated
*/
export async function evaluateToolPolicies(
dispatch: AppThunkDispatch,
ideMessenger: IIdeMessenger,
activeTools: Tool[],
generatedToolCalls: ToolCallState[],
toolPolicies: ToolPolicies,
): Promise<EvaluatedPolicy[]> {
// Check if ALL tool calls are auto-approved using dynamic evaluation
const policyResults = await Promise.all(
generatedToolCalls.map((toolCallState) =>
evaluateToolPolicy(
ideMessenger,
activeTools,
toolCallState,
toolPolicies,
),
),
);
const disabledResults = policyResults.filter(
({ policy }) => policy === "disabled",
);
for (const { displayValue, toolCallState } of disabledResults) {
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 policyResults;
}

View file

@ -0,0 +1,59 @@
import { ToolCallState } from "core";
import { IIdeMessenger } from "../../context/IdeMessenger";
import {
errorToolCall,
setToolCallArgs,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { AppThunkDispatch } from "../store";
export async function preprocessToolCalls(
dispatch: AppThunkDispatch,
ideMessenger: IIdeMessenger,
generatedToolCalls: ToolCallState[],
): Promise<void> {
// Tool call pre-processing
await Promise.all(
generatedToolCalls.map(async (tcState) => {
try {
const result = await ideMessenger.request("tools/preprocessArgs", {
toolName: tcState.toolCall.function.name,
args: tcState.parsedArgs,
});
if (result.status === "success") {
if (result.content.preprocessedArgs) {
dispatch(
setToolCallArgs({
toolCallId: tcState.toolCallId,
newArgs: result.content.preprocessedArgs,
}),
);
}
} else {
throw new Error(result.error);
}
} catch (e) {
let errorMessage = e instanceof Error ? e.message : `Unknown error`;
dispatch(
errorToolCall({
toolCallId: tcState.toolCallId,
}),
);
dispatch(
updateToolCallOutput({
toolCallId: tcState.toolCallId,
contextItems: [
{
icon: "problems",
name: "Invalid Tool Call",
description: "",
content: `${tcState.toolCall.function.name} failed because the arguments were invalid, with the following message: ${errorMessage}\n\nPlease try something else or request further instructions.`,
hidden: false,
},
],
}),
);
}
}),
);
}

View file

@ -1,5 +1,5 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage, Session, BaseSessionMetadata } from "core";
import { BaseSessionMetadata, ChatMessage, Session } from "core";
import { RemoteSessionMetadata } from "core/control-plane/client";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { renderChatMessage } from "core/util/messageContent";

View file

@ -1,20 +1,12 @@
import { ToolPolicy } from "@continuedev/terminal-security";
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import {
LLMFullCompletionOptions,
ModelDescription,
Tool,
ToolCallState,
} from "core";
import { LLMFullCompletionOptions, ModelDescription } from "core";
import { getRuleId } from "core/llm/rules/getSystemMessageWithRules";
import { ToCoreProtocol } from "core/protocol";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { selectActiveTools } from "../selectors/selectActiveTools";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
abortStream,
addPromptCompletionPair,
errorToolCall,
setActive,
setAppliedRulesAtIndex,
setContextPercentage,
@ -23,174 +15,23 @@ import {
setIsPruned,
setToolGenerated,
streamUpdate,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
import { ThunkApiType } from "../store";
import { constructMessages } from "../util/constructMessages";
import { modelSupportsNativeTools } from "core/llm/toolSupport";
import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage";
import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls";
import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks";
import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import {
selectCurrentToolCalls,
selectPendingToolCalls,
} from "../selectors/selectToolCalls";
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.
*/
async function handleToolCallExecution(
dispatch: AppThunkDispatch,
getState: () => RootState,
activeTools: Tool[],
ideMessenger: IIdeMessenger,
): Promise<boolean> {
// Return whether all tools were auto-approved
const newState = getState();
const toolSettings = newState.ui.toolSettings;
const allToolCallStates = selectCurrentToolCalls(newState);
// Only process tool calls that are in "generating" status (newly created during this streaming session)
const toolCallStates = allToolCallStates.filter(
(toolCallState) => toolCallState.status === "generating",
);
// If no generating tool calls, nothing to process
if (toolCallStates.length === 0) {
return false; // No tools to process, need to set inactive
}
// Check if ALL tool calls are auto-approved using dynamic evaluation
const policyResults = await Promise.all(
toolCallStates.map((toolCallState) =>
evaluateToolPolicy(
toolCallState,
toolSettings,
activeTools,
ideMessenger,
),
),
);
// Handle disabled tool calls and set others as generated
const autoApprovedResults = await Promise.all(
toolCallStates.map(async (toolCallState, index) => {
const { policy, displayValue } = policyResults[index];
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 nonDisabledToolCalls = toolCallStates.filter(
(_, index) => policyResults[index].policy !== "disabled",
);
const toolCallPromises = nonDisabledToolCalls.map(async (toolCallState) => {
const response = await dispatch(
callToolById({ toolCallId: toolCallState.toolCallId }),
);
unwrapResult(response);
});
await Promise.all(toolCallPromises);
}
return allAutoApproved;
}
import { evaluateToolPolicies } from "./evaluateToolPolicies";
import { preprocessToolCalls } from "./preprocessToolCallArgs";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
/**
* Builds completion options with reasoning configuration based on session state and model capabilities.
@ -228,11 +69,20 @@ export const streamNormalInput = createAsyncThunk<
void,
{
legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
depth?: number;
},
ThunkApiType
>(
"chat/streamNormalInput",
async ({ legacySlashCommandData }, { dispatch, extra, getState }) => {
async (
{ legacySlashCommandData, depth = 0 },
{ dispatch, extra, getState },
) => {
if (process.env.NODE_ENV === "test" && depth > 50) {
const message = `Max stream depth of ${50} reached in test`;
console.error(message, JSON.stringify(getState(), null, 2));
throw new Error(message);
}
const state = getState();
const selectedChatModel = selectSelectedChatModel(state);
@ -385,35 +235,78 @@ export const streamNormalInput = createAsyncThunk<
}
}
// Check if we have any tool calls that were just generated
const newState = getState();
const toolSettings = newState.ui.toolSettings;
const allToolCallStates = selectCurrentToolCalls(newState);
// Tool call sequence:
// 1. Mark generating tool calls as generated
const state1 = getState();
const originalToolCalls = selectCurrentToolCalls(state1);
await Promise.all(
allToolCallStates.map((tcState) =>
enhanceParsedArgs(
extra.ideMessenger,
dispatch,
tcState?.toolCall.function.name,
tcState.toolCallId,
tcState.parsedArgs,
),
),
const generatingCalls = originalToolCalls.filter(
(tc) => tc.status === "generating",
);
for (const { toolCallId } of generatingCalls) {
dispatch(
setToolGenerated({
toolCallId,
tools: state1.config.config.tools,
}),
);
}
// Handle tool call execution if there are any generating tool calls
const allAutoApproved = await handleToolCallExecution(
// 2. Pre-process args to catch invalid args before checking policies
const state2 = getState();
const generatedCalls2 = selectPendingToolCalls(state2);
await preprocessToolCalls(dispatch, extra.ideMessenger, generatedCalls2);
// 3. Security check: evaluate updated policies based on args
const state3 = getState();
const generatedCalls3 = selectPendingToolCalls(state3);
const toolPolicies = state3.ui.toolSettings;
const policies = await evaluateToolPolicies(
dispatch,
getState,
activeTools,
extra.ideMessenger,
activeTools,
generatedCalls3,
toolPolicies,
);
const anyRequireApproval = policies.find(
({ policy }) => policy === "allowedWithPermission",
);
// 4. Execute remaining tool calls
// Only set inactive if not all tools were auto-approved
// This prevents UI flashing for auto-approved tools
if (!allAutoApproved) {
if (originalToolCalls.length === 0 || anyRequireApproval) {
dispatch(setInactive());
} else {
// auto stream cases increase thunk depth by 1
const state4 = getState();
const generatedCalls4 = selectPendingToolCalls(state4);
if (generatedCalls4.length > 0) {
// All that didn't fail are auto approved - call them
await Promise.all(
generatedCalls4.map(async ({ toolCallId }) => {
unwrapResult(
await dispatch(
callToolById({
toolCallId,
isAutoApproved: true,
depth: depth + 1,
}),
),
);
}),
);
} else {
// All failed - stream on
for (const { toolCallId } of originalToolCalls) {
unwrapResult(
await dispatch(
streamResponseAfterToolCall({ toolCallId, depth: depth + 1 }),
),
);
}
}
}
},
);

File diff suppressed because it is too large Load diff

View file

@ -35,7 +35,6 @@ export const streamResponseThunk = createAsyncThunk<
if (!selectedChatModel) {
throw new Error("No chat model selected");
}
dispatch(
submitEditorAndInitAtIndex({ index: inputIndex, editorState }),
);
@ -45,13 +44,6 @@ export const streamResponseThunk = createAsyncThunk<
const defaultContextProviders =
state.config.config.experimental?.defaultContext ?? [];
if (!selectedChatModel) {
console.error(
"gatherContext thunk: Cannot gather context, no model selected",
);
throw new Error("No chat model selected");
}
// Resolve context providers and construct new history
const {
selectedContextItems,

View file

@ -1,13 +1,13 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage } from "core";
import { renderContextItems } from "core/util/messageContent";
import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import {
ChatHistoryItemWithMessageId,
resetNextCodeBlockToApplyIndex,
streamUpdate,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCallById } from "../util";
import { streamNormalInput } from "./streamNormalInput";
import { streamThunkWrapper } from "./streamThunkWrapper";
@ -15,11 +15,11 @@ import { streamThunkWrapper } from "./streamThunkWrapper";
* Determines if we should continue streaming based on tool call completion status.
*/
function areAllToolsDoneStreaming(
assistantMessage: ChatHistoryItemWithMessageId | undefined,
assistantMessage: ChatHistoryItemWithMessageId,
continueAfterToolRejection: boolean | undefined,
): boolean {
// This might occur because of race conditions, if so, the tools are completed
if (!assistantMessage?.toolCallStates) {
if (!assistantMessage.toolCallStates) {
return true;
}
@ -36,18 +36,17 @@ function areAllToolsDoneStreaming(
export const streamResponseAfterToolCall = createAsyncThunk<
void,
{ toolCallId: string },
{ toolCallId: string; depth?: number },
ThunkApiType
>(
"chat/streamAfterToolCall",
async ({ toolCallId }, { dispatch, getState }) => {
async ({ toolCallId, depth = 0 }, { dispatch, getState }) => {
await dispatch(
streamThunkWrapper(async () => {
const state = getState();
const toolCallState = findToolCallById(
state.session.history,
toolCallId,
const currentToolCalls = selectCurrentToolCalls(state);
const toolCallState = currentToolCalls.find(
(tc) => tc.toolCallId === toolCallId,
);
if (!toolCallState) {
@ -57,7 +56,6 @@ export const streamResponseAfterToolCall = createAsyncThunk<
const toolOutput = toolCallState.output ?? [];
dispatch(resetNextCodeBlockToApplyIndex());
// await new Promise((resolve) => setTimeout(resolve, 0));
// Create and dispatch the tool message
const newMessage: ChatMessage = {
@ -76,12 +74,13 @@ export const streamResponseAfterToolCall = createAsyncThunk<
);
if (
assistantMessage &&
areAllToolsDoneStreaming(
assistantMessage,
state.config.config.ui?.continueAfterToolRejection,
)
) {
unwrapResult(await dispatch(streamNormalInput({})));
unwrapResult(await dispatch(streamNormalInput({ depth: depth + 1 })));
}
}),
);

View file

@ -1,7 +1,7 @@
import { JSONContent } from "@tiptap/core";
import { InputModifiers } from "core";
import { describe, expect, it, vi } from "vitest";
import { createMockStore } from "../../util/test/mockStore";
import { createMockStore, getEmptyRootState } from "../../util/test/mockStore";
import { streamResponseThunk } from "./streamResponse";
// Mock external dependencies only - let selectors run naturally
@ -36,23 +36,17 @@ vi.mock(
}),
);
import { ModelDescription } from "core";
import { unwrapResult } from "@reduxjs/toolkit";
import posthog from "posthog-js";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
import { getRootStateWithClaude } from "./streamResponse.test";
const mockGetBaseSystemMessage = vi.mocked(getBaseSystemMessage);
const mockPosthog = vi.mocked(posthog);
const mockResolveEditorContent = vi.mocked(resolveEditorContent);
const mockClaudeModel: ModelDescription = {
title: "Claude 3.5 Sonnet",
model: "claude-3-5-sonnet-20241022",
provider: "anthropic",
underlyingProviderName: "anthropic",
completionOptions: { reasoningBudgetTokens: 2048 },
};
// Mock editor state (what user types in the input)
const mockEditorState: JSONContent = {
type: "doc",
@ -70,12 +64,8 @@ const mockModifiers: InputModifiers = {
noContext: false,
};
function setupTest() {
beforeEach(() => {
vi.clearAllMocks();
// Default mock implementations for external functions
// Default mock for resolveEditorContent (can be overridden in individual tests)
mockResolveEditorContent.mockResolvedValue({
selectedContextItems: [],
selectedCode: [],
@ -85,133 +75,25 @@ function setupTest() {
// Mock getBaseSystemMessage to return simple system message for readable tests
mockGetBaseSystemMessage.mockReturnValue("You are a helpful assistant.");
// Create store with realistic state that selectors can work with
const mockStore = createMockStore({
session: {
history: [
{
message: { id: "1", role: "user", content: "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: {},
ruleSettings: {},
showDialog: false,
dialogMessage: undefined,
} as any,
});
const mockIdeMessenger = mockStore.mockIdeMessenger;
return { mockStore, mockIdeMessenger };
}
});
describe("streamResponseThunk", () => {
it("should throw error when no chat model is selected", async () => {
const { mockStore, mockIdeMessenger } = setupTest();
const noModelState = getEmptyRootState();
noModelState.session.history = [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
];
// Create store with no selected chat model
const mockStoreNoModel = createMockStore({
session: {
history: [
{
message: { id: "1", role: "user", content: "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: null, // No model selected
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
} as any,
lastSelectedModelByRole: {},
} as any,
ui: {
toolSettings: {},
ruleSettings: {},
showDialog: false,
dialogMessage: undefined,
} as any,
});
const mockStoreNoModel = createMockStore(noModelState);
const requestSpy = vi.spyOn(mockStoreNoModel.mockIdeMessenger, "request");
const chatSpy = vi.spyOn(
mockStoreNoModel.mockIdeMessenger,
"llmStreamChat",
);
// Execute thunk and expect it to be rejected
const result = await mockStoreNoModel.dispatch(
@ -225,7 +107,7 @@ describe("streamResponseThunk", () => {
expect(result.type).toBe("chat/streamResponse/fulfilled");
// Verify the complete error handling flow
const dispatchedActions = (mockStoreNoModel as any).getActions();
const dispatchedActions = mockStoreNoModel.getActions();
expect(dispatchedActions).toEqual([
{
type: "chat/streamResponse/pending",
@ -316,68 +198,22 @@ describe("streamResponseThunk", () => {
]);
// Verify no IDE messenger calls were made
expect(mockStoreNoModel.mockIdeMessenger.request).not.toHaveBeenCalled();
expect(
mockStoreNoModel.mockIdeMessenger.llmStreamChat,
).not.toHaveBeenCalled();
expect(requestSpy).not.toHaveBeenCalled();
expect(chatSpy).not.toHaveBeenCalled();
// Verify final state shows error dialog and inactive streaming
const finalState = mockStoreNoModel.getState();
expect(finalState).toEqual({
...noModelState,
session: {
history: [
{
contextItems: [],
isGatheringContext: false,
message: { id: "1", role: "user", content: "Hello" },
},
],
hasReasoningEnabled: false,
isStreaming: false, // Set to inactive after error
id: "session-123",
mode: "chat",
...noModelState.session,
streamAborter: expect.any(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: null, // No model selected
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
},
lastSelectedModelByRole: {},
loading: false,
configError: undefined,
history: [
{ ...noModelState.session.history[0], isGatheringContext: false },
],
},
ui: {
toolSettings: {},
ruleSettings: {},
...noModelState.ui,
showDialog: true, // Error dialog is shown
dialogMessage: expect.objectContaining({
props: expect.objectContaining({
@ -387,37 +223,33 @@ describe("streamResponseThunk", () => {
}),
}),
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
},
tabs: {
tabsItems: [],
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
},
});
});
it("should handle compilation error - not enough context", async () => {
const { mockStore, mockIdeMessenger } = setupTest();
const initialState = getRootStateWithClaude();
initialState.session.history = [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
];
initialState.session.id = "session-123";
const mockStore = createMockStore(initialState);
const mockIdeMessenger = mockStore.mockIdeMessenger;
const requestSpy = vi.spyOn(mockIdeMessenger, "request");
const chatSpy = vi.spyOn(mockIdeMessenger, "llmStreamChat");
// Mock compilation failure with "Not enough context" error
mockIdeMessenger.request.mockResolvedValue({
status: "error",
error: "Not enough context available for this request",
requestSpy.mockImplementation(async (message, data) => {
if (message === "llm/compileChat") {
return {
done: true,
status: "error",
error: "Not enough context available for this request",
};
} else {
return await new MockIdeMessenger().request(message, data);
}
});
// Execute thunk
@ -427,12 +259,13 @@ describe("streamResponseThunk", () => {
modifiers: mockModifiers,
}) as any,
);
unwrapResult(result);
// Verify thunk completed successfully (doesn't throw, handles error gracefully)
expect(result.type).toBe("chat/streamResponse/fulfilled");
// Verify exact action sequence for this error path
const dispatchedActions = (mockStore as any).getActions();
const dispatchedActions = mockStore.getActions();
expect(dispatchedActions).toEqual([
{
type: "chat/streamResponse/pending",
@ -561,7 +394,7 @@ describe("streamResponseThunk", () => {
arg: expect.objectContaining({
history: expect.any(Array),
sessionId: "session-123",
title: "New Session",
title: "Hello",
workspaceDirectory: "",
}),
requestId: expect.any(String),
@ -573,7 +406,7 @@ describe("streamResponseThunk", () => {
type: "session/updateSessionMetadata",
payload: {
sessionId: "session-123",
title: "New Session",
title: "Hello",
},
},
{
@ -586,21 +419,21 @@ describe("streamResponseThunk", () => {
payload: undefined,
},
{
type: "session/refreshMetadata/rejected",
type: "session/setIsSessionMetadataLoading",
payload: false,
},
{
type: "session/setAllSessionMetadata",
payload: [],
},
{
type: "session/refreshMetadata/fulfilled",
meta: {
aborted: false,
arg: {},
condition: false,
rejectedWithValue: false,
arg: expect.objectContaining({}),
requestId: expect.any(String),
requestStatus: "rejected",
},
payload: undefined,
error: {
message: "Not enough context available for this request",
name: "Error",
stack: expect.any(String),
requestStatus: expect.any(String),
},
payload: [],
},
{
type: "session/update/fulfilled",
@ -608,7 +441,7 @@ describe("streamResponseThunk", () => {
arg: expect.objectContaining({
history: expect.any(Array),
sessionId: "session-123",
title: "New Session",
title: "Hello",
workspaceDirectory: "",
}),
requestId: expect.any(String),
@ -652,7 +485,7 @@ describe("streamResponseThunk", () => {
]);
// Verify IDE messenger was called for compilation but not streaming
expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", {
expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", {
messages: [
{
role: "system",
@ -677,16 +510,17 @@ describe("streamResponseThunk", () => {
],
},
],
options: {
reasoning: false,
},
options: {},
});
expect(mockIdeMessenger.llmStreamChat).not.toHaveBeenCalled();
expect(chatSpy).not.toHaveBeenCalled();
// Verify final state shows error condition
const finalState = mockStore.getState();
expect(finalState).toEqual({
...initialState,
session: {
...initialState.session,
title: "Hello",
history: [
{
contextItems: [],
@ -729,88 +563,36 @@ describe("streamResponseThunk", () => {
},
},
],
hasReasoningEnabled: false,
isStreaming: false, // Should be inactive due to error
id: "session-123",
mode: "chat",
streamAborter: expect.any(AbortController),
contextPercentage: 0, // Unchanged - no successful compilation
isPruned: false, // Unchanged - no successful compilation
isInEdit: false,
title: "New Session",
lastSessionId: undefined,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: "out-of-context", // Error message set
},
config: {
config: {
tools: [],
rules: [],
tabAutocompleteModel: undefined,
selectedModelByRole: {
chat: mockClaudeModel,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
},
lastSelectedModelByRole: {
chat: mockClaudeModel.title,
},
loading: false,
configError: undefined,
},
ui: {
toolSettings: {},
ruleSettings: {},
showDialog: false,
dialogMessage: undefined,
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
},
tabs: {
tabsItems: [],
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
},
});
});
it("should throw error for other compilation errors", async () => {
const { mockStore, mockIdeMessenger } = setupTest();
const initialState = getRootStateWithClaude();
initialState.session.history = [
{
message: { id: "1", role: "user", content: "Hello" },
contextItems: [],
},
];
const mockStore = createMockStore(initialState);
const mockIdeMessenger = mockStore.mockIdeMessenger;
const requestSpy = vi.spyOn(mockIdeMessenger, "request");
const chatSpy = vi.spyOn(mockIdeMessenger, "llmStreamChat");
// Mock compilation failure with generic error
mockIdeMessenger.request.mockResolvedValue({
status: "error",
error: "Model configuration is invalid",
requestSpy.mockImplementation(async (message, data) => {
if (message === "llm/compileChat") {
return {
done: true,
status: "error",
error: "Model configuration is invalid",
};
} else {
return await mockIdeMessenger.request(message, data);
}
});
// Execute thunk and expect it to be rejected
@ -825,7 +607,7 @@ describe("streamResponseThunk", () => {
expect(result.type).toBe("chat/streamResponse/fulfilled");
// Verify exact action sequence for compilation error with dialog
const dispatchedActions = (mockStore as any).getActions();
const dispatchedActions = mockStore.getActions();
expect(dispatchedActions).toEqual([
{
type: "chat/streamResponse/pending",
@ -1004,7 +786,7 @@ describe("streamResponseThunk", () => {
]);
// Verify IDE messenger was called for compilation but not streaming
expect(mockIdeMessenger.request).toHaveBeenCalledWith("llm/compileChat", {
expect(requestSpy).toHaveBeenCalledWith("llm/compileChat", {
messages: [
{
role: "system",
@ -1029,71 +811,21 @@ describe("streamResponseThunk", () => {
],
},
],
options: {
reasoning: false,
},
options: {},
});
expect(mockIdeMessenger.llmStreamChat).not.toHaveBeenCalled();
expect(chatSpy).not.toHaveBeenCalled();
// Verify final state shows error dialog and inactive streaming
const finalState = mockStore.getState();
expect(finalState).toEqual({
...initialState,
session: {
history: [
{
contextItems: [],
message: { id: "1", role: "user", content: "Hello" },
},
],
hasReasoningEnabled: false,
isStreaming: false, // Set to inactive after error
id: "session-123",
mode: "chat",
...initialState.session,
streamAborter: expect.any(AbortController),
contextPercentage: 0,
isPruned: false,
isInEdit: false,
title: "",
lastSessionId: undefined,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: undefined,
mainEditorContentTrigger: mockEditorState, // Editor content that triggered the request
},
config: {
config: {
tools: [],
rules: [],
tabAutocompleteModel: undefined,
selectedModelByRole: {
chat: mockClaudeModel,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
experimental: {
onlyUseSystemMessageTools: false,
},
},
lastSelectedModelByRole: {
chat: mockClaudeModel.title,
},
loading: false,
configError: undefined,
},
ui: {
toolSettings: {},
ruleSettings: {},
...initialState.ui,
showDialog: true, // Error dialog is shown
dialogMessage: expect.objectContaining({
props: expect.objectContaining({
@ -1103,27 +835,6 @@ describe("streamResponseThunk", () => {
}),
}),
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
},
tabs: {
tabsItems: [],
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
},
});
});
});

File diff suppressed because it is too large Load diff

View file

@ -13,7 +13,6 @@ export const streamThunkWrapper = createAsyncThunk<
() => Promise<void>,
ThunkApiType
>("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => {
const initialState = getState();
try {
await runStream();
const state = getState();

View file

@ -5,6 +5,7 @@ import {
ContextItemWithId,
RuleWithSource,
ThinkingChatMessage,
ToolCall,
ToolResultChatMessage,
UserChatMessage,
} from "core";
@ -435,27 +436,26 @@ describe("constructMessages", () => {
});
test("should handle multiple tool calls in a single assistant message", () => {
const toolCall1: ToolCall = {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
};
const toolCall2: ToolCall = {
id: "tool-call-2",
type: "function",
function: {
name: "weather",
arguments: '{"location": "New York"}',
},
};
const assistantWithMultipleToolCalls: AssistantChatMessage = {
role: "assistant",
content: "I will search and check the weather",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
{
id: "tool-call-2",
type: "function",
function: {
name: "weather",
arguments: '{"location": "New York"}',
},
},
],
toolCalls: [toolCall1, toolCall2],
};
// Only the first tool call has output
@ -465,21 +465,20 @@ describe("constructMessages", () => {
contextItems: [],
toolCallStates: [
{
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
toolCallId: toolCall1.id,
toolCall: toolCall1,
status: "done",
parsedArgs: { query: "test" },
output: [
createContextItem("search-result", "Search result content"),
],
},
{
toolCallId: toolCall2.id,
toolCall: toolCall2,
status: "done",
parsedArgs: { location: "New York" },
},
],
},
];
@ -957,27 +956,36 @@ describe("constructMessages", () => {
expect(toolMessage.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
});
test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState is undefined", () => {
test("should use NO_TOOL_CALL_OUTPUT_MESSAGE when toolCallState output is undefined", () => {
const toolCall: ToolCall = {
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
};
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I'll search for that",
toolCalls: [
{
id: "search-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
toolCalls: [toolCall],
};
mockHistory = [
{
message: assistantWithToolCall,
contextItems: [],
// No toolCallStates array
toolCallStates: [
{
toolCall,
parsedArgs: {
query: "test",
},
status: "generated",
toolCallId: toolCall.id,
// no output defined
},
],
},
];

View file

@ -13,6 +13,7 @@ import { RulePolicies } from "core/llm/rules/types";
import { BuiltInToolNames } from "core/tools/builtIn";
import {
CANCELLED_TOOL_CALL_MESSAGE,
ERRORED_TOOL_CALL_OUTPUT_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "core/tools/constants";
import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools";
@ -126,26 +127,25 @@ export function constructMessages(
});
// Add a tool message for each tool call
if (item.message.toolCalls?.length) {
if (item.toolCallStates?.length) {
// If the assistant message has tool calls, we need to insert tool messages
for (const toolCall of item.message.toolCalls) {
for (const toolCallState of item.toolCallStates) {
const { output, status, toolCall } = toolCallState;
let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE;
// Find the corresponding tool call state for this specific tool call
const toolCallState = item.toolCallStates?.find(
(state) => state.toolCallId === toolCall.id,
);
if (toolCallState?.status === "canceled") {
if (status === "canceled") {
content = CANCELLED_TOOL_CALL_MESSAGE;
} else if (
toolCallState?.output &&
toolCall.function?.name == BuiltInToolNames.RunTerminalCommand
) {
// Add status for tools containing detailed status outcomes per context item
content = renderContextItemsWithStatus(toolCallState.output);
} else if (toolCallState?.output) {
content = renderContextItems(toolCallState?.output);
} else if (output) {
if (
toolCall.function?.name == BuiltInToolNames.RunTerminalCommand
) {
// Add status for tools containing detailed status outcomes per context item
content = renderContextItemsWithStatus(output);
} else {
content = renderContextItems(output);
}
} else if (toolCallState.status === "errored") {
content = ERRORED_TOOL_CALL_OUTPUT_MESSAGE;
}
msgs.push({

View file

@ -30,7 +30,7 @@ function createToolCallState(
// Helper function to create a chat history item
function createChatHistoryItem(
role: "user" | "assistant" | "tool",
role: "user" | "assistant" | "tool" | "thinking",
content: string,
options?: {
toolCallStates?: ToolCallState[];
@ -187,6 +187,82 @@ describe("findCurrentToolCalls", () => {
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(toolCallStates);
});
it("should return empty array if user message interrupts assistant sequence", () => {
const toolCallStates = [createToolCallState("tool-1", "get_weather")];
const chatHistory = [
createChatHistoryItem("assistant", "I'll check the weather", {
toolCallStates,
}),
createChatHistoryItem("user", "Actually, nevermind"),
createChatHistoryItem("assistant", "Ok, no problem"),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual([]);
});
it("should handle thinking messages as part of assistant sequence", () => {
const toolCallStates = [createToolCallState("tool-1", "get_weather")];
const chatHistory = [
createChatHistoryItem("user", "What's the weather?"),
createChatHistoryItem("thinking", "I need to get weather data"),
createChatHistoryItem("assistant", "I'll check the weather", {
toolCallStates,
}),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(toolCallStates);
});
it("should find tool calls from last assistant message in sequence", () => {
const firstToolCallStates = [createToolCallState("tool-1", "get_weather")];
const secondToolCallStates = [createToolCallState("tool-2", "get_time")];
const chatHistory = [
createChatHistoryItem("user", "What's the weather?"),
createChatHistoryItem("assistant", "Let me check", {
toolCallStates: firstToolCallStates,
}),
createChatHistoryItem("thinking", "Now I should also get the time"),
createChatHistoryItem("assistant", "And the time too", {
toolCallStates: secondToolCallStates,
}),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(secondToolCallStates);
});
it("should ignore tool calls from earlier conversation turns", () => {
const oldToolCallStates = [createToolCallState("old-tool", "old_function")];
const newToolCallStates = [createToolCallState("new-tool", "new_function")];
const chatHistory = [
createChatHistoryItem("user", "First question"),
createChatHistoryItem("assistant", "First response", {
toolCallStates: oldToolCallStates,
}),
createChatHistoryItem("user", "Second question"),
createChatHistoryItem("assistant", "Second response", {
toolCallStates: newToolCallStates,
}),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual(newToolCallStates);
});
it("should handle tool message followed by assistant message", () => {
const toolCallStates = [createToolCallState("tool-1", "get_weather")];
const chatHistory = [
createChatHistoryItem("user", "What's the weather?"),
createChatHistoryItem("assistant", "I'll check the weather", {
toolCallStates,
}),
createChatHistoryItem("tool", "Weather data: sunny", {
toolCallId: "tool-1",
}),
createChatHistoryItem("assistant", "It's sunny today!"),
];
const result = findAllCurToolCalls(chatHistory);
expect(result).toEqual([]);
});
});
describe("findToolCall", () => {

View file

@ -41,17 +41,25 @@ export function findAllCurToolCalls(
chatHistory: RootState["session"]["history"],
): ToolCallState[] {
// Find the most recent assistant message that has tool call states
let seenAssistantMessage = false;
let passedAssistantMessage = false;
for (let i = chatHistory.length - 1; i >= 0; i--) {
const item = chatHistory[i];
if (
item.message.role === "assistant" &&
item.toolCallStates &&
item.toolCallStates.length > 0
) {
return item.toolCallStates;
if (item.message.role === "user") {
return [];
}
if (item.message.role === "assistant" || item.message.role === "thinking") {
seenAssistantMessage = true;
if (item.toolCallStates && item.toolCallStates.length > 0) {
return item.toolCallStates;
}
} else if (seenAssistantMessage) {
passedAssistantMessage = true;
}
if (passedAssistantMessage) {
return [];
}
}
return [];
}

View file

@ -46,7 +46,11 @@ describe("multiEditImpl GUI specific", () => {
describe("filepath validation", () => {
it("should throw if filepath is missing", async () => {
await expect(
multiEditImpl({ edits: [] }, "id", mockExtras),
multiEditImpl(
{ edits: [{ old_string: "old", new_string: "new" }] },
"id",
mockExtras,
),
).rejects.toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingFilepath,
@ -107,29 +111,6 @@ describe("multiEditImpl GUI specific", () => {
});
});
it("should use editingFileContents if provided instead of reading file", async () => {
const editingContents = "Custom content";
await multiEditImpl(
{
filepath: "file.txt",
edits: [{ old_string: "content", new_string: "text" }],
editingFileContents: editingContents,
},
"id",
mockExtras,
);
expect(mockExtras.ideMessenger.ide.readFile).not.toHaveBeenCalled();
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "Custom text",
filepath: "file:///dir/test/file.txt",
isSearchAndReplace: true,
});
});
it("should wrap IDE readFile errors", async () => {
mockExtras.ideMessenger.ide.readFile = vi
.fn()

View file

@ -1,37 +1,35 @@
import { validateMultiEdit } from "core/edit/searchAndReplace/multiEditValidation";
import { executeMultiFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "core/edit/searchAndReplace/validateArgs";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
import { validateSearchAndReplaceFilepath } from "./singleFindAndReplaceImpl";
export const multiEditImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
const { filepath, editingFileContents } = args;
const resolvedUri = await validateSearchAndReplaceFilepath(
filepath,
// Note that this is fully duplicate of what occurs in args preprocessing
// This is to handle cases where file changes while tool call is pending
const { edits } = validateMultiEdit(args);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ideMessenger.ide,
);
const { edits } = validateMultiEdit(args);
const currentContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedUri));
const fileUri = resolvedUri;
const newContent = executeMultiFindAndReplace(currentContent, edits);
const editingFileContents = await extras.ideMessenger.ide.readFile(fileUri);
const newFileContents = executeMultiFindAndReplace(
editingFileContents,
edits,
);
const streamId = uuid();
void extras.dispatch(
applyForEditTool({
streamId,
toolCallId,
text: newContent,
text: newFileContents,
filepath: fileUri,
isSearchAndReplace: true,
}),

View file

@ -1,62 +1,33 @@
import { IDE } from "core";
import { validateSingleEdit } from "core/edit/searchAndReplace/findAndReplaceUtils";
import { executeFindAndReplace } from "core/edit/searchAndReplace/performReplace";
import { ContinueError, ContinueErrorReason } from "core/util/errors";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { validateSearchAndReplaceFilepath } from "core/edit/searchAndReplace/validateArgs";
import { v4 as uuid } from "uuid";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export async function validateSearchAndReplaceFilepath(
filepath: any,
ide: IDE,
) {
if (!filepath || typeof filepath !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingFilepath,
"filepath (string) is required",
);
}
const resolvedFilepath = await resolveRelativePathInDir(filepath, ide);
if (!resolvedFilepath) {
throw new ContinueError(
ContinueErrorReason.FileNotFound,
`File ${filepath} does not exist`,
);
}
return resolvedFilepath;
}
export const singleFindAndReplaceImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
const {
filepath,
old_string,
new_string,
replace_all = false,
editingFileContents,
} = args;
const resolvedUri = await validateSearchAndReplaceFilepath(
filepath,
// Note that this is fully duplicate of what occurs in args preprocessing
// This is to handle cases where file changes while tool call is pending
const { oldString, newString, replaceAll } = validateSingleEdit(
args.old_string,
args.new_string,
args.replace_all,
);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ideMessenger.ide,
);
validateSingleEdit(old_string, new_string);
// Read the current file content
const originalContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedUri));
// Perform the find and replace operation
const newContent = executeFindAndReplace(
originalContent,
old_string,
new_string,
replace_all,
const editingFileContents = await extras.ideMessenger.ide.readFile(fileUri);
const newFileContents = executeFindAndReplace(
editingFileContents,
oldString,
newString,
replaceAll ?? false,
0,
);
@ -66,8 +37,8 @@ export const singleFindAndReplaceImpl: ClientToolImpl = async (
applyForEditTool({
streamId,
toolCallId,
text: newContent,
filepath: resolvedUri,
text: newFileContents,
filepath: fileUri,
isSearchAndReplace: true,
}),
);

View file

@ -1,23 +1,64 @@
import { configureStore } from "@reduxjs/toolkit";
import { copyOf } from "core/util";
import { vi } from "vitest";
import configReducer from "../../redux/slices/configSlice";
import editModeStateReducer from "../../redux/slices/editState";
import indexingReducer from "../../redux/slices/indexingSlice";
import { profilesReducer } from "../../redux/slices/profilesSlice";
import sessionReducer from "../../redux/slices/sessionSlice";
import tabsReducer from "../../redux/slices/tabsSlice";
import uiReducer from "../../redux/slices/uiSlice";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
import configReducer, {
INITIAL_CONFIG_SLICE,
} from "../../redux/slices/configSlice";
import editModeStateReducer, {
INITIAL_EDIT_STATE,
} from "../../redux/slices/editState";
import indexingReducer, {
INITIAL_INDEXING_STATE,
} from "../../redux/slices/indexingSlice";
import {
INITIAL_PROFILES_STATE,
profilesReducer,
} from "../../redux/slices/profilesSlice";
import sessionReducer, {
INITIAL_SESSION_STATE,
} from "../../redux/slices/sessionSlice";
import tabsReducer, { INITIAL_TABS_STATE } from "../../redux/slices/tabsSlice";
import uiReducer, { DEFAULT_UI_SLICE } from "../../redux/slices/uiSlice";
import { RootState } from "../../redux/store";
export const createMockStore = (initialState?: Partial<RootState>) => {
const mockIdeMessenger = {
request: vi.fn(),
post: vi.fn(),
respond: vi.fn(),
streamRequest: vi.fn(),
llmStreamChat: vi.fn(),
ide: {} as any,
// TODO remove non-serializable streamAborter, causes headaches
export const getEmptyRootState: () => RootState = () => {
const withoutSession: Omit<RootState, "session"> = {
config: INITIAL_CONFIG_SLICE,
ui: DEFAULT_UI_SLICE,
editModeState: INITIAL_EDIT_STATE,
indexing: INITIAL_INDEXING_STATE,
profiles: INITIAL_PROFILES_STATE,
tabs: INITIAL_TABS_STATE,
};
const { streamAborter, ...serializableSession } = INITIAL_SESSION_STATE;
const sessionCopy = copyOf(serializableSession) as Omit<
RootState["session"],
"streamAborter"
>;
const withoutSessionCopy = copyOf(withoutSession) as Omit<
RootState,
"session"
>;
return {
...withoutSessionCopy,
session: {
...sessionCopy,
streamAborter: new AbortController(),
},
};
};
export const createMockStore = (
initialState?: Partial<RootState>,
mockMessenger?: MockIdeMessenger,
): ReturnType<typeof configureStore> & {
mockIdeMessenger: MockIdeMessenger;
getActions: () => any[];
clearActions: () => void;
} => {
const mockIdeMessenger = mockMessenger ?? new MockIdeMessenger();
const store = configureStore({
reducer: {
@ -30,94 +71,14 @@ export const createMockStore = (initialState?: Partial<RootState>) => {
profiles: profilesReducer,
},
preloadedState: {
session: {
history: [],
title: "",
id: "",
lastSessionId: undefined,
mode: "chat",
isStreaming: false,
streamAborter: new AbortController(),
hasReasoningEnabled: false,
contextPercentage: 0,
isPruned: false,
isInEdit: false,
isSessionMetadataLoading: false,
allSessionMetadata: [],
symbols: {},
codeBlockApplyStates: {
states: [],
curIndex: 0,
},
newestToolbarPreviewForInput: {},
compactionLoading: {},
inlineErrorMessage: undefined,
...initialState?.session,
},
ui: {
showDialog: false,
dialogMessage: null,
toolSettings: {},
ruleSettings: {},
...initialState?.ui,
},
editModeState: {
isInEdit: false,
returnToMode: "chat",
...initialState?.editModeState,
},
config: {
config: {
models: [],
tabAutocompleteModel: undefined,
tools: [],
rules: [],
selectedModelByRole: {
chat: null,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
...initialState?.config?.config,
},
lastSelectedModelByRole: {},
loading: false,
configError: undefined,
...initialState?.config,
},
indexing: {
indexing: {
statuses: {},
hiddenChatPeekTypes: {
docs: false,
},
},
...initialState?.indexing,
},
tabs: {
tabsItems: [],
...initialState?.tabs,
},
profiles: {
organizations: [],
selectedProfileId: null,
selectedOrganizationId: null,
preferencesByProfileId: {},
...initialState?.profiles,
},
} as RootState,
...getEmptyRootState(),
...initialState,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredPaths: ["session.streamAborter"],
ignoredActions: [
"chat/streamNormalInput/pending",
"chat/streamNormalInput/fulfilled",
"chat/streamNormalInput/rejected",
],
ignoredPaths: ["session.streamAborter", "ui.dialogMessage"],
ignoredActions: ["ui/setDialogMessage"],
},
thunk: {
extraArgument: {
@ -141,11 +102,13 @@ export const createMockStore = (initialState?: Partial<RootState>) => {
}
actions.push(action);
return originalDispatch(action);
}) as any;
(store as any).getActions = () => actions;
(store as any).clearActions = () => actions.splice(0, actions.length);
});
// Expose mockIdeMessenger so tests can configure it
return { ...store, mockIdeMessenger };
return {
...store,
mockIdeMessenger,
getActions: () => actions,
clearActions: () => actions.splice(0, actions.length),
};
};

View file

@ -17,6 +17,7 @@ import { setupStore } from "../../redux/store";
type ExtendedRenderOptions = Omit<RenderOptions, "queries"> & {
store?: ReturnType<typeof setupStore>;
routerProps?: RouterProps;
mockIdeMessenger?: MockIdeMessenger;
};
function setupMocks() {
@ -32,7 +33,8 @@ export async function renderWithProviders(
extendedRenderOptions: ExtendedRenderOptions = {},
) {
setupMocks();
const ideMessenger = new MockIdeMessenger();
const ideMessenger =
extendedRenderOptions?.mockIdeMessenger ?? new MockIdeMessenger();
const {
// Automatically create a store instance if no store was passed in