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 Submitting Flag to Jotai in the Chat Package (#17121)
Marco Berettaf43e7fa041dd
diff --git a/client/src/Providers/ArtifactsContext.tsx b/client/src/Providers/ArtifactsContext.tsxindex f2bb28fabf..e5f593e80a 100644--- a/client/src/Providers/ArtifactsContext.tsx+++ b/client/src/Providers/ArtifactsContext.tsx@@ -1,5 +1,6 @@import React, { createContext, useContext, useMemo } from 'react';import { useRecoilValue } from 'recoil';+import { useIsSubmitting } from '@librechat/chat/react';import { useLatestMessage } from '~/hooks/Messages/useLatestMessage';import { getLatestText } from '~/utils';import store from '~/store';@@ -29,7 +30,7 @@ interface ArtifactsProviderProps {}export function ArtifactsProvider({ children, value }: ArtifactsProviderProps) {- const isSubmitting = useRecoilValue(store.isSubmittingFamily(0));+ const isSubmitting = useIsSubmitting(0);const latestMessage = useLatestMessage(0);const conversationId = useRecoilValue(store.conversationIdByIndex(0));diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsxindex e867175bd5..21c7513da3 100644--- a/client/src/components/Chat/ChatView.tsx+++ b/client/src/components/Chat/ChatView.tsx@@ -4,6 +4,7 @@ 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 type { TChatProject } from 'librechat-data-provider';import type { ChatFormValues } from '~/common';@@ -68,7 +69,7 @@ function ChatView({const { conversationId } = useParams();const localize = useLocalize();const rootSubmission = useRecoilValue(store.submissionByIndex(index));- const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));+ const isSubmitting = useIsSubmitting(index);const { saveDrafts } = useChatSettings();const enterToSend = useRecoilValue(store.enterToSend);const autoSendText = useRecoilValue(store.autoSendText);diff --git a/client/src/components/Chat/Header.tsx b/client/src/components/Chat/Header.tsxindex 795b4ffbb1..46651aa14f 100644--- a/client/src/components/Chat/Header.tsx+++ b/client/src/components/Chat/Header.tsx@@ -1,6 +1,7 @@import { memo, useMemo } from 'react';import { useRecoilValue } from 'recoil';import { useParams } from 'react-router-dom';+import { useIsSubmitting } from '@librechat/chat/react';import {getConfigDefaults,Constants,@@ -38,7 +39,7 @@ function Header({}) {const { data: startupConfig } = useGetStartupConfig();const navVisible = useRecoilValue(store.sidebarExpanded);- const isSubmitting = useRecoilValue(store.isSubmittingFamily(0));+ const isSubmitting = useIsSubmitting(0);const isSmallScreen = useDrawerViewport();/** The mobile row only offers a new chat when there is one to leave. Readdiff --git a/client/src/components/Chat/Input/__tests__/BrowserAudio.spec.tsx b/client/src/components/Chat/Input/__tests__/BrowserAudio.spec.tsxindex b14a53ae6a..20aed50578 100644--- a/client/src/components/Chat/Input/__tests__/BrowserAudio.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/BrowserAudio.spec.tsx@@ -1,8 +1,10 @@import React from 'react';import { RecoilRoot } from 'recoil';+import { getDefaultStore } from 'jotai';import { render, waitFor } from '@testing-library/react';import { MemoryRouter, Routes, Route } from 'react-router-dom';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import { Constants, QueryKeys, ContentTypes } from 'librechat-data-provider';import type { TMessage, TConversation } from 'librechat-data-provider';import BrowserAudio from '../BrowserAudio';@@ -68,7 +70,7 @@ const renderBrowserAudio = ({set(store.conversationByIndex(0), { conversationId } as TConversation);set(store.activeRunFamily(0), activeRunId);set(store.audioRunFamily(0), audioRunId);- set(store.isSubmittingFamily(0), isSubmitting);+ getDefaultStore().set(isSubmittingFamily(0), isSubmitting);}}><Routes>@@ -83,6 +85,10 @@ const renderBrowserAudio = ({/** Lets every effect settle so a missing utterance is a real absence, not a pending render */const settle = () => waitFor(() => expect(cancelCount).toBeGreaterThanOrEqual(0));+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('BrowserAudio autoplay', () => {beforeAll(() => {Object.defineProperty(window, 'speechSynthesis', {diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsxindex b0d2ba31e9..4556d2f2c9 100644--- a/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/ChatForm.approvalMode.spec.tsx@@ -1,4 +1,6 @@import React, { useMemo, useState } from 'react';+import { getDefaultStore, useAtom } from 'jotai';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import '@testing-library/jest-dom';import { DndProvider } from 'react-dnd';import { useForm } from 'react-hook-form';@@ -34,7 +36,7 @@ const conversation = {function Harness() {const [files, setFiles] = useRecoilState(store.filesByIndex(0));- const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));+ const [isSubmitting] = useAtom(isSubmittingFamily(0));const [, setFilesLoading] = useState(false);const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });@@ -90,7 +92,7 @@ function renderComposer({ submitting }: { submitting: boolean }) {return render(<QueryClientProvider client={queryClient}>- <RecoilRoot initializeState={({ set }) => set(store.isSubmittingFamily(0), submitting)}>+ <RecoilRoot initializeState={() => getDefaultStore().set(isSubmittingFamily(0), submitting)}><Router><AuthContextProvider authConfig={{ loginRedirect: '', test: true }}><DndProvider backend={HTML5Backend}>@@ -103,6 +105,10 @@ function renderComposer({ submitting }: { submitting: boolean }) {);}+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('ChatForm code approval mode', () => {beforeEach(() => {localStorage.clear();diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsxindex 9614e41aac..04e31d07a3 100644--- a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx@@ -1,8 +1,9 @@import React, { Profiler, useMemo, useState } from 'react';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import '@testing-library/jest-dom';import { DndProvider } from 'react-dnd';-import { getDefaultStore } from 'jotai';import { useForm } from 'react-hook-form';+import { getDefaultStore, useAtom } from 'jotai';import { RecoilRoot, useRecoilState } from 'recoil';import userEvent from '@testing-library/user-event';import { HTML5Backend } from 'react-dnd-html5-backend';@@ -91,7 +92,7 @@ let commits = 0;function Harness() {const [files, setFiles] = useRecoilState(store.filesByIndex(0));- const [isSubmitting, setIsSubmitting] = useRecoilState(store.isSubmittingFamily(0));+ const [isSubmitting, setIsSubmitting] = useAtom(isSubmittingFamily(0));/* ChatView owns this read and passes it in; the harness stands in for it. */const [speechSettingsInitialized] = useRecoilState(store.speechSettingsInitialized);const [, setFilesLoading] = useState(false);@@ -176,7 +177,7 @@ function renderComposer({<QueryClientProvider client={queryClient}><RecoilRootinitializeState={({ set }) => {- set(store.isSubmittingFamily(0), submitting);+ getDefaultStore().set(isSubmittingFamily(0), submitting);set(store.speechSettingsInitialized, speechSettingsInitialized);}}>@@ -199,6 +200,10 @@ const attach = (container: HTMLElement, file: File) =>userEvent.upload(container.querySelector('input[type="file"]') as HTMLInputElement, file);const image = () => new File(['image-bytes'], 'cat.png', { type: 'image/png' });+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('ChatForm attachments', () => {beforeEach(() => {localStorage.clear();diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.enterToSend.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.enterToSend.spec.tsxindex aa8d41b8ce..dd07472bef 100644--- a/client/src/components/Chat/Input/__tests__/ChatForm.enterToSend.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/ChatForm.enterToSend.spec.tsx@@ -1,4 +1,6 @@import React, { useMemo, useState } from 'react';+import { useAtom } from 'jotai';+import { isSubmittingFamily } from '@librechat/chat/react';import '@testing-library/jest-dom';import { DndProvider } from 'react-dnd';import { useForm } from 'react-hook-form';@@ -30,7 +32,7 @@ const conversation = {*/function Harness({ enterToSend }: { enterToSend: boolean }) {const [files, setFiles] = useRecoilState(store.filesByIndex(0));- const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));+ const [isSubmitting] = useAtom(isSubmittingFamily(0));const [, setFilesLoading] = useState(false);const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsxindex d29222cbda..002f28516a 100644--- a/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/ChatForm.pasteUpload.spec.tsx@@ -1,4 +1,6 @@import React, { useMemo, useState } from 'react';+import { useAtom } from 'jotai';+import { isSubmittingFamily } from '@librechat/chat/react';import '@testing-library/jest-dom';import { DndProvider } from 'react-dnd';import { useForm } from 'react-hook-form';@@ -66,7 +68,7 @@ class StubImage {function Harness() {const [files, setFiles] = useRecoilState(store.filesByIndex(0));- const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));+ const [isSubmitting] = useAtom(isSubmittingFamily(0));const [, setFilesLoading] = useState(false);const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsxindex 3a82223b3f..4c56435f58 100644--- a/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx@@ -3,11 +3,12 @@ import { DndProvider } from 'react-dnd';import { useForm } from 'react-hook-form';import { RecoilRoot, useRecoilState } from 'recoil';import { HTML5Backend } from 'react-dnd-html5-backend';-import { Provider as JotaiProvider, createStore } from 'jotai';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 { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';+import { Provider as JotaiProvider, createStore, getDefaultStore, useAtom } from 'jotai';import {activeGenerationCreatedAtByConvoId,activeGenerationProtocolVersionByConvoId,@@ -57,7 +58,7 @@ function Harness({speechSettingsInitialized?: boolean;}) {const [files, setFiles] = useRecoilState(store.filesByIndex(0));- const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));+ const [isSubmitting] = useAtom(isSubmittingFamily(0));const [, setFilesLoading] = useState(false);const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });const chatHelpers = useMemo<React.ContextType<typeof ChatContext>>(@@ -180,7 +181,7 @@ function mountComposer(<RecoilRootinitializeState={({ set }) => {if (liveRun) {- set(store.isSubmittingFamily(0), true);+ jotaiStore.set(isSubmittingFamily(0), true);}if (speechSettingsInitialized) {set(store.engineSTT, 'external');@@ -213,6 +214,10 @@ function mountComposer(return { ...view, navigate: (to: string) => navigate(to), getLocation: () => location };}+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('ChatForm URL submission', () => {beforeEach(() => {jest.useFakeTimers();diff --git a/client/src/components/Chat/Input/__tests__/StreamAudio.spec.tsx b/client/src/components/Chat/Input/__tests__/StreamAudio.spec.tsxindex 24b3a0dc92..8559273fe9 100644--- a/client/src/components/Chat/Input/__tests__/StreamAudio.spec.tsx+++ b/client/src/components/Chat/Input/__tests__/StreamAudio.spec.tsx@@ -2,10 +2,12 @@ import React from 'react';import { TextEncoder } from 'util';import { webcrypto } from 'crypto';import { RecoilRoot } from 'recoil';+import { getDefaultStore } from 'jotai';import { render, waitFor } from '@testing-library/react';import { MemoryRouter, Routes, Route } from 'react-router-dom';import { Constants, QueryKeys } from 'librechat-data-provider';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import type { TMessage, TConversation } from 'librechat-data-provider';import { getTTSCacheKey, setCachedTTSAudio, getTTSCacheGeneration } from '~/utils';import StreamAudio from '../StreamAudio';@@ -18,6 +20,10 @@ const conversationId = 'convo-1';const recording = new Blob(['spoken answer'], { type: 'audio/mpeg' });const fetchMock = jest.fn(() => Promise.reject(new Error('not cached')));+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('StreamAudio cache', () => {beforeAll(() => {Object.defineProperty(global, 'crypto', { value: webcrypto, configurable: true });@@ -51,7 +57,7 @@ describe('StreamAudio cache', () => {set(store.conversationByIndex(0), { conversationId } as TConversation);set(store.activeRunFamily(0), 'run-1');set(store.audioRunFamily(0), null);- set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);}}><Routes>diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsxindex dca66f5467..a4f9b52aae 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx@@ -1,6 +1,8 @@import React from 'react';+import { getDefaultStore } from 'jotai';import { RecoilRoot, useRecoilValue } from 'recoil';import { render, screen, fireEvent, act } from '@testing-library/react';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import type { TAttachment } from 'librechat-data-provider';import type { MutableSnapshot } from 'recoil';import Attachment, { AttachmentGroup } from '../Attachment';@@ -94,8 +96,8 @@ const inMessage = (ui: React.ReactElement, isSubmitting: boolean) => (const renderWith = (ui: React.ReactElement, opts: { streaming?: boolean } = {}) => {const streaming = opts.streaming ?? true;- const initializeState = (snapshot: MutableSnapshot) => {- snapshot.set(store.isSubmittingFamily(0), streaming);+ const initializeState = () => {+ getDefaultStore().set(isSubmittingFamily(0), streaming);};return render(<RecoilRoot initializeState={initializeState}>{inMessage(ui, streaming)}</RecoilRoot>,@@ -124,8 +126,8 @@ const StateProbe = ({ onSnapshot }: { onSnapshot: (snap: ArtifactsSnapshot) => vconst renderWithProbe = (ui: React.ReactElement, opts: { streaming?: boolean } = {}) => {const streaming = opts.streaming ?? true;- const initializeState = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), streaming);+ const initializeState = () => {+ getDefaultStore().set(isSubmittingFamily(0), streaming);};let snapshot: ArtifactsSnapshot = {visibility: false,@@ -148,6 +150,10 @@ const renderWithProbe = (ui: React.ReactElement, opts: { streaming?: boolean } =};};+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('Attachment routing for tool artifacts', () => {it('renders an HTML artifact card (panel artifact) and exposes a download control', () => {const html = baseAttachment({@@ -459,7 +465,7 @@ describe('ToolArtifactCard click behaviour', () => {text: '<h1>previous answer</h1>',});const initializeState = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), true);+ getDefaultStore().set(isSubmittingFamily(0), true);snap.set(store.artifactsVisibility, false);};let snapshot: ArtifactsSnapshot = {@@ -612,8 +618,8 @@ describe('ToolArtifactCard click behaviour', () => {filename: 'test.py',text: 'print("hello")',} as Partial<TAttachment>);- const initializeState = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), true);+ const initializeState = () => {+ getDefaultStore().set(isSubmittingFamily(0), true);};let snapshot: ArtifactsSnapshot = {visibility: false,@@ -649,7 +655,7 @@ describe('ToolArtifactCard click behaviour', () => {text: '<h1>fresh</h1>',} as Partial<TAttachment>);const initializeState = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), true);+ getDefaultStore().set(isSubmittingFamily(0), true);snap.set(store.artifactsVisibility, false);};let snapshot: ArtifactsSnapshot = {@@ -681,7 +687,7 @@ describe('ToolArtifactCard click behaviour', () => {text: '<h1>old</h1>',} as Partial<TAttachment>);const initializeState = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);snap.set(store.artifactsVisibility, false);};let snapshot: ArtifactsSnapshot = {@@ -721,7 +727,7 @@ describe('ToolArtifactCard click behaviour', () => {textFormat: 'html',});const initializeState = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);snap.set(store.artifactsVisibility, false);snap.set(store.previewJustResolved(['test-response', 'just-resolved-xlsx']), true);};@@ -756,7 +762,7 @@ describe('ToolArtifactCard click behaviour', () => {textFormat: 'html',});const initializeState = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);snap.set(store.artifactsVisibility, false);snap.set(store.previewJustResolved(['test-response', 'one-shot-xlsx']), true);};@@ -783,7 +789,7 @@ describe('ToolArtifactCard click behaviour', () => {unmount();snapshot = { visibility: false, currentArtifactId: null, artifactIds: [] };const secondInit = (snap: MutableSnapshot) => {- snap.set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);snap.set(store.artifactsVisibility, false);// flag stays at default (false) — already consumed};diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsxindex f81722373d..f98b4e4eb3 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx@@ -1,11 +1,11 @@import React from 'react';import { RecoilRoot } from 'recoil';+import { getDefaultStore } from 'jotai';import { render, screen } from '@testing-library/react';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import type { TAttachment } from 'librechat-data-provider';-import type { MutableSnapshot } from 'recoil';import { MessageContext } from '~/Providers/MessageContext';import LogContent from '../LogContent';-import store from '~/store';jest.mock('~/hooks', () => ({useLocalize:@@ -73,8 +73,8 @@ const baseAttachment = (overrides: Partial<TAttachment> = {}): TAttachment =>*/const renderWith = (ui: React.ReactElement, opts: { streaming?: boolean } = {}) => {const streaming = opts.streaming ?? true;- const initializeState = (snapshot: MutableSnapshot) => {- snapshot.set(store.isSubmittingFamily(0), streaming);+ const initializeState = () => {+ getDefaultStore().set(isSubmittingFamily(0), streaming);};return render(<RecoilRoot initializeState={initializeState}>@@ -87,6 +87,10 @@ const renderWith = (ui: React.ReactElement, opts: { streaming?: boolean } = {}));};+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('LogContent attachment routing', () => {it('routes HTML attachments through ToolArtifactCard (panel)', () => {const html = baseAttachment({diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsxindex e9b9257eac..7a028d4ac8 100644--- a/client/src/components/Chat/Messages/MessagesView.tsx+++ b/client/src/components/Chat/Messages/MessagesView.tsx@@ -1,7 +1,7 @@import { useState, useCallback, useEffect } from 'react';import { useAtomValue } from 'jotai';-import { useRecoilValue } from 'recoil';import { Constants } from 'librechat-data-provider';+import { useIsSubmitting } from '@librechat/chat/react';import type { TMessage } from 'librechat-data-provider';import {useLocalize,@@ -24,7 +24,6 @@ import ScrollButton from './ScrollButton';import PendingTurn from './PendingTurn';import MessageNav from './MessageNav';import { cn } from '~/utils';-import store from '~/store';function MessagesViewContent({messagesTree: _messagesTree,@@ -54,7 +53,7 @@ function MessagesViewContent({const fileMap = useFileMapContext();const threadRows = useThreadRows(FLAT_THREAD ? messages : null, conversationId, fileMap);const { index, latestMessageId, latestMessageDepth, messagesKey } = useChatContext();- const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));+ const isSubmitting = useIsSubmitting(index);const { showScrollButton, maximizeChatSpace } = useChatSurface();const autoScroll = useAtomValue(autoScrollAtom);diff --git a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsxindex 09b22f2af2..248e9c70a3 100644--- a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx+++ b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx@@ -1,8 +1,10 @@import React, { useMemo } from 'react';+import { getDefaultStore } from 'jotai';import { MemoryRouter } from 'react-router-dom';import userEvent from '@testing-library/user-event';import { RecoilRoot, type MutableSnapshot } from 'recoil';import { render, screen, act } from '@testing-library/react';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import { QueryKeys, type TConversation, type TMessage } from 'librechat-data-provider';import { QueryClient, QueryClientProvider, useQueryClient } from '@tanstack/react-query';import { useLatestMessage, useLatestMessageId } from '~/hooks/Messages/useLatestMessage';@@ -234,7 +236,7 @@ function renderStreamingRow(const initializeState = ({ set }: MutableSnapshot) => {set(store.conversationByIndex(0), conversation);- set(store.isSubmittingFamily(0), submitting);+ getDefaultStore().set(isSubmittingFamily(0), submitting);};render(@@ -255,6 +257,10 @@ function renderStreamingRow(return queryClient;}+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('streaming hover actions', () => {beforeEach(() => {mockHoverButtonsRenderCount = 0;diff --git a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsxindex 710dbecfbf..bdfb6c24c1 100644--- a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx+++ b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx@@ -54,7 +54,7 @@ jest.mock('~/components/Chat/Subagents/surface', () => ({jest.mock('~/store/autoScroll', () => ({ autoScrollAtom: {} }));jest.mock('~/store', () => ({__esModule: true,- default: { isSubmittingFamily: () => ({}) },+ default: {},}));jest.mock('../Thread', () => ({diff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsxindex 663d1bd556..d68713382a 100644--- a/client/src/components/Chat/Presentation.test.tsx+++ b/client/src/components/Chat/Presentation.test.tsx@@ -1,6 +1,7 @@import React from 'react';import { useSetAtom } from 'jotai';import { RecoilRoot, useSetRecoilState } from 'recoil';+import { isSubmittingFamily } from '@librechat/chat/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { TConversation } from 'librechat-data-provider';@@ -162,7 +163,7 @@ const SelectAgentConversation = () => {};const StartAgentRun = () => {- const setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));+ const setSubmitting = useSetAtom(isSubmittingFamily(0));return (<button type="button" onClick={() => setSubmitting(true)}>{mockStartAgentRunLabel}diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsxindex 20ef7be98e..f1da81f9d6 100644--- a/client/src/components/Chat/Presentation.tsx+++ b/client/src/components/Chat/Presentation.tsx@@ -1,6 +1,7 @@import { Suspense, useCallback, useEffect, useMemo, useRef } from 'react';import { useRecoilValue } from 'recoil';import { useAtomValue, useSetAtom } from 'jotai';+import { useIsSubmitting } from '@librechat/chat/react';import { EModelEndpoint, FileSources, LocalStorageKeys } from 'librechat-data-provider';import type { ExtendedFile } from '~/common';import { ParentSubagentsProvider } from '~/components/Chat/Subagents/ParentSubagentsProvider';@@ -44,7 +45,7 @@ export default function Presentation({const conversationId = useRecoilValue(store.conversationIdByIndex(0));const conversationEndpoint = useRecoilValue(store.effectiveEndpointByIndex(0));const conversationAgentId = useRecoilValue(store.conversationAgentIdByIndex(0));- const isSubmitting = useRecoilValue(store.isSubmittingFamily(0));+ const isSubmitting = useIsSubmitting(0);const isUndocked = useAtomValue(artifactsUndocked);const selectedSubagent = useAtomValue(activeSubagentPanel);const setSelectedSubagent = useSetAtom(activeSubagentPanel);diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsxindex 8731031b0f..a1baad5e63 100644--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx@@ -92,7 +92,6 @@ jest.mock('~/store', () => ({__esModule: true,default: {submissionByIndex: jest.fn(),- isSubmittingFamily: jest.fn(),centerFormOnLanding: {},},}));diff --git a/client/src/components/Chat/__tests__/Header.stacking.spec.tsx b/client/src/components/Chat/__tests__/Header.stacking.spec.tsxindex 220f1139db..4010fd0d85 100644--- a/client/src/components/Chat/__tests__/Header.stacking.spec.tsx+++ b/client/src/components/Chat/__tests__/Header.stacking.spec.tsx@@ -40,7 +40,6 @@ jest.mock('~/store', () => ({__esModule: true,default: {sidebarExpanded: {},- isSubmittingFamily: () => ({}),effectiveEndpointByIndex: () => 'effectiveEndpoint',},}));diff --git a/client/src/components/System/WakeLockManager.tsx b/client/src/components/System/WakeLockManager.tsxindex cae88d4ee8..12a7fb8bbf 100644--- a/client/src/components/System/WakeLockManager.tsx+++ b/client/src/components/System/WakeLockManager.tsx@@ -1,4 +1,6 @@+import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';+import { anySubmittingAtom } from '@librechat/chat/react';import useWakeLock from '~/hooks/useWakeLock';import store from '~/store';@@ -9,17 +11,17 @@ import store from '~/store';* device screens from sleeping or dimming during long-running operations.** The wake lock is only active when:- * 1. Any conversation is currently generating a response (anySubmittingSelector)+ * 1. Any conversation is currently generating a response (anySubmittingAtom)* 2. User has not disabled the feature in settings (keepScreenAwake preference)** This component is rendered at the root level of the application* to ensure wake lock state persists across all conversations and routes.** @see useWakeLock - The hook that manages the actual wake lock implementation- * @see anySubmittingSelector - Recoil selector tracking if any conversation is generating+ * @see anySubmittingAtom - Jotai atom tracking if any conversation is generating*/const WakeLockManager = () => {- const isSubmitting = useRecoilValue(store.anySubmittingSelector);+ const isSubmitting = useAtomValue(anySubmittingAtom);const keepScreenAwake = useRecoilValue(store.keepScreenAwake);const shouldPreventSleep = isSubmitting && keepScreenAwake;diff --git a/client/src/hooks/Audio/__tests__/useAutoplayTrigger.spec.tsx b/client/src/hooks/Audio/__tests__/useAutoplayTrigger.spec.tsxindex 2528440e0d..0abc74999c 100644--- a/client/src/hooks/Audio/__tests__/useAutoplayTrigger.spec.tsx+++ b/client/src/hooks/Audio/__tests__/useAutoplayTrigger.spec.tsx@@ -1,8 +1,10 @@import React from 'react';import { RecoilRoot } from 'recoil';+import { getDefaultStore } from 'jotai';import { renderHook } from '@testing-library/react';import { MemoryRouter, Routes, Route } from 'react-router-dom';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import { Constants, QueryKeys, ContentTypes } from 'librechat-data-provider';import type { TMessage, TConversation } from 'librechat-data-provider';import useAutoplayTrigger from '../useAutoplayTrigger';@@ -30,7 +32,7 @@ const renderTrigger = (message: TMessage) => {set(store.conversationByIndex(0), { conversationId } as TConversation);set(store.activeRunFamily(0), 'run-1');set(store.audioRunFamily(0), null);- set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);}}><Routes>@@ -44,6 +46,10 @@ const renderTrigger = (message: TMessage) => {return renderHook(() => useAutoplayTrigger(0), { wrapper }).result;};+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('useAutoplayTrigger', () => {it('plays a finalized answer', () => {expect(renderTrigger(assistantMessage).current.shouldPlay).toBe(true);diff --git a/client/src/hooks/Audio/useAutoplayTrigger.ts b/client/src/hooks/Audio/useAutoplayTrigger.tsindex 67049d58cc..8f3a5f3372 100644--- a/client/src/hooks/Audio/useAutoplayTrigger.ts+++ b/client/src/hooks/Audio/useAutoplayTrigger.ts@@ -1,4 +1,5 @@import { useRecoilValue } from 'recoil';+import { useIsSubmitting } from '@librechat/chat/react';import { getSpeechText } from 'librechat-data-provider';import type { TMessage } from 'librechat-data-provider';import { useLatestMessage } from '~/hooks/Messages/useLatestMessage';@@ -19,7 +20,7 @@ export type TAutoplayTrigger = {export default function useAutoplayTrigger(index: string | number = 0): TAutoplayTrigger {const activeRunId = useRecoilValue(store.activeRunFamily(index));const audioRunId = useRecoilValue(store.audioRunFamily(index));- const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));+ const isSubmitting = useIsSubmitting(index);const latestMessage = useLatestMessage(index);const shouldPlay = !!(diff --git a/client/src/hooks/Chat/__tests__/submitting.spec.tsx b/client/src/hooks/Chat/__tests__/submitting.spec.tsxnew file mode 100644index 0000000000..07ade0e282--- /dev/null+++ b/client/src/hooks/Chat/__tests__/submitting.spec.tsx@@ -0,0 +1,38 @@+import { getDefaultStore } from 'jotai';+import { act, renderHook } from '@testing-library/react';+import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';+import { isSubmittingFamily, useIsSubmitting, resetSubmitting } from '@librechat/chat/react';+import type { ReactNode } from 'react';+import store from '~/store';++const jotaiStore = getDefaultStore();+const wrapper = ({ children }: { children: ReactNode }) => <RecoilRoot>{children}</RecoilRoot>;++afterEach(() => {+ resetSubmitting(jotaiStore);+});++describe('useIsSubmitting beside a Recoil atom', () => {+ it('never commits the new Recoil text with the previous generating flag', () => {+ jotaiStore.set(isSubmittingFamily(0), true);+ const commits: Array<{ text: string; submitting: boolean }> = [];+ const { result } = renderHook(+ () => {+ const preset = useRecoilValue(store.presetByIndex(0));+ const submitting = useIsSubmitting(0);+ commits.push({ text: preset?.title ?? '', submitting });+ return useSetRecoilState(store.presetByIndex(0));+ },+ { wrapper },+ );++ act(() => {+ jotaiStore.set(isSubmittingFamily(0), false);+ result.current({ endpoint: null, title: 'next' });+ });++ const withNewText = commits.filter(({ text }) => text === 'next');+ expect(withNewText.length).toBeGreaterThan(0);+ expect(withNewText.every(({ submitting }) => !submitting)).toBe(true);+ });+});diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsxindex 984f0061b1..6b7962d272 100644--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx@@ -124,7 +124,6 @@ jest.mock('~/Providers/AgentsMapContext', () => ({jest.mock('~/store', () => ({__esModule: true,default: {- isSubmittingFamily: () => 'isSubmitting',messagesSiblingIdxFamily: () => 'messagesSiblingIdx',conversationByKeySelector: () => 'conversation',},diff --git a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsxindex 69856067e3..3c5309b15d 100644--- a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx@@ -1,9 +1,10 @@import React from 'react';+import { RecoilRoot, type MutableSnapshot } from 'recoil';import { getDefaultStore, useAtomValue, useSetAtom } from 'jotai';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 { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import { revealedQueuedTurnFamily, resetSteerFamilies } from '@librechat/chat/react';import {claimQueuedIntent,@@ -27,7 +28,6 @@ import {} from '~/hooks/Chat/queue';import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';import useQueueDrain from '../useQueueDrain';-import store from '~/store';const mockMarkFilesUsage = jest.fn();jest.mock('~/data-provider', () => ({@@ -60,7 +60,7 @@ function setup(function Harness() {setters.setRunEnd = useSetAtom(runEndByIndex(INDEX));- setters.setIsSubmitting = useSetRecoilState(store.isSubmittingFamily(INDEX));+ setters.setIsSubmitting = useSetAtom(isSubmittingFamily(INDEX));setters.setQueue = useSetAtom(queuedMessagesByConvoId(CONVO_ID));setters.queueRef = {current: useAtomValue(queuedMessagesByConvoId(CONVO_ID)),@@ -120,6 +120,10 @@ beforeEach(() => {resetSteerFamilies();});+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('useQueueDrain', () => {beforeEach(() => {getDefaultStore().set(recoveryDispositionsFamily(CONVO_ID), {});@@ -135,10 +139,10 @@ describe('useQueueDrain', () => {recoverySteerId: 'source',};const next: QueuedMessage = { id: 'ordinary', text: 'send after review', createdAt: 2 };- const { ask, setters } = setup(({ set }) => {+ const { ask, setters } = setup(() => {getDefaultStore().set(queuedMessagesByConvoId(Constants.NEW_CONVO), [held]);getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [next]);- set(store.isSubmittingFamily(INDEX), false);+ getDefaultStore().set(isSubmittingFamily(INDEX), false);});const end = runEnd({ startedAsNewConvo: true });act(() => setters.setRunEnd!(end));@@ -163,9 +167,9 @@ describe('useQueueDrain', () => {recoverySteerId: 'source',};const next: QueuedMessage = { id: 'ordinary', text: 'wait for next run', createdAt: 2 };- const { ask, setters } = setup(({ set }) => {+ const { ask, setters } = setup(() => {getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [held, next]);- set(store.isSubmittingFamily(INDEX), false);+ getDefaultStore().set(isSubmittingFamily(INDEX), false);});act(() => setters.setRunEnd!(runEnd({ outcome: 'aborted' })));await waitFor(() => expect(setters.runEnd).toBeNull());@@ -186,9 +190,9 @@ describe('useQueueDrain', () => {clientRequestId: 'same-attempt',};const firstEnd = runEnd();- const { ask, setters } = setup(({ set }) => {+ const { ask, setters } = setup(() => {getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [item]);- set(store.isSubmittingFamily(INDEX), false);+ getDefaultStore().set(isSubmittingFamily(INDEX), false);getDefaultStore().set(runEndByIndex(INDEX), firstEnd);});await waitFor(() => expect(setters.runEnd).toEqual(firstEnd));@@ -989,8 +993,8 @@ describe('useQueueDrain', () => {const wrapper = ({ children }: { children: React.ReactNode }) => (<QueryClientProvider client={queryClient}><RecoilRoot- initializeState={({ set }) => {- set(store.isSubmittingFamily(INDEX), true);+ initializeState={() => {+ getDefaultStore().set(isSubmittingFamily(INDEX), true);getDefaultStore().set(queuedMessagesByConvoId(CONVO_A), [queuedMessage('qa', 'send for A'),]);@@ -1010,7 +1014,7 @@ describe('useQueueDrain', () => {const { result, rerender } = renderHook(({ activeConversationId }: { activeConversationId: string }) => {setRunEnd = useSetAtom(runEndByIndex(INDEX));- setIsSubmitting = useSetRecoilState(store.isSubmittingFamily(INDEX));+ setIsSubmitting = useSetAtom(isSubmittingFamily(INDEX));useQueueDrain(INDEX, activeConversationId, ask);return {indexEnd: useAtomValue(runEndByIndex(INDEX)),@@ -1069,9 +1073,9 @@ describe('useQueueDrain', () => {});it('waits for isSubmitting to flip false before draining', async () => {- const { ask, setters } = setup(({ set }) => {+ const { ask, setters } = setup(() => {getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [queuedMessage('q1', 'deferred')]);- set(store.isSubmittingFamily(INDEX), true);+ getDefaultStore().set(isSubmittingFamily(INDEX), true);});act(() => {diff --git a/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx b/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsxindex 3e0713de01..06e5256f04 100644--- a/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx@@ -1,6 +1,7 @@import React from 'react';+import { RecoilRoot } from 'recoil';import { QueryKeys } from 'librechat-data-provider';-import { RecoilRoot, useSetRecoilState } from 'recoil';+import { isSubmittingFamily } from '@librechat/chat/react';import { act, renderHook, waitFor } from '@testing-library/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { Provider as JotaiProvider, createStore, useSetAtom } from 'jotai';@@ -19,7 +20,6 @@ import useQueuedTurnReveal, {} from '../useQueuedTurnReveal';import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';import { streamStatusQueryKey } from '~/data-provider/SSE/queries';-import store from '~/store';const CONVO_ID = 'convo-reveal';const RESPONSE_ID = 'response-1';@@ -182,7 +182,7 @@ describe('useQueuedTurnReveal', () => {let setSubmitting: (value: boolean) => void;let setEpoch: (value: number | null) => void;function StateProbe() {- setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));+ setSubmitting = useSetAtom(isSubmittingFamily(0));setEpoch = useSetAtom(activeGenerationCreatedAtByConvoId(CONVO_ID));return null;}@@ -214,8 +214,8 @@ describe('useQueuedTurnReveal', () => {setMessages,current,attach: (epoch: number, submitting = true) => {- setEpoch(epoch);setSubmitting(submitting);+ setEpoch(epoch);},setReceipts: (receipts: TAgentQueuedTurnReceipt[]) =>queryClient.setQueryData(agentQueuedTurnsQueryKey(CONVO_ID), receipts),diff --git a/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsxindex 5e74d2eb48..2a9b97d4ff 100644--- a/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useSteerRecovery.spec.tsx@@ -1,6 +1,7 @@import React from 'react';import { act, render, renderHook } from '@testing-library/react';import { getDefaultStore, useAtomValue, useSetAtom } from 'jotai';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import { RecoilRoot, useSetRecoilState, type MutableSnapshot } from 'recoil';import {pendingSteerCancelClientIdsFamily,@@ -41,7 +42,7 @@ const CONVO_ID = 'convo-steer-recovery';const seedRun = (snapshot: MutableSnapshot, submitting: boolean) => {snapshot.set(store.conversationKeysAtom, [0]);snapshot.set(store.conversationByIndex(0), { conversationId: CONVO_ID } as never);- snapshot.set(store.isSubmittingFamily(0), submitting);+ getDefaultStore().set(isSubmittingFamily(0), submitting);};/** Publishes a drain wake-up the way `ChatForm` does, so the retry path runs@@ -97,6 +98,10 @@ beforeEach(() => {resetSteerFamilies();});+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('useSteerRecovery', () => {beforeEach(() => {jest.clearAllMocks();@@ -428,8 +433,8 @@ describe('useSteerRecovery', () => {mockMutateAsync.mockResolvedValue({ steerId: 'srv-bound', preempt: false });const bind = async (generationProtocolVersion: 1 | 2) => {resetSteerFamilies();- const { result, unmount } = setup(({ set }) => {- set(store.isSubmittingFamily(0), false);+ const { result, unmount } = setup(() => {+ getDefaultStore().set(isSubmittingFamily(0), false);getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [{steerId: `local-v${generationProtocolVersion}`,@@ -546,7 +551,7 @@ describe('useSteerRecovery', () => {const Observer = () => {chips = useAtomValue(pendingSteersByConvoId(CONVO_ID));queue = useAtomValue(queuedMessagesByConvoId(CONVO_ID));- setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));+ setSubmitting = useSetAtom(isSubmittingFamily(0));return null;};const Tree = ({ live }: { live: boolean }) => (@@ -654,8 +659,8 @@ describe('useSteerRecovery', () => {const { result } = setup((snapshot) => {snapshot.set(store.conversationKeysAtom, [0, 1]);snapshot.set(store.conversationByIndex(1), { conversationId: CONVO_ID } as never);- snapshot.set(store.isSubmittingFamily(0), false);- snapshot.set(store.isSubmittingFamily(1), true);+ getDefaultStore().set(isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(1), true);getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [{ steerId: 'local-pane', text: 'second pane owns it', status: 'failed', createdAt: 4 },]);@@ -929,8 +934,8 @@ describe('useSteerRecovery', () => {sends them a second time: the resolver must do neither. */it('drops the chip without queueing when the apply event beat the ack', async () => {mockMutateAsync.mockResolvedValue(ack('srv-applied'));- const { result } = setup(({ set }) => {- set(store.isSubmittingFamily(0), false);+ const { result } = setup(() => {+ getDefaultStore().set(isSubmittingFamily(0), false);getDefaultStore().set(appliedSteerIdsByConvoId(CONVO_ID), ['srv-applied']);getDefaultStore().set(pendingSteersByConvoId(CONVO_ID), [{ steerId: 'local-applied', text: 'already injected', status: 'failed', createdAt: 3 },diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsxindex 6b491f32fc..d43d0f3c68 100644--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx@@ -2,6 +2,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 { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import {getDefaultStore,Provider as JotaiProvider,@@ -53,7 +54,6 @@ import { duringRunActionAtom } from '~/store/duringRun';import { applyPendingAction } from '~/utils/approval';import English from '~/locales/en/translation.json';import useQueueDrain from '../useQueueDrain';-import store from '~/store';const CONVO_ID = 'convo-steer-ui';const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;@@ -228,6 +228,10 @@ beforeEach(() => {getDefaultStore().set(pendingManualSkillsByConvoId(CONVO_ID), []);});+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('useSteering', () => {beforeEach(() => {getDefaultStore().set(duringRunActionAtom, 'steer');@@ -305,9 +309,9 @@ describe('useSteering', () => {const ask = jest.fn();const wrapper = ({ children }: { children: React.ReactNode }) => (<RecoilRoot- initializeState={withActiveGeneration(({ set }) => {+ initializeState={withActiveGeneration(() => {getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [item]);- set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);})}>{children}@@ -396,9 +400,9 @@ describe('useSteering', () => {const ask = jest.fn();const wrapper = ({ children }: { children: React.ReactNode }) => (<RecoilRoot- initializeState={withActiveGeneration(({ set }) => {+ initializeState={withActiveGeneration(() => {getDefaultStore().set(queuedMessagesByConvoId(CONVO_ID), [held, first, second]);- set(store.isSubmittingFamily(0), false);+ getDefaultStore().set(isSubmittingFamily(0), false);})}>{children}@@ -1613,8 +1617,8 @@ describe('useSteering', () => {const sendNow = jest.fn();const wrapper = ({ children }: { children: React.ReactNode }) => (<RecoilRoot- initializeState={withActiveGeneration(({ set }) => {- set(store.isSubmittingFamily(0), false);+ initializeState={withActiveGeneration(() => {+ getDefaultStore().set(isSubmittingFamily(0), false);getDefaultStore().set(runEndByIndex(0), {conversationId: CONVO_ID,outcome: 'completed',diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.tsindex d5e5719a33..7a57f91205 100644--- a/client/src/hooks/Chat/useChatFunctions.ts+++ b/client/src/hooks/Chat/useChatFunctions.ts@@ -1,11 +1,10 @@import { useCallback, useEffect, useRef } from 'react';import { cloneDeep } from 'lodash';-import { useSetRecoilState } from 'recoil';import { useStore, useSetAtom } from 'jotai';import { useNavigate } from 'react-router-dom';import { useQueryClient } from '@tanstack/react-query';import { hasPendingAssistantParent } from '@librechat/chat';-import { revealedQueuedTurnFamily } from '@librechat/chat/react';+import { revealedQueuedTurnFamily, isSubmittingFamily } from '@librechat/chat/react';import {Constants,QueryKeys,@@ -46,7 +45,6 @@ import { isHistoryRevalidating } from './ask/guards';import { createRegenerate } from './ask/regenerate';import useUserKey from '~/hooks/Input/useUserKey';import { buildTurn } from './ask/turn';-import store from '~/store';export {getRegenerateTargetResponseMessage,@@ -88,7 +86,7 @@ export default function useChatFunctions({const agentsMap = useAgentsMapContext();const { isTemporary, config, auth, getEphemeralAgent, addedConversation } = useChatSettings();const { getExpiry } = useUserKey(immutableConversation?.endpoint ?? '');- const setIsSubmitting = useSetRecoilState(store.isSubmittingFamily(index));+ const setIsSubmitting = useSetAtom(isSubmittingFamily(index));const setSubmissionStart = useSetAtom(submissionStartFamily(index));const setShowStopButton = useSetAtom(showStopButtonByIndex(index));const focusRegeneratedResponse = useFocusRegeneratedResponse();diff --git a/client/src/hooks/Chat/useChatHelpers.ts b/client/src/hooks/Chat/useChatHelpers.tsindex 1087d0011b..8ca896dc20 100644--- a/client/src/hooks/Chat/useChatHelpers.ts+++ b/client/src/hooks/Chat/useChatHelpers.ts@@ -6,6 +6,8 @@ import { Constants, QueryKeys, isAssistantsEndpoint } from 'librechat-data-proviimport {activeGenerationCreatedAtByConvoId,activeGenerationProtocolVersionByConvoId,+ isSubmittingFamily,+ useIsSubmitting,} from '@librechat/chat/react';import type { TMessage } from 'librechat-data-provider';import type { ChatContract } from './contract';@@ -96,7 +98,8 @@ export default function useChatHelpers(index = 0, paramId?: string): ChatContracFalling back to conversationId (Recoil) only if paramId is not available */const queryParam = paramId === 'new' ? paramId : (paramId ?? conversationId ?? '');- const [isSubmitting, setIsSubmitting] = useRecoilState(store.isSubmittingFamily(index));+ const isSubmitting = useIsSubmitting(index);+ const setIsSubmitting = useSetAtom(isSubmittingFamily(index));const latestMessage = useLatestMessage(index, queryParam);const latestMessageId = useLatestMessageId(index, queryParam) ?? undefined;diff --git a/client/src/hooks/Chat/useQueueDrain.ts b/client/src/hooks/Chat/useQueueDrain.tsindex b955f73035..17cb11df40 100644--- a/client/src/hooks/Chat/useQueueDrain.ts+++ b/client/src/hooks/Chat/useQueueDrain.ts@@ -1,7 +1,6 @@import { useRef, useEffect, useMemo, useCallback } from 'react';-import { useRecoilValue } from 'recoil';import { useAtomValue, useStore } from 'jotai';-import { revealedQueuedTurnFamily } from '@librechat/chat/react';+import { revealedQueuedTurnFamily, useIsSubmitting } from '@librechat/chat/react';import { Constants, DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';import { acquireQueueSendLock, releaseQueueSendLock, hasQueuedIntent } from '@librechat/chat';import {@@ -35,7 +34,6 @@ import {import { useChatSettings } from '~/Providers/ChatSettingsContext';import { useMarkFilesUsageMutation } from '~/data-provider';import { mergeQueuedMessages } from '~/utils/queue';-import store from '~/store';/*** Auto-sends queued follow-up messages when a run finishes.@@ -63,7 +61,7 @@ export default function useQueueDrain(const parkedRunEnd = useAtomValue(pendingRunEndByConvoId(activeConversationId ?? Constants.NEW_CONVO),);- const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));+ const isSubmitting = useIsSubmitting(index);/** Keyed by pane, because the contended resource is this pane's submission* slot: the rail's "Send now" reaches the same `ask` through the composer. */const sendLockKey = String(index);diff --git a/client/src/hooks/Chat/useQueuedTurnReveal.ts b/client/src/hooks/Chat/useQueuedTurnReveal.tsindex 29df7c508f..d53a5b3a54 100644--- a/client/src/hooks/Chat/useQueuedTurnReveal.ts+++ b/client/src/hooks/Chat/useQueuedTurnReveal.ts@@ -1,5 +1,4 @@import { useCallback, useEffect, useSyncExternalStore } from 'react';-import { useRecoilValue } from 'recoil';import { useStore, useAtomValue } from 'jotai';import { QueryKeys } from 'librechat-data-provider';import { useQueryClient } from '@tanstack/react-query';@@ -7,6 +6,8 @@ import { isAdmissibleQueuedTurn } from '@librechat/chat';import {revealedQueuedTurnFamily,activeGenerationCreatedAtByConvoId,+ useIsSubmitting,+ isSubmittingFamily,} from '@librechat/chat/react';import type { TMessage, TAgentQueuedTurnReceipt } from 'librechat-data-provider';import type { RevealedQueuedTurn } from '@librechat/chat/react';@@ -14,7 +15,6 @@ import type { StreamStatusResponse } from '~/data-provider/SSE/queries';import type { QueuedMessage, RunEnd } from '~/hooks/Chat/queue';import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';import { streamStatusQueryKey } from '~/data-provider/SSE/queries';-import store from '~/store';export { selectQueuedTurnReveal } from '@librechat/chat';@@ -68,7 +68,7 @@ export default function useQueuedTurnReveal(const queryClient = useQueryClient();const revealKey = conversationId ?? '';const reveal = useAtomValue(revealedQueuedTurnFamily(revealKey));- const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));+ const isSubmitting = useIsSubmitting(index);const activeEpoch = useAtomValue(activeGenerationCreatedAtByConvoId(revealKey));const readHandoff = useCallback((intent: RevealedQueuedTurn) => {@@ -78,6 +78,7 @@ export default function useQueuedTurnReveal(const status = queryClient.getQueryData<StreamStatusResponse>(streamStatusQueryKey(revealKey),);+ const submitting = jotaiStore.get(isSubmittingFamily(index));let generationCreatedAt = intent.generationCreatedAt;let waiting = false;for (const receipt of receipts ?? []) {@@ -99,7 +100,7 @@ export default function useQueuedTurnReveal(settled:(receipts != null && shouldRollbackReveal(receipts, intent)) ||(generationCreatedAt != null &&- ((isSubmitting && activeEpoch != null && activeEpoch > generationCreatedAt) ||+ ((submitting && activeEpoch != null && activeEpoch > generationCreatedAt) ||(!waiting &&status?.active === false &&(status.status === 'complete' ||@@ -109,7 +110,7 @@ export default function useQueuedTurnReveal(status.createdAt > generationCreatedAt))),};},- [queryClient, revealKey, isSubmitting, activeEpoch],+ [queryClient, jotaiStore, index, revealKey, activeEpoch],);const subscribe = useCallback((notify: () => void) =>@@ -182,7 +183,7 @@ export default function useQueuedTurnReveal(} else if (handoff.generationCreatedAt !== reveal.generationCreatedAt) {jotaiStore.set(family, { ...reveal, generationCreatedAt: handoff.generationCreatedAt });}- }, [jotaiStore, revealKey, reveal, readHandoff, handoffVersion]);+ }, [jotaiStore, revealKey, reveal, readHandoff, handoffVersion, isSubmitting]);return revealQueuedTurn;}diff --git a/client/src/hooks/Chat/useSteerRecovery.ts b/client/src/hooks/Chat/useSteerRecovery.tsindex ba63bb2289..c2c464d85d 100644--- a/client/src/hooks/Chat/useSteerRecovery.ts+++ b/client/src/hooks/Chat/useSteerRecovery.ts@@ -1,8 +1,10 @@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 {+ isSubmittingFamily,+ pendingSteersByConvoId,+ pendingSteerCancelClientIdsFamily,+} from '@librechat/chat/react';import type { PendingSteer } from '~/hooks/Chat/queue';import {getSteerErrorCode,@@ -15,7 +17,6 @@ import { carriedSteerContext, isLegacyDeliveryUncertain } from '~/utils';import { useChatSettings } from '~/Providers/ChatSettingsContext';import { useSteerRehome } from '~/hooks/Chat/useSteerCancel';import useSteerConvert from '~/hooks/Chat/useSteerConvert';-import store from '~/store';/*** Retry or re-route a pending steer from OUTSIDE the composer. The thread's@@ -36,28 +37,25 @@ export default function useSteerRecovery(conversationId: string) {* user navigates away from a run that is still going, and treating that as* the end queued the accepted steer as a follow-up on top of the injection* the server was already making. */- const isRunOver = useCallback(- (snapshot: Snapshot) => {- let held = false;- for (const pane of getPaneConversations()) {- if (pane.conversationId !== conversationId) {- continue;- }- /* Comparison mode can hold one conversation in several panes, and only+ const isRunOver = useCallback(() => {+ let held = false;+ for (const pane of getPaneConversations()) {+ if (pane.conversationId !== conversationId) {+ continue;+ }+ /* Comparison mode can hold one conversation in several panes, and onlythe pane that owns the run is submitting: any live pane means therun is still going, whichever slot comes first. */- if (snapshot.getLoadable(store.isSubmittingFamily(pane.index)).getValue() === true) {- return false;- }- held = true;+ if (jotaiStore.get(isSubmittingFamily(pane.index)) === true) {+ return false;}- /* Held by no slot at all: the user navigated to another chat, which says+ held = true;+ }+ /* Held by no slot at all: the user navigated to another chat, which saysnothing about the run they left behind. Reading that as the end is thesame mistake as reading the unmount as the end, one step further out. */- return held;- },- [conversationId, getPaneConversations],- );+ return held;+ }, [conversationId, getPaneConversations, jotaiStore]);const markStatus = useCallback((steerId: string, status: PendingSteer['status']) => {@@ -95,10 +93,9 @@ export default function useSteerRecovery(conversationId: string) {** @returns true when the caller must route the steer into the queue.*/- const acknowledgeRetry = useRecoilCallback(- ({ snapshot }) =>- (localId: string, steer: PendingSteer): boolean =>- resolveAcknowledgedSteer(jotaiStore, conversationId, localId, steer, isRunOver(snapshot)),+ const acknowledgeRetry = useCallback(+ (localId: string, steer: PendingSteer): boolean =>+ resolveAcknowledgedSteer(jotaiStore, conversationId, localId, steer, isRunOver()),[conversationId, isRunOver, jotaiStore],);diff --git a/client/src/hooks/Config/useClearStates.ts b/client/src/hooks/Config/useClearStates.tsindex d4886b1f5f..0b8d8e355b 100644--- a/client/src/hooks/Config/useClearStates.ts+++ b/client/src/hooks/Config/useClearStates.ts@@ -1,6 +1,7 @@import { useStore } from 'jotai';import { useRecoilCallback } from 'recoil';import { Constants } from 'librechat-data-provider';+import { isSubmittingFamily } from '@librechat/chat/react';import {getReasoningStateKey,clearPendingComposerContext,@@ -60,7 +61,7 @@ export default function useClearStates() {jotaiStore.set(showStopButtonByIndex(key), false);jotaiStore.set(abortScrollFamily(key), false);jotaiStore.set(submissionStartFamily(key), null);- reset(store.isSubmittingFamily(key));+ jotaiStore.set(isSubmittingFamily(key), false);reset(store.optionSettingsFamily(key));reset(store.showPopoverFamily(key));reset(store.showMentionPopoverFamily(key));diff --git a/client/src/hooks/Conversations/__tests__/useNewChat.spec.ts b/client/src/hooks/Conversations/__tests__/useNewChat.spec.tsindex 2ec286b090..4ded82c257 100644--- a/client/src/hooks/Conversations/__tests__/useNewChat.spec.ts+++ b/client/src/hooks/Conversations/__tests__/useNewChat.spec.ts@@ -211,7 +211,6 @@ jest.mock('~/store', () => ({default: {conversationIdByIndex: (index: number) => `conversationIdByIndex-${index}`,filesByIndex: (index: number) => `files-by-index-${index}`,- isSubmittingFamily: (index: number) => `isSubmitting-${index}`,},}));diff --git a/client/src/hooks/Conversations/useTemporaryChat.ts b/client/src/hooks/Conversations/useTemporaryChat.tsindex 5ba678bfc3..d038190be6 100644--- a/client/src/hooks/Conversations/useTemporaryChat.ts+++ b/client/src/hooks/Conversations/useTemporaryChat.ts@@ -1,5 +1,6 @@import { useCallback } from 'react';import { useRecoilValue } from 'recoil';+import { useIsSubmitting } from '@librechat/chat/react';import { Constants, isForcedTemporaryRetention } from 'librechat-data-provider';import { useChatSettings } from '~/Providers/ChatSettingsContext';import store from '~/store';@@ -18,7 +19,7 @@ export type UseTemporaryChatResult = {export default function useTemporaryChat(): UseTemporaryChatResult {const { isTemporary, setIsTemporary, config } = useChatSettings();const conversation = useRecoilValue(store.conversationByIndex(0));- const isSubmitting = useRecoilValue(store.isSubmittingFamily(0));+ const isSubmitting = useIsSubmitting(0);const isEnforced = isForcedTemporaryRetention(config.retentionMode);const toggle = useCallback(() => {diff --git a/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsx b/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsxindex 73a6e1f359..ffa17d53a7 100644--- a/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsx+++ b/client/src/hooks/Files/__tests__/useAttachmentPreviewSync.spec.tsx@@ -17,8 +17,10 @@import { useEffect } from 'react';import { Tools } from 'librechat-data-provider';+import { getDefaultStore, useSetAtom } from 'jotai';import { renderHook } from '@testing-library/react';import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';+import { isSubmittingFamily, resetSubmitting } from '@librechat/chat/react';import type {TAttachment,TFile,@@ -104,7 +106,7 @@ function setup({* so we have to populate both for the selector to fire. */const setMap = useSetRecoilState(store.messageAttachmentsMap);const setKeys = useSetRecoilState(store.conversationKeysAtom);- const setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));+ const setSubmitting = useSetAtom(isSubmittingFamily(0));useEffect(() => {if (seedLiveMap) {setMap({ [messageId]: seedEntries ?? [attachment] });@@ -193,8 +195,8 @@ function setupWithTransitions(initialProps: { attachment: makeAttachment({ status: 'pending' }) },wrapper: ({ children }: { children: ReactNode }) => (<RecoilRoot- initializeState={(snap) => {- snap.set(store.isSubmittingFamily(0), isSubmittingAtMount);+ initializeState={() => {+ getDefaultStore().set(isSubmittingFamily(0), isSubmittingAtMount);}}><FlagProbe id={fileId} />@@ -219,6 +221,10 @@ function setupWithTransitions(};}+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('useAttachmentPreviewSync', () => {it('enables polling whenever status=pending (no longer gated on isSubmitting)', () => {const ctx = setup({diff --git a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsxindex e430f2ffcf..bcfc84f1de 100644--- a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx+++ b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx@@ -1,8 +1,15 @@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 { Provider as JotaiProvider, createStore, useAtomValue, useSetAtom } from 'jotai';+import {+ Provider as JotaiProvider,+ createStore,+ useAtomValue,+ useSetAtom,+ getDefaultStore,+} from 'jotai';import {revealedQueuedTurnFamily,pendingSteersByConvoId,@@ -164,13 +171,13 @@ function renderUseResumeOnLoad({const initializeState = (snapshot: MutableSnapshot) => {snapshot.set(store.conversationByIndex(0), buildConversation(conversationId));snapshot.set(store.submissionByIndex(0), submission);- snapshot.set(store.isSubmittingFamily(0), isSubmitting);+ jotaiStore.set(isSubmittingFamily(0), isSubmitting);};const SubmissionProbe = () => {const currentSubmission = useRecoilValue(store.submissionByIndex(0));setSubmissionState = useSetRecoilState(store.submissionByIndex(0));- setIsSubmittingState = useSetRecoilState(store.isSubmittingFamily(0));+ setIsSubmittingState = useSetAtom(isSubmittingFamily(0));setAttachedEpochState = useSetAtom(activeGenerationCreatedAtByConvoId(conversationId));onSubmission?.(currentSubmission);return null;@@ -230,6 +237,10 @@ function renderUseResumeOnLoad({beforeEach(() => resetQueueFamilies());+afterEach(() => {+ resetSubmitting(getDefaultStore());+});+describe('useResumeOnLoad', () => {beforeEach(() => {jest.spyOn(console, 'log').mockImplementation(() => undefined);diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/client/src/hooks/SSE/useResumeOnLoad.tsindex 8b8c82e6a3..660048b22b 100644--- a/client/src/hooks/SSE/useResumeOnLoad.ts+++ b/client/src/hooks/SSE/useResumeOnLoad.ts@@ -2,16 +2,17 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';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,isAssistantsEndpoint,isForcedTemporaryRetention,} from 'librechat-data-provider';+import {+ revealedQueuedTurnFamily,+ activeGenerationCreatedAtByConvoId,+ useIsSubmitting,+} from '@librechat/chat/react';import {hasSubmissionUserMessage,getGenerationProtocolVersion,@@ -75,7 +76,7 @@ export default function useResumeOnLoad(const setSubmission = useSetRecoilState(store.submissionByIndex(runIndex));const setSubmissionStart = useSetAtom(submissionStartFamily(runIndex));const currentSubmission = useRecoilValue(store.submissionByIndex(runIndex));- const isSubmitting = useRecoilValue(store.isSubmittingFamily(runIndex));+ const isSubmitting = useIsSubmitting(runIndex);const attachedGenerationCreatedAt = useAtomValue(activeGenerationCreatedAtByConvoId(conversationId ?? ''),);diff --git a/client/src/hooks/useKeyboardShortcuts.ts b/client/src/hooks/useKeyboardShortcuts.tsindex 4ce66c1d77..ffd82ad37b 100644--- a/client/src/hooks/useKeyboardShortcuts.ts+++ b/client/src/hooks/useKeyboardShortcuts.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo } from 'react';import { useSetAtom } from 'jotai';import copy from 'copy-to-clipboard';import { useToastContext } from '@librechat/client';+import { useIsSubmitting } from '@librechat/chat/react';import { useMatch, useNavigate } from 'react-router-dom';import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';import { PermissionTypes, Permissions, isForcedTemporaryRetention } from 'librechat-data-provider';@@ -545,7 +546,7 @@ export function useShortcutActions(): ShortcutAction[] {const routeMatch = useMatch('/c/:conversationId');const routeConvoId = routeMatch?.params.conversationId ?? null;const conversation = useRecoilValue(store.conversationByIndex(0));- const isSubmitting = useRecoilValue(store.isSubmittingFamily(0));+ const isSubmitting = useIsSubmitting(0);const sidebarExpanded = useRecoilValue(store.sidebarExpanded);const { setSidebarOpen, toggleSidebar } = useSidebarToggle();const setShowShortcutsDialog = useSetRecoilState(store.showShortcutsDialog);diff --git a/client/src/hooks/useWakeLock.ts b/client/src/hooks/useWakeLock.tsindex b4eed3ab30..a071947867 100644--- a/client/src/hooks/useWakeLock.ts+++ b/client/src/hooks/useWakeLock.ts@@ -42,7 +42,7 @@ const DEBUG_WAKE_LOCK = false;** @example* ```tsx- * const isGeneratingResponse = useRecoilValue(anySubmittingSelector);+ * const isGeneratingResponse = useAtomValue(anySubmittingAtom);* useWakeLock(isGeneratingResponse);* ```*diff --git a/client/src/store/families.ts b/client/src/store/families.tsindex 1a5a93ac39..42798dabf4 100644--- a/client/src/store/families.ts+++ b/client/src/store/families.ts@@ -178,30 +178,6 @@ const presetByIndex = atomFamily<TPreset | null, string | number>({default: null,});-const isSubmittingFamily = atomFamily({- key: 'isSubmittingByIndex',- default: false,- effects: [- ({ onSet, node }) => {- onSet(async (newValue) => {- const key = Number(node.key.split(Constants.COMMON_DIVIDER)[1]);- logger.log('message_stream', 'Recoil Effect: Setting isSubmittingByIndex', {- key,- newValue,- });- });- },- ],-});--const anySubmittingSelector = selector<boolean>({- key: 'anySubmittingSelector',- get: ({ get }) => {- const keys = get(conversationKeysAtom);- return keys.some((key) => get(isSubmittingFamily(key)) === true);- },-});-const optionSettingsFamily = atomFamily<TOptionSettings, string | number>({key: 'optionSettingsByIndex',default: {},@@ -382,10 +358,8 @@ export default {filesByIndex,presetByIndex,submissionByIndex,- isSubmittingFamily,optionSettingsFamily,showPopoverFamily,- anySubmittingSelector,conversationIdByIndex,conversationEndpointByIndex,effectiveEndpointByIndex,diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.tsindex 64bce9b510..9a158b87a0 100644--- a/packages/chat/src/react.ts+++ b/packages/chat/src/react.ts@@ -50,3 +50,10 @@ export {pendingReasoningOverrideFamily,clearPendingReasoningOverrides,} from './react/composer';+export {+ isSubmittingFamily,+ anySubmittingAtom,+ resetSubmitting,+ useIsSubmitting,+} from './react/submission';+export type { PaneIndex } from './react/submission';diff --git a/packages/chat/src/react/__tests__/submission.spec.tsx b/packages/chat/src/react/__tests__/submission.spec.tsxnew file mode 100644index 0000000000..d32cf479c8--- /dev/null+++ b/packages/chat/src/react/__tests__/submission.spec.tsx@@ -0,0 +1,66 @@+/**+ * @jest-environment jsdom+ */+import { useAtom, useAtomValue } from 'jotai';+import { act, render, renderHook, screen } from '@testing-library/react';+import { anySubmittingAtom, isSubmittingFamily } from '../submission';++function Indicator({ index }: { index: number }) {+ const isSubmitting = useAtomValue(isSubmittingFamily(index));+ return <p>{isSubmitting ? 'streaming' : 'idle'}</p>;+}++describe('isSubmittingFamily', () => {+ it('shows a component and a hook in the same store the same value', () => {+ render(<Indicator index={10} />);+ const { result } = renderHook(() => useAtom(isSubmittingFamily(10)));+ expect(screen.getByText('idle')).toBeInTheDocument();++ act(() => result.current[1](true));++ expect(result.current[0]).toBe(true);+ expect(screen.getByText('streaming')).toBeInTheDocument();++ act(() => result.current[1](false));+ expect(screen.getByText('idle')).toBeInTheDocument();+ });++ it('accepts an updater function', () => {+ const { result } = renderHook(() => useAtom(isSubmittingFamily(11)));+ act(() => result.current[1]((previous) => !previous));+ expect(result.current[0]).toBe(true);+ act(() => result.current[1](false));+ });++ it('keeps panes independent', () => {+ const { result } = renderHook(() => ({+ main: useAtom(isSubmittingFamily(12)),+ added: useAtom(isSubmittingFamily(13)),+ }));+ act(() => result.current.added[1](true));+ expect(result.current.added[0]).toBe(true);+ expect(result.current.main[0]).toBe(false);+ act(() => result.current.added[1](false));+ });+});++describe('anySubmittingAtom', () => {+ it('is true while any pane generates, including one first used after the first read', () => {+ const { result } = renderHook(() => ({+ any: useAtomValue(anySubmittingAtom),+ first: useAtom(isSubmittingFamily(20)),+ second: useAtom(isSubmittingFamily(21)),+ }));+ expect(result.current.any).toBe(false);++ act(() => result.current.second[1](true));+ expect(result.current.any).toBe(true);++ act(() => result.current.first[1](true));+ act(() => result.current.second[1](false));+ expect(result.current.any).toBe(true);++ act(() => result.current.first[1](false));+ expect(result.current.any).toBe(false);+ });+});diff --git a/packages/chat/src/react/submission.ts b/packages/chat/src/react/submission.tsnew file mode 100644index 0000000000..8451efc077--- /dev/null+++ b/packages/chat/src/react/submission.ts@@ -0,0 +1,58 @@+import { atomFamily } from 'jotai/utils';+import { atom, useAtomValue, useStore } from 'jotai';+import type { Atom, WritableAtom, createStore } from 'jotai';+import type { SetStateAction } from 'react';++/** Pane index a generation runs in: `0` for the main chat, `1` for the added one. */+export type PaneIndex = string | number;++type Store = ReturnType<typeof createStore>;++const submittingIndexesAtom = atom<ReadonlySet<PaneIndex>>(new Set<PaneIndex>());++/** Whether a generation is in flight in the pane at this index. */+export type SubmittingAtom = WritableAtom<boolean, [SetStateAction<boolean>], void>;++export const isSubmittingFamily: (index: PaneIndex) => SubmittingAtom = atomFamily(+ (index: PaneIndex): SubmittingAtom => {+ const valueAtom = atom(false);+ return atom(+ (get) => get(valueAtom),+ (get, set, update: SetStateAction<boolean>) => {+ const previous = get(valueAtom);+ const next = typeof update === 'function' ? update(previous) : update;+ if (next === previous) {+ return;+ }+ set(valueAtom, next);+ const indexes = new Set(get(submittingIndexesAtom));+ if (next) {+ indexes.add(index);+ } else {+ indexes.delete(index);+ }+ set(submittingIndexesAtom, indexes);+ },+ );+ },+);++/** Whether any pane is generating, for what must stay awake while a reply streams. */+export const anySubmittingAtom: Atom<boolean> = atom((get) => get(submittingIndexesAtom).size > 0);++/** Clears every pane's in-flight flag in the given store, for teardown between runs. */+export function resetSubmitting(store: Pick<Store, 'get' | 'set'>): void {+ store.get(submittingIndexesAtom).forEach((index) => store.set(isSubmittingFamily(index), false));+}++/**+ * Whether the pane at this index is generating, read from the store at render time.+ * A render triggered by another state library (the app's Recoil atoms) can otherwise see this+ * flag one commit old, so a decision that combines the two would act on a mismatched pair.+ * The subscription still re-renders the caller when the flag changes.+ */+export function useIsSubmitting(index: PaneIndex): boolean {+ const store = useStore();+ useAtomValue(isSubmittingFamily(index));+ return store.get(isSubmittingFamily(index));+}