Skip to content

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

🧲 refactor: Move Pending Quotes and Manual Skills onto Jotai (#17126)

Marco Berettac43fba75aeff
diff --git a/client/src/components/Chat/Input/Composer/state.ts b/client/src/components/Chat/Input/Composer/state.ts
index 712b716e77..7fe26ac389 100644
--- a/client/src/components/Chat/Input/Composer/state.ts
+++ b/client/src/components/Chat/Input/Composer/state.ts
@@ -19,6 +19,30 @@ export const pendingReasoningOverrideFamily = atomFamily((_conversationId: strin
atom<TMessage['reasoningOverride']>(undefined),
);
+/**
+ * Per-conversation queue of skill names the user invoked manually via the
+ * `$` popover for the next submission. Structured channel that the submit
+ * pipeline (`useChatFunctions.ask`) drains and pins onto the user message's
+ * `manualSkills` field (also echoed at the top of the payload for the
+ * runtime resolver), then resets to `[]`. Compose-time chips above the
+ * textarea read this atom directly so users see (and can dismiss) their
+ * current selection before hitting send.
+ */
+export const pendingManualSkillsByConvoId = atomFamily((_conversationId: string) =>
+ atom<string[]>([]),
+);
+
+/**
+ * Per-conversation queue of verbatim excerpts the user quoted via the
+ * "Add to chat" selection popup for the next submission. The submit pipeline
+ * (`useChatFunctions.ask`) drains this onto the user message's `quotes` field
+ * (which the backend merges into the model-facing text and persists for the
+ * `MessageQuotes` UI), then resets to `[]`. Compose-time chips above the
+ * textarea read this atom directly so users can see and dismiss each quote
+ * before sending.
+ */
+export const pendingQuotesByConvoId = atomFamily((_conversationId: string) => atom<string[]>([]));
+
/** Landing-page lift is composer-owned UI state, scoped to its split pane. */
export const composerLiftFamily = atomFamily((_index: number) => atom(0));
@@ -38,3 +62,22 @@ export const clearPendingReasoningOverrides = (
pendingReasoningOverrideFamily.remove(key);
}
};
+
+/** Release every staged quote and manual skill pick except under the `keep`
+ * keys. Like a reasoning selection, they survive navigation, so conversations
+ * no longer on screen still hold some; clearing only the mounted panes would
+ * carry them across a sign-out. */
+export const clearPendingComposerContext = (
+ jotaiStore: ReturnType<typeof createStore>,
+ keep: ReadonlySet<string> = new Set(),
+) => {
+ for (const family of [pendingQuotesByConvoId, pendingManualSkillsByConvoId]) {
+ for (const key of Array.from(family.getParams())) {
+ if (keep.has(key)) {
+ continue;
+ }
+ jotaiStore.set(family(key), []);
+ family.remove(key);
+ }
+ }
+};
diff --git a/client/src/components/Chat/Input/QuoteButton.tsx b/client/src/components/Chat/Input/QuoteButton.tsx
index 69728496e0..83d524a7fd 100644
--- a/client/src/components/Chat/Input/QuoteButton.tsx
+++ b/client/src/components/Chat/Input/QuoteButton.tsx
@@ -1,11 +1,11 @@
import { memo, useRef, useEffect, useCallback, useLayoutEffect } from 'react';
+import { useSetAtom } from 'jotai';
import { createPortal } from 'react-dom';
import { TextQuote } from 'lucide-react';
-import { useSetRecoilState } from 'recoil';
+import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { cn, MAX_QUOTE_COUNT } from '~/utils';
import { mainTextareaId } from '~/common';
import { useLocalize } from '~/hooks';
-import store from '~/store';
/** Only selections fully inside a rendered chat message get the popup. */
const MESSAGE_SELECTOR = '.message-render';
@@ -329,7 +329,7 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
const pressedTextRef = useRef<string | null>(null);
/** Set by the listener effect so the press handlers can dismiss the popup. */
const hideRef = useRef<() => void>(() => undefined);
- const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
+ const setQuotes = useSetAtom(pendingQuotesByConvoId(conversationId));
/** Selection and scroll events must not enter React's commit/selection-restoration
* path. Keep the portal mounted and update only its transient presentation. */
diff --git a/client/src/components/Chat/Input/SkillsCommand.tsx b/client/src/components/Chat/Input/SkillsCommand.tsx
index f8823cdb6e..bc8ead6dbd 100644
--- a/client/src/components/Chat/Input/SkillsCommand.tsx
+++ b/client/src/components/Chat/Input/SkillsCommand.tsx
@@ -7,6 +7,7 @@ import { Input, Spinner, useCombobox, useRemScale } from '@librechat/client';
import { SkillsScope, resolveAgentSkillsScope } from 'librechat-data-provider';
import type { TSkillSummary } from 'librechat-data-provider';
import type { MentionOption } from '~/common';
+import { pendingManualSkillsByConvoId } from '~/components/Chat/Input/Composer/state';
import useInitPopoverInput from '~/hooks/Input/useInitPopoverInput';
import { useLocalize, useSkillActiveState } from '~/hooks';
import { useSkillsInfiniteQuery } from '~/data-provider';
@@ -15,7 +16,6 @@ import { useAgentsMapContext } from '~/Providers';
import { ephemeralAgentByConvoId } from '~/store';
import { isEphemeralAgent } from '~/common';
import MentionItem from './MentionItem';
-import store from '~/store';
const commandChar = '$';
const ROW_HEIGHT = 44;
@@ -92,9 +92,7 @@ function SkillsCommandContent({
const remScale = useRemScale();
const setShowSkillsPopover = useSetAtom(showSkillsPopoverFamily(index));
const setEphemeralAgent = useSetRecoilState(ephemeralAgentByConvoId(conversationId));
- const setPendingManualSkills = useSetRecoilState(
- store.pendingManualSkillsByConvoId(conversationId),
- );
+ const setPendingManualSkills = useSetAtom(pendingManualSkillsByConvoId(conversationId));
const agentsMap = useAgentsMapContext();
const { isActive } = useSkillActiveState();
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
index d053229d04..9614e41aac 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
@@ -1,6 +1,7 @@
import React, { Profiler, useMemo, useState } from 'react';
import '@testing-library/jest-dom';
import { DndProvider } from 'react-dnd';
+import { getDefaultStore } from 'jotai';
import { useForm } from 'react-hook-form';
import { RecoilRoot, useRecoilState } from 'recoil';
import userEvent from '@testing-library/user-event';
@@ -12,6 +13,7 @@ import { render, screen, within, waitFor, fireEvent } from '@testing-library/rea
import type { TFile, TFileUpload, TConversation } from 'librechat-data-provider';
import type { ChatFormValues, TAskFunction } from '~/common';
import type { TranslationKeys } from '~/hooks/useLocalize';
+import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { getDraft, getPendingDraftId, setDraft } from '~/utils';
import { ChatContext, ChatFormProvider } from '~/Providers';
import { AuthContextProvider } from '~/hooks/AuthContext';
@@ -169,13 +171,13 @@ function renderComposer({
queryClient.setQueryData<TFile[]>([QueryKeys.files], []);
queryClient.setQueryData([QueryKeys.endpoints], { [EModelEndpoint.openAI]: { order: 0 } });
+ getDefaultStore().set(pendingQuotesByConvoId(conversation.conversationId ?? ''), quotes);
return render(
<QueryClientProvider client={queryClient}>
<RecoilRoot
initializeState={({ set }) => {
set(store.isSubmittingFamily(0), submitting);
set(store.speechSettingsInitialized, speechSettingsInitialized);
- set(store.pendingQuotesByConvoId(conversation.conversationId ?? ''), quotes);
}}
>
<Router>
diff --git a/client/src/components/Chat/Input/__tests__/QuoteButton.test.tsx b/client/src/components/Chat/Input/__tests__/QuoteButton.test.tsx
index 1fd528b9c0..c329efc322 100644
--- a/client/src/components/Chat/Input/__tests__/QuoteButton.test.tsx
+++ b/client/src/components/Chat/Input/__tests__/QuoteButton.test.tsx
@@ -1,13 +1,13 @@
-import React, { Profiler } from 'react';
-import { RecoilRoot, useRecoilValue } from 'recoil';
+import React, { Profiler, useState } from 'react';
import { act, render, screen, fireEvent } from '@testing-library/react';
+import { Provider as JotaiProvider, createStore, useAtomValue } from 'jotai';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
import QuoteButton from '../QuoteButton';
-import store from '~/store';
+import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { mainTextareaId } from '~/common';
const CONVO_ID = 'convo-1';
@@ -37,10 +37,16 @@ const rect = ({
}) as DOMRect;
function Quotes() {
- const quotes = useRecoilValue(store.pendingQuotesByConvoId(CONVO_ID));
+ const quotes = useAtomValue(pendingQuotesByConvoId(CONVO_ID));
return <output data-testid="quotes">{JSON.stringify(quotes)}</output>;
}
+/** A fresh Jotai store per mount, so a quote committed by one test never reaches the next. */
+function JotaiRoot({ children }: { children: React.ReactNode }) {
+ const [jotaiStore] = useState(createStore);
+ return <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>;
+}
+
function pointer(target: Document | HTMLElement, type: string) {
const event = new MouseEvent(type, { bubbles: true, clientX: 50, clientY: 15 });
Object.defineProperty(event, 'pointerType', { value: 'touch' });
@@ -72,14 +78,14 @@ describe('QuoteButton', () => {
try {
const onRender = jest.fn();
render(
- <RecoilRoot>
+ <JotaiRoot>
<div className="message-render">{SELECTED_TEXT}</div>
<textarea id={mainTextareaId} />
<Quotes />
<Profiler id="quote-button" onRender={onRender}>
<QuoteButton conversationId={CONVO_ID} />
</Profiler>
- </RecoilRoot>,
+ </JotaiRoot>,
);
onRender.mockClear();
@@ -173,7 +179,7 @@ describe('QuoteButton', () => {
try {
render(
- <RecoilRoot>
+ <JotaiRoot>
<div className="message-render" style={{ overflow: 'auto' }}>
{codeFirst ? (
<>
@@ -194,7 +200,7 @@ describe('QuoteButton', () => {
<textarea id={mainTextareaId} />
<Quotes />
<QuoteButton conversationId={CONVO_ID} />
- </RecoilRoot>,
+ </JotaiRoot>,
);
const code = document.querySelector('.message-render code')?.firstChild;
const prose = screen.getByText(proseText).firstChild;
@@ -286,7 +292,7 @@ describe('QuoteButton', () => {
try {
render(
- <RecoilRoot>
+ <JotaiRoot>
<div className="message-render" style={{ overflow: 'auto' }}>
<pre style={{ overflowX: 'auto' }}>
<code>{codeLine}</code>
@@ -295,7 +301,7 @@ describe('QuoteButton', () => {
<textarea id={mainTextareaId} />
<Quotes />
<QuoteButton conversationId={CONVO_ID} />
- </RecoilRoot>,
+ </JotaiRoot>,
);
const code = document.querySelector('.message-render code');
if (!code) {
@@ -368,12 +374,12 @@ describe('QuoteButton lifecycle', () => {
function setup() {
const content = (conversationId: string) => (
- <RecoilRoot>
+ <JotaiRoot>
<div className="message-render">{SELECTED_TEXT}</div>
<textarea id={mainTextareaId} />
<Quotes />
<QuoteButton conversationId={conversationId} />
- </RecoilRoot>
+ </JotaiRoot>
);
const view = render(content(CONVO_ID));
const range = document.createRange();
diff --git a/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx b/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx
index 6cc2a17fa6..0e2ad10d68 100644
--- a/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/SkillsCommand.spec.tsx
@@ -29,9 +29,19 @@ jest.mock('jotai', () => ({
useAtomValue: jest.fn((atom: unknown) =>
atom === 'show-skills-popover' ? mockShowSkillsPopover.current : undefined,
),
- useSetAtom: jest.fn((atom: unknown) =>
- atom === 'show-skills-popover' ? mockSetShowSkillsPopover : jest.fn(),
- ),
+ useSetAtom: jest.fn((atom: unknown) => {
+ if (atom === 'show-skills-popover') {
+ return mockSetShowSkillsPopover;
+ }
+ if (atom === 'pending-manual-skills') {
+ return mockSetPendingManualSkills;
+ }
+ return jest.fn();
+ }),
+}));
+
+jest.mock('~/components/Chat/Input/Composer/state', () => ({
+ pendingManualSkillsByConvoId: () => 'pending-manual-skills',
}));
jest.mock('../skillsState', () => ({
@@ -48,9 +58,6 @@ jest.mock('recoil', () => {
if (atom === 'ephemeral-agent') {
return mockSetEphemeralAgent;
}
- if (atom === 'pending-manual-skills') {
- return mockSetPendingManualSkills;
- }
return jest.fn();
}),
};
@@ -58,11 +65,7 @@ jest.mock('recoil', () => {
jest.mock('~/store', () => ({
__esModule: true,
- default: {
- pendingManualSkillsByConvoId: () => 'pending-manual-skills',
- },
ephemeralAgentByConvoId: () => 'ephemeral-agent',
- pendingManualSkillsByConvoId: () => 'pending-manual-skills',
}));
const mockUseSkillsInfiniteQuery = jest.fn();
diff --git a/client/src/components/Messages/Content/Error/recovery.tsx b/client/src/components/Messages/Content/Error/recovery.tsx
index 10242152e0..eed80a25a9 100644
--- a/client/src/components/Messages/Content/Error/recovery.tsx
+++ b/client/src/components/Messages/Content/Error/recovery.tsx
@@ -19,7 +19,9 @@ import {
useOptionalMessagesConversation,
} from '~/Providers/MessagesViewContext';
import {
+ pendingQuotesByConvoId,
getReasoningStateKey,
+ pendingManualSkillsByConvoId,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
import { findAttachmentRecovery, isAttachmentError, mayBeAttachmentError } from './attachments';
@@ -103,10 +105,10 @@ function RecoveryActions({
set(store.pendingComposerTextByConvoId(forkedId), turn.text);
}
if ((turn.quotes?.length ?? 0) > 0) {
- set(store.pendingQuotesByConvoId(forkedId), turn.quotes ?? []);
+ reasoningStore.set(pendingQuotesByConvoId(forkedId), turn.quotes ?? []);
}
if ((turn.manualSkills?.length ?? 0) > 0) {
- set(store.pendingManualSkillsByConvoId(forkedId), turn.manualSkills ?? []);
+ reasoningStore.set(pendingManualSkillsByConvoId(forkedId), turn.manualSkills ?? []);
}
if (turn.reasoningOverride != null) {
reasoningStore.set(
diff --git a/client/src/components/Messages/Content/__tests__/recovery.spec.tsx b/client/src/components/Messages/Content/__tests__/recovery.spec.tsx
index 80a180793b..a9a0202a82 100644
--- a/client/src/components/Messages/Content/__tests__/recovery.spec.tsx
+++ b/client/src/components/Messages/Content/__tests__/recovery.spec.tsx
@@ -1,21 +1,23 @@
import React from 'react';
-import { getDefaultStore } from 'jotai';
import userEvent from '@testing-library/user-event';
import { RecoilRoot, useRecoilValue } from 'recoil';
+import { getDefaultStore, useAtomValue } from 'jotai';
import { act, render, screen } from '@testing-library/react';
import { Constants, ContentTypes, ForkOptions } from 'librechat-data-provider';
import type { TConversation, TMessage } from 'librechat-data-provider';
import type { MessagesViewContextValue } from '~/Providers/MessagesViewContext';
import type { ChatContract } from '~/hooks/Chat/contract';
+import {
+ getReasoningStateKey,
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
import {
MessagesViewContext,
MessagesSubmittingContext,
MessagesOperationsContext,
} from '~/Providers/MessagesViewContext';
-import {
- getReasoningStateKey,
- pendingReasoningOverrideFamily,
-} from '~/components/Chat/Input/Composer/state';
import { MessageContext } from '~/Providers/MessageContext';
import AttachmentRecoveryActions from '../Error/recovery';
import translation from '~/locales/en/translation.json';
@@ -81,8 +83,8 @@ let composerHandoff: { text?: string; quotes: string[]; skills: string[] } | und
function ComposerProbe() {
composerHandoff = {
text: useRecoilValue(store.pendingComposerTextByConvoId('forked')),
- quotes: useRecoilValue(store.pendingQuotesByConvoId('forked')),
- skills: useRecoilValue(store.pendingManualSkillsByConvoId('forked')),
+ quotes: useAtomValue(pendingQuotesByConvoId('forked')),
+ skills: useAtomValue(pendingManualSkillsByConvoId('forked')),
};
return null;
}
@@ -180,6 +182,8 @@ describe('AttachmentRecoveryActions', () => {
beforeEach(() => {
jest.clearAllMocks();
composerHandoff = undefined;
+ getDefaultStore().set(pendingQuotesByConvoId('forked'), []);
+ getDefaultStore().set(pendingManualSkillsByConvoId('forked'), []);
});
it('retries the failed turn as a new version without any files', async () => {
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index 7286d26b9a..18e9f63de4 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -124,8 +124,6 @@ jest.mock('~/store', () => ({
__esModule: true,
default: {
isSubmittingFamily: () => 'isSubmitting',
- pendingManualSkillsByConvoId: () => 'pendingManualSkills',
- pendingQuotesByConvoId: () => 'pendingQuotes',
messagesSiblingIdxFamily: () => 'messagesSiblingIdx',
conversationByKeySelector: () => 'conversation',
},
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index af84e63f94..03f99c56f0 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -30,6 +30,8 @@ import {
} from '~/hooks/Chat/queue';
import {
getReasoningStateKey,
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
import { revealedQueuedTurnFamily, pendingSteerCancelClientIdsFamily } from '~/store/steer';
@@ -206,7 +208,11 @@ function sendFromQueue(
current.steering.sendQueuedNow(item);
}
-beforeEach(() => resetQueueFamilies());
+beforeEach(() => {
+ resetQueueFamilies();
+ getDefaultStore().set(pendingQuotesByConvoId(CONVO_ID), []);
+ getDefaultStore().set(pendingManualSkillsByConvoId(CONVO_ID), []);
+});
describe('useSteering', () => {
beforeEach(() => {
@@ -240,9 +246,8 @@ describe('useSteering', () => {
setFiles,
consumeDraft,
};
- const { result, rerender, stopGenerating, sendNow } = setup(params, ({ set }) => {
- set(store.pendingQuotesByConvoId(CONVO_ID), ['preserved quote']);
- });
+ getDefaultStore().set(pendingQuotesByConvoId(CONVO_ID), ['preserved quote']);
+ const { result, rerender, stopGenerating, sendNow } = setup(params);
const captured = result.current[action];
params.composerDisabled = true;
rerender();
@@ -818,10 +823,10 @@ describe('useSteering', () => {
updatedAt: new Date().toISOString(),
});
});
+ getDefaultStore().set(pendingQuotesByConvoId(CONVO_ID), ['quoted context']);
+ getDefaultStore().set(pendingManualSkillsByConvoId(CONVO_ID), ['skill']);
const { result, unmount } = setup({ isSubmitting: false }, ({ set }) => {
set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
- set(store.pendingQuotesByConvoId(CONVO_ID), ['quoted context']);
- set(store.pendingManualSkillsByConvoId(CONVO_ID), ['skill']);
});
expect(result.current.duringRunActive).toBe(true);
expect(result.current.canSteer).toBe(false);
@@ -4220,8 +4225,8 @@ describe('useSteering', () => {
queue: useQueue(CONVO_ID),
setQueue: useSetAtom(queuedMessagesByConvoId(CONVO_ID)),
chips: useRecoilValue(store.pendingSteersByConvoId(CONVO_ID)),
- pendingQuotes: useRecoilValue(store.pendingQuotesByConvoId(CONVO_ID)),
- pendingSkills: useRecoilValue(store.pendingManualSkillsByConvoId(CONVO_ID)),
+ pendingQuotes: useAtomValue(pendingQuotesByConvoId(CONVO_ID)),
+ pendingSkills: useAtomValue(pendingManualSkillsByConvoId(CONVO_ID)),
pendingReasoning: useAtomValue(pendingReasoningOverrideFamily(CONVO_ID)),
markApplied: useSetRecoilState(store.appliedSteerIdsByConvoId(CONVO_ID)),
}),
@@ -4230,9 +4235,9 @@ describe('useSteering', () => {
return { ...rendered, sendNow, stopGenerating };
}
- const stageContext = ({ set }: MutableSnapshot) => {
- set(store.pendingQuotesByConvoId(CONVO_ID), ['quoted excerpt']);
- set(store.pendingManualSkillsByConvoId(CONVO_ID), ['skill-1']);
+ const stageContext = () => {
+ contextStore.set(pendingQuotesByConvoId(CONVO_ID), ['quoted excerpt']);
+ contextStore.set(pendingManualSkillsByConvoId(CONVO_ID), ['skill-1']);
};
it('queues rather than steering when reasoning is staged for a new generation', () => {
diff --git a/client/src/hooks/Chat/steering/chips.ts b/client/src/hooks/Chat/steering/chips.ts
index c836802478..91d7518b4e 100644
--- a/client/src/hooks/Chat/steering/chips.ts
+++ b/client/src/hooks/Chat/steering/chips.ts
@@ -5,6 +5,7 @@ import { isSteerRunReplaced, acknowledgeSteerChips } from '@librechat/chat';
import type { PendingSteer } from '@librechat/chat';
import type { CallbackInterface } from 'recoil';
import type { MutableRefObject } from 'react';
+import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { appendAppliedSteerIds, mergeRestagedQuotes } from '~/utils';
import { pendingSteerCancelClientIdsFamily } from '~/store/steer';
import store from '~/store';
@@ -201,7 +202,9 @@ export default function useSteerChips({
if (quotes == null || quotes.length === 0) {
return;
}
- set(store.pendingQuotesByConvoId(convoId), (prev) => mergeRestagedQuotes(prev, quotes));
+ jotaiStore.set(pendingQuotesByConvoId(convoId), (prev) =>
+ mergeRestagedQuotes(prev, quotes),
+ );
set(store.pendingSteersByConvoId(convoId), (prev) => {
let changed = false;
const next = prev.map((steer) => {
@@ -223,7 +226,7 @@ export default function useSteerChips({
return changed ? next : prev;
});
},
- [],
+ [jotaiStore],
);
return useMemo(
diff --git a/client/src/hooks/Chat/steering/composer.ts b/client/src/hooks/Chat/steering/composer.ts
index cf6ae84e95..f733e28d42 100644
--- a/client/src/hooks/Chat/steering/composer.ts
+++ b/client/src/hooks/Chat/steering/composer.ts
@@ -1,13 +1,15 @@
import { useCallback, useMemo } from 'react';
import { useStore } from 'jotai';
-import { useRecoilCallback } from 'recoil';
import type { QueuedMessageContext } from '@librechat/chat';
import type { TMessage } from 'librechat-data-provider';
import type { ExtendedFile, FileSetter } from '~/common';
-import { pendingReasoningOverrideFamily } from '~/components/Chat/Input/Composer/state';
+import {
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
import { markComposerFilesTaken } from '~/utils/composerFiles';
import { useSetFilesToDelete } from '~/hooks/Files';
-import store from '~/store';
export interface ComposerTake {
takeComposerFiles: () => TMessage['files'];
@@ -79,54 +81,38 @@ export default function useComposerTake({
/** Consumes staged quote chips + manual skill picks (mirroring `ask()`'s
* fresh-submit drain of the same atoms) so they pair with THIS queued
* message instead of gluing onto whatever the user sends next. */
- const takeComposerContext = useRecoilCallback(
- ({ snapshot, reset }) =>
- (): QueuedMessageContext => {
- const quotes = snapshot
- .getLoadable(store.pendingQuotesByConvoId(conversationId))
- .getValue();
- const manualSkills = snapshot
- .getLoadable(store.pendingManualSkillsByConvoId(conversationId))
- .getValue();
- const reasoningOverride = reasoningStore.get(
- pendingReasoningOverrideFamily(reasoningStateKey),
- );
- if (quotes.length > 0) {
- reset(store.pendingQuotesByConvoId(conversationId));
- }
- if (manualSkills.length > 0) {
- reset(store.pendingManualSkillsByConvoId(conversationId));
- }
- if (reasoningOverride != null) {
- reasoningStore.set(pendingReasoningOverrideFamily(reasoningStateKey), undefined);
- }
- return {
- ...(quotes.length > 0 && { quotes }),
- ...(manualSkills.length > 0 && { manualSkills }),
- ...(reasoningOverride != null && { reasoningOverride }),
- };
- },
- [conversationId, reasoningStateKey, reasoningStore],
- );
+ const takeComposerContext = useCallback((): QueuedMessageContext => {
+ const quotes = reasoningStore.get(pendingQuotesByConvoId(conversationId));
+ const manualSkills = reasoningStore.get(pendingManualSkillsByConvoId(conversationId));
+ const reasoningOverride = reasoningStore.get(pendingReasoningOverrideFamily(reasoningStateKey));
+ if (quotes.length > 0) {
+ reasoningStore.set(pendingQuotesByConvoId(conversationId), []);
+ }
+ if (manualSkills.length > 0) {
+ reasoningStore.set(pendingManualSkillsByConvoId(conversationId), []);
+ }
+ if (reasoningOverride != null) {
+ reasoningStore.set(pendingReasoningOverrideFamily(reasoningStateKey), undefined);
+ }
+ return {
+ ...(quotes.length > 0 && { quotes }),
+ ...(manualSkills.length > 0 && { manualSkills }),
+ ...(reasoningOverride != null && { reasoningOverride }),
+ };
+ }, [conversationId, reasoningStateKey, reasoningStore]);
/** Quotes-only drain for composer-origin steers: the excerpts ride the steer
* POST into the live run, while manual skill picks stay staged: a skill
* pick configures a NEW turn's agent run and cannot apply to a mid-run
* injection, so it keeps waiting for the next full submission. */
- const takeComposerQuotes = useRecoilCallback(
- ({ snapshot, reset }) =>
- (): QueuedMessageContext => {
- const quotes = snapshot
- .getLoadable(store.pendingQuotesByConvoId(conversationId))
- .getValue();
- if (quotes.length === 0) {
- return {};
- }
- reset(store.pendingQuotesByConvoId(conversationId));
- return { quotes };
- },
- [conversationId],
- );
+ const takeComposerQuotes = useCallback((): QueuedMessageContext => {
+ const quotes = reasoningStore.get(pendingQuotesByConvoId(conversationId));
+ if (quotes.length === 0) {
+ return {};
+ }
+ reasoningStore.set(pendingQuotesByConvoId(conversationId), []);
+ return { quotes };
+ }, [conversationId, reasoningStore]);
return useMemo(
() => ({ takeComposerFiles, takeComposerContext, takeComposerQuotes }),
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index 2e0dfed94c..7551c934d2 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -4,7 +4,7 @@ import { cloneDeep } from 'lodash';
import { useStore, useSetAtom } from 'jotai';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
-import { useSetRecoilState, useRecoilValue, useRecoilCallback } from 'recoil';
+import { useSetRecoilState, useRecoilValue } from 'recoil';
import {
Constants,
QueryKeys,
@@ -46,6 +46,8 @@ import {
} from '~/utils';
import {
getReasoningStateKey,
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
import {
@@ -290,8 +292,8 @@ export default function useChatFunctions({
/**
* Atomically read + reset the per-conversation queue of manually-invoked
- * skills from the `$` popover. Reading and resetting in a single Recoil
- * snapshot guarantees that if the user selects more skills between here and
+ * skills from the `$` popover. Reading and resetting in one synchronous
+ * store pass guarantees that if the user selects more skills between here and
* the next submission, their picks are never silently lost into a reset atom.
*
* The `hasValue` guard is defensive: this atom has a synchronous default of
@@ -299,17 +301,15 @@ export default function useChatFunctions({
* `.contents` on a loading/errored loadable yields a Promise/Error, which
* would make the `string[]` cast unsound.
*/
- const drainPendingManualSkills = useRecoilCallback(
- ({ snapshot, reset }) =>
- (convoId: string): string[] => {
- const loadable = snapshot.getLoadable(store.pendingManualSkillsByConvoId(convoId));
- const skills = loadable.state === 'hasValue' ? (loadable.contents as string[]) : [];
- if (skills.length > 0) {
- reset(store.pendingManualSkillsByConvoId(convoId));
- }
- return skills;
- },
- [],
+ const drainPendingManualSkills = useCallback(
+ (convoId: string): string[] => {
+ const skills = jotaiStore.get(pendingManualSkillsByConvoId(convoId));
+ if (skills.length > 0) {
+ jotaiStore.set(pendingManualSkillsByConvoId(convoId), []);
+ }
+ return skills;
+ },
+ [jotaiStore],
);
/**
@@ -318,17 +318,15 @@ export default function useChatFunctions({
* `drainPendingManualSkills`: a single snapshot read + reset so excerpts
* added between here and submission are never lost into a reset atom.
*/
- const drainPendingQuotes = useRecoilCallback(
- ({ snapshot, reset }) =>
- (convoId: string): string[] => {
- const loadable = snapshot.getLoadable(store.pendingQuotesByConvoId(convoId));
- const quotes = loadable.state === 'hasValue' ? (loadable.contents as string[]) : [];
- if (quotes.length > 0) {
- reset(store.pendingQuotesByConvoId(convoId));
- }
- return quotes;
- },
- [],
+ const drainPendingQuotes = useCallback(
+ (convoId: string): string[] => {
+ const quotes = jotaiStore.get(pendingQuotesByConvoId(convoId));
+ if (quotes.length > 0) {
+ jotaiStore.set(pendingQuotesByConvoId(convoId), []);
+ }
+ return quotes;
+ },
+ [jotaiStore],
);
const drainPendingReasoning = useCallback(
diff --git a/client/src/hooks/Config/__tests__/useClearStates.spec.tsx b/client/src/hooks/Config/__tests__/useClearStates.spec.tsx
index a83f9d54a3..8b2d4b599c 100644
--- a/client/src/hooks/Config/__tests__/useClearStates.spec.tsx
+++ b/client/src/hooks/Config/__tests__/useClearStates.spec.tsx
@@ -1,14 +1,18 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { act, renderHook } from '@testing-library/react';
-import { ReasoningEffort } from 'librechat-data-provider';
import { createStore, Provider as JotaiProvider } from 'jotai';
+import { Constants, ReasoningEffort } from 'librechat-data-provider';
+import {
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
import {
abortScrollFamily,
showStopButtonByIndex,
submissionStartFamily,
} from '~/store/generation';
-import { pendingReasoningOverrideFamily } from '~/components/Chat/Input/Composer/state';
import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog';
import useClearStates from '../useClearStates';
import store from '~/store';
@@ -60,6 +64,30 @@ describe('useClearStates', () => {
).toBeUndefined();
});
+ /* Quotes and skill picks are keyed by conversation, so a chat staged and then
+ left (the shared new-chat key included) still holds them at sign-out. */
+ it('drops staged quotes and skill picks for every conversation, mounted or not', async () => {
+ const jotaiStore = createStore();
+ jotaiStore.set(pendingQuotesByConvoId(Constants.NEW_CONVO), ['quote']);
+ jotaiStore.set(pendingManualSkillsByConvoId(Constants.NEW_CONVO), ['writer']);
+ jotaiStore.set(pendingQuotesByConvoId('unmounted-conversation'), ['quote']);
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>
+ <RecoilRoot>{children}</RecoilRoot>
+ </JotaiProvider>
+ );
+
+ const { result } = renderHook(() => useClearStates(), { wrapper });
+ await act(async () => {
+ await result.current();
+ });
+
+ expect(Array.from(pendingQuotesByConvoId.getParams())).toEqual([]);
+ expect(Array.from(pendingManualSkillsByConvoId.getParams())).toEqual([]);
+ expect(jotaiStore.get(pendingQuotesByConvoId(Constants.NEW_CONVO))).toEqual([]);
+ expect(jotaiStore.get(pendingManualSkillsByConvoId(Constants.NEW_CONVO))).toEqual([]);
+ });
+
/* `skipFirst` keeps the landing pane's run state; every other pane's stop
button, scroll latch and elapsed baseline reset so the next session starts idle. */
it.each([
diff --git a/client/src/hooks/Config/useClearStates.ts b/client/src/hooks/Config/useClearStates.ts
index 04e3e0fb1c..d4886b1f5f 100644
--- a/client/src/hooks/Config/useClearStates.ts
+++ b/client/src/hooks/Config/useClearStates.ts
@@ -1,7 +1,9 @@
import { useStore } from 'jotai';
import { useRecoilCallback } from 'recoil';
+import { Constants } from 'librechat-data-provider';
import {
getReasoningStateKey,
+ clearPendingComposerContext,
clearPendingReasoningOverrides,
} from '~/components/Chat/Input/Composer/state';
import {
@@ -33,13 +35,20 @@ export default function useClearStates() {
const keys = await snapshot.getPromise(store.conversationKeysAtom);
const keptReasoningKeys = new Set<string>();
+ const keptContextKeys = new Set<string>();
if (skipFirst === true) {
const firstConvoId = (await snapshot.getPromise(store.conversationByIndex(0)))
?.conversationId;
keptReasoningKeys.add(getReasoningStateKey(null, 0));
keptReasoningKeys.add(getReasoningStateKey(firstConvoId, 0));
+ keptContextKeys.add('0');
+ keptContextKeys.add(firstConvoId ?? Constants.NEW_CONVO);
}
clearPendingReasoningOverrides(jotaiStore, keptReasoningKeys);
+ /* Staged quotes and skill picks are keyed by every conversation the
+ composer has visited, not only the panes mounted now: sweep them all
+ so none reaches the next session's composer. */
+ clearPendingComposerContext(jotaiStore, keptContextKeys);
for (const key of keys) {
if (skipFirst === true && key === 0) {
@@ -58,19 +67,6 @@ export default function useClearStates() {
reset(store.showPlusPopoverFamily(key));
reset(store.showPromptsPopoverFamily(key));
jotaiStore.set(showSkillsPopoverFamily(key), false);
- reset(store.pendingManualSkillsByConvoId(key.toString()));
- reset(store.pendingQuotesByConvoId(key.toString()));
- /**
- * Pending skill/quote queues are keyed by the conversation id the
- * composer wrote under, not this UI index — also clear by the resolved
- * id so queued-but-unsent selections don't linger in Recoil.
- */
- const convoId = (await snapshot.getPromise(store.conversationByIndex(key)))
- ?.conversationId;
- if (convoId != null) {
- reset(store.pendingManualSkillsByConvoId(convoId));
- reset(store.pendingQuotesByConvoId(convoId));
- }
reset(store.activePromptByIndex(key));
reset(store.globalAudioURLFamily(key));
reset(store.globalAudioFetchingFamily(key));
diff --git a/client/src/hooks/Input/__tests__/useComposerItems.spec.tsx b/client/src/hooks/Input/__tests__/useComposerItems.spec.tsx
index 8accb68589..42552aa9a5 100644
--- a/client/src/hooks/Input/__tests__/useComposerItems.spec.tsx
+++ b/client/src/hooks/Input/__tests__/useComposerItems.spec.tsx
@@ -1,8 +1,11 @@
import React from 'react';
import { act, renderHook } from '@testing-library/react';
-import { RecoilRoot, useRecoilValue, type MutableSnapshot } from 'recoil';
+import { Provider as JotaiProvider, createStore, useAtomValue } from 'jotai';
+import {
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
+} from '~/components/Chat/Input/Composer/state';
import useComposerItems from '../useComposerItems';
-import store from '~/store';
/**
* The tray's staged context. Removal is the whole surface here, and quotes are
@@ -11,24 +14,26 @@ import store from '~/store';
const CONVO_ID = 'convo-items';
-function setup(initialize?: (snapshot: MutableSnapshot) => void) {
+function setup(initialize?: (jotaiStore: ReturnType<typeof createStore>) => void) {
+ const jotaiStore = createStore();
+ initialize?.(jotaiStore);
const wrapper = ({ children }: { children: React.ReactNode }) => (
- <RecoilRoot initializeState={initialize}>{children}</RecoilRoot>
+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
);
return renderHook(
() => ({
items: useComposerItems(CONVO_ID),
- quotes: useRecoilValue(store.pendingQuotesByConvoId(CONVO_ID)),
- skills: useRecoilValue(store.pendingManualSkillsByConvoId(CONVO_ID)),
+ quotes: useAtomValue(pendingQuotesByConvoId(CONVO_ID)),
+ skills: useAtomValue(pendingManualSkillsByConvoId(CONVO_ID)),
}),
{ wrapper },
);
}
const withStaged = (quotes: string[], skills: string[] = []) =>
- setup(({ set }) => {
- set(store.pendingQuotesByConvoId(CONVO_ID), quotes);
- set(store.pendingManualSkillsByConvoId(CONVO_ID), skills);
+ setup((jotaiStore) => {
+ jotaiStore.set(pendingQuotesByConvoId(CONVO_ID), quotes);
+ jotaiStore.set(pendingManualSkillsByConvoId(CONVO_ID), skills);
});
describe('useComposerItems', () => {
diff --git a/client/src/hooks/Input/__tests__/useComposerRestore.spec.tsx b/client/src/hooks/Input/__tests__/useComposerRestore.spec.tsx
index 4e50429b24..e643049147 100644
--- a/client/src/hooks/Input/__tests__/useComposerRestore.spec.tsx
+++ b/client/src/hooks/Input/__tests__/useComposerRestore.spec.tsx
@@ -1,14 +1,15 @@
import React from 'react';
-import { RecoilRoot } from 'recoil';
import { act, renderHook } from '@testing-library/react';
import { ReasoningEffort } from 'librechat-data-provider';
import { Provider as JotaiProvider, createStore } from 'jotai';
import type { TMessage } from 'librechat-data-provider';
-import type { MutableSnapshot } from 'recoil';
import type { ExtendedFile } from '~/common';
-import { pendingReasoningOverrideFamily } from '~/components/Chat/Input/Composer/state';
+import {
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
+ pendingReasoningOverrideFamily,
+} from '~/components/Chat/Input/Composer/state';
import useComposerRestore from '../useComposerRestore';
-import store from '~/store';
/**
* The guarded restore is the one path in the composer that can destroy text
@@ -36,7 +37,7 @@ function setup({
files?: Map<string, ExtendedFile>;
answerModeActive?: boolean;
reasoningOverride?: TMessage['reasoningOverride'];
- initialize?: (snapshot: MutableSnapshot) => void;
+ initialize?: (jotaiStore: ReturnType<typeof createStore>) => void;
} = {}) {
let text = draft;
const setFiles = jest.fn();
@@ -49,10 +50,9 @@ function setup({
const textAreaRef = { current: { focus: jest.fn() } };
const reasoningStore = createStore();
reasoningStore.set(pendingReasoningOverrideFamily(conversationId), reasoningOverride);
+ initialize?.(reasoningStore);
const wrapper = ({ children }: { children: React.ReactNode }) => (
- <JotaiProvider store={reasoningStore}>
- <RecoilRoot initializeState={initialize}>{children}</RecoilRoot>
- </JotaiProvider>
+ <JotaiProvider store={reasoningStore}>{children}</JotaiProvider>
);
const view = renderHook(
(props: { conversationId: string; answerModeActive: boolean }) =>
@@ -120,13 +120,13 @@ describe('useComposerRestore', () => {
it.each([
[
'a quote',
- (snapshot: MutableSnapshot) =>
- snapshot.set(store.pendingQuotesByConvoId(CONVO_ID), ['an excerpt']),
+ (jotaiStore: ReturnType<typeof createStore>) =>
+ jotaiStore.set(pendingQuotesByConvoId(CONVO_ID), ['an excerpt']),
],
[
'a skill pick',
- (snapshot: MutableSnapshot) =>
- snapshot.set(store.pendingManualSkillsByConvoId(CONVO_ID), ['writer']),
+ (jotaiStore: ReturnType<typeof createStore>) =>
+ jotaiStore.set(pendingManualSkillsByConvoId(CONVO_ID), ['writer']),
],
])('refuses when %s is staged', (_label, initialize) => {
const { result } = setup({ initialize });
diff --git a/client/src/hooks/Input/__tests__/usePaletteEntries.spec.tsx b/client/src/hooks/Input/__tests__/usePaletteEntries.spec.tsx
index fba0850222..a8930b216e 100644
--- a/client/src/hooks/Input/__tests__/usePaletteEntries.spec.tsx
+++ b/client/src/hooks/Input/__tests__/usePaletteEntries.spec.tsx
@@ -1,9 +1,10 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { renderHook, act } from '@testing-library/react';
+import { Provider as JotaiProvider, createStore } from 'jotai';
import { ArtifactModes, PermissionTypes } from 'librechat-data-provider';
+import { pendingManualSkillsByConvoId } from '~/components/Chat/Input/Composer/state';
import usePaletteEntries from '../usePaletteEntries';
-import store from '~/store';
/**
* What the palette is offered, before it decides how to draw it. Every row here
@@ -119,12 +120,23 @@ const allCapabilities = {
skillsEnabled: true,
};
-const wrapper = ({ children }: { children: React.ReactNode }) => (
- <RecoilRoot>{children}</RecoilRoot>
-);
+/** A fresh Jotai store per render, so a skill staged by one test never reaches the next. */
+const stagedWrapper = (skills: string[] = []) => {
+ const jotaiStore = createStore();
+ jotaiStore.set(pendingManualSkillsByConvoId('convo-1'), skills);
+ return function StagedWrapper({ children }: { children: React.ReactNode }) {
+ return (
+ <JotaiProvider store={jotaiStore}>
+ <RecoilRoot>{children}</RecoilRoot>
+ </JotaiProvider>
+ );
+ };
+};
const entries = (agentId?: string | null) =>
- renderHook(() => usePaletteEntries({ conversationId: 'convo-1', agentId }), { wrapper });
+ renderHook(() => usePaletteEntries({ conversationId: 'convo-1', agentId }), {
+ wrapper: stagedWrapper(),
+ });
const keysOf = (result: { current: Array<{ key: string }> }) =>
result.current.map((item) => item.key);
@@ -168,7 +180,7 @@ describe('usePaletteEntries', () => {
catalogEnabled: true,
catalogOpenRevision: revision,
}),
- { wrapper, initialProps: { revision: 1 } },
+ { wrapper: stagedWrapper(), initialProps: { revision: 1 } },
);
expect(refetch).not.toHaveBeenCalled();
@@ -373,7 +385,7 @@ describe('usePaletteEntries', () => {
conversationId: 'convo-1',
favoriteKeys: new Set(['skill:s2']),
}),
- { wrapper },
+ { wrapper: stagedWrapper() },
);
expect(keysOf(result).filter((key) => key.startsWith('skill:'))).toEqual([
'skill:s2',
@@ -391,15 +403,7 @@ describe('usePaletteEntries', () => {
const { result } = renderHook(
() => usePaletteEntries({ conversationId: 'convo-1', agentId: null }),
{
- wrapper: ({ children }: { children: React.ReactNode }) => (
- <RecoilRoot
- initializeState={({ set }) =>
- set(store.pendingManualSkillsByConvoId('convo-1'), ['writer'])
- }
- >
- {children}
- </RecoilRoot>
- ),
+ wrapper: stagedWrapper(['writer']),
},
);
expect(result.current.find((item) => item.key === 'skill:s1')?.active).toBe(true);
@@ -427,15 +431,7 @@ describe('usePaletteEntries', () => {
const { result } = renderHook(
() => usePaletteEntries({ conversationId: 'convo-1', agentId: null }),
{
- wrapper: ({ children }: { children: React.ReactNode }) => (
- <RecoilRoot
- initializeState={({ set }) =>
- set(store.pendingManualSkillsByConvoId('convo-1'), ['writer'])
- }
- >
- {children}
- </RecoilRoot>
- ),
+ wrapper: stagedWrapper(['writer']),
},
);
@@ -523,7 +519,7 @@ describe('usePaletteEntries', () => {
enabled: true,
toolsEnabled: false,
}),
- { wrapper },
+ { wrapper: stagedWrapper() },
);
expect(keysOf(result)).toEqual(['skill:s2']);
diff --git a/client/src/hooks/Input/useComposerItems.ts b/client/src/hooks/Input/useComposerItems.ts
index e7c595a0d3..24e3aa4946 100644
--- a/client/src/hooks/Input/useComposerItems.ts
+++ b/client/src/hooks/Input/useComposerItems.ts
@@ -1,6 +1,9 @@
import { useMemo, useCallback } from 'react';
-import { useRecoilValue, useSetRecoilState } from 'recoil';
-import store from '~/store';
+import { useAtom } from 'jotai';
+import {
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
+} from '~/components/Chat/Input/Composer/state';
export type ComposerItemKind = 'quote' | 'skill';
@@ -32,10 +35,8 @@ export default function useComposerItems(
conversationId: string,
includeQuotes = true,
): ComposerItem[] {
- const quotes = useRecoilValue(store.pendingQuotesByConvoId(conversationId));
- const skills = useRecoilValue(store.pendingManualSkillsByConvoId(conversationId));
- const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
- const setSkills = useSetRecoilState(store.pendingManualSkillsByConvoId(conversationId));
+ const [quotes, setQuotes] = useAtom(pendingQuotesByConvoId(conversationId));
+ const [skills, setSkills] = useAtom(pendingManualSkillsByConvoId(conversationId));
const removeQuoteAt = useCallback(
(index: number) => setQuotes((prev) => prev.filter((_, i) => i !== index)),
diff --git a/client/src/hooks/Input/useComposerRestore.ts b/client/src/hooks/Input/useComposerRestore.ts
index b2464e6a1d..5671c9e2ca 100644
--- a/client/src/hooks/Input/useComposerRestore.ts
+++ b/client/src/hooks/Input/useComposerRestore.ts
@@ -1,15 +1,15 @@
import { useRef, useEffect, useCallback } from 'react';
import { useStore } from 'jotai';
-import { useRecoilCallback } from 'recoil';
import type { TMessage } from 'librechat-data-provider';
import type { QueuedMessageContext } from '~/hooks/Chat/useSteering';
import type { ExtendedFile, FileSetter } from '~/common';
import type { useChatFormContext } from '~/Providers';
import {
getReasoningStateKey,
+ pendingQuotesByConvoId,
+ pendingManualSkillsByConvoId,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
-import store from '~/store';
export interface ComposerRestore {
/** Chip "Edit message": replaces the draft outright, since the caller has
@@ -68,24 +68,23 @@ export default function useComposerRestore({
const reasoningStateKey = getReasoningStateKey(conversationId, index);
/** Chip "Edit message" restore: quote chips, skill picks, and the reasoning
* override merge back into their compose-time atoms. */
- const restoreComposerContext = useRecoilCallback(
- ({ set }) =>
- (context?: QueuedMessageContext) => {
- const { quotes, manualSkills, reasoningOverride } = context ?? {};
- if (quotes != null && quotes.length > 0) {
- set(store.pendingQuotesByConvoId(conversationId), (prev) => [
- ...new Set([...prev, ...quotes]),
- ]);
- }
- if (manualSkills != null && manualSkills.length > 0) {
- set(store.pendingManualSkillsByConvoId(conversationId), (prev) => [
- ...new Set([...prev, ...manualSkills]),
- ]);
- }
- if (reasoningOverride != null) {
- reasoningStore.set(pendingReasoningOverrideFamily(reasoningStateKey), reasoningOverride);
- }
- },
+ const restoreComposerContext = useCallback(
+ (context?: QueuedMessageContext) => {
+ const { quotes, manualSkills, reasoningOverride } = context ?? {};
+ if (quotes != null && quotes.length > 0) {
+ reasoningStore.set(pendingQuotesByConvoId(conversationId), (prev) => [
+ ...new Set([...prev, ...quotes]),
+ ]);
+ }
+ if (manualSkills != null && manualSkills.length > 0) {
+ reasoningStore.set(pendingManualSkillsByConvoId(conversationId), (prev) => [
+ ...new Set([...prev, ...manualSkills]),
+ ]);
+ }
+ if (reasoningOverride != null) {
+ reasoningStore.set(pendingReasoningOverrideFamily(reasoningStateKey), reasoningOverride);
+ }
+ },
[conversationId, reasoningStateKey, reasoningStore],
);
@@ -165,13 +164,12 @@ export default function useComposerRestore({
* MERGES the steer's attachments into the composer's file map and its quotes
* and skill picks into their atoms, so restoring over staged context would
* glue the two submissions together. */
- const hasStagedContext = useRecoilCallback(
- ({ snapshot }) =>
- (convoId: string) =>
- snapshot.getLoadable(store.pendingQuotesByConvoId(convoId)).getValue().length > 0 ||
- snapshot.getLoadable(store.pendingManualSkillsByConvoId(convoId)).getValue().length > 0 ||
- reasoningStore.get(pendingReasoningOverrideFamily(getReasoningStateKey(convoId, index))) !=
- null,
+ const hasStagedContext = useCallback(
+ (convoId: string) =>
+ reasoningStore.get(pendingQuotesByConvoId(convoId)).length > 0 ||
+ reasoningStore.get(pendingManualSkillsByConvoId(convoId)).length > 0 ||
+ reasoningStore.get(pendingReasoningOverrideFamily(getReasoningStateKey(convoId, index))) !=
+ null,
[index, reasoningStore],
);
diff --git a/client/src/hooks/Input/usePaletteEntries.tsx b/client/src/hooks/Input/usePaletteEntries.tsx
index 8565351877..539984694c 100644
--- a/client/src/hooks/Input/usePaletteEntries.tsx
+++ b/client/src/hooks/Input/usePaletteEntries.tsx
@@ -1,6 +1,7 @@
import React, { useMemo, useEffect, useRef, useCallback } from 'react';
+import { useAtom } from 'jotai';
+import { useSetRecoilState } from 'recoil';
import { MCPIcon } from '@librechat/client';
-import { useRecoilValue, useSetRecoilState } from 'recoil';
import {
Brain,
Globe,
@@ -33,11 +34,12 @@ import {
useAgentCapabilities,
useSkillActiveState,
} from '~/hooks';
+import { pendingManualSkillsByConvoId } from '~/components/Chat/Input/Composer/state';
import { getStatusColor, getStatusTextKey } from '~/components/MCP/mcpServerUtils';
import { filterSkillsForPopover } from '~/components/Chat/Input/SkillsCommand';
import { useAgentsMapContext, useBadgeRowContext } from '~/Providers';
import { useSkillsInfiniteQuery } from '~/data-provider';
-import store, { ephemeralAgentByConvoId } from '~/store';
+import { ephemeralAgentByConvoId } from '~/store';
import { favoriteKey } from './useToolFavorites';
import useLocalize from '~/hooks/useLocalize';
@@ -173,9 +175,8 @@ export default function usePaletteEntries({
const agentsMap = useAgentsMapContext();
const { isActive } = useSkillActiveState();
const setEphemeralAgent = useSetRecoilState(ephemeralAgentByConvoId(conversationId));
- const pendingManualSkills = useRecoilValue(store.pendingManualSkillsByConvoId(conversationId));
- const setPendingManualSkills = useSetRecoilState(
- store.pendingManualSkillsByConvoId(conversationId),
+ const [pendingManualSkills, setPendingManualSkills] = useAtom(
+ pendingManualSkillsByConvoId(conversationId),
);
const {
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 17f3d5c48b..613153fdf6 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -1,8 +1,8 @@
import { useCallback, useEffect, useRef } from 'react';
import { v4 } from 'uuid';
+import { useSetRecoilState } from 'recoil';
import { useStore, useSetAtom } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
-import { useSetRecoilState, useRecoilCallback } from 'recoil';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import {
QueryKeys,
@@ -54,6 +54,7 @@ import {
} from '~/data-provider';
import {
getReasoningStateKey,
+ pendingQuotesByConvoId,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
import {
@@ -640,19 +641,18 @@ export default function useEventHandlers({
/** Re-stage request context when an early abort restores the draft, so a
* retry keeps the references and one-shot reasoning selection already
* drained from the composer on submit. */
- const restorePendingContext = useRecoilCallback(
- ({ set }) =>
- (convoId: string, quotes?: string[], reasoningOverride?: TMessage['reasoningOverride']) => {
- if (Array.isArray(quotes) && quotes.length > 0) {
- set(store.pendingQuotesByConvoId(convoId), quotes);
- }
- if (reasoningOverride != null) {
- const reasoningAtom = pendingReasoningOverrideFamily(
- getReasoningStateKey(convoId, runIndex),
- );
- reasoningStore.set(reasoningAtom, (current) => current ?? reasoningOverride);
- }
- },
+ const restorePendingContext = useCallback(
+ (convoId: string, quotes?: string[], reasoningOverride?: TMessage['reasoningOverride']) => {
+ if (Array.isArray(quotes) && quotes.length > 0) {
+ reasoningStore.set(pendingQuotesByConvoId(convoId), quotes);
+ }
+ if (reasoningOverride != null) {
+ const reasoningAtom = pendingReasoningOverrideFamily(
+ getReasoningStateKey(convoId, runIndex),
+ );
+ reasoningStore.set(reasoningAtom, (current) => current ?? reasoningOverride);
+ }
+ },
[reasoningStore, runIndex],
);
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index dcde0f5b18..aa95fcb95a 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -106,6 +106,7 @@ import useEventHandlers, {
buildCreatedInitialResponse,
keepLocalCodeApprovalMode,
} from './useEventHandlers';
+import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { abortScrollFamily, showStopButtonByIndex } from '~/store/generation';
import { withSubmittedCodeDecision } from '~/hooks/Agents/codeDecision';
@@ -1067,7 +1068,7 @@ export default function useResumableSSE(
(steer) => settledIds.includes(steer.steerId) && (steer.quotes?.length ?? 0) > 0,
)?.quotes;
if (droppedQuotes != null && droppedQuotes.length > 0) {
- set(store.pendingQuotesByConvoId(conversationId), (prev) =>
+ jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
mergeRestagedQuotes(prev, droppedQuotes),
);
}
@@ -1270,7 +1271,7 @@ export default function useResumableSSE(
snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue(),
);
if (droppedQuotes.length > 0) {
- set(store.pendingQuotesByConvoId(conversationId), (prev) =>
+ jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
mergeRestagedQuotes(prev, droppedQuotes),
);
}
diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/client/src/hooks/SSE/useResumeOnLoad.ts
index e08d76681c..398149aae9 100644
--- a/client/src/hooks/SSE/useResumeOnLoad.ts
+++ b/client/src/hooks/SSE/useResumeOnLoad.ts
@@ -45,6 +45,7 @@ import {
supportsGenerationProtocolV2,
} from '~/data-provider/SSE/protocol';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
+import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
@@ -454,7 +455,7 @@ export default function useResumeOnLoad(
snapshot.getLoadable(store.pendingSteersByConvoId(activeConversationId)).getValue(),
);
if (droppedQuotes.length > 0) {
- set(store.pendingQuotesByConvoId(activeConversationId), (prev) =>
+ jotaiStore.set(pendingQuotesByConvoId(activeConversationId), (prev) =>
mergeRestagedQuotes(prev, droppedQuotes),
);
}
@@ -465,7 +466,7 @@ export default function useResumeOnLoad(
prev.filter((steer) => !settled.has(steer.steerId)),
);
},
- [],
+ [jotaiStore],
);
const setActiveGenerationCreatedAt = useRecoilCallback(
({ set }) =>
diff --git a/client/src/store/families.ts b/client/src/store/families.ts
index 8be5065592..32eb075f19 100644
--- a/client/src/store/families.ts
+++ b/client/src/store/families.ts
@@ -234,34 +234,6 @@ const showPromptsPopoverFamily = atomFamily<boolean, string | number | null>({
default: false,
});
-/**
- * Per-conversation queue of skill names the user invoked manually via the
- * `$` popover for the next submission. Structured channel that the submit
- * pipeline (`useChatFunctions.ask`) drains and pins onto the user message's
- * `manualSkills` field (also echoed at the top of the payload for the
- * runtime resolver), then resets to `[]`. Compose-time chips above the
- * textarea read this atom directly so users see (and can dismiss) their
- * current selection before hitting send.
- */
-const pendingManualSkillsByConvoId = atomFamily<string[], string>({
- key: 'pendingManualSkillsByConvoId',
- default: [],
-});
-
-/**
- * Per-conversation queue of verbatim excerpts the user quoted via the
- * "Add to chat" selection popup for the next submission. The submit pipeline
- * (`useChatFunctions.ask`) drains this onto the user message's `quotes` field
- * (which the backend merges into the model-facing text and persists for the
- * `MessageQuotes` UI), then resets to `[]`. Compose-time chips above the
- * textarea read this atom directly so users can see and dismiss each quote
- * before sending.
- */
-const pendingQuotesByConvoId = atomFamily<string[], string>({
- key: 'pendingQuotesByConvoId',
- default: [],
-});
-
/**
* Text handed to a conversation's composer by a surface the user is leaving —
* today, a subagent thread continued into a chat of its own, where the panel
@@ -486,8 +458,6 @@ export default {
useClearSubmissionState,
showPromptsPopoverFamily,
pendingComposerTextByConvoId,
- pendingManualSkillsByConvoId,
- pendingQuotesByConvoId,
pendingSteersByConvoId,
appliedSteerIdsByConvoId,
acceptedSteerClientIdsByConvoId,
diff --git a/e2e/specs/mock/quotes.spec.ts b/e2e/specs/mock/quotes.spec.ts
index 620895cd28..7e336a3cc7 100644
--- a/e2e/specs/mock/quotes.spec.ts
+++ b/e2e/specs/mock/quotes.spec.ts
@@ -345,7 +345,7 @@ async function addQuote(page: Page, needle: string, expectedCount: number) {
}
test.describe('quote references', () => {
- test('merges a quoted excerpt into the model turn, pins it to the message, and persists across reload', async ({
+ test('merges a quoted excerpt into the model turn, pins it to the message, and persists across reload @scenario:quoted-excerpt-reaches-the-model-and-persists', async ({
page,
}) => {
test.setTimeout(120000);
@@ -582,7 +582,9 @@ test.describe('quote references', () => {
await expect(addToChat(page)).toBeHidden({ timeout: 5000 });
});
- test('stages each selection as its own chip in the tray, and removes one', async ({ page }) => {
+ test('stages each selection as its own chip in the tray, and removes one @scenario:staged-quotes-show-as-chips-and-remove-one', async ({
+ page,
+ }) => {
test.setTimeout(120000);
const firstMessage = 'quote target alpha';