Merge pull request #5801 from continuedev/pe/remove-edit-mode

feat: remove edit as a mode
This commit is contained in:
Patrick Erichsen 2025-05-25 19:55:15 -07:00 • committed by GitHub
commit bc4bb89877
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
42 changed files with 741 additions and 800 deletions

2
core/index.d.ts vendored
View file

@ -423,7 +423,7 @@ export interface PromptLog {
completion: string;
}
export type MessageModes = "chat" | "edit" | "agent";
export type MessageModes = "chat" | "agent";
export type ToolStatus =
| "generating"

View file

@ -3,7 +3,7 @@ import { ApplyState } from "core";
import { useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { getMetaKeyLabel } from "../util";
import { useFontSize } from "./ui/font";
import { ToolTip } from "./gui/Tooltip";
export interface AcceptRejectAllButtonsProps {
applyStates: ApplyState[];
@ -21,8 +21,6 @@ export default function AcceptRejectAllButtons({
);
const ideMessenger = useContext(IdeMessengerContext);
const tinyFont = useFontSize(-3);
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
for (const { filepath = "", streamId } of pendingApplyStates) {
ideMessenger.post(status, {
@ -36,54 +34,43 @@ export default function AcceptRejectAllButtons({
}
}
if (!pendingApplyStates.length) {
return null;
}
const rejectShortcut = `${getMetaKeyLabel()}⇧⌫`;
const acceptShortcut = `${getMetaKeyLabel()}⇧⏎`;
return (
<div
className="flex flex-row items-center justify-evenly gap-2 p-1 px-3"
className="flex flex-row items-center justify-evenly gap-3 px-3"
data-testid="accept-reject-all-buttons"
>
<button
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"
className="text-foreground flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent p-0 text-xs opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("rejectDiff")}
data-testid="edit-reject-button"
data-tooltip-id="reject-shortcut"
data-tooltip-content={`Reject All (${rejectShortcut})`}
>
<div className="flex flex-row items-center gap-1">
<XMarkIcon className="h-4 w-4 text-red-600" />
<XMarkIcon className="text-error h-4 w-4" />
<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>
<ToolTip id="reject-shortcut" />
<button
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"
className="text-foreground flex cursor-pointer flex-row flex-wrap justify-center gap-1 border-none bg-transparent p-0 text-xs opacity-80 hover:opacity-100 hover:brightness-125"
onClick={() => handleAcceptOrReject("acceptDiff")}
data-testid="edit-accept-button"
data-tooltip-id="accept-shortcut"
data-tooltip-content={`Accept All (${acceptShortcut})`}
>
<div className="flex flex-row items-center gap-1">
<CheckIcon className="h-4 w-4 text-green-600" />
<CheckIcon className="text-success h-4 w-4" />
<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>
<ToolTip id="accept-shortcut" />
</div>
);
}

View file

@ -6,7 +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 { exitEdit } from "../../redux/thunks/edit";
import {
deleteSession,
getSession,
@ -69,7 +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({}));
await dispatch(exitEdit({}));
if (sessionMetadata.sessionId !== currentSessionId) {
await dispatch(
loadSession({

View file

@ -7,9 +7,9 @@ import { IdeMessengerContext } from "../context/IdeMessenger";
import { LocalStorageProvider } from "../context/LocalStorage";
import { useWebviewListener } from "../hooks/useWebviewListener";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { setCodeToEdit } from "../redux/slices/editModeState";
import { setCodeToEdit } from "../redux/slices/editState";
import { setShowDialog } from "../redux/slices/uiSlice";
import { enterEditMode, exitEditMode } from "../redux/thunks/editMode";
import { enterEdit, exitEdit } from "../redux/thunks/edit";
import { saveCurrentSession } from "../redux/thunks/session";
import { fontSize, isMetaEquivalentKeyPressed } from "../util";
import { incrementFreeTrialCount } from "../util/freeTrial";
@ -48,14 +48,14 @@ const Layout = () => {
const dialogMessage = useAppSelector((state) => state.ui.dialogMessage);
const showDialog = useAppSelector((state) => state.ui.showDialog);
const mode = useAppSelector((state) => state.session.mode);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
useWebviewListener(
"newSession",
async () => {
navigate(ROUTES.HOME);
if (mode === "edit") {
await dispatch(exitEditMode({}));
if (isInEdit) {
await dispatch(exitEdit({}));
} else {
await dispatch(
saveCurrentSession({
@ -65,7 +65,7 @@ const Layout = () => {
);
}
},
[mode],
[isInEdit],
);
useWebviewListener(
@ -81,9 +81,9 @@ const Layout = () => {
"focusContinueInputWithNewSession",
async () => {
navigate(ROUTES.HOME);
if (mode === "edit") {
if (isInEdit) {
await dispatch(
exitEditMode({
exitEdit({
openNewSession: true,
}),
);
@ -96,7 +96,7 @@ const Layout = () => {
);
}
},
[location.pathname, mode],
[location.pathname, isInEdit],
location.pathname === ROUTES.HOME,
);
@ -148,7 +148,7 @@ const Layout = () => {
"focusEdit",
async () => {
await ideMessenger.request("edit/addCurrentSelection", undefined);
await dispatch(enterEditMode({}));
await dispatch(enterEdit({ editorContent: mainEditor?.getJSON() }));
mainEditor?.commands.focus();
},
[ideMessenger, mainEditor],
@ -169,7 +169,7 @@ const Layout = () => {
useWebviewListener(
"exitEditMode",
async () => {
await dispatch(exitEditMode({}));
await dispatch(exitEdit({}));
},
[],
);
@ -181,7 +181,7 @@ const Layout = () => {
if (selection) {
// Copy to clipboard
setTimeout(() => {
navigator.clipboard.writeText(selection);
void navigator.clipboard.writeText(selection);
}, 100);
}
}

View file

@ -0,0 +1,19 @@
import { ChatBubbleLeftIcon, SparklesIcon } from "@heroicons/react/24/outline";
import { MessageModes } from "core";
interface ModeIconProps {
mode: MessageModes;
className?: string;
}
export function ModeIcon({
mode,
className = "xs:h-3 xs:w-3 h-3 w-3",
}: ModeIconProps) {
switch (mode) {
case "agent":
return <SparklesIcon className={className} />;
case "chat":
return <ChatBubbleLeftIcon className={className} />;
}
}

View file

@ -1,21 +1,11 @@
// A dropdown menu for selecting between Chat, Edit, and Agent modes with keyboard shortcuts
import {
ChatBubbleLeftIcon,
CheckIcon,
ChevronDownIcon,
PencilIcon,
SparklesIcon,
} from "@heroicons/react/24/outline";
import { CheckIcon, ChevronDownIcon } from "@heroicons/react/24/outline";
import { MessageModes } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { useCallback, useEffect, useMemo } from "react";
import styled from "styled-components";
import { lightGray } from "..";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setMode } from "../../redux/slices/sessionSlice";
import { enterEditMode, exitEditMode } from "../../redux/thunks/editMode";
import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util";
import { getFontSize, getMetaKeyLabel } from "../../util";
import { useMainEditor } from "../mainInput/TipTapEditor";
import {
Listbox,
@ -23,14 +13,9 @@ import {
ListboxOption,
ListboxOptions,
} from "../ui/Listbox";
import { ModeIcon } from "./ModeIcon";
const ShortcutText = styled.span`
color: ${lightGray};
font-size: ${getFontSize() - 3}px;
margin-right: auto;
`;
function ModeSelect() {
export function ModeSelect() {
const dispatch = useAppDispatch();
const mode = useAppSelector((store) => store.session.mode);
const selectedModel = useAppSelector(selectSelectedChatModel);
@ -38,24 +23,10 @@ function ModeSelect() {
return selectedModel && modelSupportsTools(selectedModel);
}, [selectedModel]);
const { mainEditor } = useMainEditor();
const jetbrains = useMemo(() => {
return isJetBrains();
}, []);
const metaKeyLabel = useMemo(() => {
return getMetaKeyLabel();
}, []);
const getModeIcon = (mode: MessageModes) => {
switch (mode) {
case "agent":
return <SparklesIcon className="xs:h-3 xs:w-3 h-3 w-3" />;
case "chat":
return <ChatBubbleLeftIcon className="xs:h-3 xs:w-3 h-3 w-3" />;
case "edit":
return <PencilIcon className="xs:h-3 xs:w-3 h-3 w-3" />;
}
};
// Switch to chat mode if agent mode is selected but not supported
useEffect(() => {
if (!selectedModel) {
@ -66,55 +37,18 @@ 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));
}
}
const cycleMode = useCallback(() => {
dispatch(setMode(mode === "chat" ? "agent" : "chat"));
mainEditor?.commands.focus();
}, [jetbrains, mode, mainEditor]);
}, [mode, mainEditor]);
const selectMode = useCallback(
async (newMode: MessageModes) => {
(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));
}
}
dispatch(setMode(newMode));
mainEditor?.commands.focus();
},
@ -138,13 +72,9 @@ function ModeSelect() {
<div className="relative">
<ListboxButton
data-testid="mode-select-button"
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",
}}
className="xs:px-2 text-description-muted bg-table-oddRow gap-1 rounded-full border-none px-1.5 py-0.5 transition-colors duration-200 hover:brightness-110"
>
{getModeIcon(mode)}
<ModeIcon mode={mode} />
<span className="hidden sm:block">
{mode.charAt(0).toUpperCase() + mode.slice(1)}
</span>
@ -154,21 +84,15 @@ function ModeSelect() {
/>
</ListboxButton>
<ListboxOptions className="min-w-32 max-w-48">
{!jetbrains && (
<ListboxOption value="edit">
<div className="flex flex-row items-center gap-1.5">
<PencilIcon className="h-3 w-3" />
<span className="">Edit</span>
<ShortcutText>{getMetaKeyLabel()}I</ShortcutText>
</div>
{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" />
<ModeIcon mode="chat" />
<span className="">Chat</span>
<ShortcutText>{getMetaKeyLabel()}L</ShortcutText>
<span
className={`text-description-muted text-[${getFontSize() - 3}px] mr-auto`}
>
{getMetaKeyLabel()}L
</span>
</div>
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
@ -179,7 +103,7 @@ function ModeSelect() {
className={"gap-1"}
>
<div className="flex flex-row items-center gap-1.5">
<SparklesIcon className="h-3 w-3" />
<ModeIcon mode="agent" />
<span className="">Agent</span>
</div>
{agentModeSupported ? (
@ -189,7 +113,7 @@ function ModeSelect() {
)}
</ListboxOption>
<div className="text-lightgray px-2 py-1">
<div className="text-description-muted px-2 py-1">
{`${metaKeyLabel} . for next mode`}
</div>
</ListboxOptions>
@ -197,5 +121,3 @@ function ModeSelect() {
</Listbox>
);
}
export default ModeSelect;

View file

@ -0,0 +1 @@
export * from "./ModeSelect";

View file

@ -1,181 +0,0 @@
import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { SetCodeToEditPayload } 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: SetCodeToEditPayload;
}
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

@ -83,15 +83,15 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const availableContextProviders = useAppSelector(
(state) => state.config.config.contextProviders,
);
const mode = useAppSelector((store) => store.session.mode);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const editModeState = useAppSelector((state) => state.editModeState);
const filteredSlashCommands = useMemo(() => {
return mode === "edit" ? [] : availableSlashCommands;
}, [mode, availableSlashCommands]);
return isInEdit ? [] : availableSlashCommands;
}, [isInEdit, availableSlashCommands]);
const filteredContextProviders = useMemo(() => {
if (mode === "edit") {
if (isInEdit) {
return (
availableContextProviders?.filter(
(provider) =>
@ -101,22 +101,21 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}
return availableContextProviders ?? [];
}, [availableContextProviders, mode]);
}, [availableContextProviders, isInEdit]);
const historyKey = mode === "edit" ? "edit" : "chat";
const placeholder = mode === "edit" ? "Describe changes" : undefined;
const historyKey = isInEdit ? "edit" : "chat";
const placeholder = isInEdit ? "Edit selected code" : undefined;
const toolbarOptions: ToolbarOptions =
mode === "edit"
? {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText:
editModeState.applyState.status === "done" ? "Retry" : "Edit",
}
: {};
const toolbarOptions: ToolbarOptions = isInEdit
? {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
enterText:
editModeState.applyState.status === "done" ? "Retry" : "Edit",
}
: {};
const { appliedRules = [], contextItems = [] } = props;

View file

@ -1,59 +0,0 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/editMode";
import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons";
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>
<AcceptRejectDiffButtons
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

@ -10,7 +10,7 @@ import {
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { exitEditMode } from "../../redux/thunks/editMode";
import { exitEdit } from "../../redux/thunks/edit";
import {
getAltKeyLabel,
getMetaKeyLabel,
@ -18,7 +18,7 @@ import {
} from "../../util";
import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import ModeSelect from "../modelSelection/ModeSelect";
import { ModeSelect } from "../ModeSelect";
import { useFontSize } from "../ui/font";
import { EnterButton } from "./InputToolbar/EnterButton";
import HoverItem from "./InputToolbar/HoverItem";
@ -49,7 +49,7 @@ function InputToolbar(props: InputToolbarProps) {
const fileInputRef = useRef<HTMLInputElement | null>(null);
const defaultModel = useAppSelector(selectSelectedChatModel);
const useActiveFile = useAppSelector(selectUseActiveFile);
const mode = useAppSelector((store) => store.session.mode);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
const toolCallState = useAppSelector(selectCurrentToolCall);
const currentToolCallApplyState = useAppSelector(
@ -58,7 +58,7 @@ function InputToolbar(props: InputToolbarProps) {
const isEnterDisabled =
props.disabled ||
(mode === "edit" && codeToEdit.length === 0) ||
(isInEdit && codeToEdit.length === 0) ||
toolCallState?.status === "generated" ||
(currentToolCallApplyState &&
currentToolCallApplyState.status !== "closed");
@ -87,19 +87,21 @@ function InputToolbar(props: InputToolbarProps) {
}}
>
<div className="xs:gap-1.5 flex flex-row items-center gap-1">
<HoverItem data-tooltip-id="mode-select-tooltip" className="!p-0">
<ModeSelect />
<ToolTip id="mode-select-tooltip" place="top">
Select Mode
</ToolTip>
</HoverItem>
{!isInEdit && (
<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" className="!p-0">
<ModelSelect />
<ToolTip id="model-select-tooltip" place="top">
Select Model
</ToolTip>
</HoverItem>
<div className="xs:flex -mb-1 hidden items-center text-gray-400 transition-colors duration-200">
<div className="xs:flex text-description -mb-1 hidden items-center transition-colors duration-200">
{props.toolbarOptions?.hideImageUpload ||
(supportsImages && (
<>
@ -149,12 +151,12 @@ function InputToolbar(props: InputToolbarProps) {
</div>
<div
className="flex items-center gap-2 whitespace-nowrap text-gray-400"
className="text-description flex items-center gap-2 whitespace-nowrap"
style={{
fontSize: tinyFont,
}}
>
{!props.toolbarOptions?.hideUseCodebase && mode !== "edit" && (
{!props.toolbarOptions?.hideUseCodebase && !isInEdit && (
<div
className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`}
>
@ -184,16 +186,16 @@ function InputToolbar(props: InputToolbarProps) {
</div>
)}
{mode === "edit" && (
{isInEdit && (
<HoverItem
className="hidden hover:underline sm:flex"
onClick={async () => {
dispatch(exitEditMode({}));
void dispatch(exitEdit({}));
ideMessenger.post("focusEditor", undefined);
}}
>
<span>
<i>Esc</i> to exit
<i>Esc</i> to exit Edit
</span>
</HoverItem>
)}

View file

@ -1,174 +0,0 @@
import { useContext, useEffect, useMemo } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import { AnimatedEllipsis } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall";
import { callCurrentTool } from "../../../redux/thunks/callCurrentTool";
import { cancelCurrentToolCall } from "../../../redux/thunks/cancelCurrentToolCall";
import { cancelStream } from "../../../redux/thunks/cancelStream";
import {
getAltKeyLabel,
getFontSize,
getMetaKeyLabel,
isJetBrains,
} from "../../../util";
import { EnterButton } from "../InputToolbar/EnterButton";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
const Container = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
`;
const StopButton = styled.div`
font-size: ${getFontSize() - 3}px;
padding: 2px;
padding-right: 4px;
cursor: pointer;
`;
function GeneratingIndicator() {
return (
<div className="text-xs text-gray-400">
<span>Generating</span>
<AnimatedEllipsis />
</div>
);
}
function ApplyingIndicator() {
return (
<div className="text-xs text-gray-400">
<span>Applying</span>
<AnimatedEllipsis />
</div>
);
}
export function LumpToolbar() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const jetbrains = isJetBrains();
const applyStates = useAppSelector(
(store) => store.session.codeBlockApplyStates.states,
);
const isApplying = useMemo(() => {
return applyStates.find((state) => state.status === "streaming");
}, [applyStates]);
const toolCallState = useSelector(selectCurrentToolCall);
const handleKeyDown = (event: KeyboardEvent) => {
if (toolCallState?.status === "generated") {
const metaKey = event.metaKey || event.ctrlKey;
const altKey = event.altKey;
if (metaKey && event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
dispatch(callCurrentTool());
} else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") {
event.preventDefault();
event.stopPropagation();
dispatch(cancelCurrentToolCall());
}
}
};
useEffect(() => {
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [toolCallState]);
if (ttsActive) {
return (
<Container>
<GeneratingIndicator />
<StopButton
className="text-gray-400"
onClick={() => {
ideMessenger.post("tts/kill", undefined);
}}
>
■ Stop TTS
</StopButton>
</Container>
);
}
if (isApplying) {
return (
<Container>
<ApplyingIndicator />
<StopButton
className="text-gray-400"
onClick={() => {
// Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
// Apply is prioritized because it can be more catastrophic
// Intentional to be more WYSIWYG for now
ideMessenger.post("cancelApply", undefined);
}}
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
</Container>
);
}
if (isStreaming) {
return (
<Container>
<GeneratingIndicator />
<StopButton
className="text-gray-400"
onClick={() => {
dispatch(cancelStream());
}}
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
</Container>
);
}
if (toolCallState?.status === "generated") {
return (
<Container>
<div className="flex flex-row items-center pb-0.5 pr-1 text-xs text-gray-400">
<span className="hidden sm:flex">Pending tool call</span>
</div>
<div className="flex gap-2 pb-0.5">
<StopButton
className="text-gray-400"
onClick={() => dispatch(cancelCurrentToolCall())}
data-testid="reject-tool-call-button"
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
<EnterButton
isPrimary={true}
className="text-gray-400"
onClick={() => dispatch(callCurrentTool())}
data-testid="accept-tool-call-button"
>
{getMetaKeyLabel()} ⏎ Continue
</EnterButton>
</div>
</Container>
);
}
return <BlockSettingsTopToolbar />;
}

View file

@ -10,16 +10,16 @@ import {
WrenchScrewdriverIcon,
} from "@heroicons/react/24/outline";
import { ReactNode } from "react";
import { vscBadgeForeground } from "../..";
import { useAppSelector } from "../../../redux/hooks";
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";
import { McpSectionTooltip } from "./sections/mcp/MCPTooltip";
import { ToolsSectionTooltip } from "./sections/tool-policies/ToolPoliciesSectionTooltip";
import { vscBadgeForeground } from "../../..";
import { useAppSelector } from "../../../../redux/hooks";
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";
import { McpSectionTooltip } from "../sections/mcp/MCPTooltip";
import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSectionTooltip";
interface BlockSettingsToolbarIcon {
title: string;
@ -96,14 +96,14 @@ function BlockSettingsToolbarIcon(
className={`${
props.isSelected
? isErrorSection
? "bg-red-600"
? "bg-error"
: "bg-badge"
: undefined
} 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 ${
isErrorSection ? "text-red-600" : ""
isErrorSection ? "text-error" : ""
}`}
style={{
color: props.isSelected ? vscBadgeForeground : undefined,
@ -158,7 +158,7 @@ export function BlockSettingsTopToolbar() {
return (
<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">
<div className="xs:flex text-description hidden items-center justify-center">
<BlockSettingsToolbarIcon
className="-ml-1.5"
icon={isToolbarExpanded ? ChevronLeftIcon : EllipsisHorizontalIcon}

View file

@ -0,0 +1,34 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { exitEdit } from "../../../../redux/thunks/edit";
import AcceptRejectDiffButtons from "../../../AcceptRejectDiffButtons";
import { useMainEditor } from "../../TipTapEditor";
export function EditOutcomeToolbar() {
const dispatch = useAppDispatch();
const editApplyState = useAppSelector(
(store) => store.editModeState.applyState,
);
const { mainEditor } = useMainEditor();
const ideMessenger = useContext(IdeMessengerContext);
return (
<div className="text-description-muted flex items-center justify-between py-0.5 text-xs">
<div className="bg-badge rounded px-1.5">
<span>{`${editApplyState.numDiffs} diff${editApplyState.numDiffs !== 1 ? "s" : ""}`}</span>
</div>
<AcceptRejectDiffButtons
applyStates={[editApplyState]}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {
await dispatch(exitEdit({}));
ideMessenger.post("focusEditor", undefined);
} else {
mainEditor?.commands.focus();
}
}}
/>
</div>
);
}

View file

@ -0,0 +1,38 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { exitEdit } from "../../../../redux/thunks";
import { getEditFilenameAndRangeText } from "../../util";
export function EditToolbar() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const mode = useAppSelector((state) => state.session.mode);
const codeToEdit = useAppSelector(
(state) => state.editModeState.codeToEdit[0],
);
const handleBackClick = async () => {
void dispatch(exitEdit({}));
ideMessenger.post("focusEditor", undefined);
};
return (
<div className="text-description-muted flex items-center justify-between gap-3 text-xs">
<span
className="flex cursor-pointer items-center whitespace-nowrap hover:brightness-125"
onClick={handleBackClick}
>
<ArrowLeftIcon className="mr-1 h-2.5 w-2.5" />
Back to {mode.charAt(0).toUpperCase() + mode.slice(1)}
</span>
<span className="truncate">
Editing{" "}
<span className="italic">
{getEditFilenameAndRangeText(codeToEdit)}
</span>
</span>
</div>
);
}

View file

@ -0,0 +1,14 @@
import { AnimatedEllipsis } from "../../..";
export function GeneratingIndicator({
text = "Generating",
}: {
text?: string;
}) {
return (
<div className="text-description-muted text-xs">
<span>{text}</span>
<AnimatedEllipsis />
</div>
);
}

View file

@ -0,0 +1,29 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { getAltKeyLabel, getMetaKeyLabel } from "../../../../util";
import { Container, StopButton } from "./components";
import { GeneratingIndicator } from "./GeneratingIndicator";
export const IsApplyingToolbar = () => {
const ideMessenger = useContext(IdeMessengerContext);
const jetbrains = window.location.protocol === "jb-api:";
return (
<Container>
<GeneratingIndicator text="Applying" />
<StopButton
className="text-description"
onClick={() => {
// Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
// Apply is prioritized because it can be more catastrophic
// Intentional to be more WYSIWYG for now
ideMessenger.post("cancelApply", undefined);
}}
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
</Container>
);
};

View file

@ -0,0 +1,96 @@
import { useEffect } from "react";
import { useSelector } from "react-redux";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
import {
callCurrentTool,
cancelCurrentToolCall,
} from "../../../../redux/thunks";
import { isJetBrains } from "../../../../util";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
import { EditOutcomeToolbar } from "./EditOutcomeToolbar";
import { EditToolbar } from "./EditToolbar";
import { IsApplyingToolbar } from "./IsApplyingToolbar";
import { PendingApplyStatesToolbar } from "./PendingApplyStatesToolbar";
import { PendingToolCallToolbar } from "./PendingToolCallToolbar";
import { StreamingToolbar } from "./StreamingToolbar";
import { TtsActiveToolbar } from "./TtsActiveToolbar";
export function LumpToolbar() {
const dispatch = useAppDispatch();
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const isInEdit = useAppSelector((state) => state.session.isInEdit);
const jetbrains = isJetBrains();
const toolCallState = useSelector(selectCurrentToolCall);
const editApplyState = useAppSelector(
(state) => state.editModeState.applyState,
);
const applyStates = useAppSelector(
(state) => state.session.codeBlockApplyStates.states,
);
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const isApplying = applyStates.some((state) => state.status === "streaming");
useEffect(() => {
if (toolCallState?.status !== "generated") {
return;
}
const handleKeyDown = (event: KeyboardEvent) => {
const metaKey = event.metaKey || event.ctrlKey;
const altKey = event.altKey;
if (metaKey && event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
void dispatch(callCurrentTool());
} else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") {
event.preventDefault();
event.stopPropagation();
void dispatch(cancelCurrentToolCall());
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [toolCallState]);
if (isApplying) {
return <IsApplyingToolbar />;
}
if (isInEdit) {
if (editApplyState.status === "done") {
return <EditOutcomeToolbar />;
}
return <EditToolbar />;
}
if (ttsActive) {
return <TtsActiveToolbar />;
}
if (isStreaming) {
return <StreamingToolbar />;
}
if (toolCallState?.status === "generated") {
return <PendingToolCallToolbar />;
}
if (pendingApplyStates.length > 0) {
return (
<PendingApplyStatesToolbar pendingApplyStates={pendingApplyStates} />
);
}
return <BlockSettingsTopToolbar />;
}

View file

@ -0,0 +1,44 @@
import { ApplyState } from "core";
import { getUriPathBasename } from "core/util/uri";
import AcceptRejectDiffButtons from "../../../AcceptRejectDiffButtons";
import FileIcon from "../../../FileIcon";
interface PendingApplyStatesToolbarProps {
pendingApplyStates: ApplyState[];
}
export function PendingApplyStatesToolbar({
pendingApplyStates,
}: PendingApplyStatesToolbarProps) {
// Group apply states by filepath
const applyStatesByFilepath = pendingApplyStates.reduce(
(acc, state) => {
const filepath = state.filepath || ""; // Use empty string as fallback
if (!acc[filepath]) {
acc[filepath] = [];
}
acc[filepath].push(state);
return acc;
},
{} as Record<string, ApplyState[]>,
);
return (
<div className="flex flex-col gap-2">
{Object.entries(applyStatesByFilepath).map(([filepath, states]) => (
<div key={filepath} className="flex justify-between gap-3">
{filepath && (
<span className="bg-badge flex items-center gap-1 rounded px-0.5">
<FileIcon filename={filepath} height="18px" width="18px" />
{getUriPathBasename(filepath)}
</span>
)}
<AcceptRejectDiffButtons
applyStates={states}
onAcceptOrReject={async () => {}}
/>
</div>
))}
</div>
);
}

View file

@ -0,0 +1,59 @@
import styled from "styled-components";
import { useAppDispatch } from "../../../../redux/hooks";
import {
callCurrentTool,
cancelCurrentToolCall,
} from "../../../../redux/thunks";
import {
getAltKeyLabel,
getFontSize,
getMetaKeyLabel,
isJetBrains,
} from "../../../../util";
import { EnterButton } from "../../InputToolbar/EnterButton";
const Container = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
`;
const StopButton = styled.div`
font-size: ${getFontSize() - 3}px;
padding: 2px;
padding-right: 4px;
cursor: pointer;
`;
export function PendingToolCallToolbar() {
const dispatch = useAppDispatch();
const jetbrains = isJetBrains();
return (
<Container>
<div className="text-description flex flex-row items-center pb-0.5 pr-1 text-xs">
<span className="hidden sm:flex">Pending tool call</span>
</div>
<div className="flex gap-2 pb-0.5">
<StopButton
className="text-description"
onClick={() => dispatch(cancelCurrentToolCall())}
data-testid="reject-tool-call-button"
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
<EnterButton
isPrimary={true}
className="text-description"
onClick={() => dispatch(callCurrentTool())}
data-testid="accept-tool-call-button"
>
{getMetaKeyLabel()} ⏎ Continue
</EnterButton>
</div>
</Container>
);
}

View file

@ -0,0 +1,24 @@
import { useAppDispatch } from "../../../../redux/hooks";
import { cancelStream } from "../../../../redux/thunks";
import { getAltKeyLabel, getMetaKeyLabel, isJetBrains } from "../../../../util";
import { Container, StopButton } from "./components";
import { GeneratingIndicator } from "./GeneratingIndicator";
export function StreamingToolbar() {
const dispatch = useAppDispatch();
const jetbrains = isJetBrains();
return (
<Container>
<GeneratingIndicator />
<StopButton
className="text-description"
onClick={() => {
void dispatch(cancelStream());
}}
>
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
</Container>
);
}

View file

@ -0,0 +1,37 @@
import { useContext } from "react";
import styled from "styled-components";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { getFontSize } from "../../../../util";
import { GeneratingIndicator } from "./GeneratingIndicator";
const Container = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
`;
const StopButton = styled.div`
font-size: ${getFontSize() - 3}px;
padding: 2px;
padding-right: 4px;
cursor: pointer;
`;
export function TtsActiveToolbar() {
const ideMessenger = useContext(IdeMessengerContext);
return (
<Container>
<GeneratingIndicator />
<StopButton
className="text-description"
onClick={() => {
ideMessenger.post("tts/kill", undefined);
}}
>
■ Stop TTS
</StopButton>
</Container>
);
}

View file

@ -0,0 +1,18 @@
// TODO: Convert these to tailwind
import styled from "styled-components";
import { getFontSize } from "../../../../util";
export const Container = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
`;
export const StopButton = styled.div`
font-size: ${getFontSize() - 3}px;
padding: 2px;
padding-right: 4px;
cursor: pointer;
`;

View file

@ -0,0 +1 @@
export * from "./LumpToolbar";

View file

@ -37,7 +37,7 @@ export function Lump() {
return (
<LumpDiv>
<div className="xs:px-2 mt-0.5 px-1">
<div className="xs:px-2 px-1 py-0.5">
<LumpToolbar />
<ContentDiv

View file

@ -27,9 +27,15 @@ interface MainEditorContextType {
onEnterRef: React.MutableRefObject<(modifiers: InputModifiers) => void>;
}
const MainEditorContext = createContext<MainEditorContextType | undefined>(
undefined,
);
const initialState: MainEditorContextType = {
mainEditor: null,
setMainEditor: () => {},
inputId: null,
setInputId: () => {},
onEnterRef: { current: () => {} },
};
const MainEditorContext = createContext<MainEditorContextType>(initialState);
/**
* Provider component that maintains a reference to the main editor
@ -38,8 +44,10 @@ export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const dispatch = useAppDispatch();
const [mainEditor, setMainEditorInternal] = useState<Editor | null>(null);
const [inputId, setInputId] = useState<string | null>(null);
const [mainEditor, setMainEditorInternal] = useState<Editor | null>(
initialState.mainEditor,
);
const [inputId, setInputId] = useState<string | null>(initialState.inputId);
const onEnterRef = useRef<(modifiers: InputModifiers) => void>(() => {});
const editorFocusedRef = useRef<boolean>(false);
const historyLength = useAppSelector((store) => store.session.history.length);
@ -108,10 +116,5 @@ export const MainEditorProvider: React.FC<{ children: React.ReactNode }> = ({
/**
* Hook to access the main editor context
*/
export const useMainEditor = (): MainEditorContextType => {
const context = useContext(MainEditorContext);
if (context === undefined) {
throw new Error("useMainEditor must be used within a MainEditorProvider");
}
return context;
};
export const useMainEditor = (): MainEditorContextType =>
useContext(MainEditorContext);

View file

@ -42,14 +42,13 @@ export function TipTapEditor(props: TipTapEditorProps) {
const mainEditorContext = useMainEditor();
const ideMessenger = useContext(IdeMessengerContext);
const isOSREnabled = useIsOSREnabled();
const defaultModel = useAppSelector(selectSelectedChatModel);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const historyLength = useAppSelector((store) => store.session.history.length);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const mode = useAppSelector((store) => store.session.mode);
const { editor, onEnterRef } = createEditorConfig({
props,
ideMessenger,
@ -87,10 +86,10 @@ export function TipTapEditor(props: TipTapEditorProps) {
}, [editor, props.isMainInput]);
useEffect(() => {
if (mode === "edit") {
if (isInEdit) {
setShouldHideToolbar(false);
}
}, [mode]);
}, [isInEdit]);
const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
@ -150,7 +149,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
const handleBlur = useCallback(
(e: React.FocusEvent) => {
if (mode === "edit") {
if (isInEdit) {
return;
}
// Check if the new focus target is within our InputBoxDiv
@ -165,7 +164,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
setShouldHideToolbar(true);
}, 100);
},
[mode, blurTimeout],
[isInEdit, blurTimeout],
);
const handleFocus = useCallback(() => {
@ -213,7 +212,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
}
setShowDragOverMsg(false);
let file = event.dataTransfer.files[0];
handleImageFile(ideMessenger, file).then((result) => {
void handleImageFile(ideMessenger, file).then((result) => {
if (!editor) {
return;
}
@ -245,7 +244,7 @@ export function TipTapEditor(props: TipTapEditorProps) {
onAddContextItem={() => insertCharacterWithWhitespace("@")}
onEnter={onEnterRef.current}
onImageFileSelected={(file) => {
handleImageFile(ideMessenger, file).then((result) => {
void handleImageFile(ideMessenger, file).then((result) => {
if (!editor) {
return;
}

View file

@ -3,7 +3,7 @@ import { InputModifiers } from "core";
import { rifWithContentsToContextItem } from "core/commands/util";
import { MutableRefObject } from "react";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { clearCodeToEdit } from "../../../redux/slices/editModeState";
import { clearCodeToEdit } from "../../../redux/slices/editState";
import { setNewestToolbarPreviewForInput } from "../../../redux/slices/sessionSlice";
import { AppDispatch } from "../../../redux/store";
import { loadSession, saveCurrentSession } from "../../../redux/thunks/session";

View file

@ -23,7 +23,7 @@ import { useAppSelector } from "../../../../redux/hooks";
import { selectUseActiveFile } from "../../../../redux/selectors";
import { selectSelectedChatModel } from "../../../../redux/slices/configSlice";
import { AppDispatch } from "../../../../redux/store";
import { exitEditMode } from "../../../../redux/thunks/editMode";
import { exitEdit } from "../../../../redux/thunks/edit";
import { getFontSize, isJetBrains } from "../../../../util";
import * as ContinueExtensions from "../extensions";
import { TipTapEditorProps } from "../TipTapEditor";
@ -81,9 +81,9 @@ export function createEditorConfig(options: {
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const useActiveFile = useAppSelector(selectUseActiveFile);
const historyLength = useAppSelector((store) => store.session.history.length);
const mode = useAppSelector((store) => store.session.mode);
const modeRef = useUpdatingRef(mode);
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const isInEditRef = useUpdatingRef(isInEdit);
const inSubmenuRef = useRef<string | undefined>(undefined);
const inDropdownRef = useRef(false);
@ -157,7 +157,7 @@ export function createEditorConfig(options: {
for (const item of items) {
const file = item.getAsFile();
file &&
modelSupportsImages(
void modelSupportsImages(
model.provider,
model.model,
model.title,
@ -269,9 +269,9 @@ export function createEditorConfig(options: {
return true;
}
if (modeRef.current === "edit") {
dispatch(
exitEditMode({
if (isInEditRef.current) {
void dispatch(
exitEdit({
openNewSession: false,
}),
);
@ -345,7 +345,7 @@ export function createEditorConfig(options: {
if (!editor) {
return;
}
if (isStreaming || (codeToEdit.length === 0 && mode === "edit")) {
if (isStreaming || (codeToEdit.length === 0 && isInEdit)) {
return;
}
@ -362,7 +362,7 @@ export function createEditorConfig(options: {
props.onEnter(json, modifiers, editor);
},
[props.onEnter, editor, props.isMainInput, codeToEdit, mode],
[props.onEnter, editor, props.isMainInput, codeToEdit, isInEdit],
);
return { editor, onEnterRef };

View file

@ -0,0 +1,20 @@
import { SetCodeToEditPayload } from "core";
import { getUriPathBasename } from "core/util/uri";
export * from "./handleMetaKeyIssues";
export function getEditFilenameAndRangeText(code: SetCodeToEditPayload) {
const fileName = getUriPathBasename(code.filepath);
let title = `${fileName}`;
if ("range" in code) {
const start = code.range.start.line + 1;
const end = code.range.end.line + 1;
const isInsertion = start === end;
title += isInsertion
? ` - Inserting at line ${start}`
: ` (${start} - ${end})`;
}
return title;
}

View file

@ -1,6 +0,0 @@
import { InputModifiers } from "core";
export const defaultInputModifiers: InputModifiers = {
useCodebase: false,
noContext: true,
};

View file

@ -1,18 +0,0 @@
import { JSONContent } from "@tiptap/core";
export function getParagraphNodeFromString(str: string): JSONContent {
return {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: str,
},
],
},
],
};
}

View file

@ -6,8 +6,7 @@ import {
PlusIcon,
} from "@heroicons/react/24/outline";
import { useContext, useEffect, useRef, useState } from "react";
import styled from "styled-components";
import { defaultBorderRadius, lightGray } from "..";
import { lightGray } from "..";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import AddModelForm from "../../forms/AddModelForm";
@ -30,21 +29,6 @@ interface Option {
apiKey?: string;
}
const IconBase = styled.div<{ $hovered: boolean }>`
width: 1.2em;
height: 1.2em;
cursor: pointer;
padding: 4px;
border-radius: ${defaultBorderRadius};
opacity: ${(props) => (props.$hovered ? 0.75 : 0)};
visibility: ${(props) => (props.$hovered ? "visible" : "hidden")};
&:hover {
opacity: 1;
background-color: ${lightGray}33;
}
`;
function modelSelectTitle(model: any): string {
if (model?.title) return model?.title;
if (model?.model !== undefined && model?.model.trim() !== "") {
@ -120,12 +104,12 @@ function ModelOption({
function ModelSelect() {
const dispatch = useAppDispatch();
const mode = useAppSelector((store) => store.session.mode);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const config = useAppSelector((state) => state.config.config);
let selectedModel = null;
let allModels = null;
if (mode === "edit") {
if (isInEdit) {
allModels = config.modelsByRole.edit;
selectedModel = config.selectedModelByRole.edit;
}
@ -226,7 +210,7 @@ function ModelSelect() {
void dispatch(
updateSelectedModelByRole({
selectedProfile,
role: mode === "edit" ? "edit" : "chat",
role: isInEdit ? "edit" : "chat",
modelTitle: val,
}),
);
@ -236,7 +220,7 @@ function ModelSelect() {
<ListboxButton
data-testid="model-select-button"
ref={buttonRef}
className="h-[18px] gap-1 border-none text-gray-400"
className="text-description h-[18px] gap-1 border-none"
>
<span className="line-clamp-1 break-all hover:brightness-110">
{modelSelectTitle(selectedModel) || "Select model"}

View file

@ -126,7 +126,7 @@ const AssistantSelectOption = ({
)}
{isLocalProfile(profile) ? (
<Cog6ToothIcon
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
@ -135,7 +135,7 @@ const AssistantSelectOption = ({
/>
) : (
<ArrowTopRightOnSquareIcon
className="text-lightgray h-3 w-3 flex-shrink-0 cursor-pointer"
className="text-description h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
@ -242,12 +242,12 @@ export default function AssistantSelect() {
return (
<div
onClick={() => {
ideMessenger.request("controlPlane/openUrl", {
void ideMessenger.request("controlPlane/openUrl", {
path: "/new?type=assistant",
orgSlug: currentOrg?.slug,
});
}}
className="flex cursor-pointer select-none items-center gap-1 text-gray-400"
className="text-description flex cursor-pointer select-none items-center gap-1"
style={{ fontSize: smallFont }}
>
<PlusIcon className="h-3 w-3 flex-shrink-0 select-none" />
@ -266,7 +266,7 @@ export default function AssistantSelect() {
<ListboxButton
data-testid="assistant-select-button"
ref={buttonRef}
className="border-none bg-transparent text-gray-400 hover:brightness-125"
className="text-description border-none bg-transparent hover:brightness-125"
style={{ fontSize: fontSize(-3) }}
>
<div className="flex flex-row items-center gap-1.5">
@ -301,7 +301,7 @@ export default function AssistantSelect() {
>
<ArrowPathIcon
className={cn(
"text-lightgray h-2.5 w-2.5",
"text-description h-2.5 w-2.5",
loading && "animate-spin-slow",
)}
/>
@ -339,7 +339,7 @@ export default function AssistantSelect() {
onClick={session ? onNewAssistant : () => login(false)}
>
<div
className="text-lightgray flex flex-row items-center gap-2"
className="text-description flex flex-row items-center gap-2"
style={{
fontSize: tinyFont,
}}
@ -358,7 +358,7 @@ export default function AssistantSelect() {
/>
<div
className="text-lightgray flex items-center justify-between px-2 py-1"
className="text-description flex items-center justify-between px-2 py-1"
style={{
fontSize: tinyFont,
}}

View file

@ -3,6 +3,7 @@ import { IdeMessengerContext } from "../context/IdeMessenger";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { FromCoreProtocol } from "core/protocol";
import { useMainEditor } from "../components/mainInput/TipTapEditor";
import {
initializeProfilePreferences,
setOrganizations,
@ -15,7 +16,7 @@ import { setConfigResult } from "../redux/slices/configSlice";
import {
setLastNonEditSessionEmpty,
updateEditStateApplyState,
} from "../redux/slices/editModeState";
} from "../redux/slices/editState";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import {
acceptToolCall,
@ -23,7 +24,7 @@ import {
updateApplyState,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
import { streamResponseAfterToolCall } from "../redux/thunks";
import { exitEdit, streamResponseAfterToolCall } from "../redux/thunks";
import { cancelStream } from "../redux/thunks/cancelStream";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
@ -40,12 +41,18 @@ function ParallelListeners() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const history = useAppSelector((store) => store.session.history);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const selectedProfileId = useAppSelector(
(store) => store.profiles.selectedProfileId,
);
const hasDoneInitialConfigLoad = useRef(false);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const { mainEditor } = useMainEditor();
const handleConfigUpdate = useCallback(
async (isInitial: boolean, result: FromCoreProtocol["configUpdate"][0]) => {
@ -99,18 +106,18 @@ function ParallelListeners() {
// Load config from the IDE
useEffect(() => {
initialLoadAuthAndConfig(true);
void initialLoadAuthAndConfig(true);
const interval = setInterval(() => {
if (hasDoneInitialConfigLoad.current) {
// Init to run on initial config load
ideMessenger.post("docs/initStatuses", undefined);
dispatch(updateFileSymbolsFromHistory());
dispatch(refreshSessionMetadata({}));
void dispatch(updateFileSymbolsFromHistory());
void dispatch(refreshSessionMetadata({}));
// This triggers sending pending status to the GUI for relevant docs indexes
clearInterval(interval);
} else {
initialLoadAuthAndConfig(true);
void initialLoadAuthAndConfig(true);
}
}, 2_000);
@ -132,39 +139,43 @@ function ParallelListeners() {
const sessionId = useAppSelector((state) => state.session.id);
useEffect(() => {
if (sessionId) {
dispatch(updateFileSymbolsFromHistory());
void dispatch(updateFileSymbolsFromHistory());
}
}, [sessionId]);
// ON LOAD
useEffect(() => {
// Override persisted state
dispatch(cancelStream());
void dispatch(cancelStream());
const jetbrains = isJetBrains();
setDocumentStylesFromLocalStorage(jetbrains);
if (jetbrains) {
// Save theme colors to local storage for immediate loading in JetBrains
ideMessenger.request("jetbrains/getColors", undefined).then((result) => {
if (result.status === "success") {
setDocumentStylesFromTheme(result.content);
}
});
void ideMessenger
.request("jetbrains/getColors", undefined)
.then((result) => {
if (result.status === "success") {
setDocumentStylesFromTheme(result.content);
}
});
// Tell JetBrains the webview is ready
ideMessenger.request("jetbrains/onLoad", undefined).then((result) => {
if (result.status === "error") {
return;
}
void ideMessenger
.request("jetbrains/onLoad", undefined)
.then((result) => {
if (result.status === "error") {
return;
}
const msg = result.content;
(window as any).windowId = msg.windowId;
(window as any).serverUrl = msg.serverUrl;
(window as any).workspacePaths = msg.workspacePaths;
(window as any).vscMachineId = msg.vscMachineId;
(window as any).vscMediaUrl = msg.vscMediaUrl;
});
const msg = result.content;
(window as any).windowId = msg.windowId;
(window as any).serverUrl = msg.serverUrl;
(window as any).workspacePaths = msg.workspacePaths;
(window as any).vscMachineId = msg.vscMachineId;
(window as any).vscMediaUrl = msg.vscMediaUrl;
});
}
}, []);
@ -194,7 +205,7 @@ function ParallelListeners() {
);
useWebviewListener("setInactive", async () => {
dispatch(cancelStream());
void dispatch(cancelStream());
});
useWebviewListener("setTTSActive", async (status) => {
@ -203,7 +214,7 @@ function ParallelListeners() {
// TODO - remove?
useWebviewListener("submitMessage", async (data) => {
dispatch(
void dispatch(
streamResponseThunk({
editorState: data.message,
modifiers: { useCodebase: false, noContext: true },
@ -224,14 +235,15 @@ function ParallelListeners() {
dispatch(updateIndexingStatus(data));
});
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
useWebviewListener(
"updateApplyState",
async (state) => {
if (state.streamId === EDIT_MODE_STREAM_ID) {
dispatch(updateEditStateApplyState(state));
if (state.status === "closed") {
dispatch(exitEdit({}));
}
} else {
// chat or agent
dispatch(updateApplyState(state));
@ -253,7 +265,7 @@ function ParallelListeners() {
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
void dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
@ -264,12 +276,12 @@ function ParallelListeners() {
[currentToolCallApplyState, history],
);
const mode = useAppSelector((store) => store.session.mode);
useEffect(() => {
if (mode !== "edit") {
if (!isInEdit) {
dispatch(setLastNonEditSessionEmpty(history.length === 0));
}
}, [mode, history]);
}, [isInEdit, history]);
return <></>;
}

View file

@ -35,8 +35,8 @@ describe("Chat page test", () => {
);
});
// Check that it switched to Edit mode
expect(await screen.findByText("Edit")).toBeInTheDocument();
// Check that it switched back to Chat mode
expect(await screen.findByText("Chat")).toBeInTheDocument();
});
it.skip("should send a message and receive a response", async () => {

View file

@ -46,7 +46,7 @@ import {
} from "../../redux/slices/uiSlice";
import { streamResponseThunk } from "../../redux/thunks";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { streamEditThunk } from "../../redux/thunks/editMode";
import { streamEditThunk } from "../../redux/thunks/edit";
import { loadLastSession } from "../../redux/thunks/session";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import {
@ -54,9 +54,6 @@ import {
incrementFreeTrialCount,
} from "../../util/freeTrial";
import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
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";
@ -121,9 +118,7 @@ export function Chat() {
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 isInEdit = useAppSelector((store) => store.session.isInEdit);
const lastSessionId = useAppSelector((state) => state.session.lastSessionId);
const hasDismissedExploreDialog = useAppSelector(
@ -185,15 +180,14 @@ export function Chat() {
);
}
const model =
mode === "edit"
? (selectedModels?.edit ?? selectedModels?.chat)
: selectedModels?.chat;
const model = isInEdit
? (selectedModels?.edit ?? selectedModels?.chat)
: selectedModels?.chat;
if (!model) {
return;
}
if (mode === "edit" && codeToEdit.length === 0) {
if (isInEdit && codeToEdit.length === 0) {
return;
}
@ -224,15 +218,15 @@ export function Chat() {
}
}
if (mode === "edit") {
dispatch(
if (isInEdit) {
void dispatch(
streamEditThunk({
editorState,
codeToEdit,
}),
);
} else {
dispatch(streamResponseThunk({ editorState, modifiers, index }));
void dispatch(streamResponseThunk({ editorState, modifiers, index }));
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
@ -252,7 +246,15 @@ export function Chat() {
setLocalStorage("mainTextEntryCounter", 1);
}
},
[history, selectedModels, streamResponse, mode, codeToEdit, toolCallState],
[
history,
selectedModels,
streamResponse,
mode,
isInEdit,
codeToEdit,
toolCallState,
],
);
useWebviewListener(
@ -292,7 +294,7 @@ export function Chat() {
return (
<>
{!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />}
{!!showSessionTabs && !isInEdit && <TabBar ref={tabsRef} />}
{widget}
<StepsDiv
@ -381,24 +383,14 @@ export function Chat() {
))}
</StepsDiv>
<div className={"relative"}>
<>
{!isStreaming && mode !== "edit" && (
<AcceptRejectDiffButtons
applyStates={applyStates}
onAcceptOrReject={async () => {}}
/>
)}
{mode === "edit" && <CodeToEditCard />}
<ContinueInputBox
isMainInput
isLastUserInput={false}
onEnter={(editorState, modifiers, editor) =>
sendInput(editorState, modifiers, undefined, editor)
}
inputId={MAIN_EDITOR_INPUT_ID}
/>
<EditModeDetails />
</>
<ContinueInputBox
isMainInput
isLastUserInput={false}
onEnter={(editorState, modifiers, editor) =>
sendInput(editorState, modifiers, undefined, editor)
}
inputId={MAIN_EDITOR_INPUT_ID}
/>
<div
style={{
@ -407,7 +399,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 && mode !== "edit" && (
{history.length === 0 && lastSessionId && !isInEdit && (
<div className="xs:inline hidden">
<NewSessionButton
onClick={async () => {

View file

@ -1,14 +1,16 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ApplyState, SetCodeToEditPayload, MessageModes } from "core";
import { JSONContent } from "@tiptap/core";
import { ApplyState, MessageModes, SetCodeToEditPayload } from "core";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
export interface EditModeState {
export interface EditState {
// Array because of previous multi-file edit functionality
// Keeping array to not break persisted redux for now
codeToEdit: SetCodeToEditPayload[];
applyState: ApplyState;
returnToMode: MessageModes;
lastNonEditSessionWasEmpty: boolean;
previousModeEditorContent: JSONContent | undefined;
}
export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
@ -16,15 +18,16 @@ export const INITIAL_EDIT_APPLY_STATE: ApplyState = {
status: "not-started",
};
const initialState: EditModeState = {
const initialState: EditState = {
applyState: INITIAL_EDIT_APPLY_STATE,
codeToEdit: [],
returnToMode: "chat",
lastNonEditSessionWasEmpty: false,
previousModeEditorContent: undefined,
};
export const editModeStateSlice = createSlice({
name: "editModeState",
export const editStateSlice = createSlice({
name: "editState",
initialState,
reducers: {
setReturnToModeAfterEdit: (
@ -63,6 +66,12 @@ export const editModeStateSlice = createSlice({
) => {
state.lastNonEditSessionWasEmpty = payload;
},
setPreviousModeEditorContent: (
state,
{ payload }: PayloadAction<JSONContent | undefined>,
) => {
state.previousModeEditorContent = payload;
},
},
selectors: {},
});
@ -73,5 +82,6 @@ export const {
setCodeToEdit,
updateEditStateApplyState,
setLastNonEditSessionEmpty,
} = editModeStateSlice.actions;
export default editModeStateSlice.reducer;
setPreviousModeEditorContent,
} = editStateSlice.actions;
export default editStateSlice.reducer;

View file

@ -47,6 +47,7 @@ type SessionState = {
mainEditorContentTrigger?: JSONContent | undefined;
symbols: FileSymbolMap;
mode: MessageModes;
isInEdit: boolean;
codeBlockApplyStates: {
states: ApplyState[];
curIndex: number;
@ -63,6 +64,7 @@ const initialState: SessionState = {
streamAborter: new AbortController(),
symbols: {},
mode: "chat",
isInEdit: false,
codeBlockApplyStates: {
states: [],
curIndex: 0,
@ -645,6 +647,9 @@ export const sessionSlice = createSlice({
setMode: (state, action: PayloadAction<MessageModes>) => {
state.mode = action.payload;
},
setIsInEdit: (state, action: PayloadAction<boolean>) => {
state.isInEdit = action.payload;
},
setNewestToolbarPreviewForInput: (
state,
{
@ -741,6 +746,7 @@ export const {
updateSessionMetadata,
deleteSessionMetadata,
setNewestToolbarPreviewForInput,
setIsInEdit,
} = sessionSlice.actions;
export const { selectIsGatheringContext } = sessionSlice.selectors;

View file

@ -17,7 +17,7 @@ import storage from "redux-persist/lib/storage";
import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger";
import { profilesReducer } from "./slices";
import configReducer from "./slices/configSlice";
import editModeStateReducer from "./slices/editModeState";
import editModeStateReducer from "./slices/editState";
import indexingReducer from "./slices/indexingSlice";
import sessionReducer from "./slices/sessionSlice";
import tabsReducer from "./slices/tabsSlice";

View file

@ -1,19 +1,26 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import {
SetCodeToEditPayload,
MessageModes,
RangeInFileWithContents,
SetCodeToEditPayload,
} from "core";
import { stripImages } from "core/util/messageContent";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
import {
clearCodeToEdit,
INITIAL_EDIT_APPLY_STATE,
setPreviousModeEditorContent,
setReturnToModeAfterEdit,
updateEditStateApplyState,
} from "../slices/editModeState";
import { newSession, setActive, setMode } from "../slices/sessionSlice";
} from "../slices/editState";
import {
newSession,
setActive,
setIsInEdit,
setMainEditorContentTrigger,
setMode,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { loadLastSession, saveCurrentSession } from "./session";
import { streamThunkWrapper } from "./streamThunkWrapper";
@ -27,7 +34,7 @@ export const streamEditThunk = createAsyncThunk<
ThunkApiType
>(
"chat/streamResponse",
async ({ editorState, codeToEdit }, { dispatch, extra, getState }) => {
async ({ editorState, codeToEdit }, { dispatch, extra }) => {
await dispatch(
streamThunkWrapper(async () => {
dispatch(setActive());
@ -62,17 +69,20 @@ export const streamEditThunk = createAsyncThunk<
},
);
export const exitEditMode = createAsyncThunk<
export const exitEdit = createAsyncThunk<
void,
{ goToMode?: MessageModes; openNewSession?: boolean },
ThunkApiType
>(
"edit/exitMode",
"edit/exit",
async ({ goToMode, openNewSession }, { dispatch, extra, getState }) => {
const state = getState();
const codeToEdit = state.editModeState.codeToEdit;
const isInEdit = state.session.isInEdit;
const previousModeEditorContent =
state.editModeState.previousModeEditorContent;
if (state.session.mode !== "edit") {
if (!isInEdit) {
return;
}
@ -86,6 +96,13 @@ export const exitEditMode = createAsyncThunk<
dispatch(clearCodeToEdit());
dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
dispatch(setIsInEdit(false));
// Restore the previous editor content if available
if (previousModeEditorContent) {
dispatch(setMainEditorContentTrigger(previousModeEditorContent));
dispatch(setPreviousModeEditorContent(undefined));
}
if (openNewSession || state.editModeState.lastNonEditSessionWasEmpty) {
dispatch(newSession());
@ -101,30 +118,38 @@ export const exitEditMode = createAsyncThunk<
},
);
export const enterEditMode = createAsyncThunk<
export const enterEdit = createAsyncThunk<
void,
{ returnToMode?: MessageModes },
{ returnToMode?: MessageModes; editorContent?: JSONContent },
ThunkApiType
>("edit/enterMode", async ({ returnToMode }, { dispatch, extra, getState }) => {
const state = getState();
>(
"edit/enter",
async ({ returnToMode, editorContent }, { dispatch, extra, getState }) => {
const state = getState();
const isInEdit = state.session.isInEdit;
if (state.session.mode === "edit") {
return;
}
if (isInEdit) {
return;
}
dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode));
dispatch(setMainEditorContentTrigger({}));
dispatch(setPreviousModeEditorContent(editorContent));
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"));
dispatch(setReturnToModeAfterEdit(returnToMode ?? state.session.mode));
dispatch(updateEditStateApplyState(INITIAL_EDIT_APPLY_STATE));
if (!state.editModeState.codeToEdit[0]) {
extra.ideMessenger.post("edit/addCurrentSelection", undefined);
}
});
await dispatch(
saveCurrentSession({
openNewSession: true,
// Because this causes a lag before Edit is focused. TODO just have that happen in background
generateTitle: false,
}),
);
dispatch(setIsInEdit(true));
if (!state.editModeState.codeToEdit[0]) {
extra.ideMessenger.post("edit/addCurrentSelection", undefined);
}
},
);

View file

@ -1,7 +1,11 @@
export { gatherContext } from "./gatherContext";
export { resetStateForNewMessage } from "./resetStateForNewMessage";
export { streamNormalInput } from "./streamNormalInput";
export { streamResponseThunk } from "./streamResponse";
export { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export { streamThunkWrapper } from "./streamThunkWrapper";
export { updateSelectedModelByRole } from "./updateSelectedModelByRole";
export * from "./callCurrentTool";
export * from "./cancelCurrentToolCall";
export * from "./cancelStream";
export * from "./edit";
export * from "./gatherContext";
export * from "./resetStateForNewMessage";
export * from "./streamNormalInput";
export * from "./streamResponse";
export * from "./streamResponseAfterToolCall";
export * from "./streamThunkWrapper";
export * from "./updateSelectedModelByRole";