setOpen((prev) => !prev)}
diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx
index fee26b84a..e4c482d6d 100644
--- a/gui/src/components/mainInput/ContinueInputBox.tsx
+++ b/gui/src/components/mainInput/ContinueInputBox.tsx
@@ -69,6 +69,9 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const availableContextProviders = useAppSelector(
(state) => state.config.config.contextProviders,
);
+ const useTools = useSelector(
+ (store: RootState) => store.state.config.experimental?.useTools !== false,
+ );
useWebviewListener(
"newSessionWithPrompt",
@@ -87,7 +90,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
);
return (
-
+
diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx
index 860de3477..a7591b84c 100644
--- a/gui/src/components/mainInput/InputToolbar.tsx
+++ b/gui/src/components/mainInput/InputToolbar.tsx
@@ -18,6 +18,8 @@ import {
} from "../../util";
import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
+import HoverItem from "./InputToolbar/HoverItem";
+import ToggleToolsButton from "./InputToolbar/ToggleToolsButton";
import { useAppSelector } from "../../redux/hooks";
import { selectDefaultModel } from "../../redux/slices/configSlice";
@@ -38,17 +40,6 @@ const StyledDiv = styled.div<{ isHidden?: boolean }>`
}
`;
-const HoverItem = styled.span<{ isActive?: boolean }>`
- padding: 0 4px;
- padding-top: 2px;
- padding-bottom: 2px;
- cursor: pointer;
- transition:
- color 200ms,
- background-color 200ms,
- box-shadow 200ms;
-`;
-
const EnterButton = styled.button`
all: unset;
padding: 2px 4px;
@@ -69,6 +60,7 @@ export interface ToolbarOptions {
hideAddContext?: boolean;
enterText?: string;
hideSelectModel?: boolean;
+ hideTools?: boolean;
}
interface InputToolbarProps {
@@ -145,6 +137,8 @@ function InputToolbar(props: InputToolbarProps) {
)}
+
+ {props.toolbarOptions?.hideTools ||
}
@@ -153,7 +147,7 @@ function InputToolbar(props: InputToolbarProps) {
{props.activeKey === "Alt" ? (
- {`${getAltKeyLabel()}⏎
+ {`${getAltKeyLabel()}⏎
${useActiveFile ? "No active file" : "Active file"}`}
) : (
diff --git a/gui/src/components/mainInput/InputToolbar/HoverItem.tsx b/gui/src/components/mainInput/InputToolbar/HoverItem.tsx
new file mode 100644
index 000000000..e668a69f2
--- /dev/null
+++ b/gui/src/components/mainInput/InputToolbar/HoverItem.tsx
@@ -0,0 +1,14 @@
+import styled from "styled-components";
+
+const HoverItem = styled.span<{ isActive?: boolean }>`
+ padding: 0 4px;
+ padding-top: 2px;
+ padding-bottom: 2px;
+ cursor: pointer;
+ transition:
+ color 200ms,
+ background-color 200ms,
+ box-shadow 200ms;
+`;
+
+export default HoverItem;
diff --git a/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx
new file mode 100644
index 000000000..1c91aee04
--- /dev/null
+++ b/gui/src/components/mainInput/InputToolbar/ToggleToolsButton.tsx
@@ -0,0 +1,161 @@
+import { Listbox, Transition } from "@headlessui/react";
+import {
+ ChevronDownIcon,
+ ChevronUpIcon,
+ WrenchScrewdriverIcon,
+} from "@heroicons/react/24/outline";
+import { modelSupportsTools } from "core/llm/autodetect";
+import { useEffect, useRef, useState } from "react";
+import { useDispatch, useSelector } from "react-redux";
+import styled from "styled-components";
+import { defaultBorderRadius, lightGray, vscForeground } from "../..";
+import { defaultModelSelector } from "../../../redux/selectors/modelSelectors";
+import { toggleUseTools } from "../../../redux/slices/uiStateSlice";
+import { RootState } from "../../../redux/store";
+import { getFontSize } from "../../../util";
+import InfoHover from "../../InfoHover";
+import HoverItem from "./HoverItem";
+import ToolDropdownItem from "./ToolDropdownItem";
+
+const BackgroundDiv = styled.div<{ useTools: boolean }>`
+ background-color: ${(props) =>
+ props.useTools ? `${lightGray}33` : "transparent"};
+ border-radius: ${defaultBorderRadius};
+ padding: 1px;
+
+ font-size: ${getFontSize() - 4}px;
+
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ gap: 2px;
+
+ transition: background-color 200ms;
+`;
+
+export default function ToolDropdown() {
+ const buttonRef = useRef
(null);
+ const dispatch = useDispatch();
+ const [isDropdownOpen, setDropdownOpen] = useState(false);
+
+ const useTools = useSelector((store: RootState) => store.uiState.useTools);
+ const availableTools = useSelector(
+ (store: RootState) => store.state.config.tools,
+ );
+ const defaultModel = useSelector(defaultModelSelector);
+
+ const [showAbove, setShowAbove] = useState(false);
+
+ useEffect(() => {
+ const checkPosition = () => {
+ if (buttonRef.current) {
+ const rect = buttonRef.current.getBoundingClientRect();
+ const windowHeight = window.innerHeight;
+ const spaceBelow = windowHeight - rect.bottom;
+ setShowAbove(spaceBelow < 250);
+ }
+ };
+
+ if (isDropdownOpen) {
+ checkPosition();
+ }
+ }, [isDropdownOpen]);
+
+ if (!defaultModel || !modelSupportsTools(defaultModel.model)) {
+ return null;
+ }
+
+ return (
+ dispatch(toggleUseTools())}>
+
+
+ {useTools && (
+ <>
+ Tools
+
+
+
{}}>
+ {
+ e.stopPropagation();
+ setDropdownOpen((prev) => !prev);
+ }}
+ className="text-lightgray flex cursor-pointer items-center border-none bg-transparent outline-none"
+ >
+ {isDropdownOpen ? (
+
+ ) : (
+
+ )}
+
+
+
+
+
+ Tool policies{" "}
+
+
+
+ Automatic:
+ {" "}
+ Can be used without asking
+
+
+
+ Allowed:
+ {" "}
+ Will ask before using
+
+
+ Disabled:{" "}
+ Cannot be used
+
+
+ }
+ />
+
+
+
+ {availableTools.map((tool) => (
+
+
+
+ ))}
+
+
+
+
+
+ >
+ )}
+
+
+ );
+}
diff --git a/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx
new file mode 100644
index 000000000..7098733eb
--- /dev/null
+++ b/gui/src/components/mainInput/InputToolbar/ToolDropdownItem.tsx
@@ -0,0 +1,59 @@
+import { Tool } from "core";
+import { useEffect } from "react";
+import { useDispatch, useSelector } from "react-redux";
+import { addTool, toggleToolSetting } from "../../../redux/slices/uiStateSlice";
+import { RootState } from "../../../redux/store";
+
+interface ToolDropdownItemProps {
+ tool: Tool;
+}
+
+function ToolDropdownItem(props: ToolDropdownItemProps) {
+ const dispatch = useDispatch();
+ const settings = useSelector(
+ (state: RootState) => state.uiState.toolSettings[props.tool.function.name],
+ );
+
+ useEffect(() => {
+ if (!settings) {
+ dispatch(addTool(props.tool));
+ }
+ }, [props.tool.function.name, settings]);
+
+ if (!settings) {
+ return null;
+ }
+
+ return (
+
{
+ dispatch(toggleToolSetting(props.tool.function.name));
+ e.stopPropagation();
+ e.preventDefault();
+ }}
+ >
+
+ {props.tool.displayTitle}{" "}
+ {/* */}
+
+
+ {(settings === "allowedWithPermission" || settings === undefined) && (
+ Allowed
+ )}
+ {settings === "allowedWithoutPermission" && (
+ Automatic
+ )}
+ {settings === "disabled" && (
+ Disabled
+ )}
+
+
+ );
+}
+
+export default ToolDropdownItem;
diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts
index 77da2ee84..ae9dd88a9 100644
--- a/gui/src/components/mainInput/resolveInput.ts
+++ b/gui/src/components/mainInput/resolveInput.ts
@@ -7,7 +7,7 @@ import {
MessagePart,
RangeInFile,
} from "core";
-import { stripImages } from "core/llm/images";
+import { stripImages } from "core/util/messageContent";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { Dispatch } from "@reduxjs/toolkit";
import { setIsGatheringContext } from "../../redux/slices/sessionSlice";
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx
index d96afc7fe..42ee8e048 100644
--- a/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx
+++ b/gui/src/components/markdown/StepContainerPreToolbar/ApplyActions.tsx
@@ -1,10 +1,10 @@
-import { CheckIcon, XMarkIcon, PlayIcon } from "@heroicons/react/24/outline";
-import Spinner from "./Spinner";
-import { lightGray, vscForeground } from "../..";
-import { useState } from "react";
-import { getMetaKeyLabel } from "../../../util";
-import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
+import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
+import { useState } from "react";
+import { lightGray, vscForeground } from "../..";
+import { getMetaKeyLabel } from "../../../util";
+import Spinner from "./Spinner";
+import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
interface ApplyActionsProps {
applyState?: ApplyState;
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx
new file mode 100644
index 000000000..35bc54349
--- /dev/null
+++ b/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx
@@ -0,0 +1,35 @@
+import { CommandLineIcon } from "@heroicons/react/24/outline";
+import { useContext } from "react";
+import { lightGray, vscForeground } from "../..";
+import { IdeMessengerContext } from "../../../context/IdeMessenger";
+
+interface RunInTerminalButtonProps {
+ command: string;
+}
+
+export default function RunInTerminalButton({
+ command,
+}: RunInTerminalButtonProps) {
+ const ideMessenger = useContext(IdeMessengerContext);
+
+ function runInTerminal() {
+ void ideMessenger.post("runCommand", { command });
+ }
+
+ return (
+
+ );
+}
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx
index d5e531570..8b0573122 100644
--- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx
+++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx
@@ -7,11 +7,12 @@ import { defaultBorderRadius, lightGray, vscEditorBackground } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { getFontSize } from "../../../util";
-import { childrenToText } from "../utils";
+import { childrenToText, isTerminalCodeBlock } from "../utils";
import ApplyActions from "./ApplyActions";
import CopyButton from "./CopyButton";
import FileInfo from "./FileInfo";
import GeneratingCodeLoader from "./GeneratingCodeLoader";
+import RunInTerminalButton from "./RunInTerminalButton";
import { useAppSelector } from "../../../redux/hooks";
import { selectDefaultModel } from "../../../redux/slices/configSlice";
import { selectApplyStateBySessionId } from "../../../redux/slices/sessionSlice";
@@ -45,6 +46,8 @@ export interface StepContainerPreToolbarProps {
codeBlockIndex: number; // To track which codeblock we are applying
range?: string;
children: any;
+ expanded?: boolean;
+ hideApply?: boolean;
}
export default function StepContainerPreToolbar(
@@ -56,7 +59,9 @@ export default function StepContainerPreToolbar(
const isInEditMode = useAppSelector(
(state) => state.editModeState.isInEditMode,
);
- const [isExpanded, setIsExpanded] = useState(isInEditMode ? false : true);
+ const [isExpanded, setIsExpanded] = useState(
+ props.expanded ?? (isInEditMode ? false : true),
+ );
const [codeBlockContent, setCodeBlockContent] = useState("");
const isStreaming = useAppSelector((state) => state.session.isStreaming);
@@ -180,12 +185,17 @@ export default function StepContainerPreToolbar(
{!isGeneratingCodeBlock && (
<>
-
+ {props.hideApply ||
+ (isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
+
+ ) : (
+
+ ))}
>
)}
diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx
index 16b98df77..dcb62f3b5 100644
--- a/gui/src/components/markdown/StyledMarkdownPreview.tsx
+++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx
@@ -1,4 +1,7 @@
+import { SymbolWithRange } from "core";
+import { ctxItemToRifWithContents } from "core/commands/util";
import { memo, useEffect, useRef } from "react";
+import { useSelector } from "react-redux";
import { useRemark } from "react-remark";
import rehypeHighlight, { Options } from "rehype-highlight";
import rehypeKatex from "rehype-katex";
@@ -11,18 +14,16 @@ import {
vscEditorBackground,
vscForeground,
} from "..";
+import useUpdatingRef from "../../hooks/useUpdatingRef";
import { getFontSize, isJetBrains } from "../../util";
+import FilenameLink from "./FilenameLink";
import "./katex.css";
import "./markdown.css";
-import { ctxItemToRifWithContents } from "core/commands/util";
-import FilenameLink from "./FilenameLink";
-import StepContainerPreToolbar from "./StepContainerPreToolbar";
-import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import StepContainerPreActionButtons from "./StepContainerPreActionButtons";
-import { patchNestedMarkdown } from "./utils/patchNestedMarkdown";
-import { SymbolWithRange } from "core";
+import StepContainerPreToolbar from "./StepContainerPreToolbar";
import SymbolLink from "./SymbolLink";
-import useUpdatingRef from "../../hooks/useUpdatingRef";
+import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
+import { patchNestedMarkdown } from "./utils/patchNestedMarkdown";
import { useAppSelector } from "../../redux/hooks";
const StyledMarkdown = styled.div<{
diff --git a/gui/src/components/markdown/SyntaxHighlightedPre.tsx b/gui/src/components/markdown/SyntaxHighlightedPre.tsx
index a3caba685..6e2be08f2 100644
--- a/gui/src/components/markdown/SyntaxHighlightedPre.tsx
+++ b/gui/src/components/markdown/SyntaxHighlightedPre.tsx
@@ -1,6 +1,6 @@
import { useContext } from "react";
import styled from "styled-components";
-import { vscForeground, defaultBorderRadius } from "..";
+import { defaultBorderRadius, vscForeground } from "..";
import { VscThemeContext } from "../../context/VscTheme";
const generateThemeStyles = (theme: any) => {
diff --git a/gui/src/components/modelSelection/ModelCard.tsx b/gui/src/components/modelSelection/ModelCard.tsx
index 85658d173..2c34bdc51 100644
--- a/gui/src/components/modelSelection/ModelCard.tsx
+++ b/gui/src/components/modelSelection/ModelCard.tsx
@@ -175,7 +175,10 @@ function ModelCard(props: ModelCardProps) {
<>
@@ -204,6 +207,7 @@ function ModelCard(props: ModelCardProps) {
`
`}
`;
-const IconBase = styled.div<{ hovered: boolean }>`
+const IconBase = styled.div<{ $hovered: boolean }>`
width: 1.2em;
height: 1.2em;
cursor: pointer;
padding: 4px;
border-radius: ${defaultBorderRadius};
- opacity: ${(props) => (props.hovered ? 0.75 : 0)};
- visibility: ${(props) => (props.hovered ? "visible" : "hidden")};
+ opacity: ${(props) => (props.$hovered ? 0.75 : 0)};
+ visibility: ${(props) => (props.$hovered ? "visible" : "hidden")};
&:hover {
opacity: 1;
@@ -203,9 +203,9 @@ function ModelOption({
-
+
{showDelete && (
-
+
)}
diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts
index c5c4f9b3e..bddd3fbbe 100644
--- a/gui/src/context/IdeMessenger.ts
+++ b/gui/src/context/IdeMessenger.ts
@@ -156,7 +156,7 @@ export class IdeMessenger implements IIdeMessenger {
this.post(messageType, data, messageId);
- let buffer = "";
+ const buffer: any[] = [];
let index = 0;
let done = false;
let returnVal = undefined;
@@ -169,7 +169,7 @@ export class IdeMessenger implements IIdeMessenger {
done = true;
returnVal = responseData;
} else {
- buffer += responseData.content;
+ buffer.push(responseData.content);
}
}
};
@@ -181,16 +181,16 @@ export class IdeMessenger implements IIdeMessenger {
while (!done) {
if (buffer.length > index) {
- const chunk = buffer.slice(index);
- index = buffer.length;
+ const chunk = buffer[index];
+ index++;
yield chunk;
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
- if (buffer.length > index) {
- const chunk = buffer.slice(index);
- index = buffer.length;
+ while (buffer.length > index) {
+ const chunk = buffer[index];
+ index++;
yield chunk;
}
@@ -215,7 +215,7 @@ export class IdeMessenger implements IIdeMessenger {
let next = await gen.next();
while (!next.done) {
- yield { role: "user", content: next.value };
+ yield next.value;
next = await gen.next();
}
diff --git a/gui/src/context/SubmenuContextProviders.tsx b/gui/src/context/SubmenuContextProviders.tsx
index 70f77f651..b9cbe3bc7 100644
--- a/gui/src/context/SubmenuContextProviders.tsx
+++ b/gui/src/context/SubmenuContextProviders.tsx
@@ -7,7 +7,14 @@ import {
groupByLastNPathParts,
} from "core/util";
import MiniSearch, { SearchResult } from "minisearch";
-import { useCallback, useContext, useEffect, useMemo, useState } from "react";
+import {
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { IdeMessengerContext } from "./IdeMessenger";
import { selectContextProviderDescriptions } from "../redux/selectors";
import { useWebviewListener } from "../hooks/useWebviewListener";
@@ -40,6 +47,19 @@ const initialContextProviders: SubtextContextProvidersContextType = {
const SubmenuContextProvidersContext =
createContext
(initialContextProviders);
+function isOpenFilesChanged(
+ newFiles: { id: string }[],
+ oldFiles: { id: string }[],
+) {
+ if (newFiles.length > oldFiles.length) {
+ return true;
+ }
+ for (let i = 0; i < newFiles.length; ++i) {
+ if (newFiles[i].id !== oldFiles[i].id) return true;
+ }
+ return false;
+}
+
export const SubmenuContextProvidersProvider = ({
children,
}: {
@@ -123,18 +143,22 @@ export const SubmenuContextProvidersProvider = ({
[minisearches],
);
+ const lastOpenFilesRef = useRef([]);
useEffect(() => {
let isMounted = true;
const refreshOpenFiles = async () => {
if (!isMounted) return;
const openFiles = await getOpenFilesItems();
- setFallbackResults((prev) => ({
- ...prev,
- file: deduplicateArray(
- [...openFiles, ...(Array.isArray(prev.file) ? prev.file : [])],
- (a, b) => a.id === b.id,
- ),
- }));
+ if (isOpenFilesChanged(openFiles, lastOpenFilesRef.current)) {
+ setFallbackResults((prev) => ({
+ ...prev,
+ file: deduplicateArray(
+ [...openFiles, ...(Array.isArray(prev.file) ? prev.file : [])],
+ (a, b) => a.id === b.id,
+ ),
+ }));
+ lastOpenFilesRef.current = openFiles;
+ }
};
const interval = setInterval(refreshOpenFiles, 2000);
diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts
deleted file mode 100644
index d05e1c386..000000000
--- a/gui/src/hooks/useChatHandler.ts
+++ /dev/null
@@ -1,336 +0,0 @@
-import { Dispatch } from "@reduxjs/toolkit";
-import { JSONContent } from "@tiptap/react";
-import {
- ChatHistoryItem,
- ChatMessage,
- ContextItemWithId,
- InputModifiers,
- MessageContent,
- PromptLog,
- RangeInFile,
- SlashCommandDescription,
-} from "core";
-import { constructMessages } from "core/llm/constructMessages";
-import { stripImages } from "core/llm/images";
-import { getBasename, getRelativePath } from "core/util";
-import { usePostHog } from "posthog-js/react";
-import { useEffect, useMemo, useRef, useState } from "react";
-import { useSelector } from "react-redux";
-import resolveEditorContent, {
- hasSlashCommandOrContextProvider,
-} from "../components/mainInput/resolveInput";
-import { IIdeMessenger } from "../context/IdeMessenger";
-import {
- abortStream,
- addPromptCompletionPair,
- clearLastEmptyResponse,
- initNewActiveMessage,
- resubmitAtIndex,
- setCurCheckpointIndex,
- setInactive,
- setIsGatheringContext,
- setMessageAtIndex,
- streamUpdate,
-} from "../redux/slices/sessionSlice";
-import { resetNextCodeBlockToApplyIndex } from "../redux/slices/sessionSlice";
-import useHistory from "./useHistory";
-import { updateFileSymbolsFromContextItems } from "../util/symbols";
-import {
- selectDefaultContextProviders,
- selectSlashCommands,
-} from "../redux/selectors";
-import { useAppSelector } from "../redux/hooks";
-import { selectDefaultModel } from "../redux/slices/configSlice";
-
-function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
- const posthog = usePostHog();
-
- const defaultModel = useAppSelector(selectDefaultModel);
- const defaultContextProviders = useSelector(selectDefaultContextProviders);
- const slashCommands = useSelector(selectSlashCommands);
- const history = useAppSelector((store) => store.session.messages);
- const active = useAppSelector((store) => store.session.isStreaming);
- const streamAborter = useAppSelector((store) => store.session.streamAborter);
- const activeRef = useRef(active);
-
- const { saveSession } = useHistory(dispatch);
- const [save, triggerSave] = useState(false);
-
- useEffect(() => {
- saveSession(false);
- }, [save]);
-
- useEffect(() => {
- activeRef.current = active;
- }, [active]);
-
- async function _streamNormalInput(messages: ChatMessage[]) {
- if (!defaultModel) {
- throw new Error("Default model not defined");
- }
- const gen = ideMessenger.llmStreamChat(
- defaultModel.title,
- streamAborter.signal,
- messages,
- );
- let next = await gen.next();
- while (!next.done) {
- if (!activeRef.current) {
- dispatch(abortStream());
- break;
- }
- dispatch(streamUpdate(stripImages((next.value as ChatMessage).content)));
- next = await gen.next();
- }
-
- let returnVal = next.value as PromptLog;
- if (returnVal) {
- dispatch(addPromptCompletionPair([returnVal]));
- }
- }
-
- const getSlashCommandForInput = (
- input: MessageContent,
- ): [SlashCommandDescription, string] | undefined => {
- let slashCommand: SlashCommandDescription | undefined;
- let slashCommandName: string | undefined;
-
- let lastText =
- typeof input === "string"
- ? input
- : input.filter((part) => part.type === "text").slice(-1)[0]?.text || "";
-
- if (lastText.startsWith("/")) {
- slashCommandName = lastText.split(" ")[0].substring(1);
- slashCommand = slashCommands.find(
- (command) => command.name === slashCommandName,
- );
- }
- if (!slashCommand || !slashCommandName) {
- return undefined;
- }
-
- // Convert to actual slash command object with runnable function
- return [slashCommand, stripImages(input)];
- };
-
- async function _streamSlashCommand(
- messages: ChatMessage[],
- slashCommand: SlashCommandDescription,
- input: string,
- historyIndex: number,
- selectedCode: RangeInFile[],
- contextItems: ContextItemWithId[],
- ) {
- if (!defaultModel) {
- throw new Error("Default model not defined");
- }
-
- const modelTitle = defaultModel.title;
-
- const checkActiveInterval = setInterval(() => {
- if (!activeRef.current) {
- dispatch(abortStream());
- clearInterval(checkActiveInterval);
- }
- }, 100);
-
- try {
- for await (const update of ideMessenger.streamRequest(
- "command/run",
- {
- input,
- history: messages,
- modelTitle,
- slashCommandName: slashCommand.name,
- contextItems,
- params: slashCommand.params,
- historyIndex,
- selectedCode,
- },
- streamAborter.signal,
- )) {
- if (!activeRef.current) {
- dispatch(abortStream());
- clearInterval(checkActiveInterval);
- break;
- }
- if (typeof update === "string") {
- dispatch(streamUpdate(update));
- }
- }
- } catch (e) {
- throw e;
- } finally {
- clearInterval(checkActiveInterval);
- }
- }
-
- async function streamResponse(
- editorState: JSONContent,
- modifiers: InputModifiers,
- ideMessenger: IIdeMessenger,
- index?: number,
- promptPreamble?: string,
- ) {
- try {
- if (typeof index === "number") {
- dispatch(resubmitAtIndex({ index, editorState }));
- } else {
- dispatch(initNewActiveMessage({ editorState }));
- }
-
- // Reset current code block index
- dispatch(resetNextCodeBlockToApplyIndex());
-
- if (index) {
- dispatch(setCurCheckpointIndex(Math.floor(index / 2)));
- }
-
- const shouldGatherContext =
- modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState);
-
- if (shouldGatherContext) {
- dispatch(setIsGatheringContext(true));
- }
-
- // Resolve context providers and construct new history
- let [selectedContextItems, selectedCode, content] =
- await resolveEditorContent(
- editorState,
- modifiers,
- ideMessenger,
- defaultContextProviders,
- dispatch,
- );
-
- // Automatically use currently open file
- if (!modifiers.noContext) {
- const usingFreeTrial = defaultModel?.provider === "free-trial";
-
- const currentFile = await ideMessenger.ide.getCurrentFile();
- if (currentFile) {
- let currentFileContents = currentFile.contents;
- if (usingFreeTrial) {
- currentFileContents = currentFile.contents
- .split("\n")
- .slice(0, 1000)
- .join("\n");
- }
- if (
- !selectedContextItems.find(
- (item) => item.uri?.value === currentFile.path,
- )
- ) {
- // don't add the file if it's already in the context items
- selectedContextItems.unshift({
- content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath(
- currentFile.path,
- await ideMessenger.ide.getWorkspaceDirs(),
- )}\n${currentFileContents}\n\`\`\``,
- name: `Active file: ${getBasename(currentFile.path)}`,
- description: currentFile.path,
- id: {
- itemId: currentFile.path,
- providerTitle: "file",
- },
- uri: {
- type: "file",
- value: currentFile.path,
- },
- });
- }
- }
- }
-
- await updateFileSymbolsFromContextItems(
- selectedContextItems,
- ideMessenger,
- dispatch,
- );
- if (promptPreamble) {
- if (typeof content === "string") {
- content = promptPreamble + content;
- } else {
- content[0].text = promptPreamble + content[0].text;
- }
- }
-
- const message: ChatMessage = {
- role: "user",
- content,
- };
-
- const historyItem: ChatHistoryItem = {
- message,
- contextItems: selectedContextItems,
- editorState,
- mode: "chat",
- isBeforeCheckpoint: false,
- checkpoint: {},
- isGatheringContext: false,
- };
-
- let newHistory: ChatHistoryItem[] = [
- ...history.slice(0, index),
- historyItem,
- ];
- const historyIndex = index || newHistory.length - 1;
- dispatch(
- setMessageAtIndex({
- message,
- index: historyIndex,
- contextItems: selectedContextItems,
- }),
- );
-
- // TODO: hacky way to allow rerender
- await new Promise((resolve) => setTimeout(resolve, 0));
-
- posthog.capture("step run", {
- step_name: "User Input",
- params: {},
- });
- posthog.capture("userInput", {});
-
- const messages = constructMessages(newHistory, defaultModel.model);
-
- // Determine if the input is a slash command
- let commandAndInput = getSlashCommandForInput(content);
-
- if (!commandAndInput) {
- await _streamNormalInput(messages);
- } else {
- const [slashCommand, commandInput] = commandAndInput;
-
- let updatedContextItems = [];
-
- posthog.capture("step run", {
- step_name: slashCommand.name,
- params: {},
- });
-
- await _streamSlashCommand(
- messages,
- slashCommand,
- commandInput,
- historyIndex,
- selectedCode,
- updatedContextItems,
- );
- }
- } catch (e: any) {
- dispatch(clearLastEmptyResponse());
- console.debug("Error streaming response: ", e);
- } finally {
- dispatch(setInactive());
- triggerSave(!save);
- }
- }
-
- return {
- streamResponse,
- };
-}
-
-export default useChatHandler;
diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx
index 32b4602d6..31322ce1d 100644
--- a/gui/src/hooks/useHistory.tsx
+++ b/gui/src/hooks/useHistory.tsx
@@ -1,6 +1,6 @@
import { Dispatch } from "@reduxjs/toolkit";
import { Session, SessionMetadata } from "core";
-import { stripImages } from "core/llm/images";
+import { renderChatMessage } from "core/util/messageContent";
import { useCallback, useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useLastSessionContext } from "../context/LastSessionContext";
@@ -72,7 +72,7 @@ function useHistory(dispatch: Dispatch) {
let newTitle =
currentTitle === "New Session"
? truncateText(
- stripImages(history[0].message.content)
+ renderChatMessage(history[0].message)
.split("\n")
.filter((l) => l.trim() !== "")
.slice(-1)[0] || "",
diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts
index 5697a94f6..66d96e1c0 100644
--- a/gui/src/hooks/useSetup.ts
+++ b/gui/src/hooks/useSetup.ts
@@ -1,24 +1,25 @@
-import { Dispatch } from "@reduxjs/toolkit";
import { useCallback, useContext, useEffect, useRef } from "react";
import { VSC_THEME_COLOR_VARS } from "../components";
import { IdeMessengerContext } from "../context/IdeMessenger";
-import {
- addContextItemsAtIndex,
- setInactive,
- setSelectedProfileId,
-} from "../redux/slices/sessionSlice";
+import { AppDispatch } from "../redux/store";
+
+import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { isJetBrains } from "../util";
import { setLocalStorage } from "../util/localStorage";
-import useChatHandler from "./useChatHandler";
-import { useWebviewListener } from "./useWebviewListener";
import { updateFileSymbolsFromContextItems } from "../util/symbols";
+import { useWebviewListener } from "./useWebviewListener";
import { useAppSelector } from "../redux/hooks";
import { setConfig, setConfigError } from "../redux/slices/configSlice";
import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import { updateDocsSuggestions } from "../redux/slices/miscSlice";
+import {
+ setSelectedProfileId,
+ setInactive,
+ addContextItemsAtIndex,
+} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
-function useSetup(dispatch: Dispatch) {
+function useSetup(dispatch: AppDispatch) {
const ideMessenger = useContext(IdeMessengerContext);
const history = useAppSelector((store) => store.session.messages);
const defaultModelTitle = useAppSelector(
@@ -79,7 +80,7 @@ function useSetup(dispatch: Dispatch) {
);
// Load symbols for chat on any session change
- const sessionId = useAppSelector((store) => store.session.id);
+ const sessionId = useAppSelector((state) => state.session.id);
const sessionIdRef = useRef("");
useEffect(() => {
@@ -128,8 +129,6 @@ function useSetup(dispatch: Dispatch) {
dispatch(updateDocsSuggestions(data));
});
- const { streamResponse } = useChatHandler(dispatch, ideMessenger);
-
// IDE event listeners
useWebviewListener(
"getWebviewHistoryLength",
@@ -160,10 +159,11 @@ function useSetup(dispatch: Dispatch) {
// TODO - remove?
useWebviewListener("submitMessage", async (data) => {
- streamResponse(
- data.message,
- { useCodebase: false, noContext: true },
- ideMessenger,
+ dispatch(
+ streamResponseThunk({
+ editorState: data.message,
+ modifiers: { useCodebase: false, noContext: true },
+ }),
);
});
diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts
index cc668c0c2..4c56dd8a6 100644
--- a/gui/src/pages/AddNewModel/configs/providers.ts
+++ b/gui/src/pages/AddNewModel/configs/providers.ts
@@ -137,6 +137,31 @@ export const providers: Partial> = {
...completionParamsInputsConfigs,
],
},
+ "function-network": {
+ title: "Function Network",
+ provider: "function-network",
+ refPage: "function-network",
+ description:
+ "Run open-source models on Function Network. Private, Affordable User-Owned AI",
+ icon: "function-network.png",
+ longDescription: `Function Network is a private, affordable user-owned AI platform that allows you to run open-source models. Experience bleeding-edge Generative AI models with limitless scalability, all powered by our distributed inference network.`,
+ tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource],
+ params: {
+ apiKey: "",
+ },
+ collectInputFor: [
+ {
+ inputType: "text",
+ key: "apiKey",
+ label: "API Key",
+ placeholder: "Enter your Function Network API key",
+ required: true,
+ },
+ ...completionParamsInputsConfigs,
+ ],
+ packages: [models.llama31Chat, models.deepseek],
+ apiKeyUrl: "https://function.network/join-waitlist",
+ },
azure: {
title: "Azure OpenAI",
provider: "azure",
diff --git a/gui/src/pages/edit/Edit.tsx b/gui/src/pages/edit/Edit.tsx
index 9f14a031e..89921bf94 100644
--- a/gui/src/pages/edit/Edit.tsx
+++ b/gui/src/pages/edit/Edit.tsx
@@ -1,26 +1,26 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/core";
import { InputModifiers, RangeInFileWithContents } from "core";
-import { stripImages } from "core/llm/images";
+import { stripImages } from "core/util/messageContent";
import { useCallback, useContext, useEffect, useMemo } from "react";
-import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
+import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
+import { ToolbarOptions } from "../../components/mainInput/InputToolbar";
import { NewSessionButton } from "../../components/mainInput/NewSessionButton";
import resolveEditorContent from "../../components/mainInput/resolveInput";
import TipTapEditor from "../../components/mainInput/TipTapEditor";
+import StepContainer from "../../components/StepContainer";
+import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { setEditDone, submitEdit } from "../../redux/slices/editModeState";
-import useChatHandler from "../../hooks/useChatHandler";
-import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
-import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
-import StepContainer from "../../components/StepContainer";
-import getMultifileEditPrompt from "./getMultifileEditPrompt";
+import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import CodeToEdit from "./CodeToEdit";
+import getMultifileEditPrompt from "./getMultifileEditPrompt";
+import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import {
clearCodeToEdit,
selectApplyStateBySessionId,
} from "../../redux/slices/sessionSlice";
-import { useAppSelector } from "../../redux/hooks";
const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [
"codebase",
@@ -35,14 +35,13 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [
];
export default function Edit() {
- const dispatch = useDispatch();
+ const dispatch = useAppDispatch();
const navigate = useNavigate();
const ideMessenger = useContext(IdeMessengerContext);
- const { streamResponse } = useChatHandler(dispatch, ideMessenger);
const editModeState = useAppSelector((state) => state.editModeState);
const codeToEdit = useAppSelector((state) => state.session.codeToEdit);
const availableContextProviders = useAppSelector(
- (store) => store.config.config.contextProviders,
+ (state) => state.config.config.contextProviders,
);
const filteredContextProviders = useMemo(() => {
@@ -88,11 +87,12 @@ export default function Edit() {
editModeState.editStatus === "streaming" ||
editModeState.editStatus === "accepting";
- const toolbarOptions = {
+ const toolbarOptions: ToolbarOptions = {
hideAddContext: false,
hideImageUpload: false,
hideUseCodebase: true,
hideSelectModel: false,
+ hideTools: true,
enterText: isStreaming ? "Retry" : "Edit",
};
@@ -138,12 +138,12 @@ export default function Edit() {
} else {
const promptPreamble = getMultifileEditPrompt(codeToEdit);
- streamResponse(
- editorState,
- modifiers,
- ideMessenger,
- undefined,
- promptPreamble,
+ dispatch(
+ streamResponseThunk({
+ editorState,
+ modifiers,
+ promptPreamble,
+ }),
);
}
}
@@ -184,11 +184,12 @@ export default function Edit() {
{item.message.role === "user" ? (
{
- streamResponse(
- editorState,
- modifiers,
- ideMessenger,
- index,
+ dispatch(
+ streamResponseThunk({
+ editorState,
+ modifiers,
+ index,
+ }),
);
}}
isLastUserInput={isLastUserInput(index)}
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx
index 857476e39..ebcc5706f 100644
--- a/gui/src/pages/gui/Chat.tsx
+++ b/gui/src/pages/gui/Chat.tsx
@@ -5,19 +5,12 @@ import {
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { JSONContent } from "@tiptap/react";
-import { InputModifiers } from "core";
+import { InputModifiers, ToolCallState } from "core";
+import { streamResponse } from "core/llm/stream";
import { usePostHog } from "posthog-js/react";
-import {
- Fragment,
- useCallback,
- useContext,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
+import { useCallback, useContext, useEffect, useRef, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
-import { useDispatch } from "react-redux";
+import { useSelector } from "react-redux";
import styled from "styled-components";
import {
Button,
@@ -26,8 +19,9 @@ import {
vscBackground,
} from "../../components";
import { ChatScrollAnchor } from "../../components/ChatScrollAnchor";
-import StepContainer from "../../components/StepContainer";
+import { useFindWidget } from "../../components/find/FindWidget";
import TimelineItem from "../../components/gui/TimelineItem";
+import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks";
import ContinueInputBox from "../../components/mainInput/ContinueInputBox";
import { NewSessionButton } from "../../components/mainInput/NewSessionButton";
import { TutorialCard } from "../../components/mainInput/TutorialCard";
@@ -35,21 +29,18 @@ import {
OnboardingCard,
useOnboardingCard,
} from "../../components/OnboardingCard";
+import StepContainer from "../../components/StepContainer";
import { IdeMessengerContext } from "../../context/IdeMessenger";
-import useChatHandler from "../../hooks/useChatHandler";
import useHistory from "../../hooks/useHistory";
import { useTutorialCard } from "../../hooks/useTutorialCard";
import { useWebviewListener } from "../../hooks/useWebviewListener";
+import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall";
import {
clearLastEmptyResponse,
newSession,
setInactive,
} from "../../redux/slices/sessionSlice";
-import {
- setDialogEntryOn,
- setDialogMessage,
- setShowDialog,
-} from "../../redux/slices/uiSlice";
+import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import {
getFontSize,
getMetaKeyLabel,
@@ -58,10 +49,17 @@ import {
import { FREE_TRIAL_LIMIT_REQUESTS } from "../../util/freeTrial";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import ConfigErrorIndicator from "./ConfigError";
-import ChatIndexingPeeks from "../../components/indexing/ChatIndexingPeeks";
-import { useFindWidget } from "../../components/find/FindWidget";
+import { ToolCallDiv } from "./ToolCallDiv";
+import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv";
+import ToolOutput from "./ToolCallDiv/ToolOutput";
+import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectDefaultModel } from "../../redux/slices/configSlice";
-import { useAppSelector } from "../../redux/hooks";
+import {
+ setDialogMessage,
+ setDialogEntryOn,
+ setShowDialog,
+} from "../../redux/slices/uiSlice";
+import { RootState } from "../../redux/store";
const StopButton = styled.div`
background-color: ${vscBackground};
@@ -95,7 +93,7 @@ const StepsDiv = styled.div`
}
.thread-message {
- margin: 8px 4px 0 4px;
+ margin: 0px 4px 0 4px;
}
`;
@@ -110,6 +108,7 @@ function fallbackRender({ error, resetErrorBoundary }: any) {
>
Something went wrong:
{error.message}
+ {error.stack}
@@ -120,9 +119,8 @@ function fallbackRender({ error, resetErrorBoundary }: any) {
export function Chat() {
const posthog = usePostHog();
- const dispatch = useDispatch();
+ const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
- const { streamResponse } = useChatHandler(dispatch, ideMessenger);
const onboardingCard = useOnboardingCard();
const { showTutorialCard, closeTutorialCard } = useTutorialCard();
const defaultModel = useAppSelector(selectDefaultModel);
@@ -139,6 +137,10 @@ export function Chat() {
const { saveSession, getLastSessionId, loadLastSession } =
useHistory(dispatch);
+ const toolCallState = useSelector
(
+ selectCurrentToolCall,
+ );
+
const snapToBottom = useCallback(() => {
if (!stepsDivRef.current) return;
const elem = stepsDivRef.current;
@@ -176,7 +178,7 @@ export function Chat() {
isMetaEquivalentKeyPressed(e) &&
!e.shiftKey
) {
- dispatch(setInactive());
+ // dispatch(cancelGeneration()); TODO!!!
}
};
window.addEventListener("keydown", listener);
@@ -221,7 +223,7 @@ export function Chat() {
}
}
- streamResponse(editorState, modifiers, ideMessenger);
+ dispatch(streamResponseThunk({ editorState, modifiers }));
// Increment localstorage counter for popup
const currentCount = getLocalStorage("mainTextEntryCounter");
@@ -326,7 +328,12 @@ export function Chat() {
>
{highlights}
{messages.map((item, index: number) => (
-
+
{
@@ -336,13 +343,36 @@ export function Chat() {
{item.message.role === "user" ? (
{
- streamResponse(editorState, modifiers, ideMessenger, index);
+ dispatch(
+ streamResponseThunk({ editorState, modifiers, index }),
+ );
}}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
editorState={item.editorState}
contextItems={item.contextItems}
/>
+ ) : item.message.role === "tool" ? (
+
+ ) : item.message.role === "assistant" &&
+ item.message.toolCalls &&
+ item.toolCallState ? (
+
+ {item.message.toolCalls?.map((toolCall, i) => {
+ return (
+
+
+
+ );
+ })}
+
) : (
)}
-
+
))}
)}
+
+ {toolCallState?.status === "generated" && }
+ ) : null;
+}
diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx
new file mode 100644
index 000000000..d55055b03
--- /dev/null
+++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx
@@ -0,0 +1,31 @@
+import { ToolCall, ToolCallState } from "core";
+import { CreateFile } from "./CreateFile";
+import { RunTerminalCommand } from "./RunTerminalCommand";
+
+function FunctionSpecificToolCallDiv({
+ toolCall,
+ toolCallState,
+}: {
+ toolCall: ToolCall;
+ toolCallState: ToolCallState;
+}) {
+ const args = toolCallState.parsedArgs;
+
+ switch (toolCall.function.name) {
+ case "create_new_file":
+ return (
+
+ );
+ case "run_terminal_command":
+ return (
+
+ );
+ default:
+ return null;
+ }
+}
+
+export default FunctionSpecificToolCallDiv;
diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx
new file mode 100644
index 000000000..35fc0e54f
--- /dev/null
+++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx
@@ -0,0 +1,16 @@
+import { ToolCallState } from "core";
+import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview";
+
+interface RunTerminalCommandToolCallProps {
+ command: string;
+ toolCallState: ToolCallState;
+}
+
+export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
+ return (
+
+ );
+}
diff --git a/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx
new file mode 100644
index 000000000..e02eaca8f
--- /dev/null
+++ b/gui/src/pages/gui/ToolCallDiv/ThreadDiv.tsx
@@ -0,0 +1,78 @@
+import { Tool, ToolCall, ToolCallState } from "core";
+import Mustache from "mustache";
+import { useSelector } from "react-redux";
+import styled from "styled-components";
+import { RootState } from "../../../redux/store";
+
+interface ThreadDivProps {
+ children: React.ReactNode;
+ icon: React.ReactNode;
+ toolCall: ToolCall;
+ toolCallState: ToolCallState;
+ reactKey: string;
+}
+
+const Container = styled.div`
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ position: relative;
+ padding: 8px;
+ padding-bottom: 0;
+`;
+
+const ChildrenDiv = styled.div``;
+
+const W = 16;
+
+const HeaderDiv = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+`;
+
+export function ThreadDiv(props: ThreadDivProps) {
+ const availableTools = useSelector(
+ (state: RootState) => state.state.config.tools,
+ );
+
+ function renderWouldLikeToMessage(
+ tool: Tool | undefined,
+ toolCallState: ToolCallState,
+ ): string {
+ if (!tool) return "";
+
+ const rendered = Mustache.render(
+ tool.wouldLikeTo,
+ toolCallState.parsedArgs,
+ );
+ return rendered;
+ }
+
+ return (
+
+
+
+ {props.icon}
+
+ Continue wants to{" "}
+ {renderWouldLikeToMessage(
+ availableTools.find(
+ (tool) => props.toolCall.function.name === tool.function.name,
+ ),
+ props.toolCallState,
+ )}
+
+ {props.children}
+
+ );
+}
diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx
new file mode 100644
index 000000000..d088091ca
--- /dev/null
+++ b/gui/src/pages/gui/ToolCallDiv/ToolCallButtonsDiv.tsx
@@ -0,0 +1,91 @@
+import { useSelector } from "react-redux";
+import styled from "styled-components";
+import {
+ defaultBorderRadius,
+ lightGray,
+ vscButtonBackground,
+ vscButtonForeground,
+} from "../../../components";
+import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner";
+import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall";
+import { useAppDispatch } from "../../../redux/store";
+import { callTool } from "../../../redux/thunks/callTool";
+import { cancelTool } from "../../../redux/thunks/cancelTool";
+
+const ButtonContainer = styled.div`
+ display: flex;
+ gap: 8px;
+ margin-top: 12px;
+ margin: 8px;
+`;
+
+const Button = styled.button`
+ padding: 5px;
+ border-radius: ${defaultBorderRadius};
+ flex: 1;
+
+ &:hover {
+ cursor: pointer;
+ opacity: 0.8;
+ }
+`;
+
+const AcceptButton = styled(Button)`
+ color: ${vscButtonForeground};
+ border: none;
+ background-color: ${vscButtonBackground};
+ color: ${vscButtonForeground};
+
+ &:hover {
+ cursor: pointer;
+ }
+`;
+
+const RejectButton = styled(Button)`
+ color: ${lightGray};
+ border: 1px solid ${lightGray};
+ background-color: transparent;
+`;
+
+interface ToolCallButtonsProps {}
+
+export function ToolCallButtons(props: ToolCallButtonsProps) {
+ const dispatch = useAppDispatch();
+ const toolCallState = useSelector(selectCurrentToolCall);
+
+ if (!toolCallState) {
+ return null;
+ }
+
+ return (
+ <>
+
+ {toolCallState.status === "generating" ? (
+
+ Thinking...
+
+ ) : toolCallState.status === "generated" ? (
+ <>
+ dispatch(cancelTool())}>
+ Cancel
+
+ dispatch(callTool())}>
+ Continue
+
+ >
+ ) : toolCallState.status === "calling" ? (
+
+ Loading...
+
+
+ ) : null}
+
+ >
+ );
+}
diff --git a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx
new file mode 100644
index 000000000..46057e90c
--- /dev/null
+++ b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx
@@ -0,0 +1,24 @@
+import { ContextItemWithId } from "core";
+import ContextItemsPeek from "../../../components/mainInput/ContextItemsPeek";
+
+interface ToolOutputProps {
+ contextItems: ContextItemWithId[];
+ toolCallId: string;
+}
+
+function ToolOutput(props: ToolOutputProps) {
+ if (props.contextItems.length === 0) {
+ return null;
+ }
+
+ return (
+
+
+
+ );
+}
+
+export default ToolOutput;
diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx
new file mode 100644
index 000000000..e1745c459
--- /dev/null
+++ b/gui/src/pages/gui/ToolCallDiv/index.tsx
@@ -0,0 +1,46 @@
+import {
+ ArrowRightIcon,
+ CheckIcon,
+ XMarkIcon,
+} from "@heroicons/react/24/outline";
+import { ToolCall, ToolCallState, ToolStatus } from "core";
+import { vscButtonBackground } from "../../../components";
+import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner";
+import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv";
+import { ThreadDiv } from "./ThreadDiv";
+
+interface ToolCallDivProps {
+ toolCall: ToolCall;
+ toolCallState: ToolCallState;
+ reactKey: string;
+}
+
+export function ToolCallDiv(props: ToolCallDivProps) {
+ function getIcon(state: ToolStatus) {
+ switch (state) {
+ case "generating":
+ case "calling":
+ return ;
+ case "generated":
+ return ;
+ case "done":
+ return ;
+ case "canceled":
+ return ;
+ }
+ }
+
+ return (
+
+
+
+ );
+}
diff --git a/gui/src/redux/selectors/selectCurrentToolCall.ts b/gui/src/redux/selectors/selectCurrentToolCall.ts
new file mode 100644
index 000000000..cd0b47f50
--- /dev/null
+++ b/gui/src/redux/selectors/selectCurrentToolCall.ts
@@ -0,0 +1,10 @@
+import { createSelector } from "@reduxjs/toolkit";
+import { RootState } from "../store";
+import { findCurrentToolCall } from "../util";
+
+export const selectCurrentToolCall = createSelector(
+ (store: RootState) => store.state.history,
+ (history) => {
+ return findCurrentToolCall(history);
+ },
+);
diff --git a/gui/src/redux/selectors/selectLastToolCall.ts b/gui/src/redux/selectors/selectLastToolCall.ts
new file mode 100644
index 000000000..5509ab476
--- /dev/null
+++ b/gui/src/redux/selectors/selectLastToolCall.ts
@@ -0,0 +1,19 @@
+import { createSelector } from "@reduxjs/toolkit";
+import { ToolCallState } from "core";
+import { RootState } from "../store";
+
+export const selectLastToolCall = createSelector(
+ [(store: RootState) => store.state.history],
+ (history): ToolCallState | null => {
+ let lastToolCallHistoryItem = null;
+ for (let i = history.length - 1; i >= 0; i--) {
+ const item = history[i];
+ if (item.message.role === "assistant" && item.message.toolCalls?.length) {
+ lastToolCallHistoryItem = item;
+ break;
+ }
+ }
+ if (!lastToolCallHistoryItem) return null;
+ return lastToolCallHistoryItem.toolCallState;
+ },
+);
diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts
index 070b67bd0..4751fed5c 100644
--- a/gui/src/redux/slices/uiSlice.ts
+++ b/gui/src/redux/slices/uiSlice.ts
@@ -1,28 +1,50 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
+import { Tool } from "core";
+import { BuiltInToolNames } from "core/tools/builtIn";
import {
defaultOnboardingCardState,
OnboardingCardState,
} from "../../components/OnboardingCard";
+type ToolSetting =
+ | "allowedWithPermission"
+ | "allowedWithoutPermission"
+ | "disabled";
+
type UIState = {
showDialog: boolean;
dialogMessage: string | JSX.Element | undefined;
dialogEntryOn: boolean;
onboardingCard: OnboardingCardState;
+ shouldAddFileForEditing: boolean;
+ useTools: boolean;
+ toolSettings: { [toolName: string]: ToolSetting };
ttsActive: boolean;
};
-const initialState: UIState = {
- showDialog: false,
- ttsActive: false,
- dialogMessage: "",
- dialogEntryOn: false,
- onboardingCard: defaultOnboardingCardState,
-};
+export const DEFAULT_TOOL_SETTING: ToolSetting = "allowedWithPermission";
export const uiSlice = createSlice({
- name: "uiState",
- initialState,
+ name: "ui",
+ initialState: {
+ showDialog: false,
+ dialogMessage: "",
+ dialogEntryOn: false,
+ onboardingCard: defaultOnboardingCardState,
+ shouldAddFileForEditing: false,
+ ttsActive: false,
+ useTools: false,
+ toolSettings: {
+ [BuiltInToolNames.ReadFile]: "allowedWithoutPermission",
+ [BuiltInToolNames.CreateNewFile]: "allowedWithPermission",
+ [BuiltInToolNames.RunTerminalCommand]: "allowedWithPermission",
+ [BuiltInToolNames.ViewSubdirectory]: "allowedWithoutPermission",
+ [BuiltInToolNames.ViewRepoMap]: "allowedWithoutPermission",
+ [BuiltInToolNames.ExactSearch]: "allowedWithoutPermission",
+ [BuiltInToolNames.SearchWeb]: "allowedWithoutPermission",
+ [BuiltInToolNames.ViewDiff]: "allowedWithoutPermission",
+ },
+ } as UIState,
reducers: {
setOnboardingCard: (
state,
@@ -45,6 +67,33 @@ export const uiSlice = createSlice({
setShowDialog: (state, action: PayloadAction) => {
state.showDialog = action.payload;
},
+ // Tools
+ toggleUseTools: (state) => {
+ state.useTools = !state.useTools;
+ },
+ addTool: (state, action: PayloadAction) => {
+ state.toolSettings[action.payload.function.name] = action.payload.readonly
+ ? "allowedWithoutPermission"
+ : "allowedWithPermission";
+ },
+ toggleToolSetting: (state, action: PayloadAction) => {
+ const setting = state.toolSettings[action.payload];
+
+ switch (setting) {
+ case "allowedWithPermission":
+ state.toolSettings[action.payload] = "allowedWithoutPermission";
+ break;
+ case "allowedWithoutPermission":
+ state.toolSettings[action.payload] = "disabled";
+ break;
+ case "disabled":
+ state.toolSettings[action.payload] = "allowedWithPermission";
+ break;
+ default:
+ state.toolSettings[action.payload] = DEFAULT_TOOL_SETTING;
+ break;
+ }
+ },
setTTSActive: (state, { payload }: PayloadAction) => {
state.ttsActive = payload;
},
@@ -56,6 +105,9 @@ export const {
setDialogMessage,
setDialogEntryOn,
setShowDialog,
+ toggleUseTools,
+ toggleToolSetting,
+ addTool,
setTTSActive,
} = uiSlice.actions;
diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts
index 38483dfdf..6a9b0f5d8 100644
--- a/gui/src/redux/store.ts
+++ b/gui/src/redux/store.ts
@@ -1,14 +1,15 @@
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import miscReducer from "./slices/miscSlice";
-import sessionReducer from "./slices/sessionSlice";
-import uiReducer from "./slices/uiSlice";
import { persistReducer, persistStore } from "redux-persist";
import { createFilter } from "redux-persist-transform-filter";
import autoMergeLevel2 from "redux-persist/lib/stateReconciler/autoMergeLevel2";
import storage from "redux-persist/lib/storage";
+import { IdeMessenger, IIdeMessenger } from "../context/IdeMessenger";
import editModeStateReducer from "./slices/editModeState";
import configReducer from "./slices/configSlice";
import indexingReducer from "./slices/indexingSlice";
+import sessionReducer from "./slices/sessionSlice";
+import uiReducer from "./slices/uiSlice";
export interface ChatMessage {
role: "system" | "user" | "assistant";
@@ -23,12 +24,9 @@ const rootReducer = combineReducers({
config: configReducer,
indexing: indexingReducer,
});
-
-export type RootState = ReturnType;
-export type AppDispatch = typeof store.dispatch;
-
const saveSubsetFilters = [
createFilter("session", ["history", "sessionId", "defaultModelTitle"]),
+ // Don't persist any of the edit state for now
createFilter("editModeState", []),
];
@@ -52,14 +50,30 @@ const persistedReducer = persistReducer(persistConfig, rootReducer);
export function setupStore() {
return configureStore({
- reducer: persistedReducer,
+ // persistedReducer causes type errors with async thunks
+ reducer: persistedReducer as unknown as typeof rootReducer,
+ // reducer: rootReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: false,
+ thunk: {
+ extraArgument: {
+ ideMessenger: new IdeMessenger(),
+ },
+ },
}),
});
}
+export type ThunkApiType = {
+ state: RootState;
+ extra: { ideMessenger: IIdeMessenger };
+};
+
export const store = setupStore();
+export type RootState = ReturnType;
+
+export type AppDispatch = typeof store.dispatch;
+
export const persistor = persistStore(store);
diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts
new file mode 100644
index 000000000..b022b3497
--- /dev/null
+++ b/gui/src/redux/thunks/callTool.ts
@@ -0,0 +1,46 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
+import {
+ acceptToolCall,
+ setCalling,
+ setToolCallOutput,
+} from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
+
+export const callTool = createAsyncThunk(
+ "chat/callTool",
+ async (_, { dispatch, extra, getState }) => {
+ const state = getState();
+ const toolCallState = selectCurrentToolCall(state);
+
+ console.log("calling tool", toolCallState.toolCall);
+ if (!toolCallState) {
+ return;
+ }
+
+ if (toolCallState.status !== "generated") {
+ return;
+ }
+
+ dispatch(setCalling());
+
+ const result = await extra.ideMessenger.request("tools/call", {
+ toolCall: toolCallState.toolCall,
+ });
+
+ if (result.status === "success") {
+ const contextItems = result.content.contextItems;
+ dispatch(setToolCallOutput(contextItems));
+ dispatch(acceptToolCall());
+
+ // Send to the LLM to continue the conversation
+ dispatch(
+ streamResponseAfterToolCall({
+ toolCallId: toolCallState.toolCall.id,
+ toolOutput: contextItems,
+ }),
+ );
+ }
+ },
+);
diff --git a/gui/src/redux/thunks/cancelTool.ts b/gui/src/redux/thunks/cancelTool.ts
new file mode 100644
index 000000000..c93c4585c
--- /dev/null
+++ b/gui/src/redux/thunks/cancelTool.ts
@@ -0,0 +1,78 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
+import {
+ cancelToolCall,
+ setCalling,
+ setToolCallOutput,
+} from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
+
+export const cancelTool = createAsyncThunk(
+ "chat/callTool",
+ async (_, { dispatch, extra, getState }) => {
+ const state = getState();
+ const toolCallState = selectCurrentToolCall(state);
+
+ if (!toolCallState) {
+ return;
+ }
+
+ if (toolCallState.status !== "generated") {
+ return;
+ }
+
+ dispatch(cancelToolCall());
+
+ dispatch(
+ streamResponseAfterToolCall({
+ toolCallId: toolCallState.toolCallId,
+ toolOutput: [
+ {
+ name: "Tool Cancelled",
+ description: "Tool Cancelled",
+ content:
+ "The tool call was cancelled by the user. Please try something else or request further instructions.",
+ hidden: true,
+ },
+ ],
+ }),
+ );
+ },
+);
+
+export const callTool = createAsyncThunk(
+ "chat/callTool",
+ async (_, { dispatch, extra, getState }) => {
+ const state = getState();
+ const toolCallState = selectCurrentToolCall(state);
+
+ console.log("calling tool", toolCallState.toolCall);
+ if (!toolCallState) {
+ return;
+ }
+
+ if (toolCallState.status !== "generated") {
+ return;
+ }
+
+ dispatch(setCalling());
+
+ const result = await extra.ideMessenger.request("tools/call", {
+ toolCall: toolCallState.toolCall,
+ });
+
+ if (result.status === "success") {
+ const contextItems = result.content.contextItems;
+ dispatch(setToolCallOutput(contextItems));
+
+ // Send to the LLM to continue the conversation
+ dispatch(
+ streamResponseAfterToolCall({
+ toolCallId: toolCallState.toolCall.id,
+ toolOutput: contextItems,
+ }),
+ );
+ }
+ },
+);
diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts
new file mode 100644
index 000000000..409004e08
--- /dev/null
+++ b/gui/src/redux/thunks/gatherContext.ts
@@ -0,0 +1,119 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import { JSONContent } from "@tiptap/core";
+import {
+ ContextItemWithId,
+ InputModifiers,
+ MessageContent,
+ RangeInFile,
+} from "core";
+import { getBasename, getRelativePath } from "core/util";
+import resolveEditorContent, {
+ hasSlashCommandOrContextProvider,
+} from "../../components/mainInput/resolveInput";
+import { updateFileSymbolsFromContextItems } from "../../util/symbols";
+import { defaultModelSelector } from "../selectors/modelSelectors";
+import { setIsGatheringContext } from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+
+export const gatherContext = createAsyncThunk<
+ {
+ selectedContextItems: ContextItemWithId[];
+ selectedCode: RangeInFile[];
+ content: MessageContent;
+ },
+ {
+ editorState: JSONContent;
+ modifiers: InputModifiers;
+ promptPreamble?: string;
+ },
+ ThunkApiType
+>(
+ "chat/gatherContext",
+ async (
+ { modifiers, editorState, promptPreamble },
+ { dispatch, extra, getState },
+ ) => {
+ const state = getState();
+ const defaultModel = defaultModelSelector(state);
+ const defaultContextProviders =
+ state.state.config.experimental?.defaultContext ?? [];
+
+ // Resolve context providers and construct new history
+ const shouldGatherContext =
+ modifiers.useCodebase || hasSlashCommandOrContextProvider(editorState);
+
+ if (shouldGatherContext) {
+ dispatch(
+ setIsGatheringContext({
+ isGathering: true,
+ gatheringMessage: "Gathering Context",
+ }),
+ );
+ }
+
+ let [selectedContextItems, selectedCode, content] =
+ await resolveEditorContent(
+ editorState,
+ modifiers,
+ extra.ideMessenger,
+ defaultContextProviders,
+ dispatch,
+ );
+
+ // Automatically use currently open file
+ if (!modifiers.noContext) {
+ const usingFreeTrial = defaultModel?.provider === "free-trial";
+
+ const currentFile = await extra.ideMessenger.ide.getCurrentFile();
+ if (currentFile) {
+ let currentFileContents = currentFile.contents;
+ if (usingFreeTrial) {
+ currentFileContents = currentFile.contents
+ .split("\n")
+ .slice(0, 1000)
+ .join("\n");
+ }
+ if (
+ !selectedContextItems.find(
+ (item) => item.uri?.value === currentFile.path,
+ )
+ ) {
+ // don't add the file if it's already in the context items
+ selectedContextItems.unshift({
+ content: `The following file is currently open. Don't reference it if it's not relevant to the user's message.\n\n\`\`\`${getRelativePath(
+ currentFile.path,
+ await extra.ideMessenger.ide.getWorkspaceDirs(),
+ )}\n${currentFileContents}\n\`\`\``,
+ name: `Active file: ${getBasename(currentFile.path)}`,
+ description: currentFile.path,
+ id: {
+ itemId: currentFile.path,
+ providerTitle: "file",
+ },
+ uri: {
+ type: "file",
+ value: currentFile.path,
+ },
+ });
+ }
+ }
+ }
+
+ await updateFileSymbolsFromContextItems(
+ selectedContextItems,
+ extra.ideMessenger,
+ dispatch,
+ );
+
+ if (promptPreamble) {
+ if (typeof content === "string") {
+ content = promptPreamble + content;
+ } else {
+ content[0].text = promptPreamble + content[0].text;
+ }
+ }
+
+ // dispatch(addContextItems(contextItems));
+ return { selectedContextItems, selectedCode, content };
+ },
+);
diff --git a/gui/src/redux/thunks/handleErrors.ts b/gui/src/redux/thunks/handleErrors.ts
new file mode 100644
index 000000000..6d7afb632
--- /dev/null
+++ b/gui/src/redux/thunks/handleErrors.ts
@@ -0,0 +1,18 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import { setInactive } from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+
+export const handleErrors = createAsyncThunk<
+ void,
+ () => Promise,
+ ThunkApiType
+>("chat/handleErrors", async (runStream, { dispatch, extra }) => {
+ try {
+ await runStream();
+ } catch (e: any) {
+ console.debug("Error streaming response: ", e);
+ } finally {
+ dispatch(setInactive());
+ // triggerSave(!save); TODO
+ }
+});
diff --git a/gui/src/redux/thunks/resetStateForNewMessage.ts b/gui/src/redux/thunks/resetStateForNewMessage.ts
new file mode 100644
index 000000000..e7f534e42
--- /dev/null
+++ b/gui/src/redux/thunks/resetStateForNewMessage.ts
@@ -0,0 +1,11 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import { resetNextCodeBlockToApplyIndex } from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+
+export const resetStateForNewMessage = createAsyncThunk<
+ void,
+ undefined,
+ ThunkApiType
+>("chat/resetStateForNewMessage", async (_, { dispatch }) => {
+ dispatch(resetNextCodeBlockToApplyIndex());
+});
diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts
new file mode 100644
index 000000000..d17f2d870
--- /dev/null
+++ b/gui/src/redux/thunks/streamNormalInput.ts
@@ -0,0 +1,91 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import { ChatMessage, PromptLog } from "core";
+import { defaultModelSelector } from "../selectors/modelSelectors";
+import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
+import {
+ abortStream,
+ addPromptCompletionPair,
+ clearLastEmptyResponse,
+ setToolGenerated,
+ streamUpdate,
+} from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+import { callTool } from "./callTool";
+
+export const streamNormalInput = createAsyncThunk<
+ void,
+ ChatMessage[],
+ ThunkApiType
+>("chat/streamNormalInput", async (messages, { dispatch, extra, getState }) => {
+ try {
+ // Gather state
+ const state = getState();
+ const defaultModel = defaultModelSelector(state);
+ const toolSettings = state.uiState.toolSettings;
+ const streamAborter = state.state.streamAborter;
+ const useTools = state.uiState.useTools;
+
+ if (!defaultModel) {
+ throw new Error("Default model not defined");
+ }
+
+ // Send request
+ const gen = extra.ideMessenger.llmStreamChat(
+ defaultModel.title,
+ streamAborter.signal,
+ messages,
+ {
+ tools: useTools
+ ? Object.keys(toolSettings)
+ .filter((tool) => toolSettings[tool] !== "disabled")
+ .map((toolName) =>
+ state.state.config.tools.find(
+ (tool) => tool.function.name === toolName,
+ ),
+ )
+ .filter(Boolean)
+ : undefined,
+ },
+ );
+
+ // Stream response
+ let next = await gen.next();
+ while (!next.done) {
+ if (!getState().state.active) {
+ dispatch(abortStream());
+ break;
+ }
+
+ const update = next.value as ChatMessage;
+ dispatch(streamUpdate(update));
+ next = await gen.next();
+
+ // There has been lag when streaming tool calls. This is a temporary solution
+ if (update.role === "assistant" && update.toolCalls) {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ }
+
+ // Attach prompt log
+ let returnVal = next.value as PromptLog;
+ if (returnVal) {
+ dispatch(addPromptCompletionPair([returnVal]));
+ }
+
+ // If it's a tool call that is automatically accepted, we should call it
+ const toolCallState = selectCurrentToolCall(getState());
+ if (toolCallState) {
+ dispatch(setToolGenerated());
+
+ if (
+ toolSettings[toolCallState.toolCall.function.name] ===
+ "allowedWithoutPermission"
+ ) {
+ await dispatch(callTool());
+ }
+ }
+ } catch (e) {
+ // If there's an error, we should clear the response so there aren't two input boxes
+ dispatch(clearLastEmptyResponse());
+ }
+});
diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts
new file mode 100644
index 000000000..c1f6ba4d8
--- /dev/null
+++ b/gui/src/redux/thunks/streamResponse.ts
@@ -0,0 +1,157 @@
+import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
+import { JSONContent } from "@tiptap/core";
+import {
+ ChatHistoryItem,
+ ChatMessage,
+ InputModifiers,
+ MessageContent,
+ SlashCommandDescription,
+} from "core";
+import { constructMessages } from "core/llm/constructMessages";
+import { renderChatMessage } from "core/util/messageContent";
+import posthog from "posthog-js";
+import { defaultModelSelector } from "../selectors/modelSelectors";
+import {
+ initNewActiveMessage,
+ resubmitAtIndex,
+ setCurCheckpointIndex,
+ setMessageAtIndex,
+} from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+import { gatherContext } from "./gatherContext";
+import { handleErrors } from "./handleErrors";
+import { resetStateForNewMessage } from "./resetStateForNewMessage";
+import { streamNormalInput } from "./streamNormalInput";
+import { streamSlashCommand } from "./streamSlashCommand";
+
+const getSlashCommandForInput = (
+ input: MessageContent,
+ slashCommands: SlashCommandDescription[],
+): [SlashCommandDescription, string] | undefined => {
+ let slashCommand: SlashCommandDescription | undefined;
+ let slashCommandName: string | undefined;
+
+ let lastText =
+ typeof input === "string"
+ ? input
+ : input.filter((part) => part.type === "text").slice(-1)[0]?.text || "";
+
+ if (lastText.startsWith("/")) {
+ slashCommandName = lastText.split(" ")[0].substring(1);
+ slashCommand = slashCommands.find(
+ (command) => command.name === slashCommandName,
+ );
+ }
+ if (!slashCommand || !slashCommandName) {
+ return undefined;
+ }
+
+ // Convert to actual slash command object with runnable function
+ return [slashCommand, renderChatMessage({ role: "user", content: input })];
+};
+
+export const streamResponseThunk = createAsyncThunk<
+ void,
+ {
+ editorState: JSONContent;
+ modifiers: InputModifiers;
+ index?: number;
+ promptPreamble?: string;
+ },
+ ThunkApiType
+>(
+ "chat/streamResponse",
+ async (
+ { editorState, modifiers, index, promptPreamble },
+ { dispatch, extra, getState },
+ ) => {
+ await dispatch(
+ handleErrors(async () => {
+ const state = getState();
+ const defaultModel = defaultModelSelector(state);
+ const slashCommands = state.state.config.slashCommands || [];
+ const inputIndex = index ?? state.state.history.length;
+
+ if (typeof index === "number") {
+ dispatch(resubmitAtIndex({ index, editorState }));
+ } else {
+ dispatch(initNewActiveMessage({ editorState }));
+ }
+
+ resetStateForNewMessage();
+
+ if (index) {
+ dispatch(setCurCheckpointIndex(Math.floor(index / 2)));
+ }
+
+ const result = await dispatch(
+ gatherContext({
+ editorState,
+ modifiers,
+ promptPreamble,
+ }),
+ );
+ const unwrapped = unwrapResult(result);
+ const { selectedContextItems, selectedCode, content } = unwrapped;
+
+ // Add the message to the history
+ const message: ChatMessage = {
+ role: "user",
+ content,
+ };
+ const historyItem: ChatHistoryItem = {
+ message,
+ contextItems: selectedContextItems,
+ editorState,
+ };
+
+ dispatch(
+ setMessageAtIndex({
+ message,
+ index: inputIndex,
+ contextItems: selectedContextItems,
+ }),
+ );
+
+ // Construct messages from updated history
+ const updatedHistory = getState().state.history;
+ const messages = constructMessages(updatedHistory, defaultModel.model);
+
+ posthog.capture("step run", {
+ step_name: "User Input",
+ params: {},
+ });
+ posthog.capture("userInput", {});
+
+ // Determine if the input is a slash command
+ let commandAndInput = getSlashCommandForInput(content, slashCommands);
+
+ if (!commandAndInput) {
+ await dispatch(streamNormalInput(messages));
+ } else {
+ const [slashCommand, commandInput] = commandAndInput;
+ let updatedContextItems = [];
+ posthog.capture("step run", {
+ step_name: slashCommand.name,
+ params: {},
+ });
+
+ // if (slashCommand.name === "multifile-edit") {
+ // dispatch(setIsInMultifileEdit(true));
+ // }
+
+ await dispatch(
+ streamSlashCommand({
+ messages,
+ slashCommand,
+ input: commandInput,
+ historyIndex: inputIndex,
+ selectedCode,
+ contextItems: updatedContextItems,
+ }),
+ );
+ }
+ }),
+ );
+ },
+);
diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts
new file mode 100644
index 000000000..6652f3a0e
--- /dev/null
+++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts
@@ -0,0 +1,67 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import { ChatMessage, ContextItem } from "core";
+import { constructMessages } from "core/llm/constructMessages";
+import { renderContextItems } from "core/util/messageContent";
+import { defaultModelSelector } from "../selectors/modelSelectors";
+import {
+ addContextItemsAtIndex,
+ setActive,
+ streamUpdate,
+} from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+import { handleErrors } from "./handleErrors";
+import { resetStateForNewMessage } from "./resetStateForNewMessage";
+import { streamNormalInput } from "./streamNormalInput";
+
+export const streamResponseAfterToolCall = createAsyncThunk<
+ void,
+ {
+ toolCallId: string;
+ toolOutput: ContextItem[];
+ },
+ ThunkApiType
+>(
+ "chat/streamAfterToolCall",
+ async ({ toolCallId, toolOutput }, { dispatch, getState, extra }) => {
+ await dispatch(
+ handleErrors(async () => {
+ const state = getState();
+ const initialHistory = state.state.history;
+ const defaultModel = defaultModelSelector(state);
+
+ resetStateForNewMessage();
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const newMessage: ChatMessage = {
+ role: "tool",
+ content: renderContextItems(toolOutput),
+ toolCallId,
+ };
+
+ dispatch(streamUpdate(newMessage));
+ dispatch(
+ addContextItemsAtIndex({
+ index: initialHistory.length,
+ contextItems: toolOutput.map((contextItem) => ({
+ ...contextItem,
+ id: {
+ providerTitle: "toolCall",
+ itemId: toolCallId,
+ },
+ })),
+ }),
+ );
+
+ dispatch(setActive());
+
+ const updatedHistory = getState().state.history;
+ const messages = constructMessages(
+ [...updatedHistory],
+ defaultModel.model,
+ );
+ await dispatch(streamNormalInput(messages));
+ }),
+ );
+ },
+);
diff --git a/gui/src/redux/thunks/streamSlashCommand.ts b/gui/src/redux/thunks/streamSlashCommand.ts
new file mode 100644
index 000000000..4b6c71791
--- /dev/null
+++ b/gui/src/redux/thunks/streamSlashCommand.ts
@@ -0,0 +1,71 @@
+import { createAsyncThunk } from "@reduxjs/toolkit";
+import {
+ ChatMessage,
+ ContextItemWithId,
+ RangeInFile,
+ SlashCommandDescription,
+} from "core";
+import { defaultModelSelector } from "../selectors/modelSelectors";
+import { abortStream, streamUpdate } from "../slices/stateSlice";
+import { ThunkApiType } from "../store";
+
+export const streamSlashCommand = createAsyncThunk<
+ void,
+ {
+ messages: ChatMessage[];
+ slashCommand: SlashCommandDescription;
+ input: string;
+ historyIndex: number;
+ selectedCode: RangeInFile[];
+ contextItems: ContextItemWithId[];
+ },
+ ThunkApiType
+>(
+ "chat/streamSlashCommand",
+ async (
+ { messages, selectedCode, slashCommand, input, historyIndex, contextItems },
+ { dispatch, getState, extra },
+ ) => {
+ const state = getState();
+ const defaultModel = defaultModelSelector(state);
+ const active = state.state.active;
+ const streamAborter = state.state.streamAborter;
+
+ if (!defaultModel) {
+ throw new Error("Default model not defined");
+ }
+
+ const modelTitle = defaultModel.title;
+
+ const checkActiveInterval = setInterval(() => {
+ if (!active) {
+ dispatch(abortStream());
+ clearInterval(checkActiveInterval);
+ }
+ }, 100);
+
+ for await (const update of extra.ideMessenger.streamRequest(
+ "command/run",
+ {
+ input,
+ history: messages,
+ modelTitle,
+ slashCommandName: slashCommand.name,
+ contextItems,
+ params: slashCommand.params,
+ historyIndex,
+ selectedCode,
+ },
+ streamAborter.signal,
+ )) {
+ if (!getState().state.active) {
+ dispatch(abortStream());
+ break;
+ }
+ if (typeof update === "string") {
+ dispatch(streamUpdate(update));
+ }
+ }
+ clearInterval(checkActiveInterval);
+ },
+);
diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts
new file mode 100644
index 000000000..06ceebb4a
--- /dev/null
+++ b/gui/src/redux/util/index.ts
@@ -0,0 +1,8 @@
+import { ToolCallState } from "core";
+import { RootState } from "../store";
+
+export function findCurrentToolCall(
+ state: RootState["state"]["history"],
+): ToolCallState | undefined {
+ return state[state.length - 1]?.toolCallState;
+}
diff --git a/manual-testing-sandbox/test.ts b/manual-testing-sandbox/test.ts
new file mode 100644
index 000000000..9cf524421
--- /dev/null
+++ b/manual-testing-sandbox/test.ts
@@ -0,0 +1,41 @@
+class Calculator {
+ private result: number;
+
+ constructor() {
+ this.result = 0;
+ }
+
+ add(number: number): Calculator {
+ this.result += number;
+ return this;
+ }
+
+ subtract(number: number): Calculator {
+ this.result -= number;
+ return this;
+ }
+
+ multiply(number: number): Calculator {
+ this.result *= number;
+ return this;
+ }
+
+ divide(number: number): Calculator {
+ if (number === 0) {
+ throw new Error("Cannot divide by zero");
+ }
+ this.result /= number;
+ return this;
+ }
+
+ getResult(): number {
+ return this.result;
+ }
+
+ reset(): Calculator {
+ this.result = 0;
+ return this;
+ }
+}
+
+export default Calculator;
\ No newline at end of file
diff --git a/packages/llm-info/package.json b/packages/llm-info/package.json
index 4ba97f6b8..af8303938 100644
--- a/packages/llm-info/package.json
+++ b/packages/llm-info/package.json
@@ -1,6 +1,6 @@
{
"name": "@continuedev/llm-info",
- "version": "1.0.6",
+ "version": "1.0.7",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/packages/llm-info/src/index.ts b/packages/llm-info/src/index.ts
index 84d88e031..fe71f419d 100644
--- a/packages/llm-info/src/index.ts
+++ b/packages/llm-info/src/index.ts
@@ -22,7 +22,7 @@ export const allModelProviders: ModelProvider[] = [
Vllm,
Bedrock,
Cohere,
- xAI
+ xAI,
];
export const allLlms: LlmInfo[] = allModelProviders.flatMap((provider) =>