diff --git a/client/src/components/Chat/Input/PromptsCommand.tsx b/client/src/components/Chat/Input/PromptsCommand.tsx index 887666eabf..16be48a528 100644 --- a/client/src/components/Chat/Input/PromptsCommand.tsx +++ b/client/src/components/Chat/Input/PromptsCommand.tsx @@ -1,17 +1,10 @@ -import { useState, useRef, useEffect, useMemo, memo, useCallback } from 'react'; -import { AutoSizer, List } from 'react-virtualized'; -import { MentionItem } from '@librechat/chat/components'; +import { useState, useEffect, useMemo, memo, useCallback } from 'react'; +import { useToastContext } from '@librechat/client'; import { useSetRecoilState, useRecoilValue } from 'recoil'; -import { useInitPopoverInput } from '@librechat/chat/react'; -import { Input, Spinner, useCombobox, useRemScale, useToastContext } from '@librechat/client'; +import { PromptsPopover } from '@librechat/chat/components'; import type { TPromptGroup } from 'librechat-data-provider'; import type { PromptOption } from '~/common'; -import { - removeCharIfLast, - detectVariables, - isExternalPromptGroup, - getPromptResolveErrorMessage, -} from '~/utils'; +import { detectVariables, isExternalPromptGroup, getPromptResolveErrorMessage } from '~/utils'; import { activateCatalog, useLocalize, usePromptContentResolver } from '~/hooks'; import useChatScopedRequest from '~/hooks/Prompts/useChatScopedRequest'; import { useRecordPromptUsage } from '~/data-provider'; @@ -19,8 +12,6 @@ import { VariableDialog } from '~/components/Prompts'; import { usePromptGroupsContext } from '~/Providers'; import store from '~/store'; -const commandChar = '/'; - const PopoverContainer = memo( ({ index, @@ -59,8 +50,6 @@ const PopoverContainer = memo( }, ); -const ROW_HEIGHT = 44; - function PromptsCommand({ index, textAreaRef, @@ -71,7 +60,6 @@ function PromptsCommand({ submitPrompt: (textPrompt: string) => void; }) { const localize = useLocalize(); - const remScale = useRemScale(); const { showToast } = useToastContext(); const { mutate: recordUsage } = useRecordPromptUsage(); const resolvePromptContent = usePromptContentResolver(); @@ -80,9 +68,6 @@ function PromptsCommand({ const { data, isLoading } = allPromptGroups ?? {}; const showPromptsPopover = useRecoilValue(store.showPromptsPopoverFamily(index)); - const [activeIndex, setActiveIndex] = useState(0); - const timeoutRef = useRef(null); - const inputRef = useRef(null); const [isVariableDialogOpen, setVariableDialogOpen] = useState(false); const [variableGroup, setVariableGroup] = useState(null); const [variableText, setVariableText] = useState(undefined); @@ -99,33 +84,8 @@ function PromptsCommand({ const prompts = useMemo(() => data?.promptGroups, [data]); const promptsMap = useMemo(() => data?.promptsMap, [data]); - const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({ - value: '', - options: prompts ?? [], - }); - - const initInputRef = useInitPopoverInput({ - inputRef, - textAreaRef, - commandChar, - setSearchValue, - setOpen, - }); - const handleSelect = useCallback( - async (mention?: PromptOption, e?: React.KeyboardEvent) => { - if (!mention) { - return; - } - - setSearchValue(''); - setOpen(false); - setShowPromptsPopover(false); - - if (textAreaRef.current) { - removeCharIfLast(textAreaRef.current, commandChar); - } - + async (mention: PromptOption, e?: React.KeyboardEvent) => { const group = promptsMap?.[mention.id]; if (!group) { return; @@ -180,9 +140,6 @@ function PromptsCommand({ } }, [ - setSearchValue, - setOpen, - setShowPromptsPopover, textAreaRef, promptsMap, submitPrompt, @@ -196,17 +153,15 @@ function PromptsCommand({ ], ); - useEffect(() => { + const handleOpenChange = useCallback((open: boolean) => { if (!open) { - setActiveIndex(0); - setSearchValue(''); - } else { - /** Opening the picker before background warmup starts the fetch now */ - activateCatalog('prompts'); - setVariableGroup(null); - setVariableText(undefined); + return; } - }, [open, setSearchValue]); + /** Opening the picker before background warmup starts the fetch now */ + activateCatalog('prompts'); + setVariableGroup(null); + setVariableText(undefined); + }, []); /** The full prompt list is fetched on first popover open, not at app startup */ useEffect(() => { @@ -215,58 +170,10 @@ function PromptsCommand({ } }, [showPromptsPopover, requestAllPromptGroups]); - useEffect(() => { - setActiveIndex((prev) => Math.min(prev, Math.max(matches.length - 1, 0))); - }, [matches.length]); - - useEffect(() => { - return () => { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - }; - }, []); - - useEffect(() => { - const currentActiveItem = document.getElementById(`prompt-item-${activeIndex}`); - currentActiveItem?.scrollIntoView({ behavior: 'instant', block: 'nearest' }); - }, [activeIndex]); - if (!hasAccess) { return null; } - const rowRenderer = ({ - index, - key, - style, - }: { - index: number; - key: string; - style: React.CSSProperties; - }) => { - const mention = matches[index] as PromptOption; - return ( - { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current); - } - timeoutRef.current = null; - handleSelect(mention); - }} - name={mention.label ?? ''} - icon={mention.icon} - description={mention.description} - isActive={index === activeIndex} - /> - ); - }; - return ( -
-
- { - if (e.key === 'Escape') { - setOpen(false); - setShowPromptsPopover(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); - setShowPromptsPopover(false); - textAreaRef.current?.focus(); - return; - } - if (e.key === 'Enter') { - e.preventDefault(); - } - handleSelect(matches[activeIndex] as PromptOption | undefined, e); - } else if (e.key === 'Backspace' && searchValue === '') { - setOpen(false); - setShowPromptsPopover(false); - textAreaRef.current?.focus(); - } - }} - onChange={(e) => setSearchValue(e.target.value)} - onFocus={() => setOpen(true)} - onBlur={() => { - timeoutRef.current = setTimeout(() => { - setOpen(false); - setShowPromptsPopover(false); - }, 150); - }} - /> - {open && isLoading && matches.length === 0 && ( -
- -
- )} - {open && matches.length > 0 && ( -
- - {({ width }) => ( - - )} - -
- )} -
-
+ setShowPromptsPopover(false)} + />
); } diff --git a/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx b/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx index 4d5c5ef754..87f9a850f8 100644 --- a/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx +++ b/client/src/components/Chat/Input/__tests__/PromptsCommand.spec.tsx @@ -92,31 +92,6 @@ jest.mock('~/hooks', () => ({ usePromptContentResolver: () => mockResolve, })); -/* 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
    {rows}
; - }, -})); - import PromptsCommand from '../PromptsCommand'; const makeTextarea = (initial = '/') => { @@ -236,14 +211,14 @@ describe('PromptsCommand keyboard navigation', () => { const input = getInput(); fireEvent.change(input, { target: { value: 'zzz' } }); - expect(screen.queryByRole('button')).toBeNull(); + expect(screen.queryByRole('option')).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); + expect(screen.getAllByRole('option')).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. */ diff --git a/client/src/utils/textarea.ts b/client/src/utils/textarea.ts index 917f256ecd..882cfebb3d 100644 --- a/client/src/utils/textarea.ts +++ b/client/src/utils/textarea.ts @@ -1,5 +1,3 @@ -export { removeCharIfLast } from '@librechat/chat'; - /** * Insert text at the cursor position in a textarea. */ diff --git a/e2e/specs/mock/scenarios/composer-prompts.spec.ts b/e2e/specs/mock/scenarios/composer-prompts.spec.ts new file mode 100644 index 0000000000..0795377aa1 --- /dev/null +++ b/e2e/specs/mock/scenarios/composer-prompts.spec.ts @@ -0,0 +1,141 @@ +import { expect, test } from '@playwright/test'; +import type { Page } from '@playwright/test'; +import { + MOCK_ENDPOINTS, + NEW_CHAT_PATH, + messagesView, + requestJson, + getAccessToken, + selectMockEndpoint, +} from '../helpers'; + +/** + * The `/` prompts popover, drawn by the chat package's command popover: a combobox over the + * user's prompts that sends a plain prompt on pick and asks for the variables of one that has + * them, keeping focus in that dialog when the pick was made with Tab. + */ +test.describe.configure({ timeout: 120_000 }); + +type CreatedGroup = { group?: { _id?: string } }; + +async function createPrompt(page: Page, name: string, prompt: string): Promise { + const token = await getAccessToken(page); + const body = await requestJson(page, { + path: '/api/prompts', + token, + method: 'POST', + body: { prompt: { prompt, type: 'text' }, group: { name, category: 'e2e' } }, + }); + const id = body.group?._id ?? ''; + expect(id).not.toBe(''); + return id; +} + +async function deletePrompt(page: Page, id: string) { + const token = await getAccessToken(page); + await requestJson<{ message?: string }>(page, { + path: `/api/prompts/groups/${encodeURIComponent(id)}`, + token, + method: 'DELETE', + }); +} + +async function openPrompts(page: Page) { + const textarea = page.getByRole('textbox', { name: 'Message input' }); + await textarea.click(); + await textarea.press('/'); + const combobox = page.getByRole('combobox', { name: /Select a Prompt/ }); + await expect(combobox).toBeFocused(); + return { textarea, combobox }; +} + +async function withPrompts( + page: Page, + prompts: Array<{ name: string; text: string }>, + run: () => Promise, +) { + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + const ids: string[] = []; + try { + for (const { name, text } of prompts) { + ids.push(await createPrompt(page, name, text)); + } + await page.reload(); + await selectMockEndpoint(page, MOCK_ENDPOINTS[0]); + await run(); + } finally { + for (const id of ids) { + await deletePrompt(page, id); + } + } +} + +test.describe('prompts popover', () => { + test('keyboard moves and announces the active prompt @scenario:prompts-popover-keyboard-combobox', async ({ + page, + }, testInfo) => { + const tag = `${testInfo.project.name}-${Date.now()}`; + await withPrompts( + page, + [ + { name: `e2e-alpha-${tag}`, text: 'Alpha prompt text' }, + { name: `e2e-beta-${tag}`, text: 'Beta prompt text' }, + ], + async () => { + const { textarea, combobox } = await openPrompts(page); + await combobox.fill(`e2e-`); + await expect(combobox).toHaveAttribute('aria-expanded', 'true'); + const listbox = page.locator(`[id="${await combobox.getAttribute('aria-controls')}"]`); + await expect(listbox.getByRole('option')).not.toHaveCount(0); + await expect(combobox).toHaveAttribute('aria-activedescendant', 'prompt-item-0'); + + await combobox.press('ArrowDown'); + await expect(combobox).toHaveAttribute('aria-activedescendant', 'prompt-item-1'); + await expect(page.locator('[id="prompt-item-1"]')).toHaveAttribute('aria-selected', 'true'); + + await combobox.press('Escape'); + await expect(page.getByRole('combobox', { name: /Select a Prompt/ })).toHaveCount(0); + await expect(textarea).toBeFocused(); + }, + ); + }); + + test('a plain prompt picked with Enter is sent @scenario:prompts-popover-sends-plain-prompt', async ({ + page, + }, testInfo) => { + const name = `e2e-send-${testInfo.project.name}-${Date.now()}`; + const text = `Summarize the e2e note ${Date.now()}`; + await withPrompts(page, [{ name, text }], async () => { + const { combobox } = await openPrompts(page); + await combobox.fill(name); + await expect(page.getByRole('option', { name })).toBeVisible(); + await combobox.press('Enter'); + + await expect(page.getByRole('combobox', { name: /Select a Prompt/ })).toHaveCount(0); + await expect(messagesView(page)).toContainText(text, { timeout: 30000 }); + }); + }); + + test('a prompt with variables picked with Tab opens its dialog and keeps focus there @scenario:prompts-popover-variables-dialog', async ({ + page, + }, testInfo) => { + const name = `e2e-vars-${testInfo.project.name}-${Date.now()}`; + await withPrompts( + page, + [{ name, text: 'Write to {{recipient}} about the e2e run' }], + async () => { + const { combobox } = await openPrompts(page); + await combobox.fill(name); + await expect(page.getByRole('option', { name })).toBeVisible(); + await combobox.press('Tab'); + + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + await expect(dialog).toContainText(name); + await expect + .poll(() => dialog.evaluate((node) => node.contains(document.activeElement))) + .toBe(true); + }, + ); + }); +}); diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index ccd1d6105e..86261b246c 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -20,6 +20,7 @@ export type { 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 PromptsPopover } from './components/composer/popover/Prompts'; 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'; @@ -34,6 +35,7 @@ export { export type { ComposerSubmitRoute } from './components/composer/submit'; export type { MentionItemProps } from './components/composer/MentionItem'; export type { MentionPopoverProps } from './components/composer/popover/Mention'; +export type { PromptsPopoverProps } from './components/composer/popover/Prompts'; export type { CommandOption, CommandPopoverProps, diff --git a/packages/chat/src/components/composer/popover/Prompts.tsx b/packages/chat/src/components/composer/popover/Prompts.tsx new file mode 100644 index 0000000000..9551a1f73e --- /dev/null +++ b/packages/chat/src/components/composer/popover/Prompts.tsx @@ -0,0 +1,111 @@ +import { useState, useRef, useEffect } from 'react'; +import { useCombobox } from '@librechat/client'; +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'; + +const COMMAND_CHAR = '/'; + +export interface PromptsPopoverProps { + textAreaRef: MutableRefObject; + /** Localized placeholder for the search field. */ + placeholder: string; + prompts: T[]; + isLoading: boolean; + /** The search field opened or closed; the host loads its catalog on open. */ + onOpenChange?: (open: boolean) => void; + /** A prompt was picked; the popover has already closed and dropped the `/`. A Tab pick passes + * its event so the host can keep focus for a dialog that follows. */ + onSelectPrompt: (prompt: T, event?: KeyboardEvent) => void; + /** Hides the popover. */ + onClose: () => void; +} + +/** The `/` popover: filters the user's prompts and hands the pick to the host, which resolves + * its text and either submits it or asks for its variables. */ +export default function PromptsPopover({ + textAreaRef, + placeholder, + prompts, + isLoading, + onOpenChange, + onSelectPrompt, + onClose, +}: PromptsPopoverProps): React.JSX.Element { + const [activeIndex, setActiveIndex] = useState(0); + const inputRef = useRef(null); + + const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({ + value: '', + options: prompts, + }); + + const initInputRef = useInitPopoverInput({ + inputRef, + textAreaRef, + commandChar: COMMAND_CHAR, + setSearchValue, + setOpen, + }); + + const openChangeRef = useRef(onOpenChange); + openChangeRef.current = onOpenChange; + + /** The popover mounts closed and opens from its input's ref, which may already have moved the + * text typed after the `/` into the search; only a real close clears it. */ + const wasOpen = useRef(false); + useEffect(() => { + if (open) { + wasOpen.current = true; + } else if (wasOpen.current) { + wasOpen.current = false; + setActiveIndex(0); + setSearchValue(''); + } + openChangeRef.current?.(open); + }, [open, setSearchValue]); + + const handleSelect = (prompt: CommandOption, e?: KeyboardEvent) => { + if (e?.key === 'Enter') { + e.preventDefault(); + } + setSearchValue(''); + setOpen(false); + onClose(); + if (textAreaRef.current) { + removeCharIfLast(textAreaRef.current, COMMAND_CHAR); + } + onSelectPrompt(prompt as T, e); + }; + + const handleDismiss = (reason: CommandDismissReason, e?: KeyboardEvent) => { + if (reason === 'commit') { + e?.preventDefault(); + } + setOpen(false); + onClose(); + if (reason !== 'blur') { + textAreaRef.current?.focus(); + } + }; + + return ( + 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__/Prompts.spec.tsx b/packages/chat/src/components/composer/popover/__tests__/Prompts.spec.tsx new file mode 100644 index 0000000000..2d84eaeff5 --- /dev/null +++ b/packages/chat/src/components/composer/popover/__tests__/Prompts.spec.tsx @@ -0,0 +1,128 @@ +/** + * @jest-environment jsdom + */ +import React from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; +import type { PromptsPopoverProps } from '../Prompts'; +import type { CommandOption } from '../Command'; +import PromptsPopover from '../Prompts'; + +/** + * The `/` popover's contract with its host: a pick closes the popover, drops the `/` from the + * draft and hands the prompt over; Enter never submits the form behind it, while Tab's default is + * left to the host, which keeps focus only when a dialog follows. + */ + +type Prompt = CommandOption & { id: string }; + +const prompts: Prompt[] = [ + { id: 'g1', type: 'prompt', value: 'summarize', label: 'summarize' }, + { id: 'g2', type: 'prompt', value: 'translate', label: 'translate' }, +]; + +beforeAll(() => { + Element.prototype.scrollIntoView = jest.fn(); +}); + +beforeEach(() => { + document.body.innerHTML = ''; +}); + +const renderPrompts = (props: Partial> = {}) => { + const textarea = document.createElement('textarea'); + textarea.value = '/'; + document.body.appendChild(textarea); + const textAreaRef = { current: textarea }; + const onClose = jest.fn(); + const onSelectPrompt = jest.fn(); + const onOpenChange = jest.fn(); + render( + , + ); + return { textarea, onClose, onSelectPrompt, onOpenChange }; +}; + +const input = () => screen.getByRole('combobox'); + +describe('PromptsPopover', () => { + it('reports opening to the host and lists the prompts as options', () => { + const { onOpenChange } = renderPrompts(); + + expect(onOpenChange).toHaveBeenLastCalledWith(true); + expect(screen.getByRole('listbox', { name: 'Prompts' })).toBeInTheDocument(); + expect(screen.getAllByRole('option')).toHaveLength(2); + expect(input()).toHaveAttribute('aria-activedescendant', 'prompt-item-0'); + }); + + it('keeps the text typed after the slash as the search when it opens', () => { + const textarea = document.createElement('textarea'); + textarea.value = '/tra'; + document.body.appendChild(textarea); + render( + , + ); + + expect(input()).toHaveValue('tra'); + expect(screen.getAllByRole('option').map((option) => option.textContent)).toEqual([ + 'translate', + ]); + expect(textarea.value).toBe(''); + }); + + it('hands an Enter pick to the host after closing, without submitting the form', () => { + const { onClose, onSelectPrompt, textarea } = renderPrompts(); + textarea.value = 'draft /'; + + fireEvent.keyDown(input(), { key: 'ArrowDown' }); + const notPrevented = fireEvent.keyDown(input(), { key: 'Enter' }); + + expect(notPrevented).toBe(false); + expect(onClose).toHaveBeenCalled(); + expect(onSelectPrompt).toHaveBeenCalledWith( + prompts[1], + expect.objectContaining({ key: 'Enter' }), + ); + expect(textarea.value).toBe('draft '); + }); + + it("leaves Tab's default to the host", () => { + const keepsFocus = jest.fn((_prompt: Prompt, event?: React.KeyboardEvent) => + event?.preventDefault(), + ); + renderPrompts({ onSelectPrompt: keepsFocus }); + const { onSelectPrompt: movesOn } = renderPrompts(); + + const [first, second] = screen.getAllByRole('combobox'); + expect(fireEvent.keyDown(first, { key: 'Tab' })).toBe(false); + expect(keepsFocus).toHaveBeenCalledWith(prompts[0], expect.anything()); + expect(fireEvent.keyDown(second, { key: 'Tab' })).toBe(true); + expect(movesOn).toHaveBeenCalledWith(prompts[0], expect.anything()); + }); + + it('closes and refocuses the draft on Enter with no matches', () => { + const { onClose, onSelectPrompt, textarea } = renderPrompts(); + + fireEvent.change(input(), { target: { value: 'zzz' } }); + expect(fireEvent.keyDown(input(), { key: 'Enter' })).toBe(false); + + expect(onClose).toHaveBeenCalled(); + expect(onSelectPrompt).not.toHaveBeenCalled(); + expect(document.activeElement).toBe(textarea); + }); +});