mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-19 14:33:38 +00:00
🪄 refactor: Move the Skills Popover Into the Chat Package (#17675)
This commit is contained in:
parent
75cf23e8a1
commit
759f6aebe5
7 changed files with 408 additions and 236 deletions
|
|
@ -1,16 +1,10 @@
|
|||
import { memo, useState, useRef, useEffect, useMemo, useCallback } from 'react';
|
||||
import { memo, useEffect, useMemo, useCallback } from 'react';
|
||||
import { ScrollText } from 'lucide-react';
|
||||
import { useSetRecoilState } from 'recoil';
|
||||
import { useSetAtom, useAtomValue } from 'jotai';
|
||||
import { AutoSizer, List } from 'react-virtualized';
|
||||
import { MentionItem } from '@librechat/chat/components';
|
||||
import { Input, Spinner, useCombobox, useRemScale } from '@librechat/client';
|
||||
import { SkillsPopover } from '@librechat/chat/components';
|
||||
import { SkillsScope, resolveAgentSkillsScope } from 'librechat-data-provider';
|
||||
import {
|
||||
pendingManualSkillsByConvoId,
|
||||
showSkillsPopoverFamily,
|
||||
useInitPopoverInput,
|
||||
} from '@librechat/chat/react';
|
||||
import { pendingManualSkillsByConvoId, showSkillsPopoverFamily } from '@librechat/chat/react';
|
||||
import type { TSkillSummary } from 'librechat-data-provider';
|
||||
import type { MentionOption } from '~/common';
|
||||
import { useLocalize, useSkillActiveState } from '~/hooks';
|
||||
|
|
@ -19,8 +13,6 @@ import { useAgentsMapContext } from '~/Providers';
|
|||
import { ephemeralAgentByConvoId } from '~/store';
|
||||
import { isEphemeralAgent } from '~/common';
|
||||
|
||||
const commandChar = '$';
|
||||
const ROW_HEIGHT = 44;
|
||||
const skillIcon = <ScrollText className="icon-md text-status-info" />;
|
||||
|
||||
/**
|
||||
|
|
@ -91,7 +83,6 @@ function SkillsCommandContent({
|
|||
agentId?: string | null;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const remScale = useRemScale();
|
||||
const setShowSkillsPopover = useSetAtom(showSkillsPopoverFamily(index));
|
||||
const setEphemeralAgent = useSetRecoilState(ephemeralAgentByConvoId(conversationId));
|
||||
const setPendingManualSkills = useSetAtom(pendingManualSkillsByConvoId(conversationId));
|
||||
|
|
@ -172,34 +163,8 @@ function SkillsCommandContent({
|
|||
return options;
|
||||
}, [data?.pages, agentSkillIds, isActive]);
|
||||
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({
|
||||
value: '',
|
||||
options: skillOptions,
|
||||
});
|
||||
|
||||
const initInputRef = useInitPopoverInput({
|
||||
inputRef,
|
||||
textAreaRef,
|
||||
commandChar,
|
||||
preserveTextAfterCursor: true,
|
||||
setSearchValue,
|
||||
setOpen,
|
||||
});
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(mention?: MentionOption) => {
|
||||
if (!mention) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSearchValue('');
|
||||
setOpen(false);
|
||||
setShowSkillsPopover(false);
|
||||
|
||||
(mention: { value: string }) => {
|
||||
setEphemeralAgent((prev) => {
|
||||
if (prev?.skills) {
|
||||
return prev;
|
||||
|
|
@ -217,161 +182,25 @@ function SkillsCommandContent({
|
|||
setPendingManualSkills((prev) =>
|
||||
prev.includes(mention.value) ? prev : [...prev, mention.value],
|
||||
);
|
||||
|
||||
textAreaRef.current?.focus();
|
||||
},
|
||||
[
|
||||
setSearchValue,
|
||||
setOpen,
|
||||
setShowSkillsPopover,
|
||||
textAreaRef,
|
||||
setEphemeralAgent,
|
||||
setPendingManualSkills,
|
||||
],
|
||||
[setEphemeralAgent, setPendingManualSkills],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setActiveIndex(0);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
setActiveIndex((prev) => Math.min(prev, Math.max(matches.length - 1, 0)));
|
||||
}, [matches.length]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = document.getElementById(`skill-item-${activeIndex}`);
|
||||
el?.scrollIntoView({ behavior: 'instant', block: 'nearest' });
|
||||
}, [activeIndex]);
|
||||
|
||||
const rowRenderer = ({
|
||||
index,
|
||||
key,
|
||||
style,
|
||||
}: {
|
||||
index: number;
|
||||
key: string;
|
||||
style: React.CSSProperties;
|
||||
}) => {
|
||||
const mention = matches[index] as MentionOption;
|
||||
return (
|
||||
<MentionItem
|
||||
index={index}
|
||||
type="skill"
|
||||
key={key}
|
||||
style={style}
|
||||
onClick={() => {
|
||||
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-tertiary-alt rounded-theme-popover border p-2 shadow-lg">
|
||||
<Input
|
||||
ref={initInputRef}
|
||||
placeholder={localize('com_ui_skills_command_placeholder')}
|
||||
variant="embedded"
|
||||
className="mb-1"
|
||||
autoComplete="off"
|
||||
value={searchValue}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') {
|
||||
setOpen(false);
|
||||
setShowSkillsPopover(false);
|
||||
textAreaRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
}
|
||||
setOpen(false);
|
||||
setShowSkillsPopover(false);
|
||||
textAreaRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
handleSelect(matches[activeIndex] as MentionOption | undefined);
|
||||
} else if (e.key === 'Backspace' && searchValue === '') {
|
||||
setOpen(false);
|
||||
setShowSkillsPopover(false);
|
||||
textAreaRef.current?.focus();
|
||||
}
|
||||
}}
|
||||
onChange={(e) => setSearchValue(e.target.value)}
|
||||
onFocus={() => setOpen(true)}
|
||||
onBlur={() => {
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
setOpen(false);
|
||||
setShowSkillsPopover(false);
|
||||
}, 150);
|
||||
}}
|
||||
/>
|
||||
{open && (isLoading || isFetchingNextPage) && matches.length === 0 && (
|
||||
<div className="text-text-primary flex h-32 items-center justify-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{open && isError && (
|
||||
<div className="text-text-secondary p-4 text-center text-sm">
|
||||
{localize('com_ui_skills_load_error')}
|
||||
</div>
|
||||
)}
|
||||
{open && !isLoading && !isFetchingNextPage && !isError && matches.length === 0 && (
|
||||
<div className="text-text-secondary p-4 text-center text-sm">
|
||||
{localize(searchValue ? 'com_ui_no_skills_found' : 'com_ui_skills_empty')}
|
||||
</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>
|
||||
<SkillsPopover
|
||||
textAreaRef={textAreaRef}
|
||||
placeholder={localize('com_ui_skills_command_placeholder')}
|
||||
skills={skillOptions}
|
||||
isLoading={isLoading || isFetchingNextPage}
|
||||
isError={isError}
|
||||
notices={{
|
||||
error: localize('com_ui_skills_load_error'),
|
||||
empty: localize('com_ui_skills_empty'),
|
||||
noMatch: localize('com_ui_no_skills_found'),
|
||||
}}
|
||||
onSelectSkill={handleSelect}
|
||||
onClose={() => setShowSkillsPopover(false)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -95,31 +95,6 @@ jest.mock('@librechat/client', () => {
|
|||
};
|
||||
});
|
||||
|
||||
/* react-virtualized renders nothing in jsdom without measured size; replace
|
||||
AutoSizer + List with a flat ul so row clicks are exercised normally. */
|
||||
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="skills-list">{rows}</ul>;
|
||||
},
|
||||
}));
|
||||
|
||||
import SkillsCommand, { filterSkillsForPopover } from '../SkillsCommand';
|
||||
|
||||
const makeTextarea = (initial = '$', selectionStart = initial.length) => {
|
||||
|
|
@ -207,7 +182,7 @@ describe('SkillsCommand', () => {
|
|||
expect(textAreaRef.current).toHaveValue('Keep this draft');
|
||||
expect(textAreaRef.current?.selectionStart).toBe(0);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Brand Guidelines/i }));
|
||||
await user.click(await screen.findByRole('option', { name: /Brand Guidelines/i }));
|
||||
|
||||
expect(textAreaRef.current).toHaveValue('Keep this draft');
|
||||
expect(document.activeElement).toBe(textAreaRef.current);
|
||||
|
|
@ -219,7 +194,7 @@ describe('SkillsCommand', () => {
|
|||
|
||||
render(<SkillsCommand index={0} textAreaRef={textAreaRef} conversationId={CONVO_ID} />);
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Brand Guidelines/i }));
|
||||
await user.click(await screen.findByRole('option', { name: /Brand Guidelines/i }));
|
||||
|
||||
expect(textAreaRef.current).toHaveValue('Keep this $');
|
||||
});
|
||||
|
|
@ -243,7 +218,7 @@ describe('SkillsCommand', () => {
|
|||
const textAreaRef = makeTextarea('$');
|
||||
render(<SkillsCommand index={0} textAreaRef={textAreaRef} conversationId={CONVO_ID} />);
|
||||
|
||||
const skillButton = await screen.findByRole('button', { name: /Brand Guidelines/i });
|
||||
const skillButton = await screen.findByRole('option', { name: /Brand Guidelines/i });
|
||||
await act(async () => {
|
||||
await user.click(skillButton);
|
||||
});
|
||||
|
|
@ -298,8 +273,8 @@ describe('SkillsCommand', () => {
|
|||
);
|
||||
|
||||
/* Only the skill whose _id is in agent.skills should appear. */
|
||||
expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(await screen.findByRole('button', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(await screen.findByRole('option', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows nothing when the agent has skills_enabled:false, regardless of allowlist', () => {
|
||||
|
|
@ -325,8 +300,8 @@ describe('SkillsCommand', () => {
|
|||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull();
|
||||
});
|
||||
|
||||
it('hides all skills for a persisted agent with skills_enabled undefined (default off)', async () => {
|
||||
|
|
@ -355,8 +330,8 @@ describe('SkillsCommand', () => {
|
|||
/* Mirrors backend `resolveAgentScopedSkillIds`: persisted agents are
|
||||
off by default; the builder's `skills_enabled` master toggle is
|
||||
the only signal that activates skills for the agent. */
|
||||
expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull();
|
||||
});
|
||||
|
||||
it('shows the full catalog for a persisted agent with skills_enabled:true and empty allowlist', async () => {
|
||||
|
|
@ -382,8 +357,8 @@ describe('SkillsCommand', () => {
|
|||
/>,
|
||||
);
|
||||
|
||||
expect(await screen.findByRole('button', { name: /Brand Guidelines/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
expect(await screen.findByRole('option', { name: /Brand Guidelines/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('option', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows no catalog entries for an enabled authoring-only agent', () => {
|
||||
|
|
@ -415,8 +390,8 @@ describe('SkillsCommand', () => {
|
|||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull();
|
||||
});
|
||||
|
||||
it('treats an ephemeral agent id as unscoped and shows the full ACL catalog', async () => {
|
||||
|
|
@ -442,8 +417,8 @@ describe('SkillsCommand', () => {
|
|||
|
||||
/* `ephemeral` doesn't start with `agent_`, so it's an ephemeral id;
|
||||
scope filter should be skipped and the full catalog displayed. */
|
||||
expect(await screen.findByRole('button', { name: /Brand Guidelines/i })).toBeInTheDocument();
|
||||
expect(await screen.findByRole('button', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
expect(await screen.findByRole('option', { name: /Brand Guidelines/i })).toBeInTheDocument();
|
||||
expect(await screen.findByRole('option', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('fails closed for persisted agents while the agents map is hydrating', async () => {
|
||||
|
|
@ -471,8 +446,8 @@ describe('SkillsCommand', () => {
|
|||
visibility we cannot prove the persisted agent opted in, so fail
|
||||
closed; otherwise the user can pick a skill the backend will then
|
||||
refuse for the turn. */
|
||||
expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull();
|
||||
});
|
||||
|
||||
it('fails closed when the agent id is set but missing from the agents map', () => {
|
||||
|
|
@ -496,8 +471,8 @@ describe('SkillsCommand', () => {
|
|||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Style Guide/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.queryByRole('option', { name: /Style Guide/i })).toBeNull();
|
||||
});
|
||||
|
||||
it('hides inactive skills from the popover', () => {
|
||||
|
|
@ -514,8 +489,8 @@ describe('SkillsCommand', () => {
|
|||
const textAreaRef = makeTextarea('$');
|
||||
render(<SkillsCommand index={0} textAreaRef={textAreaRef} conversationId={CONVO_ID} />);
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.getByRole('button', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('option', { name: /Brand Guidelines/i })).toBeNull();
|
||||
expect(screen.getByRole('option', { name: /Style Guide/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('resumes catalog pagination after an external refetch clears an error', () => {
|
||||
|
|
|
|||
136
e2e/specs/mock/scenarios/composer-skills.spec.ts
Normal file
136
e2e/specs/mock/scenarios/composer-skills.spec.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import type { Page } from '@playwright/test';
|
||||
import {
|
||||
MOCK_ENDPOINTS,
|
||||
NEW_CHAT_PATH,
|
||||
requestJson,
|
||||
sendMessage,
|
||||
getAccessToken,
|
||||
selectMockEndpoint,
|
||||
} from '../helpers';
|
||||
|
||||
/**
|
||||
* The `$` skills popover, drawn by the chat package's command popover: a combobox over the
|
||||
* user's skills whose pick stages the skill for the next turn instead of writing it into the
|
||||
* draft, and which says so when a search matches nothing.
|
||||
*/
|
||||
test.describe.configure({ timeout: 120_000 });
|
||||
|
||||
type SkillSummary = { _id: string; name: string };
|
||||
|
||||
const uniqueName = (prefix: string) =>
|
||||
`${prefix}-${Date.now().toString(36)}-${Math.floor(Math.random() * 1e4)}`;
|
||||
|
||||
async function createSkill(page: Page, name: string): Promise<string> {
|
||||
const token = await getAccessToken(page);
|
||||
const skill = await requestJson<SkillSummary>(page, {
|
||||
path: '/api/skills',
|
||||
token,
|
||||
method: 'POST',
|
||||
body: { name, description: `Composer popover skill ${name}`, body: `# ${name}\n\nE2E.` },
|
||||
});
|
||||
expect(skill._id).toBeTruthy();
|
||||
return skill._id;
|
||||
}
|
||||
|
||||
async function deleteSkill(page: Page, id: string) {
|
||||
const token = await getAccessToken(page);
|
||||
await requestJson<unknown>(page, {
|
||||
path: `/api/skills/${encodeURIComponent(id)}`,
|
||||
token,
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
async function withSkills(page: Page, names: string[], run: () => Promise<void>) {
|
||||
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
|
||||
const ids: string[] = [];
|
||||
try {
|
||||
for (const name of names) {
|
||||
ids.push(await createSkill(page, name));
|
||||
}
|
||||
await page.reload();
|
||||
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
|
||||
await run();
|
||||
} finally {
|
||||
for (const id of ids) {
|
||||
await deleteSkill(page, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function openSkills(page: Page) {
|
||||
const textarea = page.getByRole('textbox', { name: 'Message input' });
|
||||
await textarea.click();
|
||||
await textarea.fill('');
|
||||
await textarea.pressSequentially('$');
|
||||
const combobox = page.getByRole('combobox', { name: /Select a Skill/ });
|
||||
await expect(combobox).toBeFocused();
|
||||
return { textarea, combobox };
|
||||
}
|
||||
|
||||
test.describe('skills popover', () => {
|
||||
test('keyboard moves and announces the active skill @scenario:skills-popover-keyboard-combobox', async ({
|
||||
page,
|
||||
}) => {
|
||||
const prefix = uniqueName('e2e-kbd');
|
||||
await withSkills(page, [`${prefix}-a`, `${prefix}-b`], async () => {
|
||||
const { textarea, combobox } = await openSkills(page);
|
||||
await combobox.fill(prefix);
|
||||
await expect(page.getByRole('option')).toHaveCount(2);
|
||||
await expect(combobox).toHaveAttribute('aria-activedescendant', 'skill-item-0');
|
||||
|
||||
await combobox.press('ArrowDown');
|
||||
await expect(combobox).toHaveAttribute('aria-activedescendant', 'skill-item-1');
|
||||
await expect(page.locator('[id="skill-item-1"]')).toHaveAttribute('aria-selected', 'true');
|
||||
|
||||
await combobox.press('Escape');
|
||||
await expect(page.getByRole('combobox', { name: /Select a Skill/ })).toHaveCount(0);
|
||||
await expect(textarea).toBeFocused();
|
||||
});
|
||||
});
|
||||
|
||||
test('a pick stages the skill for the next turn @scenario:skills-popover-stages-skill', async ({
|
||||
page,
|
||||
}) => {
|
||||
const name = uniqueName('e2e-stage');
|
||||
await withSkills(page, [name], async () => {
|
||||
const { textarea, combobox } = await openSkills(page);
|
||||
await combobox.fill(name);
|
||||
await expect(page.getByRole('option', { name: new RegExp(name) })).toBeVisible();
|
||||
await combobox.press('Enter');
|
||||
|
||||
await expect(page.getByRole('combobox', { name: /Select a Skill/ })).toHaveCount(0);
|
||||
await expect(textarea).toBeFocused();
|
||||
await expect(textarea).toHaveValue('');
|
||||
await expect(
|
||||
page
|
||||
.getByTestId('composer-tray')
|
||||
.getByTestId('composer-chip-skill')
|
||||
.filter({ hasText: name }),
|
||||
).toBeVisible();
|
||||
|
||||
const response = await sendMessage(page, 'Use the staged skill');
|
||||
expect(response.ok()).toBeTruthy();
|
||||
expect(
|
||||
(response.request().postDataJSON() as { manualSkills?: string[] }).manualSkills,
|
||||
).toEqual([name]);
|
||||
});
|
||||
});
|
||||
|
||||
test('a search that matches nothing says so and Enter closes @scenario:skills-popover-no-match-notice', async ({
|
||||
page,
|
||||
}) => {
|
||||
await withSkills(page, [uniqueName('e2e-none')], async () => {
|
||||
const { textarea, combobox } = await openSkills(page);
|
||||
await combobox.fill('zzzz-no-such-skill');
|
||||
|
||||
await expect(page.getByRole('status').filter({ hasText: 'No skills found' })).toBeVisible();
|
||||
await expect(combobox).toHaveAttribute('aria-expanded', 'false');
|
||||
await combobox.press('Enter');
|
||||
|
||||
await expect(page.getByRole('combobox', { name: /Select a Skill/ })).toHaveCount(0);
|
||||
await expect(textarea).toBeFocused();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -21,6 +21,7 @@ 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 SkillsPopover } from './components/composer/popover/Skills';
|
||||
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';
|
||||
|
|
@ -38,6 +39,10 @@ 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 {
|
||||
SkillsPopoverProps,
|
||||
SkillsPopoverNotices,
|
||||
} from './components/composer/popover/Skills';
|
||||
export type {
|
||||
CommandOption,
|
||||
CommandPopoverProps,
|
||||
|
|
|
|||
|
|
@ -35,6 +35,8 @@ export interface CommandPopoverProps {
|
|||
activeIndex: number;
|
||||
onActiveIndexChange: Dispatch<SetStateAction<number>>;
|
||||
isLoading?: boolean;
|
||||
/** A message shown under the search field while open, such as an empty or failed list. */
|
||||
notice?: ReactNode;
|
||||
/** 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. */
|
||||
|
|
@ -67,6 +69,7 @@ export default function CommandPopover({
|
|||
activeIndex,
|
||||
onActiveIndexChange,
|
||||
isLoading = false,
|
||||
notice,
|
||||
onSelect,
|
||||
onDismiss,
|
||||
}: CommandPopoverProps): React.JSX.Element {
|
||||
|
|
@ -183,6 +186,11 @@ export default function CommandPopover({
|
|||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{open && notice != null && (
|
||||
<div role="status" className="text-text-secondary p-4 text-center text-sm">
|
||||
{notice}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={listRef}
|
||||
id={listboxId}
|
||||
|
|
|
|||
118
packages/chat/src/components/composer/popover/Skills.tsx
Normal file
118
packages/chat/src/components/composer/popover/Skills.tsx
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useCombobox } from '@librechat/client';
|
||||
import type { KeyboardEvent, MutableRefObject } from 'react';
|
||||
import type { CommandOption, CommandDismissReason } from './Command';
|
||||
import useInitPopoverInput from '../../../react/popover';
|
||||
import CommandPopover from './Command';
|
||||
|
||||
const COMMAND_CHAR = '$';
|
||||
|
||||
/** Localized messages the skills popover shows in place of a list. */
|
||||
export interface SkillsPopoverNotices {
|
||||
/** The skills failed to load. */
|
||||
error: string;
|
||||
/** The user has no skills to offer here. */
|
||||
empty: string;
|
||||
/** The search matched none of them. */
|
||||
noMatch: string;
|
||||
}
|
||||
|
||||
export interface SkillsPopoverProps {
|
||||
textAreaRef: MutableRefObject<HTMLTextAreaElement | null>;
|
||||
/** Localized placeholder for the search field. */
|
||||
placeholder: string;
|
||||
skills: CommandOption[];
|
||||
/** True while any page of the catalog is still loading. */
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
notices: SkillsPopoverNotices;
|
||||
/** A skill was picked; the popover has already closed and the draft keeps its text. */
|
||||
onSelectSkill: (skill: CommandOption) => void;
|
||||
/** Hides the popover. */
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** The `$` popover: picks a skill to invoke on the next turn. Text typed after the `$` stays in
|
||||
* the draft, and the pick is handed to the host rather than written into the text. */
|
||||
export default function SkillsPopover({
|
||||
textAreaRef,
|
||||
placeholder,
|
||||
skills,
|
||||
isLoading,
|
||||
isError,
|
||||
notices,
|
||||
onSelectSkill,
|
||||
onClose,
|
||||
}: SkillsPopoverProps): React.JSX.Element {
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
const { open, setOpen, searchValue, setSearchValue, matches } = useCombobox({
|
||||
value: '',
|
||||
options: skills,
|
||||
});
|
||||
|
||||
const initInputRef = useInitPopoverInput({
|
||||
inputRef,
|
||||
textAreaRef,
|
||||
commandChar: COMMAND_CHAR,
|
||||
preserveTextAfterCursor: true,
|
||||
setSearchValue,
|
||||
setOpen,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setActiveIndex(0);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const handleSelect = (skill: CommandOption, e?: KeyboardEvent<HTMLInputElement>) => {
|
||||
e?.preventDefault();
|
||||
setSearchValue('');
|
||||
setOpen(false);
|
||||
onClose();
|
||||
onSelectSkill(skill);
|
||||
textAreaRef.current?.focus();
|
||||
};
|
||||
|
||||
const handleDismiss = (reason: CommandDismissReason, e?: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (reason === 'commit' && e?.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
}
|
||||
setOpen(false);
|
||||
onClose();
|
||||
if (reason !== 'blur') {
|
||||
textAreaRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const notice = (() => {
|
||||
if (isError) {
|
||||
return notices.error;
|
||||
}
|
||||
if (isLoading || matches.length > 0) {
|
||||
return undefined;
|
||||
}
|
||||
return searchValue ? notices.noMatch : notices.empty;
|
||||
})();
|
||||
|
||||
return (
|
||||
<CommandPopover
|
||||
type="skill"
|
||||
placeholder={placeholder}
|
||||
inputRef={initInputRef}
|
||||
searchValue={searchValue}
|
||||
onSearchChange={setSearchValue}
|
||||
open={open}
|
||||
onOpen={() => setOpen(true)}
|
||||
matches={matches as CommandOption[]}
|
||||
activeIndex={activeIndex}
|
||||
onActiveIndexChange={setActiveIndex}
|
||||
isLoading={isLoading}
|
||||
notice={notice}
|
||||
onSelect={handleSelect}
|
||||
onDismiss={handleDismiss}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,101 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { SkillsPopoverProps } from '../Skills';
|
||||
import type { CommandOption } from '../Command';
|
||||
import SkillsPopover from '../Skills';
|
||||
|
||||
/**
|
||||
* The `$` popover's contract: text after the `$` stays in the draft, a pick goes to the host and
|
||||
* never into the text, Enter and Tab on a skill are consumed, and an empty, unmatched or failed
|
||||
* list says so in a status message.
|
||||
*/
|
||||
|
||||
const skills: CommandOption[] = [
|
||||
{ type: 'skill', value: 'brand-guidelines', label: 'Brand Guidelines' },
|
||||
{ type: 'skill', value: 'style-guide', label: 'Style Guide' },
|
||||
];
|
||||
|
||||
const notices = { error: 'Load failed', empty: 'No skills yet', noMatch: 'No match' };
|
||||
|
||||
beforeAll(() => {
|
||||
Element.prototype.scrollIntoView = jest.fn();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
const renderSkills = (props: Partial<SkillsPopoverProps> = {}, draft = '$') => {
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = draft;
|
||||
document.body.appendChild(textarea);
|
||||
textarea.setSelectionRange(1, 1);
|
||||
const onClose = jest.fn();
|
||||
const onSelectSkill = jest.fn();
|
||||
render(
|
||||
<SkillsPopover
|
||||
textAreaRef={{ current: textarea }}
|
||||
placeholder="Skills"
|
||||
skills={skills}
|
||||
isLoading={false}
|
||||
isError={false}
|
||||
notices={notices}
|
||||
onClose={onClose}
|
||||
onSelectSkill={onSelectSkill}
|
||||
{...props}
|
||||
/>,
|
||||
);
|
||||
return { textarea, onClose, onSelectSkill };
|
||||
};
|
||||
|
||||
const input = () => screen.getByRole('combobox');
|
||||
|
||||
describe('SkillsPopover', () => {
|
||||
it('keeps the text after the cursor in the draft and hands the pick to the host', () => {
|
||||
const { textarea, onClose, onSelectSkill } = renderSkills({}, '$ please review');
|
||||
|
||||
expect(textarea.value).toBe(' please review');
|
||||
fireEvent.keyDown(input(), { key: 'ArrowDown' });
|
||||
expect(fireEvent.keyDown(input(), { key: 'Tab' })).toBe(false);
|
||||
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
expect(onSelectSkill).toHaveBeenCalledWith(skills[1]);
|
||||
expect(textarea.value).toBe(' please review');
|
||||
expect(document.activeElement).toBe(textarea);
|
||||
});
|
||||
|
||||
it('lets Tab move on but consumes Enter when nothing matches', () => {
|
||||
renderSkills();
|
||||
fireEvent.change(input(), { target: { value: 'zzz' } });
|
||||
|
||||
expect(screen.getByRole('status')).toHaveTextContent('No match');
|
||||
expect(fireEvent.keyDown(input(), { key: 'Tab' })).toBe(true);
|
||||
});
|
||||
|
||||
it('consumes Enter when nothing matches and closes', () => {
|
||||
const { onClose } = renderSkills();
|
||||
fireEvent.change(input(), { target: { value: 'zzz' } });
|
||||
|
||||
expect(fireEvent.keyDown(input(), { key: 'Enter' })).toBe(false);
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('says when there are no skills', () => {
|
||||
renderSkills({ skills: [] });
|
||||
expect(screen.getByRole('status')).toHaveTextContent('No skills yet');
|
||||
});
|
||||
|
||||
it('says when the skills failed to load, keeping any already listed', () => {
|
||||
renderSkills({ isError: true });
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Load failed');
|
||||
expect(screen.getAllByRole('option')).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('shows no notice while the catalog is still loading', () => {
|
||||
renderSkills({ skills: [], isLoading: true });
|
||||
expect(screen.queryByRole('status')).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue