diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index d30874a94..29797cc81 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,12 +1,17 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionMetadata } from "core"; -import React, { useState } from "react"; -import { useDispatch } from "react-redux"; +import React, { useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; -import useHistory from "../../hooks/useHistory"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { useAppSelector } from "../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { + deleteSession, + getSession, + loadSession, + updateSession, +} from "../../redux/thunks/session"; function lastPartOfPath(path: string): string { const sep = path.includes("/") ? "/" : "\\"; @@ -16,18 +21,15 @@ function lastPartOfPath(path: string): string { export function HistoryTableRow({ sessionMetadata, date, - onDelete, - onEdit, index, }: { sessionMetadata: SessionMetadata; date: Date; - onDelete: (sessionId: string) => void; - onEdit: (session: SessionMetadata) => void; index: number; }) { - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const navigate = useNavigate(); + const ideMessenger = useContext(IdeMessengerContext); const [hovered, setHovered] = useState(false); const [editing, setEditing] = useState(false); @@ -36,24 +38,30 @@ export function HistoryTableRow({ ); const currentSessionId = useAppSelector((state) => state.session.id); - const { saveSession, deleteSession, loadSession, getSession, updateSession } = - useHistory(dispatch); + useEffect(() => { + setSessionTitleEditValue(sessionMetadata.title); + }, [sessionMetadata]); const handleKeyUp = async (e: React.KeyboardEvent) => { if (e.key === "Enter") { if (sessionTitleEditValue !== sessionMetadata.title) { - const sessionData = await getSession(sessionMetadata.sessionId); - sessionData.title = sessionTitleEditValue; - await updateSession(sessionData); - onEdit({ - ...sessionMetadata, - title: sessionTitleEditValue, - }); + // imperfect solution of loading session just to update it + // but fine for now, pretty low latency + const currentSession = await getSession( + ideMessenger, + sessionMetadata.sessionId, + ); + await dispatch( + updateSession({ + ...currentSession, + title: sessionTitleEditValue, + }), + ); } setEditing(false); } else if (e.key === "Escape") { - setEditing(false); setSessionTitleEditValue(sessionMetadata.title); + setEditing(false); } }; @@ -68,12 +76,14 @@ export function HistoryTableRow({
{ - // Save current session if (sessionMetadata.sessionId !== currentSessionId) { - await saveSession(); - await loadSession(sessionMetadata.sessionId); + await dispatch( + loadSession({ + sessionId: sessionMetadata.sessionId, + saveCurrentSession: true, + }), + ); } - navigate("/"); }} > @@ -93,7 +103,7 @@ export function HistoryTableRow({
) : ( - {JSON.stringify(sessionMetadata.title).slice(1, -1)} + {sessionMetadata.title} )} @@ -130,8 +140,7 @@ export function HistoryTableRow({ text="Delete" onClick={async (e) => { e.stopPropagation(); - await deleteSession(sessionMetadata.sessionId); - onDelete(sessionMetadata.sessionId); + await dispatch(deleteSession(sessionMetadata.sessionId)); }} > diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index 425d1a5fb..9c6bc054e 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -1,9 +1,7 @@ import { SessionMetadata } from "core"; import MiniSearch from "minisearch"; import React, { Fragment, useEffect, useMemo, useRef, useState } from "react"; -import { useDispatch } from "react-redux"; -import useHistory from "../../hooks/useHistory"; import { getFontSize, getMetaKeyLabel } from "../../util"; import { HistoryTableRow } from "./HistoryTableRow"; import { XMarkIcon } from "@heroicons/react/24/solid"; @@ -21,13 +19,8 @@ const HEADER_CLASS = "flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6"; export function History() { - const [sessions, setSessions] = useState([]); - const searchInputRef = React.useRef(null); - const dispatch = useDispatch(); - const { getHistory, lastSessionId } = useHistory(dispatch); - const [searchTerm, setSearchTerm] = useState(""); const sessionTitle = useAppSelector((state) => state.session.title); @@ -39,47 +32,24 @@ export function History() { }), ).current; + const allSessionMetadata = useAppSelector( + (state) => state.session.allSessionMetadata, + ); + useEffect(() => { - const fetchSessions = async () => { - const sessions = await getHistory(); - setSessions(sessions); - - try { - // Consider adding just last session to existing instead of clearing/adding all - minisearch.removeAll(); - minisearch.addAll( - sessions.map((session) => ({ - title: session.title, - sessionId: session.sessionId, - id: session.sessionId, - })), - ); - } catch (e) { - console.log("error adding sessions to minisearch", e); - } - }; - fetchSessions(); - }, [lastSessionId, sessionTitle]); - - const deleteSessionInUI = async (sessionId: string) => { - setSessions((prev) => - prev.filter((session) => session.sessionId !== sessionId), - ); - minisearch.discard(sessionId); - }; - - const updateSessionInUI = async (session: SessionMetadata) => { - setSessions((prev) => - prev.map((sess) => - sess.sessionId === session.sessionId ? session : sess, - ), - ); - minisearch.replace({ - title: session.title, - sessionId: session.sessionId, - id: session.sessionId, - }); - }; + try { + minisearch.removeAll(); + minisearch.addAll( + allSessionMetadata.map((session) => ({ + title: session.title, + sessionId: session.sessionId, + id: session.sessionId, + })), + ); + } catch (e) { + console.log("error adding sessions to minisearch", e); + } + }, [allSessionMetadata]); const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => { const sessionIds = minisearch @@ -88,7 +58,7 @@ export function History() { }) .map((result) => result.id); - return sessions + return allSessionMetadata .filter((session) => { return searchTerm === "" || sessionIds.includes(session.sessionId); }) @@ -97,7 +67,7 @@ export function History() { parseDate(b.dateCreated).getTime() - parseDate(a.dateCreated).getTime(), ); - }, [sessions, searchTerm, minisearch]); + }, [allSessionMetadata, searchTerm, minisearch]); const yesterday = new Date(Date.now() - 1000 * 60 * 60 * 24); const lastWeek = new Date(Date.now() - 1000 * 60 * 60 * 24 * 7); @@ -171,11 +141,9 @@ export function History() { )} ); diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 2f4b13f2f..b183e24e4 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -2,7 +2,6 @@ import { useEffect, useMemo } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; import { CustomScrollbarDiv, defaultBorderRadius } from "."; -import { LastSessionProvider } from "../context/LastSessionContext"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setEditStatus, focusEdit } from "../redux/slices/editModeState"; @@ -22,8 +21,8 @@ import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; import PostHogPageView from "./PosthogPageView"; import AccountDialog from "./AccountDialog"; import { AuthProvider } from "../context/Auth"; -import useHistory from "../hooks/useHistory"; import { exitEditMode } from "../redux/thunks"; +import { loadLastSession, saveCurrentSession } from "../redux/thunks/session"; const LayoutTopDiv = styled(CustomScrollbarDiv)` height: 100%; @@ -55,7 +54,6 @@ const Layout = () => { const dispatch = useAppDispatch(); const onboardingCard = useOnboardingCard(); const { pathname } = useLocation(); - const { saveSession, loadLastSession } = useHistory(dispatch); const configError = useAppSelector((state) => state.config.configError); @@ -159,7 +157,11 @@ const Layout = () => { useWebviewListener( "focusEdit", async () => { - await saveSession(false); + await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); dispatch(newSession()); dispatch(focusEdit()); dispatch(setMode("edit")); @@ -170,8 +172,11 @@ const Layout = () => { useWebviewListener( "focusEditWithoutClear", async () => { - await saveSession(false); - dispatch(newSession()); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); dispatch(focusEdit()); dispatch(setMode("edit")); }, @@ -195,10 +200,11 @@ const Layout = () => { ); useWebviewListener("exitEditMode", async () => { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); }); @@ -231,61 +237,53 @@ const Layout = () => { } }, [location]); - useEffect(() => { - if (isStreaming === false) { - saveSession(false); - } - }, [isStreaming]); - return ( - - -
+
+ { + dispatch(setShowDialog(false)); }} - > - { - dispatch(setShowDialog(false)); - }} - onClose={() => { - dispatch(setShowDialog(false)); - }} - message={dialogMessage} - /> - - - - - - {hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && ( -
navigate(ROUTES.CONFIG_ERROR)} - > - Error!{" "} - - Could not load config.json - -
Learn More
-
- )} -
- -
-
{ + dispatch(setShowDialog(false)); + }} + message={dialogMessage} /> - - + + + + + + {hasFatalErrors && pathname !== ROUTES.CONFIG_ERROR && ( +
navigate(ROUTES.CONFIG_ERROR)} + > + Error!{" "} + + Could not load config.json + +
Learn More
+
+ )} +
+ +
+
+ ); }; diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index d653012f0..ac6078818 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -1,11 +1,11 @@ import { useDispatch } from "react-redux"; import { useNavigate } from "react-router-dom"; import { TabTitle } from "../components/OnboardingCardTabs"; -import useHistory from "../../../hooks/useHistory"; import { setOnboardingCard } from "../../../redux/slices/uiSlice"; import { OnboardingCardState } from ".."; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; -import { useAppSelector } from "../../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { saveCurrentSession } from "../../../redux/thunks/session"; export interface UseOnboardingCard { show: OnboardingCardState["show"]; @@ -17,8 +17,7 @@ export interface UseOnboardingCard { export function useOnboardingCard(): UseOnboardingCard { const navigate = useNavigate(); - const dispatch = useDispatch(); - const { saveSession } = useHistory(dispatch); + const dispatch = useAppDispatch(); const onboardingCard = useAppSelector((state) => state.ui.onboardingCard); @@ -37,11 +36,15 @@ export function useOnboardingCard(): UseOnboardingCard { show = onboardingStatus !== "Completed" && !hasDismissedOnboardingCard; } - function open(tab: TabTitle) { + async function open(tab: TabTitle) { navigate("/"); // Used to clear the chat panel before showing onboarding card - saveSession(); + dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); dispatch(setOnboardingCard({ show: true, activeTab: tab })); } diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index 4c4f89a75..bd1f1f5d9 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -5,8 +5,8 @@ import FeedbackButtons from "./FeedbackButtons"; import { renderChatMessage } from "core/util/messageContent"; import { CopyIconButton } from "../gui/CopyIconButton"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import useHistory from "../../hooks/useHistory"; import { exitEditMode } from "../../redux/thunks/exitEditMode"; +import { loadLastSession } from "../../redux/thunks/session"; export interface EditActionsProps { index: number; @@ -18,7 +18,6 @@ export default function EditActions({ index, item }: EditActionsProps) { // (store: RootState) => store.state.curCheckpointIndex, // ); const dispatch = useAppDispatch(); - const { loadLastSession } = useHistory(dispatch); const isStreaming = useAppSelector((state) => state.session.isStreaming); @@ -58,12 +57,13 @@ export default function EditActions({ index, item }: EditActionsProps) { {hasPendingApplies && ( { + onAcceptOrReject={async (outcome) => { if (outcome === "acceptDiff") { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); } }} diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index f83c27d1e..d80d0e50c 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -27,7 +27,7 @@ import { selectIsInEditMode, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; -import useHistory from "../../hooks/useHistory"; +import { loadLastSession } from "../../redux/thunks/session"; const StyledDiv = styled.div<{ isHidden?: boolean }>` padding-top: 4px; @@ -89,7 +89,6 @@ function InputToolbar(props: InputToolbarProps) { const useActiveFile = useAppSelector(selectUseActiveFile); const isInEditMode = useAppSelector(selectIsInEditMode); const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); - const { loadLastSession } = useHistory(dispatch); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit; const shouldRenderToolsButton = @@ -193,11 +192,12 @@ function InputToolbar(props: InputToolbarProps) { {isInEditMode && ( { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + onClick={async (e) => { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); }} > diff --git a/gui/src/components/mainInput/TipTapEditor.tsx b/gui/src/components/mainInput/TipTapEditor.tsx index 561d044d0..1aee79743 100644 --- a/gui/src/components/mainInput/TipTapEditor.tsx +++ b/gui/src/components/mainInput/TipTapEditor.tsx @@ -37,7 +37,6 @@ import { } from ".."; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useSubmenuContextProviders } from "../../context/SubmenuContextProviders"; -import useHistory from "../../hooks/useHistory"; import { useInputHistory } from "../../hooks/useInputHistory"; import useIsOSREnabled from "../../hooks/useIsOSREnabled"; import useUpdatingRef from "../../hooks/useUpdatingRef"; @@ -73,6 +72,11 @@ import { setMainEditorContentTrigger, } from "../../redux/slices/sessionSlice"; import { exitEditMode } from "../../redux/thunks"; +import { + loadLastSession, + loadSession, + saveCurrentSession, +} from "../../redux/thunks/session"; const InputBoxDiv = styled.div<{ border?: string }>` resize: none; @@ -187,8 +191,6 @@ function TipTapEditor(props: TipTapEditorProps) { const useActiveFile = useAppSelector(selectUseActiveFile); - const { saveSession, loadSession, loadLastSession } = useHistory(dispatch); - const posthog = usePostHog(); const inSubmenuRef = useRef(undefined); @@ -420,12 +422,14 @@ function TipTapEditor(props: TipTapEditorProps) { if (inDropdownRef.current || !isInEditModeRef.current) { return false; } - - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), - ); - - dispatch(exitEditMode()); + (async () => { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + dispatch(exitEditMode()); + })(); return true; }, @@ -695,14 +699,18 @@ function TipTapEditor(props: TipTapEditorProps) { dispatch(clearCodeToEdit()); if (historyLength > 0) { - await saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); } setTimeout(() => { editor?.commands.blur(); editor?.commands.focus("end"); }, 20); }, - [historyLength, saveSession, editor, props.isMainInput], + [historyLength, editor, props.isMainInput], ); useWebviewListener( @@ -724,12 +732,16 @@ function TipTapEditor(props: TipTapEditorProps) { if (!props.isMainInput) { return; } - await saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); setTimeout(() => { editor?.commands.focus("end"); }, 20); }, - [editor, props.isMainInput, saveSession], + [editor, props.isMainInput], ); useWebviewListener( @@ -850,12 +862,17 @@ function TipTapEditor(props: TipTapEditorProps) { useWebviewListener( "focusContinueSessionId", async (data) => { - if (!props.isMainInput) { + if (!props.isMainInput || !data.sessionId) { return; } - loadSession(data.sessionId); + await dispatch( + loadSession({ + sessionId: data.sessionId, + saveCurrentSession: true, + }), + ); }, - [loadSession, props.isMainInput], + [props.isMainInput], ); const [showDragOverMsg, setShowDragOverMsg] = useState(false); diff --git a/gui/src/context/LastSessionContext.tsx b/gui/src/context/LastSessionContext.tsx deleted file mode 100644 index d3b555dc6..000000000 --- a/gui/src/context/LastSessionContext.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import React, { createContext, useState } from "react"; - -export const LastSessionContext = createContext<{ - lastSessionId: string | undefined; - setLastSessionId: (id: string | undefined) => void; -}>({ - lastSessionId: undefined, - setLastSessionId: () => {}, -}); - -export const LastSessionProvider: React.FC<{ - children: React.ReactNode; -}> = ({ children }) => { - const [lastSessionId, setLastSessionId] = useState(); - - return ( - - {children} - - ); -}; - -export const useLastSessionContext = () => React.useContext(LastSessionContext); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx deleted file mode 100644 index 63252d8f1..000000000 --- a/gui/src/hooks/useHistory.tsx +++ /dev/null @@ -1,164 +0,0 @@ -import { Dispatch } from "@reduxjs/toolkit"; -import { Session, SessionMetadata } from "core"; -import { NEW_SESSION_TITLE } from "core/util/constants"; -import { renderChatMessage } from "core/util/messageContent"; -import { useCallback, useContext } from "react"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { useLastSessionContext } from "../context/LastSessionContext"; -import { useAppSelector } from "../redux/hooks"; -import { newSession, updateSessionTitle } from "../redux/slices/sessionSlice"; -import { getLocalStorage, setLocalStorage } from "../util/localStorage"; - -const MAX_TITLE_LENGTH = 100; - -function truncateText(text: string, maxLength: number) { - if (text.length > maxLength) { - return text.slice(0, maxLength - 3) + "..."; - } - return text; -} - -function useHistory(dispatch: Dispatch) { - const sessionId = useAppSelector((store) => store.session.id); - const config = useAppSelector((store) => store.config.config); - const history = useAppSelector((store) => store.session.history); - const title = useAppSelector((store) => store.session.title); - const ideMessenger = useContext(IdeMessengerContext); - const { lastSessionId, setLastSessionId } = useLastSessionContext(); - const selectedModelTitle = useAppSelector( - (store) => store.config.defaultModelTitle, - ); - - const updateLastSessionId = useCallback((sessionId: string) => { - setLastSessionId(sessionId); - setLocalStorage("lastSessionId", sessionId); - }, []); - - async function getHistory( - offset?: number, - limit?: number, - ): Promise { - const result = await ideMessenger.request("history/list", { - offset, - limit, - }); - return result.status === "success" ? result.content : []; - } - - async function getChatTitle(message?: string): Promise { - if (!selectedModelTitle) { - console.error("Failed to get chat title"); - return; - } - const result = await ideMessenger.request("chatDescriber/describe", { - text: message, - selectedModelTitle, - }); - return result.status === "success" ? result.content : undefined; - } - - async function saveSession(openNewSession: boolean = true) { - if (history.length === 0) return; - - if (openNewSession) { - dispatch(newSession()); - updateLastSessionId(sessionId); - } - - let currentTitle = title; - if (config?.ui?.getChatTitles && currentTitle === NEW_SESSION_TITLE) { - try { - // Check if we have first assistant response - let assistantResponse = history - ?.filter((h) => h.message.role === "assistant")[0] - ?.message?.content?.toString(); - - if (assistantResponse) { - currentTitle = await getChatTitle(assistantResponse); - } - } catch (e) { - throw new Error("Unable to get chat title"); - } - } - - // Fallback if we get an error above or if the user has not set getChatTitles - let newTitle = - currentTitle === NEW_SESSION_TITLE - ? truncateText( - renderChatMessage(history[0].message) - .split("\n") - .filter((l) => l.trim() !== "") - .slice(-1)[0] || "", - MAX_TITLE_LENGTH, - ) - : currentTitle?.length > 0 - ? currentTitle - : (await getSession(sessionId)).title; // to ensure titles are synced with updates from history page. - - const session: Session = { - sessionId, - title: newTitle, - workspaceDirectory: window.workspacePaths?.[0] || "", - history, - }; - - await ideMessenger.request("history/save", session); - - if (!openNewSession) { - dispatch(updateSessionTitle(newTitle)); - } - } - - async function getSession(id: string): Promise { - const result = await ideMessenger.request("history/load", { id }); - if (result.status === "error") { - throw new Error(result.error); - } - return result.content; - } - - async function updateSession(session: Session) { - return await ideMessenger.request("history/save", session); - } - - async function deleteSession(id: string) { - return await ideMessenger.request("history/delete", { id }); - } - - async function loadSession(id: string): Promise { - updateLastSessionId(sessionId); - const result = await ideMessenger.request("history/load", { id }); - if (result.status === "error") { - throw new Error(result.error); - } - - const sessionContent = result.content; - dispatch(newSession(sessionContent)); - return sessionContent; - } - - async function loadLastSession(): Promise { - const lastSessionId = getLocalStorage("lastSessionId"); - if (lastSessionId) { - return await loadSession(lastSessionId); - } - } - - function getLastSessionId(): string | undefined { - return getLocalStorage("lastSessionId"); - } - - return { - getHistory, - saveSession, - deleteSession, - loadSession, - loadLastSession, - getLastSessionId, - updateSession, - getSession, - lastSessionId, - }; -} - -export default useHistory; diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index ec1284e06..1ad3b2765 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -19,6 +19,7 @@ import { } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; import useUpdatingRef from "./useUpdatingRef"; +import { refreshSessionMetadata } from "../redux/thunks/session"; function useSetup(dispatch: AppDispatch) { const ideMessenger = useContext(IdeMessengerContext); @@ -26,7 +27,7 @@ function useSetup(dispatch: AppDispatch) { const defaultModelTitle = useAppSelector( (store) => store.config.defaultModelTitle, ); - const defaultModelTitleRef = useUpdatingRef(defaultModelTitle); + const hasLoadedConfig = useRef(false); const loadConfig = useCallback( async (initial: boolean) => { @@ -62,6 +63,7 @@ function useSetup(dispatch: AppDispatch) { // Init to run on initial config load ideMessenger.post("docs/getSuggestedDocs", undefined); ideMessenger.post("docs/initStatuses", undefined); + dispatch(refreshSessionMetadata({})); // This triggers sending pending status to the GUI for relevant docs indexes clearInterval(interval); diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 347220084..ea7ed37fd 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -1,29 +1,26 @@ import { - ArrowLeftIcon, ArrowTopRightOnSquareIcon, DocumentArrowUpIcon, TableCellsIcon, } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { useNavigate } from "react-router-dom"; -import { vscBackground } from "../../components"; import KeyboardShortcuts from "./KeyboardShortcuts"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { useDispatch } from "react-redux"; import { setOnboardingCard } from "../../redux/slices/uiSlice"; -import useHistory from "../../hooks/useHistory"; import MoreHelpRow from "./MoreHelpRow"; import IndexingProgress from "./IndexingProgress"; import DocsIndexingStatuses from "../../components/indexing/DocsIndexingStatuses"; import PageHeader from "../../components/PageHeader"; +import { useAppDispatch } from "../../redux/hooks"; +import { saveCurrentSession } from "../../redux/thunks/session"; function MorePage() { useNavigationListener(); - const dispatch = useDispatch(); + const dispatch = useAppDispatch(); const navigate = useNavigate(); const ideMessenger = useContext(IdeMessengerContext); - const { saveSession } = useHistory(dispatch); return (
@@ -87,10 +84,14 @@ function MorePage() { title="Quickstart" description="Reopen the quickstart and tutorial file" Icon={DocumentArrowUpIcon} - onClick={() => { + onClick={async () => { navigate("/"); // Used to clear the chat panel before showing onboarding card - saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); dispatch(setOnboardingCard({ show: true, activeTab: "Best" })); ideMessenger.post("showTutorial", undefined); }} diff --git a/gui/src/pages/error.tsx b/gui/src/pages/error.tsx index d7e10f51a..0014a580e 100644 --- a/gui/src/pages/error.tsx +++ b/gui/src/pages/error.tsx @@ -48,7 +48,6 @@ const ErrorPage: React.FC = () => { localStorage.removeItem("inputHistory_chat"); // localStorage.removeItem("showTutorialCard"); // localStorage.removeItem("onboardingStatus"); - // localStorage.removeItem("lastSessionId"); navigate("/"); }} > diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 66d6183f1..ea514b833 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -37,7 +37,6 @@ import PageHeader from "../../components/PageHeader"; import StepContainer from "../../components/StepContainer"; import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { IdeMessengerContext } from "../../context/IdeMessenger"; -import useHistory from "../../hooks/useHistory"; import { useTutorialCard } from "../../hooks/useTutorialCard"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -72,6 +71,10 @@ import ConfigErrorIndicator from "./ConfigError"; import { ToolCallDiv } from "./ToolCallDiv"; import { ToolCallButtons } from "./ToolCallDiv/ToolCallButtonsDiv"; import ToolOutput from "./ToolCallDiv/ToolOutput"; +import { + loadLastSession, + saveCurrentSession, +} from "../../redux/thunks/session"; const StopButton = styled.div` background-color: ${vscBackground}; @@ -149,8 +152,6 @@ export function Chat() { const showChatScrollbar = useAppSelector( (state) => state.config.config.ui?.showChatScrollbar, ); - const { saveSession, getLastSessionId, loadLastSession } = - useHistory(dispatch); const codeToEdit = useAppSelector((state) => state.session.codeToEdit); const toolCallState = useSelector( selectCurrentToolCall, @@ -166,7 +167,7 @@ export function Chat() { const isSingleRangeEditOrInsertion = useAppSelector( selectIsSingleRangeEditOrInsertion, ); - + const lastSessionId = useAppSelector((state) => state.session.lastSessionId); const snapToBottom = useCallback(() => { if (!stepsDivRef.current) return; const elem = stepsDivRef.current; @@ -320,11 +321,16 @@ export function Chat() { useWebviewListener( "newSession", async () => { - saveSession(); + await dispatch( + saveCurrentSession({ + openNewSession: true, + }), + ); + // unwrapResult(response) // errors if session creation failed mainTextInputRef.current?.focus?.(); dispatch(exitEditMode()); }, - [saveSession], + [mainTextInputRef], ); const isLastUserInput = useCallback( @@ -343,14 +349,9 @@ export function Chat() { {isInEditMode && ( { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), - ); - - if (isInEditMode) { - dispatch(exitEditMode()); - } + onClick={async () => { + await dispatch(loadLastSession({ saveCurrentSession: false })); + dispatch(exitEditMode()); }} /> )} @@ -497,14 +498,16 @@ export function Chat() { >
- {history.length === 0 && getLastSessionId() && !isInEditMode && ( + {history.length === 0 && lastSessionId && !isInEditMode && (
- loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), - ) - } + onClick={async () => { + await dispatch( + loadLastSession({ + saveCurrentSession: true, + }), + ); + }} className="flex items-center gap-2" > @@ -519,12 +522,13 @@ export function Chat() { {hasPendingApplies && isSingleRangeEditOrInsertion && ( { + onAcceptOrReject={async (outcome) => { if (outcome === "acceptDiff") { - loadLastSession().catch((e) => - console.error(`Failed to load last session: ${e}`), + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), ); - dispatch(exitEditMode()); } }} diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index c8b3f1048..75a73af2b 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -17,6 +17,7 @@ import { MessageModes, PromptLog, Session, + SessionMetadata, ToolCall, } from "core"; import { NEW_SESSION_TITLE } from "core/util/constants"; @@ -34,6 +35,8 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & { }; type SessionState = { + lastSessionId?: string; + allSessionMetadata: SessionMetadata[]; history: ChatHistoryItemWithMessageId[]; isStreaming: boolean; title: string; @@ -72,6 +75,7 @@ function isCodeToEditEqual(a: CodeToEdit, b: CodeToEdit) { } const initialState: SessionState = { + allSessionMetadata: [], history: [], isStreaming: false, title: NEW_SESSION_TITLE, @@ -86,6 +90,7 @@ const initialState: SessionState = { states: [], curIndex: 0, }, + lastSessionId: undefined, }; export const sessionSlice = createSlice({ @@ -344,6 +349,8 @@ export const sessionSlice = createSlice({ } }, newSession: (state, { payload }: PayloadAction) => { + state.lastSessionId = state.id; + state.streamAborter.abort(); state.streamAborter = new AbortController(); @@ -357,14 +364,58 @@ export const sessionSlice = createSlice({ state.curCheckpointIndex = 0; } else { state.history = []; - state.title = "New Session"; + state.title = NEW_SESSION_TITLE; state.id = uuidv4(); state.curCheckpointIndex = 0; } }, + updateSessionTitle: (state, { payload }: PayloadAction) => { state.title = payload; }, + setAllSessionMetadata: ( + state, + { payload }: PayloadAction, + ) => { + state.allSessionMetadata = payload; + }, + ////////////////////////////////////////////////////////////////////////////////// + // These are for optimistic session metadata updates, especially for History page + addSessionMetadata: ( + state, + { payload }: PayloadAction, + ) => { + state.allSessionMetadata = [...state.allSessionMetadata, payload]; + }, + updateSessionMetadata: ( + state, + { + payload, + }: PayloadAction< + { + sessionId: string; + } & Partial + >, + ) => { + state.allSessionMetadata = state.allSessionMetadata.map((session) => + session.sessionId === payload.sessionId + ? { + ...session, + ...payload, + } + : session, + ); + if (payload.title && payload.sessionId === state.id) { + state.title = payload.title; + } + }, + deleteSessionMetadata: (state, { payload }: PayloadAction) => { + // Note, should not be allowed to delete current session from chat session + state.allSessionMetadata = state.allSessionMetadata.filter( + (session) => session.sessionId !== payload, + ); + }, + ////////////////////////////////////////////////////////////////////////////////// addHighlightedCode: ( state, { @@ -585,6 +636,10 @@ export const { setToolGenerated, setToolCallOutput, setMode, + setAllSessionMetadata, + addSessionMetadata, + updateSessionMetadata, + deleteSessionMetadata, } = sessionSlice.actions; export const { diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts new file mode 100644 index 000000000..f0553f4bb --- /dev/null +++ b/gui/src/redux/thunks/session.ts @@ -0,0 +1,217 @@ +import { createAsyncThunk, Dispatch, unwrapResult } from "@reduxjs/toolkit"; +import { ChatMessage, Session, SessionMetadata } from "core"; +import { NEW_SESSION_TITLE } from "core/util/constants"; +import { renderChatMessage } from "core/util/messageContent"; +import { ThunkApiType } from "../store"; +import { + deleteSessionMetadata, + newSession, + setAllSessionMetadata, + updateSessionMetadata, +} from "../slices/sessionSlice"; +import { IIdeMessenger } from "../../context/IdeMessenger"; + +const MAX_TITLE_LENGTH = 100; + +// Async session functions live in thunks (because of IDE messaging mostly) +// see sessionSlice for sync redux session functions + +export async function getSession( + ideMessenger: IIdeMessenger, + id: string, +): Promise { + const result = await ideMessenger.request("history/load", { id }); + if (result.status === "error") { + throw new Error(result.error); + } + return result.content; +} + +export const refreshSessionMetadata = createAsyncThunk< + SessionMetadata[], + { + offset?: number; + limit?: number; + }, + ThunkApiType +>("session/refreshMetadata", async ({ offset, limit }, { dispatch, extra }) => { + const result = await extra.ideMessenger.request("history/list", { + limit, + offset, + }); + if (result.status === "error") { + throw new Error(result.error); + } + dispatch(setAllSessionMetadata(result.content)); + return result.content; +}); + +export const deleteSession = createAsyncThunk( + "session/delete", + async (id, { getState, dispatch, extra }) => { + dispatch(deleteSessionMetadata(id)); // optimistic + const state = getState(); + if (id === state.session.id) { + await dispatch( + loadLastSession({ + saveCurrentSession: false, + }), + ); + } + const result = await extra.ideMessenger.request("history/delete", { id }); + if (result.status === "error") { + throw new Error(result.error); + } + dispatch(refreshSessionMetadata({})); + }, +); + +export const updateSession = createAsyncThunk( + "session/update", + async (session, { extra, dispatch }) => { + dispatch( + updateSessionMetadata({ + sessionId: session.sessionId, + title: session.title, + }), + ); // optimistic session metadata update + await extra.ideMessenger.request("history/save", session); + await dispatch(refreshSessionMetadata({})); + }, +); + +/* + this is only used for the custom focusContinueSessionId command at the moment +*/ +export const loadSession = createAsyncThunk< + void, + { + sessionId: string; + saveCurrentSession: boolean; + }, + ThunkApiType +>( + "session/load", + async ({ sessionId, saveCurrentSession: save }, { extra, dispatch }) => { + if (save) { + const result = await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); + unwrapResult(result); + } + const session = await getSession(extra.ideMessenger, sessionId); + dispatch(newSession(session)); + }, +); + +export const loadLastSession = createAsyncThunk< + void, + { + saveCurrentSession: boolean; + }, + ThunkApiType +>( + "session/loadLast", + async ({ saveCurrentSession }, { extra, dispatch, getState }) => { + const state = getState(); + + if (state.session.id && saveCurrentSession) { + } + const lastSessionId = getState().session.lastSessionId; + + if (!lastSessionId) { + dispatch(newSession()); + return; + } + + const session = await getSession(extra.ideMessenger, lastSessionId); + dispatch(newSession(session)); + }, +); + +function getChatTitleFromMessage(message: ChatMessage) { + const text = + renderChatMessage(message) + .split("\n") + .filter((l) => l.trim() !== "") + .slice(-1)[0] || ""; + + // Truncate + if (text.length > MAX_TITLE_LENGTH) { + return text.slice(0, MAX_TITLE_LENGTH - 3) + "..."; + } + return text; +} + +export const saveCurrentSession = createAsyncThunk< + void, + { openNewSession: boolean }, + ThunkApiType +>( + "session/saveCurrent", + async ({ openNewSession }, { dispatch, extra, getState }) => { + const state = getState(); + if (state.session.history.length === 0) { + return; + } + + if (openNewSession) { + dispatch(newSession()); + } + + // New session has already been dispatched + // Now save previous session and update chat title if relevant + let title = state.session.title; + if (title === NEW_SESSION_TITLE) { + if ( + state.config.config?.ui?.getChatTitles && + state.config.defaultModelTitle + ) { + let assistantResponse = state.session.history + ?.filter((h) => h.message.role === "assistant")[0] + ?.message?.content?.toString(); + + if (assistantResponse) { + const result = await extra.ideMessenger.request( + "chatDescriber/describe", + { + text: assistantResponse, + selectedModelTitle: state.config.defaultModelTitle, + }, + ); + if (result.status === "success" && result.content) { + title = result.content; + } + } + } + // Fallbacks if above doesn't work out or getChatTitles = false + if (title === NEW_SESSION_TITLE) { + title = getChatTitleFromMessage(history[0].message); + } + } + // More fallbacks in case of no title + if (!title.length) { + const metadata = getState().session.allSessionMetadata.find( + (m) => m.sessionId === state.session.id, + ); + if (metadata?.title) { + title = metadata.title; + } + } + if (!title.length) { + title = NEW_SESSION_TITLE; + } + + const session: Session = { + sessionId: state.session.id, + title, + workspaceDirectory: window.workspacePaths?.[0] || "", + history: state.session.history, + }; + + const result = await dispatch(updateSession(session)); + unwrapResult(result); + }, +); diff --git a/gui/src/redux/thunks/streamThunkWrapper.ts b/gui/src/redux/thunks/streamThunkWrapper.ts index da67b2814..7b9000be8 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.ts +++ b/gui/src/redux/thunks/streamThunkWrapper.ts @@ -1,6 +1,7 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { saveCurrentSession } from "./session"; export const streamThunkWrapper = createAsyncThunk< void, @@ -15,6 +16,10 @@ export const streamThunkWrapper = createAsyncThunk< dispatch(clearLastEmptyResponse()); } finally { dispatch(setInactive()); - // triggerSave(!save); TODO + await dispatch( + saveCurrentSession({ + openNewSession: false, + }), + ); } }); diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index 1f3fa7a61..f457e3544 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -8,7 +8,6 @@ type LocalStorageTypes = { ide: "vscode" | "jetbrains"; ftc: number; fontSize: number; - lastSessionId: string | undefined; [key: `inputHistory_${string}`]: JSONContent[]; extensionVersion: string; showTutorialCard: boolean;