Skip to content

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

🔎 refactor: Move the Mention Popover Into the Chat Package as a Combobox (#17659)

Marco Berettacd3367b24ddc
diff --git a/client/src/Providers/ComposerHostContext.tsx b/client/src/Providers/ComposerHostContext.tsx
index 9c0ec8aa1d..0861bf4262 100644
--- a/client/src/Providers/ComposerHostContext.tsx
+++ b/client/src/Providers/ComposerHostContext.tsx
@@ -1,12 +1,14 @@
import type { ComposerHost } from '@librechat/chat/react';
import { useShortcutAriaKey, useShortcutDisplay } from '~/hooks/useKeyboardShortcuts';
import useComposerBindings from '~/hooks/Input/useComposerBindings';
+import CommandList from '~/components/Chat/Input/CommandList';
/** The app's capabilities for the composer controls in `@librechat/chat`. */
export const appComposerHost: ComposerHost = {
useComposerBindings,
useShortcutDisplay,
useShortcutAriaKey,
+ renderCommandList: (props) => <CommandList {...props} />,
};
export { ComposerHostProvider, useComposerHost } from '@librechat/chat/react';
diff --git a/client/src/components/Chat/Input/CommandList.tsx b/client/src/components/Chat/Input/CommandList.tsx
new file mode 100644
index 0000000000..a607e7f52e
--- /dev/null
+++ b/client/src/components/Chat/Input/CommandList.tsx
@@ -0,0 +1,30 @@
+import { AutoSizer, List } from 'react-virtualized';
+import type { CommandListProps } from '@librechat/chat/react';
+
+/** Windows a command popover's rows; the popover's listbox owns the semantics, so the list's
+ * own grid roles step aside. */
+export default function CommandList({
+ count,
+ activeIndex,
+ rowHeight,
+ height,
+ renderRow,
+}: CommandListProps) {
+ return (
+ <AutoSizer disableHeight>
+ {({ width }) => (
+ <List
+ width={width}
+ height={height}
+ rowCount={count}
+ rowHeight={rowHeight}
+ overscanRowCount={5}
+ rowRenderer={renderRow}
+ scrollToIndex={activeIndex}
+ role="presentation"
+ containerRole="presentation"
+ />
+ )}
+ </AutoSizer>
+ );
+}
diff --git a/client/src/components/Chat/Input/Mention.tsx b/client/src/components/Chat/Input/Mention.tsx
index 25c4b81326..4d7eaf55f1 100644
--- a/client/src/components/Chat/Input/Mention.tsx
+++ b/client/src/components/Chat/Input/Mention.tsx
@@ -1,19 +1,12 @@
-import { memo, useState, useRef, useEffect } from 'react';
-import { AutoSizer, List } from 'react-virtualized';
-import { EModelEndpoint } from 'librechat-data-provider';
-import { MentionItem } from '@librechat/chat/components';
+import { memo } from 'react';
import { useRecoilValue, useSetRecoilState } from 'recoil';
-import { useInitPopoverInput } from '@librechat/chat/react';
-import { Input, Spinner, useCombobox, useRemScale } from '@librechat/client';
+import { MentionPopover } from '@librechat/chat/components';
import type { RecoilState } from 'recoil';
-import type { MentionOption, ConvoGenerator } from '~/common';
+import type { ConvoGenerator } from '~/common';
import { useGetConversation, useLocalize, TranslationKeys } from '~/hooks';
import useSelectMention from '~/hooks/Input/useSelectMention';
import { useAssistantsMapContext } from '~/Providers';
import useMentions from '~/hooks/Input/useMentions';
-import { removeCharIfLast } from '~/utils';
-
-const ROW_HEIGHT = 44;
type MentionProps = {
index: number;
@@ -34,7 +27,6 @@ function MentionContent({
includeAssistants = true,
}: Omit<MentionProps, 'index'>) {
const localize = useLocalize();
- const remScale = useRemScale();
const getConversation = useGetConversation(0);
const assistantsMap = useAssistantsMapContext();
const setShowPopover = useSetRecoilState(popoverAtom);
@@ -57,208 +49,19 @@ function MentionContent({
newConversation,
});
- const [activeIndex, setActiveIndex] = useState(0);
- const timeoutRef = useRef<NodeJS.Timeout | null>(null);
- const inputRef = useRef<HTMLInputElement | null>(null);
- const [inputOptions, setInputOptions] = useState<MentionOption[]>(options);
-
- const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({
- value: '',
- options: inputOptions,
- });
-
- const initInputRef = useInitPopoverInput({
- inputRef,
- textAreaRef,
- commandChar,
- setSearchValue,
- setOpen,
- });
-
- const handleSelect = (mention?: MentionOption) => {
- if (!mention) {
- return;
- }
-
- const defaultSelect = () => {
- setSearchValue('');
- setOpen(false);
- setShowPopover(false);
- onSelectMention?.(mention);
-
- if (textAreaRef.current) {
- removeCharIfLast(textAreaRef.current, commandChar);
- }
- };
-
- if (mention.type === 'endpoint' && mention.value === EModelEndpoint.agents) {
- setSearchValue('');
- setInputOptions(agentsList ?? []);
- setActiveIndex(0);
- inputRef.current?.focus();
- } else if (mention.type === 'endpoint' && mention.value === EModelEndpoint.assistants) {
- setSearchValue('');
- setInputOptions(assistantListMap[EModelEndpoint.assistants] ?? []);
- setActiveIndex(0);
- inputRef.current?.focus();
- } else if (mention.type === 'endpoint' && mention.value === EModelEndpoint.azureAssistants) {
- setSearchValue('');
- setInputOptions(assistantListMap[EModelEndpoint.azureAssistants] ?? []);
- setActiveIndex(0);
- inputRef.current?.focus();
- } else if (mention.type === 'endpoint') {
- const models = (modelsConfig?.[mention.value || ''] ?? []).map((model) => ({
- value: mention.value,
- label: model,
- type: 'model',
- }));
-
- setActiveIndex(0);
- setSearchValue('');
- setInputOptions(models);
- inputRef.current?.focus();
- } else {
- defaultSelect();
- }
- };
-
- useEffect(() => {
- if (!open) {
- setInputOptions(options);
- setActiveIndex(0);
- }
- }, [open, options]);
-
- useEffect(() => {
- setActiveIndex((prev) => Math.min(prev, Math.max(matches.length - 1, 0)));
- }, [matches.length]);
-
- useEffect(() => {
- return () => {
- if (timeoutRef.current) {
- clearTimeout(timeoutRef.current);
- }
- };
- }, []);
-
- const type = commandChar !== '@' ? 'add-convo' : 'mention';
- useEffect(() => {
- const currentActiveItem = document.getElementById(`${type}-item-${activeIndex}`);
- currentActiveItem?.scrollIntoView({ behavior: 'instant', block: 'nearest' });
- }, [type, activeIndex]);
-
- const rowRenderer = ({
- index,
- key,
- style,
- }: {
- index: number;
- key: string;
- style: React.CSSProperties;
- }) => {
- const mention = matches[index] as MentionOption;
- return (
- <MentionItem
- type={type}
- index={index}
- key={key}
- style={style}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (timeoutRef.current) {
- clearTimeout(timeoutRef.current);
- }
- timeoutRef.current = null;
- handleSelect(mention);
- }}
- name={mention.label ?? ''}
- icon={mention.icon}
- description={mention.description}
- isActive={index === activeIndex}
- />
- );
- };
-
return (
- <div className="absolute bottom-28 z-10 w-full space-y-2">
- <div className="popover border-border-light bg-surface-secondary rounded-theme-popover border p-2 shadow-lg">
- <Input
- ref={initInputRef}
- placeholder={localize(placeholder)}
- className="bg-surface-secondary mb-1 h-auto w-full rounded-none border-0 p-2"
- autoComplete="off"
- value={searchValue}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- setOpen(false);
- setShowPopover(false);
- textAreaRef.current?.focus();
- }
- if (e.key === 'ArrowDown') {
- if (matches.length === 0) {
- return;
- }
- setActiveIndex((prevIndex) => (prevIndex + 1) % matches.length);
- } else if (e.key === 'ArrowUp') {
- if (matches.length === 0) {
- return;
- }
- setActiveIndex((prevIndex) => (prevIndex - 1 + matches.length) % matches.length);
- } else if (e.key === 'Enter' || e.key === 'Tab') {
- if (matches.length === 0) {
- e.preventDefault();
- setOpen(false);
- setShowPopover(false);
- textAreaRef.current?.focus();
- return;
- }
- const mentionOption = matches[activeIndex] as MentionOption | undefined;
- if (mentionOption?.type === 'endpoint') {
- e.preventDefault();
- } else if (e.key === 'Enter') {
- e.preventDefault();
- }
- handleSelect(matches[activeIndex] as MentionOption);
- } else if (e.key === 'Backspace' && searchValue === '') {
- setOpen(false);
- setShowPopover(false);
- textAreaRef.current?.focus();
- }
- }}
- onChange={(e) => setSearchValue(e.target.value)}
- onFocus={() => setOpen(true)}
- onBlur={() => {
- timeoutRef.current = setTimeout(() => {
- setOpen(false);
- setShowPopover(false);
- }, 150);
- }}
- />
- {open && isLoading && matches.length === 0 && (
- <div className="text-text-primary flex h-32 items-center justify-center">
- <Spinner />
- </div>
- )}
- {open && matches.length > 0 && (
- <div className="max-h-40">
- <AutoSizer disableHeight>
- {({ width }) => (
- <List
- width={width}
- overscanRowCount={5}
- rowHeight={ROW_HEIGHT * remScale}
- rowCount={matches.length}
- rowRenderer={rowRenderer}
- scrollToIndex={activeIndex}
- height={Math.min(matches.length * ROW_HEIGHT, 160) * remScale}
- />
- )}
- </AutoSizer>
- </div>
- )}
- </div>
- </div>
+ <MentionPopover
+ textAreaRef={textAreaRef}
+ commandChar={commandChar}
+ placeholder={localize(placeholder)}
+ options={options}
+ isLoading={isLoading}
+ agentsList={agentsList}
+ assistantListMap={assistantListMap}
+ modelsConfig={modelsConfig}
+ onSelectMention={(option) => onSelectMention?.(option)}
+ onClose={() => setShowPopover(false)}
+ />
);
}
diff --git a/client/src/components/Chat/Input/__tests__/Mention.spec.tsx b/client/src/components/Chat/Input/__tests__/Mention.spec.tsx
deleted file mode 100644
index d5a9d863a0..0000000000
--- a/client/src/components/Chat/Input/__tests__/Mention.spec.tsx
+++ /dev/null
@@ -1,208 +0,0 @@
-/**
- * Locks in the `@` mention popover keyboard contract for the empty-result
- * edge case (issue #13929 / PR #13928): when filtering yields zero matches
- * the arrow keys must be no-ops rather than computing a `% 0` -> NaN active
- * index, and Enter/Tab must close the popover and return focus to the
- * textarea. Deleting back to a non-empty list has to leave keyboard
- * navigation working from a valid index.
- */
-import React from 'react';
-import { fireEvent, render, screen } from '@testing-library/react';
-import type { RecoilState } from 'recoil';
-import type { MentionOption } from '~/common';
-
-const POPOVER_ATOM = 'show-mention-popover';
-const PLACEHOLDER = 'com_ui_mention';
-
-const mockSetShowPopover = jest.fn();
-const mockShowPopover = { current: true };
-
-jest.mock('recoil', () => {
- const actual = jest.requireActual('recoil');
- return {
- ...actual,
- useRecoilValue: jest.fn((atom: unknown) =>
- atom === POPOVER_ATOM ? mockShowPopover.current : undefined,
- ),
- useSetRecoilState: jest.fn((atom: unknown) =>
- atom === POPOVER_ATOM ? mockSetShowPopover : jest.fn(),
- ),
- };
-});
-
-const mockUseMentions = jest.fn();
-jest.mock('~/hooks/Input/useMentions', () => ({
- __esModule: true,
- default: () => mockUseMentions(),
-}));
-
-jest.mock('~/hooks/Input/useSelectMention', () => ({
- __esModule: true,
- default: () => ({ onSelectMention: jest.fn() }),
-}));
-
-jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => key,
- useGetConversation: () => jest.fn(),
-}));
-
-jest.mock('~/Providers', () => ({
- useAssistantsMapContext: () => ({}),
-}));
-
-/* react-virtualized renders nothing in jsdom without a measured size; replace
- AutoSizer + List with a flat ul so every row's MentionItem button renders. */
-jest.mock('react-virtualized', () => ({
- ...jest.requireActual('react-virtualized'),
- AutoSizer: ({ children }: { children: (size: { width: number }) => React.ReactNode }) =>
- children({ width: 320 }),
- List: ({
- rowCount,
- rowRenderer,
- }: {
- rowCount: number;
- rowRenderer: (args: {
- index: number;
- key: string;
- style: React.CSSProperties;
- }) => React.ReactNode;
- }) => {
- const rows: React.ReactNode[] = [];
- for (let i = 0; i < rowCount; i++) {
- rows.push(rowRenderer({ index: i, key: `row-${i}`, style: {} }));
- }
- return <ul data-testid="mention-list">{rows}</ul>;
- },
-}));
-
-import Mention from '../Mention';
-
-const makeTextarea = (initial = '@') => {
- const textarea = document.createElement('textarea');
- textarea.value = initial;
- document.body.appendChild(textarea);
- return { current: textarea } as React.MutableRefObject<HTMLTextAreaElement | null>;
-};
-
-const makeMention = (overrides: Partial<MentionOption>): MentionOption => ({
- type: 'preset',
- label: 'Alpha',
- value: 'alpha',
- description: '',
- ...overrides,
-});
-
-const options: MentionOption[] = [
- makeMention({ label: 'Alpha', value: 'alpha' }),
- makeMention({ label: 'Beta', value: 'beta' }),
-];
-
-const mentionsBundle = {
- options,
- presets: [],
- isLoading: false,
- modelSpecs: [],
- agentsList: [],
- modelsConfig: {},
- endpointsConfig: {},
- assistantListMap: {},
-};
-
-const activeItemId = () =>
- document.querySelector('.bg-surface-active')?.closest('button')?.id ?? null;
-
-const getInput = () => screen.getByPlaceholderText(PLACEHOLDER);
-
-beforeAll(() => {
- Element.prototype.scrollIntoView = jest.fn();
-});
-
-beforeEach(() => {
- jest.clearAllMocks();
- document.body.innerHTML = '';
- mockShowPopover.current = true;
- mockUseMentions.mockReturnValue(mentionsBundle);
-});
-
-const renderMention = () => {
- const textAreaRef = makeTextarea('@');
- const utils = render(
- <Mention
- index={0}
- popoverAtom={POPOVER_ATOM as unknown as RecoilState<boolean>}
- newConversation={jest.fn()}
- textAreaRef={textAreaRef}
- />,
- );
- return { textAreaRef, ...utils };
-};
-
-describe('Mention keyboard navigation', () => {
- it('renders nothing when the popover atom is false', () => {
- mockShowPopover.current = false;
- const { container } = renderMention();
- expect(container).toBeEmptyDOMElement();
- });
-
- it('moves the active highlight with ArrowDown/ArrowUp and wraps around', () => {
- renderMention();
- const input = getInput();
-
- expect(activeItemId()).toBe('mention-item-0');
-
- fireEvent.keyDown(input, { key: 'ArrowDown' });
- expect(activeItemId()).toBe('mention-item-1');
-
- fireEvent.keyDown(input, { key: 'ArrowDown' });
- expect(activeItemId()).toBe('mention-item-0');
-
- fireEvent.keyDown(input, { key: 'ArrowUp' });
- expect(activeItemId()).toBe('mention-item-1');
- });
-
- it('keeps navigation working after filtering to zero matches and back', () => {
- renderMention();
- const input = getInput();
-
- fireEvent.change(input, { target: { value: 'zzz' } });
- expect(screen.queryByRole('button')).toBeNull();
-
- /* Arrow keys on an empty list must be no-ops, not `% 0` -> NaN. */
- fireEvent.keyDown(input, { key: 'ArrowDown' });
- fireEvent.keyDown(input, { key: 'ArrowUp' });
-
- fireEvent.change(input, { target: { value: '' } });
- expect(screen.getAllByRole('button')).toHaveLength(2);
-
- /* Without the guard the active index would still be NaN here and no
- item would highlight; with it, navigation resumes from a valid index. */
- fireEvent.keyDown(input, { key: 'ArrowDown' });
- expect(activeItemId()).toBe('mention-item-1');
- });
-
- it('closes the popover and refocuses the textarea when Enter is pressed with no matches', () => {
- const { textAreaRef } = renderMention();
- const input = getInput();
-
- fireEvent.change(input, { target: { value: 'zzz' } });
- const notPrevented = fireEvent.keyDown(input, { key: 'Enter' });
-
- expect(notPrevented).toBe(false);
- expect(mockSetShowPopover).toHaveBeenCalledWith(false);
- expect(document.activeElement).toBe(textAreaRef.current);
- });
-
- it('prevents the default Tab action when closing on no matches so the refocus sticks', () => {
- const { textAreaRef } = renderMention();
- const input = getInput();
-
- fireEvent.change(input, { target: { value: 'zzz' } });
- const notPrevented = fireEvent.keyDown(input, { key: 'Tab' });
-
- /* Without preventDefault the browser's default Tab would move focus off
- the textarea right after we refocus it. */
- expect(notPrevented).toBe(false);
- expect(mockSetShowPopover).toHaveBeenCalledWith(false);
- expect(document.activeElement).toBe(textAreaRef.current);
- });
-});
diff --git a/client/src/utils/textarea.ts b/client/src/utils/textarea.ts
index d45e3f7d0a..917f256ecd 100644
--- a/client/src/utils/textarea.ts
+++ b/client/src/utils/textarea.ts
@@ -1,3 +1,5 @@
+export { removeCharIfLast } from '@librechat/chat';
+
/**
* Insert text at the cursor position in a textarea.
*/
@@ -39,23 +41,6 @@ export const forceResize = (element: HTMLTextAreaElement | null) => {
element.style.height = `${element.scrollHeight}px`;
};
-/**
- * Remove the specified character from the end of the textarea's text if it's present.
- * This function ensures that the specified character is only removed if it's the last character.
- *
- * @param {HTMLTextAreaElement} textarea - The textarea element where text manipulation will occur.
- * @param {string} charToRemove - The character to remove if it's the last character in the textarea's value.
- */
-export function removeCharIfLast(textarea: HTMLTextAreaElement, charToRemove: string) {
- if (textarea.value.endsWith(charToRemove)) {
- textarea.value = textarea.value.slice(0, -1);
- textarea.setSelectionRange(textarea.value.length, textarea.value.length);
- textarea.dispatchEvent(new Event('input', { bubbles: true }));
- }
-
- textarea.focus();
-}
-
/**
* Check if the textarea is scrollable.
* @param element
diff --git a/e2e/specs/mock/scenarios/composer-mention.spec.ts b/e2e/specs/mock/scenarios/composer-mention.spec.ts
new file mode 100644
index 0000000000..c99a5541bf
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-mention.spec.ts
@@ -0,0 +1,110 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ MOCK_ENDPOINTS,
+ NEW_CHAT_PATH,
+ modelSelectorTrigger,
+ selectMockEndpoint,
+} from '../helpers';
+
+/**
+ * The `@` mention popover, drawn by the chat package's command popover through the app's
+ * windowed list: a combobox whose active option the keyboard moves and announces, which drills
+ * an endpoint into its models and switches the conversation to the model picked.
+ */
+test.describe.configure({ timeout: 120_000 });
+
+async function openMention(page: Page) {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ const textarea = page.getByRole('textbox', { name: 'Message input' });
+ await textarea.click();
+ await textarea.press('@');
+ const combobox = page.getByRole('combobox', { name: /Mention/ });
+ await expect(combobox).toBeFocused();
+ return { textarea, combobox };
+}
+
+const activeOption = async (page: Page) => {
+ const id = await page
+ .getByRole('combobox', { name: /Mention/ })
+ .getAttribute('aria-activedescendant');
+ return page.locator(`[id="${id}"]`);
+};
+
+test.describe('mention popover', () => {
+ test('keyboard moves and announces the active option @scenario:mention-popover-keyboard-combobox', async ({
+ page,
+ }) => {
+ const { textarea, combobox } = await openMention(page);
+
+ await expect(combobox).toHaveAttribute('aria-expanded', 'true');
+ const listbox = page.locator(`[id="${await combobox.getAttribute('aria-controls')}"]`);
+ await expect(listbox).toHaveAttribute('role', 'listbox');
+ await expect(listbox.getByRole('option').first()).toBeVisible();
+ await expect(listbox.locator('[role="grid"], [role="rowgroup"]')).toHaveCount(0);
+
+ await expect(combobox).toHaveAttribute('aria-activedescendant', 'mention-item-0');
+ await combobox.press('ArrowDown');
+ await expect(combobox).toHaveAttribute('aria-activedescendant', 'mention-item-1');
+ const active = await activeOption(page);
+ await expect(active).toHaveAttribute('role', 'option');
+ await expect(active).toHaveAttribute('aria-selected', 'true');
+ await expect(active).toBeInViewport();
+ await expect(listbox.locator('[aria-selected="true"]')).toHaveCount(1);
+
+ await combobox.press('ArrowUp');
+ await expect(combobox).toHaveAttribute('aria-activedescendant', 'mention-item-0');
+
+ await combobox.press('Escape');
+ await expect(page.getByRole('combobox', { name: /Mention/ })).toHaveCount(0);
+ await expect(textarea).toBeFocused();
+ });
+
+ test('an endpoint drills into its models and the pick switches the model @scenario:mention-popover-switches-model', async ({
+ page,
+ }) => {
+ /* Mock Providers A and B are model specs in the e2e config, so they switch on pick; C is a
+ plain custom endpoint the mention list offers as an endpoint row. */
+ const target = { label: 'Mock Provider C', model: 'mock-model-c' };
+ const { textarea, combobox } = await openMention(page);
+
+ /* The filter also matches the endpoint's own models (their value is the endpoint name), so
+ walk to the endpoint row itself rather than assuming it ranks first. */
+ await combobox.fill(target.label);
+ const endpointRow = page.getByRole('option', { name: target.label, exact: true });
+ await expect(endpointRow).toBeVisible();
+ const endpointId = await endpointRow.getAttribute('id');
+ for (let step = 0; step < 10; step++) {
+ if ((await combobox.getAttribute('aria-activedescendant')) === endpointId) {
+ break;
+ }
+ await combobox.press('ArrowDown');
+ }
+ await expect(combobox).toHaveAttribute('aria-activedescendant', endpointId ?? '');
+ await combobox.press('Enter');
+
+ await expect(combobox).toHaveValue('');
+ await expect(await activeOption(page)).toContainText(target.model);
+ await combobox.press('Enter');
+
+ await expect(page.getByRole('combobox', { name: /Mention/ })).toHaveCount(0);
+ await expect(modelSelectorTrigger(page)).toContainText(/Mock Provider C|mock-model-c/);
+ await expect(textarea).toBeFocused();
+ await expect(textarea).toHaveValue('');
+ });
+
+ test('no match closes the popover and returns to the draft @scenario:mention-popover-no-match-closes', async ({
+ page,
+ }) => {
+ const { textarea, combobox } = await openMention(page);
+
+ await combobox.fill('zzzz-no-such-entry');
+ await expect(combobox).toHaveAttribute('aria-expanded', 'false');
+ await expect(combobox).not.toHaveAttribute('aria-activedescendant', /.*/);
+ await combobox.press('Enter');
+
+ await expect(page.getByRole('combobox', { name: /Mention/ })).toHaveCount(0);
+ await expect(textarea).toBeFocused();
+ });
+});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index d3cba89fce..81e89802a8 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -127,11 +127,6 @@
"count": 15
}
},
- "client/src/components/Chat/Input/Mention.tsx": {
- "shadcn/no-restyle": {
- "count": 4
- }
- },
"client/src/components/Chat/Input/PopoverButtons.tsx": {
"shadcn/no-restyle": {
"count": 11
diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts
index f88c4fe6c7..7939ae0b98 100644
--- a/packages/chat/src/components.ts
+++ b/packages/chat/src/components.ts
@@ -19,6 +19,8 @@ export type {
/** Composer: the chat input, its controls and the steering queue. */
export { default as StopButton } from './components/composer/StopButton';
export { default as MentionItem } from './components/composer/MentionItem';
+export { default as MentionPopover } from './components/composer/popover/Mention';
+export { default as CommandPopover } from './components/composer/popover/Command';
export { default as CollapseChat } from './components/composer/CollapseChat';
export { default as ComposerChip } from './components/composer/bar/Chip';
export { default as composerClearance } from './components/composer/clearance';
@@ -31,6 +33,12 @@ export {
} from './components/composer/steering/QueuedTurnPortal';
export type { ComposerSubmitRoute } from './components/composer/submit';
export type { MentionItemProps } from './components/composer/MentionItem';
+export type { MentionPopoverProps } from './components/composer/popover/Mention';
+export type {
+ CommandOption,
+ CommandPopoverProps,
+ CommandDismissReason,
+} from './components/composer/popover/Command';
export type { ChipProps as ComposerChipProps } from './components/composer/bar/Chip';
export type { SteerReceiptState } from './components/composer/steering/Receipt';
export { default as FileUpload } from './components/composer/files/FileUpload';
diff --git a/packages/chat/src/components/composer/MentionItem.tsx b/packages/chat/src/components/composer/MentionItem.tsx
index 84af581bf3..14e7245f0a 100644
--- a/packages/chat/src/components/composer/MentionItem.tsx
+++ b/packages/chat/src/components/composer/MentionItem.tsx
@@ -11,6 +11,8 @@ export interface MentionItemProps {
isActive?: boolean;
description?: string;
style?: React.CSSProperties;
+ /** `option` makes the row a listbox option the popover's input points at, out of the tab order. */
+ role?: 'option';
}
export default function MentionItem({
@@ -21,13 +23,16 @@ export default function MentionItem({
isActive,
description,
style,
+ role,
type = 'mention',
}: MentionItemProps): React.JSX.Element {
return (
<button
type="button"
style={style}
- tabIndex={index}
+ role={role}
+ aria-selected={role === 'option' ? isActive === true : undefined}
+ tabIndex={role === 'option' ? -1 : index}
onClick={onClick}
id={`${type}-item-${index}`}
className="w-full touch-manipulation"
diff --git a/packages/chat/src/components/composer/popover/Command.tsx b/packages/chat/src/components/composer/popover/Command.tsx
new file mode 100644
index 0000000000..e923c82ef3
--- /dev/null
+++ b/packages/chat/src/components/composer/popover/Command.tsx
@@ -0,0 +1,200 @@
+import { useId, useRef, useEffect } from 'react';
+import { Input, Spinner, useRemScale } from '@librechat/client';
+import type { Dispatch, ReactNode, SetStateAction, KeyboardEvent } from 'react';
+import type { CommandListProps, CommandListRow } from '../../../react/input';
+import type { MentionItemProps } from '../MentionItem';
+import { useComposerHost } from '../../../react/input';
+import MentionItem from '../MentionItem';
+
+const ROW_HEIGHT = 44;
+const MAX_LIST_HEIGHT = 160;
+const BLUR_CLOSE_DELAY = 150;
+
+/** One entry a command popover lists. */
+export type CommandOption = {
+ type: string;
+ value: string;
+ label?: string;
+ description?: string;
+ icon?: ReactNode;
+};
+
+/** Why a popover asks to close: the key that closed it, or focus leaving its input. */
+export type CommandDismissReason = 'escape' | 'backspace' | 'commit' | 'blur';
+
+export interface CommandPopoverProps {
+ type: NonNullable<MentionItemProps['type']>;
+ /** Localized placeholder, also the listbox's accessible name. */
+ placeholder: string;
+ inputRef: (node: HTMLInputElement | null) => void;
+ searchValue: string;
+ onSearchChange: (value: string) => void;
+ open: boolean;
+ onOpen: () => void;
+ matches: CommandOption[];
+ activeIndex: number;
+ onActiveIndexChange: Dispatch<SetStateAction<number>>;
+ isLoading?: boolean;
+ /** Enter or Tab on an option, or a click; the key event lets the caller decide its default. */
+ onSelect: (option: CommandOption, event?: KeyboardEvent<HTMLInputElement>) => void;
+ /** The popover asks to close; a key event is present unless focus left the input. */
+ onDismiss: (reason: CommandDismissReason, event?: KeyboardEvent<HTMLInputElement>) => void;
+}
+
+/** Without a host list every option renders, inside the scrolling listbox. */
+function PlainList({ count, renderRow }: CommandListProps): React.JSX.Element {
+ return (
+ <>
+ {Array.from({ length: count }, (_, index) =>
+ renderRow({ index, key: `${index}`, style: {} }),
+ )}
+ </>
+ );
+}
+
+/** A search field that filters a list of composer commands, driven by the keyboard as a combobox:
+ * arrows move the active option, Enter or Tab picks it, Escape or Backspace on an empty search
+ * closes. Rows go through the host's windowed list when it supplies one. */
+export default function CommandPopover({
+ type,
+ placeholder,
+ inputRef,
+ searchValue,
+ onSearchChange,
+ open,
+ onOpen,
+ matches,
+ activeIndex,
+ onActiveIndexChange,
+ isLoading = false,
+ onSelect,
+ onDismiss,
+}: CommandPopoverProps): React.JSX.Element {
+ const listboxId = useId();
+ const remScale = useRemScale();
+ const { renderCommandList } = useComposerHost();
+ const listRef = useRef<HTMLDivElement | null>(null);
+ const blurTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const cancelBlurClose = () => {
+ if (blurTimer.current) {
+ clearTimeout(blurTimer.current);
+ }
+ blurTimer.current = null;
+ };
+
+ useEffect(() => cancelBlurClose, []);
+
+ useEffect(() => {
+ onActiveIndexChange((prev) => Math.min(prev, Math.max(matches.length - 1, 0)));
+ }, [matches.length, onActiveIndexChange]);
+
+ useEffect(() => {
+ const active = listRef.current?.querySelector<HTMLElement>('[aria-selected="true"]');
+ active?.scrollIntoView({ behavior: 'instant', block: 'nearest' });
+ }, [activeIndex, matches]);
+
+ const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Escape') {
+ onDismiss('escape', e);
+ return;
+ }
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ if (matches.length === 0) {
+ return;
+ }
+ e.preventDefault();
+ const step = e.key === 'ArrowDown' ? 1 : -1;
+ onActiveIndexChange((prev) => (prev + step + matches.length) % matches.length);
+ return;
+ }
+ if (e.key === 'Enter' || e.key === 'Tab') {
+ const option = matches[activeIndex];
+ if (option == null) {
+ onDismiss('commit', e);
+ return;
+ }
+ onSelect(option, e);
+ return;
+ }
+ if (e.key === 'Backspace' && searchValue === '') {
+ onDismiss('backspace', e);
+ }
+ };
+
+ const showList = open && matches.length > 0;
+ const activeId = showList ? `${type}-item-${activeIndex}` : undefined;
+
+ const renderRow = ({ index, key, style }: CommandListRow): ReactNode => {
+ const option = matches[index];
+ return (
+ <MentionItem
+ key={key}
+ type={type}
+ role="option"
+ index={index}
+ style={style}
+ name={option.label ?? ''}
+ icon={option.icon}
+ description={option.description}
+ isActive={index === activeIndex}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ cancelBlurClose();
+ onSelect(option);
+ }}
+ />
+ );
+ };
+
+ const listProps: CommandListProps = {
+ count: matches.length,
+ activeIndex,
+ rowHeight: ROW_HEIGHT * remScale,
+ height: Math.min(matches.length * ROW_HEIGHT, MAX_LIST_HEIGHT) * remScale,
+ renderRow,
+ };
+
+ return (
+ <div className="absolute bottom-28 z-10 w-full space-y-2">
+ <div className="popover border-border-light bg-surface-tertiary-alt rounded-theme-popover border p-2 shadow-lg">
+ <Input
+ ref={inputRef}
+ role="combobox"
+ aria-autocomplete="list"
+ aria-expanded={showList}
+ aria-controls={listboxId}
+ aria-activedescendant={activeId}
+ placeholder={placeholder}
+ variant="embedded"
+ className="mb-1"
+ autoComplete="off"
+ value={searchValue}
+ onKeyDown={handleKeyDown}
+ onChange={(e) => onSearchChange(e.target.value)}
+ onFocus={onOpen}
+ onBlur={() => {
+ blurTimer.current = setTimeout(() => onDismiss('blur'), BLUR_CLOSE_DELAY);
+ }}
+ />
+ {open && isLoading && matches.length === 0 && (
+ <div className="text-text-primary flex h-32 items-center justify-center">
+ <Spinner />
+ </div>
+ )}
+ <div
+ ref={listRef}
+ id={listboxId}
+ role="listbox"
+ aria-label={placeholder}
+ hidden={!showList}
+ className="max-h-40 overflow-y-auto"
+ >
+ {showList &&
+ (renderCommandList ? renderCommandList(listProps) : <PlainList {...listProps} />)}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/chat/src/components/composer/popover/Mention.tsx b/packages/chat/src/components/composer/popover/Mention.tsx
new file mode 100644
index 0000000000..77724f7b5b
--- /dev/null
+++ b/packages/chat/src/components/composer/popover/Mention.tsx
@@ -0,0 +1,141 @@
+import { useState, useRef, useEffect } from 'react';
+import { useCombobox } from '@librechat/client';
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { KeyboardEvent, MutableRefObject } from 'react';
+import type { CommandOption, CommandDismissReason } from './Command';
+import { removeCharIfLast } from '../../../core/textarea';
+import useInitPopoverInput from '../../../react/popover';
+import CommandPopover from './Command';
+
+export interface MentionPopoverProps {
+ textAreaRef: MutableRefObject<HTMLTextAreaElement | null>;
+ /** The character that opened the popover; `+` adds a conversation instead of switching. */
+ commandChar?: string;
+ /** Localized placeholder for the search field. */
+ placeholder: string;
+ options: CommandOption[];
+ isLoading: boolean;
+ /** Options listed after picking the Agents endpoint. */
+ agentsList?: CommandOption[] | null;
+ /** Options listed after picking an Assistants endpoint, by endpoint. */
+ assistantListMap: Partial<Record<string, CommandOption[] | undefined>>;
+ /** Model names by endpoint, listed after picking any other endpoint. */
+ modelsConfig?: Record<string, string[]> | null;
+ /** A final pick: a model, preset, spec, agent or assistant. */
+ onSelectMention: (option: CommandOption) => void;
+ /** Hides the popover. */
+ onClose: () => void;
+}
+
+/** The `@` (and `+`) popover: endpoints drill into their agents, assistants or models, and any
+ * other pick switches the conversation through `onSelectMention`. */
+export default function MentionPopover({
+ textAreaRef,
+ commandChar = '@',
+ placeholder,
+ options,
+ isLoading,
+ agentsList,
+ assistantListMap,
+ modelsConfig,
+ onSelectMention,
+ onClose,
+}: MentionPopoverProps): React.JSX.Element {
+ const [activeIndex, setActiveIndex] = useState(0);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [inputOptions, setInputOptions] = useState<CommandOption[]>(options);
+
+ const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({
+ value: '',
+ options: inputOptions,
+ });
+
+ const initInputRef = useInitPopoverInput({
+ inputRef,
+ textAreaRef,
+ commandChar,
+ setSearchValue,
+ setOpen,
+ });
+
+ useEffect(() => {
+ if (!open) {
+ setInputOptions(options);
+ setActiveIndex(0);
+ }
+ }, [open, options]);
+
+ const drillInto = (next: CommandOption[]) => {
+ setSearchValue('');
+ setInputOptions(next);
+ setActiveIndex(0);
+ inputRef.current?.focus();
+ };
+
+ const nextOptions = (mention: CommandOption): CommandOption[] | undefined => {
+ if (mention.type !== 'endpoint') {
+ return undefined;
+ }
+ if (mention.value === EModelEndpoint.agents) {
+ return agentsList ?? [];
+ }
+ if (
+ mention.value === EModelEndpoint.assistants ||
+ mention.value === EModelEndpoint.azureAssistants
+ ) {
+ return assistantListMap[mention.value] ?? [];
+ }
+ return (modelsConfig?.[mention.value] ?? []).map((model) => ({
+ value: mention.value,
+ label: model,
+ type: 'model',
+ }));
+ };
+
+ const handleSelect = (mention: CommandOption, e?: KeyboardEvent<HTMLInputElement>) => {
+ if (mention.type === 'endpoint' || e?.key === 'Enter') {
+ e?.preventDefault();
+ }
+ const next = nextOptions(mention);
+ if (next) {
+ drillInto(next);
+ return;
+ }
+ setSearchValue('');
+ setOpen(false);
+ onClose();
+ onSelectMention(mention);
+ if (textAreaRef.current) {
+ removeCharIfLast(textAreaRef.current, commandChar);
+ }
+ };
+
+ const handleDismiss = (reason: CommandDismissReason, e?: KeyboardEvent<HTMLInputElement>) => {
+ if (reason === 'commit') {
+ e?.preventDefault();
+ }
+ setOpen(false);
+ onClose();
+ if (reason !== 'blur') {
+ textAreaRef.current?.focus();
+ }
+ };
+
+ return (
+ <CommandPopover
+ type={commandChar !== '@' ? 'add-convo' : 'mention'}
+ placeholder={placeholder}
+ inputRef={initInputRef}
+ searchValue={searchValue}
+ onSearchChange={setSearchValue}
+ open={open}
+ onOpen={() => setOpen(true)}
+ matches={matches as CommandOption[]}
+ activeIndex={activeIndex}
+ onActiveIndexChange={setActiveIndex}
+ isLoading={isLoading}
+ onSelect={handleSelect}
+ onDismiss={handleDismiss}
+ />
+ );
+}
diff --git a/packages/chat/src/components/composer/popover/__tests__/Mention.spec.tsx b/packages/chat/src/components/composer/popover/__tests__/Mention.spec.tsx
new file mode 100644
index 0000000000..e3ff91ee7c
--- /dev/null
+++ b/packages/chat/src/components/composer/popover/__tests__/Mention.spec.tsx
@@ -0,0 +1,248 @@
+/**
+ * @jest-environment jsdom
+ */
+import React from 'react';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import type { CommandListProps, ComposerHost } from '../../../../react/input';
+import type { MentionPopoverProps } from '../Mention';
+import type { CommandOption } from '../Command';
+import { ComposerHostProvider } from '../../../../react/input';
+import { NO_HOST_BINDINGS } from '../../../../core/shortcuts';
+import MentionPopover from '../Mention';
+
+/**
+ * The `@` popover's keyboard contract, exercised through the plain list a host without a windowed
+ * list gets: the input is a combobox pointing at the active option, arrows wrap and are no-ops on
+ * an empty list (issue #13929), Enter and Tab on no matches close and refocus the textarea, and
+ * endpoints drill into their models instead of selecting.
+ */
+
+const PLACEHOLDER = 'Mention a model';
+
+const makeTextarea = (initial = '@') => {
+ const textarea = document.createElement('textarea');
+ textarea.value = initial;
+ document.body.appendChild(textarea);
+ return { current: textarea } as React.MutableRefObject<HTMLTextAreaElement | null>;
+};
+
+const option = (overrides: Partial<CommandOption>): CommandOption => ({
+ type: 'preset',
+ label: 'Alpha',
+ value: 'alpha',
+ description: '',
+ ...overrides,
+});
+
+const options: CommandOption[] = [
+ option({ label: 'Alpha', value: 'alpha' }),
+ option({ label: 'Beta', value: 'beta' }),
+];
+
+const scrollIntoView = jest.fn();
+const lastScrolled = () => scrollIntoView.mock.contexts[scrollIntoView.mock.contexts.length - 1];
+
+beforeAll(() => {
+ Element.prototype.scrollIntoView = scrollIntoView;
+});
+
+beforeEach(() => {
+ document.body.innerHTML = '';
+ scrollIntoView.mockClear();
+});
+
+const renderMention = (props: Partial<MentionPopoverProps> = {}, host?: ComposerHost) => {
+ const textAreaRef = makeTextarea('@');
+ const onClose = jest.fn();
+ const onSelectMention = jest.fn();
+ const ui = (
+ <MentionPopover
+ textAreaRef={textAreaRef}
+ placeholder={PLACEHOLDER}
+ options={options}
+ isLoading={false}
+ assistantListMap={{}}
+ onClose={onClose}
+ onSelectMention={onSelectMention}
+ {...props}
+ />
+ );
+ const utils = render(host ? <ComposerHostProvider host={host}>{ui}</ComposerHostProvider> : ui);
+ return { textAreaRef, onClose, onSelectMention, ...utils };
+};
+
+const input = () => screen.getByRole('combobox');
+const activeId = () => input().getAttribute('aria-activedescendant');
+
+describe('MentionPopover through the plain list', () => {
+ it('exposes the input as a combobox controlling a listbox of options', () => {
+ renderMention();
+
+ const listbox = screen.getByRole('listbox', { name: PLACEHOLDER });
+ expect(input()).toHaveAttribute('aria-controls', listbox.id);
+ expect(input()).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getAllByRole('option')).toHaveLength(2);
+ expect(activeId()).toBe('mention-item-0');
+ expect(document.getElementById('mention-item-0')).toHaveAttribute('aria-selected', 'true');
+ expect(document.getElementById('mention-item-1')).toHaveAttribute('aria-selected', 'false');
+ });
+
+ it('moves the active option with ArrowDown/ArrowUp, wraps, and scrolls it into view', () => {
+ renderMention();
+
+ fireEvent.keyDown(input(), { key: 'ArrowDown' });
+ expect(activeId()).toBe('mention-item-1');
+ expect(document.getElementById('mention-item-1')).toHaveAttribute('aria-selected', 'true');
+ expect(lastScrolled()).toBe(document.getElementById('mention-item-1'));
+
+ fireEvent.keyDown(input(), { key: 'ArrowDown' });
+ expect(activeId()).toBe('mention-item-0');
+
+ fireEvent.keyDown(input(), { key: 'ArrowUp' });
+ expect(activeId()).toBe('mention-item-1');
+ expect(lastScrolled()).toBe(document.getElementById('mention-item-1'));
+ });
+
+ it('keeps navigation working after filtering to zero matches and back', () => {
+ renderMention();
+
+ fireEvent.change(input(), { target: { value: 'zzz' } });
+ expect(screen.queryByRole('option')).toBeNull();
+ expect(input()).toHaveAttribute('aria-expanded', 'false');
+ expect(input()).not.toHaveAttribute('aria-activedescendant');
+
+ fireEvent.keyDown(input(), { key: 'ArrowDown' });
+ fireEvent.keyDown(input(), { key: 'ArrowUp' });
+
+ fireEvent.change(input(), { target: { value: '' } });
+ expect(screen.getAllByRole('option')).toHaveLength(2);
+
+ fireEvent.keyDown(input(), { key: 'ArrowDown' });
+ expect(activeId()).toBe('mention-item-1');
+ });
+
+ it.each(['Enter', 'Tab'])(
+ 'closes and refocuses the textarea when %s is pressed with no matches',
+ (key) => {
+ const { textAreaRef, onClose } = renderMention();
+
+ fireEvent.change(input(), { target: { value: 'zzz' } });
+ const notPrevented = fireEvent.keyDown(input(), { key });
+
+ expect(notPrevented).toBe(false);
+ expect(onClose).toHaveBeenCalled();
+ expect(document.activeElement).toBe(textAreaRef.current);
+ },
+ );
+
+ it('closes on Escape and returns focus to the textarea', () => {
+ const { textAreaRef, onClose } = renderMention();
+
+ fireEvent.keyDown(input(), { key: 'Escape' });
+
+ expect(onClose).toHaveBeenCalled();
+ expect(document.activeElement).toBe(textAreaRef.current);
+ });
+
+ it('selects the active option on Enter', () => {
+ const { onClose, onSelectMention } = renderMention();
+
+ fireEvent.keyDown(input(), { key: 'ArrowDown' });
+ const notPrevented = fireEvent.keyDown(input(), { key: 'Enter' });
+
+ expect(notPrevented).toBe(false);
+ expect(onSelectMention).toHaveBeenCalledWith(options[1]);
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('drills an endpoint into its models instead of selecting it', () => {
+ const { onSelectMention, onClose } = renderMention({
+ options: [option({ type: 'endpoint', label: 'OpenAI', value: 'openAI' })],
+ modelsConfig: { openAI: ['gpt-a', 'gpt-b'] },
+ });
+
+ fireEvent.keyDown(input(), { key: 'Tab' });
+
+ expect(onSelectMention).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getAllByRole('option').map((el) => el.textContent)).toEqual(['gpt-a', 'gpt-b']);
+ expect(activeId()).toBe('mention-item-0');
+
+ fireEvent.keyDown(input(), { key: 'Enter' });
+ expect(onSelectMention).toHaveBeenCalledWith({
+ type: 'model',
+ value: 'openAI',
+ label: 'gpt-a',
+ });
+ });
+
+ it('closes once focus leaves the input, without pulling focus back', () => {
+ jest.useFakeTimers();
+ try {
+ const { onClose, textAreaRef } = renderMention();
+
+ fireEvent.blur(input());
+ expect(onClose).not.toHaveBeenCalled();
+ act(() => {
+ jest.advanceTimersByTime(150);
+ });
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(document.activeElement).not.toBe(textAreaRef.current);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('keeps the popover open when a click on an option follows the blur', () => {
+ jest.useFakeTimers();
+ try {
+ const { onClose } = renderMention({
+ options: [option({ type: 'endpoint', label: 'OpenAI', value: 'openAI' })],
+ modelsConfig: { openAI: ['gpt-a'] },
+ });
+
+ fireEvent.blur(input());
+ fireEvent.click(document.getElementById('mention-item-0') as HTMLElement);
+ act(() => {
+ jest.runAllTimers();
+ });
+
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getByRole('option')).toHaveTextContent('gpt-a');
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+});
+
+describe('MentionPopover through a host list', () => {
+ it('renders its rows through the host windowed list', () => {
+ const renderCommandList = jest.fn(({ count, renderRow }: CommandListProps) => (
+ <div data-testid="host-list">
+ {Array.from({ length: count }, (_, index) =>
+ renderRow({ index, key: `${index}`, style: { height: 44 } }),
+ )}
+ </div>
+ ));
+ const host: ComposerHost = {
+ useComposerBindings: () => NO_HOST_BINDINGS,
+ useShortcutDisplay: () => '',
+ useShortcutAriaKey: () => undefined,
+ renderCommandList,
+ };
+ renderMention({}, host);
+
+ expect(renderCommandList).toHaveBeenLastCalledWith(
+ expect.objectContaining({ count: 2, activeIndex: 0 }),
+ );
+ expect(screen.getByTestId('host-list')).toBeInTheDocument();
+ expect(screen.getByRole('listbox')).toContainElement(screen.getByTestId('host-list'));
+
+ fireEvent.keyDown(input(), { key: 'ArrowDown' });
+ expect(renderCommandList).toHaveBeenLastCalledWith(
+ expect.objectContaining({ count: 2, activeIndex: 1 }),
+ );
+ expect(activeId()).toBe('mention-item-1');
+ });
+});
diff --git a/packages/chat/src/core/index.ts b/packages/chat/src/core/index.ts
index 80ae190147..e95b2a45db 100644
--- a/packages/chat/src/core/index.ts
+++ b/packages/chat/src/core/index.ts
@@ -23,4 +23,5 @@ export * from './branch';
export * from './subagents';
export { strongDirection } from './direction';
export * from './shortcuts';
+export { removeCharIfLast } from './textarea';
export * from './pane';
diff --git a/packages/chat/src/core/textarea.ts b/packages/chat/src/core/textarea.ts
new file mode 100644
index 0000000000..e42b8c7078
--- /dev/null
+++ b/packages/chat/src/core/textarea.ts
@@ -0,0 +1,11 @@
+/** Drops the command character a popover was opened with when it still ends the draft, and puts
+ * the caret back in the textarea. */
+export function removeCharIfLast(textarea: HTMLTextAreaElement, charToRemove: string): void {
+ if (textarea.value.endsWith(charToRemove)) {
+ textarea.value = textarea.value.slice(0, -1);
+ textarea.setSelectionRange(textarea.value.length, textarea.value.length);
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+
+ textarea.focus();
+}
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index 00ac7a83c9..65086119ab 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -169,7 +169,12 @@ export { default as useElementSize } from './react/size';
export { default as useAudioLevels, frameLevel } from './react/levels';
export { default as useInitPopoverInput } from './react/popover';
export { useComposerHost, ComposerHostProvider } from './react/input';
-export type { ComposerHost, ComposerShortcutAction } from './react/input';
+export type {
+ ComposerHost,
+ CommandListRow,
+ CommandListProps,
+ ComposerShortcutAction,
+} from './react/input';
export {
RowMountProvider,
useRowMountWindow,
diff --git a/packages/chat/src/react/input.tsx b/packages/chat/src/react/input.tsx
index 372e188349..61c161b665 100644
--- a/packages/chat/src/react/input.tsx
+++ b/packages/chat/src/react/input.tsx
@@ -1,11 +1,29 @@
import { createContext, useContext } from 'react';
-import type { ReactNode } from 'react';
+import type { CSSProperties, ReactNode } from 'react';
import type { ComposerBindings } from '../core/shortcuts';
import { NO_HOST_BINDINGS } from '../core/shortcuts';
/** Composer actions whose chord the user can rebind and the composer advertises. */
export type ComposerShortcutAction = 'escalateSteer';
+/** One row of a command popover's list, in the shape a windowing library hands its renderer. */
+export interface CommandListRow {
+ index: number;
+ key: string;
+ style: CSSProperties;
+}
+
+/** What a command popover gives the list it renders its options into. */
+export interface CommandListProps {
+ count: number;
+ activeIndex: number;
+ /** Row height in pixels, already scaled to the root font size. */
+ rowHeight: number;
+ /** Visible list height in pixels, already scaled to the root font size. */
+ height: number;
+ renderRow: (row: CommandListRow) => ReactNode;
+}
+
/** App capabilities the composer controls read. */
export interface ComposerHost {
/** The user's effective composer-relevant shortcut bindings. */
@@ -14,6 +32,8 @@ export interface ComposerHost {
useShortcutDisplay: (action: ComposerShortcutAction) => string;
/** The chord bound to an action, in `aria-keyshortcuts` form; undefined when unbound. */
useShortcutAriaKey: (action: ComposerShortcutAction) => string | undefined;
+ /** Renders a command popover's options through a windowed list; without it every row renders. */
+ renderCommandList?: (props: CommandListProps) => ReactNode;
}
/** Without a host the composer keeps the stock chords and advertises no rebound ones. */
diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx
index 9f6da2aa1d..375b4816dd 100644
--- a/packages/chat/test/consumer.spec.tsx
+++ b/packages/chat/test/consumer.spec.tsx
@@ -5,7 +5,13 @@ import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';
import { Chat } from '@librechat/chat';
import { createInstance } from 'i18next';
import { ContentTypes } from 'librechat-data-provider';
-import { Part, Text, MessageRow, getHeaderHoverLabel } from '@librechat/chat/components';
+import {
+ Part,
+ Text,
+ MessageRow,
+ MentionPopover,
+ getHeaderHoverLabel,
+} from '@librechat/chat/components';
import { initReactI18next, I18nextProvider } from 'react-i18next';
import { act, fireEvent, render, screen, within } from '@testing-library/react';
import { Button, Textarea, ThemeProvider, clickHouseTheme } from '@librechat/client';
@@ -359,4 +365,37 @@ describe('a consumer built on the public entries', () => {
'Inconsolata',
);
});
+
+ it('picks a mention from the composer popover with the keyboard alone', () => {
+ /** jsdom lays nothing out, so it has no `scrollIntoView` for the active option to call. */
+ Element.prototype.scrollIntoView = jest.fn();
+ const textarea = document.createElement('textarea');
+ textarea.value = '@';
+ document.body.appendChild(textarea);
+ const onSelectMention = jest.fn();
+ render(
+ <ThemeProvider themeDefinition={clickHouseTheme} persistThemeDefinition={false}>
+ <MentionPopover
+ textAreaRef={{ current: textarea }}
+ placeholder="Mention"
+ options={[
+ { type: 'preset', value: 'draft', label: 'Draft' },
+ { type: 'preset', value: 'review', label: 'Review' },
+ ]}
+ isLoading={false}
+ assistantListMap={{}}
+ onSelectMention={onSelectMention}
+ onClose={jest.fn()}
+ />
+ </ThemeProvider>,
+ );
+
+ const combobox = screen.getByRole('combobox');
+ fireEvent.keyDown(combobox, { key: 'ArrowDown' });
+ const active = combobox.getAttribute('aria-activedescendant') ?? '';
+ expect(document.getElementById(active)).toHaveTextContent('Review');
+ fireEvent.keyDown(combobox, { key: 'Enter' });
+ expect(onSelectMention).toHaveBeenCalledWith(expect.objectContaining({ value: 'review' }));
+ textarea.remove();
+ });
});