(undefined);
const sendFeedback = (feedback: boolean) => {
- setFeedback(feedback);
- console.log(sessionHistory, props.index);
- const logs = sessionHistory[props.index].logs;
- if (!logs || logs.length < 1) return;
- const prompt = logs[0].split("#########\n")[1];
- const completion = props.item.message.content;
-
- console.log(prompt, completion, client);
-
- client?.sendPromptCompletionFeedback("chat", prompt, completion, feedback);
+ // TODO: Feedback
+ // setFeedback(feedback);
+ // console.log(sessionHistory, props.index);
+ // const logs = sessionHistory[props.index].logs;
+ // if (!logs || logs.length < 1) return;
+ // const prompt = logs[0].split("#########\n")[1];
+ // const completion = props.item.message.content;
+ // console.log(prompt, completion, client);
+ // client?.sendPromptCompletionFeedback("chat", prompt, completion, feedback);
};
return (
@@ -110,43 +100,6 @@ function StepContainer(props: StepContainerProps) {
}}
>
- {isHovered && (false || props.noUserInputParent) && (
-
- {false &&
- ((
- {
- e.stopPropagation();
- props.onRetry();
- }}
- >
-
-
- ) as any)}
-
- {props.noUserInputParent && (
- {
- e.stopPropagation();
- props.onDelete();
- }}
- >
-
-
- )}
-
- )}
-
{
setSearchClient(client);
}, [meilisearchUrl]);
- const client = useContext(GUIClientContext);
const dispatch = useDispatch();
const workspacePaths = (window as any).workspacePaths || [];
- const sessionState = useSelector((state: RootStore) => state.sessionState);
+ const state = useSelector((state: RootStore) => state.state);
const [history, setHistory] = React.useState([]);
// The position of the current command you are typing now, so the one that will be appended to history once you press enter
@@ -437,10 +434,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}
});
- const timeline = useSelector(
- (state: RootStore) => state.sessionState.history
- );
- const active = useSelector((state: RootStore) => state.sessionState.active);
+ const active = useSelector((state: RootStore) => state.state.active);
useEffect(() => {
if (!currentlyInContextQuery) {
@@ -492,7 +486,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
dispatch(addContextItemsAtIndex({ contextItems, index: props.index }));
}
},
- [client, props.index, getContextItems]
+ [props.index, getContextItems]
);
const onInputValueChangeCallback = useCallback(
@@ -733,9 +727,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
};
}, []);
- const persistSession = () => {
- client?.persistSession(sessionState, workspacePaths[0] || "");
- };
+ const { saveSession } = useHistory();
useEffect(() => {
if (!inputRef.current || !props.isMainInput) {
@@ -747,18 +739,15 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
const handler = (event: any) => {
if (event.data.type === "focusContinueInput") {
inputRef.current!.focus();
- console.log(sessionState.history.length, "OHPOI");
- if (sessionState.history.length > 0) {
- client?.stopSession();
- persistSession();
+ if (state.history.length > 0) {
+ saveSession();
dispatch(newSession());
}
dispatch(setTakenActionTrue(null));
} else if (event.data.type === "focusContinueInputWithEdit") {
inputRef.current!.focus();
- if (sessionState.history.length > 0) {
- client?.stopSession();
- persistSession();
+ if (state.history.length > 0) {
+ saveSession();
dispatch(newSession());
}
@@ -767,8 +756,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
}
dispatch(setTakenActionTrue(null));
} else if (event.data.type === "focusContinueInputWithNewSession") {
- client?.stopSession();
- persistSession();
+ saveSession();
dispatch(newSession());
dispatch(setTakenActionTrue(null));
}
@@ -777,7 +765,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
return () => {
window.removeEventListener("message", handler);
};
- }, [inputRef.current, props.isMainInput, sessionState.history.length]);
+ }, [inputRef.current, props.isMainInput, state.history.length]);
const deleteButtonDivRef = React.useRef(null);
const stickyDropdownHeaderDiv = React.useRef(null);
@@ -1215,8 +1203,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
ref={divRef}
>
{
// }
onClick={() => {
if (active) {
- client?.stopSession();
dispatch(setInactive());
} else {
props.onEnter?.(undefined);
@@ -1676,11 +1662,10 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
>
- ) : sessionState.history.length > 0 ? (
+ ) : state.history.length > 0 ? (
{
- client?.stopSession();
- persistSession();
+ saveSession();
dispatch(newSession());
}}
className="mr-auto"
diff --git a/gui/src/components/mainInput/PillButton.tsx b/gui/src/components/mainInput/PillButton.tsx
index fb44d028b..e3a25bf2a 100644
--- a/gui/src/components/mainInput/PillButton.tsx
+++ b/gui/src/components/mainInput/PillButton.tsx
@@ -1,4 +1,11 @@
-import { useCallback, useContext, useEffect, useRef, useState } from "react";
+import {
+ ExclamationTriangleIcon,
+ PaintBrushIcon,
+ TrashIcon,
+} from "@heroicons/react/24/outline";
+import { ContextItem } from "core/llm/types";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import {
StyledTooltip,
@@ -7,20 +14,12 @@ import {
secondaryDark,
vscForeground,
} from "..";
-import {
- TrashIcon,
- PaintBrushIcon,
- ExclamationTriangleIcon,
-} from "@heroicons/react/24/outline";
-import { GUIClientContext } from "../../App";
-import { getFontSize } from "../../util";
-import HeaderButtonWithText from "../HeaderButtonWithText";
-import FileIcon from "../FileIcon";
-import { ContextItem } from "core/llm/types";
-import { postToIde } from "../../util/ide";
-import { useDispatch, useSelector } from "react-redux";
-import { setEditingAtIds } from "../../redux/slices/sessionStateReducer";
+import { setEditingAtIds } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
+import { getFontSize } from "../../util";
+import { postToIde } from "../../util/ide";
+import FileIcon from "../FileIcon";
+import HeaderButtonWithText from "../HeaderButtonWithText";
const Button = styled.button<{ fontSize?: number }>`
border: none;
@@ -145,7 +144,6 @@ const ClickableInsidePillButton = styled(HeaderButtonWithText)<{
const PillButton = (props: PillButtonProps) => {
const [isHovered, setIsHovered] = useState(false);
- const client = useContext(GUIClientContext);
const dispatch = useDispatch();
const [warning, setWarning] = useState(undefined);
@@ -179,7 +177,7 @@ const PillButton = (props: PillButtonProps) => {
const buttonRef = useRef(null);
const selectedContextItems = useSelector(
- (store: RootStore) => store.sessionState.context_items
+ (store: RootStore) => store.state.contextItems
);
return (
diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx
index a687a9c05..f63c000d2 100644
--- a/gui/src/components/markdown/CodeSnippetPreview.tsx
+++ b/gui/src/components/markdown/CodeSnippetPreview.tsx
@@ -12,7 +12,7 @@ import {
ChevronUpIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
-import { deleteContextWithIds } from "../../redux/slices/sessionStateReducer";
+import { deleteContextWithIds } from "../../redux/slices/stateSlice";
import { useDispatch } from "react-redux";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
diff --git a/gui/src/components/markdown/LinkableCode.tsx b/gui/src/components/markdown/LinkableCode.tsx
index 5cb936c88..4f10cbc1d 100644
--- a/gui/src/components/markdown/LinkableCode.tsx
+++ b/gui/src/components/markdown/LinkableCode.tsx
@@ -1,7 +1,7 @@
-import React, { useCallback, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
+import { useSelector } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius, secondaryDark } from "..";
-import { useDispatch, useSelector } from "react-redux";
import { RootStore } from "../../redux/store";
import { postToIde } from "../../util/ide";
@@ -19,7 +19,7 @@ const StyledCode = styled.code<{ link: boolean }>`
function LinkableCode(props: any) {
const contextItems = useSelector(
- (store: RootStore) => store.sessionState.context_items
+ (store: RootStore) => store.state.contextItems
);
const [linkingDone, setLinkingDone] = useState(false);
diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx
index 63a9ec52a..c24b400b4 100644
--- a/gui/src/components/modelSelection/ModelSelect.tsx
+++ b/gui/src/components/modelSelection/ModelSelect.tsx
@@ -1,3 +1,13 @@
+import { Listbox, Transition } from "@headlessui/react";
+import {
+ ChevronUpDownIcon,
+ PlusIcon,
+ TrashIcon,
+} from "@heroicons/react/24/outline";
+import { Fragment, useEffect, useState } from "react";
+import ReactDOM from "react-dom";
+import { useSelector } from "react-redux";
+import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import {
buttonColor,
@@ -7,21 +17,10 @@ import {
vscBackground,
vscForeground,
} from "..";
-import React, { Fragment, useContext, useEffect, useState } from "react";
-import { GUIClientContext } from "../../App";
-import { RootStore } from "../../redux/store";
-import { useSelector } from "react-redux";
-import {
- ChevronUpDownIcon,
- PlusIcon,
- TrashIcon,
-} from "@heroicons/react/24/outline";
-import { useNavigate } from "react-router-dom";
-import { Listbox, Transition } from "@headlessui/react";
-import ReactDOM from "react-dom";
-import HeaderButtonWithText from "../HeaderButtonWithText";
import { defaultModelSelector } from "../../redux/selectors/configSelectors";
+import { RootStore } from "../../redux/store";
import { getMetaKeyLabel } from "../../util";
+import HeaderButtonWithText from "../HeaderButtonWithText";
const GridDiv = styled.div`
display: grid;
@@ -136,7 +135,6 @@ const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean }>`
`;
function ListBoxOption({ option, idx }: { option: Option; idx: number }) {
- const client = useContext(GUIClientContext);
const [hovered, setHovered] = useState(false);
return (
@@ -163,7 +161,8 @@ function ListBoxOption({ option, idx }: { option: Option; idx: number }) {
{
- client?.deleteModelAtIndex(idx - 1); // -1 because 0 is default, not in saved array
+ // TODO
+ // client?.deleteModelAtIndex(idx - 1); // -1 because 0 is default, not in saved array
e.stopPropagation();
e.preventDefault();
}}
@@ -196,7 +195,6 @@ interface Option {
}
function ModelSelect(props: {}) {
- const client = useContext(GUIClientContext);
const defaultModel = useSelector(defaultModelSelector);
const allModels = useSelector(
(state: RootStore) => state.serverState.config.models
@@ -234,7 +232,8 @@ function ModelSelect(props: {}) {
(option) => option.value === defaultModel?.title
);
const nextIndex = (currentIndex + 1) % options.length;
- client?.setModelForRoleFromTitle("default", options[nextIndex].value);
+ // TODO
+ // client?.setModelForRoleFromTitle("default", options[nextIndex].value);
}
};
@@ -251,7 +250,8 @@ function ModelSelect(props: {}) {
value={"GPT-4"}
onChange={(val: string) => {
if (val === defaultModel?.title) return;
- client?.setModelForRoleFromTitle("default", val);
+ // TODO
+ // client?.setModelForRoleFromTitle("default", val);
}}
defaultValue={"GPT-4"}
>
diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx
new file mode 100644
index 000000000..9d3c58144
--- /dev/null
+++ b/gui/src/hooks/useHistory.tsx
@@ -0,0 +1,34 @@
+import { ideRequest } from "core/ide/messaging";
+import { PersistedSessionInfo, SessionInfo } from "core/types";
+import { useSelector } from "react-redux";
+import { RootStore } from "../redux/store";
+
+function useHistory() {
+ const state = useSelector((state: RootStore) => state.state);
+
+ async function getHistory(): Promise {
+ return await ideRequest("history", {});
+ }
+
+ async function saveSession() {
+ const sessionInfo: PersistedSessionInfo = {
+ history: state.history,
+ title: state.title,
+ sessionId: state.sessionId,
+ workspaceDirectory: (window as any).workspacePaths?.[0] || "",
+ };
+ return await ideRequest("saveSession", sessionInfo);
+ }
+
+ async function deleteSession(sessionId: string) {
+ return await ideRequest("deleteSession", { sessionId });
+ }
+
+ async function loadSession(sessionId: string): Promise {
+ return await ideRequest("loadSession", { sessionId });
+ }
+
+ return { getHistory, saveSession, deleteSession, loadSession };
+}
+
+export default useHistory;
diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts
index 9fa740ca8..e9f103433 100644
--- a/gui/src/hooks/useSetup.ts
+++ b/gui/src/hooks/useSetup.ts
@@ -1,15 +1,12 @@
import { Dispatch } from "@reduxjs/toolkit";
import { useEffect } from "react";
-import {
- addHighlightedCode,
- setActive,
-} from "../redux/slices/sessionStateReducer";
import { setServerStatusMessage } from "../redux/slices/miscSlice";
import { postToIde } from "../util/ide";
import { setVscMachineId } from "../redux/slices/configSlice";
import { ExtensionIde } from "core/ide/index";
import { setConfig } from "../redux/slices/serverStateReducer";
+import { addHighlightedCode, setInactive } from "../redux/slices/stateSlice";
function useSetup(dispatch: Dispatch) {
// Load config from the IDE
@@ -21,7 +18,7 @@ function useSetup(dispatch: Dispatch) {
useEffect(() => {
// Override persisted state
- dispatch(setActive(false));
+ dispatch(setInactive());
// Tell JetBrains the webview is ready
postToIde("onLoad", {});
diff --git a/gui/src/main.tsx b/gui/src/main.tsx
index 6f1a3700d..5cf5f14ef 100644
--- a/gui/src/main.tsx
+++ b/gui/src/main.tsx
@@ -2,7 +2,10 @@ import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
-import { store, persistor } from "./redux/store";
+import {
+ store,
+ // persistor
+} from "./redux/store";
import "./index.css";
import { PersistGate } from "redux-persist/integration/react";
diff --git a/gui/src/pages/error.tsx b/gui/src/pages/error.tsx
index a93f55a8f..885043989 100644
--- a/gui/src/pages/error.tsx
+++ b/gui/src/pages/error.tsx
@@ -1,6 +1,6 @@
import { useDispatch } from "react-redux";
import { useNavigate, useRouteError } from "react-router-dom";
-import { newSession } from "../redux/slices/sessionStateReducer";
+import { newSession } from "../redux/slices/stateSlice";
import ContinueButton from "../components/mainInput/ContinueButton";
import { vscBackground } from "../components";
diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx
index b5e085b2a..4595238b4 100644
--- a/gui/src/pages/gui.tsx
+++ b/gui/src/pages/gui.tsx
@@ -1,29 +1,44 @@
+import {
+ ChatBubbleOvalLeftIcon,
+ CodeBracketSquareIcon,
+ ExclamationTriangleIcon,
+} from "@heroicons/react/24/outline";
+import { constructMessages } from "core/llm/constructMessages";
+import { ChatHistoryItem, ChatMessage } from "core/llm/types";
+import { usePostHog } from "posthog-js/react";
+import {
+ Fragment,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import { ErrorBoundary } from "react-error-boundary";
+import { useDispatch, useSelector } from "react-redux";
+import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import {
Button,
- Input,
defaultBorderRadius,
lightGray,
vscBackground,
} from "../components";
-import { ErrorBoundary } from "react-error-boundary";
-import {
- useEffect,
- useRef,
- useState,
- useContext,
- useLayoutEffect,
- useCallback,
- Fragment,
-} from "react";
+import FTCDialog from "../components/dialogs/FTCDialog";
+import ErrorStepContainer from "../components/gui/ErrorStepContainer";
import StepContainer from "../components/gui/StepContainer";
-import { GUIClientContext } from "../App";
+import TimelineItem from "../components/gui/TimelineItem";
import ComboBox from "../components/mainInput/ComboBox";
-import { usePostHog } from "posthog-js/react";
-import { useDispatch, useSelector } from "react-redux";
-import { RootStore } from "../redux/store";
-import { postToIde } from "../util/ide";
-import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../util";
+import useHistory from "../hooks/useHistory";
+import useModels from "../hooks/useModels";
+import { setTakenActionTrue } from "../redux/slices/miscSlice";
+import {
+ newSession,
+ resubmitAtIndex,
+ setInactive,
+ streamUpdate,
+ submitMessage,
+} from "../redux/slices/stateSlice";
import {
setBottomMessage,
setDialogEntryOn,
@@ -31,33 +46,8 @@ import {
setDisplayBottomMessageOnBottom,
setShowDialog,
} from "../redux/slices/uiStateSlice";
-import RingLoader from "../components/loaders/RingLoader";
-import TimelineItem from "../components/gui/TimelineItem";
-import ErrorStepContainer from "../components/gui/ErrorStepContainer";
-import {
- ArrowsPointingInIcon,
- ArrowsPointingOutIcon,
- ChatBubbleOvalLeftIcon,
- CodeBracketSquareIcon,
- ExclamationTriangleIcon,
- FolderIcon,
- PlusIcon,
-} from "@heroicons/react/24/outline";
-import FTCDialog from "../components/dialogs/FTCDialog";
-import HeaderButtonWithText from "../components/HeaderButtonWithText";
-import { useNavigate } from "react-router-dom";
-import { setTakenActionTrue } from "../redux/slices/miscSlice";
-import FreeTrial from "core/llm/llms/FreeTrial";
-import { constructMessages } from "core/llm/constructMessages";
-import { ChatHistory, ChatHistoryItem, ChatMessage } from "core/llm/types";
-import {
- resubmitAtIndex,
- streamUpdate,
- submitMessage,
- newSession,
- setInactive,
-} from "../redux/slices/stateSlice";
-import useModels from "../hooks/useModels";
+import { RootStore } from "../redux/store";
+import { isMetaEquivalentKeyPressed } from "../util";
const TopGuiDiv = styled.div`
overflow-y: scroll;
@@ -131,7 +121,6 @@ interface GUIProps {
function GUI(props: GUIProps) {
// #region Hooks
- const client = useContext(GUIClientContext);
const posthog = usePostHog();
const dispatch = useDispatch();
const navigate = useNavigate();
@@ -139,15 +128,13 @@ function GUI(props: GUIProps) {
// #endregion
// #region Selectors
- const sessionState = useSelector((state: RootStore) => state.sessionState);
+ const sessionState = useSelector((state: RootStore) => state.state);
const workspacePaths = (window as any).workspacePaths || [];
const { defaultModel } = useModels();
- const sessionTitle = useSelector(
- (state: RootStore) => state.sessionState.title
- );
- const active = useSelector((state: RootStore) => state.sessionState.active);
+ const sessionTitle = useSelector((state: RootStore) => state.state.title);
+ const active = useSelector((state: RootStore) => state.state.active);
// #endregion
@@ -230,7 +217,6 @@ function GUI(props: GUIProps) {
isMetaEquivalentKeyPressed(e) &&
!e.shiftKey
) {
- client?.stopSession();
dispatch(setInactive());
} else if (e.key === "Escape") {
dispatch(setBottomMessage(undefined));
@@ -241,7 +227,7 @@ function GUI(props: GUIProps) {
return () => {
window.removeEventListener("keydown", listener);
};
- }, [client, active]);
+ }, [active]);
// #endregion
@@ -284,6 +270,7 @@ function GUI(props: GUIProps) {
for await (const update of defaultModel.streamChat(messages)) {
dispatch(streamUpdate(update.content));
}
+ dispatch(setInactive());
})();
// Increment localstorage counter for popup
@@ -360,24 +347,15 @@ function GUI(props: GUIProps) {
localStorage.setItem("mainTextEntryCounter", "1");
}
},
- [
- client,
- sessionState.history,
- sessionState.context_items,
- defaultModel,
- state,
- ]
+ [sessionState.history, sessionState.contextItems, defaultModel, state]
);
- const persistSession = useCallback(() => {
- client?.persistSession(sessionState, workspacePaths[0] || "");
- }, [client, sessionState, workspacePaths]);
+ const { saveSession } = useHistory();
useEffect(() => {
const handler = (event: any) => {
if (event.data.type === "newSession") {
- client?.stopSession();
- persistSession();
+ saveSession();
dispatch(newSession());
mainTextInputRef.current?.focus?.();
}
@@ -422,11 +400,6 @@ function GUI(props: GUIProps) {
}
};
- const onStepUserInput = (input: string, index: number) => {
- if (!client) return;
- client.sendStepUserInput(input, index);
- };
-
const isLastUserInput = useCallback(
(index: number): boolean => {
let foundLaterUserInput = false;
@@ -441,41 +414,6 @@ function GUI(props: GUIProps) {
[state.history]
);
- const getStepsInUserInputGroup = useCallback(
- (index: number): number[] => {
- // index is the index in the entire timeline, hidden steps included
- const stepsInUserInputGroup: number[] = [];
-
- // First find the closest above UserInputStep
- let userInputIndex = -1;
- for (let i = index; i >= 0; i--) {
- if (
- typeof sessionState.history[i] !== "undefined" &&
- sessionState.history[i].name === "User Input" &&
- sessionState.history[i].hide === false
- ) {
- stepsInUserInputGroup.push(i);
- userInputIndex = i;
- break;
- }
- }
- if (stepsInUserInputGroup.length === 0) return [];
-
- for (let i = userInputIndex + 1; i < sessionState.history.length; i++) {
- if (
- typeof sessionState.history[i] !== "undefined" &&
- sessionState.history[i].name === "User Input" &&
- sessionState.history[i].hide === false
- ) {
- break;
- }
- stepsInUserInputGroup.push(i);
- }
- return stepsInUserInputGroup;
- },
- [sessionState.history]
- );
-
useEffect(() => {
if (sessionTitle) {
setSessionTitleInput(sessionTitle);
@@ -503,7 +441,6 @@ function GUI(props: GUIProps) {
{
- client?.stopSession();
dispatch(newSession());
}}
>
@@ -570,20 +507,11 @@ function GUI(props: GUIProps) {
: stepsOpen[index]!
}
key={index}
- onUserInput={(input: string) => {
- onStepUserInput(input, index);
- }}
+ onUserInput={(input: string) => {}}
item={item}
- onReverse={() => {
- client?.reverseToIndex(index);
- }}
- onRetry={() => {
- client?.retryAtIndex(index);
- }}
+ onReverse={() => {}}
+ onRetry={() => {}}
onDelete={() => {}}
- noUserInputParent={
- getStepsInUserInputGroup(index).length === 0
- }
/>
)}
@@ -599,7 +527,6 @@ function GUI(props: GUIProps) {
{active ? (
{
- client?.stopSession();
dispatch(setInactive());
}}
>
@@ -616,9 +543,7 @@ function GUI(props: GUIProps) {
e?.preventDefault();
}}
onInputValueChange={() => {}}
- onToggleAddContext={() => {
- client?.toggleAddingHighlightedCode();
- }}
+ onToggleAddContext={() => {}}
/>
)}
diff --git a/gui/src/pages/history.tsx b/gui/src/pages/history.tsx
index 408c2df61..98045f4b6 100644
--- a/gui/src/pages/history.tsx
+++ b/gui/src/pages/history.tsx
@@ -1,17 +1,15 @@
-import React, { Fragment, useContext, useEffect, useState } from "react";
-import { SessionInfo } from "../schema/SessionInfo";
-import { GUIClientContext } from "../App";
-import { useDispatch, useSelector } from "react-redux";
-import { RootStore } from "../redux/store";
-import { useNavigate } from "react-router-dom";
-import { lightGray, secondaryDark, vscBackground } from "../components";
-import styled from "styled-components";
import { ArrowLeftIcon, TrashIcon } from "@heroicons/react/24/outline";
+import { PersistedSessionInfo, SessionInfo } from "core/types";
+import React, { Fragment, useEffect, useState } from "react";
+import { useDispatch } from "react-redux";
+import { useNavigate } from "react-router-dom";
+import styled from "styled-components";
+import { lightGray, secondaryDark, vscBackground } from "../components";
import CheckDiv from "../components/CheckDiv";
-import { getFontSize } from "../util";
-import { newSession } from "../redux/slices/sessionStateReducer";
-import { PersistedSessionInfo } from "../schema/PersistedSessionInfo";
import HeaderButtonWithText from "../components/HeaderButtonWithText";
+import useHistory from "../hooks/useHistory";
+import { newSession } from "../redux/slices/stateSlice";
+import { getFontSize } from "../util";
const Tr = styled.tr`
&:hover {
@@ -64,12 +62,12 @@ function TableRow({
}) {
const dispatch = useDispatch();
const navigate = useNavigate();
- const client = useContext(GUIClientContext);
const apiUrl = (window as any).serverUrl;
- const currentSession = useSelector((state: RootStore) => state.sessionState);
const workspacePaths = (window as any).workspacePaths || [""];
const [hovered, setHovered] = useState(false);
+ const { saveSession, deleteSession } = useHistory();
+
return (
setHovered(true)}
@@ -79,17 +77,16 @@ function TableRow({
{
// Save current session
- client?.persistSession(currentSession, workspacePaths[0]);
+ saveSession();
// Load new session
const response = await fetch(
- `${apiUrl}/sessions/${session.session_id}`
+ `${apiUrl}/sessions/${session.sessionId}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const json: PersistedSessionInfo = await response.json();
- client?.stopSession();
dispatch(newSession(json));
navigate("/");
}}
@@ -105,7 +102,7 @@ function TableRow({
hour12: true,
})}
{" | "}
- {lastPartOfPath(session.workspace_directory || "")}/
+ {lastPartOfPath(session.workspaceDirectory || "")}/
@@ -114,8 +111,8 @@ function TableRow({
className="mr-2"
text="Delete"
onClick={async () => {
- client?.deleteSession(session.session_id);
- onDelete(session.session_id);
+ deleteSession(session.sessionId);
+ onDelete(session.sessionId);
}}
>
@@ -137,13 +134,12 @@ function History() {
const [filteredAndSortedSessions, setFilteredAndSortedSessions] = useState<
SessionInfo[]
>([]);
- const client = useContext(GUIClientContext);
const apiUrl = (window as any).serverUrl;
const workspacePaths = (window as any).workspacePaths || [];
const deleteSessionInUI = async (sessionId: string) => {
setSessions((prev) =>
- prev.filter((session) => session.session_id !== sessionId)
+ prev.filter((session) => session.sessionId !== sessionId)
);
};
@@ -151,20 +147,15 @@ function History() {
const stickyHistoryHeaderRef = React.useRef(null);
const [headerHeight, setHeaderHeight] = useState(0);
+ const { getHistory } = useHistory();
+
useEffect(() => {
const fetchSessions = async () => {
- if (!apiUrl) {
- return;
- }
- const response = await fetch(`${apiUrl}/sessions/list`);
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
- const json = await response.json();
- setSessions(json);
+ const sessions = await getHistory();
+ setSessions(sessions);
};
fetchSessions();
- }, [client]);
+ }, []);
useEffect(() => {
setFilteredAndSortedSessions(
@@ -173,22 +164,22 @@ function History() {
if (
!filteringByWorkspace ||
typeof workspacePaths === "undefined" ||
- typeof session.workspace_directory === "undefined"
+ typeof session.workspaceDirectory === "undefined"
) {
return true;
}
- return workspacePaths.includes(session.workspace_directory);
+ return workspacePaths.includes(session.workspaceDirectory);
})
.sort(
(a, b) =>
- parseDate(b.date_created).getTime() -
- parseDate(a.date_created).getTime()
+ parseDate(b.dateCreated).getTime() -
+ parseDate(a.dateCreated).getTime()
)
);
}, [filteringByWorkspace, sessions]);
useEffect(() => {
- setHeaderHeight(stickyHistoryHeaderRef.current?.clientHeight || 100);
+ setHeaderHeight(stickyHistoryHeaderRef.current?.clientHeight || 100);
}, [stickyHistoryHeaderRef.current]);
const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24);
@@ -198,7 +189,11 @@ function History() {
return (
-
+
No past sessions found. To start a new session, either click the "+"
@@ -246,30 +241,36 @@ function History() {
{filteredAndSortedSessions.map((session, index) => {
const prevDate =
index > 0
- ? parseDate(filteredAndSortedSessions[index - 1].date_created)
+ ? parseDate(filteredAndSortedSessions[index - 1].dateCreated)
: earlier;
- const date = parseDate(session.date_created);
+ const date = parseDate(session.dateCreated);
return (
{index === 0 && date > yesterday && (
- Today
+
+ Today
+
)}
{date < yesterday &&
date > lastWeek &&
prevDate > yesterday && (
- This Week
+
+ This Week
+
)}
{date < lastWeek &&
date > lastMonth &&
prevDate > lastWeek && (
- This Month
+
+ This Month
+
)}
deleteSessionInUI(session.session_id)}
+ onDelete={() => deleteSessionInUI(session.sessionId)}
>
diff --git a/gui/src/pages/modelconfig.tsx b/gui/src/pages/modelconfig.tsx
index 419ad4dc0..eb437dcfc 100644
--- a/gui/src/pages/modelconfig.tsx
+++ b/gui/src/pages/modelconfig.tsx
@@ -1,26 +1,23 @@
-import React, { useCallback, useContext, useEffect, useState } from "react";
-import ModelCard from "../components/modelSelection/ModelCard";
-import styled from "styled-components";
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
+import { useCallback, useEffect, useState } from "react";
+import { FormProvider, useForm } from "react-hook-form";
+import { useDispatch } from "react-redux";
+import { useNavigate, useParams } from "react-router-dom";
+import styled from "styled-components";
import {
Input,
defaultBorderRadius,
lightGray,
vscBackground,
} from "../components";
-import { useNavigate } from "react-router-dom";
-import { useDispatch } from "react-redux";
-import { GUIClientContext } from "../App";
-import { useParams } from "react-router-dom";
+import StyledMarkdownPreview from "../components/markdown/StyledMarkdownPreview";
+import ModelCard from "../components/modelSelection/ModelCard";
import {
- PROVIDER_INFO,
MODEL_PROVIDER_TAG_COLORS,
ModelInfo,
+ PROVIDER_INFO,
updatedObj,
} from "../util/modelData";
-import StyledMarkdownPreview from "../components/markdown/StyledMarkdownPreview";
-import { FormProvider, useForm } from "react-hook-form";
-import _ from "lodash";
const GridDiv = styled.div`
display: grid;
@@ -67,7 +64,6 @@ function ModelConfig() {
}
}, [modelName]);
- const client = useContext(GUIClientContext);
const dispatch = useDispatch();
const navigate = useNavigate();
const vscMediaUrl = (window as any).vscMediaUrl;
@@ -229,21 +225,22 @@ function ModelConfig() {
});
}
- client?.addModelForRole("default", {
- ...pkg.params,
- ...modelInfo.params,
- ..._.merge(
- {},
- ...(pkg.dimensions?.map((dimension, i) => {
- if (!dimensionChoices?.[i]) return {};
- return {
- ...dimension.options[dimensionChoices[i]],
- };
- }) || [])
- ),
- ...formParams,
- provider: modelInfo.provider,
- });
+ // TODO
+ // client?.addModelForRole("default", {
+ // ...pkg.params,
+ // ...modelInfo.params,
+ // ..._.merge(
+ // {},
+ // ...(pkg.dimensions?.map((dimension, i) => {
+ // if (!dimensionChoices?.[i]) return {};
+ // return {
+ // ...dimension.options[dimensionChoices[i]],
+ // };
+ // }) || [])
+ // ),
+ // ...formParams,
+ // provider: modelInfo.provider,
+ // });
navigate("/");
}}
/>
@@ -262,11 +259,12 @@ function ModelConfig() {
: parseFloat(formMethods.watch(d.key));
}
- client?.addModelForRole("default", {
- ...modelInfo.packages[0]?.params,
- ...modelInfo.params,
- ...formParams,
- });
+ // TODO
+ // client?.addModelForRole("default", {
+ // ...modelInfo.packages[0]?.params,
+ // ...modelInfo.params,
+ // ...formParams,
+ // });
navigate("/");
}}
>
diff --git a/gui/src/pages/models.tsx b/gui/src/pages/models.tsx
index 24510bb23..074aa519a 100644
--- a/gui/src/pages/models.tsx
+++ b/gui/src/pages/models.tsx
@@ -1,14 +1,12 @@
-import React, { useContext } from "react";
-import ModelCard from "../components/modelSelection/ModelCard";
-import styled from "styled-components";
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
-import { lightGray, vscBackground } from "../components";
+import React from "react";
import { useNavigate } from "react-router-dom";
-import { useDispatch } from "react-redux";
-import { GUIClientContext } from "../App";
-import { MODEL_INFO, PROVIDER_INFO } from "../util/modelData";
+import styled from "styled-components";
+import { lightGray, vscBackground } from "../components";
+import ModelCard from "../components/modelSelection/ModelCard";
+
import Toggle from "../components/modelSelection/Toggle";
-import _ from "lodash";
+import { MODEL_INFO, PROVIDER_INFO } from "../util/modelData";
const GridDiv = styled.div`
display: grid;
@@ -21,7 +19,6 @@ const GridDiv = styled.div`
function Models() {
const navigate = useNavigate();
- const client = useContext(GUIClientContext);
const [providersSelected, setProvidersSelected] = React.useState(true);
@@ -78,19 +75,20 @@ function Models() {
dimensions={pkg.dimensions}
providerOptions={pkg.providerOptions}
onClick={(e, dimensionChoices, selectedProvider) => {
- client?.addModelForRole("*", {
- ...pkg.params,
- ..._.merge(
- {},
- ...(pkg.dimensions?.map((dimension, i) => {
- if (!dimensionChoices?.[i]) return {};
- return {
- ...dimension.options[dimensionChoices[i]],
- };
- }) || [])
- ),
- provider: PROVIDER_INFO[selectedProvider].provider,
- });
+ // TODO
+ // client?.addModelForRole("*", {
+ // ...pkg.params,
+ // ..._.merge(
+ // {},
+ // ...(pkg.dimensions?.map((dimension, i) => {
+ // if (!dimensionChoices?.[i]) return {};
+ // return {
+ // ...dimension.options[dimensionChoices[i]],
+ // };
+ // }) || [])
+ // ),
+ // provider: PROVIDER_INFO[selectedProvider].provider,
+ // });
navigate("/");
}}
/>
diff --git a/gui/src/pages/settings.tsx b/gui/src/pages/settings.tsx
index ad1eebde3..33335b352 100644
--- a/gui/src/pages/settings.tsx
+++ b/gui/src/pages/settings.tsx
@@ -1,9 +1,9 @@
-import React, { useContext, useEffect } from "react";
-import { GUIClientContext } from "../App";
+import { ArrowLeftIcon } from "@heroicons/react/24/outline";
+import { useEffect } from "react";
+import { FormProvider, useForm } from "react-hook-form";
import { useDispatch, useSelector } from "react-redux";
-import { RootStore } from "../redux/store";
import { useNavigate } from "react-router-dom";
-import { ContinueConfig } from "../schema/ContinueConfig";
+import styled from "styled-components";
import {
Button,
NumberInput,
@@ -13,11 +13,10 @@ import {
vscBackground,
vscForeground,
} from "../components";
-import styled from "styled-components";
-import { ArrowLeftIcon } from "@heroicons/react/24/outline";
-import Loader from "../components/loaders/Loader";
import InfoHover from "../components/InfoHover";
-import { FormProvider, useForm } from "react-hook-form";
+import Loader from "../components/loaders/Loader";
+import { RootStore } from "../redux/store";
+import { ContinueConfig } from "../schema/ContinueConfig";
import { getFontSize, getPlatform } from "../util";
import { postToIde } from "../util/ide";
@@ -100,22 +99,19 @@ function Settings() {
const onSubmit = (data: ContinueConfig) => console.log(data);
const navigate = useNavigate();
- const client = useContext(GUIClientContext);
const config = useSelector((state: RootStore) => state.serverState.config);
const dispatch = useDispatch();
const submitChanges = () => {
- if (!client) return;
-
- const systemMessage = formMethods.watch("system_message") as
- | string
- | undefined;
- const temperature = formMethods.watch("temperature") as number | undefined;
- // const models = formMethods.watch("models");
-
- client.setSystemMessage(systemMessage || "");
- if (temperature) client.setTemperature(temperature);
-
+ // TODO
+ // if (!client) return;
+ // const systemMessage = formMethods.watch("system_message") as
+ // | string
+ // | undefined;
+ // const temperature = formMethods.watch("temperature") as number | undefined;
+ // // const models = formMethods.watch("models");
+ // client.setSystemMessage(systemMessage || "");
+ // if (temperature) client.setTemperature(temperature);
// if (models) {
// for (const role of ALL_MODEL_ROLES) {
// if (models[role]) {
diff --git a/gui/src/redux/slices/sessionStateReducer.ts b/gui/src/redux/slices/sessionStateReducer.ts
deleted file mode 100644
index 9be5d1064..000000000
--- a/gui/src/redux/slices/sessionStateReducer.ts
+++ /dev/null
@@ -1,417 +0,0 @@
-import { createSlice } from "@reduxjs/toolkit";
-import { StepDescription } from "../../schema/SessionState";
-import { SessionUpdate } from "../../schema/SessionUpdate";
-import { ContextItem } from "core/llm/types";
-import { PersistedSessionInfo } from "../../schema/PersistedSessionInfo";
-import { v4 } from "uuid";
-import { ContextItemId } from "core/llm/types";
-
-const TEST_CONTEXT_ITEMS: ContextItem[] = [
- {
- content: "def add(a, b):\n return a + b",
- description: "test.py",
- name: "test.py",
-
- id: {
- itemId: "test.py",
- providerTitle: "file",
- },
- },
- {
- content: "function add(a, b) {\n return a + b\n}",
-
- description: "test.js",
- name: "test.js",
- id: {
- itemId: "test.js",
- providerTitle: "file",
- },
- },
-];
-
-const TEST_TIMELINE = [
- {
- description: "Hi, please write bubble sort in python",
- name: "User Input",
- params: { context_items: TEST_CONTEXT_ITEMS },
- hide: false,
- depth: 0,
- },
- {
- description: `\`\`\`python
-def bubble_sort(arr):
- n = len(arr)
- for i in range(n):
- for j in range(0, n - i - 1):
- if arr[j] > arr[j + 1]:
- arr[j], arr[j + 1] = arr[j + 1], arr[j]
- return arr
-\`\`\``,
- name: "Bubble Sort in Python",
- params: {},
- hide: false,
- depth: 0,
- },
- {
- description: "Now write it in Rust",
- name: "User Input",
- params: {},
- },
- {
- description: "Hello! This is a test...\n\n1, 2, 3, testing...",
- name: "Testing",
- hide: false,
- },
- {
- description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
-fn bubble_sort (values: &mut[T]) {
- let len = values.len();
- for i in 0..len {
- for j in 0..(len - i - 1) {
- if values[j] > values[j + 1] {
- values.swap(j, j + 1);
- }
- }
- }
-}
-\`\`\`\nIs there anything else I can answer?`,
- name: "Rust Bubble Sort",
- depth: 0,
- },
-];
-
-export interface SessionFullState {
- history: StepDescription[];
- context_items: ContextItem[];
- active: boolean;
- title: string;
- session_id: string;
-}
-
-export const sessionStateSlice = createSlice({
- name: "sessionState",
- initialState: {
- history: [],
- context_items: [],
- active: false,
- title: "New Session",
- session_id: v4(),
- },
- reducers: {
- processSessionUpdate: (
- state: SessionFullState,
- { payload }: { payload: SessionUpdate }
- ) => {
- let active = state.active;
- if (typeof payload.stop === "boolean") {
- active = !payload.stop;
- } else {
- active = true;
- }
-
- let step: StepDescription | undefined = undefined;
-
- if (payload.index > state.history.length) {
- // Partial above to allow here
- step = {
- ...(payload.update as StepDescription),
- };
- } else if (payload.delta === true) {
- step = {
- ...state.history[payload.index],
- };
- if (payload.update.name) {
- step.name = (step.name ?? "") + payload.update.name;
- }
- if (payload.update.description) {
- step.description =
- (step.description ?? "") + payload.update.description;
- }
- if (payload.update.observations) {
- step.observations = [
- ...(step.observations ?? []),
- ...(payload.update.observations as any),
- ];
- }
- if (payload.update.logs) {
- step.logs = [...(step.logs ?? []), ...(payload.update.logs as any)];
- }
- } else if (payload.delta === false) {
- step = {
- ...state.history[payload.index],
- ...payload.update,
- };
- }
-
- let history = [...state.history];
- if (step) {
- if (payload.index >= history.length) {
- history.push(step);
- } else {
- history[payload.index] = step;
- }
- }
-
- return {
- ...state,
- history,
- active,
- };
- },
- newSession: (
- state: SessionFullState,
- { payload }: { payload: PersistedSessionInfo | undefined }
- ) => {
- if (payload) {
- return {
- ...state,
- history: payload.session_state.history,
- context_items: payload.session_state.context_items,
- contextItemsAtIndex: {},
- active: false,
- title: payload.title,
- session_id: payload.session_id,
- };
- }
- return {
- ...state,
- history: [],
- context_items: [],
- contextItemsAtIndex: {},
- active: false,
- title: "New Session",
- session_id: v4(),
- };
- },
- setTitle: (state: SessionFullState, { payload }: { payload: string }) => {
- return {
- ...state,
- title: payload,
- };
- },
- setActive: (state: SessionFullState, { payload }: { payload: boolean }) => {
- return {
- ...state,
- active: payload,
- };
- },
- setHistory: (
- state: SessionFullState,
- { payload }: { payload: StepDescription[] }
- ) => {
- return {
- ...state,
- history: payload,
- };
- },
- deleteAtIndex: (
- state: SessionFullState,
- { payload }: { payload: number }
- ) => {
- let newHistory = [...state.history];
- newHistory[payload] = {
- ...newHistory[payload],
- hide: true,
- };
- return { ...state, history: newHistory };
- },
- addContextItem: (
- state: SessionFullState,
- { payload }: { payload: ContextItem }
- ) => {
- return {
- ...state,
- context_items: [...state.context_items, payload],
- };
- },
- addContextItemAtIndex: (
- state: SessionFullState,
- { payload }: { payload: { item: ContextItem; index: number } }
- ) => {
- let history = [...state.history];
- history[payload.index] = {
- ...history[payload.index],
- params: {
- ...history[payload.index].params,
- context_items: [
- ...((history[payload.index].params?.context_items as any) || []),
- payload.item,
- ],
- },
- };
-
- return {
- ...state,
- history,
- };
- },
- addHighlightedCode: (
- state: SessionFullState,
- {
- payload,
- }: {
- payload: { rangeInFileWithContents: any; edit: boolean };
- }
- ) => {
- let contextItems = [...state.context_items].map((item) => {
- return { ...item, editing: false };
- });
- const base = payload.rangeInFileWithContents.filepath
- .split(/[\\/]/)
- .pop();
-
- // Merge if there is overlap
- for (let i = 0; i < contextItems.length; i++) {
- const item = contextItems[i];
- if (item.description === payload.rangeInFileWithContents.filepath) {
- let newStart = payload.rangeInFileWithContents.range.start.line;
- let newEnd = payload.rangeInFileWithContents.range.end.line;
- let [oldStart, oldEnd] = item.name
- .split("(")[1]
- .split(")")[0]
- .split("-")
- .map((x: string) => parseInt(x) - 1);
- if (newStart > oldEnd || newEnd < oldStart) {
- continue;
- }
- const startLine = Math.min(newStart, oldStart);
- const endLine = Math.max(newEnd, oldEnd);
-
- // const oldContents = item.content.split("\n");
- // const newContents =
- // payload.rangeInFileWithContents.contents.split("\n");
- // const finalContents = [];
-
- contextItems[i] = {
- ...item,
- name: `${base} (${startLine + 1}-${endLine + 1})`,
- content: payload.rangeInFileWithContents.contents,
- editing: true,
- editable: true,
- };
- return { ...state, context_items: contextItems };
- }
- }
-
- const lineNums = `(${
- payload.rangeInFileWithContents.range.start.line + 1
- }-${payload.rangeInFileWithContents.range.end.line + 1})`;
- contextItems.push({
- name: `${base} ${lineNums}`,
- description: payload.rangeInFileWithContents.filepath,
- id: {
- providerTitle: "code",
- itemId: v4(),
- },
- content: payload.rangeInFileWithContents.contents,
- editing: true,
- editable: true,
- });
-
- return { ...state, context_items: contextItems };
- },
- deleteContextWithIds: (
- state: SessionFullState,
- {
- payload,
- }: { payload: { ids: ContextItemId[]; index: number | undefined } }
- ) => {
- const ids = payload.ids.map((id) => `${id.providerTitle}-${id.itemId}`);
- if (typeof payload.index === "undefined") {
- return {
- ...state,
- context_items: state.context_items.filter(
- (item) =>
- !ids.includes(`${item.id.providerTitle}-${item.id.itemId}`)
- ),
- };
- } else {
- return {
- ...state,
- history: state.history.map((step, i) => {
- if (i === payload.index) {
- return {
- ...step,
- params: {
- ...step.params,
- context_items: (step.params?.context_items as any).filter(
- (item: ContextItem) =>
- !ids.includes(
- `${item.id.providerTitle}-${item.id.itemId}`
- )
- ),
- },
- };
- }
- return step;
- }),
- };
- }
- },
- clearContextItems: (state: SessionFullState) => {
- return {
- ...state,
- context_items: [],
- };
- },
- setEditingAtIds: (
- state: SessionFullState,
- {
- payload,
- }: { payload: { ids: ContextItemId[]; index: number | undefined } }
- ) => {
- const ids = payload.ids.map((id) => id.itemId);
-
- if (typeof payload.index === "undefined") {
- return {
- ...state,
- context_items: state.context_items.map((item) => {
- return {
- ...item,
- editing: ids.includes(item.id.itemId),
- };
- }),
- };
- } else {
- return {
- ...state,
- history: state.history.map((step, i) => {
- if (i === payload.index) {
- return {
- ...step,
- params: {
- ...step.params,
- context_items: (step.params?.context_items as any).map(
- (item: ContextItem) => {
- return {
- ...item,
- editing: ids.includes(item.id.itemId),
- };
- }
- ),
- },
- };
- }
- return step;
- }),
- };
- }
- },
- },
-});
-
-export const {
- setActive,
- setHistory,
- processSessionUpdate,
- newSession,
- deleteAtIndex,
- addContextItem,
- addContextItemAtIndex,
- addHighlightedCode,
- deleteContextWithIds,
- setTitle,
- setEditingAtIds,
- clearContextItems,
-} = sessionStateSlice.actions;
-export default sessionStateSlice.reducer;
diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts
index 1f3062edd..ed4e349d9 100644
--- a/gui/src/redux/slices/stateSlice.ts
+++ b/gui/src/redux/slices/stateSlice.ts
@@ -1,12 +1,91 @@
import { createSlice } from "@reduxjs/toolkit";
import { RootStore } from "../store";
-import { ContextItemId } from "core/llm/types";
+import { ContextItem, ContextItemId } from "core/llm/types";
import defaultConfig from "core/config/default";
+import { v4 } from "uuid";
+import { PersistedSessionInfo } from "core/types";
+
+const TEST_CONTEXT_ITEMS: ContextItem[] = [
+ {
+ content: "def add(a, b):\n return a + b",
+ description: "test.py",
+ name: "test.py",
+
+ id: {
+ itemId: "test.py",
+ providerTitle: "file",
+ },
+ },
+ {
+ content: "function add(a, b) {\n return a + b\n}",
+
+ description: "test.js",
+ name: "test.js",
+ id: {
+ itemId: "test.js",
+ providerTitle: "file",
+ },
+ },
+];
+
+const TEST_TIMELINE = [
+ {
+ description: "Hi, please write bubble sort in python",
+ name: "User Input",
+ params: { context_items: TEST_CONTEXT_ITEMS },
+ hide: false,
+ depth: 0,
+ },
+ {
+ description: `\`\`\`python
+def bubble_sort(arr):
+ n = len(arr)
+ for i in range(n):
+ for j in range(0, n - i - 1):
+ if arr[j] > arr[j + 1]:
+ arr[j], arr[j + 1] = arr[j + 1], arr[j]
+ return arr
+\`\`\``,
+ name: "Bubble Sort in Python",
+ params: {},
+ hide: false,
+ depth: 0,
+ },
+ {
+ description: "Now write it in Rust",
+ name: "User Input",
+ params: {},
+ },
+ {
+ description: "Hello! This is a test...\n\n1, 2, 3, testing...",
+ name: "Testing",
+ hide: false,
+ },
+ {
+ description: `Sure, here's bubble sort written in rust: \n\`\`\`rust
+fn bubble_sort(values: &mut[T]) {
+ let len = values.len();
+ for i in 0..len {
+ for j in 0..(len - i - 1) {
+ if values[j] > values[j + 1] {
+ values.swap(j, j + 1);
+ }
+ }
+ }
+}
+\`\`\`\nIs there anything else I can answer?`,
+ name: "Rust Bubble Sort",
+ depth: 0,
+ },
+];
+
const initialState: RootStore["state"] = {
history: [],
contextItems: [],
active: false,
config: defaultConfig,
+ title: "New Session",
+ sessionId: v4(),
};
export const stateSlice = createSlice({
@@ -14,7 +93,10 @@ export const stateSlice = createSlice({
initialState,
reducers: {
setConfig: (state, action) => {
- state.config = action.payload;
+ return {
+ ...state,
+ config: action.payload,
+ };
},
addContextItemsAtIndex: (state, action) => {
if (action.payload.index < state.history.length) {
@@ -73,7 +155,10 @@ export const stateSlice = createSlice({
state.active = true;
},
setInactive: (state) => {
- state.active = false;
+ return {
+ ...state,
+ active: false,
+ };
},
streamUpdate: (state, action) => {
if (state.history.length > 0) {
@@ -81,10 +166,26 @@ export const stateSlice = createSlice({
action.payload;
}
},
- newSession: (state) => {
- state.history = [];
- state.contextItems = [];
- state.active = false;
+ newSession: (
+ state,
+ { payload }: { payload: PersistedSessionInfo | undefined }
+ ) => {
+ if (payload) {
+ return {
+ ...state,
+ history: payload.history,
+ title: payload.title,
+ sessionId: payload.sessionId,
+ };
+ }
+ return {
+ ...state,
+ history: [],
+ contextItems: [],
+ active: false,
+ title: "New Session",
+ sessionId: v4(),
+ };
},
deleteContextWithIds: (
state,
@@ -120,6 +221,109 @@ export const stateSlice = createSlice({
};
}
},
+ addHighlightedCode: (
+ state,
+ {
+ payload,
+ }: {
+ payload: { rangeInFileWithContents: any; edit: boolean };
+ }
+ ) => {
+ let contextItems = [...state.contextItems].map((item) => {
+ return { ...item, editing: false };
+ });
+ const base = payload.rangeInFileWithContents.filepath
+ .split(/[\\/]/)
+ .pop();
+
+ // Merge if there is overlap
+ for (let i = 0; i < contextItems.length; i++) {
+ const item = contextItems[i];
+ if (item.description === payload.rangeInFileWithContents.filepath) {
+ let newStart = payload.rangeInFileWithContents.range.start.line;
+ let newEnd = payload.rangeInFileWithContents.range.end.line;
+ let [oldStart, oldEnd] = item.name
+ .split("(")[1]
+ .split(")")[0]
+ .split("-")
+ .map((x: string) => parseInt(x) - 1);
+ if (newStart > oldEnd || newEnd < oldStart) {
+ continue;
+ }
+ const startLine = Math.min(newStart, oldStart);
+ const endLine = Math.max(newEnd, oldEnd);
+
+ // const oldContents = item.content.split("\n");
+ // const newContents =
+ // payload.rangeInFileWithContents.contents.split("\n");
+ // const finalContents = [];
+
+ contextItems[i] = {
+ ...item,
+ name: `${base} (${startLine + 1}-${endLine + 1})`,
+ content: payload.rangeInFileWithContents.contents,
+ editing: true,
+ editable: true,
+ };
+ return { ...state, contextItems };
+ }
+ }
+
+ const lineNums = `(${
+ payload.rangeInFileWithContents.range.start.line + 1
+ }-${payload.rangeInFileWithContents.range.end.line + 1})`;
+ contextItems.push({
+ name: `${base} ${lineNums}`,
+ description: payload.rangeInFileWithContents.filepath,
+ id: {
+ providerTitle: "code",
+ itemId: v4(),
+ },
+ content: payload.rangeInFileWithContents.contents,
+ editing: true,
+ editable: true,
+ });
+
+ return { ...state, contextItems };
+ },
+ setEditingAtIds: (
+ state,
+ {
+ payload,
+ }: { payload: { ids: ContextItemId[]; index: number | undefined } }
+ ) => {
+ const ids = payload.ids.map((id) => id.itemId);
+
+ if (typeof payload.index === "undefined") {
+ return {
+ ...state,
+ contextItems: state.contextItems.map((item) => {
+ return {
+ ...item,
+ editing: ids.includes(item.id.itemId),
+ };
+ }),
+ };
+ } else {
+ return {
+ ...state,
+ history: state.history.map((step, i) => {
+ if (i === payload.index) {
+ return {
+ ...step,
+ contextItems: step.contextItems.map((item) => {
+ return {
+ ...item,
+ editing: ids.includes(item.id.itemId),
+ };
+ }),
+ };
+ }
+ return step;
+ }),
+ };
+ }
+ },
},
});
@@ -133,5 +337,7 @@ export const {
newSession,
deleteContextWithIds,
resubmitAtIndex,
+ addHighlightedCode,
+ setEditingAtIds,
} = stateSlice.actions;
export default stateSlice.reducer;
diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts
index b13d53584..7b96935fa 100644
--- a/gui/src/redux/store.ts
+++ b/gui/src/redux/store.ts
@@ -4,11 +4,7 @@ import miscReducer from "./slices/miscSlice";
import uiStateReducer from "./slices/uiStateSlice";
import serverStateReducer from "./slices/serverStateReducer";
import stateReducer from "./slices/stateSlice";
-import sessionStateReducer, {
- SessionFullState,
-} from "./slices/sessionStateReducer";
import { ContinueConfig } from "../schema/ContinueConfig";
-// import { ContextItem } from "../schema/ContextItem";
import { ContextItem } from "core/llm/types";
import { ContextProviderDescription } from "../schema/ContextProviderDescription";
import { SlashCommandDescription } from "../schema/SlashCommandDescription";
@@ -29,6 +25,8 @@ export interface RootStore {
contextItems: ContextItem[];
active: boolean;
config: SerializedContinueConfig;
+ title: string;
+ sessionId: string;
};
config: {
@@ -46,7 +44,6 @@ export interface RootStore {
dialogMessage: string | JSX.Element;
dialogEntryOn: boolean;
};
- sessionState: SessionFullState;
serverState: {
meilisearchUrl: string | undefined;
slashCommands: SlashCommandDescription[];
@@ -63,7 +60,6 @@ const rootReducer = combineReducers({
config: configReducer,
misc: miscReducer,
uiState: uiStateReducer,
- sessionState: sessionStateReducer,
serverState: serverStateReducer,
});
|