Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🪟 refactor: Serve ChatView and the Sidebar Through the Chat Provider (#17423)

Marco Berettac376b9071932
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx
index bddfae5c0c..417d017228 100644
--- a/client/src/components/Chat/ChatView.tsx
+++ b/client/src/components/Chat/ChatView.tsx
@@ -5,24 +5,11 @@ import { useForm } from 'react-hook-form';
import { Spinner } from '@librechat/client';
import { useParams } from 'react-router-dom';
import { Constants, buildTree } from 'librechat-data-provider';
-import {
- useQueueDrain,
- submissionByIndex,
- useIsSubmitting,
- useQueuedTurnReveal,
- ComposerRestoreProvider,
-} from '@librechat/chat/react';
-import type { TChatProject } from 'librechat-data-provider';
+import { submissionByIndex, ComposerRestoreProvider } from '@librechat/chat/react';
+import type { TChatProject, TMessage } from 'librechat-data-provider';
import type { ChatFormValues } from '~/common';
-import {
- useScrollbarGutterSeed,
- useAddedResponse,
- useResumeOnLoad,
- useAdaptiveSSE,
- useChatHelpers,
- useLocalize,
-} from '~/hooks';
-import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers';
+import { AddedChatContext, ChatFormProvider, useChatContext, useFileMapContext } from '~/Providers';
+import { useScrollbarGutterSeed, useAddedResponse, useLocalize } from '~/hooks';
import Footer, { useLandingFooter, useConfiguredFooter } from './Footer';
import { QueuedTurnPortalProvider } from './Steering/QueuedTurnPortal';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
@@ -31,8 +18,8 @@ import ConversationStarters from './Input/ConversationStarters';
import { pendingApprovalActionFamily } from './approval/state';
import ProjectBadge from '~/components/Projects/ProjectBadge';
import { composerLiftFamily } from './Input/Composer/state';
+import { ChatSessionProvider } from '~/hooks/Chat/provider';
import { OwnerTextProvider } from './Messages/PrivateText';
-import { useGetMessagesByConvoId } from '~/data-provider';
import { AskAnswerHostProvider } from './ask/state';
import MessagesView from './Messages/MessagesView';
import Presentation from './Presentation';
@@ -54,20 +41,27 @@ function LoadingSpinner() {
);
}
-function ChatView({
- index = 0,
- project,
- routePending = false,
-}: {
+type ChatViewProps = {
index?: number;
project?: TChatProject;
/** The route is loading another conversation, or failed to. */
routePending?: boolean;
+};
+
+function ChatPane({
+ index = 0,
+ project,
+ routePending = false,
+ conversationId,
+ messages,
+ isLoading,
+}: ChatViewProps & {
+ conversationId?: string;
+ messages: TMessage[] | null;
+ isLoading: boolean;
}) {
- const { conversationId } = useParams();
const localize = useLocalize();
const rootSubmission = useAtomValue(submissionByIndex(index));
- const isSubmitting = useIsSubmitting(index);
const { saveDrafts } = useChatSettings();
const enterToSend = useRecoilValue(store.enterToSend);
const autoSendText = useRecoilValue(store.autoSendText);
@@ -99,51 +93,19 @@ function ChatView({
const fileMap = useFileMapContext();
- const {
- data: messages = null,
- isLoading,
- isFetching,
- } = useGetMessagesByConvoId(
- conversationId ?? '',
- {
- enabled: !!conversationId && conversationId !== Constants.SEARCH,
- /** Refetch stale caches on mount: navigation invalidates (not removes)
- * messages now, so a warm conversation renders instantly from cache and
- * reconciles in the background instead of unmounting into a spinner. */
- refetchOnMount: true,
- },
- { isStreaming: isSubmitting },
- );
const messagesTree = useMemo(() => {
const dataTree = buildTree({ messages, fileMap });
return dataTree?.length === 0 ? null : (dataTree ?? null);
}, [messages, fileMap]);
- const chatHelpers = useChatHelpers(index, conversationId);
+ const chat = useChatContext();
const addedChatHelpers = useAddedResponse();
const activeConversation =
- chatHelpers.conversation?.conversationId === conversationId
- ? chatHelpers.conversation
- : undefined;
+ chat.conversation?.conversationId === conversationId ? chat.conversation : undefined;
const activeSubagentThread = activeConversation?.subagentThread;
const chatProjectId = activeConversation?.chatProjectId || undefined;
- useAdaptiveSSE(rootSubmission, chatHelpers, false, index);
-
- // Auto-resume if navigating back to conversation with active job.
- // Wait for messages to load AND the warm-cache background revalidation to
- // settle: a stale invalidated cache mounts with isLoading false while the
- // refetch is in flight, and resume must not build from (or race) it.
- useResumeOnLoad(conversationId, chatHelpers.getMessages, index, !isLoading && !isFetching);
-
- // Show a server-owned queued follow-up as the next user turn as soon as its
- // predecessor completes, ahead of the receipt and active-job polls.
- const revealQueuedTurn = useQueuedTurnReveal(conversationId, index);
-
- // Auto-send queued follow-up messages once a run finishes cleanly.
- useQueueDrain(index, conversationId, chatHelpers.ask, revealQueuedTurn);
-
let content: JSX.Element | null | undefined;
const isLandingPage =
(!messagesTree || messagesTree.length === 0) &&
@@ -173,10 +135,7 @@ function ChatView({
// Recoil conversation can lag the route during navigation; only announce a
// title that belongs to the conversation currently in the URL.
- const conversationTitle =
- chatHelpers.conversation?.conversationId === conversationId
- ? chatHelpers.conversation?.title?.trim()
- : undefined;
+ const conversationTitle = activeConversation?.title?.trim();
const pageHeading =
isLandingPage || !conversationTitle ? localize('com_ui_new_chat') : conversationTitle;
const parentConversationId = activeSubagentThread?.parentConversationId;
@@ -190,36 +149,33 @@ function ChatView({
<ChatFormProvider {...methods}>
<ComposerRestoreProvider>
<QueuedTurnPortalProvider>
- <ChatContext.Provider value={chatHelpers}>
- <AddedChatContext.Provider value={addedChatHelpers}>
- <ApprovalProvider pendingAction={pendingAction}>
- <Presentation routePending={routePending}>
- <TraceSurface conversationId={conversationId}>
- <h1 className="sr-only">{pageHeading}</h1>
- {/* Marks the header's controls as this pane's, so a pane-scoped
+ <AddedChatContext.Provider value={addedChatHelpers}>
+ <ApprovalProvider pendingAction={pendingAction}>
+ <Presentation routePending={routePending}>
+ <TraceSurface conversationId={conversationId}>
+ <h1 className="sr-only">{pageHeading}</h1>
+ {/* Marks the header's controls as this pane's, so a pane-scoped
shortcut pressed from them acts here, not on the first pane. */}
- <div data-chat-pane-portal={index} className="contents">
- <Header
- parentConversationId={parentConversationId}
- readOnly={isSubagentThreadReadOnly}
- />
- </div>
- {!isLandingPage && chatProjectId && (
- <ProjectBadge projectId={chatProjectId} />
- )}
- <>
- <div
- data-chat-pane={index}
- style={
- isLandingPage && composerLift > 0
- ? { transform: `translateY(-${composerLift}px)` }
- : undefined
- }
- className={cn(
- 'flex flex-col',
- isLandingPage && 'relative',
- isLandingPage
- ? /* The gutter is reserved once per state, wherever the
+ <div data-chat-pane-portal={index} className="contents">
+ <Header
+ parentConversationId={parentConversationId}
+ readOnly={isSubagentThreadReadOnly}
+ />
+ </div>
+ {!isLandingPage && chatProjectId && <ProjectBadge projectId={chatProjectId} />}
+ <>
+ <div
+ data-chat-pane={index}
+ style={
+ isLandingPage && composerLift > 0
+ ? { transform: `translateY(-${composerLift}px)` }
+ : undefined
+ }
+ className={cn(
+ 'flex flex-col',
+ isLandingPage && 'relative',
+ isLandingPage
+ ? /* The gutter is reserved once per state, wherever the
centring happens. A conversation centres the composer
inside the band below, against a message column that
holds the scrollbar band back; the landing page centres
@@ -227,73 +183,72 @@ function ChatView({
together, so it holds the same band back here. Without
it the composer lands 4px right of where a conversation
puts it and slides sideways on the way in. */
- 'scrollbar-gutter-spacer flex-1 items-center justify-end sm:justify-center'
- : 'h-full overflow-y-auto',
- !isLandingPage && chatProjectId && 'pt-9',
- )}
+ 'scrollbar-gutter-spacer flex-1 items-center justify-end sm:justify-center'
+ : 'h-full overflow-y-auto',
+ !isLandingPage && chatProjectId && 'pt-9',
+ )}
+ >
+ <OwnerTextProvider
+ messages={messages}
+ conversationId={conversationId}
+ isSubmitting={chat.isSubmitting}
>
- <OwnerTextProvider
- messages={messages}
- conversationId={conversationId}
- isSubmitting={chatHelpers.isSubmitting}
- >
- {content}
- </OwnerTextProvider>
- {/* Named + opaque so a view transition (the ask_user_question
+ {content}
+ </OwnerTextProvider>
+ {/* Named + opaque so a view transition (the ask_user_question
popover ⇄ chat-card morph) paints the whole composer band
over the travelling card instead of letting it show
through below the composer. The background matches the
page, so normal rendering is unchanged. The named surface
is a stacking context; keep it above positioned tool glyphs
so they cannot paint through the approval preview. */}
- <div
- ref={composerBandRef}
- className={cn(
- 'bg-surface-canvas relative z-10 w-full [view-transition-name:chat-form]',
- !isLandingPage && 'scrollbar-gutter-spacer',
- isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',
- )}
- >
- {isLandingPage && <ConversationStarters />}
- {isSubagentThreadReadOnly ? (
- <div
- className="text-text-secondary mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm xl:max-w-4xl"
- role="note"
- >
- {localize('com_ui_subagent_thread_read_only')}
- </div>
- ) : (
- <ChatForm
- index={index}
- routePending={routePending}
- placeholder={chatFormPlaceholder}
- project={isProjectLandingPage ? project : undefined}
- isLandingPage={isLandingPage}
- enterToSend={enterToSend}
- autoSendText={autoSendText}
- speechSettingsInitialized={speechSettingsInitialized}
- footerBelow={footerBelow}
- centerFormOnLanding={centerFormOnLanding}
- />
- )}
- {/* The generic disclaimer and the policy links are the
+ <div
+ ref={composerBandRef}
+ className={cn(
+ 'bg-surface-canvas relative z-10 w-full [view-transition-name:chat-form]',
+ !isLandingPage && 'scrollbar-gutter-spacer',
+ isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',
+ )}
+ >
+ {isLandingPage && <ConversationStarters />}
+ {isSubagentThreadReadOnly ? (
+ <div
+ className="text-text-secondary mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm xl:max-w-4xl"
+ role="note"
+ >
+ {localize('com_ui_subagent_thread_read_only')}
+ </div>
+ ) : (
+ <ChatForm
+ index={index}
+ routePending={routePending}
+ placeholder={chatFormPlaceholder}
+ project={isProjectLandingPage ? project : undefined}
+ isLandingPage={isLandingPage}
+ enterToSend={enterToSend}
+ autoSendText={autoSendText}
+ speechSettingsInitialized={speechSettingsInitialized}
+ footerBelow={footerBelow}
+ centerFormOnLanding={centerFormOnLanding}
+ />
+ )}
+ {/* The generic disclaimer and the policy links are the
welcome screen's; a deployment's own footer stays
with the conversation that always showed it. */}
- {!fullFooter && configuredFooter && <Footer configuredOnly />}
- </div>
- <Lia
- bandRef={composerBandRef}
- landing={isLandingPage}
- submission={rootSubmission}
- />
+ {!fullFooter && configuredFooter && <Footer configuredOnly />}
</div>
- {fullFooter && <Footer />}
- </>
- </TraceSurface>
- </Presentation>
- </ApprovalProvider>
- </AddedChatContext.Provider>
- </ChatContext.Provider>
+ <Lia
+ bandRef={composerBandRef}
+ landing={isLandingPage}
+ submission={rootSubmission}
+ />
+ </div>
+ {fullFooter && <Footer />}
+ </>
+ </TraceSurface>
+ </Presentation>
+ </ApprovalProvider>
+ </AddedChatContext.Provider>
</QueuedTurnPortalProvider>
</ComposerRestoreProvider>
</ChatFormProvider>
@@ -301,4 +256,22 @@ function ChatView({
);
}
+function ChatView(props: ChatViewProps) {
+ const { index = 0 } = props;
+ const { conversationId } = useParams();
+
+ return (
+ <ChatSessionProvider index={index} conversationId={conversationId}>
+ {({ messages, isLoading }) => (
+ <ChatPane
+ {...props}
+ conversationId={conversationId}
+ messages={messages}
+ isLoading={isLoading}
+ />
+ )}
+ </ChatSessionProvider>
+ );
+}
+
export default memo(ChatView);
diff --git a/client/src/components/Chat/__tests__/ChatView.spec.tsx b/client/src/components/Chat/__tests__/ChatView.spec.tsx
index 92e87a6f0d..6902c2ef14 100644
--- a/client/src/components/Chat/__tests__/ChatView.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.spec.tsx
@@ -38,11 +38,18 @@ jest.mock('@librechat/chat/react', () => ({
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => (key === 'com_ui_new_chat' ? 'New chat' : key),
- useChatHelpers: () => ({ conversation: mockConversation() }),
useAddedResponse: () => ({}),
+ useScrollbarGutterSeed: jest.fn(),
+}));
+
+jest.mock('~/hooks/Chat/useChatHelpers', () => ({
+ __esModule: true,
+ default: () => ({ conversation: mockConversation() }),
+}));
+
+jest.mock('~/hooks/SSE', () => ({
useAdaptiveSSE: jest.fn(),
useResumeOnLoad: jest.fn(),
- useScrollbarGutterSeed: jest.fn(),
}));
jest.mock('../Presentation', () => ({
diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
index 5b16b6e1d9..8affd7f2f5 100644
--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
@@ -35,23 +35,30 @@ jest.mock('@librechat/chat/react', () => ({
jest.mock('~/hooks', () => ({
useAddedResponse: () => ({}),
- useResumeOnLoad: jest.fn(),
- useAdaptiveSSE: jest.fn(),
useScrollbarGutterSeed: jest.fn(),
useLocalize: () => (key: string) => key,
- useChatHelpers: () => ({
+}));
+
+jest.mock('~/hooks/Chat/useChatHelpers', () => ({
+ __esModule: true,
+ default: () => ({
conversation: mockConversation,
getMessages: jest.fn(),
ask: jest.fn(),
}),
}));
+jest.mock('~/hooks/SSE', () => ({
+ useAdaptiveSSE: jest.fn(),
+ useResumeOnLoad: jest.fn(),
+}));
+
jest.mock('~/Providers', () => {
const Passthrough = ({ children }: { children: React.ReactNode }) => <>{children}</>;
const Context = { Provider: Passthrough };
return {
- ChatContext: Context,
AddedChatContext: Context,
+ useChatContext: jest.requireActual('~/Providers/ChatContext').useChatContext,
ChatFormProvider: Passthrough,
ComposerRestoreProvider: Passthrough,
useFileMapContext: () => new Map(),
diff --git a/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx b/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx
index bf71938691..462ac92ac1 100644
--- a/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx
+++ b/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx
@@ -17,16 +17,17 @@ import {
DRAWER_UNPAINTED,
} from './constants';
import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog';
-import { ChatContext, ChatFormProvider, ActivePanelProvider } from '~/Providers';
import { MobileHeader, MobileBottomBar, MobileShortcutTargets } from './mobile';
import AgentMarketplaceButton from '~/components/Nav/AgentMarketplaceButton';
import { MyFilesModal } from '~/components/Chat/Input/Files/MyFilesModal';
import useUnifiedSidebarLinks from '~/hooks/Nav/useUnifiedSidebarLinks';
+import { ChatFormProvider, ActivePanelProvider } from '~/Providers';
import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';
import useSidebarState from '~/hooks/Nav/useSidebarState';
-import { useChatHelpers, useLocalize } from '~/hooks';
import SidePanelNav from '~/components/SidePanel/Nav';
+import { ChatProvider } from '~/hooks/Chat/provider';
import { createResizeMeasure } from './resize';
+import { useLocalize } from '~/hooks';
import Sidebar from './Sidebar';
import { cn } from '~/utils';
@@ -36,17 +37,16 @@ function getInitialWidth(): number {
}
/**
- * Isolates useChatHelpers Recoil subscriptions from the sidebar layout.
- * Atom changes (e.g. during streaming) only re-render this component
- * and the active panel — not the sidebar shell, resize logic, or icon strip.
- * This works because Recoil subscriptions don't propagate to parent components.
+ * Isolates the root pane's chat contract subscriptions from the sidebar layout.
+ * Atom changes (e.g. during streaming) only re-render `ChatProvider` and the
+ * active panel, not the sidebar shell, resize logic, or icon strip, because
+ * atom subscriptions don't propagate to parent components.
*/
function SidebarChatProvider({ children }: { children: ReactNode }) {
- const chatHelpers = useChatHelpers(0);
const sidebarFormMethods = useForm<ChatFormValues>({ defaultValues: { text: '' } });
return (
<ChatFormProvider {...sidebarFormMethods}>
- <ChatContext.Provider value={chatHelpers}>{children}</ChatContext.Provider>
+ <ChatProvider index={0}>{children}</ChatProvider>
</ChatFormProvider>
);
}
diff --git a/client/src/components/UnifiedSidebar/__tests__/drawerPaint.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/drawerPaint.spec.tsx
index 32daf4e9c6..64a896fbf4 100644
--- a/client/src/components/UnifiedSidebar/__tests__/drawerPaint.spec.tsx
+++ b/client/src/components/UnifiedSidebar/__tests__/drawerPaint.spec.tsx
@@ -42,12 +42,14 @@ jest.mock('~/hooks/Nav/useUnifiedSidebarLinks', () => ({
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
- useChatHelpers: () => ({}),
useShowMarketplace: () => false,
}));
+jest.mock('~/hooks/Chat/provider', () => ({
+ ChatProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
jest.mock('~/Providers', () => ({
- ChatContext: { Provider: ({ children }: { children: ReactNode }) => <>{children}</> },
ChatFormProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
ActivePanelProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
diff --git a/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx b/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx
index 054c81a2ee..42968b83be 100644
--- a/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx
+++ b/client/src/components/UnifiedSidebar/mobile/ShortcutTargets.tsx
@@ -11,7 +11,7 @@ import { useActivePanel, resolveActivePanel } from '~/Providers';
* These hidden buttons keep that contract intact without reviving the rail.
* Routing the shortcuts through `useActivePanel` instead would mean hoisting
* `ActivePanelProvider` above `SidebarChatProvider`, which exists specifically
- * to keep panel changes from re-running `useChatHelpers`.
+ * to keep panel changes from rebuilding the chat contract in `ChatProvider`.
*
* Only available links render, so a shortcut for a panel this endpoint does not
* offer still correctly does nothing.
diff --git a/client/src/hooks/Chat/__tests__/provider.spec.tsx b/client/src/hooks/Chat/__tests__/provider.spec.tsx
index 6df6843416..ea3d16c08d 100644
--- a/client/src/hooks/Chat/__tests__/provider.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/provider.spec.tsx
@@ -1,18 +1,34 @@
import React from 'react';
+import { MemoryRouter } from 'react-router-dom';
import { renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TConversation } from 'librechat-data-provider';
import type { ChatContract } from '../contract';
+import { ChatProvider, ChatSessionProvider } from '../provider';
import { useChatActions } from '../facade';
-import { ChatProvider } from '../provider';
const mockUseChatHelpers = jest.fn();
+const mockUseAdaptiveSSE = jest.fn();
+const mockUseResumeOnLoad = jest.fn();
+const mockUseQueueDrain = jest.fn();
+const mockRevealQueuedTurn = jest.fn();
jest.mock('../useChatHelpers', () => ({
__esModule: true,
default: (index?: number, paramId?: string) => mockUseChatHelpers(index, paramId),
}));
+jest.mock('~/hooks/SSE', () => ({
+ useAdaptiveSSE: (...args: unknown[]) => mockUseAdaptiveSSE(...args),
+ useResumeOnLoad: (...args: unknown[]) => mockUseResumeOnLoad(...args),
+}));
+
+jest.mock('@librechat/chat/react', () => ({
+ ...jest.requireActual('@librechat/chat/react'),
+ useQueuedTurnReveal: () => mockRevealQueuedTurn,
+ useQueueDrain: (...args: unknown[]) => mockUseQueueDrain(...args),
+}));
+
const noop = () => undefined;
const contract: ChatContract = {
@@ -81,3 +97,36 @@ describe('ChatProvider', () => {
expect(mockUseChatHelpers).toHaveBeenCalledWith(0, undefined);
});
});
+
+describe('ChatSessionProvider', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockUseChatHelpers.mockReturnValue(contract);
+ });
+
+ it('runs the stream, resume and queue drain against the contract it serves', () => {
+ const queryClient = new QueryClient();
+ const { result } = renderHook(() => useChatActions(), {
+ wrapper: ({ children }) => (
+ <MemoryRouter>
+ <QueryClientProvider client={queryClient}>
+ <ChatSessionProvider index={1} conversationId="convo-1">
+ {() => children}
+ </ChatSessionProvider>
+ </QueryClientProvider>
+ </MemoryRouter>
+ ),
+ });
+
+ expect(mockUseChatHelpers).toHaveBeenCalledWith(1, 'convo-1');
+ expect(result.current.id).toBe('convo-1');
+ expect(mockUseAdaptiveSSE).toHaveBeenCalledWith(null, contract, false, 1);
+ expect(mockUseResumeOnLoad).toHaveBeenCalledWith('convo-1', contract.getMessages, 1, false);
+ expect(mockUseQueueDrain).toHaveBeenCalledWith(
+ 1,
+ 'convo-1',
+ contract.ask,
+ mockRevealQueuedTurn,
+ );
+ });
+});
diff --git a/client/src/hooks/Chat/provider.tsx b/client/src/hooks/Chat/provider.tsx
index e5974de430..8213665045 100644
--- a/client/src/hooks/Chat/provider.tsx
+++ b/client/src/hooks/Chat/provider.tsx
@@ -1,4 +1,15 @@
+import { useAtomValue } from 'jotai';
+import { Constants } from 'librechat-data-provider';
+import {
+ useQueueDrain,
+ useIsSubmitting,
+ submissionByIndex,
+ useQueuedTurnReveal,
+} from '@librechat/chat/react';
+import type { TMessage } from 'librechat-data-provider';
import type { ReactNode } from 'react';
+import { useAdaptiveSSE, useResumeOnLoad } from '~/hooks/SSE';
+import { useGetMessagesByConvoId } from '~/data-provider';
import { ChatContext } from '~/Providers/ChatContext';
import useChatHelpers from './useChatHelpers';
@@ -21,3 +32,67 @@ export function ChatProvider({
const chat = useChatHelpers(index, conversationId);
return <ChatContext.Provider value={chat}>{children}</ChatContext.Provider>;
}
+
+/** The pane's messages query, as `ChatSessionProvider` hands it to the pane it renders. */
+export type ChatSessionMessages = {
+ messages: TMessage[] | null;
+ isLoading: boolean;
+};
+
+/**
+ * `ChatProvider` for the pane that owns the conversation's stream: it also loads the
+ * conversation's messages and runs the SSE connection, resume on load and the queued-turn drain
+ * against the contract it serves.
+ *
+ * Every session hook runs in this one component, in the order the pane has always run them:
+ * the messages query subscribes (and starts its mount refetch) before the contract and the
+ * session effects commit, and the queue drain commits after `useChatHelpers`, so `ask` has
+ * released its in-flight guard and sees the refetch before the drain can call it. The pane is
+ * a render function so it re-renders with every session render, as it did when it ran these
+ * hooks itself.
+ */
+export function ChatSessionProvider({
+ index = 0,
+ conversationId,
+ children,
+}: {
+ index?: number;
+ conversationId?: string;
+ children: (session: ChatSessionMessages) => ReactNode;
+}) {
+ const isSubmitting = useIsSubmitting(index);
+ const {
+ data: messages = null,
+ isLoading,
+ isFetching,
+ } = useGetMessagesByConvoId(
+ conversationId ?? '',
+ {
+ enabled: !!conversationId && conversationId !== Constants.SEARCH,
+ /** Refetch stale caches on mount: navigation invalidates (not removes)
+ * messages now, so a warm conversation renders instantly from cache and
+ * reconciles in the background instead of unmounting into a spinner. */
+ refetchOnMount: true,
+ },
+ { isStreaming: isSubmitting },
+ );
+
+ const chat = useChatHelpers(index, conversationId);
+ const rootSubmission = useAtomValue(submissionByIndex(index));
+
+ useAdaptiveSSE(rootSubmission, chat, false, index);
+
+ /** Auto-resume waits for messages to load AND the warm-cache background revalidation to
+ * settle: a stale invalidated cache mounts with isLoading false while the refetch is in
+ * flight, and resume must not build from (or race) it. */
+ useResumeOnLoad(conversationId, chat.getMessages, index, !isLoading && !isFetching);
+
+ /** Shows a server-owned queued follow-up as the next user turn as soon as its predecessor
+ * completes, ahead of the receipt and active-job polls. */
+ const revealQueuedTurn = useQueuedTurnReveal(conversationId, index);
+ useQueueDrain(index, conversationId, chat.ask, revealQueuedTurn);
+
+ return (
+ <ChatContext.Provider value={chat}>{children({ messages, isLoading })}</ChatContext.Provider>
+ );
+}
diff --git a/e2e/specs/mock/scenarios/reload-resume.spec.ts b/e2e/specs/mock/scenarios/reload-resume.spec.ts
index c7994eef0c..a58466951f 100644
--- a/e2e/specs/mock/scenarios/reload-resume.spec.ts
+++ b/e2e/specs/mock/scenarios/reload-resume.spec.ts
@@ -74,4 +74,48 @@ test.describe('reload during a reply', () => {
expect(events[snapshot]).not.toContain(LONG_REPLY_LAST_CHUNK);
expect(terminal - snapshot).toBeGreaterThan(1);
});
+
+ test('returning to a chat mid-reply shows the reply finishing @scenario:returning-to-a-running-chat-finishes-its-reply', async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ const label = `return-resume-${Date.now()}`;
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10_000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const setup = await sendMessage(page, replyPrompt(`${label}-setup`));
+ expect(setup.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(replyText(`${label}-setup`))).toBeVisible({
+ timeout: 30_000,
+ });
+ await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/, { timeout: 15_000 });
+ const conversationPath = new URL(page.url()).pathname;
+
+ const response = await sendMessage(page, `${LONG_REPLY_MARKER}:${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText('chunk-010')).toBeVisible({ timeout: 15_000 });
+
+ /** In-app navigation keeps the warm message cache, so the return exercises the
+ * resume gate that waits for the background revalidation, not a cold load. */
+ await page
+ .getByRole('link', { name: 'New chat', exact: true })
+ .or(page.getByRole('button', { name: 'New chat', exact: true }))
+ .filter({ visible: true })
+ .first()
+ .click();
+ await expect(page).toHaveURL(/\/c\/new$/);
+ await page.goBack();
+ await expect(page).toHaveURL((url) => url.pathname === conversationPath);
+
+ const assistantMessage = messagesView(page).locator('.message-render').last();
+ await expect(assistantMessage).toContainText(LONG_REPLY_LAST_CHUNK, { timeout: 90_000 });
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden();
+
+ await page.reload();
+ await expect(messagesView(page).locator('.message-render').last()).toContainText(
+ LONG_REPLY_LAST_CHUNK,
+ { timeout: 30_000 },
+ );
+ });
});