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/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/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 addbb7e6f..d9f26d1b9 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1016,6 +1016,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 1d18e1a6f..91fa40395 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: [ @@ -53,30 +59,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "edit/escape": [undefined, void]; }; -export interface EditModeArgs { - highlightedCode: RangeInFileWithContents; -} - -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 @@ -97,6 +79,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { }, void, ]; + addCodeToEdit: [CodeToEdit, void]; navigateTo: [{ path: string; toggle?: boolean }, void]; addModel: [undefined, void]; @@ -116,7 +99,8 @@ 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]; + focusEditWithoutClear: [undefined, void]; }; 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 ,提供你的问题的详情,我们将能更快的帮助你。 diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 939638b16..8d96504f0 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -199,12 +199,6 @@ "title": "Debug Terminal", "group": "Continue" }, - { - "command": "continue.edit", - "category": "Continue", - "title": "Edit code with natural language", - "group": "Continue" - }, { "command": "continue.exitEditMode", "category": "Continue", @@ -397,10 +391,16 @@ "key": "alt+ctrl+n" }, { - "command": "continue.edit", + "command": "continue.focusEdit", + "title": "Edit code with natural language", "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/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 83db06586..43115ae93 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"; @@ -138,7 +137,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 +147,6 @@ async function addEntireFileToContext( if (type === vscode.FileType.File) { addEntireFileToContext( vscode.Uri.joinPath(filepath, filename), - edit, webviewProtocol, ); } @@ -203,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 getCommandsMap: ( ide: VsCodeIde, @@ -269,77 +318,34 @@ const getCommandsMap: ( 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); @@ -455,42 +461,96 @@ const getCommandsMap: ( void addHighlightedCodeToContext(sidebar.webviewProtocol); } }, - "continue.edit": async () => { - captureCommandTelemetry("edit"); + "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( + "addCodeToEdit", + 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.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"); @@ -703,12 +763,11 @@ const getCommandsMap: ( 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/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 1267d5781..ae7995b88 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -250,7 +250,9 @@ export class VsCodeMessenger { llm, fastLlm, ); + const verticalDiffManager = await this.verticalDiffManagerPromise; + if (instant) { await verticalDiffManager.streamDiffLines( diffLines, 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/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/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( - "startEditMode", - async (args) => { - dispatch(startEditMode(args)); + "focusEdit", + async () => { + dispatch(focusEdit()); + dispatch(clearCodeToEdit()); navigate("/edit"); }, [navigate], ); + useWebviewListener( + "focusEditWithoutClear", + async () => { + dispatch(focusEdit()); + navigate("/edit"); + }, + [navigate], + ); + + useWebviewListener( + "addCodeToEdit", + async (payload) => { + dispatch(addCodeToEdit(payload)); + }, + [navigate], + ); + useWebviewListener("setEditStatus", async ({ status, fileAfterEdit }) => { dispatch(setEditStatus({ status, fileAfterEdit })); }); diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx index a1e7b28f6..d8a17ec8a 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx @@ -1,17 +1,22 @@ 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[]; + onAcceptOrReject?: () => void; } export default function AcceptRejectAllButtons({ pendingApplyStates, + 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") { for (const { filepath, streamId } of pendingApplyStates) { ideMessenger.post(status, { @@ -19,8 +24,11 @@ export default function AcceptRejectAllButtons({ streamId, }); } - } + if (onAcceptOrReject) { + onAcceptOrReject(); + } + } return (
); diff --git a/gui/src/components/StepContainer/MultifileEditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx similarity index 69% rename from gui/src/components/StepContainer/MultifileEditActions.tsx rename to gui/src/components/StepContainer/EditActions.tsx index 5fb7122df..733ae623b 100644 --- a/gui/src/components/StepContainer/MultifileEditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -7,18 +7,17 @@ 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 MultifileEditActions({ - index, - item, -}: MultifileEditActionsProps) { - const curCheckpointIndex = useSelector( - (store: RootState) => store.state.curCheckpointIndex, - ); +export default function EditActions({ index, item }: EditActionsProps) { + // const curCheckpointIndex = useSelector( + // (store: RootState) => store.state.curCheckpointIndex, + // ); + + const active = useSelector((state: RootState) => state.state.active); const applyStates = useSelector( (state: RootState) => state.state.applyStates, @@ -32,23 +31,32 @@ export default function MultifileEditActions({ (state) => state.status === "closed", ); - const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; + // const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex; const hasPendingApplies = pendingApplyStates.length > 0; + if (active) return; + return (
- {isCurCheckpoint && ( + {/* {isCurCheckpoint && (
{hasPendingApplies && ( )} {hasClosedAllStreams && }
- )} + )} */} + +
+ {hasPendingApplies && ( + + )} + {/* {hasClosedAllStreams && } */} +
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..9223a4044 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; + // const isStepAheadOfCurCheckpoint = + // isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; useEffect(() => { if (!active) { @@ -76,7 +76,7 @@ export default function StepContainer(props: StepContainerProps) { return (
; + 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/CodeBlockComponent.tsx b/gui/src/components/mainInput/CodeBlockComponent.tsx index 51e57cae1..a8f3eeeb1 100644 --- a/gui/src/components/mainInput/CodeBlockComponent.tsx +++ b/gui/src/components/mainInput/CodeBlockComponent.tsx @@ -14,7 +14,7 @@ export const CodeBlockComponent = (props: any) => { const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now return ( - + ` resize: none; @@ -158,7 +161,6 @@ interface TipTapEditorProps { toolbarOptions?: ToolbarOptions; border?: string; placeholder?: string; - header?: React.ReactNode; historyKey: string; } @@ -171,6 +173,7 @@ function TipTapEditor(props: TipTapEditorProps) { const historyLength = useSelector( (store: RootState) => store.state.history.length, ); + const useActiveFile = useSelector(selectUseActiveFile); const { saveSession, loadSession } = useHistory(dispatch); @@ -184,6 +187,14 @@ function TipTapEditor(props: TipTapEditorProps) { const isOSREnabled = useIsOSREnabled(); + const isInEditMode = useSelector( + (state: RootState) => state.editModeState.isInEditMode, + ); + + const shouldAddFileForEditing = useSelector( + (state: RootState) => state.uiState.shouldAddFileForEditing, + ); + const enterSubmenu = async (editor: Editor, providerId: string) => { const contents = editor.getText(); const indexOfAt = contents.lastIndexOf("@"); @@ -467,6 +478,49 @@ function TipTapEditor(props: TipTapEditorProps) { }, }) : undefined, + isInEditMode + ? AddCodeToEdit.configure({ + HTMLAttributes: { + class: "add-code-to-edit", + }, + suggestion: { + ...getContextProviderDropdownOptions( + availableContextProvidersRef, + getSubmenuContextItemsRef, + enterSubmenu, + onClose, + onOpen, + inSubmenuRef, + ideMessenger, + ), + 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( + "file", + query, + ); + return results.map((result) => ({ + ...result, + label: result.title, + type: "file", + query: result.id, + icon: result.icon, + })); + }, + }, + }) + : undefined, props.availableSlashCommands.length ? SlashCommand.configure({ HTMLAttributes: { @@ -768,6 +822,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(); @@ -829,8 +890,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?.(); + }} + > + + +
+
+ )}
- + {getBasename(rif.filepath)} 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/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index fbc43e5d2..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(); @@ -174,7 +174,7 @@ export default function StepContainerPreToolbar(
diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index ca1ea2afd..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(" "); @@ -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]); @@ -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/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 96ef161a7..7dd914dd6 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -31,7 +31,6 @@ import { setCurCheckpointIndex, setInactive, setIsGatheringContext, - setIsInMultifileEdit, setMessageAtIndex, streamUpdate, } from "../redux/slices/stateSlice"; @@ -177,6 +176,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { modifiers: InputModifiers, ideMessenger: IIdeMessenger, index?: number, + promptPreamble?: string, ) { try { if (typeof index === "number") { @@ -205,7 +205,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, @@ -259,6 +259,12 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { dispatch, ); + if (promptPreamble) { + typeof content === "string" + ? (content += promptPreamble) + : (content.at(-1).text += promptPreamble); + } + const message: ChatMessage = { role: "user", content, @@ -298,16 +304,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/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/AddFileButton.tsx b/gui/src/pages/Edit/AddFileButton.tsx new file mode 100644 index 000000000..2f9e0f0dd --- /dev/null +++ b/gui/src/pages/Edit/AddFileButton.tsx @@ -0,0 +1,66 @@ +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 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); + dispatch(addCodeToEdit({ filepath, contents })); + } + } + + 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 new file mode 100644 index 000000000..26cb145d4 --- /dev/null +++ b/gui/src/pages/Edit/CodeToEdit.tsx @@ -0,0 +1,66 @@ +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 { CodeToEdit, RangeInFileWithContents } from "core"; +import AddFileButton from "./AddFileButton"; + +export default function WorkingSet() { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const editModeState = useSelector((state: RootState) => state.editModeState); + + const hasCodeToEdit = editModeState.codeToEdit.length > 0; + + 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)); + } + + 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] + .reverse() + .map((code, i) => ( + + )); + + return ( +
+
+ {title} + +
+ + {hasCodeToEdit && ( +
    + {codeToEditItems} +
+ )} +
+ ); +} diff --git a/gui/src/pages/Edit/CodeToEditListItem.tsx b/gui/src/pages/Edit/CodeToEditListItem.tsx new file mode 100644 index 000000000..8d84ef34b --- /dev/null +++ b/gui/src/pages/Edit/CodeToEditListItem.tsx @@ -0,0 +1,110 @@ +import FileIcon from "../../components/FileIcon"; +import { + ChevronDownIcon, + ChevronRightIcon, + 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"; +import { CodeToEdit } from "core"; + +export interface CodeToEditListItemProps { + code: CodeToEdit; + onDelete: (codeToEdit: CodeToEdit) => void; + onClickFilename: (codeToEdit: CodeToEdit) => 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: 0px 0px 0px 10px !important; + } +`; + +export default function CodeToEditListItem({ + code, + onDelete, + onClickFilename, +}: CodeToEditListItemProps) { + 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})`; + } + + const source = + "```" + + getMarkdownLanguageTagForFile(code.filepath) + + "\n" + + code.contents + + "\n" + + "```"; + + return ( +
  • setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet)} + > +
    +
    + {showCodeSnippet ? ( + { + e.stopPropagation(); + setShowCodeSnippet(false); + }} + 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" + /> + ) : ( + { + e.stopPropagation(); + setShowCodeSnippet(true); + }} + 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" + /> + )} + + { + e.stopPropagation(); + onClickFilename(code); + }} + > + {title} + +
    +
    + { + e.stopPropagation(); + onDelete(code); + }} + 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" + /> +
    +
    + {showCodeSnippet && ( +
    + + + +
    + )} +
  • + ); +} diff --git a/gui/src/pages/Edit/Edit.tsx b/gui/src/pages/Edit/Edit.tsx new file mode 100644 index 000000000..c69200bc1 --- /dev/null +++ b/gui/src/pages/Edit/Edit.tsx @@ -0,0 +1,240 @@ +import { ArrowLeftIcon } from "@heroicons/react/24/outline"; +import { Editor, JSONContent } from "@tiptap/core"; +import { InputModifiers, RangeInFileWithContents } from "core"; +import { stripImages } from "core/llm/images"; +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 { + 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 getMultifileEditPrompt from "./getMultifileEditPrompt"; + +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 { streamResponse } = useChatHandler(dispatch, ideMessenger); + const editModeState = useSelector((state: RootState) => state.editModeState); + const availableContextProviders = useSelector( + (store: RootState) => store.state.config.contextProviders, + ); + + const history = useSelector((state: RootState) => state.state.history); + + const applyStates = useSelector( + (state: RootState) => state.state.applyStates, + ); + + const applyState = useSelector( + (store: RootState) => + store.state.applyStates.find((state) => state.streamId === "edit") + ?.status ?? "closed", + ); + + const isSingleRangeEdit = + editModeState.codeToEdit.length === 0 || + (editModeState.codeToEdit.length === 1 && + "range" in editModeState.codeToEdit[0]); + + 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 active = useSelector((state: RootState) => state.state.active); + + const pendingApplyStates = applyStates.filter( + (state) => state.status === "done", + ); + + const isStreaming = + editModeState.editStatus === "streaming" || + editModeState.editStatus === "accepting"; + + const toolbarOptions = { + hideAddContext: false, + hideImageUpload: false, + hideUseCodebase: true, + hideSelectModel: false, + enterText: isStreaming ? "Retry" : "Edit", + }; + + const hasPendingApplies = pendingApplyStates.length > 0; + + const filteredContextProviders = availableContextProviders.filter( + (provider) => !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), + ); + + async function handleSingleRangeEdit( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + ) { + const [contextItems, __, userInstructions] = await resolveEditorContent( + editorState, + { + noContext: true, + useCodebase: false, + }, + ideMessenger, + [], + dispatch, + ); + + const prompt = [ + ...contextItems.map((item) => item.content), + stripImages(userInstructions), + ].join("\n\n"); + + ideMessenger.post("edit/sendPrompt", { + prompt, + range: editModeState.codeToEdit[0] as RangeInFileWithContents, + }); + + dispatch(submitEdit(prompt)); + editor.commands.selectTextblockEnd(); + } + + async function handleEditorEnter( + editorState: JSONContent, + modifiers: InputModifiers, + editor: Editor, + ) { + if (isSingleRangeEdit) { + 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 !history + .slice(index + 1) + .some((entry) => entry.message.role === "user"); + }, + [history], + ); + + return ( +
    +
    +
    + + +
    + + {!isSingleRangeEdit && history.length > 1 && ( +
    + {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 && isSingleRangeEdit && ( + dispatch(clearCodeToEdit())} + /> + )} + + {!hasPendingApplies && isSingleRangeEdit && ( + + + 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..8f526f1e2 --- /dev/null +++ b/gui/src/pages/Edit/getMultifileEditPrompt.ts @@ -0,0 +1,56 @@ +import { CodeToEdit } from "core"; + +export default function getMultifileEditPrompt( + codeToEdit: CodeToEdit[], +): string { + const codeToEditStr = codeToEdit + .map( + (code) => ` +\`\`\` ${code.filepath} +${code.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: + + +${codeToEditStr} + + +Please provide the multi-file edit details based on the engineer's request below: + `; +} 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 26fbacbb1..d1c8752c8 100644 --- a/gui/src/pages/edit/index.tsx +++ b/gui/src/pages/edit/index.tsx @@ -1,214 +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, - [], - dispatch, - ); - - // Note, not currently updating file symbols in edit mode - - 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..489bc7b41 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -1,26 +1,40 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; -import { MessageContent } from "core"; -import { RangeInFileWithContents } from "core/commands/util"; -import { EditModeArgs, EditStatus } from "core/protocol/ideWebview"; +import { CodeToEdit, EditStatus, MessageContent } from "core"; interface EditModeState { - highlightedCode?: RangeInFileWithContents; editStatus: EditStatus; previousInputs: MessageContent[]; fileAfterEdit?: string; + codeToEdit: CodeToEdit[]; + isInEditMode: boolean; } const initialState: EditModeState = { editStatus: "not-started", previousInputs: [], + codeToEdit: [], + 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: { - startEditMode: (state, { payload }: PayloadAction) => { - state.highlightedCode = payload.highlightedCode; + addCodeToEdit: (state, { payload }: PayloadAction) => { + const entryExists = state.codeToEdit.some((entry) => + isCodeToEditEqual(entry, payload), + ); + + if (!entryExists) { + state.codeToEdit.push(payload); + } + }, + focusEdit: (state) => { + state.isInEditMode = true; state.editStatus = "not-started"; state.previousInputs = []; state.fileAfterEdit = undefined; @@ -29,6 +43,14 @@ export const editModeStateSlice = createSlice({ state.previousInputs.push(payload); state.editStatus = "streaming"; }, + removeCodeToEdit: (state, { payload }: PayloadAction) => { + state.codeToEdit = state.codeToEdit.filter( + (entry) => !isCodeToEditEqual(entry, payload), + ); + }, + clearCodeToEdit: (state) => { + state.codeToEdit = []; + }, setEditStatus: ( state, { @@ -77,10 +99,13 @@ export const editModeStateSlice = createSlice({ }); export const { - startEditMode, + addCodeToEdit, setEditStatus, addPreviousInput, setEditDone, submitEdit, + removeCodeToEdit, + focusEdit, + clearCodeToEdit, } = editModeStateSlice.actions; export default editModeStateSlice.reducer; diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 770e9ce69..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. @@ -21,6 +21,7 @@ import { v4 as uuidv4, v4 } from "uuid"; type ChatHistoryItemWithMessageId = ChatHistoryItem & { message: ChatMessage & { id: string }; }; + type State = { history: ChatHistoryItemWithMessageId[]; symbols: FileSymbolMap; @@ -46,7 +47,6 @@ type State = { statuses: Record; }; streamAborter: AbortController; - isMultifileEdit: boolean; }; const initialState: State = { @@ -78,7 +78,6 @@ const initialState: State = { defaultModelTitle: "GPT-4", selectedProfileId: "local", checkpoints: [], - isMultifileEdit: false, curCheckpointIndex: 0, nextCodeBlockToApplyIndex: 0, applyStates: [], @@ -308,7 +307,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 +372,6 @@ export const stateSlice = createSlice({ selectedProfileId: payload, }; }, - - setIsInMultifileEdit: (state, { payload }: PayloadAction) => { - state.isMultifileEdit = payload; - }, setCurCheckpointIndex: (state, { payload }: PayloadAction) => { state.curCheckpointIndex = payload; }, @@ -472,7 +466,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; diff --git a/gui/tailwind.config.cjs b/gui/tailwind.config.cjs index f021c748b..7ec8df9e8 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))", @@ -46,8 +47,10 @@ 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))", }, }, }, diff --git a/manual-testing-sandbox/testCalculator.js b/manual-testing-sandbox/testCalculator.js new file mode 100644 index 000000000..e69de29bb