From e02741cb5e641388647bda2f486e05b360fc65a9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 19:04:28 -0700 Subject: [PATCH 01/21] edit tool first take --- core/tools/builtIn.ts | 1 + core/tools/callTool.ts | 3 ++ core/tools/definitions/editFile.ts | 28 +++++++++++++++ core/tools/implementations/editFile.ts | 22 ++++++++++++ core/tools/index.ts | 2 ++ .../StepContainerPreToolbar.tsx | 36 +++++++++++-------- .../markdown/StyledMarkdownPreview.tsx | 22 ++++++++++-- gui/src/redux/slices/uiSlice.ts | 1 + 8 files changed, 97 insertions(+), 18 deletions(-) create mode 100644 core/tools/definitions/editFile.ts create mode 100644 core/tools/implementations/editFile.ts diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index fa76358c9..4ac7ad4ae 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,5 +1,6 @@ export enum BuiltInToolNames { ReadFile = "builtin_read_file", + EditExistingFile = "builtin_edit_existing_file", ReadCurrentlyOpenFile = "builtin_read_currently_open_file", CreateNewFile = "builtin_create_new_file", RunTerminalCommand = "builtin_run_terminal_command", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 25c56507c..2866124ef 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -4,6 +4,7 @@ import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; +import { editFileImpl } from "./implementations/editFile"; import { exactSearchImpl } from "./implementations/exactSearch"; import { lsToolImpl } from "./implementations/lsTool"; import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; @@ -138,6 +139,8 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); + case BuiltInToolNames.EditExistingFile: + return await editFileImpl(args, extras); case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.ExactSearch: diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts new file mode 100644 index 000000000..1ff44f7c7 --- /dev/null +++ b/core/tools/definitions/editFile.ts @@ -0,0 +1,28 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const editFileTool: Tool = { + type: "function", + displayTitle: "Edit File", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + function: { + name: BuiltInToolNames.EditExistingFile, + description: + "To edit an existing file, call this tool and follow the returned instructions. If you don't have the contents of the file, read it first.", + parameters: { + type: "object", + required: ["filepath"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to edit, relative to the root of the workspace.", + }, + }, + }, + }, +}; diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts new file mode 100644 index 000000000..80de79923 --- /dev/null +++ b/core/tools/implementations/editFile.ts @@ -0,0 +1,22 @@ +import { ToolImpl } from "."; +import { resolveRelativePathInDir } from "../../util/ideUtils"; + +export const EDIT_TOOL_CONTEXT_ITEM_NAME = "Edit Tool Instructions"; + +export const editFileImpl: ToolImpl = async (args, extras) => { + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + extras.ide, + ); + if (!firstUriMatch) { + throw new Error(`File ${args.filepath} does not exist.`); + } + return [ + { + name: EDIT_TOOL_CONTEXT_ITEM_NAME, + description: "Instructions for editing the file", + content: + "Edit Instructions: return the full new file contents in a codeblock. The codeblock header should be of the format '```language filepath'", + }, + ]; +}; diff --git a/core/tools/index.ts b/core/tools/index.ts index eea4ee79b..407510691 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -1,4 +1,5 @@ import { createNewFileTool } from "./definitions/createNewFile"; +import { editFileTool } from "./definitions/editFile"; import { exactSearchTool } from "./definitions/exactSearch"; import { lsTool } from "./definitions/lsTool"; import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile"; @@ -9,6 +10,7 @@ import { viewDiffTool } from "./definitions/viewDiff"; export const allTools = [ readFileTool, + editFileTool, createNewFileTool, runTerminalCommandTool, diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 46fa90d68..ec0000b2c 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -3,7 +3,6 @@ import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; import { debounce } from "lodash"; import { useContext, useEffect, useRef, useState } from "react"; import styled from "styled-components"; -import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, vscCommandCenterInactiveBorder, @@ -52,17 +51,18 @@ export interface StepContainerPreToolbarProps { relativeFilepath: string; isGeneratingCodeBlock: boolean; codeBlockIndex: number; // To track which codeblock we are applying + codeBlockStreamId: string; range?: string; children: any; expanded?: boolean; hideApply?: boolean; + autoApply?: boolean; } export default function StepContainerPreToolbar( props: StepContainerPreToolbarProps, ) { const ideMessenger = useContext(IdeMessengerContext); - const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); const isInEditMode = useAppSelector(selectIsInEditMode); const [isExpanded, setIsExpanded] = useState( @@ -76,7 +76,7 @@ export default function StepContainerPreToolbar( ); const applyState = useAppSelector((state) => - selectApplyStateByStreamId(state, streamIdRef.current), + selectApplyStateByStreamId(state, props.codeBlockStreamId), ); // This handles an edge case when the last node in the markdown syntax tree is a codeblock. @@ -104,7 +104,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, filepath: fileUri, text: codeBlockContent, curSelectedModelTitle: defaultModel.title, @@ -135,19 +135,25 @@ export default function StepContainerPreToolbar( } }, [props.children, codeBlockContent]); - // Temporarily disabling auto apply for Edit mode // useEffect(() => { // const hasCompletedGenerating = // wasGeneratingRef.current && !isGeneratingCodeBlock; - - // const shouldAutoApply = hasCompletedGenerating && isInEditMode; - - // if (shouldAutoApply) { - // onClickApply(); - // } - + // console.log( + // wasGeneratingRef.current, + // isGeneratingCodeBlock, + // props.autoApply, + // ); // wasGeneratingRef.current = isGeneratingCodeBlock; - // }, [isGeneratingCodeBlock]); + // if (hasCompletedGenerating) { + // console.log("Completed generating", props.autoApply); + // if (props.autoApply) { + // onClickApply(); + // } + // // else if(isInEditMode) { + // // onClickApply(); + // // } + // } + // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( @@ -156,7 +162,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("acceptDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } @@ -167,7 +173,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("rejectDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index d968101d0..fbd6801b9 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -1,5 +1,5 @@ import { ctxItemToRifWithContents } from "core/commands/util"; -import { memo, useEffect, useMemo } from "react"; +import { memo, useEffect, useMemo, useRef } from "react"; import { useRemark } from "react-remark"; import rehypeHighlight, { Options } from "rehype-highlight"; import rehypeKatex from "rehype-katex"; @@ -196,6 +196,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }, [props.itemIndex, history, allSymbols]); const pastFileInfoRef = useUpdatingRef(pastFileInfo); + const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( + [], + ); + const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ remarkTables, @@ -282,8 +286,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const { className, range } = preChildProps; const relativeFilePath = preChildProps["data-relativefilepath"]; const codeBlockContent = preChildProps["data-codeblockcontent"]; - const isGeneratingCodeBlock = - preChildProps["data-isgeneratingcodeblock"]; if (!props.isRenderingInStepContainer) { return ; @@ -307,6 +309,18 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( ); } + const isGeneratingCodeBlock = + preChildProps["data-isgeneratingcodeblock"]; + + if (codeblockState.current[codeBlockIndex] === undefined) { + codeblockState.current[codeBlockIndex] = { + streamId: uuidv4(), + isGenerating: isGeneratingCodeBlock, + }; + } + const codeblockStreamId = + codeblockState.current[codeBlockIndex].streamId; + // We use a custom toolbar for codeblocks in the step container return ( diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 9ebf8969f..e7eccbad6 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -45,6 +45,7 @@ export const uiSlice = createSlice({ ttsActive: false, toolSettings: { [BuiltInToolNames.ReadFile]: "allowedWithoutPermission", + [BuiltInToolNames.EditExistingFile]: "allowedWithPermission", [BuiltInToolNames.CreateNewFile]: "allowedWithPermission", [BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission", [BuiltInToolNames.ViewSubdirectory]: "allowedWithoutPermission", From 9c0f43342e6ba576c5105d810eda8101ec238426 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:08:48 -0700 Subject: [PATCH 02/21] edit tool ui take zero --- core/tools/definitions/editFile.ts | 13 +++++++++++-- .../markdown/StyledMarkdownPreview.tsx | 3 ++- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 19 +++++++++++++++++++ .../FunctionSpecificToolCallDiv.tsx | 15 ++++++++++++--- 4 files changed, 44 insertions(+), 6 deletions(-) create mode 100644 gui/src/pages/gui/ToolCallDiv/EditFile.tsx diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 1ff44f7c7..6ee5cee6b 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,6 +1,11 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +export interface EditToolArgs { + filepath: string; + new_contents: string; +} + export const editFileTool: Tool = { type: "function", displayTitle: "Edit File", @@ -12,16 +17,20 @@ export const editFileTool: Tool = { function: { name: BuiltInToolNames.EditExistingFile, description: - "To edit an existing file, call this tool and follow the returned instructions. If you don't have the contents of the file, read it first.", + "Use this tool to edit an existing file. If you don't know the contents of the file, read it first.", parameters: { type: "object", - required: ["filepath"], + required: ["filepath", "new_contents"], properties: { filepath: { type: "string", description: "The path of the file to edit, relative to the root of the workspace.", }, + new_contents: { + type: "string", + description: "The new file contents", + }, }, }, }, diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index fbd6801b9..4c2635ce1 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -130,6 +130,7 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; itemIndex?: number; useParentBackgroundColor?: boolean; + autoApplyCodeblocks?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -330,7 +331,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( relativeFilepath={relativeFilePath} isGeneratingCodeBlock={isGeneratingCodeBlock} range={range} - autoApply={false} + autoApply={props.autoApplyCodeblocks} codeBlockStreamId={codeblockStreamId} > diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx new file mode 100644 index 000000000..0dee7ab2b --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -0,0 +1,19 @@ +import { getMarkdownLanguageTagForFile } from "core/util"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; + +type EditToolCallProps = { + relativeFilePath: string; + newContents: string; +}; + +export function EditFile(props: EditToolCallProps) { + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + + return props.relativeFilePath ? ( + + ) : null; +} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 52b41f505..8592960eb 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -1,5 +1,7 @@ -import { ToolCall, ToolCallDelta, ToolCallState } from "core"; +import { ToolCallDelta, ToolCallState } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { CreateFile } from "./CreateFile"; +import { EditFile } from "./EditFile"; import { RunTerminalCommand } from "./RunTerminalCommand"; function FunctionSpecificToolCallDiv({ @@ -12,14 +14,21 @@ function FunctionSpecificToolCallDiv({ const args = toolCallState.parsedArgs; switch (toolCall.function?.name) { - case "builtin_create_new_file": + case BuiltInToolNames.CreateNewFile: return ( ); - case "builtin_run_terminal_command": + case BuiltInToolNames.EditExistingFile: + return ( + + ); + case BuiltInToolNames.RunTerminalCommand: return ( Date: Thu, 3 Apr 2025 20:46:19 -0700 Subject: [PATCH 03/21] error if already exists" --- core/tools/implementations/createNewFile.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index b5d5e6c1b..cf8746328 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -1,6 +1,7 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; +import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; export const createNewFileImpl: ToolImpl = async (args, extras) => { const resolvedFileUri = await inferResolvedUriFromRelativePath( @@ -8,8 +9,26 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { extras.ide, ); if (resolvedFileUri) { + const exists = await extras.ide.fileExists(resolvedFileUri); + if (exists) { + throw new Error( + `File ${args.filepath} already exists. Use the edit too to edit this file`, + ); + } await extras.ide.writeFile(resolvedFileUri, args.contents); await extras.ide.openFile(resolvedFileUri); + return [ + { + name: getUriPathBasename(resolvedFileUri), + description: getCleanUriPath(resolvedFileUri), + content: "File created successfuly", + uri: { + type: "file", + value: resolvedFileUri, + }, + }, + ]; + } else { + throw new Error("Failed to resolve path"); } - return []; }; From e595ce871f7cf21f19d946641c7415594fac7a27 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:17:04 -0700 Subject: [PATCH 04/21] edit tool call div --- extensions/vscode/package-lock.json | 4 ++-- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 1 + gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index c01a1eb12..a26290f1a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.18", + "version": "1.1.19", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.18", + "version": "1.1.19", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 0dee7ab2b..56ee77ef3 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -14,6 +14,7 @@ export function EditFile(props: EditToolCallProps) { isRenderingInStepContainer={true} source={src} autoApplyCodeblocks={true} + hideApply={true} /> ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index 8592960eb..ee8726fae 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -25,7 +25,7 @@ function FunctionSpecificToolCallDiv({ return ( ); case BuiltInToolNames.RunTerminalCommand: From 95016e5c3c67a7f79c602d6826197eaf3c303363 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 20:57:16 -0700 Subject: [PATCH 05/21] merge create tool updates --- .../StepContainerPreToolbar.tsx | 21 +++++++++---------- .../markdown/StyledMarkdownPreview.tsx | 2 ++ gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 8 +++++-- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index ec0000b2c..1a67e2cb4 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -216,17 +216,16 @@ export default function StepContainerPreToolbar( {!isGeneratingCodeBlock && ( <> - {props.hideApply || - (isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - - ) : ( - - ))} + {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( + + ) : props.hideApply ? null : ( + + )} )} diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 4c2635ce1..4aed38536 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -131,6 +131,7 @@ interface StyledMarkdownPreviewProps { itemIndex?: number; useParentBackgroundColor?: boolean; autoApplyCodeblocks?: boolean; + hideApply?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -333,6 +334,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( range={range} autoApply={props.autoApplyCodeblocks} codeBlockStreamId={codeblockStreamId} + hideApply={props.hideApply} > diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index bca805f45..9829ef64b 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -7,9 +7,13 @@ interface CreateFileToolCallProps { } export function CreateFile(props: CreateFileToolCallProps) { - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "test.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``; + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``; return props.relativeFilepath ? ( - + ) : null; } From 2780b588f749b6743bc8514d32d854c4b6aa6653 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:19:40 -0700 Subject: [PATCH 06/21] edit tool autoapply --- .../StepContainerPreToolbar.tsx | 30 +++++++------------ 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 1a67e2cb4..26fdb6261 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -135,25 +135,17 @@ export default function StepContainerPreToolbar( } }, [props.children, codeBlockContent]); - // useEffect(() => { - // const hasCompletedGenerating = - // wasGeneratingRef.current && !isGeneratingCodeBlock; - // console.log( - // wasGeneratingRef.current, - // isGeneratingCodeBlock, - // props.autoApply, - // ); - // wasGeneratingRef.current = isGeneratingCodeBlock; - // if (hasCompletedGenerating) { - // console.log("Completed generating", props.autoApply); - // if (props.autoApply) { - // onClickApply(); - // } - // // else if(isInEditMode) { - // // onClickApply(); - // // } - // } - // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); + useEffect(() => { + const hasCompletedGenerating = + wasGeneratingRef.current && !isGeneratingCodeBlock; + + wasGeneratingRef.current = isGeneratingCodeBlock; + if (hasCompletedGenerating) { + if (props.autoApply) { + onClickApply(); + } + } + }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( From af9b80f4731275d0e5c97c8d931beafa6fd0e431 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:43:59 -0700 Subject: [PATCH 07/21] toolbar styling --- gui/src/components/FileIcon.tsx | 2 +- .../StepContainerPreToolbar/FileInfo.tsx | 25 ++++++++++--------- .../StepContainerPreToolbar.tsx | 25 ++++++++----------- 3 files changed, 25 insertions(+), 27 deletions(-) diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 6f96e498d..0f2b729cb 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -45,7 +45,7 @@ export default function FileIcon({ filename, height, width }: FileIconProps) { height: height, fill: color, flexShrink: 0, - display: "block", + display: "flex", }} /> ); diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index c2f09a24a..06defbeac 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -1,8 +1,8 @@ -import FileIcon from "../../FileIcon"; +import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; +import { getLastNPathParts } from "core/util/uri"; import { useContext } from "react"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { getLastNPathParts, getUriPathBasename } from "core/util/uri"; -import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; +import FileIcon from "../../FileIcon"; export interface FileInfoProps { relativeFilepath: string; @@ -23,17 +23,18 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => { } return ( -
-
+
+
- - {getLastNPathParts(relativeFilepath, 1)} - {range && ` ${range}`} -
+ + asdfasdfasdfasdfasdfasdfasdf + {getLastNPathParts(relativeFilepath, 1)} + {range && ` ${range}`} +
); }; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 26fdb6261..776192e45 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -25,6 +25,8 @@ import GeneratingCodeLoader from "./GeneratingCodeLoader"; import RunInTerminalButton from "./RunInTerminalButton"; const TopDiv = styled.div` + display: flex; + flex-direction: column; outline: 1px solid ${vscCommandCenterInactiveBorder}; outline-offset: -0.5px; border-radius: ${defaultBorderRadius}; @@ -37,7 +39,6 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>` display: flex; justify-content: space-between; align-items: center; - background: inherit; font-size: ${getFontSize() - 2}px; padding: 4px 6px; margin: 0; @@ -181,31 +182,27 @@ export default function StepContainerPreToolbar( return ( - -
+ +
-
- -
+
- {isGeneratingCodeBlock && ( + {isGeneratingCodeBlock ? ( - )} - - {!isGeneratingCodeBlock && ( + ) : ( <> {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( From ac27ec97d7044d2aedeeea85247c13dd0f8fd0ab Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 21:44:15 -0700 Subject: [PATCH 08/21] cleanup --- gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index 06defbeac..ee46ccee8 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx @@ -31,7 +31,6 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => {
- asdfasdfasdfasdfasdfasdfasdf {getLastNPathParts(relativeFilepath, 1)} {range && ` ${range}`} From 1a63ea756df3827c27f6d114d03044460d004baf Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 3 Apr 2025 23:41:05 -0700 Subject: [PATCH 09/21] hacky apply implementation --- core/core.ts | 18 ++- core/index.d.ts | 1 + core/protocol/core.ts | 2 +- core/protocol/ide.ts | 11 ++ core/protocol/ideWebview.ts | 12 -- core/tools/implementations/editFile.ts | 16 ++- core/util/filesystem.ts | 4 + .../continue/IntelliJIde.kt | 117 +++++++++++++++++- .../continueintellijextension/protocol/ide.kt | 1 - extensions/vscode/src/VsCodeIde.ts | 13 +- .../vscode/src/extension/VsCodeMessenger.ts | 4 +- .../StepContainerPreToolbar.tsx | 21 ++-- .../markdown/StyledMarkdownPreview.tsx | 21 +++- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 13 +- gui/src/redux/slices/sessionSlice.ts | 8 ++ gui/src/redux/thunks/callTool.ts | 6 + 16 files changed, 215 insertions(+), 53 deletions(-) diff --git a/core/core.ts b/core/core.ts index 11fecffb2..911ea0072 100644 --- a/core/core.ts +++ b/core/core.ts @@ -36,6 +36,7 @@ import { TTS } from "./util/tts"; import { DiffLine, + ToolExtras, type ContextItemId, type IDE, type IndexingProgressUpdate, @@ -871,7 +872,8 @@ export class Core { } }); - on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { + on("tools/call", async (msg) => { + const { toolCall, selectedModelTitle, applyStreamId } = msg.data; const { config } = await this.configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -887,6 +889,19 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); + let applyToFile: ToolExtras["applyToFile"] = undefined; + if (applyStreamId) { + applyToFile = async (path: string, contents: string) => { + return await this.messenger.request("applyToFile", { + filepath: path, + text: contents, + streamId: applyStreamId, + curSelectedModelTitle: + config.selectedModelByRole.apply?.title ?? selectedModelTitle, + }); + }; + } + const contextItems = await callTool( tool, JSON.parse(toolCall.function.arguments || "{}"), @@ -896,6 +911,7 @@ export class Core { fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), tool, + applyToFile, }, ); diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..5b2b482ed 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -891,6 +891,7 @@ export interface ToolExtras { llm: ILLM; fetch: FetchFunction; tool: Tool; + applyToFile?: (path: string, content: string) => Promise; } export interface Tool { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 03940c283..f92f70a50 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -193,7 +193,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ - { toolCall: ToolCall; selectedModelTitle: string }, + { toolCall: ToolCall; selectedModelTitle: string; applyStreamId?: string }, { contextItems: ContextItem[] }, ]; "clipboardCache/add": [{ content: string }, void]; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 5b2a7ab1f..9b3d030f6 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -23,6 +23,17 @@ export interface GetGhTokenArgs { export type ToIdeFromWebviewOrCoreProtocol = { // Methods from IDE type + // We pass the `curSelectedModel` because we currently cannot access the + // default model title in the GUI from JB + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath?: string; + }, + void, + ]; getIdeInfo: [undefined, IdeInfo]; getWorkspaceDirs: [undefined, string[]]; writeFile: [{ path: string; contents: string }, void]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index a7cd16e5b..03074b95f 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, - ContextSubmenuItem, EditStatus, MessageContent, RangeInFileWithContents, @@ -12,17 +11,6 @@ import type { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; - // We pass the `curSelectedModel` because we currently cannot access the - // default model title in the GUI from JB - applyToFile: [ - { - text: string; - streamId: string; - curSelectedModelTitle: string; - filepath?: string; - }, - void, - ]; overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index 80de79923..deac3cc54 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -1,8 +1,6 @@ import { ToolImpl } from "."; import { resolveRelativePathInDir } from "../../util/ideUtils"; -export const EDIT_TOOL_CONTEXT_ITEM_NAME = "Edit Tool Instructions"; - export const editFileImpl: ToolImpl = async (args, extras) => { const firstUriMatch = await resolveRelativePathInDir( args.filepath, @@ -11,12 +9,18 @@ export const editFileImpl: ToolImpl = async (args, extras) => { if (!firstUriMatch) { throw new Error(`File ${args.filepath} does not exist.`); } + if (!extras.applyToFile) { + throw new Error("Failed to apply to file: invalid apply stream id"); + } + if (!extras.llm.title) { + throw new Error("Failed to apply to file: no model selected"); + } + await extras.applyToFile(firstUriMatch, args.new_contents); return [ { - name: EDIT_TOOL_CONTEXT_ITEM_NAME, - description: "Instructions for editing the file", - content: - "Edit Instructions: return the full new file contents in a codeblock. The codeblock header should be of the format '```language filepath'", + name: "Edit results", + description: `Result of editing ${args.filepath}`, + content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs, prompt them to do so`, }, ]; }; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 3c6963071..573838caa 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -242,6 +242,10 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } + async applyToFile() { + throw new Error("not implemented"); + } + async subprocess(command: string, cwd?: string): Promise<[string, string]> { return ["", ""]; } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 7e68cf007..ce1eea771 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -7,6 +7,8 @@ import com.github.continuedev.continueintellijextension.utils.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil +import com.intellij.find.FindModel +import com.intellij.find.impl.FindInProjectUtil import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity @@ -20,8 +22,10 @@ import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir +import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager @@ -46,7 +50,6 @@ class IntelliJIDE( private val gitService = GitService(project, continuePluginService) - private val ripgrep: String init { @@ -309,12 +312,116 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getSearchResults(query: String): String { - val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".") - command.setWorkDirectory(project.basePath) - return ExecUtil.execAndGetOutput(command).stdout + override suspend fun getFileResults(pattern: String): List { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "--files", + "--iglob", + pattern, + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + ) + + command.setWorkDirectory(project.basePath) + val results = ExecUtil.execAndGetOutput(command).stdout + return results.split("\n") + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // Leaving in here for ideas + // val projectBasePath = project.basePath ?: return emptyList() + // val scope = GlobalSearchScope.projectScope(project) + // + // // Get all ignore patterns from .continueignore files + // val ignorePatterns = mutableSetOf() + // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> + // VfsUtil.collectChildrenRecursively(root).forEach { file -> + // if (file.name == ".continueignore") { + // file.inputStream.bufferedReader().useLines { lines -> + // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) + // } + // } + // } + // } + // + // return FilenameIndex.getAllFilesByExt(project, "*", scope) + // .filter { file -> + // val relativePath = file.path.removePrefix("$projectBasePath/") + // // Check if file matches pattern and isn't ignored + // PatternUtil.(relativePath, pattern) && + // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } + // } + // .map { it.path.removePrefix("$projectBasePath/") } + } } + override suspend fun getSearchResults(query: String): String { + val ideInfo = this.getIdeInfo() + if (ideInfo.remoteName == "local") { + val command = GeneralCommandLine( + ripgrep, + "-i", + "--ignore-file", + ".continueignore", + "--ignore-file", + ".gitignore", + "-C", + "2", + "--heading", + "-e", + query, + "." + ) + + command.setWorkDirectory(project.basePath) + return ExecUtil.execAndGetOutput(command).stdout + } else { + throw NotImplementedError("Ripgrep not supported, this workspace is remote") + + // For remote workspaces, use JetBrains search functionality + // val searchResults = StringBuilder() + // ApplicationManager.getApplication().invokeAndWait { + // val options = FindModel().apply { + // stringToFind = query + // isCaseSensitive = false + // isRegularExpressions = false + // isWholeWordsOnly = false + // searchContext = FindModel.SearchContext.ANY // or IN_CODE, IN_COMMENTS, IN_STRING_LITERALS, etc. + // isMultiline = true // Allow matching across multiple lines + // } + // + // val progressIndicator = EmptyProgressIndicator() + // val presentation = FindUsagesProcessPresentation( + // UsageViewPresentation() + // ) + // val filesToSearch = ProjectFileIndex.getInstance(project) + // .iterateContent(::ArrayList) + // .filterNot { it.isDirectory } + // .toSet() + // + // + // FindInProjectUtil.findUsages( + // options, + // project, + // progressIndicator, + // presentation, + // filesToSearch + // ) { result -> + // val virtualFile = result.virtualFile + // searchResults.append(virtualFile.path).append("\n") + // searchResults.append("${result..trim()}\n") + // true // continue searching + // } + // } + // return searchResults.toString() + } + } + + override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") val builder = ProcessBuilder(commandList) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 5ce49e80a..0e16eeba6 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -23,7 +23,6 @@ typealias getTagsParams = String data class GetSearchResultsParams(val query: String) - data class SaveFileParams(val filepath: String) data class FileExistsParams(val filepath: String) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 883039263..504acce2b 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -8,13 +8,6 @@ import { editConfigFile, getConfigJsonPath } from "core/util/paths"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import { executeGotoProvider } from "./autocomplete/lsp"; -import { Repository } from "./otherExtensions/git"; -import { SecretStorage } from "./stubs/SecretStorage"; -import { VsCodeIdeUtils } from "./util/ideUtils"; -import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; -import { VsCodeWebviewProtocol } from "./webviewProtocol"; - import type { ContinueRcJson, FileStatsMap, @@ -29,6 +22,12 @@ import type { TerminalOptions, Thread, } from "core"; +import { executeGotoProvider } from "./autocomplete/lsp"; +import { Repository } from "./otherExtensions/git"; +import { SecretStorage } from "./stubs/SecretStorage"; +import { VsCodeIdeUtils } from "./util/ideUtils"; +import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 23669305a..43987c4b8 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,6 +18,7 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -28,7 +29,6 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -128,7 +128,7 @@ export class VsCodeMessenger { ); }); - this.onWebview("applyToFile", async ({ data }) => { + this.onWebviewOrCore("applyToFile", async ({ data }) => { webviewProtocol.request("updateApplyState", { streamId: data.streamId, status: "streaming", diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 776192e45..e9393f384 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -57,7 +57,6 @@ export interface StepContainerPreToolbarProps { children: any; expanded?: boolean; hideApply?: boolean; - autoApply?: boolean; } export default function StepContainerPreToolbar( @@ -136,17 +135,17 @@ export default function StepContainerPreToolbar( } }, [props.children, codeBlockContent]); - useEffect(() => { - const hasCompletedGenerating = - wasGeneratingRef.current && !isGeneratingCodeBlock; + // useEffect(() => { + // const hasCompletedGenerating = + // wasGeneratingRef.current && !isGeneratingCodeBlock; - wasGeneratingRef.current = isGeneratingCodeBlock; - if (hasCompletedGenerating) { - if (props.autoApply) { - onClickApply(); - } - } - }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); + // wasGeneratingRef.current = isGeneratingCodeBlock; + // if (hasCompletedGenerating) { + // if (props.autoApply) { + // onClickApply(); + // } + // } + // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 4aed38536..5137c63b9 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -130,8 +130,8 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; itemIndex?: number; useParentBackgroundColor?: boolean; - autoApplyCodeblocks?: boolean; hideApply?: boolean; + firstCodeblockStreamId?: string; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -199,7 +199,14 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const pastFileInfoRef = useUpdatingRef(pastFileInfo); const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( - [], + props.firstCodeblockStreamId + ? [ + { + streamId: props.firstCodeblockStreamId, + isGenerating: false, + }, + ] + : [], ); const [reactContent, setMarkdownSource] = useRemark({ @@ -319,9 +326,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( streamId: uuidv4(), isGenerating: isGeneratingCodeBlock, }; + } else { + codeblockState.current[codeBlockIndex].isGenerating = + isGeneratingCodeBlock; } - const codeblockStreamId = - codeblockState.current[codeBlockIndex].streamId; // We use a custom toolbar for codeblocks in the step container return ( @@ -332,8 +340,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( relativeFilepath={relativeFilePath} isGeneratingCodeBlock={isGeneratingCodeBlock} range={range} - autoApply={props.autoApplyCodeblocks} - codeBlockStreamId={codeblockStreamId} + codeBlockStreamId={ + codeblockState.current[codeBlockIndex].streamId + } hideApply={props.hideApply} > diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 56ee77ef3..f1c528966 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,5 +1,9 @@ import { getMarkdownLanguageTagForFile } from "core/util"; +import { useMemo } from "react"; +import { v4 as uuidv4 } from "uuid"; import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import { useAppDispatch } from "../../../redux/hooks"; +import { setLastApplyToolStreamId } from "../../../redux/slices/sessionSlice"; type EditToolCallProps = { relativeFilePath: string; @@ -7,14 +11,21 @@ type EditToolCallProps = { }; export function EditFile(props: EditToolCallProps) { + const dispatch = useAppDispatch(); const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + const streamId = useMemo(() => { + const id = uuidv4(); + dispatch(setLastApplyToolStreamId({ streamId: id })); + return id; + }, []); + return props.relativeFilePath ? ( ) : null; } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 5aa714acc..88ac4e3b4 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -54,6 +54,7 @@ type SessionState = { curIndex: number; }; newestCodeblockForInput: Record; + lastApplyToolStreamId?: string; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -637,6 +638,12 @@ export const sessionSlice = createSlice({ toolCallState.status = "calling"; }, + setLastApplyToolStreamId: ( + state, + action: PayloadAction<{ streamId: string }>, + ) => { + state.lastApplyToolStreamId = action.payload.streamId; + }, setMode: (state, action: PayloadAction) => { state.mode = action.payload; }, @@ -759,6 +766,7 @@ export const { updateSessionMetadata, deleteSessionMetadata, setNewestCodeblocksForInput, + setLastApplyToolStreamId, cycleMode, } = sessionSlice.actions; diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 34ae00390..82ec08f0f 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,4 +1,5 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { @@ -34,6 +35,11 @@ export const callTool = createAsyncThunk( const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, selectedModelTitle: defaultModel.title, + applyStreamId: + toolCallState.toolCall.function.name === + BuiltInToolNames.EditExistingFile + ? state.session.lastApplyToolStreamId + : undefined, }); if (result.status === "success") { From 1bc816b1f1bf43c354f153a43d3875cb4273d21d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 00:38:33 -0700 Subject: [PATCH 10/21] edit file apply state --- core/tools/implementations/editFile.ts | 5 +- .../StepContainerPreToolbar/ApplyActions.tsx | 12 +++-- .../StepContainerPreToolbar.tsx | 5 +- .../markdown/StyledMarkdownPreview.tsx | 4 +- gui/src/pages/gui/ToolCallDiv/CreateFile.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 54 +++++++++++++------ gui/src/redux/slices/sessionSlice.ts | 37 ++++++++----- 7 files changed, 80 insertions(+), 39 deletions(-) diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index deac3cc54..6862b29f2 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -12,15 +12,12 @@ export const editFileImpl: ToolImpl = async (args, extras) => { if (!extras.applyToFile) { throw new Error("Failed to apply to file: invalid apply stream id"); } - if (!extras.llm.title) { - throw new Error("Failed to apply to file: no model selected"); - } await extras.applyToFile(firstUriMatch, args.new_contents); return [ { name: "Edit results", description: `Result of editing ${args.filepath}`, - content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs, prompt them to do so`, + content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs. Prompt them to do so in your response`, }, ]; }; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 71e7ca9cf..0da1c5c7f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -7,6 +7,7 @@ import Spinner from "../../gui/Spinner"; import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; interface ApplyActionsProps { + disableManualApply?: boolean; applyState?: ApplyState; onClickAccept: () => void; onClickReject: () => void; @@ -59,8 +60,8 @@ export default function ApplyActions(props: ApplyActionsProps) { ); case "done": return ( -
- +
+ {`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`} {` remaining`} @@ -90,10 +91,15 @@ export default function ApplyActions(props: ApplyActionsProps) { ); } - + if (props.disableManualApply) { + return null; + } return applyButton("Reapply"); } default: + if (props.disableManualApply) { + return null; + } return applyButton("Apply"); } } diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index e9393f384..375fd7ab8 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -56,7 +56,7 @@ export interface StepContainerPreToolbarProps { range?: string; children: any; expanded?: boolean; - hideApply?: boolean; + disableManualApply?: boolean; } export default function StepContainerPreToolbar( @@ -206,8 +206,9 @@ export default function StepContainerPreToolbar( {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - ) : props.hideApply ? null : ( + ) : ( diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 9829ef64b..45396dc23 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -13,7 +13,7 @@ export function CreateFile(props: CreateFileToolCallProps) { ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index f1c528966..b3cb2bb63 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,9 +1,9 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useMemo } from "react"; -import { v4 as uuidv4 } from "uuid"; import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; -import { useAppDispatch } from "../../../redux/hooks"; -import { setLastApplyToolStreamId } from "../../../redux/slices/sessionSlice"; +import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; type EditToolCallProps = { relativeFilePath: string; @@ -11,21 +11,45 @@ type EditToolCallProps = { }; export function EditFile(props: EditToolCallProps) { - const dispatch = useAppDispatch(); const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + const dispatch = useAppDispatch(); + + const isStreaming = useAppSelector((state) => state.session.isStreaming); + const lastApplyToolStreamId = useAppSelector( + (state) => state.session.lastApplyToolStreamId, + ); const streamId = useMemo(() => { - const id = uuidv4(); - dispatch(setLastApplyToolStreamId({ streamId: id })); - return id; + return lastApplyToolStreamId; }, []); - return props.relativeFilePath ? ( - - ) : null; + console.log("STREAM ID", streamId); + + const applyState = useAppSelector((state) => + selectApplyStateByStreamId(state, streamId), + ); + + if (!props.relativeFilePath) { + return null; + } + + return ( + <> + + + {!isStreaming && applyState?.status === "done" && ( +
+ {}} + /> +
+ )} + + ); } diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 88ac4e3b4..51af56ee7 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -21,6 +21,7 @@ import { ToolCallDelta, ToolCallState, } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; @@ -354,16 +355,25 @@ export const sessionSlice = createSlice({ if (message.role === "assistant" && message.toolCalls?.[0]) { const toolCallDelta = message.toolCalls[0]; if ( - toolCallDelta.id && - toolCallDelta.function?.arguments && - toolCallDelta.function?.name && - toolCallDelta.type + !( + toolCallDelta.id && + toolCallDelta.function?.arguments && + toolCallDelta.function?.name && + toolCallDelta.type + ) ) { console.warn( "Received streamed tool call without required fields", toolCallDelta, ); } + + if ( + toolCallDelta.function?.name === + BuiltInToolNames.EditExistingFile + ) { + state.lastApplyToolStreamId = uuidv4(); + } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -638,12 +648,6 @@ export const sessionSlice = createSlice({ toolCallState.status = "calling"; }, - setLastApplyToolStreamId: ( - state, - action: PayloadAction<{ streamId: string }>, - ) => { - state.lastApplyToolStreamId = action.payload.streamId; - }, setMode: (state, action: PayloadAction) => { state.mode = action.payload; }, @@ -723,7 +727,17 @@ export const selectCurrentToolCall = createSelector( export const selectApplyStateByStreamId = createSelector( [ (state: RootState) => state.session.codeBlockApplyStates.states, - (state: RootState, streamId: string) => streamId, + (state: RootState, streamId?: string) => streamId, + ], + (states, streamId) => { + return states.find((state) => state.streamId === streamId); + }, +); + +export const selectLastEditToolApplyState = createSelector( + [ + (state: RootState) => state.session.codeBlockApplyStates.states, + (state: RootState) => state.session.lastApplyToolStreamId, ], (states, streamId) => { return states.find((state) => state.streamId === streamId); @@ -766,7 +780,6 @@ export const { updateSessionMetadata, deleteSessionMetadata, setNewestCodeblocksForInput, - setLastApplyToolStreamId, cycleMode, } = sessionSlice.actions; From 4683a20c2fbc0c70fe5457221743bd6a15749a3b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 00:51:31 -0700 Subject: [PATCH 11/21] cleanup --- core/tools/implementations/editFile.ts | 4 +- core/util/filesystem.ts | 4 - .../continue/IntelliJIde.kt | 115 +----------------- .../continueintellijextension/protocol/ide.kt | 1 + extensions/vscode/src/VsCodeIde.ts | 13 +- manual-testing-sandbox/requirements.txt | 2 +- 6 files changed, 15 insertions(+), 124 deletions(-) diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index 6862b29f2..26156352b 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -16,8 +16,8 @@ export const editFileImpl: ToolImpl = async (args, extras) => { return [ { name: "Edit results", - description: `Result of editing ${args.filepath}`, - content: `Successfully applied edits to ${args.filepath}. The users must manually reject/accept diffs. Prompt them to do so in your response`, + description: `Edited ${args.filepath}`, + content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, }, ]; }; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 573838caa..3c6963071 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -242,10 +242,6 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } - async applyToFile() { - throw new Error("not implemented"); - } - async subprocess(command: string, cwd?: string): Promise<[string, string]> { return ["", ""]; } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index ce1eea771..7e68cf007 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -7,8 +7,6 @@ import com.github.continuedev.continueintellijextension.utils.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil -import com.intellij.find.FindModel -import com.intellij.find.impl.FindInProjectUtil import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.annotation.HighlightSeverity @@ -22,10 +20,8 @@ import com.intellij.openapi.editor.impl.DocumentMarkupModel import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager -import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir -import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager @@ -50,6 +46,7 @@ class IntelliJIDE( private val gitService = GitService(project, continuePluginService) + private val ripgrep: String init { @@ -312,115 +309,11 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getFileResults(pattern: String): List { - val ideInfo = this.getIdeInfo() - if (ideInfo.remoteName == "local") { - val command = GeneralCommandLine( - ripgrep, - "--files", - "--iglob", - pattern, - "--ignore-file", - ".continueignore", - "--ignore-file", - ".gitignore", - ) - - command.setWorkDirectory(project.basePath) - val results = ExecUtil.execAndGetOutput(command).stdout - return results.split("\n") - } else { - throw NotImplementedError("Ripgrep not supported, this workspace is remote") - - // Leaving in here for ideas - // val projectBasePath = project.basePath ?: return emptyList() - // val scope = GlobalSearchScope.projectScope(project) - // - // // Get all ignore patterns from .continueignore files - // val ignorePatterns = mutableSetOf() - // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> - // VfsUtil.collectChildrenRecursively(root).forEach { file -> - // if (file.name == ".continueignore") { - // file.inputStream.bufferedReader().useLines { lines -> - // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) - // } - // } - // } - // } - // - // return FilenameIndex.getAllFilesByExt(project, "*", scope) - // .filter { file -> - // val relativePath = file.path.removePrefix("$projectBasePath/") - // // Check if file matches pattern and isn't ignored - // PatternUtil.(relativePath, pattern) && - // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } - // } - // .map { it.path.removePrefix("$projectBasePath/") } - } - } - override suspend fun getSearchResults(query: String): String { - val ideInfo = this.getIdeInfo() - if (ideInfo.remoteName == "local") { - val command = GeneralCommandLine( - ripgrep, - "-i", - "--ignore-file", - ".continueignore", - "--ignore-file", - ".gitignore", - "-C", - "2", - "--heading", - "-e", - query, - "." - ) - - command.setWorkDirectory(project.basePath) - return ExecUtil.execAndGetOutput(command).stdout - } else { - throw NotImplementedError("Ripgrep not supported, this workspace is remote") - - // For remote workspaces, use JetBrains search functionality - // val searchResults = StringBuilder() - // ApplicationManager.getApplication().invokeAndWait { - // val options = FindModel().apply { - // stringToFind = query - // isCaseSensitive = false - // isRegularExpressions = false - // isWholeWordsOnly = false - // searchContext = FindModel.SearchContext.ANY // or IN_CODE, IN_COMMENTS, IN_STRING_LITERALS, etc. - // isMultiline = true // Allow matching across multiple lines - // } - // - // val progressIndicator = EmptyProgressIndicator() - // val presentation = FindUsagesProcessPresentation( - // UsageViewPresentation() - // ) - // val filesToSearch = ProjectFileIndex.getInstance(project) - // .iterateContent(::ArrayList) - // .filterNot { it.isDirectory } - // .toSet() - // - // - // FindInProjectUtil.findUsages( - // options, - // project, - // progressIndicator, - // presentation, - // filesToSearch - // ) { result -> - // val virtualFile = result.virtualFile - // searchResults.append(virtualFile.path).append("\n") - // searchResults.append("${result..trim()}\n") - // true // continue searching - // } - // } - // return searchResults.toString() - } + val command = GeneralCommandLine(ripgrep, "-i", "-C", "2", "--heading", "-e", query, ".") + command.setWorkDirectory(project.basePath) + return ExecUtil.execAndGetOutput(command).stdout } - override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 0e16eeba6..5ce49e80a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -23,6 +23,7 @@ typealias getTagsParams = String data class GetSearchResultsParams(val query: String) + data class SaveFileParams(val filepath: String) data class FileExistsParams(val filepath: String) diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 504acce2b..883039263 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -8,6 +8,13 @@ import { editConfigFile, getConfigJsonPath } from "core/util/paths"; import * as URI from "uri-js"; import * as vscode from "vscode"; +import { executeGotoProvider } from "./autocomplete/lsp"; +import { Repository } from "./otherExtensions/git"; +import { SecretStorage } from "./stubs/SecretStorage"; +import { VsCodeIdeUtils } from "./util/ideUtils"; +import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; + import type { ContinueRcJson, FileStatsMap, @@ -22,12 +29,6 @@ import type { TerminalOptions, Thread, } from "core"; -import { executeGotoProvider } from "./autocomplete/lsp"; -import { Repository } from "./otherExtensions/git"; -import { SecretStorage } from "./stubs/SecretStorage"; -import { VsCodeIdeUtils } from "./util/ideUtils"; -import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode"; -import { VsCodeWebviewProtocol } from "./webviewProtocol"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt index 87f2e654b..9de6f14df 100644 --- a/manual-testing-sandbox/requirements.txt +++ b/manual-testing-sandbox/requirements.txt @@ -54,4 +54,4 @@ aiohttp==3.7.4 # Others jupyter==1.0.0 gunicorn==20.1.0 -psycopg2==2.9.1 \ No newline at end of file +psycopg2==2.9.1 From 8f556c0b014b16f9586a8cccca0b8a4fcfc36711 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 01:02:48 -0700 Subject: [PATCH 12/21] move to custom edit impl --- core/index.d.ts | 1 - core/protocol/core.ts | 2 +- core/protocol/ide.ts | 11 -------- core/protocol/ideWebview.ts | 12 +++++++++ core/tools/callTool.ts | 6 ++--- core/tools/implementations/editFile.ts | 24 +---------------- .../vscode/src/extension/VsCodeMessenger.ts | 4 +-- gui/src/redux/thunks/callTool.ts | 27 ++++++++++++++----- manual-testing-sandbox/requirements.txt | 2 +- 9 files changed, 41 insertions(+), 48 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 5b2b482ed..ba97377d3 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -891,7 +891,6 @@ export interface ToolExtras { llm: ILLM; fetch: FetchFunction; tool: Tool; - applyToFile?: (path: string, content: string) => Promise; } export interface Tool { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index f92f70a50..03940c283 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -193,7 +193,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ - { toolCall: ToolCall; selectedModelTitle: string; applyStreamId?: string }, + { toolCall: ToolCall; selectedModelTitle: string }, { contextItems: ContextItem[] }, ]; "clipboardCache/add": [{ content: string }, void]; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 9b3d030f6..5b2a7ab1f 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -23,17 +23,6 @@ export interface GetGhTokenArgs { export type ToIdeFromWebviewOrCoreProtocol = { // Methods from IDE type - // We pass the `curSelectedModel` because we currently cannot access the - // default model title in the GUI from JB - applyToFile: [ - { - text: string; - streamId: string; - curSelectedModelTitle: string; - filepath?: string; - }, - void, - ]; getIdeInfo: [undefined, IdeInfo]; getWorkspaceDirs: [undefined, string[]]; writeFile: [{ path: string; contents: string }, void]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 03074b95f..a7cd16e5b 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,6 +4,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, + ContextSubmenuItem, EditStatus, MessageContent, RangeInFileWithContents, @@ -11,6 +12,17 @@ import type { export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { openUrl: [string, void]; + // We pass the `curSelectedModel` because we currently cannot access the + // default model title in the GUI from JB + applyToFile: [ + { + text: string; + streamId: string; + curSelectedModelTitle: string; + filepath?: string; + }, + void, + ]; overwriteFile: [{ filepath: string; prevFileContent: string | null }, void]; showTutorial: [undefined, void]; showFile: [{ filepath: string }, void]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 2866124ef..2a04cb828 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -4,7 +4,6 @@ import { canParseUrl } from "../util/url"; import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; -import { editFileImpl } from "./implementations/editFile"; import { exactSearchImpl } from "./implementations/exactSearch"; import { lsToolImpl } from "./implementations/lsTool"; import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; @@ -139,8 +138,9 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); - case BuiltInToolNames.EditExistingFile: - return await editFileImpl(args, extras); + // Custom GUI handling for edit + // case BuiltInToolNames.EditExistingFile: + // return await editFileImpl(args, extras); case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.ExactSearch: diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts index 26156352b..cb829af6a 100644 --- a/core/tools/implementations/editFile.ts +++ b/core/tools/implementations/editFile.ts @@ -1,23 +1 @@ -import { ToolImpl } from "."; -import { resolveRelativePathInDir } from "../../util/ideUtils"; - -export const editFileImpl: ToolImpl = async (args, extras) => { - const firstUriMatch = await resolveRelativePathInDir( - args.filepath, - extras.ide, - ); - if (!firstUriMatch) { - throw new Error(`File ${args.filepath} does not exist.`); - } - if (!extras.applyToFile) { - throw new Error("Failed to apply to file: invalid apply stream id"); - } - await extras.applyToFile(firstUriMatch, args.new_contents); - return [ - { - name: "Edit results", - description: `Edited ${args.filepath}`, - content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, - }, - ]; -}; +// Edit has custom handling on the GUI side diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 43987c4b8..23669305a 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,7 +18,6 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; -import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -29,6 +28,7 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -128,7 +128,7 @@ export class VsCodeMessenger { ); }); - this.onWebviewOrCore("applyToFile", async ({ data }) => { + this.onWebview("applyToFile", async ({ data }) => { webviewProtocol.request("updateApplyState", { streamId: data.streamId, status: "streaming", diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 82ec08f0f..8df0ccfa9 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,5 +1,4 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { BuiltInToolNames } from "core/tools/builtIn"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { @@ -35,11 +34,6 @@ export const callTool = createAsyncThunk( const result = await extra.ideMessenger.request("tools/call", { toolCall: toolCallState.toolCall, selectedModelTitle: defaultModel.title, - applyStreamId: - toolCallState.toolCall.function.name === - BuiltInToolNames.EditExistingFile - ? state.session.lastApplyToolStreamId - : undefined, }); if (result.status === "success") { @@ -76,3 +70,24 @@ export const callTool = createAsyncThunk( } }, ); + +// export const editFileImpl: ToolImpl = async (args, extras) => { +// const firstUriMatch = await resolveRelativePathInDir( +// args.filepath, +// extras.ide, +// ); +// if (!firstUriMatch) { +// throw new Error(`File ${args.filepath} does not exist.`); +// } +// if (!extras.applyToFile) { +// throw new Error("Failed to apply to file: invalid apply stream id"); +// } +// await extras.applyToFile(firstUriMatch, args.new_contents); +// return [ +// { +// name: "Edit results", +// description: `Edited ${args.filepath}`, +// content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, +// }, +// ]; +// }; diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt index 9de6f14df..87f2e654b 100644 --- a/manual-testing-sandbox/requirements.txt +++ b/manual-testing-sandbox/requirements.txt @@ -54,4 +54,4 @@ aiohttp==3.7.4 # Others jupyter==1.0.0 gunicorn==20.1.0 -psycopg2==2.9.1 +psycopg2==2.9.1 \ No newline at end of file From e1ff2a9e57f21740672edddb24b45d8968d4d67b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 02:07:43 -0700 Subject: [PATCH 13/21] custom gui approach --- core/core.ts | 17 +--- gui/src/hooks/useSetup.ts | 8 ++ gui/src/redux/slices/sessionSlice.ts | 12 +-- gui/src/redux/thunks/callTool.ts | 121 ++++++++++++++++++--------- 4 files changed, 95 insertions(+), 63 deletions(-) diff --git a/core/core.ts b/core/core.ts index 911ea0072..b1393f8cd 100644 --- a/core/core.ts +++ b/core/core.ts @@ -36,7 +36,6 @@ import { TTS } from "./util/tts"; import { DiffLine, - ToolExtras, type ContextItemId, type IDE, type IndexingProgressUpdate, @@ -873,7 +872,7 @@ export class Core { }); on("tools/call", async (msg) => { - const { toolCall, selectedModelTitle, applyStreamId } = msg.data; + const { toolCall, selectedModelTitle } = msg.data; const { config } = await this.configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -889,19 +888,6 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - let applyToFile: ToolExtras["applyToFile"] = undefined; - if (applyStreamId) { - applyToFile = async (path: string, contents: string) => { - return await this.messenger.request("applyToFile", { - filepath: path, - text: contents, - streamId: applyStreamId, - curSelectedModelTitle: - config.selectedModelByRole.apply?.title ?? selectedModelTitle, - }); - }; - } - const contextItems = await callTool( tool, JSON.parse(toolCall.function.arguments || "{}"), @@ -911,7 +897,6 @@ export class Core { fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), tool, - applyToFile, }, ); diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index d90259a9b..f1909afc5 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -17,6 +17,7 @@ import { import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { addContextItemsAtIndex, + selectLastEditToolApplyState, setInactive, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; @@ -245,6 +246,13 @@ function useSetup() { }, [defaultModel], ); + + const lastEditToolApplyState = useAppSelector(selectLastEditToolApplyState); + useEffect(() => { + ideMessenger.post("showToast", ["info", "updated last apply state"]); + // dispatch(setToolCallOutput(output)); + // dispatch(acceptToolCall()); + }, [lastEditToolApplyState]); } export default useSetup; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 51af56ee7..544a8c401 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -21,7 +21,6 @@ import { ToolCallDelta, ToolCallState, } from "core"; -import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; @@ -368,12 +367,6 @@ export const sessionSlice = createSlice({ ); } - if ( - toolCallDelta.function?.name === - BuiltInToolNames.EditExistingFile - ) { - state.lastApplyToolStreamId = uuidv4(); - } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -559,7 +552,9 @@ export const sessionSlice = createSlice({ state.history[state.history.length - 1].contextItems = contextItems; }, - + setLastToolApplyStreamId: (state, { payload }: PayloadAction) => { + state.lastApplyToolStreamId = payload; + }, updateCurCheckpoint: ( state, { payload }: PayloadAction<{ filepath: string; content: string }>, @@ -781,6 +776,7 @@ export const { deleteSessionMetadata, setNewestCodeblocksForInput, cycleMode, + setLastToolApplyStreamId, } = sessionSlice.actions; export const { diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 8df0ccfa9..190c25ccf 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,10 +1,17 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { ContextItem } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; +import { EditToolArgs } from "core/tools/definitions/editFile"; +import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { v4 as uuidv4 } from "uuid"; +import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { acceptToolCall, cancelToolCall, setCalling, + setLastToolApplyStreamId, setToolCallOutput, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -31,28 +38,46 @@ export const callTool = createAsyncThunk( dispatch(setCalling()); - const result = await extra.ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - selectedModelTitle: defaultModel.title, - }); + let errorMessage = ""; + let output: ContextItem[] | undefined = undefined; - if (result.status === "success") { - const contextItems = result.content.contextItems; - dispatch(setToolCallOutput(contextItems)); - dispatch(acceptToolCall()); - - // Send to the LLM to continue the conversation - const response = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCall.id, - toolOutput: contextItems, - }), + if ( + toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile + ) { + const newToolStreamId = uuidv4(); + dispatch(setLastToolApplyStreamId(newToolStreamId)); + const args = JSON.parse( + toolCallState.toolCall.function.arguments || "{}", ); - unwrapResult(response); + try { + await customGuiEditImpl( + args, + extra.ideMessenger, + newToolStreamId, + defaultModel.title, + ); + } catch (e) { + errorMessage = "Failed to call edit tool"; + if (e instanceof Error) { + errorMessage = e.message; + } + } } else { + const result = await extra.ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + selectedModelTitle: defaultModel.title, + }); + if (result.status === "error") { + errorMessage = result.error; + } else { + output = result.content.contextItems; + } + } + + if (errorMessage) { dispatch(cancelToolCall()); - const output = await dispatch( + const wrapped = await dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, toolOutput: [ @@ -60,34 +85,52 @@ export const callTool = createAsyncThunk( icon: "problems", name: "Tool Call Error", description: "Tool Call Failed", - content: `The tool call failed with the message:\n\n${result.error}\n\nPlease try something else or request further instructions.`, + content: `The tool call failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, hidden: false, }, ], }), ); - unwrapResult(output); + unwrapResult(wrapped); + } else if (output) { + dispatch(setToolCallOutput(output)); + dispatch(acceptToolCall()); + + // Send to the LLM to continue the conversation + const wrapped = await dispatch( + streamResponseAfterToolCall({ + toolCallId: toolCallState.toolCall.id, + toolOutput: output, + }), + ); + unwrapResult(wrapped); } + // okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool }, ); -// export const editFileImpl: ToolImpl = async (args, extras) => { -// const firstUriMatch = await resolveRelativePathInDir( -// args.filepath, -// extras.ide, -// ); -// if (!firstUriMatch) { -// throw new Error(`File ${args.filepath} does not exist.`); -// } -// if (!extras.applyToFile) { -// throw new Error("Failed to apply to file: invalid apply stream id"); -// } -// await extras.applyToFile(firstUriMatch, args.new_contents); -// return [ -// { -// name: "Edit results", -// description: `Edited ${args.filepath}`, -// content: `Applied edit diffs to ${args.filepath}. The user must manually reject/accept diffs. Prompt them to do so in your response`, -// }, -// ]; -// }; +async function customGuiEditImpl( + args: EditToolArgs, + ideMessenger: IIdeMessenger, + streamId: string, + modelTitle: string, +) { + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + ideMessenger.ide, + ); + if (!firstUriMatch) { + return [ + { + name: "Edit failure", + description: `editing ${args.filepath}`, + content: `Failed to edit ${args.filepath}: does not exist`, + }, + ]; + } + ideMessenger.post("applyToFile", { + streamId, + text: args.new_contents, + curSelectedModelTitle: modelTitle, + }); +} From 2efd3ff03a17b3a58d4c950ad9393dda3f82cb78 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:16:18 -0700 Subject: [PATCH 14/21] working and disable input when pending tool call stream --- core/core.ts | 3 +- core/index.d.ts | 1 + core/protocol/ideWebview.ts | 2 +- core/tools/definitions/exactSearch.ts | 2 +- core/tools/implementations/editFile.ts | 1 - .../protocol/ideWebview.kt | 3 +- extensions/vscode/src/commands.ts | 2 + .../vscode/src/diff/vertical/manager.ts | 4 ++ .../vscode/src/extension/VsCodeMessenger.ts | 5 ++- gui/src/components/mainInput/InputToolbar.tsx | 7 ++- .../markdown/StyledMarkdownPreview.tsx | 21 +++++---- gui/src/hooks/useSetup.ts | 44 +++++++++++++++---- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 33 +++++++------- .../FunctionSpecificToolCallDiv.tsx | 1 + gui/src/redux/slices/sessionSlice.ts | 32 +++++++------- gui/src/redux/thunks/callTool.ts | 22 ++++------ 16 files changed, 112 insertions(+), 71 deletions(-) delete mode 100644 core/tools/implementations/editFile.ts diff --git a/core/core.ts b/core/core.ts index b1393f8cd..11fecffb2 100644 --- a/core/core.ts +++ b/core/core.ts @@ -871,8 +871,7 @@ export class Core { } }); - on("tools/call", async (msg) => { - const { toolCall, selectedModelTitle } = msg.data; + on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { const { config } = await this.configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..98f724fda 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1141,6 +1141,7 @@ export interface ApplyState { numDiffs?: number; filepath?: string; fileContent?: string; + toolCallId?: string; } export interface RangeInFileWithContents { diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index a7cd16e5b..6aae337f0 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; import type { ApplyState, CodeToEdit, - ContextSubmenuItem, EditStatus, MessageContent, RangeInFileWithContents, @@ -20,6 +19,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { streamId: string; curSelectedModelTitle: string; filepath?: string; + toolCallId?: string; }, void, ]; diff --git a/core/tools/definitions/exactSearch.ts b/core/tools/definitions/exactSearch.ts index d20db3cec..7f6e03d6b 100644 --- a/core/tools/definitions/exactSearch.ts +++ b/core/tools/definitions/exactSearch.ts @@ -6,7 +6,7 @@ export const exactSearchTool: Tool = { displayTitle: "Exact Search", wouldLikeTo: 'search for "{{{ query }}}" in the repository', isCurrently: 'getting search results for "{{{ query }}}"', - hasAlready: 'retreived search results for "{{{ query }}}"', + hasAlready: 'retrieved search results for "{{{ query }}}"', readonly: true, group: BUILT_IN_GROUP_NAME, function: { diff --git a/core/tools/implementations/editFile.ts b/core/tools/implementations/editFile.ts deleted file mode 100644 index cb829af6a..000000000 --- a/core/tools/implementations/editFile.ts +++ /dev/null @@ -1 +0,0 @@ -// Edit has custom handling on the GUI side diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 07988ad0e..5c587c54d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -12,7 +12,8 @@ data class ApplyToFileParams( val text: String, val streamId: String, val curSelectedModelTitle: String, - val filepath: String? + val filepath: String?, + val toolCallId: String? ) data class InsertAtCursorParams( diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 836360e51..32d240d5f 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -247,6 +247,7 @@ async function processDiff( verticalDiffManager: VerticalDiffManager, newFileUri?: string, streamId?: string, + toolCallId?: string, ) { captureCommandTelemetry(`${action}Diff`); @@ -280,6 +281,7 @@ async function processDiff( streamId, status: "closed", numDiffs: 0, + toolCallId, }); } diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 34c3345ac..4d4256a1f 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -190,6 +190,7 @@ export class VerticalDiffManager { diffStream: AsyncGenerator, instant: boolean, streamId: string, + toolCallId?: string, ) { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -226,6 +227,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); @@ -276,6 +278,7 @@ export class VerticalDiffManager { quickEdit?: string, range?: vscode.Range, newCode?: string, + toolCallId?: string, ): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); @@ -351,6 +354,7 @@ export class VerticalDiffManager { numDiffs, fileContent, filepath: fileUri, + toolCallId, }), }, ); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 23669305a..98fe8489b 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -18,6 +18,7 @@ import { stripImages } from "core/util/messageContent"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ILLM } from "core"; import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { @@ -28,7 +29,6 @@ import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { ILLM } from "core"; /** * A shared messenger class between Core and Webview @@ -133,6 +133,7 @@ export class VsCodeMessenger { streamId: data.streamId, status: "streaming", fileContent: data.text, + toolCallId: data.toolCallId, }); if (data.filepath) { @@ -164,6 +165,7 @@ export class VsCodeMessenger { status: "closed", numDiffs: 0, fileContent: data.text, + toolCallId: data.toolCallId, }); return; @@ -232,6 +234,7 @@ export class VsCodeMessenger { undefined, rangeToApplyTo, data.text, + data.toolCallId, ); } }); diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 3d0a38cec..27c034721 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -98,11 +98,16 @@ function InputToolbar(props: InputToolbarProps) { const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; + const activeToolCallStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit || - toolCallState?.status === "generated"; + toolCallState?.status === "generated" || + activeToolCallStreamId; + const toolsSupported = defaultModel && modelSupportsTools(defaultModel); const supportsImages = diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index b473bb6f0..52ede7cbd 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -131,7 +131,7 @@ interface StyledMarkdownPreviewProps { itemIndex?: number; useParentBackgroundColor?: boolean; disableManualApply?: boolean; - firstCodeblockStreamId?: string; + singleCodeblockStreamId?: string; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -199,15 +199,18 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const pastFileInfoRef = useUpdatingRef(pastFileInfo); const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( - props.firstCodeblockStreamId - ? [ - { - streamId: props.firstCodeblockStreamId, - isGenerating: false, - }, - ] - : [], + [], ); + useEffect(() => { + if (props.singleCodeblockStreamId) { + codeblockState.current = [ + { + streamId: props.singleCodeblockStreamId, + isGenerating: false, + }, + ]; + } + }, [props.singleCodeblockStreamId]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index f1909afc5..914b96089 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,9 +1,9 @@ -import { useCallback, useContext, useEffect, useRef } from "react"; +import { useCallback, useContext, useEffect, useMemo, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { ConfigResult } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig } from "core"; +import { BrowserSerializedContinueConfig, ContextItem } from "core"; import { initializeProfilePreferencesThunk, selectProfileThunk, @@ -16,11 +16,13 @@ import { } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { + acceptToolCall, addContextItemsAtIndex, - selectLastEditToolApplyState, setInactive, + setToolCallOutput, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; +import { streamResponseAfterToolCall } from "../redux/thunks"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; @@ -247,12 +249,38 @@ function useSetup() { [defaultModel], ); - const lastEditToolApplyState = useAppSelector(selectLastEditToolApplyState); + const activeToolStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); + const applyStates = useAppSelector( + (store) => store.session.codeBlockApplyStates, + ); + const activeToolApplyState = useMemo(() => { + if (!activeToolStreamId) { + return undefined; + } + return applyStates.states.find( + (state) => state.streamId && state.streamId === activeToolStreamId, + ); + }, [applyStates, activeToolStreamId]); + useEffect(() => { - ideMessenger.post("showToast", ["info", "updated last apply state"]); - // dispatch(setToolCallOutput(output)); - // dispatch(acceptToolCall()); - }, [lastEditToolApplyState]); + if (activeToolApplyState?.status === "closed") { + const output: ContextItem = { + name: "Edit tool output", + content: "Completed edit", + description: "", + }; + dispatch(acceptToolCall()); + dispatch(setToolCallOutput([output])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: activeToolApplyState.toolCallId!, + toolOutput: [output], + }), + ); + } + }, [activeToolApplyState?.status]); } export default useSetup; diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index b3cb2bb63..56263b0a1 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -2,32 +2,25 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useMemo } from "react"; import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice"; +import { useAppSelector } from "../../../redux/hooks"; type EditToolCallProps = { relativeFilePath: string; newContents: string; + toolCallId?: string; }; export function EditFile(props: EditToolCallProps) { const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; - const dispatch = useAppDispatch(); - const isStreaming = useAppSelector((state) => state.session.isStreaming); - const lastApplyToolStreamId = useAppSelector( - (state) => state.session.lastApplyToolStreamId, - ); - const streamId = useMemo(() => { - return lastApplyToolStreamId; - }, []); + const states = useAppSelector((store) => store.session.codeBlockApplyStates); - console.log("STREAM ID", streamId); - - const applyState = useAppSelector((state) => - selectApplyStateByStreamId(state, streamId), - ); + const applyState = useMemo(() => { + return states.states.find( + (state) => state.toolCallId && state.toolCallId === props.toolCallId, + ); + }, [states, props.toolCallId]); if (!props.relativeFilePath) { return null; @@ -39,11 +32,15 @@ export function EditFile(props: EditToolCallProps) { isRenderingInStepContainer={true} source={src} disableManualApply={true} - firstCodeblockStreamId={streamId} + singleCodeblockStreamId={applyState?.streamId} /> - + {isStreaming && applyState?.status === "streaming" && ( +
+ Generating... +
+ )} {!isStreaming && applyState?.status === "done" && ( -
+
{}} diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index ee8726fae..55ed79e2a 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -26,6 +26,7 @@ function FunctionSpecificToolCallDiv({ ); case BuiltInToolNames.RunTerminalCommand: diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 544a8c401..bf22a1858 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -21,6 +21,7 @@ import { ToolCallDelta, ToolCallState, } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; @@ -54,7 +55,7 @@ type SessionState = { curIndex: number; }; newestCodeblockForInput: Record; - lastApplyToolStreamId?: string; + activeToolStreamId?: string; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -367,6 +368,19 @@ export const sessionSlice = createSlice({ ); } + if ( + toolCallDelta.id && + toolCallDelta.function?.name === + BuiltInToolNames.EditExistingFile + ) { + const streamId = uuidv4(); + state.codeBlockApplyStates.states.push({ + streamId, + toolCallId: toolCallDelta.id, + status: "streaming", + }); + state.activeToolStreamId = streamId; + } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -552,9 +566,7 @@ export const sessionSlice = createSlice({ state.history[state.history.length - 1].contextItems = contextItems; }, - setLastToolApplyStreamId: (state, { payload }: PayloadAction) => { - state.lastApplyToolStreamId = payload; - }, + updateCurCheckpoint: ( state, { payload }: PayloadAction<{ filepath: string; content: string }>, @@ -632,6 +644,7 @@ export const sessionSlice = createSlice({ toolCallState.status = "canceled"; }, acceptToolCall: (state) => { + state.activeToolStreamId = undefined; const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -729,16 +742,6 @@ export const selectApplyStateByStreamId = createSelector( }, ); -export const selectLastEditToolApplyState = createSelector( - [ - (state: RootState) => state.session.codeBlockApplyStates.states, - (state: RootState) => state.session.lastApplyToolStreamId, - ], - (states, streamId) => { - return states.find((state) => state.streamId === streamId); - }, -); - export const { updateFileSymbols, setContextItemsAtIndex, @@ -776,7 +779,6 @@ export const { deleteSessionMetadata, setNewestCodeblocksForInput, cycleMode, - setLastToolApplyStreamId, } = sessionSlice.actions; export const { diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 190c25ccf..7ee80973f 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -3,7 +3,6 @@ import { ContextItem } from "core"; import { BuiltInToolNames } from "core/tools/builtIn"; import { EditToolArgs } from "core/tools/definitions/editFile"; import { resolveRelativePathInDir } from "core/util/ideUtils"; -import { v4 as uuidv4 } from "uuid"; import { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; @@ -11,7 +10,6 @@ import { acceptToolCall, cancelToolCall, setCalling, - setLastToolApplyStreamId, setToolCallOutput, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; @@ -44,17 +42,19 @@ export const callTool = createAsyncThunk( if ( toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile ) { - const newToolStreamId = uuidv4(); - dispatch(setLastToolApplyStreamId(newToolStreamId)); const args = JSON.parse( toolCallState.toolCall.function.arguments || "{}", ); try { + if (!state.session.activeToolStreamId) { + throw new Error("Invalid apply state"); + } await customGuiEditImpl( args, extra.ideMessenger, - newToolStreamId, + state.session.activeToolStreamId, defaultModel.title, + toolCallState.toolCallId, ); } catch (e) { errorMessage = "Failed to call edit tool"; @@ -85,7 +85,7 @@ export const callTool = createAsyncThunk( icon: "problems", name: "Tool Call Error", description: "Tool Call Failed", - content: `The tool call failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, + content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, hidden: false, }, ], @@ -114,23 +114,19 @@ async function customGuiEditImpl( ideMessenger: IIdeMessenger, streamId: string, modelTitle: string, + toolCallId: string, ) { const firstUriMatch = await resolveRelativePathInDir( args.filepath, ideMessenger.ide, ); if (!firstUriMatch) { - return [ - { - name: "Edit failure", - description: `editing ${args.filepath}`, - content: `Failed to edit ${args.filepath}: does not exist`, - }, - ]; + throw new Error(`${args.filepath} does not exist`); } ideMessenger.post("applyToFile", { streamId, text: args.new_contents, curSelectedModelTitle: modelTitle, + toolCallId, }); } From 05c0d85942c853d806ccb866122e25e97e8d015d Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:17:13 -0700 Subject: [PATCH 15/21] cleanup --- gui/src/components/mainInput/InputToolbar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 27c034721..20e40d9a9 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -106,7 +106,7 @@ function InputToolbar(props: InputToolbarProps) { props.disabled || isEditModeAndNoCodeToEdit || toolCallState?.status === "generated" || - activeToolCallStreamId; + !!activeToolCallStreamId; const toolsSupported = defaultModel && modelSupportsTools(defaultModel); From 05c092b3022913c7a879f4b2c739783cab8e4108 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:39:51 -0700 Subject: [PATCH 16/21] remove useeffect --- gui/src/components/Layout.tsx | 15 ------- gui/src/hooks/useSetup.ts | 62 +++++++++++++++------------- gui/src/redux/slices/sessionSlice.ts | 4 +- gui/src/redux/thunks/callTool.ts | 2 +- 4 files changed, 36 insertions(+), 47 deletions(-) diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 5b70f2e62..0f52d3d0b 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -12,7 +12,6 @@ import { newSession, selectIsInEditMode, setMode, - updateApplyState, } from "../redux/slices/sessionSlice"; import { setShowDialog } from "../redux/slices/uiSlice"; import { exitEditMode } from "../redux/thunks"; @@ -125,20 +124,6 @@ const Layout = () => { [], ); - useWebviewListener( - "updateApplyState", - async (state) => { - // dispatch( - // updateCurCheckpoint({ - // filepath: state.filepath, - // content: state.fileContent, - // }), - // ); - dispatch(updateApplyState(state)); - }, - [], - ); - useWebviewListener( "openOnboardingCard", async () => { diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 914b96089..25b1a7fc0 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useMemo, useRef } from "react"; +import { useCallback, useContext, useEffect, useRef } from "react"; import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; @@ -20,6 +20,7 @@ import { addContextItemsAtIndex, setInactive, setToolCallOutput, + updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; import { streamResponseAfterToolCall } from "../redux/thunks"; @@ -252,35 +253,38 @@ function useSetup() { const activeToolStreamId = useAppSelector( (store) => store.session.activeToolStreamId, ); - const applyStates = useAppSelector( - (store) => store.session.codeBlockApplyStates, + useWebviewListener( + "updateApplyState", + async (state) => { + // dispatch( + // updateCurCheckpoint({ + // filepath: state.filepath, + // content: state.fileContent, + // }), + // ); + dispatch(updateApplyState(state)); + if ( + activeToolStreamId && + state.streamId === activeToolStreamId[0] && + state.status === "closed" + ) { + const output: ContextItem = { + name: "Edit tool output", + content: "Completed edit", + description: "", + }; + dispatch(acceptToolCall()); + dispatch(setToolCallOutput([output])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: activeToolStreamId[1], + toolOutput: [output], + }), + ); + } + }, + [activeToolStreamId], ); - const activeToolApplyState = useMemo(() => { - if (!activeToolStreamId) { - return undefined; - } - return applyStates.states.find( - (state) => state.streamId && state.streamId === activeToolStreamId, - ); - }, [applyStates, activeToolStreamId]); - - useEffect(() => { - if (activeToolApplyState?.status === "closed") { - const output: ContextItem = { - name: "Edit tool output", - content: "Completed edit", - description: "", - }; - dispatch(acceptToolCall()); - dispatch(setToolCallOutput([output])); - dispatch( - streamResponseAfterToolCall({ - toolCallId: activeToolApplyState.toolCallId!, - toolOutput: [output], - }), - ); - } - }, [activeToolApplyState?.status]); } export default useSetup; diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index bf22a1858..1813f9af2 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -55,7 +55,7 @@ type SessionState = { curIndex: number; }; newestCodeblockForInput: Record; - activeToolStreamId?: string; + activeToolStreamId?: [string, string]; }; function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { @@ -379,7 +379,7 @@ export const sessionSlice = createSlice({ toolCallId: toolCallDelta.id, status: "streaming", }); - state.activeToolStreamId = streamId; + state.activeToolStreamId = [streamId, toolCallDelta.id]; } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 7ee80973f..b1cf85650 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -52,7 +52,7 @@ export const callTool = createAsyncThunk( await customGuiEditImpl( args, extra.ideMessenger, - state.session.activeToolStreamId, + state.session.activeToolStreamId[0], defaultModel.title, toolCallState.toolCallId, ); From c50fbbbb4f6d3afa1f6bad105b761ef647e964b1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 03:48:49 -0700 Subject: [PATCH 17/21] tool call id for instant apply --- extensions/vscode/src/extension/VsCodeMessenger.ts | 1 + gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 98fe8489b..05f307c55 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -213,6 +213,7 @@ export class VsCodeMessenger { diffLines, instant, data.streamId, + data.toolCallId, ); } else { const prompt = `The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`; diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 56263b0a1..2ff34d489 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -34,11 +34,12 @@ export function EditFile(props: EditToolCallProps) { disableManualApply={true} singleCodeblockStreamId={applyState?.streamId} /> - {isStreaming && applyState?.status === "streaming" && ( + {/* TODO better indicator of generation at bottom */} + {/* {isStreaming && applyState?.status === "streaming" && (
Generating...
- )} + )} */} {!isStreaming && applyState?.status === "done" && (
Date: Fri, 4 Apr 2025 13:14:44 -0700 Subject: [PATCH 18/21] fix apply for jetgrains --- .../continue/IdeProtocolClient.kt | 45 ++++++++++++++++++- .../editor/DiffStreamHandler.kt | 33 ++++++++++++-- .../editor/InlineEditAction.kt | 5 ++- .../markdown/StyledMarkdownPreview.tsx | 8 +--- gui/src/redux/thunks/callTool.ts | 6 ++- 5 files changed, 84 insertions(+), 13 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 95270f26b..75f393172 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -16,6 +16,7 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service +import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager @@ -423,11 +424,45 @@ class IdeProtocolClient( dataElement.toString(), ApplyToFileParams::class.java ) + val filepath = params.filepath - val editor = FileEditorManager.getInstance(project).selectedTextEditor + continuePluginService.sendToWebview("updateApplyState", mapOf( + "streamId" to params.streamId, + "status" to "streaming", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + + + fun closeStream () { + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to 0, + "streamId" to params.streamId, + "status" to "closed", + "fileContent" to params.text, + "toolCallId" to params.toolCallId, + "filepath" to filepath + )) + } + + var editor: Editor? = null; + +// if (!filepath.isNullOrEmpty()) { +// val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) +// if (virtualFile != null) { +//// ApplicationManager.getApplication().invokeAndWait { +// FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() +// editor = FileEditorManager.getInstance(project).selectedTextEditor +//// } +// } +// } else { +// } + editor = FileEditorManager.getInstance(project).selectedTextEditor if (editor == null) { ide.showToast(ToastType.ERROR, "No active editor to apply edits to") + closeStream() respond(null) return@launch } @@ -436,6 +471,7 @@ class IdeProtocolClient( WriteCommandAction.runWriteCommandAction(project) { editor.document.insertString(0, params.text) } + closeStream() respond(null) return@launch } @@ -481,6 +517,7 @@ class IdeProtocolClient( ToastType.ERROR, "Failed to fetch model configuration" ) } + closeStream() respond(null) return@launch } @@ -519,7 +556,11 @@ class IdeProtocolClient( editor, rif?.range?.start?.line ?: 0, rif?.range?.end?.line ?: (editor.document.lineCount - 1), - {}, {}) + {}, + {}, + params.streamId, + params.toolCallId + ) diffStreamService.register(diffStreamHandler, editor) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt index 55df303a8..f6cf5972f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/DiffStreamHandler.kt @@ -27,14 +27,15 @@ class DiffStreamHandler( private val startLine: Int, private val endLine: Int, private val onClose: () -> Unit, - private val onFinish: () -> Unit + private val onFinish: () -> Unit, + private val streamId: String?, + private val toolCallId: String? ) { private data class CurLineState( var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null ) private var curLine = CurLineState(startLine) - private var isRunning: Boolean = false private var hasAcceptedOrRejectedBlock: Boolean = false @@ -48,8 +49,26 @@ class DiffStreamHandler( initUnfinishedRangeHighlights() } + private fun sendUpdate(status: String) { + if(this.streamId == null) { + return + } + val virtualFile = getVirtualFile() + val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) + continuePluginService.sendToWebview("updateApplyState", mapOf( + "numDiffs" to this.diffBlocks.size, + "streamId" to this.streamId, + "status" to status, + "fileContent" to "not implemented", + "toolCallId" to this.toolCallId, + "filepath" to virtualFile?.url + )) + } + fun acceptAll() { - editor.markupModel.removeAllHighlighters() + editor.markupModel.removeAllHighlighters(); + sendUpdate("closed") + resetState() } @@ -62,6 +81,7 @@ class DiffStreamHandler( } else { undoChanges() } + sendUpdate("closed") resetState() } @@ -70,6 +90,7 @@ class DiffStreamHandler( input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String ) { isRunning = true + this.sendUpdate("streaming") val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java) val virtualFile = getVirtualFile() @@ -83,6 +104,7 @@ class DiffStreamHandler( if (response["done"] as? Boolean == true) { handleFinishedResponse() + sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done") return@request } @@ -133,7 +155,10 @@ class DiffStreamHandler( } if (diffBlocks.isEmpty()) { + sendUpdate("closed") onClose() + } else { + sendUpdate("done") } } @@ -144,6 +169,7 @@ class DiffStreamHandler( ) diffBlocks.add(diffBlock) + sendUpdate("streaming") return diffBlock } @@ -234,6 +260,7 @@ class DiffStreamHandler( undoManager.undo(fileEditor) } } + sendUpdate("done") } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index faaf7d058..fd910308d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -207,7 +207,10 @@ fun openInlineEdit(project: Project?, editor: Editor) { textArea.document.insertString(textArea.caretPosition, ", ", null) textArea.requestFocus() customPanelRef.get().finish() - }) + }, + null, + null + ) val diffStreamService = project.service() diffStreamService.register(diffStreamHandler, editor) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 52ede7cbd..d10a3dab7 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -17,7 +17,7 @@ import useUpdatingRef from "../../hooks/useUpdatingRef"; import { useAppSelector } from "../../redux/hooks"; import { selectUIConfig } from "../../redux/slices/configSlice"; import { getContextItemsFromHistory } from "../../redux/thunks/updateFileSymbols"; -import { getFontSize, isJetBrains } from "../../util"; +import { getFontSize } from "../../util"; import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; @@ -305,11 +305,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const language = getLanguageFromClassName(className); - // If we don't have a filepath show the more basic toolbar - // that is just action buttons on hover. - // We also use this in JB since we haven't yet implemented - // the logic forfileUri lazy apply. - if (!relativeFilePath || isJetBrains()) { + if (!relativeFilePath) { return ( Date: Fri, 4 Apr 2025 14:04:31 -0700 Subject: [PATCH 19/21] open new editor with file --- .../continue/IdeProtocolClient.kt | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 75f393172..d8905445e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -448,17 +448,15 @@ class IdeProtocolClient( var editor: Editor? = null; -// if (!filepath.isNullOrEmpty()) { -// val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) -// if (virtualFile != null) { -//// ApplicationManager.getApplication().invokeAndWait { -// FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() -// editor = FileEditorManager.getInstance(project).selectedTextEditor -//// } -// } -// } else { -// } - editor = FileEditorManager.getInstance(project).selectedTextEditor + if (!filepath.isNullOrEmpty()) { + val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() + } + } + } + editor = FileEditorManager.getInstance(project).selectedTextEditor if (editor == null) { ide.showToast(ToastType.ERROR, "No active editor to apply edits to") From 1c4ee082d4beba387742f30cc80bd5e914bdb08c Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 14:35:43 -0700 Subject: [PATCH 20/21] isGenerating logic fix --- .../StepContainerPreToolbar.tsx | 12 +----------- .../markdown/StyledMarkdownPreview.tsx | 18 +++++++++++++++--- gui/src/hooks/useSetup.ts | 16 ++++++++-------- gui/src/pages/gui/ToolCallDiv/EditFile.tsx | 1 + gui/src/redux/thunks/callTool.ts | 14 +++++++++++++- 5 files changed, 38 insertions(+), 23 deletions(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 375fd7ab8..f09ed1a9f 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -69,7 +69,6 @@ export default function StepContainerPreToolbar( props.expanded ?? (isInEditMode ? false : true), ); const [codeBlockContent, setCodeBlockContent] = useState(""); - const isStreaming = useAppSelector((state) => state.session.isStreaming); const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, @@ -79,15 +78,6 @@ export default function StepContainerPreToolbar( selectApplyStateByStreamId(state, props.codeBlockStreamId), ); - // This handles an edge case when the last node in the markdown syntax tree is a codeblock. - // In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if - // we are done generating based on whether the next node in the tree is not a codeblock. - // The tree parsing logic for Remark is defined on page load, so we can't access state - // during the actual tree parsing. - const isGeneratingCodeBlock = !isStreaming - ? false - : props.isGeneratingCodeBlock; - const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex; const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath); @@ -196,7 +186,7 @@ export default function StepContainerPreToolbar(
- {isGeneratingCodeBlock ? ( + {props.isGeneratingCodeBlock ? ( { + return props.itemIndex && props.itemIndex === history.length - 1; + }, [history.length, props.itemIndex]); + const isLastItemRef = useUpdatingRef(isLastItem); + + const isStreaming = useAppSelector((store) => store.session.isStreaming); + const isStreamingRef = useUpdatingRef(isStreaming); + const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( [], ); + useEffect(() => { if (props.singleCodeblockStreamId) { codeblockState.current = [ @@ -235,8 +245,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( node.data = node.data || {}; node.data.hProperties = node.data.hProperties || {}; - node.data.hProperties["data-isgeneratingcodeblock"] = - lastCodeNode === node; + node.data.hProperties["data-islastcodeblock"] = lastCodeNode === node; node.data.hProperties["data-codeblockcontent"] = node.value; if (node.meta) { @@ -318,7 +327,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( } const isGeneratingCodeBlock = - preChildProps["data-isgeneratingcodeblock"]; + preChildProps["data-islastcodeblock"] && + isLastItemRef.current && + !isStreamingRef.current; if (codeblockState.current[codeBlockIndex] === undefined) { codeblockState.current[codeBlockIndex] = { @@ -342,6 +353,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( codeBlockStreamId={ codeblockState.current[codeBlockIndex].streamId } + expanded={props.expandCodeblocks} disableManualApply={props.disableManualApply} > diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 25b1a7fc0..ded57ee08 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -3,7 +3,7 @@ import { VSC_THEME_COLOR_VARS } from "../components"; import { IdeMessengerContext } from "../context/IdeMessenger"; import { ConfigResult } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig, ContextItem } from "core"; +import { BrowserSerializedContinueConfig } from "core"; import { initializeProfilePreferencesThunk, selectProfileThunk, @@ -268,17 +268,17 @@ function useSetup() { state.streamId === activeToolStreamId[0] && state.status === "closed" ) { - const output: ContextItem = { - name: "Edit tool output", - content: "Completed edit", - description: "", - }; + // const output: ContextItem = { + // name: "Edit tool output", + // content: "Completed edit", + // description: "", + // }; dispatch(acceptToolCall()); - dispatch(setToolCallOutput([output])); + dispatch(setToolCallOutput([])); dispatch( streamResponseAfterToolCall({ toolCallId: activeToolStreamId[1], - toolOutput: [output], + toolOutput: [], }), ); } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 2ff34d489..80927e6e7 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -33,6 +33,7 @@ export function EditFile(props: EditToolCallProps) { source={src} disableManualApply={true} singleCodeblockStreamId={applyState?.streamId} + expandCodeblocks={false} /> {/* TODO better indicator of generation at bottom */} {/* {isStreaming && applyState?.status === "streaming" && ( diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 41557cb40..bf15e7ae8 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -11,6 +11,7 @@ import { cancelToolCall, setCalling, setToolCallOutput, + updateApplyState, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -61,6 +62,17 @@ export const callTool = createAsyncThunk( if (e instanceof Error) { errorMessage = e.message; } + if (state.session.activeToolStreamId?.[0]) { + dispatch( + updateApplyState({ + streamId: state.session.activeToolStreamId[0], + status: "closed", + toolCallId: toolCallState.toolCallId, + numDiffs: 0, + filepath: args.filepath, + }), + ); + } } } else { const result = await extra.ideMessenger.request("tools/call", { @@ -128,7 +140,7 @@ async function customGuiEditImpl( text: args.new_contents, curSelectedModelTitle: modelTitle, toolCallId, - filepath: firstUriMatch + filepath: firstUriMatch, }); if (apply.status === "error") { throw new Error(apply.error); From f2237c03994948e8df430d696954a2bc62cba61b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 4 Apr 2025 17:10:24 -0700 Subject: [PATCH 21/21] cleanup --- core/tools/callTool.ts | 4 +--- core/tools/implementations/createNewFile.ts | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 2a04cb828..c81a0a6e4 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -138,9 +138,7 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); - // Custom GUI handling for edit - // case BuiltInToolNames.EditExistingFile: - // return await editFileImpl(args, extras); + // Note: Custom GUI handling for edit case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.ExactSearch: diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index cf8746328..5a89141eb 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -12,7 +12,7 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => { const exists = await extras.ide.fileExists(resolvedFileUri); if (exists) { throw new Error( - `File ${args.filepath} already exists. Use the edit too to edit this file`, + `File ${args.filepath} already exists. Use the edit tool to edit this file`, ); } await extras.ide.writeFile(resolvedFileUri, args.contents);