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: Keep Composer Focus Off Clicked Controls So Menus Can Close (#15669)

Danny Avilab5c5624f1384
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 08a428d3d0..971179c66b 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -77,6 +77,23 @@ interface ChatFormProps {
stopGenerating: () => void;
}
+/** Targets that own focus themselves: form fields and links, popup disclosures
+ * (Ariakit and Radix both emit `aria-haspopup`), and popup content, which React
+ * bubbles through portals. */
+const focusOwningTargetSelector = [
+ 'a',
+ 'input',
+ 'select',
+ 'textarea',
+ 'label',
+ '[aria-haspopup]:not([aria-haspopup="false"])',
+ '[role="combobox"]',
+ '[role="menu"]',
+ '[role="listbox"]',
+ '[role="dialog"]',
+ '[role="alertdialog"]',
+].join(', ');
+
const ChatForm = memo(function ChatForm({
index,
placeholder,
@@ -162,14 +179,38 @@ const ChatForm = memo(function ChatForm({
[requiresKey, invalidAssistant],
);
- const handleContainerClick = useCallback(() => {
- /** Check if the device is a touchscreen */
+ /** Skipped on touchscreens so a tap does not raise the keyboard. */
+ const focusTextArea = useCallback(() => {
if (window.matchMedia?.('(pointer: coarse)').matches) {
return;
}
textAreaRef.current?.focus();
}, []);
+ /** The surface returns focus to the textarea after any click (send, stop, badge
+ * toggles), except when the target owns focus itself or opens a popup. Ariakit
+ * records `document.activeElement` at open time as a menu's disclosure, so
+ * refocusing the textarea behind a menu button made the textarea the disclosure
+ * and the menu could never close on textarea interaction (#15624). */
+ const handleContainerClick = useCallback(
+ (event: React.MouseEvent<HTMLDivElement>) => {
+ const owner =
+ event.target instanceof Element ? event.target.closest(focusOwningTargetSelector) : null;
+ if (owner && !owner.contains(event.currentTarget)) {
+ return;
+ }
+ focusTextArea();
+ },
+ [focusTextArea],
+ );
+
+ /** Actions that consume the composer from inside a popup (the during-run
+ * hovercard) sit in exempted popup content, so they restore focus themselves. */
+ const consumeComposer = useCallback(() => {
+ methods.reset();
+ focusTextArea();
+ }, [methods, focusTextArea]);
+
const handleFocusOrClick = useCallback(() => {
if (isCollapsed) {
setIsCollapsed(false);
@@ -498,7 +539,7 @@ const ChatForm = memo(function ChatForm({
control={methods.control}
steering={steering}
getText={() => methods.getValues('text')}
- onConsumed={() => methods.reset()}
+ onConsumed={consumeComposer}
disabled={filesLoading}
/>
);
@@ -592,6 +633,7 @@ const ChatForm = memo(function ChatForm({
agentId={conversation?.agent_id}
/>
<div
+ data-testid="composer-surface"
onClick={handleContainerClick}
className={cn(
'relative flex w-full flex-grow flex-col overflow-hidden rounded-t-3xl pb-4 sm:rounded-3xl sm:pb-0',
@@ -613,7 +655,9 @@ const ChatForm = memo(function ChatForm({
{project ? <ProjectLandingChip project={project} /> : null}
<TextareaHeader addedConvo={addedConvo} setAddedConvo={setAddedConvo} />
<PendingManualSkillsChips conversationId={conversationId} />
- {quotesEnabled && <PendingQuoteChips conversationId={conversationId} />}
+ {quotesEnabled && (
+ <PendingQuoteChips conversationId={conversationId} focusComposer={focusTextArea} />
+ )}
{steering.enabled && (
<PendingSteerChips
conversationId={conversationId}
@@ -752,7 +796,7 @@ const ChatForm = memo(function ChatForm({
<InterruptSteerButton
steering={steering}
getText={() => methods.getValues('text')}
- onConsumed={() => methods.reset()}
+ onConsumed={consumeComposer}
disabled={filesLoading}
/>
</div>
diff --git a/client/src/components/Chat/Input/PendingQuoteChips.tsx b/client/src/components/Chat/Input/PendingQuoteChips.tsx
index ef2f441d5b..9002509cf5 100644
--- a/client/src/components/Chat/Input/PendingQuoteChips.tsx
+++ b/client/src/components/Chat/Input/PendingQuoteChips.tsx
@@ -39,7 +39,14 @@ const CLOSE_DELAY_MS = 120;
* once the message is sent (the excerpts then re-render as `MessageQuotes` on
* the user bubble, or inside the steer bubble for a mid-run injection).
*/
-function PendingQuoteChips({ conversationId }: { conversationId: string }) {
+function PendingQuoteChips({
+ conversationId,
+ focusComposer,
+}: {
+ conversationId: string;
+ /** The composer's guarded refocus, which skips touchscreens. */
+ focusComposer?: () => void;
+}) {
const localize = useLocalize();
const quotes = useRecoilValue(store.pendingQuotesByConvoId(conversationId));
const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
@@ -73,9 +80,34 @@ function PendingQuoteChips({ conversationId }: { conversationId: string }) {
useEffect(() => cancelClose, [cancelClose]);
const clearAll = useCallback(() => setQuotes([]), [setQuotes]);
+ /** The clicked remove button unmounts with its row, and the composer surface
+ * does not refocus the textarea for clicks inside popup content, so restore
+ * focus here: to the composer once the popup collapses, otherwise to the
+ * remove button now at the same row (or the last one) once React has
+ * re-rendered the list. */
+ const pendingFocusIndexRef = useRef<number | null>(null);
+ useEffect(() => {
+ const index = pendingFocusIndexRef.current;
+ if (index == null) {
+ return;
+ }
+ pendingFocusIndexRef.current = null;
+ const buttons = popover.getState().contentElement?.querySelectorAll('button');
+ if (!buttons?.length) {
+ return;
+ }
+ buttons[Math.min(index, buttons.length - 1)].focus();
+ }, [quotes, popover]);
const removeAt = useCallback(
- (index: number) => setQuotes((prev) => prev.filter((_, i) => i !== index)),
- [setQuotes],
+ (index: number) => {
+ setQuotes((prev) => prev.filter((_, i) => i !== index));
+ if (quotes.length <= 2) {
+ focusComposer?.();
+ return;
+ }
+ pendingFocusIndexRef.current = index;
+ },
+ [setQuotes, quotes.length, focusComposer],
);
if (quotes.length === 0) {
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
index dc21d840f2..23b2168ec7 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
@@ -6,9 +6,9 @@ import { RecoilRoot, useRecoilState } from 'recoil';
import userEvent from '@testing-library/user-event';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { BrowserRouter as Router } from 'react-router-dom';
-import { render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { QueryKeys, FileSources, EModelEndpoint } from 'librechat-data-provider';
+import { render, screen, within, waitFor, fireEvent } from '@testing-library/react';
import type { TFile, TFileUpload, TConversation } from 'librechat-data-provider';
import type { ChatFormValues } from '~/common';
import { ChatContext, ChatFormProvider } from '~/Providers';
@@ -117,7 +117,10 @@ function Harness() {
);
}
-function renderComposer() {
+function renderComposer({
+ submitting = false,
+ quotes = [],
+}: { submitting?: boolean; quotes?: string[] } = {}) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
@@ -127,7 +130,12 @@ function renderComposer() {
return render(
<QueryClientProvider client={queryClient}>
- <RecoilRoot>
+ <RecoilRoot
+ initializeState={({ set }) => {
+ set(store.isSubmittingFamily(0), submitting);
+ set(store.pendingQuotesByConvoId(conversation.conversationId ?? ''), quotes);
+ }}
+ >
<Router>
<AuthContextProvider authConfig={{ loginRedirect: '', test: true }}>
<DndProvider backend={HTML5Backend}>
@@ -174,6 +182,142 @@ describe('ChatForm attachments', () => {
expect(textarea).toHaveValue('hi');
}, 20000);
+ test('does not steal focus when clicking the nested attachment icon', async () => {
+ renderComposer();
+ const textarea = await screen.findByTestId('text-input');
+ const trigger = screen.getByRole('button', { name: 'Attach File Options' });
+ expect(trigger).toBeEnabled();
+ const icon = trigger.querySelector('svg');
+ expect(icon).not.toBeNull();
+ const focus = jest.spyOn(textarea, 'focus');
+
+ await userEvent.click(icon as SVGElement);
+
+ expect(focus).not.toHaveBeenCalled();
+ expect(await screen.findByRole('menu', { name: 'Attach File Options' })).toBeInTheDocument();
+ }, 20000);
+
+ test('closes an open menu when the textarea is clicked', async () => {
+ renderComposer();
+ const textarea = await screen.findByTestId('text-input');
+ await userEvent.click(screen.getByRole('button', { name: 'Attach File Options' }));
+ expect(await screen.findByRole('menu', { name: 'Attach File Options' })).toBeInTheDocument();
+
+ await userEvent.click(textarea);
+
+ await waitFor(() =>
+ expect(screen.queryByRole('menu', { name: 'Attach File Options' })).not.toBeInTheDocument(),
+ );
+ expect(textarea).toHaveFocus();
+ }, 20000);
+
+ test('still returns focus to the textarea after a plain control click', async () => {
+ renderComposer();
+ const textarea = await screen.findByTestId('text-input');
+ await userEvent.type(textarea, 'hi');
+ expect(sendButton()).toBeEnabled();
+
+ await userEvent.click(sendButton());
+
+ expect(textarea).toHaveFocus();
+ }, 20000);
+
+ test('returns focus to the textarea after a during-run hovercard action', async () => {
+ renderComposer({ submitting: true });
+ const textarea = await screen.findByTestId('text-input');
+ await userEvent.type(textarea, 'later');
+ /** Ariakit shows a hovercard only after the pointer has travelled, and a
+ * keydown resets that, so the hover needs real screen-coordinate movement. */
+ const anchor = await screen.findByTestId('during-run-send-button');
+ fireEvent.mouseMove(anchor, { screenX: 10, screenY: 10 });
+ fireEvent.mouseMove(anchor, { screenX: 20, screenY: 20 });
+ const hovercard = await screen.findByRole('dialog');
+ const queue = within(hovercard).getByRole('button', { name: /^Queue\b/ });
+ expect(queue).toBeEnabled();
+
+ await userEvent.click(queue);
+
+ await waitFor(() => expect(textarea).toHaveValue(''));
+ expect(textarea).toHaveFocus();
+ }, 20000);
+
+ test('returns focus to the textarea after the primary during-run submit', async () => {
+ renderComposer({ submitting: true });
+ const textarea = await screen.findByTestId('text-input');
+ await userEvent.type(textarea, 'later');
+
+ await userEvent.click(await screen.findByTestId('during-run-send-button'));
+
+ await waitFor(() => expect(textarea).toHaveValue(''));
+ expect(textarea).toHaveFocus();
+ }, 20000);
+
+ test('returns focus to the textarea when removing a quote collapses the popup', async () => {
+ renderComposer({ quotes: ['alpha', 'beta'] });
+ const textarea = await screen.findByTestId('text-input');
+ // Hover opens this disclosure too; test the click path without a synthetic hover toggle.
+ await userEvent.click(screen.getByRole('button', { name: '2 selections' }), {
+ skipHover: true,
+ });
+ const popup = await screen.findByRole('dialog');
+
+ await userEvent.click(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]);
+
+ await waitFor(() => expect(screen.queryByTestId('quote-selections-popup')).toBeNull());
+ expect(screen.getByText('beta')).toBeInTheDocument();
+ expect(textarea).toHaveFocus();
+ }, 20000);
+
+ test('keeps focus inside the popup when removing a quote leaves several', async () => {
+ renderComposer({ quotes: ['alpha', 'beta', 'gamma'] });
+ await screen.findByTestId('text-input');
+ // Hover opens this disclosure too; test the click path without a synthetic hover toggle.
+ await userEvent.click(screen.getByRole('button', { name: '3 selections' }), {
+ skipHover: true,
+ });
+ const popup = await screen.findByRole('dialog');
+
+ await userEvent.click(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]);
+
+ await waitFor(() => expect(within(popup).getAllByRole('button')).toHaveLength(2));
+ expect(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]).toHaveFocus();
+ }, 20000);
+
+ test('does not raise the keyboard when a quote removal collapses the popup on touch', async () => {
+ const matchMedia = window.matchMedia;
+ window.matchMedia = jest
+ .fn()
+ .mockReturnValue({ matches: true }) as unknown as typeof matchMedia;
+ try {
+ renderComposer({ quotes: ['alpha', 'beta'] });
+ const textarea = await screen.findByTestId('text-input');
+ // Hover opens this disclosure too; test the click path without a synthetic hover toggle.
+ await userEvent.click(screen.getByRole('button', { name: '2 selections' }), {
+ skipHover: true,
+ });
+ const popup = await screen.findByRole('dialog');
+
+ await userEvent.click(within(popup).getAllByRole('button', { name: 'Remove quote' })[0]);
+
+ await waitFor(() => expect(screen.queryByTestId('quote-selections-popup')).toBeNull());
+ expect(textarea).not.toHaveFocus();
+ } finally {
+ window.matchMedia = matchMedia;
+ }
+ }, 20000);
+
+ test('focuses the textarea when clicking empty composer space', async () => {
+ renderComposer();
+ const textarea = await screen.findByTestId('text-input');
+ const surface = screen.getByTestId('composer-surface');
+ const focus = jest.spyOn(textarea, 'focus');
+
+ fireEvent.click(surface);
+
+ expect(focus).toHaveBeenCalledTimes(1);
+ expect(textarea).toHaveFocus();
+ }, 20000);
+
test('enables send for an attachment with no composer text', async () => {
const { container } = renderComposer();
await screen.findByTestId('text-input');
diff --git a/e2e/specs/mock/quotes.spec.ts b/e2e/specs/mock/quotes.spec.ts
index 37e2cba038..f0342c33c1 100644
--- a/e2e/specs/mock/quotes.spec.ts
+++ b/e2e/specs/mock/quotes.spec.ts
@@ -581,11 +581,12 @@ test.describe('quote references', () => {
// Opening via keyboard moves focus into the popup (first excerpt's remove ×).
await expect(popup.getByRole('button').first()).toBeFocused();
- // Escape closes it and returns focus to the composer (NOT the page top, the
- // bug this guards against). `document.activeElement` must be a real control.
+ // Escape closes it and returns focus to the pill that opened it (NOT the
+ // page top, the bug this guards against). `document.activeElement` must be
+ // a real control.
await page.keyboard.press('Escape');
await expect(popup).toBeHidden();
- await expect(page.getByRole('textbox', { name: 'Message input' })).toBeFocused();
+ await expect(trigger).toBeFocused();
const focusTag = await page.evaluate(() => document.activeElement?.tagName ?? 'NONE');
expect(focusTag).not.toBe('BODY');
});