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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🛰️ refactor: Move the Pane Submission to Jotai in the Chat Package (#17159)
Marco Beretta4f4bda9ebee8
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsxindex 21c7513da3..93506c6d69 100644--- a/client/src/components/Chat/ChatView.tsx+++ b/client/src/components/Chat/ChatView.tsx@@ -4,8 +4,8 @@ import { useRecoilValue } from 'recoil';import { useForm } from 'react-hook-form';import { Spinner } from '@librechat/client';import { useParams } from 'react-router-dom';-import { useIsSubmitting } from '@librechat/chat/react';import { Constants, buildTree } from 'librechat-data-provider';+import { useIsSubmitting, submissionByIndex } from '@librechat/chat/react';import type { TChatProject } from 'librechat-data-provider';import type { ChatFormValues } from '~/common';import {@@ -68,7 +68,7 @@ function ChatView({}) {const { conversationId } = useParams();const localize = useLocalize();- const rootSubmission = useRecoilValue(store.submissionByIndex(index));+ const rootSubmission = useAtomValue(submissionByIndex(index));const isSubmitting = useIsSubmitting(index);const { saveDrafts } = useChatSettings();const enterToSend = useRecoilValue(store.enterToSend);diff --git a/client/src/components/Chat/Input/Reasoning.tsx b/client/src/components/Chat/Input/Reasoning.tsxindex c6ad392a7f..a5373f292c 100644--- a/client/src/components/Chat/Input/Reasoning.tsx+++ b/client/src/components/Chat/Input/Reasoning.tsx@@ -1,7 +1,7 @@import { useEffect, useId, useMemo, useRef, useState } from 'react';-import { useRecoilValue } from 'recoil';-import { useAtom, useStore } from 'jotai';import * as Popover from '@radix-ui/react-popover';+import { useAtom, useStore, useAtomValue } from 'jotai';+import { submissionByIndex } from '@librechat/chat/react';import { Button, Input, Slider } from '@librechat/client';import { BrainCircuit, ChevronDown, X } from 'lucide-react';import {@@ -28,7 +28,6 @@ import { useModelReasoning } from '~/hooks/Endpoint/useModelReasoning';import { formatTokens, resolveAgentTarget } from '~/utils';import { useAgentsMapContext } from '~/Providers';import { useLocalize } from '~/hooks';-import store from '~/store';type ReasoningControlProps = {index: number;@@ -279,7 +278,7 @@ export function useComposerReasoning({const [value, setValue] = useAtom(pendingReasoningOverrideFamily(reasoningStateKey));const reasoningStore = useStore();const placeholderStateKey = getReasoningStateKey(null, index);- const submission = useRecoilValue(store.submissionByIndex(index));+ const submission = useAtomValue(submissionByIndex(index));const submissionConversationId =submission?.conversation?.conversationId ?? submission?.userMessage?.conversationId;const submittedConversationRef = useRef<string | null>(null);diff --git a/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx b/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsxindex 0b617f7999..de4e873332 100644--- a/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/Reasoning.spec.tsx@@ -1,6 +1,7 @@import { RecoilRoot } from 'recoil';-import { Provider as JotaiProvider, createStore } from 'jotai';import { Constants, ReasoningEffort } from 'librechat-data-provider';+import { submissionByIndex, clearSubmissions } from '@librechat/chat/react';+import { Provider as JotaiProvider, createStore, getDefaultStore } from 'jotai';import { act, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react';import type {SettingDefinition,@@ -12,7 +13,6 @@ import type {import type { ReactNode } from 'react';import { getReasoningStateKey, pendingReasoningOverrideFamily } from '../Composer/state';import { ReasoningControl, useComposerReasoning } from '../Reasoning';-import store from '~/store';type MockEndpointConfig = {type?: string;@@ -87,6 +87,10 @@ const budgetSetting: SettingDefinition = {range: { min: -1, positiveMin: 128, max: 32768, step: 128 },};+afterEach(() => {+ clearSubmissions(getDefaultStore());+});+describe('ReasoningControl', () => {it('renders a compact, localized disclosure for the next message', async () => {render(@@ -515,10 +519,9 @@ describe('useComposerReasoning', () => {conversation: { conversationId: Constants.NEW_CONVO },userMessage: { conversationId: Constants.NEW_CONVO },} as TSubmission;+ reasoningStore.set(submissionByIndex(0), submission);const wrapper = ({ children }: { children: ReactNode }) => (- <RecoilRoot- initializeState={(snapshot) => snapshot.set(store.submissionByIndex(0), submission)}- >+ <RecoilRoot><JotaiProvider store={reasoningStore}>{children}</JotaiProvider></RecoilRoot>);diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsxindex a1baad5e63..e1df77ddc3 100644--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx@@ -91,7 +91,6 @@ jest.mock('~/utils', () => ({jest.mock('~/store', () => ({__esModule: true,default: {- submissionByIndex: jest.fn(),centerFormOnLanding: {},},}));diff --git a/client/src/hooks/Chat/__tests__/abort.spec.tsx b/client/src/hooks/Chat/__tests__/abort.spec.tsxindex 17cf729c55..7cb3d6f34d 100644--- a/client/src/hooks/Chat/__tests__/abort.spec.tsx+++ b/client/src/hooks/Chat/__tests__/abort.spec.tsx@@ -1,13 +1,15 @@import React from 'react';+import { RecoilRoot } from 'recoil';import { Constants } from 'librechat-data-provider';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,+ submissionByIndex,+ clearSubmissions,} from '@librechat/chat/react';import type { TSubmission, TConversation } from 'librechat-data-provider';import type { DrainAfterAbort, RunEnd } from '~/hooks/Chat/queue';@@ -77,10 +79,10 @@ function setup() {const cleanup = useAbortCleanup(INDEX);handles.captureSubmission = cleanup.captureSubmission;handles.clearSubmissionsUnlessReplaced = cleanup.clearSubmissionsUnlessReplaced;- handles.setSubmission = useSetRecoilState(store.submissionByIndex(INDEX));- handles.setOtherSubmission = useSetRecoilState(store.submissionByIndex(OTHER_INDEX));- current.submission = useRecoilValue(store.submissionByIndex(INDEX));- current.otherSubmission = useRecoilValue(store.submissionByIndex(OTHER_INDEX));+ handles.setSubmission = useSetAtom(submissionByIndex(INDEX));+ handles.setOtherSubmission = useSetAtom(submissionByIndex(OTHER_INDEX));+ current.submission = useAtomValue(submissionByIndex(INDEX));+ current.otherSubmission = useAtomValue(submissionByIndex(OTHER_INDEX));return null;}@@ -104,6 +106,10 @@ beforeEach(() => {resetSteerFamilies();});+afterEach(() => {+ clearSubmissions(getDefaultStore());+});+describe('useAbortCleanup', () => {it('clears all submissions when the captured submission is still current', async () => {const { handles, current } = setup();@@ -199,7 +205,7 @@ describe('useChatHelpers stopGenerating (abort steer targeting)', () => {let setDrainAfterAbort: ((value: DrainAfterAbort | false) => void) | undefined;const stoppedSubmission = submission('stopped-run');function RunEndProbe() {- currentSubmission = useRecoilValue(store.submissionByIndex(INDEX));+ currentSubmission = useAtomValue(submissionByIndex(INDEX));observed.runEnd = useAtomValue(runEndByIndex(INDEX));observed.drainAfterAbort = useAtomValue(drainAfterAbortByIndex(INDEX));setDrainAfterAbort = useSetAtom(drainAfterAbortByIndex(INDEX));@@ -211,7 +217,7 @@ describe('useChatHelpers stopGenerating (abort steer targeting)', () => {<RecoilRootinitializeState={({ set }) => {set(store.conversationKeysAtom, [INDEX]);- set(store.submissionByIndex(INDEX), stoppedSubmission);+ getDefaultStore().set(submissionByIndex(INDEX), stoppedSubmission);set(store.conversationByIndex(INDEX), {conversationId,endpoint: 'agents',diff --git a/client/src/hooks/Chat/__tests__/transport.spec.tsx b/client/src/hooks/Chat/__tests__/transport.spec.tsxindex 4d9fe04608..d8f5b5e6a1 100644--- a/client/src/hooks/Chat/__tests__/transport.spec.tsx+++ b/client/src/hooks/Chat/__tests__/transport.spec.tsx@@ -1,8 +1,8 @@import React from 'react';import { MemoryRouter } from 'react-router-dom';import { useAtomValue, getDefaultStore } from 'jotai';+import { RecoilRoot, useSetRecoilState } from 'recoil';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 {@@ -10,6 +10,8 @@ import {activeGenerationProtocolVersionByConvoId,pendingSteersByConvoId,resetSteerFamilies,+ submissionByIndex,+ clearSubmissions,} from '@librechat/chat/react';import type {TEnqueueAgentQueuedTurnRequest,@@ -203,6 +205,10 @@ beforeEach(() => {resetSteerFamilies();});+afterEach(() => {+ clearSubmissions(getDefaultStore());+});+describe('chat transport boundary', () => {describe('send (agents)', () => {it('starts the turn and attaches to its stream through the host transport', async () => {@@ -520,7 +526,7 @@ describe('chat transport boundary', () => {const useResumablePane = () => {const helpers = useChatContext();useResumeOnLoad('convo-1', helpers.getMessages, 0, true);- const submission = useRecoilValue(store.submissionByIndex(0));+ const submission = useAtomValue(submissionByIndex(0));useResumableSSE(submission, helpers, false, 0);const showConversation = useSetRecoilState(store.conversationByIndex(0));return { ...useChat(), showConversation };@@ -780,7 +786,7 @@ describe('chat transport boundary', () => {*/const usePane = () => {const helpers = useChatContext();- const submission = useRecoilValue(store.submissionByIndex(0));+ const submission = useAtomValue(submissionByIndex(0));useResumableSSE(submission, helpers, false, 0);const steering = useSteering({consumeDraft,diff --git a/client/src/hooks/Chat/abort.ts b/client/src/hooks/Chat/abort.tsindex 0e6e2109fa..443e3b5202 100644--- a/client/src/hooks/Chat/abort.ts+++ b/client/src/hooks/Chat/abort.ts@@ -1,6 +1,7 @@-import { useRecoilCallback } from 'recoil';+import { useCallback } from 'react';+import { useStore } from 'jotai';+import { submissionByIndex, useClearSubmissions } from '@librechat/chat/react';import type { TSubmission } from 'librechat-data-provider';-import store from '~/store';/*** Identity-guarded post-abort cleanup: the abort HTTP response can resolve@@ -11,25 +12,23 @@ import store from '~/store';* only clear when it is still the current one.*/export function useAbortCleanup(index: string | number) {- const clearAllSubmissions = store.useClearSubmissionState();+ const jotaiStore = useStore();+ const clearAllSubmissions = useClearSubmissions();- const captureSubmission = useRecoilCallback(- ({ snapshot }) =>- (): TSubmission | null =>- snapshot.getLoadable(store.submissionByIndex(index)).getValue(),- [index],+ const captureSubmission = useCallback(+ (): TSubmission | null => jotaiStore.get(submissionByIndex(index)),+ [jotaiStore, index],);- const clearSubmissionsUnlessReplaced = useRecoilCallback(- ({ snapshot }) =>- (captured: TSubmission | null) => {- const current = snapshot.getLoadable(store.submissionByIndex(index)).getValue();- if (current != null && current !== captured) {- return;- }- clearAllSubmissions();- },- [clearAllSubmissions, index],+ const clearSubmissionsUnlessReplaced = useCallback(+ (captured: TSubmission | null) => {+ const current = jotaiStore.get(submissionByIndex(index));+ if (current != null && current !== captured) {+ return;+ }+ clearAllSubmissions();+ },+ [clearAllSubmissions, jotaiStore, index],);return { captureSubmission, clearSubmissionsUnlessReplaced };diff --git a/client/src/hooks/Chat/useChatHelpers.ts b/client/src/hooks/Chat/useChatHelpers.tsindex ac542cb523..4f0c85cdd7 100644--- a/client/src/hooks/Chat/useChatHelpers.ts+++ b/client/src/hooks/Chat/useChatHelpers.ts@@ -1,7 +1,7 @@import { useCallback, useMemo, useRef, useState } from 'react';import { useQueryClient } from '@tanstack/react-query';+import { useRecoilState, useRecoilValue } from 'recoil';import { useAtom, useSetAtom, useStore, useAtomValue } from 'jotai';-import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';import { Constants, QueryKeys, isAssistantsEndpoint } from 'librechat-data-provider';import {activeGenerationCreatedAtByConvoId,@@ -9,6 +9,8 @@ import {isSubmittingFamily,useIsSubmitting,abortScrollFamily,+ submissionByIndex,+ useClearSubmissions,} from '@librechat/chat/react';import type { TMessage } from 'librechat-data-provider';import type { ChatContract } from './contract';@@ -30,7 +32,7 @@ const useLiveAttachments = () => useRecoilValue(store.messageAttachmentsMap);// this to be set somewhere elseexport default function useChatHelpers(index = 0, paramId?: string): ChatContract {- const clearAllSubmissions = store.useClearSubmissionState();+ const clearAllSubmissions = useClearSubmissions();const [files, setFiles] = useRecoilState(store.filesByIndex(index));const [filesLoading, setFilesLoading] = useState(false);@@ -135,7 +137,7 @@ export default function useChatHelpers(index = 0, paramId?: string): ChatContrac[queryParam, queryClient],);- const setSubmission = useSetRecoilState(store.submissionByIndex(index));+ const setSubmission = useSetAtom(submissionByIndex(index));const { ask: _ask, regenerate: _regenerate } = useChatFunctions({index,diff --git a/client/src/hooks/Config/useClearStates.ts b/client/src/hooks/Config/useClearStates.tsindex f7d9bbae86..27e53b6965 100644--- a/client/src/hooks/Config/useClearStates.ts+++ b/client/src/hooks/Config/useClearStates.ts@@ -1,7 +1,7 @@import { useStore } from 'jotai';import { useRecoilCallback } from 'recoil';import { Constants } from 'librechat-data-provider';-import { isSubmittingFamily } from '@librechat/chat/react';+import { isSubmittingFamily, useClearSubmissions } from '@librechat/chat/react';import {abortScrollFamily,showStopButtonByIndex,@@ -20,7 +20,7 @@ import store from '~/store';export default function useClearStates() {const clearConversations = store.useClearConvoState();- const clearSubmissions = store.useClearSubmissionState();+ const clearSubmissions = useClearSubmissions();const jotaiStore = useStore();const clearStates = useRecoilCallback(diff --git a/client/src/hooks/Conversations/useNavigateToConvo.tsx b/client/src/hooks/Conversations/useNavigateToConvo.tsxindex 5787a7f348..5a491906f6 100644--- a/client/src/hooks/Conversations/useNavigateToConvo.tsx+++ b/client/src/hooks/Conversations/useNavigateToConvo.tsx@@ -1,6 +1,7 @@import { useCallback } from 'react';-import { useSetRecoilState } from 'recoil';+import { useSetAtom } from 'jotai';import { useNavigate } from 'react-router-dom';+import { submissionByIndex } from '@librechat/chat/react';import { useQueryClient, isCancelledError } from '@tanstack/react-query';import {QueryKeys,@@ -95,7 +96,7 @@ const useNavigateToConvo = (index = 0) => {const queryClient = useQueryClient();const clearAllConversations = store.useClearConvoState();const applyModelSpecEffects = useApplyModelSpecEffects();- const setSubmission = useSetRecoilState(store.submissionByIndex(index));+ const setSubmission = useSetAtom(submissionByIndex(index));const { hasSetConversation, setConversation: setConvo } = store.useSetConversationAtom(index);const setConversation = useCallback(diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.tsindex c39a0ba283..b5c41c121f 100644--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts@@ -104,7 +104,6 @@ const mockQueryClient = {};const mockActiveRunAtom = { key: 'activeRun' };-const mockSubmissionAtom = { key: 'submission' };/** The follow-up queue a restored submission lands back in. */const queuedIn = (conversationId: string) =>getDefaultStore().get(queuedMessagesByConvoId(conversationId));@@ -125,9 +124,6 @@ const mockUseSetRecoilStateMock = jest.fn((atom: unknown) => {if (atom === mockActiveRunAtom) {return mockSetActiveRun;}- if (atom === mockSubmissionAtom) {- return mockSetSubmission;- }return jest.fn();});function mockUseSetRecoilState(atom: unknown) {@@ -178,6 +174,9 @@ jest.mock('jotai', () => {return mockSetDrainAfterAbort;}const generation = jest.requireActual('@librechat/chat/react');+ if (atom === generation.submissionByIndex(0)) {+ return mockSetSubmission;+ }if (atom === generation.abortScrollFamily(0)) {return mockSetAbortScroll;}@@ -193,7 +192,6 @@ jest.mock('~/store', () => ({__esModule: true,default: {activeRunFamily: jest.fn(() => mockActiveRunAtom),- submissionByIndex: jest.fn(() => mockSubmissionAtom),},}));diff --git a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsxindex a600efb06c..cbda09e449 100644--- a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx+++ b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx@@ -1,8 +1,8 @@+import { RecoilRoot } from 'recoil';import { renderHook, act, waitFor } from '@testing-library/react';-import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import { Constants, ContentTypes, QueryKeys } from 'librechat-data-provider';+import { isSubmittingFamily, resetSubmitting, submissionByIndex } from '@librechat/chat/react';import {Provider as JotaiProvider,createStore,@@ -170,13 +170,13 @@ function renderUseResumeOnLoad({let setAttachedEpochState: ((value: number | null) => void) | undefined;const initializeState = (snapshot: MutableSnapshot) => {snapshot.set(store.conversationByIndex(0), buildConversation(conversationId));- snapshot.set(store.submissionByIndex(0), submission);+ jotaiStore.set(submissionByIndex(0), submission);jotaiStore.set(isSubmittingFamily(0), isSubmitting);};const SubmissionProbe = () => {- const currentSubmission = useRecoilValue(store.submissionByIndex(0));- setSubmissionState = useSetRecoilState(store.submissionByIndex(0));+ const currentSubmission = useAtomValue(submissionByIndex(0));+ setSubmissionState = useSetAtom(submissionByIndex(0));setIsSubmittingState = useSetAtom(isSubmittingFamily(0));setAttachedEpochState = useSetAtom(activeGenerationCreatedAtByConvoId(conversationId));onSubmission?.(currentSubmission);diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.tsindex a4ffe6ff35..8d9855edcf 100644--- a/client/src/hooks/SSE/useResumableSSE.ts+++ b/client/src/hooks/SSE/useResumableSSE.ts@@ -5,6 +5,7 @@ import { useStore, useSetAtom } from 'jotai';import { useQueryClient } from '@tanstack/react-query';import { ABORT_SWEEP_STATUSES, selectLocalSteersForQueue } from '@librechat/chat';import {+ submissionByIndex,liveAppliedSteerIdsAtom,abortScrollFamily,showStopButtonByIndex,@@ -329,7 +330,7 @@ export default function useResumableSSE(const [_completed, setCompleted] = useState(new Set());const [streamId, setStreamId] = useState<string | null>(null);const setAbortScroll = useSetAtom(abortScrollFamily(runIndex));- const setSubmission = useSetRecoilState(store.submissionByIndex(runIndex));+ const setSubmission = useSetAtom(submissionByIndex(runIndex));const setShowStopButton = useSetAtom(showStopButtonByIndex(runIndex));const setLiveAppliedSteerIds = useSetAtom(liveAppliedSteerIdsAtom);diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/client/src/hooks/SSE/useResumeOnLoad.tsindex fcfb3292ac..a286f64ee5 100644--- a/client/src/hooks/SSE/useResumeOnLoad.ts+++ b/client/src/hooks/SSE/useResumeOnLoad.ts@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useRecoilValue } from 'recoil';import { useQueryClient } from '@tanstack/react-query';-import { useSetRecoilState, useRecoilValue } from 'recoil';import { useStore, useAtom, useSetAtom, useAtomValue } from 'jotai';import {Constants,@@ -13,6 +13,8 @@ import {activeGenerationCreatedAtByConvoId,useIsSubmitting,submissionStartFamily,+ submissionByIndex,+ useSubmission,} from '@librechat/chat/react';import {hasSubmissionUserMessage,@@ -73,9 +75,9 @@ export default function useResumeOnLoad() {const jotaiStore = useStore();const queryClient = useQueryClient();- const setSubmission = useSetRecoilState(store.submissionByIndex(runIndex));+ const setSubmission = useSetAtom(submissionByIndex(runIndex));const setSubmissionStart = useSetAtom(submissionStartFamily(runIndex));- const currentSubmission = useRecoilValue(store.submissionByIndex(runIndex));+ const currentSubmission = useSubmission(runIndex);const isSubmitting = useIsSubmitting(runIndex);const attachedGenerationCreatedAt = useAtomValue(activeGenerationCreatedAtByConvoId(conversationId ?? ''),diff --git a/client/src/hooks/__tests__/useNewConvo.spec.ts b/client/src/hooks/__tests__/useNewConvo.spec.tsindex 23b9daf543..c72c2cf782 100644--- a/client/src/hooks/__tests__/useNewConvo.spec.ts+++ b/client/src/hooks/__tests__/useNewConvo.spec.ts@@ -108,7 +108,6 @@ jest.mock('~/store', () => ({defaultPreset: 'defaultPreset',saveBadgesState: 'saveBadgesState',filesByIndex: () => 'filesByIndex',- submissionByIndex: () => 'submissionByIndex',useClearConvoState: () => jest.fn(),useSetConversationAtom: () => ({ setConversation: jest.fn() }),},diff --git a/client/src/hooks/useNewConvo.ts b/client/src/hooks/useNewConvo.tsindex 6915536d97..2b291b2c0b 100644--- a/client/src/hooks/useNewConvo.ts+++ b/client/src/hooks/useNewConvo.ts@@ -1,7 +1,9 @@import { useCallback } from 'react';+import { useSetAtom } from 'jotai';+import { submissionByIndex } from '@librechat/chat/react';import { useNavigate, useSearchParams } from 'react-router-dom';import { useGetModelsQuery } from 'librechat-data-provider/react-query';-import { useRecoilState, useRecoilValue, useSetRecoilState, useRecoilCallback } from 'recoil';+import { useRecoilState, useRecoilValue, useRecoilCallback } from 'recoil';import {Constants,FileSources,@@ -84,7 +86,7 @@ const useNewConvo = (index = 0) => {const defaultPreset = useRecoilValue(store.defaultPreset);const { setConversation } = store.useSetConversationAtom(index);const [files, setFiles] = useRecoilState(store.filesByIndex(index));- const setSubmission = useSetRecoilState<TSubmission | null>(store.submissionByIndex(index));+ const setSubmission = useSetAtom(submissionByIndex(index));const { data: endpointsConfig = {} as TEndpointsConfig } = useGetEndpointsQuery();const agentsMap = useAgentsMapContext();diff --git a/client/src/store/families.ts b/client/src/store/families.tsindex 42798dabf4..1bd8933ac2 100644--- a/client/src/store/families.ts+++ b/client/src/store/families.ts@@ -3,7 +3,6 @@ import { createSearchParams } from 'react-router-dom';import { LocalStorageKeys, isEphemeralAgentId, Constants } from 'librechat-data-provider';import {atom,- selector,atomFamily,DefaultValue,selectorFamily,@@ -11,7 +10,7 @@ import {useSetRecoilState,useRecoilCallback,} from 'recoil';-import type { EModelEndpoint, TConversation, TSubmission, TPreset } from 'librechat-data-provider';+import type { EModelEndpoint, TConversation, TPreset } from 'librechat-data-provider';import type { TOptionSettings, ExtendedFile } from '~/common';import {clearModelForNonEphemeralAgent,@@ -21,19 +20,6 @@ import {} from '~/utils';import { useSetConvoContext } from '~/Providers/SetConvoContext';-const submissionByIndex = atomFamily<TSubmission | null, string | number>({- key: 'submissionByIndex',- default: null,-});--const submissionKeysSelector = selector<(string | number)[]>({- key: 'submissionKeysSelector',- get: ({ get }) => {- const keys = get(conversationKeysAtom);- return keys.filter((key) => get(submissionByIndex(key)) !== null);- },-});-const conversationByIndex = atomFamily<TConversation | null, string | number>({key: 'conversationByIndex',default: null,@@ -305,28 +291,6 @@ function useClearConvoState() {const conversationByKeySelector = conversationByIndex;-function useClearSubmissionState() {- const clearAllSubmissions = useRecoilCallback(- ({ reset, snapshot }) =>- async (skipFirst?: boolean) => {- const submissionKeys = await snapshot.getPromise(submissionKeysSelector);- logger.log('submissionKeys', submissionKeys);-- for (const key of submissionKeys) {- if (skipFirst === true && key == 0) {- continue;- }-- logger.log('resetting submission', key);- reset(submissionByIndex(key));- }- },- [],- );-- return clearAllSubmissions;-}-const updateConversationSelector = selectorFamily({key: 'updateConversationSelector',get: () => () => null as Partial<TConversation> | null,@@ -357,7 +321,6 @@ export default {conversationByIndex,filesByIndex,presetByIndex,- submissionByIndex,optionSettingsFamily,showPopoverFamily,conversationIdByIndex,@@ -379,7 +342,6 @@ export default {globalAudioFetchingFamily,showPlusPopoverFamily,activePromptByIndex,- useClearSubmissionState,showPromptsPopoverFamily,pendingComposerTextByConvoId,updateConversationSelector,diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.tsindex 57001a5ebf..f7a7b74b85 100644--- a/packages/chat/src/react.ts+++ b/packages/chat/src/react.ts@@ -51,12 +51,16 @@ export {clearPendingReasoningOverrides,} from './react/composer';export {+ submissionByIndex,+ clearSubmissions,+ useSubmission,+ useClearSubmissions,isSubmittingFamily,anySubmittingAtom,resetSubmitting,useIsSubmitting,} from './react/submission';-export type { PaneIndex } from './react/submission';+export type { PaneIndex, SubmissionAtom } from './react/submission';export {submissionStartFamily,showStopButtonByIndex,diff --git a/packages/chat/src/react/__tests__/submission.spec.tsx b/packages/chat/src/react/__tests__/submission.spec.tsxindex d32cf479c8..dc8d92ddc7 100644--- a/packages/chat/src/react/__tests__/submission.spec.tsx+++ b/packages/chat/src/react/__tests__/submission.spec.tsx@@ -1,9 +1,17 @@/*** @jest-environment jsdom*/-import { useAtom, useAtomValue } from 'jotai';import { act, render, renderHook, screen } from '@testing-library/react';-import { anySubmittingAtom, isSubmittingFamily } from '../submission';+import { Provider, createStore, useAtom, useAtomValue, useSetAtom } from 'jotai';+import type { TSubmission } from 'librechat-data-provider';+import type { ReactNode } from 'react';+import {+ clearSubmissions,+ submissionByIndex,+ isSubmittingFamily,+ anySubmittingAtom,+ useClearSubmissions,+} from '../submission';function Indicator({ index }: { index: number }) {const isSubmitting = useAtomValue(isSubmittingFamily(index));@@ -64,3 +72,44 @@ describe('anySubmittingAtom', () => {expect(result.current.any).toBe(false);});});++describe('submissionByIndex', () => {+ const run = (id: string) => ({ userMessage: { messageId: id } }) as unknown as TSubmission;++ it('shows a component and a hook in the same store the same submission', () => {+ function Probe() {+ const submission = useAtomValue(submissionByIndex(30));+ return <p>{submission?.userMessage.messageId ?? 'none'}</p>;+ }+ render(<Probe />);+ const { result } = renderHook(() => useSetAtom(submissionByIndex(30)));+ act(() => result.current(run('m1')));+ expect(screen.getByText('m1')).toBeInTheDocument();+ act(() => result.current(null));+ expect(screen.getByText('none')).toBeInTheDocument();+ });++ it('clears every pane, or every pane but the first when asked', () => {+ const store = createStore();+ store.set(submissionByIndex(0), run('main'));+ store.set(submissionByIndex(1), run('added'));++ clearSubmissions(store, true);+ expect(store.get(submissionByIndex(0))).not.toBeNull();+ expect(store.get(submissionByIndex(1))).toBeNull();++ clearSubmissions(store);+ expect(store.get(submissionByIndex(0))).toBeNull();+ });++ it('clears through the store the caller renders in', () => {+ const store = createStore();+ store.set(submissionByIndex(2), run('x'));+ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider store={store}>{children}</Provider>+ );+ const { result } = renderHook(() => useClearSubmissions(), { wrapper });+ act(() => result.current());+ expect(store.get(submissionByIndex(2))).toBeNull();+ });+});diff --git a/packages/chat/src/react/submission.ts b/packages/chat/src/react/submission.tsindex 8451efc077..5f5e073bd7 100644--- a/packages/chat/src/react/submission.ts+++ b/packages/chat/src/react/submission.ts@@ -1,6 +1,8 @@+import { useCallback } from 'react';import { atomFamily } from 'jotai/utils';import { atom, useAtomValue, useStore } from 'jotai';import type { Atom, WritableAtom, createStore } from 'jotai';+import type { TSubmission } from 'librechat-data-provider';import type { SetStateAction } from 'react';/** Pane index a generation runs in: `0` for the main chat, `1` for the added one. */@@ -56,3 +58,55 @@ export function useIsSubmitting(index: PaneIndex): boolean {useAtomValue(isSubmittingFamily(index));return store.get(isSubmittingFamily(index));}++const submissionIndexesAtom = atom<ReadonlySet<PaneIndex>>(new Set<PaneIndex>());++/** The submission a pane is running, or `null`; setting a new value is what sends a message. */+export type SubmissionAtom = WritableAtom<+ TSubmission | null,+ [SetStateAction<TSubmission | null>],+ void+>;++export const submissionByIndex: (index: PaneIndex) => SubmissionAtom = atomFamily(+ (index: PaneIndex): SubmissionAtom => {+ const valueAtom = atom<TSubmission | null>(null);+ return atom(+ (get) => get(valueAtom),+ (get, set, update: SetStateAction<TSubmission | null>) => {+ const next = typeof update === 'function' ? update(get(valueAtom)) : update;+ set(valueAtom, next);+ const indexes = new Set(get(submissionIndexesAtom));+ if (next === null) {+ indexes.delete(index);+ } else {+ indexes.add(index);+ }+ set(submissionIndexesAtom, indexes);+ },+ );+ },+);++/** Drops every pane's submission, keeping the main pane's when `skipFirst` is set. */+export function clearSubmissions(store: Pick<Store, 'get' | 'set'>, skipFirst?: boolean): void {+ store.get(submissionIndexesAtom).forEach((index) => {+ if (skipFirst === true && index == 0) {+ return;+ }+ store.set(submissionByIndex(index), null);+ });+}++/** Stable callback that clears the submissions of the store the caller renders in. */+export function useClearSubmissions(): (skipFirst?: boolean) => void {+ const store = useStore();+ return useCallback((skipFirst?: boolean) => clearSubmissions(store, skipFirst), [store]);+}++/** The pane's submission read from the store at render time, for the same reason as `useIsSubmitting`. */+export function useSubmission(index: PaneIndex): TSubmission | null {+ const store = useStore();+ useAtomValue(submissionByIndex(index));+ return store.get(submissionByIndex(index));+}