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

📩 fix: Stage URL Prompts Before Agent Submission (#16647)

lia-by-librechat[bot]1f195dcf9d98
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx
index 3ab4180407..e5aba033e3 100644
--- a/client/src/components/Chat/ChatView.tsx
+++ b/client/src/components/Chat/ChatView.tsx
@@ -259,6 +259,7 @@ function ChatView({
) : (
<ChatForm
index={index}
+ routePending={routePending}
placeholder={chatFormPlaceholder}
project={isProjectLandingPage ? project : undefined}
isLandingPage={isLandingPage}
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 8a0dbf8c74..e3788e4ab2 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -107,6 +107,8 @@ interface ChatFormProps {
index: number;
placeholder?: string;
project?: TChatProject;
+ /** The host is reconciling the requested route with its conversation record. */
+ routePending: boolean;
/** Owned by ChatView: which layout the composer sits in — the welcome screen
* floats or bottoms it out, a conversation ends the page with it. */
isLandingPage: boolean;
@@ -160,6 +162,7 @@ const ChatForm = memo(function ChatForm({
index,
placeholder,
project,
+ routePending,
isLandingPage,
enterToSend,
autoSendText,
@@ -317,7 +320,7 @@ const ChatForm = memo(function ChatForm({
* collapsed batch is neither, it hands the composer back to the thread. */
const composerReserved = answerMode.composerAnswers || answerMode.composerLocked;
- const consumeDraft = useAutoSave({
+ const { consumeDraft, preserveText, settleText } = useAutoSave({
index,
files,
setFiles,
@@ -330,6 +333,17 @@ const ChatForm = memo(function ChatForm({
draftId: answerMode.draftId,
});
+ const {
+ isPreparing: isPreparingFromUrl,
+ settingsError: urlSettingsError,
+ clearSettingsError,
+ } = useQueryParams({
+ textAreaRef,
+ routePending,
+ onBeforePrompt: preserveText,
+ onPromptSettled: settleText,
+ });
+
const pastedTextEdit = usePastedTextEdit({ index, files, setFiles, textAreaRef });
/** Provenance, not the filename, decides which chips are pastes: a user can deliberately
@@ -410,6 +424,7 @@ const ChatForm = memo(function ChatForm({
conversation,
isSubmitting,
answerModeActive: composerReserved,
+ composerDisabled: isPreparingFromUrl,
files,
setFiles,
filesLoading,
@@ -462,8 +477,7 @@ const ChatForm = memo(function ChatForm({
textAreaRef,
submitButtonRef,
setIsScrollable,
- /* Only picks the missing-key placeholder; a batch lock is applied to the
- textarea itself and keeps its own "answer above" placeholder. */
+ /* Only picks the missing-key placeholder; preparation and answer holds live on the textarea. */
disabled: disableInputs,
// The composer IS the free-form answer box while a question pause is live.
placeholder: composerReserved ? answerPlaceholder : placeholder,
@@ -474,8 +488,6 @@ const ChatForm = memo(function ChatForm({
enterToSend,
});
- useQueryParams({ textAreaRef });
-
/** Attachments stand in for text only on the normal send path. Answer mode
* hands the composer text straight to the paused run, which answers with
* values and cannot consume files, so an empty draft must stay unsubmittable
@@ -535,7 +547,11 @@ const ChatForm = memo(function ChatForm({
const { submitText: submitAnswerText } = answerMode;
const dictationAnswerModeActive = answerMode.composerAnswers;
const speechDisabled =
- !speechSettingsInitialized || disableInputs || isNotAppendable || answerMode.composerLocked;
+ !speechSettingsInitialized ||
+ disableInputs ||
+ isNotAppendable ||
+ answerMode.composerLocked ||
+ isPreparingFromUrl;
/** The same gate `onSubmit` applies: while a question pause is live the
* composer IS the answer box, so a dictated turn has to answer it rather
* than start a turn the paused run would drop. */
@@ -597,7 +613,7 @@ const ChatForm = memo(function ChatForm({
stop={handleStopGenerating}
setShowStopButton={setShowStopButton}
canStop={canStop}
- hidden={sendOwnsSlot}
+ hidden={sendOwnsSlot && !isPreparingFromUrl}
/>
) : null;
if (sendOwnsSlot) {
@@ -610,7 +626,7 @@ const ChatForm = memo(function ChatForm({
isNewConversation={isNewConversation}
getText={() => methods.getValues('text')}
onConsumed={consumeComposer}
- disabled={filesLoading}
+ disabled={filesLoading || isPreparingFromUrl}
enterToSend={enterToSend}
/>
{stopButton}
@@ -621,6 +637,7 @@ const ChatForm = memo(function ChatForm({
}, [
consumeComposer,
isNewConversation,
+ isPreparingFromUrl,
steering,
textValue,
methods,
@@ -651,6 +668,7 @@ const ChatForm = memo(function ChatForm({
fileCount={submittableFileCount}
disabled={
filesLoading ||
+ isPreparingFromUrl ||
disableInputs ||
!codeWorkspace.canSubmit ||
isNotAppendable ||
@@ -661,6 +679,7 @@ const ChatForm = memo(function ChatForm({
),
[
codeWorkspace.canSubmit,
+ isPreparingFromUrl,
endpoint,
duringRunSlot,
filesLoading,
@@ -727,7 +746,9 @@ const ChatForm = memo(function ChatForm({
return (
<form
onSubmit={methods.handleSubmit((data) => {
- submitComposerText(data);
+ if (!isPreparingFromUrl && submitComposerText(data) !== false) {
+ clearSettingsError();
+ }
})}
className={cn(
/* `margin-bottom` is animated as well as `max-width`: it is what carries
@@ -883,7 +904,12 @@ const ChatForm = memo(function ChatForm({
textAreaRef as React.MutableRefObject<HTMLTextAreaElement | null>
).current = e;
}}
- disabled={disableInputs || isNotAppendable || answerMode.composerLocked}
+ disabled={
+ disableInputs ||
+ isNotAppendable ||
+ answerMode.composerLocked ||
+ isPreparingFromUrl
+ }
onPaste={handlePaste}
onKeyDown={(e) => {
// Answer mode consumes option-navigation keys from the
@@ -938,6 +964,11 @@ const ChatForm = memo(function ChatForm({
</div>
</div>
)}
+ {(isPreparingFromUrl || urlSettingsError) && (
+ <p role="status" className="text-text-secondary px-5 pb-2 text-sm">
+ {localize(urlSettingsError ? 'com_ui_url_settings_failed' : 'com_ui_sending')}
+ </p>
+ )}
{(codeWorkspace.state === 'choose' || codeWorkspace.state === 'missing') && (
<p
id={`code-workspace-hint-${index}`}
@@ -1038,6 +1069,7 @@ function ChatFormWrapper({
index = 0,
placeholder,
project,
+ routePending = false,
isLandingPage,
/** Defaults to the atom's own default (`atomWithLocalStorage('enterToSend',
* true)`) so call sites that predate this prop, mainly tests, keep their
@@ -1053,6 +1085,7 @@ function ChatFormWrapper({
index?: number;
placeholder?: string;
project?: TChatProject;
+ routePending?: boolean;
enterToSend?: boolean;
autoSendText?: number;
speechSettingsInitialized?: boolean;
@@ -1137,6 +1170,7 @@ function ChatFormWrapper({
speechSettingsInitialized={speechSettingsInitialized}
placeholder={placeholder}
project={project}
+ routePending={routePending}
isLandingPage={isLandingPage}
footerBelow={footerBelow}
centerFormOnLanding={centerFormOnLanding}
diff --git a/client/src/components/Chat/Input/Composer/Bar.tsx b/client/src/components/Chat/Input/Composer/Bar.tsx
index badf9a6ae7..7b7d50c572 100644
--- a/client/src/components/Chat/Input/Composer/Bar.tsx
+++ b/client/src/components/Chat/Input/Composer/Bar.tsx
@@ -524,7 +524,7 @@ function Bar({
primary
label={localize('com_nav_send_message')}
onClick={dictation.stopAndSend}
- disabled={dictation.transcribing}
+ disabled={speechDisabled || dictation.transcribing}
>
<SendIcon size={18} />
</RoundButton>
diff --git a/client/src/components/Chat/Input/DuringRunSendButton.tsx b/client/src/components/Chat/Input/DuringRunSendButton.tsx
index 15d39332cf..e9c2db3cc0 100644
--- a/client/src/components/Chat/Input/DuringRunSendButton.tsx
+++ b/client/src/components/Chat/Input/DuringRunSendButton.tsx
@@ -1,4 +1,4 @@
-import React, { forwardRef, useMemo } from 'react';
+import React, { forwardRef, useMemo, useRef } from 'react';
import { useWatch } from 'react-hook-form';
import { Zap, Clock, OctagonPause, ZapOff } from 'lucide-react';
import { composerSubmitClasses, SendActions, SendIcon } from '@librechat/client';
@@ -42,6 +42,8 @@ const DuringRunSendButton = React.memo(
const localize = useLocalize();
const { shortcutsEnabled, submitOverride, yieldedChords } = useComposerBindings();
const { steering, enterToSend } = props;
+ const disabledRef = useRef(props.disabled);
+ disabledRef.current = props.disabled;
const { steerInterruptsByDefault } = steering;
const data = useWatch({ control: props.control });
const content = data?.text?.trim();
@@ -107,6 +109,9 @@ const DuringRunSendButton = React.memo(
}
const runAction = (action: (text: string) => boolean | void) => {
+ if (disabledRef.current) {
+ return;
+ }
const text = props.getText().trim();
if (text.length === 0) {
return;
@@ -127,7 +132,7 @@ const DuringRunSendButton = React.memo(
kbd: steerKbd,
icon: <Zap className="text-status-warning h-4 w-4" aria-hidden="true" />,
// A staged reasoning choice is a queued full turn, not a live steer.
- disabled: !steering.canSteer || steering.pendingReasoningOverride != null,
+ disabled: props.disabled || !steering.canSteer || steering.pendingReasoningOverride != null,
onClick: () => runAction((text) => steering.steerFromComposer(text)),
};
const queueRow: ActionRow = {
@@ -135,6 +140,7 @@ const DuringRunSendButton = React.memo(
label: localize('com_ui_queue'),
kbd: primary === 'queue' ? submitHint : alternateHint,
icon: <Clock className="text-status-info h-4 w-4" aria-hidden="true" />,
+ disabled: props.disabled,
onClick: () => runAction((text) => steering.queueFromComposer(text)),
};
/** When steering is available, keeps visible text; a new chat instead hard-stops. */
@@ -146,6 +152,7 @@ const DuringRunSendButton = React.memo(
kbd: interruptSteerKbd,
icon: <ZapOff className="text-status-warning h-4 w-4" aria-hidden="true" />,
disabled:
+ props.disabled ||
steering.pausedOnApproval ||
!steering.canControlGeneration ||
steering.pendingReasoningOverride != null,
@@ -156,7 +163,7 @@ const DuringRunSendButton = React.memo(
label: localize('com_ui_interrupt_send'),
kbd: verdicts.altEnter === 'interrupt' ? altEnter : undefined,
icon: <OctagonPause className="text-status-error h-4 w-4" aria-hidden="true" />,
- disabled: !steering.canControlGeneration,
+ disabled: props.disabled || !steering.canControlGeneration,
onClick: () => runAction((text) => steering.interruptAndSend(text)),
};
const rows = primary === 'steer' ? [steerRow, queueRow] : [queueRow, steerRow];
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
new file mode 100644
index 0000000000..cf293107cc
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.queryParams.spec.tsx
@@ -0,0 +1,890 @@
+import React, { useMemo, useState } from 'react';
+import { DndProvider } from 'react-dnd';
+import { useForm } from 'react-hook-form';
+import { RecoilRoot, useRecoilState } from 'recoil';
+import { HTML5Backend } from 'react-dnd-html5-backend';
+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 type { TConversation } from 'librechat-data-provider';
+import type { Transport } from '~/hooks/Chat/contract';
+import type { ChatFormValues } from '~/common';
+import { ChatTransportContext, defaultChatTransport } from '~/Providers/ChatTransportContext';
+import { getNewConversationDraftId, getDraft, setDraft } from '~/utils/drafts';
+import { ChatContext, ChatFormProvider } from '~/Providers';
+import { AuthContextProvider } from '~/hooks/AuthContext';
+import { startupConfigKey } from '~/data-provider';
+import ChatForm from '../ChatForm';
+import store from '~/store';
+
+const initialConversation = {
+ conversationId: 'new',
+ endpoint: EModelEndpoint.openAI,
+ model: 'gpt-4o',
+ title: 'New Chat',
+} as TConversation;
+
+const ask = jest.fn();
+const newConversation = jest.fn();
+const stopGeneration = jest.fn();
+const transport: Transport = {
+ ...defaultChatTransport,
+ listQueued: async () => [],
+ steer: jest.fn(async (params) => ({
+ status: 'queued' as const,
+ steerId: 'test-steer',
+ position: 0,
+ conversationId: params.conversationId,
+ })),
+};
+
+function Harness({
+ conversation,
+ routePending = false,
+ onAsk = ask,
+ speechSettingsInitialized = false,
+}: {
+ conversation: TConversation;
+ routePending?: boolean;
+ onAsk?: typeof ask;
+ speechSettingsInitialized?: boolean;
+}) {
+ const [files, setFiles] = useRecoilState(store.filesByIndex(0));
+ const [isSubmitting] = useRecoilState(store.isSubmittingFamily(0));
+ const [, setFilesLoading] = useState(false);
+ const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });
+ const chatHelpers = useMemo<React.ContextType<typeof ChatContext>>(
+ () => ({
+ index: 0,
+ conversation,
+ setConversation: () => undefined,
+ files,
+ setFiles,
+ isSubmitting,
+ setIsSubmitting: () => undefined,
+ filesLoading: false,
+ setFilesLoading,
+ newConversation,
+ handleStopGenerating: stopGeneration,
+ stopGenerating: () => Promise.resolve(),
+ getMessages: () => [],
+ messagesKey: 'new',
+ latestMessageId: undefined,
+ latestMessageDepth: undefined,
+ feedbackEnabled: false,
+ setMessages: () => undefined,
+ ask: onAsk,
+ regenerate: () => undefined,
+ setSiblingIdx: () => undefined,
+ showPopover: false,
+ setShowPopover: () => undefined,
+ abortScroll: false,
+ setAbortScroll: () => undefined,
+ preset: null,
+ setPreset: () => undefined,
+ optionSettings: {},
+ setOptionSettings: () => undefined,
+ handleRegenerate: () => undefined,
+ handleContinue: () => undefined,
+ }),
+ [conversation, files, setFiles, isSubmitting, onAsk],
+ );
+ return (
+ <ChatFormProvider {...methods}>
+ <ChatContext.Provider value={chatHelpers}>
+ <ChatForm
+ index={0}
+ routePending={routePending}
+ isLandingPage
+ enterToSend
+ autoSendText={-1}
+ speechSettingsInitialized={speechSettingsInitialized}
+ footerBelow={false}
+ centerFormOnLanding={false}
+ />
+ </ChatContext.Provider>
+ </ChatFormProvider>
+ );
+}
+
+function mountComposer(
+ conversation = initialConversation,
+ {
+ pathname = `/c/${conversation.conversationId}`,
+ query = 'agent_id=agent_test&q=hi&submit=true',
+ routePending = false,
+ speechSettingsInitialized = false,
+ liveRun = false,
+ } = {},
+) {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, staleTime: Infinity, cacheTime: Infinity },
+ mutations: { retry: false },
+ },
+ });
+ queryClient.setQueryData([QueryKeys.files], []);
+ queryClient.setQueryData(startupConfigKey(true), { modelSpecs: { list: [] } });
+ queryClient.setQueryData(startupConfigKey(false), { modelSpecs: { list: [] } });
+ queryClient.setQueryData([QueryKeys.fileConfig], {});
+ queryClient.setQueryData([QueryKeys.tokenConfig], {});
+ queryClient.setQueryData([QueryKeys.customConfigSpeech], {});
+ queryClient.setQueryData([QueryKeys.name, EModelEndpoint.openAI], { expiresAt: '' });
+ queryClient.setQueryData([QueryKeys.name, EModelEndpoint.agents], { expiresAt: '' });
+ queryClient.setQueryData([QueryKeys.name, EModelEndpoint.assistants], { expiresAt: '' });
+ queryClient.setQueryData([QueryKeys.messages, conversation.conversationId], []);
+ queryClient.setQueryData([QueryKeys.messages, 'other-chat'], []);
+ queryClient.setQueryData([QueryKeys.messages, 'chat-b'], []);
+ queryClient.setQueryData([QueryKeys.assistant, EModelEndpoint.assistants, 'asst_test'], {
+ id: 'asst_test',
+ model: 'gpt-4o',
+ });
+ queryClient.setQueryData([QueryKeys.toolAuth, 'web_search'], { authenticated: false });
+ queryClient.setQueryData([QueryKeys.toolFavorites], []);
+ queryClient.setQueryData([QueryKeys.skillStates], {});
+ queryClient.setQueryData([QueryKeys.agent, 'agent_test'], {
+ id: 'agent_test',
+ name: 'Test agent',
+ provider: EModelEndpoint.openAI,
+ model: 'gpt-4o',
+ tools: [],
+ });
+ queryClient.setQueryData([QueryKeys.endpoints], {
+ [EModelEndpoint.openAI]: { order: 0 },
+ [EModelEndpoint.agents]: { order: 1 },
+ });
+ let navigate: ReturnType<typeof useNavigate>;
+ let location: ReturnType<typeof useLocation>;
+ function NavigationBridge() {
+ navigate = useNavigate();
+ location = useLocation();
+ return null;
+ }
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot
+ initializeState={({ set }) => {
+ if (liveRun) {
+ set(store.isSubmittingFamily(0), true);
+ set(store.showStopButtonByIndex(0), true);
+ set(store.activeGenerationCreatedAtByConvoId(conversation.conversationId ?? ''), 1000);
+ set(
+ store.activeGenerationProtocolVersionByConvoId(conversation.conversationId ?? ''),
+ 2,
+ );
+ }
+ if (speechSettingsInitialized) {
+ set(store.engineSTT, 'external');
+ set(store.autoTranscribeAudio, false);
+ }
+ }}
+ >
+ <MemoryRouter initialEntries={[`${pathname}?${query}`]}>
+ <NavigationBridge />
+ <AuthContextProvider authConfig={{ loginRedirect: '', test: true }}>
+ <ChatTransportContext.Provider value={transport}>
+ <DndProvider backend={HTML5Backend}>{children}</DndProvider>
+ </ChatTransportContext.Provider>
+ </AuthContextProvider>
+ </MemoryRouter>
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ const view = render(
+ <Harness
+ conversation={conversation}
+ routePending={routePending}
+ speechSettingsInitialized={speechSettingsInitialized}
+ />,
+ {
+ wrapper,
+ },
+ );
+ return { ...view, navigate: (to: string) => navigate(to), getLocation: () => location };
+}
+
+describe('ChatForm URL submission', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ localStorage.clear();
+ ask.mockReset();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('processes a queued prompt URL after ordinary conversation navigation without remounting', async () => {
+ const source = { ...initialConversation, conversationId: 'source-chat' };
+ const view = mountComposer(source, { query: '' });
+ await act(async () => jest.advanceTimersByTime(100));
+ const destinationAsk = jest.fn();
+ await act(async () => {
+ view.navigate('/c/new?prompt=queued+words&submit=true');
+ view.rerender(<Harness conversation={source} routePending onAsk={destinationAsk} />);
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(destinationAsk).not.toHaveBeenCalled();
+ await act(async () => {
+ view.rerender(<Harness conversation={initialConversation} onAsk={destinationAsk} />);
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(destinationAsk).toHaveBeenCalledTimes(1);
+ expect(destinationAsk).toHaveBeenCalledWith(
+ expect.objectContaining({ text: 'queued words' }),
+ expect.anything(),
+ );
+ expect(view.getLocation().search).toBe('');
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('processes a new agent URL once after a previous URL request has completed', async () => {
+ const view = mountComposer(initialConversation, { query: 'q=first&submit=true' });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(ask).toHaveBeenCalledTimes(1);
+ await act(async () => view.navigate('/c/new?agent_id=agent_test&q=second&submit=true'));
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByTestId('text-input')).toHaveValue('second');
+ expect(screen.getByText('Sending...')).toBeInTheDocument();
+ await act(async () => {
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ }}
+ />,
+ );
+ });
+ expect(ask).toHaveBeenCalledTimes(2);
+ expect(ask).toHaveBeenLastCalledWith(
+ expect.objectContaining({ text: 'second' }),
+ expect.anything(),
+ );
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(ask).toHaveBeenCalledTimes(2);
+ expect(view.getLocation().search).toBe('');
+ });
+
+ it('replaces a pending URL request without replaying its timeout into the new request', async () => {
+ const view = mountComposer(initialConversation, {
+ query: 'agent_id=missing&q=old&submit=true',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByTestId('text-input')).toHaveValue('old');
+ await act(async () => view.navigate('/c/new?q=new&submit=true'));
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ text: 'new' }), expect.anything());
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(/Chat settings could not be applied/)).not.toBeInTheDocument();
+ expect(view.getLocation().search).toBe('');
+ });
+
+ it.each(['chat-a', 'chat-b'])(
+ 'waits for route reconciliation while %s remains in the store',
+ async (sourceId) => {
+ const source = { ...initialConversation, conversationId: sourceId };
+ setDraft({ id: sourceId, value: 'source draft' });
+ const view = mountComposer(source, {
+ pathname: '/c/chat-b',
+ query: 'endpoint=openAI&q=hi&submit=true',
+ routePending: true,
+ });
+ await act(async () => jest.advanceTimersByTime(6000));
+ expect(ask).not.toHaveBeenCalled();
+ expect(newConversation).not.toHaveBeenCalled();
+ expect(screen.getByTestId('text-input')).toHaveValue('source draft');
+ expect(view.getLocation().search).toContain('q=hi');
+ const destinationAsk = jest.fn();
+ await act(async () => {
+ view.rerender(
+ <Harness
+ conversation={{ ...initialConversation, conversationId: 'chat-b' }}
+ onAsk={destinationAsk}
+ />,
+ );
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(destinationAsk).toHaveBeenCalledTimes(1);
+ expect(destinationAsk).toHaveBeenCalledWith(
+ expect.objectContaining({ text: 'hi' }),
+ expect.anything(),
+ );
+ expect(ask).not.toHaveBeenCalled();
+ expect(getDraft(sourceId)).toBe('source draft');
+ },
+ );
+
+ it.each(['', 'old draft'])(
+ 'persists an unsent URL prompt over settled draft %p',
+ async (oldDraft) => {
+ const source = { ...initialConversation, conversationId: 'source-chat' };
+ setDraft({ id: source.conversationId, value: oldDraft });
+ const view = mountComposer(source, { query: 'q=hi' });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(getDraft(source.conversationId)).toBe('hi');
+ await act(async () => {
+ view.navigate('/c/other-chat');
+ view.rerender(
+ <Harness conversation={{ ...initialConversation, conversationId: 'other-chat' }} />,
+ );
+ });
+ await act(async () => {
+ view.navigate('/c/source-chat');
+ view.rerender(<Harness conversation={source} />);
+ });
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(ask).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['timeout', 'refusal'])(
+ 'persists a URL prompt after %s without native input',
+ async (outcome) => {
+ setDraft({ id: getNewConversationDraftId(), value: 'old draft' });
+ const source =
+ outcome === 'refusal'
+ ? {
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ }
+ : initialConversation;
+ if (outcome === 'refusal') {
+ ask.mockReturnValueOnce(false);
+ }
+ const view = mountComposer(source);
+ await act(async () => jest.advanceTimersByTime(100));
+ if (outcome === 'timeout') {
+ await act(async () => jest.advanceTimersByTime(3000));
+ }
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(getDraft(getNewConversationDraftId())).toBe('hi');
+ await act(async () => {
+ view.navigate('/c/other-chat');
+ view.rerender(
+ <Harness conversation={{ ...initialConversation, conversationId: 'other-chat' }} />,
+ );
+ });
+ await act(async () => {
+ view.navigate('/c/new');
+ view.rerender(<Harness conversation={source} />);
+ });
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(ask).toHaveBeenCalledTimes(outcome === 'refusal' ? 1 : 0);
+ },
+ );
+
+ it('holds live-run composer actions during URL preparation while leaving Stop available', async () => {
+ mountComposer(
+ { ...initialConversation, conversationId: 'existing-live-chat' },
+ {
+ query: 'endpoint=openAI&model=unavailable-model&q=hi&submit=true',
+ liveRun: true,
+ },
+ );
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByText('Sending...')).toBeInTheDocument();
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(screen.getByTestId('during-run-send-button')).toBeDisabled();
+ expect(screen.queryByTestId('interrupt-steer-button')).not.toBeInTheDocument();
+ const stop = screen.getByRole('button', { name: 'Stop generating' });
+ expect(stop).toBeEnabled();
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('during-run-send-button'));
+ fireEvent.submit(screen.getByTestId('text-input').closest('form') as HTMLFormElement);
+ fireEvent.keyDown(screen.getByTestId('text-input'), {
+ key: 'Enter',
+ ctrlKey: true,
+ shiftKey: true,
+ });
+ });
+ expect(transport.steer).not.toHaveBeenCalled();
+ expect(ask).not.toHaveBeenCalled();
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ await act(async () => fireEvent.click(stop));
+ expect(stopGeneration).toHaveBeenCalledTimes(1);
+ expect(transport.steer).not.toHaveBeenCalled();
+ });
+
+ it('disables the microphone while URL settings are preparing and re-enables it on timeout', async () => {
+ mountComposer(initialConversation, { speechSettingsInitialized: true });
+ expect(screen.getByRole('button', { name: 'Use microphone' })).not.toBeDisabled();
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByRole('button', { name: 'Use microphone' })).toBeDisabled();
+ expect(screen.getByText('Sending...')).toBeInTheDocument();
+ await act(async () => jest.advanceTimersByTime(3000));
+ expect(screen.getByRole('button', { name: 'Use microphone' })).not.toBeDisabled();
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('disables recording send during URL preparation without disabling stop', async () => {
+ const recorderDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'MediaRecorder');
+ const devicesDescriptor = Object.getOwnPropertyDescriptor(navigator, 'mediaDevices');
+ const audioContextDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'AudioContext');
+ const tracks: jest.Mock[] = [];
+ class TestRecorder extends EventTarget {
+ static isTypeSupported = () => true;
+
+ state: RecordingState = 'inactive';
+
+ start() {
+ this.state = 'recording';
+ }
+
+ stop() {
+ this.state = 'inactive';
+ this.dispatchEvent(new Event('stop'));
+ }
+ }
+ class TestAudioContext {
+ state: AudioContextState = 'running';
+
+ close() {
+ this.state = 'closed';
+ return Promise.resolve();
+ }
+
+ createMediaStreamSource() {
+ return { connect: () => undefined };
+ }
+
+ createAnalyser() {
+ return { fftSize: 1024, getByteTimeDomainData: (buffer: Uint8Array) => buffer.fill(128) };
+ }
+ }
+ Object.defineProperty(globalThis, 'MediaRecorder', { configurable: true, value: TestRecorder });
+ Object.defineProperty(globalThis, 'AudioContext', {
+ configurable: true,
+ value: TestAudioContext,
+ });
+ Object.defineProperty(navigator, 'mediaDevices', {
+ configurable: true,
+ value: {
+ getUserMedia: async () => {
+ const stop = jest.fn();
+ tracks.push(stop);
+ return { getTracks: () => [{ stop }] };
+ },
+ },
+ });
+ setDraft({ id: getNewConversationDraftId(), value: 'unsent draft' });
+ const view = mountComposer(initialConversation, { speechSettingsInitialized: true });
+ try {
+ await act(async () =>
+ fireEvent.click(screen.getByRole('button', { name: 'Use microphone' })),
+ );
+ expect(screen.getByRole('button', { name: 'Stop' })).not.toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Send message' })).not.toBeDisabled();
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByRole('button', { name: 'Send message' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Stop' })).not.toBeDisabled();
+ await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Stop' })));
+ expect(tracks[0]).toHaveBeenCalledTimes(1);
+ expect(ask).not.toHaveBeenCalled();
+ } finally {
+ view.unmount();
+ if (recorderDescriptor)
+ Object.defineProperty(globalThis, 'MediaRecorder', recorderDescriptor);
+ else Reflect.deleteProperty(globalThis, 'MediaRecorder');
+ if (devicesDescriptor) Object.defineProperty(navigator, 'mediaDevices', devicesDescriptor);
+ else Reflect.deleteProperty(navigator, 'mediaDevices');
+ if (audioContextDescriptor)
+ Object.defineProperty(globalThis, 'AudioContext', audioContextDescriptor);
+ else Reflect.deleteProperty(globalThis, 'AudioContext');
+ }
+ });
+
+ it('shows the prompt and Sending status while blocking duplicate manual sends', async () => {
+ mountComposer();
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(screen.getByTestId('text-input')).toBeDisabled();
+ expect(screen.getByTestId('send-button')).toBeDisabled();
+ expect(screen.getByText('Sending...')).toHaveAttribute('role', 'status');
+ await act(async () => {
+ fireEvent.submit(screen.getByTestId('text-input').closest('form') as HTMLFormElement);
+ });
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('keeps the draft and explains a timeout instead of sending to a different agent', async () => {
+ mountComposer();
+ await act(async () => jest.advanceTimersByTime(100));
+ await act(async () => jest.advanceTimersByTime(3000));
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(screen.getByText(/Chat settings could not be applied/)).toHaveAttribute(
+ 'role',
+ 'status',
+ );
+ expect(ask).not.toHaveBeenCalled();
+ await act(async () => {
+ fireEvent.submit(screen.getByTestId('text-input').closest('form') as HTMLFormElement);
+ });
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(/Chat settings could not be applied/)).not.toBeInTheDocument();
+ });
+
+ it.each(['', 'unrelated saved message'])(
+ 'preserves the URL prompt when the new conversation restores draft %p',
+ async (savedText) => {
+ setDraft({ id: getNewConversationDraftId(), value: savedText });
+ const view = mountComposer({
+ ...initialConversation,
+ conversationId: 'existing-assistants-chat',
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst_test',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ }}
+ />,
+ );
+ await act(async () => Promise.resolve());
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ text: 'hi' }), expect.anything());
+ },
+ );
+
+ it.each([EModelEndpoint.openAI, EModelEndpoint.agents])(
+ 'cancels the URL request when navigating to another %s chat',
+ async (endpoint) => {
+ setDraft({ id: 'other-chat', value: 'destination draft' });
+ const view = mountComposer();
+ await act(async () => jest.advanceTimersByTime(100));
+ await act(async () => {
+ view.navigate('/c/other-chat');
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ conversationId: 'other-chat',
+ endpoint,
+ ...(endpoint === EModelEndpoint.agents ? { agent_id: 'agent_test' } : {}),
+ }}
+ />,
+ );
+ });
+ expect(screen.getByTestId('text-input')).toHaveValue('destination draft');
+ expect(screen.getByTestId('text-input')).not.toBeDisabled();
+ expect(screen.queryByText('Sending...')).not.toBeInTheDocument();
+ expect(ask).not.toHaveBeenCalled();
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(screen.getByTestId('text-input')).toHaveValue('destination draft');
+ expect(screen.queryByText(/Chat settings could not be applied/)).not.toBeInTheDocument();
+ expect(ask).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['', 'original unsent draft'])(
+ 'preserves the departing chat draft %p when a URL prompt starts another chat',
+ async (sourceDraft) => {
+ const sourceConversation = {
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst_test',
+ };
+ setDraft({ id: sourceConversation.conversationId, value: sourceDraft });
+ const view = mountComposer(sourceConversation);
+ expect(screen.getByTestId('text-input')).toHaveValue(sourceDraft);
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ await act(async () => {
+ view.navigate('/c/new?agent_id=agent_test&q=hi&submit=true');
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ }}
+ />,
+ );
+ });
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ text: 'hi' }), expect.anything());
+ expect(getDraft(sourceConversation.conversationId) ?? '').toBe(sourceDraft);
+ await act(async () => {
+ view.navigate('/c/existing-chat');
+ view.rerender(<Harness conversation={sourceConversation} />);
+ });
+ expect(screen.getByTestId('text-input')).toHaveValue(sourceDraft);
+ },
+ );
+
+ it('preserves the source draft if the URL request is cancelled before its switch completes', async () => {
+ const sourceConversation = {
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst_test',
+ };
+ setDraft({ id: sourceConversation.conversationId, value: 'original unsent draft' });
+ setDraft({ id: 'other-chat', value: 'destination draft' });
+ const view = mountComposer(sourceConversation);
+ await act(async () => jest.advanceTimersByTime(100));
+ await act(async () => {
+ view.navigate('/c/other-chat');
+ view.rerender(
+ <Harness conversation={{ ...initialConversation, conversationId: 'other-chat' }} />,
+ );
+ });
+ expect(screen.getByTestId('text-input')).toHaveValue('destination draft');
+ expect(getDraft(sourceConversation.conversationId)).toBe('original unsent draft');
+ expect(ask).not.toHaveBeenCalled();
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(getDraft(sourceConversation.conversationId)).toBe('original unsent draft');
+ });
+
+ it.each([null, 'project-one'])(
+ 'submits changed settings in an existing conversation with project %p',
+ async (chatProjectId) => {
+ const conversation = {
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ chatProjectId,
+ };
+ const view = mountComposer(conversation, {
+ query: 'endpoint=openAI&model=gpt-4.1&q=hi&submit=true',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(newConversation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ template: expect.objectContaining({ conversationId: 'existing-chat', chatProjectId }),
+ preset: expect.objectContaining({ model: 'gpt-4.1' }),
+ }),
+ );
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(screen.getByText('Sending...')).toBeInTheDocument();
+ expect(ask).not.toHaveBeenCalled();
+ await act(async () => {
+ view.rerender(<Harness conversation={{ ...conversation, model: 'gpt-4.1' }} />);
+ });
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ text: 'hi' }), expect.anything());
+ expect(view.getLocation().pathname).toBe('/c/existing-chat');
+ expect(view.getLocation().search).toBe('');
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(/Chat settings could not be applied/)).not.toBeInTheDocument();
+ },
+ );
+
+ it('retains timeout guidance for unapplied settings in an existing project conversation', async () => {
+ const conversation = {
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ chatProjectId: 'project-one',
+ };
+ const view = mountComposer(conversation, {
+ query: 'endpoint=openAI&model=gpt-4.1&q=hi&submit=true',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByText('Sending...')).toBeInTheDocument();
+ await act(async () => jest.advanceTimersByTime(3000));
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(screen.getByText(/Chat settings could not be applied/)).toBeInTheDocument();
+ expect(getDraft(conversation.conversationId)).toBe('hi');
+ expect(view.getLocation().search).toBe('');
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('cancels when the existing conversation project changes before settings apply', async () => {
+ const conversation = {
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ chatProjectId: 'project-one',
+ };
+ const view = mountComposer(conversation, {
+ query: 'endpoint=openAI&model=gpt-4.1&q=hi&submit=true',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(screen.getByText('Sending...')).toBeInTheDocument();
+ await act(async () => {
+ view.rerender(
+ <Harness
+ conversation={{ ...conversation, model: 'gpt-4.1', chatProjectId: 'project-two' }}
+ />,
+ );
+ });
+ expect(screen.queryByText('Sending...')).not.toBeInTheDocument();
+ expect(ask).not.toHaveBeenCalled();
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(screen.queryByText(/Chat settings could not be applied/)).not.toBeInTheDocument();
+ expect(view.getLocation().search).toContain('submit=true');
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('clears settled setup guidance when leaving for another chat', async () => {
+ setDraft({ id: 'other-chat', value: 'destination draft' });
+ const view = mountComposer();
+ await act(async () => jest.advanceTimersByTime(3100));
+ expect(screen.getByText(/Chat settings could not be applied/)).toBeInTheDocument();
+ await act(async () => {
+ view.navigate('/c/other-chat');
+ view.rerender(
+ <Harness conversation={{ ...initialConversation, conversationId: 'other-chat' }} />,
+ );
+ });
+ expect(screen.getByTestId('text-input')).toHaveValue('destination draft');
+ expect(screen.queryByText(/Chat settings could not be applied/)).not.toBeInTheDocument();
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('allows its own URL-preserving switch from an existing chat to a new one', async () => {
+ const view = mountComposer({
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst_test',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ await act(async () => {
+ view.navigate('/c/new?agent_id=agent_test&q=hi&submit=true');
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ }}
+ />,
+ );
+ });
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ text: 'hi' }), expect.anything());
+ });
+
+ it.each(['', 'unrelated saved draft'])(
+ 'submits across the inherited project rewrite with destination draft %p',
+ async (savedText) => {
+ setDraft({ id: getNewConversationDraftId(), value: savedText });
+ const view = mountComposer({
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ chatProjectId: 'project-one',
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst_test',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ expect(newConversation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ template: expect.objectContaining({ chatProjectId: 'project-one' }),
+ }),
+ );
+ await act(async () => {
+ view.navigate('/c/new?agent_id=agent_test&q=hi&submit=true&projectId=project-one');
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ chatProjectId: 'project-one',
+ }}
+ />,
+ );
+ });
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ text: 'hi' }), expect.anything());
+ expect(view.getLocation().search).toBe('?projectId=project-one');
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(screen.queryByText(/Chat settings could not be applied/)).not.toBeInTheDocument();
+ },
+ );
+
+ it('preserves the inherited project during setup-timeout URL cleanup', async () => {
+ const view = mountComposer({
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ chatProjectId: 'project-one',
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst_test',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ await act(async () => {
+ view.navigate('/c/new?agent_id=agent_test&q=hi&submit=true&projectId=project-one');
+ view.rerender(
+ <Harness conversation={{ ...initialConversation, chatProjectId: 'project-one' }} />,
+ );
+ });
+ expect(screen.getByText('Sending...')).toBeInTheDocument();
+ await act(async () => jest.advanceTimersByTime(3000));
+ expect(screen.getByTestId('text-input')).toHaveValue('hi');
+ expect(screen.getByText(/Chat settings could not be applied/)).toBeInTheDocument();
+ expect(view.getLocation().search).toBe('?projectId=project-one');
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unrelated project rewrite even when it retains the submission query', async () => {
+ const view = mountComposer({
+ ...initialConversation,
+ conversationId: 'existing-chat',
+ chatProjectId: 'project-one',
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst_test',
+ });
+ await act(async () => jest.advanceTimersByTime(100));
+ setDraft({ id: getNewConversationDraftId(), value: 'destination draft' });
+ await act(async () => {
+ view.navigate('/c/new?agent_id=agent_test&q=hi&submit=true&projectId=project-two');
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ chatProjectId: 'project-two',
+ }}
+ />,
+ );
+ });
+ expect(screen.getByTestId('text-input')).toHaveValue('destination draft');
+ expect(screen.getByTestId('text-input')).not.toBeDisabled();
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(view.getLocation().search).toContain('projectId=project-two');
+ expect(screen.getByTestId('text-input')).toHaveValue('destination draft');
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('sends the visible prompt once when the requested agent reaches the conversation', async () => {
+ const view = mountComposer();
+ await act(async () => jest.advanceTimersByTime(100));
+ view.rerender(
+ <Harness
+ conversation={{
+ ...initialConversation,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ }}
+ />,
+ );
+ await act(async () => Promise.resolve());
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(ask).toHaveBeenCalledWith(expect.objectContaining({ text: 'hi' }), expect.anything());
+ expect(screen.queryByText('Sending...')).not.toBeInTheDocument();
+ await act(async () => jest.advanceTimersByTime(4000));
+ expect(ask).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
index 90d751f6b8..7da8d50860 100644
--- a/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
+++ b/client/src/components/Chat/Input/__tests__/DuringRunSendButton.test.tsx
@@ -58,10 +58,12 @@ function Harness({
steering,
isNewConversation,
enterToSend,
+ disabled = false,
}: {
steering: SteeringControls;
isNewConversation: boolean;
enterToSend: boolean;
+ disabled?: boolean;
}) {
const methods = useForm<{ text: string }>({ defaultValues: { text: TEXT } });
return (
@@ -72,6 +74,7 @@ function Harness({
getText={() => TEXT}
onConsumed={mockOnConsumed}
enterToSend={enterToSend}
+ disabled={disabled}
/>
);
}
@@ -116,6 +119,43 @@ beforeEach(() => {
jest.clearAllMocks();
});
+describe('DuringRunSendButton — external hold', () => {
+ test('holds every open hovercard action and restores them when the hold lifts', () => {
+ const controls = steeringStub({});
+ const frame = (disabled: boolean) => (
+ <RecoilRoot>
+ <Harness steering={controls} isNewConversation={false} enterToSend disabled={disabled} />
+ </RecoilRoot>
+ );
+ const view = render(frame(false));
+ const labels = [
+ 'com_ui_steer',
+ 'com_ui_queue',
+ 'com_ui_interrupt_steer',
+ 'com_ui_interrupt_send',
+ ];
+ view.rerender(frame(true));
+ expect(screen.getByTestId('during-run-send-button')).toBeDisabled();
+ for (const label of labels) {
+ const row = screen.getByText(label).closest('button') as HTMLButtonElement;
+ expect(row).toHaveAttribute('aria-disabled', 'true');
+ expect(row.querySelector('kbd')).toBeNull();
+ fireEvent.click(row);
+ }
+ expect(mockInterruptSteer).not.toHaveBeenCalled();
+ expect(mockSteerFromComposer).not.toHaveBeenCalled();
+ expect(mockQueueFromComposer).not.toHaveBeenCalled();
+ expect(mockInterruptAndSend).not.toHaveBeenCalled();
+ expect(mockOnConsumed).not.toHaveBeenCalled();
+ view.rerender(frame(false));
+ const queue = screen.getByText('com_ui_queue').closest('button') as HTMLButtonElement;
+ expect(queue).toHaveAttribute('aria-disabled', 'false');
+ fireEvent.click(queue);
+ expect(mockQueueFromComposer).toHaveBeenCalledWith(TEXT);
+ expect(mockOnConsumed).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('DuringRunSendButton — Interrupt & steer availability', () => {
/**
* `useSteering.interruptSteer` hard-refuses while a run is paused for tool
diff --git a/client/src/components/Chat/__tests__/ChatView.spec.tsx b/client/src/components/Chat/__tests__/ChatView.spec.tsx
index e8d4d94b8a..a7fcf6876f 100644
--- a/client/src/components/Chat/__tests__/ChatView.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.spec.tsx
@@ -149,6 +149,11 @@ describe('ChatView composer preferences', () => {
);
});
+ test.each([true, false])('passes routePending=%p into ChatForm', (routePending) => {
+ render(<ChatView routePending={routePending} />);
+ expect(mockChatFormProps).toHaveBeenCalledWith(expect.objectContaining({ routePending }));
+ });
+
test('falls back to the atom default when nothing is persisted', () => {
render(<ChatView />);
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index d4ffa3e7f7..0cee03c406 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -214,6 +214,50 @@ describe('useSteering', () => {
mockFileMap = {};
});
+ it.each([
+ 'steerFromComposer',
+ 'queueFromComposer',
+ 'interruptAndSend',
+ 'interruptSteer',
+ 'submitDuringRun',
+ ] as const)('holds captured %s callbacks without consuming composer context', (action) => {
+ const consumeDraft = jest.fn();
+ const setFiles = jest.fn();
+ const files = new Map<string, ExtendedFile>([
+ ['file-one', { file_id: 'file-one', type: 'text/plain', progress: 1 } as ExtendedFile],
+ ]);
+ const params: HookParams = {
+ composerDisabled: false,
+ conversation: { ...agentsConversation, endpoint: EModelEndpoint.openAI },
+ files,
+ setFiles,
+ consumeDraft,
+ };
+ const { result, rerender, stopGenerating, sendNow } = setup(params, ({ set }) => {
+ set(store.pendingQuotesByConvoId(CONVO_ID), ['preserved quote']);
+ });
+ const captured = result.current[action];
+ params.composerDisabled = true;
+ rerender();
+ act(() => expect(captured('hi')).toBe(false));
+ expect(consumeDraft).not.toHaveBeenCalled();
+ expect(setFiles).not.toHaveBeenCalled();
+ expect(mockMutate).not.toHaveBeenCalled();
+ expect(mockEnqueueQueuedTurn).not.toHaveBeenCalled();
+ expect(stopGenerating).not.toHaveBeenCalled();
+ expect(sendNow).not.toHaveBeenCalled();
+ expect(getDefaultStore().get(queuedMessagesByConvoId(CONVO_ID))).toEqual([]);
+ params.composerDisabled = false;
+ rerender();
+ act(() => expect(result.current.queueFromComposer('hi')).toBe(true));
+ expect(consumeDraft).toHaveBeenCalledTimes(1);
+ expect(getDefaultStore().get(queuedMessagesByConvoId(CONVO_ID))[0]).toMatchObject({
+ text: 'hi',
+ quotes: ['preserved quote'],
+ files: [expect.objectContaining({ file_id: 'file-one' })],
+ });
+ });
+
it.each([true, false])(
'reserves a recovery against queue drain while cancelling (removed=%s)',
async (removed) => {
diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts
index 303ac699f1..2bd8eb89c3 100644
--- a/client/src/hooks/Chat/useSteering.ts
+++ b/client/src/hooks/Chat/useSteering.ts
@@ -546,6 +546,8 @@ export interface UseSteeringParams {
addedConversation?: TConversation | null;
isSubmitting: boolean;
answerModeActive: boolean;
+ /** Host-owned preparation hold; existing queued-message and Stop actions remain independent. */
+ composerDisabled?: boolean;
/** Composer attachments: consumed into queued items (steering is text-only). */
files?: Map<string, ExtendedFile>;
setFiles?: FileSetter;
@@ -581,6 +583,7 @@ export default function useSteering({
addedConversation,
isSubmitting,
answerModeActive,
+ composerDisabled = false,
files,
setFiles,
filesLoading = false,
@@ -588,6 +591,8 @@ export default function useSteering({
stopGenerating,
}: UseSteeringParams) {
const localize = useLocalize();
+ const composerDisabledRef = useRef(composerDisabled);
+ composerDisabledRef.current = composerDisabled;
const reasoningStore = useStore();
const { showToast } = useToastContext();
const jotaiStore = useStore();
@@ -2216,7 +2221,7 @@ export default function useSteering({
const steerFromComposer = useCallback(
(text: string, preempt = false): boolean => {
const trimmed = text.trim();
- if (trimmed.length === 0 || filesLoading || !canSteer) {
+ if (composerDisabledRef.current || trimmed.length === 0 || filesLoading || !canSteer) {
return false;
}
/** A live steer cannot change the provider request already in flight.
@@ -2255,7 +2260,7 @@ export default function useSteering({
const queueFromComposer = useCallback(
(text: string): boolean => {
const trimmed = text.trim();
- if (trimmed.length === 0 || filesLoading) {
+ if (composerDisabledRef.current || trimmed.length === 0 || filesLoading) {
return false;
}
enqueue(trimmed, {
@@ -2498,7 +2503,12 @@ export default function useSteering({
const interruptAndSend = useCallback(
(text: string): boolean => {
const trimmed = text.trim();
- if (trimmed.length === 0 || filesLoading || !canControlGeneration) {
+ if (
+ composerDisabledRef.current ||
+ trimmed.length === 0 ||
+ filesLoading ||
+ !canControlGeneration
+ ) {
return false;
}
enqueue(trimmed, {
@@ -2545,7 +2555,13 @@ export default function useSteering({
const interruptSteer = useCallback(
(text: string): boolean => {
const trimmed = text.trim();
- if (trimmed.length === 0 || filesLoading || pausedOnApproval || !canControlGeneration) {
+ if (
+ composerDisabledRef.current ||
+ trimmed.length === 0 ||
+ filesLoading ||
+ pausedOnApproval ||
+ !canControlGeneration
+ ) {
return false;
}
/* A staged reasoning choice belongs to a new generation, which a steer
@@ -2585,7 +2601,7 @@ export default function useSteering({
/** Routes a during-run submit to the effective action. Returns true when consumed. */
const submitDuringRun = useCallback(
(text: string): boolean => {
- if (!duringRunActive) {
+ if (composerDisabledRef.current || !duringRunActive) {
return false;
}
if (effectiveAction === 'steer') {
diff --git a/client/src/hooks/Input/__tests__/useDictation.spec.tsx b/client/src/hooks/Input/__tests__/useDictation.spec.tsx
index 8942879f84..330a13ec9f 100644
--- a/client/src/hooks/Input/__tests__/useDictation.spec.tsx
+++ b/client/src/hooks/Input/__tests__/useDictation.spec.tsx
@@ -62,6 +62,7 @@ function setup({
speechToText = true,
draft = '',
isSubmitting = false,
+ duringRunSubmit,
filesLoading = false,
deferComposerReset = false,
disabled = false,
@@ -71,6 +72,7 @@ function setup({
speechToText?: boolean;
draft?: string;
isSubmitting?: boolean;
+ duringRunSubmit?: (text: string) => boolean | void;
filesLoading?: boolean;
deferComposerReset?: boolean;
disabled?: boolean;
@@ -78,6 +80,7 @@ function setup({
} = {}) {
let text = draft;
let uploading = filesLoading;
+ let speechDisabled = disabled;
const methods = {
setValue: jest.fn((_name: string, value: string) => {
text = value;
@@ -92,9 +95,10 @@ function setup({
ask: ask as unknown as TAskFunction,
methods: methods as never,
isSubmitting,
+ duringRunSubmit,
filesLoading: uploading,
deferComposerReset,
- disabled,
+ disabled: speechDisabled,
autoSendText,
speechToText,
index,
@@ -108,6 +112,9 @@ function setup({
setFilesLoading: (value: boolean) => {
uploading = value;
},
+ setDisabled: (value: boolean) => {
+ speechDisabled = value;
+ },
};
}
@@ -234,6 +241,86 @@ describe('useDictation', () => {
expect(mockStart).not.toHaveBeenCalled();
});
+ it('blocks a captured external auto-send callback when the host becomes disabled', async () => {
+ mockSpeechEndpoint = 'external';
+ const { result, rerender, currentText, methods, setDisabled } = setup({
+ autoSendText: 0,
+ draft: 'hi',
+ });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+ act(() => result.current.stopToComposer());
+ const complete = mockOnTranscriptionComplete;
+ setDisabled(true);
+ act(() => rerender());
+ act(() => mockSetTextCallback('dictated words'));
+ await settle(rerender);
+ act(() => complete('dictated words'));
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('hi dictated words');
+ expect(methods.reset).not.toHaveBeenCalled();
+ setDisabled(false);
+ act(() => rerender());
+ act(() => complete('dictated words'));
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('stands an armed recording send down if the host disables speech before it settles', async () => {
+ const { result, rerender, currentText, setDisabled } = setup();
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+ act(() => result.current.stopAndSend());
+ setDisabled(true);
+ act(() => rerender());
+ act(() => mockSetTextCallback('keep these words'));
+ await settle(rerender);
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('keep these words');
+ setDisabled(false);
+ act(() => rerender());
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('holds a transcript before invoking the during-run route', async () => {
+ const duringRunSubmit = jest.fn();
+ const { result, rerender, currentText, setDisabled } = setup({
+ isSubmitting: true,
+ duringRunSubmit,
+ });
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+ act(() => result.current.stopAndSend());
+ setDisabled(true);
+ act(() => rerender());
+ act(() => mockSetTextCallback('do not steer yet'));
+ await settle(rerender);
+ expect(duringRunSubmit).not.toHaveBeenCalled();
+ expect(ask).not.toHaveBeenCalled();
+ expect(currentText()).toBe('do not steer yet');
+ });
+
+ it('refuses a stale recording-send action during the hold but leaves stop and cancel available', async () => {
+ const { result, rerender, setDisabled } = setup();
+ act(() => result.current.start());
+ mockIsListening = true;
+ act(() => rerender());
+ const stopAndSend = result.current.stopAndSend;
+ setDisabled(true);
+ act(() => rerender());
+ act(() => stopAndSend());
+ expect(mockStop).not.toHaveBeenCalled();
+ expect(result.current.startDisabled).toBe(true);
+ act(() => result.current.stopToComposer());
+ expect(mockStop).toHaveBeenCalledTimes(1);
+ await settle(rerender);
+ expect(ask).not.toHaveBeenCalled();
+ act(() => result.current.cancel());
+ expect(mockAbort).toHaveBeenCalledTimes(1);
+ });
+
it('leaves a plain stop in the composer', async () => {
const { result, rerender, currentText } = setup();
act(() => result.current.start());
diff --git a/client/src/hooks/Input/useAutoSave.spec.ts b/client/src/hooks/Input/useAutoSave.spec.ts
index 5927d39067..d878185489 100644
--- a/client/src/hooks/Input/useAutoSave.spec.ts
+++ b/client/src/hooks/Input/useAutoSave.spec.ts
@@ -131,6 +131,145 @@ describe('useAutoSave — conversation switching', () => {
expect(mockSetDraft).toHaveBeenCalledWith({ id: 'convo-1', value: 'draft in progress' });
});
+ it('preserves live text before replacement and saves it when switching away', () => {
+ const textAreaRef = { current: document.createElement('textarea') };
+ const { result, rerender } = renderHook(
+ ({ conversationId }: { conversationId: string }) =>
+ useAutoSave({ conversationId, textAreaRef, files: new Map(), setFiles: jest.fn() }),
+ { initialProps: { conversationId: 'convo-1' } },
+ );
+ textAreaRef.current.value = 'original unsent draft';
+ act(() => result.current.preserveText());
+ textAreaRef.current.value = 'URL prompt';
+ mockSetDraft.mockClear();
+ act(() => rerender({ conversationId: 'convo-2' }));
+ expect(mockSetDraft).toHaveBeenCalledWith({ id: 'convo-1', value: 'original unsent draft' });
+ expect(mockSetDraft).not.toHaveBeenCalledWith({ id: 'convo-1', value: 'URL prompt' });
+ });
+
+ it('flushes an earlier input debounce without persisting the programmatic replacement', () => {
+ jest.useFakeTimers();
+ const textAreaRef = { current: document.createElement('textarea') };
+ const { result, unmount } = renderHook(() =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ textAreaRef,
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ );
+ textAreaRef.current.value = 'unfinished typing';
+ textAreaRef.current.dispatchEvent(new Event('input'));
+ act(() => result.current.preserveText());
+ textAreaRef.current.value = 'URL prompt';
+ mockSetDraft.mockClear();
+ unmount();
+ expect(mockSetDraft).toHaveBeenCalledWith({ id: 'convo-1', value: 'unfinished typing' });
+ expect(mockSetDraft).not.toHaveBeenCalledWith({ id: 'convo-1', value: 'URL prompt' });
+ jest.useRealTimers();
+ });
+
+ it('persists a settled replacement in the current draft without native input', () => {
+ const textAreaRef = { current: document.createElement('textarea') };
+ const { result, rerender } = renderHook(
+ ({ conversationId }: { conversationId: string }) =>
+ useAutoSave({ conversationId, textAreaRef, files: new Map(), setFiles: jest.fn() }),
+ { initialProps: { conversationId: 'convo-1' } },
+ );
+ textAreaRef.current.value = 'original draft';
+ act(() => result.current.preserveText());
+ textAreaRef.current.value = 'retained URL prompt';
+ act(() => result.current.settleText('retained URL prompt', 'convo-1'));
+ mockSetDraft.mockClear();
+ act(() => rerender({ conversationId: 'convo-2' }));
+ expect(mockSetDraft).toHaveBeenCalledWith({ id: 'convo-1', value: 'retained URL prompt' });
+ expect(mockSetDraft).not.toHaveBeenCalledWith({ id: 'convo-1', value: 'original draft' });
+ });
+
+ it('settles into the requested new-chat draft without overwriting the departing source', () => {
+ const textAreaRef = { current: document.createElement('textarea') };
+ const { result, rerender } = renderHook(
+ ({ conversationId }: { conversationId: string }) =>
+ useAutoSave({ conversationId, textAreaRef, files: new Map(), setFiles: jest.fn() }),
+ { initialProps: { conversationId: 'convo-1' } },
+ );
+ textAreaRef.current.value = 'original source draft';
+ act(() => result.current.preserveText());
+ textAreaRef.current.value = 'retained URL prompt';
+ act(() => result.current.settleText('retained URL prompt', Constants.NEW_CONVO));
+ expect(mockSetDraft).toHaveBeenCalledWith({
+ id: Constants.NEW_CONVO,
+ value: 'retained URL prompt',
+ });
+ mockSetDraft.mockClear();
+ act(() => rerender({ conversationId: Constants.NEW_CONVO as string }));
+ expect(mockSetDraft).toHaveBeenCalledWith({ id: 'convo-1', value: 'original source draft' });
+ expect(mockSetDraft).not.toHaveBeenCalledWith({ id: 'convo-1', value: 'retained URL prompt' });
+ });
+
+ it('does not replace another live tab’s draft during settlement', () => {
+ markTabLive('other-tab');
+ setFilesDraft('convo-1', { fileIds: ['theirs'], pendingPastes: {}, tabId: 'other-tab' });
+ const textAreaRef = { current: document.createElement('textarea') };
+ mockSetDraft.mockImplementation(jest.requireActual('~/utils').setDraft);
+ localStorage.setItem(`${LocalStorageKeys.TEXT_DRAFT}convo-1`, encodeBase64('their draft'));
+ const { result } = renderHook(() =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ textAreaRef,
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ );
+ act(() => result.current.settleText('our URL prompt', 'convo-1'));
+ expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}convo-1`)).toBe(
+ encodeBase64('their draft'),
+ );
+ mockSetDraft.mockReset();
+ });
+
+ it('resumes normal persistence when the user edits the programmatically replaced text', () => {
+ jest.useFakeTimers();
+ const textAreaRef = { current: document.createElement('textarea') };
+ const { result } = renderHook(() =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ textAreaRef,
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ );
+ textAreaRef.current.value = 'original unsent draft';
+ act(() => result.current.preserveText());
+ textAreaRef.current.value = 'edited URL prompt';
+ textAreaRef.current.dispatchEvent(new Event('input'));
+ act(() => jest.advanceTimersByTime(25));
+ expect(mockSetDraft).toHaveBeenLastCalledWith({ id: 'convo-1', value: 'edited URL prompt' });
+ jest.useRealTimers();
+ });
+
+ it('does not overwrite another live tab’s draft while preserving replacement text', () => {
+ markTabLive('other-tab');
+ setFilesDraft('convo-1', { fileIds: ['theirs'], pendingPastes: {}, tabId: 'other-tab' });
+ const textAreaRef = { current: document.createElement('textarea') };
+ mockSetDraft.mockImplementation(jest.requireActual('~/utils').setDraft);
+ localStorage.setItem(`${LocalStorageKeys.TEXT_DRAFT}convo-1`, encodeBase64('their draft'));
+ const { result } = renderHook(() =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ textAreaRef,
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ );
+ textAreaRef.current.value = 'our text';
+ act(() => result.current.preserveText());
+ expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}convo-1`)).toBe(
+ encodeBase64('their draft'),
+ );
+ mockSetDraft.mockReset();
+ });
+
it('restores an incomplete pasted-text upload into the composer after reload', () => {
mockGetDraft.mockReturnValue('before after');
setFilesDraft('convo-1', {
@@ -936,7 +1075,7 @@ describe('useAutoSave — file cache updates', () => {
localStorage.setItem(pendingTextKey, encodeBase64('submitted text'));
localStorage.setItem(foreignTextKey, encodeBase64('their text'));
act(() => rerender({ isSubmitting: false }));
- act(() => result.current());
+ act(() => result.current.consumeDraft());
expect(clearAllDrafts).toHaveBeenLastCalledWith(Constants.PENDING_CONVO);
expect(localStorage.getItem(pendingTextKey)).toBeNull();
expect(getFilesDraft(Constants.PENDING_CONVO).fileIds).toEqual([]);
diff --git a/client/src/hooks/Input/useAutoSave.ts b/client/src/hooks/Input/useAutoSave.ts
index 8c42d91634..cba8b39529 100644
--- a/client/src/hooks/Input/useAutoSave.ts
+++ b/client/src/hooks/Input/useAutoSave.ts
@@ -65,6 +65,14 @@ export const useAutoSave = ({
const { data: fileList } = useGetFiles<TFile[]>();
const filesRef = useRef(files);
filesRef.current = files;
+ const preservedTextRef = useRef<{ id: string; text: string } | null>(null);
+ const readTextToSave = useCallback(
+ (id: string) =>
+ preservedTextRef.current?.id === id
+ ? preservedTextRef.current.text
+ : (textAreaRef?.current?.value ?? ''),
+ [textAreaRef],
+ );
/** Publishes what this composer holds so cleanup running in another tab can see it. Not gated
* on `saveDrafts`: with draft saving off nothing is persisted at all, which is exactly when a
@@ -203,14 +211,14 @@ export const useAutoSave = ({
if (!textAreaRef?.current) {
return;
}
- // Save the draft of the current conversation before switching
- if (textAreaRef.current.value === '') {
+ const text = readTextToSave(id);
+ if (text === '') {
clearDraft(id);
} else {
- setDraft({ id, value: textAreaRef.current.value });
+ setDraft({ id, value: text });
}
},
- [textAreaRef],
+ [textAreaRef, readTextToSave],
);
/** The key this composer reads and writes right now. It is the conversation, except while the
* switch effect has parked storage on the pending key because the destination is not writable.
@@ -219,6 +227,38 @@ export const useAutoSave = ({
* which after a send put the just-sent attachment straight back as a chip. */
const activeStorageId =
currentConversationId === pendingDraftId ? pendingDraftId : conversationId;
+ /** Snapshot before a URL prompt replaces text; user input resumes normal persistence. */
+ const preserveText = useCallback(() => {
+ if (!saveDrafts || !activeStorageId || !textAreaRef?.current) {
+ return;
+ }
+ if (preservedTextRef.current?.id === activeStorageId) {
+ return;
+ }
+ preservedTextRef.current = { id: activeStorageId, text: textAreaRef.current.value };
+ saveText(activeStorageId);
+ }, [saveDrafts, activeStorageId, textAreaRef, saveText]);
+
+ /** A retained replacement becomes its destination draft, not the departing source draft. */
+ const settleText = useCallback(
+ (text: string, targetConversationId: string | null | undefined = _conversationId) => {
+ let id = targetConversationId;
+ if (targetConversationId === _conversationId) {
+ id = activeStorageId;
+ } else if (targetConversationId === Constants.NEW_CONVO) {
+ id = getNewConversationDraftId(index);
+ }
+ if (!saveDrafts || !id) {
+ return;
+ }
+ if (preservedTextRef.current?.id === id) {
+ preservedTextRef.current = null;
+ }
+ setDraft({ id, value: text });
+ },
+ [saveDrafts, activeStorageId, _conversationId, index],
+ );
+
/** Only autosave knows whether a foreign tab kept this composer on the
* pending key. Submission consumes that actual key under its ownership guard. */
const consumeDraft = useCallback(() => {
@@ -240,7 +280,7 @@ export const useAutoSave = ({
* clears the composer programmatically, so a write still in flight would
* otherwise land after the submit and restore the just-sent text. */
const saveLatest = () =>
- setDraft({ id: draftStorageId, value: textAreaRef?.current?.value ?? '' });
+ setDraft({ id: draftStorageId, value: readTextToSave(draftStorageId) });
/** Use shorter debounce for saving text (25ms) to capture rapid typing */
const handleInputFast = debounce(saveLatest, 25);
@@ -251,6 +291,9 @@ export const useAutoSave = ({
const eventListener = (e: Event) => {
const target = e.target as HTMLTextAreaElement;
const value = target.value;
+ if (preservedTextRef.current?.id === draftStorageId) {
+ preservedTextRef.current = null;
+ }
/** Cancel any pending operations to avoid conflicts */
handleInputFast.cancel();
@@ -284,7 +327,7 @@ export const useAutoSave = ({
handleInputFast.flush();
handleInputSlow.flush();
};
- }, [activeStorageId, saveDrafts, textAreaRef]);
+ }, [activeStorageId, saveDrafts, textAreaRef, readTextToSave]);
const prevConversationIdRef = useRef<string | null>(null);
const pendingDestinationRef = useRef<string | null>(null);
@@ -402,6 +445,9 @@ export const useAutoSave = ({
saveText(currentConversationId);
}
+ if (preservedTextRef.current?.id !== nextConversationId) {
+ preservedTextRef.current = null;
+ }
if (isFilesDraftOwnedByThisTab(getFilesDraft(filesDraftId))) {
const pendingPastes = restoreFiles(filesDraftId);
restoreText(textDraftId, pendingPastes);
@@ -487,5 +533,5 @@ export const useAutoSave = ({
});
}, [conversationId, saveDrafts, currentConversationId, fileIds, files]);
- return consumeDraft;
+ return { consumeDraft, preserveText, settleText };
};
diff --git a/client/src/hooks/Input/useDictation.ts b/client/src/hooks/Input/useDictation.ts
index c5c1df0d8f..0be89d0326 100644
--- a/client/src/hooks/Input/useDictation.ts
+++ b/client/src/hooks/Input/useDictation.ts
@@ -82,6 +82,8 @@ export default function useDictation({
const takeIdRef = useRef(0);
const isSubmittingRef = useRef(isSubmitting);
isSubmittingRef.current = isSubmitting;
+ const disabledRef = useRef(disabled);
+ disabledRef.current = disabled;
const duringRunSubmitRef = useRef(duringRunSubmit);
duringRunSubmitRef.current = duringRunSubmit;
const filesLoadingRef = useRef(filesLoading);
@@ -105,6 +107,11 @@ export default function useDictation({
if (spentRef.current || !text) {
return;
}
+ if (disabledRef.current) {
+ /** Retain the transcript for manual send; lifting the hold must not replay this take. */
+ spentRef.current = true;
+ return;
+ }
const runSubmit = duringRunSubmitRef.current;
if (isSubmittingRef.current && runSubmit == null) {
showToast({ message: localize('com_ui_speech_while_submitting'), status: 'error' });
@@ -266,7 +273,7 @@ export default function useDictation({
activeRef.current = active;
const stopWith = useCallback(
(mode: StopMode) => {
- if (!activeRef.current) {
+ if (!activeRef.current || (mode === 'send' && disabledRef.current)) {
return;
}
modeRef.current = mode;
diff --git a/client/src/hooks/Input/useQueryParams.spec.ts b/client/src/hooks/Input/useQueryParams.spec.ts
index 1f39c1c4ba..87b66749e1 100644
--- a/client/src/hooks/Input/useQueryParams.spec.ts
+++ b/client/src/hooks/Input/useQueryParams.spec.ts
@@ -18,9 +18,12 @@ jest.mock('~/store', () => ({
}));
import { renderHook, act } from '@testing-library/react';
-import { useSearchParams } from 'react-router-dom';
+import { useLocation, useSearchParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { useRecoilValue } from 'recoil';
+import { EModelEndpoint, parseConvo } from 'librechat-data-provider';
+import type { TConversation, TStartupConfig } from 'librechat-data-provider';
+import buildDefaultConvo from '~/utils/buildDefaultConvo';
import useQueryParams from './useQueryParams';
import { useChatContext, useChatFormContext } from '~/Providers';
import useSubmitMessage from '~/hooks/Messages/useSubmitMessage';
@@ -30,6 +33,7 @@ import store from '~/store';
// Other mocks
jest.mock('react-router-dom', () => ({
useSearchParams: jest.fn(),
+ useLocation: jest.fn(),
}));
jest.mock('@tanstack/react-query', () => ({
@@ -77,22 +81,6 @@ jest.mock('~/utils', () => {
};
});
-// Use actual librechat-data-provider with minimal overrides
-jest.mock('librechat-data-provider', () => {
- const actual = jest.requireActual('librechat-data-provider');
- return {
- ...actual,
- // Override schema to avoid complex validation in tests
- tQueryParamsSchema: {
- shape: {
- model: { parse: jest.fn((value) => value) },
- endpoint: { parse: jest.fn((value) => value) },
- temperature: { parse: jest.fn((value) => value) },
- },
- },
- };
-});
-
// Mock data-provider hooks while preserving real exports like startupConfigKey
jest.mock('~/data-provider', () => {
const actual = jest.requireActual<typeof import('~/data-provider')>('~/data-provider');
@@ -128,6 +116,7 @@ describe('useQueryParams', () => {
// Setup common mocks before each test
beforeEach(() => {
jest.useFakeTimers();
+ (useLocation as jest.Mock).mockReturnValue({ pathname: '/c/new', key: 'origin' });
// Reset mock for window.history.replaceState
jest.spyOn(window.history, 'replaceState').mockClear();
@@ -146,10 +135,11 @@ describe('useQueryParams', () => {
const mockQueryClient = {
getQueryData: jest.fn().mockImplementation((key) => {
- if (key === 'startupConfig') {
+ const k = Array.isArray(key) ? key[0] : key;
+ if (k === 'startupConfig') {
return { modelSpecs: { list: [] } };
}
- if (key === 'endpoints') {
+ if (k === 'endpoints') {
return {};
}
return null;
@@ -207,7 +197,425 @@ describe('useQueryParams', () => {
(useSearchParams as jest.Mock).mockReturnValue([searchParams, jest.fn()]);
};
- // Test cases remain the same
+ const mountQuery = (
+ params: Record<string, string>,
+ startupConfig: {
+ modelSpecs?: Partial<NonNullable<TStartupConfig['modelSpecs']>>;
+ interface?: Partial<NonNullable<TStartupConfig['interface']>>;
+ } | null = { modelSpecs: { list: [] } },
+ ) => {
+ const textAreaRef = { current: document.createElement('textarea') };
+ const mockSetValue = jest.fn((_field: string, text: string) => {
+ textAreaRef.current.value = text;
+ });
+ const mockSubmitMessage = jest.fn();
+ const mockNewConversation = jest.fn();
+ const mockSetSearchParams = jest.fn();
+ const searchParams = new URLSearchParams(params);
+ (useSearchParams as jest.Mock).mockReturnValue([searchParams, mockSetSearchParams]);
+ (useQueryClient as jest.Mock).mockReturnValue({
+ getQueryData: jest.fn((key) => {
+ if (key[0] === 'startupConfig') {
+ return startupConfig;
+ }
+ if (key[0] === 'endpoints') {
+ return { MyProvider: { type: 'custom' }, agents: {} };
+ }
+ return null;
+ }),
+ });
+ (useChatFormContext as jest.Mock).mockReturnValue({
+ setValue: mockSetValue,
+ getValues: jest.fn(() => textAreaRef.current.value),
+ handleSubmit: jest.fn((callback) => () => callback({ text: textAreaRef.current.value })),
+ });
+ (useSubmitMessage as jest.Mock).mockReturnValue({ submitMessage: mockSubmitMessage });
+ const updateConversation = (conversation: Partial<TConversation>) => {
+ (useChatContext as jest.Mock).mockReturnValue({
+ conversation,
+ newConversation: mockNewConversation,
+ });
+ };
+ updateConversation({ endpoint: EModelEndpoint.openAI, model: 'gpt-4o' });
+ const hook = renderHook(() => useQueryParams({ textAreaRef }));
+ act(() => jest.advanceTimersByTime(100));
+ return {
+ ...hook,
+ mockSetValue,
+ mockSubmitMessage,
+ mockNewConversation,
+ mockSetSearchParams,
+ updateConversation,
+ textAreaRef,
+ updateRoute: (pathname: string, params: Record<string, string> = {}) => {
+ (useLocation as jest.Mock).mockReturnValue({ pathname, key: 'destination' });
+ (useSearchParams as jest.Mock).mockReturnValue([
+ new URLSearchParams(params),
+ mockSetSearchParams,
+ ]);
+ },
+ };
+ };
+
+ it('shows the URL prompt and pending state before the requested agent is ready', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true' });
+ expect(hook.mockSetValue).toHaveBeenCalledWith('text', 'hi', { shouldValidate: true });
+ expect(hook.result.current).toEqual(
+ expect.objectContaining({ isPreparing: true, settingsError: false }),
+ );
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.mockSetSearchParams).not.toHaveBeenCalled();
+ expect(hook.mockNewConversation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ template: expect.objectContaining({ agent_id: 'agent_test' }),
+ preset: expect.objectContaining({ endpoint: 'agents', agent_id: 'agent_test' }),
+ keepComposerState: true,
+ }),
+ );
+
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.result.current).toEqual(
+ expect.objectContaining({ isPreparing: false, settingsError: false }),
+ );
+ act(() => jest.advanceTimersByTime(4000));
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('matches the canonical custom endpoint instead of its URL casing', () => {
+ const hook = mountQuery({ endpoint: 'myprovider', q: 'hi', submit: 'true' });
+ hook.updateConversation({
+ endpoint: 'MyProvider' as EModelEndpoint,
+ endpointType: EModelEndpoint.custom,
+ });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.result.current.isPreparing).toBe(false);
+ });
+
+ it('matches an agent after the conversation intentionally clears its model', () => {
+ const hook = mountQuery({
+ agent_id: 'agent_test',
+ model: 'gpt-4o',
+ q: 'hi',
+ submit: 'true',
+ });
+ hook.updateConversation({
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ model: undefined,
+ });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the timeout alive across conversation rerenders without sending to the wrong agent', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true', projectId: 'p1' });
+ act(() => jest.advanceTimersByTime(1000));
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_other' });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(2000));
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.result.current).toEqual(
+ expect.objectContaining({ isPreparing: false, settingsError: true }),
+ );
+ expect(hook.mockSetValue).toHaveBeenCalledTimes(1);
+ const [params, options] = hook.mockSetSearchParams.mock.calls[0];
+ expect(params.toString()).toBe('projectId=p1');
+ expect(options).toEqual({ replace: true });
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ });
+
+ it('submits using the latest conversation-bound callback', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true' });
+ const latestSubmit = jest.fn();
+ (useSubmitMessage as jest.Mock).mockReturnValue({ submitMessage: latestSubmit });
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ expect(latestSubmit).toHaveBeenCalledWith({ text: 'hi' });
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ });
+
+ it('waits for the resolved model spec rather than accepting any conversation', () => {
+ const hook = mountQuery(
+ { spec: 'helper', q: 'hi', submit: 'true' },
+ {
+ modelSpecs: {
+ list: [
+ {
+ name: 'helper',
+ label: 'Helper',
+ preset: { endpoint: 'agents', agent_id: 'agent_test', model: 'gpt-4o' },
+ },
+ ],
+ },
+ },
+ );
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ hook.updateConversation({
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_other',
+ spec: 'helper',
+ });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ hook.updateConversation({
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent_test',
+ spec: 'helper',
+ });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('stages the prompt even before startup config has loaded', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true' }, null);
+ expect(hook.mockSetValue).toHaveBeenCalledWith('text', 'hi', { shouldValidate: true });
+ expect(hook.mockNewConversation).not.toHaveBeenCalled();
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ });
+
+ it('honors the server policy disabling auto-submit while still staging the prompt', () => {
+ const hook = mountQuery(
+ { agent_id: 'agent_test', q: 'hi', submit: 'true' },
+ { interface: { autoSubmitFromUrl: false } },
+ );
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ expect(hook.mockSetValue).toHaveBeenCalledWith('text', 'hi', { shouldValidate: true });
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.result.current).toEqual(
+ expect.objectContaining({ isPreparing: false, settingsError: false }),
+ );
+ });
+
+ it('matches nullable spec settings after the endpoint schema removes them', () => {
+ const preset = { endpoint: EModelEndpoint.openAI, model: 'gpt-4o', temperature: null };
+ const hook = mountQuery(
+ { spec: 'helper', q: 'hi', submit: 'true' },
+ { modelSpecs: { list: [{ name: 'helper', label: 'Helper', preset }] } },
+ );
+ const conversation = parseConvo({
+ endpoint: EModelEndpoint.openAI,
+ conversation: { ...preset, spec: 'helper' },
+ });
+ expect(conversation?.temperature).toBeUndefined();
+ hook.updateConversation({ ...conversation, endpoint: EModelEndpoint.openAI });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.result.current.settingsError).toBe(false);
+ });
+
+ it.each([
+ { endpoint: EModelEndpoint.openAI, endpointType: undefined },
+ { endpoint: 'MyProvider' as EModelEndpoint, endpointType: EModelEndpoint.custom },
+ ])('matches nullable endpoint metadata for $endpoint', ({ endpoint, endpointType }) => {
+ const preset = { endpoint, endpointType: null, model: 'gpt-4o' };
+ const hook = mountQuery(
+ { spec: 'helper', q: 'hi', submit: 'true' },
+ { modelSpecs: { list: [{ name: 'helper', label: 'Helper', preset }] } },
+ );
+ const conversation = buildDefaultConvo({
+ models: ['gpt-4o'],
+ endpoint,
+ conversation: { conversationId: 'new', endpointType } as TConversation,
+ lastConversationSetup: { ...preset, spec: 'helper' } as TConversation,
+ });
+ expect(conversation.endpointType).toBe(endpointType);
+ hook.updateConversation(conversation);
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.result.current.settingsError).toBe(false);
+ });
+
+ it.each([{ tools: [] }, { tools: ['web_search'] }])(
+ 'matches preset tools retained by the conversation builder: $tools',
+ ({ tools }) => {
+ const preset = { endpoint: EModelEndpoint.openAI, model: 'gpt-4o', tools };
+ const hook = mountQuery(
+ { spec: 'helper', q: 'hi', submit: 'true' },
+ { modelSpecs: { list: [{ name: 'helper', label: 'Helper', preset }] } },
+ );
+ const conversation = buildDefaultConvo({
+ models: ['gpt-4o'],
+ endpoint: EModelEndpoint.openAI,
+ conversation: { conversationId: 'new' } as TConversation,
+ lastConversationSetup: { ...preset, spec: 'helper' } as TConversation,
+ });
+ expect(conversation.tools).toEqual(tools);
+ hook.updateConversation(conversation);
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.result.current.settingsError).toBe(false);
+ },
+ );
+
+ it('preserves explicit URL overrides over visible spec defaults', () => {
+ const hook = mountQuery(
+ { spec: 'helper', temperature: '0.1', q: 'hi', submit: 'true' },
+ {
+ modelSpecs: {
+ list: [
+ {
+ name: 'helper',
+ label: 'Helper',
+ preset: { endpoint: 'openAI', model: 'gpt-4o', temperature: 0.8 },
+ },
+ ],
+ },
+ },
+ );
+ expect(hook.mockNewConversation).toHaveBeenCalledWith(
+ expect.objectContaining({ preset: expect.objectContaining({ temperature: 0.1 }) }),
+ );
+ hook.updateConversation({
+ endpoint: EModelEndpoint.openAI,
+ model: 'gpt-4o',
+ spec: 'helper',
+ temperature: 0.1,
+ });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('preserves menu-hidden spec names for the server to resolve', () => {
+ const hook = mountQuery({ spec: 'hidden', endpoint: 'openAI', q: 'hi', submit: 'true' });
+ expect(hook.mockNewConversation).toHaveBeenCalledWith(
+ expect.objectContaining({
+ preset: expect.objectContaining({ spec: 'hidden', endpoint: 'openAI' }),
+ }),
+ );
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ hook.updateConversation({ endpoint: EModelEndpoint.openAI, model: 'gpt-4o', spec: 'hidden' });
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.result.current.settingsError).toBe(false);
+ });
+
+ it('cancels pending URL setup before startup config arrives', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true' }, null);
+ hook.textAreaRef.current.value = 'destination draft';
+ hook.updateRoute('/c/other-chat');
+ hook.updateConversation({ conversationId: 'other-chat', endpoint: EModelEndpoint.openAI });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(6000));
+ expect(hook.textAreaRef.current.value).toBe('destination draft');
+ expect(hook.mockSetSearchParams).not.toHaveBeenCalled();
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ });
+
+ it('cancels a pending URL request when the new-chat project changes', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true', projectId: 'p1' });
+ hook.textAreaRef.current.value = 'project two draft';
+ hook.updateRoute('/c/new', { projectId: 'p2' });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(4000));
+ expect(hook.textAreaRef.current.value).toBe('project two draft');
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.mockSetSearchParams).not.toHaveBeenCalled();
+ expect(hook.result.current.isPreparing).toBe(false);
+ });
+
+ it('does not submit or clean the destination URL if validation finishes after navigation', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true' });
+ let finishValidation: (() => void) | undefined;
+ const methods = (useChatFormContext as jest.Mock).mock.results.at(-1)?.value;
+ methods.handleSubmit.mockImplementation((callback) => () => {
+ finishValidation = () => callback({ text: 'hi' });
+ });
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ expect(finishValidation).toBeDefined();
+ expect(hook.mockSetSearchParams).not.toHaveBeenCalled();
+ hook.updateRoute('/c/other-chat');
+ hook.updateConversation({ conversationId: 'other-chat', endpoint: EModelEndpoint.openAI });
+ hook.rerender();
+ act(() => finishValidation?.());
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.mockSetSearchParams).not.toHaveBeenCalled();
+ });
+
+ it.each(['valid', 'invalid'])(
+ 'ignores superseded %s validation callbacks after a new prompt URL',
+ (outcome) => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'old', submit: 'true' });
+ const completions: { valid: () => void; invalid: () => void }[] = [];
+ const methods = (useChatFormContext as jest.Mock).mock.results.at(-1)?.value;
+ methods.handleSubmit.mockImplementation(
+ (valid: (data: { text: string }) => void, invalid: () => void) => () => {
+ const text = hook.textAreaRef.current.value;
+ completions.push({ valid: () => valid({ text }), invalid });
+ },
+ );
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ expect(completions).toHaveLength(1);
+ hook.updateRoute('/c/new', { q: 'new', submit: 'true' });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(100));
+ expect(completions).toHaveLength(2);
+ expect(hook.textAreaRef.current.value).toBe('new');
+ act(() => completions[0][outcome]());
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.mockSetSearchParams).not.toHaveBeenCalled();
+ expect(hook.result.current.isPreparing).toBe(true);
+ act(() => completions[1].valid());
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.mockSubmitMessage).toHaveBeenCalledWith({ text: 'new' });
+ expect(hook.mockSetSearchParams).toHaveBeenCalledTimes(1);
+ act(() => jest.advanceTimersByTime(4000));
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it('handles the same prompt URL again only after a separate navigation', () => {
+ const hook = mountQuery({ q: 'same', submit: 'true' });
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ hook.updateRoute('/c/new', { submit: 'true', q: 'same' });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(100));
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ hook.updateRoute('/c/new');
+ hook.rerender();
+ hook.updateRoute('/c/new', { q: 'same', submit: 'true' });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(100));
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(2);
+ });
+
+ it('retains a refused auto-submission without retrying it', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true' });
+ hook.mockSubmitMessage.mockReturnValue(false);
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(4000));
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.textAreaRef.current.value).toBe('hi');
+ expect(hook.result.current.isPreparing).toBe(false);
+ });
+
+ it('clears the pending timer on unmount', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: 'hi', submit: 'true' });
+ hook.unmount();
+ act(() => jest.advanceTimersByTime(4000));
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.mockSetSearchParams).not.toHaveBeenCalled();
+ });
+
+ it('does not submit a whitespace-only prompt', () => {
+ const hook = mountQuery({ agent_id: 'agent_test', q: ' ', submit: 'true' });
+ hook.updateConversation({ endpoint: EModelEndpoint.agents, agent_id: 'agent_test' });
+ hook.rerender();
+ act(() => jest.advanceTimersByTime(4000));
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.result.current.isPreparing).toBe(false);
+ });
+
it('should process query parameters on initial render', () => {
// Setup
const mockSetValue = jest.fn();
@@ -364,6 +772,7 @@ describe('useQueryParams', () => {
});
// Assert initial state
+ expect(mockSetValue).toHaveBeenCalledWith('text', 'hello world', { shouldValidate: true });
expect(mockGetQueryData).toHaveBeenCalledWith(expect.anything());
expect(mockNewConversation).toHaveBeenCalled();
expect(mockSubmitMessage).not.toHaveBeenCalled(); // Not submitted yet
@@ -387,7 +796,7 @@ describe('useQueryParams', () => {
expect(mockSubmitMessage).toHaveBeenCalled();
});
- it('should submit after timeout if settings never get applied', () => {
+ it('should retain the prompt after timeout if settings never get applied', () => {
// Setup
const mockSetValue = jest.fn();
const mockHandleSubmit = jest.fn((callback) => () => callback({ text: 'test message' }));
@@ -448,8 +857,8 @@ describe('useQueryParams', () => {
jest.advanceTimersByTime(3000); // MAX_SETTINGS_WAIT_MS
});
- // Now the message should be submitted due to timeout
- expect(mockSubmitMessage).toHaveBeenCalled();
+ expect(mockSubmitMessage).not.toHaveBeenCalled();
+ expect(mockSetValue).toHaveBeenCalledWith('text', 'hello world', { shouldValidate: true });
});
it('should mark as submitted when no submit parameter is present', () => {
diff --git a/client/src/hooks/Input/useQueryParams.ts b/client/src/hooks/Input/useQueryParams.ts
index 4c13ddff2f..d494c67955 100644
--- a/client/src/hooks/Input/useQueryParams.ts
+++ b/client/src/hooks/Input/useQueryParams.ts
@@ -1,20 +1,31 @@
-import { useEffect, useCallback, useRef } from 'react';
+import { useEffect, useCallback, useRef, useState, useMemo } from 'react';
+import isEqual from 'lodash/isEqual';
import { useRecoilValue } from 'recoil';
-import { useSearchParams } from 'react-router-dom';
-import { QueryClient, useQueryClient } from '@tanstack/react-query';
-import { QueryKeys, EModelEndpoint, PermissionBits } from 'librechat-data-provider';
+import { useQueryClient } from '@tanstack/react-query';
+import { useLocation, useSearchParams } from 'react-router-dom';
+import {
+ QueryKeys,
+ parseConvo,
+ EModelEndpoint,
+ PermissionBits,
+ getEndpointField,
+ getDefaultParamsEndpoint,
+} from 'librechat-data-provider';
import type {
AgentListResponse,
TEndpointsConfig,
+ TConversation,
TStartupConfig,
TPreset,
} from 'librechat-data-provider';
+import type { QueryClient } from '@tanstack/react-query';
import {
clearModelForNonEphemeralAgent,
removeUnavailableTools,
specDisplayFieldReset,
processValidSettings,
- getModelSpecIconURL,
+ mergeQuerySettingsWithSpec,
+ getModelSpecPreset,
getConvoSwitchLogic,
logger,
} from '~/utils';
@@ -25,7 +36,10 @@ import store from '~/store';
const PROJECT_ID_SEARCH_PARAM = 'projectId';
-const injectAgentIntoAgentsMap = (queryClient: QueryClient, agent: any) => {
+const injectAgentIntoAgentsMap = (
+ queryClient: QueryClient,
+ agent: AgentListResponse['data'][number],
+) => {
const editCacheKey = [QueryKeys.agents, { requiredPermission: PermissionBits.EDIT }];
const editCache = queryClient.getQueryData<AgentListResponse>(editCacheKey);
@@ -40,33 +54,73 @@ const injectAgentIntoAgentsMap = (queryClient: QueryClient, agent: any) => {
}
};
-/**
- * Hook that processes URL query parameters to initialize chat with specified settings and prompt.
- * Handles model switching, prompt auto-filling, and optional auto-submission with race condition protection.
- * Supports immediate or deferred submission based on whether settings need to be applied first.
- */
+/** Stages URL prompts, then auto-submits once normalized conversation settings match. */
export default function useQueryParams({
textAreaRef,
+ routePending = false,
+ onBeforePrompt,
+ onPromptSettled,
}: {
textAreaRef: React.RefObject<HTMLTextAreaElement>;
+ routePending?: boolean;
+ onBeforePrompt?: () => void;
+ onPromptSettled?: (text: string, conversationId: string | null | undefined) => void;
}) {
const maxAttempts = 50;
const attemptsRef = useRef(0);
const MAX_SETTINGS_WAIT_MS = 3000;
const processedRef = useRef(false);
const pendingSubmitRef = useRef(false);
- const settingsAppliedRef = useRef(false);
+ const validatingRef = useRef(false);
const submissionHandledRef = useRef(false);
const promptTextRef = useRef<string | null>(null);
const validSettingsRef = useRef<TPreset | null>(null);
const settingsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const requestIdRef = useRef(0);
+ const [submissionStatus, setSubmissionStatus] = useState<'idle' | 'preparing' | 'failed'>('idle');
+ const routePendingRef = useRef(routePending);
+ routePendingRef.current = routePending;
+ const onPromptSettledRef = useRef(onPromptSettled);
+ onPromptSettledRef.current = onPromptSettled;
const methods = useChatFormContext();
const [searchParams, setSearchParams] = useSearchParams();
+ const setSearchParamsRef = useRef(setSearchParams);
+ setSearchParamsRef.current = setSearchParams;
+ const location = useLocation();
+ const searchIdentity = useMemo(() => {
+ const params = new URLSearchParams(searchParams);
+ params.sort();
+ return params.toString();
+ }, [searchParams]);
+ const requestIdentity = useMemo(() => {
+ const params = new URLSearchParams(searchIdentity);
+ params.delete(PROJECT_ID_SEARCH_PARAM);
+ return params.toString();
+ }, [searchIdentity]);
+ const previousRequestIdentityRef = useRef(requestIdentity);
+ const route = {
+ pathname: location.pathname,
+ search: searchIdentity,
+ projectId: searchParams.get(PROJECT_ID_SEARCH_PARAM),
+ };
+ const originRouteRef = useRef(route);
+ const routeRef = useRef(route);
+ routeRef.current = route;
+ const originConversationRef = useRef<string | null | undefined>(null);
+ const destinationRef = useRef<{
+ conversationId: string;
+ chatProjectId: TConversation['chatProjectId'];
+ route: typeof route;
+ } | null>(null);
+ const cancelledRef = useRef(false);
+ const mountedRef = useRef(true);
const getDefaultConversation = useDefaultConvo();
const modularChat = useRecoilValue(store.modularChat);
const availableTools = useRecoilValue(store.availableTools);
const { submitMessage } = useSubmitMessage();
+ const submitMessageRef = useRef(submitMessage);
+ submitMessageRef.current = submitMessage;
const queryClient = useQueryClient();
const { conversation, newConversation } = useChatContext();
@@ -76,12 +130,155 @@ export default function useQueryParams({
const getPreservedSearchParams = useCallback(() => {
const preservedParams = new URLSearchParams();
- const projectId = searchParams.get(PROJECT_ID_SEARCH_PARAM);
+ const projectId = routeRef.current.projectId;
if (projectId) {
preservedParams.set(PROJECT_ID_SEARCH_PARAM, projectId);
}
return preservedParams;
- }, [searchParams]);
+ }, []);
+
+ const conversationRef = useRef(conversation);
+ conversationRef.current = conversation;
+
+ const ownsComposer = useCallback(() => {
+ const currentId = conversationRef.current?.conversationId;
+ const current = routeRef.current;
+ return (
+ ((current.projectId === originRouteRef.current.projectId &&
+ current.pathname === originRouteRef.current.pathname) ||
+ (destinationRef.current != null &&
+ current.pathname === destinationRef.current.route.pathname &&
+ current.projectId === destinationRef.current.route.projectId)) &&
+ (!processedRef.current ||
+ currentId == null ||
+ currentId === originConversationRef.current ||
+ currentId === destinationRef.current?.conversationId) &&
+ (destinationRef.current == null ||
+ currentId !== destinationRef.current.conversationId ||
+ (conversationRef.current?.chatProjectId ?? null) === destinationRef.current.chatProjectId)
+ );
+ }, []);
+
+ const ownsRequest = useCallback(
+ (requestId = requestIdRef.current) =>
+ requestId === requestIdRef.current &&
+ mountedRef.current &&
+ !cancelledRef.current &&
+ ((routeRef.current.pathname === originRouteRef.current.pathname &&
+ routeRef.current.search === originRouteRef.current.search) ||
+ (routeRef.current.pathname === destinationRef.current?.route.pathname &&
+ routeRef.current.search === destinationRef.current.route.search)) &&
+ ownsComposer(),
+ [ownsComposer],
+ );
+
+ /** Match the route that useNewConvo writes, including its inherited project. */
+ const expectDestination = useCallback((template: Partial<TConversation>) => {
+ const conversationId = template.conversationId ?? 'new';
+ const params = new URLSearchParams(originRouteRef.current.search);
+ params.delete(PROJECT_ID_SEARCH_PARAM);
+ const projectId = conversationId === 'new' ? template.chatProjectId || null : null;
+ if (projectId) {
+ params.set(PROJECT_ID_SEARCH_PARAM, projectId);
+ }
+ params.sort();
+ destinationRef.current = {
+ conversationId,
+ chatProjectId: template.chatProjectId ?? null,
+ route: { pathname: `/c/${conversationId}`, search: params.toString(), projectId },
+ };
+ }, []);
+
+ const cancelRequest = useCallback(() => {
+ requestIdRef.current += 1;
+ cancelledRef.current = true;
+ processedRef.current = true;
+ submissionHandledRef.current = true;
+ pendingSubmitRef.current = false;
+ validatingRef.current = false;
+ if (settingsTimeoutRef.current) {
+ clearTimeout(settingsTimeoutRef.current);
+ settingsTimeoutRef.current = null;
+ }
+ setSubmissionStatus('idle');
+ }, []);
+
+ useEffect(() => {
+ const identityChanged = previousRequestIdentityRef.current !== requestIdentity;
+ previousRequestIdentityRef.current = requestIdentity;
+ const prompt = searchParams.get('prompt') || searchParams.get('q');
+ if (identityChanged && prompt) {
+ /** Project rewrites retain this identity; a new prompt URL starts a separate request. */
+ if (settingsTimeoutRef.current) {
+ clearTimeout(settingsTimeoutRef.current);
+ settingsTimeoutRef.current = null;
+ }
+ requestIdRef.current += 1;
+ attemptsRef.current = 0;
+ processedRef.current = false;
+ submissionHandledRef.current = false;
+ pendingSubmitRef.current = false;
+ validatingRef.current = false;
+ promptTextRef.current = null;
+ validSettingsRef.current = null;
+ originConversationRef.current = null;
+ destinationRef.current = null;
+ originRouteRef.current = routeRef.current;
+ cancelledRef.current = false;
+ setSubmissionStatus('idle');
+ }
+ if (
+ ((!submissionHandledRef.current || validatingRef.current) && !ownsRequest()) ||
+ (submissionStatus === 'failed' && !ownsComposer())
+ ) {
+ cancelRequest();
+ }
+ }, [
+ location,
+ conversation,
+ searchIdentity,
+ requestIdentity,
+ searchParams,
+ submissionStatus,
+ ownsComposer,
+ ownsRequest,
+ cancelRequest,
+ ]);
+
+ const areSettingsApplied = useCallback(() => {
+ const convo = conversationRef.current;
+ if (!validSettingsRef.current || !convo) {
+ return false;
+ }
+
+ const endpointsConfig = queryClient.getQueryData<TEndpointsConfig>([QueryKeys.endpoints]) ?? {};
+ const normalizedSettings = convo.endpoint
+ ? parseConvo({
+ endpoint: convo.endpoint,
+ endpointType: convo.endpointType,
+ conversation: validSettingsRef.current,
+ defaultParamsEndpoint: getDefaultParamsEndpoint(endpointsConfig, convo.endpoint),
+ })
+ : validSettingsRef.current;
+
+ for (const [key, value] of Object.entries(validSettingsRef.current)) {
+ if (['presetOverride', 'iconURL', 'modelLabel'].includes(key)) {
+ continue;
+ }
+
+ let expectedValue = normalizedSettings?.[key];
+ if (key === 'endpoint' || (key === 'tools' && value != null)) {
+ expectedValue = value;
+ } else if (key === 'endpointType') {
+ expectedValue = value ?? getEndpointField(endpointsConfig, convo.endpoint, 'type');
+ }
+ if (!isEqual(convo[key], expectedValue)) {
+ return false;
+ }
+ }
+
+ return true;
+ }, [queryClient]);
/**
* Applies settings from URL query parameters to create a new conversation.
@@ -98,14 +295,10 @@ export default function useQueryParams({
const startupConfig = queryClient.getQueryData<TStartupConfig>(startupConfigKey(true));
const modelSpecs = startupConfig?.modelSpecs?.list ?? [];
const spec = modelSpecs.find((s) => s.name === newPreset.spec);
- if (!spec) {
- return;
+ if (spec) {
+ newPreset = mergeQuerySettingsWithSpec(getModelSpecPreset(spec), newPreset);
}
- newPreset = {
- ...spec.preset,
- iconURL: getModelSpecIconURL(spec),
- spec: spec.name,
- } as TPreset;
+ /** Hidden specs remain opaque here and are resolved server-side by name. */
}
let newEndpoint = newPreset.endpoint ?? '';
@@ -127,6 +320,12 @@ export default function useQueryParams({
}
}
+ clearModelForNonEphemeralAgent(newPreset);
+ validSettingsRef.current = newPreset;
+ if (areSettingsApplied()) {
+ return true;
+ }
+
const {
template,
shouldSwitch,
@@ -170,21 +369,32 @@ export default function useQueryParams({
/* We don't reset the latest message, only when changing settings mid-converstion */
logger.log('conversation', 'Switching conversation from query params', currentConvo);
+ expectDestination(currentConvo);
newConversation({
template: currentConvo,
preset: newPreset,
keepAddedConvos: true,
+ keepComposerState: true,
});
- return;
+ return true;
}
+ const newTemplate = {
+ chatProjectId: conversation?.chatProjectId ?? null,
+ ...(newPreset.agent_id ? { agent_id: newPreset.agent_id } : {}),
+ };
+ expectDestination(newTemplate);
newConversation({
- template: { chatProjectId: conversation?.chatProjectId ?? null },
+ template: newTemplate,
preset: newPreset,
keepAddedConvos: true,
+ keepComposerState: true,
});
+ return true;
},
[
+ areSettingsApplied,
+ expectDestination,
queryClient,
modularChat,
conversation,
@@ -194,52 +404,90 @@ export default function useQueryParams({
],
);
- const conversationRef = useRef(conversation);
- conversationRef.current = conversation;
-
- const areSettingsApplied = useCallback(() => {
- const convo = conversationRef.current;
- if (!validSettingsRef.current || !convo) {
- return false;
+ const restoreUrlPrompt = useCallback(() => {
+ const prompt = promptTextRef.current;
+ if (ownsRequest() && prompt != null && methods.getValues('text') !== prompt) {
+ methods.setValue('text', prompt, { shouldValidate: true });
}
+ }, [methods, ownsRequest]);
- for (const [key, value] of Object.entries(validSettingsRef.current)) {
- if (['presetOverride', 'iconURL', 'spec', 'modelLabel'].includes(key)) {
- continue;
- }
-
- if (convo[key] !== value) {
- return false;
- }
+ const settlePrompt = useCallback(() => {
+ if (!ownsRequest() || promptTextRef.current == null) {
+ return;
}
+ onPromptSettledRef.current?.(
+ methods.getValues('text'),
+ destinationRef.current?.conversationId ?? conversationRef.current?.conversationId,
+ );
+ }, [methods, ownsRequest]);
- return true;
- }, []);
-
- /**
- * Processes message submission exactly once, preventing duplicate submissions.
- * Sets the prompt text, submits the message, and cleans up URL parameters afterward.
- * Has internal guards to ensure it only executes once regardless of how many times it's called.
- */
+ /** Consumes an auto-submit once, leaving a refused submission in the composer. */
const processSubmission = useCallback(() => {
- if (submissionHandledRef.current || !pendingSubmitRef.current || !promptTextRef.current) {
+ if (
+ submissionHandledRef.current ||
+ !pendingSubmitRef.current ||
+ !promptTextRef.current ||
+ !ownsRequest()
+ ) {
return;
}
submissionHandledRef.current = true;
pendingSubmitRef.current = false;
- methods.setValue('text', promptTextRef.current, { shouldValidate: true });
+ setSubmissionStatus('preparing');
+ if (settingsTimeoutRef.current) {
+ clearTimeout(settingsTimeoutRef.current);
+ settingsTimeoutRef.current = null;
+ }
- methods.handleSubmit((data) => {
- if (data.text?.trim()) {
- submitMessage(data);
- logger.log('conversation', 'Message submitted from query params');
+ restoreUrlPrompt();
+ const requestId = requestIdRef.current;
+ validatingRef.current = true;
+ const cleanUp = () => {
+ if (requestId !== requestIdRef.current) {
+ return;
}
- })();
-
- setSearchParams(getPreservedSearchParams(), { replace: true });
- }, [methods, submitMessage, setSearchParams, getPreservedSearchParams]);
+ validatingRef.current = false;
+ if (ownsRequest(requestId)) {
+ setSearchParamsRef.current(getPreservedSearchParams(), { replace: true });
+ }
+ };
+ methods.handleSubmit(
+ (data) => {
+ if (!ownsRequest(requestId)) {
+ return;
+ }
+ if (validSettingsRef.current && !areSettingsApplied()) {
+ setSubmissionStatus('failed');
+ settlePrompt();
+ cleanUp();
+ return;
+ }
+ setSubmissionStatus('idle');
+ if (data.text?.trim() && submitMessageRef.current(data) !== false) {
+ logger.log('conversation', 'Message submitted from query params');
+ } else {
+ settlePrompt();
+ }
+ cleanUp();
+ },
+ () => {
+ if (ownsRequest(requestId)) {
+ setSubmissionStatus('idle');
+ settlePrompt();
+ }
+ cleanUp();
+ },
+ )();
+ }, [
+ methods,
+ ownsRequest,
+ areSettingsApplied,
+ getPreservedSearchParams,
+ restoreUrlPrompt,
+ settlePrompt,
+ ]);
useEffect(() => {
const processQueryParams = () => {
@@ -260,7 +508,12 @@ export default function useQueryParams({
return { decodedPrompt, validSettings, shouldAutoSubmit };
};
+ const requestId = requestIdRef.current;
const intervalId = setInterval(() => {
+ if (requestId !== requestIdRef.current) {
+ clearInterval(intervalId);
+ return;
+ }
if (processedRef.current || attemptsRef.current >= maxAttempts) {
clearInterval(intervalId);
if (attemptsRef.current >= maxAttempts) {
@@ -269,17 +522,38 @@ export default function useQueryParams({
return;
}
- attemptsRef.current += 1;
+ if (!ownsRequest()) {
+ cancelRequest();
+ clearInterval(intervalId);
+ return;
+ }
+ const currentConversation = conversationRef.current;
+ if (
+ routePendingRef.current ||
+ !currentConversation ||
+ (currentConversation.conversationId != null &&
+ routeRef.current.pathname !== `/c/${currentConversation.conversationId}`)
+ ) {
+ return;
+ }
+ attemptsRef.current += 1;
if (!textAreaRef.current) {
return;
}
+ const { decodedPrompt, validSettings, shouldAutoSubmit } = processQueryParams();
+ if (decodedPrompt && promptTextRef.current == null) {
+ promptTextRef.current = decodedPrompt;
+ onBeforePrompt?.();
+ methods.setValue('text', decodedPrompt, { shouldValidate: true });
+ textAreaRef.current.focus();
+ textAreaRef.current.setSelectionRange(decodedPrompt.length, decodedPrompt.length);
+ }
+
const startupConfig = queryClient.getQueryData<TStartupConfig>(startupConfigKey(true));
if (!startupConfig) {
return;
}
-
- const { decodedPrompt, validSettings, shouldAutoSubmit } = processQueryParams();
const hasSettings = Object.keys(validSettings).length > 0;
const autoSubmitAllowed = startupConfig.interface?.autoSubmitFromUrl !== false;
@@ -296,79 +570,72 @@ export default function useQueryParams({
clearInterval(intervalId);
// Defer URL cleanup until after submission completes (processSubmission handles it)
- if (!pendingSubmitRef.current) {
- setSearchParams(getPreservedSearchParams(), { replace: true });
+ if ((!willAutoSubmit || !decodedPrompt.trim()) && ownsRequest()) {
+ settlePrompt();
+ setSearchParamsRef.current(getPreservedSearchParams(), { replace: true });
}
};
- if (hasSettings) {
- validSettingsRef.current = validSettings;
- }
-
- if (decodedPrompt) {
- promptTextRef.current = decodedPrompt;
- }
-
- // Handle auto-submission
- if (willAutoSubmit && decodedPrompt) {
- if (hasSettings) {
- // Settings are changing, defer submission
- pendingSubmitRef.current = true;
-
- // Set a timeout to handle the case where settings might never fully apply
+ originConversationRef.current = conversationRef.current?.conversationId;
+ const settingsAccepted = !hasSettings || newQueryConvo(validSettings) === true;
+ if (willAutoSubmit && decodedPrompt.trim()) {
+ pendingSubmitRef.current = true;
+ if (!settingsAccepted) {
+ pendingSubmitRef.current = false;
+ submissionHandledRef.current = true;
+ setSubmissionStatus('failed');
+ } else if (!hasSettings || areSettingsApplied()) {
+ processSubmission();
+ } else {
+ setSubmissionStatus('preparing');
settingsTimeoutRef.current = setTimeout(() => {
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
+ settingsTimeoutRef.current = null;
+ if (!ownsRequest()) {
+ cancelRequest();
+ return;
+ }
if (!submissionHandledRef.current && pendingSubmitRef.current) {
- logger.log(
- 'conversation',
- 'Settings application timeout, proceeding with submission',
- );
- processSubmission();
+ restoreUrlPrompt();
+ pendingSubmitRef.current = false;
+ submissionHandledRef.current = true;
+ setSubmissionStatus('failed');
+ logger.log('conversation', 'Settings application timeout, retaining prompt');
+ settlePrompt();
+ setSearchParamsRef.current(getPreservedSearchParams(), { replace: true });
}
}, MAX_SETTINGS_WAIT_MS);
- } else {
- methods.setValue('text', decodedPrompt, { shouldValidate: true });
- textAreaRef.current.focus();
- textAreaRef.current.setSelectionRange(decodedPrompt.length, decodedPrompt.length);
-
- methods.handleSubmit((data) => {
- if (data.text?.trim()) {
- submitMessage(data);
- }
- })();
}
- } else if (decodedPrompt) {
- methods.setValue('text', decodedPrompt, { shouldValidate: true });
- textAreaRef.current.focus();
- textAreaRef.current.setSelectionRange(decodedPrompt.length, decodedPrompt.length);
} else {
submissionHandledRef.current = true;
}
- if (hasSettings && !areSettingsApplied()) {
- newQueryConvo(validSettings);
- }
-
success();
}, 100);
return () => {
clearInterval(intervalId);
- if (settingsTimeoutRef.current) {
- clearTimeout(settingsTimeoutRef.current);
- }
};
}, [
searchParams,
+ requestIdentity,
methods,
textAreaRef,
+ onBeforePrompt,
+ routePending,
+ settlePrompt,
newQueryConvo,
newConversation,
submitMessage,
- setSearchParams,
getPreservedSearchParams,
queryClient,
processSubmission,
areSettingsApplied,
+ restoreUrlPrompt,
+ ownsRequest,
+ cancelRequest,
]);
useEffect(() => {
@@ -376,27 +643,30 @@ export default function useQueryParams({
if (
!processedRef.current ||
submissionHandledRef.current ||
- settingsAppliedRef.current ||
+ !pendingSubmitRef.current ||
!validSettingsRef.current ||
- !conversation
+ !conversation ||
+ !ownsRequest()
) {
return;
}
+ restoreUrlPrompt();
if (areSettingsApplied()) {
- settingsAppliedRef.current = true;
-
- if (pendingSubmitRef.current) {
- if (settingsTimeoutRef.current) {
- clearTimeout(settingsTimeoutRef.current);
- settingsTimeoutRef.current = null;
- }
+ logger.log('conversation', 'Settings fully applied, processing submission');
+ processSubmission();
+ }
+ }, [conversation, processSubmission, areSettingsApplied, restoreUrlPrompt, ownsRequest]);
- logger.log('conversation', 'Settings fully applied, processing submission');
- processSubmission();
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ if (settingsTimeoutRef.current) {
+ clearTimeout(settingsTimeoutRef.current);
}
- }
- }, [conversation, processSubmission, areSettingsApplied]);
+ };
+ }, []);
const { isAuthenticated } = useAuthContext();
const agentsMap = useAgentsMap({ isAuthenticated });
@@ -405,4 +675,12 @@ export default function useQueryParams({
injectAgentIntoAgentsMap(queryClient, urlAgent);
}
}, [urlAgent, queryClient, agentsMap]);
+
+ const clearSettingsError = useCallback(() => setSubmissionStatus('idle'), []);
+
+ return {
+ clearSettingsError,
+ isPreparing: submissionStatus === 'preparing' && ownsRequest(),
+ settingsError: submissionStatus === 'failed' && ownsComposer(),
+ };
}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 6e2cd03a4d..8ae9110b93 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2519,6 +2519,7 @@
"com_ui_send_now": "Send now",
"com_ui_send_now_paused": "Available after you respond to the pending request",
"com_ui_sending": "Sending...",
+ "com_ui_url_settings_failed": "Chat settings could not be applied. Review them before sending.",
"com_ui_set": "Set",
"com_ui_settings_label_2fa": "Two-factor authentication",
"com_ui_settings_label_agent_api_keys": "Agent API keys",
diff --git a/e2e/specs/mock/activity-prose.spec.ts b/e2e/specs/mock/activity-prose.spec.ts
index 4e15ad3102..a7366546a7 100644
--- a/e2e/specs/mock/activity-prose.spec.ts
+++ b/e2e/specs/mock/activity-prose.spec.ts
@@ -2,6 +2,7 @@ import { expect, test } from '@playwright/test';
import { NEW_CHAT_PATH, messagesView, selectMockEndpoint, sendMessage } from './helpers';
const INTRO = "Let me establish today's date and gather independent signals in parallel.";
+const PHASE_LABEL = 'Verified runtime configuration and deployment';
const LABELS = [
'Established current date, found active incidents and recent chart updates',
'Checked chart version and loaded the logs schema',
@@ -38,7 +39,7 @@ for (const autoExpandTools of [false, true]) {
await request.post(`${LABEL_SERVER}/__e2e/behavior`, {
data: {
delayMs: 700,
- phaseLabel: 'Verified runtime configuration and deployment',
+ phaseLabel: PHASE_LABEL,
labelsByPrompt: Object.fromEntries(
LABELS.map((text, batch) => [`activity prose ${label} ${batch}`, text]),
),
@@ -155,6 +156,12 @@ for (const autoExpandTools of [false, true]) {
timeout: 30_000,
});
await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden();
+ /** Settled work intentionally folds its prose; wait for that boundary before reopening. */
+ const phase = messagesView(page).getByRole('button', { name: PHASE_LABEL, exact: true });
+ await expect(phase).toBeVisible({ timeout: 30_000 });
+ await expect(phase).toHaveAttribute('aria-expanded', 'false');
+ await phase.click();
+ await expect(phase).toHaveAttribute('aria-expanded', 'true');
await expect(intro).toHaveText(INTRO);
});
}