Merge branch 'continuedev:main' into main

This commit is contained in:
Anoyi 2024-11-22 09:54:45 +08:00 • committed by GitHub
commit 5ff6bf6c5d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
58 changed files with 1319 additions and 777 deletions

View file

@ -1,5 +1,4 @@
import { IDE } from "../..";
import { RangeInFileWithContents } from "../../commands/util";
import { IDE, RangeInFileWithContents } from "../..";
import { PrecalculatedLruCache } from "../../util/LruCache";
import {
getFullLanguageName,

View file

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

View file

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

View file

@ -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[];

View file

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

View file

@ -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 </modified_code_to_edit> 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;
}
}

View file

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

View file

@ -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:
<example>
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]
</example>
Now, let's make the changes based on the engineer's request:
<input>
${input}
</input>
Here are the files to base your edits on:
<files>
${filesToEditStr}
</files>
And here is any additional context the engineer has provided:
<context>
${additionalContextStr}
</context>
Please provide the multi-file edit details based on the engineer's request.
`;
}
export default MultiFileEditSlashCommand;

View file

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

31
core/index.d.ts vendored
View file

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

View file

@ -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];
};

View file

@ -19,19 +19,19 @@ You can include the currently open file as context by pressing <kbd>cmd/ctrl</kb
## Specific file
You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#files) and selecting the file.
You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#file) and selecting the file.
## Specific folder
You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folders) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder.
You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folder) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder.
## Entire codebase
You can include your entire codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase-retrieval). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
You can include your entire codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
## Documentation site
You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#documentation) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md).
You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#docs) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md).
## Terminal contents

View file

@ -19,19 +19,19 @@ sidebar_position: 3
## 指定文件
你可以通过输入 [`@Files`](../customize/context-providers.md#files) 并选择文件,包含当前工作区中的指定文件作为上下文。
你可以通过输入 [`@Files`](../customize/context-providers.md#file) 并选择文件,包含当前工作区中的指定文件作为上下文。
## 指定目录
你可以通过输入 [`@Folder`](../customize/context-providers.md#folders) 并选择目录,包含当前工作区中指定目录作为上下文。它像 [`@Codebase`](../customize/deep-dives/codebase.md) 一样工作,但是只包含指定目录中的文件。
你可以通过输入 [`@Folder`](../customize/context-providers.md#folder) 并选择目录,包含当前工作区中指定目录作为上下文。它像 [`@Codebase`](../customize/deep-dives/codebase.md) 一样工作,但是只包含指定目录中的文件。
## 整个代码库
你可以通过输入 [`@Codebase`](../customize/context-providers.md#codebase-retrieval) 包含整个代码库作为上下文。你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的。
你可以通过输入 [`@Codebase`](../customize/context-providers.md#codebase) 包含整个代码库作为上下文。你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的。
## 文档网址
你可以通过输入 [`@Docs`](../customize/context-providers.md#documentation) 并选择文档网址,包含文档网址作文上下文。你可以 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 是如何工作的。
你可以通过输入 [`@Docs`](../customize/context-providers.md#docs) 并选择文档网址,包含文档网址作文上下文。你可以 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 是如何工作的。
## 终端内容

View file

@ -9,7 +9,7 @@ sidebar_position: 4
模型的响应会直接流式地返回到侧边栏。每个响应中的代码片段将放在它自己的代码块中,每个代码块会给你一些按钮,“应用到当前文件”, “插入到光标处” 或 “复制” 。当你在会话的结尾按下 `cmd/ctrl + L` (VS Code) 或 `cmd/ctrl + J` (JetBrains) ,所有上下文会被清除,一个新的会话将会开始,让你可以开始一个新的任务。
如果你想查看聊天中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](troubleshooting.md#llm-prompt-logs) 。
如果你想查看聊天中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](../troubleshooting.md#llm-提示词日志) 。
You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.md) and `@Docs` [here](../customize/deep-dives/docs.md).

View file

@ -11,6 +11,6 @@ sidebar_position: 1
## 推荐的自动补全模型
如果你有使用任何模型的能力,我们推荐通过 [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) 使用 `Codestral` 。
如果你有使用任何模型的能力,我们推荐通过 [Mistral](../model-providers/top-level/mistral.md#自动补全模型) 使用 `Codestral` 。
如果你想要在本地运行模型,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#autocomplete-model) 使用 `Starcoder2-3B` 。
如果你想要在本地运行模型,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#自动补全模型) 使用 `Starcoder2-3B` 。

View file

@ -13,7 +13,7 @@ sidebar_position: 3
如果你有使用任何模型的能力,我们推荐 `voyage-code-2` ,它独立列在下面,和其他的嵌入模型选项一起。
如果你想本地生成嵌入,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#embeddings-model) 使用 `nomic-embed-text` 。
如果你想本地生成嵌入,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#嵌入模型) 使用 `nomic-embed-text` 。
### Voyage AI
@ -31,7 +31,7 @@ sidebar_position: 3
### Ollama
查看 [这个](../model-providers/top-level/ollama.md#embeddings-model) 获取如何使用 Ollama 来嵌入的指令。
查看 [这个](../model-providers/top-level/ollama.md#嵌入模型) 获取如何使用 Ollama 来嵌入的指令。
### Transformers.js (当前只有 VS Code)
@ -60,12 +60,12 @@ sidebar_position: 3
### OpenAI
查看 [这里](../model-providers/top-level/openai.md#embeddings-model) 获取如何使用 OpenAI 嵌入的指令。
查看 [这里](../model-providers/top-level/openai.md#嵌入模型) 获取如何使用 OpenAI 嵌入的指令。
### Cohere
查看 [这里](../model-providers/more/cohere.md#embeddings-model) 获取如何使用 Cohere 嵌入的指令。
查看 [这里](../model-providers/more/cohere.md#嵌入模型) 获取如何使用 Cohere 嵌入的指令。
### Gemini
查看 [这里](../model-providers/top-level/gemini.md#embeddings-model) 获取如何使用 Gemini 嵌入的指令。
查看 [这里](../model-providers/top-level/gemini.md#嵌入模型) 获取如何使用 Gemini 嵌入的指令。

View file

@ -20,4 +20,4 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config
`config.json` 可以处理大多数需要的配置,所以我们推荐在可能的情况下使用它。不过,如果你需要可编程的配置 Continue ,你可以使用 `config.ts` ,它位于 `~/.continue/config.ts` (MacOS / Linux) 或 `%USERPROFILE%\.continue\config.ts` (Windows) 。
例如,如何使用 `config.ts` ,查看 [编写定制斜杠命令](./tutorials/build-your-own-slash-command.md#custom-slash-commands) 或者 [编写定制上下文提供者](./tutorials/build-your-own-context-provider.md) 。
例如,如何使用 `config.ts` ,查看 [编写定制斜杠命令](./tutorials/build-your-own-slash-command.md#自定义斜杠命令) 或者 [编写定制上下文提供者](./tutorials/build-your-own-context-provider.md) 。

View file

@ -11,4 +11,4 @@ keywords: [编辑, cmd l, 工作]
如果你接受 diff ,我们移除之前的高亮行,如果你拒绝 diff ,我们移除建议的变更。
如果你想查看在编辑中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](troubleshooting.md#check-the-logs) 。
如果你想查看在编辑中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](../troubleshooting.md#检查日志) 。

View file

@ -13,45 +13,45 @@ import Admonition from "@theme/Admonition";
<Tabs>
<TabItem value="chat" label="聊天">
[聊天](../chat/how-to-use-it.md#how-to-use-it) 让你方便向 LLM 寻求帮助,而不需要离开 IDE
[聊天](../chat/how-to-use-it.md#如何使用它) 让你方便向 LLM 寻求帮助,而不需要离开 IDE
![chat](/img/chat.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于 [聊天](../chat/how-to-use-it.md#how-to-use-it)
了解更多关于 [聊天](../chat/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>
<TabItem value="autocomplete" label="自动补全">
[自动补全](../autocomplete/how-to-use-it.md#how-to-use-it) 随着你的输入提供行内代码建议
[自动补全](../autocomplete/how-to-use-it.md#如何使用它) 随着你的输入提供行内代码建议
![autocomplete](/img/autocomplete.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于 [自动补全](../autocomplete/how-to-use-it.md#how-to-use-it)
了解更多关于 [自动补全](../autocomplete/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>
<TabItem value="edit" label="编辑">
[编辑](../edit/how-to-use-it.md#how-to-use-it) 是一种编辑代码的方便的方式,不需要离开你的当前文件
[编辑](../edit/how-to-use-it.md#如何使用它) 是一种编辑代码的方便的方式,不需要离开你的当前文件
![edit](/img/edit.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于 [编辑](../edit/how-to-use-it.md#how-to-use-it)
了解更多关于 [编辑](../edit/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>
<TabItem value="s" label="Actions">
[Actions](../actions/how-to-use-it.md#how-to-use-it) 是常用情况的快捷方式
[Actions](../actions/how-to-use-it.md#如何使用它) 是常用情况的快捷方式
![actions](/img/actions.gif)
<Admonition type="info" title="了解更多" icon="📚">
了解更多关于如何使用 [Actions](../actions/how-to-use-it.md#how-to-use-it)
了解更多关于如何使用 [Actions](../actions/how-to-use-it.md#如何使用它)
</Admonition>
</TabItem>

View file

@ -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 ,提供你的问题的详情,我们将能更快的帮助你。

View file

@ -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",

View file

@ -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<AutocompleteSnippet[]> => {
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()) {

View file

@ -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 = {

View file

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

View file

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

View file

@ -250,7 +250,9 @@ export class VsCodeMessenger {
llm,
fastLlm,
);
const verticalDiffManager = await this.verticalDiffManagerPromise;
if (instant) {
await verticalDiffManager.streamDiffLines(
diffLines,

6
gui/package-lock.json generated
View file

@ -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",

View file

@ -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";

View file

@ -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;
}

View file

@ -129,18 +129,26 @@ export function History() {
return (
<Fragment key={index}>
{index === 0 && date > yesterday && (
<tr className={HEADER_CLASS}>Today</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>Today</td>
</tr>
)}
{date < yesterday &&
date > lastWeek &&
prevDate > yesterday && (
<tr className={HEADER_CLASS}>This Week</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>This Week</td>
</tr>
)}
{date < lastWeek && date > lastMonth && prevDate > lastWeek && (
<tr className={HEADER_CLASS}>This Month</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>This Month</td>
</tr>
)}
{date < lastMonth && prevDate > lastMonth && (
<tr className={HEADER_CLASS}>Older</tr>
<tr className={HEADER_CLASS}>
<td colSpan={3}>Older</td>
</tr>
)}
<HistoryTableRow

View file

@ -10,7 +10,9 @@ import { useConfigError } from "../redux/hooks";
import {
setEditDone,
setEditStatus,
startEditMode,
addCodeToEdit,
focusEdit,
clearCodeToEdit,
} from "../redux/slices/editModeState";
import { setDialogMessage, setShowDialog } from "../redux/slices/uiStateSlice";
import {
@ -183,14 +185,32 @@ const Layout = () => {
);
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 }));
});

View file

@ -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 (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<button
@ -28,18 +36,30 @@ export default function AcceptRejectAllButtons({
onClick={() => handleAcceptOrReject("rejectDiff")}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-600" />
<span className="sm:hidden">Reject</span>
<span className="max-sm:hidden md:hidden">Reject all</span>
<span className="max-md:hidden">Reject all changes</span>
{hasSinglePendingApplyStates ? (
<span>Reject</span>
) : (
<>
<span className="sm:hidden">Reject</span>
<span className="max-sm:hidden md:hidden">Reject all</span>
<span className="max-md:hidden">Reject all changes</span>
</>
)}
</button>
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("acceptDiff")}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-600" />
<span className="sm:hidden">Accept</span>
<span className="max-sm:hidden md:hidden">Accept all</span>
<span className="max-md:hidden">Accept all changes</span>
{hasSinglePendingApplyStates ? (
<span>Accept</span>
) : (
<>
<span className="sm:hidden">Accept</span>
<span className="max-sm:hidden md:hidden">Accept all</span>
<span className="max-md:hidden">Accept all changes</span>
</>
)}
</button>
</div>
);

View file

@ -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 (
<div
className={`mx-2 mb-2 mt-2 flex h-7 items-center justify-between pb-0 text-xs text-gray-400`}
>
<div className="flex-1" />
{isCurCheckpoint && (
{/* {isCurCheckpoint && (
<div className="flex-2 flex justify-center">
{hasPendingApplies && (
<AcceptRejectAllButtons pendingApplyStates={pendingApplyStates} />
)}
{hasClosedAllStreams && <UndoAndRedoButtons />}
</div>
)}
)} */}
<div className="flex-2 flex justify-center">
{hasPendingApplies && (
<AcceptRejectAllButtons pendingApplyStates={pendingApplyStates} />
)}
{/* {hasClosedAllStreams && <UndoAndRedoButtons />} */}
</div>
<div className="flex flex-1 justify-end">
<CopyIconButton

View file

@ -6,7 +6,7 @@ import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import { ChatHistoryItem } from "core";
import FeedbackButtons from "./FeedbackButtons";
import MultifileEditActions from "./MultifileEditActions";
import EditActions from "./EditActions";
export interface ResponseActionsProps {
isTruncated: boolean;
@ -23,15 +23,15 @@ export default function ResponseActions({
isTruncated,
onDelete,
}: ResponseActionsProps) {
const isInMultifileEdit = useSelector(
(store: RootState) => store.state.isMultifileEdit,
const isInEditMode = useSelector(
(store: RootState) => store.editModeState.isInEditMode,
);
// Only render delete button if there is more than one message
const shouldRenderDelete = index !== 1;
if (isInMultifileEdit) {
return <MultifileEditActions index={index} item={item} />;
if (isInEditMode) {
return <EditActions index={index} item={item} />;
}
return (

View file

@ -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 (
<div
className={isStepAheadOfCurCheckpoint ? "opacity-25" : "relative"}
// className={isStepAheadOfCurCheckpoint ? "opacity-25" : "relative"}
style={{
minHeight: props.isLast ? "50vh" : 0,
}}

View file

@ -1,12 +1,11 @@
import { Tooltip } from "react-tooltip";
import { vscInputBackground, vscBadgeBackground, vscForeground } from "..";
import { vscInputBackground, vscForeground } from "..";
import { getFontSize } from "../../util";
import ReactDOM from "react-dom";
const TooltipStyles = {
fontSize: `${getFontSize() - 2}px`,
backgroundColor: vscInputBackground,
boxShadow: `0px 0px 2px 1px ${vscBadgeBackground}`,
color: vscForeground,
padding: "4px 8px",
zIndex: 1000,

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

@ -14,7 +14,7 @@ export const CodeBlockComponent = (props: any) => {
const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now
return (
<NodeViewWrapper className="code-block-with-content" as="p">
<NodeViewWrapper className="code-block-with-content" as="div">
<CodeSnippetPreview
borderColor={
isFirstContextItem

View file

@ -65,6 +65,9 @@ import {
} from "./handleMetaKeyIssues";
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;
@ -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<string | null>(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();
}}
>
<div>{props.header}</div>
<PaddingDiv>
<EditorContent
spellCheck={false}

View file

@ -44,6 +44,7 @@ interface CodeSnippetPreviewProps {
item: ContextItemWithId;
onDelete?: () => 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"
>
<PreviewMarkdownHeader
className="flex cursor-pointer justify-between"
onClick={() => {
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,
});
}
}}
>
<div className="flex items-center gap-1">
<FileIcon height="16px" width="16px" filename={props.item.name} />
{props.item.name}
</div>
<div className="flex items-center gap-1">
<HeaderButtonWithToolTip
text="Delete"
onClick={(e) => {
e.stopPropagation();
props.onDelete?.();
}}
>
<XMarkIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
</div>
</PreviewMarkdownHeader>
{!props.hideHeader && (
<PreviewMarkdownHeader
className="flex cursor-pointer justify-between"
onClick={() => {
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,
});
}
}}
>
<div className="flex items-center gap-1">
<FileIcon height="16px" width="16px" filename={props.item.name} />
{props.item.name}
</div>
<div className="flex items-center gap-1">
<HeaderButtonWithToolTip
text="Delete"
onClick={(e) => {
e.stopPropagation();
props.onDelete?.();
}}
>
<XMarkIcon width="1em" height="1em" />
</HeaderButtonWithToolTip>
</div>
</PreviewMarkdownHeader>
)}
<div
contentEditable={false}
className={`m-0 ${collapsed ? "max-h-[33vh] overflow-hidden" : "overflow-auto"}`}

View file

@ -25,7 +25,7 @@ function FilenameLink({ rif }: FilenameLinkProps) {
onClick={onClick}
>
<FileIcon filename={rif.filepath} height="20px" width="20px" />
<span className="align-middle underline underline-offset-2">
<span className="align-baseline underline underline-offset-2 mb-0.5">
{getBasename(rif.filepath)}
</span>
</span>

View file

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

View file

@ -68,11 +68,11 @@ export default function StepContainerPreToolbar(
const ideMessenger = useContext(IdeMessengerContext);
const streamIdRef = useRef<string>(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(
<div className="flex min-w-0 max-w-[45%] items-center">
<ChevronDownIcon
onClick={onClickExpand}
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 hover:bg-gray-800 hover:brightness-125 ${
className={`h-3.5 w-3.5 shrink-0 cursor-pointer text-gray-400 transition-colors hover:bg-white/10 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>

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(" ");
@ -166,7 +166,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
// So in this case we just put them in refs
const symbolsRef = useRef<SymbolWithRange[]>([]);
const contextItemsRef = useRef<ContextItemWithId[]>([]);
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 <SyntaxHighlightedPre {...preProps} />;

View file

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

View file

@ -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";

View file

@ -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<HTMLButtonElement>(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 (
<Listbox onChange={handleAddAllOpenFiles}>
<div className="relative">
<Listbox.Button
ref={buttonRef}
className="bg-lightgray/10 border-lightgray flex cursor-pointer items-center justify-between rounded-md border-[0.5px] border-solid px-0 shadow-sm transition-colors"
>
<div
className="flex items-center gap-1 px-1.5 hover:brightness-125"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onClickAddFileToCodeToEdit();
}}
>
<PlusIcon className="text-vsc-foreground inline h-2.5 w-2.5 brightness-75" />
<span className="text-vsc-foreground text-[10px] brightness-75">
Add file
</span>
</div>
<div className="border-lightgray h-4 w-[1px] border-y-0 border-l-0 border-r border-solid" />
<ChevronDownIcon className="text-vsc-foreground h-2.5 w-2.5 cursor-pointer px-1 brightness-75 hover:brightness-125" />
</Listbox.Button>
<Listbox.Options
className={`bg-vsc-input-background border-lightgray absolute right-0 top-full z-50 mt-1 min-w-fit whitespace-nowrap rounded-md border border-solid px-1 py-0 shadow-lg`}
>
<Listbox.Option
value="addAllFiles"
className="text-vsc-foreground hover:bg-lightgray/33 block w-full cursor-pointer px-2 py-1 text-left text-[10px] brightness-75 hover:brightness-125"
>
Add all open files
</Listbox.Option>
</Listbox.Options>
</div>
</Listbox>
);
}

View file

@ -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) => (
<CodeToEditListItem
key={code.filepath + i}
code={code}
onDelete={onDelete}
onClickFilename={onClickFilename}
/>
));
return (
<div className="bg-vsc-editor-background border-vsc-input-border mx-1 flex flex-col rounded-t-lg border border-b-0 border-solid p-1">
<div className="text-lightgray flex items-center justify-between gap-1.5 px-1 py-1.5 text-xs">
<span>{title}</span>
<AddFileButton />
</div>
{hasCodeToEdit && (
<ul className="no-scrollbar mb-1.5 mt-1 max-h-[50vh] list-outside list-none space-y-1.5 overflow-y-auto pl-0">
{codeToEditItems}
</ul>
)}
</div>
);
}

View file

@ -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 (
<li
className="flex cursor-pointer flex-col"
onClick={() => setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet)}
>
<div
className={`hover:bg-lightgray hover:text-vsc-foreground flex justify-between rounded px-2 py-1 transition-colors hover:bg-opacity-20 ${showCodeSnippet && "text-vsc-foreground bg-lightgray bg-opacity-20"}`}
>
<div className="flex items-center gap-0.5">
{showCodeSnippet ? (
<ChevronDownIcon
onClick={(e) => {
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"
/>
) : (
<ChevronRightIcon
onClick={(e) => {
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"
/>
)}
<FileIcon filename={code.filepath} height={"18px"} width={"18px"} />
<span
className="text-xs hover:underline"
onClick={(e) => {
e.stopPropagation();
onClickFilename(code);
}}
>
{title}
</span>
</div>
<div className="flex gap-1.5">
<XMarkIcon
onClick={(e) => {
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"
/>
</div>
</div>
{showCodeSnippet && (
<div className="max-h-[25vh] overflow-y-auto px-1 py-2">
<NoPaddingWrapper>
<StyledMarkdownPreview source={source} />
</NoPaddingWrapper>
</div>
)}
</li>
);
}

240
gui/src/pages/Edit/Edit.tsx Normal file
View file

@ -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 (
<div className="h-full overflow-y-auto">
<div className="m-auto max-w-3xl">
<div className="relative mb-1 mt-3 flex flex-col px-2">
<CodeToEdit />
<TipTapEditor
isMainInput
toolbarOptions={toolbarOptions}
placeholder="Describe how to modify the code - use '#' to add files"
availableContextProviders={filteredContextProviders}
historyKey="edit"
availableSlashCommands={[]}
onEnter={handleEditorEnter}
/>
</div>
{!isSingleRangeEdit && history.length > 1 && (
<div>
{history.slice(1).map((item, index: number) => (
<div>
{item.message.role === "user" ? (
<ContinueInputBox
onEnter={async (editorState, modifiers) => {
streamResponse(
editorState,
modifiers,
ideMessenger,
index,
);
}}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
editorState={item.editorState}
contextItems={item.contextItems}
/>
) : (
<StepContainer
index={index}
isLast={index === history.length - 1}
item={item}
/>
)}
</div>
))}
{/* {!active && (
<ContinueInputBox
isMainInput
isLastUserInput={false}
onEnter={handleEditorEnter}
/>
)} */}
</div>
)}
<div className="mt-2">
{hasPendingApplies && isSingleRangeEdit && (
<AcceptRejectAllButtons
pendingApplyStates={pendingApplyStates}
onAcceptOrReject={() => dispatch(clearCodeToEdit())}
/>
)}
{!hasPendingApplies && isSingleRangeEdit && (
<NewSessionButton
onClick={handleBackClick}
className="mr-auto flex items-center gap-2"
>
<ArrowLeftIcon width="11px" height="11px" />
Back to Chat
</NewSessionButton>
)}
</div>
</div>
</div>
);
}

View file

@ -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:
<example>
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]
</example>
Here are the files to base your edits on:
<files>
${codeToEditStr}
</files>
Please provide the multi-file edit details based on the engineer's request below:
`;
}

View file

@ -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 (
<>
<div
className="select-none p-1"
style={{
backgroundColor: "#fff2",
}}
>
<div className="flex items-center justify-between">
<div className="flex cursor-pointer" onClick={onClick}>
<FileIcon
filename={editModeState.highlightedCode.filepath}
height={"18px"}
width={"18px"}
></FileIcon>
{getBasename(editModeState.highlightedCode.filepath)} (
{editModeState.highlightedCode.range.start.line}-
{editModeState.highlightedCode.range.end.line})
</div>
{editModeState.editStatus === "accepting" ||
editModeState.editStatus === "accepting:full-diff" ? (
<div className="float-right flex items-center gap-2">
{/* {editModeState.editStatus === "accepting" ? (
<>
<HeaderButtonWithToolTip text="View full diff">
<DocumentPlusIcon
className="h-4 w-4 cursor-pointer"
onClick={showFullDiff}
></DocumentPlusIcon>
</HeaderButtonWithToolTip>
<span className="text-xs text-gray-400">
N diffs remaining
</span>
</>
) : (
<div>hi</div>
)} */}
<div className="flex">
<HeaderButtonWithToolTip text="Reject">
<XMarkIcon
className="h-4 w-4 cursor-pointer px-2"
color="red"
onClick={() => {
ideMessenger.post("edit/acceptReject", {
accept: false,
onlyFirst: false,
filepath: editModeState.highlightedCode.filepath,
});
dispatch(setEditDone());
}}
></XMarkIcon>
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip text="Accept">
<CheckIcon
className="h-4 w-4 cursor-pointer px-2 text-green-500"
onClick={() => {
ideMessenger.post("edit/acceptReject", {
accept: true,
onlyFirst: false,
filepath: editModeState.highlightedCode.filepath,
});
dispatch(setEditDone());
}}
></CheckIcon>
</HeaderButtonWithToolTip>
</div>
</div>
) : null}
</div>
</div>
</>
);
}

View file

@ -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 (
<>
<TopDiv>
<div className="m-auto max-w-3xl">
{/* Edit session history */}
{/* {editModeState.previousInputs.length > 0 && (
<div className="mt-3 px-2">
{editModeState.previousInputs.map((input, index) => (
<div key={index} className="flex items-center gap-2">
<EditHistoryDiv>
<div className="text-gray-400">{stripImages(input)}</div>
<EyeIcon className="ml-auto h-4 w-4" color={lightGray} />
</EditHistoryDiv>
</div>
))}
</div>
)} */}
<div className="relative mb-1 mt-3 flex px-2">
<TipTapEditor
header={<EditInputHeader />}
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<void> {
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();
}}
></TipTapEditor>
</div>
</div>
<div className="mt-2">
<NewSessionButton
onClick={async () => {
dispatch(setEditDone());
}}
className="mr-auto flex items-center gap-2"
>
<ArrowLeftIcon width="11px" height="11px" />
Back to Chat
</NewSessionButton>
</div>
</TopDiv>
</>
);
}
export default Edit;
export { default } from "./Edit";

View file

@ -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<EditModeArgs>) => {
state.highlightedCode = payload.highlightedCode;
addCodeToEdit: (state, { payload }: PayloadAction<CodeToEdit>) => {
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<CodeToEdit>) => {
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;

View file

@ -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<string, IndexingStatus>;
};
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<boolean>) => {
state.isMultifileEdit = payload;
},
setCurCheckpointIndex: (state, { payload }: PayloadAction<number>) => {
state.curCheckpointIndex = payload;
},
@ -472,7 +466,6 @@ export const {
setSelectedProfileId,
deleteMessage,
setIsGatheringContext,
setIsInMultifileEdit,
updateCurCheckpoint,
setCurCheckpointIndex,
resetNextCodeBlockToApplyIndex,

View file

@ -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<UiState["showDialog"]>) => {
state.showDialog = action.payload;
},
setShouldAddFileForEditing: (
state,
action: PayloadAction<UiState["shouldAddFileForEditing"]>,
) => {
state.shouldAddFileForEditing = action.payload;
},
},
});
@ -49,6 +57,7 @@ export const {
setDialogMessage,
setDialogEntryOn,
setShowDialog,
setShouldAddFileForEditing,
} = uiStateSlice.actions;
export default uiStateSlice.reducer;

View file

@ -25,6 +25,7 @@ module.exports = {
"spin-slow": "spin 6s linear infinite",
},
colors: {
lightgray: "#999998",
"vsc-background": "rgb(var(--vsc-background) / <alpha-value>)",
"secondary-dark": "rgb(var(--secondary-dark) / <alpha-value>)",
"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))",
},
},
},

View file