diff --git a/core/index.d.ts b/core/index.d.ts index 4615b8a5a..158a27df0 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1143,6 +1143,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/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..c81a0a6e4 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -138,6 +138,7 @@ export async function callTool( switch (uri) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); + // Note: Custom GUI handling for edit 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..6ee5cee6b --- /dev/null +++ b/core/tools/definitions/editFile.ts @@ -0,0 +1,37 @@ +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", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + function: { + name: BuiltInToolNames.EditExistingFile, + description: + "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", "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/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/createNewFile.ts b/core/tools/implementations/createNewFile.ts index b5d5e6c1b..5a89141eb 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 tool 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 []; }; 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/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..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 @@ -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,43 @@ 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 if (editor == null) { ide.showToast(ToastType.ERROR, "No active editor to apply edits to") + closeStream() respond(null) return@launch } @@ -436,6 +469,7 @@ class IdeProtocolClient( WriteCommandAction.runWriteCommandAction(project) { editor.document.insertString(0, params.text) } + closeStream() respond(null) return@launch } @@ -481,6 +515,7 @@ class IdeProtocolClient( ToastType.ERROR, "Failed to fetch model configuration" ) } + closeStream() respond(null) return@launch } @@ -519,7 +554,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/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..05f307c55 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; @@ -211,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.`; @@ -232,6 +235,7 @@ export class VsCodeMessenger { undefined, rangeToApplyTo, data.text, + data.toolCallId, ); } }); diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index 5d364bf03..24003595a 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -46,7 +46,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/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/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 3d0a38cec..20e40d9a9 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/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/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx index c2f09a24a..ee46ccee8 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,17 @@ const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => { } return ( -
-
+
+
- - {getLastNPathParts(relativeFilepath, 1)} - {range && ` ${range}`} -
+ + {getLastNPathParts(relativeFilepath, 1)} + {range && ` ${range}`} +
); }; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 46fa90d68..f09ed1a9f 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, @@ -26,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}; @@ -38,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; @@ -52,42 +52,32 @@ 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; + disableManualApply?: 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( props.expanded ?? (isInEditMode ? false : true), ); const [codeBlockContent, setCodeBlockContent] = useState(""); - const isStreaming = useAppSelector((state) => state.session.isStreaming); const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, ); 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. - // 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); @@ -104,7 +94,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("applyToFile", { - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, filepath: fileUri, text: codeBlockContent, curSelectedModelTitle: defaultModel.title, @@ -135,19 +125,17 @@ 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(); - // } - // wasGeneratingRef.current = isGeneratingCodeBlock; - // }, [isGeneratingCodeBlock]); + // if (hasCompletedGenerating) { + // if (props.autoApply) { + // onClickApply(); + // } + // } + // }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]); async function onClickAcceptApply() { const fileUri = await inferResolvedUriFromRelativePath( @@ -156,7 +144,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("acceptDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } @@ -167,7 +155,7 @@ export default function StepContainerPreToolbar( ); ideMessenger.post("rejectDiff", { filepath: fileUri, - streamId: streamIdRef.current, + streamId: props.codeBlockStreamId, }); } @@ -183,44 +171,40 @@ export default function StepContainerPreToolbar( return ( - -
+ +
-
- -
+
- {isGeneratingCodeBlock && ( + {props.isGeneratingCodeBlock ? ( - )} - - {!isGeneratingCodeBlock && ( + ) : ( <> - {props.hideApply || - (isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( - - ) : ( - - ))} + {isTerminalCodeBlock(props.language, props.codeBlockContent) ? ( + + ) : ( + + )} )}
diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index bc60451bf..6af2f68d5 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"; @@ -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"; @@ -126,6 +126,9 @@ interface StyledMarkdownPreviewProps { scrollLocked?: boolean; itemIndex?: number; useParentBackgroundColor?: boolean; + disableManualApply?: boolean; + singleCodeblockStreamId?: string; + expandCodeblocks?: boolean; } const HLJS_LANGUAGE_CLASSNAME_PREFIX = "language-"; @@ -192,6 +195,29 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( }, [props.itemIndex, history, allSymbols]); const pastFileInfoRef = useUpdatingRef(pastFileInfo); + const isLastItem = useMemo(() => { + 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 = [ + { + streamId: props.singleCodeblockStreamId, + isGenerating: false, + }, + ]; + } + }, [props.singleCodeblockStreamId]); + const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ remarkTables, @@ -215,8 +241,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) { @@ -278,8 +303,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 ; @@ -287,11 +310,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 ( diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index d90259a9b..ded57ee08 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -16,10 +16,14 @@ import { } from "../redux/slices/configSlice"; import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { + acceptToolCall, addContextItemsAtIndex, setInactive, + setToolCallOutput, + updateApplyState, } 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"; @@ -245,6 +249,42 @@ function useSetup() { }, [defaultModel], ); + + const activeToolStreamId = useAppSelector( + (store) => store.session.activeToolStreamId, + ); + 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([])); + dispatch( + streamResponseAfterToolCall({ + toolCallId: activeToolStreamId[1], + toolOutput: [], + }), + ); + } + }, + [activeToolStreamId], + ); } export default useSetup; diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index bca805f45..45396dc23 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; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx new file mode 100644 index 000000000..80927e6e7 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -0,0 +1,54 @@ +import { getMarkdownLanguageTagForFile } from "core/util"; +import { useMemo } from "react"; +import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +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 isStreaming = useAppSelector((state) => state.session.isStreaming); + const states = useAppSelector((store) => store.session.codeBlockApplyStates); + + const applyState = useMemo(() => { + return states.states.find( + (state) => state.toolCallId && state.toolCallId === props.toolCallId, + ); + }, [states, props.toolCallId]); + + if (!props.relativeFilePath) { + return null; + } + + return ( + <> + + {/* TODO better indicator of generation at bottom */} + {/* {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 52b41f505..55ed79e2a 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,22 @@ 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 ( ; }; @@ -353,16 +355,32 @@ 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.id && + toolCallDelta.function?.name === + BuiltInToolNames.EditExistingFile + ) { + const streamId = uuidv4(); + state.codeBlockApplyStates.states.push({ + streamId, + toolCallId: toolCallDelta.id, + status: "streaming", + }); + state.activeToolStreamId = [streamId, toolCallDelta.id]; + } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -626,6 +644,7 @@ export const sessionSlice = createSlice({ toolCallState.status = "canceled"; }, acceptToolCall: (state) => { + state.activeToolStreamId = undefined; const toolCallState = findCurrentToolCall(state.history); if (!toolCallState) return; @@ -717,7 +736,7 @@ 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); diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 5f76390f2..c1d38f2ea 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -44,6 +44,7 @@ export const uiSlice = createSlice({ ttsActive: false, toolSettings: { [BuiltInToolNames.ReadFile]: "allowedWithoutPermission", + [BuiltInToolNames.EditExistingFile]: "allowedWithPermission", [BuiltInToolNames.CreateNewFile]: "allowedWithPermission", [BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission", [BuiltInToolNames.ViewSubdirectory]: "allowedWithoutPermission", diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index 34ae00390..bf15e7ae8 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -1,4 +1,9 @@ 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 { IIdeMessenger } from "../../context/IdeMessenger"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectDefaultModel } from "../slices/configSlice"; import { @@ -6,6 +11,7 @@ import { cancelToolCall, setCalling, setToolCallOutput, + updateApplyState, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -31,28 +37,59 @@ 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 args = JSON.parse( + toolCallState.toolCall.function.arguments || "{}", ); - unwrapResult(response); + try { + if (!state.session.activeToolStreamId) { + throw new Error("Invalid apply state"); + } + await customGuiEditImpl( + args, + extra.ideMessenger, + state.session.activeToolStreamId[0], + defaultModel.title, + toolCallState.toolCallId, + ); + } catch (e) { + errorMessage = "Failed to call edit tool"; + 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", { + 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,13 +97,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: `${toolCallState.toolCall.function.name} 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 }, ); + +async function customGuiEditImpl( + args: EditToolArgs, + ideMessenger: IIdeMessenger, + streamId: string, + modelTitle: string, + toolCallId: string, +) { + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + ideMessenger.ide, + ); + if (!firstUriMatch) { + throw new Error(`${args.filepath} does not exist`); + } + const apply = await ideMessenger.request("applyToFile", { + streamId, + text: args.new_contents, + curSelectedModelTitle: modelTitle, + toolCallId, + filepath: firstUriMatch, + }); + if (apply.status === "error") { + throw new Error(apply.error); + } +}