WIP: handle whole file additions

This commit is contained in:
Test 2024-11-20 16:36:53 -08:00
parent 0ac11c5398
commit f90d4bc502
14 changed files with 321 additions and 118 deletions

View file

@ -94,7 +94,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
},
void,
];
addRIFToCodeToEdit: [RangeInFileWithContents, void];
addCodeToEdit: [RangeInFileWithContents, void];
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];

View file

@ -486,7 +486,7 @@ const commandsMap: (
if (rangeInFileWithContents) {
sidebar.webviewProtocol?.request(
"addRIFToCodeToEdit",
"addCodeToEdit",
rangeInFileWithContents,
);

View file

@ -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],
);

View file

@ -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,
);

View file

@ -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<string, any>;
renderHTML: (props: {
options: MentionOptions;
node: ProseMirrorNode;
}) => DOMOutputSpec;
suggestion: Omit<SuggestionOptions, "editor">;
};
export const AddCodeToEditPluginKey = new PluginKey("add-code-to-edit");
export const AddCodeToEdit = Node.create<MentionOptions>({
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,
}),
];
},
});

View file

@ -28,6 +28,8 @@ export const Mention = Node.create<MentionOptions>({
];
},
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<MentionOptions>({
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();
},

View file

@ -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(

View file

@ -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 <SyntaxHighlightedPre {...preProps} />;

View file

@ -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) => (
<CodeToEditListItem
key={rif.filepath + rif.range.start.line + rif.range.end.line}
rif={rif}
key={code.filepath + i}
code={code}
onDelete={onDelete}
onClickFilename={onClickFilename}
/>
@ -47,7 +50,7 @@ export default function WorkingSet() {
className="mx-1 flex flex-col rounded-t-lg px-1 pb-1"
style={{ backgroundColor: vscEditorBackground }}
>
<div className="flex items-center justify-between gap-1.5 border-0 border-b border-solid border-neutral-500 px-1 py-1.5 text-xs text-neutral-500">
<div className="flex items-center justify-between gap-1.5 px-1 py-1.5 text-xs text-neutral-500">
<span>Code to edit</span>
<span

View file

@ -9,11 +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";
export interface CodeToEditListItemProps {
rif: RangeInFileWithContents;
onDelete: (rif: RangeInFileWithContents) => 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"
/>
)}
<FileIcon filename={rif.filepath} height={"18px"} width={"18px"} />
<FileIcon filename={code.filepath} height={"18px"} width={"18px"} />
<span
className="text-xs hover:underline"
onClick={(e) => {
e.stopPropagation();
onClickFilename(rif);
onClickFilename(code);
}}
>
{title}
@ -88,7 +93,7 @@ export default function CodeToEditListItem({
<XMarkIcon
onClick={(e) => {
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"
/>

View file

@ -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() {
/>
</div>
{!isSingleFileEdit && history.length > 1 && (
{!isSingleRangeEdit && history.length > 1 && (
<div>
{history.slice(1).map((item, index: number) => (
<div>
@ -230,14 +227,14 @@ export default function Edit() {
)}
<div className="mt-2">
{hasPendingApplies && isSingleFileEdit && (
{hasPendingApplies && isSingleRangeEdit && (
<AcceptRejectAllButtons
pendingApplyStates={pendingApplyStates}
onAcceptOrReject={() => dispatch(clearCodeToEdit())}
/>
)}
{!hasPendingApplies && isSingleFileEdit && (
{!hasPendingApplies && isSingleRangeEdit && (
<NewSessionButton
onClick={handleBackClick}
className="mr-auto flex items-center gap-2"

View file

@ -1,13 +1,14 @@
import { RangeInFileWithContents } from "core/commands/util";
import { CodeToEdit } from "../../redux/slices/editModeState";
export default function getMultifileEditPrompt(
rifs: RangeInFileWithContents[],
codeToEdit: CodeToEdit[],
): string {
const filesToEditStr = rifs
const codeToEditStr = codeToEdit
.map(
(rif) => `
\`\`\` ${rif.filepath}
${rif.contents}
(code) => `
\`\`\` ${code.filepath}
${code.contents}
\`\`\`
`,
)
@ -48,7 +49,7 @@ Summary:
Here are the files to base your edits on:
<files>
${filesToEditStr}
${codeToEditStr}
</files>
Please provide the multi-file edit details based on the engineer's request below:

View file

@ -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<RangeInFileWithContents>,
) => {
addCodeToEdit: (state, { payload }: PayloadAction<CodeToEdit>) => {
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<RangeInFileWithContents>,
) => {
removeCodeToEdit: (state, { payload }: PayloadAction<CodeToEdit>) => {
// 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,

View file