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: Wait for Chat History Before URL Auto-Submit (#17224)

Marco Beretta012e01dc7fac
diff --git a/client/src/hooks/Input/useQueryParams.spec.ts b/client/src/hooks/Input/useQueryParams.spec.ts
index 12c8e6e111..5902def966 100644
--- a/client/src/hooks/Input/useQueryParams.spec.ts
+++ b/client/src/hooks/Input/useQueryParams.spec.ts
@@ -19,7 +19,7 @@ jest.mock('~/store', () => ({
import { renderHook, act } from '@testing-library/react';
import { useLocation, useSearchParams } from 'react-router-dom';
-import { useQueryClient } from '@tanstack/react-query';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useRecoilValue } from 'recoil';
import { EModelEndpoint, parseConvo } from 'librechat-data-provider';
import type { TConversation, TStartupConfig } from 'librechat-data-provider';
@@ -115,6 +115,7 @@ describe('useQueryParams', () => {
// Setup common mocks before each test
beforeEach(() => {
jest.useFakeTimers();
+ (useQuery as jest.Mock).mockReturnValue({ status: 'loading', fetchStatus: 'idle' });
(useLocation as jest.Mock).mockReturnValue({ pathname: '/c/new', key: 'origin' });
// Reset mock for window.history.replaceState
@@ -202,6 +203,10 @@ describe('useQueryParams', () => {
modelSpecs?: Partial<NonNullable<TStartupConfig['modelSpecs']>>;
interface?: Partial<NonNullable<TStartupConfig['interface']>>;
} | null = { modelSpecs: { list: [] } },
+ options: {
+ conversation?: Partial<TConversation>;
+ queryClient?: Record<string, unknown>;
+ } = {},
) => {
const textAreaRef = { current: document.createElement('textarea') };
const mockSetValue = jest.fn((_field: string, text: string) => {
@@ -222,6 +227,7 @@ describe('useQueryParams', () => {
}
return null;
}),
+ ...options.queryClient,
});
(useChatFormContext as jest.Mock).mockReturnValue({
setValue: mockSetValue,
@@ -235,7 +241,9 @@ describe('useQueryParams', () => {
newConversation: mockNewConversation,
});
};
- updateConversation({ endpoint: EModelEndpoint.openAI, model: 'gpt-4o' });
+ updateConversation(
+ options.conversation ?? { endpoint: EModelEndpoint.openAI, model: 'gpt-4o' },
+ );
const hook = renderHook(() => useQueryParams({ textAreaRef }));
act(() => jest.advanceTimersByTime(100));
return {
@@ -598,6 +606,48 @@ describe('useQueryParams', () => {
expect(hook.result.current.isPreparing).toBe(false);
});
+ /** Mounts a prompt URL on an existing chat whose history query has not resolved yet. */
+ const mountExistingChat = () => {
+ (useLocation as jest.Mock).mockReturnValue({ pathname: '/c/convo-1', key: 'origin' });
+ const history: { state?: { status: string; data?: unknown } } = {};
+ const hook = mountQuery({ q: 'hi', submit: 'true' }, undefined, {
+ conversation: { conversationId: 'convo-1', endpoint: EModelEndpoint.openAI },
+ queryClient: { getQueryState: jest.fn(() => history.state) },
+ });
+ /** The history observer re-renders the hook once the messages query settles. */
+ const settle = (state: { status: string; data?: unknown }) => {
+ history.state = state;
+ (useQuery as jest.Mock).mockReturnValue({ ...state, fetchStatus: 'idle', dataUpdatedAt: 1 });
+ hook.rerender();
+ };
+ return { hook, settle };
+ };
+
+ it('waits for an existing chat history to load before auto-submitting', () => {
+ const { hook, settle } = mountExistingChat();
+ act(() => jest.advanceTimersByTime(1000));
+ expect(hook.textAreaRef.current.value).toBe('hi');
+ expect(hook.mockSubmitMessage).not.toHaveBeenCalled();
+ expect(hook.result.current.isPreparing).toBe(true);
+
+ settle({ status: 'success', data: [] });
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ expect(hook.mockSubmitMessage).toHaveBeenCalledWith({ text: 'hi' });
+ expect(hook.mockSetSearchParams).toHaveBeenCalled();
+ hook.rerender();
+ expect(hook.mockSubmitMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('stops waiting for chat history when the history request fails', () => {
+ const { hook, settle } = mountExistingChat();
+ hook.mockSubmitMessage.mockReturnValue(false);
+ settle({ status: 'error' });
+ 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();
diff --git a/client/src/hooks/Input/useQueryParams.ts b/client/src/hooks/Input/useQueryParams.ts
index d494c67955..f62b465099 100644
--- a/client/src/hooks/Input/useQueryParams.ts
+++ b/client/src/hooks/Input/useQueryParams.ts
@@ -1,10 +1,11 @@
import { useEffect, useCallback, useRef, useState, useMemo } from 'react';
import isEqual from 'lodash/isEqual';
import { useRecoilValue } from 'recoil';
-import { useQueryClient } from '@tanstack/react-query';
import { useLocation, useSearchParams } from 'react-router-dom';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
QueryKeys,
+ Constants,
parseConvo,
EModelEndpoint,
PermissionBits,
@@ -14,6 +15,7 @@ import {
import type {
AgentListResponse,
TEndpointsConfig,
+ TMessage,
TConversation,
TStartupConfig,
TPreset,
@@ -32,6 +34,7 @@ import {
import { useAuthContext, useAgentsMap, useDefaultConvo, useSubmitMessage } from '~/hooks';
import { startupConfigKey, useGetAgentByIdQuery } from '~/data-provider';
import { useChatContext, useChatFormContext } from '~/Providers';
+import { isHistoryRevalidating } from '~/hooks/Chat/ask/guards';
import store from '~/store';
const PROJECT_ID_SEARCH_PARAM = 'projectId';
@@ -76,6 +79,7 @@ export default function useQueryParams({
const promptTextRef = useRef<string | null>(null);
const validSettingsRef = useRef<TPreset | null>(null);
const settingsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const awaitingHistoryRef = useRef(false);
const requestIdRef = useRef(0);
const [submissionStatus, setSubmissionStatus] = useState<'idle' | 'preparing' | 'failed'>('idle');
@@ -189,6 +193,19 @@ export default function useQueryParams({
};
}, []);
+ /** Existing chats refuse sends until their history has loaded and settled. */
+ const isHistoryPending = useCallback(() => {
+ const conversationId = conversationRef.current?.conversationId;
+ if (conversationId == null || conversationId === Constants.NEW_CONVO) {
+ return false;
+ }
+ const state = queryClient.getQueryState([QueryKeys.messages, conversationId]);
+ if (state?.status === 'error') {
+ return false;
+ }
+ return state?.data == null || isHistoryRevalidating(queryClient, conversationId);
+ }, [queryClient]);
+
const cancelRequest = useCallback(() => {
requestIdRef.current += 1;
cancelledRef.current = true;
@@ -215,6 +232,7 @@ export default function useQueryParams({
}
requestIdRef.current += 1;
attemptsRef.current = 0;
+ awaitingHistoryRef.current = false;
processedRef.current = false;
submissionHandledRef.current = false;
pendingSubmitRef.current = false;
@@ -432,15 +450,20 @@ export default function useQueryParams({
return;
}
- submissionHandledRef.current = true;
- pendingSubmitRef.current = false;
-
setSubmissionStatus('preparing');
if (settingsTimeoutRef.current) {
clearTimeout(settingsTimeoutRef.current);
settingsTimeoutRef.current = null;
}
+ awaitingHistoryRef.current = isHistoryPending();
+ if (awaitingHistoryRef.current) {
+ return;
+ }
+
+ submissionHandledRef.current = true;
+ pendingSubmitRef.current = false;
+
restoreUrlPrompt();
const requestId = requestIdRef.current;
validatingRef.current = true;
@@ -483,12 +506,33 @@ export default function useQueryParams({
}, [
methods,
ownsRequest,
+ isHistoryPending,
areSettingsApplied,
getPreservedSearchParams,
restoreUrlPrompt,
settlePrompt,
]);
+ /** Observes the history the composer sends from, so a retry runs after the
+ * render that derives the latest message from it, not during the cache write. */
+ const historyKey = [QueryKeys.messages, conversation?.conversationId ?? ''];
+ const history = useQuery<TMessage[]>(
+ historyKey,
+ async () => queryClient.getQueryData<TMessage[]>(historyKey) ?? [],
+ { enabled: false },
+ );
+ useEffect(() => {
+ if (awaitingHistoryRef.current && !isHistoryPending()) {
+ processSubmission();
+ }
+ }, [
+ history.status,
+ history.fetchStatus,
+ history.dataUpdatedAt,
+ isHistoryPending,
+ processSubmission,
+ ]);
+
useEffect(() => {
const processQueryParams = () => {
const queryParams: Record<string, string> = {};
diff --git a/e2e/specs/mock/scenarios/url-submit-slow-history.spec.ts b/e2e/specs/mock/scenarios/url-submit-slow-history.spec.ts
new file mode 100644
index 0000000000..bf7836ab51
--- /dev/null
+++ b/e2e/specs/mock/scenarios/url-submit-slow-history.spec.ts
@@ -0,0 +1,69 @@
+import { expect, test } from '@playwright/test';
+import type { Route } from '@playwright/test';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ isAgentsStream,
+ messagesView,
+ replyPrompt,
+ replyText,
+ selectMockEndpoint,
+ sendMessageAndWaitForCompletion,
+} from '../helpers';
+
+/**
+ * An existing chat refuses a send until its history has loaded, so a
+ * `?q=...&submit=true` link opened on a chat whose history is slow to arrive
+ * must hold the prompt and send it once the history lands.
+ */
+
+const HISTORY_DELAY_MS = 3000;
+
+test('a submit link on a slow-loading chat sends its prompt once @scenario:a-submit-link-on-a-slow-loading-chat-sends-its-prompt', async ({
+ page,
+}) => {
+ test.setTimeout(120000);
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ const seed = await sendMessageAndWaitForCompletion(page, replyPrompt('seed'));
+ const { conversationId } = (await seed.json()) as { conversationId: string };
+ await expect(messagesView(page).getByText(replyText('seed'))).toBeVisible();
+
+ const historyPath = `/api/messages/${encodeURIComponent(conversationId)}`;
+ let historyRequests = 0;
+ await page.route(
+ (url) => url.pathname === historyPath,
+ async (route: Route) => {
+ historyRequests += 1;
+ await new Promise((resolve) => setTimeout(resolve, HISTORY_DELAY_MS));
+ await route.continue();
+ },
+ );
+
+ const prompt = replyPrompt('from-link');
+ const sends: string[] = [];
+ page.on('request', (request) => {
+ const { pathname } = new URL(request.url());
+ if (request.method() === 'POST' && pathname.startsWith('/api/agents/chat')) {
+ sends.push(request.postData() ?? '');
+ }
+ });
+
+ const [admission] = await Promise.all([
+ page.waitForResponse(isAgentsStream, { timeout: 30000 }),
+ page.goto(`/c/${conversationId}?q=${encodeURIComponent(prompt)}&submit=true`),
+ ]);
+ expect(historyRequests).toBeGreaterThan(0);
+ expect(((await admission.json()) as { conversationId: string }).conversationId).toBe(
+ conversationId,
+ );
+
+ await expect(messagesView(page).getByText(replyText('from-link'))).toBeVisible({
+ timeout: 30000,
+ });
+ await expect(messagesView(page).getByText(replyText('seed'))).toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`/c/${conversationId}$`));
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toHaveValue('');
+ expect(sends.filter((body) => body.includes(prompt))).toHaveLength(1);
+});