Merge pull request #7367 from continuedev/dallin/diff-UI

feat: diff UI for find and replace tools
This commit is contained in:
Tomasz Stefaniak 2025-08-25 12:55:16 -07:00 • committed by GitHub
commit ff931ec433
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 762 additions and 35 deletions

20
gui/package-lock.json generated
View file

@ -27,10 +27,12 @@
"@tiptap/react": "^2.1.13",
"@tiptap/starter-kit": "^2.1.13",
"@tiptap/suggestion": "^2.1.13",
"@types/diff": "^7.0.2",
"@types/uuid": "^10.0.0",
"anser": "^2.3.2",
"clsx": "^2.1.1",
"core": "file:../core",
"diff": "^8.0.2",
"dompurify": "^3.0.6",
"downshift": "^7.6.0",
"escape-carriage": "^1.3.1",
@ -129,7 +131,6 @@
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -209,6 +210,8 @@
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"@typescript-eslint/eslint-plugin": "^8.40.0",
"@typescript-eslint/parser": "^8.40.0",
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
@ -3865,6 +3868,12 @@
"@types/ms": "*"
}
},
"node_modules/@types/diff": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/@types/diff/-/diff-7.0.2.tgz",
"integrity": "sha512-JSWRMozjFKsGlEjiiKajUjIJVKuKdE3oVy2DNtK+fUo8q82nhFZ2CPQwicAIkXrofahDXrWJ7mjelvZphMS98Q==",
"license": "MIT"
},
"node_modules/@types/dompurify": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/@types/dompurify/-/dompurify-3.2.0.tgz",
@ -6194,6 +6203,15 @@
"integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==",
"dev": true
},
"node_modules/diff": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/diff/-/diff-8.0.2.tgz",
"integrity": "sha512-sSuxWU5j5SR9QQji/o2qMvqRNYRDOcBTgsJ/DeCf4iSN4gW+gNMXM7wFIP+fdXZxoNiAnHUTGjCr+TSWXdRDKg==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.3.1"
}
},
"node_modules/direction": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/direction/-/direction-1.0.4.tgz",

View file

@ -36,10 +36,12 @@
"@tiptap/react": "^2.1.13",
"@tiptap/starter-kit": "^2.1.13",
"@tiptap/suggestion": "^2.1.13",
"@types/diff": "^7.0.2",
"@types/uuid": "^10.0.0",
"anser": "^2.3.2",
"clsx": "^2.1.1",
"core": "file:../core",
"diff": "^8.0.2",
"dompurify": "^3.0.6",
"downshift": "^7.6.0",
"escape-carriage": "^1.3.1",

View file

@ -11,7 +11,7 @@ interface ApplyActionsProps {
applyState?: ApplyState;
onClickAccept: () => void;
onClickReject: () => void;
onClickApply: () => void;
onClickApply?: () => void;
}
export function ApplyActions(props: ApplyActionsProps) {

View file

@ -1,10 +1,11 @@
import { getLastNPathParts } from "core/util/uri";
import { MouseEventHandler } from "react";
import FileIcon from "../../FileIcon";
import { ToolTip } from "../../gui/Tooltip";
export interface FileInfoProps {
filepath: string;
onClick?: () => void;
onClick?: MouseEventHandler<HTMLDivElement>;
range?: string;
}

View file

@ -96,7 +96,7 @@ export function StepContainerPreToolbar({
toolCallState?.status === "errored" ||
toolCallState?.status === "done") ? (
<div
className={`mr-1 h-4 w-4 ${toolCallState.output ? "cursor-pointer" : ""}`}
className={`mr-1 h-4 w-4 flex-shrink-0 ${toolCallState.output ? "cursor-pointer" : ""}`}
onClick={() => {
if (toolCallState.output) {
ideMessenger.post("showVirtualFile", {

View file

@ -0,0 +1,347 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { ApplyState } from "core";
import { EditOperation } from "core/tools/definitions/multiEdit";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { FindAndReplaceDisplay } from "./FindAndReplace";
// Mock the dependencies
vi.mock("../../../context/IdeMessenger", () => ({
IdeMessengerContext: {
_currentValue: { post: vi.fn() },
},
}));
vi.mock("../../../redux/hooks", () => ({
useAppSelector: vi.fn(),
}));
vi.mock("../../../components/ui", () => ({
useFontSize: () => 14,
}));
vi.mock("../../../util/clientTools/findAndReplaceUtils", () => ({
performFindAndReplace: vi.fn(),
}));
vi.mock("./utils", () => ({
getStatusIcon: vi.fn(() => <div data-testid="status-icon">✓</div>),
}));
vi.mock("react", async () => {
const actual = await vi.importActual("react");
return {
...actual,
useContext: () => ({ post: vi.fn() }),
};
});
// Import mocked modules
import { useAppSelector } from "../../../redux/hooks";
import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils";
const mockPost = vi.fn();
const mockUseAppSelector = useAppSelector as any;
const mockPerformFindAndReplace = performFindAndReplace as any;
describe("FindAndReplaceDisplay", () => {
const defaultProps = {
fileUri: "file:///test/file.ts",
relativeFilePath: "test/file.ts",
editingFileContents: "const old = 'value';\nconst other = 'test';",
edits: [
{
old_string: "const old = 'value';",
new_string: "const new = 'value';",
replace_all: false,
},
] as EditOperation[],
toolCallId: "test-tool-call-id",
historyIndex: 0,
};
const mockToolCallState = {
status: "done" as const,
output: null,
};
const mockConfig = {
ui: {
showChatScrollbar: true,
codeWrap: false,
},
};
beforeEach(() => {
vi.clearAllMocks();
mockUseAppSelector.mockImplementation((selector: any) => {
const mockState = {
config: { config: mockConfig },
session: {
history: [],
codeBlockApplyStates: { states: [] },
},
};
if (selector.toString().includes("selectApplyStateByToolCallId")) {
return undefined; // No apply state by default
}
if (selector.toString().includes("selectToolCallById")) {
return mockToolCallState;
}
return selector(mockState);
});
mockPerformFindAndReplace.mockImplementation(
(content: string, oldStr: string, newStr: string) => {
return content.replace(oldStr, newStr);
},
);
});
describe("basic rendering", () => {
it("should render with collapsed state by default", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
expect(screen.getByText("file.ts")).toBeInTheDocument();
expect(
screen.getByTestId("toggle-find-and-replace-diff"),
).toBeInTheDocument();
// Should not show diff content when collapsed
const diffContent = screen.queryByText("-");
expect(diffContent).not.toBeInTheDocument();
});
it("should display file name from fileUri", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
expect(screen.getByText("file.ts")).toBeInTheDocument();
});
it("should display file name from relativeFilePath when no fileUri", () => {
render(
<FindAndReplaceDisplay
{...defaultProps}
fileUri={undefined}
relativeFilePath="src/components/test.tsx"
/>,
);
expect(screen.getByText("test.tsx")).toBeInTheDocument();
});
it("should handle missing file paths gracefully", () => {
render(
<FindAndReplaceDisplay
{...defaultProps}
fileUri={undefined}
relativeFilePath={undefined}
/>,
);
// Should still render the component structure
expect(
screen.getByTestId("toggle-find-and-replace-diff"),
).toBeInTheDocument();
});
});
describe("expand/collapse functionality", () => {
it("should expand when clicked", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
// Should show diff content when expanded
expect(screen.getByText("-")).toBeInTheDocument();
expect(screen.getByText("+")).toBeInTheDocument();
});
it("should show content when tool call status is 'generated'", () => {
mockUseAppSelector.mockImplementation((selector: any) => {
const mockState = {
config: { config: mockConfig },
session: {
history: [],
codeBlockApplyStates: { states: [] },
},
};
if (selector.toString().includes("selectToolCallById")) {
return { ...mockToolCallState, status: "generated" };
}
if (selector.toString().includes("selectApplyStateByToolCallId")) {
return undefined;
}
return selector(mockState);
});
render(<FindAndReplaceDisplay {...defaultProps} />);
// Should show diff content without expanding
expect(screen.getByText("-")).toBeInTheDocument();
expect(screen.getByText("+")).toBeInTheDocument();
});
});
describe("diff generation", () => {
it("should generate and display diff correctly", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
// Should show removed line
expect(screen.getByText("const old = 'value';")).toBeInTheDocument();
// Should show added line
expect(screen.getByText("const new = 'value';")).toBeInTheDocument();
// Should show unchanged line
expect(screen.getByText("const other = 'test';")).toBeInTheDocument();
});
it("should handle multiple edits", () => {
const multipleEdits = [
{
old_string: "const old = 'value';",
new_string: "const new = 'value';",
replace_all: false,
},
{
old_string: "const other = 'test';",
new_string: "const other = 'updated';",
replace_all: false,
},
] as EditOperation[];
mockPerformFindAndReplace
.mockReturnValueOnce("const new = 'value';\nconst other = 'test';")
.mockReturnValueOnce("const new = 'value';\nconst other = 'updated';");
render(<FindAndReplaceDisplay {...defaultProps} edits={multipleEdits} />);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(mockPerformFindAndReplace).toHaveBeenCalledTimes(2);
});
it("should handle diff generation errors", () => {
mockPerformFindAndReplace.mockImplementation(() => {
throw new Error("Test error");
});
render(<FindAndReplaceDisplay {...defaultProps} />);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(screen.getByText("Error generating diff")).toBeInTheDocument();
expect(screen.getByText("Test error")).toBeInTheDocument();
});
it("should show 'No changes to display' when diff is empty", () => {
// Mock the function to return the exact same content (no changes)
mockPerformFindAndReplace.mockReturnValue(
defaultProps.editingFileContents,
);
render(<FindAndReplaceDisplay {...defaultProps} />);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(screen.getByText("No changes to display")).toBeInTheDocument();
});
});
describe("apply actions", () => {
const mockApplyState: ApplyState = {
streamId: "test-stream-id",
status: "streaming",
numDiffs: 1,
fileContent: "test content",
};
beforeEach(() => {
mockUseAppSelector.mockImplementation((selector: any) => {
const mockState = {
config: { config: mockConfig },
session: {
history: [],
codeBlockApplyStates: { states: [mockApplyState] },
},
};
if (selector.toString().includes("selectApplyStateByToolCallId")) {
return mockApplyState;
}
if (selector.toString().includes("selectToolCallById")) {
return mockToolCallState;
}
return selector(mockState);
});
});
it("should show apply actions when applyState exists", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
// ApplyActions component should be rendered (we can test by looking for its structure)
// Since we don't have the exact structure, we test that the container is there
expect(
screen.getByTestId("toggle-find-and-replace-diff"),
).toBeInTheDocument();
});
it("should handle accept action", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
// This would need more detailed testing if ApplyActions was properly mocked
// For now, we verify the component renders without errors
expect(
screen.getByTestId("toggle-find-and-replace-diff"),
).toBeInTheDocument();
});
});
describe("content handling", () => {
it("should use editingFileContents when provided", () => {
render(<FindAndReplaceDisplay {...defaultProps} />);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(mockPerformFindAndReplace).toHaveBeenCalledWith(
"const old = 'value';\nconst other = 'test';",
"const old = 'value';",
"const new = 'value';",
false,
0,
);
});
it("should fallback to edit old_strings when no editingFileContents", () => {
render(
<FindAndReplaceDisplay
{...defaultProps}
editingFileContents={undefined}
/>,
);
const toggleButton = screen.getByTestId("toggle-find-and-replace-diff");
fireEvent.click(toggleButton);
expect(mockPerformFindAndReplace).toHaveBeenCalledWith(
"const old = 'value';",
"const old = 'value';",
"const new = 'value';",
false,
0,
);
});
});
});

View file

@ -0,0 +1,274 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { EditOperation } from "core/tools/definitions/multiEdit";
import { renderContextItems } from "core/util/messageContent";
import { getLastNPathParts, getUriPathBasename } from "core/util/uri";
import { diffLines } from "diff";
import { useContext, useMemo, useState } from "react";
import { ApplyActions } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions";
import { FileInfo } from "../../../components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo";
import { useFontSize } from "../../../components/ui";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppSelector } from "../../../redux/hooks";
import {
selectApplyStateByToolCallId,
selectToolCallById,
} from "../../../redux/selectors/selectToolCalls";
import { performFindAndReplace } from "../../../util/clientTools/findAndReplaceUtils";
import { getStatusIcon } from "./utils";
interface FindAndReplaceDisplayProps {
fileUri?: string;
editingFileContents?: string;
relativeFilePath?: string;
edits: EditOperation[];
toolCallId: string;
historyIndex: number;
}
export function FindAndReplaceDisplay({
fileUri,
relativeFilePath,
editingFileContents,
edits,
toolCallId,
historyIndex,
}: FindAndReplaceDisplayProps) {
const [isExpanded, setIsExpanded] = useState(false);
const ideMessenger = useContext(IdeMessengerContext);
const applyState: ApplyState | undefined = useAppSelector((state) =>
selectApplyStateByToolCallId(state, toolCallId),
);
const fontSize = useFontSize();
const toolCallState = useAppSelector((state) =>
selectToolCallById(state, toolCallId),
);
const config = useAppSelector((state) => state.config.config);
const displayName = useMemo(() => {
if (fileUri) {
return getUriPathBasename(fileUri);
}
if (relativeFilePath) {
return getLastNPathParts(relativeFilePath, 1);
}
return "";
}, [fileUri, relativeFilePath]);
// Get file content from tool call state instead of reading file
const currentFileContent = useMemo(() => {
if (editingFileContents) {
return editingFileContents;
}
return edits?.map((edit) => edit.old_string ?? "").join("\n");
}, [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 = performFindAndReplace(
newContent,
oldString,
newString,
replaceAll,
i,
);
}
// Generate diff between original and final content
const diff = diffLines(currentFileContent, newContent);
return { diff, newContent, error: null };
} catch (error) {
return {
diff: null,
newContent: null,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}, [currentFileContent, edits]);
const statusIcon = useMemo(() => {
const status = toolCallState?.status;
if (status) {
if (status === "canceled" || status === "errored" || status === "done") {
return (
<div
className={`mr-1 h-4 w-4 flex-shrink-0 ${toolCallState.output ? "cursor-pointer" : ""}`}
onClick={(e) => {
if (toolCallState.output) {
e.stopPropagation();
ideMessenger.post("showVirtualFile", {
name: "Edit output",
content: renderContextItems(toolCallState.output),
});
}
}}
>
{getStatusIcon(toolCallState.status)}
</div>
);
}
}
}, [toolCallState?.status, toolCallState?.output]);
// Unified container component that always renders the same structure
const renderContainer = (content: React.ReactNode) => (
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor mx-2 my-1 flex min-w-0 flex-col outline outline-1">
<div
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex cursor-pointer items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
onClick={() => {
setIsExpanded((prev) => !prev);
}}
>
<div className="flex max-w-[50%] flex-row items-center text-xs">
{statusIcon}
<ChevronDownIcon
data-testid="toggle-find-and-replace-diff"
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer transition-all hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
<FileInfo
filepath={displayName}
onClick={(e) => {
if (!fileUri) {
return;
}
e.stopPropagation();
ideMessenger.post("openFile", { path: fileUri });
}}
/>
</div>
{applyState && (
<ApplyActions
onClickAccept={() => {
ideMessenger.post(`acceptDiff`, {
filepath: fileUri,
streamId: applyState.streamId,
});
}}
onClickReject={() => {
ideMessenger.post(`rejectDiff`, {
filepath: fileUri,
streamId: applyState.streamId,
});
}}
disableManualApply={true}
applyState={applyState}
/>
)}
</div>
{toolCallState?.status === "generated" || isExpanded ? content : null}
</div>
);
if (diffResult?.error) {
return renderContainer(
<div className="text-error p-3 text-sm">
<strong>Error generating diff</strong> {diffResult.error}
</div>,
);
}
if (
!diffResult?.diff ||
(diffResult.diff.length === 1 &&
!diffResult.diff[0].added &&
!diffResult.diff[0].removed)
) {
return renderContainer(
<div className="text-description-muted p-3">No changes to display</div>,
);
}
return renderContainer(
<div
className={`${config?.ui?.showChatScrollbar ? "thin-scrollbar" : "no-scrollbar"} max-h-72 overflow-auto`}
>
<pre
className={`m-0 text-xs leading-tight ${config?.ui?.codeWrap ? "w-full whitespace-pre-wrap" : "w-min whitespace-pre"}`}
>
{diffResult.diff.map((part, index) => {
if (part.removed) {
return (
<div
key={index}
className="text-foreground border-l-4 border-red-900 bg-red-900/30"
>
{part.value.split("\n").map((line, lineIndex) => {
if (
line === "" &&
lineIndex === part.value.split("\n").length - 1
)
return null;
return (
<div key={lineIndex} className="px-3 py-px font-mono">
<span className="mr-2 select-none text-red-600">-</span>
{line}
</div>
);
})}
</div>
);
} else if (part.added) {
return (
<div
key={index}
className="text-foreground border-l-4 border-green-600 bg-green-600/20"
>
{part.value.split("\n").map((line, lineIndex) => {
if (
line === "" &&
lineIndex === part.value.split("\n").length - 1
)
return null;
return (
<div key={lineIndex} className="px-3 py-px font-mono">
<span className="mr-2 select-none text-green-600">+</span>
{line}
</div>
);
})}
</div>
);
} else {
return (
<div key={index} className="bg-background">
{part.value.split("\n").map((line, lineIndex) => {
if (
line === "" &&
lineIndex === part.value.split("\n").length - 1
)
return null;
return (
<div
key={lineIndex}
className="text-foreground px-3 py-px font-mono"
>
<span className="text-description-muted mr-2 select-none">
{" "}
</span>
{line}
</div>
);
})}
</div>
);
}
})}
</pre>
</div>,
);
}

View file

@ -1,7 +1,9 @@
import { ToolCallState } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { EditOperation } from "core/tools/definitions/multiEdit";
import { CreateFile } from "./CreateFile";
import { EditFile } from "./EditFile";
import { FindAndReplaceDisplay } from "./FindAndReplace";
import { RunTerminalCommand } from "./RunTerminalCommand";
function FunctionSpecificToolCallDiv({
@ -50,40 +52,30 @@ function FunctionSpecificToolCallDiv({
/>
);
case BuiltInToolNames.SingleFindAndReplace:
const fakeSearchReplaceBlock = `===== SEARCH
${args?.old_string ?? ""}
=====
${args?.new_string ?? ""}
===== REPLACE`;
const edits: EditOperation[] = [
{
old_string: args?.old_string ?? "",
new_string: args?.new_string ?? "",
replace_all: args?.replace_all,
},
];
return (
<EditFile
showToolCallStatusIcon={true}
status={toolCallState.status}
<FindAndReplaceDisplay
editingFileContents={args?.editingFileContents}
fileUri={args?.fileUri}
relativeFilePath={args?.filepath ?? ""}
changes={fakeSearchReplaceBlock}
edits={edits}
toolCallId={toolCall.id}
historyIndex={historyIndex}
/>
);
case BuiltInToolNames.MultiEdit:
const fakeSearchReplaceBlocks =
(args?.edits as { old_string: string; new_string: string }[])
?.map(
(edit) => `===== SEARCH
${edit?.old_string ?? ""}
=====
${edit?.new_string ?? ""}
===== REPLACE`,
)
?.join("\n\n---\n\n") ?? "";
return (
<EditFile
showToolCallStatusIcon={true}
status={toolCallState.status}
<FindAndReplaceDisplay
editingFileContents={args?.editingFileContents}
relativeFilePath={args?.filepath ?? ""}
changes={fakeSearchReplaceBlocks}
fileUri={args?.fileUri}
edits={args?.edits ?? []}
toolCallId={toolCall.id}
historyIndex={historyIndex}
/>

View file

@ -849,6 +849,21 @@ export const sessionSlice = createSlice({
);
}
},
setToolCallArgs: (
state,
action: PayloadAction<{
toolCallId: string;
newArgs: Record<string, any>;
}>,
) => {
const toolCallState = findToolCallById(
state.history,
action.payload.toolCallId,
);
if (toolCallState) {
toolCallState.parsedArgs = action.payload.newArgs;
}
},
cancelToolCall: (
state,
action: PayloadAction<{
@ -1024,6 +1039,7 @@ export const {
acceptToolCall,
setToolGenerated,
updateToolCallOutput,
setToolCallArgs,
setMode,
setIsSessionMetadataLoading,
setAllSessionMetadata,

View file

@ -0,0 +1,53 @@
import { BuiltInToolNames } from "core/tools/builtIn";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { getUriPathBasename } from "core/util/uri";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { setToolCallArgs } from "../slices/sessionSlice";
import { AppThunkDispatch } from "../store";
export async function enhanceParsedArgs(
ideMessenger: IIdeMessenger,
dispatch: AppThunkDispatch,
toolName: string | undefined,
toolCallId: string,
currentArgs: undefined | Record<string, any>,
) {
// Add file content to parsedArgs for find/replace tools
let enhancedArgs = { ...currentArgs };
if (
(toolName === BuiltInToolNames.SingleFindAndReplace ||
toolName === BuiltInToolNames.MultiEdit ||
toolName === BuiltInToolNames.SearchAndReplaceInFile) &&
currentArgs?.filepath &&
!currentArgs?.editingFileContents
) {
try {
const fileUri = await resolveRelativePathInDir(
currentArgs.filepath,
ideMessenger.ide,
);
if (!fileUri) {
throw new Error(`File ${currentArgs.filepath} not found`);
}
const baseName = getUriPathBasename(fileUri);
const fileContent = await ideMessenger.ide.readFile(fileUri);
enhancedArgs = {
...currentArgs,
fileUri,
baseName,
editingFileContents: fileContent,
};
dispatch(
setToolCallArgs({
toolCallId,
newArgs: enhancedArgs,
}),
);
} catch (error) {
// If we can't read the file, let the tool handle the error
console.warn(
`Failed to enhance args: failed to read file ${currentArgs?.filepath}`,
);
}
}
}

View file

@ -28,6 +28,7 @@ import { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice";
import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
import { callToolById } from "./callToolById";
import { enhanceParsedArgs } from "./enhanceParsedArgs";
/**
* Handles the execution of tool calls that may be automatically accepted.
* Sets all tools as generated first, then executes auto-approved tool calls.
@ -253,6 +254,19 @@ export const streamNormalInput = createAsyncThunk<
const newState = getState();
const toolSettings = newState.ui.toolSettings;
const allToolCallStates = selectCurrentToolCalls(newState);
await Promise.all(
allToolCallStates.map((tcState) =>
enhanceParsedArgs(
extra.ideMessenger,
dispatch,
tcState?.toolCall.function.name,
tcState.toolCallId,
tcState.parsedArgs,
),
),
);
const generatingToolCalls = allToolCallStates.filter(
(toolCallState) => toolCallState.status === "generating",
);

View file

@ -16,7 +16,7 @@ export const multiEditImpl: ClientToolImpl = async (
toolCallId,
extras,
) => {
const { filepath, edits } = args;
const { filepath, edits, editingFileContents } = args;
const streamId = uuid();
@ -64,7 +64,9 @@ export const multiEditImpl: ClientToolImpl = async (
`file ${filepath} does not exist. If you are trying to edit it, correct the filepath. If you are trying to create it, you must pass old_string=""`,
);
}
newContent = await extras.ideMessenger.ide.readFile(resolvedUri);
newContent =
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedUri));
fileUri = resolvedUri;
for (let i = 0; i < edits.length; i++) {
const { old_string, new_string, replace_all } = edits[i];

View file

@ -11,7 +11,7 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
toolCallId,
extras,
) => {
const { filepath, diffs } = args;
const { filepath, diffs, editingFileContents } = args;
const state = extras.getState();
const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry;
@ -46,7 +46,8 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
try {
// Read the current file content
const originalContent =
await extras.ideMessenger.ide.readFile(resolvedFilepath);
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedFilepath));
let currentContent = originalContent;
// Apply all replacements sequentially to build the final content

View file

@ -12,7 +12,13 @@ export const singleFindAndReplaceImpl: ClientToolImpl = async (
toolCallId,
extras,
) => {
const { filepath, old_string, new_string, replace_all = false } = args;
const {
filepath,
old_string,
new_string,
replace_all = false,
editingFileContents,
} = args;
const streamId = uuid();
@ -33,7 +39,8 @@ export const singleFindAndReplaceImpl: ClientToolImpl = async (
// Read the current file content
const originalContent =
await extras.ideMessenger.ide.readFile(resolvedFilepath);
editingFileContents ??
(await extras.ideMessenger.ide.readFile(resolvedFilepath));
// Perform the find and replace operation
const newContent = performFindAndReplace(