Merge pull request #2861 from continuedev/pe/mfe-chat-styling

feat: add accept/reject logic to MFE
This commit is contained in:
Patrick Erichsen 2024-11-11 13:07:57 -08:00 • committed by GitHub
commit 7b321de346
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
53 changed files with 1110 additions and 752 deletions

View file

@ -23,7 +23,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
text: string;
streamId: string;
curSelectedModelTitle: string;
filepath: string;
filepath?: string;
},
void,
];
@ -60,7 +60,9 @@ export type EditStatus = "not-started" | "streaming" | "accepting" | "done";
export interface ApplyState {
streamId: string;
status: "streaming" | "done" | "closed";
status?: "streaming" | "done" | "closed";
numDiffs?: number;
filepath?: string;
}
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {

View file

@ -1,13 +1,13 @@
import {
ToCoreFromWebviewProtocol,
ToWebviewFromCoreProtocol,
} from "./coreWebview.js";
import { ToWebviewOrCoreFromIdeProtocol } from "./ide.js";
import { ToCoreFromIdeProtocol, ToIdeFromCoreProtocol } from "./ideCore.js";
} from "./coreWebview";
import { ToWebviewOrCoreFromIdeProtocol } from "./ide";
import { ToCoreFromIdeProtocol, ToIdeFromCoreProtocol } from "./ideCore";
import {
ToIdeFromWebviewProtocol,
ToWebviewFromIdeProtocol,
} from "./ideWebview.js";
} from "./ideWebview";
export type IProtocol = Record<string, [any, any]>;

View file

@ -124,7 +124,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"lru-cache": "^11.0.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -182,23 +182,6 @@ export class ContinueGUIWebviewViewProvider
</head>
<body>
<div id="root"></div>
${`<script>
function log(level, ...args) {
const text = args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
).join(' ');
vscode.postMessage({ messageType: 'log', level, text, messageId: "log" });
}
window.console.log = (...args) => log('log', ...args);
window.console.info = (...args) => log('info', ...args);
window.console.warn = (...args) => log('warn', ...args);
window.console.error = (...args) => log('error', ...args);
window.console.debug = (...args) => log('debug', ...args);
console.debug('Logging initialized');
</script>`}
${
inDevelopmentMode
? `<script type="module">

View file

@ -283,6 +283,7 @@ const commandsMap: (
verticalDiffManager.clearForFilepath(fullPath, true);
await diffManager.acceptDiff(fullPath);
await sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});

View file

@ -13,21 +13,25 @@ import type { VerticalDiffCodeLens } from "./manager";
export interface VerticalDiffHandlerOptions {
input?: string;
instant?: boolean;
onStatusUpdate: (status: ApplyState["status"]) => void;
onStatusUpdate: (
status?: ApplyState["status"],
numDiffs?: ApplyState["numDiffs"],
) => void;
}
export class VerticalDiffHandler implements vscode.Disposable {
private currentLineIndex: number;
private cancelled = false;
private newLinesAdded = 0;
private get diffBlocks() {
return this.editorToVerticalDiffCodeLens.get(this.filepath) || [];
}
public get range(): vscode.Range {
const startLine = Math.min(this.startLine, this.endLine);
const endLine = Math.max(this.startLine, this.endLine);
return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
}
private newLinesAdded = 0;
constructor(
private startLine: number,
private endLine: number,
@ -92,15 +96,13 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || [];
blocks.push({
this.diffBlocks.push({
start: this.currentLineIndex - this.insertedInCurrentBlock,
numRed: this.deletionBuffer.length,
numGreen: this.insertedInCurrentBlock,
});
this.editorToVerticalDiffCodeLens.set(this.filepath, blocks);
this.editorToVerticalDiffCodeLens.set(this.filepath, this.diffBlocks);
}
if (this.deletionBuffer.length === 0) {
@ -267,7 +269,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
},
);
this.options.onStatusUpdate("closed");
this.options.onStatusUpdate("closed", this.diffBlocks.length);
this.cancelled = true;
this.refreshCodeLens();
@ -336,7 +338,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
let diffLines = []
let diffLines = [];
try {
// As an indicator of loading
this.updateIndexLineDecorations();
@ -345,7 +347,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
if (this.isCancelled) {
return;
}
diffLines.push(diffLine)
diffLines.push(diffLine);
await this.queueDiffLine(diffLine);
}
@ -355,7 +357,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.refreshCodeLens();
this.options.onStatusUpdate("done");
this.options.onStatusUpdate("done", this.diffBlocks.length);
// Reject on user typing
// const listener = vscode.workspace.onDidChangeTextDocument((e) => {
@ -368,7 +370,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.clearForFilepath(this.filepath, false);
throw e;
}
return diffLines
return diffLines;
}
async acceptRejectBlock(
@ -404,6 +406,9 @@ export class VerticalDiffHandler implements vscode.Disposable {
// Shift the codelens objects
this.shiftCodeLensObjects(startLine, offset);
const status = this.diffBlocks.length === 0 ? "closed" : undefined;
this.options.onStatusUpdate(status, this.diffBlocks.length);
}
private shiftCodeLensObjects(startLine: number, offset: number) {
@ -443,7 +448,6 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
public hasDiffForCurrentFile(): boolean {
const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.filepath);
return diffBlocks !== undefined && diffBlocks.length > 0;
return this.diffBlocks.length > 0;
}
}

View file

@ -213,10 +213,11 @@ export class VerticalDiffManager {
endLine,
{
instant,
onStatusUpdate: (status) =>
onStatusUpdate: (status, numDiffs) =>
this.webviewProtocol.request("updateApplyState", {
streamId,
status,
numDiffs,
}),
},
);
@ -331,11 +332,12 @@ export class VerticalDiffManager {
endLine,
{
input,
onStatusUpdate: (status) =>
onStatusUpdate: (status, numDiffs) =>
streamId &&
this.webviewProtocol.request("updateApplyState", {
streamId,
status,
numDiffs,
}),
},
);

View file

@ -159,29 +159,35 @@ export class VsCodeMessenger {
});
this.onWebview("applyToFile", async ({ data }) => {
const fullPath = getFullyQualifiedPath(ide, data.filepath);
let filepath = data.filepath;
if (!fullPath) {
return;
}
// If there is a filepath, verify it exists and then open the file
if (filepath) {
const fullPath = getFullyQualifiedPath(ide, filepath);
const fileExists = await this.ide.fileExists(fullPath);
if (!fullPath) {
return;
}
const fileExists = await this.ide.fileExists(fullPath);
// If it's a new file, no need to apply, just write directly
if (!fileExists) {
await this.ide.writeFile(fullPath, data.text);
await this.ide.openFile(fullPath);
await webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "done",
numDiffs: 0,
});
return;
}
// If it's a new file, no need to apply, just write directly
if (!fileExists) {
await this.ide.writeFile(fullPath, data.text);
await this.ide.openFile(fullPath);
await webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "done",
});
return;
}
await this.ide.openFile(fullPath);
// Get active text editor
const editor = vscode.window.activeTextEditor;
@ -198,6 +204,7 @@ export class VsCodeMessenger {
await webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "done",
numDiffs: 0,
});
return;
}

2
gui/package-lock.json generated
View file

@ -126,7 +126,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
"lru-cache": "^10.2.2",
"lru-cache": "^11.0.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",

View file

@ -11,7 +11,7 @@ import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import { RootState } from "../redux/store";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial";
import { ROUTES } from "../util/navigation";
import ButtonWithTooltip from "./ButtonWithTooltip";
import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip";
import FreeTrialProgressBar from "./loaders/FreeTrialProgressBar";
import ProfileSwitcher from "./ProfileSwitcher";
@ -60,30 +60,30 @@ function Footer() {
<div className="flex gap-1">
{configError && (
<ButtonWithTooltip
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="Config error"
onClick={onClickError}
>
<ExclamationTriangleIcon className="h-4 w-4" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
)}
<ButtonWithTooltip
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="More"
onClick={onClickMore}
>
<EllipsisHorizontalCircleIcon className="h-4 w-4" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
<ButtonWithTooltip
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
onClick={onClickSettings}
text="Configure Continue"
>
<Cog6ToothIcon className="h-4 w-4" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
</div>
</footer>
);

View file

@ -5,7 +5,7 @@ import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Input } from "..";
import useHistory from "../../hooks/useHistory";
import ButtonWithTooltip from "../ButtonWithTooltip";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
function lastPartOfPath(path: string): string {
const sep = path.includes("/") ? "/" : "\\";
@ -101,7 +101,7 @@ export function HistoryTableRow({
{hovered && !editing && (
<div className="bg-vsc-background absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-2 rounded-full py-1.5 pl-4 pr-4 shadow-md">
<ButtonWithTooltip
<HeaderButtonWithToolTip
text="Edit"
onClick={async (e) => {
e.stopPropagation();
@ -109,8 +109,8 @@ export function HistoryTableRow({
}}
>
<PencilSquareIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
<ButtonWithTooltip
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Delete"
onClick={async () => {
await deleteSession(session.sessionId);
@ -118,7 +118,7 @@ export function HistoryTableRow({
}}
>
<TrashIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
</div>
)}
</div>

View file

@ -1,20 +1,20 @@
import ContinueLogo from "../../ContinueLogo";
import ContinueLogo from "../../gui/ContinueLogo";
import QuickStartSubmitButton from "../components/QuickStartSubmitButton";
function OnboardingQuickstartTab() {
return (
<div className="flex justify-center items-center w-full h-full">
<div className="flex flex-col items-center justify-center w-full max-w-full px-4 xs:px-0 text-center">
<div className="hidden xs:flex">
<div className="flex h-full w-full items-center justify-center">
<div className="xs:px-0 flex w-full max-w-full flex-col items-center justify-center px-4 text-center">
<div className="xs:flex hidden">
<ContinueLogo height={75} />
</div>
<p className="text-sm w-full xs:w-3/4">
<p className="xs:w-3/4 w-full text-sm">
Quickly get up and running using our API keys. After this trial, we'll
help you set up your own models.
</p>
<p className="text-sm w-full xs:w-3/4">
<p className="xs:w-3/4 w-full text-sm">
To prevent abuse, we'll ask you to sign in to GitHub.
</p>

View file

@ -24,7 +24,7 @@ import { useWebviewListener } from "../hooks/useWebviewListener";
import { setLastControlServerBetaEnabledStatus } from "../redux/slices/miscSlice";
import { RootState } from "../redux/store";
import { getFontSize } from "../util";
import ButtonWithTooltip from "./ButtonWithTooltip";
import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip";
const StyledListbox = styled(Listbox)`
background-color: ${vscBackground};
@ -247,7 +247,7 @@ function ProfileSwitcher() {
{controlServerBetaEnabled &&
(session?.account ? (
<ButtonWithTooltip
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text={
session.account.label === ""
@ -257,15 +257,15 @@ function ProfileSwitcher() {
onClick={logout}
>
<UserCircleIconSolid className="h-4 w-4" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
) : (
<ButtonWithTooltip
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text="Click to login to Continue"
onClick={login}
>
<UserCircleIconOutline className="h-4 w-4" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
))}
</>
);

View file

@ -1,4 +1,4 @@
import { vscForeground } from ".";
import { vscForeground } from "..";
interface ContinueLogoProps {
height?: number;

View file

@ -2,48 +2,38 @@ import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline";
import { useContext, useState } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { isJetBrains } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip";
import useCopy from "../../hooks/useCopy";
interface CopyButtonProps {
interface CopyIconButtonProps {
text: string | (() => string);
tabIndex?: number;
checkIconClassName?: string;
clipboardIconClassName?: string;
}
export function CopyButton({
export function CopyIconButton({
text,
tabIndex,
checkIconClassName = "h-4 w-4 text-green-400",
clipboardIconClassName = "h-4 w-4 text-gray-400",
}: CopyButtonProps) {
const [copied, setCopied] = useState<boolean>(false);
const ideMessenger = useContext(IdeMessengerContext);
}: CopyIconButtonProps) {
const { copyText, copied } = useCopy(text);
return (
<>
<ButtonWithTooltip
<HeaderButtonWithToolTip
tooltipPlacement="top"
tabIndex={tabIndex}
text={copied ? "Copied!" : "Copy"}
onClick={(e) => {
const textVal = typeof text === "string" ? text : text();
if (isJetBrains()) {
ideMessenger.request("copyText", { text: textVal });
} else {
navigator.clipboard.writeText(textVal);
}
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}}
text={copied ? "Copied" : "Copy"}
onClick={copyText}
>
{copied ? (
<CheckIcon className={checkIconClassName} />
) : (
<ClipboardIcon className={clipboardIconClassName} />
)}
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
</>
);
}

View file

@ -2,7 +2,7 @@ import { MinusCircleIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ContinueError } from "core";
import styled from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import ButtonWithTooltip from "../ButtonWithTooltip";
import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip";
const Div = styled.div`
padding: 8px;
@ -29,12 +29,15 @@ function ErrorStepContainer(props: ErrorStepContainerProps) {
display: "flex",
}}
>
<ButtonWithTooltip text="Collapse" onClick={() => props.onClose()}>
<HeaderButtonWithToolTip
text="Collapse"
onClick={() => props.onClose()}
>
<MinusCircleIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
<ButtonWithTooltip text="Delete" onClick={() => props.onDelete()}>
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip text="Delete" onClick={() => props.onDelete()}>
<XMarkIcon width="1.3em" height="1.3em" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
</div>
<Div>
<pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>

View file

@ -1,10 +1,10 @@
import React from "react";
import { type PlacesType } from "react-tooltip";
import { HeaderButton } from ".";
import { HeaderButton } from "..";
import { v4 as uuidv4 } from "uuid";
import { ToolTip } from "./gui/Tooltip";
import { ToolTip } from "./Tooltip";
interface HeaderButtonWithTextProps {
interface HeaderButtonWithToolTipProps {
text: string | undefined;
onClick?: (e: any) => void;
children: React.ReactNode;
@ -20,10 +20,10 @@ interface HeaderButtonWithTextProps {
tooltipPlacement?: PlacesType;
}
const ButtonWithTooltip = React.forwardRef<
const HeaderButtonWithToolTip = React.forwardRef<
HTMLButtonElement,
HeaderButtonWithTextProps
>((props: HeaderButtonWithTextProps, ref) => {
HeaderButtonWithToolTipProps
>((props: HeaderButtonWithToolTipProps, ref) => {
const id = uuidv4();
const tooltipId = `header_button_${id}`;
@ -52,4 +52,4 @@ const ButtonWithTooltip = React.forwardRef<
);
});
export default ButtonWithTooltip;
export default HeaderButtonWithToolTip;

View file

@ -13,10 +13,10 @@ import { vscBackground, vscInputBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import useUIConfig from "../../hooks/useUIConfig";
import { RootState } from "../../redux/store";
import { getFontSize, getMetaKeyLabel } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import { CopyButton } from "../markdown/CopyButton";
import { getFontSize } from "../../util";
import HeaderButtonWithToolTip from "./HeaderButtonWithToolTip";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import { CopyIconButton } from "./CopyIconButton";
interface StepContainerProps {
item: ChatHistoryItem;
@ -83,9 +83,10 @@ function StepContainer(props: StepContainerProps) {
};
return (
<div className="relative"
<div
className="relative"
style={{
minHeight: props.isLast ? "50vh" : 0
minHeight: props.isLast ? "50vh" : 0,
}}
>
<ContentDiv
@ -95,66 +96,71 @@ function StepContainer(props: StepContainerProps) {
>
{uiConfig?.displayRawMarkdown ? (
<pre
className="whitespace-pre-wrap break-words p-4 max-w-full overflow-x-auto"
className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4"
style={{ fontSize: getFontSize() - 2 }}
>
{stripImages(props.item.message.content)}
</pre>
) : (
<StyledMarkdownPreview
showCodeBorder
isRenderingInStepContainer
source={stripImages(props.item.message.content)}
/>
)}
</ContentDiv>
<div className="h-7 mb-2 mx-2 flex items-center justify-end gap-0.5 xs:flex text-xs text-gray-400 pb-0 cursor-default"
<div
className="xs:flex mx-2 mb-2 flex h-7 cursor-default items-center justify-end gap-0.5 pb-0 text-xs text-gray-400"
style={{
opacity: shouldRenderActions ? 1 : 0,
pointerEvents: shouldRenderActions ? "auto" : "none"
pointerEvents: shouldRenderActions ? "auto" : "none",
}}
>
{truncatedEarly && (
<ButtonWithTooltip
<HeaderButtonWithToolTip
tabIndex={-1}
text="Continue generation"
onClick={props.onContinueGeneration}
>
<BarsArrowDownIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
)}
{props.index !== 1 && (
<ButtonWithTooltip
<HeaderButtonWithToolTip
text="Delete"
tabIndex={-1}
onClick={props.onDelete}
>
<TrashIcon className="h-3.5 w-3.5 text-gray-500" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
)}
<CopyButton
<CopyIconButton
tabIndex={-1}
text={stripImages(props.item.message.content)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>
<ButtonWithTooltip
<HeaderButtonWithToolTip
text="Helpful"
tabIndex={-1}
onClick={() => sendFeedback(true)}
>
<HandThumbUpIcon className={`h-3.5 w-3.5 mx-0.5 ${feedback === true ? 'text-green-400' : 'text-gray-500'}`} />
</ButtonWithTooltip>
<HandThumbUpIcon
className={`mx-0.5 h-3.5 w-3.5 ${feedback === true ? "text-green-400" : "text-gray-500"}`}
/>
</HeaderButtonWithToolTip>
<ButtonWithTooltip
<HeaderButtonWithToolTip
text="Unhelpful"
tabIndex={-1}
onClick={() => sendFeedback(false)}
>
<HandThumbDownIcon className={`h-3.5 w-3.5 ${feedback === false ? 'text-red-400' : 'text-gray-500'}`} />
</ButtonWithTooltip>
<HandThumbDownIcon
className={`h-3.5 w-3.5 ${feedback === false ? "text-red-400" : "text-gray-500"}`}
/>
</HeaderButtonWithToolTip>
</div>
</div>
);

View file

@ -0,0 +1,61 @@
import { useContext } from "react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { updateApplyState } from "../../redux/slices/uiStateSlice";
import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
export default function AcceptRejectAllButtons() {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const applyStates = useSelector(
(state: RootState) => state.uiState.applyStates,
);
const pendingApplyStates = applyStates.filter(
(state) => state.status === "done",
);
const handleAcceptAll = async () => {
for (const applyState of pendingApplyStates) {
ideMessenger.post("acceptDiff", { filepath: applyState.filepath });
dispatch(
updateApplyState({
streamId: applyState.streamId,
status: "closed",
}),
);
}
};
const handleRejectAll = async () => {
for (const applyState of pendingApplyStates) {
ideMessenger.post("rejectDiff", { filepath: applyState.filepath });
dispatch(
updateApplyState({
streamId: applyState.streamId,
status: "closed",
}),
);
}
};
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={handleRejectAll}
>
<XMarkIcon className="mr-1 h-4 w-4" />
Reject all changes
</button>
<button
className="flex cursor-pointer items-center border-none bg-transparent px-2 py-1 text-xs text-gray-300 opacity-80 hover:opacity-100 hover:brightness-125"
onClick={handleAcceptAll}
>
<CheckIcon className="mr-1 h-4 w-4" />
Accept all changes
</button>
</div>
);
}

View file

@ -10,6 +10,7 @@ import { newSession, setMessageAtIndex } from "../../redux/slices/stateSlice";
import { RootState } from "../../redux/store";
import ContextItemsPeek from "./ContextItemsPeek";
import TipTapEditor from "./TipTapEditor";
import AcceptRejectAllButtons from "./AcceptRejectAllButtons";
interface ContinueInputBoxProps {
isLastUserInput: boolean;
@ -76,6 +77,13 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const [isGatheringContext, setIsGatheringContext] = useState(false);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const isInMultifileEdit = useSelector(
(state: RootState) => state.state.isInMultifileEdit,
);
const shouldShowAcceptRejectButtons =
props.isMainInput && isInMultifileEdit && !active;
useWebviewListener(
"newSessionWithPrompt",
async (data) => {
@ -110,6 +118,8 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
return (
<div className={`mb-1 ${props.hidden ? "hidden" : ""}`}>
{shouldShowAcceptRejectButtons && <AcceptRejectAllButtons />}
<div className={`relative flex px-2`}>
<GradientBorder
loading={active && props.isLastUserInput ? 1 : 0}

View file

@ -41,7 +41,7 @@ import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiStateSlice";
import ButtonWithTooltip from "../ButtonWithTooltip";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import FileIcon from "../FileIcon";
import SafeImg from "../SafeImg";
import AddDocsDialog from "../dialogs/AddDocsDialog";
@ -434,7 +434,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
{item.subActions?.map((subAction) => {
const Icon = ICONS_FOR_DROPDOWN[subAction.icon];
return (
<ButtonWithTooltip
<HeaderButtonWithToolTip
onClick={(e) => {
subAction.action(item);
e.stopPropagation();
@ -444,7 +444,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
text={undefined}
>
<Icon width="1.2em" height="1.2em" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
);
})}
</span>

View file

@ -1,358 +0,0 @@
import {
ArrowLeftEndOnRectangleIcon,
CheckIcon,
ClipboardIcon,
CommandLineIcon,
PlayIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { getBasename } from "core/util";
import { useContext, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import { v4 as uuidv4 } from "uuid";
import {
defaultBorderRadius,
lightGray,
vscEditorBackground,
vscForeground,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
import {
incrementNextCodeBlockToApplyIndex,
updateApplyState,
} from "../../redux/slices/uiStateSlice";
import { RootState } from "../../redux/store";
import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import FileIcon from "../FileIcon";
import { CopyButton as CopyButtonHeader } from "./CopyButton";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
const ToolbarDiv = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
background: inherit;
font-size: ${getFontSize() - 2}px;
padding: 3px;
padding-left: 4px;
padding-right: 4px;
border-bottom: 0.5px solid ${lightGray}80;
margin: 0;
`;
export const ToolbarButton = styled.button`
display: flex;
align-items: center;
border: none;
outline: none;
background: transparent;
color: ${vscForeground};
font-size: ${getFontSize() - 2}px;
&:hover {
cursor: pointer;
}
`;
const HoverDiv = styled.div`
position: sticky;
top: 0;
left: 100%;
height: 0;
width: 0;
overflow: visible;
z-index: 100;
`;
const InnerHoverDiv = styled.div<{ bottom: boolean }>`
position: absolute;
${(props) => (props.bottom ? "bottom: 3px;" : "top: -11px;")}
right: 10px;
display: flex;
padding: 1px 2px;
gap: 4px;
border: 0.5px solid #8888;
border-radius: ${defaultBorderRadius};
background-color: ${vscEditorBackground};
`;
interface CodeBlockToolBarProps {
text: string;
bottom: boolean;
language: string | undefined;
isNextCodeBlock: boolean;
filepath?: string;
range?: string;
}
const terminalLanguages = ["bash", "sh"];
const commonTerminalCommands = [
"npm",
"pnpm",
"yarn",
"bun",
"deno",
"npx",
"cd",
"ls",
"pwd",
"pip",
"python",
"node",
"git",
"curl",
"wget",
"rbenv",
"gem",
"ruby",
"bundle",
];
function isTerminalCodeBlock(language: string | undefined, text: string) {
return (
terminalLanguages.includes(language) ||
((!language || language?.length === 0) &&
(text.trim().split("\n").length === 1 ||
commonTerminalCommands.some((c) => text.trim().startsWith(c))))
);
}
function getTerminalCommand(text: string): string {
return text.startsWith("$ ") ? text.slice(2) : text;
}
function CodeBlockToolBar(props: CodeBlockToolBarProps) {
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useDispatch();
const defaultModel = useSelector(defaultModelSelector);
const isTerminal = isTerminalCodeBlock(props.language, props.text);
const [isCopied, setIsCopied] = useState(false);
const streamIdRef = useRef<string | null>(null);
if (streamIdRef.current === null) {
streamIdRef.current = uuidv4();
}
const applyState = useSelector(
(store: RootState) =>
store.uiState.applyStates.find(
(state) => state.streamId === streamIdRef.current,
)?.status ?? "closed",
);
// Handle apply keyboard shortcut
useWebviewListener(
"applyCodeFromChat",
async () => {
await ideMessenger.request("applyToFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
filepath: props.filepath,
});
dispatch(incrementNextCodeBlockToApplyIndex({}));
},
[props.isNextCodeBlock, props.text],
!props.isNextCodeBlock,
);
async function onClickCopy() {
if (isJetBrains()) {
await ideMessenger.request("copyText", { text: props.text });
} else {
await navigator.clipboard.writeText(props.text);
}
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
}
async function onClickApply() {
if (isTerminal) {
await ideMessenger.ide.runCommand(getTerminalCommand(props.text));
return;
}
if (!props.filepath) return;
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "streaming",
}),
);
ideMessenger.post("applyToFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
filepath: props.filepath,
});
}
function onClickHeader() {
// TODO: Need to turn into relative or fq path
ideMessenger.post("showFile", {
filepath: props.filepath,
});
}
function onClickAccept() {
ideMessenger.post("acceptDiff", { filepath: props.filepath });
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "closed",
}),
);
}
function onClickReject() {
ideMessenger.post("rejectDiff", { filepath: props.filepath });
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "closed",
}),
);
}
// Currently we only use the "old" apply logic in JetBrains. This check can be removed once
// we implement the "new" lazy apply logic.
if (!props.filepath || isJetBrains()) {
return (
<HoverDiv>
<InnerHoverDiv bottom={props.bottom || false}>
{!isJetBrains() && isTerminal && (
<ButtonWithTooltip
text="Run in terminal"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
<CommandLineIcon className="h-4 w-4 text-gray-400" />
</ButtonWithTooltip>
)}
<ButtonWithTooltip
text="Apply"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
<PlayIcon className="h-4 w-4 text-gray-400" />
</ButtonWithTooltip>
<ButtonWithTooltip
text="Insert at cursor"
style={{ backgroundColor: vscEditorBackground }}
onClick={() =>
ideMessenger.post("insertAtCursor", { text: props.text })
}
>
<ArrowLeftEndOnRectangleIcon className="h-4 w-4 text-gray-400" />
</ButtonWithTooltip>
<CopyButtonHeader text={props.text} />
</InnerHoverDiv>
</HoverDiv>
);
}
return (
<ToolbarDiv>
<div
className="flex max-w-[50%] cursor-pointer items-center gap-1"
onClick={onClickHeader}
>
<FileIcon height="20px" width="20px" filename={props.filepath} />
<span className="truncate">
{getBasename(props.filepath)}
{props.range && ` ${props.range}`}
</span>
</div>
<div className="flex items-center gap-1">
<ToolbarButton onClick={onClickCopy}>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
{isCopied ? (
<>
<CheckIcon className="h-3 w-3 text-green-500 hover:brightness-125" />
<span className="hidden sm:inline">Copied</span>
</>
) : (
<>
<ClipboardIcon className="h-3 w-3 hover:brightness-125" />
<span className="xs:inline hidden">Copy</span>
</>
)}
</div>
</ToolbarButton>
<div className="flex">
{applyState === "closed" ? (
<ToolbarButton onClick={onClickApply} style={{ color: lightGray }}>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
<PlayIcon className="h-3 w-3" />
<span className="xs:inline hidden">Apply</span>
</div>
</ToolbarButton>
) : applyState === "done" ? (
<>
<ToolbarButtonWithTooltip
onClick={onClickReject}
tooltipContent={`${getMetaKeyLabel()}⇧⌫`}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Reject</span>
</div>
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
onClick={onClickAccept}
tooltipContent={`${getMetaKeyLabel()}⇧⏎`}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Accept</span>
</div>
</ToolbarButtonWithTooltip>
</>
) : (
<div className="mr-2 flex items-center">
<svg
className="h-4 w-4 animate-spin text-gray-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="2"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
</div>
)}
</div>
</div>
</ToolbarDiv>
);
}
export default CodeBlockToolBar;

View file

@ -10,7 +10,7 @@ import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscEditorBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { getFontSize } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import FileIcon from "../FileIcon";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
@ -103,7 +103,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
{props.item.name}
</div>
<div className="flex items-center gap-1">
<ButtonWithTooltip
<HeaderButtonWithToolTip
text="Delete"
onClick={(e) => {
e.stopPropagation();
@ -111,7 +111,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
}}
>
<XMarkIcon width="1em" height="1em" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
</div>
</PreviewMarkdownHeader>
<div
@ -125,12 +125,11 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
source={`${fence}${getMarkdownLanguageTagForFile(
props.item.description.split(" ")[0],
)} ${props.item.description}\n${content}\n${fence}`}
showCodeBorder={false}
/>
</div>
{(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && (
<ButtonWithTooltip
<HeaderButtonWithToolTip
className="absolute bottom-1 right-2"
text={collapsed ? "Expand" : "Collapse"}
>
@ -145,7 +144,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
onClick={() => setCollapsed(true)}
/>
)}
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
)}
</PreviewMarkdownDiv>
);

View file

@ -1,7 +1,7 @@
import { RangeInFile } from "core";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useContext } from "react";
import { getBasename } from "core/util";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import FileIcon from "../FileIcon";
interface FilenameLinkProps {
@ -21,11 +21,11 @@ function FilenameLink({ rif }: FilenameLinkProps) {
return (
<div
className="inline-flex items-center align-middle hover:bg-stone-800 rounded-md py-0.5 pl-0 pr-1 mb-0.5 cursor-pointer gap-0.5"
className="mb-0.5 inline-flex cursor-pointer items-center gap-0.5 rounded-md py-0.5 pl-0 pr-1 align-middle hover:bg-stone-800"
onClick={onClick}
>
<FileIcon filename={rif.filepath} height="20px" width="20px" />
<span className="align-middle underline underline-offset-2 decoration-gray-600">
<span className="align-middle underline decoration-gray-600 underline-offset-2">
{getBasename(rif.filepath)}
</span>
</div>

View file

@ -1,99 +0,0 @@
import { debounce } from "lodash";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius, vscEditorBackground } from "..";
import useUIConfig from "../../hooks/useUIConfig";
import { RootState } from "../../redux/store";
import CodeBlockToolBar from "./CodeBlockToolbar";
const TopDiv = styled.div`
outline: 0.5px solid rgba(153, 153, 152);
outline-offset: -0.5px;
border-radius: ${defaultBorderRadius};
margin-bottom: 8px;
background-color: ${vscEditorBackground};
`;
function childToText(child: any) {
if (typeof child === "string") {
return child;
} else if (child?.props) {
return childToText(child.props?.children);
} else if (Array.isArray(child)) {
return childrenToText(child);
} else {
return "";
}
}
function childrenToText(children: any) {
return children.map((child: any) => childToText(child)).join("");
}
function PreWithToolbar(props: {
children: any;
language: string | null;
codeBlockIndex: number;
filepath?: string | undefined;
range?: string;
}) {
const uiConfig = useUIConfig();
const toolbarBottom = uiConfig?.codeBlockToolbarPosition == "bottom";
const [hovering, setHovering] = useState(false);
const [copyValue, setCopyValue] = useState("");
const nextCodeBlockIndex = useSelector(
(state: RootState) => state.uiState.nextCodeBlockToApplyIndex,
);
useEffect(() => {
if (copyValue === "") {
setCopyValue(childrenToText(props.children.props.children));
} else {
const debouncedEffect = debounce(() => {
setCopyValue(childrenToText(props.children.props.children));
}, 100);
debouncedEffect();
return () => {
debouncedEffect.cancel();
};
}
}, [props.children, copyValue]);
return (
<TopDiv
tabIndex={-1}
onMouseEnter={() => setHovering(true)}
onMouseLeave={() => setHovering(false)}
>
{!!props.filepath ? (
<CodeBlockToolBar
isNextCodeBlock={nextCodeBlockIndex === props.codeBlockIndex}
text={copyValue}
bottom={toolbarBottom}
language={props.language}
filepath={props.filepath}
range={props.range}
/>
) : (
hovering && (
<CodeBlockToolBar
isNextCodeBlock={nextCodeBlockIndex === props.codeBlockIndex}
text={copyValue}
bottom={toolbarBottom}
language={props.language}
range={props.range}
/>
)
)}
{props.children}
</TopDiv>
);
}
export default PreWithToolbar;

View file

@ -0,0 +1,145 @@
import { useContext, useRef, useState } from "react";
import styled from "styled-components";
import {
CommandLineIcon,
PlayIcon,
ArrowLeftEndOnRectangleIcon,
} from "@heroicons/react/24/outline";
import { defaultBorderRadius, vscEditorBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { isJetBrains } from "../../util";
import { isTerminalCodeBlock } from "./utils";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import { CopyIconButton } from "../gui/CopyIconButton";
import useUIConfig from "../../hooks/useUIConfig";
import { v4 as uuidv4 } from "uuid";
import { useApplyCodeBlock } from "./utils/useApplyCodeBlock";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
const TopDiv = styled.div`
outline: 0.5px solid rgba(153, 153, 152);
outline-offset: -0.5px;
border-radius: ${defaultBorderRadius};
margin-bottom: 8px;
background-color: ${vscEditorBackground};
`;
const HoverDiv = styled.div`
position: sticky;
top: 0;
left: 100%;
height: 0;
width: 0;
overflow: visible;
z-index: 100;
`;
const InnerHoverDiv = styled.div<{ isBottomToolbarPosition: boolean }>`
position: absolute;
${(props) => (props.isBottomToolbarPosition ? "bottom: 3px;" : "top: -11px;")}
right: 10px;
display: flex;
padding: 1px 2px;
gap: 4px;
border: 0.5px solid #8888;
border-radius: ${defaultBorderRadius};
background-color: ${vscEditorBackground};
`;
interface StepContainerPreActionButtonsProps {
language: string;
codeBlockContent: string;
codeBlockIndex: number;
children: any;
}
export default function StepContainerPreActionButtons({
language,
codeBlockContent,
codeBlockIndex,
children,
}: StepContainerPreActionButtonsProps) {
const [hovering, setHovering] = useState(false);
const ideMessenger = useContext(IdeMessengerContext);
const uiConfig = useUIConfig();
const streamIdRef = useRef<string | null>(null);
const nextCodeBlockIndex = useSelector(
(state: RootState) => state.uiState.nextCodeBlockToApplyIndex,
);
const onClickApply = useApplyCodeBlock({
codeBlockContent,
streamId: streamIdRef.current,
});
const isBottomToolbarPosition =
uiConfig?.codeBlockToolbarPosition == "bottom";
const shouldRunTerminalCmd =
!isJetBrains() && isTerminalCodeBlock(language, codeBlockContent);
const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex;
if (streamIdRef.current === null) {
streamIdRef.current = uuidv4();
}
// Handle apply keyboard shortcut
useWebviewListener(
"applyCodeFromChat",
onClickApply,
[isNextCodeBlock, codeBlockContent],
!isNextCodeBlock,
);
if (!hovering) {
return (
<TopDiv
tabIndex={-1}
onMouseEnter={() => setHovering(true)}
onMouseLeave={() => setHovering(false)}
>
{children}
</TopDiv>
);
}
return (
<TopDiv
tabIndex={-1}
onMouseEnter={() => setHovering(true)}
onMouseLeave={() => setHovering(false)}
>
<HoverDiv>
<InnerHoverDiv isBottomToolbarPosition={isBottomToolbarPosition}>
{shouldRunTerminalCmd && (
<HeaderButtonWithToolTip
text="Run in terminal"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
<CommandLineIcon className="h-4 w-4 text-gray-400" />
</HeaderButtonWithToolTip>
)}
<HeaderButtonWithToolTip
text="Apply"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
<PlayIcon className="h-4 w-4 text-gray-400" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Insert at cursor"
style={{ backgroundColor: vscEditorBackground }}
onClick={() =>
ideMessenger.post("insertAtCursor", { text: codeBlockContent })
}
>
<ArrowLeftEndOnRectangleIcon className="h-4 w-4 text-gray-400" />
</HeaderButtonWithToolTip>
<CopyIconButton text={codeBlockContent} />
</InnerHoverDiv>
</HoverDiv>
{children}
</TopDiv>
);
}

View file

@ -0,0 +1,79 @@
import { CheckIcon, XMarkIcon, PlayIcon } from "@heroicons/react/24/outline";
import Spinner from "./Spinner";
import { lightGray, vscForeground } from "../..";
import { ApplyState } from "core/protocol/ideWebview";
import { useState } from "react";
import { getMetaKeyLabel } from "../../../util";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
interface ApplyActionsProps {
applyState?: ApplyState;
onClickAccept: () => void;
onClickReject: () => void;
onClickApply: () => void;
}
export default function ApplyActions(props: ApplyActionsProps) {
const [hasRejected, setHasRejected] = useState(false);
function onClickReject() {
props.onClickReject();
setHasRejected(true);
}
switch (props.applyState ? props.applyState.status : null) {
case "streaming":
return (
<div className="flex items-center rounded bg-zinc-700 pl-2 pr-1">
<span className="inline-flex items-center gap-2 text-xs text-gray-400">
Applying changes
<Spinner />
</span>
</div>
);
case "done":
return (
<div className="flex items-center rounded bg-zinc-700 pl-2 pr-1">
<span className="mr-2 text-xs text-gray-400">
{`${props.applyState.numDiffs === 1 ? "1 diff" : `${props.applyState.numDiffs} diffs`} remaining`}
</span>
<ToolbarButtonWithTooltip
onClick={onClickReject}
tooltipContent={`Reject all (${getMetaKeyLabel()}⇧⌫)`}
>
<XMarkIcon className="h-4 w-4 text-red-600" />
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
onClick={props.onClickAccept}
tooltipContent={`Accept all (${getMetaKeyLabel()}⇧⏎)`}
>
<CheckIcon className="h-4 w-4 text-green-600 hover:brightness-125" />
</ToolbarButtonWithTooltip>
</div>
);
case "closed":
if (!hasRejected && props.applyState.numDiffs === 0) {
return (
<span className="flex items-center rounded bg-zinc-700 pl-2 pr-1 text-slate-400">
Applied
<CheckIcon className="h-4 w-4 pl-1 hover:brightness-125" />
</span>
);
}
default:
return (
<button
className={`flex items-center border-none bg-transparent text-xs text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
onClick={props.onClickApply}
style={{ color: lightGray }}
>
<div className="flex items-center gap-1 text-gray-400">
<PlayIcon className="h-3 w-3" />
<span className="xs:inline hidden">Apply</span>
</div>
</button>
);
}
}

View file

@ -0,0 +1,35 @@
import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline";
import useCopy from "../../../hooks/useCopy";
import { lightGray, vscForeground } from "../..";
interface CopyButtonProps {
text: string;
}
export default function CopyButton({ text }: CopyButtonProps) {
const { copyText, copied } = useCopy(text);
return (
<div
className={`flex items-center border-none bg-transparent text-xs text-gray-400 text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
onClick={copyText}
>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
{copied ? (
<>
<CheckIcon className="h-3 w-3 text-green-500 hover:brightness-125" />
<span className="hidden sm:inline">Copied</span>
</>
) : (
<>
<ClipboardIcon className="h-3 w-3 hover:brightness-125" />
<span className="xs:inline hidden text-gray-400">Copy</span>
</>
)}
</div>
</div>
);
}

View file

@ -0,0 +1,38 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { getBasename } from "core/util";
import FileIcon from "../../FileIcon";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
export interface FileInfoProps {
filepath: string;
range?: string;
}
const FileInfo = ({ filepath, range }: FileInfoProps) => {
const ideMessenger = useContext(IdeMessengerContext);
// TODO: Need to turn into relative or fq path
function onClickFileName() {
ideMessenger.post("showFile", {
filepath,
});
}
return (
<div className="flex max-w-[20%] items-center">
<div
className="flex cursor-pointer items-center gap-1"
onClick={onClickFileName}
>
<FileIcon height="20px" width="20px" filename={filepath} />
<span className="truncate hover:underline">
{getBasename(filepath)}
{range && ` ${range}`}
</span>
</div>
</div>
);
};
export default FileInfo;

View file

@ -0,0 +1,24 @@
import Spinner from "./Spinner";
export interface GeneratingCodeLoaderProps {
showLineCount: boolean;
codeBlockContent: string;
}
export default function GeneratingCodeLoader({
showLineCount,
codeBlockContent,
}: GeneratingCodeLoaderProps) {
const numLinesCodeBlock = codeBlockContent.split("\n").length;
const linesGeneratedText =
numLinesCodeBlock === 1
? `1 line generated`
: `${numLinesCodeBlock} lines generated`;
return (
<span className="inline-flex items-center gap-2 text-gray-400">
{showLineCount ? linesGeneratedText : "Generating..."}
<Spinner />
</span>
);
}

View file

@ -0,0 +1,27 @@
/**
* Custom spinner since HeroIcons doesn't have a good one
*/
export default function Spinner() {
return (
<svg
className="animate-spin-slow h-3.5 w-3.5 text-gray-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="2"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
);
}

View file

@ -0,0 +1,217 @@
import { debounce } from "lodash";
import { useContext, useEffect, useRef, useState } from "react";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { updateApplyState } from "../../../redux/slices/uiStateSlice";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../redux/store";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { childrenToText } from "../utils";
import { v4 as uuidv4 } from "uuid";
import { defaultBorderRadius, lightGray, vscEditorBackground } from "../..";
import { getFontSize } from "../../../util";
import FileInfo from "./FileInfo";
import styled, { keyframes } from "styled-components";
import Spinner from "./Spinner";
import ApplyActions from "./ApplyActions";
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import CopyButton from "./CopyButton";
import { useApplyCodeBlock } from "../utils/useApplyCodeBlock";
import GeneratingCodeLoader from "./GeneratingCodeLoader";
const fadeInAnimation = keyframes`
from {
opacity: 0;
}
to {
opacity: 1;
}
`;
const TopDiv = styled.div`
outline: 1px solid rgba(153, 153, 152);
outline-offset: -0.5px;
border-radius: ${defaultBorderRadius};
margin-bottom: 8px !important;
background-color: ${vscEditorBackground};
animation: ${fadeInAnimation} 300ms ease-out forwards;
`;
const ToolbarDiv = styled.div<{ isExpanded: boolean }>`
display: flex;
justify-content: space-between;
align-items: center;
background: inherit;
font-size: ${getFontSize() - 2}px;
padding: 4px 6px;
margin: 0;
border-bottom: ${({ isExpanded }) =>
isExpanded ? `0.5px solid ${lightGray}80` : "inherit"};
`;
export interface StepContainerPreToolbarProps {
codeBlockContent: string;
language: string;
filepath: string;
isGeneratingCodeBlock: boolean;
codeBlockIndex: number; // To track which codeblock we are applying
range?: string;
children: any;
}
export default function StepContainerPreToolbar(
props: StepContainerPreToolbarProps,
) {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const streamIdRef = useRef<string | null>(null);
const wasGeneratingRef = useRef(props.isGeneratingCodeBlock);
const isMultifileEdit = useSelector(
(state: RootState) => state.state.isInMultifileEdit,
);
const [isExpanded, setIsExpanded] = useState(isMultifileEdit ? false : true);
const [codeBlockContent, setCodeBlockContent] = useState("");
const isChatActive = useSelector((state: RootState) => state.state.active);
const onClickApply = useApplyCodeBlock({
streamId: streamIdRef.current,
filepath: props.filepath,
codeBlockContent: props.codeBlockContent,
});
const nextCodeBlockIndex = useSelector(
(state: RootState) => state.uiState.nextCodeBlockToApplyIndex,
);
const applyState = useSelector((store: RootState) =>
store.uiState.applyStates.find(
(state) => state.streamId === streamIdRef.current,
),
);
// This handles an edge case when the last node in the markdown syntax tree is a codeblock.
// In this scenario, `isGeneratingCodeBlock` is never set to false since we determine if
// we are done generating based on whether the next node in the tree is not a codeblock.
// The tree parsing logic for Remark is defined on page load, so we can't access state
// during the actual tree parsing.
const isGeneratingCodeBlock = !isChatActive
? false
: props.isGeneratingCodeBlock;
const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex;
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.filepath);
if (streamIdRef.current === null) {
streamIdRef.current = uuidv4();
}
// Handle apply keyboard shortcut
useWebviewListener(
"applyCodeFromChat",
onClickApply,
[isNextCodeBlock, codeBlockContent],
!isNextCodeBlock,
);
useEffect(() => {
if (codeBlockContent === "") {
setCodeBlockContent(childrenToText(props.children.props.children));
} else {
const debouncedEffect = debounce(() => {
setCodeBlockContent(childrenToText(props.children.props.children));
}, 100);
debouncedEffect();
return () => {
debouncedEffect.cancel();
};
}
}, [props.children, codeBlockContent]);
useEffect(() => {
const hasCompletedGenerating =
wasGeneratingRef.current && !isGeneratingCodeBlock;
const shouldAutoApply = hasCompletedGenerating && isMultifileEdit;
if (shouldAutoApply) {
onClickApply();
}
wasGeneratingRef.current = isGeneratingCodeBlock;
}, [isGeneratingCodeBlock]);
function onClickAcceptApply() {
ideMessenger.post("acceptDiff", { filepath: props.filepath });
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "closed",
}),
);
}
function onClickRejectApply() {
ideMessenger.post("rejectDiff", { filepath: props.filepath });
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "closed",
}),
);
}
function onClickExpand() {
setIsExpanded(!isExpanded);
}
// We want until there is an extension in the filepath to avoid rendering
// an incomplete filepath
if (!hasFileExtension) {
return props.children;
}
return (
<TopDiv>
<ToolbarDiv isExpanded={isExpanded}>
<div className="flex items-center">
<ChevronDownIcon
onClick={onClickExpand}
className={`h-4 w-4 cursor-pointer text-gray-400 hover:bg-gray-800 hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
<FileInfo filepath={props.filepath} range={props.range} />
</div>
<div className="flex items-center gap-3">
{isGeneratingCodeBlock && (
<GeneratingCodeLoader
showLineCount={!isExpanded}
codeBlockContent={codeBlockContent}
/>
)}
{!isGeneratingCodeBlock && (
<>
<CopyButton text={props.codeBlockContent} />
<ApplyActions
applyState={applyState}
onClickApply={onClickApply}
onClickAccept={onClickAcceptApply}
onClickReject={onClickRejectApply}
/>
</>
)}
</div>
</ToolbarDiv>
{isExpanded && (
<div
className={`overflow-hidden overflow-y-auto ${
isExpanded ? "max-h-[400px] opacity-100" : "max-h-0 opacity-0"
}`}
>
{props.children}
</div>
)}
</TopDiv>
);
}

View file

@ -0,0 +1,47 @@
import { useMemo } from "react";
import { Tooltip } from "react-tooltip";
import { lightGray, vscForeground } from "../..";
import styled from "styled-components";
import { getFontSize } from "../../../util";
export const ToolbarButton = styled.button`
display: flex;
align-items: center;
border: none;
outline: none;
background: transparent;
color: ${vscForeground};
font-size: ${getFontSize() - 2}px;
&:hover {
cursor: pointer;
filter: brightness(1.25);
}
`;
export function ToolbarButtonWithTooltip({
onClick,
children,
tooltipContent,
}) {
const tooltipId = useMemo(
() => `tooltip-${Math.random().toString(36).slice(2, 11)}`,
[],
);
return (
<>
<ToolbarButton
onClick={onClick}
style={{ color: lightGray }}
data-tooltip-id={tooltipId}
className="px-0.5"
>
{children}
</ToolbarButton>
<Tooltip id={tooltipId} place="top">
{tooltipContent}
</Tooltip>
</>
);
}

View file

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

View file

@ -11,15 +11,16 @@ import {
vscEditorBackground,
vscForeground,
} from "..";
import { getFontSize } from "../../util";
import { getFontSize, isJetBrains } from "../../util";
import "./katex.css";
import FilenameLink from "./FilenameLink";
import "./markdown.css";
import PreWithToolbar from "./PreWithToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import { useSelector } from "react-redux";
import { memoizedContextItemsSelector } from "../../redux/slices/stateSlice";
import { ctxItemToRifWithContents } from "core/commands/util";
import FilenameLink from "./FilenameLink";
import StepContainerPreToolbar from "./StepContainerPreToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import StepContainerPreActionButtons from "./StepContainerPreActionButtons";
const StyledMarkdown = styled.div<{
fontSize?: number;
@ -53,9 +54,19 @@ const StyledMarkdown = styled.div<{
}
background-color: ${vscBackground};
font-family: var(--vscode-font-family), system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell,
"Open Sans", "Helvetica Neue", sans-serif;
font-family:
var(--vscode-font-family),
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Oxygen,
Ubuntu,
Cantarell,
"Open Sans",
"Helvetica Neue",
sans-serif;
font-size: ${(props) => props.fontSize || getFontSize()}px;
padding-left: 8px;
padding-right: 8px;
@ -80,7 +91,7 @@ const StyledMarkdown = styled.div<{
interface StyledMarkdownPreviewProps {
source?: string;
className?: string;
showCodeBorder?: boolean;
isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks
scrollLocked?: boolean;
}
@ -105,7 +116,8 @@ function getCodeChildrenContent(children: any) {
} else if (
Array.isArray(children) &&
children.length > 0 &&
typeof children[0] === "string"
typeof children[0] === "string" &&
children[0] !== ""
) {
return children[0];
}
@ -113,33 +125,38 @@ function getCodeChildrenContent(children: any) {
return undefined;
}
function processCodeBlocks(tree: any) {
const lastNode = tree.children[tree.children.length - 1];
const lastCodeNode = lastNode.type === "code" ? lastNode : null;
visit(tree, "code", (node: any) => {
if (!node.lang) {
node.lang = "javascript";
} else if (node.lang.includes(".")) {
node.lang = node.lang.split(".").slice(-1)[0];
}
if (node.meta) {
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node;
node.data.hProperties.codeBlockContent = node.value;
let meta = node.meta.split(" ");
node.data.hProperties.filepath = meta[0];
node.data.hProperties.range = meta[1];
}
});
}
const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
props: StyledMarkdownPreviewProps,
) {
const contextItems = useSelector(memoizedContextItemsSelector);
const [reactContent, setMarkdownSource] = useRemark({
remarkPlugins: [
remarkMath,
() => {
return (tree) => {
visit(tree, "code", (node: any) => {
if (!node.lang) {
node.lang === "javascript";
}
if (node.meta) {
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
let meta = node.meta.split(" ");
node.data.hProperties.filepath = meta[0];
node.data.hProperties.range = meta[1];
}
});
};
},
],
remarkPlugins: [remarkMath, () => processCodeBlocks],
rehypePlugins: [
rehypeKatex as any,
{},
@ -165,27 +182,56 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
],
rehypeReactOptions: {
components: {
a: ({ node, ...props }) => {
a: ({ node, ...aProps }) => {
return (
<a {...props} target="_blank">
{props.children}
<a {...aProps} target="_blank">
{aProps.children}
</a>
);
},
pre: ({ node, ...preProps }) => {
const { className, filepath, range } = preProps?.children?.[0]?.props;
const {
className,
filepath,
isGeneratingCodeBlock,
codeBlockContent,
range,
} = preProps?.children?.[0]?.props;
return props.showCodeBorder ? (
<PreWithToolbar
if (!props.isRenderingInStepContainer) {
return <SyntaxHighlightedPre {...preProps} />;
}
const language = getLanuageFromClassName(className);
// If we don't have a filepath show the more basic toolbar
// that is just action buttons on hover.
// We also use this in JB since we haven't yet implemented
// the logic for lazy apply.
if (!filepath || isJetBrains()) {
return (
<StepContainerPreActionButtons
language={language}
codeBlockContent={codeBlockContent}
codeBlockIndex={preProps.codeBlockIndex}
>
<SyntaxHighlightedPre {...preProps} />
</StepContainerPreActionButtons>
);
}
// We use a custom toolbar for codeblocks in the step container
return (
<StepContainerPreToolbar
codeBlockContent={codeBlockContent}
codeBlockIndex={preProps.codeBlockIndex}
language={getLanuageFromClassName(className)}
language={language}
filepath={filepath}
isGeneratingCodeBlock={isGeneratingCodeBlock}
range={range}
>
<SyntaxHighlightedPre {...preProps}></SyntaxHighlightedPre>
</PreWithToolbar>
) : (
<SyntaxHighlightedPre {...preProps}></SyntaxHighlightedPre>
<SyntaxHighlightedPre {...preProps} />
</StepContainerPreToolbar>
);
},
code: ({ node, ...codeProps }) => {

View file

@ -1,8 +1,20 @@
import { useContext } from "react";
import styled from "styled-components";
import { defaultBorderRadius, vscForeground } from "..";
import { vscForeground, defaultBorderRadius } from "..";
import { VscThemeContext } from "../../context/VscTheme";
const generateThemeStyles = (theme: any) => {
return Object.keys(theme)
.map((key) => {
return `
& ${key} {
color: ${theme[key]};
}
`;
})
.join("");
};
const StyledPre = styled.pre<{ theme: any }>`
& .hljs {
color: ${vscForeground};
@ -12,20 +24,10 @@ const StyledPre = styled.pre<{ theme: any }>`
margin-bottom: 0;
border-radius: 0 0 ${defaultBorderRadius} ${defaultBorderRadius} !important;
${(props) =>
Object.keys(props.theme)
.map((key, index) => {
return `
& ${key} {
color: ${props.theme[key]};
}
`;
})
.join("")}
${(props) => generateThemeStyles(props.theme)}
`;
export const SyntaxHighlightedPre = (props: any) => {
const currentTheme = useContext(VscThemeContext);
return <StyledPre {...props} theme={currentTheme} />;
};

View file

@ -1,31 +0,0 @@
import { useMemo } from "react";
import { ToolbarButton } from "./CodeBlockToolbar";
import { Tooltip } from "react-tooltip";
import { lightGray } from "..";
export function ToolbarButtonWithTooltip({
onClick,
children,
tooltipContent,
}) {
const tooltipId = useMemo(
() => `tooltip-${Math.random().toString(36).substr(2, 9)}`,
[],
);
return (
<>
<ToolbarButton
onClick={onClick}
style={{ color: lightGray }}
data-tooltip-id={tooltipId}
className="px-1"
>
{children}
</ToolbarButton>
<Tooltip id={tooltipId} place="top">
{tooltipContent}
</Tooltip>
</>
);
}

View file

@ -1,18 +0,0 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
function VSCodeFileLink(props: { path: string; text?: string }) {
const ideMessenger = useContext(IdeMessengerContext);
return (
<a
href={`file://${props.path}`}
onClick={() => {
ideMessenger.post("openFile", { path: props.path });
}}
>
{props.text || props.path}
</a>
);
}
export default VSCodeFileLink;

View file

@ -0,0 +1,54 @@
const terminalLanguages = ["bash", "sh"];
const commonTerminalCommands = [
"npm",
"pnpm",
"yarn",
"bun",
"deno",
"npx",
"cd",
"ls",
"pwd",
"pip",
"python",
"node",
"git",
"curl",
"wget",
"rbenv",
"gem",
"ruby",
"bundle",
];
export function getTerminalCommand(text: string): string {
return text.startsWith("$ ") ? text.slice(2) : text;
}
export function isTerminalCodeBlock(
language: string | undefined,
text: string,
) {
return (
terminalLanguages.includes(language) ||
((!language || language?.length === 0) &&
(text.trim().split("\n").length === 1 ||
commonTerminalCommands.some((c) => text.trim().startsWith(c))))
);
}
function childToText(child: any) {
if (typeof child === "string") {
return child;
} else if (child?.props) {
return childToText(child.props?.children);
} else if (Array.isArray(child)) {
return childrenToText(child);
} else {
return "";
}
}
export function childrenToText(children: any) {
return children.map((child: any) => childToText(child)).join("");
}

View file

@ -0,0 +1,45 @@
import { useContext } from "react";
import { useDispatch, useSelector } from "react-redux";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import {
incrementNextCodeBlockToApplyIndex,
updateApplyState,
} from "../../../redux/slices/uiStateSlice";
import { defaultModelSelector } from "../../../redux/selectors/modelSelectors";
export interface useApplyCodeBlock {
streamId: string;
filepath?: string;
codeBlockContent: string;
}
export function useApplyCodeBlock({
streamId,
filepath,
codeBlockContent,
}: useApplyCodeBlock) {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const defaultModel = useSelector(defaultModelSelector);
const applyCodeBlock = async () => {
dispatch(
updateApplyState({
streamId,
filepath,
status: "streaming",
}),
);
await ideMessenger.request("applyToFile", {
text: codeBlockContent,
streamId,
curSelectedModelTitle: defaultModel.title,
filepath,
});
dispatch(incrementNextCodeBlockToApplyIndex({}));
};
return applyCodeBlock;
}

View file

@ -9,7 +9,7 @@ import {
} from "..";
import { PackageDimension } from "../../pages/AddNewModel/configs/models";
import { providers } from "../../pages/AddNewModel/configs/providers";
import ButtonWithTooltip from "../ButtonWithTooltip";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import InfoHover from "../InfoHover";
import { ModelProviderTag } from "./ModelProviderTag";
import { ModelProviderTags } from "./utils";
@ -43,11 +43,11 @@ const Div = styled.div<{ color: string; disabled: boolean; hovered: boolean }>`
opacity: 0.5;
`
: props.hovered
? `
? `
border: 1px solid ${props.color};
background-color: ${props.color}22;
cursor: pointer;`
: ""}
: ""}
`;
const DimensionsDiv = styled.div`
@ -148,9 +148,7 @@ function ModelCard(props: ModelCardProps) {
<h3>{props.title}</h3>
</div>
{props.tags?.map((tag, i) => (
<ModelProviderTag key={i} tag={tag} />
))}
{props.tags?.map((tag, i) => <ModelProviderTag key={i} tag={tag} />)}
<p>{props.description}</p>
@ -164,9 +162,9 @@ function ModelCard(props: ModelCardProps) {
href={props.refUrl}
target="_blank"
>
<ButtonWithTooltip text="Read the docs">
<HeaderButtonWithToolTip text="Read the docs">
<BookOpenIcon width="1.6em" height="1.6em" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
</a>
)}
</div>
@ -179,7 +177,7 @@ function ModelCard(props: ModelCardProps) {
<div className="flex items-center justify-between">
<div className="flex items-center">
<InfoHover msg={dimension.description} />
<p className="mx-2 text-sm my-0 py-0">{dimension.name}</p>
<p className="mx-2 my-0 py-0 text-sm">{dimension.name}</p>
</div>
<div className="flex items-center">
{Object.keys(dimension.options).map((key) => {
@ -204,7 +202,7 @@ function ModelCard(props: ModelCardProps) {
);
})}
{props.providerOptions?.length && (
<div className="flex items-center flex-wrap justify-end rtl">
<div className="rtl flex flex-wrap items-center justify-end">
<div className="flex items-center">
<InfoHover
msg={
@ -212,16 +210,16 @@ function ModelCard(props: ModelCardProps) {
}
/>
</div>
<div className="flex items-center flex-wrap justify-end rtl">
<div className="rtl flex flex-wrap items-center justify-end">
{props.providerOptions?.map((option, i) => {
const info = providers[option];
if (!info) {
return null;
}
return (
<ButtonWithTooltip
<HeaderButtonWithToolTip
text={info.title}
className="p-2 text-center mx-1 items-center"
className="mx-1 items-center p-2 text-center"
style={{
backgroundColor:
(i === 0 &&
@ -240,7 +238,7 @@ function ModelCard(props: ModelCardProps) {
height="24px"
/>
)}
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
);
})}
</div>

View file

@ -30,6 +30,7 @@ import {
resubmitAtIndex,
setInactive,
setIsGatheringContext,
setIsInMultifileEdit,
setMessageAtIndex,
streamUpdate,
} from "../redux/slices/stateSlice";
@ -291,6 +292,10 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
params: {},
});
if (slashCommand.name === "multifile-edit") {
dispatch(setIsInMultifileEdit(true));
}
await _streamSlashCommand(
messages,
slashCommand,

22
gui/src/hooks/useCopy.tsx Normal file
View file

@ -0,0 +1,22 @@
import { useState, useContext, useCallback } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { isJetBrains } from "../util";
export default function useCopy(text: string | (() => string)) {
const [copied, setCopied] = useState<boolean>(false);
const ideMessenger = useContext(IdeMessengerContext);
const copyText = useCallback(() => {
const textVal = typeof text === "string" ? text : text();
if (isJetBrains()) {
ideMessenger.request("copyText", { text: textVal });
} else {
navigator.clipboard.writeText(textVal);
}
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [text, ideMessenger]);
return { copied, copyText };
}

View file

@ -54,7 +54,7 @@ function useHistory(dispatch: Dispatch) {
if (state.history.length === 0) return;
const stateCopy = { ...state };
if (open_new_session){
if (open_new_session) {
dispatch(newSession());
updateLastSessionId(stateCopy.sessionId);
}
@ -89,8 +89,8 @@ function useHistory(dispatch: Dispatch) {
MAX_TITLE_LENGTH,
)
: stateCopy.title?.length > 0
? stateCopy.title
: (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page.
? stateCopy.title
: (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page.
const sessionInfo: PersistedSessionInfo = {
history: stateCopy.history,
@ -98,6 +98,7 @@ function useHistory(dispatch: Dispatch) {
sessionId: stateCopy.sessionId,
workspaceDirectory: window.workspacePaths?.[0] || "",
};
return await ideMessenger.request("history/save", sessionInfo);
}

View file

@ -86,7 +86,7 @@ function ConfigureProvider() {
<FormProvider {...formMethods}>
<div className="overflow-y-scroll">
<div
className="items-center flex m-0 p-0 sticky top-0"
className="sticky top-0 m-0 flex items-center p-0"
style={{
borderBottom: `0.5px solid ${lightGray}`,
backgroundColor: vscBackground,
@ -97,9 +97,9 @@ function ConfigureProvider() {
width="1.2em"
height="1.2em"
onClick={() => navigate("/addModel")}
className="inline-block ml-4 cursor-pointer"
className="ml-4 inline-block cursor-pointer"
/>
<h3 className="text-lg font-bold m-2 inline-block">
<h3 className="m-2 inline-block text-lg font-bold">
Configure provider
</h3>
</div>
@ -139,7 +139,7 @@ function ConfigureProvider() {
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
className="m-2 rounded-md border-2 border-gray-200 p-2"
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}
@ -169,7 +169,7 @@ function ConfigureProvider() {
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
className="m-2 rounded-md border-2 border-gray-200 p-2"
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}

View file

@ -207,7 +207,7 @@ function Edit() {
</div>
{["accepting", "streaming"].includes(editModeState.editStatus) && (
<div className="my-2 flex w-full">
<div className="my-2 flex w-full cursor-pointer">
<AcceptRejectButton
disabled={editModeState.editStatus !== "accepting"}
backgroundColor={parseColorForHex(
@ -222,7 +222,7 @@ function Edit() {
dispatch(setEditDone());
}}
>
{getMetaKeyLabel()}⇧⌫ Reject all
<code>{getMetaKeyLabel()}⇧⌫</code> Reject all
</AcceptRejectButton>
<AcceptRejectButton
disabled={editModeState.editStatus !== "accepting"}
@ -238,7 +238,7 @@ function Edit() {
dispatch(setEditDone());
}}
>
{getMetaKeyLabel()}⇧⏎ Accept all
<code>{getMetaKeyLabel()}⇧⏎</code> Accept all
</AcceptRejectButton>
</div>
)}

View file

@ -479,7 +479,6 @@ export function Chat() {
/>
<div
style={{
// opacity: active ? 0 : 1,
pointerEvents: active ? "none" : "auto",
}}
>
@ -494,7 +493,7 @@ export function Chat() {
<span className="xs:inline hidden">
New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "L"})
</span>
</NewSessionButton>{" "}
</NewSessionButton>
</div>
) : (
<>

View file

@ -3,7 +3,7 @@ import { DiffEditor } from "@monaco-editor/react";
import React, { useContext, useEffect } from "react";
import { v4 } from "uuid";
import { vscInputBackground } from "../components";
import ButtonWithTooltip from "../components/ButtonWithTooltip";
import HeaderButtonWithToolTip from "../components/gui/HeaderButtonWithToolTip";
import { IdeMessengerContext } from "../context/IdeMessenger";
interface EditorFrameProps {
@ -37,7 +37,7 @@ function EditorFrame(props: EditorFrameProps) {
return (
<div>
<div
className="my-2 px-2 py-1 flex justify-between items-center"
className="my-2 flex items-center justify-between px-2 py-1"
style={{
backgroundColor: vscInputBackground,
}}
@ -53,12 +53,12 @@ function EditorFrame(props: EditorFrameProps) {
{props.filename.split("/").pop()}
</code>
<div className="flex items-center">
<ButtonWithTooltip text="Reject" onClick={() => {}}>
<HeaderButtonWithToolTip text="Reject" onClick={() => {}}>
<XMarkIcon width="1.3em" height="1.3em" color="red" />
</ButtonWithTooltip>
<ButtonWithTooltip text="Accept" onClick={() => {}}>
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip text="Accept" onClick={() => {}}>
<CheckIcon width="1.3em" height="1.3em" color="lightgreen" />
</ButtonWithTooltip>
</HeaderButtonWithToolTip>
</div>
</div>
{/* <Editor

View file

@ -4,9 +4,9 @@ import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { table } from "table";
import { lightGray, vscBackground, vscInputBackground } from "../components";
import { CopyButton } from "../components/markdown/CopyButton";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useNavigationListener } from "../hooks/useNavigationListener";
import { CopyIconButton } from "../components/gui/CopyIconButton";
const Th = styled.th`
padding: 0.5rem;
@ -80,7 +80,7 @@ function Stats() {
<div className="p-2">
<div className="flex items-center gap-2">
<h2 className="ml-2">Tokens per Day</h2>
<CopyButton
<CopyIconButton
text={generateTable(
([["Day", "Generated Tokens", "Prompt Tokens"]] as any).concat(
days.map((day) => [
@ -113,7 +113,7 @@ function Stats() {
<div className="flex items-center gap-2">
<h2 className="ml-2">Tokens per Model</h2>
<CopyButton
<CopyIconButton
text={generateTable(
([["Model", "Generated Tokens", "Prompt Tokens"]] as any).concat(
models.map((model) => [

View file

@ -44,6 +44,7 @@ type State = {
mainEditorContent?: JSONContent;
selectedProfileId: string;
configError: ConfigValidationError[] | undefined;
isInMultifileEdit: boolean;
};
const initialState: State = {
@ -71,6 +72,7 @@ const initialState: State = {
sessionId: v4(),
defaultModelTitle: "GPT-4",
selectedProfileId: "local",
isInMultifileEdit: false,
};
export const stateSlice = createSlice({
@ -274,6 +276,7 @@ export const stateSlice = createSlice({
state.active = false;
state.title = "New Session";
state.sessionId = v4();
state.isInMultifileEdit = false;
}
},
deleteContextWithIds: (
@ -415,6 +418,9 @@ export const stateSlice = createSlice({
selectedProfileId: payload,
};
},
setIsInMultifileEdit: (state, action: PayloadAction<boolean>) => {
state.isInMultifileEdit = action.payload;
},
},
});
@ -442,6 +448,7 @@ export const {
setSelectedProfileId,
deleteMessage,
setIsGatheringContext,
setIsInMultifileEdit,
} = stateSlice.actions;
export default stateSlice.reducer;

View file

@ -57,17 +57,19 @@ export const uiStateSlice = createSlice({
incrementNextCodeBlockToApplyIndex: (state, action) => {
state.nextCodeBlockToApplyIndex++;
},
updateApplyState: (state, action: PayloadAction<ApplyState>) => {
const { streamId, status } = action.payload;
updateApplyState: (state, { payload }: PayloadAction<ApplyState>) => {
const index = state.applyStates.findIndex(
(applyState) => applyState.streamId === streamId,
(applyState) => applyState.streamId === payload.streamId,
);
if (status === "closed" && index !== -1) {
state.applyStates.splice(index, 1);
} else if (index === -1) {
state.applyStates.push(action.payload);
const curApplyState = state.applyStates[index];
if (index === -1) {
state.applyStates.push(payload);
} else {
state.applyStates[index].status = status;
curApplyState.status = payload.status ?? curApplyState.status;
curApplyState.numDiffs = payload.numDiffs ?? curApplyState.numDiffs;
curApplyState.filepath = payload.filepath ?? curApplyState.filepath;
}
},
},

View file

@ -22,7 +22,7 @@ module.exports = {
},
extend: {
animation: {
"spin-slow": "spin 10s linear infinite",
"spin-slow": "spin 6s linear infinite",
},
colors: {
"vsc-background": "rgb(var(--vsc-background) / <alpha-value>)",

View file

@ -17,6 +17,8 @@
"jsx": "react-jsx",
"noEmitOnError": false,
"types": ["vitest/globals"]
// Disabled for now since it's causing too many errors
// "strictNullChecks": true
},
"include": ["src", "../src/util/messenger.ts"],
"references": [{ "path": "./tsconfig.node.json" }]