feat: unify edit tool apply handling

This commit is contained in:
Dallin Romney 2025-08-22 14:42:25 -07:00
parent 832b2d6f46
commit 393c06f97e
9 changed files with 924 additions and 264 deletions

View file

@ -0,0 +1,762 @@
import { ApplyState, ApplyToFilePayload, ToolCallState } from "core";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { logAgentModeEditOutcome } from "../../util/editOutcomeLogger";
import {
selectApplyStateByToolCallId,
selectToolCallById,
} from "../selectors/selectToolCalls";
import { updateEditStateApplyState } from "../slices/editState";
import {
acceptToolCall,
errorToolCall,
updateApplyState,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { findToolCallById, logToolUsage } from "../util";
import { exitEdit } from "./edit";
import {
applyForEditTool,
handleApplyStateUpdate,
} from "./handleApplyStateUpdate";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
// Mock dependencies
vi.mock("../../util/editOutcomeLogger", () => ({
logAgentModeEditOutcome: vi.fn(),
}));
vi.mock("../selectors/selectToolCalls", () => ({
selectApplyStateByToolCallId: vi.fn(),
selectToolCallById: vi.fn(),
}));
vi.mock("../slices/editState", () => ({
updateEditStateApplyState: vi.fn(() => ({
type: "editState/updateApplyState",
})),
}));
vi.mock("../slices/sessionSlice", () => ({
acceptToolCall: vi.fn(() => ({ type: "session/acceptToolCall" })),
errorToolCall: vi.fn(() => ({ type: "session/errorToolCall" })),
updateApplyState: vi.fn(() => ({ type: "session/updateApplyState" })),
updateToolCallOutput: vi.fn(() => ({ type: "session/updateToolCallOutput" })),
}));
vi.mock("../util", () => ({
findToolCallById: vi.fn(),
logToolUsage: vi.fn(),
}));
vi.mock("./edit", () => ({
exitEdit: vi.fn(() => ({ type: "edit/exitEdit" })),
}));
vi.mock("./streamResponseAfterToolCall", () => ({
streamResponseAfterToolCall: vi.fn(() => ({
type: "session/streamResponseAfterToolCall",
})),
}));
const UNUSED_TOOL_CALL_PARAMS = {
toolCall: {
id: "name",
function: {
name: "unused",
arguments: "unused",
},
type: "function" as const,
},
parsedArgs: {},
};
describe("handleApplyStateUpdate", () => {
let mockDispatch: any;
let mockGetState: any;
let mockExtra: any;
beforeEach(() => {
vi.clearAllMocks();
mockDispatch = vi.fn();
mockGetState = vi.fn();
mockExtra = {
ideMessenger: {
post: vi.fn(),
request: vi.fn(),
},
};
});
describe("edit mode handling", () => {
it("should handle edit mode apply state updates", async () => {
const applyState: ApplyState = {
streamId: EDIT_MODE_STREAM_ID,
toolCallId: "test-tool-call",
status: "streaming",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(updateEditStateApplyState).toHaveBeenCalledWith(applyState);
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({ type: "editState/updateApplyState" }),
);
});
it("should exit edit mode when status is closed", async () => {
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "done",
...UNUSED_TOOL_CALL_PARAMS,
};
vi.mocked(findToolCallById).mockReturnValue(toolCallState);
mockGetState.mockReturnValue({
session: { history: [] },
});
const applyState: ApplyState = {
streamId: EDIT_MODE_STREAM_ID,
toolCallId: "test-tool-call",
status: "closed",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(logToolUsage).toHaveBeenCalledWith(
toolCallState,
true,
true,
mockExtra.ideMessenger,
);
expect(exitEdit).toHaveBeenCalledWith({});
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({ type: "edit/exitEdit" }),
);
});
});
describe("chat/agent mode handling", () => {
it("should handle non-edit mode apply state updates", async () => {
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "streaming",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(updateApplyState).toHaveBeenCalledWith(applyState);
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({ type: "session/updateApplyState" }),
);
});
it("should auto-accept diffs when configured and status is done", async () => {
mockGetState.mockReturnValue({
config: {
config: {
ui: {
autoAcceptEditToolDiffs: true,
},
},
},
session: { history: [] },
});
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "done",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(mockExtra.ideMessenger.post).toHaveBeenCalledWith("acceptDiff", {
streamId: "chat-stream",
filepath: "test.txt",
});
});
it("should not auto-accept when config is disabled", async () => {
mockGetState.mockReturnValue({
config: {
config: {
ui: {
autoAcceptEditToolDiffs: false,
},
},
},
session: { history: [] },
});
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "done",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(mockExtra.ideMessenger.post).not.toHaveBeenCalled();
});
});
describe("closed status handling", () => {
it("should handle accepted tool call closure", async () => {
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "done",
...UNUSED_TOOL_CALL_PARAMS,
};
const newApplyState = { streamId: "chat-stream" };
vi.mocked(findToolCallById).mockReturnValue(toolCallState);
mockGetState.mockReturnValue({
session: {
history: [],
codeBlockApplyStates: {
states: [newApplyState],
},
},
config: { config: {} },
});
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "closed",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(logToolUsage).toHaveBeenCalledWith(
toolCallState,
true,
true,
mockExtra.ideMessenger,
);
expect(logAgentModeEditOutcome).toHaveBeenCalledWith(
[],
{},
toolCallState,
newApplyState,
true,
mockExtra.ideMessenger,
);
expect(acceptToolCall).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
});
expect(streamResponseAfterToolCall).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
});
});
it("should handle canceled tool call closure", async () => {
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "canceled",
...UNUSED_TOOL_CALL_PARAMS,
};
const newApplyState = { streamId: "chat-stream" };
vi.mocked(findToolCallById).mockReturnValue(toolCallState);
mockGetState.mockReturnValue({
session: {
history: [],
codeBlockApplyStates: {
states: [newApplyState],
},
},
config: { config: {} },
});
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "closed",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(logToolUsage).toHaveBeenCalledWith(
toolCallState,
false,
true,
mockExtra.ideMessenger,
);
expect(logAgentModeEditOutcome).toHaveBeenCalledWith(
[],
{},
toolCallState,
newApplyState,
false,
mockExtra.ideMessenger,
);
expect(acceptToolCall).not.toHaveBeenCalled();
expect(streamResponseAfterToolCall).not.toHaveBeenCalled();
});
it("should handle errored tool call closure", async () => {
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "errored",
...UNUSED_TOOL_CALL_PARAMS,
};
const newApplyState = { streamId: "chat-stream" };
vi.mocked(findToolCallById).mockReturnValue(toolCallState);
mockGetState.mockReturnValue({
session: {
history: [],
codeBlockApplyStates: {
states: [newApplyState],
},
},
config: { config: {} },
});
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "closed",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(acceptToolCall).not.toHaveBeenCalled();
expect(streamResponseAfterToolCall).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
});
});
it("should handle closure when no tool call found", async () => {
vi.mocked(findToolCallById).mockReturnValue(undefined);
mockGetState.mockReturnValue({
session: {
history: [],
codeBlockApplyStates: {
states: [],
},
},
});
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "closed",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(logToolUsage).not.toHaveBeenCalled();
expect(acceptToolCall).not.toHaveBeenCalled();
expect(streamResponseAfterToolCall).not.toHaveBeenCalled();
});
it("should handle closure when no apply state found", async () => {
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "done",
...UNUSED_TOOL_CALL_PARAMS,
};
vi.mocked(findToolCallById).mockReturnValue(toolCallState);
mockGetState.mockReturnValue({
session: {
history: [],
codeBlockApplyStates: {
states: [],
},
},
config: { config: {} },
});
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status: "closed",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(logAgentModeEditOutcome).not.toHaveBeenCalled();
expect(acceptToolCall).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
});
});
});
describe("edge cases", () => {
it("should handle apply state without toolCallId", async () => {
const applyState: ApplyState = {
streamId: "chat-stream",
status: "streaming",
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(updateApplyState).toHaveBeenCalledWith(applyState);
expect(acceptToolCall).not.toHaveBeenCalled();
expect(streamResponseAfterToolCall).not.toHaveBeenCalled();
});
it("should handle different status values", async () => {
const statusValues: ApplyState["status"][] = [
"not-started",
"streaming",
"done",
"closed",
];
for (const status of statusValues) {
vi.clearAllMocks();
const applyState: ApplyState = {
streamId: "chat-stream",
toolCallId: "test-tool-call",
status,
filepath: "test.txt",
numDiffs: 1,
};
const thunk = handleApplyStateUpdate(applyState);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(updateApplyState).toHaveBeenCalledWith(applyState);
}
});
});
});
describe("applyForEditTool", () => {
let mockDispatch: any;
let mockGetState: any;
let mockExtra: any;
beforeEach(() => {
vi.clearAllMocks();
mockDispatch = vi.fn();
mockGetState = vi.fn();
mockExtra = {
ideMessenger: {
request: vi.fn(),
},
};
});
describe("successful application", () => {
it("should successfully apply changes to file", async () => {
const payload: ApplyToFilePayload & { toolCallId: string } = {
toolCallId: "test-tool-call",
streamId: "test-stream",
filepath: "test.txt",
text: "new content",
isSearchAndReplace: true,
};
mockExtra.ideMessenger.request.mockResolvedValue({ status: "success" });
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(updateApplyState).toHaveBeenCalledWith({
streamId: "test-stream",
toolCallId: "test-tool-call",
status: "not-started",
});
expect(mockDispatch).toHaveBeenCalledWith(
expect.objectContaining({ type: "session/updateApplyState" }),
);
expect(mockExtra.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
payload,
);
});
});
describe("error handling", () => {
it("should handle IDE messenger request failure", async () => {
const payload: ApplyToFilePayload & { toolCallId: string } = {
toolCallId: "test-tool-call",
streamId: "test-stream",
filepath: "test.txt",
text: "new content",
isSearchAndReplace: true,
};
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "calling",
...UNUSED_TOOL_CALL_PARAMS,
};
const applyState: ApplyState = {
status: "streaming",
streamId: "test-stream",
};
vi.mocked(selectToolCallById).mockReturnValue(toolCallState);
vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState);
mockGetState.mockReturnValue({});
mockExtra.ideMessenger.request.mockRejectedValue(
new Error("Request failed"),
);
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(errorToolCall).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
});
expect(updateToolCallOutput).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
contextItems: [
{
icon: "problems",
name: "Apply Error",
description: "Failed to apply changes",
content: `Error editing file: failed to apply changes to file.\n\nPlease try again with correct args or notify the user and request further instructions.`,
hidden: false,
},
],
});
});
it("should handle IDE messenger error response", async () => {
const payload: ApplyToFilePayload & { toolCallId: string } = {
toolCallId: "test-tool-call",
streamId: "test-stream",
filepath: "test.txt",
text: "new content",
isSearchAndReplace: true,
};
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "calling",
...UNUSED_TOOL_CALL_PARAMS,
};
const applyState: ApplyState = {
status: "streaming",
streamId: "test-stream",
};
vi.mocked(selectToolCallById).mockReturnValue(toolCallState);
vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState);
mockGetState.mockReturnValue({});
mockExtra.ideMessenger.request.mockResolvedValue({ status: "error" });
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(errorToolCall).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
});
expect(updateToolCallOutput).toHaveBeenCalledWith({
toolCallId: "test-tool-call",
contextItems: [
{
icon: "problems",
name: "Apply Error",
description: "Failed to apply changes",
content: `Error editing file: failed to apply changes to file.\n\nPlease try again with correct args or notify the user and request further instructions.`,
hidden: false,
},
],
});
});
it("should not error if tool call is not in calling state", async () => {
const payload: ApplyToFilePayload & { toolCallId: string } = {
toolCallId: "test-tool-call",
streamId: "test-stream",
filepath: "test.txt",
text: "new content",
isSearchAndReplace: true,
};
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "done",
...UNUSED_TOOL_CALL_PARAMS,
};
const applyState: ApplyState = {
status: "streaming",
streamId: "test-stream",
};
vi.mocked(selectToolCallById).mockReturnValue(toolCallState);
vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState);
mockGetState.mockReturnValue({});
mockExtra.ideMessenger.request.mockRejectedValue(
new Error("Request failed"),
);
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(errorToolCall).not.toHaveBeenCalled();
expect(updateToolCallOutput).not.toHaveBeenCalled();
});
it("should not error if apply state is closed", async () => {
const payload: ApplyToFilePayload & { toolCallId: string } = {
toolCallId: "test-tool-call",
streamId: "test-stream",
filepath: "test.txt",
text: "new content",
isSearchAndReplace: true,
};
const toolCallState: ToolCallState = {
toolCallId: "test-tool-call",
status: "calling",
...UNUSED_TOOL_CALL_PARAMS,
};
const applyState: ApplyState = {
status: "closed",
streamId: "test-stream",
}; // Already closed
vi.mocked(selectToolCallById).mockReturnValue(toolCallState);
vi.mocked(selectApplyStateByToolCallId).mockReturnValue(applyState);
mockGetState.mockReturnValue({});
mockExtra.ideMessenger.request.mockRejectedValue(
new Error("Request failed"),
);
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(errorToolCall).not.toHaveBeenCalled();
expect(updateToolCallOutput).not.toHaveBeenCalled();
});
it("should not error if tool call state is not found", async () => {
const payload: ApplyToFilePayload & { toolCallId: string } = {
toolCallId: "test-tool-call",
streamId: "test-stream",
filepath: "test.txt",
text: "new content",
isSearchAndReplace: true,
};
vi.mocked(selectToolCallById).mockReturnValue(undefined); // Tool call not found
vi.mocked(selectApplyStateByToolCallId).mockReturnValue({
status: "streaming",
streamId: "test-stream",
});
mockGetState.mockReturnValue({});
mockExtra.ideMessenger.request.mockRejectedValue(
new Error("Request failed"),
);
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(errorToolCall).not.toHaveBeenCalled();
expect(updateToolCallOutput).not.toHaveBeenCalled();
});
it("should not error if apply state is not found", async () => {
const payload: ApplyToFilePayload & { toolCallId: string } = {
toolCallId: "test-tool-call",
streamId: "test-stream",
filepath: "test.txt",
text: "new content",
isSearchAndReplace: true,
};
vi.mocked(selectApplyStateByToolCallId).mockReturnValue(undefined); // Apply state not found
mockGetState.mockReturnValue({});
mockExtra.ideMessenger.request.mockRejectedValue(
new Error("Request failed"),
);
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(errorToolCall).not.toHaveBeenCalled();
expect(updateToolCallOutput).not.toHaveBeenCalled();
});
});
describe("edge cases", () => {
it("should handle different payload types", async () => {
const payloads: (ApplyToFilePayload & { toolCallId: string })[] = [
{
toolCallId: "test-1",
streamId: "stream-1",
filepath: "file1.txt",
text: "content 1",
isSearchAndReplace: false,
},
{
toolCallId: "test-2",
streamId: "stream-2",
filepath: "file2.js",
text: "content 2",
isSearchAndReplace: true,
},
];
for (const payload of payloads) {
vi.clearAllMocks();
mockExtra.ideMessenger.request.mockResolvedValue({ status: "success" });
const thunk = applyForEditTool(payload);
await thunk(mockDispatch, mockGetState, mockExtra);
expect(mockExtra.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
payload,
);
expect(updateApplyState).toHaveBeenCalledWith({
streamId: payload.streamId,
toolCallId: payload.toolCallId,
status: "not-started",
});
}
});
});
});

View file

@ -1,5 +1,5 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { ApplyState } from "core";
import { ApplyState, ApplyToFilePayload } from "core";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { logAgentModeEditOutcome } from "../../util/editOutcomeLogger";
import {
@ -105,13 +105,30 @@ export const handleApplyStateUpdate = createAsyncThunk<
},
);
export const handleEditToolApplyError = createAsyncThunk<
export const applyForEditTool = createAsyncThunk<
void,
{ toolCallId: string },
ApplyToFilePayload & { toolCallId: string },
ThunkApiType
>(
"apply/handleEditError",
async ({ toolCallId }, { dispatch, getState, extra }) => {
>("apply/editTool", async (payload, { dispatch, getState, extra }) => {
const { toolCallId, streamId } = payload;
dispatch(
updateApplyState({
streamId,
toolCallId,
status: "not-started",
}),
);
let didError = false;
try {
const response = await extra.ideMessenger.request("applyToFile", payload);
if (response.status === "error") {
didError = true;
}
} catch (e) {
didError = true;
}
if (didError) {
const state = getState();
const toolCallState = selectToolCallById(state, toolCallId);
@ -149,5 +166,5 @@ export const handleEditToolApplyError = createAsyncThunk<
}),
);
}
},
);
}
});

View file

@ -1,7 +1,6 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { updateApplyState } from "../../redux/slices/sessionSlice";
import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export const editToolImpl: ClientToolImpl = async (
args,
@ -21,29 +20,15 @@ export const editToolImpl: ClientToolImpl = async (
throw new Error(`${args.filepath} does not exist`);
}
const streamId = uuid();
extras.dispatch(
updateApplyState({
streamId,
toolCallId,
status: "not-started",
}),
);
void extras.ideMessenger
.request("applyToFile", {
void extras.dispatch(
applyForEditTool({
streamId,
text: args.changes,
toolCallId,
filepath: firstUriMatch,
})
.then((res) => {
if (res.status === "error") {
void extras.dispatch(
handleEditToolApplyError({
toolCallId,
}),
);
}
});
}),
);
return {
respondImmediately: false,
output: undefined, // No immediate output.

View file

@ -1,5 +1,6 @@
import * as ideUtils from "core/util/ideUtils";
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolExtras } from "./callClientTool";
import { multiEditImpl } from "./multiEditImpl";
@ -11,14 +12,20 @@ vi.mock("core/util/ideUtils", () => ({
resolveRelativePathInDir: vi.fn(),
}));
vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({
applyForEditTool: vi.fn(),
}));
describe("multiEditImpl", () => {
let mockExtras: ClientToolExtras;
let mockResolveRelativePathInDir: Mock;
let mockApplyForEditTool: Mock;
beforeEach(() => {
vi.clearAllMocks();
mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir);
mockApplyForEditTool = vi.mocked(applyForEditTool);
mockExtras = {
getState: vi.fn(() => ({
@ -106,16 +113,13 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "id",
text: "Hi world",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "Hi world",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should apply multiple edits sequentially", async () => {
@ -135,16 +139,13 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "id",
text: "Hi universe\nGoodbye universe",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "Hi universe\nGoodbye universe",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should handle edits that depend on previous edits", async () => {
@ -164,16 +165,13 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "id",
text: "let x = 2;",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "let x = 2;",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should throw if string not found in edit sequence", async () => {
@ -227,16 +225,13 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "id",
text: "New content\nLine 2",
filepath: "new.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "New content\nLine 2",
filepath: "new.txt",
isSearchAndReplace: true,
});
});
it("should create and edit new file", async () => {
@ -254,16 +249,13 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "id",
text: "Hello universe",
filepath: "new.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "Hello universe",
filepath: "new.txt",
isSearchAndReplace: true,
});
});
});
@ -286,16 +278,13 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "id",
text: "qux bar qux baz qux",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "qux bar qux baz qux",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should handle mixed replace_all settings", async () => {
@ -315,16 +304,13 @@ describe("multiEditImpl", () => {
mockExtras,
);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "id",
text: "a b a z a",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "id",
text: "a b a z a",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
});
@ -346,25 +332,6 @@ describe("multiEditImpl", () => {
),
).rejects.toThrow("Failed to apply multi edit: Read failed");
});
it("should wrap applyToFile errors", async () => {
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
mockExtras.ideMessenger.ide.readFile = vi.fn().mockResolvedValue("test");
mockExtras.ideMessenger.request = vi
.fn()
.mockRejectedValue(new Error("Write failed"));
await expect(
multiEditImpl(
{
filepath: "file.txt",
edits: [{ old_string: "test", new_string: "new" }],
},
"id",
mockExtras,
),
).rejects.toThrow("Failed to apply multi edit: Write failed");
});
});
describe("return value", () => {

View file

@ -1,6 +1,6 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
interface EditOperation {
@ -118,23 +118,15 @@ export const multiEditImpl: ClientToolImpl = async (
}
// Apply the changes to the file
void extras.ideMessenger
.request("applyToFile", {
void extras.dispatch(
applyForEditTool({
streamId,
toolCallId,
text: newContent,
filepath: targetFilepath,
isSearchAndReplace: true,
})
.then((res) => {
if (res.status === "error") {
void extras.dispatch(
handleEditToolApplyError({
toolCallId,
}),
);
}
});
}),
);
// Return success - applyToFile will handle the completion state
return {

View file

@ -2,6 +2,7 @@ import { findSearchMatch } from "core/edit/searchAndReplace/findSearchMatch";
import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSearchReplaceBlock";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolExtras } from "./callClientTool";
import { searchReplaceToolImpl } from "./searchReplaceImpl";
@ -12,10 +13,14 @@ vi.mock("core/util/ideUtils");
vi.mock("uuid", () => ({
v4: vi.fn(() => "test-stream-id"),
}));
vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({
applyForEditTool: vi.fn(),
}));
const mockFindSearchMatch = vi.mocked(findSearchMatch);
const mockParseAllSearchReplaceBlocks = vi.mocked(parseAllSearchReplaceBlocks);
const mockResolveRelativePathInDir = vi.mocked(resolveRelativePathInDir);
const mockApplyForEditTool = vi.mocked(applyForEditTool);
describe("searchReplaceToolImpl", () => {
let mockExtras: ClientToolExtras;
@ -144,8 +149,6 @@ describe("searchReplaceToolImpl", () => {
endIndex,
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
const result = await searchReplaceToolImpl(
{ filepath: "test.js", diffs: ["mock diff content"] },
"tool-call-id",
@ -159,7 +162,7 @@ describe("searchReplaceToolImpl", () => {
});
// Verify applyToFile was called with correct parameters
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.js",
@ -202,8 +205,6 @@ describe("searchReplaceToolImpl", () => {
endIndex,
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
const result = await searchReplaceToolImpl(
{ filepath: "test.js", diffs: ["mock diff content"] },
"tool-call-id",
@ -217,7 +218,7 @@ describe("searchReplaceToolImpl", () => {
});
// Verify applyToFile was called with correct parameters
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.js",
@ -283,8 +284,6 @@ const c = 3;`;
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
const result = await searchReplaceToolImpl(
{ filepath: "test.js", diffs: ["mock diff content"] },
"tool-call-id",
@ -310,7 +309,7 @@ const c = 3;`;
"const b = 2;",
);
// Verify final applyToFile call
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.js",
@ -379,8 +378,6 @@ const c = 3;`;
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
const result = await searchReplaceToolImpl(
{ filepath: "test.js", diffs: ["first diff", "second diff"] },
"tool-call-id",
@ -405,7 +402,7 @@ const c = 3;`;
);
// Verify final applyToFile call
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.js",
@ -440,7 +437,6 @@ keep this too`;
endIndex: 26, // End of "remove this line"
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
const result = await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
@ -453,7 +449,7 @@ keep this too`;
output: undefined,
});
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
@ -480,15 +476,13 @@ keep this too`;
endIndex: 11,
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
@ -602,15 +596,13 @@ keep this too`;
endIndex: 0,
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
"tool-call-id",
mockExtras,
);
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
@ -637,7 +629,6 @@ keep this too`;
endIndex: originalContent.length,
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
await searchReplaceToolImpl(
{ filepath: "test.txt", diffs: ["mock diff content"] },
@ -645,7 +636,7 @@ keep this too`;
mockExtras,
);
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: expectedFinalContent,
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",
@ -673,7 +664,6 @@ keep this too`;
endIndex: 4,
strategyName: "exactMatch",
});
mockIdeMessenger.request.mockResolvedValue({ status: "success" });
await searchReplaceToolImpl(
{ filepath: "relative/test.txt", diffs: ["mock diff content"] },
@ -693,7 +683,7 @@ keep this too`;
"/resolved/path/test.txt",
);
expect(mockFindSearchMatch).toHaveBeenCalledWith(originalContent, "test");
expect(mockIdeMessenger.request).toHaveBeenCalledWith("applyToFile", {
expect(mockApplyForEditTool).toHaveBeenCalledWith({
text: "updated content",
streamId: "test-stream-id",
filepath: "/resolved/path/test.txt",

View file

@ -3,8 +3,7 @@ import { parseAllSearchReplaceBlocks } from "core/edit/searchAndReplace/parseSea
import { resolveRelativePathInDir } from "core/util/ideUtils";
import posthog from "posthog-js";
import { v4 as uuid } from "uuid";
import { updateApplyState } from "../../redux/slices/sessionSlice";
import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export const searchReplaceToolImpl: ClientToolImpl = async (
@ -84,30 +83,15 @@ export const searchReplaceToolImpl: ClientToolImpl = async (
// This works becaues of our logic in `applyCodeBlock` that determines
// that the full file rewrite here can be applied instantly, so the diff
// lines are generated with meyers diff and streamed instantaneously
extras.dispatch(
updateApplyState({
streamId,
toolCallId,
status: "not-started",
}),
);
void extras.ideMessenger
.request("applyToFile", {
void extras.dispatch(
applyForEditTool({
streamId,
toolCallId,
text: currentContent,
filepath: resolvedFilepath,
isSearchAndReplace: true,
})
.then((res) => {
if (res.status === "error") {
void extras.dispatch(
handleEditToolApplyError({
toolCallId,
}),
);
}
});
}),
);
// Return success - applyToFile will handle the completion state
return {

View file

@ -1,9 +1,8 @@
import { describe, it, expect, beforeEach, vi, Mock } from "vitest";
import { v4 as uuid } from "uuid";
import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl";
import { ClientToolExtras } from "./callClientTool";
import * as ideUtils from "core/util/ideUtils";
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolExtras } from "./callClientTool";
import { singleFindAndReplaceImpl } from "./singleFindAndReplaceImpl";
vi.mock("uuid", () => ({
v4: vi.fn(() => "test-uuid"),
}));
@ -12,14 +11,20 @@ vi.mock("core/util/ideUtils", () => ({
resolveRelativePathInDir: vi.fn(),
}));
vi.mock("../../redux/thunks/handleApplyStateUpdate", () => ({
applyForEditTool: vi.fn(),
}));
describe("singleFindAndReplaceImpl", () => {
let mockExtras: ClientToolExtras;
let mockResolveRelativePathInDir: Mock;
let mockApplyForEditTool: Mock;
beforeEach(() => {
vi.clearAllMocks();
mockResolveRelativePathInDir = vi.mocked(ideUtils.resolveRelativePathInDir);
mockApplyForEditTool = vi.mocked(applyForEditTool);
mockExtras = {
getState: vi.fn(() => ({
@ -159,16 +164,14 @@ describe("singleFindAndReplaceImpl", () => {
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "Hi there\nThis is a test file\nGoodbye world",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
// Check that the dispatch was called with the applyForEditTool thunk
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "Hi there\nThis is a test file\nGoodbye world",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should throw error if old_string appears multiple times and replace_all is false", async () => {
@ -204,16 +207,13 @@ describe("singleFindAndReplaceImpl", () => {
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "Hello universe\nThis is a test file\nGoodbye universe",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "Hello universe\nThis is a test file\nGoodbye universe",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should handle empty new_string (deletion)", async () => {
@ -229,16 +229,13 @@ describe("singleFindAndReplaceImpl", () => {
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "world\nThis is a test file",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "world\nThis is a test file",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should handle special characters in strings", async () => {
@ -256,16 +253,13 @@ describe("singleFindAndReplaceImpl", () => {
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: 'const regex = /[a-z]+/g;\nconst text = "Hi $universe"',
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: 'const regex = /[a-z]+/g;\nconst text = "Hi $universe"',
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
it("should preserve whitespace and indentation", async () => {
@ -283,16 +277,13 @@ describe("singleFindAndReplaceImpl", () => {
await singleFindAndReplaceImpl(args, "tool-call-id", mockExtras);
expect(mockExtras.ideMessenger.request).toHaveBeenCalledWith(
"applyToFile",
{
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "function test() {\n const value = 'new';\n return value;\n}",
filepath: "/test/file.txt",
isSearchAndReplace: true,
},
);
expect(mockApplyForEditTool).toHaveBeenCalledWith({
streamId: "test-uuid",
toolCallId: "tool-call-id",
text: "function test() {\n const value = 'new';\n return value;\n}",
filepath: "/test/file.txt",
isSearchAndReplace: true,
});
});
});
@ -339,25 +330,5 @@ describe("singleFindAndReplaceImpl", () => {
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow("Failed to apply find and replace: Permission denied");
});
it("should wrap and rethrow errors from applyToFile", async () => {
mockResolveRelativePathInDir.mockResolvedValue("/test/file.txt");
mockExtras.ideMessenger.ide.readFile = vi
.fn()
.mockResolvedValue("test content");
mockExtras.ideMessenger.request = vi
.fn()
.mockRejectedValue(new Error("Write failed"));
const args = {
filepath: "file.txt",
old_string: "test",
new_string: "replacement",
};
await expect(
singleFindAndReplaceImpl(args, "tool-call-id", mockExtras),
).rejects.toThrow("Failed to apply find and replace: Write failed");
});
});
});

View file

@ -1,6 +1,6 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { handleEditToolApplyError } from "../../redux/thunks/handleApplyStateUpdate";
import { applyForEditTool } from "../../redux/thunks/handleApplyStateUpdate";
import { ClientToolImpl } from "./callClientTool";
export const singleFindAndReplaceImpl: ClientToolImpl = async (
@ -62,23 +62,15 @@ export const singleFindAndReplaceImpl: ClientToolImpl = async (
}
// Apply the changes to the file
void extras.ideMessenger
.request("applyToFile", {
void extras.dispatch(
applyForEditTool({
streamId,
toolCallId,
text: newContent,
filepath: resolvedFilepath,
isSearchAndReplace: true,
})
.then((res) => {
if (res.status === "error") {
void extras.dispatch(
handleEditToolApplyError({
toolCallId,
}),
);
}
});
}),
);
// Return success - applyToFile will handle the completion state
return {