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 the Steer Atoms to Jotai in the Chat Package (#17135)

Marco Berettac577e384ed21
diff --git a/client/src/Providers/MessagePartsHostContext.tsx b/client/src/Providers/MessagePartsHostContext.tsx
index 694e067a47..603da1065c 100644
--- a/client/src/Providers/MessagePartsHostContext.tsx
+++ b/client/src/Providers/MessagePartsHostContext.tsx
@@ -1,7 +1,12 @@
import { useCallback, useMemo } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { useToastContext } from '@librechat/client';
-import { setDefaultMessagePartsHost } from '@librechat/chat/react';
+import { setDefaultMessagePartsHost, pendingSteersByConvoId } from '@librechat/chat/react';
+import {
+ liveAppliedSteerFamily,
+ liveAppliedSteerIdsAtom,
+ escalatingSteerFamily,
+} from '@librechat/chat/react';
import {
useRecoilCallback,
useRecoilState,
@@ -17,11 +22,6 @@ import type {
MessagePartsHost,
} from '~/hooks/Chat/contract';
import type { Artifact } from '~/common';
-import {
- liveAppliedSteerFamily,
- liveAppliedSteerIdsAtom,
- escalatingSteerFamily,
-} from '~/store/steer';
import store, { ptcTraceByToolCallId, ptcTraceKey, sandboxStartingByToolCallId } from '~/store';
import { useMessageContext, useFileMapContext, useAgentsMapContext } from '~/Providers';
import { getAppPartRenderers } from '~/components/Chat/Messages/Content/Parts/slots';
@@ -124,8 +124,7 @@ export const appMessagePartsHost: MessagePartsHost = {
),
useToolArtifactClaim: (artifactId) => useRecoilState(store.toolArtifactClaim(artifactId)),
useArtifactPanel: useAppArtifactPanel,
- usePendingSteers: (conversationId) =>
- useRecoilValue(store.pendingSteersByConvoId(conversationId)),
+ usePendingSteers: (conversationId) => useAtomValue(pendingSteersByConvoId(conversationId)),
useSteerEscalating: (conversationId) => useAtomValue(escalatingSteerFamily(conversationId)),
usePaneConversationId: (index) => useRecoilValue(store.conversationIdByIndex(index)),
useLiveAppliedSteer: useAppLiveAppliedSteer,
diff --git a/client/src/components/Chat/Input/Composer/Queue.tsx b/client/src/components/Chat/Input/Composer/Queue.tsx
index 58cd451267..29adc478f6 100644
--- a/client/src/components/Chat/Input/Composer/Queue.tsx
+++ b/client/src/components/Chat/Input/Composer/Queue.tsx
@@ -1,11 +1,15 @@
import { memo, useId, useRef, useMemo, useState, useCallback } from 'react';
import { useAtomValue } from 'jotai';
-import { useRecoilValue } from 'recoil';
import { createPortal } from 'react-dom';
import * as Ariakit from '@ariakit/react';
import { useDrag, useDrop } from 'react-dnd';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { claimQueuedIntent, releaseQueuedIntent, hasQueuedIntent } from '@librechat/chat';
+import {
+ escalatingSteerFamily,
+ revealedQueuedTurnFamily,
+ pendingSteersByConvoId,
+} from '@librechat/chat/react';
import {
Button,
IconButton,
@@ -31,12 +35,10 @@ import type { RestoreToComposer } from '~/Providers/ComposerRestoreContext';
import type { SteeringControls } from '~/hooks/Chat/useSteering';
import type { QueuedMessage } from '~/hooks/Chat/queue';
import { useQueuedTurnPortal } from '~/components/Chat/Steering/QueuedTurnPortal';
-import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';
import EscalateNowButton from '~/components/Chat/Input/EscalateNowButton';
import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
-import store from '~/store';
const DRAG_TYPE = 'queued-message';
@@ -733,7 +735,7 @@ function Queue({
`aria-describedby` at whichever copy the document happened to keep. */
const reorderHintId = useId();
const queued = useAtomValue(queuedMessagesByConvoId(steering.queueKey));
- const pendingSteers = useRecoilValue(store.pendingSteersByConvoId(conversationId));
+ const pendingSteers = useAtomValue(pendingSteersByConvoId(conversationId));
const escalating = useAtomValue(escalatingSteerFamily(conversationId));
/* Only one interrupt can be unresolved at a time: a second arm would seal the
same run twice. The escalating flag covers an arm's round trip, before its
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
index b77eeac11c..06387ccaf7 100644
--- a/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
+++ b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
@@ -5,6 +5,7 @@ import { getDefaultStore, useSetAtom } from 'jotai';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { ReasoningEffort } from 'librechat-data-provider';
import { hasQueuedIntent, releaseQueuedIntent } from '@librechat/chat';
+import { revealedQueuedTurnFamily, resetSteerFamilies } from '@librechat/chat/react';
import { act, render, screen, within, waitFor, fireEvent } from '@testing-library/react';
import type { SteeringControls } from '~/hooks/Chat/useSteering';
import type { QueuedMessage } from '~/hooks/Chat/queue';
@@ -13,7 +14,6 @@ import {
useQueuedTurnPortal,
} from '~/components/Chat/Steering/QueuedTurnPortal';
import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import Queue from '../Queue';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, options?: Record<string, string | number>) => {
@@ -201,7 +201,10 @@ function renderQueue(
);
}
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ resetSteerFamilies();
+});
describe('Queue', () => {
beforeEach(() => jest.clearAllMocks());
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
index c7afc15f62..3a82223b3f 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
@@ -8,6 +8,10 @@ import { QueryKeys, EModelEndpoint } from 'librechat-data-provider';
import { act, render, screen, fireEvent } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MemoryRouter, useNavigate, useLocation } from 'react-router-dom';
+import {
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '@librechat/chat/react';
import type { TConversation } from 'librechat-data-provider';
import type { Transport } from '~/hooks/Chat/contract';
import type { ChatFormValues } from '~/common';
@@ -167,6 +171,8 @@ function mountComposer(
const jotaiStore = createStore();
if (liveRun) {
jotaiStore.set(showStopButtonByIndex(0), true);
+ jotaiStore.set(activeGenerationCreatedAtByConvoId(conversation.conversationId ?? ''), 1000);
+ jotaiStore.set(activeGenerationProtocolVersionByConvoId(conversation.conversationId ?? ''), 2);
}
const wrapper = ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>
@@ -175,14 +181,6 @@ function mountComposer(
initializeState={({ set }) => {
if (liveRun) {
set(store.isSubmittingFamily(0), true);
- set(
- store.activeGenerationCreatedAtByConvoId(conversation.conversationId ?? ''),
- 1000,
- );
- set(
- store.activeGenerationProtocolVersionByConvoId(conversation.conversationId ?? ''),
- 2,
- );
}
if (speechSettingsInitialized) {
set(store.engineSTT, 'external');
diff --git a/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx
index e658271345..0078ae44b9 100644
--- a/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx
@@ -3,13 +3,13 @@ import { RecoilRoot } from 'recoil';
import { EModelEndpoint } from 'librechat-data-provider';
import { act, render, screen } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import type { TConversation } from 'librechat-data-provider';
import {
QueuedTurnPortalProvider,
useQueuedTurnPortal,
} from '~/components/Chat/Steering/QueuedTurnPortal';
import PendingTurn from '~/components/Chat/Messages/PendingTurn';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import { ChatContext } from '~/Providers';
jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
diff --git a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
index aeae1ff74e..950722a49a 100644
--- a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
+++ b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
@@ -7,9 +7,9 @@ import {
useRef,
useState,
} from 'react';
-import { useRecoilValue } from 'recoil';
-import { useAtom, useStore } from 'jotai';
import { Constants } from 'librechat-data-provider';
+import { useAtom, useStore, useAtomValue } from 'jotai';
+import { activeGenerationCreatedAtByConvoId } from '@librechat/chat/react';
import type { Agents } from 'librechat-data-provider';
import type { AskAnswerStatus } from '~/components/Chat/ask/state';
import {
@@ -22,7 +22,6 @@ import { askSubmitStatusAtom } from '~/components/Chat/ask/state';
import { resolveAskUserQuestionPart } from '~/utils/approval';
import { ChatContext } from '~/Providers/ChatContext';
import { useGetEphemeralAgent } from '~/store/agents';
-import store from '~/store';
/** Shared read/write for the ask-answer submit status. */
export function useAskSubmitStatus(): {
@@ -438,8 +437,8 @@ export function useResumeSubmit() {
/** Ask status lives in Jotai so it works from the composer (outside the
* provider); tool-approval status stays on the context. */
const { setAskStatus } = useAskSubmitStatus();
- const activeGenerationCreatedAt = useRecoilValue(
- store.activeGenerationCreatedAtByConvoId(conversation?.conversationId ?? Constants.NEW_CONVO),
+ const activeGenerationCreatedAt = useAtomValue(
+ activeGenerationCreatedAtByConvoId(conversation?.conversationId ?? Constants.NEW_CONVO),
);
const buildResumeFields = useCallback((): ResumeAgentFields | null => {
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx
index fb5523d298..eef407ebaf 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import { MemoryRouter } from 'react-router-dom';
import { Provider as JotaiProvider, createStore } from 'jotai';
+import { pendingSteersByConvoId } from '@librechat/chat/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Constants, ContentTypes, QueryKeys } from 'librechat-data-provider';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
@@ -86,6 +87,7 @@ function renderPending(
});
queryClient.setQueryData([QueryKeys.messages, CONVO_ID], messages ?? []);
const jotaiStore = createStore();
+ jotaiStore.set(pendingSteersByConvoId(CONVO_ID), steers);
if (activeSiblingIndex != null) {
jotaiStore.set(
siblingIdxFamily(
@@ -110,7 +112,6 @@ function renderPending(
conversationId: CONVO_ID,
} as TConversation);
}
- set(store.pendingSteersByConvoId(CONVO_ID), steers);
}}
>
<PendingSteers conversationId={CONVO_ID} index={pane?.index} fullWidth={fullWidth} />
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
index 3b2f7ba18d..7b6ef55626 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
@@ -2,11 +2,11 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import { QueryKeys } from 'librechat-data-provider';
import { Provider, createStore, useAtomValue } from 'jotai';
+import { liveAppliedSteerIdsAtom } from '@librechat/chat/react';
import { render, screen, fireEvent } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TMessage } from 'librechat-data-provider';
import { STEER_ICON } from '~/components/Chat/Steering/identity';
-import { liveAppliedSteerIdsAtom } from '~/store/steer';
import SteerPart from '../SteerPart';
import store from '~/store';
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx
index 42fea58c9c..b5e0651496 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx
@@ -2,10 +2,9 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import { act, renderHook } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
-import type { MutableSnapshot } from 'recoil';
+import { activeGenerationCreatedAtByConvoId } from '@librechat/chat/react';
import ApprovalProvider, { useApprovalContext, useResumeSubmit } from '../ApprovalContext';
import { ChatContext } from '~/Providers/ChatContext';
-import store from '~/store';
const mockApprovalMutate = jest.fn();
const mockAskMutate = jest.fn();
@@ -29,17 +28,15 @@ const chatContextValue = {
const createWrapper = (generationCreatedAt: number | null) =>
function ResumeWrapper({ children }: { children: React.ReactNode }) {
- const jotaiStore = React.useRef(createStore()).current;
- const initializeState = (snapshot: MutableSnapshot) => {
+ const [jotaiStore] = React.useState(() => {
+ const created = createStore();
if (generationCreatedAt != null) {
- snapshot.set(
- store.activeGenerationCreatedAtByConvoId('conversation-1'),
- generationCreatedAt,
- );
+ created.set(activeGenerationCreatedAtByConvoId('conversation-1'), generationCreatedAt);
}
- };
+ return created;
+ });
return (
- <RecoilRoot initializeState={initializeState}>
+ <RecoilRoot>
<JotaiProvider store={jotaiStore}>
<ChatContext.Provider value={chatContextValue}>
<ApprovalProvider>{children}</ApprovalProvider>
diff --git a/client/src/components/Chat/Messages/HoverButtons.tsx b/client/src/components/Chat/Messages/HoverButtons.tsx
index b4e02676b5..d955ce11b7 100644
--- a/client/src/components/Chat/Messages/HoverButtons.tsx
+++ b/client/src/components/Chat/Messages/HoverButtons.tsx
@@ -2,6 +2,7 @@ import React, { useState, useMemo, useCallback, memo } from 'react';
import { Copy, Check } from 'lucide';
import { useAtomValue } from 'jotai';
import { useRecoilState } from 'recoil';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { getSpeechText, findMessageById, isUserInitiatedCompaction } from 'librechat-data-provider';
import {
Button,
@@ -15,7 +16,6 @@ import type { TConversation, TMessage, TFeedback } from 'librechat-data-provider
import { useMessagesIsSubmitting, useOptionalMessagesOperations } from '~/Providers';
import { useGenerationsByLatest, useLocalize } from '~/hooks';
import { hasEditablePart } from './Content/editableParts';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import { Fork } from '~/components/Conversations';
import { hoverButtonClasses } from './styles';
import MessageAudio from './MessageAudio';
diff --git a/client/src/components/Chat/Messages/PendingTurn.tsx b/client/src/components/Chat/Messages/PendingTurn.tsx
index 7651a49058..44b28ce039 100644
--- a/client/src/components/Chat/Messages/PendingTurn.tsx
+++ b/client/src/components/Chat/Messages/PendingTurn.tsx
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { useRecoilValue } from 'recoil';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import type { TMessage } from 'librechat-data-provider';
import type { RefObject } from 'react';
import type { TMessageIcon } from '~/common';
@@ -10,7 +11,6 @@ import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
import { messageFooterClasses } from '~/components/Chat/Messages/styles';
import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import { useAuthContext } from '~/hooks/AuthContext';
import MarkdownLite from './Content/MarkdownLite';
import { useChatContext } from '~/Providers';
diff --git a/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx b/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx
index ae4a67fa3c..59ce83da2f 100644
--- a/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx
+++ b/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx
@@ -3,11 +3,11 @@ import { RecoilRoot } from 'recoil';
import { EModelEndpoint } from 'librechat-data-provider';
import { act, render, screen } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TConversation, TMessage } from 'librechat-data-provider';
-import type { RevealedQueuedTurn } from '~/store/steer';
+import type { RevealedQueuedTurn } from '@librechat/chat/react';
import PendingTurn from '~/components/Chat/Messages/PendingTurn';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import { ChatContext } from '~/Providers';
jest.mock('~/hooks', () => ({
diff --git a/client/src/hooks/Chat/__tests__/abort.spec.tsx b/client/src/hooks/Chat/__tests__/abort.spec.tsx
index ff30b0d457..17cf729c55 100644
--- a/client/src/hooks/Chat/__tests__/abort.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/abort.spec.tsx
@@ -4,6 +4,11 @@ import { useAtomValue, useSetAtom, getDefaultStore } from 'jotai';
import { act, renderHook, waitFor } from '@testing-library/react';
import { RecoilRoot, useSetRecoilState, useRecoilValue } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import {
+ resetSteerFamilies,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '@librechat/chat/react';
import type { TSubmission, TConversation } from 'librechat-data-provider';
import type { DrainAfterAbort, RunEnd } from '~/hooks/Chat/queue';
import {
@@ -94,7 +99,10 @@ function setup() {
return { handles, current };
}
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ resetSteerFamilies();
+});
describe('useAbortCleanup', () => {
it('clears all submissions when the captured submission is still current', async () => {
@@ -214,8 +222,11 @@ describe('useChatHelpers stopGenerating (abort steer targeting)', () => {
generationCreatedAt: 41,
});
if (generationCreatedAt != null) {
- set(store.activeGenerationCreatedAtByConvoId(conversationId), generationCreatedAt);
- set(store.activeGenerationProtocolVersionByConvoId(conversationId), 2);
+ getDefaultStore().set(
+ activeGenerationCreatedAtByConvoId(conversationId),
+ generationCreatedAt,
+ );
+ getDefaultStore().set(activeGenerationProtocolVersionByConvoId(conversationId), 2);
}
}}
>
diff --git a/client/src/hooks/Chat/__tests__/transport.spec.tsx b/client/src/hooks/Chat/__tests__/transport.spec.tsx
index 431c797529..b850423fdc 100644
--- a/client/src/hooks/Chat/__tests__/transport.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/transport.spec.tsx
@@ -5,6 +5,12 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Tools, QueryKeys, ContentTypes, EModelEndpoint, request } from 'librechat-data-provider';
+import {
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+ pendingSteersByConvoId,
+ resetSteerFamilies,
+} from '@librechat/chat/react';
import type {
TEnqueueAgentQueuedTurnRequest,
TSubmission,
@@ -147,8 +153,8 @@ const seedSteerableRun = ({ set }: MutableSnapshot) => {
conversationId: 'convo-1',
endpoint: 'agents',
} as TConversation);
- set(store.activeGenerationCreatedAtByConvoId('convo-1'), 1000);
- set(store.activeGenerationProtocolVersionByConvoId('convo-1'), 2);
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId('convo-1'), 1000);
+ getDefaultStore().set(activeGenerationProtocolVersionByConvoId('convo-1'), 2);
};
/** The running turn: queued follow-ups chain off its in-flight response. */
@@ -192,7 +198,10 @@ function ChatHost({ children }: { children: React.ReactNode }) {
return <ChatContext.Provider value={helpers}>{children}</ChatContext.Provider>;
}
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ resetSteerFamilies();
+});
describe('chat transport boundary', () => {
describe('send (agents)', () => {
@@ -275,8 +284,8 @@ describe('chat transport boundary', () => {
conversationId: 'convo-1',
endpoint: 'agents',
} as TConversation);
- set(store.activeGenerationCreatedAtByConvoId('convo-1'), 1000);
- set(store.activeGenerationProtocolVersionByConvoId('convo-1'), 2);
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId('convo-1'), 1000);
+ getDefaultStore().set(activeGenerationProtocolVersionByConvoId('convo-1'), 2);
};
it('stops a resumable generation through the host transport', async () => {
@@ -383,7 +392,7 @@ describe('chat transport boundary', () => {
};
const seedPendingSteer = (snapshot: MutableSnapshot) => {
seedSteerableRun(snapshot);
- snapshot.set(store.pendingSteersByConvoId('convo-1'), [pendingSteer]);
+ getDefaultStore().set(pendingSteersByConvoId('convo-1'), [pendingSteer]);
};
it('withdraws a waiting steer through the host transport', async () => {
@@ -391,7 +400,7 @@ describe('chat transport boundary', () => {
const { result } = renderHook(
() => ({
reclaim: useSteerReclaim('convo-1'),
- pending: useRecoilValue(store.pendingSteersByConvoId('convo-1')),
+ pending: useAtomValue(pendingSteersByConvoId('convo-1')),
}),
{ wrapper: createWrapper(fake.transport, seedPendingSteer) },
);
@@ -421,7 +430,7 @@ describe('chat transport boundary', () => {
const { result } = renderHook(
() => ({
escalate: useSteerEscalate('convo-1'),
- pending: useRecoilValue(store.pendingSteersByConvoId('convo-1')),
+ pending: useAtomValue(pendingSteersByConvoId('convo-1')),
}),
{ wrapper: createWrapper(fake.transport, seedPendingSteer) },
);
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index 18e9f63de4..5ea98a3850 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -1,5 +1,6 @@
import { renderHook, act } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import {
Constants,
ContentTypes,
@@ -25,7 +26,6 @@ import {
} from '~/components/Chat/Input/TokenUsage/store';
import { pendingReasoningOverrideFamily } from '~/components/Chat/Input/Composer/state';
import { submissionStartFamily, showStopButtonByIndex } from '~/store/generation';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import useChatFunctions from '../useChatFunctions';
import { isPasteSubmitted } from '~/utils';
diff --git a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
index c091fd3acf..69856067e3 100644
--- a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
@@ -4,6 +4,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { Constants, ReasoningEffort } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { RecoilRoot, useSetRecoilState, type MutableSnapshot } from 'recoil';
+import { revealedQueuedTurnFamily, resetSteerFamilies } from '@librechat/chat/react';
import {
claimQueuedIntent,
releaseQueuedIntent,
@@ -25,7 +26,6 @@ import {
resetQueueFamilies,
} from '~/hooks/Chat/queue';
import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import useQueueDrain from '../useQueueDrain';
import store from '~/store';
@@ -115,7 +115,10 @@ const runEnd = (overrides: Partial<RunEnd> = {}): RunEnd => ({
...overrides,
});
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ resetSteerFamilies();
+});
describe('useQueueDrain', () => {
beforeEach(() => {
diff --git a/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx b/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx
index 65664d6fc9..3e0713de01 100644
--- a/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx
@@ -1,12 +1,16 @@
import React from 'react';
import { QueryKeys } from 'librechat-data-provider';
import { RecoilRoot, useSetRecoilState } from 'recoil';
-import { Provider as JotaiProvider, createStore } from 'jotai';
import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { Provider as JotaiProvider, createStore, useSetAtom } from 'jotai';
+import {
+ revealedQueuedTurnFamily,
+ activeGenerationCreatedAtByConvoId,
+} from '@librechat/chat/react';
import type { TMessage, TAgentQueuedTurnReceipt } from 'librechat-data-provider';
+import type { RevealedQueuedTurn } from '@librechat/chat/react';
import type { QueuedMessage, RunEnd } from '~/hooks/Chat/queue';
-import type { RevealedQueuedTurn } from '~/store/steer';
import useQueuedTurnReveal, {
buildRevealedMessage,
hasRevealSuccessor,
@@ -15,7 +19,6 @@ import useQueuedTurnReveal, {
} from '../useQueuedTurnReveal';
import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import { streamStatusQueryKey } from '~/data-provider/SSE/queries';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import store from '~/store';
const CONVO_ID = 'convo-reveal';
@@ -180,7 +183,7 @@ describe('useQueuedTurnReveal', () => {
let setEpoch: (value: number | null) => void;
function StateProbe() {
setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));
- setEpoch = useSetRecoilState(store.activeGenerationCreatedAtByConvoId(CONVO_ID));
+ setEpoch = useSetAtom(activeGenerationCreatedAtByConvoId(CONVO_ID));
return null;
}
const queryClient = new QueryClient({
diff --git a/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx
index 4772621fef..ed044e0b63 100644
--- a/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteerCancel.spec.tsx
@@ -1,8 +1,13 @@
import React from 'react';
-import { useAtomValue } from 'jotai';
-import { RecoilRoot, useRecoilValue } from 'recoil';
+import { RecoilRoot } from 'recoil';
+import { useAtomValue, getDefaultStore } from 'jotai';
import { act, renderHook } from '@testing-library/react';
import { ReasoningEffort } from 'librechat-data-provider';
+import {
+ activeGenerationCreatedAtByConvoId,
+ pendingSteersByConvoId,
+ resetSteerFamilies,
+} from '@librechat/chat/react';
import type { RestoreToComposer } from '~/Providers/ComposerRestoreContext';
import type { PendingSteer } from '~/hooks/Chat/queue';
import {
@@ -11,7 +16,6 @@ import {
} from '~/Providers/ComposerRestoreContext';
import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';
import useSteerCancel, { useSteerMoveToQueue } from '../useSteerCancel';
-import store from '~/store';
const mockCancelAsync = jest.fn();
@@ -39,9 +43,9 @@ const pending = (overrides: Partial<PendingSteer> = {}): PendingSteer => ({
function setup(steer: PendingSteer) {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<RecoilRoot
- initializeState={({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
- set(store.pendingSteersByConvoId(CONVO_ID), [steer]);
+ initializeState={() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [steer]);
}}
>
{children}
@@ -50,14 +54,17 @@ function setup(steer: PendingSteer) {
return renderHook(
() => ({
moveToQueue: useSteerMoveToQueue(CONVO_ID),
- chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ chips: useAtomValue(pendingSteersByConvoId(CONVO_ID)),
queue: useAtomValue(queuedMessagesByConvoId(CONVO_ID)),
}),
{ wrapper },
);
}
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ resetSteerFamilies();
+});
describe('useSteerMoveToQueue', () => {
beforeEach(() => {
@@ -115,9 +122,9 @@ describe('useSteerMoveToQueue', () => {
const steer = pending();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<RecoilRoot
- initializeState={({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
- set(store.pendingSteersByConvoId(CONVO_ID), [steer]);
+ initializeState={() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [steer]);
}}
>
<ComposerRestoreProvider>
@@ -197,9 +204,9 @@ function setupCancel(
) {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<RecoilRoot
- initializeState={({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
- set(store.pendingSteersByConvoId(CONVO_ID), [steer]);
+ initializeState={() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [steer]);
}}
>
<ComposerRestoreProvider>
@@ -212,7 +219,7 @@ function setupCancel(
return renderHook(
() => ({
cancel: useSteerCancel(CONVO_ID),
- chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ chips: useAtomValue(pendingSteersByConvoId(CONVO_ID)),
queue: useAtomValue(queuedMessagesByConvoId(CONVO_ID)),
}),
{ wrapper },
diff --git a/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx
index cdc100c603..16cb3bc29f 100644
--- a/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteerConvert.spec.tsx
@@ -1,11 +1,16 @@
import React from 'react';
import { act, renderHook } from '@testing-library/react';
+import { RecoilRoot, type MutableSnapshot } from 'recoil';
import { getDefaultStore, useAtomValue, useSetAtom } from 'jotai';
-import { RecoilRoot, useRecoilValue, type MutableSnapshot } from 'recoil';
+import {
+ activeGenerationProtocolVersionByConvoId,
+ appliedSteerIdsByConvoId,
+ pendingSteersByConvoId,
+ resetSteerFamilies,
+} from '@librechat/chat/react';
import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';
import useSteerConvert from '../useSteerConvert';
-import store from '~/store';
const mockFetchStreamStatus = jest.fn();
let mockFileMap: Record<string, { llmDeliveryPath: 'text' }> = {};
@@ -26,7 +31,7 @@ function setup(initialize?: (snapshot: MutableSnapshot) => void) {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<RecoilRoot
initializeState={(snapshot) => {
- snapshot.set(store.activeGenerationProtocolVersionByConvoId(CONVO_ID), 2);
+ getDefaultStore().set(activeGenerationProtocolVersionByConvoId(CONVO_ID), 2);
initialize?.(snapshot);
}}
>
@@ -38,9 +43,9 @@ function setup(initialize?: (snapshot: MutableSnapshot) => void) {
const setQueue = useSetAtom(queuedMessagesByConvoId(CONVO_ID));
return {
convert: useSteerConvert(),
- chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ chips: useAtomValue(pendingSteersByConvoId(CONVO_ID)),
queue: useAtomValue(queuedMessagesByConvoId(CONVO_ID)),
- applied: useRecoilValue(store.appliedSteerIdsByConvoId(CONVO_ID)),
+ applied: useAtomValue(appliedSteerIdsByConvoId(CONVO_ID)),
// Mirrors `useQueueDrain` dequeuing the head item after auto-send.
drainQueue: () => setQueue((prev) => prev.slice(1)),
};
@@ -49,7 +54,10 @@ function setup(initialize?: (snapshot: MutableSnapshot) => void) {
);
}
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ resetSteerFamilies();
+});
describe('useSteerConvert', () => {
beforeEach(() => {
@@ -61,8 +69,8 @@ describe('useSteerConvert', () => {
'hydrates late metadata during terminal recovery (queued origin: %s)',
(fromQueue) => {
const files = [{ file_id: 'f1', filename: 'notes.pdf' }];
- const { result, rerender } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result, rerender } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'legacy',
text: 'recover',
@@ -95,8 +103,8 @@ describe('useSteerConvert', () => {
);
it('converts leftover steers to queued chips and drops their pending chips', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'srv-1', text: 'leftover', status: 'pending' as const, createdAt: 1 },
{ steerId: 'local-x', text: 'still sending', status: 'sending' as const, createdAt: 2 },
]);
@@ -109,8 +117,8 @@ describe('useSteerConvert', () => {
});
it('restores quotes + manual skills from the local chip (server steers never carry them)', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'srv-ctx',
text: 'carried',
@@ -143,9 +151,9 @@ describe('useSteerConvert', () => {
quotes: ['original quote'],
};
const after = { id: 'queue-after', text: 'still queued', createdAt: 20 };
- const { result } = setup(({ set }) => {
+ const { result } = setup(() => {
getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [after]);
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'server-replacement-id',
text: original.text,
@@ -257,9 +265,9 @@ describe('useSteerConvert', () => {
priority: true,
};
const after = { id: 'queue-after-race', text: 'after', createdAt: 20 };
- const { result } = setup(({ set }) => {
+ const { result } = setup(() => {
getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [after]);
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-correlation-id',
text: original.text,
@@ -329,8 +337,8 @@ describe('useSteerConvert', () => {
});
it('retains previously applied ids so a late 202 ACK still drops its chip', () => {
- const { result } = setup(({ set }) => {
- set(store.appliedSteerIdsByConvoId(CONVO_ID), ['srv-applied']);
+ const { result } = setup(() => {
+ getDefaultStore().set(appliedSteerIdsByConvoId(CONVO_ID), ['srv-applied']);
});
act(() => {
result.current.convert(CONVO_ID, [{ steerId: 'srv-queued', text: 'to queue' }]);
@@ -357,8 +365,8 @@ describe('useSteerConvert', () => {
A conversion arriving afterwards may only place its own items; sorting the
whole list would quietly restore the order the messages were written in. */
it('leaves a hand-reordered queue in the order the user left it', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'srv-late', text: 'converted', status: 'pending' as const, createdAt: 9 },
]);
// As if the user had dragged the newest message to the front.
@@ -375,8 +383,8 @@ describe('useSteerConvert', () => {
});
it('still places a converted steer ahead of messages written after it', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'srv-early', text: 'accepted first', status: 'pending' as const, createdAt: 1 },
]);
getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [
diff --git a/client/src/hooks/Chat/__tests__/useSteerEscalate.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerEscalate.spec.tsx
index 9196cee7fc..147f51f5d4 100644
--- a/client/src/hooks/Chat/__tests__/useSteerEscalate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteerEscalate.spec.tsx
@@ -1,13 +1,17 @@
import React from 'react';
-import { RecoilRoot, useRecoilValue } from 'recoil';
+import { RecoilRoot } from 'recoil';
import { getDefaultStore, useAtomValue } from 'jotai';
import { act, renderHook, waitFor } from '@testing-library/react';
-import type { MutableSnapshot } from 'recoil';
+import {
+ escalatingSteerFamily,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+ pendingSteersByConvoId,
+ resetSteerFamilies,
+} from '@librechat/chat/react';
import type { PendingSteer } from '~/hooks/Chat/queue';
import { ChatSettingsContext, defaultChatSettings } from '~/Providers/ChatSettingsContext';
-import { escalatingSteerFamily } from '~/store/steer';
import useSteerEscalate from '../useSteerEscalate';
-import store from '~/store';
const mockArmMutateAsync = jest.fn();
const mockShowToast = jest.fn();
@@ -52,18 +56,17 @@ function setup({
activeGenerationProtocolVersion = 2,
steers = [pending()],
}: SetupOptions = {}) {
- const initializeState = (snapshot: MutableSnapshot) => {
- snapshot.set(store.pendingSteersByConvoId(CONVO_ID), steers);
- if (activeGenerationCreatedAt != null) {
- snapshot.set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), activeGenerationCreatedAt);
- }
- snapshot.set(
- store.activeGenerationProtocolVersionByConvoId(CONVO_ID),
- activeGenerationProtocolVersion,
- );
- };
+ const jotaiStore = getDefaultStore();
+ jotaiStore.set(pendingSteersByConvoId(CONVO_ID), steers);
+ if (activeGenerationCreatedAt != null) {
+ jotaiStore.set(activeGenerationCreatedAtByConvoId(CONVO_ID), activeGenerationCreatedAt);
+ }
+ jotaiStore.set(
+ activeGenerationProtocolVersionByConvoId(CONVO_ID),
+ activeGenerationProtocolVersion,
+ );
const wrapper = ({ children }: { children: React.ReactNode }) => (
- <RecoilRoot initializeState={initializeState}>
+ <RecoilRoot>
<ChatSettingsContext.Provider
value={{
...defaultChatSettings,
@@ -78,7 +81,7 @@ function setup({
return renderHook(
() => ({
escalate: useSteerEscalate(CONVO_ID),
- steers: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ steers: useAtomValue(pendingSteersByConvoId(CONVO_ID)),
escalating: useAtomValue(escalatingSteerFamily(CONVO_ID)),
}),
{ wrapper },
@@ -88,6 +91,7 @@ function setup({
describe('useSteerEscalate', () => {
beforeEach(() => {
jest.clearAllMocks();
+ resetSteerFamilies();
act(() => getDefaultStore().set(escalatingSteerFamily(CONVO_ID), false));
steerArmConfirmationTimeoutMs = undefined;
});
diff --git a/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx
index 367e3c5411..9e7dc72b1d 100644
--- a/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx
@@ -1,14 +1,21 @@
import React from 'react';
-import { getDefaultStore, useAtomValue } from 'jotai';
import { act, render, renderHook } from '@testing-library/react';
-import { RecoilRoot, useRecoilValue, useSetRecoilState, type MutableSnapshot } from 'recoil';
+import { getDefaultStore, useAtomValue, useSetAtom } from 'jotai';
+import { RecoilRoot, useSetRecoilState, type MutableSnapshot } from 'recoil';
+import {
+ pendingSteerCancelClientIdsFamily,
+ acceptedSteerClientIdsByConvoId,
+ activeGenerationCreatedAtByConvoId,
+ appliedSteerIdsByConvoId,
+ pendingSteersByConvoId,
+ resetSteerFamilies,
+} from '@librechat/chat/react';
import type { RewakeDrain } from '~/Providers/ComposerRestoreContext';
import {
ComposerRestoreProvider,
useComposerRestoreHost,
} from '~/Providers/ComposerRestoreContext';
import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';
-import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
import useSteerRecovery from '../useSteerRecovery';
import store from '~/store';
@@ -62,16 +69,19 @@ function setup(initialize?: (snapshot: MutableSnapshot) => void, rewake?: Rewake
return renderHook(
() => ({
recovery: useSteerRecovery(CONVO_ID),
- chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ chips: useAtomValue(pendingSteersByConvoId(CONVO_ID)),
queue: useAtomValue(queuedMessagesByConvoId(CONVO_ID)),
- applied: useRecoilValue(store.appliedSteerIdsByConvoId(CONVO_ID)),
- accepted: useRecoilValue(store.acceptedSteerClientIdsByConvoId(CONVO_ID)),
+ applied: useAtomValue(appliedSteerIdsByConvoId(CONVO_ID)),
+ accepted: useAtomValue(acceptedSteerClientIdsByConvoId(CONVO_ID)),
}),
{ wrapper },
);
}
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ resetSteerFamilies();
+});
describe('useSteerRecovery', () => {
beforeEach(() => {
@@ -82,8 +92,8 @@ describe('useSteerRecovery', () => {
describe('retry', () => {
it('marks the chip sending immediately', () => {
mockMutateAsync.mockReturnValue(new Promise(() => undefined));
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-1', text: 'redo this', status: 'failed', createdAt: 5 },
]);
});
@@ -96,8 +106,8 @@ describe('useSteerRecovery', () => {
});
it('does not retry an uncertain protocol-v1 delivery', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'legacy-uncertain',
text: 'may already be committed',
@@ -124,8 +134,8 @@ describe('useSteerRecovery', () => {
position: 1,
conversationId: CONVO_ID,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-1', text: 'redo this', status: 'failed', createdAt: 5 },
]);
});
@@ -147,8 +157,8 @@ describe('useSteerRecovery', () => {
position: 1,
conversationId: CONVO_ID,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-safe',
text: 'retry safely',
@@ -171,8 +181,8 @@ describe('useSteerRecovery', () => {
it('routes to the queue on NO_ACTIVE_RUN instead of marking it failed again', async () => {
mockMutateAsync.mockRejectedValue({ response: { data: { code: 'NO_ACTIVE_RUN' } } });
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-2', text: 'too late', status: 'failed', createdAt: 7 },
]);
});
@@ -192,8 +202,8 @@ describe('useSteerRecovery', () => {
it('wakes the queue drain when a late retry lands in the queue', async () => {
mockMutateAsync.mockRejectedValue({ response: { data: { code: 'NO_ACTIVE_RUN' } } });
const rewake = jest.fn();
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-late', text: 'after the end', status: 'failed', createdAt: 8 },
]);
}, rewake);
@@ -210,8 +220,8 @@ describe('useSteerRecovery', () => {
it('leaves the drain alone when a retry is accepted into a live run', async () => {
mockMutateAsync.mockResolvedValue({ steerId: 'srv-live', preempt: false });
const rewake = jest.fn();
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-live', text: 'still running', status: 'failed', createdAt: 9 },
]);
}, rewake);
@@ -244,10 +254,10 @@ describe('useSteerRecovery', () => {
let cancelLikeTheUiDoes: () => void = () => undefined;
function Tree() {
recovery = useSteerRecovery(CONVO_ID);
- chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
+ chips = useAtomValue(pendingSteersByConvoId(CONVO_ID));
queue = useAtomValue(queuedMessagesByConvoId(CONVO_ID));
- accepted = useRecoilValue(store.acceptedSteerClientIdsByConvoId(CONVO_ID));
- const setChips = useSetRecoilState(store.pendingSteersByConvoId(CONVO_ID));
+ accepted = useAtomValue(acceptedSteerClientIdsByConvoId(CONVO_ID));
+ const setChips = useSetAtom(pendingSteersByConvoId(CONVO_ID));
/* What the optimistic cancel does to a `sending` chip: hide it and
arm the marker the deferred settle has to consult. */
cancelLikeTheUiDoes = () =>
@@ -259,7 +269,7 @@ describe('useSteerRecovery', () => {
<RecoilRoot
initializeState={(snapshot) => {
seedRun(snapshot, true);
- snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-race',
text: 'changed my mind',
@@ -302,8 +312,8 @@ describe('useSteerRecovery', () => {
it('settles the steer as live when the racing cancel lost', async () => {
mockMutateAsync.mockResolvedValue({ steerId: 'srv-kept', preempt: false });
mockCancelSteer.mockResolvedValue({ removed: false });
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-kept', text: 'still wanted', status: 'failed', createdAt: 4 },
]);
});
@@ -322,8 +332,8 @@ describe('useSteerRecovery', () => {
it('treats the steer as live when the racing cancel POST fails', async () => {
mockMutateAsync.mockResolvedValue({ steerId: 'srv-unknown', preempt: false });
mockCancelSteer.mockRejectedValue(new Error('network'));
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-unknown', text: 'unknown outcome', status: 'failed', createdAt: 4 },
]);
});
@@ -350,8 +360,8 @@ describe('useSteerRecovery', () => {
let dropChip: () => void = () => undefined;
const Tree = () => {
recovery = useSteerRecovery(CONVO_ID);
- chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
- const setChips = useSetRecoilState(store.pendingSteersByConvoId(CONVO_ID));
+ chips = useAtomValue(pendingSteersByConvoId(CONVO_ID));
+ const setChips = useSetAtom(pendingSteersByConvoId(CONVO_ID));
dropChip = () =>
setChips((prev) => prev.filter((chip) => chip.steerId !== 'local-vanish'));
return null;
@@ -361,7 +371,7 @@ describe('useSteerRecovery', () => {
<RecoilRoot
initializeState={(snapshot) => {
seedRun(snapshot, true);
- snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-vanish',
text: 'do not lose me',
@@ -399,9 +409,10 @@ describe('useSteerRecovery', () => {
it('binds a queued retry ack to its receipt only under protocol v2', async () => {
mockMutateAsync.mockResolvedValue({ steerId: 'srv-bound', preempt: false });
const bind = async (generationProtocolVersion: 1 | 2) => {
+ resetSteerFamilies();
const { result, unmount } = setup(({ set }) => {
set(store.isSubmittingFamily(0), false);
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: `local-v${generationProtocolVersion}`,
text: 'landed after the end',
@@ -439,8 +450,8 @@ describe('useSteerRecovery', () => {
/** Each code gets its own render; the queue lives in the shared default store. */
resetQueueFamilies();
mockMutateAsync.mockRejectedValue({ response: { data: { code } } });
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: `local-${code}`, text: code, status: 'failed', createdAt: 1 },
]);
});
@@ -454,8 +465,8 @@ describe('useSteerRecovery', () => {
it('marks delivery uncertain after an ambiguous retry error', async () => {
mockMutateAsync.mockRejectedValue(new Error('network'));
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-3', text: 'network flake', status: 'failed', createdAt: 1 },
]);
});
@@ -475,8 +486,8 @@ describe('useSteerRecovery', () => {
it('keeps a definite retry rejection ordinary', async () => {
mockMutateAsync.mockRejectedValue({ response: { status: 400 } });
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-rejected',
text: 'rejected',
@@ -515,7 +526,7 @@ describe('useSteerRecovery', () => {
/* Outlives the run, the way the store does: the hook's own tree goes
away while the conversation's state stays behind to be read. */
const Observer = () => {
- chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
+ chips = useAtomValue(pendingSteersByConvoId(CONVO_ID));
queue = useAtomValue(queuedMessagesByConvoId(CONVO_ID));
setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));
return null;
@@ -524,7 +535,7 @@ describe('useSteerRecovery', () => {
<RecoilRoot
initializeState={(snapshot) => {
seedRun(snapshot, true);
- snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-late', text: 'landed too late', status: 'failed', createdAt: 3 },
]);
}}
@@ -580,7 +591,7 @@ describe('useSteerRecovery', () => {
let queue: unknown[] = [];
const Tree = () => {
recovery = useSteerRecovery(CONVO_ID);
- chips = useRecoilValue(store.pendingSteersByConvoId(CONVO_ID));
+ chips = useAtomValue(pendingSteersByConvoId(CONVO_ID));
queue = useAtomValue(queuedMessagesByConvoId(CONVO_ID));
const setConvo = useSetRecoilState(store.conversationByIndex(0));
navigateAway = () => setConvo({ conversationId: 'a-different-chat' } as never);
@@ -591,7 +602,7 @@ describe('useSteerRecovery', () => {
<RecoilRoot
initializeState={(snapshot) => {
seedRun(snapshot, true);
- snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-nav', text: 'still running', status: 'failed', createdAt: 2 },
]);
}}
@@ -623,7 +634,7 @@ describe('useSteerRecovery', () => {
snapshot.set(store.conversationByIndex(1), { conversationId: CONVO_ID } as never);
snapshot.set(store.isSubmittingFamily(0), false);
snapshot.set(store.isSubmittingFamily(1), true);
- snapshot.set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-pane', text: 'second pane owns it', status: 'failed', createdAt: 4 },
]);
});
@@ -652,8 +663,8 @@ describe('useSteerRecovery', () => {
conversationId: CONVO_ID,
preempt: true,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-preempt',
text: 'stop and read this',
@@ -682,8 +693,8 @@ describe('useSteerRecovery', () => {
position: 1,
conversationId: CONVO_ID,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-plain', text: 'just a steer', status: 'failed', createdAt: 6 },
]);
});
@@ -704,8 +715,8 @@ describe('useSteerRecovery', () => {
conversationId: CONVO_ID,
preempt: false,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-degraded',
text: 'seal it',
@@ -733,8 +744,8 @@ describe('useSteerRecovery', () => {
position: 1,
conversationId: CONVO_ID,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-ctx',
text: 'about that quote',
@@ -774,8 +785,8 @@ describe('useSteerRecovery', () => {
position: 1,
conversationId: CONVO_ID,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-id',
text: 'pin me to my generation',
@@ -808,8 +819,8 @@ describe('useSteerRecovery', () => {
position: 1,
conversationId: CONVO_ID,
});
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'srv-known',
clientSteerId: 'local-known',
@@ -843,9 +854,9 @@ describe('useSteerRecovery', () => {
is still submitting and looks live. */
it('queues an ack whose source generation was replaced', async () => {
mockMutateAsync.mockResolvedValue(ack('srv-epoch'));
- const { result } = setup(({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 900);
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 900);
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-epoch',
text: 'older generation',
@@ -869,9 +880,9 @@ describe('useSteerRecovery', () => {
so the server will inject it and the chip waits for that event. */
it('keeps an ack pending while its own generation is still the active one', async () => {
mockMutateAsync.mockResolvedValue(ack('srv-live'));
- const { result } = setup(({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 100);
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'local-live',
text: 'same generation',
@@ -898,8 +909,8 @@ describe('useSteerRecovery', () => {
mockMutateAsync.mockResolvedValue(ack('srv-applied'));
const { result } = setup(({ set }) => {
set(store.isSubmittingFamily(0), false);
- set(store.appliedSteerIdsByConvoId(CONVO_ID), ['srv-applied']);
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(appliedSteerIdsByConvoId(CONVO_ID), ['srv-applied']);
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-applied', text: 'already injected', status: 'failed', createdAt: 3 },
]);
});
@@ -915,8 +926,8 @@ describe('useSteerRecovery', () => {
for the same attempt cannot re-mint a chip that was already settled. */
it('records the accepted client id', async () => {
mockMutateAsync.mockResolvedValue(ack('srv-accepted'));
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 'local-accepted', text: 'note the id', status: 'failed', createdAt: 4 },
]);
});
@@ -939,8 +950,8 @@ describe('useSteerRecovery', () => {
describe('sendAsNew', () => {
it('does not reroute an uncertain protocol-v1 delivery', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'legacy-uncertain',
text: 'may already be committed',
@@ -959,8 +970,8 @@ describe('useSteerRecovery', () => {
});
it('does not reroute an uncertain protocol-v2 delivery as a new turn', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'modern-uncertain',
text: 'retry only under the same id',
@@ -979,8 +990,8 @@ describe('useSteerRecovery', () => {
});
it('moves the chip to the queue, merged chronologically with existing items', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 's-old', text: 'older failed steer', status: 'failed', createdAt: 0 },
]);
getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [
@@ -997,8 +1008,8 @@ describe('useSteerRecovery', () => {
});
it('records the id in appliedSteerIds so a late ACK cannot re-mint the chip', () => {
- const { result } = setup(({ set }) => {
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ const { result } = setup(() => {
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{ steerId: 's-late', text: 'send me', status: 'failed', createdAt: 1 },
]);
});
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index 03f99c56f0..6b491f32fc 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -1,7 +1,7 @@
import React from 'react';
+import { RecoilRoot, type MutableSnapshot } from 'recoil';
import { claimQueuedIntent, releaseQueuedIntent } from '@librechat/chat';
import { act, render, renderHook, waitFor } from '@testing-library/react';
-import { RecoilRoot, useRecoilValue, useSetRecoilState, type MutableSnapshot } from 'recoil';
import {
getDefaultStore,
Provider as JotaiProvider,
@@ -16,6 +16,16 @@ import {
LocalStorageKeys,
ReasoningEffort,
} from 'librechat-data-provider';
+import {
+ revealedQueuedTurnFamily,
+ pendingSteerCancelClientIdsFamily,
+ acceptedSteerClientIdsByConvoId,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+ appliedSteerIdsByConvoId,
+ pendingSteersByConvoId,
+ resetSteerFamilies,
+} from '@librechat/chat/react';
import type { CodeApprovalMode, TConversation, TFile, TMessage } from 'librechat-data-provider';
import type { QueuedMessage } from '~/hooks/Chat/queue';
import type { ExtendedFile } from '~/common';
@@ -34,7 +44,6 @@ import {
pendingManualSkillsByConvoId,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
-import { revealedQueuedTurnFamily, pendingSteerCancelClientIdsFamily } from '~/store/steer';
import useSteering, { hasLiveRunPause, mergeQueuedTurnFileMetadata } from '../useSteering';
import { clearAllDrafts, getPendingDraftId, getNewConversationDraftId } from '~/utils';
import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
@@ -136,10 +145,14 @@ const agentsConversation = {
type HookParams = Partial<Parameters<typeof useSteering>[0]>;
const withActiveGeneration =
- (initialize?: (snapshot: MutableSnapshot) => void, conversationId = CONVO_ID) =>
+ (
+ initialize?: (snapshot: MutableSnapshot) => void,
+ conversationId = CONVO_ID,
+ jotaiStore: ReturnType<typeof createStore> = getDefaultStore(),
+ ) =>
(snapshot: MutableSnapshot) => {
- snapshot.set(store.activeGenerationCreatedAtByConvoId(conversationId), 41);
- snapshot.set(store.activeGenerationProtocolVersionByConvoId(conversationId), 2);
+ jotaiStore.set(activeGenerationCreatedAtByConvoId(conversationId), 41);
+ jotaiStore.set(activeGenerationProtocolVersionByConvoId(conversationId), 2);
initialize?.(snapshot);
};
@@ -148,8 +161,8 @@ function setup(params: HookParams = {}, initialize?: (snapshot: MutableSnapshot)
const stopGenerating = jest.fn();
let setGenerationCreatedAt: ((value: number | null) => void) | undefined;
const GenerationProbe = () => {
- setGenerationCreatedAt = useSetRecoilState(
- store.activeGenerationCreatedAtByConvoId(params.conversationId ?? CONVO_ID),
+ setGenerationCreatedAt = useSetAtom(
+ activeGenerationCreatedAtByConvoId(params.conversationId ?? CONVO_ID),
);
return null;
};
@@ -210,6 +223,7 @@ function sendFromQueue(
beforeEach(() => {
resetQueueFamilies();
+ resetSteerFamilies();
getDefaultStore().set(pendingQuotesByConvoId(CONVO_ID), []);
getDefaultStore().set(pendingManualSkillsByConvoId(CONVO_ID), []);
});
@@ -606,8 +620,8 @@ describe('useSteering', () => {
});
it('queues during startup and exposes no live mutation until the generation epoch arrives', () => {
- const { result, stopGenerating, setGenerationCreatedAt } = setup({}, ({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ const { result, stopGenerating, setGenerationCreatedAt } = setup({}, () => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), null);
});
expect(result.current.duringRunActive).toBe(true);
@@ -750,8 +764,8 @@ describe('useSteering', () => {
it('keeps startup turns local until the server generation epoch exists', async () => {
const { result } = setupServerQueue(
- withActiveGeneration(({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ withActiveGeneration(() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), null);
}),
);
@@ -769,8 +783,8 @@ describe('useSteering', () => {
it('keeps a re-queued row durable on its own lineage once the run it waited on has ended', async () => {
const { result } = setupServerQueue(
- withActiveGeneration(({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ withActiveGeneration(() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), null);
}),
);
@@ -825,8 +839,8 @@ describe('useSteering', () => {
});
getDefaultStore().set(pendingQuotesByConvoId(CONVO_ID), ['quoted context']);
getDefaultStore().set(pendingManualSkillsByConvoId(CONVO_ID), ['skill']);
- const { result, unmount } = setup({ isSubmitting: false }, ({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ const { result, unmount } = setup({ isSubmitting: false }, () => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), null);
});
expect(result.current.duringRunActive).toBe(true);
expect(result.current.canSteer).toBe(false);
@@ -2576,11 +2590,11 @@ describe('useSteering', () => {
const stopGenerating = jest.fn();
const wrapper = ({ children }: { children: React.ReactNode }) => (
<RecoilRoot
- initializeState={({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 41);
- set(store.activeGenerationProtocolVersionByConvoId(CONVO_ID), 2);
- set(store.activeGenerationCreatedAtByConvoId(otherConversationId), 42);
- set(store.activeGenerationProtocolVersionByConvoId(otherConversationId), 2);
+ initializeState={() => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 41);
+ getDefaultStore().set(activeGenerationProtocolVersionByConvoId(CONVO_ID), 2);
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(otherConversationId), 42);
+ getDefaultStore().set(activeGenerationProtocolVersionByConvoId(otherConversationId), 2);
}}
>
{children}
@@ -2662,14 +2676,12 @@ describe('useSteering', () => {
}),
queue: useQueue(CONVO_ID),
setQueue: useSetAtom(queuedMessagesByConvoId(CONVO_ID)),
- setActiveEpoch: useSetRecoilState(store.activeGenerationCreatedAtByConvoId(CONVO_ID)),
- setActiveProtocol: useSetRecoilState(
- store.activeGenerationProtocolVersionByConvoId(CONVO_ID),
- ),
- setAcceptedIds: useSetRecoilState(store.acceptedSteerClientIdsByConvoId(CONVO_ID)),
- chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
- setChips: useSetRecoilState(store.pendingSteersByConvoId(CONVO_ID)),
- setAppliedIds: useSetRecoilState(store.appliedSteerIdsByConvoId(CONVO_ID)),
+ setActiveEpoch: useSetAtom(activeGenerationCreatedAtByConvoId(CONVO_ID)),
+ setActiveProtocol: useSetAtom(activeGenerationProtocolVersionByConvoId(CONVO_ID)),
+ setAcceptedIds: useSetAtom(acceptedSteerClientIdsByConvoId(CONVO_ID)),
+ chips: useAtomValue(pendingSteersByConvoId(CONVO_ID)),
+ setChips: useSetAtom(pendingSteersByConvoId(CONVO_ID)),
+ setAppliedIds: useSetAtom(appliedSteerIdsByConvoId(CONVO_ID)),
drainFlag: useAtomValue(drainAfterAbortByIndex(0)),
}),
{ wrapper },
@@ -2802,8 +2814,8 @@ describe('useSteering', () => {
mockMutate.mockImplementationOnce((_params, { onError }) =>
onError(new Error('network disconnected')),
);
- const { result } = setupWithState({}, ({ set }) => {
- set(store.activeGenerationProtocolVersionByConvoId(CONVO_ID), 1);
+ const { result } = setupWithState({}, () => {
+ getDefaultStore().set(activeGenerationProtocolVersionByConvoId(CONVO_ID), 1);
});
act(() => {
@@ -2914,8 +2926,8 @@ describe('useSteering', () => {
mockMutate.mockImplementation((_params, { onError }) => {
onError({ response: { status: 400, data: { code: 'INVALID_STEER' } } });
});
- const { result } = setupWithState({}, ({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 41);
+ const { result } = setupWithState({}, () => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 41);
});
act(() => {
@@ -3025,10 +3037,10 @@ describe('useSteering', () => {
conversationId: CONVO_ID,
});
});
- const { result } = setupWithState({}, ({ set }) => {
+ const { result } = setupWithState({}, () => {
// seedSteerChips already re-minted this chip from resumeState before
// the 202 ACK landed; the ACK must upsert, not append.
- set(store.pendingSteersByConvoId(CONVO_ID), [
+ getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [
{
steerId: 'srv-3',
text: 'reseeded',
@@ -3773,7 +3785,7 @@ describe('useSteering', () => {
initialize === null
? undefined
: (snapshot) => {
- snapshot.set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), 41);
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), 41);
initialize?.(snapshot);
}
}
@@ -4203,7 +4215,11 @@ describe('useSteering', () => {
const wrapper = ({ children }: { children: React.ReactNode }) => (
<JotaiProvider store={reasoningStore}>
<RecoilRoot
- initializeState={withActiveGeneration(initialize, params.conversationId ?? CONVO_ID)}
+ initializeState={withActiveGeneration(
+ initialize,
+ params.conversationId ?? CONVO_ID,
+ reasoningStore,
+ )}
>
{children}
</RecoilRoot>
@@ -4224,11 +4240,11 @@ describe('useSteering', () => {
}),
queue: useQueue(CONVO_ID),
setQueue: useSetAtom(queuedMessagesByConvoId(CONVO_ID)),
- chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
+ chips: useAtomValue(pendingSteersByConvoId(CONVO_ID)),
pendingQuotes: useAtomValue(pendingQuotesByConvoId(CONVO_ID)),
pendingSkills: useAtomValue(pendingManualSkillsByConvoId(CONVO_ID)),
pendingReasoning: useAtomValue(pendingReasoningOverrideFamily(CONVO_ID)),
- markApplied: useSetRecoilState(store.appliedSteerIdsByConvoId(CONVO_ID)),
+ markApplied: useSetAtom(appliedSteerIdsByConvoId(CONVO_ID)),
}),
{ wrapper },
);
@@ -4870,8 +4886,8 @@ describe('useSteering', () => {
text: 'pending',
revealedAt: new Date().toISOString(),
});
- const { result, unmount } = setup({ isSubmitting: false, filesLoading }, ({ set }) => {
- set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ const { result, unmount } = setup({ isSubmitting: false, filesLoading }, () => {
+ getDefaultStore().set(activeGenerationCreatedAtByConvoId(CONVO_ID), null);
});
await act(async () => {
expect(result.current.submitDuringRun('drafted text')).toBe(!filesLoading);
diff --git a/client/src/hooks/Chat/steering/chips.ts b/client/src/hooks/Chat/steering/chips.ts
index 91d7518b4e..2e0df72f77 100644
--- a/client/src/hooks/Chat/steering/chips.ts
+++ b/client/src/hooks/Chat/steering/chips.ts
@@ -1,14 +1,18 @@
import { useCallback, useMemo } from 'react';
import { useStore } from 'jotai';
-import { useRecoilCallback } from 'recoil';
import { isSteerRunReplaced, acknowledgeSteerChips } from '@librechat/chat';
+import {
+ pendingSteerCancelClientIdsFamily,
+ pendingSteersByConvoId,
+ appliedSteerIdsByConvoId,
+ acceptedSteerClientIdsByConvoId,
+ activeGenerationCreatedAtByConvoId,
+} from '@librechat/chat/react';
import type { PendingSteer } from '@librechat/chat';
-import type { CallbackInterface } from 'recoil';
import type { MutableRefObject } from 'react';
+import type { createStore } from 'jotai';
import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { appendAppliedSteerIds, mergeRestagedQuotes } from '~/utils';
-import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
-import store from '~/store';
/**
* Resolves a steer's 202 ACK against the applied-id set and the run's live
@@ -29,27 +33,26 @@ import store from '~/store';
*
* @returns true when the caller must route the steer into the queue.
*/
+type JotaiStore = Pick<ReturnType<typeof createStore>, 'get' | 'set'>;
+
export function resolveAcknowledgedSteer(
- { snapshot, set }: Pick<CallbackInterface, 'snapshot' | 'set'>,
+ jotaiStore: JotaiStore,
conversationId: string,
localId: string,
steer: PendingSteer,
ordinaryRunOver: boolean,
): boolean {
- const applied = snapshot.getLoadable(store.appliedSteerIdsByConvoId(conversationId)).getValue();
+ const applied = jotaiStore.get(appliedSteerIdsByConvoId(conversationId));
const alreadyApplied = applied.includes(steer.steerId) || applied.includes(localId);
- const alreadyAccepted = snapshot
- .getLoadable(store.acceptedSteerClientIdsByConvoId(conversationId))
- .getValue()
+ const alreadyAccepted = jotaiStore
+ .get(acceptedSteerClientIdsByConvoId(conversationId))
.includes(localId);
- const activeEpoch = snapshot
- .getLoadable(store.activeGenerationCreatedAtByConvoId(conversationId))
- .getValue();
+ const activeEpoch = jotaiStore.get(activeGenerationCreatedAtByConvoId(conversationId));
const runOver = ordinaryRunOver || isSteerRunReplaced(steer, activeEpoch);
- set(store.acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
+ jotaiStore.set(acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
appendAppliedSteerIds(prev, [localId]),
);
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
acknowledgeSteerChips(prev, localId, steer, alreadyApplied || alreadyAccepted || runOver),
);
/** `alreadyAccepted` can come from the correlation update that precedes the
@@ -77,31 +80,29 @@ export default function useSteerChips({
isSubmittingRef: MutableRefObject<boolean>;
}) {
const jotaiStore = useStore();
- const upsertSteerChip = useRecoilCallback(
- ({ set }) =>
- (convoId: string, steer: PendingSteer) => {
- set(store.pendingSteersByConvoId(convoId), (prev) => {
- const existing = prev.findIndex((item) => item.steerId === steer.steerId);
- if (existing >= 0) {
- const next = [...prev];
- next[existing] = steer;
- return next;
- }
- return [...prev, steer];
- });
- },
- [],
+ const upsertSteerChip = useCallback(
+ (convoId: string, steer: PendingSteer) => {
+ jotaiStore.set(pendingSteersByConvoId(convoId), (prev) => {
+ const existing = prev.findIndex((item) => item.steerId === steer.steerId);
+ if (existing >= 0) {
+ const next = [...prev];
+ next[existing] = steer;
+ return next;
+ }
+ return [...prev, steer];
+ });
+ },
+ [jotaiStore],
);
- const replaceSteerChip = useRecoilCallback(
- ({ set }) =>
- (convoId: string, localId: string, steer: PendingSteer | null) => {
- set(store.pendingSteersByConvoId(convoId), (prev) => {
- const next = prev.filter((item) => item.steerId !== localId);
- return steer ? [...next, steer] : next;
- });
- },
- [],
+ const replaceSteerChip = useCallback(
+ (convoId: string, localId: string, steer: PendingSteer | null) => {
+ jotaiStore.set(pendingSteersByConvoId(convoId), (prev) => {
+ const next = prev.filter((item) => item.steerId !== localId);
+ return steer ? [...next, steer] : next;
+ });
+ },
+ [jotaiStore],
);
/**
@@ -114,57 +115,51 @@ export default function useSteerChips({
* only be inferred while the callback still belongs to the visible chat.
* Epoch replacement is derived inside the resolver for every caller.
*/
- const acknowledgeSteer = useRecoilCallback(
- (cbInterface) =>
- (convoId: string, localId: string, steer: PendingSteer): boolean =>
- resolveAcknowledgedSteer(
- cbInterface,
- convoId,
- localId,
- steer,
- visibleConversationRef.current === convoId && !isSubmittingRef.current,
- ),
- [],
+ const acknowledgeSteer = useCallback(
+ (convoId: string, localId: string, steer: PendingSteer): boolean =>
+ resolveAcknowledgedSteer(
+ jotaiStore,
+ convoId,
+ localId,
+ steer,
+ visibleConversationRef.current === convoId && !isSubmittingRef.current,
+ ),
+ [jotaiStore, visibleConversationRef, isSubmittingRef],
);
- const settleReceiptReplay = useRecoilCallback(
- ({ set }) =>
- (convoId: string, localId: string, serverId: string) => {
- set(store.appliedSteerIdsByConvoId(convoId), (prev) =>
- appendAppliedSteerIds(prev, [localId, serverId]),
- );
- set(store.acceptedSteerClientIdsByConvoId(convoId), (prev) =>
- appendAppliedSteerIds(prev, [localId]),
- );
- set(store.pendingSteersByConvoId(convoId), (prev) =>
- prev.filter((steer) => steer.steerId !== localId && steer.steerId !== serverId),
- );
- },
- [],
+ const settleReceiptReplay = useCallback(
+ (convoId: string, localId: string, serverId: string) => {
+ jotaiStore.set(appliedSteerIdsByConvoId(convoId), (prev) =>
+ appendAppliedSteerIds(prev, [localId, serverId]),
+ );
+ jotaiStore.set(acceptedSteerClientIdsByConvoId(convoId), (prev) =>
+ appendAppliedSteerIds(prev, [localId]),
+ );
+ jotaiStore.set(pendingSteersByConvoId(convoId), (prev) =>
+ prev.filter((steer) => steer.steerId !== localId && steer.steerId !== serverId),
+ );
+ },
+ [jotaiStore],
);
/** Terminal/applied SSE can settle the optimistic client id before either
* HTTP callback. Those callbacks must become no-ops or a lost response can
* resurrect already-delivered words as a failed chip or queued fallback. */
- const isSteerAcceptedOrSettled = useRecoilCallback(
- ({ snapshot }) =>
- (convoId: string, clientSteerId: string) => {
- const applied = snapshot.getLoadable(store.appliedSteerIdsByConvoId(convoId)).getValue();
- if (applied.includes(clientSteerId)) {
- return true;
- }
- const accepted = snapshot
- .getLoadable(store.acceptedSteerClientIdsByConvoId(convoId))
- .getValue();
- if (accepted.includes(clientSteerId)) {
- return true;
- }
- return snapshot
- .getLoadable(store.pendingSteersByConvoId(convoId))
- .getValue()
- .some((steer) => steer.status === 'pending' && steer.clientSteerId === clientSteerId);
- },
- [],
+ const isSteerAcceptedOrSettled = useCallback(
+ (convoId: string, clientSteerId: string) => {
+ const applied = jotaiStore.get(appliedSteerIdsByConvoId(convoId));
+ if (applied.includes(clientSteerId)) {
+ return true;
+ }
+ const accepted = jotaiStore.get(acceptedSteerClientIdsByConvoId(convoId));
+ if (accepted.includes(clientSteerId)) {
+ return true;
+ }
+ return jotaiStore
+ .get(pendingSteersByConvoId(convoId))
+ .some((steer) => steer.status === 'pending' && steer.clientSteerId === clientSteerId);
+ },
+ [jotaiStore],
);
const hasPendingSteerCancel = useCallback(
(convoId: string, clientSteerId: string) =>
@@ -193,39 +188,36 @@ export default function useSteerChips({
* double-deliver. The chip is stripped in the same update (including its
* captured queue-origin copy) so the restaged composer chips stay their
* single representation. */
- const reclaimRejectedChipQuotes = useRecoilCallback(
- ({ snapshot, set }) =>
- (convoId: string, steerIds: string[]) => {
- const chips = snapshot.getLoadable(store.pendingSteersByConvoId(convoId)).getValue();
- const chip = chips.find((steer) => steerIds.includes(steer.steerId));
- const quotes = chip?.quotes ?? chip?.queuedOrigin?.item.quotes;
- if (quotes == null || quotes.length === 0) {
- return;
- }
- jotaiStore.set(pendingQuotesByConvoId(convoId), (prev) =>
- mergeRestagedQuotes(prev, quotes),
- );
- set(store.pendingSteersByConvoId(convoId), (prev) => {
- let changed = false;
- const next = prev.map((steer) => {
- const originHasQuotes = steer.queuedOrigin?.item.quotes != null;
- if (!steerIds.includes(steer.steerId) || (steer.quotes == null && !originHasQuotes)) {
- return steer;
- }
- changed = true;
- const { quotes: _quotes, ...rest } = steer;
- if (!originHasQuotes || rest.queuedOrigin == null) {
- return rest;
- }
- const { quotes: _originQuotes, ...originItem } = rest.queuedOrigin.item;
- return {
- ...rest,
- queuedOrigin: { ...rest.queuedOrigin, item: originItem },
- };
- });
- return changed ? next : prev;
+ const reclaimRejectedChipQuotes = useCallback(
+ (convoId: string, steerIds: string[]) => {
+ const chips = jotaiStore.get(pendingSteersByConvoId(convoId));
+ const chip = chips.find((steer) => steerIds.includes(steer.steerId));
+ const quotes = chip?.quotes ?? chip?.queuedOrigin?.item.quotes;
+ if (quotes == null || quotes.length === 0) {
+ return;
+ }
+ jotaiStore.set(pendingQuotesByConvoId(convoId), (prev) => mergeRestagedQuotes(prev, quotes));
+ jotaiStore.set(pendingSteersByConvoId(convoId), (prev) => {
+ let changed = false;
+ const next = prev.map((steer) => {
+ const originHasQuotes = steer.queuedOrigin?.item.quotes != null;
+ if (!steerIds.includes(steer.steerId) || (steer.quotes == null && !originHasQuotes)) {
+ return steer;
+ }
+ changed = true;
+ const { quotes: _quotes, ...rest } = steer;
+ if (!originHasQuotes || rest.queuedOrigin == null) {
+ return rest;
+ }
+ const { quotes: _originQuotes, ...originItem } = rest.queuedOrigin.item;
+ return {
+ ...rest,
+ queuedOrigin: { ...rest.queuedOrigin, item: originItem },
+ };
});
- },
+ return changed ? next : prev;
+ });
+ },
[jotaiStore],
);
diff --git a/client/src/hooks/Chat/steering/enqueue.ts b/client/src/hooks/Chat/steering/enqueue.ts
index 0ead90ad61..645e60f840 100644
--- a/client/src/hooks/Chat/steering/enqueue.ts
+++ b/client/src/hooks/Chat/steering/enqueue.ts
@@ -3,8 +3,8 @@ import { v4 } from 'uuid';
import { useStore } from 'jotai';
import { getSteerErrorCode, toQueuedTurnFileRefs, QUEUE_USAGE_MAX_FILES } from '@librechat/chat';
import type { TMessage, CodeApprovalMode } from 'librechat-data-provider';
+import type { RevealedQueuedTurn } from '@librechat/chat/react';
import type { QueuedMessage } from '@librechat/chat';
-import type { RevealedQueuedTurn } from '~/store/steer';
import type { QueuedTurnReceipts } from './receipts';
import type { QueueRows } from './rows';
import {
diff --git a/client/src/hooks/Chat/steering/recovery.ts b/client/src/hooks/Chat/steering/recovery.ts
index 6782c15412..60cdbb6754 100644
--- a/client/src/hooks/Chat/steering/recovery.ts
+++ b/client/src/hooks/Chat/steering/recovery.ts
@@ -1,13 +1,13 @@
import { useCallback, useMemo } from 'react';
import { useStore } from 'jotai';
import { useToastContext } from '@librechat/client';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { blockRecovery, canRestoreRecovery, recoveryDisposition } from '@librechat/chat';
import type { QueuedMessage } from '@librechat/chat';
import type { QueuedTurnReceipts } from './receipts';
import type { QueueRows } from './rows';
import { useCancelSteerMutation, useCancelAgentQueuedTurnMutation } from '~/data-provider';
import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import useLocalize from '~/hooks/useLocalize';
/** Lets go of a queued row's server copy (a durable queued turn or a parked
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index 7551c934d2..45e6cecc3d 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -5,6 +5,7 @@ import { useStore, useSetAtom } from 'jotai';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { useSetRecoilState, useRecoilValue } from 'recoil';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import {
Constants,
QueryKeys,
@@ -65,7 +66,6 @@ import { useAgentsMapContext } from '~/Providers/AgentsMapContext';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace';
import useGetSender from '~/hooks/Conversations/useGetSender';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import store, { useGetEphemeralAgent } from '~/store';
import useUserKey from '~/hooks/Input/useUserKey';
diff --git a/client/src/hooks/Chat/useChatHelpers.ts b/client/src/hooks/Chat/useChatHelpers.ts
index 902b6d9d3d..1087d0011b 100644
--- a/client/src/hooks/Chat/useChatHelpers.ts
+++ b/client/src/hooks/Chat/useChatHelpers.ts
@@ -1,8 +1,12 @@
import { useCallback, useMemo, useRef, useState } from 'react';
-import { useAtom, useSetAtom, useStore } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
+import { useAtom, useSetAtom, useStore, useAtomValue } from 'jotai';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { Constants, QueryKeys, isAssistantsEndpoint } from 'librechat-data-provider';
+import {
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '@librechat/chat/react';
import type { TMessage } from 'librechat-data-provider';
import type { ChatContract } from './contract';
import { stopRequestedByConvoId, drainAfterAbortByIndex, runEndByIndex } from '~/hooks/Chat/queue';
@@ -81,11 +85,11 @@ export default function useChatHelpers(index = 0, paramId?: string): ChatContrac
const { useCreateConversationAtom } = store;
const { conversation, setConversation } = useCreateConversationAtom(index);
const { conversationId, endpoint, endpointType } = conversation ?? {};
- const activeGenerationCreatedAt = useRecoilValue(
- store.activeGenerationCreatedAtByConvoId(conversationId ?? Constants.NEW_CONVO),
+ const activeGenerationCreatedAt = useAtomValue(
+ activeGenerationCreatedAtByConvoId(conversationId ?? Constants.NEW_CONVO),
);
- const activeGenerationProtocolVersion = useRecoilValue(
- store.activeGenerationProtocolVersionByConvoId(conversationId ?? Constants.NEW_CONVO),
+ const activeGenerationProtocolVersion = useAtomValue(
+ activeGenerationProtocolVersionByConvoId(conversationId ?? Constants.NEW_CONVO),
);
/** Use paramId (from URL) as primary source for query key - this must match what ChatView uses
diff --git a/client/src/hooks/Chat/useQueueDrain.ts b/client/src/hooks/Chat/useQueueDrain.ts
index 2187f4689c..327a6270bf 100644
--- a/client/src/hooks/Chat/useQueueDrain.ts
+++ b/client/src/hooks/Chat/useQueueDrain.ts
@@ -2,6 +2,7 @@ import { useRef, useEffect, useMemo, useCallback } from 'react';
import { useRecoilValue } from 'recoil';
import { useAtomValue, useStore } from 'jotai';
import { insertQueuedOrigin } from '@librechat/chat';
+import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { Constants, DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';
import { acquireQueueSendLock, releaseQueueSendLock, hasQueuedIntent } from '@librechat/chat';
import type { QueueSendLock } from '@librechat/chat';
@@ -23,7 +24,6 @@ import {
import { selectQueuedTurnReveal } from '~/hooks/Chat/useQueuedTurnReveal';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import { useMarkFilesUsageMutation } from '~/data-provider';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import { mergeQueuedMessages } from '~/utils/queue';
import store from '~/store';
diff --git a/client/src/hooks/Chat/useQueuedTurnReveal.ts b/client/src/hooks/Chat/useQueuedTurnReveal.ts
index 84b1e6723f..fca7b8e3c2 100644
--- a/client/src/hooks/Chat/useQueuedTurnReveal.ts
+++ b/client/src/hooks/Chat/useQueuedTurnReveal.ts
@@ -3,13 +3,16 @@ import { useRecoilValue } from 'recoil';
import { useStore, useAtomValue } from 'jotai';
import { QueryKeys } from 'librechat-data-provider';
import { useQueryClient } from '@tanstack/react-query';
+import {
+ revealedQueuedTurnFamily,
+ activeGenerationCreatedAtByConvoId,
+} from '@librechat/chat/react';
import type { TMessage, TAgentQueuedTurnReceipt } from 'librechat-data-provider';
+import type { RevealedQueuedTurn } from '@librechat/chat/react';
import type { StreamStatusResponse } from '~/data-provider/SSE/queries';
import type { QueuedMessage, RunEnd } from '~/hooks/Chat/queue';
-import type { RevealedQueuedTurn } from '~/store/steer';
import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import { streamStatusQueryKey } from '~/data-provider/SSE/queries';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import store from '~/store';
const isAdmissible = (item: QueuedMessage): boolean =>
@@ -90,7 +93,7 @@ export default function useQueuedTurnReveal(
const revealKey = conversationId ?? '';
const reveal = useAtomValue(revealedQueuedTurnFamily(revealKey));
const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));
- const activeEpoch = useRecoilValue(store.activeGenerationCreatedAtByConvoId(revealKey));
+ const activeEpoch = useAtomValue(activeGenerationCreatedAtByConvoId(revealKey));
const readHandoff = useCallback(
(intent: RevealedQueuedTurn) => {
const receipts = queryClient.getQueryData<TAgentQueuedTurnReceipt[]>(
diff --git a/client/src/hooks/Chat/useSteerCancel.ts b/client/src/hooks/Chat/useSteerCancel.ts
index 783b510903..1ab4713d7f 100644
--- a/client/src/hooks/Chat/useSteerCancel.ts
+++ b/client/src/hooks/Chat/useSteerCancel.ts
@@ -1,14 +1,17 @@
import { useCallback } from 'react';
-import { useSetAtom, useStore } from 'jotai';
-import { useRecoilCallback, useRecoilValue } from 'recoil';
+import { useSetAtom, useStore, useAtomValue } from 'jotai';
+import {
+ pendingSteerCancelClientIdsFamily,
+ pendingSteersByConvoId,
+ appliedSteerIdsByConvoId,
+ activeGenerationCreatedAtByConvoId,
+} from '@librechat/chat/react';
import type { PendingSteer } from '~/hooks/Chat/queue';
import { useComposerRestoreHost } from '~/Providers/ComposerRestoreContext';
import { appendAppliedSteerIds, carriedSteerContext } from '~/utils';
-import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { useCancelSteerMutation } from '~/data-provider';
-import store from '~/store';
export type SteerCancelOutcome = 'reclaimed' | 'applied' | 'failed';
@@ -21,37 +24,36 @@ export type SteerRehomeTarget = 'composer' | 'queue';
*/
export function useSteerReclaim(conversationId: string) {
const cancelMutation = useCancelSteerMutation();
- const activeGenerationCreatedAt = useRecoilValue(
- store.activeGenerationCreatedAtByConvoId(conversationId),
+ const activeGenerationCreatedAt = useAtomValue(
+ activeGenerationCreatedAtByConvoId(conversationId),
);
const setPendingCancelIds = useSetAtom(pendingSteerCancelClientIdsFamily(conversationId));
- const queueStore = useStore();
- const settleReclaimed = useRecoilCallback(
- ({ set }) =>
- (steer: PendingSteer) => {
- const ids = [steer.steerId, ...(steer.clientSteerId ? [steer.clientSteerId] : [])];
- const settled = new Set(ids);
- set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, ids),
- );
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.filter(
- (item) =>
- !settled.has(item.steerId) &&
- (item.clientSteerId == null || !settled.has(item.clientSteerId)),
- ),
- );
- setPendingCancelIds((prev) => prev.filter((id) => !ids.includes(id)));
- queueStore.set(queuedMessagesByConvoId(conversationId), (prev) =>
- prev.filter(
- (item) =>
- !settled.has(item.id) &&
- (item.recoverySteerId == null || !settled.has(item.recoverySteerId)) &&
- (item.recoveryClientSteerId == null || !settled.has(item.recoveryClientSteerId)),
- ),
- );
- },
- [conversationId, setPendingCancelIds, queueStore],
+ const jotaiStore = useStore();
+ const settleReclaimed = useCallback(
+ (steer: PendingSteer) => {
+ const ids = [steer.steerId, ...(steer.clientSteerId ? [steer.clientSteerId] : [])];
+ const settled = new Set(ids);
+ jotaiStore.set(appliedSteerIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, ids),
+ );
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ prev.filter(
+ (item) =>
+ !settled.has(item.steerId) &&
+ (item.clientSteerId == null || !settled.has(item.clientSteerId)),
+ ),
+ );
+ setPendingCancelIds((prev) => prev.filter((id) => !ids.includes(id)));
+ jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) =>
+ prev.filter(
+ (item) =>
+ !settled.has(item.id) &&
+ (item.recoverySteerId == null || !settled.has(item.recoverySteerId)) &&
+ (item.recoveryClientSteerId == null || !settled.has(item.recoveryClientSteerId)),
+ ),
+ );
+ },
+ [conversationId, setPendingCancelIds, jotaiStore],
);
return useCallback(
@@ -130,19 +132,18 @@ export interface SteerRehomeOptions {
export function useSteerRehome(conversationId: string) {
const { restore, rewakeDrain } = useComposerRestoreHost();
const convertSteersToQueued = useSteerConvert();
- const dropPendingSteer = useRecoilCallback(
- ({ set }) =>
- (steer: PendingSteer) => {
- const ids = new Set([steer.steerId, ...(steer.clientSteerId ? [steer.clientSteerId] : [])]);
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.filter(
- (item) =>
- !ids.has(item.steerId) &&
- (item.clientSteerId == null || !ids.has(item.clientSteerId)),
- ),
- );
- },
- [conversationId],
+ const jotaiStore = useStore();
+ const dropPendingSteer = useCallback(
+ (steer: PendingSteer) => {
+ const ids = new Set([steer.steerId, ...(steer.clientSteerId ? [steer.clientSteerId] : [])]);
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ prev.filter(
+ (item) =>
+ !ids.has(item.steerId) && (item.clientSteerId == null || !ids.has(item.clientSteerId)),
+ ),
+ );
+ },
+ [conversationId, jotaiStore],
);
return useCallback(
@@ -173,18 +174,18 @@ export default function useSteerCancel(conversationId: string) {
const reclaim = useSteerReclaim(conversationId);
const rehome = useSteerRehome(conversationId);
const setPendingCancelIds = useSetAtom(pendingSteerCancelClientIdsFamily(conversationId));
- const markOptimisticCancel = useRecoilCallback(
- ({ set }) =>
- (steer: PendingSteer) => {
- const clientId = steer.clientSteerId ?? steer.steerId;
- setPendingCancelIds((prev) => (prev.includes(clientId) ? prev : [...prev, clientId]));
- if (steer.status === 'sending') {
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.filter((item) => item.steerId !== steer.steerId),
- );
- }
- },
- [conversationId, setPendingCancelIds],
+ const jotaiStore = useStore();
+ const markOptimisticCancel = useCallback(
+ (steer: PendingSteer) => {
+ const clientId = steer.clientSteerId ?? steer.steerId;
+ setPendingCancelIds((prev) => (prev.includes(clientId) ? prev : [...prev, clientId]));
+ if (steer.status === 'sending') {
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ prev.filter((item) => item.steerId !== steer.steerId),
+ );
+ }
+ },
+ [conversationId, setPendingCancelIds, jotaiStore],
);
const clearOptimisticCancel = useCallback(
(steer: PendingSteer) => {
diff --git a/client/src/hooks/Chat/useSteerConvert.ts b/client/src/hooks/Chat/useSteerConvert.ts
index f5c0ccbf06..a3bcfc26eb 100644
--- a/client/src/hooks/Chat/useSteerConvert.ts
+++ b/client/src/hooks/Chat/useSteerConvert.ts
@@ -1,7 +1,11 @@
import { useCallback, useRef } from 'react';
import { v4 } from 'uuid';
import { useStore } from 'jotai';
-import { useRecoilCallback } from 'recoil';
+import {
+ pendingSteersByConvoId,
+ appliedSteerIdsByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '@librechat/chat/react';
import type { TPendingSteer } from 'librechat-data-provider';
import type { QueuedMessage, QueuedMessageOrigin } from '~/hooks/Chat/queue';
import type { GenerationProtocolVersion } from '~/data-provider';
@@ -19,7 +23,6 @@ import {
import { fetchStreamStatus, getGenerationProtocolVersion } from '~/data-provider';
import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';
import { useFileMapContext } from '~/Providers';
-import store from '~/store';
/** A server-reported steer, or a local one that carries its own client-only
* context (quotes / skill picks) because its chip may already be gone. */
@@ -69,184 +72,176 @@ export default function useSteerConvert() {
const fileMap = useFileMapContext();
const fileMapRef = useRef(fileMap);
fileMapRef.current = fileMap;
- const convert = useRecoilCallback(
- ({ snapshot, set }) =>
- (
- conversationId: string,
- steers: ConvertibleSteer[],
- generationProtocolVersion?: GenerationProtocolVersion,
- allowPreviouslyConvertedIds: readonly string[] = [],
- bindRecoverySource?: boolean,
- needsExplicitSend?: boolean,
- ) => {
- if (steers.length === 0) {
- return;
- }
- const negotiatedVersion =
- generationProtocolVersion ??
- snapshot
- .getLoadable(store.activeGenerationProtocolVersionByConvoId(conversationId))
- .getValue();
- const shouldBindRecoverySource = bindRecoverySource ?? negotiatedVersion === 2;
- // Restore quotes/skill picks from the local chip (matched by id)
- // before the chips are dropped below: the chip is the only carrier of
- // skill picks, and of quotes accepted by an older server whose queue
- // items did not persist them yet.
- const localChips = snapshot
- .getLoadable(store.pendingSteersByConvoId(conversationId))
- .getValue();
- const chipById = new Map(localChips.map((chip) => [chip.steerId, chip]));
- const localChipFor = (steer: ConvertibleSteer) =>
- chipById.get(steer.steerId) ??
- (steer.clientSteerId ? chipById.get(steer.clientSteerId) : undefined);
- const steerIds = new Set(
- steers.flatMap((steer) =>
- steer.clientSteerId ? [steer.steerId, steer.clientSteerId] : [steer.steerId],
- ),
- );
- // Steers already settled (applied on the server OR converted here on an
- // earlier delivery) must not re-enter the queue. Read BEFORE the append
- // below so a first-time conversion still queues, but a redelivery whose
- // item was already DRAINED out of the queue is a no-op: without this,
- // the queue-only dedup below misses a message the run-end drain already
- // submitted and re-mints it as a stranded queued chip.
- const settledSteerIds = new Set(
- snapshot.getLoadable(store.appliedSteerIdsByConvoId(conversationId)).getValue(),
- );
- const allowedRedeliveries = new Set(allowPreviouslyConvertedIds);
- set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, [...steerIds]),
- );
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.filter((steer) => !steerIds.has(steer.steerId)),
- );
- jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) => {
- /** A legacy status read is destructive: if a v2 live-final path
- * already created a receipt-bound item before the claim reached an
- * old replica, that source no longer exists. Downgrade the existing
- * item in place to an ordinary local follow-up. */
- const existing: QueuedMessage[] = shouldBindRecoverySource
- ? prev
- : prev.map((item) => {
- const matchesClaimedSource =
- (item.recoverySteerId != null && steerIds.has(item.recoverySteerId)) ||
- (item.recoveryClientSteerId != null && steerIds.has(item.recoveryClientSteerId));
- if (
- !matchesClaimedSource ||
- (item.recoverySteerId != null &&
- jotaiStore.get(recoveryDispositionsFamily(conversationId))[
- item.recoverySteerId
- ] != null)
- ) {
- return item;
- }
- const {
- clientRequestId: _clientRequestId,
- recoverySteerId: _recoverySteerId,
- recoveryClientSteerId: _recoveryClientSteerId,
- ...ordinary
- } = item;
- return ordinary;
- });
- const fresh = steers
- .filter(
- (steer) =>
- canRestoreRecovery(jotaiStore.get(recoveryDispositionsFamily(conversationId)), {
- recoverySteerId: steer.steerId,
- }) &&
- (allowedRedeliveries.has(steer.steerId) ||
- (!settledSteerIds.has(steer.steerId) &&
- (steer.clientSteerId == null || !settledSteerIds.has(steer.clientSteerId)))),
- )
- .map((steer): { item: QueuedMessage; queuedOrigin?: QueuedMessageOrigin } => {
- const local = localChipFor(steer);
- const source = local ?? steer;
- const queuedOrigin = source.queuedOrigin;
- const files = hydrateFileDeliveryMetadata(
- queuedOrigin?.item.files ?? steer.files,
- local?.files,
- fileMapRef.current,
- );
- const held =
- jotaiStore.get(recoveryDispositionsFamily(conversationId))[steer.steerId] != null;
- const recoveryFields =
- shouldBindRecoverySource || held
- ? {
- // One UUID is stable for this queued attempt and all of
- // its POST retries. A later failed generation re-converts
- // the durable source and receives a new key, so the old
- // started idempotency tombstone cannot make it unsendable.
- clientRequestId: v4(),
- recoverySteerId: steer.steerId,
- ...(steer.clientSteerId && { recoveryClientSteerId: steer.clientSteerId }),
- }
- : {};
- const explicitSend = needsExplicitSend === true ? { needsExplicitSend: true } : {};
- const item =
- queuedOrigin != null
- ? {
- ...queuedOrigin.item,
- ...recoveryFields,
- ...explicitSend,
- ...(files && { files }),
- }
- : ({
- id: steer.steerId,
- text: steer.text,
- createdAt: steer.createdAt ?? Date.now(),
- ...recoveryFields,
- ...explicitSend,
- ...(files && files.length > 0 && { files }),
- // The chip is the usual source, but a reclaimed steer may
- // have lost its chip to a competing cancel mid-round-trip.
- ...carriedSteerContext(source),
- } satisfies QueuedMessage);
- return {
- item,
- queuedOrigin: queuedOrigin != null ? { ...queuedOrigin, item } : undefined,
- };
- })
- .filter(
- ({ item }) =>
- !existing.some(
- (queued) =>
- queued.id === item.id ||
- (item.recoverySteerId != null &&
- queued.recoverySteerId === item.recoverySteerId),
- ),
- );
- if (fresh.length === 0) {
- return existing;
- }
- // Each new item is placed chronologically (a steer accepted BEFORE
- // the user queued a later follow-up must drain first) EXCEPT explicit
- // front-inserts ("Interrupt & send"), whose urgency outranks age.
- //
- // Placed rather than sorted: the queue can be reordered by hand from
- // the rail, and sorting the whole list would quietly restore the order
- // the messages were written in, changing which one sends next.
- let merged: QueuedMessage[] = [...existing];
- const ordinary = fresh
- .filter(({ queuedOrigin }) => queuedOrigin == null)
- .map(({ item }) => item)
- .sort((a, b) => a.createdAt - b.createdAt);
- for (const item of ordinary) {
- const at = merged.findIndex(
- (queued) => queued.priority !== true && queued.createdAt > item.createdAt,
+ const convert = useCallback(
+ (
+ conversationId: string,
+ steers: ConvertibleSteer[],
+ generationProtocolVersion?: GenerationProtocolVersion,
+ allowPreviouslyConvertedIds: readonly string[] = [],
+ bindRecoverySource?: boolean,
+ needsExplicitSend?: boolean,
+ ) => {
+ if (steers.length === 0) {
+ return;
+ }
+ const negotiatedVersion =
+ generationProtocolVersion ??
+ jotaiStore.get(activeGenerationProtocolVersionByConvoId(conversationId));
+ const shouldBindRecoverySource = bindRecoverySource ?? negotiatedVersion === 2;
+ // Restore quotes/skill picks from the local chip (matched by id)
+ // before the chips are dropped below: the chip is the only carrier of
+ // skill picks, and of quotes accepted by an older server whose queue
+ // items did not persist them yet.
+ const localChips = jotaiStore.get(pendingSteersByConvoId(conversationId));
+ const chipById = new Map(localChips.map((chip) => [chip.steerId, chip]));
+ const localChipFor = (steer: ConvertibleSteer) =>
+ chipById.get(steer.steerId) ??
+ (steer.clientSteerId ? chipById.get(steer.clientSteerId) : undefined);
+ const steerIds = new Set(
+ steers.flatMap((steer) =>
+ steer.clientSteerId ? [steer.steerId, steer.clientSteerId] : [steer.steerId],
+ ),
+ );
+ // Steers already settled (applied on the server OR converted here on an
+ // earlier delivery) must not re-enter the queue. Read BEFORE the append
+ // below so a first-time conversion still queues, but a redelivery whose
+ // item was already DRAINED out of the queue is a no-op: without this,
+ // the queue-only dedup below misses a message the run-end drain already
+ // submitted and re-mints it as a stranded queued chip.
+ const settledSteerIds = new Set(jotaiStore.get(appliedSteerIdsByConvoId(conversationId)));
+ const allowedRedeliveries = new Set(allowPreviouslyConvertedIds);
+ jotaiStore.set(appliedSteerIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, [...steerIds]),
+ );
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ prev.filter((steer) => !steerIds.has(steer.steerId)),
+ );
+ jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) => {
+ /** A legacy status read is destructive: if a v2 live-final path
+ * already created a receipt-bound item before the claim reached an
+ * old replica, that source no longer exists. Downgrade the existing
+ * item in place to an ordinary local follow-up. */
+ const existing: QueuedMessage[] = shouldBindRecoverySource
+ ? prev
+ : prev.map((item) => {
+ const matchesClaimedSource =
+ (item.recoverySteerId != null && steerIds.has(item.recoverySteerId)) ||
+ (item.recoveryClientSteerId != null && steerIds.has(item.recoveryClientSteerId));
+ if (
+ !matchesClaimedSource ||
+ (item.recoverySteerId != null &&
+ jotaiStore.get(recoveryDispositionsFamily(conversationId))[
+ item.recoverySteerId
+ ] != null)
+ ) {
+ return item;
+ }
+ const {
+ clientRequestId: _clientRequestId,
+ recoverySteerId: _recoverySteerId,
+ recoveryClientSteerId: _recoveryClientSteerId,
+ ...ordinary
+ } = item;
+ return ordinary;
+ });
+ const fresh = steers
+ .filter(
+ (steer) =>
+ canRestoreRecovery(jotaiStore.get(recoveryDispositionsFamily(conversationId)), {
+ recoverySteerId: steer.steerId,
+ }) &&
+ (allowedRedeliveries.has(steer.steerId) ||
+ (!settledSteerIds.has(steer.steerId) &&
+ (steer.clientSteerId == null || !settledSteerIds.has(steer.clientSteerId)))),
+ )
+ .map((steer): { item: QueuedMessage; queuedOrigin?: QueuedMessageOrigin } => {
+ const local = localChipFor(steer);
+ const source = local ?? steer;
+ const queuedOrigin = source.queuedOrigin;
+ const files = hydrateFileDeliveryMetadata(
+ queuedOrigin?.item.files ?? steer.files,
+ local?.files,
+ fileMapRef.current,
);
- merged.splice(at === -1 ? merged.length : at, 0, item);
- }
- /** A steer that originated in this queue restores its exact
- * object/identity and captured position instead of being re-minted
- * under the server id at a merely chronological spot. */
- for (const { queuedOrigin } of fresh) {
- if (queuedOrigin != null) {
- merged = insertQueuedOrigin(merged, queuedOrigin);
- }
+ const held =
+ jotaiStore.get(recoveryDispositionsFamily(conversationId))[steer.steerId] != null;
+ const recoveryFields =
+ shouldBindRecoverySource || held
+ ? {
+ // One UUID is stable for this queued attempt and all of
+ // its POST retries. A later failed generation re-converts
+ // the durable source and receives a new key, so the old
+ // started idempotency tombstone cannot make it unsendable.
+ clientRequestId: v4(),
+ recoverySteerId: steer.steerId,
+ ...(steer.clientSteerId && { recoveryClientSteerId: steer.clientSteerId }),
+ }
+ : {};
+ const explicitSend = needsExplicitSend === true ? { needsExplicitSend: true } : {};
+ const item =
+ queuedOrigin != null
+ ? {
+ ...queuedOrigin.item,
+ ...recoveryFields,
+ ...explicitSend,
+ ...(files && { files }),
+ }
+ : ({
+ id: steer.steerId,
+ text: steer.text,
+ createdAt: steer.createdAt ?? Date.now(),
+ ...recoveryFields,
+ ...explicitSend,
+ ...(files && files.length > 0 && { files }),
+ // The chip is the usual source, but a reclaimed steer may
+ // have lost its chip to a competing cancel mid-round-trip.
+ ...carriedSteerContext(source),
+ } satisfies QueuedMessage);
+ return {
+ item,
+ queuedOrigin: queuedOrigin != null ? { ...queuedOrigin, item } : undefined,
+ };
+ })
+ .filter(
+ ({ item }) =>
+ !existing.some(
+ (queued) =>
+ queued.id === item.id ||
+ (item.recoverySteerId != null && queued.recoverySteerId === item.recoverySteerId),
+ ),
+ );
+ if (fresh.length === 0) {
+ return existing;
+ }
+ // Each new item is placed chronologically (a steer accepted BEFORE
+ // the user queued a later follow-up must drain first) EXCEPT explicit
+ // front-inserts ("Interrupt & send"), whose urgency outranks age.
+ //
+ // Placed rather than sorted: the queue can be reordered by hand from
+ // the rail, and sorting the whole list would quietly restore the order
+ // the messages were written in, changing which one sends next.
+ let merged: QueuedMessage[] = [...existing];
+ const ordinary = fresh
+ .filter(({ queuedOrigin }) => queuedOrigin == null)
+ .map(({ item }) => item)
+ .sort((a, b) => a.createdAt - b.createdAt);
+ for (const item of ordinary) {
+ const at = merged.findIndex(
+ (queued) => queued.priority !== true && queued.createdAt > item.createdAt,
+ );
+ merged.splice(at === -1 ? merged.length : at, 0, item);
+ }
+ /** A steer that originated in this queue restores its exact
+ * object/identity and captured position instead of being re-minted
+ * under the server id at a merely chronological spot. */
+ for (const { queuedOrigin } of fresh) {
+ if (queuedOrigin != null) {
+ merged = insertQueuedOrigin(merged, queuedOrigin);
}
- return merged;
- });
- },
+ }
+ return merged;
+ });
+ },
[jotaiStore],
);
diff --git a/client/src/hooks/Chat/useSteerEscalate.ts b/client/src/hooks/Chat/useSteerEscalate.ts
index 4576829d11..c6758a063e 100644
--- a/client/src/hooks/Chat/useSteerEscalate.ts
+++ b/client/src/hooks/Chat/useSteerEscalate.ts
@@ -1,13 +1,16 @@
import { useCallback } from 'react';
-import { useSetAtom } from 'jotai';
import { useToastContext } from '@librechat/client';
-import { useRecoilValue, useRecoilCallback } from 'recoil';
+import { useSetAtom, useAtomValue, useStore } from 'jotai';
import { DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS } from 'librechat-data-provider';
+import {
+ escalatingSteerFamily,
+ pendingSteersByConvoId,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '@librechat/chat/react';
import { supportsGenerationProtocolV2, useArmSteerMutation } from '~/data-provider';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
-import { escalatingSteerFamily } from '~/store/steer';
import useLocalize from '~/hooks/useLocalize';
-import store from '~/store';
type ArmFailure = {
name?: string;
@@ -51,26 +54,26 @@ export default function useSteerEscalate(conversationId: string) {
const armConfirmTimeoutMs =
config.steerArmConfirmationTimeoutMs ?? DEFAULT_STEER_ARM_CONFIRMATION_TIMEOUT_MS;
const setEscalating = useSetAtom(escalatingSteerFamily(conversationId));
- const activeGenerationCreatedAt = useRecoilValue(
- store.activeGenerationCreatedAtByConvoId(conversationId),
+ const jotaiStore = useStore();
+ const activeGenerationCreatedAt = useAtomValue(
+ activeGenerationCreatedAtByConvoId(conversationId),
);
- const activeGenerationProtocolVersion = useRecoilValue(
- store.activeGenerationProtocolVersionByConvoId(conversationId),
+ const activeGenerationProtocolVersion = useAtomValue(
+ activeGenerationProtocolVersionByConvoId(conversationId),
);
/** Relabels the chip in place once the server confirms the durable arm:
* same steerId, same position, only the `preempt` flag flips. */
- const markSteerPreempt = useRecoilCallback(
- ({ set }) =>
- (steerId: string, revision: number) =>
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.map((item) =>
- item.steerId === steerId && revision >= (item.preemptRevision ?? 0)
- ? { ...item, preempt: true, preemptRevision: revision }
- : item,
- ),
+ const markSteerPreempt = useCallback(
+ (steerId: string, revision: number) =>
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ prev.map((item) =>
+ item.steerId === steerId && revision >= (item.preemptRevision ?? 0)
+ ? { ...item, preempt: true, preemptRevision: revision }
+ : item,
),
- [conversationId],
+ ),
+ [conversationId, jotaiStore],
);
return useCallback(
diff --git a/client/src/hooks/Chat/useSteerRecovery.ts b/client/src/hooks/Chat/useSteerRecovery.ts
index 167aa102e9..3ec1005d72 100644
--- a/client/src/hooks/Chat/useSteerRecovery.ts
+++ b/client/src/hooks/Chat/useSteerRecovery.ts
@@ -1,6 +1,7 @@
import { useCallback } from 'react';
import { useStore } from 'jotai';
import { useRecoilCallback } from 'recoil';
+import { pendingSteerCancelClientIdsFamily, pendingSteersByConvoId } from '@librechat/chat/react';
import type { Snapshot } from 'recoil';
import type { PendingSteer } from '~/hooks/Chat/queue';
import {
@@ -11,7 +12,6 @@ import {
import { useSteerMessageMutation, useCancelSteerMutation } from '~/data-provider';
import { useComposerRestoreHost } from '~/Providers/ComposerRestoreContext';
import { carriedSteerContext, isLegacyDeliveryUncertain } from '~/utils';
-import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
import { useSteerRehome } from '~/hooks/Chat/useSteerCancel';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import store from '~/store';
@@ -59,34 +59,32 @@ export default function useSteerRecovery(conversationId: string) {
[conversationId],
);
- const markStatus = useRecoilCallback(
- ({ set }) =>
- (steerId: string, status: PendingSteer['status']) => {
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.map((steer) => (steer.steerId === steerId ? { ...steer, status } : steer)),
- );
- },
- [conversationId],
+ const markStatus = useCallback(
+ (steerId: string, status: PendingSteer['status']) => {
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ prev.map((steer) => (steer.steerId === steerId ? { ...steer, status } : steer)),
+ );
+ },
+ [conversationId, jotaiStore],
);
- const markFailure = useRecoilCallback(
- ({ set }) =>
- (steerId: string, deliveryUncertain: boolean) => {
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.map((steer) => {
- if (steer.steerId !== steerId) {
- return steer;
- }
- const { deliveryUncertain: _deliveryUncertain, ...rest } = steer;
- return {
- ...rest,
- status: 'failed',
- ...(deliveryUncertain && { deliveryUncertain: true }),
- };
- }),
- );
- },
- [conversationId],
+ const markFailure = useCallback(
+ (steerId: string, deliveryUncertain: boolean) => {
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ prev.map((steer) => {
+ if (steer.steerId !== steerId) {
+ return steer;
+ }
+ const { deliveryUncertain: _deliveryUncertain, ...rest } = steer;
+ return {
+ ...rest,
+ status: 'failed',
+ ...(deliveryUncertain && { deliveryUncertain: true }),
+ };
+ }),
+ );
+ },
+ [conversationId, jotaiStore],
);
/**
@@ -98,16 +96,10 @@ export default function useSteerRecovery(conversationId: string) {
* @returns true when the caller must route the steer into the queue.
*/
const acknowledgeRetry = useRecoilCallback(
- (cbInterface) =>
+ ({ snapshot }) =>
(localId: string, steer: PendingSteer): boolean =>
- resolveAcknowledgedSteer(
- cbInterface,
- conversationId,
- localId,
- steer,
- isRunOver(cbInterface.snapshot),
- ),
- [conversationId, isRunOver],
+ resolveAcknowledgedSteer(jotaiStore, conversationId, localId, steer, isRunOver(snapshot)),
+ [conversationId, isRunOver, jotaiStore],
);
/** Routes a steer straight into the queue: reused for a retry that degrades
@@ -155,150 +147,148 @@ export default function useSteerRecovery(conversationId: string) {
[conversationId, convertSteersToQueued, rewakeDrain],
);
- const retry = useRecoilCallback(
- ({ snapshot, set }) =>
- (steerId: string) => {
- const steer = snapshot
- .getLoadable(store.pendingSteersByConvoId(conversationId))
- .getValue()
- .find((item) => item.steerId === steerId);
- if (!steer || isLegacyDeliveryUncertain(steer)) {
- return;
- }
- markStatus(steerId, 'sending');
- /* Resolved through the promise rather than through `mutate`'s
+ const retry = useCallback(
+ (steerId: string) => {
+ const steer = jotaiStore
+ .get(pendingSteersByConvoId(conversationId))
+ .find((item) => item.steerId === steerId);
+ if (!steer || isLegacyDeliveryUncertain(steer)) {
+ return;
+ }
+ markStatus(steerId, 'sending');
+ /* Resolved through the promise rather than through `mutate`'s
per-call callbacks, which react-query drops once the observer has no
listeners. This hook lives in the block that unmounts the moment the
run ends, which is exactly when a retry's ack tends to land: those
callbacks never ran, and the chip was left saying `sending` for the
rest of the conversation with the words neither sent nor queued. */
- /* `preempt` rides along: a chip that failed as an interrupt-steer has to
+ /* `preempt` rides along: a chip that failed as an interrupt-steer has to
retry AS one. Resent without it the words land at the run's next tool
step instead of sealing the stream, which is a different action than
the one the user asked for and the chip still claims to be. */
- /* The same identity fields the composer's retry sends. `clientSteerId`
+ /* The same identity fields the composer's retry sends. `clientSteerId`
is what the server dedupes a committed POST on, so an uncertain
transport cannot apply these words twice, and `generationCreatedAt`
pins the attempt to the generation the chip belongs to rather than
whichever turn now occupies the conversation-scoped stream id. */
- const clientSteerId = steer.clientSteerId ?? steerId;
- steerMessage({
- conversationId,
- clientSteerId,
- text: steer.text,
- files: steer.files,
- ...(steer.quotes != null && { quotes: steer.quotes }),
- ...(steer.generationCreatedAt != null && {
- generationCreatedAt: steer.generationCreatedAt,
- }),
- ...(steer.preempt === true && { preempt: true }),
- })
- .then((response) => {
- const acceptAck = () => {
- const { deliveryUncertain: _deliveryUncertain, ...resolvedSteer } = steer;
- const acknowledged: PendingSteer = {
- ...resolvedSteer,
- steerId: response.steerId,
- clientSteerId,
- status: 'pending',
- /* The server echoes what it actually armed: without the
+ const clientSteerId = steer.clientSteerId ?? steerId;
+ steerMessage({
+ conversationId,
+ clientSteerId,
+ text: steer.text,
+ files: steer.files,
+ ...(steer.quotes != null && { quotes: steer.quotes }),
+ ...(steer.generationCreatedAt != null && {
+ generationCreatedAt: steer.generationCreatedAt,
+ }),
+ ...(steer.preempt === true && { preempt: true }),
+ })
+ .then((response) => {
+ const acceptAck = () => {
+ const { deliveryUncertain: _deliveryUncertain, ...resolvedSteer } = steer;
+ const acknowledged: PendingSteer = {
+ ...resolvedSteer,
+ steerId: response.steerId,
+ clientSteerId,
+ status: 'pending',
+ /* The server echoes what it actually armed: without the
capability it queues the steer and reports `preempt: false`,
which relabels the chip rather than failing it. */
- preempt: response.preempt === true,
- };
- /* The resolver owns the decision: an ACK for a run that already
+ preempt: response.preempt === true,
+ };
+ /* The resolver owns the decision: an ACK for a run that already
ended, or for a generation since replaced, has no later SSE event
left to settle a `pending` chip, so the words go to the queue
instead of being stranded. */
- if (acknowledgeRetry(steerId, acknowledged)) {
- queueSteer(acknowledged);
- }
- };
- if (
- !jotaiStore
- .get(pendingSteerCancelClientIdsFamily(conversationId))
- .includes(clientSteerId)
- ) {
- acceptAck();
- return;
+ if (acknowledgeRetry(steerId, acknowledged)) {
+ queueSteer(acknowledged);
}
- /* The user cancelled while the retry POST was in flight. The
+ };
+ if (
+ !jotaiStore
+ .get(pendingSteerCancelClientIdsFamily(conversationId))
+ .includes(clientSteerId)
+ ) {
+ acceptAck();
+ return;
+ }
+ /* The user cancelled while the retry POST was in flight. The
composer settles this same race with a deferred cancel: clearing
the marker without one loses the words, and accepting the ACK
without one injects them after the user asked for them back. */
- void cancelSteer({
- conversationId,
- steerId: response.steerId,
- clientSteerId,
- ...(steer.generationCreatedAt != null && {
- generationCreatedAt: steer.generationCreatedAt,
- }),
- }).then(
- ({ removed }) => {
- jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
- ids.filter((id) => id !== clientSteerId),
- );
- if (removed !== true) {
- /* The server kept the steer: it is live and will still reach
+ void cancelSteer({
+ conversationId,
+ steerId: response.steerId,
+ clientSteerId,
+ ...(steer.generationCreatedAt != null && {
+ generationCreatedAt: steer.generationCreatedAt,
+ }),
+ }).then(
+ ({ removed }) => {
+ jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
+ ids.filter((id) => id !== clientSteerId),
+ );
+ if (removed !== true) {
+ /* The server kept the steer: it is live and will still reach
the agent. The chip the optimistic cancel hid comes back
through the ordinary acknowledgement, so it settles like
any other accepted retry. */
- acceptAck();
- return;
- }
- /* The cancel beat the retry's POST, so the words are off the
+ acceptAck();
+ return;
+ }
+ /* The cancel beat the retry's POST, so the words are off the
server: they come back through the same boundary as an
immediate cancel, whole, and queued for an explicit send
when the composer will not take them. */
- rehomeSteer({ ...steer, steerId: response.steerId });
- },
- () => {
- jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
- ids.filter((id) => id !== clientSteerId),
- );
- /* Unknown cancel outcome, but the retry POST was accepted:
- treat the steer as live rather than claiming it is gone. */
- acceptAck();
- },
- );
- })
- .catch((error: unknown) => {
- if (
- jotaiStore
- .get(pendingSteerCancelClientIdsFamily(conversationId))
- .includes(clientSteerId)
- ) {
+ rehomeSteer({ ...steer, steerId: response.steerId });
+ },
+ () => {
jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
ids.filter((id) => id !== clientSteerId),
);
- /* The optimistic cancel removed the sending chip, and every
+ /* Unknown cancel outcome, but the retry POST was accepted:
+ treat the steer as live rather than claiming it is gone. */
+ acceptAck();
+ },
+ );
+ })
+ .catch((error: unknown) => {
+ if (
+ jotaiStore
+ .get(pendingSteerCancelClientIdsFamily(conversationId))
+ .includes(clientSteerId)
+ ) {
+ jotaiStore.set(pendingSteerCancelClientIdsFamily(conversationId), (ids) =>
+ ids.filter((id) => id !== clientSteerId),
+ );
+ /* The optimistic cancel removed the sending chip, and every
path below settles by mapping chips that still exist: without
the chip back the words vanish, unsent and unqueued both. */
- set(store.pendingSteersByConvoId(conversationId), (prev) => [...prev, steer]);
- }
- const code = getSteerErrorCode(error);
- // The run ended, is paused, was replaced, or can't accept a steer
- // right now: none of that means the words are lost, just that a
- // queued follow-up is the only way left to send them. `RUN_REPLACED`
- // belongs here too, because the retry pins `generationCreatedAt` to
- // the chip's own generation: once a newer run owns the conversation
- // every retry earns that same 409 and the chip would be stuck failed
- // forever. Queueing is what the composer does with it, and unlike
- // the composer's normal-send fallback it cannot displace the
- // replacement run.
- if (
- code === 'NO_ACTIVE_RUN' ||
- code === 'RUN_PAUSED' ||
- code === 'RUN_REPLACED' ||
- code === 'STEER_UNSUPPORTED' ||
- code === 'STEER_QUEUE_FULL'
- ) {
- queueSteer(steer, false);
- return;
- }
- markFailure(steerId, !isDefiniteSteerRejection(error));
- });
- },
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) => [...prev, steer]);
+ }
+ const code = getSteerErrorCode(error);
+ // The run ended, is paused, was replaced, or can't accept a steer
+ // right now: none of that means the words are lost, just that a
+ // queued follow-up is the only way left to send them. `RUN_REPLACED`
+ // belongs here too, because the retry pins `generationCreatedAt` to
+ // the chip's own generation: once a newer run owns the conversation
+ // every retry earns that same 409 and the chip would be stuck failed
+ // forever. Queueing is what the composer does with it, and unlike
+ // the composer's normal-send fallback it cannot displace the
+ // replacement run.
+ if (
+ code === 'NO_ACTIVE_RUN' ||
+ code === 'RUN_PAUSED' ||
+ code === 'RUN_REPLACED' ||
+ code === 'STEER_UNSUPPORTED' ||
+ code === 'STEER_QUEUE_FULL'
+ ) {
+ queueSteer(steer, false);
+ return;
+ }
+ markFailure(steerId, !isDefiniteSteerRejection(error));
+ });
+ },
[
conversationId,
steerMessage,
@@ -313,19 +303,17 @@ export default function useSteerRecovery(conversationId: string) {
);
/** Move a failed steer into the queue: it sends when the reply finishes. */
- const sendAsNew = useRecoilCallback(
- ({ snapshot }) =>
- (steerId: string) => {
- const steer = snapshot
- .getLoadable(store.pendingSteersByConvoId(conversationId))
- .getValue()
- .find((item) => item.steerId === steerId);
- if (!steer || steer.deliveryUncertain === true) {
- return;
- }
- queueSteer(steer, false);
- },
- [conversationId, queueSteer],
+ const sendAsNew = useCallback(
+ (steerId: string) => {
+ const steer = jotaiStore
+ .get(pendingSteersByConvoId(conversationId))
+ .find((item) => item.steerId === steerId);
+ if (!steer || steer.deliveryUncertain === true) {
+ return;
+ }
+ queueSteer(steer, false);
+ },
+ [conversationId, queueSteer, jotaiStore],
);
return { retry, sendAsNew };
diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts
index 45a8088662..d214425527 100644
--- a/client/src/hooks/Chat/useSteering.ts
+++ b/client/src/hooks/Chat/useSteering.ts
@@ -1,6 +1,5 @@
import { useCallback, useMemo, useRef } from 'react';
import { useAtomValue } from 'jotai';
-import { useRecoilValue } from 'recoil';
import { hasLiveRunPause, selectLiveMessageState } from '@librechat/chat';
import {
Constants,
@@ -8,6 +7,12 @@ import {
isAssistantsEndpoint,
DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS,
} from 'librechat-data-provider';
+import {
+ revealedQueuedTurnFamily,
+ pendingSteersByConvoId,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '@librechat/chat/react';
import type { TMessage, TConversation, CodeEnvironmentMode } from 'librechat-data-provider';
import type { SubmitSteerOptions, QueuedMessageContext } from '@librechat/chat';
import type { QueuedMessageOrigin } from '~/hooks/Chat/queue';
@@ -20,7 +25,6 @@ import {
} from '~/components/Chat/Input/Composer/state';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import useCodeApprovalMode from '../Agents/useCodeApprovalMode';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import useQueuedTurnReceipts from './steering/receipts';
import useDuringRunActions from './steering/actions';
import { useLatestMessage } from '~/hooks/Messages';
@@ -32,7 +36,6 @@ import { carriedSteerContext } from '~/utils';
import useSteerChips from './steering/chips';
import useQueuedSend from './steering/send';
import useQueueRows from './steering/rows';
-import store from '~/store';
export type { DuringRunAction };
@@ -137,11 +140,9 @@ export default function useSteering({
* ordinary sends must not overtake the server-owned successor. */
const pendingReveal = useAtomValue(revealedQueuedTurnFamily(queueKey));
const revealPending = pendingReveal != null;
- const activeGenerationCreatedAt = useRecoilValue(
- store.activeGenerationCreatedAtByConvoId(queueKey),
- );
- const activeGenerationProtocolVersion = useRecoilValue(
- store.activeGenerationProtocolVersionByConvoId(queueKey),
+ const activeGenerationCreatedAt = useAtomValue(activeGenerationCreatedAtByConvoId(queueKey));
+ const activeGenerationProtocolVersion = useAtomValue(
+ activeGenerationProtocolVersionByConvoId(queueKey),
);
/** The start POST installs this epoch before any live mutation may be sent.
@@ -149,7 +150,7 @@ export default function useSteering({
* bounded interval submits degrade to the local queue and Stop/steer refuse. */
const canControlGeneration = activeGenerationCreatedAt != null;
const duringRunActive = enabled && (isSubmitting || revealPending) && !answerModeActive;
- const pendingSteers = useRecoilValue(store.pendingSteersByConvoId(queueKey));
+ const pendingSteers = useAtomValue(pendingSteersByConvoId(queueKey));
const rows = useQueueRows({
index,
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 5a0a70f25a..9ae21fbd3d 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -105,7 +105,6 @@ const mockQueryClient = {
const mockActiveRunAtom = { key: 'activeRun' };
const mockSubmissionAtom = { key: 'submission' };
-const mockPendingSteersAtom = { key: 'pendingSteers' };
/** The follow-up queue a restored submission lands back in. */
const queuedIn = (conversationId: string) =>
getDefaultStore().get(queuedMessagesByConvoId(conversationId));
@@ -122,18 +121,6 @@ const mockSeedSteerChips = jest.fn();
const mockSettleAppliedSteerParts = jest.fn();
const mockConvertLocalSteersToQueued = jest.fn();
const mockUpdateGenerationEpoch = jest.fn();
-let mockRecoilCallbackIndex = 0;
-const mockRecoilCallbacks = [
- mockResolveSteerChip,
- mockUpdateSteerChips,
- mockSeedSteerChips,
- mockSettleAppliedSteerParts,
- mockConvertLocalSteersToQueued,
- mockUpdateGenerationEpoch,
-];
-function mockUseRecoilCallback() {
- return mockRecoilCallbacks[mockRecoilCallbackIndex++ % mockRecoilCallbacks.length];
-}
const mockUseSetRecoilStateMock = jest.fn((atom: unknown) => {
if (atom === mockActiveRunAtom) {
return mockSetActiveRun;
@@ -174,9 +161,6 @@ jest.mock('@tanstack/react-query', () => ({
jest.mock('recoil', () => ({
...jest.requireActual('recoil'),
useSetRecoilState: mockUseSetRecoilState,
- // The hook's steer-chip/queue callbacks need a RecoilRoot; these tests render
- // bare, so return stable named spies in the hook's declaration order.
- useRecoilCallback: mockUseRecoilCallback,
}));
/** The run-end, interrupt-drain, abort-scroll and stop-button state are Jotai atoms; their pane
@@ -210,7 +194,6 @@ jest.mock('~/store', () => ({
default: {
activeRunFamily: jest.fn(() => mockActiveRunAtom),
submissionByIndex: jest.fn(() => mockSubmissionAtom),
- pendingSteersByConvoId: jest.fn(() => mockPendingSteersAtom),
},
}));
@@ -249,6 +232,22 @@ jest.mock('~/hooks/Chat/useSteerConvert', () => ({
default: () => mockConvertSteersToQueued,
}));
+/** The steer-chip/queue writers are swapped for stable named spies, so these tests
+ * assert what the hook hands them rather than the chip state they would write. */
+const mockSteerState = {
+ resolveSteerChip: mockResolveSteerChip,
+ updateSteerChips: mockUpdateSteerChips,
+ seedSteerChips: mockSeedSteerChips,
+ settleAppliedSteerParts: mockSettleAppliedSteerParts,
+ convertSteersToQueued: mockConvertSteersToQueued,
+ convertLocalSteersToQueued: mockConvertLocalSteersToQueued,
+ updateActiveGenerationCreatedAt: mockUpdateGenerationEpoch,
+};
+jest.mock('~/hooks/SSE/steer', () => ({
+ __esModule: true,
+ default: () => mockSteerState,
+}));
+
const mockErrorHandler = jest.fn();
const mockFinalHandler = jest.fn();
const mockCreatedHandler = jest.fn();
@@ -451,7 +450,6 @@ describe('useResumableSSE', () => {
mockConvertLocalSteersToQueued.mockClear();
mockUpdateGenerationEpoch.mockClear();
resetQueueFamilies();
- mockRecoilCallbackIndex = 0;
mockConvertSteersToQueued.mockClear();
mockFetchStreamStatus.mockReset();
mockFetchStreamStatus.mockResolvedValue({ active: false });
@@ -6057,18 +6055,17 @@ describe('useResumableSSE - sync response identity', () => {
/**
* `convertLocalSteersToQueued` (the `final` handler and the intentional-close
* `abort` listener both call it, alongside the two failure-terminal paths
- * covered above) is a thin `useRecoilCallback` wrapper: read the conversation's
+ * covered above) is a thin `useSteerState` callback: read the conversation's
* chips, run them through this selection, hand the result to `useSteerConvert`.
- * This file's `useRecoilCallback: () => jest.fn()` mock (see above, "the
- * hook's steer-chip/queue callbacks need a RecoilRoot; these tests render
- * bare") makes that wrapper, and every other recoil-callback in this hook
+ * This file's `~/hooks/SSE/steer` mock (see above, `mockSteerState`) makes that
+ * callback, and every other steer-state writer in this hook
* (`resolveSteerChip`, `seedSteerChips` included; neither has a direct test
* in this file either), inert: calling it from the `final`/`abort` source
* lines is invisible to `mockConvertSteersToQueued` assertions here, since the
* mock discards the real closure before it can ever call through. Covering
* the selection logic directly (this is the exact piece of logic finding 3
* was about: which statuses survive a run end) rather than faking a
- * RecoilRoot-backed integration around the rest of this large hook's mocks.
+ * store-backed integration around the rest of this large hook's mocks.
*
* The `statuses` parameter pins a second contract: the `final` handler and
* the two error/404 terminals call `convertLocalSteersToQueued` with no
diff --git a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
index 869956eced..e430f2ffcf 100644
--- a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
+++ b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
@@ -1,8 +1,13 @@
import { renderHook, act, waitFor } from '@testing-library/react';
import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { Provider as JotaiProvider, createStore, useAtomValue } from 'jotai';
import { Constants, ContentTypes, QueryKeys } from 'librechat-data-provider';
+import { Provider as JotaiProvider, createStore, useAtomValue, useSetAtom } from 'jotai';
+import {
+ revealedQueuedTurnFamily,
+ pendingSteersByConvoId,
+ activeGenerationCreatedAtByConvoId,
+} from '@librechat/chat/react';
import type { Agents, TMessage, TConversation, TSubmission } from 'librechat-data-provider';
import type { MutableSnapshot } from 'recoil';
import type { ReactNode } from 'react';
@@ -19,7 +24,6 @@ import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import { submissionStartFamily } from '~/store/generation';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import useResumeOnLoad from '../useResumeOnLoad';
import store from '~/store';
@@ -145,6 +149,10 @@ function renderUseResumeOnLoad({
if (detachedRun != null) {
jotaiStore.set(detachedRunByConvoId(conversationId), detachedRun);
}
+ jotaiStore.set(activeGenerationCreatedAtByConvoId(conversationId), attachedGenerationCreatedAt);
+ if (pendingSteers) {
+ jotaiStore.set(pendingSteersByConvoId(conversationId), pendingSteers);
+ }
seedJotai?.(jotaiStore);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -157,22 +165,13 @@ function renderUseResumeOnLoad({
snapshot.set(store.conversationByIndex(0), buildConversation(conversationId));
snapshot.set(store.submissionByIndex(0), submission);
snapshot.set(store.isSubmittingFamily(0), isSubmitting);
- snapshot.set(
- store.activeGenerationCreatedAtByConvoId(conversationId),
- attachedGenerationCreatedAt,
- );
- if (pendingSteers) {
- snapshot.set(store.pendingSteersByConvoId(conversationId), pendingSteers);
- }
};
const SubmissionProbe = () => {
const currentSubmission = useRecoilValue(store.submissionByIndex(0));
setSubmissionState = useSetRecoilState(store.submissionByIndex(0));
setIsSubmittingState = useSetRecoilState(store.isSubmittingFamily(0));
- setAttachedEpochState = useSetRecoilState(
- store.activeGenerationCreatedAtByConvoId(conversationId),
- );
+ setAttachedEpochState = useSetAtom(activeGenerationCreatedAtByConvoId(conversationId));
onSubmission?.(currentSubmission);
return null;
};
@@ -182,7 +181,7 @@ function renderUseResumeOnLoad({
return null;
};
const PendingSteersProbe = () => {
- const steers = useRecoilValue(store.pendingSteersByConvoId(conversationId));
+ const steers = useAtomValue(pendingSteersByConvoId(conversationId));
onPendingSteers?.(steers);
return null;
};
diff --git a/client/src/hooks/SSE/steer.ts b/client/src/hooks/SSE/steer.ts
index 36cf6ce7b2..e0fa2aa1fd 100644
--- a/client/src/hooks/SSE/steer.ts
+++ b/client/src/hooks/SSE/steer.ts
@@ -1,6 +1,12 @@
-import { useMemo, useRef } from 'react';
+import { useCallback, useMemo, useRef } from 'react';
import { useStore } from 'jotai';
-import { useRecoilCallback } from 'recoil';
+import {
+ pendingSteersByConvoId,
+ appliedSteerIdsByConvoId,
+ acceptedSteerClientIdsByConvoId,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from '@librechat/chat/react';
import {
seedPendingSteers,
settledSteerQuotes,
@@ -23,7 +29,6 @@ import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { useFileMapContext } from '~/Providers';
-import store from '~/store';
/**
* The one place the stream handlers write steer state: pending-steer chips,
@@ -49,117 +54,113 @@ export default function useSteerState() {
* 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 = useRecoilCallback(
- ({ snapshot, set }) =>
- (
- 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(
- snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue(),
- settledIds,
+ 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),
);
- if (droppedQuotes != null) {
- jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
- mergeRestagedQuotes(prev, droppedQuotes),
- );
- }
}
- const alreadyApplied = snapshot
- .getLoadable(store.appliedSteerIdsByConvoId(conversationId))
- .getValue();
- const firstApplication = settledIds.filter((id) => !alreadyApplied.includes(id));
- set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, settledIds),
- );
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- removePendingSteers(prev, settledIds),
- );
- jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) =>
- withoutRecoveredSteers(prev, settledIds),
- );
- return firstApplication;
- },
+ }
+ 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 = useRecoilCallback(
- ({ set }) =>
- (event: TSteerUpdatedEvent) => {
- const acceptedClientIds = acceptedClientSteerIds(event.steers);
- if (acceptedClientIds.length > 0) {
- set(store.acceptedSteerClientIdsByConvoId(event.conversationId), (prev) =>
- appendAppliedSteerIds(prev, acceptedClientIds),
- );
- }
- set(store.pendingSteersByConvoId(event.conversationId), (prev) =>
- updatePendingSteerLabels(prev, event.steers),
+ 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 = useRecoilCallback(
- ({ set }) =>
- (
- conversationId: string,
- steers: TPendingSteer[] | undefined,
- generationCreatedAt?: number,
- generationProtocolVersion: GenerationProtocolVersion = 1,
- ) => {
- const acceptedClientIds = acceptedClientSteerIds(steers);
- if (acceptedClientIds.length > 0) {
- set(store.acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, acceptedClientIds),
- );
- }
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- seedPendingSteers(prev, steers, {
- generationCreatedAt,
- generationProtocolVersion,
- storedFiles: fileMapRef.current,
- }),
+ 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 = useRecoilCallback(
- ({ snapshot, set }) =>
- (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,
- snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue(),
- );
- if (droppedQuotes.length > 0) {
- jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
- mergeRestagedQuotes(prev, droppedQuotes),
- );
- }
- set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, ids),
+ 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),
);
- set(store.pendingSteersByConvoId(conversationId), (prev) => removePendingSteers(prev, ids));
- },
+ }
+ jotaiStore.set(appliedSteerIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, ids),
+ );
+ jotaiStore.set(pendingSteersByConvoId(conversationId), (prev) =>
+ removePendingSteers(prev, ids),
+ );
+ },
[jotaiStore],
);
@@ -171,78 +172,74 @@ export default function useSteerState() {
* 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 = useRecoilCallback(
- ({ snapshot }) =>
- (
- conversationId: string,
- options?: {
- claimParked?: boolean;
- statuses?: readonly PendingSteer['status'][];
- excludeSteerIds?: Iterable<string>;
- generationProtocolVersion?: GenerationProtocolVersion;
- },
- ) => {
- const chips = snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue();
- const generationProtocolVersion =
- options?.generationProtocolVersion ??
- snapshot
- .getLoadable(store.activeGenerationProtocolVersionByConvoId(conversationId))
- .getValue();
- 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,
- });
- }
+ const convertLocalSteersToQueued = useCallback(
+ (
+ conversationId: string,
+ options?: {
+ claimParked?: boolean;
+ statuses?: readonly PendingSteer['status'][];
+ excludeSteerIds?: Iterable<string>;
+ generationProtocolVersion?: GenerationProtocolVersion;
},
- [convertSteersToQueued],
+ ) => {
+ 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 = useRecoilCallback(
- ({ snapshot, set }) =>
- (
- conversationId: string,
- next: number | null,
- expected?: number,
- generationProtocolVersion: GenerationProtocolVersion = 1,
- ): boolean => {
- const state = store.activeGenerationCreatedAtByConvoId(conversationId);
- if (expected != null && snapshot.getLoadable(state).getValue() !== expected) {
- return false;
- }
- set(state, next);
- set(
- store.activeGenerationProtocolVersionByConvoId(conversationId),
- next == null ? 1 : generationProtocolVersion,
- );
- return true;
- },
- [],
+ 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(
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 261a74c607..5042cbb391 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -3,6 +3,7 @@ import { v4 } from 'uuid';
import { useSetRecoilState } from 'recoil';
import { useStore, useSetAtom } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
+import { liveAppliedSteerIdsAtom } from '@librechat/chat/react';
import { ABORT_SWEEP_STATUSES, selectLocalSteersForQueue } from '@librechat/chat';
import {
Constants,
@@ -106,7 +107,6 @@ import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { abortScrollFamily, showStopButtonByIndex } from '~/store/generation';
import { withSubmittedCodeDecision } from '~/hooks/Agents/codeDecision';
import { useChatTransport } from '~/Providers/ChatTransportContext';
-import { liveAppliedSteerIdsAtom } from '~/store/steer';
import { reopenTermsOnRefusal } from '~/utils/terms';
import { useAuthContext } from '~/hooks/AuthContext';
import { fetchConvoSnapshot } from '~/utils/convos';
diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/client/src/hooks/SSE/useResumeOnLoad.ts
index 64d166cd66..78b518794b 100644
--- a/client/src/hooks/SSE/useResumeOnLoad.ts
+++ b/client/src/hooks/SSE/useResumeOnLoad.ts
@@ -1,7 +1,11 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { useStore, useAtom, useSetAtom } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
import { useSetRecoilState, useRecoilValue } from 'recoil';
+import { useStore, useAtom, useSetAtom, useAtomValue } from 'jotai';
+import {
+ revealedQueuedTurnFamily,
+ activeGenerationCreatedAtByConvoId,
+} from '@librechat/chat/react';
import {
Constants,
QueryKeys,
@@ -42,7 +46,6 @@ import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import { submissionStartFamily } from '~/store/generation';
-import { revealedQueuedTurnFamily } from '~/store/steer';
import { resumeRequestsAtom } from '~/hooks/Chat/resume';
import useSteerState from './steer';
import store from '~/store';
@@ -299,8 +302,8 @@ export default function useResumeOnLoad(
const setSubmissionStart = useSetAtom(submissionStartFamily(runIndex));
const currentSubmission = useRecoilValue(store.submissionByIndex(runIndex));
const isSubmitting = useRecoilValue(store.isSubmittingFamily(runIndex));
- const attachedGenerationCreatedAt = useRecoilValue(
- store.activeGenerationCreatedAtByConvoId(conversationId ?? ''),
+ const attachedGenerationCreatedAt = useAtomValue(
+ activeGenerationCreatedAtByConvoId(conversationId ?? ''),
);
const currentConversation = useRecoilValue(store.conversationByIndex(runIndex));
const endpoint = currentConversation?.endpoint;
diff --git a/client/src/store/families.ts b/client/src/store/families.ts
index 32eb075f19..1a5a93ac39 100644
--- a/client/src/store/families.ts
+++ b/client/src/store/families.ts
@@ -12,9 +12,7 @@ import {
useRecoilCallback,
} from 'recoil';
import type { EModelEndpoint, TConversation, TSubmission, TPreset } from 'librechat-data-provider';
-import type { GenerationProtocolVersion } from '~/data-provider/SSE/protocol';
import type { TOptionSettings, ExtendedFile } from '~/common';
-import type { PendingSteer } from '~/hooks/Chat/queue';
import {
clearModelForNonEphemeralAgent,
createChatSearchParams,
@@ -253,54 +251,6 @@ const pendingComposerTextByConvoId = atomFamily<string | undefined, string>({
default: undefined,
});
-/**
- * Per-conversation steers awaiting injection. Reconciled against the server:
- * `on_steer_applied` removes its chip; `sync`/`resumeState.pendingSteers`
- * replaces the list on reconnect; run-end reports convert leftovers into
- * `queuedMessagesByConvoId` entries.
- */
-const pendingSteersByConvoId = atomFamily<PendingSteer[], string>({
- key: 'pendingSteersByConvoId',
- default: [],
-});
-
-/**
- * Server steer ids whose `on_steer_applied` event already landed. The 202 ACK
- * and the SSE ride different connections, so the applied event can arrive
- * FIRST — the ACK handler checks this set and drops its local chip instead of
- * minting a `pending` chip whose only removal event has already passed. A late
- * ACK can land after the run's final event, so the set is capped
- * (`appendAppliedSteerIds`), never cleared.
- */
-const appliedSteerIdsByConvoId = atomFamily<string[], string>({
- key: 'appliedSteerIdsByConvoId',
- default: [],
-});
-
-/** Optimistic ids the server has proven accepted via ACK or SYNC. Separate
- * from `appliedSteerIdsByConvoId`: accepted-but-still-queued steers must not
- * be suppressed by terminal conversion, but a late POST error must not
- * resurrect them after Cancel/Edit/Convert removes the visible chip. */
-const acceptedSteerClientIdsByConvoId = atomFamily<string[], string>({
- key: 'acceptedSteerClientIdsByConvoId',
- default: [],
-});
-
-/** Server generation epoch currently attached for each conversation. Stream
- * ids are conversation-scoped and reused by later turns; every mutation that
- * can affect a live run carries this value as an optimistic concurrency fence. */
-const activeGenerationCreatedAtByConvoId = atomFamily<number | null, string>({
- key: 'activeGenerationCreatedAtByConvoId',
- default: null,
-});
-
-/** Negotiated behavior contract for the active generation. Missing echoes are
- * legacy by definition, so the safe default is always v1. */
-const activeGenerationProtocolVersionByConvoId = atomFamily<GenerationProtocolVersion, string>({
- key: 'activeGenerationProtocolVersionByConvoId',
- default: 1,
-});
-
const globalAudioURLFamily = atomFamily<string | null, string | number | null>({
key: 'globalAudioURLByIndex',
default: null,
@@ -458,10 +408,5 @@ export default {
useClearSubmissionState,
showPromptsPopoverFamily,
pendingComposerTextByConvoId,
- pendingSteersByConvoId,
- appliedSteerIdsByConvoId,
- acceptedSteerClientIdsByConvoId,
- activeGenerationCreatedAtByConvoId,
- activeGenerationProtocolVersionByConvoId,
updateConversationSelector,
};
diff --git a/client/src/store/steer.ts b/client/src/store/steer.ts
deleted file mode 100644
index 380a457f78..0000000000
--- a/client/src/store/steer.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { atom } from 'jotai';
-import { atomFamily } from 'jotai/utils';
-import type { TMessage } from 'librechat-data-provider';
-
-/**
- * Set synchronously before a bubble's arm request and cleared on settlement.
- * Purely a UX gate: with the atomic in-place arm, a double-arm is harmless
- * server-side (the run seals once and drains the whole queue in order), but
- * every escalation control advertises "one interrupt at a time" by disabling,
- * and the chip-derived check cannot see an arm until its response lands.
- */
-export const escalatingSteerFamily = atomFamily((_conversationId: string) => atom<boolean>(false));
-
-/** A server-owned follow-up and its admission handoff, keyed by conversation.
- * The drawing never enters history. Its guard survives the drawing until a
- * successor generation owns the pane or terminal evidence settles the turn. */
-export type RevealedQueuedTurn = {
- clientRequestId: string;
- /** The drawing follows this response only while history has no successor. */
- parentMessageId: string;
- /** Completion boundary, advanced as later queued turns are admitted. */
- generationCreatedAt?: number;
- /** Immutable queue lineage, independent of the display/completion boundary. */
- queueParentMessageId?: string;
- queuePredecessorCreatedAt?: number;
- text: string;
- files?: TMessage['files'];
- quotes?: string[];
- manualSkills?: string[];
- revealedAt: string;
-};
-
-export const revealedQueuedTurnFamily = atomFamily((_conversationId: string) =>
- atom<RevealedQueuedTurn | null>(null),
-);
-
-/** Client ids cancelled before the steer POST receives its authoritative id. */
-export const pendingSteerCancelClientIdsFamily = atomFamily((_conversationId: string) =>
- atom<string[]>([]),
-);
-
-/**
- * Steer ids whose applied event landed in THIS session, pending their one-shot
- * receipt draw-in. `SteerPart` consumes its id on mount so the animation plays
- * exactly once, at the live chip to inline hand-off, never on reload, share, or
- * a later revisit. Global rather than per-conversation: steer ids are unique,
- * and the applied part renders in surfaces that don't know their convo id. */
-export const liveAppliedSteerIdsAtom = atom<string[]>([]);
-
-/** Membership view of `liveAppliedSteerIdsAtom` so each `SteerPart` subscribes to
- * its own id only: stamping/consuming one steer re-renders that part, not
- * every mounted historical part in a long conversation. */
-export const liveAppliedSteerFamily = atomFamily((steerId: string) =>
- atom((get) => steerId.length > 0 && get(liveAppliedSteerIdsAtom).includes(steerId)),
-);
diff --git a/package-lock.json b/package-lock.json
index cbd99b0d50..6563afa0b9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -41376,6 +41376,7 @@
"babel-plugin-replace-ts-export-assignment": "^0.0.2",
"jest": "^30.2.0",
"jest-environment-jsdom": "^30.2.0",
+ "jotai": "^2.12.5",
"librechat-data-provider": "*",
"lucide": "^0.528.0",
"lucide-react": "^0.528.0",
@@ -41387,6 +41388,7 @@
},
"peerDependencies": {
"@librechat/client": "*",
+ "jotai": "^2.12.5",
"librechat-data-provider": "*",
"lucide": "^0.528.0",
"lucide-react": "^0.528.0",
diff --git a/packages/chat/package.json b/packages/chat/package.json
index 7a42df0e1a..ceb9e033e2 100644
--- a/packages/chat/package.json
+++ b/packages/chat/package.json
@@ -59,6 +59,7 @@
},
"peerDependencies": {
"@librechat/client": "*",
+ "jotai": "^2.12.5",
"librechat-data-provider": "*",
"lucide": "^0.528.0",
"lucide-react": "^0.528.0",
@@ -79,6 +80,7 @@
"babel-plugin-replace-ts-export-assignment": "^0.0.2",
"jest": "^30.2.0",
"jest-environment-jsdom": "^30.2.0",
+ "jotai": "^2.12.5",
"librechat-data-provider": "*",
"lucide": "^0.528.0",
"lucide-react": "^0.528.0",
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index 81aa78c4e9..519f454981 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -13,3 +13,17 @@ export type {
MessagePartsMarkdownProps,
MessagePartsUserTextPreferences,
} from './react/host';
+export {
+ resetSteerFamilies,
+ escalatingSteerFamily,
+ pendingSteersByConvoId,
+ liveAppliedSteerFamily,
+ liveAppliedSteerIdsAtom,
+ appliedSteerIdsByConvoId,
+ revealedQueuedTurnFamily,
+ acceptedSteerClientIdsByConvoId,
+ pendingSteerCancelClientIdsFamily,
+ activeGenerationCreatedAtByConvoId,
+ activeGenerationProtocolVersionByConvoId,
+} from './react/steer/atoms';
+export type { RevealedQueuedTurn } from './react/steer/atoms';
diff --git a/packages/chat/src/react/steer/atoms.ts b/packages/chat/src/react/steer/atoms.ts
new file mode 100644
index 0000000000..7bd750b3c7
--- /dev/null
+++ b/packages/chat/src/react/steer/atoms.ts
@@ -0,0 +1,131 @@
+import { atom } from 'jotai';
+import { atomFamily } from 'jotai/utils';
+import type { TMessage } from 'librechat-data-provider';
+import type { Atom, PrimitiveAtom } from 'jotai';
+import type { GenerationProtocolVersion } from '../../core/protocol';
+import type { PendingSteer } from '../../core/steer/types';
+
+/** One atom per key, created on first read; `getParams`/`remove` let tests and teardown drop them. */
+type Family<Value, AtomType extends Atom<Value> = PrimitiveAtom<Value>> = ReturnType<
+ typeof atomFamily<string, AtomType>
+>;
+
+/**
+ * Set synchronously before a bubble's arm request and cleared on settlement.
+ * Purely a UX gate: with the atomic in-place arm, a double-arm is harmless
+ * server-side (the run seals once and drains the whole queue in order), but
+ * every escalation control advertises "one interrupt at a time" by disabling,
+ * and the chip-derived check cannot see an arm until its response lands.
+ */
+export const escalatingSteerFamily: Family<boolean> = atomFamily((_conversationId: string) =>
+ atom<boolean>(false),
+);
+
+/** A server-owned follow-up and its admission handoff, keyed by conversation.
+ * The drawing never enters history. Its guard survives the drawing until a
+ * successor generation owns the pane or terminal evidence settles the turn. */
+export type RevealedQueuedTurn = {
+ clientRequestId: string;
+ /** The drawing follows this response only while history has no successor. */
+ parentMessageId: string;
+ /** Completion boundary, advanced as later queued turns are admitted. */
+ generationCreatedAt?: number;
+ /** Immutable queue lineage, independent of the display/completion boundary. */
+ queueParentMessageId?: string;
+ queuePredecessorCreatedAt?: number;
+ text: string;
+ files?: TMessage['files'];
+ quotes?: string[];
+ manualSkills?: string[];
+ revealedAt: string;
+};
+
+export const revealedQueuedTurnFamily: Family<RevealedQueuedTurn | null> = atomFamily(
+ (_conversationId: string) => atom<RevealedQueuedTurn | null>(null),
+);
+
+/** Client ids cancelled before the steer POST receives its authoritative id. */
+export const pendingSteerCancelClientIdsFamily: Family<string[]> = atomFamily(
+ (_conversationId: string) => atom<string[]>([]),
+);
+
+/**
+ * Steer ids whose applied event landed in THIS session, pending their one-shot
+ * receipt draw-in. `SteerPart` consumes its id on mount so the animation plays
+ * exactly once, at the live chip to inline hand-off, never on reload, share, or
+ * a later revisit. Global rather than per-conversation: steer ids are unique,
+ * and the applied part renders in surfaces that don't know their convo id. */
+export const liveAppliedSteerIdsAtom: PrimitiveAtom<string[]> = atom<string[]>([]);
+
+/** Membership view of `liveAppliedSteerIdsAtom` so each `SteerPart` subscribes to
+ * its own id only: stamping/consuming one steer re-renders that part, not
+ * every mounted historical part in a long conversation. */
+export const liveAppliedSteerFamily: Family<boolean, Atom<boolean>> = atomFamily(
+ (steerId: string) =>
+ atom((get) => steerId.length > 0 && get(liveAppliedSteerIdsAtom).includes(steerId)),
+);
+
+/**
+ * Per-conversation steers awaiting injection. Reconciled against the server:
+ * `on_steer_applied` removes its chip; `sync`/`resumeState.pendingSteers`
+ * replaces the list on reconnect; run-end reports convert leftovers into
+ * `queuedMessagesByConvoId` entries.
+ */
+export const pendingSteersByConvoId: Family<PendingSteer[]> = atomFamily(
+ (_conversationId: string) => atom<PendingSteer[]>([]),
+);
+
+/**
+ * Server steer ids whose `on_steer_applied` event already landed. The 202 ACK
+ * and the SSE ride different connections, so the applied event can arrive
+ * FIRST; the ACK handler checks this set and drops its local chip instead of
+ * minting a `pending` chip whose only removal event has already passed. A late
+ * ACK can land after the run's final event, so the set is capped
+ * (`appendAppliedSteerIds`), never cleared.
+ */
+export const appliedSteerIdsByConvoId: Family<string[]> = atomFamily((_conversationId: string) =>
+ atom<string[]>([]),
+);
+
+/** Optimistic ids the server has proven accepted via ACK or SYNC. Separate
+ * from `appliedSteerIdsByConvoId`: accepted-but-still-queued steers must not
+ * be suppressed by terminal conversion, but a late POST error must not
+ * resurrect them after Cancel/Edit/Convert removes the visible chip. */
+export const acceptedSteerClientIdsByConvoId: Family<string[]> = atomFamily(
+ (_conversationId: string) => atom<string[]>([]),
+);
+
+/** Server generation epoch currently attached for each conversation. Stream
+ * ids are conversation-scoped and reused by later turns; every mutation that
+ * can affect a live run carries this value as an optimistic concurrency fence. */
+export const activeGenerationCreatedAtByConvoId: Family<number | null> = atomFamily(
+ (_conversationId: string) => atom<number | null>(null),
+);
+
+/** Negotiated behavior contract for the active generation. Missing echoes are
+ * legacy by definition, so the safe default is always v1. */
+export const activeGenerationProtocolVersionByConvoId: Family<GenerationProtocolVersion> =
+ atomFamily((_conversationId: string) => atom<GenerationProtocolVersion>(1));
+
+const clearFamily = <Param>(family: {
+ getParams(): Iterable<Param>;
+ remove(param: Param): void;
+}) => {
+ for (const param of [...family.getParams()]) {
+ family.remove(param);
+ }
+};
+
+/** Drops every per-conversation steer atom, so the next read of any key starts from its
+ * default. Isolates tests that share the default store. */
+export function resetSteerFamilies(): void {
+ clearFamily(escalatingSteerFamily);
+ clearFamily(revealedQueuedTurnFamily);
+ clearFamily(pendingSteerCancelClientIdsFamily);
+ clearFamily(liveAppliedSteerFamily);
+ clearFamily(pendingSteersByConvoId);
+ clearFamily(appliedSteerIdsByConvoId);
+ clearFamily(acceptedSteerClientIdsByConvoId);
+ clearFamily(activeGenerationCreatedAtByConvoId);
+ clearFamily(activeGenerationProtocolVersionByConvoId);
+}