+
{
+ props.onEnter(...args);
+ if (props.isMainInput) {
+ args[2].commands.clearContent(true);
+ }
+ }}
isMainInput={props.isMainInput ?? false}
availableContextProviders={availableContextProviders ?? []}
availableSlashCommands={availableSlashCommands}
+ historyKey="chat"
/>
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx
index deddde65e..6701e092e 100644
--- a/gui/src/components/mainInput/InputToolbar.tsx
+++ b/gui/src/components/mainInput/InputToolbar.tsx
@@ -1,8 +1,4 @@
-import {
- AtSymbolIcon,
- PhotoIcon,
- SlashIcon,
-} from "@heroicons/react/24/outline";
+import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline";
import { InputModifiers } from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { useRef } from "react";
@@ -11,8 +7,6 @@ import styled from "styled-components";
import {
defaultBorderRadius,
lightGray,
- vscBadgeBackground,
- vscBadgeForeground,
vscForeground,
vscInputBackground,
} from "..";
@@ -24,8 +18,8 @@ import {
getMetaKeyLabel,
isMetaEquivalentKeyPressed,
} from "../../util";
-import ModelSelect from "../modelSelection/ModelSelect";
import { ToolTip } from "../gui/Tooltip";
+import ModelSelect from "../modelSelection/ModelSelect";
const StyledDiv = styled.div<{ isHidden: boolean }>`
padding: 4px 0;
@@ -69,6 +63,14 @@ const EnterButton = styled.button`
}
`;
+export interface ToolbarOptions {
+ hideUseCodebase?: boolean;
+ hideImageUpload?: boolean;
+ hideAddContext?: boolean;
+ enterText?: string;
+ hideSelectModel?: boolean;
+}
+
interface InputToolbarProps {
onEnter?: (modifiers: InputModifiers) => void;
onAddContextItem?: () => void;
@@ -77,6 +79,7 @@ interface InputToolbarProps {
onImageFileSelected?: (file: File) => void;
hidden?: boolean;
activeKey: string | null;
+ toolbarOptions?: ToolbarOptions;
disabled?: boolean;
}
@@ -105,69 +108,73 @@ function InputToolbar(props: InputToolbarProps) {
-
-
-
- {props.activeKey === "Alt" ? (
-
- {`${getAltKeyLabel()}⏎
- ${useActiveFile ? "No active file" : "Active file"}`}
-
- ) : (
-
- props.onEnter({
- useCodebase: true,
- noContext: !useActiveFile,
- })
- }
- >
-
- {getMetaKeyLabel()}⏎ @codebase
-
-
- Submit with the codebase as context ({getMetaKeyLabel()}⏎)
+
+ Add context (files, docs, urls, etc.)
)}
+
+
+
+ {props.toolbarOptions?.hideUseCodebase || (
+
+ {props.activeKey === "Alt" ? (
+
+ {`${getAltKeyLabel()}⏎
+ ${useActiveFile ? "No active file" : "Active file"}`}
+
+ ) : (
+
+ props.onEnter({
+ useCodebase: true,
+ noContext: !useActiveFile,
+ })
+ }
+ >
+
+ {getMetaKeyLabel()}⏎ @codebase
+
+
+ Submit with the codebase as context ({getMetaKeyLabel()}⏎)
+
+
+ )}
+
+ )}
{
@@ -178,7 +185,9 @@ function InputToolbar(props: InputToolbarProps) {
}}
disabled={props.disabled}
>
- ⏎ Enter
+
+ ⏎ {props.toolbarOptions?.enterText ?? "Enter"}
+
⏎
diff --git a/gui/src/components/mainInput/NewSessionButton.tsx b/gui/src/components/mainInput/NewSessionButton.tsx
new file mode 100644
index 000000000..04193450c
--- /dev/null
+++ b/gui/src/components/mainInput/NewSessionButton.tsx
@@ -0,0 +1,23 @@
+import styled from "styled-components";
+import { defaultBorderRadius, lightGray, vscForeground } from "..";
+import { getFontSize } from "../../util";
+
+export const NewSessionButton = styled.div`
+ width: fit-content;
+ margin-right: auto;
+ margin-left: 6px;
+ margin-top: 2px;
+ margin-bottom: 8px;
+ font-size: ${getFontSize() - 2}px;
+
+ border-radius: ${defaultBorderRadius};
+ padding: 2px 6px;
+ color: ${lightGray};
+
+ &:hover {
+ background-color: ${lightGray}33;
+ color: ${vscForeground};
+ }
+
+ cursor: pointer;
+`;
diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx
index 2c17a1f17..01ee8dea6 100644
--- a/gui/src/components/mainInput/TipTapEditor.tsx
+++ b/gui/src/components/mainInput/TipTapEditor.tsx
@@ -50,12 +50,14 @@ import {
getFontSize,
isJetBrains,
isMetaEquivalentKeyPressed,
- isWebEnvironment,
} from "../../util";
-import { handleMetaKeyPressJetBrains } from "../../util/handleMetaKeyPressJetBrains";
+import {
+ handleJetBrainsMetaKeyPress,
+ handleMetaKeyPress,
+} from "./handleMetaKeyPress";
import { CodeBlockExtension } from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
-import InputToolbar from "./InputToolbar";
+import InputToolbar, { ToolbarOptions } from "./InputToolbar";
import { Mention } from "./MentionExtension";
import "./TipTapEditor.css";
import {
@@ -64,20 +66,21 @@ import {
} from "./getSuggestion";
import { ComboBoxItem } from "./types";
-const InputBoxDiv = styled.div`
+const InputBoxDiv = styled.div<{ border?: string }>`
resize: none;
- padding: 8px 12px;
padding-bottom: 4px;
font-family: inherit;
border-radius: ${defaultBorderRadius};
margin: 0;
height: auto;
- width: calc(100% - 24px);
+ width: 100%;
background-color: ${vscInputBackground};
color: ${vscForeground};
- border: 0.5px solid ${vscInputBorder};
+ border: ${(props) =>
+ props.border ? props.border : `0.5px solid ${vscInputBorder}`};
outline: none;
font-size: ${getFontSize()}px;
+
&:focus {
outline: none;
@@ -92,6 +95,11 @@ const InputBoxDiv = styled.div`
flex-direction: column;
`;
+const PaddingDiv = styled.div`
+ padding: 8px 12px;
+ padding-bottom: 4px;
+`;
+
const HoverDiv = styled.div`
position: absolute;
width: 100%;
@@ -141,8 +149,17 @@ interface TipTapEditorProps {
availableContextProviders: ContextProviderDescription[];
availableSlashCommands: ComboBoxItem[];
isMainInput: boolean;
- onEnter: (editorState: JSONContent, modifiers: InputModifiers) => void;
+ onEnter: (
+ editorState: JSONContent,
+ modifiers: InputModifiers,
+ editor: Editor,
+ ) => void;
editorState?: JSONContent;
+ toolbarOptions?: ToolbarOptions;
+ border?: string;
+ placeholder?: string;
+ header?: React.ReactNode;
+ historyKey: string;
}
function TipTapEditor(props: TipTapEditorProps) {
@@ -231,8 +248,8 @@ function TipTapEditor(props: TipTapEditorProps) {
const timer = setTimeout(() => {
setHasDefaultModel(
!!defaultModel &&
- defaultModel.apiKey !== undefined &&
- defaultModel.apiKey !== "",
+ defaultModel.apiKey !== undefined &&
+ defaultModel.apiKey !== "",
);
}, 3500);
@@ -285,7 +302,7 @@ function TipTapEditor(props: TipTapEditorProps) {
(store: RootState) => store.state.mainEditorContent,
);
- const { prevRef, nextRef, addRef } = useInputHistory();
+ const { prevRef, nextRef, addRef } = useInputHistory(props.historyKey);
function getPlaceholder() {
if (!hasDefaultModel) {
@@ -337,7 +354,11 @@ function TipTapEditor(props: TipTapEditorProps) {
},
}),
Placeholder.configure({
- placeholder: getPlaceholder,
+ placeholder:
+ props.placeholder ??
+ (historyLengthRef.current === 0
+ ? "Ask anything, '/' for slash commands, '@' to add context"
+ : "Ask a follow-up"),
}),
Paragraph.extend({
addKeyboardShortcuts() {
@@ -429,37 +450,41 @@ function TipTapEditor(props: TipTapEditorProps) {
},
}),
Text,
- Mention.configure({
- HTMLAttributes: {
- class: "mention",
- },
- suggestion: getContextProviderDropdownOptions(
- availableContextProvidersRef,
- getSubmenuContextItemsRef,
- enterSubmenu,
- onClose,
- onOpen,
- inSubmenuRef,
- ideMessenger,
- ),
- renderHTML: (props) => {
- return `@${props.node.attrs.label || props.node.attrs.id}`;
- },
- }),
- SlashCommand.configure({
- HTMLAttributes: {
- class: "mention",
- },
- suggestion: getSlashCommandDropdownOptions(
- availableSlashCommandsRef,
- onClose,
- onOpen,
- ideMessenger,
- ),
- renderText: (props) => {
- return props.node.attrs.label;
- },
- }),
+ props.availableContextProviders.length
+ ? Mention.configure({
+ HTMLAttributes: {
+ class: "mention",
+ },
+ suggestion: getContextProviderDropdownOptions(
+ availableContextProvidersRef,
+ getSubmenuContextItemsRef,
+ enterSubmenu,
+ onClose,
+ onOpen,
+ inSubmenuRef,
+ ideMessenger,
+ ),
+ renderHTML: (props) => {
+ return `@${props.node.attrs.label || props.node.attrs.id}`;
+ },
+ })
+ : undefined,
+ props.availableSlashCommands.length
+ ? SlashCommand.configure({
+ HTMLAttributes: {
+ class: "mention",
+ },
+ suggestion: getSlashCommandDropdownOptions(
+ availableSlashCommandsRef,
+ onClose,
+ onOpen,
+ ideMessenger,
+ ),
+ renderText: (props) => {
+ return props.node.attrs.label;
+ },
+ })
+ : undefined,
CodeBlockExtension,
],
editorProps: {
@@ -539,86 +564,28 @@ function TipTapEditor(props: TipTapEditorProps) {
/**
* This handles various issues with meta key actions
- * - In JetBrains, when using "off screen rendering", there is a bug where using the meta key to
+ * - In JetBrains, when using OSR in JCEF, there is a bug where using the meta key to
* highlight code using arrow keys is not working
* - In VS Code, while working with .ipynb files there is a problem where copy/paste/cut will affect
* the actual notebook cells, even when performing them in our GUI
+ *
+ * Currently keydown events for a number of keys are not registering if the
+ * meta/shift key is pressed, for example "x", "c", "v", "z", etc.
+ * Until this is resolved we can't turn on OSR for non-Mac users due to issues
+ * with those key actions.
*/
const handleKeyDown = async (e: KeyboardEvent
) => {
- if (!editor || !editorFocusedRef.current) return;
+ if (!editorFocusedRef?.current) return;
setActiveKey(e.key);
+ // Handle meta key issues
if (isMetaEquivalentKeyPressed(e)) {
- const { key, code } = e;
- const isWebEnv = isWebEnvironment();
- const text = editor.state.doc.textBetween(
- editor.state.selection.from,
- editor.state.selection.to,
- );
-
if (isJetBrains()) {
- if (code === "KeyJ") {
- e.stopPropagation();
- e.preventDefault();
- setIgnoreHighlightedCode(true);
- setTimeout(() => {
- setIgnoreHighlightedCode(false);
- }, 100);
- }
-
- if (isMetaEquivalentKeyPressed(e)) {
- e.stopPropagation();
- e.preventDefault();
- handleMetaKeyPressJetBrains(e, text, editor.commands.setContent);
- }
- } else {
- if (code === "KeyL") {
- e.stopPropagation();
- e.preventDefault();
- setIgnoreHighlightedCode(true);
- setTimeout(() => {
- setIgnoreHighlightedCode(false);
- }, 100);
- return;
- }
-
- switch (key) {
- case "x":
- e.stopPropagation();
- e.preventDefault();
- if (isWebEnv) {
- await navigator.clipboard.writeText(text);
- editor.commands.deleteSelection();
- } else {
- document.execCommand("cut");
- }
- break;
- case "c":
- e.stopPropagation();
- e.preventDefault();
- if (isWebEnv) {
- await navigator.clipboard.writeText(text);
- } else {
- document.execCommand("copy");
- }
- break;
- case "v":
- e.stopPropagation();
- e.preventDefault();
- if (isWebEnv) {
- const clipboardText = await navigator.clipboard.readText();
- editor.commands.insertContent(clipboardText);
- } else {
- document.execCommand("paste");
- }
- break;
- }
+ handleJetBrainsMetaKeyPress(e, editor);
}
- } else if (e.key === "Escape") {
- e.stopPropagation();
- e.preventDefault();
- ideMessenger.post("focusEditor", undefined);
+
+ await handleMetaKeyPress(e, editor);
}
};
@@ -639,20 +606,16 @@ function TipTapEditor(props: TipTapEditorProps) {
return;
}
- props.onEnter(json, modifiers);
+ props.onEnter(json, modifiers, editor);
if (props.isMainInput) {
const content = editor.state.toJSON().doc;
addRef.current(content);
- editor.commands.clearContent(true);
}
},
[props.onEnter, editor, props.isMainInput],
);
- // This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview
- const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false);
-
// Re-focus main input after done generating
useEffect(() => {
if (editor && !active && props.isMainInput && document.hasFocus()) {
@@ -684,7 +647,7 @@ function TipTapEditor(props: TipTapEditorProps) {
return;
}
if (historyLength > 0) {
- saveSession();
+ await saveSession();
}
setTimeout(() => {
editor?.commands.blur();
@@ -713,12 +676,12 @@ function TipTapEditor(props: TipTapEditorProps) {
if (!props.isMainInput) {
return;
}
- saveSession();
+ await saveSession();
setTimeout(() => {
editor?.commands.focus("end");
}, 20);
},
- [editor, props.isMainInput],
+ [editor, props.isMainInput, saveSession],
);
useWebviewListener(
@@ -727,71 +690,67 @@ function TipTapEditor(props: TipTapEditorProps) {
if (!props.isMainInput || !editor) {
return;
}
- if (!ignoreHighlightedCode) {
- const rif: RangeInFile & { contents: string } =
- data.rangeInFileWithContents;
- const basename = getBasename(rif.filepath);
- const relativePath = getRelativePath(
- rif.filepath,
- await ideMessenger.ide.getWorkspaceDirs(),
- );
- const rangeStr = `(${rif.range.start.line + 1}-${
- rif.range.end.line + 1
+
+ const rif: RangeInFile & { contents: string } =
+ data.rangeInFileWithContents;
+ const basename = getBasename(rif.filepath);
+ const relativePath = getRelativePath(
+ rif.filepath,
+ await ideMessenger.ide.getWorkspaceDirs(),
+ );
+ const rangeStr = `(${rif.range.start.line + 1}-${rif.range.end.line + 1
})`;
- const item: ContextItemWithId = {
- content: rif.contents,
- name: `${basename} ${rangeStr}`,
- // Description is passed on to the LLM to give more context on file path
- description: `${relativePath} ${rangeStr}`,
- id: {
- providerTitle: "code",
- itemId: v4(),
- },
- uri: {
- type: "file",
- value: rif.filepath,
- },
- };
+ const item: ContextItemWithId = {
+ content: rif.contents,
+ name: `${basename} ${rangeStr}`,
+ // Description is passed on to the LLM to give more context on file path
+ description: `${relativePath} ${rangeStr}`,
+ id: {
+ providerTitle: "code",
+ itemId: v4(),
+ },
+ uri: {
+ type: "file",
+ value: rif.filepath,
+ },
+ };
- let index = 0;
- for (const el of editor.getJSON().content) {
- if (el.type === "codeBlock") {
- index += 2;
- } else {
- break;
- }
+ let index = 0;
+ for (const el of editor.getJSON().content) {
+ if (el.type === "codeBlock") {
+ index += 2;
+ } else {
+ break;
}
- editor
- .chain()
- .insertContentAt(index, {
- type: "codeBlock",
- attrs: {
- item,
- },
- })
- .run();
-
- if (data.prompt) {
- editor.commands.focus("end");
- editor.commands.insertContent(data.prompt);
- }
-
- if (data.shouldRun) {
- onEnterRef.current({ useCodebase: false, noContext: true });
- }
-
- setTimeout(() => {
- editor.commands.blur();
- editor.commands.focus("end");
- }, 20);
}
- setIgnoreHighlightedCode(false);
+ editor
+ .chain()
+ .insertContentAt(index, {
+ type: "codeBlock",
+ attrs: {
+ item,
+ },
+ })
+ .run();
+
+ if (data.prompt) {
+ editor.commands.focus("end");
+ editor.commands.insertContent(data.prompt);
+ }
+
+ if (data.shouldRun) {
+ onEnterRef.current({ useCodebase: false, noContext: true });
+ }
+
+ setTimeout(() => {
+ editor.commands.blur();
+ editor.commands.focus("end");
+ }, 20);
},
[
editor,
props.isMainInput,
historyLength,
- ignoreHighlightedCode,
props.isMainInput,
onEnterRef.current,
],
@@ -859,6 +818,7 @@ function TipTapEditor(props: TipTapEditorProps) {
return (
- {
- event.stopPropagation();
- }}
- />
- insertCharacterWithWhitespace("@")}
- onAddSlashCommand={() => insertCharacterWithWhitespace("/")}
- onEnter={onEnterRef.current}
- onImageFileSelected={(file) => {
- handleImageFile(file).then(([img, dataUrl]) => {
- const { schema } = editor.state;
- const node = schema.nodes.image.create({ src: dataUrl });
- editor.commands.command(({ tr }) => {
- tr.insert(0, node);
- return true;
+ {props.header}
+
+
+ {
+ event.stopPropagation();
+ }}
+ />
+ insertCharacterWithWhitespace("@")}
+ onAddSlashCommand={() => insertCharacterWithWhitespace("/")}
+ onEnter={onEnterRef.current}
+ onImageFileSelected={(file) => {
+ handleImageFile(file).then(([img, dataUrl]) => {
+ const { schema } = editor.state;
+ const node = schema.nodes.image.create({ src: dataUrl });
+ editor.commands.command(({ tr }) => {
+ tr.insert(0, node);
+ return true;
+ });
});
- });
- }}
- disabled={active}
- />
+ }}
+ disabled={active}
+ />
+
{showDragOverMsg &&
modelSupportsImages(
diff --git a/gui/src/components/mainInput/handleMetaKeyPress.ts b/gui/src/components/mainInput/handleMetaKeyPress.ts
new file mode 100644
index 000000000..fd122350f
--- /dev/null
+++ b/gui/src/components/mainInput/handleMetaKeyPress.ts
@@ -0,0 +1,107 @@
+import { KeyboardEvent } from "react";
+import { isWebEnvironment } from "../../util";
+import { Editor } from "@tiptap/react";
+
+const isWebEnv = isWebEnvironment();
+
+export const handleJetBrainsMetaKeyPress = (
+ e: KeyboardEvent,
+ editor: Editor,
+) => {
+ const selection = window.getSelection();
+
+ const handlers: Record void> = {
+ Backspace: () => handleJetBrainsMetaBackspace(editor),
+ ArrowLeft: () =>
+ selection.modify(
+ e.shiftKey ? "extend" : "move",
+ "backward",
+ "lineboundary",
+ ),
+ ArrowRight: () =>
+ selection.modify(
+ e.shiftKey ? "extend" : "move",
+ "forward",
+ "lineboundary",
+ ),
+ ArrowDown: () =>
+ selection.modify(
+ e.shiftKey ? "extend" : "move",
+ "forward",
+ "documentboundary",
+ ),
+ ArrowUp: () => {
+ selection.modify(
+ e.shiftKey ? "extend" : "move",
+ "backward",
+ "documentboundary",
+ );
+ },
+ };
+
+ if (e.key in handlers) {
+ e.stopPropagation();
+ e.preventDefault();
+ handlers[e.key]();
+ }
+};
+
+export const handleMetaKeyPress = async (e: KeyboardEvent, editor: Editor) => {
+ const text = editor.state.doc.textBetween(
+ editor.state.selection.from,
+ editor.state.selection.to,
+ );
+
+ const handlers: Record Promise> = {
+ x: () => handleCutOperation(text, editor),
+ c: () => handleCopyOperation(text),
+ v: () => handlePasteOperation(editor),
+ };
+
+ if (e.key in handlers) {
+ e.stopPropagation();
+ e.preventDefault();
+ await handlers[e.key]();
+ }
+};
+
+export const handleJetBrainsMetaBackspace = (editor: Editor) => {
+ const { doc } = editor.state;
+
+ for (let i = doc.content.childCount - 1; i >= 0; i--) {
+ const node = doc.content.child(i);
+
+ if (node.type.name !== "codeBlock") {
+ editor.commands.deleteNode(node.type.name);
+ }
+ }
+
+ // Add an empty string so the user can keep typing
+ editor.commands.createParagraphNear();
+};
+
+export const handleCutOperation = async (text: string, editor: Editor) => {
+ if (isWebEnv) {
+ await navigator.clipboard.writeText(text);
+ editor.commands.deleteSelection();
+ } else {
+ document.execCommand("cut");
+ }
+};
+
+export const handleCopyOperation = async (text: string) => {
+ if (isWebEnv) {
+ await navigator.clipboard.writeText(text);
+ } else {
+ document.execCommand("copy");
+ }
+};
+
+export const handlePasteOperation = async (editor: Editor) => {
+ if (isWebEnv) {
+ const clipboardText = await navigator.clipboard.readText();
+ editor.commands.insertContent(clipboardText);
+ } else {
+ document.execCommand("paste");
+ }
+};
diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx
index b5380e26d..ac4c03bb2 100644
--- a/gui/src/components/markdown/CodeBlockToolbar.tsx
+++ b/gui/src/components/markdown/CodeBlockToolbar.tsx
@@ -131,7 +131,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
const defaultModel = useSelector(defaultModelSelector);
const isTerminal = isTerminalCodeBlock(props.language, props.text);
const [isCopied, setIsCopied] = useState(false);
- const [isApplying, setIsApplying] = useState(false);
const streamIdRef = useRef(null);
if (streamIdRef.current === null) {
@@ -149,10 +148,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
useWebviewListener(
"applyCodeFromChat",
async () => {
- await ideMessenger.request("applyToCurrentFile", {
+ await ideMessenger.request("applyToFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
+ filepath: props.filepath,
});
dispatch(incrementNextCodeBlockToApplyIndex({}));
},
@@ -172,23 +172,26 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
}
async function onClickApply() {
- if (isApplying) return;
-
if (isTerminal) {
await ideMessenger.ide.runCommand(getTerminalCommand(props.text));
- } else {
- ideMessenger.post("applyToCurrentFile", {
- curSelectedModelTitle: defaultModel.title,
- text: props.text,
- streamId: streamIdRef.current,
- });
- dispatch(
- updateApplyState({
- streamId: streamIdRef.current,
- status: "streaming",
- }),
- );
+ 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() {
@@ -227,7 +230,6 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
{!isJetBrains() && isTerminal && (
@@ -235,15 +237,11 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) {
)}
- {isApplying ? (
-
- ) : (
-
- )}
+
{
console.log("Enter: ", e, modifiers);
}}
+ historyKey="chat"
>
);
diff --git a/gui/src/hooks/useInputHistory.ts b/gui/src/hooks/useInputHistory.ts
index ec3c96880..8a664a9e4 100644
--- a/gui/src/hooks/useInputHistory.ts
+++ b/gui/src/hooks/useInputHistory.ts
@@ -10,9 +10,10 @@ const emptyJsonContent = () => ({
const MAX_HISTORY_LENGTH = 100;
-export function useInputHistory() {
+export function useInputHistory(historyKey: string) {
const [inputHistory, setInputHistory] = useState(
- getLocalStorage("inputHistory")?.slice(-MAX_HISTORY_LENGTH) ?? [],
+ getLocalStorage(`inputHistory_${historyKey}`)?.slice(-MAX_HISTORY_LENGTH) ??
+ [],
);
const [pendingInput, setPendingInput] =
useState(emptyJsonContent());
@@ -58,7 +59,7 @@ export function useInputHistory() {
return [...prev, inputValue].slice(-MAX_HISTORY_LENGTH);
});
setLocalStorage(
- "inputHistory",
+ `inputHistory_${historyKey}`,
[...inputHistory, inputValue].slice(-MAX_HISTORY_LENGTH),
);
}
diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts
index 09bb77010..f7c9fdf10 100644
--- a/gui/src/hooks/useSetup.ts
+++ b/gui/src/hooks/useSetup.ts
@@ -87,6 +87,11 @@ function useSetup(dispatch: Dispatch) {
);
// IDE event listeners
+ const history = useSelector((store: RootState) => store.state.history);
+ useWebviewListener("getWebviewHistoryLength", async () => {
+ return history.length;
+ }, [history]);
+
useWebviewListener("setInactive", async () => {
dispatch(setInactive());
});
diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts
index 6949d9760..87bdfc546 100644
--- a/gui/src/pages/AddNewModel/configs/models.ts
+++ b/gui/src/pages/AddNewModel/configs/models.ts
@@ -1,6 +1,6 @@
import { ILLM, ModelProvider } from "core";
-import { InputDescriptor } from "./providers";
import { ModelProviderTags } from "../../../components/modelSelection/utils";
+import { InputDescriptor } from "./providers";
// A dimension is like parameter count - 7b, 13b, 34b, etc.
// You would set options to the field that should be changed for that option in the params field of ModelPackage
@@ -752,7 +752,7 @@ export const models: { [key: string]: ModelPackage } = {
description:
"Anthropic's most intelligent model, but much less expensive than Claude 3 Opus",
params: {
- model: "claude-3-5-sonnet-20240620",
+ model: "claude-3-5-sonnet-latest",
contextLength: 200_000,
title: "Claude 3.5 Sonnet",
apiKey: "",
@@ -870,27 +870,29 @@ export const models: { [key: string]: ModelPackage } = {
},
granite3Instruct8b: {
title: "Granite 3.0 8b Instruct",
- description: "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
+ description:
+ "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-3-8b-instruct",
contextLength: 8_000,
- title: "Granite 3.0 8b Instruct"
+ title: "Granite 3.0 8b Instruct",
},
providerOptions: ["watsonx"],
icon: "WatsonX.png",
- isOpenSource: false
+ isOpenSource: false,
},
granite3Instruct2b: {
title: "Granite 3.0 2b Instruct",
- description: "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
+ description:
+ "The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-3-2b-instruct",
contextLength: 2_000,
- title: "Granite 3.0 2b Instruct"
+ title: "Granite 3.0 2b Instruct",
},
providerOptions: ["watsonx"],
icon: "WatsonX.png",
- isOpenSource: false
+ isOpenSource: false,
},
MistralLarge: {
title: "Mistral Large",
@@ -973,8 +975,6 @@ export const models: { [key: string]: ModelPackage } = {
isOpenSource: false,
},
-
-
gpt4gov: {
title: "GPT-4 gov",
description:
@@ -1059,6 +1059,19 @@ export const models: { [key: string]: ModelPackage } = {
providerOptions: ["nebius"],
isOpenSource: true,
},
+ grokBeta: {
+ title: "Grok Beta",
+ description: "Generative artificial intelligence chatbot developed by xAI.",
+ refUrl: "",
+ params: {
+ title: "Grok Beta",
+ model: "grok-beta",
+ contextLength: 128_000,
+ },
+ icon: "xAI.png",
+ providerOptions: ["xAI"],
+ isOpenSource: false,
+ },
AUTODETECT: {
title: "Autodetect",
description:
diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts
index 62f6905d1..dd1c3fbdb 100644
--- a/gui/src/pages/AddNewModel/configs/providers.ts
+++ b/gui/src/pages/AddNewModel/configs/providers.ts
@@ -352,6 +352,27 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
packages: [models.gemini15Pro, models.geminiPro, models.gemini15Flash],
apiKeyUrl: "https://aistudio.google.com/app/apikey",
},
+ xAI: {
+ title: "xAI",
+ provider: "xAI",
+ icon: "xAI.png",
+ description: "xAI is a company working on building artificial intelligence to accelerate human scientific discovery",
+ longDescription: "To get started with xAI, obtain an API key from their [console](https://console.x.ai/).",
+ tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
+ collectInputFor: [
+ {
+ inputType: "text",
+ key: "apiKey",
+ label: "API Key",
+ placeholder: "Enter your xAI API key",
+ required: true,
+ },
+ ],
+ packages: [
+ models.grokBeta,
+ ],
+ apiKeyUrl: "https://console.x.ai/",
+ },
lmstudio: {
title: "LM Studio",
provider: "lmstudio",
diff --git a/gui/src/pages/edit.tsx b/gui/src/pages/edit.tsx
new file mode 100644
index 000000000..f05648875
--- /dev/null
+++ b/gui/src/pages/edit.tsx
@@ -0,0 +1,250 @@
+import { ArrowLeftIcon } from "@heroicons/react/24/outline";
+import { Editor, JSONContent } from "@tiptap/core";
+import { InputModifiers } from "core";
+import { getBasename } from "core/util";
+import { usePostHog } from "posthog-js/react";
+import { useContext, useEffect, useState } from "react";
+import { useDispatch, useSelector } from "react-redux";
+import { useNavigate } from "react-router-dom";
+import styled from "styled-components";
+import { defaultBorderRadius, lightGray, vscForeground } from "../components";
+import FileIcon from "../components/FileIcon";
+import { NewSessionButton } from "../components/mainInput/NewSessionButton";
+import resolveEditorContent from "../components/mainInput/resolveInput";
+import TipTapEditor from "../components/mainInput/TipTapEditor";
+import { IdeMessengerContext } from "../context/IdeMessenger";
+import { setEditDone, submitEdit } from "../redux/slices/editModeState";
+import { RootState } from "../redux/store";
+import { getMetaKeyLabel } from "../util";
+
+const TopDiv = styled.div`
+ overflow-y: auto;
+ height: 100%;
+ scrollbar-width: none;
+ &::-webkit-scrollbar {
+ display: none;
+ }
+`;
+
+const AcceptRejectButton = styled.div<{
+ backgroundColor: string;
+ disabled: boolean;
+}>`
+ border: none;
+ background-color: ${(props) => props.backgroundColor};
+ border-radius: ${defaultBorderRadius};
+ padding: 8px 16px;
+ color: ${vscForeground};
+ width: 100%;
+ text-align: center;
+ margin: 0 8px;
+ transition: filter 0.2s ease;
+
+ opacity: ${(props) => (props.disabled ? 0.5 : 1)};
+ cursor: ${(props) => (props.disabled ? "default" : "pointer")};
+
+ &:hover {
+ filter: ${(props) => (props.disabled ? "none" : "brightness(1.2)")};
+ }
+`;
+
+const EditHistoryDiv = styled.div`
+ display: flex;
+ align-items: center;
+ width: 100%;
+ padding: 8px 16px;
+
+ cursor: pointer;
+
+ border: 1px solid ${lightGray}55;
+ border-radius: ${defaultBorderRadius};
+
+ &:hover {
+ background-color: ${lightGray}22;
+ }
+`;
+
+const EDIT_ALLOWS_CONTEXT_PROVIDERS = ["file", "code"];
+
+function Edit() {
+ const posthog = usePostHog();
+ const dispatch = useDispatch();
+ const navigate = useNavigate();
+ const ideMessenger = useContext(IdeMessengerContext);
+ const editModeState = useSelector((state: RootState) => state.editModeState);
+ const availableContextProviders = useSelector(
+ (store: RootState) => store.state.config.contextProviders,
+ );
+ useEffect(() => {}, []);
+
+ const [showCode, setShowCode] = useState(false);
+
+ // Reusing the applyState logic which was just the fastest way to get this working
+ useEffect(() => {
+ if (editModeState.editStatus === "done") {
+ ideMessenger.request("edit/escape", undefined);
+ navigate("/");
+ }
+ }, [editModeState.editStatus]);
+
+ const applyState = useSelector(
+ (store: RootState) =>
+ store.uiState.applyStates.find((state) => state.streamId === "edit")
+ ?.status ?? "closed",
+ );
+
+ useEffect(() => {
+ if (applyState === "closed" && editModeState.editStatus === "accepting") {
+ dispatch(dispatch(setEditDone()));
+ }
+ }, [applyState, editModeState.editStatus]);
+
+ return (
+ <>
+
+
+ {/* Edit session history */}
+ {/* {editModeState.previousInputs.length > 0 && (
+
+ {editModeState.previousInputs.map((input, index) => (
+
+
+ {stripImages(input)}
+
+
+
+ ))}
+
+ )} */}
+
+
+
+ {
+ ideMessenger.ide.showLines(
+ editModeState.highlightedCode.filepath,
+ editModeState.highlightedCode.range.start.line,
+ editModeState.highlightedCode.range.end.line,
+ );
+ setShowCode(!showCode);
+ }}
+ >
+
+ {getBasename(editModeState.highlightedCode.filepath)} (
+ {editModeState.highlightedCode.range.start.line}-
+ {editModeState.highlightedCode.range.end.line})
+
+
+ }
+ toolbarOptions={{
+ hideAddContext: true,
+ hideImageUpload: true,
+ hideUseCodebase: true,
+ hideSelectModel: false,
+ enterText: ["streaming", "accepting"].includes(
+ editModeState.editStatus,
+ )
+ ? "Retry"
+ : "Edit",
+ }}
+ placeholder={
+ ["streaming", "accepting"].includes(editModeState.editStatus)
+ ? "Enter instructions for edit"
+ : "Enter follow-up instructions"
+ }
+ border={`1px solid #aa0`}
+ availableContextProviders={availableContextProviders.filter(
+ (provider) =>
+ EDIT_ALLOWS_CONTEXT_PROVIDERS.includes(provider.title),
+ )}
+ historyKey="edit"
+ availableSlashCommands={[]}
+ isMainInput={true}
+ onEnter={async function (
+ editorState: JSONContent,
+ modifiers: InputModifiers,
+ editor: Editor,
+ ): Promise
{
+ const [_, __, prompt] = await resolveEditorContent(
+ editorState,
+ {
+ noContext: true,
+ useCodebase: false,
+ },
+ ideMessenger,
+ [],
+ );
+ ideMessenger.request("edit/sendPrompt", {
+ prompt,
+ range: editModeState.highlightedCode,
+ });
+ dispatch(submitEdit(prompt));
+
+ // Move cursor to end of editor (it's already focused)
+ editor.commands.selectTextblockEnd();
+ }}
+ >
+
+
+
+ {["accepting", "streaming"].includes(editModeState.editStatus) && (
+
+
+ >
+ );
+}
+export default Edit;
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx
index 243657462..6ca0cc167 100644
--- a/gui/src/pages/gui/Chat.tsx
+++ b/gui/src/pages/gui/Chat.tsx
@@ -23,13 +23,13 @@ import {
defaultBorderRadius,
lightGray,
vscBackground,
- vscForeground,
} from "../../components";
import { ChatScrollAnchor } from "../../components/ChatScrollAnchor";
import StepContainer from "../../components/gui/StepContainer";
import TimelineItem from "../../components/gui/TimelineItem";
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
import { defaultInputModifiers } from "../../components/mainInput/inputModifiers";
+import { NewSessionButton } from "../../components/mainInput/NewSessionButton";
import { TutorialCard } from "../../components/mainInput/TutorialCard";
import {
OnboardingCard,
@@ -66,7 +66,6 @@ const TopGuiDiv = styled.div<{
showScrollbar?: boolean;
}>`
overflow-y: auto;
- height: 100%;
scrollbar-width: ${(props) => (props.showScrollbar ? "thin" : "none")};
&::-webkit-scrollbar {
@@ -75,6 +74,7 @@ const TopGuiDiv = styled.div<{
`;
const StopButton = styled.div`
+ background-color: ${vscBackground};
width: fit-content;
margin-right: auto;
margin-left: auto;
@@ -84,15 +84,20 @@ const StopButton = styled.div`
padding: 4px 8px;
color: ${lightGray};
cursor: pointer;
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
+ box-shadow:
+ 0 4px 6px rgba(0, 0, 0, 0.1),
+ 0 1px 3px rgba(0, 0, 0, 0.08);
transition: box-shadow 0.3s ease;
&:hover {
- box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1);
+ box-shadow:
+ 0 6px 8px rgba(0, 0, 0, 0.15),
+ 0 3px 6px rgba(0, 0, 0, 0.1);
}
`;
const StepsDiv = styled.div`
+ margin-top: 8px;
position: relative;
background-color: transparent;
@@ -105,26 +110,6 @@ const StepsDiv = styled.div`
}
`;
-const NewSessionButton = styled.div`
- width: fit-content;
- margin-right: auto;
- margin-left: 6px;
- margin-top: 2px;
- margin-bottom: 8px;
- font-size: ${getFontSize() - 2}px;
-
- border-radius: ${defaultBorderRadius};
- padding: 2px 6px;
- color: ${lightGray};
-
- &:hover {
- background-color: ${lightGray}33;
- color: ${vscForeground};
- }
-
- cursor: pointer;
-`;
-
function fallbackRender({ error, resetErrorBoundary }: any) {
// Call resetErrorBoundary() to reset the error boundary and retry the render.
@@ -163,16 +148,17 @@ export function Chat() {
const { saveSession, getLastSessionId, loadLastSession } =
useHistory(dispatch);
- useEffect(() => {
- if (!active || !topGuiDivRef.current) return;
-
- const scrollAreaElement = topGuiDivRef.current;
-
- scrollAreaElement.scrollTop =
- scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight;
+ const scrollToBottom = useCallback(() => {
+ if (!topGuiDivRef.current) return;
+ const elem = topGuiDivRef.current;
+ elem.scrollTop = elem.scrollHeight - elem.clientHeight;
setIsAtBottom(true);
- }, [active]);
+ }, [topGuiDivRef, setIsAtBottom]);
+
+ useEffect(() => {
+ if (active) scrollToBottom();
+ }, [active, scrollToBottom]);
useEffect(() => {
// Cmd + Backspace to delete current step
@@ -234,7 +220,7 @@ export function Chat() {
if (currentCount === 300) {
dispatch(
setDialogMessage(
-