Merge pull request #5439 from continuedev/dallin/single-file-edit

Make Edit Mode Single-file
This commit is contained in:
Dallin Romney 2025-05-01 10:36:54 -07:00 • committed by GitHub
commit 11b45af8f7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
63 changed files with 1113 additions and 2014 deletions

View file

@ -235,10 +235,6 @@ declare global {
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface Checkpoint {
[filepath: string]: string;
}
export interface Session {
sessionId: string;
title: string;
@ -423,8 +419,6 @@ declare global {
promptLogs?: PromptLog[];
toolCallState?: ToolCallState;
isGatheringContext?: boolean;
checkpoint?: Checkpoint;
isBeforeCheckpoint?: boolean;
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@ -1051,13 +1045,6 @@ declare global {
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

1
core/edit/constants.ts Normal file
View file

@ -0,0 +1 @@
export const EDIT_MODE_STREAM_ID = "edit-mode";

17
core/index.d.ts vendored
View file

@ -158,9 +158,7 @@ export interface ModelInstaller {
progressReporter?: (task: string, increment: number, total: number) => void,
): Promise<any>;
isInstallingModel(
modelName: string
): Promise<boolean>;
isInstallingModel(modelName: string): Promise<boolean>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
@ -248,10 +246,6 @@ export interface IContextProvider {
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface Checkpoint {
[filepath: string]: string;
}
export interface Session {
sessionId: string;
title: string;
@ -464,8 +458,6 @@ export interface ChatHistoryItem {
promptLogs?: PromptLog[];
toolCallState?: ToolCallState;
isGatheringContext?: boolean;
checkpoint?: Checkpoint;
isBeforeCheckpoint?: boolean;
reasoning?: Reasoning;
}
@ -1213,13 +1205,6 @@ export interface ExperimentalMCPOptions {
faviconUrl?: string;
}
export type EditStatus =
| "not-started"
| "streaming"
| "accepting"
| "accepting:full-diff"
| "done";
export type ApplyStateStatus =
| "not-started" // Apply state created but not necessarily streaming
| "streaming" // Changes are being applied to the file

View file

@ -4,7 +4,6 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
import type {
ApplyState,
CodeToEdit,
EditStatus,
MessageContent,
RangeInFileWithContents,
} from "../";
@ -50,9 +49,10 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
prompt: MessageContent;
range: RangeInFileWithContents;
},
void,
string | undefined,
];
"edit/exit": [{ shouldFocusEditor: boolean }, void];
"edit/addCurrentSelection": [undefined, void];
"edit/clearDecorations": [undefined, void];
};
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
@ -71,7 +71,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
},
void,
];
addCodeToEdit: [CodeToEdit, void];
setCodeToEdit: [CodeToEdit, void];
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];
@ -87,8 +87,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
openOnboardingCard: [undefined, void];
applyCodeFromChat: [undefined, void];
updateApplyState: [ApplyState, void];
setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void];
exitEditMode: [undefined, void];
focusEdit: [undefined, void];
focusEditWithoutClear: [undefined, void];
};

View file

@ -11,7 +11,7 @@ The input you provide is included in the prompt.
## Code to Edit
The **entire contents** of each file (the current file for Jetbrains inline Edit, each `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
## Context Providers

View file

@ -20,7 +20,7 @@ Edit is recommended for small, targeted changes, such as
## Highlight code and activate
Highlight the block of code you would like to modify and press <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> to active Edit mode. You can also enter Edit mode by pressing <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> with no code highlighted.
Highlight the block of code you would like to modify and press <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> to active Edit mode. You can also enter Edit mode by pressing <kbd>cmd/ctrl</kbd> + <kbd>i</kbd> with no code highlighted, which will default to editing the current file.
## Describe code changes
@ -48,32 +48,6 @@ You can also reject and accept diffs using the `Reject All` and `Accept All` but
Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor.
**_Add file combobox_**
![edit mode add file combobox](/img/edit-mode-add-files.png)
**_Add all open files dropdown_**
![edit mode add file combobox](/img/edit-mode-add-all-open-files.png)
### Single File Edit
If one file/range is present in `Code to Edit` on submission, Continue will prompt the Edit model and then automatically stream the diff into the editor.
![Edit mode single file diffs](/img/edit-mode-single-file-diff.png)
### Multi-File Edit
If multiple files/ranges are present in `Code to Edit` on submission, Continue will prompt the Edit model to output codeblocks per-file, which the user can then choose to apply and accept/reject independently.
**_Generated Content_**
![Edit mode multi file generated content](/img/edit-mode-multi-file-generation.png)
**_Diffs_**
![Edit mode multi file diffs](/img/edit-mode-multi-file-diffs.png)
## Jetbrains
In Jetbrains, Edit is implemented as an inline popup (see the header GIF example) for single-file edit. Multi-file edit mode is not currently implemented.
In Jetbrains, Edit is implemented as an inline popup. See the header GIF example.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 256 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.29",
"version": "1.1.30",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.29",
"version": "1.1.30",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -108,7 +108,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.4",
"@continuedev/fetch": "^1.0.6",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@modelcontextprotocol/sdk": "^1.5.0",

View file

@ -383,11 +383,6 @@
"mac": "cmd+i",
"key": "ctrl+i"
},
{
"command": "continue.focusEditWithoutClear",
"mac": "cmd+shift+i",
"key": "ctrl+shift+i"
},
{
"command": "continue.exitEditMode",
"mac": "escape",

View file

@ -1,13 +1,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
import * as fs from "node:fs";
import * as os from "node:os";
import {
ContextMenuConfig,
ILLM,
ModelInstaller,
RangeInFileWithContents,
} from "core";
import { ContextMenuConfig, ILLM, ModelInstaller } from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { ConfigHandler } from "core/config/ConfigHandler";
import { ContinueServerClient } from "core/continueServer/stubs/client";
@ -47,8 +41,12 @@ import { getMetaKeyLabel } from "./util/util";
import { VsCodeIde } from "./VsCodeIde";
import { convertJsonToYamlConfig } from "../../../packages/config-yaml/dist";
import {
addCodeToContextFromRange,
addEntireFileToContext,
addHighlightedCodeToContext,
} from "./util/addCode";
import { openEditorAndRevealRange } from "./util/vscode";
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
let fullScreenPanel: vscode.WebviewPanel | undefined;
@ -71,160 +69,6 @@ function captureCommandTelemetry(
Telemetry.capture(commandName, { isCommandEvent: true, ...properties });
}
function addCodeToContextFromRange(
range: vscode.Range,
webviewProtocol: VsCodeWebviewProtocol,
prompt?: string,
) {
const document = vscode.window.activeTextEditor?.document;
if (!document) {
return;
}
const rangeInFileWithContents = {
filepath: document.uri.toString(),
contents: document.getText(range),
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
prompt,
// Assume `true` since range selection is currently only used for quick actions/fixes
shouldRun: true,
});
}
function getRangeInFileWithContents(
allowEmpty?: boolean,
range?: vscode.Range,
): RangeInFileWithContents | null {
const editor = vscode.window.activeTextEditor;
if (editor) {
const selection = editor.selection;
const filepath = editor.document.uri.toString();
if (range) {
const contents = editor.document.getText(range);
return {
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
filepath,
contents,
};
}
if (selection.isEmpty && !allowEmpty) {
return null;
}
let selectionRange = new vscode.Range(selection.start, selection.end);
const document = editor.document;
// Select the context from the beginning of the selection start line to the selection start position
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
const textBeforeSelectionStart = document.getText(
new vscode.Range(beginningOfSelectionStartLine, selection.start),
);
// If there are only whitespace before the start of the selection, include the indentation
if (textBeforeSelectionStart.trim().length === 0) {
selectionRange = selectionRange.with({
start: beginningOfSelectionStartLine,
});
}
const contents = editor.document.getText(selectionRange);
return {
filepath,
contents,
range: {
start: {
line: selection.start.line,
character: selection.start.character,
},
end: {
line: selection.end.line,
character: selection.end.character,
},
},
};
}
return null;
}
async function addHighlightedCodeToContext(
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
const rangeInFileWithContents = getRangeInFileWithContents();
if (rangeInFileWithContents) {
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
}
async function addEntireFileToContext(
uri: vscode.Uri,
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
// If a directory, add all files in the directory
const stat = await vscode.workspace.fs.stat(uri);
if (stat.type === vscode.FileType.Directory) {
const files = await vscode.workspace.fs.readDirectory(uri);
for (const [filename, type] of files) {
if (type === vscode.FileType.File) {
addEntireFileToContext(
vscode.Uri.joinPath(uri, filename),
webviewProtocol,
);
}
}
return;
}
// Get the contents of the file
const contents = (await vscode.workspace.fs.readFile(uri)).toString();
const rangeInFileWithContents = {
filepath: uri.toString(),
contents: contents,
range: {
start: {
line: 0,
character: 0,
},
end: {
line: contents.split(os.EOL).length - 1,
character: 0,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
function focusGUI() {
const fullScreenTab = getFullScreenTab();
if (fullScreenTab) {
@ -260,9 +104,10 @@ async function processDiff(
) {
captureCommandTelemetry(`${action}Diff`);
const currentFile = await ide.getCurrentFile();
let newOrCurrentUri = newFileUri;
if (!newOrCurrentUri) {
const currentFile = await ide.getCurrentFile();
newOrCurrentUri = currentFile?.path;
}
if (!newOrCurrentUri) {
@ -277,10 +122,6 @@ async function processDiff(
// Clear vertical diffs depending on action
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
void sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});
if (streamId) {
const fileContent = await ide.readFile(newOrCurrentUri);
@ -294,8 +135,6 @@ async function processDiff(
});
}
await sidebar.webviewProtocol.request("exitEditMode", undefined);
// Save the file
await ide.saveFile(newOrCurrentUri);
}
@ -546,102 +385,7 @@ const getCommandsMap: (
"continue.focusEdit": async (args?: QuickEditShowParams) => {
captureCommandTelemetry("focusEdit");
focusGUI();
sidebar.webviewProtocol?.request("focusEdit", undefined);
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const existingDiff = verticalDiffManager.getHandlerForFile(
editor.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 startFromCharZero = editor.selection.start.with(undefined, 0);
const document = editor.document;
let lastLine, lastChar;
// If the user selected onto a trailing line but didn't actually include any characters in it
// they don't want to include that line, so trim it off.
if (editor.selection.end.character === 0) {
// This is to prevent the rare case that the previous line gets selected when user
// is selecting nothing and the cursor is at the beginning of the line
if (editor.selection.end.line === editor.selection.start.line) {
lastLine = editor.selection.start.line;
} else {
lastLine = editor.selection.end.line - 1;
}
} else {
lastLine = editor.selection.end.line;
}
lastChar = document.lineAt(lastLine).range.end.character;
const endAtCharLast = new vscode.Position(lastLine, lastChar);
const range =
args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast);
editDecorationManager.addDecorations(editor, [range]);
const rangeInFileWithContents = getRangeInFileWithContents(true, range);
if (rangeInFileWithContents) {
sidebar.webviewProtocol?.request(
"addCodeToEdit",
rangeInFileWithContents,
);
// Un-select the current selection
editor.selection = new vscode.Selection(
editor.selection.anchor,
editor.selection.anchor,
);
}
},
"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 = getRangeInFileWithContents(false);
if (rangeInFileWithContents) {
sidebar.webviewProtocol?.request(
"addCodeToEdit",
rangeInFileWithContents,
);
} else {
const contents = document.getText();
sidebar.webviewProtocol?.request("addCodeToEdit", {
filepath: document.uri.toString(),
contents,
});
}
},
"continue.exitEditMode": async () => {
captureCommandTelemetry("exitEditMode");
@ -959,7 +703,7 @@ const getCommandsMap: (
if (core.configHandler.currentProfile?.profileDescription.id) {
core.invoke("config/updateSelectedModel", {
profileId:
core.configHandler.currentProfile?.profileDescription.id,
core.configHandler.currentProfile?.profileDescription.id,
role: "autocomplete",
title: selectedOption,
});

View file

@ -15,8 +15,10 @@ import {
import { stripImages } from "core/util/messageContent";
import * as vscode from "vscode";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { ApplyManager } from "../apply";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import {
getControlPlaneSessionInfo,
@ -188,6 +190,15 @@ export class VsCodeMessenger {
);
});
});
this.onWebview("edit/addCurrentSelection", async (msg) => {
const verticalDiffManager = await this.verticalDiffManagerPromise;
await addCurrentSelectionToEdit({
args: undefined,
editDecorationManager,
webviewProtocol: this.webviewProtocol,
verticalDiffManager,
});
});
this.onWebview("edit/sendPrompt", async (msg) => {
const prompt = msg.data.prompt;
const { start, end } = msg.data.range.range;
@ -210,39 +221,28 @@ export class VsCodeMessenger {
const fileAfterEdit = await verticalDiffManager.streamEdit({
input: stripImages(prompt),
llm: model,
streamId: "edit",
streamId: EDIT_MODE_STREAM_ID,
range: new vscode.Range(
new vscode.Position(start.line, start.character),
new vscode.Position(end.line, end.character),
),
rules: config.rules,
});
void this.webviewProtocol.request("setEditStatus", {
status: "accepting",
fileAfterEdit,
});
return fileAfterEdit;
});
this.onWebview("edit/exit", async (msg) => {
if (msg.data.shouldFocusEditor) {
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
vscode.window.showTextDocument(activeEditor.document);
}
}
this.onWebview("edit/clearDecorations", async (msg) => {
editDecorationManager.clear();
});
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
this.onWebview(messageType, async (msg) => {
return await this.inProcessMessenger.externalRequest(
messageType,
msg.data,
msg.messageId,
);
return await this.inProcessMessenger.externalRequest(
messageType,
msg.data,
msg.messageId,
);
});
});

View file

@ -0,0 +1,70 @@
import * as vscode from "vscode";
import { VerticalDiffManager } from "../diff/vertical/manager";
import { getRangeInFileWithContents } from "../util/addCode";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import EditDecorationManager from "./EditDecorationManager";
import { QuickEditShowParams } from "./QuickEditQuickPick";
export async function addCurrentSelectionToEdit({
webviewProtocol,
verticalDiffManager,
args,
editDecorationManager,
}: {
webviewProtocol: VsCodeWebviewProtocol;
verticalDiffManager: VerticalDiffManager;
args: QuickEditShowParams | undefined;
editDecorationManager: EditDecorationManager;
}) {
const editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const existingDiff = verticalDiffManager.getHandlerForFile(
editor.document.fileName,
);
// If there's a diff currently being applied, then we just toggle focus back to the input
if (existingDiff) {
webviewProtocol?.request("focusContinueInput", undefined);
return;
}
const startFromCharZero = editor.selection.start.with(undefined, 0);
const document = editor.document;
let lastLine, lastChar;
// If the user selected onto a trailing line but didn't actually include any characters in it
// they don't want to include that line, so trim it off.
if (editor.selection.end.character === 0) {
// This is to prevent the rare case that the previous line gets selected when user
// is selecting nothing and the cursor is at the beginning of the line
if (editor.selection.end.line === editor.selection.start.line) {
lastLine = editor.selection.start.line;
} else {
lastLine = editor.selection.end.line - 1;
}
} else {
lastLine = editor.selection.end.line;
}
lastChar = document.lineAt(lastLine).range.end.character;
const endAtCharLast = new vscode.Position(lastLine, lastChar);
const range =
args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast);
editDecorationManager.clear();
editDecorationManager.addDecorations(editor, [range]);
const rangeInFileWithContents = getRangeInFileWithContents(true, range);
if (rangeInFileWithContents) {
webviewProtocol?.request("setCodeToEdit", rangeInFileWithContents);
// Un-select the current selection
editor.selection = new vscode.Selection(
editor.selection.anchor,
editor.selection.anchor,
);
}
}

View file

@ -0,0 +1,158 @@
import { RangeInFileWithContents } from "core";
import * as os from "node:os";
import * as vscode from "vscode";
import type { VsCodeWebviewProtocol } from "../webviewProtocol";
export function getRangeInFileWithContents(
allowEmpty?: boolean,
range?: vscode.Range,
): RangeInFileWithContents | null {
const editor = vscode.window.activeTextEditor;
if (editor) {
const selection = editor.selection;
const filepath = editor.document.uri.toString();
if (range) {
const contents = editor.document.getText(range);
return {
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
filepath,
contents,
};
}
if (selection.isEmpty && !allowEmpty) {
return null;
}
let selectionRange = new vscode.Range(selection.start, selection.end);
const document = editor.document;
// Select the context from the beginning of the selection start line to the selection start position
const beginningOfSelectionStartLine = selection.start.with(undefined, 0);
const textBeforeSelectionStart = document.getText(
new vscode.Range(beginningOfSelectionStartLine, selection.start),
);
// If there are only whitespace before the start of the selection, include the indentation
if (textBeforeSelectionStart.trim().length === 0) {
selectionRange = selectionRange.with({
start: beginningOfSelectionStartLine,
});
}
const contents = editor.document.getText(selectionRange);
return {
filepath,
contents,
range: {
start: {
line: selection.start.line,
character: selection.start.character,
},
end: {
line: selection.end.line,
character: selection.end.character,
},
},
};
}
return null;
}
export async function addHighlightedCodeToContext(
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
const rangeInFileWithContents = getRangeInFileWithContents();
if (rangeInFileWithContents) {
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
}
export async function addEntireFileToContext(
uri: vscode.Uri,
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
// If a directory, add all files in the directory
const stat = await vscode.workspace.fs.stat(uri);
if (stat.type === vscode.FileType.Directory) {
const files = await vscode.workspace.fs.readDirectory(uri);
for (const [filename, type] of files) {
if (type === vscode.FileType.File) {
addEntireFileToContext(
vscode.Uri.joinPath(uri, filename),
webviewProtocol,
);
}
}
return;
}
// Get the contents of the file
const contents = (await vscode.workspace.fs.readFile(uri)).toString();
const rangeInFileWithContents = {
filepath: uri.toString(),
contents: contents,
range: {
start: {
line: 0,
character: 0,
},
end: {
line: contents.split(os.EOL).length - 1,
character: 0,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
});
}
export function addCodeToContextFromRange(
range: vscode.Range,
webviewProtocol: VsCodeWebviewProtocol,
prompt?: string,
) {
const document = vscode.window.activeTextEditor?.document;
if (!document) {
return;
}
const rangeInFileWithContents = {
filepath: document.uri.toString(),
contents: document.getText(range),
range: {
start: {
line: range.start.line,
character: range.start.character,
},
end: {
line: range.end.line,
character: range.end.character,
},
},
};
webviewProtocol?.request("highlightedCode", {
rangeInFileWithContents,
prompt,
// Assume `true` since range selection is currently only used for quick actions/fixes
shouldRun: true,
});
}

View file

@ -3,7 +3,7 @@ import Layout from "./components/Layout";
import { MainEditorProvider } from "./components/mainInput/TipTapEditor";
import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders";
import { VscThemeProvider } from "./context/VscTheme";
import useSetup from "./hooks/useSetup";
import ParallelListeners from "./hooks/ParallelListeners";
import ConfigPage from "./pages/config";
import ErrorPage from "./pages/error";
import Chat from "./pages/gui";
@ -42,14 +42,9 @@ const router = createMemoryRouter([
]);
/*
Prevents entire app from rerendering continuously with useSetup in App
TODO - look into a more redux-esque way to do this
ParallelListeners prevents entire app from rerendering on any change in the listeners,
most of which interact with redux etc.
*/
export function SetupListeners() {
useSetup();
return <></>;
}
function App() {
return (
<VscThemeProvider>
@ -58,7 +53,7 @@ function App() {
<RouterProvider router={router} />
</SubmenuContextProvidersProvider>
</MainEditorProvider>
<SetupListeners />
<ParallelListeners />
</VscThemeProvider>
);
}

View file

@ -2,24 +2,26 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAppSelector } from "../redux/hooks";
import { selectIsSingleRangeEditOrInsertion } from "../redux/slices/sessionSlice";
import { getMetaKeyLabel } from "../util";
import { useFontSize } from "./ui/font";
export interface AcceptRejectAllButtonsProps {
pendingApplyStates: ApplyState[];
applyStates: ApplyState[];
onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void;
}
export type AcceptOrRejectOutcome = "acceptDiff" | "rejectDiff";
export default function AcceptRejectAllButtons({
pendingApplyStates,
applyStates,
onAcceptOrReject,
}: AcceptRejectAllButtonsProps) {
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const ideMessenger = useContext(IdeMessengerContext);
const isSingleRangeEdit = useAppSelector(selectIsSingleRangeEditOrInsertion);
const tinyFont = useFontSize(-3);
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
for (const { filepath = "", streamId } of pendingApplyStates) {
ideMessenger.post(status, {
@ -33,39 +35,50 @@ export default function AcceptRejectAllButtons({
}
}
if (!pendingApplyStates.length) {
return null;
}
return (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<div className="flex flex-row items-center justify-evenly gap-2 p-1 px-3">
<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"
className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("rejectDiff")}
data-testid="edit-reject-button"
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-600" />
{isSingleRangeEdit ? (
<span>Reject ({getMetaKeyLabel()}⇧⌫)</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>
</>
)}
<div className="flex flex-row items-center gap-1">
<XMarkIcon className="h-4 w-4 text-red-600" />
<span>Reject</span>
<span className="xs:inline-block hidden">All</span>
</div>
<span
className="xs:inline-block hidden text-gray-400"
style={{
fontSize: tinyFont,
}}
>
({getMetaKeyLabel()}⇧⌫)
</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"
className="flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("acceptDiff")}
data-testid="edit-accept-button"
>
<CheckIcon className="mr-1 h-4 w-4 text-green-600" />
{isSingleRangeEdit ? (
<span>Accept ({getMetaKeyLabel()}⇧⏎)</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>
</>
)}
<div className="flex flex-row items-center gap-1">
<CheckIcon className="h-4 w-4 text-green-600" />
<span>Accept</span>
<span className="xs:inline-block hidden">All</span>
</div>
<span
className="xs:inline-block hidden text-gray-400"
style={{
fontSize: tinyFont,
}}
>
({getMetaKeyLabel()}⇧⏎)
</span>
</button>
</div>
);

View file

@ -1,66 +0,0 @@
import { ChevronDownIcon, PlusIcon } from "@heroicons/react/24/outline";
import { useContext, useRef } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch } from "../../redux/hooks";
import { addCodeToEdit } from "../../redux/slices/sessionSlice";
import {
Listbox,
ListboxButton,
ListboxOption,
ListboxOptions,
} from "../ui/Listbox";
export interface AddFileButtonProps {
onClick: () => void;
}
export default function AddFileButton({ onClick }: AddFileButtonProps) {
const buttonRef = useRef<HTMLButtonElement>(null);
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useAppDispatch();
async function handleAddAllOpenFiles() {
const openFiles = await ideMessenger.ide.getOpenFiles();
const filesData = await Promise.all(
openFiles.map(async (filepath) => {
const contents = await ideMessenger.ide.readFile(filepath);
return { filepath, contents };
}),
);
dispatch(addCodeToEdit(filesData));
}
return (
<Listbox onChange={handleAddAllOpenFiles}>
<div className="relative">
<ListboxButton
ref={buttonRef}
className="bg-vsc-editor-background m-0 rounded-md p-0"
>
<div
className="flex h-5 items-center justify-center gap-1 hover:brightness-125"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onClick();
}}
>
<PlusIcon className="text-vsc-foreground inline h-2.5 w-2.5 px-1 brightness-75" />
<span className="text-vsc-foreground xs:block hidden text-[10px] brightness-75">
Add file
</span>
</div>
<div className="border-lightgray/50 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" />
</ListboxButton>
<ListboxOptions className="bg-vsc-editor-background" anchor="top end">
<ListboxOption value="addAllFiles">Add all open files</ListboxOption>
</ListboxOptions>
</div>
</Listbox>
);
}

View file

@ -1,143 +0,0 @@
import { ContextSubmenuItemWithProvider } from "core";
import { useEffect, useRef, useState } from "react";
import {
Combobox,
ComboboxButton,
ComboboxInput,
ComboboxOption,
ComboboxOptions,
} from "../../components/ui/Combobox";
import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders";
import { useAppSelector } from "../../redux/hooks";
import FileIcon from "../FileIcon";
export interface AddFileComboboxProps {
onSelect: (filepaths: string[]) => void | Promise<void>;
onEscape: () => void | Promise<void>;
}
export default function AddFileCombobox({
onSelect,
onEscape,
}: AddFileComboboxProps) {
const [query, setQuery] = useState("");
const [selectedFiles, setSelectedFiles] = useState<
ContextSubmenuItemWithProvider[]
>([]);
const inputRef = useRef<HTMLInputElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const { getSubmenuContextItems } = useSubmenuContextProviders();
const allFiles = getSubmenuContextItems("file", "");
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const remainingFiles = allFiles.filter(
(file) => !codeToEdit.find((code) => code.filepath === file.id),
);
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
useEffect(() => {
// update selectedFiles showing only the files that are in codeToEdit
setSelectedFiles(
(prevSelectedFiles) =>
prevSelectedFiles.filter(
(file) =>
codeToEdit.findIndex((code) => code.filepath === file.id) !== -1,
),
);
}, [codeToEdit]);
const filteredFiles =
query === ""
? remainingFiles
: remainingFiles.filter((file) =>
file.title.toLowerCase().includes(query.toLowerCase()),
);
return (
<div className="pb-2 pl-3.5 pr-2">
<Combobox
multiple
value={selectedFiles}
onChange={(files) => {
setSelectedFiles(files);
void onSelect(files.map((file) => file.id));
buttonRef.current?.click();
setQuery("");
}}
>
{({ open }) => (
<div className="relative">
<ComboboxButton className="hidden" ref={buttonRef} />
<ComboboxInput
value={query}
ref={inputRef}
onClick={() => {
if (!open) {
buttonRef.current?.click();
}
}}
onFocus={() => {
buttonRef.current?.click();
}}
className="bg-vsc-background border-lightgray text-vsc-foreground box-border w-full rounded border border-solid py-0.5 pl-2 text-xs focus:outline-none"
onChange={(event) => setQuery(event.target.value)}
placeholder="Type to search files..."
onKeyDown={(e) => {
if (e.key === "Escape" && !open) {
void onEscape();
}
}}
/>
<ComboboxOptions className="no-scrollbar bg-vsc-editor-background border-lightgray/50 absolute left-0 right-0 z-50 mt-1 max-h-60 overflow-y-auto overflow-x-hidden rounded-md border border-solid px-1 py-0 pl-0 pr-5 shadow-lg focus:outline-none">
{filteredFiles.length > 0 ? (
filteredFiles.map((file) => (
<ComboboxOption
key={file.id}
value={file}
className={({ active }) =>
`relative flex w-full cursor-pointer px-2 py-1 text-left text-xs ${
active
? "bg-list-active text-list-active-foreground"
: ""
}`
}
>
{({ active, selected }) => (
<div className="group flex w-full min-w-0 items-center gap-1">
<div className="flex min-w-0 flex-1 items-center gap-1">
<FileIcon
height="20px"
width="20px"
filename={file.title}
/>
<span className="truncate">{file.title}</span>
</div>
<span
className={`text-lightgray max-w-[30%] truncate ${
active || selected ? "visible" : "invisible"
} group-hover:visible`}
>
{file.description}
</span>
</div>
)}
</ComboboxOption>
))
) : (
<div className="text-list-active-foreground px-2 py-1 text-xs">
No results
</div>
)}
</ComboboxOptions>
</div>
)}
</Combobox>
</div>
);
}

View file

@ -1,109 +0,0 @@
import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline";
import type { CodeToEdit } from "core";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import {
addCodeToEdit,
removeCodeToEdit,
} from "../../redux/slices/sessionSlice";
import AddFileButton from "./AddFileButton";
import AddFileCombobox from "./AddFileCombobox";
import CodeToEditListItem from "./CodeToEditListItem";
export default function CodeToEditCard() {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const [showAddFileCombobox, setShowAddFileCombobox] = useState(false);
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const itemCount =
codeToEdit.length === 0
? ""
: codeToEdit.length === 1
? "(1 item)"
: `(${codeToEdit.length} items)`;
function onDelete(rif: CodeToEdit) {
dispatch(removeCodeToEdit(rif));
}
async function onClickFilename(code: CodeToEdit) {
if ("range" in code) {
await ideMessenger.ide.showLines(
code.filepath,
code.range.start.line,
code.range.end.line,
);
} else {
await ideMessenger.ide.openFile(code.filepath);
}
}
async function onSelectFilesToAdd(uris: string[]) {
const filePromises = uris.map(async (uri) => {
const contents = await ideMessenger.ide.readFile(uri);
return { contents, filepath: uri };
});
const fileResults = await Promise.all(filePromises);
for (const file of fileResults) {
dispatch(addCodeToEdit(file));
}
}
return (
<div className="bg-vsc-editor-background mx-3 flex flex-col rounded-t-lg p-1">
<div className="text-lightgray flex items-center justify-between gap-1.5 py-1.5 pl-3 pr-2 text-xs">
<div className="flex items-center gap-1">
<span>Code to edit</span>
<span className="hidden sm:inline">{itemCount}</span>
</div>
<AddFileButton onClick={() => setShowAddFileCombobox(true)} />
</div>
{codeToEdit.length > 0 ? (
<ul className="no-scrollbar my-0 mb-1.5 max-h-[50vh] list-outside list-none overflow-y-auto pl-0">
{codeToEdit.map((code, i) => (
<CodeToEditListItem
key={code.filepath + i}
code={code}
onDelete={onDelete}
onClickFilename={onClickFilename}
/>
))}
</ul>
) : (
!showAddFileCombobox && (
<div
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground -mt-0.5 flex cursor-pointer items-center justify-center gap-1 rounded py-1 text-center text-xs transition-colors hover:bg-opacity-20"
onClick={() => setShowAddFileCombobox(true)}
>
<PlusIcon className="h-3.5 w-3.5" />
<span>Add a file to get started</span>
</div>
)
)}
{showAddFileCombobox && (
<div className="mr-2 flex items-center py-1">
<div className="flex-grow">
<AddFileCombobox
onSelect={onSelectFilesToAdd}
onEscape={() => setShowAddFileCombobox(false)}
/>
</div>
<XMarkIcon
onClick={() => {
setShowAddFileCombobox(false);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground mb-2 h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>
</div>
)}
</div>
);
}

View file

@ -1,142 +0,0 @@
import {
ChevronDownIcon,
ChevronRightIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { CodeToEdit } from "core";
import { getMarkdownLanguageTagForFile } from "core/util";
import {
getLastNUriRelativePathParts,
getUriPathBasename,
} from "core/util/uri";
import { useState } from "react";
import styled from "styled-components";
import FileIcon from "../FileIcon";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
export interface CodeToEditListItemProps {
code: CodeToEdit;
onDelete: (codeToEdit: CodeToEdit) => void | Promise<void>;
onClickFilename: (codeToEdit: CodeToEdit) => void | Promise<void>;
}
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 fileName = getUriPathBasename(code.filepath);
const last2Parts = getLastNUriRelativePathParts(
window.workspacePaths ?? [],
code.filepath,
2,
);
let isInsertion = false;
let title = fileName;
if ("range" in code) {
const start = code.range.start.line + 1;
const end = code.range.end.line + 1;
isInsertion = start === end;
title += isInsertion
? ` - Inserting at line ${start}`
: ` (${start} - ${end})`;
}
const source =
"```" +
getMarkdownLanguageTagForFile(code.filepath) +
"\n" +
code.contents +
"\n" +
"```";
return (
<li
className="group flex cursor-pointer flex-col"
onClick={() => {
if (!isInsertion) {
setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet);
}
}}
>
<div
className={`hover:bg-lightgray hover:text-vsc-foreground flex items-center justify-between rounded px-2 py-0.5 transition-colors hover:bg-opacity-20 ${showCodeSnippet && "text-vsc-foreground bg-lightgray bg-opacity-20"}`}
>
<div className="flex w-4/5 min-w-0 items-center gap-0.5">
<FileIcon filename={code.filepath} height={"18px"} width={"18px"} />
<div className="flex min-w-0 gap-1.5">
<span
className="flex-shrink-0 text-xs hover:underline"
onClick={(e) => {
e.stopPropagation();
void onClickFilename(code);
}}
>
{title}
</span>
<span className="text-lightgray invisible flex-grow truncate text-xs group-hover:visible">
{last2Parts}
</span>
</div>
</div>
<div className="invisible flex items-center group-hover:visible">
<div className={`flex items-center ${isInsertion ? "hidden" : ""}`}>
{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-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-sm p-0.5 hover:bg-opacity-20"
/>
)}
</div>
<div className="flex items-center">
<XMarkIcon
onClick={(e) => {
e.stopPropagation();
void onDelete(code);
}}
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20"
/>
</div>
</div>
</div>
{showCodeSnippet && (
<div className="max-h-[25vh] overflow-y-auto px-1 py-2">
<NoPaddingWrapper>
<StyledMarkdownPreview source={source} />
</NoPaddingWrapper>
</div>
)}
</li>
);
}

View file

@ -1 +0,0 @@
export { default } from "./CodeToEditCard";

View file

@ -6,6 +6,7 @@ import { useNavigate } from "react-router-dom";
import { Input } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/editMode";
import {
deleteSession,
getSession,
@ -68,6 +69,7 @@ export function HistoryTableRow({
data-testid={`history-row-${index}`}
className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3"
onClick={async () => {
await dispatch(exitEditMode({}));
if (sessionMetadata.sessionId !== currentSessionId) {
await dispatch(
loadSession({

View file

@ -1,21 +1,16 @@
import { useEffect } from "react";
import { useContext, useEffect } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import styled from "styled-components";
import { CustomScrollbarDiv, defaultBorderRadius } from ".";
import { AuthProvider } from "../context/Auth";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { LocalStorageProvider } from "../context/LocalStorage";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { focusEdit, setEditStatus } from "../redux/slices/editModeState";
import {
addCodeToEdit,
newSession,
selectIsInEditMode,
setMode,
} from "../redux/slices/sessionSlice";
import { setCodeToEdit } from "../redux/slices/editModeState";
import { setShowDialog } from "../redux/slices/uiSlice";
import { exitEditMode } from "../redux/thunks";
import { loadLastSession, saveCurrentSession } from "../redux/thunks/session";
import { enterEditMode, exitEditMode } from "../redux/thunks/editMode";
import { saveCurrentSession } from "../redux/thunks/session";
import { fontSize, isMetaEquivalentKeyPressed } from "../util";
import { incrementFreeTrialCount } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
@ -23,6 +18,7 @@ import { FatalErrorIndicator } from "./config/FatalErrorNotice";
import TextDialog from "./dialogs";
import Footer from "./Footer";
import { LumpProvider } from "./mainInput/Lump/LumpContext";
import { useMainEditor } from "./mainInput/TipTapEditor";
import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard";
import OSRContextMenu from "./OSRContextMenu";
import PostHogPageView from "./PosthogPageView";
@ -46,24 +42,30 @@ const Layout = () => {
const location = useLocation();
const dispatch = useAppDispatch();
const onboardingCard = useOnboardingCard();
const ideMessenger = useContext(IdeMessengerContext);
const { mainEditor } = useMainEditor();
const dialogMessage = useAppSelector((state) => state.ui.dialogMessage);
const showDialog = useAppSelector((state) => state.ui.showDialog);
const mode = useAppSelector((state) => state.session.mode);
useWebviewListener(
"newSession",
async () => {
navigate(ROUTES.HOME);
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
dispatch(exitEditMode());
if (mode === "edit") {
await dispatch(exitEditMode({}));
} else {
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
}
},
[],
[mode],
);
useWebviewListener(
@ -79,15 +81,22 @@ const Layout = () => {
"focusContinueInputWithNewSession",
async () => {
navigate(ROUTES.HOME);
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
dispatch(exitEditMode());
if (mode === "edit") {
await dispatch(
exitEditMode({
openNewSession: true,
}),
);
} else {
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
}
},
[location.pathname],
[location.pathname, mode],
location.pathname === ROUTES.HOME,
);
@ -138,66 +147,31 @@ const Layout = () => {
useWebviewListener(
"focusEdit",
async () => {
await dispatch(
saveCurrentSession({
openNewSession: false,
// Because this causes a lag before Edit mode is focused. TODO just have that happen in background
generateTitle: false,
}),
);
dispatch(newSession());
dispatch(focusEdit());
dispatch(setMode("edit"));
await ideMessenger.request("edit/addCurrentSelection", undefined);
await dispatch(enterEditMode({}));
mainEditor?.commands.focus();
},
[],
[ideMessenger, mainEditor],
);
useWebviewListener(
"focusEditWithoutClear",
async () => {
await dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: true,
}),
);
dispatch(focusEdit());
dispatch(setMode("edit"));
},
[],
);
useWebviewListener(
"addCodeToEdit",
"setCodeToEdit",
async (payload) => {
dispatch(addCodeToEdit(payload));
},
[navigate],
);
useWebviewListener(
"setEditStatus",
async ({ status, fileAfterEdit }) => {
dispatch(setEditStatus({ status, fileAfterEdit }));
dispatch(
setCodeToEdit({
codeToEdit: payload,
}),
);
},
[],
);
const isInEditMode = useAppSelector(selectIsInEditMode);
useWebviewListener(
"exitEditMode",
async () => {
if (!isInEditMode) {
return;
}
dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
await dispatch(exitEditMode({}));
},
[isInEditMode],
[],
);
useEffect(() => {

View file

@ -12,9 +12,9 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch } from "../../../redux/hooks";
import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
import { updateSelectedModelByRole } from "../../../redux/thunks";
import OllamaModelDownload from "../components/OllamaModelDownload";
import { OllamaStatus } from "../components/OllamaStatus";
import { useSubmitOnboarding } from "../hooks";
import OllamaModelDownload from "./OllamaModelDownload";
import { OllamaStatus } from "./OllamaStatus";
const OLLAMA_CHECK_INTERVAL_MS = 3000;

View file

@ -5,8 +5,8 @@ import { getLocalStorage, setLocalStorage } from "../../../util/localStorage";
import Alert from "../../gui/Alert";
import { ReusableCard } from "../../ReusableCard";
import { TabTitle } from "../components/OnboardingCardTabs";
import OnboardingLocalTab from "../components/OnboardingLocalTab";
import { useOnboardingCard } from "../hooks";
import OnboardingLocalTab from "../tabs/OnboardingLocalTab";
import MainTab from "./tabs/main";
export interface OnboardingCardState {

View file

@ -1,3 +1,3 @@
export { default as Local } from "../components/OnboardingLocalTab";
export { default as Best } from "./OnboardingBestTab";
export { default as Local } from "./OnboardingLocalTab";
export { default as Quickstart } from "./OnboardingQuickstartTab";

View file

@ -1,87 +0,0 @@
import { ChatHistoryItem } from "core";
import { renderChatMessage } from "core/util/messageContent";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/exitEditMode";
import { loadLastSession } from "../../redux/thunks/session";
import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
import FeedbackButtons from "../FeedbackButtons";
import { CopyIconButton } from "../gui/CopyIconButton";
export interface EditActionsProps {
index: number;
item: ChatHistoryItem;
}
export default function EditActions({ index, item }: EditActionsProps) {
// const curCheckpointIndex = useSelector(
// (store: RootState) => store.state.curCheckpointIndex,
// );
const dispatch = useAppDispatch();
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const applyStates = useAppSelector(
(state) => state.session.codeBlockApplyStates.states,
);
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const hasClosedAllStreams = applyStates.every(
(state) => state.status === "closed",
);
// const isCurCheckpoint = Math.floor(index / 2) === curCheckpointIndex;
const hasPendingApplies = pendingApplyStates.length > 0;
if (isStreaming) return null;
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 && (
<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}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
}
}}
/>
)}
{/* {hasClosedAllStreams && <UndoAndRedoButtons />} */}
</div>
<div className="flex flex-1 justify-end">
<CopyIconButton
tabIndex={-1}
text={renderChatMessage(item.message)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<FeedbackButtons item={item} />
</div>
</div>
);
}

View file

@ -1,12 +1,9 @@
import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { renderChatMessage } from "core/util/messageContent";
import { useAppSelector } from "../../redux/hooks";
import { selectIsInEditMode } from "../../redux/slices/sessionSlice";
import FeedbackButtons from "../FeedbackButtons";
import { CopyIconButton } from "../gui/CopyIconButton";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import EditActions from "./EditActions";
export interface ResponseActionsProps {
isTruncated: boolean;
@ -23,12 +20,6 @@ export default function ResponseActions({
isTruncated,
onDelete,
}: ResponseActionsProps) {
const isInEditMode = useAppSelector(selectIsInEditMode);
if (isInEditMode) {
return <EditActions index={index} item={item} />;
}
return (
<div className="mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs text-gray-400">
{isTruncated && (

View file

@ -1,62 +0,0 @@
import { useDispatch } from "react-redux";
import {
ArrowUturnLeftIcon,
ArrowUturnRightIcon,
} from "@heroicons/react/24/outline";
import { setCurCheckpointIndex } from "../../redux/slices/sessionSlice";
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
export default function UndoAndRedoButtons() {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const history = useAppSelector((store) => store.session.history);
const curCheckpointIndex = useAppSelector(
(store) => store.session.curCheckpointIndex,
);
const shouldRenderRedo = false; // curCheckpointIndex !== checkpoints.length - 1;
async function handleUndoOrRedo(type: "undo" | "redo") {
const checkpointIndex = Math.max(
0,
type === "undo" ? curCheckpointIndex - 1 : curCheckpointIndex + 1,
);
const checkpoint = history[checkpointIndex]?.checkpoint ?? {};
for (const [filepath, cachedFileContent] of Object.entries(checkpoint)) {
ideMessenger.post("overwriteFile", {
filepath,
prevFileContent: cachedFileContent,
});
}
dispatch(setCurCheckpointIndex(checkpointIndex));
}
return (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<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={() => handleUndoOrRedo("undo")}
>
<ArrowUturnLeftIcon className="mr-2 h-3.5 w-3.5" />
Undo changes
</button>
{shouldRenderRedo && (
<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={() => handleUndoOrRedo("redo")}
>
<ArrowUturnRightIcon className="mr-2 h-3.5 w-3.5" />
Redo changes
</button>
)}
</div>
);
}

View file

@ -11,10 +11,7 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useIdeMessengerRequest } from "../../../hooks";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { useAppSelector } from "../../../redux/hooks";
import {
selectApplyStateByStreamId,
selectIsInEditMode,
} from "../../../redux/slices/sessionSlice";
import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice";
import { getFontSize } from "../../../util";
import { isTerminalCodeBlock } from "../utils";
import { ApplyActions } from "./ApplyActions";
@ -74,10 +71,7 @@ export function StepContainerPreToolbar({
disableManualApply,
}: StepContainerPreToolbarProps) {
const ideMessenger = useContext(IdeMessengerContext);
const isInEditMode = useAppSelector(selectIsInEditMode);
const [isExpanded, setIsExpanded] = useState(
expanded ?? (isInEditMode ? false : true),
);
const [isExpanded, setIsExpanded] = useState(expanded ?? true);
const [relativeFilepathUri, setRelativeFilepathUri] = useState<string | null>(
null,

View file

@ -1,15 +1,12 @@
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../redux/hooks";
import { selectUseHub } from "../../redux/selectors";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { OnboardingCard } from "../OnboardingCard";
import { PlatformOnboardingCard } from "../OnboardingCard/platform/PlatformOnboardingCard";
function FreeTrialOverDialog() {
const dispatch = useDispatch();
const history = useAppSelector((store) => store.session.history);
const usePlatform = useAppSelector(selectUseHub);
useEffect(() => {
if (history.length === 0) {
@ -20,11 +17,7 @@ function FreeTrialOverDialog() {
return (
<div className="flex-1">
{usePlatform ? (
<PlatformOnboardingCard isDialog />
) : (
<OnboardingCard isDialog />
)}
<PlatformOnboardingCard isDialog />
</div>
);
}

View file

@ -0,0 +1,180 @@
import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { CodeToEdit } from "core";
import { getMarkdownLanguageTagForFile } from "core/util";
import { getUriPathBasename } from "core/util/uri";
import { useContext, useMemo, useState } from "react";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { clearCodeToEdit } from "../../redux/slices/editModeState";
import { getMetaKeyLabel } from "../../util";
import FileIcon from "../FileIcon";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import { useFontSize } from "../ui/font";
const NoPaddingWrapper = styled.div`
> * {
margin: 0 !important;
padding: 0 !important;
}
pre {
margin: 0 !important;
padding: 0px 0px 0px 10px !important;
}
`;
interface CodeToEditItemProps {
code: CodeToEdit;
}
function CodeToEditItem({ code }: CodeToEditItemProps) {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const [showCodeSnippet, setShowCodeSnippet] = useState(false);
function onDelete() {
dispatch(clearCodeToEdit());
ideMessenger.post("edit/clearDecorations", undefined);
}
const fileName = getUriPathBasename(code.filepath);
let isInsertion = false;
let title = fileName;
if ("range" in code) {
const start = code.range.start.line + 1;
const end = code.range.end.line + 1;
isInsertion = start === end;
title += isInsertion
? ` - Inserting at line ${start}`
: ` (${start} - ${end})`;
}
const source =
"```" +
getMarkdownLanguageTagForFile(code.filepath) +
"\n" +
code.contents +
"\n" +
"```";
async function onClickFilename() {
if ("range" in code) {
await ideMessenger.ide.showLines(
code.filepath,
code.range.start.line,
code.range.end.line,
);
} else {
await ideMessenger.ide.openFile(code.filepath);
}
}
const smallFont = useFontSize(-3);
const iconClass =
"text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20";
return (
<div className="flex flex-col gap-1 py-0.5">
<div className="group flex flex-row items-center justify-start gap-1.5 px-1">
<span
className="hidden flex-shrink-0 pl-2 font-semibold text-gray-400 sm:flex"
style={{
fontSize: smallFont,
}}
>
Code to edit
</span>
{/* <CodeBracketIcon className="h-3 w-3 flex-shrink-0 text-gray-400 sm:hidden" /> */}
<div
className={`hover:bg-lightgray flex flex-1 cursor-pointer items-center justify-between rounded transition-colors hover:bg-opacity-20 ${showCodeSnippet && "bg-lightgray bg-opacity-20"}`}
onClick={() => {
if (!isInsertion) {
setShowCodeSnippet((showCodeSnippet) => !showCodeSnippet);
}
}}
>
<div className="flex items-center gap-0.5">
<FileIcon filename={code.filepath} height={"18px"} width={"18px"} />
<span
className="line-clamp-1 text-xs hover:underline"
onClick={(e) => {
e.stopPropagation();
void onClickFilename();
}}
>
{title}
</span>
</div>
<div className="invisible flex items-center group-hover:visible">
<ChevronRightIcon
onClick={(e) => {
e.stopPropagation();
setShowCodeSnippet((val) => !val);
}}
className={`text-lightgray hover:bg-lightgray hover:text-vsc-foreground h-3.5 w-3.5 cursor-pointer rounded-sm p-0.5 hover:bg-opacity-20 ${showCodeSnippet ? "rotate-90" : ""} ${isInsertion ? "hidden" : ""}`}
/>
<div className="flex items-center">
<XMarkIcon
onClick={(e) => {
e.stopPropagation();
void onDelete();
}}
className={iconClass}
/>
</div>
</div>
</div>
</div>
{showCodeSnippet && (
<div className="!m-0 max-h-48 overflow-y-auto !p-0">
<NoPaddingWrapper>
<StyledMarkdownPreview source={source} />
</NoPaddingWrapper>
</div>
)}
</div>
);
}
export default function CodeToEditCard() {
// Array from previous multi-file edit
const codeToEditArray = useAppSelector(
(state) => state.editModeState.codeToEdit,
);
const codeToEdit = useMemo(() => {
return codeToEditArray[0];
}, [codeToEditArray]);
const metaKeyLabel = useMemo(() => {
return getMetaKeyLabel();
}, []);
const tinyFont = useFontSize(-3);
return (
<div className="bg-vsc-editor-background mx-3 flex flex-col rounded-t-lg py-1">
{codeToEdit ? (
<CodeToEditItem code={codeToEdit} />
) : (
<>
<span
className="text-balance px-3 text-center font-semibold text-gray-400"
style={{
fontSize: tinyFont,
}}
>
{`To edit code, highlight it and press `}
<kbd>{metaKeyLabel}</kbd> <kbd>I</kbd>
</span>
</>
)}
</div>
);
}

View file

@ -11,7 +11,6 @@ import { Lump } from "./Lump";
import { TipTapEditor } from "./TipTapEditor";
interface ContinueInputBoxProps {
isEditMode?: boolean;
isLastUserInput: boolean;
isMainInput?: boolean;
onEnter: (
@ -82,36 +81,40 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const availableContextProviders = useAppSelector(
(state) => state.config.config.contextProviders,
);
const mode = useAppSelector((store) => store.session.mode);
const editModeState = useAppSelector((state) => state.editModeState);
const filteredSlashCommands = props.isEditMode ? [] : availableSlashCommands;
const filteredSlashCommands = useMemo(() => {
return mode === "edit" ? [] : availableSlashCommands;
}, [mode, availableSlashCommands]);
const filteredContextProviders = useMemo(() => {
if (!props.isEditMode) {
return availableContextProviders ?? [];
if (mode === "edit") {
return (
availableContextProviders?.filter(
(provider) =>
!EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title),
) ?? []
);
}
return (
availableContextProviders?.filter(
(provider) =>
!EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title),
) ?? []
);
}, [availableContextProviders]);
return availableContextProviders ?? [];
}, [availableContextProviders, mode]);
const historyKey = props.isEditMode ? "edit" : "chat";
const placeholder = props.isEditMode
? "Describe changes, '#' to add files"
: undefined;
const historyKey = mode === "edit" ? "edit" : "chat";
const placeholder = mode === "edit" ? "Describe changes" : undefined;
const toolbarOptions: ToolbarOptions = props.isEditMode
? {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText: editModeState.editStatus === "accepting" ? "Retry" : "Edit",
}
: {};
const toolbarOptions: ToolbarOptions =
mode === "edit"
? {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText:
editModeState.applyState.status === "done" ? "Retry" : "Edit",
}
: {};
return (
<div

View file

@ -0,0 +1,59 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/editMode";
import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
import { useMainEditor } from "./TipTapEditor";
const EditModeDetails = () => {
const isStreaming = useAppSelector((store) => store.session.isStreaming);
const mode = useAppSelector((store) => store.session.mode);
const dispatch = useAppDispatch();
const editApplyState = useAppSelector(
(store) => store.editModeState.applyState,
);
const { mainEditor } = useMainEditor();
const ideMessenger = useContext(IdeMessengerContext);
if (mode !== "edit") {
return null;
}
if (isStreaming) {
return null;
}
if (editApplyState.status === "done") {
const plural = editApplyState.numDiffs === 1 ? "" : "s";
return (
<>
<div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400">
<span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span>
</div>
<AcceptRejectAllButtons
applyStates={[editApplyState]}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {
await dispatch(exitEditMode({}));
ideMessenger.post("focusEditor", undefined);
} else {
mainEditor?.commands.focus();
}
}}
/>
</>
);
}
// Will only still show if not all accepted
if (editApplyState.status === "closed") {
return (
<div>
<span></span>
</div>
);
}
// Not started/streaming
return null;
};
export default EditModeDetails;

View file

@ -1,7 +1,8 @@
import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline";
import { InputModifiers } from "core";
import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect";
import { useRef } from "react";
import { useContext, useRef } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
import {
@ -9,12 +10,7 @@ import {
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import {
selectHasCodeToEdit,
selectIsInEditMode,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
import { loadLastSession } from "../../redux/thunks/session";
import { exitEditMode } from "../../redux/thunks/editMode";
import {
getAltKeyLabel,
getMetaKeyLabel,
@ -49,20 +45,20 @@ interface InputToolbarProps {
function InputToolbar(props: InputToolbarProps) {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const defaultModel = useAppSelector(selectSelectedChatModel);
const useActiveFile = useAppSelector(selectUseActiveFile);
const isInEditMode = useAppSelector(selectIsInEditMode);
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
const mode = useAppSelector((store) => store.session.mode);
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
const toolCallState = useAppSelector(selectCurrentToolCall);
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const isEnterDisabled =
props.disabled ||
isEditModeAndNoCodeToEdit ||
(mode === "edit" && codeToEdit.length === 0) ||
toolCallState?.status === "generated" ||
(currentToolCallApplyState &&
currentToolCallApplyState.status !== "closed");
@ -91,13 +87,13 @@ function InputToolbar(props: InputToolbarProps) {
}}
>
<div className="xs:gap-1.5 flex flex-row items-center gap-1">
<HoverItem data-tooltip-id="mode-select-tooltip">
<HoverItem data-tooltip-id="mode-select-tooltip" className="!p-0">
<ModeSelect />
<ToolTip id="mode-select-tooltip" place="top">
Select Mode
</ToolTip>
</HoverItem>
<HoverItem data-tooltip-id="model-select-tooltip">
<HoverItem data-tooltip-id="model-select-tooltip" className="!p-0">
<ModelSelect />
<ToolTip id="model-select-tooltip" place="top">
Select Model
@ -158,7 +154,7 @@ function InputToolbar(props: InputToolbarProps) {
fontSize: tinyFont,
}}
>
{!props.toolbarOptions?.hideUseCodebase && !isInEditMode && (
{!props.toolbarOptions?.hideUseCodebase && mode !== "edit" && (
<div
className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`}
>
@ -188,16 +184,12 @@ function InputToolbar(props: InputToolbarProps) {
</div>
)}
{isInEditMode && (
{mode === "edit" && (
<HoverItem
className="hidden hover:underline sm:flex"
onClick={async (e) => {
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
onClick={async () => {
dispatch(exitEditMode({}));
ideMessenger.post("focusEditor", undefined);
}}
>
<span>

View file

@ -12,9 +12,9 @@ import {
import { ReactNode } from "react";
import { vscBadgeForeground } from "../..";
import { useAppSelector } from "../../../redux/hooks";
import { fontSize } from "../../../util";
import { ToolTip } from "../../gui/Tooltip";
import AssistantSelect from "../../modelSelection/platform/AssistantSelect";
import { useFontSize } from "../../ui/font";
import HoverItem from "../InputToolbar/HoverItem";
import { useLump } from "./LumpContext";
import { ErrorsSectionTooltip } from "./sections/errors/ErrorsSectionTooltip";
@ -74,8 +74,9 @@ function BlockSettingsToolbarIcon(
const isErrorSection = props.sectionId === "error";
const id = `block-settings-toolbar-icon-${props.sectionId}`;
return (
const fontSize = useFontSize(-3);
return (
<>
<HoverItem
px={0}
@ -98,7 +99,7 @@ function BlockSettingsToolbarIcon(
? "bg-red-600"
: "bg-badge"
: undefined
} relative flex select-none items-center rounded-full px-1 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 ${props.className || ""}`}
} relative flex select-none items-center rounded-full px-[3px] transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 sm:px-1 ${props.className || ""}`}
>
<props.icon
className={`h-[13px] w-[13px] flex-shrink-0 hover:brightness-125 ${
@ -110,7 +111,7 @@ function BlockSettingsToolbarIcon(
aria-hidden="true"
/>
<div
style={{ fontSize: fontSize(-3) }}
style={{ fontSize }}
className={`overflow-hidden transition-all duration-200 ${
props.isSelected ? "ml-1 w-auto opacity-100" : "w-0 opacity-0"
}`}
@ -123,7 +124,6 @@ function BlockSettingsToolbarIcon(
</span>
</div>
</div>
</HoverItem>
<ToolTip delayShow={700} id={id}>
{props.tooltip}
@ -156,7 +156,7 @@ export function BlockSettingsTopToolbar() {
);
return (
<div className="flex w-full items-center justify-between gap-4">
<div className="flex flex-1 items-center justify-between gap-2">
<div className="flex flex-row">
<div className="xs:flex hidden items-center justify-center text-gray-400">
<BlockSettingsToolbarIcon
@ -191,7 +191,10 @@ export function BlockSettingsTopToolbar() {
</div>
</div>
<div className="flex gap-0.5">
<HoverItem data-tooltip-id="assistant-select-tooltip">
<HoverItem
data-tooltip-id="assistant-select-tooltip"
className="!m-0 !p-0"
>
<AssistantSelect />
<ToolTip id="assistant-select-tooltip" place="top">
Select Assistant

View file

@ -4,7 +4,7 @@ export const ErrorsSectionTooltip = () => {
const configError = useAppSelector((store) => store.config.configError);
const numErrors = configError?.length ?? 0;
const plural = numErrors > 1 ? "s" : "";
const plural = numErrors === 1 ? "" : "s";
return (
<div>

View file

@ -7,7 +7,6 @@ import useIsOSREnabled from "../../../hooks/useIsOSREnabled";
import useUpdatingRef from "../../../hooks/useUpdatingRef";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { selectSelectedChatModel } from "../../../redux/slices/configSlice";
import { selectIsInEditMode } from "../../../redux/slices/sessionSlice";
import InputToolbar, { ToolbarOptions } from "../InputToolbar";
import { ComboBoxItem } from "../types";
import { DragOverlay, InputBoxDiv } from "./components";
@ -48,9 +47,9 @@ export function TipTapEditor(props: TipTapEditorProps) {
const defaultModel = useAppSelector(selectSelectedChatModel);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const isInEditMode = useAppSelector(selectIsInEditMode);
const historyLength = useAppSelector((store) => store.session.history.length);
const mode = useAppSelector((store) => store.session.mode);
const { editor, onEnterRef } = createEditorConfig({
props,
ideMessenger,
@ -82,13 +81,16 @@ export function TipTapEditor(props: TipTapEditorProps) {
}, [editor, props.placeholder, historyLength]);
useEffect(() => {
if (isInEditMode) {
setShouldHideToolbar(false);
}
if (props.isMainInput) {
editor?.commands.clearContent(true);
}
}, [editor, isInEditMode, props.isMainInput]);
}, [editor, props.isMainInput]);
useEffect(() => {
if (mode === "edit") {
setShouldHideToolbar(false);
}
}, [mode]);
const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
@ -148,7 +150,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
const handleBlur = useCallback(
(e: React.FocusEvent) => {
if (isInEditMode) {
if (mode === "edit") {
return;
}
// Check if the new focus target is within our InputBoxDiv
@ -163,7 +165,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
setShouldHideToolbar(true);
}, 100);
},
[isInEditMode, blurTimeout],
[mode, blurTimeout],
);
const handleFocus = useCallback(() => {

View file

@ -1,189 +0,0 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion from "@tiptap/suggestion";
import { MentionOptions } from "./types";
export const AddCodeToEdit = Node.create<MentionOptions>({
name: "add-code-to-edit",
addOptions() {
return {
HTMLAttributes: {
class: "add-code-to-edit",
},
renderHTML({ options, node }) {
return [
"span",
this.HTMLAttributes,
`${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`,
];
},
suggestion: {
char: "#",
pluginKey: new PluginKey(this.name),
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 (typeof attributes.renderInlineAs !== "string") {
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

@ -1,4 +1,3 @@
export * from "./AddCodeToEdit";
export * from "./CodeBlock";
export * from "./Mention";
export * from "./Prompt";

View file

@ -3,10 +3,8 @@ import { InputModifiers } from "core";
import { rifWithContentsToContextItem } from "core/commands/util";
import { MutableRefObject } from "react";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import {
clearCodeToEdit,
setNewestToolbarPreviewForInput,
} from "../../../redux/slices/sessionSlice";
import { clearCodeToEdit } from "../../../redux/slices/editModeState";
import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice";
import { AppDispatch } from "../../../redux/store";
import { loadSession, saveCurrentSession } from "../../../redux/thunks/session";
import { CodeBlock, PromptBlock } from "./extensions";
@ -158,26 +156,6 @@ export function useMainEditorWebviewListeners({
[editor, inputId, onEnterRef.current],
);
useWebviewListener(
"focusEdit",
async () => {
setTimeout(() => {
editor?.commands.focus("end");
}, 20);
},
[editor],
);
useWebviewListener(
"focusEditWithoutClear",
async () => {
setTimeout(() => {
editor?.commands.focus("end");
}, 2000);
},
[editor],
);
useWebviewListener(
"isContinueInputFocused",
async () => {

View file

@ -22,14 +22,8 @@ import useUpdatingRef from "../../../../hooks/useUpdatingRef";
import { useAppSelector } from "../../../../redux/hooks";
import { selectUseActiveFile } from "../../../../redux/selectors";
import { selectSelectedChatModel } from "../../../../redux/slices/configSlice";
import {
addCodeToEdit,
selectHasCodeToEdit,
selectIsInEditMode,
} from "../../../../redux/slices/sessionSlice";
import { AppDispatch } from "../../../../redux/store";
import { exitEditMode } from "../../../../redux/thunks";
import { loadLastSession } from "../../../../redux/thunks/session";
import { exitEditMode } from "../../../../redux/thunks/editMode";
import { getFontSize, isJetBrains } from "../../../../util";
import * as ContinueExtensions from "../extensions";
import { TipTapEditorProps } from "../TipTapEditor";
@ -87,15 +81,14 @@ export function createEditorConfig(options: {
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const useActiveFile = useAppSelector(selectUseActiveFile);
const historyLength = useAppSelector((store) => store.session.history.length);
const isInEditMode = useAppSelector(selectIsInEditMode);
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
const mode = useAppSelector((store) => store.session.mode);
const modeRef = useUpdatingRef(mode);
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
const inSubmenuRef = useRef<string | undefined>(undefined);
const inDropdownRef = useRef(false);
const defaultModelRef = useUpdatingRef(defaultModel);
const isStreamingRef = useUpdatingRef(isStreaming);
const isInEditModeRef = useUpdatingRef(isInEditMode);
const getSubmenuContextItemsRef = useUpdatingRef(getSubmenuContextItems);
const availableContextProvidersRef = useUpdatingRef(
props.availableContextProviders,
@ -267,24 +260,23 @@ export function createEditorConfig(options: {
return false;
},
Escape: () => {
if (inDropdownRef.current) {
return false;
}
// In JetBrains, this is how we close the sidebar when the input box is focused
if (isJetBrains()) {
ideMessenger.post("closeSidebar", undefined);
return true;
}
if (inDropdownRef.current || !isInEditModeRef.current) {
ideMessenger.post("focusEditor", undefined);
return true;
}
(async () => {
await dispatch(
loadLastSession({
saveCurrentSession: false,
if (modeRef.current === "edit") {
dispatch(
exitEditMode({
openNewSession: false,
}),
);
dispatch(exitEditMode());
})();
}
ideMessenger.post("focusEditor", undefined);
return true;
},
@ -325,42 +317,6 @@ export function createEditorConfig(options: {
ideMessenger,
),
}),
ContinueExtensions.AddCodeToEdit.configure({
suggestion: {
...getContextProviderDropdownOptions(
availableContextProvidersRef,
getSubmenuContextItemsRef,
enterSubmenu,
onClose,
onOpen,
inSubmenuRef,
ideMessenger,
),
allow: () => isInEditModeRef.current,
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,
}));
},
},
}),
ContinueExtensions.SlashCommand.configure({
suggestion: getSlashCommandDropdownOptions(
availableSlashCommandsRef,
@ -389,7 +345,7 @@ export function createEditorConfig(options: {
if (!editor) {
return;
}
if (isStreaming || isEditModeAndNoCodeToEdit) {
if (isStreaming || (codeToEdit.length === 0 && mode === "edit")) {
return;
}
@ -406,7 +362,7 @@ export function createEditorConfig(options: {
props.onEnter(json, modifiers, editor);
},
[props.onEnter, editor, props.isMainInput],
[props.onEnter, editor, props.isMainInput, codeToEdit, mode],
);
return { editor, onEnterRef };

View file

@ -8,23 +8,15 @@ import {
} from "@heroicons/react/24/outline";
import { MessageModes } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo } from "react";
import styled from "styled-components";
import { lightGray } from "..";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import {
cycleMode,
selectCurrentMode,
setMode,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
import {
loadLastSession,
saveCurrentSession,
} from "../../redux/thunks/session";
import { setMode } from "../../redux/slices/sessionSlice";
import { enterEditMode, exitEditMode } from "../../redux/thunks/editMode";
import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util";
import { useMainEditor } from "../mainInput/TipTapEditor";
import {
Listbox,
ListboxButton,
@ -40,12 +32,12 @@ const ShortcutText = styled.span`
function ModeSelect() {
const dispatch = useAppDispatch();
const mode = useAppSelector(selectCurrentMode);
const mode = useAppSelector((store) => store.session.mode);
const selectedModel = useAppSelector(selectSelectedChatModel);
const currentSession = useAppSelector((state) => state.session);
const [newSessionInitialized, setNewSessionInitialized] = useState(false);
const agentModeSupported = selectedModel && modelSupportsTools(selectedModel);
const agentModeSupported = useMemo(() => {
return selectedModel && modelSupportsTools(selectedModel);
}, [selectedModel]);
const { mainEditor } = useMainEditor();
const jetbrains = useMemo(() => {
return isJetBrains();
}, []);
@ -74,59 +66,79 @@ function ModeSelect() {
}
}, [mode, agentModeSupported, dispatch, selectedModel]);
const cycleMode = useCallback(async () => {
const modes: MessageModes[] = jetbrains
? ["chat", "agent"]
: ["chat", "agent", "edit"];
const currentIndex = modes.indexOf(mode);
const nextMode = modes[(currentIndex + 1) % modes.length];
if (mode === "edit") {
await dispatch(
exitEditMode({
goToMode: nextMode,
}),
);
} else {
if (nextMode === "edit") {
await dispatch(
enterEditMode({
returnToMode: mode,
}),
);
} else {
dispatch(setMode(nextMode));
}
}
mainEditor?.commands.focus();
}, [jetbrains, mode, mainEditor]);
const selectMode = useCallback(
async (newMode: MessageModes) => {
if (newMode === mode) {
return;
}
if (newMode === "edit") {
await dispatch(
enterEditMode({
returnToMode: mode,
}),
);
} else {
if (mode === "edit") {
await dispatch(
exitEditMode({
goToMode: newMode,
}),
);
} else {
dispatch(setMode(newMode));
}
}
mainEditor?.commands.focus();
},
[mode, mainEditor],
);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "." && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
dispatch(cycleMode({ isJetBrains: jetbrains }));
void cycleMode();
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [dispatch, mode, jetbrains]);
useWebviewListener("newSession", async () => {
setNewSessionInitialized(true);
});
useEffect(() => {
if (currentSession.history.length > 0) {
setNewSessionInitialized(false);
}
}, [currentSession.history]);
}, [cycleMode]);
return (
<Listbox
value={mode}
onChange={async (newMode) => {
if (newMode === mode) {
return;
}
dispatch(setMode(newMode));
if (newMode === "edit" || newSessionInitialized) {
// generate a new session for edit mode and if user opened a new session explicitly
await dispatch(
saveCurrentSession({
generateTitle: false,
openNewSession: true,
}),
);
} else if (mode === "edit") {
// load last session if the previous mode was edit
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
}
}}
>
<Listbox value={mode} onChange={selectMode}>
<div className="relative">
<ListboxButton
data-testid="mode-select-button"
className="gap-1 border-none px-2 py-0.5 text-gray-400 transition-colors duration-200"
className="xs:px-2 gap-1 border-none px-1.5 py-0.5 text-gray-400 transition-colors duration-200"
style={{
backgroundColor: `${lightGray}33`,
borderRadius: "9999px",
@ -142,24 +154,6 @@ function ModeSelect() {
/>
</ListboxButton>
<ListboxOptions className="min-w-32 max-w-48">
<ListboxOption value="agent" disabled={!agentModeSupported}>
<div className="flex flex-row items-center gap-1.5">
<SparklesIcon className="h-3 w-3" />
<span className="">Agent</span>
</div>
{mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />}
{!agentModeSupported && <span> (Not supported)</span>}
</ListboxOption>
<ListboxOption value="chat">
<div className="flex flex-row items-center gap-1.5">
<ChatBubbleLeftIcon className="h-3 w-3" />
<span className="">Chat</span>
<ShortcutText>{getMetaKeyLabel()}L</ShortcutText>
</div>
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
{!jetbrains && (
<ListboxOption value="edit">
<div className="flex flex-row items-center gap-1.5">
@ -170,6 +164,23 @@ function ModeSelect() {
{mode === "edit" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
)}
<ListboxOption value="chat">
<div className="flex flex-row items-center gap-1.5">
<ChatBubbleLeftIcon className="h-3 w-3" />
<span className="">Chat</span>
<ShortcutText>{getMetaKeyLabel()}L</ShortcutText>
</div>
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
<ListboxOption value="agent" disabled={!agentModeSupported}>
<div className="flex flex-row items-center gap-1.5">
<SparklesIcon className="h-3 w-3" />
<span className="">Agent</span>
</div>
{mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />}
{!agentModeSupported && <span> (Not supported)</span>}
</ListboxOption>
<div className="text-lightgray px-2 py-1">
{metaKeyLabel}. for next mode

View file

@ -12,9 +12,6 @@ import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import AddModelForm from "../../forms/AddModelForm";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {
selectIsInEditMode,
} from "../../redux/slices/sessionSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { updateSelectedModelByRole } from "../../redux/thunks";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
@ -123,12 +120,12 @@ function ModelOption({
function ModelSelect() {
const dispatch = useAppDispatch();
const isInEditMode = useAppSelector(selectIsInEditMode);
const mode = useAppSelector((store) => store.session.mode);
const config = useAppSelector((state) => state.config.config);
let selectedModel = null;
let allModels = null;
if (isInEditMode) {
if (mode === "edit") {
allModels = config.modelsByRole.edit;
selectedModel = config.selectedModelByRole.edit;
}
@ -158,14 +155,14 @@ function ModelSelect() {
useEffect(() => {
setOptions(
allModels.map((model) => {
return {
value: model.title,
title: modelSelectTitle(model),
apiKey: model.apiKey,
};
}),
return {
value: model.title,
title: modelSelectTitle(model),
apiKey: model.apiKey,
};
}),
);
}, [isInEditMode, config]);
}, [config]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
@ -225,7 +222,7 @@ function ModelSelect() {
dispatch(
updateSelectedModelByRole({
selectedProfile,
role: isInEditMode ? "edit" : "chat",
role: mode === "edit" ? "edit" : "chat",
modelTitle: val,
}),
);

View file

@ -2,6 +2,7 @@ import { useCallback, useContext, useEffect, useRef } from "react";
import { VSC_THEME_COLOR_VARS } from "../components";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { FromCoreProtocol } from "core/protocol";
import {
initializeProfilePreferences,
@ -11,10 +12,11 @@ import {
} from "../redux";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
import { setConfigResult } from "../redux/slices/configSlice";
import {
selectSelectedChatModel,
setConfigResult,
} from "../redux/slices/configSlice";
setLastNonEditSessionEmpty,
updateEditStateApplyState,
} from "../redux/slices/editModeState";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import {
acceptToolCall,
@ -31,11 +33,11 @@ import { isJetBrains } from "../util";
import { setLocalStorage } from "../util/localStorage";
import { useWebviewListener } from "./useWebviewListener";
function useSetup() {
function ParallelListeners() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const history = useAppSelector((store) => store.session.history);
const defaultModel = useAppSelector(selectSelectedChatModel);
const selectedProfileId = useAppSelector(
(store) => store.profiles.selectedProfileId,
);
@ -81,10 +83,6 @@ function useSetup() {
const initialLoadAuthAndConfig = useCallback(
async (initial: boolean) => {
// const authResult = await ideMessenger.request(
// "auth/getState",
// undefined
// )
const result = await ideMessenger.request(
"config/getSerializedProfileInfo",
undefined,
@ -259,34 +257,47 @@ function useSetup() {
useWebviewListener(
"updateApplyState",
async (state) => {
dispatch(updateApplyState(state));
if (state.streamId === EDIT_MODE_STREAM_ID) {
dispatch(updateEditStateApplyState(state));
} else {
// chat or agent
dispatch(updateApplyState(state));
// Handle apply status updates that are associated with current tool call
if (
state.status === "closed" &&
currentToolCallApplyState &&
currentToolCallApplyState.streamId === state.streamId
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// Handle apply status updates that are associated with current tool call
if (
state.status === "closed" &&
currentToolCallApplyState &&
currentToolCallApplyState.streamId === state.streamId
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
}
},
[currentToolCallApplyState, history],
);
const mode = useAppSelector((store) => store.session.mode);
useEffect(() => {
if (mode !== "edit") {
dispatch(setLastNonEditSessionEmpty(history.length === 0));
}
}, [mode, history]);
return <></>;
}
export default useSetup;
export default ParallelListeners;

View file

@ -1,13 +1,13 @@
import { useDispatch } from "react-redux";
import { useNavigate, useRouteError } from "react-router-dom";
import { newSession } from "../redux/slices/sessionSlice";
import { GithubIcon } from "../components/svg/GithubIcon";
import { DiscordIcon } from "../components/svg/DiscordIcon";
import { useContext, useEffect, useState } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { Button, SecondaryButton } from "../components";
import { ArrowPathIcon, FlagIcon } from "@heroicons/react/24/outline";
import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { useNavigate, useRouteError } from "react-router-dom";
import { Button, SecondaryButton } from "../components";
import { DiscordIcon } from "../components/svg/DiscordIcon";
import { GithubIcon } from "../components/svg/GithubIcon";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { newSession } from "../redux/slices/sessionSlice";
const ErrorPage: React.FC = () => {
const error: any = useRouteError();
@ -61,16 +61,16 @@ const ErrorPage: React.FC = () => {
Report the issue on GitHub or Discord:
</p>
<div className="flex space-x-4">
<div className="mt-2 flex flex-row flex-wrap justify-center gap-2">
<SecondaryButton
onClick={() => openUrl(GITHUB_LINK)}
className="flex w-full items-center justify-center space-x-2 rounded-lg px-4 py-2 text-base text-white"
className="flex items-center justify-center space-x-2 rounded-lg px-4 py-2 text-base text-white"
>
<GithubIcon size={20} /> <span className="ml-2">GitHub</span>
</SecondaryButton>
<SecondaryButton
onClick={() => openUrl(DISCORD_LINK)}
className="flex w-full items-center justify-center rounded-lg text-base"
className="flex items-center justify-center rounded-lg text-base"
>
<DiscordIcon size={20} /> <span className="ml-2">Discord</span>
</SecondaryButton>

View file

@ -1,6 +1,6 @@
import { renderWithProviders } from "../../util/test/render";
import { screen, waitFor } from "@testing-library/dom";
import { act, fireEvent } from "@testing-library/react";
import { act } from "@testing-library/react";
import { renderWithProviders } from "../../util/test/render";
import { Chat } from "./Chat";
describe("Chat page test", () => {
@ -23,8 +23,8 @@ describe("Chat page test", () => {
);
});
// Check that it switched to Edit mode
expect(await screen.findByText("Edit")).toBeInTheDocument();
// Check that it switched to Agent mode
expect(await screen.findByText("Agent")).toBeInTheDocument();
act(() => {
document.dispatchEvent(
@ -35,8 +35,8 @@ describe("Chat page test", () => {
);
});
// Check that it switched to Agent mode
expect(await screen.findByText("Agent")).toBeInTheDocument();
// Check that it switched to Edit mode
expect(await screen.findByText("Edit")).toBeInTheDocument();
});
it.skip("should send a message and receive a response", async () => {

View file

@ -5,16 +5,22 @@ import {
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/react";
import { InputModifiers, RangeInFileWithContents } from "core";
import { InputModifiers } from "core";
import { streamResponse } from "core/llm/stream";
import { renderChatMessage, stripImages } from "core/util/messageContent";
import { renderChatMessage } from "core/util/messageContent";
import { usePostHog } from "posthog-js/react";
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { ErrorBoundary } from "react-error-boundary";
import styled from "styled-components";
import { Button, lightGray, vscBackground } from "../../components";
import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons";
import CodeToEditCard from "../../components/CodeToEditCard";
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog";
import { useFindWidget } from "../../components/find/FindWidget";
@ -22,24 +28,18 @@ import TimelineItem from "../../components/gui/TimelineItem";
import { NewSessionButton } from "../../components/mainInput/belowMainInput/NewSessionButton";
import ThinkingBlockPeek from "../../components/mainInput/belowMainInput/ThinkingBlockPeek";
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils";
import { useOnboardingCard } from "../../components/OnboardingCard";
import StepContainer from "../../components/StepContainer";
import { TabBar } from "../../components/TabBar/TabBar";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseHub } from "../../redux/selectors";
import {
selectCurrentToolCall,
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { submitEdit } from "../../redux/slices/editModeState";
import {
newSession,
selectIsInEditMode,
selectIsSingleRangeEditOrInsertion,
updateToolCallOutput,
} from "../../redux/slices/sessionSlice";
import {
@ -48,7 +48,7 @@ import {
setShowDialog,
} from "../../redux/slices/uiSlice";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { exitEditMode } from "../../redux/thunks/exitEditMode";
import { streamEditThunk } from "../../redux/thunks/editMode";
import { loadLastSession } from "../../redux/thunks/session";
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
@ -56,7 +56,9 @@ import {
FREE_TRIAL_LIMIT_REQUESTS,
incrementFreeTrialCount,
} from "../../util/freeTrial";
import getMultifileEditPrompt from "../../util/getMultifileEditPrompt";
import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
import EditModeDetails from "../../components/mainInput/EditModeDetails";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
@ -106,7 +108,9 @@ export function Chat() {
const showSessionTabs = useAppSelector(
(store) => store.config.config.ui?.showSessionTabs,
);
const selectedChatModel = useAppSelector(selectSelectedChatModel);
const selectedModels = useAppSelector(
(store) => store.config?.config.selectedModelByRole,
);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
const mainTextInputRef = useRef<HTMLInputElement>(null);
@ -115,25 +119,20 @@ export function Chat() {
const showChatScrollbar = useAppSelector(
(state) => state.config.config.ui?.showChatScrollbar,
);
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const codeToEdit = useAppSelector((state) => state.editModeState.codeToEdit);
const toolCallState = useAppSelector(selectCurrentToolCall);
const mode = useAppSelector((store) => store.session.mode);
const applyStates = useAppSelector(
(state) => state.session.codeBlockApplyStates.states,
);
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const hasPendingApplies = pendingApplyStates.length > 0;
const isInEditMode = useAppSelector(selectIsInEditMode);
const isSingleRangeEditOrInsertion = useAppSelector(
selectIsSingleRangeEditOrInsertion,
);
const lastSessionId = useAppSelector((state) => state.session.lastSessionId);
const useHub = useAppSelector(selectUseHub);
const hasDismissedExploreDialog = useAppSelector(
(state) => state.ui.hasDismissedExploreDialog,
);
const jetbrains = isJetBrains();
const jetbrains = useMemo(() => {
return isJetBrains();
}, []);
useEffect(() => {
// Cmd + Backspace to delete current step
@ -151,7 +150,7 @@ export function Chat() {
return () => {
window.removeEventListener("keydown", listener);
};
}, [isStreaming]);
}, [isStreaming, jetbrains]);
const { widget, highlights } = useFindWidget(stepsDivRef);
@ -179,7 +178,20 @@ export function Chat() {
"Cannot submit message while awaiting tool call apply",
);
}
if (selectedChatModel?.provider === "free-trial") {
const model =
mode === "edit"
? (selectedModels?.edit ?? selectedModels?.chat)
: selectedModels?.chat;
if (!model) {
return;
}
if (mode === "edit" && codeToEdit.length === 0) {
return;
}
if (model.provider === "free-trial") {
const newCount = incrementFreeTrialCount();
if (newCount === FREE_TRIAL_LIMIT_REQUESTS) {
@ -206,21 +218,19 @@ export function Chat() {
}
}
if (isSingleRangeEditOrInsertion) {
handleSingleRangeEditOrInsertion(editorState);
return;
}
if (mode === "edit") {
dispatch(
streamEditThunk({
editorState,
codeToEdit,
}),
);
} else {
dispatch(streamResponseThunk({ editorState, modifiers, index }));
const promptPreamble = isInEditMode
? getMultifileEditPrompt(codeToEdit)
: undefined;
dispatch(
streamResponseThunk({ editorState, modifiers, promptPreamble, index }),
);
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
}
}
// Increment localstorage counter for popup
@ -236,47 +246,9 @@ export function Chat() {
setLocalStorage("mainTextEntryCounter", 1);
}
},
[
history,
selectedChatModel,
streamResponse,
isSingleRangeEditOrInsertion,
codeToEdit,
toolCallState,
],
[history, selectedModels, streamResponse, mode, codeToEdit, toolCallState],
);
async function handleSingleRangeEditOrInsertion(editorState: JSONContent) {
if (!selectedChatModel) {
console.error("No selected chat model");
return;
}
const [contextItems, __, userInstructions, _] = await resolveEditorContent({
editorState,
modifiers: {
noContext: true,
useCodebase: false,
},
ideMessenger,
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
});
const prompt = [
...contextItems.map((item) => item.content),
stripImages(userInstructions),
].join("\n\n");
ideMessenger.post("edit/sendPrompt", {
prompt,
range: codeToEdit[0] as RangeInFileWithContents,
});
dispatch(submitEdit(prompt));
}
useWebviewListener(
"newSession",
async () => {
@ -314,8 +286,6 @@ export function Chat() {
useAutoScroll(stepsDivRef, history);
const showPageHeader = isInEditMode || useHub;
return (
<>
{widget}
@ -324,7 +294,7 @@ export function Chat() {
<StepsDiv
ref={stepsDivRef}
className={`mt-3 overflow-y-scroll ${showPageHeader ? "" : "pt-[8px]"} ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
>
{highlights}
{history.map((item, index: number) => (
@ -342,9 +312,7 @@ export function Chat() {
>
{item.message.role === "user" ? (
<>
{isInEditMode && index === 0 && <CodeToEditCard />}
<ContinueInputBox
isEditMode={isInEditMode}
onEnter={(editorState, modifiers) =>
sendInput(editorState, modifiers, index)
}
@ -421,19 +389,24 @@ export function Chat() {
))}
</StepsDiv>
<div className={"relative"}>
{isInEditMode && history.length === 0 && <CodeToEditCard />}
{isInEditMode && history.length > 0 ? null : (
<>
{!isStreaming && mode !== "edit" && (
<AcceptRejectAllButtons
applyStates={applyStates}
onAcceptOrReject={async () => {}}
/>
)}
{mode === "edit" && <CodeToEditCard />}
<ContinueInputBox
isMainInput
isEditMode={isInEditMode}
isLastUserInput={false}
onEnter={(editorState, modifiers, editor) =>
sendInput(editorState, modifiers, undefined, editor)
}
inputId={MAIN_EDITOR_INPUT_ID}
/>
)}
<EditModeDetails />
</>
<div
style={{
@ -442,7 +415,7 @@ export function Chat() {
>
<div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
<div className="xs:inline hidden">
{history.length === 0 && lastSessionId && !isInEditMode && (
{history.length === 0 && lastSessionId && mode !== "edit" && (
<div className="xs:inline hidden">
<NewSessionButton
onClick={async () => {
@ -461,30 +434,9 @@ export function Chat() {
)}
</div>
</div>
{hasPendingApplies && isSingleRangeEditOrInsertion && (
<AcceptRejectAllButtons
pendingApplyStates={pendingApplyStates}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
dispatch(exitEditMode());
}
}}
/>
)}
{!hasDismissedExploreDialog && <ExploreDialogWatcher />}
{history.length === 0 && (
<EmptyChatBody
useHub={useHub}
showOnboardingCard={onboardingCard.show}
/>
<EmptyChatBody showOnboardingCard={onboardingCard.show} />
)}
</div>
</div>

View file

@ -4,18 +4,15 @@ import { OnboardingCard } from "../../components/OnboardingCard";
import { PlatformOnboardingCard } from "../../components/OnboardingCard/platform/PlatformOnboardingCard";
export interface EmptyChatBodyProps {
useHub: boolean;
showOnboardingCard?: boolean;
}
export function EmptyChatBody({
useHub,
showOnboardingCard,
}: EmptyChatBodyProps) {
export function EmptyChatBody({ showOnboardingCard }: EmptyChatBodyProps) {
if (showOnboardingCard) {
return (
<div className="mx-2 mt-6">
{useHub ? (
{true ? (
// For now we are excluding local onboarding options other than ollama
<PlatformOnboardingCard isDialog={false} />
) : (
<OnboardingCard isDialog={false} />

View file

@ -11,7 +11,6 @@ import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { selectSelectedProfile } from "../../redux/";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseHub } from "../../redux/selectors";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { isLocalProfile } from "../../util";
@ -36,7 +35,6 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const selectedModel = useAppSelector(selectSelectedChatModel);
const hubEnabled = useAppSelector(selectUseHub);
const selectedProfile = useAppSelector(selectSelectedProfile);
const { session, refreshProfiles } = useAuth();
@ -180,17 +178,14 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
if (statusCode === 401) {
errorContent = (
<div className="flex flex-col gap-2">
{hubEnabled &&
session &&
selectedProfile &&
!isLocalProfile(selectedProfile) && (
<div className="flex flex-col gap-1">
<span>{`If your hub secret values may have changed, refresh your assistants`}</span>
<SecondaryButton onClick={handleRefreshProfiles}>
Refresh assistant secrets
</SecondaryButton>
</div>
)}
{session && selectedProfile && !isLocalProfile(selectedProfile) && (
<div className="flex flex-col gap-1">
<span>{`If your hub secret values may have changed, refresh your assistants`}</span>
<SecondaryButton onClick={handleRefreshProfiles}>
Refresh assistant secrets
</SecondaryButton>
</div>
)}
<span>{`It's possible that your API key is invalid.`}</span>
<div className="flex flex-row flex-wrap gap-2">
{checkKeysButton}

View file

@ -1,7 +1,6 @@
import { getMarkdownLanguageTagForFile } from "core/util";
import { useEffect } from "react";
import { v4 as uuidv4 } from "uuid";
import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons";
import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
@ -41,29 +40,13 @@ export function EditFile(props: EditToolCallProps) {
}
return (
<>
<StyledMarkdownPreview
isRenderingInStepContainer
disableManualApply
source={src}
forceStreamId={applyState?.streamId}
expandCodeblocks={false}
itemIndex={props.historyIndex}
/>
{/* TODO better indicator of generation at bottom */}
{/* {isStreaming && applyState?.status === "streaming" && (
<div className={`m-2 flex items-center justify-center`}>
Generating...
</div>
)} */}
{!isStreaming && applyState?.status === "done" && (
<div className={`m-2 flex items-center justify-center`}>
<AcceptRejectAllButtons
pendingApplyStates={[applyState]}
onAcceptOrReject={async (outcome) => {}}
/>
</div>
)}
</>
<StyledMarkdownPreview
isRenderingInStepContainer
disableManualApply
source={src}
forceStreamId={applyState?.streamId}
expandCodeblocks={false}
itemIndex={props.historyIndex}
/>
);
}

View file

@ -46,6 +46,3 @@ export const selectUseActiveFile = createSelector(
[(state: RootState) => state.config.config.experimental?.defaultContext],
(defaultContext) => defaultContext?.includes("activeFile" as any),
);
export const selectUseHub = (state: RootState) =>
state.config.config.usePlatform;

View file

@ -1,82 +1,76 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { EditStatus, MessageContent } from "core";
import { ApplyState, CodeToEdit, MessageModes } from "core";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
export interface EditModeState {
editStatus: EditStatus;
previousInputs: MessageContent[];
fileAfterEdit?: string;
// Array because of previous multi-file edit functionality
// Keeping array to not break persisted redux for now
codeToEdit: CodeToEdit[];
applyState: ApplyState;
returnToMode: MessageModes;
lastNonEditSessionWasEmpty: boolean;
}
export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
streamId: EDIT_MODE_STREAM_ID,
status: "not-started",
};
const initialState: EditModeState = {
editStatus: "not-started",
previousInputs: [],
applyState: INITIAL_EDIT_APPLY_STATE,
codeToEdit: [],
returnToMode: "chat",
lastNonEditSessionWasEmpty: false,
};
export const editModeStateSlice = createSlice({
name: "editModeState",
initialState,
reducers: {
focusEdit: (state) => {
state.editStatus = "not-started";
state.previousInputs = [];
state.fileAfterEdit = undefined;
setReturnToModeAfterEdit: (
state,
{ payload }: PayloadAction<MessageModes>,
) => {
state.returnToMode = payload;
},
submitEdit: (state, { payload }: PayloadAction<MessageContent>) => {
state.previousInputs.push(payload);
state.editStatus = "streaming";
updateEditStateApplyState: (
state,
{ payload }: PayloadAction<ApplyState>,
) => {
state.applyState = {
...state.applyState,
...payload,
};
},
setEditStatus: (
setCodeToEdit: (
state,
{
payload,
}: PayloadAction<{ status: EditStatus; fileAfterEdit?: string }>,
}: PayloadAction<{
codeToEdit: CodeToEdit | CodeToEdit[];
}>,
) => {
// Only allow valid transitions
const currentStatus = state.editStatus;
if (currentStatus === "not-started" && payload.status === "streaming") {
state.editStatus = payload.status;
} else if (
currentStatus === "streaming" &&
payload.status === "accepting"
) {
state.editStatus = payload.status;
state.fileAfterEdit = payload.fileAfterEdit;
} else if (currentStatus === "accepting" && payload.status === "done") {
state.editStatus = payload.status;
} else if (
currentStatus === "accepting:full-diff" &&
payload.status === "done"
) {
state.editStatus = payload.status;
} else if (
currentStatus === "accepting" &&
payload.status === "accepting:full-diff"
) {
state.editStatus = payload.status;
} else if (
currentStatus === "accepting:full-diff" &&
payload.status === "accepting"
) {
state.editStatus = payload.status;
} else if (currentStatus === "done" && payload.status === "not-started") {
state.editStatus = payload.status;
}
state.codeToEdit = Array.isArray(payload.codeToEdit)
? payload.codeToEdit
: [payload.codeToEdit];
},
addPreviousInput: (state, { payload }: PayloadAction<MessageContent>) => {
state.previousInputs.push(payload);
clearCodeToEdit: (state) => {
state.codeToEdit = [];
},
setEditDone: (state) => {
state.editStatus = "done";
state.previousInputs = [];
setLastNonEditSessionEmpty: (
state,
{ payload }: PayloadAction<boolean>,
) => {
state.lastNonEditSessionWasEmpty = payload;
},
},
selectors: {},
});
export const {
setEditStatus,
addPreviousInput,
setEditDone,
submitEdit,
focusEdit,
setReturnToModeAfterEdit,
clearCodeToEdit,
setCodeToEdit,
updateEditStateApplyState,
setLastNonEditSessionEmpty,
} = editModeStateSlice.actions;
export default editModeStateSlice.reducer;

View file

@ -10,7 +10,6 @@ import {
ApplyState,
ChatHistoryItem,
ChatMessage,
CodeToEdit,
ContextItem,
ContextItemWithId,
FileSymbolMap,
@ -44,8 +43,6 @@ type SessionState = {
title: string;
id: string;
streamAborter: AbortController;
codeToEdit: CodeToEdit[];
curCheckpointIndex: number;
mainEditorContentTrigger?: JSONContent | undefined;
symbols: FileSymbolMap;
mode: MessageModes;
@ -56,34 +53,13 @@ type SessionState = {
newestToolbarPreviewForInput: Record<string, string>;
};
function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) {
if (a.filepath !== b.filepath || a.contents !== b.contents) {
return false;
}
if ("range" in a && "range" in b) {
const rangeA = a.range;
const rangeB = b.range;
return (
rangeA.start.line === rangeB.start.line &&
rangeA.end.line === rangeB.end.line
);
}
// If neither has a range, they are considered equal in this context
return !("range" in a) && !("range" in b);
}
const initialState: SessionState = {
allSessionMetadata: [],
history: [],
isStreaming: false,
title: NEW_SESSION_TITLE,
id: uuidv4(),
curCheckpointIndex: 0,
streamAborter: new AbortController(),
codeToEdit: [],
symbols: {},
mode: "chat",
codeBlockApplyStates: {
@ -200,8 +176,6 @@ export const sessionSlice = createSlice({
},
contextItems: [],
});
state.curCheckpointIndex = Math.floor(index / 2);
} else {
// New input/response messages
state.history = state.history.concat([
@ -223,8 +197,6 @@ export const sessionSlice = createSlice({
contextItems: [],
},
]);
state.curCheckpointIndex = Math.floor((state.history.length - 1) / 2); // TODO this feels really fragile
}
state.isStreaming = true;
@ -454,12 +426,10 @@ export const sessionSlice = createSlice({
state.history = payload.history as any;
state.title = payload.title;
state.id = payload.sessionId;
state.curCheckpointIndex = 0;
} else {
state.history = [];
state.title = NEW_SESSION_TITLE;
state.id = uuidv4();
state.curCheckpointIndex = 0;
}
},
updateSessionTitle: (state, { payload }: PayloadAction<string>) => {
@ -551,19 +521,6 @@ export const sessionSlice = createSlice({
state.history[state.history.length - 1].contextItems = contextItems;
},
updateCurCheckpoint: (
state,
{ payload }: PayloadAction<{ filepath: string; content: string }>,
) => {
const checkpoint = state.history[state.curCheckpointIndex].checkpoint;
if (checkpoint) {
checkpoint[payload.filepath] = payload.content;
}
},
setCurCheckpointIndex: (state, { payload }: PayloadAction<number>) => {
state.curCheckpointIndex = payload;
},
updateApplyState: (state, { payload }: PayloadAction<ApplyState>) => {
const applyState = state.codeBlockApplyStates.states.find(
(state) => state.streamId === payload.streamId,
@ -584,31 +541,7 @@ export const sessionSlice = createSlice({
resetNextCodeBlockToApplyIndex: (state) => {
state.codeBlockApplyStates.curIndex = 0;
},
addCodeToEdit: (
state,
{ payload }: PayloadAction<CodeToEdit | CodeToEdit[]>,
) => {
const entries = Array.isArray(payload) ? payload : [payload];
const newEntries = entries.filter(
(entry) =>
!state.codeToEdit.some((existingEntry) =>
isCodeToEditEqual(existingEntry, entry),
),
);
if (newEntries.length > 0) {
state.codeToEdit.push(...newEntries);
}
},
removeCodeToEdit: (state, { payload }: PayloadAction<CodeToEdit>) => {
state.codeToEdit = state.codeToEdit.filter(
(entry) => !isCodeToEditEqual(entry, payload),
);
},
clearCodeToEdit: (state) => {
state.codeToEdit = [];
},
// TOOL CALL STATE
setToolGenerated: (
state,
@ -698,14 +631,6 @@ export const sessionSlice = createSlice({
setMode: (state, action: PayloadAction<MessageModes>) => {
state.mode = action.payload;
},
cycleMode: (state, action: PayloadAction<{ isJetBrains: boolean }>) => {
const modes = action.payload.isJetBrains
? ["chat", "agent"]
: ["chat", "edit", "agent"];
const currentIndex = modes.indexOf(state.mode);
const nextIndex = (currentIndex + 1) % modes.length;
state.mode = modes[nextIndex] as MessageModes;
},
setNewestToolbarPreviewForInput: (
state,
{
@ -724,26 +649,6 @@ export const sessionSlice = createSlice({
const curHistoryItem = state.history.at(-1);
return curHistoryItem?.isGatheringContext || false;
},
selectIsInEditMode: (state) => {
return state.mode === "edit";
},
selectCurrentMode: (state) => {
return state.mode;
},
selectIsSingleRangeEditOrInsertion: (state) => {
if (state.mode !== "edit") {
return false;
}
const isInsertion = state.codeToEdit.length === 0;
const selectIsSingleRangeEdit =
state.codeToEdit.length === 1 && "range" in state.codeToEdit[0];
return selectIsSingleRangeEdit || isInsertion;
},
selectHasCodeToEdit: (state) => {
return state.codeToEdit.length > 0;
},
},
extraReducers: (builder) => {
addPassthroughCases(builder, [streamResponseThunk]);
@ -806,14 +711,9 @@ export const {
setMainEditorContentTrigger,
deleteMessage,
setIsGatheringContext,
updateCurCheckpoint,
setCurCheckpointIndex,
resetNextCodeBlockToApplyIndex,
updateApplyState,
abortStream,
clearCodeToEdit,
addCodeToEdit,
removeCodeToEdit,
setToolCallCalling,
cancelToolCall,
errorToolCall,
@ -826,15 +726,8 @@ export const {
updateSessionMetadata,
deleteSessionMetadata,
setNewestToolbarPreviewForInput,
cycleMode,
} = sessionSlice.actions;
export const {
selectIsGatheringContext,
selectIsInEditMode,
selectCurrentMode,
selectIsSingleRangeEditOrInsertion,
selectHasCodeToEdit,
} = sessionSlice.selectors;
export const { selectIsGatheringContext } = sessionSlice.selectors;
export default sessionSlice.reducer;

View file

@ -47,15 +47,16 @@ const saveSubsetFilters = [
// Persist edit mode in case closes in middle
"mode",
"codeToEdit",
// higher risk to persist
// codeBlockApplyStates
// symbols
// curCheckpointIndex
]),
// Don't persist any of the edit state for now
createFilter("editModeState", []),
createFilter("editModeState", [
"returnToMode",
"lastNonEditSessionWasEmpty",
"codeToEdit",
]),
createFilter("config", ["defaultModelTitle"]),
createFilter("ui", ["toolSettings", "toolGroupSettings"]),
createFilter("indexing", []),

View file

@ -0,0 +1,126 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import { CodeToEdit, MessageModes, RangeInFileWithContents } from "core";
import { stripImages } from "core/util/messageContent";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
import {
clearCodeToEdit,
INITIAL_EDIT_APPLY_STATE,
setReturnToModeAfterEdit,
updateEditStateApplyState,
} from "../slices/editModeState";
import { newSession, setActive, setMode } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { loadLastSession, saveCurrentSession } from "./session";
import { streamThunkWrapper } from "./streamThunkWrapper";
export const streamEditThunk = createAsyncThunk<
void,
{
editorState: JSONContent;
codeToEdit: CodeToEdit[];
},
ThunkApiType
>(
"chat/streamResponse",
async ({ editorState, codeToEdit }, { dispatch, extra, getState }) => {
await dispatch(
streamThunkWrapper(async () => {
dispatch(setActive());
const [contextItems, __, userInstructions, _] =
await resolveEditorContent({
editorState,
modifiers: {
noContext: true,
useCodebase: false,
},
ideMessenger: extra.ideMessenger,
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
});
const prompt = [
...contextItems.map((item) => item.content),
stripImages(userInstructions),
].join("\n\n");
const response = await extra.ideMessenger.request("edit/sendPrompt", {
prompt,
range: codeToEdit[0] as RangeInFileWithContents,
});
if (response.status === "error") {
throw new Error(response.error);
}
}),
);
},
);
export const exitEditMode = createAsyncThunk<
void,
{ goToMode?: MessageModes; openNewSession?: boolean },
ThunkApiType
>(
"edit/exitMode",
async ({ goToMode, openNewSession }, { dispatch, extra, getState }) => {
const state = getState();
const codeToEdit = state.editModeState.codeToEdit;
if (state.session.mode !== "edit") {
return;
}
if (codeToEdit[0] && state.editModeState.applyState.numDiffs) {
extra.ideMessenger.post("rejectDiff", {
filepath: codeToEdit[0].filepath,
});
}
extra.ideMessenger.post("edit/clearDecorations", undefined);
dispatch(clearCodeToEdit());
dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) {
dispatch(newSession());
} else {
await dispatch(
loadLastSession({
saveCurrentSession: false,
}),
);
}
dispatch(setMode(goToMode ?? state.editModeState.returnToMode));
},
);
export const enterEditMode = createAsyncThunk<
void,
{ returnToMode?: MessageModes },
ThunkApiType
>("edit/enterMode", async ({ returnToMode }, { dispatch, extra, getState }) => {
const state = getState();
if (state.session.mode === "edit") {
return;
}
dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode));
await dispatch(
saveCurrentSession({
openNewSession: true,
// Because this causes a lag before Edit mode is focused. TODO just have that happen in background
generateTitle: false,
}),
);
dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
dispatch(setMode("edit"));
if (!state.editModeState.codeToEdit[0]) {
extra.ideMessenger.post("edit/addCurrentSelection", undefined);
}
});

View file

@ -1,41 +0,0 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import {
clearCodeToEdit,
selectIsInEditMode,
selectIsSingleRangeEditOrInsertion,
setMainEditorContentTrigger,
setMode,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { setEditDone } from "../slices/editModeState";
export const exitEditMode = createAsyncThunk<void, undefined, ThunkApiType>(
"edit/complete",
async (_, { dispatch, extra, getState }) => {
const state = getState();
const isInEditMode = selectIsInEditMode(state);
const codeToEdit = state.session.codeToEdit;
const isSingleRangeEditOrInsertion =
selectIsSingleRangeEditOrInsertion(state);
if (!isInEditMode) {
return;
}
dispatch(setMode("chat"));
for (const code of codeToEdit) {
extra.ideMessenger.post("rejectDiff", {
filepath: code.filepath,
});
}
dispatch(clearCodeToEdit());
dispatch(setEditDone());
dispatch(setMainEditorContentTrigger(undefined));
extra.ideMessenger.post("edit/exit", {
shouldFocusEditor: isSingleRangeEditOrInsertion,
});
},
);

View file

@ -1,4 +1,3 @@
export { exitEditMode } from "./exitEditMode";
export { gatherContext } from "./gatherContext";
export { resetStateForNewMessage } from "./resetStateForNewMessage";
export { streamNormalInput } from "./streamNormalInput";

View file

@ -1,62 +0,0 @@
import { CodeToEdit, IDE } from "core";
import { findUriInDirs } from "core/util/uri";
export default function getMultifileEditPrompt(
codeToEdit: CodeToEdit[],
dirs?: string[],
): string {
const codeToEditStr = codeToEdit
.map((code) => {
const { relativePathOrBasename } = findUriInDirs(
code.filepath,
dirs ?? window.workspacePaths ?? [],
);
return `
\`\`\` ${relativePathOrBasename}
${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,17 +1,16 @@
import type { RenderOptions, RenderResult } from "@testing-library/react";
import { render } from "@testing-library/react";
import { act, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { PropsWithChildren } from "react";
import { Provider } from "react-redux";
import { MemoryRouter, RouterProps } from "react-router-dom";
import { LumpProvider } from "../../components/mainInput/Lump/LumpContext";
import { MainEditorProvider } from "../../components/mainInput/TipTapEditor";
import { AuthProvider } from "../../context/Auth";
import { IdeMessengerProvider } from "../../context/IdeMessenger";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
import ParallelListeners from "../../hooks/ParallelListeners";
import { setupStore } from "../../redux/store";
import { SetupListeners } from "../../App";
import { act } from "@testing-library/react";
import { LumpProvider } from "../../components/mainInput/Lump/LumpContext";
import { MainEditorProvider } from "../../components/mainInput/TipTapEditor";
// As a basic setup, import your same slice reducers
// This type interface extends the default options for render from RTL, as well
@ -55,7 +54,7 @@ export async function renderWithProviders(
<MainEditorProvider>
<LumpProvider>
{children}
<SetupListeners />
<ParallelListeners />
</LumpProvider>
</MainEditorProvider>
</AuthProvider>