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: Move Resume-on-Load and Stream Steer State Into the Chat Package (#17565)

Marco Beretta0269b9688991
diff --git a/client/src/Providers/ChatHostContext.tsx b/client/src/Providers/ChatHostContext.tsx
index c13784d475..becf077e12 100644
--- a/client/src/Providers/ChatHostContext.tsx
+++ b/client/src/Providers/ChatHostContext.tsx
@@ -12,7 +12,6 @@ import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import { getMappingOptions } from '~/hooks/Chat/outcomes';
import useTurnServices from '~/hooks/Chat/services';
-import { useResumeOnLoad } from '~/hooks/SSE';
import useNewConvo from '~/hooks/useNewConvo';
/** Cache events that add, drop or rewrite a query's data. */
@@ -124,9 +123,6 @@ export const appChatHost: ChatHost = {
useFeedbackEnabled: () => useChatSettings().config.feedbackEnabled,
getMappingOptions,
useMessages,
- useSessionEffects: ({ index, conversationId, chat, isSettled }) => {
- useResumeOnLoad(conversationId, chat.getMessages, index, isSettled);
- },
};
export { ChatHostProvider, useChatHost } from '@librechat/chat/react';
diff --git a/client/src/Providers/StreamHostContext.tsx b/client/src/Providers/StreamHostContext.tsx
index f062bcae28..1adc16e253 100644
--- a/client/src/Providers/StreamHostContext.tsx
+++ b/client/src/Providers/StreamHostContext.tsx
@@ -1,7 +1,13 @@
import { useMemo } from 'react';
import type { StreamHost } from '@librechat/chat/react';
-import { useActiveJobs, useAgentQueuedTurns, extendActiveJobsGrace } from '~/data-provider';
+import {
+ useActiveJobs,
+ useStreamStatus,
+ useAgentQueuedTurns,
+ extendActiveJobsGrace,
+} from '~/data-provider';
import { useChatTransport } from '~/Providers/ChatTransportContext';
+import { useChatSettings } from '~/Providers/ChatSettingsContext';
import { useResumableServices } from '~/hooks/SSE/resumable';
import { useAuthContext } from '~/hooks/AuthContext';
import useSSE from '~/hooks/SSE/useSSE';
@@ -26,6 +32,15 @@ export const appStreamHost: StreamHost = {
useQueuedTurnReceipts: (conversationId) => useAgentQueuedTurns(conversationId, false),
useActiveJobs,
extendActiveJobsGrace,
+ useStreamStatus,
+ useResumeSettings: (runIndex) => {
+ const { config, usePaneConversation } = useChatSettings();
+ return {
+ configLoaded: config.loaded !== false,
+ retentionMode: config.retentionMode,
+ conversation: usePaneConversation(runIndex),
+ };
+ },
};
export { StreamHostProvider, useStreamHost } from '@librechat/chat/react';
diff --git a/client/src/Providers/__tests__/ChatHostContext.spec.tsx b/client/src/Providers/__tests__/ChatHostContext.spec.tsx
index 7293b00e10..a500852c11 100644
--- a/client/src/Providers/__tests__/ChatHostContext.spec.tsx
+++ b/client/src/Providers/__tests__/ChatHostContext.spec.tsx
@@ -3,17 +3,9 @@ import { MemoryRouter } from 'react-router-dom';
import { renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Constants, QueryKeys, dataService } from 'librechat-data-provider';
-import type { ChatContract } from '@librechat/chat/react';
import type { TMessage } from 'librechat-data-provider';
import { appChatHost } from '../ChatHostContext';
-const mockUseResumeOnLoad = jest.fn();
-
-/** Resume owns the transport; the host only hands it the session's values. */
-jest.mock('~/hooks/SSE', () => ({
- useResumeOnLoad: (...args: unknown[]) => mockUseResumeOnLoad(...args),
-}));
-
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return {
@@ -77,20 +69,3 @@ describe('appChatHost.useMessages', () => {
expect(getMessages).not.toHaveBeenCalled();
});
});
-
-describe('appChatHost.useSessionEffects', () => {
- it('runs resume on load against the session contract', () => {
- const chat = { getMessages: jest.fn() } as unknown as ChatContract;
-
- renderHook(() =>
- appChatHost.useSessionEffects({
- index: 1,
- conversationId: 'convo-1',
- chat,
- isSettled: true,
- }),
- );
-
- expect(mockUseResumeOnLoad).toHaveBeenCalledWith('convo-1', chat.getMessages, 1, true);
- });
-});
diff --git a/client/src/hooks/Chat/__tests__/transport.spec.tsx b/client/src/hooks/Chat/__tests__/transport.spec.tsx
index 8b7c8bd4e7..914cc6c786 100644
--- a/client/src/hooks/Chat/__tests__/transport.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/transport.spec.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { useAtomValue, getDefaultStore } from 'jotai';
import { RecoilRoot, useSetRecoilState } from 'recoil';
+import { useResumeOnLoad } from '@librechat/chat/react';
import { act, renderHook, waitFor } from '@testing-library/react';
import { useChat, resumeRequestsAtom } from '@librechat/chat/react';
import { useChatHelpers, useResumableSSE } from '@librechat/chat/react';
@@ -37,7 +38,6 @@ import { usePaneConversation, usePaneConversationState } from '~/routes/ChatSett
import { ChatTransportContext } from '~/Providers/ChatTransportContext';
import { ChatContext, useChatContext } from '~/Providers/ChatContext';
import { startupConfigKey } from '~/data-provider/Endpoints/queries';
-import useResumeOnLoad from '~/hooks/SSE/useResumeOnLoad';
import { StreamHostTestProvider } from 'test/streamHost';
import { SteerHostTestProvider } from 'test/steerHost';
import { ChatHostTestProvider } from 'test/chatHost';
diff --git a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
index 7daa4b3465..5caabf3f71 100644
--- a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
+++ b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
@@ -1,4 +1,5 @@
import { RecoilRoot } from 'recoil';
+import { useResumeOnLoad } from '@librechat/chat/react';
import { renderHook, act, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Constants, ContentTypes, QueryKeys, RetentionMode } from 'librechat-data-provider';
@@ -36,7 +37,6 @@ import { usePaneConversation } from '~/routes/ChatSettings';
import { StreamHostTestProvider } from 'test/streamHost';
import { SteerHostTestProvider } from 'test/steerHost';
import { ChatHostTestProvider } from 'test/chatHost';
-import useResumeOnLoad from '../useResumeOnLoad';
import store from '~/store';
const mockUseStreamStatus = jest.fn();
diff --git a/client/src/hooks/SSE/index.ts b/client/src/hooks/SSE/index.ts
index d3081d1894..b5c35ee111 100644
--- a/client/src/hooks/SSE/index.ts
+++ b/client/src/hooks/SSE/index.ts
@@ -1,6 +1,6 @@
export { default as useSSE } from './useSSE';
export { useResumableSSE, useAdaptiveSSE } from '@librechat/chat/react';
-export { default as useResumeOnLoad } from './useResumeOnLoad';
+export { useResumeOnLoad } from '@librechat/chat/react';
export { useStepHandler } from '@librechat/chat/react';
export { useUsageHandler } from '@librechat/chat/react';
export { default as useContentHandler } from './useContentHandler';
diff --git a/client/src/hooks/SSE/steer.ts b/client/src/hooks/SSE/steer.ts
index c597c48009..b00fa70181 100644
--- a/client/src/hooks/SSE/steer.ts
+++ b/client/src/hooks/SSE/steer.ts
@@ -1,267 +1,2 @@
-import { useCallback, useMemo, useRef } from 'react';
-import { useStore } from 'jotai';
-import { useSteerConvert } from '@librechat/chat/react';
-import { pendingQuotesByConvoId } from '@librechat/chat/react';
-import { queuedMessagesByConvoId } from '@librechat/chat/react';
-import {
- pendingSteersByConvoId,
- appliedSteerIdsByConvoId,
- acceptedSteerClientIdsByConvoId,
- activeGenerationCreatedAtByConvoId,
- activeGenerationProtocolVersionByConvoId,
-} from '@librechat/chat/react';
-import {
- seedPendingSteers,
- settledSteerQuotes,
- removePendingSteers,
- RUN_ENDED_STATUSES,
- acceptedClientSteerIds,
- withoutRecoveredSteers,
- updatePendingSteerLabels,
- selectLocalSteersForQueue,
-} from '@librechat/chat';
-import type { TPendingSteer, TSteerUpdatedEvent } from 'librechat-data-provider';
-import type { GenerationProtocolVersion, PendingSteer } from '@librechat/chat';
-import {
- mergeRestagedQuotes,
- appendAppliedSteerIds,
- collectAppliedSteerIds,
- collectDroppedSteerQuotes,
-} from '~/utils';
-import { useFileMapContext } from '~/Providers';
-
-/**
- * The one place the stream handlers write steer state: pending-steer chips,
- * the applied and accepted id sets, the quotes a lost chip restages, and the
- * generation epoch a conversation's live run carries. The rules live in the
- * chat core (`core/steer/chips`); this binds them to the app's atoms.
- */
-export default function useSteerState() {
- const jotaiStore = useStore();
- const fileMap = useFileMapContext();
- const fileMapRef = useRef(fileMap);
- fileMapRef.current = fileMap;
-
- /** Converts steers that never reached an injection boundary into queued
- * follow-up messages (reported on the run's final/abort event; the abort
- * HTTP response consumes the same data as a fallback in useChatHelpers). */
- const convertSteersToQueued = useSteerConvert();
-
- /** Removes the pending chip once its steer is injected (the inline content
- * part becomes the durable record), and records the id so a 202 ACK that
- * arrives AFTER the applied event drops its chip instead of re-minting it.
- * Returns the ids seen by the durable set for the first time: the caller
- * stamps these as live-applied only when it actually commits the inline
- * part, so an abandoned placement or a replayed event cannot arm a draw-in
- * with no part mounting to consume it. */
- const resolveSteerChip = useCallback(
- (
- conversationId: string,
- steerId: string,
- clientSteerId?: string,
- appliedPartQuotes?: string[],
- ): string[] => {
- const settledIds = clientSteerId ? [steerId, clientSteerId] : [steerId];
- /** A part applied by a pre-quotes server carries no quotes while the
- * chip being settled may hold the only copy of the user's excerpts
- * (its 202 was lost, so the ACK-echo restore never ran). Re-stage
- * them before removal; `mergeRestagedQuotes` keeps this idempotent
- * with the ACK path for the same excerpts. */
- if (appliedPartQuotes == null || appliedPartQuotes.length === 0) {
- const droppedQuotes = settledSteerQuotes(
- jotaiStore.get(pendingSteersByConvoId(conversationId)),
- settledIds,
- );
- if (droppedQuotes != null) {
- jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
- mergeRestagedQuotes(prev, droppedQuotes),
- );
- }
- }
- const alreadyApplied = jotaiStore.get(appliedSteerIdsByConvoId(conversationId));
- const firstApplication = settledIds.filter((id) => !alreadyApplied.includes(id));
- jotaiStore.set(appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, settledIds),
- );
- jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
- removePendingSteers(prev, settledIds),
- );
- jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) =>
- withoutRecoveredSteers(prev, settledIds),
- );
- return firstApplication;
- },
- [jotaiStore],
- );
-
- /** Capability can change while the same generation resumes after HITL. */
- const updateSteerChips = useCallback(
- (event: TSteerUpdatedEvent) => {
- const acceptedClientIds = acceptedClientSteerIds(event.steers);
- if (acceptedClientIds.length > 0) {
- jotaiStore.set(acceptedSteerClientIdsByConvoId(event.conversationId), (prev) =>
- appendAppliedSteerIds(prev, acceptedClientIds),
- );
- }
- jotaiStore.set(pendingSteersByConvoId(event.conversationId), (prev) =>
- updatePendingSteerLabels(prev, event.steers),
- );
- },
- [jotaiStore],
- );
-
- /** Replaces the chip list with the server's still-queued steers (sync, resume). */
- const seedSteerChips = useCallback(
- (
- conversationId: string,
- steers: TPendingSteer[] | undefined,
- generationCreatedAt?: number,
- generationProtocolVersion: GenerationProtocolVersion = 1,
- ) => {
- const acceptedClientIds = acceptedClientSteerIds(steers);
- if (acceptedClientIds.length > 0) {
- jotaiStore.set(acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, acceptedClientIds),
- );
- }
- jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
- seedPendingSteers(prev, steers, {
- generationCreatedAt,
- generationProtocolVersion,
- storedFiles: fileMapRef.current,
- }),
- );
- },
- [jotaiStore],
- );
-
- /** Settles the chips of every steer whose applied part already rides `values`. */
- const settleAppliedSteerParts = useCallback(
- (conversationId: string, values: unknown[] | undefined) => {
- const ids = collectAppliedSteerIds(values);
- if (ids.length === 0) {
- return;
- }
- /** Chips settled by quote-less applied parts hold the only copy of
- * their excerpts (a pre-quotes server injected the words bare):
- * re-stage them as composer chips before the removal below. */
- const droppedQuotes = collectDroppedSteerQuotes(
- values,
- jotaiStore.get(pendingSteersByConvoId(conversationId)),
- );
- if (droppedQuotes.length > 0) {
- jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
- mergeRestagedQuotes(prev, droppedQuotes),
- );
- }
- jotaiStore.set(appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, ids),
- );
- jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
- removePendingSteers(prev, ids),
- );
- },
- [jotaiStore],
- );
-
- /** Sweeps this conversation's local chips (see `selectLocalSteersForQueue`)
- * into queued follow-ups. Error events carry no `pendingSteers` payload of
- * their own (the server drops its copy on failure); this is the only
- * source of truth for those runs; the `final` and error/404 terminals call
- * it (default `statuses`, i.e. `pending || failed`) alongside their own
- * server-reported list as a backstop for `failed` chips, which never rode
- * that list at all. The intentional-abort path passes `statuses: ['failed']`
- * since the run may still be live server-side there (see its call site). */
- const convertLocalSteersToQueued = useCallback(
- (
- conversationId: string,
- options?: {
- claimParked?: boolean;
- statuses?: readonly PendingSteer['status'][];
- excludeSteerIds?: Iterable<string>;
- generationProtocolVersion?: GenerationProtocolVersion;
- },
- ) => {
- const chips = jotaiStore.get(pendingSteersByConvoId(conversationId));
- const generationProtocolVersion =
- options?.generationProtocolVersion ??
- jotaiStore.get(activeGenerationProtocolVersionByConvoId(conversationId));
- const activeStatuses = options?.statuses ?? RUN_ENDED_STATUSES;
- const excluded = new Set(options?.excludeSteerIds ?? []);
- const accepted = selectLocalSteersForQueue(
- chips,
- activeStatuses.filter((status) => status === 'pending'),
- excluded,
- );
- if (accepted.length > 0) {
- convertSteersToQueued(conversationId, accepted, {
- claimParked: options?.claimParked,
- generationProtocolVersion,
- });
- }
- const failed = selectLocalSteersForQueue(
- chips,
- activeStatuses.filter((status) => status === 'failed'),
- excluded,
- );
- if (failed.length > 0) {
- convertSteersToQueued(conversationId, failed, {
- generationProtocolVersion,
- bindRecoverySource: false,
- /** Swept out of the chip surface so it cannot render under the next
- * reply, but the server refused these words: the rail holds the row
- * for Retry or an explicit send instead of draining it automatically. */
- needsExplicitSend: true,
- });
- }
- },
- [convertSteersToQueued, jotaiStore],
- );
-
- /** Conversation ids are reused by successive agent turns. Keep the exact
- * live epoch beside the UI controls, and only clear it if the terminal event
- * still belongs to the epoch that installed it. */
- const updateActiveGenerationCreatedAt = useCallback(
- (
- conversationId: string,
- next: number | null,
- expected?: number,
- generationProtocolVersion: GenerationProtocolVersion = 1,
- ): boolean => {
- const state = activeGenerationCreatedAtByConvoId(conversationId);
- if (expected != null && jotaiStore.get(state) !== expected) {
- return false;
- }
- jotaiStore.set(state, next);
- jotaiStore.set(
- activeGenerationProtocolVersionByConvoId(conversationId),
- next == null ? 1 : generationProtocolVersion,
- );
- return true;
- },
- [jotaiStore],
- );
-
- return useMemo(
- () => ({
- resolveSteerChip,
- updateSteerChips,
- seedSteerChips,
- settleAppliedSteerParts,
- convertSteersToQueued,
- convertLocalSteersToQueued,
- updateActiveGenerationCreatedAt,
- }),
- [
- resolveSteerChip,
- updateSteerChips,
- seedSteerChips,
- settleAppliedSteerParts,
- convertSteersToQueued,
- convertLocalSteersToQueued,
- updateActiveGenerationCreatedAt,
- ],
- );
-}
-
-export type SteerState = ReturnType<typeof useSteerState>;
+export { useSteerState as default } from '@librechat/chat/react';
+export type { SteerState } from '@librechat/chat/react';
diff --git a/client/src/utils/messages.ts b/client/src/utils/messages.ts
index 939ee971fe..df83431834 100644
--- a/client/src/utils/messages.ts
+++ b/client/src/utils/messages.ts
@@ -1,4 +1,5 @@
import { isEmptyContentPart } from '@librechat/chat/react';
+import { getBranchSiblingIndexesForTarget } from '@librechat/chat';
import { QueryKeys, Constants, buildTree, ContentTypes } from 'librechat-data-provider';
import {
hasStreamStartFailed,
@@ -7,6 +8,7 @@ import {
STREAM_START_FAILED_METADATA_KEY,
} from '@librechat/chat';
import type { Agents, TMessage, TMessageContentParts } from 'librechat-data-provider';
+import type { BranchSiblingIndex } from '@librechat/chat';
import type { QueryClient } from '@tanstack/react-query';
import type { LocalizeFunction, TMessageProps } from '~/common';
@@ -29,12 +31,10 @@ export function isUnacknowledgedUserMessage(message: TMessage): boolean {
);
}
-type SiblingIndexLookup = (parentMessageId: string | null | undefined) => number;
+export { getBranchSiblingIndexesForTarget };
+export type { BranchSiblingIndex };
-export type BranchSiblingIndex = {
- parentMessageId: string | null | undefined;
- siblingIdx: number;
-};
+type SiblingIndexLookup = (parentMessageId: string | null | undefined) => number;
export const selectActiveBranchTail = (
messages: TMessage[] | null | undefined,
@@ -95,54 +95,6 @@ export const getMessageBranchSiblingParentIds = (
return Array.from(parentIds);
};
-export const getBranchSiblingIndexesForTarget = (
- messages: TMessage[] | null | undefined,
- targetMessageId: string | null | undefined,
- rootSiblingKey: string | null | undefined,
-): BranchSiblingIndex[] => {
- if (!targetMessageId) {
- return [];
- }
-
- const messagesTree = buildTree({ messages: messages ?? null });
- if (!messagesTree?.length) {
- return [];
- }
-
- const branchIndexes: BranchSiblingIndex[] = [];
- const stack = [
- { siblings: messagesTree, parentMessageId: rootSiblingKey, index: 0, branchCount: 0 },
- ];
- while (stack.length > 0) {
- const frame = stack[stack.length - 1];
- const index = frame.index++;
- const message = frame.siblings[index];
- if (!message) {
- stack.pop();
- continue;
- }
- branchIndexes.length = frame.branchCount;
- if (frame.siblings.length > 1) {
- branchIndexes.push({
- parentMessageId: frame.parentMessageId,
- siblingIdx: frame.siblings.length - index - 1,
- });
- }
- if (message.messageId === targetMessageId) {
- return branchIndexes;
- }
- if (message.children?.length) {
- stack.push({
- siblings: message.children,
- parentMessageId: message.messageId,
- index: 0,
- branchCount: branchIndexes.length,
- });
- }
- }
- return [];
-};
-
export const getLatestText = (message?: TMessage | null, includeIndex?: boolean): string => {
if (!message) {
return '';
diff --git a/packages/chat/src/core/branch.ts b/packages/chat/src/core/branch.ts
new file mode 100644
index 0000000000..ebba281026
--- /dev/null
+++ b/packages/chat/src/core/branch.ts
@@ -0,0 +1,61 @@
+import { buildTree } from 'librechat-data-provider';
+import type { TMessage } from 'librechat-data-provider';
+
+/** The sibling a parent must show for a branch to reach a target message. */
+export type BranchSiblingIndex = {
+ parentMessageId: string | null | undefined;
+ siblingIdx: number;
+};
+
+/**
+ * The sibling selections that put `targetMessageId` on screen: for every parent with more
+ * than one child on the path from the root to the target, the reversed index of the child the
+ * path goes through (0 is the newest). Empty when the target is not in `messages`.
+ */
+export const getBranchSiblingIndexesForTarget = (
+ messages: TMessage[] | null | undefined,
+ targetMessageId: string | null | undefined,
+ rootSiblingKey: string | null | undefined,
+): BranchSiblingIndex[] => {
+ if (!targetMessageId) {
+ return [];
+ }
+
+ const messagesTree = buildTree({ messages: messages ?? null });
+ if (!messagesTree?.length) {
+ return [];
+ }
+
+ const branchIndexes: BranchSiblingIndex[] = [];
+ const stack = [
+ { siblings: messagesTree, parentMessageId: rootSiblingKey, index: 0, branchCount: 0 },
+ ];
+ while (stack.length > 0) {
+ const frame = stack[stack.length - 1];
+ const index = frame.index++;
+ const message = frame.siblings[index];
+ if (!message) {
+ stack.pop();
+ continue;
+ }
+ branchIndexes.length = frame.branchCount;
+ if (frame.siblings.length > 1) {
+ branchIndexes.push({
+ parentMessageId: frame.parentMessageId,
+ siblingIdx: frame.siblings.length - index - 1,
+ });
+ }
+ if (message.messageId === targetMessageId) {
+ return branchIndexes;
+ }
+ if (message.children?.length) {
+ stack.push({
+ siblings: message.children,
+ parentMessageId: message.messageId,
+ index: 0,
+ branchCount: branchIndexes.length,
+ });
+ }
+ }
+ return [];
+};
diff --git a/packages/chat/src/core/index.ts b/packages/chat/src/core/index.ts
index 35a90defa0..c447311cee 100644
--- a/packages/chat/src/core/index.ts
+++ b/packages/chat/src/core/index.ts
@@ -19,5 +19,6 @@ export * from './turns';
export * from './parts';
export * from './a11y';
export * from './ptc';
+export * from './branch';
export * from './subagents';
export { strongDirection } from './direction';
diff --git a/packages/chat/src/react/chat/__tests__/session.spec.tsx b/packages/chat/src/react/chat/__tests__/session.spec.tsx
index 8b8dab3ea2..49ba9ec99f 100644
--- a/packages/chat/src/react/chat/__tests__/session.spec.tsx
+++ b/packages/chat/src/react/chat/__tests__/session.spec.tsx
@@ -14,6 +14,7 @@ import { ChatHostProvider } from '../host';
const mockUseChatHelpers = jest.fn();
const mockUseQueueDrain = jest.fn();
const mockUseAdaptiveSSE = jest.fn();
+const mockUseResumeOnLoad = jest.fn();
const mockRevealQueuedTurn = jest.fn();
/** The contract and the queue have specs of their own; here they only witness the order and
@@ -30,6 +31,9 @@ jest.mock('../../stream/adaptive', () => ({
__esModule: true,
default: (...args: unknown[]) => mockUseAdaptiveSSE(...args),
}));
+jest.mock('../../stream/resume/load', () => ({
+ useResumeOnLoad: (...args: unknown[]) => mockUseResumeOnLoad(...args),
+}));
jest.mock('../../steering/useQueueDrain', () => ({
__esModule: true,
default: (...args: unknown[]) => mockUseQueueDrain(...args),
@@ -44,9 +48,8 @@ const contract = {
function createHost(query: ChatMessagesQuery) {
const useMessages = jest.fn((): ChatMessagesQuery => query);
- const useSessionEffects = jest.fn();
- const host = { useMessages, useSessionEffects } as unknown as ChatHost;
- return { host, useMessages, useSessionEffects };
+ const host = { useMessages } as unknown as ChatHost;
+ return { host, useMessages };
}
function renderSession(host: ChatHost, pane = jest.fn(() => <Probe />)) {
@@ -99,22 +102,13 @@ describe('ChatSessionProvider', () => {
it('serves the contract and runs the stream, resume and queue drain against it', () => {
const submission = { conversation: {} } as TSubmission;
getDefaultStore().set(submissionByIndex(1), submission);
- const { host, useSessionEffects } = createHost({
- messages,
- isLoading: false,
- isFetching: false,
- });
+ const { host } = createHost({ messages, isLoading: false, isFetching: false });
renderSession(host);
expect(mockUseChatHelpers).toHaveBeenCalledWith(1, 'convo-1');
expect(served).toBe(contract);
expect(mockUseAdaptiveSSE).toHaveBeenLastCalledWith(submission, contract, false, 1);
- expect(useSessionEffects).toHaveBeenLastCalledWith({
- index: 1,
- conversationId: 'convo-1',
- chat: contract,
- isSettled: true,
- });
+ expect(mockUseResumeOnLoad).toHaveBeenLastCalledWith('convo-1', contract.getMessages, 1, true);
expect(mockUseQueueDrain).toHaveBeenCalledWith(
1,
'convo-1',
@@ -127,12 +121,10 @@ describe('ChatSessionProvider', () => {
['loading', { isLoading: true, isFetching: true }],
['revalidating a warm cache', { isLoading: false, isFetching: true }],
])('holds resume back while %s', (_label, state) => {
- const { host, useSessionEffects } = createHost({ messages: null, ...state });
+ const { host } = createHost({ messages: null, ...state });
renderSession(host);
- expect(useSessionEffects).toHaveBeenLastCalledWith(
- expect.objectContaining({ isSettled: false }),
- );
+ expect(mockUseResumeOnLoad).toHaveBeenLastCalledWith('convo-1', contract.getMessages, 1, false);
});
it('runs the stream and resume after the contract and before the drain', () => {
@@ -143,7 +135,7 @@ describe('ChatSessionProvider', () => {
});
mockUseQueueDrain.mockImplementation(() => order.push('drain'));
mockUseAdaptiveSSE.mockImplementation(() => order.push('stream'));
- const { host, useMessages, useSessionEffects } = createHost({
+ const { host, useMessages } = createHost({
messages,
isLoading: false,
isFetching: false,
@@ -152,7 +144,7 @@ describe('ChatSessionProvider', () => {
order.push('messages');
return { messages, isLoading: false, isFetching: false };
});
- useSessionEffects.mockImplementation(() => order.push('resume'));
+ mockUseResumeOnLoad.mockImplementation(() => order.push('resume'));
renderSession(host);
expect(order.slice(0, 5)).toEqual(['messages', 'contract', 'stream', 'resume', 'drain']);
diff --git a/packages/chat/src/react/chat/__tests__/stop.spec.tsx b/packages/chat/src/react/chat/__tests__/stop.spec.tsx
index d113a80c6b..6e7dad77ac 100644
--- a/packages/chat/src/react/chat/__tests__/stop.spec.tsx
+++ b/packages/chat/src/react/chat/__tests__/stop.spec.tsx
@@ -62,7 +62,6 @@ const createHost = (conversation: TConversation | null): ChatHost => ({
useFeedbackEnabled: () => false,
getMappingOptions: () => ({}),
useMessages: () => ({ messages: null, isLoading: false, isFetching: false }),
- useSessionEffects: noop,
});
const INDEX = 0;
diff --git a/packages/chat/src/react/chat/host.tsx b/packages/chat/src/react/chat/host.tsx
index 5197817684..52234780ab 100644
--- a/packages/chat/src/react/chat/host.tsx
+++ b/packages/chat/src/react/chat/host.tsx
@@ -158,15 +158,6 @@ export type ChatMessagesQuery = {
isFetching: boolean;
};
-/** What a pane's session hands its effects each render. */
-export type ChatSessionEffectsParams = {
- index: number;
- conversationId?: string;
- chat: ChatContract;
- /** The messages finished loading and no revalidation is in flight. */
- isSettled: boolean;
-};
-
/**
* What `useChatHelpers` needs from the app that hosts it. Members named `use*` are hooks, called
* unconditionally by the chat hook, so the host can back each one with its own router, query
@@ -198,13 +189,6 @@ export interface ChatHost {
conversationId: string | undefined,
options: { isStreaming: boolean },
): ChatMessagesQuery;
- /**
- * Runs the pane's resume on load.
- *
- * @deprecated On arrival: a bridge to the app's `useResumeOnLoad` until it moves into this
- * package (#17565), after which the session calls it itself and this member is removed.
- */
- useSessionEffects(params: ChatSessionEffectsParams): void;
}
const ChatHostContext = createContext<ChatHost | null>(null);
diff --git a/packages/chat/src/react/chat/index.ts b/packages/chat/src/react/chat/index.ts
index 90faf13277..1ba4d73243 100644
--- a/packages/chat/src/react/chat/index.ts
+++ b/packages/chat/src/react/chat/index.ts
@@ -18,7 +18,6 @@ export type {
AbortStreamParams,
AbortStreamResponse,
ChatPaneConversation,
- ChatSessionEffectsParams,
} from './host';
export { useChatActions } from './actions';
export { getChatStatus, isEmptyContentPart } from './status';
diff --git a/packages/chat/src/react/chat/session.tsx b/packages/chat/src/react/chat/session.tsx
index 3fde2a0d19..a13f138f72 100644
--- a/packages/chat/src/react/chat/session.tsx
+++ b/packages/chat/src/react/chat/session.tsx
@@ -4,6 +4,7 @@ import type { ReactNode } from 'react';
import { submissionByIndex, useIsSubmitting } from '../submission';
import useQueuedTurnReveal from '../steering/useQueuedTurnReveal';
import useQueueDrain from '../steering/useQueueDrain';
+import { useResumeOnLoad } from '../stream/resume/load';
import useAdaptiveSSE from '../stream/adaptive';
import { ChatContext } from './context';
import useChatHelpers from './helpers';
@@ -51,12 +52,7 @@ export function ChatSessionProvider({
/** 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. */
- host.useSessionEffects({
- index,
- conversationId,
- chat,
- isSettled: !isLoading && !isFetching,
- });
+ 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. */
diff --git a/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx b/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx
index d828c94c9d..81a8fd25fe 100644
--- a/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx
+++ b/packages/chat/src/react/stream/__tests__/adaptive.spec.tsx
@@ -22,6 +22,13 @@ const host: StreamHost = {
useQueuedTurnReceipts: () => ({ data: undefined, dataUpdatedAt: 0 }),
useActiveJobs: () => ({ data: undefined, dataUpdatedAt: 0 }),
extendActiveJobsGrace: () => undefined,
+ useStreamStatus: () => ({
+ data: undefined,
+ dataUpdatedAt: 0,
+ isSuccess: false,
+ isFetching: false,
+ }),
+ useResumeSettings: () => ({ configLoaded: true, conversation: null }),
};
const wrapper = ({ children }: { children: React.ReactNode }) => (
diff --git a/packages/chat/src/react/stream/host.tsx b/packages/chat/src/react/stream/host.tsx
index ef569a039f..598dd67594 100644
--- a/packages/chat/src/react/stream/host.tsx
+++ b/packages/chat/src/react/stream/host.tsx
@@ -1,7 +1,13 @@
import { createContext, useContext } from 'react';
-import type { ChatTransport, TSubmission, TAgentQueuedTurnReceipt } from 'librechat-data-provider';
+import type {
+ TSubmission,
+ ChatTransport,
+ RetentionMode,
+ TConversation,
+ TAgentQueuedTurnReceipt,
+} from 'librechat-data-provider';
import type { Dispatch, ReactNode, SetStateAction } from 'react';
-import type { ResumableHost, ResumableRun } from '../../core';
+import type { ResumableHost, ResumableRun, StreamStatusResponse } from '../../core';
import type { ChatContract } from '../chat/contract';
/** The chat members a stream writes through: the message cache, the pane's conversation and its
@@ -28,6 +34,21 @@ export type ResumeQuery<Data> = {
dataUpdatedAt: number;
};
+/** The stream status read a resume decides on. */
+export type ResumeStatusQuery = ResumeQuery<StreamStatusResponse> & {
+ isSuccess: boolean;
+ isFetching: boolean;
+};
+
+/** What a pane's resume check reads from the app's settings. */
+export type ResumeSettings = {
+ /** Whether the deployment's startup configuration has loaded. */
+ configLoaded: boolean;
+ retentionMode?: RetentionMode;
+ /** The conversation the pane shows. */
+ conversation: TConversation | null;
+};
+
/** Everything a resumable stream runs on except how it re-attaches, which the binding owns. */
export type ResumableServices = Omit<ResumableHost, 'subscribe'>;
@@ -67,6 +88,10 @@ export interface StreamHost {
): ResumeQuery<{ activeJobIds: string[] }>;
/** Restarts the active-job list's handover window after a run was seen live another way. */
extendActiveJobsGrace(): void;
+ /** A conversation's generation status, read only while `enabled`. */
+ useStreamStatus(conversationId: string | undefined, enabled: boolean): ResumeStatusQuery;
+ /** The settings a pane's resume check reads. */
+ useResumeSettings(runIndex: number): ResumeSettings;
}
const StreamHostContext = createContext<StreamHost | null>(null);
diff --git a/packages/chat/src/react/stream/index.ts b/packages/chat/src/react/stream/index.ts
index 4ef03784c2..d0af00a110 100644
--- a/packages/chat/src/react/stream/index.ts
+++ b/packages/chat/src/react/stream/index.ts
@@ -7,6 +7,9 @@ export { useContentHandler } from './content';
export { settleFinishedRun } from './resume/finished';
export { useResumeAnnouncements } from './resume/announcements';
export { useOwedSuccessor, ACTIVE_JOBS_SUCCESSOR_GRACE_MS } from './resume/successor';
+export { useResumeOnLoad } from './resume/load';
+export { useSteerState } from './steer';
+export type { SteerState } from './steer';
export type { FinishedRunSteers } from './resume/finished';
export type { OwedSuccessorState } from './resume/successor';
export { useAttachmentHandler } from './attachments';
@@ -26,6 +29,8 @@ export type {
StreamHost,
StreamChat,
ResumeQuery,
+ ResumeSettings,
+ ResumeStatusQuery,
ResumableServices,
ResumableStreamParams,
} from './host';
diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/packages/chat/src/react/stream/resume/load.ts
similarity index 93%
rename from client/src/hooks/SSE/useResumeOnLoad.ts
rename to packages/chat/src/react/stream/resume/load.ts
index f8f8de037e..b999d10482 100644
--- a/client/src/hooks/SSE/useResumeOnLoad.ts
+++ b/packages/chat/src/react/stream/resume/load.ts
@@ -5,17 +5,7 @@ import {
isAssistantsEndpoint,
isForcedTemporaryRetention,
} from 'librechat-data-provider';
-import {
- useChatHost,
- useSubmission,
- useIsSubmitting,
- useOwedSuccessor,
- settleFinishedRun,
- submissionByIndex,
- submissionStartFamily,
- useResumeAnnouncements,
- activeGenerationCreatedAtByConvoId,
-} from '@librechat/chat/react';
+import type { TMessage, Agents } from 'librechat-data-provider';
import {
hasSubmissionUserMessage,
getGenerationProtocolVersion,
@@ -24,14 +14,19 @@ import {
resumeStateMatchesSubmission,
getResumeBranchTargetMessageId,
buildSubmissionFromResumeState,
-} from '@librechat/chat';
-import type { TMessage, Agents } from 'librechat-data-provider';
-import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
-import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
-import { useChatSettings } from '~/Providers/ChatSettingsContext';
-import { getBranchSiblingIndexesForTarget } from '~/utils';
-import { useStreamStatus } from '~/data-provider';
-import useSteerState from './steer';
+ getBranchSiblingIndexesForTarget,
+} from '../../../core';
+import { useSubmission, useIsSubmitting, submissionByIndex } from '../../submission';
+import { activeGenerationCreatedAtByConvoId } from '../../steer/atoms';
+import { pendingApprovalActionFamily } from '../../approval';
+import { siblingIdxFamily, siblingKey } from '../../thread';
+import { submissionStartFamily } from '../../generation';
+import { useResumeAnnouncements } from './announcements';
+import { useOwedSuccessor } from './successor';
+import { settleFinishedRun } from './finished';
+import { useChatHost } from '../../chat/host';
+import { useSteerState } from '../steer';
+import { useStreamHost } from '../host';
/**
* Hook to resume streaming if navigating to a conversation with active generation.
@@ -44,12 +39,12 @@ import useSteerState from './steer';
*
* @param messagesLoaded - Whether the messages query has finished loading (prevents race condition)
*/
-export default function useResumeOnLoad(
+export function useResumeOnLoad(
conversationId: string | undefined,
getMessages: () => TMessage[] | undefined,
runIndex = 0,
messagesLoaded = true,
-) {
+): void {
const jotaiStore = useStore();
const cache = useChatHost().useMessageCache();
const setSubmission = useSetAtom(submissionByIndex(runIndex));
@@ -59,14 +54,18 @@ export default function useResumeOnLoad(
const attachedGenerationCreatedAt = useAtomValue(
activeGenerationCreatedAtByConvoId(conversationId ?? ''),
);
- const { config, usePaneConversation } = useChatSettings();
- const currentConversation = usePaneConversation(runIndex);
+ const streamHost = useStreamHost();
+ const {
+ configLoaded,
+ retentionMode,
+ conversation: currentConversation,
+ } = streamHost.useResumeSettings(runIndex);
const endpoint = currentConversation?.endpoint;
const endpointType = currentConversation?.endpointType;
const actualEndpoint = endpointType ?? endpoint;
const resumableEnabled = !isAssistantsEndpoint(actualEndpoint);
- const startupConfigSettled = config.loaded !== false;
- const isRetentionForced = isForcedTemporaryRetention(config.retentionMode);
+ const startupConfigSettled = configLoaded;
+ const isRetentionForced = isForcedTemporaryRetention(retentionMode);
// Track conversations we've already processed (either resumed or skipped)
const processedConvoRef = useRef<string | null>(null);
/**
@@ -162,7 +161,7 @@ export default function useResumeOnLoad(
dataUpdatedAt: streamStatusUpdatedAt,
isSuccess,
isFetching,
- } = useStreamStatus(conversationId, shouldCheck);
+ } = streamHost.useStreamStatus(conversationId, shouldCheck);
useEffect(() => {
console.log('[ResumeOnLoad] Effect check', {
diff --git a/packages/chat/src/react/stream/steer.ts b/packages/chat/src/react/stream/steer.ts
new file mode 100644
index 0000000000..38403981ca
--- /dev/null
+++ b/packages/chat/src/react/stream/steer.ts
@@ -0,0 +1,297 @@
+import { useCallback, useMemo, useRef } from 'react';
+import { useStore } from 'jotai';
+import type { TPendingSteer, TSteerUpdatedEvent } from 'librechat-data-provider';
+import type { GenerationProtocolVersion, PendingSteer } from '../../core';
+import {
+ seedPendingSteers,
+ settledSteerQuotes,
+ removePendingSteers,
+ RUN_ENDED_STATUSES,
+ acceptedClientSteerIds,
+ withoutRecoveredSteers,
+ updatePendingSteerLabels,
+ selectLocalSteersForQueue,
+ mergeRestagedQuotes,
+ appendAppliedSteerIds,
+ collectAppliedSteerIds,
+ collectDroppedSteerQuotes,
+} from '../../core';
+import {
+ pendingSteersByConvoId,
+ appliedSteerIdsByConvoId,
+ acceptedSteerClientIdsByConvoId,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '../steer/atoms';
+import useSteerConvert from '../steering/useSteerConvert';
+import { queuedMessagesByConvoId } from '../steer/queue';
+import { pendingQuotesByConvoId } from '../composer';
+import { useSteerHost } from '../steer/host';
+
+/** The steer writers the stream handlers and the resume path call. */
+export type SteerState = {
+ resolveSteerChip: (
+ conversationId: string,
+ steerId: string,
+ clientSteerId?: string,
+ appliedPartQuotes?: string[],
+ ) => string[];
+ updateSteerChips: (event: TSteerUpdatedEvent) => void;
+ seedSteerChips: (
+ conversationId: string,
+ steers: TPendingSteer[] | undefined,
+ generationCreatedAt?: number,
+ generationProtocolVersion?: GenerationProtocolVersion,
+ ) => void;
+ settleAppliedSteerParts: (conversationId: string, values: unknown[] | undefined) => void;
+ convertSteersToQueued: ReturnType<typeof useSteerConvert>;
+ convertLocalSteersToQueued: (
+ conversationId: string,
+ options?: {
+ claimParked?: boolean;
+ statuses?: readonly PendingSteer['status'][];
+ excludeSteerIds?: Iterable<string>;
+ generationProtocolVersion?: GenerationProtocolVersion;
+ },
+ ) => void;
+ updateActiveGenerationCreatedAt: (
+ conversationId: string,
+ next: number | null,
+ expected?: number,
+ generationProtocolVersion?: GenerationProtocolVersion,
+ ) => boolean;
+};
+
+/**
+ * The one place the stream handlers write steer state: pending-steer chips,
+ * the applied and accepted id sets, the quotes a lost chip restages, and the
+ * generation epoch a conversation's live run carries. The rules live in the
+ * chat core (`core/steer/chips`); this binds them to the app's atoms.
+ */
+export function useSteerState(): SteerState {
+ const jotaiStore = useStore();
+ const fileMap = useSteerHost().useFileMap();
+ const fileMapRef = useRef(fileMap);
+ fileMapRef.current = fileMap;
+
+ /** Converts steers that never reached an injection boundary into queued
+ * follow-up messages (reported on the run's final/abort event; the abort
+ * HTTP response consumes the same data as a fallback in useChatHelpers). */
+ const convertSteersToQueued = useSteerConvert();
+
+ /** Removes the pending chip once its steer is injected (the inline content
+ * part becomes the durable record), and records the id so a 202 ACK that
+ * arrives AFTER the applied event drops its chip instead of re-minting it.
+ * Returns the ids seen by the durable set for the first time: the caller
+ * stamps these as live-applied only when it actually commits the inline
+ * part, so an abandoned placement or a replayed event cannot arm a draw-in
+ * with no part mounting to consume it. */
+ const resolveSteerChip = useCallback(
+ (
+ conversationId: string,
+ steerId: string,
+ clientSteerId?: string,
+ appliedPartQuotes?: string[],
+ ): string[] => {
+ const settledIds = clientSteerId ? [steerId, clientSteerId] : [steerId];
+ /** A part applied by a pre-quotes server carries no quotes while the
+ * chip being settled may hold the only copy of the user's excerpts
+ * (its 202 was lost, so the ACK-echo restore never ran). Re-stage
+ * them before removal; `mergeRestagedQuotes` keeps this idempotent
+ * with the ACK path for the same excerpts. */
+ if (appliedPartQuotes == null || appliedPartQuotes.length === 0) {
+ const droppedQuotes = settledSteerQuotes(
+ jotaiStore.get(pendingSteersByConvoId(conversationId)),
+ settledIds,
+ );
+ if (droppedQuotes != null) {
+ jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
+ mergeRestagedQuotes(prev, droppedQuotes),
+ );
+ }
+ }
+ const alreadyApplied = jotaiStore.get(appliedSteerIdsByConvoId(conversationId));
+ const firstApplication = settledIds.filter((id) => !alreadyApplied.includes(id));
+ jotaiStore.set(appliedSteerIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, settledIds),
+ );
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ removePendingSteers(prev, settledIds),
+ );
+ jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) =>
+ withoutRecoveredSteers(prev, settledIds),
+ );
+ return firstApplication;
+ },
+ [jotaiStore],
+ );
+
+ /** Capability can change while the same generation resumes after HITL. */
+ const updateSteerChips = useCallback(
+ (event: TSteerUpdatedEvent) => {
+ const acceptedClientIds = acceptedClientSteerIds(event.steers);
+ if (acceptedClientIds.length > 0) {
+ jotaiStore.set(acceptedSteerClientIdsByConvoId(event.conversationId), (prev) =>
+ appendAppliedSteerIds(prev, acceptedClientIds),
+ );
+ }
+ jotaiStore.set(pendingSteersByConvoId(event.conversationId), (prev) =>
+ updatePendingSteerLabels(prev, event.steers),
+ );
+ },
+ [jotaiStore],
+ );
+
+ /** Replaces the chip list with the server's still-queued steers (sync, resume). */
+ const seedSteerChips = useCallback(
+ (
+ conversationId: string,
+ steers: TPendingSteer[] | undefined,
+ generationCreatedAt?: number,
+ generationProtocolVersion: GenerationProtocolVersion = 1,
+ ) => {
+ const acceptedClientIds = acceptedClientSteerIds(steers);
+ if (acceptedClientIds.length > 0) {
+ jotaiStore.set(acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, acceptedClientIds),
+ );
+ }
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ seedPendingSteers(prev, steers, {
+ generationCreatedAt,
+ generationProtocolVersion,
+ storedFiles: fileMapRef.current,
+ }),
+ );
+ },
+ [jotaiStore],
+ );
+
+ /** Settles the chips of every steer whose applied part already rides `values`. */
+ const settleAppliedSteerParts = useCallback(
+ (conversationId: string, values: unknown[] | undefined) => {
+ const ids = collectAppliedSteerIds(values);
+ if (ids.length === 0) {
+ return;
+ }
+ /** Chips settled by quote-less applied parts hold the only copy of
+ * their excerpts (a pre-quotes server injected the words bare):
+ * re-stage them as composer chips before the removal below. */
+ const droppedQuotes = collectDroppedSteerQuotes(
+ values,
+ jotaiStore.get(pendingSteersByConvoId(conversationId)),
+ );
+ if (droppedQuotes.length > 0) {
+ jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
+ mergeRestagedQuotes(prev, droppedQuotes),
+ );
+ }
+ jotaiStore.set(appliedSteerIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, ids),
+ );
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ removePendingSteers(prev, ids),
+ );
+ },
+ [jotaiStore],
+ );
+
+ /** Sweeps this conversation's local chips (see `selectLocalSteersForQueue`)
+ * into queued follow-ups. Error events carry no `pendingSteers` payload of
+ * their own (the server drops its copy on failure); this is the only
+ * source of truth for those runs; the `final` and error/404 terminals call
+ * it (default `statuses`, i.e. `pending || failed`) alongside their own
+ * server-reported list as a backstop for `failed` chips, which never rode
+ * that list at all. The intentional-abort path passes `statuses: ['failed']`
+ * since the run may still be live server-side there (see its call site). */
+ const convertLocalSteersToQueued = useCallback(
+ (
+ conversationId: string,
+ options?: {
+ claimParked?: boolean;
+ statuses?: readonly PendingSteer['status'][];
+ excludeSteerIds?: Iterable<string>;
+ generationProtocolVersion?: GenerationProtocolVersion;
+ },
+ ) => {
+ const chips = jotaiStore.get(pendingSteersByConvoId(conversationId));
+ const generationProtocolVersion =
+ options?.generationProtocolVersion ??
+ jotaiStore.get(activeGenerationProtocolVersionByConvoId(conversationId));
+ const activeStatuses = options?.statuses ?? RUN_ENDED_STATUSES;
+ const excluded = new Set(options?.excludeSteerIds ?? []);
+ const accepted = selectLocalSteersForQueue(
+ chips,
+ activeStatuses.filter((status) => status === 'pending'),
+ excluded,
+ );
+ if (accepted.length > 0) {
+ convertSteersToQueued(conversationId, accepted, {
+ claimParked: options?.claimParked,
+ generationProtocolVersion,
+ });
+ }
+ const failed = selectLocalSteersForQueue(
+ chips,
+ activeStatuses.filter((status) => status === 'failed'),
+ excluded,
+ );
+ if (failed.length > 0) {
+ convertSteersToQueued(conversationId, failed, {
+ generationProtocolVersion,
+ bindRecoverySource: false,
+ /** Swept out of the chip surface so it cannot render under the next
+ * reply, but the server refused these words: the rail holds the row
+ * for Retry or an explicit send instead of draining it automatically. */
+ needsExplicitSend: true,
+ });
+ }
+ },
+ [convertSteersToQueued, jotaiStore],
+ );
+
+ /** Conversation ids are reused by successive agent turns. Keep the exact
+ * live epoch beside the UI controls, and only clear it if the terminal event
+ * still belongs to the epoch that installed it. */
+ const updateActiveGenerationCreatedAt = useCallback(
+ (
+ conversationId: string,
+ next: number | null,
+ expected?: number,
+ generationProtocolVersion: GenerationProtocolVersion = 1,
+ ): boolean => {
+ const state = activeGenerationCreatedAtByConvoId(conversationId);
+ if (expected != null && jotaiStore.get(state) !== expected) {
+ return false;
+ }
+ jotaiStore.set(state, next);
+ jotaiStore.set(
+ activeGenerationProtocolVersionByConvoId(conversationId),
+ next == null ? 1 : generationProtocolVersion,
+ );
+ return true;
+ },
+ [jotaiStore],
+ );
+
+ return useMemo(
+ () => ({
+ resolveSteerChip,
+ updateSteerChips,
+ seedSteerChips,
+ settleAppliedSteerParts,
+ convertSteersToQueued,
+ convertLocalSteersToQueued,
+ updateActiveGenerationCreatedAt,
+ }),
+ [
+ resolveSteerChip,
+ updateSteerChips,
+ seedSteerChips,
+ settleAppliedSteerParts,
+ convertSteersToQueued,
+ convertLocalSteersToQueued,
+ updateActiveGenerationCreatedAt,
+ ],
+ );
+}
diff --git a/packages/chat/src/react/subagents/__tests__/stream.spec.tsx b/packages/chat/src/react/subagents/__tests__/stream.spec.tsx
index e1ca91715e..befd27f792 100644
--- a/packages/chat/src/react/subagents/__tests__/stream.spec.tsx
+++ b/packages/chat/src/react/subagents/__tests__/stream.spec.tsx
@@ -80,6 +80,13 @@ const host: StreamHost = {
useQueuedTurnReceipts: () => ({ data: undefined, dataUpdatedAt: 0 }),
useActiveJobs: () => ({ data: undefined, dataUpdatedAt: 0 }),
extendActiveJobsGrace: () => undefined,
+ useStreamStatus: () => ({
+ data: undefined,
+ dataUpdatedAt: 0,
+ isSuccess: false,
+ isFetching: false,
+ }),
+ useResumeSettings: () => ({ configLoaded: true, conversation: null }),
};
const transport = createSSETransport({ token: 'token-1' });
diff --git a/prep-stream-dev-restack b/prep-stream-dev-restack
new file mode 120000
index 0000000000..6d9b7c550c
--- /dev/null
+++ b/prep-stream-dev-restack
@@ -0,0 +1 @@
+/home/berry13/worktrees/librechat-theme-update/prep-stream-dev-restack
\ No newline at end of file