From e44072620782ee0e9e0e656a6066bf6bb4d3113d Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 19 Nov 2024 12:02:11 -0800 Subject: [PATCH 01/13] WIP: add "Code to edit" section --- core/protocol/ideWebview.ts | 7 +- extensions/vscode/package.json | 9 +- extensions/vscode/src/commands.ts | 54 +++-- gui/src/App.tsx | 2 +- gui/src/components/FileIcon.tsx | 13 +- gui/src/components/Layout.tsx | 17 +- gui/src/components/mainInput/TipTapEditor.tsx | 3 - .../markdown/CodeSnippetPreview.tsx | 85 +++---- .../StepContainerPreToolbar.tsx | 2 +- gui/src/pages/Edit/CodeToEdit.tsx | 76 +++++++ gui/src/pages/Edit/CodeToEditListItem.tsx | 77 +++++++ gui/src/pages/Edit/Edit.tsx | 133 +++++++++++ gui/src/pages/edit/EditInputHeader.tsx | 114 ---------- gui/src/pages/edit/index.tsx | 212 +----------------- gui/src/redux/slices/editModeState.ts | 29 ++- 15 files changed, 414 insertions(+), 419 deletions(-) create mode 100644 gui/src/pages/Edit/CodeToEdit.tsx create mode 100644 gui/src/pages/Edit/CodeToEditListItem.tsx create mode 100644 gui/src/pages/Edit/Edit.tsx delete mode 100644 gui/src/pages/edit/EditInputHeader.tsx diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index c833c3a7a..2ef3c9e06 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -54,10 +54,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "edit/escape": [undefined, void]; }; -export interface EditModeArgs { - highlightedCode: RangeInFileWithContents; -} - export type EditStatus = | "not-started" | "streaming" @@ -98,6 +94,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { }, void, ]; + addRIFToCodeToEdit: [RangeInFileWithContents, void]; navigateTo: [{ path: string; toggle?: boolean }, void]; addModel: [undefined, void]; @@ -118,7 +115,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { openOnboardingCard: [undefined, void]; applyCodeFromChat: [undefined, void]; updateApplyState: [ApplyState, void]; - startEditMode: [EditModeArgs, void]; setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void]; exitEditMode: [undefined, void]; + focusEdit: [undefined, void]; }; diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 697bf61c1..c4741e44d 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -200,7 +200,7 @@ "group": "Continue" }, { - "command": "continue.edit", + "command": "continue.focusEdit", "category": "Continue", "title": "Edit code with natural language", "group": "Continue" @@ -369,10 +369,15 @@ "key": "alt+ctrl+n" }, { - "command": "continue.edit", + "command": "continue.focusEdit", "mac": "cmd+i", "key": "ctrl+i" }, + { + "command": "continue.focusEditWithoutClear", + "mac": "cmd+shift+i", + "key": "ctrl+shift+i" + }, { "command": "continue.exitEditMode", "mac": "escape", diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 6847238e3..be3ff12ca 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -138,7 +138,6 @@ async function addHighlightedCodeToContext( async function addEntireFileToContext( filepath: vscode.Uri, - edit: boolean, webviewProtocol: VsCodeWebviewProtocol | undefined, ) { // If a directory, add all files in the directory @@ -149,7 +148,6 @@ async function addEntireFileToContext( if (type === vscode.FileType.File) { addEntireFileToContext( vscode.Uri.joinPath(filepath, filename), - edit, webviewProtocol, ); } @@ -455,42 +453,53 @@ const commandsMap: ( void addHighlightedCodeToContext(sidebar.webviewProtocol); } }, - "continue.edit": async () => { - captureCommandTelemetry("edit"); + // TODO + "continue.focusEditWithoutClear": async () => {}, + "continue.focusEdit": async () => { + captureCommandTelemetry("focusEdit"); focusGUI(); + sidebar.webviewProtocol?.request("focusEdit", undefined); + const editor = vscode.window.activeTextEditor; + if (!editor) { return; } - const existingDiff = await verticalDiffManager.getHandlerForFile( + const existingDiff = verticalDiffManager.getHandlerForFile( editor.document.fileName, ); - if (!existingDiff) { - // If there's a diff currently being applied, then we just toggle focus back to the input - editDecorationManager.setDecoration( - editor, - new vscode.Range(editor.selection.start, editor.selection.end), - ); - const highlightedCode = getCurrentlyHighlightedCode(true)!; - await sidebar.webviewProtocol?.request("startEditMode", { - highlightedCode, - }); + // If there's a diff currently being applied, then we just toggle focus back to the input + if (existingDiff) { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + return; + } + + editDecorationManager.setDecoration( + editor, + new vscode.Range(editor.selection.start, editor.selection.end), + ); + + const rangeInFileWithContents = getCurrentlyHighlightedCode(true); + + if (rangeInFileWithContents) { + sidebar.webviewProtocol?.request( + "addRIFToCodeToEdit", + rangeInFileWithContents, + ); // Un-select the current selection editor.selection = new vscode.Selection( editor.selection.anchor, editor.selection.anchor, ); - - setTimeout(() => { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); - }, 30); - } else { - sidebar.webviewProtocol?.request("focusContinueInput", undefined); } + + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); }, "continue.exitEditMode": async () => { captureCommandTelemetry("exitEditMode"); @@ -705,12 +714,11 @@ const commandsMap: ( for await (const filepath of walkDirAsync(uri.fsPath, ide)) { addEntireFileToContext( uriFromFilePath(filepath), - false, sidebar.webviewProtocol, ); } } else { - addEntireFileToContext(uri, false, sidebar.webviewProtocol); + addEntireFileToContext(uri, sidebar.webviewProtocol); } } }, diff --git a/gui/src/App.tsx b/gui/src/App.tsx index ca807a876..1e34e6e15 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -8,7 +8,7 @@ import useSubmenuContextProviders from "./hooks/useSubmenuContextProviders"; import { useVscTheme } from "./hooks/useVscTheme"; import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; import ConfigErrorPage from "./pages/config-error"; -import Edit from "./pages/edit"; +import Edit from "./pages/Edit"; import ErrorPage from "./pages/error"; import Chat from "./pages/gui"; import History from "./pages/history"; diff --git a/gui/src/components/FileIcon.tsx b/gui/src/components/FileIcon.tsx index d1be4fbbf..8117ce734 100644 --- a/gui/src/components/FileIcon.tsx +++ b/gui/src/components/FileIcon.tsx @@ -1,15 +1,12 @@ import DOMPurify from "dompurify"; import { themeIcons } from "seti-file-icons"; -const FileIcon = ({ - filename, - height, - width, -}: { +export interface FileIconProps { filename: string; height: string; width: string; -}) => { +} +export default function FileIcon({ filename, height, width }: FileIconProps) { const filenameParts = filename.includes(" (") ? filename.split(" ") : [filename, ""]; @@ -39,6 +36,4 @@ const FileIcon = ({ style={{ width: width, height: height, fill: color, flexShrink: 0 }} /> ); -}; - -export default FileIcon; +} diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 5879bd2e0..cd7155540 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -10,7 +10,8 @@ import { useConfigError } from "../redux/hooks"; import { setEditDone, setEditStatus, - startEditMode, + addRIFToCodeToEdit, + focusEdit, } from "../redux/slices/editModeState"; import { setShowDialog } from "../redux/slices/uiStateSlice"; import { @@ -190,14 +191,22 @@ const Layout = () => { ); useWebviewListener( - "startEditMode", - async (args) => { - dispatch(startEditMode(args)); + "focusEdit", + async (payload) => { + dispatch(focusEdit(payload)); navigate("/edit"); }, [navigate], ); + useWebviewListener( + "addRIFToCodeToEdit", + async (payload) => { + dispatch(addRIFToCodeToEdit(payload)); + }, + [navigate], + ); + useWebviewListener("setEditStatus", async ({ status, fileAfterEdit }) => { dispatch(setEditStatus({ status, fileAfterEdit })); }); diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 6da867b40..821258cf5 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -158,7 +158,6 @@ interface TipTapEditorProps { toolbarOptions?: ToolbarOptions; border?: string; placeholder?: string; - header?: React.ReactNode; historyKey: string; } @@ -829,8 +828,6 @@ function TipTapEditor(props: TipTapEditorProps) { event.preventDefault(); }} > -
{props.header}
- void; borderColor?: string; + hideHeader?: boolean; } const MAX_PREVIEW_HEIGHT = 300; @@ -74,47 +75,49 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { borderColor={props.borderColor} className="find-widget-skip" > - { - if (props.item.id.providerTitle === "file") { - ideMessenger.post("showFile", { - filepath: props.item.description, - }); - } else if (props.item.id.providerTitle === "code") { - const lines = props.item.name - .split("(")[1] - .split(")")[0] - .split("-"); - ideMessenger.ide.showLines( - props.item.description.split(" ")[0], - parseInt(lines[0]) - 1, - parseInt(lines[1]) - 1, - ); - } else { - ideMessenger.post("showVirtualFile", { - content, - name: props.item.name, - }); - } - }} - > -
- - {props.item.name} -
-
- { - e.stopPropagation(); - props.onDelete?.(); - }} - > - - -
-
+ {!props.hideHeader && ( + { + if (props.item.id.providerTitle === "file") { + ideMessenger.post("showFile", { + filepath: props.item.description, + }); + } else if (props.item.id.providerTitle === "code") { + const lines = props.item.name + .split("(")[1] + .split(")")[0] + .split("-"); + ideMessenger.ide.showLines( + props.item.description.split(" ")[0], + parseInt(lines[0]) - 1, + parseInt(lines[1]) - 1, + ); + } else { + ideMessenger.post("showVirtualFile", { + content, + name: props.item.name, + }); + } + }} + > +
+ + {props.item.name} +
+
+ { + e.stopPropagation(); + props.onDelete?.(); + }} + > + + +
+
+ )}
diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx new file mode 100644 index 000000000..b8df8ac24 --- /dev/null +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -0,0 +1,76 @@ +import { InformationCircleIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { useContext } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { removeEntryFromCodeToEdit } from "../../redux/slices/editModeState"; +import { RootState } from "../../redux/store"; +import CodeToEditListItem from "./CodeToEditListItem"; +import { RangeInFileWithContents } from "core/commands/util"; +import { vscEditorBackground } from "../../components"; + +export default function WorkingSet() { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const editModeState = useSelector((state: RootState) => state.editModeState); + + const hasCodeToEdit = editModeState.codeToEdit.length > 0; + + function onDelete(rif: RangeInFileWithContents) { + dispatch(removeEntryFromCodeToEdit(rif)); + } + + function onClickAddFileToCodeToEdit() {} + + function onClickCodeToEditItem(rif: RangeInFileWithContents) { + const { filepath, range } = editModeState.codeToEdit.find( + (workingSetRIF) => workingSetRIF === rif, + ); + + ideMessenger.ide.showLines(filepath, range.start.line, range.end.line); + } + + const codeToEditItems = editModeState.codeToEdit.map((rif) => ( + + )); + + return ( +
+
+
+ Code to edit + +
+ + + + Add file + +
+ + {hasCodeToEdit ? ( +
    + {codeToEditItems} +
+ ) : ( + + + Add a file to get started + + )} +
+ ); +} diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/Edit/CodeToEditListItem.tsx new file mode 100644 index 000000000..30cf0266e --- /dev/null +++ b/gui/src/pages/Edit/CodeToEditListItem.tsx @@ -0,0 +1,77 @@ +import { RangeInFileWithContents } from "core/commands/util"; +import FileIcon from "../../components/FileIcon"; +import { + ChevronDownIcon, + ChevronUpIcon, + XMarkIcon, +} from "@heroicons/react/24/outline"; +import { useState } from "react"; +import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview"; +import { getMarkdownLanguageTagForFile } from "core/util"; + +export interface CodeToEditListItemProps { + rif: RangeInFileWithContents; + onDelete: (rif: RangeInFileWithContents) => void; + onClick: (rif: RangeInFileWithContents) => void; +} + +export default function CodeToEditListItem({ + rif, + onDelete, + onClick, +}: CodeToEditListItemProps) { + const [showCodeSnippet, setShowCodeSnippet] = useState(false); + + const filepath = rif.filepath.split("/").pop() || rif.filepath; + const title = `${filepath} (${rif.range.start.line + 1} - ${rif.range.end.line + 1})`; + + const source = + "```" + + getMarkdownLanguageTagForFile(rif.filepath) + + "\n" + + rif.contents + + "\n" + + "```"; + + return ( +
  • onClick(rif)} + > +
    +
    + + {title} +
    +
    + {showCodeSnippet ? ( + { + e.stopPropagation(); + setShowCodeSnippet(false); + }} + className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" + /> + ) : ( + { + e.stopPropagation(); + setShowCodeSnippet(true); + }} + className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" + /> + )} + { + e.stopPropagation(); + onDelete(rif); + }} + className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" + /> +
    +
    + + {showCodeSnippet && } +
  • + ); +} diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx new file mode 100644 index 000000000..0a92b09b2 --- /dev/null +++ b/gui/src/pages/Edit/Edit.tsx @@ -0,0 +1,133 @@ +import { ArrowLeftIcon } from "@heroicons/react/24/outline"; +import { Editor, JSONContent } from "@tiptap/core"; +import { InputModifiers } from "core"; +import { stripImages } from "core/llm/images"; +import { useContext, useEffect } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { useNavigate } from "react-router-dom"; +import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; +import resolveEditorContent from "../../components/mainInput/resolveInput"; +import TipTapEditor from "../../components/mainInput/TipTapEditor"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { setEditDone, submitEdit } from "../../redux/slices/editModeState"; +import { RootState } from "../../redux/store"; +import CodeToEdit from "./CodeToEdit"; + +const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ + "codebase", + "tree", + "open", + "web", + "diff", + "folder", + "search", + "debugger", + "repo-map", +]; + +export default function Edit() { + const dispatch = useDispatch(); + const navigate = useNavigate(); + const ideMessenger = useContext(IdeMessengerContext); + const editModeState = useSelector((state: RootState) => state.editModeState); + const availableContextProviders = useSelector( + (store: RootState) => store.state.config.contextProviders, + ); + + const applyState = useSelector( + (store: RootState) => + store.state.applyStates.find((state) => state.streamId === "edit") + ?.status ?? "closed", + ); + + useEffect(() => { + if (editModeState.editStatus === "done") { + ideMessenger.post("edit/escape", undefined); + navigate("/"); + } + }, [editModeState.editStatus]); + + useEffect(() => { + if (applyState === "closed" && editModeState.editStatus === "accepting") { + dispatch(setEditDone()); + } + }, [applyState, editModeState.editStatus]); + + const isStreaming = + editModeState.editStatus === "streaming" || + editModeState.editStatus === "accepting"; + + const toolbarOptions = { + hideAddContext: true, + hideImageUpload: true, + hideUseCodebase: true, + hideSelectModel: false, + enterText: isStreaming ? "Retry" : "Edit", + }; + + const filteredContextProviders = availableContextProviders.filter( + (provider) => !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), + ); + + const handleEditorEnter = async ( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + ) => { + const [contextItems, __, userInstructions] = await resolveEditorContent( + editorState, + { + noContext: true, + useCodebase: false, + }, + ideMessenger, + [], + ); + + const prompt = [ + ...contextItems.map((item) => item.content), + stripImages(userInstructions), + ].join("\n\n"); + + ideMessenger.post("edit/sendPrompt", { + prompt, + range: editModeState.highlightedCode, + }); + + dispatch(submitEdit(prompt)); + editor.commands.selectTextblockEnd(); + }; + + const handleBackClick = () => { + dispatch(setEditDone()); + }; + + return ( +
    +
    +
    + + +
    +
    + +
    + + + Back to Chat + +
    +
    + ); +} diff --git a/gui/src/pages/edit/EditInputHeader.tsx b/gui/src/pages/edit/EditInputHeader.tsx deleted file mode 100644 index 00695e66b..000000000 --- a/gui/src/pages/edit/EditInputHeader.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { getBasename } from "core/util"; -import { useContext, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import FileIcon from "../../components/FileIcon"; -import HeaderButtonWithToolTip from "../../components/gui/HeaderButtonWithToolTip"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setEditDone, setEditStatus } from "../../redux/slices/editModeState"; -import { RootState } from "../../redux/store"; - -interface EditInputHeaderParams {} - -/** - * @description This is a class that represents an edit input header. - */ -export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) { - const dispatch = useDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const editModeState = useSelector((state: RootState) => state.editModeState); - - const [showCode, setShowCode] = useState(false); - - function onClick() { - ideMessenger.ide.showLines( - editModeState.highlightedCode.filepath, - editModeState.highlightedCode.range.start.line, - editModeState.highlightedCode.range.end.line, - ); - setShowCode(!showCode); - } - - async function showFullDiff() { - await ideMessenger.ide.showDiff( - editModeState.highlightedCode.filepath, - editModeState.fileAfterEdit, - 0, - ); - dispatch(setEditStatus({ status: "accepting:full-diff" })); - } - - return ( - <> -
    -
    -
    - - {getBasename(editModeState.highlightedCode.filepath)} ( - {editModeState.highlightedCode.range.start.line}- - {editModeState.highlightedCode.range.end.line}) -
    - {editModeState.editStatus === "accepting" || - editModeState.editStatus === "accepting:full-diff" ? ( -
    - {/* {editModeState.editStatus === "accepting" ? ( - <> - - - - - N diffs remaining - - - ) : ( -
    hi
    - )} */} - -
    - - { - ideMessenger.post("edit/acceptReject", { - accept: false, - onlyFirst: false, - filepath: editModeState.highlightedCode.filepath, - }); - dispatch(setEditDone()); - }} - > - - - { - ideMessenger.post("edit/acceptReject", { - accept: true, - onlyFirst: false, - filepath: editModeState.highlightedCode.filepath, - }); - dispatch(setEditDone()); - }} - > - -
    -
    - ) : null} -
    -
    - - ); -} diff --git a/gui/src/pages/edit/index.tsx b/gui/src/pages/edit/index.tsx index c601c9650..d1c8752c8 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -1,211 +1 @@ -import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import { Editor, JSONContent } from "@tiptap/core"; -import { InputModifiers } from "core"; -import { stripImages } from "core/llm/images"; -import { useContext, useEffect } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { useNavigate } from "react-router-dom"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscForeground, -} from "../../components"; -import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; -import resolveEditorContent from "../../components/mainInput/resolveInput"; -import TipTapEditor from "../../components/mainInput/TipTapEditor"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setEditDone, submitEdit } from "../../redux/slices/editModeState"; -import { RootState } from "../../redux/store"; -import { EditInputHeader } from "./EditInputHeader"; - -const TopDiv = styled.div` - overflow-y: auto; - height: 100%; - scrollbar-width: none; - &::-webkit-scrollbar { - display: none; - } -`; - -const ToolbarDiv = styled.div` - padding: 8px; - border-bottom: 1px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - display: flex; -`; - -const AcceptRejectButton = styled.div<{ - backgroundColor: string; - disabled: boolean; -}>` - border: none; - background-color: ${(props) => props.backgroundColor}; - border-radius: ${defaultBorderRadius}; - padding: 8px 16px; - color: ${vscForeground}; - width: 100%; - text-align: center; - margin: 0 8px; - transition: filter 0.2s ease; - - opacity: ${(props) => (props.disabled ? 0.5 : 1)}; - cursor: ${(props) => (props.disabled ? "default" : "pointer")}; - - &:hover { - filter: ${(props) => (props.disabled ? "none" : "brightness(1.2)")}; - } -`; - -const EditHistoryDiv = styled.div` - display: flex; - align-items: center; - width: 100%; - padding: 8px 16px; - - cursor: pointer; - - border: 1px solid ${lightGray}55; - border-radius: ${defaultBorderRadius}; - - &:hover { - background-color: ${lightGray}22; - } -`; - -const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ - "codebase", - "tree", - "open", - "web", - "diff", - "folder", - "search", - "debugger", - "repo-map", -]; - -function Edit() { - const dispatch = useDispatch(); - const navigate = useNavigate(); - const ideMessenger = useContext(IdeMessengerContext); - const editModeState = useSelector((state: RootState) => state.editModeState); - const availableContextProviders = useSelector( - (store: RootState) => store.state.config.contextProviders, - ); - useEffect(() => {}, []); - - // Reusing the applyState logic which was just the fastest way to get this working - useEffect(() => { - if (editModeState.editStatus === "done") { - ideMessenger.post("edit/escape", undefined); - navigate("/"); - } - }, [editModeState.editStatus]); - - const applyState = useSelector( - (store: RootState) => - store.state.applyStates.find((state) => state.streamId === "edit") - ?.status ?? "closed", - ); - - useEffect(() => { - if (applyState === "closed" && editModeState.editStatus === "accepting") { - dispatch(dispatch(setEditDone())); - } - }, [applyState, editModeState.editStatus]); - - return ( - <> - -
    - {/* Edit session history */} - {/* {editModeState.previousInputs.length > 0 && ( -
    - {editModeState.previousInputs.map((input, index) => ( -
    - -
    {stripImages(input)}
    - -
    -
    - ))} -
    - )} */} - -
    - } - toolbarOptions={{ - hideAddContext: true, - hideImageUpload: true, - hideUseCodebase: true, - hideSelectModel: false, - enterText: ["streaming", "accepting"].includes( - editModeState.editStatus, - ) - ? "Retry" - : "Edit", - }} - placeholder={ - ["streaming", "accepting"].includes(editModeState.editStatus) - ? "Describe how to modify code" - : "Describe how to modify code" - } - border={`1px solid #aa0`} - availableContextProviders={availableContextProviders.filter( - (provider) => - !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), - )} - historyKey="edit" - availableSlashCommands={[]} - isMainInput={true} - onEnter={async function ( - editorState: JSONContent, - modifiers: InputModifiers, - editor: Editor, - ): Promise { - const [contextItems, __, userInstructions] = - await resolveEditorContent( - editorState, - { - noContext: true, - useCodebase: false, - }, - ideMessenger, - [], - ); - - const prompt = [ - ...contextItems.map((item) => item.content), - stripImages(userInstructions), - ].join("\n\n"); - ideMessenger.post("edit/sendPrompt", { - prompt, - range: editModeState.highlightedCode, - }); - dispatch(submitEdit(prompt)); - - // Move cursor to end of editor (it's already focused) - editor.commands.selectTextblockEnd(); - }} - > -
    -
    - -
    - { - dispatch(setEditDone()); - }} - className="mr-auto flex items-center gap-2" - > - - Back to Chat - -
    -
    - - ); -} -export default Edit; +export { default } from "./Edit"; diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index 38091ccbf..f39814dfd 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -1,26 +1,35 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { MessageContent } from "core"; import { RangeInFileWithContents } from "core/commands/util"; -import { EditModeArgs, EditStatus } from "core/protocol/ideWebview"; +import { EditStatus } from "core/protocol/ideWebview"; interface EditModeState { - highlightedCode?: RangeInFileWithContents; editStatus: EditStatus; previousInputs: MessageContent[]; fileAfterEdit?: string; + codeToEdit: RangeInFileWithContents[]; } const initialState: EditModeState = { editStatus: "not-started", previousInputs: [], + codeToEdit: [], }; export const editModeStateSlice = createSlice({ name: "editModeState", initialState, reducers: { - startEditMode: (state, { payload }: PayloadAction) => { - state.highlightedCode = payload.highlightedCode; + addRIFToCodeToEdit: ( + state, + { payload }: PayloadAction, + ) => { + state.codeToEdit.push(payload); + state.editStatus = "not-started"; + state.previousInputs = []; + state.fileAfterEdit = undefined; + }, + focusEdit: (state) => { state.editStatus = "not-started"; state.previousInputs = []; state.fileAfterEdit = undefined; @@ -29,6 +38,14 @@ export const editModeStateSlice = createSlice({ state.previousInputs.push(payload); state.editStatus = "streaming"; }, + removeEntryFromCodeToEdit: ( + state, + { payload }: PayloadAction, + ) => { + state.codeToEdit = state.codeToEdit.filter( + (entry) => entry.toString() !== payload.toString(), + ); + }, setEditStatus: ( state, { @@ -77,10 +94,12 @@ export const editModeStateSlice = createSlice({ }); export const { - startEditMode, + addRIFToCodeToEdit, setEditStatus, addPreviousInput, setEditDone, submitEdit, + removeEntryFromCodeToEdit, + focusEdit, } = editModeStateSlice.actions; export default editModeStateSlice.reducer; From fe21a2645a5275ea1c75f32eb0877a4b0141e9d4 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 20 Nov 2024 13:41:13 -0800 Subject: [PATCH 02/13] WIP: add prompt preamble for MFE --- gui/package-lock.json | 6 + gui/package.json | 1 + gui/src/components/Layout.tsx | 4 + .../StepContainer/AcceptRejectAllButtons.tsx | 32 +++- .../StepContainer/MultifileEditActions.tsx | 2 + gui/src/components/gui/Tooltip.tsx | 3 +- .../components/mainInput/MentionExtension.ts | 33 ++-- gui/src/components/mainInput/TipTapEditor.tsx | 65 ++++++-- gui/src/hooks/useChatHandler.ts | 16 +- gui/src/pages/Edit/CodeToEdit.tsx | 42 ++--- gui/src/pages/Edit/CodeToEditListItem.tsx | 37 +++-- gui/src/pages/Edit/Edit.tsx | 155 ++++++++++++++++-- gui/src/pages/Edit/getMultifileEditPrompt.ts | 56 +++++++ gui/src/redux/slices/editModeState.ts | 11 +- gui/tailwind.config.cjs | 8 +- 15 files changed, 373 insertions(+), 98 deletions(-) create mode 100644 gui/src/pages/Edit/getMultifileEditPrompt.ts diff --git a/gui/package-lock.json b/gui/package-lock.json index 7d5bf06c9..3be234fb8 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -56,6 +56,7 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", + "tailwind-scrollbar-hide": "^1.1.7", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", @@ -8983,6 +8984,11 @@ "node": ">=10.0.0" } }, + "node_modules/tailwind-scrollbar-hide": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/tailwind-scrollbar-hide/-/tailwind-scrollbar-hide-1.1.7.tgz", + "integrity": "sha512-X324n9OtpTmOMqEgDUEA/RgLrNfBF/jwJdctaPZDzB3mppxJk7TLIDmOreEDm1Bq4R9LSPu4Epf8VSdovNU+iA==" + }, "node_modules/tailwindcss": { "version": "3.4.12", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.12.tgz", diff --git a/gui/package.json b/gui/package.json index ef77ac910..b0fe1809d 100644 --- a/gui/package.json +++ b/gui/package.json @@ -64,6 +64,7 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", + "tailwind-scrollbar-hide": "^1.1.7", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index cd7155540..14cd63249 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -15,6 +15,7 @@ import { } from "../redux/slices/editModeState"; import { setShowDialog } from "../redux/slices/uiStateSlice"; import { + setIsInMultifileEdit, updateApplyState, updateCurCheckpoint, } from "../redux/slices/stateSlice"; @@ -193,6 +194,9 @@ const Layout = () => { useWebviewListener( "focusEdit", async (payload) => { + // TODO: Move into edit state + dispatch(setIsInMultifileEdit(true)); + dispatch(focusEdit(payload)); navigate("/edit"); }, diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index a1e7b28f6..6a2574bc0 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -5,12 +5,15 @@ import { ApplyState } from "core/protocol/ideWebview"; export interface AcceptRejectAllButtonsProps { pendingApplyStates: ApplyState[]; + onAcceptOrReject?: () => void; } export default function AcceptRejectAllButtons({ pendingApplyStates, + onAcceptOrReject, }: AcceptRejectAllButtonsProps) { const ideMessenger = useContext(IdeMessengerContext); + const hasSinglePendingApplyStates = pendingApplyStates.length === 1; async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") { for (const { filepath, streamId } of pendingApplyStates) { @@ -19,8 +22,11 @@ export default function AcceptRejectAllButtons({ streamId, }); } - } + if (onAcceptOrReject) { + onAcceptOrReject(); + } + } return (
    ); diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/MultifileEditActions.tsx index 5fb7122df..603d6e15a 100644 --- a/gui/src/components/StepContainer/MultifileEditActions.tsx +++ b/gui/src/components/StepContainer/MultifileEditActions.tsx @@ -35,6 +35,8 @@ export default function MultifileEditActions({ const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; const hasPendingApplies = pendingApplyStates.length > 0; + console.log({ isCurCheckpoint, curCheckpointIndex, index }); + return (
    ({ ]; }, suggestion: { - char: "@", - pluginKey: MentionPluginKey, command: ({ editor, range, props }) => { // increase range.to by one when the next node is of type "text" // and starts with a space character @@ -40,20 +38,23 @@ export const Mention = Node.create({ range.to += 1; } - editor - .chain() - .focus() - .insertContentAt(range, [ - { - type: this.name, - attrs: props, - }, - { - type: "text", - text: " ", - }, - ]) - .run(); + // For # symbol mentions, we add the file to the "Code to edit" rather than the editor + const text = editor.state.doc.textBetween(range.from, range.to); + const startsWithHash = text.startsWith("#"); + const content = startsWithHash + ? [] + : [ + { + type: this.name, + attrs: props, + }, + { + type: "text", + text: " ", + }, + ]; + + editor.chain().focus().insertContentAt(range, content).run(); window.getSelection()?.collapseToEnd(); }, diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 821258cf5..65c148f57 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -4,7 +4,7 @@ import Image from "@tiptap/extension-image"; import Paragraph from "@tiptap/extension-paragraph"; import Placeholder from "@tiptap/extension-placeholder"; import Text from "@tiptap/extension-text"; -import { Plugin } from "@tiptap/pm/state"; +import { Plugin, PluginKey } from "@tiptap/pm/state"; import { Editor, EditorContent, JSONContent, useEditor } from "@tiptap/react"; import { ContextItemWithId, @@ -183,6 +183,12 @@ function TipTapEditor(props: TipTapEditorProps) { const isOSREnabled = useIsOSREnabled(); + const isMultifileEdit = useSelector( + (state: RootState) => state.state.isMultifileEdit, + ); + + console.log("isMultifileEdit", isMultifileEdit); + const enterSubmenu = async (editor: Editor, providerId: string) => { const contents = editor.getText(); const indexOfAt = contents.lastIndexOf("@"); @@ -452,17 +458,52 @@ function TipTapEditor(props: TipTapEditorProps) { HTMLAttributes: { class: "mention", }, - suggestion: getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - renderHTML: (props) => { - return `@${props.node.attrs.label || props.node.attrs.id}`; + suggestion: { + ...getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + char: "@", + pluginKey: new PluginKey("defaultContextProviders"), + }, + }) + : undefined, + isMultifileEdit + ? Mention.configure({ + HTMLAttributes: { + class: "mention", + }, + suggestion: { + ...getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + char: "#", + pluginKey: new PluginKey("fileOnlyContextProviders"), + items: async ({ query }) => { + // Only display files in the dropdown + const results = getSubmenuContextItemsRef.current( + "file", + query, + ); + return results.map((result) => ({ + ...result, + label: result.title, + type: "file", + query: result.id, + icon: result.icon, + })); + }, }, }) : undefined, diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index ce599454d..0561c8f89 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -30,7 +30,6 @@ import { setCurCheckpointIndex, setInactive, setIsGatheringContext, - setIsInMultifileEdit, setMessageAtIndex, streamUpdate, } from "../redux/slices/stateSlice"; @@ -180,6 +179,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { modifiers: InputModifiers, ideMessenger: IIdeMessenger, index?: number, + promptPreamble?: string, ) { try { if (typeof index === "number") { @@ -203,7 +203,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } // Resolve context providers and construct new history - const [selectedContextItems, selectedCode, content] = + let [selectedContextItems, selectedCode, content] = await resolveEditorContent( editorState, modifiers, @@ -254,6 +254,12 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { // dispatch(addContextItems(contextItems)); + if (promptPreamble) { + typeof content === "string" + ? (content += promptPreamble) + : (content.at(-1).text += promptPreamble); + } + const message: ChatMessage = { role: "user", content, @@ -293,16 +299,14 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { await _streamNormalInput(messages); } else { const [slashCommand, commandInput] = commandAndInput; + let updatedContextItems = []; + posthog.capture("step run", { step_name: slashCommand.name, params: {}, }); - if (slashCommand.name === "multifile-edit") { - dispatch(setIsInMultifileEdit(true)); - } - await _streamSlashCommand( messages, slashCommand, diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index b8df8ac24..1bfac2d0d 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -7,6 +7,7 @@ import { RootState } from "../../redux/store"; import CodeToEditListItem from "./CodeToEditListItem"; import { RangeInFileWithContents } from "core/commands/util"; import { vscEditorBackground } from "../../components"; +import { ToolTip } from "../../components/gui/Tooltip"; export default function WorkingSet() { const dispatch = useDispatch(); @@ -21,9 +22,9 @@ export default function WorkingSet() { function onClickAddFileToCodeToEdit() {} - function onClickCodeToEditItem(rif: RangeInFileWithContents) { + function onClickFilename(rif: RangeInFileWithContents) { const { filepath, range } = editModeState.codeToEdit.find( - (workingSetRIF) => workingSetRIF === rif, + (codeToEdit) => codeToEdit === rif, ); ideMessenger.ide.showLines(filepath, range.start.line, range.end.line); @@ -34,20 +35,17 @@ export default function WorkingSet() { key={rif.filepath + rif.range.start.line + rif.range.end.line} rif={rif} onDelete={onDelete} - onClick={onClickCodeToEditItem} + onClickFilename={onClickFilename} /> )); return (
    -
    - Code to edit - -
    + Code to edit
    - {hasCodeToEdit ? ( -
      - {codeToEditItems} -
    - ) : ( - - - Add a file to get started - - )} +
    + {hasCodeToEdit ? ( +
      + {codeToEditItems} +
    + ) : ( + + + Add a file to get started + + )} +
    ); } diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/Edit/CodeToEditListItem.tsx index 30cf0266e..7668f702f 100644 --- a/gui/src/pages/Edit/CodeToEditListItem.tsx +++ b/gui/src/pages/Edit/CodeToEditListItem.tsx @@ -2,6 +2,7 @@ import { RangeInFileWithContents } from "core/commands/util"; import FileIcon from "../../components/FileIcon"; import { ChevronDownIcon, + ChevronRightIcon, ChevronUpIcon, XMarkIcon, } from "@heroicons/react/24/outline"; @@ -12,15 +13,15 @@ import { getMarkdownLanguageTagForFile } from "core/util"; export interface CodeToEditListItemProps { rif: RangeInFileWithContents; onDelete: (rif: RangeInFileWithContents) => void; - onClick: (rif: RangeInFileWithContents) => void; + onClickFilename: (rif: RangeInFileWithContents) => void; } export default function CodeToEditListItem({ rif, onDelete, - onClick, + onClickFilename, }: CodeToEditListItemProps) { - const [showCodeSnippet, setShowCodeSnippet] = useState(false); + const [showCodeSnippet, setShowCodeSnippet] = useState(true); const filepath = rif.filepath.split("/").pop() || rif.filepath; const title = `${filepath} (${rif.range.start.line + 1} - ${rif.range.end.line + 1})`; @@ -36,16 +37,13 @@ export default function CodeToEditListItem({ return (
  • onClick(rif)} + onClick={() => setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet)} > + {" "}
    - - {title} -
    -
    {showCodeSnippet ? ( - { e.stopPropagation(); setShowCodeSnippet(false); @@ -53,7 +51,7 @@ export default function CodeToEditListItem({ className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" /> ) : ( - { e.stopPropagation(); setShowCodeSnippet(true); @@ -61,6 +59,18 @@ export default function CodeToEditListItem({ className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" /> )} + + { + e.stopPropagation(); + onClickFilename(rif); + }} + > + {title} + +
    +
    { e.stopPropagation(); @@ -70,8 +80,11 @@ export default function CodeToEditListItem({ />
    - - {showCodeSnippet && } + {showCodeSnippet && ( +
    + +
    + )}
  • ); } diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index 0a92b09b2..93aae4c3b 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -2,16 +2,39 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/core"; import { InputModifiers } from "core"; import { stripImages } from "core/llm/images"; -import { useContext, useEffect } from "react"; +import { useCallback, useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; import resolveEditorContent from "../../components/mainInput/resolveInput"; import TipTapEditor from "../../components/mainInput/TipTapEditor"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { setEditDone, submitEdit } from "../../redux/slices/editModeState"; +import { + clearCodeToEdit, + setEditDone, + submitEdit, +} from "../../redux/slices/editModeState"; import { RootState } from "../../redux/store"; import CodeToEdit from "./CodeToEdit"; +import useChatHandler from "../../hooks/useChatHandler"; +import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; +import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; +import StepContainer from "../../components/StepContainer"; +import styled from "styled-components"; +import getMultifileEditPrompt from "./getMultifileEditPrompt"; + +const StepsDiv = styled.div` + position: relative; + background-color: transparent; + + & > * { + position: relative; + } + + .thread-message { + margin: 8px 4px 0 4px; + } +`; const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ "codebase", @@ -29,17 +52,24 @@ export default function Edit() { const dispatch = useDispatch(); const navigate = useNavigate(); const ideMessenger = useContext(IdeMessengerContext); + const { streamResponse } = useChatHandler(dispatch, ideMessenger); const editModeState = useSelector((state: RootState) => state.editModeState); const availableContextProviders = useSelector( (store: RootState) => store.state.config.contextProviders, ); + const state = useSelector((state: RootState) => state.state); + const applyState = useSelector( (store: RootState) => store.state.applyStates.find((state) => state.streamId === "edit") ?.status ?? "closed", ); + const isSingleFileEdit = + editModeState.codeToEdit.map((codeToEdit) => codeToEdit.filepath).length <= + 1; + useEffect(() => { if (editModeState.editStatus === "done") { ideMessenger.post("edit/escape", undefined); @@ -53,6 +83,16 @@ export default function Edit() { } }, [applyState, editModeState.editStatus]); + const applyStates = useSelector( + (state: RootState) => state.state.applyStates, + ); + + const active = useSelector((state: RootState) => state.state.active); + + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + const isStreaming = editModeState.editStatus === "streaming" || editModeState.editStatus === "accepting"; @@ -65,15 +105,17 @@ export default function Edit() { enterText: isStreaming ? "Retry" : "Edit", }; + const hasPendingApplies = pendingApplyStates.length > 0; + const filteredContextProviders = availableContextProviders.filter( (provider) => !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), ); - const handleEditorEnter = async ( + async function handleSingleRangeEdit( editorState: JSONContent, modifiers: InputModifiers, editor: Editor, - ) => { + ) { const [contextItems, __, userInstructions] = await resolveEditorContent( editorState, { @@ -91,16 +133,45 @@ export default function Edit() { ideMessenger.post("edit/sendPrompt", { prompt, - range: editModeState.highlightedCode, + range: editModeState.codeToEdit[0], }); dispatch(submitEdit(prompt)); editor.commands.selectTextblockEnd(); - }; + } - const handleBackClick = () => { + async function handleEditorEnter( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + ) { + if (isSingleFileEdit) { + handleSingleRangeEdit(editorState, modifiers, editor); + } else { + const promptPreamble = getMultifileEditPrompt(editModeState.codeToEdit); + + streamResponse( + editorState, + modifiers, + ideMessenger, + undefined, + promptPreamble, + ); + } + } + + function handleBackClick() { dispatch(setEditDone()); - }; + } + + const isLastUserInput = useCallback( + (index: number): boolean => { + return !state.history + .slice(index + 1) + .some((entry) => entry.message.role === "user"); + }, + [state.history], + ); return (
    @@ -110,23 +181,71 @@ export default function Edit() {
    -
    -
    - - - Back to Chat - + {!isSingleFileEdit && state.history.length > 1 && ( +
    + {state.history.slice(1).map((item, index: number) => ( +
    + {item.message.role === "user" ? ( + { + streamResponse( + editorState, + modifiers, + ideMessenger, + index, + ); + }} + isLastUserInput={isLastUserInput(index)} + isMainInput={false} + editorState={item.editorState} + contextItems={item.contextItems} + /> + ) : ( + + )} +
    + ))} + + {/* {!active && ( + + )} */} +
    + )} + +
    + {hasPendingApplies && isSingleFileEdit && ( + dispatch(clearCodeToEdit())} + /> + )} + + {!hasPendingApplies && isSingleFileEdit && ( + + + Back to Chat + + )} +
    ); diff --git a/gui/src/pages/Edit/getMultifileEditPrompt.ts b/gui/src/pages/Edit/getMultifileEditPrompt.ts new file mode 100644 index 000000000..5f0113695 --- /dev/null +++ b/gui/src/pages/Edit/getMultifileEditPrompt.ts @@ -0,0 +1,56 @@ +import { RangeInFileWithContents } from "core/commands/util"; + +export default function getMultifileEditPrompt( + rifs: RangeInFileWithContents[], +): string { + const filesToEditStr = rifs + .map( + (rif) => ` +\`\`\` ${rif.filepath} +${rif.contents} +\`\`\` + `, + ) + .join("\n"); + + return ` +You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: + +1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!" +2. When providing instructions, if a user needs to interact with a CLI, walk them through each step +2. Perform file edits in a logical, sequential ordering +3. For each file edit, provide a brief explanation of the changes +4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. + a. When creating new files, also inlcude the filname in the language specifier of the code block. +6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits + +Remember to be concise and focus on the code changes and their impact. + +Here's an example of how your response should be structured: + + +I'll make the following changes to implement feature X: + +1. First, I'll modify file1.js to add a new function: +\`\`\`javascript /path/to/file1.js +// Entire content of file1.js or changes to be made +\`\`\` + +2. Next, let's create a new test file: +\`\`\`javascript /path/to/file1.test.js +# Entire content of file2.py or changes to be made +\`\`\` + +Summary: +- [Sequential overview of the most important 3-5 edits] + + +Here are the files to base your edits on: + + +${filesToEditStr} + + +Please provide the multi-file edit details based on the engineer's request below: + `; +} diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index f39814dfd..dc872f5c3 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -42,10 +42,18 @@ export const editModeStateSlice = createSlice({ state, { payload }: PayloadAction, ) => { + // Remove entry from codeToEdit that doesn't match the payload's filepath and contents state.codeToEdit = state.codeToEdit.filter( - (entry) => entry.toString() !== payload.toString(), + (entry) => + !( + entry.filepath === payload.filepath && + entry.contents === payload.contents + ), ); }, + clearCodeToEdit: (state) => { + state.codeToEdit = []; + }, setEditStatus: ( state, { @@ -101,5 +109,6 @@ export const { submitEdit, removeEntryFromCodeToEdit, focusEdit, + clearCodeToEdit, } = editModeStateSlice.actions; export default editModeStateSlice.reducer; diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index f021c748b..5758b18db 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -46,12 +46,14 @@ module.exports = { "vsc-badge-background": "var(--vscode-badge-background, #1bbe84)", "vsc-badge-foreground": "var(--vscode-badge-foreground, #fff)", "vsc-sidebar-border": "var(--vscode-sideBar-border, transparent)", - "vsc-find-match": "var(--vscode-editor-findMatchBackground, rgba(255, 255, 0, 0.6))", - "vsc-find-match-selected": "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0, 0.8))", + "vsc-find-match": + "var(--vscode-editor-findMatchBackground, rgba(255, 255, 0, 0.6))", + "vsc-find-match-selected": + "var(--vscode-editor-findMatchHighlightBackground, rgba(255, 223, 0, 0.8))", }, }, }, - plugins: [], + plugins: [require("tailwind-scrollbar-hide")], corePlugins: { preflight: false, }, From 0ac11c5398dfb057c29d164165f4e5b83de14150 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 20 Nov 2024 14:51:38 -0800 Subject: [PATCH 03/13] WIP: rename MFE -> Edit --- core/commands/slash/index.ts | 2 - core/commands/slash/multifileEdit.ts | 107 ------------------ extensions/vscode/package-lock.json | 4 +- gui/src/components/Layout.tsx | 4 +- ...ltifileEditActions.tsx => EditActions.tsx} | 2 +- .../StepContainer/ResponseActions.tsx | 10 +- .../StepContainer/StepContainer.tsx | 6 +- gui/src/components/mainInput/TipTapEditor.tsx | 19 +++- .../StepContainerPreToolbar.tsx | 8 +- .../markdown/StyledMarkdownPreview.tsx | 2 +- gui/src/pages/Edit/CodeToEdit.tsx | 9 +- gui/src/pages/Edit/CodeToEditListItem.tsx | 32 ++++-- gui/src/pages/Edit/Edit.tsx | 29 ++--- gui/src/redux/slices/editModeState.ts | 6 + gui/src/redux/slices/stateSlice.ts | 8 -- gui/src/redux/slices/uiStateSlice.ts | 9 ++ 16 files changed, 93 insertions(+), 164 deletions(-) delete mode 100644 core/commands/slash/multifileEdit.ts rename gui/src/components/StepContainer/{MultifileEditActions.tsx => EditActions.tsx} (97%) diff --git a/core/commands/slash/index.ts b/core/commands/slash/index.ts index 544673901..18008e251 100644 --- a/core/commands/slash/index.ts +++ b/core/commands/slash/index.ts @@ -2,7 +2,6 @@ import GenerateTerminalCommand from "./cmd"; import CommitMessageCommand from "./commit"; import DraftIssueCommand from "./draftIssue"; import HttpSlashCommand from "./http"; -import MultiFileEditSlashCommand from "./multifileEdit"; import OnboardSlashCommand from "./onboard"; import ReviewMessageCommand from "./review"; import ShareSlashCommand from "./share"; @@ -15,5 +14,4 @@ export default [ CommitMessageCommand, ReviewMessageCommand, OnboardSlashCommand, - MultiFileEditSlashCommand, ]; diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts deleted file mode 100644 index c8cf64679..000000000 --- a/core/commands/slash/multifileEdit.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { SlashCommand } from "../.."; -import { stripImages } from "../../llm/images"; - -const MultiFileEditSlashCommand: SlashCommand = { - name: "multifile-edit", - description: "Edit multiple files in the codebase at once", - run: async function* ({ llm, contextItems, selectedCode, input, ide }) { - // TODO: This is causing GUI builds to fail, so we're disabling it for now - // const selectedCodeStr = ( - // await Promise.all( - // selectedCode.map(async (item) => { - // // Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]` - // const [filepath, rangeStr] = item.filepath.split(" "); - // const { getFullyQualifiedPath } = await import( - // "../../../extensions/vscode/src/util/util" - // ); - // const fullPath = getFullyQualifiedPath(ide as any, filepath); // any = VsCodeIde here, but importing it breaks tests - // if (!fullPath) { - // return ""; - // } - // const codeStr = await ide.readRangeInFile(fullPath, item.range); - // // Include the filepath so the model can map it correctly with codeblock outputs - // return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``; - // }), - // ) - // ).join("\n"); - - const fileContextItemsStr = contextItems - .filter((item) => item.uri?.type === "file") - .map((item) => item.content) - .join("\n"); - - const filesToEditStr = fileContextItemsStr + "\n"; // + selectedCodeStr; - - const additionalContextStr = contextItems - .filter((item) => item.uri?.type !== "file") - .map((item) => `${item.description}: ${item.content}`) - .join("\n"); - - const content = createPrompt(filesToEditStr, additionalContextStr, input); - - for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) { - yield stripImages(chunk.content); - } - }, -}; - -function createPrompt( - filesToEditStr: string, - additionalContextStr: string, - input: string, -): string { - return ` -You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines: - -1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!" -2. When providing instructions, if a user needs to interact with a CLI, walk them through each step -2. Perform file edits in a logical, sequential ordering -3. For each file edit, provide a brief explanation of the changes -4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block. - a. When creating new files, also inlcude the filname in the language specifier of the code block. -6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits - -Remember to be concise and focus on the code changes and their impact. - -Here's an example of how your response should be structured: - - -I'll make the following changes to implement feature X: - -1. First, I'll modify file1.js to add a new function: -\`\`\`javascript /path/to/file1.js -// Entire content of file1.js or changes to be made -\`\`\` - -2. Next, let's create a new test file: -\`\`\`javascript /path/to/file1.test.js -# Entire content of file2.py or changes to be made -\`\`\` - -Summary: -- [Sequential overview of the most important 3-5 edits] - - -Now, let's make the changes based on the engineer's request: - - -${input} - - -Here are the files to base your edits on: - - -${filesToEditStr} - - -And here is any additional context the engineer has provided: - - -${additionalContextStr} - - -Please provide the multi-file edit details based on the engineer's request. - `; -} - -export default MultiFileEditSlashCommand; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3dc6757e7..940503505 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.231", + "version": "0.9.232", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.231", + "version": "0.9.232", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 14cd63249..00be6a870 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -15,7 +15,7 @@ import { } from "../redux/slices/editModeState"; import { setShowDialog } from "../redux/slices/uiStateSlice"; import { - setIsInMultifileEdit, + setIsInEditMode, updateApplyState, updateCurCheckpoint, } from "../redux/slices/stateSlice"; @@ -195,7 +195,7 @@ const Layout = () => { "focusEdit", async (payload) => { // TODO: Move into edit state - dispatch(setIsInMultifileEdit(true)); + dispatch(setIsInEditMode(true)); dispatch(focusEdit(payload)); navigate("/edit"); diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx similarity index 97% rename from gui/src/components/StepContainer/MultifileEditActions.tsx rename to gui/src/components/StepContainer/EditActions.tsx index 603d6e15a..c5bf7699f 100644 --- a/gui/src/components/StepContainer/MultifileEditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -12,7 +12,7 @@ export interface MultifileEditActionsProps { item: ChatHistoryItem; } -export default function MultifileEditActions({ +export default function EditActions({ index, item, }: MultifileEditActionsProps) { diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 66d62575c..0aa08ccd6 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -6,7 +6,7 @@ import { useSelector } from "react-redux"; import { RootState } from "../../redux/store"; import { ChatHistoryItem } from "core"; import FeedbackButtons from "./FeedbackButtons"; -import MultifileEditActions from "./MultifileEditActions"; +import EditActions from "./EditActions"; export interface ResponseActionsProps { isTruncated: boolean; @@ -23,15 +23,15 @@ export default function ResponseActions({ isTruncated, onDelete, }: ResponseActionsProps) { - const isInMultifileEdit = useSelector( - (store: RootState) => store.state.isMultifileEdit, + const isInEditMode = useSelector( + (store: RootState) => store.editModeState.isInEditMode, ); // Only render delete button if there is more than one message const shouldRenderDelete = index !== 1; - if (isInMultifileEdit) { - return ; + if (isInEditMode) { + return ; } return ( diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 4fdd6eda2..0c56cf40a 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -31,13 +31,13 @@ export default function StepContainer(props: StepContainerProps) { const curCheckpointIndex = useSelector( (store: RootState) => store.state.curCheckpointIndex, ); - const isMultifileEdit = useSelector( - (store: RootState) => store.state.isMultifileEdit, + const isInEditMode = useSelector( + (store: RootState) => store.editModeState.isInEditMode, ); const uiConfig = useUIConfig(); const shouldHideActions = active && props.isLast; const isStepAheadOfCurCheckpoint = - isMultifileEdit && Math.floor(props.index / 2) > curCheckpointIndex; + isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; useEffect(() => { if (!active) { diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 65c148f57..960f27e75 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -65,6 +65,7 @@ import { } from "./handleMetaKeyIssues"; import { ComboBoxItem } from "./types"; import useIsOSREnabled from "../../hooks/useIsOSREnabled"; +import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; const InputBoxDiv = styled.div<{ border?: string }>` resize: none; @@ -170,6 +171,7 @@ function TipTapEditor(props: TipTapEditorProps) { const historyLength = useSelector( (store: RootState) => store.state.history.length, ); + const useActiveFile = useSelector(selectUseActiveFile); const { saveSession, loadSession } = useHistory(dispatch); @@ -183,11 +185,13 @@ function TipTapEditor(props: TipTapEditorProps) { const isOSREnabled = useIsOSREnabled(); - const isMultifileEdit = useSelector( - (state: RootState) => state.state.isMultifileEdit, + const isInEditMode = useSelector( + (state: RootState) => state.editModeState.isInEditMode, ); - console.log("isMultifileEdit", isMultifileEdit); + const shouldAddFileForEditing = useSelector( + (state: RootState) => state.uiState.shouldAddFileForEditing, + ); const enterSubmenu = async (editor: Editor, providerId: string) => { const contents = editor.getText(); @@ -473,7 +477,7 @@ function TipTapEditor(props: TipTapEditorProps) { }, }) : undefined, - isMultifileEdit + isInEditMode ? Mention.configure({ HTMLAttributes: { class: "mention", @@ -808,6 +812,13 @@ function TipTapEditor(props: TipTapEditorProps) { const [activeKey, setActiveKey] = useState(null); + useEffect(() => { + if (shouldAddFileForEditing && props.isMainInput) { + insertCharacterWithWhitespace("#"); + dispatch(setShouldAddFileForEditing(false)); + } + }, [shouldAddFileForEditing]); + const insertCharacterWithWhitespace = useCallback( (char: string) => { const text = editor.getText(); diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 5bed71147..4692e1bb1 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -68,11 +68,11 @@ export default function StepContainerPreToolbar( const ideMessenger = useContext(IdeMessengerContext); const streamIdRef = useRef(uuidv4()); const wasGeneratingRef = useRef(props.isGeneratingCodeBlock); - const isMultifileEdit = useSelector( - (state: RootState) => state.state.isMultifileEdit, + const isInEditMode = useSelector( + (state: RootState) => state.editModeState.isInEditMode, ); const active = useSelector((state: RootState) => state.state.active); - const [isExpanded, setIsExpanded] = useState(isMultifileEdit ? false : true); + const [isExpanded, setIsExpanded] = useState(isInEditMode ? false : true); const [codeBlockContent, setCodeBlockContent] = useState(""); const isChatActive = useSelector((state: RootState) => state.state.active); @@ -135,7 +135,7 @@ export default function StepContainerPreToolbar( useEffect(() => { const hasCompletedGenerating = wasGeneratingRef.current && !isGeneratingCodeBlock; - const shouldAutoApply = hasCompletedGenerating && isMultifileEdit; + const shouldAutoApply = hasCompletedGenerating && isInEditMode; if (shouldAutoApply) { onClickApply(); diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index ca1ea2afd..ff8cbfbfb 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -166,7 +166,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( // So in this case we just put them in refs const symbolsRef = useRef([]); const contextItemsRef = useRef([]); - + useEffect(() => { contextItemsRef.current = contextItems || []; }, [contextItems]); diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index 1bfac2d0d..81b2dc609 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -8,6 +8,7 @@ import CodeToEditListItem from "./CodeToEditListItem"; import { RangeInFileWithContents } from "core/commands/util"; import { vscEditorBackground } from "../../components"; import { ToolTip } from "../../components/gui/Tooltip"; +import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; export default function WorkingSet() { const dispatch = useDispatch(); @@ -20,7 +21,9 @@ export default function WorkingSet() { dispatch(removeEntryFromCodeToEdit(rif)); } - function onClickAddFileToCodeToEdit() {} + function onClickAddFileToCodeToEdit() { + dispatch(setShouldAddFileForEditing(true)); + } function onClickFilename(rif: RangeInFileWithContents) { const { filepath, range } = editModeState.codeToEdit.find( @@ -44,7 +47,7 @@ export default function WorkingSet() { className="mx-1 flex flex-col rounded-t-lg px-1 pb-1" style={{ backgroundColor: vscEditorBackground }} > -
    +
    Code to edit {hasCodeToEdit ? ( -
      +
        {codeToEditItems}
      ) : ( diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/Edit/CodeToEditListItem.tsx index 7668f702f..a39d40ed4 100644 --- a/gui/src/pages/Edit/CodeToEditListItem.tsx +++ b/gui/src/pages/Edit/CodeToEditListItem.tsx @@ -3,12 +3,12 @@ import FileIcon from "../../components/FileIcon"; import { ChevronDownIcon, ChevronRightIcon, - ChevronUpIcon, XMarkIcon, } from "@heroicons/react/24/outline"; import { useState } from "react"; import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview"; import { getMarkdownLanguageTagForFile } from "core/util"; +import styled from "styled-components"; export interface CodeToEditListItemProps { rif: RangeInFileWithContents; @@ -16,6 +16,19 @@ export interface CodeToEditListItemProps { onClickFilename: (rif: RangeInFileWithContents) => void; } +// Easiest method to overwrite the top level styling of the markdown preview +const NoPaddingWrapper = styled.div` + > * { + margin: 0 !important; + padding: 0 !important; + } + + pre { + margin: 0 !important; + padding: 0 !important; + } +`; + export default function CodeToEditListItem({ rif, onDelete, @@ -36,12 +49,13 @@ export default function CodeToEditListItem({ return (
    • setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet)} > - {" "} -
      -
      +
      +
      {showCodeSnippet ? ( { @@ -61,7 +75,7 @@ export default function CodeToEditListItem({ )} { e.stopPropagation(); onClickFilename(rif); @@ -81,8 +95,10 @@ export default function CodeToEditListItem({
      {showCodeSnippet && ( -
      - +
      + + +
      )}
    • diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index 93aae4c3b..8a1280a6b 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -58,7 +58,11 @@ export default function Edit() { (store: RootState) => store.state.config.contextProviders, ); - const state = useSelector((state: RootState) => state.state); + const history = useSelector((state: RootState) => state.state.history); + + const applyStates = useSelector( + (state: RootState) => state.state.applyStates, + ); const applyState = useSelector( (store: RootState) => @@ -83,11 +87,7 @@ export default function Edit() { } }, [applyState, editModeState.editStatus]); - const applyStates = useSelector( - (state: RootState) => state.state.applyStates, - ); - - const active = useSelector((state: RootState) => state.state.active); + // const active = useSelector((state: RootState) => state.state.active); const pendingApplyStates = applyStates.filter( (state) => state.status === "done", @@ -98,8 +98,8 @@ export default function Edit() { editModeState.editStatus === "accepting"; const toolbarOptions = { - hideAddContext: true, - hideImageUpload: true, + hideAddContext: false, + hideImageUpload: false, hideUseCodebase: true, hideSelectModel: false, enterText: isStreaming ? "Retry" : "Edit", @@ -124,6 +124,7 @@ export default function Edit() { }, ideMessenger, [], + dispatch, ); const prompt = [ @@ -166,11 +167,11 @@ export default function Edit() { const isLastUserInput = useCallback( (index: number): boolean => { - return !state.history + return !history .slice(index + 1) .some((entry) => entry.message.role === "user"); }, - [state.history], + [history], ); return ( @@ -181,7 +182,7 @@ export default function Edit() {
    - {!isSingleFileEdit && state.history.length > 1 && ( + {!isSingleFileEdit && history.length > 1 && (
    - {state.history.slice(1).map((item, index: number) => ( + {history.slice(1).map((item, index: number) => (
    {item.message.role === "user" ? ( )} diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index dc872f5c3..a4c5ac1fa 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -8,12 +8,14 @@ interface EditModeState { previousInputs: MessageContent[]; fileAfterEdit?: string; codeToEdit: RangeInFileWithContents[]; + isInEditMode: boolean; } const initialState: EditModeState = { editStatus: "not-started", previousInputs: [], codeToEdit: [], + isInEditMode: false, }; export const editModeStateSlice = createSlice({ @@ -98,6 +100,9 @@ export const editModeStateSlice = createSlice({ state.editStatus = "done"; state.previousInputs = []; }, + setIsInEditMode: (state, { payload }: PayloadAction) => { + state.isInEditMode = payload; + }, }, }); @@ -110,5 +115,6 @@ export const { removeEntryFromCodeToEdit, focusEdit, clearCodeToEdit, + setIsInEditMode, } = editModeStateSlice.actions; export default editModeStateSlice.reducer; diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 770e9ce69..bc4f6ce63 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -46,7 +46,6 @@ type State = { statuses: Record; }; streamAborter: AbortController; - isMultifileEdit: boolean; }; const initialState: State = { @@ -78,7 +77,6 @@ const initialState: State = { defaultModelTitle: "GPT-4", selectedProfileId: "local", checkpoints: [], - isMultifileEdit: false, curCheckpointIndex: 0, nextCodeBlockToApplyIndex: 0, applyStates: [], @@ -308,7 +306,6 @@ export const stateSlice = createSlice({ state.active = false; state.context.isGathering = false; - state.isMultifileEdit = false; state.symbols = {}; if (payload) { state.history = payload.history as any; @@ -374,10 +371,6 @@ export const stateSlice = createSlice({ selectedProfileId: payload, }; }, - - setIsInMultifileEdit: (state, { payload }: PayloadAction) => { - state.isMultifileEdit = payload; - }, setCurCheckpointIndex: (state, { payload }: PayloadAction) => { state.curCheckpointIndex = payload; }, @@ -472,7 +465,6 @@ export const { setSelectedProfileId, deleteMessage, setIsGatheringContext, - setIsInMultifileEdit, updateCurCheckpoint, setCurCheckpointIndex, resetNextCodeBlockToApplyIndex, diff --git a/gui/src/redux/slices/uiStateSlice.ts b/gui/src/redux/slices/uiStateSlice.ts index f4b531c39..9a13415d3 100644 --- a/gui/src/redux/slices/uiStateSlice.ts +++ b/gui/src/redux/slices/uiStateSlice.ts @@ -9,6 +9,7 @@ type UiState = { dialogMessage: string | JSX.Element | undefined; dialogEntryOn: boolean; onboardingCard: OnboardingCardState; + shouldAddFileForEditing: boolean; }; export const uiStateSlice = createSlice({ @@ -18,6 +19,7 @@ export const uiStateSlice = createSlice({ dialogMessage: "", dialogEntryOn: false, onboardingCard: defaultOnboardingCardState, + shouldAddFileForEditing: false, } as UiState, reducers: { setOnboardingCard: ( @@ -41,6 +43,12 @@ export const uiStateSlice = createSlice({ setShowDialog: (state, action: PayloadAction) => { state.showDialog = action.payload; }, + setShouldAddFileForEditing: ( + state, + action: PayloadAction, + ) => { + state.shouldAddFileForEditing = action.payload; + }, }, }); @@ -49,6 +57,7 @@ export const { setDialogMessage, setDialogEntryOn, setShowDialog, + setShouldAddFileForEditing, } = uiStateSlice.actions; export default uiStateSlice.reducer; From f90d4bc5020de215b556ff48bd8c26357644cb13 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 20 Nov 2024 16:36:53 -0800 Subject: [PATCH 04/13] WIP: handle whole file additions --- core/protocol/ideWebview.ts | 2 +- extensions/vscode/src/commands.ts | 2 +- gui/src/components/Layout.tsx | 10 +- .../components/StepContainer/EditActions.tsx | 7 +- .../mainInput/AddCodeToEditExtension.ts | 198 ++++++++++++++++++ .../components/mainInput/MentionExtension.ts | 33 ++- gui/src/components/mainInput/TipTapEditor.tsx | 42 ++-- .../markdown/StyledMarkdownPreview.tsx | 17 +- gui/src/pages/Edit/CodeToEdit.tsx | 29 +-- gui/src/pages/Edit/CodeToEditListItem.tsx | 27 ++- gui/src/pages/Edit/Edit.tsx | 39 ++-- gui/src/pages/Edit/getMultifileEditPrompt.ts | 13 +- gui/src/redux/slices/editModeState.ts | 20 +- manual-testing-sandbox/testCalculator.js | 0 14 files changed, 321 insertions(+), 118 deletions(-) create mode 100644 gui/src/components/mainInput/AddCodeToEditExtension.ts create mode 100644 manual-testing-sandbox/testCalculator.js diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 2ef3c9e06..4dd0aa2d8 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -94,7 +94,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { }, void, ]; - addRIFToCodeToEdit: [RangeInFileWithContents, void]; + addCodeToEdit: [RangeInFileWithContents, void]; navigateTo: [{ path: string; toggle?: boolean }, void]; addModel: [undefined, void]; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index be3ff12ca..b4252f8dd 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -486,7 +486,7 @@ const commandsMap: ( if (rangeInFileWithContents) { sidebar.webviewProtocol?.request( - "addRIFToCodeToEdit", + "addCodeToEdit", rangeInFileWithContents, ); diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 00be6a870..44185ee6c 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -10,12 +10,12 @@ import { useConfigError } from "../redux/hooks"; import { setEditDone, setEditStatus, - addRIFToCodeToEdit, + addCodeToEdit, focusEdit, + setIsInEditMode, } from "../redux/slices/editModeState"; import { setShowDialog } from "../redux/slices/uiStateSlice"; import { - setIsInEditMode, updateApplyState, updateCurCheckpoint, } from "../redux/slices/stateSlice"; @@ -194,9 +194,7 @@ const Layout = () => { useWebviewListener( "focusEdit", async (payload) => { - // TODO: Move into edit state dispatch(setIsInEditMode(true)); - dispatch(focusEdit(payload)); navigate("/edit"); }, @@ -204,9 +202,9 @@ const Layout = () => { ); useWebviewListener( - "addRIFToCodeToEdit", + "addCodeToEdit", async (payload) => { - dispatch(addRIFToCodeToEdit(payload)); + dispatch(addCodeToEdit(payload)); }, [navigate], ); diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index c5bf7699f..d38255659 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -7,15 +7,12 @@ import { ChatHistoryItem } from "core"; import { stripImages } from "core/llm/images"; import { CopyIconButton } from "../gui/CopyIconButton"; -export interface MultifileEditActionsProps { +export interface EditActionsProps { index: number; item: ChatHistoryItem; } -export default function EditActions({ - index, - item, -}: MultifileEditActionsProps) { +export default function EditActions({ index, item }: EditActionsProps) { const curCheckpointIndex = useSelector( (store: RootState) => store.state.curCheckpointIndex, ); diff --git a/gui/src/components/mainInput/AddCodeToEditExtension.ts b/gui/src/components/mainInput/AddCodeToEditExtension.ts new file mode 100644 index 000000000..795b7a2e4 --- /dev/null +++ b/gui/src/components/mainInput/AddCodeToEditExtension.ts @@ -0,0 +1,198 @@ +import { mergeAttributes, Node } from "@tiptap/core"; +import { DOMOutputSpec, Node as ProseMirrorNode } from "@tiptap/pm/model"; +import { PluginKey } from "@tiptap/pm/state"; +import Suggestion, { SuggestionOptions } from "@tiptap/suggestion"; + +export type MentionOptions = { + HTMLAttributes: Record; + renderHTML: (props: { + options: MentionOptions; + node: ProseMirrorNode; + }) => DOMOutputSpec; + suggestion: Omit; +}; + +export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit"); + +export const AddCodeToEdit = Node.create({ + name: "add-code-to-edit", + + addOptions() { + return { + HTMLAttributes: {}, + renderHTML({ options, node }) { + return [ + "span", + this.HTMLAttributes, + `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`, + ]; + }, + suggestion: { + char: "#", + pluginKey: AddCodeToEditPluginKey, + allow: ({ state, range }) => { + const $from = state.doc.resolve(range.from); + const type = state.schema.nodes[this.name]; + const allow = !!$from.parent.type.contentMatch.matchType(type); + + // Check if there's a space after the "#" + const textFrom = range.from; + const textTo = state.selection.$to.pos; + const text = state.doc.textBetween(textFrom, textTo); + const hasSpace = text.includes(" "); + + return allow && !hasSpace; + }, + }, + }; + }, + + group: "inline", + + inline: true, + + selectable: false, + + atom: true, + + addAttributes() { + return { + id: { + default: null, + parseHTML: (element) => element.getAttribute("data-id"), + renderHTML: (attributes) => { + if (!attributes.id) { + return {}; + } + + return { + "data-id": attributes.id, + }; + }, + }, + + label: { + default: null, + parseHTML: (element) => element.getAttribute("data-label"), + renderHTML: (attributes) => { + if (!attributes.label) { + return {}; + } + + return { + "data-label": attributes.label, + }; + }, + }, + + renderInlineAs: { + default: null, + parseHTML: (element) => element.getAttribute("data-renderInlineAs"), + renderHTML: (attributes) => { + if (!attributes.renderInlineAs) { + return {}; + } + + return { + "data-renderInlineAs": attributes.renderInlineAs, + }; + }, + }, + + query: { + default: null, + parseHTML: (element) => element.getAttribute("data-query"), + renderHTML: (attributes) => { + if (!attributes.query) { + return {}; + } + + return { + "data-query": attributes.query, + }; + }, + }, + + itemType: { + default: null, + parseHTML: (element) => element.getAttribute("data-itemType"), + renderHTML: (attributes) => { + if (!attributes.itemType) { + return {}; + } + + return { + "data-itemType": attributes.itemType, + }; + }, + }, + }; + }, + + parseHTML() { + return [ + { + tag: `span[data-type="${this.name}"]`, + }, + ]; + }, + + renderHTML({ node, HTMLAttributes }) { + const html = this.options.renderHTML({ + options: this.options, + node, + }); + + if (typeof html === "string") { + return [ + "span", + mergeAttributes( + { "data-type": this.name }, + this.options.HTMLAttributes, + HTMLAttributes, + ), + html, + ]; + } + return html; + }, + + addKeyboardShortcuts() { + return { + Backspace: () => + this.editor.commands.command(({ tr, state }) => { + let isMention = false; + const { selection } = state; + const { empty, anchor } = selection; + + if (!empty) { + return false; + } + + state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => { + if (node.type.name === this.name) { + isMention = true; + tr.insertText( + this.options.suggestion.char || "", + pos, + pos + node.nodeSize, + ); + + return false; + } + }); + + return isMention; + }), + }; + }, + + addProseMirrorPlugins() { + return [ + Suggestion({ + editor: this.editor, + ...this.options.suggestion, + }), + ]; + }, +}); diff --git a/gui/src/components/mainInput/MentionExtension.ts b/gui/src/components/mainInput/MentionExtension.ts index 775c3eb22..71d282d46 100644 --- a/gui/src/components/mainInput/MentionExtension.ts +++ b/gui/src/components/mainInput/MentionExtension.ts @@ -28,6 +28,8 @@ export const Mention = Node.create({ ]; }, suggestion: { + char: "@", + pluginKey: MentionPluginKey, command: ({ editor, range, props }) => { // increase range.to by one when the next node is of type "text" // and starts with a space character @@ -38,23 +40,20 @@ export const Mention = Node.create({ range.to += 1; } - // For # symbol mentions, we add the file to the "Code to edit" rather than the editor - const text = editor.state.doc.textBetween(range.from, range.to); - const startsWithHash = text.startsWith("#"); - const content = startsWithHash - ? [] - : [ - { - type: this.name, - attrs: props, - }, - { - type: "text", - text: " ", - }, - ]; - - editor.chain().focus().insertContentAt(range, content).run(); + editor + .chain() + .focus() + .insertContentAt(range, [ + { + type: this.name, + attrs: props, + }, + { + type: "text", + text: " ", + }, + ]) + .run(); window.getSelection()?.collapseToEnd(); }, diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 960f27e75..67d71eee8 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -66,6 +66,8 @@ import { import { ComboBoxItem } from "./types"; import useIsOSREnabled from "../../hooks/useIsOSREnabled"; import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; +import { AddCodeToEdit } from "./AddCodeToEditExtension"; +import { addCodeToEdit } from "../../redux/slices/editModeState"; const InputBoxDiv = styled.div<{ border?: string }>` resize: none; @@ -462,25 +464,24 @@ function TipTapEditor(props: TipTapEditorProps) { HTMLAttributes: { class: "mention", }, - suggestion: { - ...getContextProviderDropdownOptions( - availableContextProvidersRef, - getSubmenuContextItemsRef, - enterSubmenu, - onClose, - onOpen, - inSubmenuRef, - ideMessenger, - ), - char: "@", - pluginKey: new PluginKey("defaultContextProviders"), + suggestion: getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + renderHTML: (props) => { + return `@${props.node.attrs.label || props.node.attrs.id}`; }, }) : undefined, isInEditMode - ? Mention.configure({ + ? AddCodeToEdit.configure({ HTMLAttributes: { - class: "mention", + class: "add-code-to-edit", }, suggestion: { ...getContextProviderDropdownOptions( @@ -492,8 +493,17 @@ function TipTapEditor(props: TipTapEditorProps) { inSubmenuRef, ideMessenger, ), - char: "#", - pluginKey: new PluginKey("fileOnlyContextProviders"), + command: async ({ editor, range, props }) => { + editor.chain().focus().insertContentAt(range, "").run(); + const filepath = props.id; + const contents = await ideMessenger.ide.readFile(filepath); + dispatch( + addCodeToEdit({ + filepath, + contents, + }), + ); + }, items: async ({ query }) => { // Only display files in the dropdown const results = getSubmenuContextItemsRef.current( diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index ff8cbfbfb..cdd8babf7 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -141,8 +141,8 @@ function processCodeBlocks(tree: any) { node.data = node.data || {}; node.data.hProperties = node.data.hProperties || {}; - node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node; - node.data.hProperties.codeBlockContent = node.value; + node.data.hProperties["data-isgeneratingcodeblock"] = lastCodeNode === node; + node.data.hProperties["data-codeblockcontent"] = node.value; if (node.meta) { let meta = node.meta.split(" "); @@ -212,13 +212,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( ); }, pre: ({ node, ...preProps }) => { - const { - className, - filepath, - isGeneratingCodeBlock, - codeBlockContent, - range, - } = preProps?.children?.[0]?.props; + const preChildProps = preProps?.children?.[0]?.props; + const { className, filepath, range } = preProps?.children?.[0]?.props; + + const codeBlockContent = preChildProps["data-codeblockcontent"]; + const isGeneratingCodeBlock = + preChildProps["data-isgeneratingcodeblock"]; if (!props.isRenderingInStepContainer) { return ; diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index 81b2dc609..562c37028 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -2,12 +2,11 @@ import { InformationCircleIcon, PlusIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { useDispatch, useSelector } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { removeEntryFromCodeToEdit } from "../../redux/slices/editModeState"; +import { CodeToEdit, removeCodeToEdit } from "../../redux/slices/editModeState"; import { RootState } from "../../redux/store"; import CodeToEditListItem from "./CodeToEditListItem"; import { RangeInFileWithContents } from "core/commands/util"; import { vscEditorBackground } from "../../components"; -import { ToolTip } from "../../components/gui/Tooltip"; import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; export default function WorkingSet() { @@ -18,25 +17,29 @@ export default function WorkingSet() { const hasCodeToEdit = editModeState.codeToEdit.length > 0; function onDelete(rif: RangeInFileWithContents) { - dispatch(removeEntryFromCodeToEdit(rif)); + dispatch(removeCodeToEdit(rif)); } function onClickAddFileToCodeToEdit() { dispatch(setShouldAddFileForEditing(true)); } - function onClickFilename(rif: RangeInFileWithContents) { - const { filepath, range } = editModeState.codeToEdit.find( - (codeToEdit) => codeToEdit === rif, - ); - - ideMessenger.ide.showLines(filepath, range.start.line, range.end.line); + function onClickFilename(code: CodeToEdit) { + if ("range" in code) { + ideMessenger.ide.showLines( + code.filepath, + code.range.start.line, + code.range.end.line, + ); + } else { + ideMessenger.ide.openFile(code.filepath); + } } - const codeToEditItems = editModeState.codeToEdit.map((rif) => ( + const codeToEditItems = editModeState.codeToEdit.map((code, i) => ( @@ -47,7 +50,7 @@ export default function WorkingSet() { className="mx-1 flex flex-col rounded-t-lg px-1 pb-1" style={{ backgroundColor: vscEditorBackground }} > -
    +
    Code to edit void; - onClickFilename: (rif: RangeInFileWithContents) => void; + code: CodeToEdit; + onDelete: (code: CodeToEdit) => void; + onClickFilename: (code: CodeToEdit) => void; } // Easiest method to overwrite the top level styling of the markdown preview @@ -30,20 +31,24 @@ const NoPaddingWrapper = styled.div` `; export default function CodeToEditListItem({ - rif, + code, onDelete, onClickFilename, }: CodeToEditListItemProps) { const [showCodeSnippet, setShowCodeSnippet] = useState(true); - const filepath = rif.filepath.split("/").pop() || rif.filepath; - const title = `${filepath} (${rif.range.start.line + 1} - ${rif.range.end.line + 1})`; + const filepath = code.filepath.split("/").pop() || code.filepath; + let title = filepath; + + if ("range" in code) { + title += `(${code.range.start.line + 1} - ${code.range.end.line + 1})`; + } const source = "```" + - getMarkdownLanguageTagForFile(rif.filepath) + + getMarkdownLanguageTagForFile(code.filepath) + "\n" + - rif.contents + + code.contents + "\n" + "```"; @@ -73,12 +78,12 @@ export default function CodeToEditListItem({ className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" /> )} - + { e.stopPropagation(); - onClickFilename(rif); + onClickFilename(code); }} > {title} @@ -88,7 +93,7 @@ export default function CodeToEditListItem({ { e.stopPropagation(); - onDelete(rif); + onDelete(code); }} className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" /> diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index 8a1280a6b..38fdeaad4 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -22,19 +22,7 @@ import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import StepContainer from "../../components/StepContainer"; import styled from "styled-components"; import getMultifileEditPrompt from "./getMultifileEditPrompt"; - -const StepsDiv = styled.div` - position: relative; - background-color: transparent; - - & > * { - position: relative; - } - - .thread-message { - margin: 8px 4px 0 4px; - } -`; +import { RangeInFileWithContents } from "core/commands/util"; const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ "codebase", @@ -70,9 +58,10 @@ export default function Edit() { ?.status ?? "closed", ); - const isSingleFileEdit = - editModeState.codeToEdit.map((codeToEdit) => codeToEdit.filepath).length <= - 1; + const isSingleRangeEdit = + editModeState.codeToEdit.length === 0 || + (editModeState.codeToEdit.length === 1 && + "range" in editModeState.codeToEdit[0]); useEffect(() => { if (editModeState.editStatus === "done") { @@ -132,9 +121,17 @@ export default function Edit() { stripImages(userInstructions), ].join("\n\n"); + const codeToEdit = editModeState.codeToEdit[0]; + + let rif: RangeInFileWithContents = { + filepath: codeToEdit.filepath, + contents: codeToEdit.contents, + range: "range" in codeToEdit ? codeToEdit.range : undefined, + }; + ideMessenger.post("edit/sendPrompt", { prompt, - range: editModeState.codeToEdit[0], + range: editModeState.codeToEdit[0] as RangeInFileWithContents, }); dispatch(submitEdit(prompt)); @@ -146,7 +143,7 @@ export default function Edit() { modifiers: InputModifiers, editor: Editor, ) { - if (isSingleFileEdit) { + if (isSingleRangeEdit) { handleSingleRangeEdit(editorState, modifiers, editor); } else { const promptPreamble = getMultifileEditPrompt(editModeState.codeToEdit); @@ -190,7 +187,7 @@ export default function Edit() { />
    - {!isSingleFileEdit && history.length > 1 && ( + {!isSingleRangeEdit && history.length > 1 && (
    {history.slice(1).map((item, index: number) => (
    @@ -230,14 +227,14 @@ export default function Edit() { )}
    - {hasPendingApplies && isSingleFileEdit && ( + {hasPendingApplies && isSingleRangeEdit && ( dispatch(clearCodeToEdit())} /> )} - {!hasPendingApplies && isSingleFileEdit && ( + {!hasPendingApplies && isSingleRangeEdit && ( ` -\`\`\` ${rif.filepath} -${rif.contents} + (code) => ` +\`\`\` ${code.filepath} +${code.contents} \`\`\` `, ) @@ -48,7 +49,7 @@ Summary: Here are the files to base your edits on: -${filesToEditStr} +${codeToEditStr} Please provide the multi-file edit details based on the engineer's request below: diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index a4c5ac1fa..db633c062 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -1,13 +1,15 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { MessageContent } from "core"; +import { FileWithContents, MessageContent } from "core"; import { RangeInFileWithContents } from "core/commands/util"; import { EditStatus } from "core/protocol/ideWebview"; +export type CodeToEdit = RangeInFileWithContents | FileWithContents; + interface EditModeState { editStatus: EditStatus; previousInputs: MessageContent[]; fileAfterEdit?: string; - codeToEdit: RangeInFileWithContents[]; + codeToEdit: CodeToEdit[]; isInEditMode: boolean; } @@ -22,10 +24,7 @@ export const editModeStateSlice = createSlice({ name: "editModeState", initialState, reducers: { - addRIFToCodeToEdit: ( - state, - { payload }: PayloadAction, - ) => { + addCodeToEdit: (state, { payload }: PayloadAction) => { state.codeToEdit.push(payload); state.editStatus = "not-started"; state.previousInputs = []; @@ -40,10 +39,7 @@ export const editModeStateSlice = createSlice({ state.previousInputs.push(payload); state.editStatus = "streaming"; }, - removeEntryFromCodeToEdit: ( - state, - { payload }: PayloadAction, - ) => { + removeCodeToEdit: (state, { payload }: PayloadAction) => { // Remove entry from codeToEdit that doesn't match the payload's filepath and contents state.codeToEdit = state.codeToEdit.filter( (entry) => @@ -107,12 +103,12 @@ export const editModeStateSlice = createSlice({ }); export const { - addRIFToCodeToEdit, + addCodeToEdit, setEditStatus, addPreviousInput, setEditDone, submitEdit, - removeEntryFromCodeToEdit, + removeCodeToEdit, focusEdit, clearCodeToEdit, setIsInEditMode, diff --git a/manual-testing-sandbox/testCalculator.js b/manual-testing-sandbox/testCalculator.js new file mode 100644 index 000000000..e69de29bb From b4d364f7616a7bed85469d8655ff048b108aa786 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 20 Nov 2024 17:38:29 -0800 Subject: [PATCH 05/13] WIP: comment out checkpoint logic --- gui/src/components/History/index.tsx | 16 +++++++++---- gui/src/components/Layout.tsx | 6 ++--- .../components/StepContainer/EditActions.tsx | 23 +++++++++++++------ .../StepContainer/StepContainer.tsx | 6 ++--- .../mainInput/CodeBlockComponent.tsx | 2 +- gui/src/components/markdown/FilenameLink.tsx | 2 +- gui/src/pages/Edit/CodeToEdit.tsx | 18 ++++++++------- gui/src/redux/slices/editModeState.ts | 6 +---- 8 files changed, 46 insertions(+), 33 deletions(-) diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index 4aee636bd..e509a9be9 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -129,18 +129,26 @@ export function History() { return ( {index === 0 && date > yesterday && ( - Today + + Today + )} {date < yesterday && date > lastWeek && prevDate > yesterday && ( - This Week + + This Week + )} {date < lastWeek && date > lastMonth && prevDate > lastWeek && ( - This Month + + This Month + )} {date < lastMonth && prevDate > lastMonth && ( - Older + + Older + )} { useWebviewListener( "focusEdit", - async (payload) => { - dispatch(setIsInEditMode(true)); - dispatch(focusEdit(payload)); + async () => { + dispatch(focusEdit()); navigate("/edit"); }, [navigate], diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index d38255659..733ae623b 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -13,9 +13,11 @@ export interface EditActionsProps { } export default function EditActions({ index, item }: EditActionsProps) { - const curCheckpointIndex = useSelector( - (store: RootState) => store.state.curCheckpointIndex, - ); + // const curCheckpointIndex = useSelector( + // (store: RootState) => store.state.curCheckpointIndex, + // ); + + const active = useSelector((state: RootState) => state.state.active); const applyStates = useSelector( (state: RootState) => state.state.applyStates, @@ -29,10 +31,10 @@ export default function EditActions({ index, item }: EditActionsProps) { (state) => state.status === "closed", ); - const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; + // const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; const hasPendingApplies = pendingApplyStates.length > 0; - console.log({ isCurCheckpoint, curCheckpointIndex, index }); + if (active) return; return (
    - {isCurCheckpoint && ( + {/* {isCurCheckpoint && (
    {hasPendingApplies && ( )} {hasClosedAllStreams && }
    - )} + )} */} + +
    + {hasPendingApplies && ( + + )} + {/* {hasClosedAllStreams && } */} +
    curCheckpointIndex; + // const isStepAheadOfCurCheckpoint = + // isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; useEffect(() => { if (!active) { @@ -76,7 +76,7 @@ export default function StepContainer(props: StepContainerProps) { return (
    { const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now return ( - + - + {getBasename(rif.filepath)} diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index 562c37028..b72847b10 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -36,14 +36,16 @@ export default function WorkingSet() { } } - const codeToEditItems = editModeState.codeToEdit.map((code, i) => ( - - )); + const codeToEditItems = [...editModeState.codeToEdit] + .reverse() + .map((code, i) => ( + + )); return (
    { + state.isInEditMode = true; state.editStatus = "not-started"; state.previousInputs = []; state.fileAfterEdit = undefined; @@ -40,7 +41,6 @@ export const editModeStateSlice = createSlice({ state.editStatus = "streaming"; }, removeCodeToEdit: (state, { payload }: PayloadAction) => { - // Remove entry from codeToEdit that doesn't match the payload's filepath and contents state.codeToEdit = state.codeToEdit.filter( (entry) => !( @@ -96,9 +96,6 @@ export const editModeStateSlice = createSlice({ state.editStatus = "done"; state.previousInputs = []; }, - setIsInEditMode: (state, { payload }: PayloadAction) => { - state.isInEditMode = payload; - }, }, }); @@ -111,6 +108,5 @@ export const { removeCodeToEdit, focusEdit, clearCodeToEdit, - setIsInEditMode, } = editModeStateSlice.actions; export default editModeStateSlice.reducer; From 59e6cee114b6ec6ce59b83db1409bec6e53889e4 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 20 Nov 2024 18:04:03 -0800 Subject: [PATCH 06/13] style updates --- gui/src/pages/Edit/CodeToEdit.tsx | 4 ++-- gui/src/pages/Edit/CodeToEditListItem.tsx | 2 +- gui/src/pages/Edit/Edit.tsx | 2 +- gui/src/redux/slices/stateSlice.ts | 1 + 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index b72847b10..a97bdc5e3 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -64,9 +64,9 @@ export default function WorkingSet() {
    -
    +
    {hasCodeToEdit ? ( -
      +
        {codeToEditItems}
      ) : ( diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/Edit/CodeToEditListItem.tsx index 68dda3629..7f872a4ae 100644 --- a/gui/src/pages/Edit/CodeToEditListItem.tsx +++ b/gui/src/pages/Edit/CodeToEditListItem.tsx @@ -100,7 +100,7 @@ export default function CodeToEditListItem({
    {showCodeSnippet && ( -
    +
    diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index 38fdeaad4..4c201bf29 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -179,7 +179,7 @@ export default function Edit() { Date: Thu, 21 Nov 2024 14:12:08 -0800 Subject: [PATCH 07/13] fix broken docs refs in zh-CN --- docs/docs/chat/context-selection.md | 8 ++++---- .../current/chat/context-selection.md | 8 ++++---- .../current/chat/how-it-works.md | 2 +- .../customize/model-types/autocomplete.md | 4 ++-- .../current/customize/model-types/embeddings.md | 10 +++++----- .../current/customize/overview.md | 2 +- .../current/edit/how-it-works.md | 2 +- .../current/getting-started/overview.mdx | 16 ++++++++-------- .../current/troubleshooting.md | 12 ++++++------ 9 files changed, 32 insertions(+), 32 deletions(-) diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index 072bc0128..25e85e450 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -19,19 +19,19 @@ You can include the currently open file as context by pressing cmd/ctrl - [聊天](../chat/how-to-use-it.md#how-to-use-it) 让你方便向 LLM 寻求帮助,而不需要离开 IDE + [聊天](../chat/how-to-use-it.md#如何使用它) 让你方便向 LLM 寻求帮助,而不需要离开 IDE ![chat](/img/chat.gif) - 了解更多关于 [聊天](../chat/how-to-use-it.md#how-to-use-it) + 了解更多关于 [聊天](../chat/how-to-use-it.md#如何使用它) - [自动补全](../autocomplete/how-to-use-it.md#how-to-use-it) 随着你的输入提供行内代码建议 + [自动补全](../autocomplete/how-to-use-it.md#如何使用它) 随着你的输入提供行内代码建议 ![autocomplete](/img/autocomplete.gif) - 了解更多关于 [自动补全](../autocomplete/how-to-use-it.md#how-to-use-it) + 了解更多关于 [自动补全](../autocomplete/how-to-use-it.md#如何使用它) - [编辑](../edit/how-to-use-it.md#how-to-use-it) 是一种编辑代码的方便的方式,不需要离开你的当前文件 + [编辑](../edit/how-to-use-it.md#如何使用它) 是一种编辑代码的方便的方式,不需要离开你的当前文件 ![edit](/img/edit.gif) - 了解更多关于 [编辑](../edit/how-to-use-it.md#how-to-use-it) + 了解更多关于 [编辑](../edit/how-to-use-it.md#如何使用它) - [Actions](../actions/how-to-use-it.md#how-to-use-it) 是常用情况的快捷方式 + [Actions](../actions/how-to-use-it.md#如何使用它) 是常用情况的快捷方式 ![actions](/img/actions.gif) - 了解更多关于如何使用 [Actions](../actions/how-to-use-it.md#how-to-use-it) + 了解更多关于如何使用 [Actions](../actions/how-to-use-it.md#如何使用它) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/troubleshooting.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/troubleshooting.md index 9f1ceab6a..4b5dda9ab 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/troubleshooting.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/troubleshooting.md @@ -6,11 +6,11 @@ keywords: [重新加载, 删除, 手动, 日志, 服务器, 控制台] Continue VS Code 扩展现在是 beta , JetBrains 扩展现在是 Alpha 。如果你有问题,请跟随下面的步骤。 -1. [检查日志](#check-the-logs) -2. [尝试最新的预览版](#download-the-latest-pre-release) -3. [下载较老的版本](#download-an-older-version) -4. [解析快件键问题](#keyboard-shortcuts-not-resolving) -5. [检查常见问题的 FAQ](#faqs) +1. [检查日志](#检查日志) +2. [尝试最新的预览版](#下载最新的预览版) +3. [下载较老的版本](#下载一个较老的版本) +4. [解析快件键问题](#快捷键无法解析) +5. [检查常见问题的 FAQ](#常见问题) ## 检查日志 @@ -128,4 +128,4 @@ Continue 可以在 [code-server](https://coder.com/) 中使用,但是如果你 ## 仍然有问题? -你还可以 [在这里](https://discord.gg/vapESyrFmJ) 加入我们的 Discord 社区,获得更多的支持和讨论。另外,你可以 [在这里](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=) 创建一个 GitHub issue ,提供你的问题的详情,我们将能更快的帮助你。 +你还可以 [在这里](https://discord.gg/vapESyrFmJ) 加入我们的 Discord 社区,获得更多的支持和讨论。另外,你可以 [在这里](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=) 创建一个 GitHub issue ,提供你的问题的详情,我们将能更快的帮助你。 From e0704b273be2f385d906d2915052c46ea381c42b Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 21 Nov 2024 15:23:20 -0800 Subject: [PATCH 08/13] updates based on feedback --- .../context/ImportDefinitionsService.ts | 3 +- core/autocomplete/context/ranking/index.ts | 7 +- .../context/ranking/slidingWindow.ts | 4 +- core/autocomplete/util/ast.ts | 4 +- core/autocomplete/util/types.ts | 9 +- core/commands/slash/edit.ts | 53 +++-- core/commands/util.ts | 11 +- core/index.d.ts | 33 +++- core/protocol/ideWebview.ts | 37 ++-- extensions/vscode/src/autocomplete/lsp.ts | 15 +- .../vscode/src/autocomplete/recentlyEdited.ts | 2 +- extensions/vscode/src/commands.ts | 185 +++++++++++------- .../vscode/src/diff/vertical/handler.ts | 3 +- .../vscode/src/extension/VsCodeMessenger.ts | 2 + gui/src/components/Layout.tsx | 11 ++ .../StepContainer/AcceptRejectAllButtons.tsx | 2 + gui/src/components/mainInput/TipTapEditor.tsx | 2 +- gui/src/hooks/useNavigationListener.tsx | 2 +- gui/src/pages/Edit/CodeToEdit.tsx | 48 +++-- gui/src/pages/Edit/CodeToEditListItem.tsx | 22 +-- gui/src/pages/Edit/Edit.tsx | 9 - gui/src/redux/slices/editModeState.ts | 27 ++- gui/src/redux/slices/stateSlice.ts | 2 +- gui/tailwind.config.cjs | 1 + 24 files changed, 290 insertions(+), 204 deletions(-) diff --git a/core/autocomplete/context/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts index 525834a95..128dbf78e 100644 --- a/core/autocomplete/context/ImportDefinitionsService.ts +++ b/core/autocomplete/context/ImportDefinitionsService.ts @@ -1,5 +1,4 @@ -import { IDE } from "../.."; -import { RangeInFileWithContents } from "../../commands/util"; +import { IDE, RangeInFileWithContents } from "../.."; import { PrecalculatedLruCache } from "../../util/LruCache"; import { getFullLanguageName, diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 3e83afca5..e68763746 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,7 +1,6 @@ -import { RangeInFileWithContents } from "../../../commands/util.js"; -import { Range } from "../../../index.js"; -import { countTokens } from "../../../llm/countTokens.js"; -import { HelperVars } from "../../util/HelperVars.js"; +import { Range, RangeInFileWithContents } from "../../../"; +import { countTokens } from "../../../llm/countTokens"; +import { HelperVars } from "../../util/HelperVars"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts index 7b650eb44..61c505c13 100644 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,6 +1,6 @@ -import { RangeInFileWithContents } from "../../../commands/util.js"; +import { RangeInFileWithContents } from "../../../"; -import { AutocompleteSnippet, jaccardSimilarity } from "./index.js"; +import { AutocompleteSnippet, jaccardSimilarity } from "./"; function* slidingWindow( content: string, diff --git a/core/autocomplete/util/ast.ts b/core/autocomplete/util/ast.ts index 6bd6e1f88..241c42fb9 100644 --- a/core/autocomplete/util/ast.ts +++ b/core/autocomplete/util/ast.ts @@ -1,7 +1,7 @@ import Parser from "web-tree-sitter"; -import { RangeInFileWithContents } from "../../commands/util.js"; -import { getParserForFile } from "../../util/treeSitter.js"; +import { RangeInFileWithContents } from "../../"; +import { getParserForFile } from "../../util/treeSitter"; export type AstPath = Parser.SyntaxNode[]; diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index cb9064b62..8d531d026 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -1,5 +1,10 @@ -import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../.."; -import { RangeInFileWithContents } from "../../commands/util"; +import { + Position, + Range, + RangeInFile, + RangeInFileWithContents, + TabAutocompleteOptions, +} from "../.."; export type RecentlyEditedRange = RangeInFile & { timestamp: number; diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index 78d86beee..a8f8db944 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -1,4 +1,9 @@ -import { ContextItemWithId, ILLM, SlashCommand } from "../../"; +import { + ContextItemWithId, + ILLM, + RangeInFileWithContents, + SlashCommand, +} from "../../"; import { filterCodeBlockLines, filterEnglishLinesAtEnd, @@ -13,10 +18,7 @@ import { dedentAndGetCommonWhitespace, getMarkdownLanguageTagForFile, } from "../../util/"; -import { - ctxItemToRifWithContents, - type RangeInFileWithContents, -} from "../util"; +import { ctxItemToRifWithContents } from "../util"; const PROMPT = `Take the file prefix and suffix into account, but only rewrite the code_to_edit as specified in the user_request. The code you write in modified_code_to_edit will replace the code between the code_to_edit tags. Do NOT preface your answer or write anything other than code. The tag should be written to indicate the end of the modified code section. Do not ever use nested tags. @@ -478,10 +480,18 @@ const EditSlashCommand: SlashCommand = { messages = rendered; } - const completion = llm.streamComplete(rendered as string, new AbortController().signal, { - maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096), - raw: true, - }); + const completion = llm.streamComplete( + rendered as string, + new AbortController().signal, + { + maxTokens: Math.min( + maxTokens, + Math.floor(llm.contextLength / 2), + 4096, + ), + raw: true, + }, + ); let lineStream = streamLines(completion); lineStream = filterEnglishLinesAtStart(lineStream); @@ -494,14 +504,18 @@ const EditSlashCommand: SlashCommand = { ); } else { async function* gen() { - for await (const chunk of llm.streamChat(messages, new AbortController().signal,{ - temperature: 0.5, // TODO - maxTokens: Math.min( - maxTokens, - Math.floor(llm.contextLength / 2), - 4096, - ), - })) { + for await (const chunk of llm.streamChat( + messages, + new AbortController().signal, + { + temperature: 0.5, // TODO + maxTokens: Math.min( + maxTokens, + Math.floor(llm.contextLength / 2), + 4096, + ), + }, + )) { yield stripImages(chunk.content); } } @@ -609,7 +623,10 @@ ${lines.join("\n")} Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; - for await (const update of llm.streamComplete(prompt, new AbortController().signal)) { + for await (const update of llm.streamComplete( + prompt, + new AbortController().signal, + )) { yield update; } } diff --git a/core/commands/util.ts b/core/commands/util.ts index a6be440e9..74266e70f 100644 --- a/core/commands/util.ts +++ b/core/commands/util.ts @@ -1,13 +1,4 @@ -import { ContextItemWithId } from "../"; - -export interface RangeInFileWithContents { - filepath: string; - range: { - start: { line: number; character: number }; - end: { line: number; character: number }; - }; - contents: string; -} +import { ContextItemWithId, RangeInFileWithContents } from "../"; export function ctxItemToRifWithContents( item: ContextItemWithId, diff --git a/core/index.d.ts b/core/index.d.ts index ce2e59449..d08b00b11 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -106,7 +106,7 @@ export interface ILLM extends LLMOptions { complete( prompt: string, signal: AbortSignal, - options?: LLMFullCompletionOptions + options?: LLMFullCompletionOptions, ): Promise; streamComplete( @@ -1012,6 +1012,37 @@ interface ModelRoles { repoMapFileSelection?: string; } +export type EditStatus = + | "not-started" + | "streaming" + | "accepting" + | "accepting:full-diff" + | "done"; + +export type ApplyStateStatus = + | "streaming" // Changes are being applied to the file + | "done" // All changes have been applied, awaiting user to accept/reject + | "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed" + +export interface ApplyState { + streamId: string; + status?: ApplyStateStatus; + numDiffs?: number; + filepath?: string; + fileContent?: string; +} + +export interface RangeInFileWithContents { + filepath: string; + range: { + start: { line: number; character: number }; + end: { line: number; character: number }; + }; + contents: string; +} + +export type CodeToEdit = RangeInFileWithContents | FileWithContents; + /** * Represents the configuration for a quick action in the Code Lens. * Quick actions are custom commands that can be added to function and class declarations. diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 4dd0aa2d8..a4d9f923a 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -1,8 +1,14 @@ -import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js"; -import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; +import { ToIdeFromWebviewOrCoreProtocol } from "./ide"; +import { ToWebviewFromIdeOrCoreProtocol } from "./webview"; -import type { RangeInFileWithContents } from "../commands/util.js"; -import type { ContextSubmenuItem, MessageContent } from "../index.js"; +import type { + ApplyState, + CodeToEdit, + ContextSubmenuItem, + EditStatus, + MessageContent, + RangeInFileWithContents, +} from "../"; export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { onLoad: [ @@ -54,26 +60,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "edit/escape": [undefined, void]; }; -export type EditStatus = - | "not-started" - | "streaming" - | "accepting" - | "accepting:full-diff" - | "done"; - -export type ApplyStateStatus = - | "streaming" // Changes are being applied to the file - | "done" // All changes have been applied, awaiting user to accept/reject - | "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed" - -export interface ApplyState { - streamId: string; - status?: ApplyStateStatus; - numDiffs?: number; - filepath?: string; - fileContent?: string; -} - export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap @@ -94,7 +80,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { }, void, ]; - addCodeToEdit: [RangeInFileWithContents, void]; + addCodeToEdit: [CodeToEdit, void]; navigateTo: [{ path: string; toggle?: boolean }, void]; addModel: [undefined, void]; @@ -118,4 +104,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void]; exitEditMode: [undefined, void]; focusEdit: [undefined, void]; + focusEditWithoutClear: [undefined, void]; }; diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index f900058ab..90b034a2e 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -2,7 +2,6 @@ import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider" import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; -import { RangeInFileWithContents } from "core/commands/util"; import { FUNCTION_BLOCK_NODE_TYPES, FUNCTION_DECLARATION_NODE_TYPEs, @@ -10,7 +9,7 @@ import { import { intersection } from "core/util/ranges"; import * as vscode from "vscode"; -import type { IDE, Range, RangeInFile } from "core"; +import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core"; import type Parser from "web-tree-sitter"; type GotoProviderName = @@ -134,7 +133,9 @@ async function crawlTypes( // Parse AST const ast = await getAst(rif.filepath, contents); - if (!ast) {return results;} + if (!ast) { + return results; + } const astLineCount = ast.rootNode.text.split("\n").length; // Find type identifiers @@ -343,10 +344,14 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( ): Promise => { try { const ast = await getAst(filepath, contents); - if (!ast) {return [];} + if (!ast) { + return []; + } const treePath = await getTreePathAtCursor(ast, cursorIndex); - if (!treePath) {return [];} + if (!treePath) { + return []; + } const results: RangeInFileWithContents[] = []; for (const node of treePath.reverse()) { diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 0b206eab2..221d7df66 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -1,6 +1,6 @@ +import { RangeInFileWithContents } from "core"; import { getSymbolsForSnippet } from "core/autocomplete/context/ranking"; import { RecentlyEditedRange } from "core/autocomplete/util/types"; -import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; type VsCodeRecentlyEditedRange = { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index b4252f8dd..22e9fe10b 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -3,9 +3,8 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -import { ContextMenuConfig } from "core"; +import { ContextMenuConfig, RangeInFileWithContents } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; -import { RangeInFileWithContents } from "core/commands/util"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -201,6 +200,58 @@ function hideGUI() { } } +async function processDiff( + action: "accept" | "reject", + sidebar: ContinueGUIWebviewViewProvider, + diffManager: DiffManager, + ide: VsCodeIde, + verticalDiffManager: VerticalDiffManager, + newFilepath?: string | vscode.Uri, + streamId?: string, +) { + captureCommandTelemetry(`${action}Diff`); + + let fullPath = newFilepath; + + if (fullPath instanceof vscode.Uri) { + fullPath = fullPath.fsPath; + } else if (fullPath) { + fullPath = getFullyQualifiedPath(ide, fullPath); + } else { + console.warn(`Unable to resolve filepath: ${newFilepath}`); + } + + if (!fullPath) return; + + await ide.openFile(fullPath); + + // Clear vertical diffs depending on action + verticalDiffManager.clearForFilepath(fullPath, action === "accept"); + + // Accept or reject the diff + if (action === "accept") { + await diffManager.acceptDiff(fullPath); + } else { + await diffManager.rejectDiff(fullPath); + } + + void sidebar.webviewProtocol.request("setEditStatus", { + status: "done", + }); + + if (streamId) { + const fileContent = await ide.readFile(fullPath); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: fullPath, + streamId, + status: "closed", + numDiffs: 0, + }); + } +} + // Copy everything over from extension.ts const commandsMap: ( ide: VsCodeIde, @@ -267,77 +318,34 @@ const commandsMap: ( range, ); } - return { "continue.acceptDiff": async ( newFilepath?: string | vscode.Uri, streamId?: string, - ) => { - captureCommandTelemetry("acceptDiff"); + ) => + processDiff( + "accept", + sidebar, + diffManager, + ide, + verticalDiffManager, + newFilepath, + streamId, + ), - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - } - - verticalDiffManager.clearForFilepath(fullPath, true); - await diffManager.acceptDiff(fullPath); - - void sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - - if (streamId && fullPath) { - const fileContent = await ide.readFile(fullPath); - - await sidebar.webviewProtocol.request("updateApplyState", { - fileContent, - filepath: fullPath, - streamId: streamId, - status: "closed", - numDiffs: 0, - }); - } - }, "continue.rejectDiff": async ( newFilepath?: string | vscode.Uri, streamId?: string, - ) => { - captureCommandTelemetry("rejectDiff"); - - let fullPath = newFilepath; - - if (fullPath instanceof vscode.Uri) { - fullPath = fullPath.fsPath; - } else if (fullPath) { - fullPath = getFullyQualifiedPath(ide, fullPath); - } else { - console.warn(`Unable to resolve filepath: ${newFilepath}`); - } - - verticalDiffManager.clearForFilepath(fullPath, false); - await diffManager.rejectDiff(fullPath); - void sidebar.webviewProtocol.request("setEditStatus", { - status: "done", - }); - - if (streamId && fullPath) { - const fileContent = await ide.readFile(fullPath); - - await sidebar.webviewProtocol.request("updateApplyState", { - fileContent, - filepath: fullPath, - streamId: streamId, - status: "closed", - numDiffs: 0, - }); - } - }, + ) => + processDiff( + "reject", + sidebar, + diffManager, + ide, + verticalDiffManager, + newFilepath, + streamId, + ), "continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => { captureCommandTelemetry("acceptVerticalDiffBlock"); verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index); @@ -453,8 +461,6 @@ const commandsMap: ( void addHighlightedCodeToContext(sidebar.webviewProtocol); } }, - // TODO - "continue.focusEditWithoutClear": async () => {}, "continue.focusEdit": async () => { captureCommandTelemetry("focusEdit"); focusGUI(); @@ -501,6 +507,51 @@ const commandsMap: ( sidebar.webviewProtocol?.request("focusContinueInput", undefined); }, 30); }, + "continue.focusEditWithoutClear": async () => { + captureCommandTelemetry("focusEditWithoutClear"); + focusGUI(); + + sidebar.webviewProtocol?.request("focusEditWithoutClear", undefined); + + const editor = vscode.window.activeTextEditor; + + if (!editor) { + return; + } + + const document = editor.document; + + const existingDiff = verticalDiffManager.getHandlerForFile( + document.fileName, + ); + + // If there's a diff currently being applied, then we just toggle focus back to the input + if (existingDiff) { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + return; + } + + const rangeInFileWithContents = getCurrentlyHighlightedCode(false); + + if (rangeInFileWithContents) { + sidebar.webviewProtocol?.request( + "addCodeToEdit", + rangeInFileWithContents, + ); + } else { + const filepath = document.uri.fsPath; + const contents = document.getText(); + + sidebar.webviewProtocol?.request("addCodeToEdit", { + filepath, + contents, + }); + } + + setTimeout(() => { + sidebar.webviewProtocol?.request("focusContinueInput", undefined); + }, 30); + }, "continue.exitEditMode": async () => { captureCommandTelemetry("exitEditMode"); await sidebar.webviewProtocol?.request("exitEditMode", undefined); diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index 3286749a6..c68619277 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -1,4 +1,3 @@ -import { ApplyState } from "core/protocol/ideWebview"; import * as vscode from "vscode"; import { @@ -10,7 +9,7 @@ import { } from "./decorations"; import type { VerticalDiffCodeLens } from "./manager"; -import type { DiffLine } from "core"; +import type { ApplyState, DiffLine } from "core"; export interface VerticalDiffHandlerOptions { input?: string; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 3b5baad5f..b031241c6 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -255,7 +255,9 @@ export class VsCodeMessenger { llm, fastLlm, ); + const verticalDiffManager = await this.verticalDiffManagerPromise; + if (instant) { await verticalDiffManager.streamDiffLines( diffLines, diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index f4598ec8f..b7006a9a8 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -12,6 +12,7 @@ import { setEditStatus, addCodeToEdit, focusEdit, + clearCodeToEdit, } from "../redux/slices/editModeState"; import { setShowDialog } from "../redux/slices/uiStateSlice"; import { @@ -192,6 +193,16 @@ const Layout = () => { useWebviewListener( "focusEdit", + async () => { + dispatch(focusEdit()); + dispatch(clearCodeToEdit()); + navigate("/edit"); + }, + [navigate], + ); + + useWebviewListener( + "focusEditWithoutClear", async () => { dispatch(focusEdit()); navigate("/edit"); diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index 6a2574bc0..c6f06979d 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -13,6 +13,8 @@ export default function AcceptRejectAllButtons({ onAcceptOrReject, }: AcceptRejectAllButtonsProps) { const ideMessenger = useContext(IdeMessengerContext); + + // To handle the case of a single-range edit const hasSinglePendingApplyStates = pendingApplyStates.length === 1; async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") { diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 67d71eee8..bde052274 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -4,7 +4,7 @@ import Image from "@tiptap/extension-image"; import Paragraph from "@tiptap/extension-paragraph"; import Placeholder from "@tiptap/extension-placeholder"; import Text from "@tiptap/extension-text"; -import { Plugin, PluginKey } from "@tiptap/pm/state"; +import { Plugin } from "@tiptap/pm/state"; import { Editor, EditorContent, JSONContent, useEditor } from "@tiptap/react"; import { ContextItemWithId, diff --git a/gui/src/hooks/useNavigationListener.tsx b/gui/src/hooks/useNavigationListener.tsx index cadc40330..503b4a997 100644 --- a/gui/src/hooks/useNavigationListener.tsx +++ b/gui/src/hooks/useNavigationListener.tsx @@ -1,5 +1,5 @@ import type { ToWebviewProtocol } from "core/protocol"; -import { useLocation, useNavigate } from "react-router-dom"; +import { useNavigate } from "react-router-dom"; import { v4 as uuidv4 } from "uuid"; import { useWebviewListener } from "./useWebviewListener"; diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index a97bdc5e3..7f990415b 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -1,13 +1,13 @@ -import { InformationCircleIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { PlusIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { useDispatch, useSelector } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { CodeToEdit, removeCodeToEdit } from "../../redux/slices/editModeState"; +import { removeCodeToEdit } from "../../redux/slices/editModeState"; import { RootState } from "../../redux/store"; import CodeToEditListItem from "./CodeToEditListItem"; -import { RangeInFileWithContents } from "core/commands/util"; import { vscEditorBackground } from "../../components"; import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; +import { CodeToEdit, RangeInFileWithContents } from "core"; export default function WorkingSet() { const dispatch = useDispatch(); @@ -16,6 +16,15 @@ export default function WorkingSet() { const hasCodeToEdit = editModeState.codeToEdit.length > 0; + const addFileText = hasCodeToEdit ? "Add file" : "Add a file to get started"; + + const title = + editModeState.codeToEdit.length === 0 + ? "Code to edit" + : editModeState.codeToEdit.length === 1 + ? "Code to edit (1 item)" + : `Code to edit (${editModeState.codeToEdit.length} items)`; + function onDelete(rif: RangeInFileWithContents) { dispatch(removeCodeToEdit(rif)); } @@ -48,37 +57,24 @@ export default function WorkingSet() { )); return ( -
    -
    - Code to edit +
    +
    + {title} - Add file + {addFileText}
    -
    - {hasCodeToEdit ? ( -
      - {codeToEditItems} -
    - ) : ( - - - Add a file to get started - - )} -
    + {hasCodeToEdit && ( +
      + {codeToEditItems} +
    + )}
    ); } diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/Edit/CodeToEditListItem.tsx index 7f872a4ae..f6ddca996 100644 --- a/gui/src/pages/Edit/CodeToEditListItem.tsx +++ b/gui/src/pages/Edit/CodeToEditListItem.tsx @@ -9,12 +9,12 @@ import { useState } from "react"; import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview"; import { getMarkdownLanguageTagForFile } from "core/util"; import styled from "styled-components"; -import { CodeToEdit } from "../../redux/slices/editModeState"; +import { CodeToEdit } from "core"; export interface CodeToEditListItemProps { code: CodeToEdit; - onDelete: (code: CodeToEdit) => void; - onClickFilename: (code: CodeToEdit) => void; + onDelete: (codeToEdit: CodeToEdit) => void; + onClickFilename: (codeToEdit: CodeToEdit) => void; } // Easiest method to overwrite the top level styling of the markdown preview @@ -26,7 +26,7 @@ const NoPaddingWrapper = styled.div` pre { margin: 0 !important; - padding: 0 !important; + padding: 0px 0px 0px 10px !important; } `; @@ -35,13 +35,13 @@ export default function CodeToEditListItem({ onDelete, onClickFilename, }: CodeToEditListItemProps) { - const [showCodeSnippet, setShowCodeSnippet] = useState(true); + const [showCodeSnippet, setShowCodeSnippet] = useState(false); const filepath = code.filepath.split("/").pop() || code.filepath; let title = filepath; if ("range" in code) { - title += `(${code.range.start.line + 1} - ${code.range.end.line + 1})`; + title += ` (${code.range.start.line + 1} - ${code.range.end.line + 1})`; } const source = @@ -54,11 +54,11 @@ export default function CodeToEditListItem({ return (
  • setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet)} >
    {showCodeSnippet ? ( @@ -67,7 +67,7 @@ export default function CodeToEditListItem({ e.stopPropagation(); setShowCodeSnippet(false); }} - className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" + className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 hover:bg-opacity-20" /> ) : ( )} @@ -95,7 +95,7 @@ export default function CodeToEditListItem({ e.stopPropagation(); onDelete(code); }} - className="h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 text-gray-400 transition-colors hover:bg-white/10" + className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-md rounded-sm p-0.5 hover:bg-opacity-20" />
    diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index 4c201bf29..522f99fda 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -20,7 +20,6 @@ import useChatHandler from "../../hooks/useChatHandler"; import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import StepContainer from "../../components/StepContainer"; -import styled from "styled-components"; import getMultifileEditPrompt from "./getMultifileEditPrompt"; import { RangeInFileWithContents } from "core/commands/util"; @@ -121,14 +120,6 @@ export default function Edit() { stripImages(userInstructions), ].join("\n\n"); - const codeToEdit = editModeState.codeToEdit[0]; - - let rif: RangeInFileWithContents = { - filepath: codeToEdit.filepath, - contents: codeToEdit.contents, - range: "range" in codeToEdit ? codeToEdit.range : undefined, - }; - ideMessenger.post("edit/sendPrompt", { prompt, range: editModeState.codeToEdit[0] as RangeInFileWithContents, diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index 9f370c95a..489bc7b41 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -1,9 +1,5 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { FileWithContents, MessageContent } from "core"; -import { RangeInFileWithContents } from "core/commands/util"; -import { EditStatus } from "core/protocol/ideWebview"; - -export type CodeToEdit = RangeInFileWithContents | FileWithContents; +import { CodeToEdit, EditStatus, MessageContent } from "core"; interface EditModeState { editStatus: EditStatus; @@ -20,15 +16,22 @@ const initialState: EditModeState = { isInEditMode: false, }; +function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { + return a.filepath === b.filepath && a.contents === b.contents; +} + export const editModeStateSlice = createSlice({ name: "editModeState", initialState, reducers: { addCodeToEdit: (state, { payload }: PayloadAction) => { - state.codeToEdit.push(payload); - state.editStatus = "not-started"; - state.previousInputs = []; - state.fileAfterEdit = undefined; + const entryExists = state.codeToEdit.some((entry) => + isCodeToEditEqual(entry, payload), + ); + + if (!entryExists) { + state.codeToEdit.push(payload); + } }, focusEdit: (state) => { state.isInEditMode = true; @@ -42,11 +45,7 @@ export const editModeStateSlice = createSlice({ }, removeCodeToEdit: (state, { payload }: PayloadAction) => { state.codeToEdit = state.codeToEdit.filter( - (entry) => - !( - entry.filepath === payload.filepath && - entry.contents === payload.contents - ), + (entry) => !isCodeToEditEqual(entry, payload), ); }, clearCodeToEdit: (state) => { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 17c317ee5..71e26711d 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -1,6 +1,7 @@ import { PayloadAction, createSlice } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/react"; import { + ApplyState, ChatHistoryItem, ChatMessage, Checkpoint, @@ -13,7 +14,6 @@ import { import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { ApplyState } from "core/protocol/ideWebview"; import { v4 as uuidv4, v4 } from "uuid"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index 5758b18db..bc8b5273e 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -25,6 +25,7 @@ module.exports = { "spin-slow": "spin 6s linear infinite", }, colors: { + lightgray: "#999998", "vsc-background": "rgb(var(--vsc-background) / )", "secondary-dark": "rgb(var(--secondary-dark) / )", "vsc-input-background": "var(--vscode-input-background, rgb(45 45 45))", From f5684d7ca1cb3404bc77d82d4495611b97654876 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 21 Nov 2024 17:24:37 -0800 Subject: [PATCH 09/13] add option to add all open files --- gui/src/pages/Edit/AddFileButton.tsx | 79 ++++++++++++++++++++++++++++ gui/src/pages/Edit/CodeToEdit.tsx | 20 ++----- 2 files changed, 82 insertions(+), 17 deletions(-) create mode 100644 gui/src/pages/Edit/AddFileButton.tsx diff --git a/gui/src/pages/Edit/AddFileButton.tsx b/gui/src/pages/Edit/AddFileButton.tsx new file mode 100644 index 000000000..93611e9f7 --- /dev/null +++ b/gui/src/pages/Edit/AddFileButton.tsx @@ -0,0 +1,79 @@ +import { useContext, useState, useRef, useEffect } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; +import { useDispatch } from "react-redux"; +import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline"; +import { addCodeToEdit } from "../../redux/slices/editModeState"; +import { Listbox } from "@headlessui/react"; + +export default function AddFileButton() { + const [showAbove, setShowAbove] = useState(false); + const buttonRef = useRef(null); + const ideMessenger = useContext(IdeMessengerContext); + const dispatch = useDispatch(); + + function onClickAddFileToCodeToEdit() { + dispatch(setShouldAddFileForEditing(true)); + } + + async function handleAddAllOpenFiles() { + const openFiles = await ideMessenger.ide.getOpenFiles(); + + for (const filepath of openFiles) { + const contents = await ideMessenger.ide.readFile(filepath); + console.log({ filepath, contents }); + dispatch(addCodeToEdit({ filepath, contents })); + } + } + + // function calculatePosition() { + // const rect = buttonRef.current?.getBoundingClientRect(); + // if (!rect) return; + // const spaceBelow = window.innerHeight - rect.bottom; + // const spaceAbove = rect.top; + // const dropdownHeight = 300; + + // setShowAbove(spaceBelow < dropdownHeight && spaceAbove > spaceBelow); + // } + + return ( + +
    + +
    { + e.preventDefault(); + e.stopPropagation(); + onClickAddFileToCodeToEdit(); + }} + > + + Add file +
    + +
    + + + + + + + Add all open files + + +
    + + ); +} diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index 7f990415b..984d724f8 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -1,13 +1,12 @@ -import { PlusIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { useDispatch, useSelector } from "react-redux"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { removeCodeToEdit } from "../../redux/slices/editModeState"; import { RootState } from "../../redux/store"; import CodeToEditListItem from "./CodeToEditListItem"; -import { vscEditorBackground } from "../../components"; -import { setShouldAddFileForEditing } from "../../redux/slices/uiStateSlice"; + import { CodeToEdit, RangeInFileWithContents } from "core"; +import AddFileButton from "./AddFileButton"; export default function WorkingSet() { const dispatch = useDispatch(); @@ -16,8 +15,6 @@ export default function WorkingSet() { const hasCodeToEdit = editModeState.codeToEdit.length > 0; - const addFileText = hasCodeToEdit ? "Add file" : "Add a file to get started"; - const title = editModeState.codeToEdit.length === 0 ? "Code to edit" @@ -29,10 +26,6 @@ export default function WorkingSet() { dispatch(removeCodeToEdit(rif)); } - function onClickAddFileToCodeToEdit() { - dispatch(setShouldAddFileForEditing(true)); - } - function onClickFilename(code: CodeToEdit) { if ("range" in code) { ideMessenger.ide.showLines( @@ -60,14 +53,7 @@ export default function WorkingSet() {
    {title} - - - - {addFileText} - +
    {hasCodeToEdit && ( From f95eff5712c74072f717fb0527f1afee7318d290 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 21 Nov 2024 17:30:00 -0800 Subject: [PATCH 10/13] Update AddFileButton.tsx --- gui/src/pages/Edit/AddFileButton.tsx | 17 +---------------- 1 file changed, 1 insertion(+), 16 deletions(-) diff --git a/gui/src/pages/Edit/AddFileButton.tsx b/gui/src/pages/Edit/AddFileButton.tsx index 93611e9f7..65470c7ad 100644 --- a/gui/src/pages/Edit/AddFileButton.tsx +++ b/gui/src/pages/Edit/AddFileButton.tsx @@ -7,7 +7,6 @@ import { addCodeToEdit } from "../../redux/slices/editModeState"; import { Listbox } from "@headlessui/react"; export default function AddFileButton() { - const [showAbove, setShowAbove] = useState(false); const buttonRef = useRef(null); const ideMessenger = useContext(IdeMessengerContext); const dispatch = useDispatch(); @@ -21,27 +20,15 @@ export default function AddFileButton() { for (const filepath of openFiles) { const contents = await ideMessenger.ide.readFile(filepath); - console.log({ filepath, contents }); dispatch(addCodeToEdit({ filepath, contents })); } } - // function calculatePosition() { - // const rect = buttonRef.current?.getBoundingClientRect(); - // if (!rect) return; - // const spaceBelow = window.innerHeight - rect.bottom; - // const spaceAbove = rect.top; - // const dropdownHeight = 300; - - // setShowAbove(spaceBelow < dropdownHeight && spaceAbove > spaceBelow); - // } - return (
    Date: Thu, 21 Nov 2024 17:33:20 -0800 Subject: [PATCH 11/13] update type imports --- gui/src/components/StepContainer/AcceptRejectAllButtons.tsx | 2 +- .../markdown/StepContainerPreToolbar/ApplyActions.tsx | 2 +- gui/src/pages/Edit/CodeToEditListItem.tsx | 1 - gui/src/pages/Edit/Edit.tsx | 3 +-- gui/src/pages/Edit/getMultifileEditPrompt.ts | 3 +-- 5 files changed, 4 insertions(+), 7 deletions(-) diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index c6f06979d..d8a17ec8a 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -1,7 +1,7 @@ import { useContext } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; -import { ApplyState } from "core/protocol/ideWebview"; +import { ApplyState } from "core"; export interface AcceptRejectAllButtonsProps { pendingApplyStates: ApplyState[]; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx index 286277d4f..d96afc7fe 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx @@ -1,10 +1,10 @@ import { CheckIcon, XMarkIcon, PlayIcon } from "@heroicons/react/24/outline"; import Spinner from "./Spinner"; import { lightGray, vscForeground } from "../.."; -import { ApplyState } from "core/protocol/ideWebview"; import { useState } from "react"; import { getMetaKeyLabel } from "../../../util"; import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip"; +import { ApplyState } from "core"; interface ApplyActionsProps { applyState?: ApplyState; diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/Edit/CodeToEditListItem.tsx index f6ddca996..8d84ef34b 100644 --- a/gui/src/pages/Edit/CodeToEditListItem.tsx +++ b/gui/src/pages/Edit/CodeToEditListItem.tsx @@ -1,4 +1,3 @@ -import { RangeInFileWithContents } from "core/commands/util"; import FileIcon from "../../components/FileIcon"; import { ChevronDownIcon, diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx index 522f99fda..c69200bc1 100644 --- a/gui/src/pages/Edit/Edit.tsx +++ b/gui/src/pages/Edit/Edit.tsx @@ -1,6 +1,6 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/core"; -import { InputModifiers } from "core"; +import { InputModifiers, RangeInFileWithContents } from "core"; import { stripImages } from "core/llm/images"; import { useCallback, useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; @@ -21,7 +21,6 @@ import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectA import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import StepContainer from "../../components/StepContainer"; import getMultifileEditPrompt from "./getMultifileEditPrompt"; -import { RangeInFileWithContents } from "core/commands/util"; const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ "codebase", diff --git a/gui/src/pages/Edit/getMultifileEditPrompt.ts b/gui/src/pages/Edit/getMultifileEditPrompt.ts index ce0adb1b6..8f526f1e2 100644 --- a/gui/src/pages/Edit/getMultifileEditPrompt.ts +++ b/gui/src/pages/Edit/getMultifileEditPrompt.ts @@ -1,5 +1,4 @@ -import { RangeInFileWithContents } from "core/commands/util"; -import { CodeToEdit } from "../../redux/slices/editModeState"; +import { CodeToEdit } from "core"; export default function getMultifileEditPrompt( codeToEdit: CodeToEdit[], From a47153a000016ff3a501fcce359568de7d09bab2 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 21 Nov 2024 17:40:21 -0800 Subject: [PATCH 12/13] update styling --- extensions/vscode/package.json | 7 +------ gui/src/pages/Edit/AddFileButton.tsx | 12 +++++++----- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index faea45aed..3e18a0f90 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -199,12 +199,6 @@ "title": "Debug Terminal", "group": "Continue" }, - { - "command": "continue.focusEdit", - "category": "Continue", - "title": "Edit code with natural language", - "group": "Continue" - }, { "command": "continue.exitEditMode", "category": "Continue", @@ -370,6 +364,7 @@ }, { "command": "continue.focusEdit", + "title": "Edit code with natural language", "mac": "cmd+i", "key": "ctrl+i" }, diff --git a/gui/src/pages/Edit/AddFileButton.tsx b/gui/src/pages/Edit/AddFileButton.tsx index 65470c7ad..2f9e0f0dd 100644 --- a/gui/src/pages/Edit/AddFileButton.tsx +++ b/gui/src/pages/Edit/AddFileButton.tsx @@ -29,7 +29,7 @@ export default function AddFileButton() {
    - - Add file + + + Add file +
    - + Add all open files From e4e6ff77f1855a8a18df638aff84a27f80c5a587 Mon Sep 17 00:00:00 2001 From: Test Date: Thu, 21 Nov 2024 17:47:03 -0800 Subject: [PATCH 13/13] remove scrollbar-hide package --- gui/package.json | 1 - gui/src/pages/Edit/CodeToEdit.tsx | 2 +- gui/tailwind.config.cjs | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/gui/package.json b/gui/package.json index b0fe1809d..ef77ac910 100644 --- a/gui/package.json +++ b/gui/package.json @@ -64,7 +64,6 @@ "socket.io-client": "^4.7.2", "styled-components": "^5.3.6", "table": "^6.8.1", - "tailwind-scrollbar-hide": "^1.1.7", "tippy.js": "^6.3.7", "unist-util-visit": "^5.0.0", "uuid": "^9.0.1", diff --git a/gui/src/pages/Edit/CodeToEdit.tsx b/gui/src/pages/Edit/CodeToEdit.tsx index 984d724f8..26cb145d4 100644 --- a/gui/src/pages/Edit/CodeToEdit.tsx +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -57,7 +57,7 @@ export default function WorkingSet() {
    {hasCodeToEdit && ( -
      +
        {codeToEditItems}
      )} diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index bc8b5273e..7ec8df9e8 100644 --- a/gui/tailwind.config.cjs +++ b/gui/tailwind.config.cjs @@ -54,7 +54,7 @@ module.exports = { }, }, }, - plugins: [require("tailwind-scrollbar-hide")], + plugins: [], corePlugins: { preflight: false, },