From f90d4bc5020de215b556ff48bd8c26357644cb13 Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 20 Nov 2024 16:36:53 -0800 Subject: [PATCH] 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