diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index 1ca79a25f..c880fbf3f 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -50,45 +50,36 @@ export class ApplyManager { toolCallId, }); - try { - const hasExistingDocument = !!activeTextEditor.document.getText().trim(); + const hasExistingDocument = !!activeTextEditor.document.getText().trim(); + if (hasExistingDocument) { + // Currently `isSearchAndReplace` will always provide a full file rewrite + // as the contents of `text`, so we can just instantly apply + if (isSearchAndReplace) { + const diffLinesGenerator = generateLines( + myersDiff(activeTextEditor.document.getText(), text), + ); - if (hasExistingDocument) { - // Currently `isSearchAndReplace` will always provide a full file rewrite - // as the contents of `text`, so we can just instantly apply - if (isSearchAndReplace) { - const diffLinesGenerator = generateLines( - myersDiff(activeTextEditor.document.getText(), text), - ); - - await this.verticalDiffManager.streamDiffLines( - diffLinesGenerator, - true, - streamId, - toolCallId, - ); - } else { - await this.handleExistingDocument( - activeTextEditor, - text, - streamId, - toolCallId, - ); - } + await this.verticalDiffManager.streamDiffLines( + diffLinesGenerator, + true, + streamId, + toolCallId, + ); } else { - await this.handleEmptyDocument( + await this.handleExistingDocument( activeTextEditor, text, streamId, toolCallId, ); } - } finally { - await this.webviewProtocol.request("updateApplyState", { + } else { + await this.handleEmptyDocument( + activeTextEditor, + text, streamId, - status: "done", toolCallId, - }); + ); } } diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 1c90477f4..9f5875202 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -1,14 +1,10 @@ import { useCallback, useContext, useEffect, useRef } from "react"; import { IdeMessengerContext } from "../context/IdeMessenger"; -import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; import { FromCoreProtocol } from "core/protocol"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setConfigLoading, setConfigResult } from "../redux/slices/configSlice"; -import { - setLastNonEditSessionEmpty, - updateEditStateApplyState, -} from "../redux/slices/editState"; +import { setLastNonEditSessionEmpty } from "../redux/slices/editState"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { initializeProfilePreferences, @@ -17,27 +13,21 @@ import { setSelectedProfile, } from "../redux/slices/profilesSlice"; import { - acceptToolCall, addContextItemsAtIndex, setHasReasoningEnabled, setIsSessionMetadataLoading, - updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; -import { exitEdit } from "../redux/thunks/edit"; -import { streamResponseAfterToolCall } from "../redux/thunks/streamResponseAfterToolCall"; -import { store } from "../redux/store"; import { cancelStream } from "../redux/thunks/cancelStream"; +import { handleApplyStateUpdate } from "../redux/thunks/handleApplyStateUpdate"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; -import { findToolCallById, logToolUsage } from "../redux/util"; import { setDocumentStylesFromLocalStorage, setDocumentStylesFromTheme, } from "../styles/theme"; import { isJetBrains } from "../util"; -import { logAgentModeEditOutcome } from "../util/editOutcomeLogger"; import { setLocalStorage } from "../util/localStorage"; import { migrateLocalStorage } from "../util/migrateLocalStorage"; import { useWebviewListener } from "./useWebviewListener"; @@ -51,9 +41,7 @@ function ParallelListeners() { (store) => store.profiles.selectedProfileId, ); const hasDoneInitialConfigLoad = useRef(false); - const autoAcceptEditToolDiffs = useAppSelector( - (store) => store.config.config.ui?.autoAcceptEditToolDiffs, - ); + // Load symbols for chat on any session change const sessionId = useAppSelector((state) => state.session.id); @@ -235,83 +223,9 @@ function ParallelListeners() { useWebviewListener( "updateApplyState", async (state) => { - if (state.streamId === EDIT_MODE_STREAM_ID) { - dispatch(updateEditStateApplyState(state)); - - if (state.status === "closed") { - const toolCallState = findToolCallById( - store.getState().session.history, - state.toolCallId!, - ); - if (toolCallState) { - logToolUsage(toolCallState, true, true, ideMessenger); - } - void dispatch(exitEdit({})); - } - } else { - // chat or agent - dispatch(updateApplyState(state)); - - // Handle apply status updates - use toolCallId from event payload - if (state.toolCallId) { - if (state.status === "done" && autoAcceptEditToolDiffs) { - ideMessenger.post("acceptDiff", { - streamId: state.streamId, - filepath: state.filepath, - }); - } - if (state.status === "closed") { - // Find the tool call to check if it was canceled - const toolCallState = findToolCallById( - store.getState().session.history, - state.toolCallId, - ); - - if (toolCallState) { - const accepted = toolCallState.status !== "canceled"; - - logToolUsage(toolCallState, accepted, true, ideMessenger); - - // Log edit outcome for Agent Mode - const applyState = store - .getState() - .session.codeBlockApplyStates.states.find( - (s) => s.streamId === state.streamId, - ); - - if (applyState) { - void logAgentModeEditOutcome( - toolCallState, - applyState, - accepted, - ideMessenger, - ); - } - - if (accepted) { - dispatch( - acceptToolCall({ - toolCallId: state.toolCallId, - }), - ); - void dispatch( - streamResponseAfterToolCall({ - toolCallId: state.toolCallId, - }), - ); - } - } - // const output: ContextItem = { - // name: "Edit tool output", - // content: "Completed edit", - // description: "", - // }; - // dispatch(setToolCallOutput([])); - } - } - } + void dispatch(handleApplyStateUpdate(state)); }, - [autoAcceptEditToolDiffs, ideMessenger], + [], ); useEffect(() => { diff --git a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx index 7e346a678..b99d580b8 100644 --- a/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx +++ b/gui/src/pages/gui/chat-tests/EditToolScenarios.test.tsx @@ -1,19 +1,16 @@ import { BuiltInToolNames } from "core/tools/builtIn"; +import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; import { addAndSelectMockLlm, triggerConfigUpdate, } from "../../../util/test/config"; import { renderWithProviders } from "../../../util/test/render"; import { Chat } from "../Chat"; -import { generateToolCallButtonTestId } from "../../../components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar"; import { waitFor } from "@testing-library/dom"; import { act } from "@testing-library/react"; import { ChatMessage } from "core"; -import { - setToolPolicy, - toggleToolSetting, -} from "../../../redux/slices/uiSlice"; +import { setToolPolicy } from "../../../redux/slices/uiSlice"; import { getElementByTestId, getElementByText, @@ -63,6 +60,7 @@ test( ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; const messengerPostSpy = vi.spyOn(ideMessenger, "post"); + const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); addAndSelectMockLlm(store, ideMessenger); @@ -92,7 +90,7 @@ test( // Tool call, check that applyToFile was called for edit await waitFor(() => { - expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", { + expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { streamId: expect.any(String), filepath: EDIT_FILE_URI, text: EDIT_CHANGES, @@ -101,7 +99,7 @@ test( }); // Extract stream ID and initiate mock streaming - const streamId = messengerPostSpy.mock.calls.find( + const streamId = messengerRequestSpy.mock.calls.find( (call) => call[0] === "applyToFile", )?.[1]?.streamId; expect(streamId).toBeDefined(); @@ -172,6 +170,7 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => { ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR]; const messengerPostSpy = vi.spyOn(ideMessenger, "post"); + const messengerRequestSpy = vi.spyOn(ideMessenger, "request"); addAndSelectMockLlm(store, ideMessenger); @@ -219,7 +218,7 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => { ); // Tool call, check that applyToFile was called for edit await waitFor(() => { - expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", { + expect(messengerRequestSpy).toHaveBeenCalledWith("applyToFile", { streamId: expect.any(String), filepath: EDIT_FILE_URI, text: EDIT_CHANGES, @@ -228,7 +227,7 @@ test("Edit run with no policy and yolo mode", { timeout: 15000 }, async () => { }); // Extract stream ID and initiate mock streaming - const streamId = messengerPostSpy.mock.calls.find( + const streamId = messengerRequestSpy.mock.calls.find( (call) => call[0] === "applyToFile", )?.[1]?.streamId; expect(streamId).toBeDefined(); diff --git a/gui/src/redux/thunks/handleApplyStateUpdate.ts b/gui/src/redux/thunks/handleApplyStateUpdate.ts new file mode 100644 index 000000000..1a56fe04b --- /dev/null +++ b/gui/src/redux/thunks/handleApplyStateUpdate.ts @@ -0,0 +1,153 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { ApplyState } from "core"; +import { EDIT_MODE_STREAM_ID } from "core/edit/constants"; +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 { ThunkApiType } from "../store"; +import { findToolCallById, logToolUsage } from "../util"; +import { exitEdit } from "./edit"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +export const handleApplyStateUpdate = createAsyncThunk< + void, + ApplyState, + ThunkApiType +>( + "apply/handleStateUpdate", + async (applyState, { dispatch, getState, extra }) => { + if (applyState.streamId === EDIT_MODE_STREAM_ID) { + dispatch(updateEditStateApplyState(applyState)); + + if (applyState.status === "closed") { + const toolCallState = findToolCallById( + getState().session.history, + applyState.toolCallId!, + ); + if (toolCallState) { + logToolUsage(toolCallState, true, true, extra.ideMessenger); + } + void dispatch(exitEdit({})); + } + } else { + // chat or agent + dispatch(updateApplyState(applyState)); + + // Handle apply status updates - use toolCallId from event payload + if (applyState.toolCallId) { + if ( + applyState.status === "done" && + getState().config.config?.ui?.autoAcceptEditToolDiffs + ) { + extra.ideMessenger.post("acceptDiff", { + streamId: applyState.streamId, + filepath: applyState.filepath, + }); + } + if (applyState.status === "closed") { + // Find the tool call to check if it was canceled + const toolCallState = findToolCallById( + getState().session.history, + applyState.toolCallId, + ); + + if (toolCallState) { + const accepted = toolCallState.status !== "canceled"; + + logToolUsage(toolCallState, accepted, true, extra.ideMessenger); + + // Log edit outcome for Agent Mode + const newApplyState = + getState().session.codeBlockApplyStates.states.find( + (s) => s.streamId === applyState.streamId, + ); + const newState = getState(); + if (newApplyState) { + void logAgentModeEditOutcome( + newState.session.history, + newState.config.config, + toolCallState, + newApplyState, + accepted, + extra.ideMessenger, + ); + } + + if (accepted) { + if (toolCallState.status !== "errored") { + dispatch( + acceptToolCall({ + toolCallId: applyState.toolCallId, + }), + ); + } + + void dispatch( + streamResponseAfterToolCall({ + toolCallId: applyState.toolCallId, + }), + ); + } + } + // TODO return output from edit tools so the model knows the result + } + } + } + }, +); + +export const handleEditToolApplyError = createAsyncThunk< + void, + { toolCallId: string }, + ThunkApiType +>( + "apply/handleEditError", + async ({ toolCallId }, { dispatch, getState, extra }) => { + const state = getState(); + + const toolCallState = selectToolCallById(state, toolCallId); + const applyState = selectApplyStateByToolCallId(state, toolCallId); + if ( + toolCallState && + applyState && + applyState.status !== "closed" && + toolCallState.status === "calling" + ) { + dispatch( + errorToolCall({ + toolCallId, + }), + ); + dispatch( + updateToolCallOutput({ + toolCallId, + 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, + }, + ], + }), + ); + void dispatch( + handleApplyStateUpdate({ + status: "closed", + streamId: applyState.streamId, + toolCallId, + }), + ); + } + }, +); diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts index a6f56e7c9..edd49dd06 100644 --- a/gui/src/util/clientTools/editImpl.ts +++ b/gui/src/util/clientTools/editImpl.ts @@ -1,5 +1,7 @@ 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 { ClientToolImpl } from "./callClientTool"; export const editToolImpl: ClientToolImpl = async ( args, @@ -19,13 +21,29 @@ export const editToolImpl: ClientToolImpl = async ( throw new Error(`${args.filepath} does not exist`); } const streamId = uuid(); - extras.ideMessenger.post("applyToFile", { - streamId, - text: args.changes, - toolCallId, - filepath: firstUriMatch, - }); - + extras.dispatch( + updateApplyState({ + streamId, + toolCallId, + status: "not-started", + }), + ); + void extras.ideMessenger + .request("applyToFile", { + 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. diff --git a/gui/src/util/clientTools/searchReplaceImpl.test.ts b/gui/src/util/clientTools/searchReplaceImpl.test.ts index a8eb74d77..8d8e2ed07 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.test.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.test.ts @@ -581,32 +581,6 @@ keep this too`; ), ).rejects.toThrow("Failed to apply search and replace: File read error"); }); - - it("should handle applyToFile errors", async () => { - mockResolveRelativePathInDir.mockResolvedValue("/resolved/path/test.txt"); - mockParseAllSearchReplaceBlocks.mockReturnValue([ - { - isComplete: true, - searchContent: "content", - replaceContent: "replacement", - }, - ]); - mockIdeMessenger.ide.readFile.mockResolvedValue("content"); - mockFindSearchMatch.mockReturnValue({ - startIndex: 0, - endIndex: 7, - strategyName: "exactMatch", - }); - mockIdeMessenger.request.mockRejectedValue(new Error("Apply failed")); - - await expect( - searchReplaceToolImpl( - { filepath: "test.txt", diffs: ["mock diff content"] }, - "tool-call-id", - mockExtras, - ), - ).rejects.toThrow("Failed to apply search and replace: Apply failed"); - }); }); describe("edge cases", () => { diff --git a/gui/src/util/clientTools/searchReplaceImpl.ts b/gui/src/util/clientTools/searchReplaceImpl.ts index 1fcf649e5..b734b61ca 100644 --- a/gui/src/util/clientTools/searchReplaceImpl.ts +++ b/gui/src/util/clientTools/searchReplaceImpl.ts @@ -3,6 +3,8 @@ 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 { ClientToolImpl } from "./callClientTool"; export const searchReplaceToolImpl: ClientToolImpl = async ( @@ -81,14 +83,31 @@ export const searchReplaceToolImpl: ClientToolImpl = async ( // Single applyToFile call with all accumulated changes // 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 just st - await extras.ideMessenger.request("applyToFile", { - streamId, - toolCallId, - text: currentContent, - filepath: resolvedFilepath, - isSearchAndReplace: true, - }); + // lines are generated with meyers diff and streamed instantaneously + extras.dispatch( + updateApplyState({ + streamId, + toolCallId, + status: "not-started", + }), + ); + void extras.ideMessenger + .request("applyToFile", { + 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 { diff --git a/gui/src/util/editOutcomeLogger.test.ts b/gui/src/util/editOutcomeLogger.test.ts index 92c2263eb..f34f6572c 100644 --- a/gui/src/util/editOutcomeLogger.test.ts +++ b/gui/src/util/editOutcomeLogger.test.ts @@ -1,5 +1,10 @@ -import { ApplyState, ToolCallState } from "core"; +import { + ApplyState, + BrowserSerializedContinueConfig, + ToolCallState, +} from "core"; import { describe, expect, it, vi } from "vitest"; +import { EMPTY_CONFIG } from "../redux/slices/configSlice"; import { assembleEditOutcomeData } from "./editOutcomeLogger"; vi.mock("../redux/store", () => ({ @@ -17,6 +22,19 @@ vi.mock("../redux/store", () => ({ }, })); +const EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED: BrowserSerializedContinueConfig = { + ...EMPTY_CONFIG, + selectedModelByRole: { + ...EMPTY_CONFIG.selectedModelByRole, + chat: { + provider: "test", + model: "test-model", + title: "Test model", + underlyingProviderName: "provider", + }, + }, +}; + describe("assembleEditOutcomeData", () => { it("should assemble complete edit outcome data correctly", () => { const toolCallState: ToolCallState = { @@ -37,7 +55,13 @@ describe("assembleEditOutcomeData", () => { fileContent: "const new = 2;\nconst another = 3;", }; - const result = assembleEditOutcomeData(toolCallState, applyState, true); + const result = assembleEditOutcomeData( + [], + EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED, + toolCallState, + applyState, + true, + ); console.log(result); expect(result).toMatchObject({ @@ -71,7 +95,13 @@ describe("assembleEditOutcomeData", () => { fileContent: "", }; - const result = assembleEditOutcomeData(toolCallState, applyState, false); + const result = assembleEditOutcomeData( + [], + EMPTY_CONFIG_WITH_TEST_MODEL_SELECTED, + toolCallState, + applyState, + false, + ); expect(result.previousCodeLines).toBe(0); expect(result.newCodeLines).toBe(0); diff --git a/gui/src/util/editOutcomeLogger.ts b/gui/src/util/editOutcomeLogger.ts index 124f11ed3..e7e51bb49 100644 --- a/gui/src/util/editOutcomeLogger.ts +++ b/gui/src/util/editOutcomeLogger.ts @@ -1,18 +1,23 @@ -import { ApplyState, ToolCallState } from "core"; +import { + ApplyState, + BrowserSerializedContinueConfig, + ToolCallState, +} from "core"; import { IIdeMessenger } from "../context/IdeMessenger"; -import { store } from "../redux/store"; +import { ChatHistoryItemWithMessageId } from "../redux/slices/sessionSlice"; /** * Extract model information from tool call state */ -function extractModelInfo(toolCallState: ToolCallState): { +function extractModelInfo( + history: ChatHistoryItemWithMessageId[], + config: BrowserSerializedContinueConfig, + toolCallState: ToolCallState, +): { modelProvider: string; modelName: string; modelTitle: string; } { - // Get the conversation history to find the model info - const history = store.getState().session.history; - // Find the assistant message that contains this tool call const assistantMessage = history.find( (item) => @@ -35,7 +40,6 @@ function extractModelInfo(toolCallState: ToolCallState): { } // Fallback to config if not found in message - const config = store.getState().config.config; const chatModel = config?.selectedModelByRole?.chat; return { @@ -48,12 +52,13 @@ function extractModelInfo(toolCallState: ToolCallState): { /** * Extract prompt and completion from tool call state */ -function extractPromptAndCompletion(toolCallState: ToolCallState): { +function extractPromptAndCompletion( + history: ChatHistoryItemWithMessageId[], + toolCallState: ToolCallState, +): { prompt: string; completion: string; } { - const history = store.getState().session.history; - // Find the assistant message with this tool call const assistantMessageIndex = history.findIndex( (item) => @@ -144,12 +149,17 @@ function extractCodeChanges(applyState: ApplyState): { * Assemble complete edit outcome data from tool call and apply state */ export function assembleEditOutcomeData( + history: ChatHistoryItemWithMessageId[], + config: BrowserSerializedContinueConfig, toolCallState: ToolCallState, applyState: ApplyState, accepted: boolean, ) { - const modelInfo = extractModelInfo(toolCallState); - const promptAndCompletion = extractPromptAndCompletion(toolCallState); + const modelInfo = extractModelInfo(history, config, toolCallState); + const promptAndCompletion = extractPromptAndCompletion( + history, + toolCallState, + ); const codeChanges = extractCodeChanges(applyState); return { @@ -174,6 +184,8 @@ export function assembleEditOutcomeData( * Log Agent Mode edit outcome to editOutcome.jsonl */ export async function logAgentModeEditOutcome( + history: ChatHistoryItemWithMessageId[], + config: BrowserSerializedContinueConfig, toolCallState: ToolCallState, applyState: ApplyState, accepted: boolean, @@ -182,6 +194,8 @@ export async function logAgentModeEditOutcome( // Use the original file content stored in applyState, captured before edits were applied const editOutcomeData = assembleEditOutcomeData( + history, + config, toolCallState, applyState, accepted,