mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-21 15:33:45 +00:00
🧭 feat: Palette Show All Catalogs, MCP Status and Composer Polish (#16422)
This commit is contained in:
parent
66a6e638f7
commit
f1d8d8ae9c
24 changed files with 2154 additions and 362 deletions
|
|
@ -554,6 +554,9 @@ const ChatForm = memo(function ChatForm({
|
|||
speechToText: SpeechToText,
|
||||
index,
|
||||
});
|
||||
/** The waveform stands in for the placeholder until words arrive, and is
|
||||
* then the only thing drawn on that line. */
|
||||
const listening = dictation.active && (textValue?.trim() ?? '') === '';
|
||||
const uploadingCount = useMemo(() => {
|
||||
let count = 0;
|
||||
for (const file of files.values()) {
|
||||
|
|
@ -843,7 +846,11 @@ const ChatForm = memo(function ChatForm({
|
|||
{endpoint && (
|
||||
<div className={cn('flex', isRTL ? 'flex-row-reverse' : 'flex-row')}>
|
||||
<div
|
||||
className="relative flex-1"
|
||||
className={cn(
|
||||
'relative flex-1',
|
||||
listening &&
|
||||
'[&_textarea]:caret-transparent [&_textarea]:placeholder:text-transparent',
|
||||
)}
|
||||
style={
|
||||
isCollapsed
|
||||
? {
|
||||
|
|
@ -895,14 +902,14 @@ const ChatForm = memo(function ChatForm({
|
|||
'scrollbar-hover transition-[max-height] duration-200 disabled:cursor-not-allowed',
|
||||
)}
|
||||
/>
|
||||
{dictation.active && (textValue?.trim() ?? '') === '' && (
|
||||
{listening && (
|
||||
/* Stands in for the placeholder: same inset, same line, so
|
||||
it reads as the input listening rather than as a widget
|
||||
bolted on. Once words arrive the transcript takes over. */
|
||||
<Waveform
|
||||
active={dictation.active}
|
||||
className={cn(
|
||||
'pointer-events-none absolute inset-y-0 h-full',
|
||||
'pointer-events-none absolute inset-y-2',
|
||||
isMoreThanThreeRows ? 'right-2 left-5' : 'inset-x-5',
|
||||
)}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import React, { memo, useMemo, useState, useCallback } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { Mic, Plus, Check, Square, ChevronDown } from 'lucide-react';
|
||||
import { MCPIcon, IconButton, TooltipAnchor, SendIcon } from '@librechat/client';
|
||||
import { IconButton, TooltipAnchor, SendIcon } from '@librechat/client';
|
||||
import type { TConversation, EModelEndpoint, EndpointFileConfig } from 'librechat-data-provider';
|
||||
import type { PaletteEntry, PaletteMode } from '~/hooks/Input/usePaletteEntries';
|
||||
import type { Dictation } from '~/hooks/Input/useDictation';
|
||||
|
|
@ -24,14 +24,6 @@ const EMPTY_ENTRIES: PaletteEntry[] = [];
|
|||
|
||||
/** Matches the rows' `gap-1.5`, which the split arithmetic has to account for. */
|
||||
const CHIP_GAP = 6;
|
||||
/**
|
||||
* Key of the aggregate MCP menu chip. Server rows are keyed `mcp:${serverName}`
|
||||
* (`usePaletteEntries`), so this cannot live in that namespace: a server named
|
||||
* `pinned` would produce the same key, and the bar would render two entries
|
||||
* with one React key and one packing-width slot.
|
||||
*/
|
||||
export const PINNED_MCP_KEY = 'aggregate:mcp';
|
||||
|
||||
/**
|
||||
* Whether every chip fits on the button row beside the `+` and the controls.
|
||||
*
|
||||
|
|
@ -78,35 +70,8 @@ export function chipMenuModes(modes?: PaletteMode[]) {
|
|||
}
|
||||
|
||||
/** Projects palette state into the persistent quick controls in one pass. */
|
||||
export function projectBarEntries(
|
||||
entries: PaletteEntry[],
|
||||
pinnedMcpEntry?: PaletteEntry,
|
||||
): PaletteEntry[] {
|
||||
const projected: PaletteEntry[] = [];
|
||||
const mcpModes: PaletteMode[] = [];
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.section === 'skill') {
|
||||
continue;
|
||||
}
|
||||
if (entry.section === 'mcp') {
|
||||
mcpModes.push({
|
||||
id: entry.itemId,
|
||||
label: entry.label,
|
||||
active: entry.active,
|
||||
onSelect: entry.onSelect,
|
||||
});
|
||||
}
|
||||
if (entry.active || entry.pinned) {
|
||||
projected.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
if (pinnedMcpEntry != null && mcpModes.length > 0) {
|
||||
projected.push({ ...pinnedMcpEntry, modes: mcpModes });
|
||||
}
|
||||
|
||||
return projected;
|
||||
export function projectBarEntries(entries: PaletteEntry[]): PaletteEntry[] {
|
||||
return entries.filter((entry) => entry.section !== 'skill' && (entry.active || entry.pinned));
|
||||
}
|
||||
|
||||
interface RoundButtonProps {
|
||||
|
|
@ -160,10 +125,9 @@ function RoundButton({
|
|||
*/
|
||||
interface ChipModesProps {
|
||||
modes: PaletteMode[];
|
||||
menuLabel?: string;
|
||||
}
|
||||
|
||||
export function ChipModes({ modes, menuLabel }: ChipModesProps) {
|
||||
export function ChipModes({ modes }: ChipModesProps) {
|
||||
const localize = useLocalize();
|
||||
const [open, setOpen] = useState(false);
|
||||
const active = modes.find((mode) => mode.active);
|
||||
|
|
@ -174,7 +138,7 @@ export function ChipModes({ modes, menuLabel }: ChipModesProps) {
|
|||
aria-label={
|
||||
active != null
|
||||
? localize('com_ui_mode_value', { 0: active.label })
|
||||
: (menuLabel ?? localize('com_ui_mode'))
|
||||
: localize('com_ui_mode')
|
||||
}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="text-text-secondary hover:bg-surface-tertiary hover:text-text-primary focus-visible:ring-border-xheavy -mr-0.5 flex shrink-0 items-center gap-0.5 rounded px-1 text-xs transition-colors focus-visible:ring-2 focus-visible:outline-hidden"
|
||||
|
|
@ -305,33 +269,10 @@ function Bar({
|
|||
gate lives in one place rather than being re-applied to its result here. */
|
||||
const entries = allEntries;
|
||||
|
||||
const manager = context?.mcpServerManager;
|
||||
const pinnedMcpEntry = useMemo<PaletteEntry | undefined>(() => {
|
||||
if (manager?.isPinned !== true) {
|
||||
return undefined;
|
||||
}
|
||||
const { placeholderText, setIsPinned } = manager;
|
||||
return {
|
||||
key: PINNED_MCP_KEY,
|
||||
itemType: 'mcp',
|
||||
itemId: 'mcp',
|
||||
label: placeholderText || localize('com_ui_mcp_servers'),
|
||||
icon: <MCPIcon className="h-4 w-4" aria-hidden="true" />,
|
||||
section: 'mcp',
|
||||
active: true,
|
||||
pinned: true,
|
||||
onSelect: () => setIsPinned(false),
|
||||
};
|
||||
}, [manager, localize]);
|
||||
|
||||
/* Catalog skills are excluded: a picked skill is staged context for the next
|
||||
turn, so it belongs in the tray above the textarea with files and quotes.
|
||||
Built-in tool pins remain visible while off. The legacy aggregate MCP pin
|
||||
remains one server menu alongside any selected server chips. */
|
||||
const barEntries = useMemo(
|
||||
() => projectBarEntries(entries, pinnedMcpEntry),
|
||||
[entries, pinnedMcpEntry],
|
||||
);
|
||||
Built-in tool pins remain visible while off. */
|
||||
const barEntries = useMemo(() => projectBarEntries(entries), [entries]);
|
||||
/* Catalog order puts long skill and MCP names mid-row, stranding the rest of
|
||||
that row; packing widest-first fills the rows instead. */
|
||||
const { ordered: packedEntries, rootRef, widths } = useChipPacking(barEntries);
|
||||
|
|
@ -382,12 +323,8 @@ function Bar({
|
|||
|
||||
const renderChip = (entry: PaletteEntry) => {
|
||||
const pinnedInactive = entry.pinned && !entry.active;
|
||||
const isPinnedMcp = entry.key === PINNED_MCP_KEY;
|
||||
const menuModes = chipMenuModes(entry.modes);
|
||||
const modeMenu =
|
||||
menuModes.length > 0 ? (
|
||||
<ChipModes modes={menuModes} menuLabel={isPinnedMcp ? entry.label : undefined} />
|
||||
) : null;
|
||||
const modeMenu = menuModes.length > 0 ? <ChipModes modes={menuModes} /> : null;
|
||||
const activate = pinnedInactive ? (
|
||||
<IconButton
|
||||
label={localize('com_ui_select_var', { 0: entry.label })}
|
||||
|
|
@ -417,7 +354,7 @@ function Bar({
|
|||
}
|
||||
onRemove={pinnedInactive ? entry.onUnpin : entry.onSelect}
|
||||
removeLabel={
|
||||
isPinnedMcp || pinnedInactive
|
||||
pinnedInactive
|
||||
? localize('com_ui_unpin')
|
||||
: localize('com_ui_remove_var', { 0: entry.label })
|
||||
}
|
||||
|
|
|
|||
269
client/src/components/Chat/Input/Composer/Catalog.tsx
Normal file
269
client/src/components/Chat/Input/Composer/Catalog.tsx
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
import React, { useRef, useMemo, useState, useEffect } from 'react';
|
||||
import {
|
||||
Input,
|
||||
Label,
|
||||
Radio,
|
||||
OGDialog,
|
||||
OGDialogTitle,
|
||||
OGDialogContent,
|
||||
OGDialogDescription,
|
||||
} from '@librechat/client';
|
||||
import type { TFile } from 'librechat-data-provider';
|
||||
import type { AgentItem, ItemFilter } from '~/components/SidePanel/Agents/Tools/items/types';
|
||||
import type { PaletteEntry } from '~/hooks/Input/usePaletteEntries';
|
||||
import type { TranslationKeys } from '~/hooks';
|
||||
import type { FileView } from './Files';
|
||||
import MarketplaceCatalog from '~/components/SidePanel/Agents/Tools/MarketplaceCatalog';
|
||||
import { matchesView } from '~/components/SidePanel/Agents/Tools/items/filtering';
|
||||
import { itemKey } from '~/components/SidePanel/Agents/Tools/items/selectors';
|
||||
import { useLocalize, useToolFavorites } from '~/hooks';
|
||||
import FileGrid, { FILE_VIEWS } from './Files';
|
||||
|
||||
export type CatalogSection = 'skill' | 'mcp' | 'files';
|
||||
|
||||
type View = NonNullable<ItemFilter['view']>;
|
||||
|
||||
/** The agent builder's Skills dialog views, in the same order and wording. */
|
||||
const VIEWS: Array<{ value: View; labelKey: TranslationKeys }> = [
|
||||
{ value: 'marketplace', labelKey: 'com_ui_all_proper' },
|
||||
{ value: 'mine', labelKey: 'com_ui_tools_view_made_by_you' },
|
||||
{ value: 'favorites', labelKey: 'com_ui_tools_view_favorites' },
|
||||
];
|
||||
|
||||
const TITLE: Record<CatalogSection, TranslationKeys> = {
|
||||
skill: 'com_ui_skills',
|
||||
mcp: 'com_ui_mcp_servers',
|
||||
files: 'com_ui_composer_files',
|
||||
};
|
||||
|
||||
const SEARCH: Record<CatalogSection, TranslationKeys> = {
|
||||
skill: 'com_ui_composer_search_skills',
|
||||
mcp: 'com_ui_composer_search_mcp',
|
||||
files: 'com_ui_composer_search_files',
|
||||
};
|
||||
|
||||
const FILTER: Record<CatalogSection, TranslationKeys> = {
|
||||
skill: 'com_ui_skills_filter',
|
||||
mcp: 'com_ui_composer_mcp_filter',
|
||||
files: 'com_ui_composer_files_filter',
|
||||
};
|
||||
|
||||
/** The palette row as the agent builder's card expects it. Rows without a
|
||||
* catalog record (a skill staged by name before the catalog loaded) have no
|
||||
* card to show and are left to the chip in the bar. */
|
||||
function toItem(entry: PaletteEntry): AgentItem | null {
|
||||
if (entry.section === 'skill') {
|
||||
if (entry.skill == null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: 'skill',
|
||||
id: entry.itemId,
|
||||
name: entry.label,
|
||||
description: entry.description ?? '',
|
||||
iconKey: 'skill',
|
||||
skill: entry.skill,
|
||||
ownedByUser: entry.ownedByUser,
|
||||
};
|
||||
}
|
||||
if (entry.section === 'mcp') {
|
||||
return {
|
||||
kind: 'mcp',
|
||||
id: entry.itemId,
|
||||
name: entry.label,
|
||||
description: entry.description ?? '',
|
||||
iconKey: 'mcp',
|
||||
ownedByUser: entry.ownedByUser,
|
||||
toolCount: 0,
|
||||
server: {
|
||||
serverName: entry.itemId,
|
||||
tools: [],
|
||||
isConfigured: true,
|
||||
isConnected: true,
|
||||
metadata: { name: entry.label, pluginKey: entry.itemId, icon: entry.iconUrl },
|
||||
},
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const matches = (query: string, ...fields: Array<string | undefined>) =>
|
||||
query === '' || fields.some((field) => field?.toLowerCase().includes(query) === true);
|
||||
|
||||
function EntryGrid({
|
||||
section,
|
||||
entries,
|
||||
query,
|
||||
view,
|
||||
}: {
|
||||
section: 'skill' | 'mcp';
|
||||
entries: PaletteEntry[];
|
||||
query: string;
|
||||
view: View;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const { favoriteKeys, toggle } = useToolFavorites();
|
||||
|
||||
const { items, selectedIds, byKey } = useMemo(() => {
|
||||
const nextItems: AgentItem[] = [];
|
||||
const selected = new Set<string>();
|
||||
const keyed = new Map<string, PaletteEntry>();
|
||||
for (const entry of entries) {
|
||||
if (entry.section !== section || !matches(query, entry.label, entry.description)) {
|
||||
continue;
|
||||
}
|
||||
const item = toItem(entry);
|
||||
if (item == null || !matchesView(item, view, { favoritedIds: favoriteKeys })) {
|
||||
continue;
|
||||
}
|
||||
const key = itemKey(item);
|
||||
nextItems.push(item);
|
||||
keyed.set(key, entry);
|
||||
if (entry.active) {
|
||||
selected.add(key);
|
||||
}
|
||||
}
|
||||
return { items: nextItems, selectedIds: selected, byKey: keyed };
|
||||
}, [entries, section, query, view, favoriteKeys]);
|
||||
|
||||
return (
|
||||
<MarketplaceCatalog
|
||||
items={items}
|
||||
selectedIds={selectedIds}
|
||||
onToggle={(item) => byKey.get(itemKey(item))?.onSelect()}
|
||||
view={view}
|
||||
statusFor={(item) => byKey.get(itemKey(item))?.status}
|
||||
favoriteKeys={favoriteKeys}
|
||||
onToggleFavorite={toggle}
|
||||
emptyKey={view === 'marketplace' || query !== '' ? 'com_ui_composer_no_results' : undefined}
|
||||
ariaLabel={localize(TITLE[section])}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface CatalogProps {
|
||||
section: CatalogSection | null;
|
||||
onClose: () => void;
|
||||
entries: PaletteEntry[];
|
||||
onAttach: (file: TFile) => void;
|
||||
/** Where focus returns on close: the palette that opened this is gone. */
|
||||
returnFocusRef: React.RefObject<HTMLElement | null>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything behind a palette section's "Show all": the palette keeps a short
|
||||
* list per section, and this is where the rest of it lives. Skills and MCP
|
||||
* servers reuse the agent builder's card grid, toggled through the same
|
||||
* handlers as the palette rows so the two cannot disagree.
|
||||
*/
|
||||
export default function Catalog({
|
||||
section,
|
||||
onClose,
|
||||
entries,
|
||||
onAttach,
|
||||
returnFocusRef,
|
||||
}: CatalogProps) {
|
||||
const localize = useLocalize();
|
||||
const [search, setSearch] = useState('');
|
||||
const [view, setView] = useState<View>('marketplace');
|
||||
const [fileView, setFileView] = useState<FileView>('all');
|
||||
const [shown, setShown] = useState(section);
|
||||
if (section !== shown) {
|
||||
setShown(section);
|
||||
if (section != null) {
|
||||
setSearch('');
|
||||
setView('marketplace');
|
||||
setFileView('all');
|
||||
}
|
||||
}
|
||||
const current = section ?? shown;
|
||||
const viewOptions = useMemo(
|
||||
() =>
|
||||
(current === 'files' ? FILE_VIEWS : VIEWS).map((option) => ({
|
||||
value: option.value,
|
||||
label: localize(option.labelKey),
|
||||
})),
|
||||
[current, localize],
|
||||
);
|
||||
const query = search.trim().toLowerCase();
|
||||
|
||||
/* Focus goes back to the message field only after a mouse or keyboard close:
|
||||
after a tap it would summon the on-screen keyboard the user just left, the
|
||||
same rule the palette applies to its own close. */
|
||||
const focusTargetRef = useRef<HTMLElement | null>(null);
|
||||
useEffect(() => {
|
||||
if (section == null) {
|
||||
return;
|
||||
}
|
||||
const aim = (touch: boolean) => {
|
||||
focusTargetRef.current = touch ? null : returnFocusRef.current;
|
||||
};
|
||||
aim(window.matchMedia('(pointer: coarse)').matches);
|
||||
const onPointer = (event: PointerEvent) => aim(event.pointerType !== 'mouse');
|
||||
const onKey = () => aim(false);
|
||||
window.addEventListener('pointerdown', onPointer, true);
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
return () => {
|
||||
window.removeEventListener('pointerdown', onPointer, true);
|
||||
window.removeEventListener('keydown', onKey, true);
|
||||
};
|
||||
}, [section, returnFocusRef]);
|
||||
|
||||
return (
|
||||
<OGDialog
|
||||
open={section != null}
|
||||
triggerRef={focusTargetRef}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{current != null && (
|
||||
<OGDialogContent className="flex h-[80vh] max-h-[720px] w-11/12 max-w-[960px] flex-col overflow-hidden">
|
||||
<div className="flex h-full min-h-0 min-w-0 flex-col gap-3">
|
||||
<OGDialogTitle>{localize(TITLE[current])}</OGDialogTitle>
|
||||
<OGDialogDescription className="sr-only">
|
||||
{localize(SEARCH[current])}
|
||||
</OGDialogDescription>
|
||||
{/* Reaches into the dialog's right padding so the scrollbar sits at the
|
||||
edge, and pads the content back so the cards keep their inset. The
|
||||
controls ride inside it as a sticky header, so they share the cards'
|
||||
exact width whether the scrollbar takes space or overlays; the small
|
||||
left inset keeps the search field's focus ring from being clipped. */}
|
||||
<div className="-mr-5 -ml-1 min-h-0 flex-1 overflow-y-auto pr-5 pl-1">
|
||||
<div className="bg-surface-dialog sticky top-0 z-10 flex flex-wrap items-center gap-2 pt-1 pb-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<Input
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
placeholder={localize(SEARCH[current])}
|
||||
aria-label={localize(SEARCH[current])}
|
||||
/>
|
||||
</div>
|
||||
<Label id="composer-catalog-view-label" className="sr-only">
|
||||
{localize(FILTER[current])}
|
||||
</Label>
|
||||
<Radio
|
||||
wrap
|
||||
options={viewOptions}
|
||||
value={current === 'files' ? fileView : view}
|
||||
onChange={(value) =>
|
||||
current === 'files' ? setFileView(value as FileView) : setView(value as View)
|
||||
}
|
||||
aria-labelledby="composer-catalog-view-label"
|
||||
/>
|
||||
</div>
|
||||
{current === 'files' ? (
|
||||
<FileGrid query={query} view={fileView} onAttach={onAttach} />
|
||||
) : (
|
||||
<EntryGrid section={current} entries={entries} query={query} view={view} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</OGDialogContent>
|
||||
)}
|
||||
</OGDialog>
|
||||
);
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import type { SettingDefinition, TConversation, TReasoningOverride } from 'libre
|
|||
import type { CSSProperties } from 'react';
|
||||
import type { LocalizeFunction } from '~/common';
|
||||
import type { TranslationKeys } from '~/hooks';
|
||||
import useReducedMotion from '~/hooks/Generic/useReducedMotion';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
|
|
@ -28,6 +29,16 @@ const TRACK_H = 24;
|
|||
* row is sized to the largest it can get and the rail is banded inside it. */
|
||||
const THUMB = 28;
|
||||
const THUMB_ACTIVE = 32;
|
||||
/** How far, in px, the held thumb can lean toward the pointer before the
|
||||
* gesture commits to the next stop. The lean approaches this and never
|
||||
* reaches it, so pulling harder only ever tightens. */
|
||||
const MAX_LEAN = 10;
|
||||
/** How quickly the lean stiffens; the constant iOS uses for rubber banding. */
|
||||
const LEAN_STIFFNESS = 0.55;
|
||||
/** Stretch along the pull and the matching squash across it, at full lean. */
|
||||
const LEAN_STRETCH = 0.16;
|
||||
const LEAN_SQUASH = 0.08;
|
||||
|
||||
/** Which way each arrow key moves along the track. */
|
||||
const ARROW_STEP: Record<string, number | undefined> = {
|
||||
ArrowLeft: -1,
|
||||
|
|
@ -41,6 +52,27 @@ const ARROW_STEP: Record<string, number | undefined> = {
|
|||
* rendering it directly is what leaks `com_ui_medium` into the UI. Shared with
|
||||
* the trigger button, which is the only place the level is named.
|
||||
*/
|
||||
/**
|
||||
* Where a value sits on the effort scale, for telling whether a change went up
|
||||
* or down. The separate mode ranks below every level.
|
||||
*/
|
||||
export function effortRank(setting: SettingDefinition, value: string | undefined): number {
|
||||
if (value == null || UNGRADED_VALUES.has(value)) {
|
||||
return -1;
|
||||
}
|
||||
return (setting.options ?? [])
|
||||
.map(String)
|
||||
.filter((option) => !UNGRADED_VALUES.has(option))
|
||||
.indexOf(value);
|
||||
}
|
||||
|
||||
/** Rubber-band resistance: tracks the pointer closely at first and stiffens
|
||||
* toward `MAX_LEAN`, the curve iOS uses at the end of a scroll view. */
|
||||
export function leanFor(distance: number): number {
|
||||
const magnitude = MAX_LEAN * (1 - 1 / ((Math.abs(distance) * LEAN_STIFFNESS) / MAX_LEAN + 1));
|
||||
return Math.sign(distance) * magnitude;
|
||||
}
|
||||
|
||||
export function resolveEffortLabel(
|
||||
setting: SettingDefinition,
|
||||
value: string,
|
||||
|
|
@ -87,6 +119,7 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {
|
|||
/** One per stop, so an arrow key can move focus along with the selection. */
|
||||
const stopRefs = useRef<(HTMLButtonElement | null)[]>([]);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const reducedMotion = useReducedMotion();
|
||||
|
||||
const { levels, ungradedValue } = useMemo(() => {
|
||||
const options = (setting.options ?? []).map(String);
|
||||
|
|
@ -195,7 +228,21 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {
|
|||
return;
|
||||
}
|
||||
const ratio = (clientX - rect.left - THUMB / 2) / usable;
|
||||
pendingRef.current = Math.round(Math.min(1, Math.max(0, ratio)) * (levels.length - 1));
|
||||
const index = Math.round(Math.min(1, Math.max(0, ratio)) * (levels.length - 1));
|
||||
pendingRef.current = index;
|
||||
/* The thumb leans toward the pointer from the stop it is on, stretching
|
||||
along the pull, and only moves stops once the pointer crosses halfway.
|
||||
Written straight to the track as custom properties: the thumb follows
|
||||
the pointer at frame rate without re-rendering anything. */
|
||||
if (!reducedMotion) {
|
||||
const stopX =
|
||||
rect.left + THUMB / 2 + (levels.length === 1 ? 1 : index / (levels.length - 1)) * usable;
|
||||
const lean = leanFor(clientX - stopX);
|
||||
const strength = Math.abs(lean) / MAX_LEAN;
|
||||
track.style.setProperty('--effort-lean', `${lean.toFixed(2)}px`);
|
||||
track.style.setProperty('--effort-stretch', (1 + LEAN_STRETCH * strength).toFixed(3));
|
||||
track.style.setProperty('--effort-squash', (1 - LEAN_SQUASH * strength).toFixed(3));
|
||||
}
|
||||
if (frameRef.current != null) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -208,9 +255,17 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {
|
|||
}
|
||||
});
|
||||
},
|
||||
[levels, select],
|
||||
[levels, select, reducedMotion],
|
||||
);
|
||||
|
||||
/** Lets go of the lean; the thumb springs back onto its stop. */
|
||||
const settle = useCallback(() => {
|
||||
const track = trackRef.current;
|
||||
track?.style.removeProperty('--effort-lean');
|
||||
track?.style.removeProperty('--effort-stretch');
|
||||
track?.style.removeProperty('--effort-squash');
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (frameRef.current != null) {
|
||||
|
|
@ -245,16 +300,12 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {
|
|||
thumb lifting rather than as a misaligned track. */
|
||||
const centerOf = (index: number) =>
|
||||
`calc(${THUMB / 2}px + ${ratioOf(index)} * (100% - ${THUMB}px))`;
|
||||
/* Ends half a rail-height PAST the thumb's centre, which puts the fill's own
|
||||
rounded cap concentric with the thumb. The cap's radius (TRACK_H / 2) is
|
||||
smaller than the thumb's, so the thumb geometrically contains it at every
|
||||
position, including the first stop where the fill disappears entirely
|
||||
beneath it.
|
||||
That containment holds mid-animation too, because the offset is constant:
|
||||
collapsing to zero at the first stop instead left the fill briefly wider
|
||||
than the thumb could cover, which flashed green on the way down. */
|
||||
/* Ends at the thumb's centre, so the thumb covers the fill's end even while
|
||||
it leans toward the pointer (up to MAX_LEAN, well inside its radius), and
|
||||
the fill disappears entirely beneath it at the first stop. The two glide
|
||||
on the same curve, so that holds mid-animation as well. */
|
||||
const fillWidth = (index: number) =>
|
||||
`calc(${THUMB / 2 + TRACK_H / 2}px + ${ratioOf(index)} * (100% - ${THUMB}px))`;
|
||||
`calc(${THUMB / 2}px + ${ratioOf(index)} * (100% - ${THUMB}px))`;
|
||||
|
||||
/* `descriptionCode` is what says whether this is a translation key or the
|
||||
literal text an admin wrote. Translating it either way sent literal text
|
||||
|
|
@ -305,10 +356,12 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {
|
|||
}
|
||||
draggingRef.current = false;
|
||||
setDragging(false);
|
||||
settle();
|
||||
}}
|
||||
onPointerCancel={() => {
|
||||
draggingRef.current = false;
|
||||
setDragging(false);
|
||||
settle();
|
||||
}}
|
||||
className={cn(
|
||||
'relative w-full touch-none transition-opacity duration-200 select-none',
|
||||
|
|
@ -345,15 +398,15 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {
|
|||
<span
|
||||
aria-hidden="true"
|
||||
style={{ height: TRACK_H, width: fillWidth(shownIndex) }}
|
||||
className={cn(
|
||||
'absolute top-1/2 left-0 -translate-y-1/2 transition-all ease-out motion-reduce:duration-0',
|
||||
dragging ? 'duration-75' : 'duration-150',
|
||||
)}
|
||||
className="composer-effort-glide absolute top-1/2 left-0 -translate-y-1/2"
|
||||
>
|
||||
<span
|
||||
data-dragging={dragging || undefined}
|
||||
className={cn(
|
||||
'bg-accent-primary block h-full w-full rounded-full transition-opacity duration-100 ease-out motion-reduce:duration-0',
|
||||
isUngraded ? 'opacity-0' : 'opacity-100',
|
||||
'composer-effort-fill bg-accent-primary block h-full rounded-full',
|
||||
/* At the first stop the fill lies wholly under the thumb, and a
|
||||
thumb leaning away from the rail's end would uncover its start. */
|
||||
isUngraded || shownIndex === 0 ? 'opacity-0' : 'opacity-100',
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
|
|
@ -391,17 +444,19 @@ function Effort({ setting, conversation, value, onChange }: EffortProps) {
|
|||
<span
|
||||
aria-hidden="true"
|
||||
style={{ left: centerOf(shownIndex), height: thumbSize, width: thumbSize }}
|
||||
className={cn(
|
||||
'absolute top-1/2 -translate-x-1/2 -translate-y-1/2 transition-all ease-out motion-reduce:duration-0',
|
||||
dragging ? 'duration-75' : 'duration-150',
|
||||
)}
|
||||
className="composer-effort-glide absolute top-1/2 -translate-x-1/2 -translate-y-1/2"
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'bg-surface-fixed block h-full w-full rounded-full shadow-md transition-opacity duration-150 ease-out motion-reduce:delay-0 motion-reduce:duration-0',
|
||||
isUngraded ? 'opacity-0 delay-100' : 'opacity-100 delay-0',
|
||||
)}
|
||||
/>
|
||||
data-dragging={dragging || undefined}
|
||||
className="composer-effort-thumb block h-full w-full"
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'bg-surface-fixed block h-full w-full rounded-full shadow-md transition-opacity duration-150 ease-out motion-reduce:delay-0 motion-reduce:duration-0',
|
||||
isUngraded ? 'opacity-0 delay-100' : 'opacity-100 delay-0',
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
</span>
|
||||
|
||||
{levels.map((value, index) => {
|
||||
|
|
|
|||
322
client/src/components/Chat/Input/Composer/Files.tsx
Normal file
322
client/src/components/Chat/Input/Composer/Files.tsx
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
import { memo, useRef, useMemo, useState, useEffect } from 'react';
|
||||
import { Eye, Search } from 'lucide-react';
|
||||
import { apiBaseUrl } from 'librechat-data-provider';
|
||||
import { Button, IconButton, Spinner, useToastContext } from '@librechat/client';
|
||||
import type { TFile } from 'librechat-data-provider';
|
||||
import type { TranslationKeys } from '~/hooks';
|
||||
import FilePreviewDialog, {
|
||||
formatBytes,
|
||||
getDisplayType,
|
||||
} from '~/components/Chat/Messages/Content/FilePreviewDialog';
|
||||
import { getPreviewKind } from '~/components/Chat/Messages/Content/preview';
|
||||
import { getFileType, toAbsoluteFilePath, triggerDownload } from '~/utils';
|
||||
import DialogImage from '~/components/Chat/Messages/Content/DialogImage';
|
||||
import FilePreview from '~/components/Chat/Input/Files/FilePreview';
|
||||
import { useGetFiles, useFilePreviewBlob } from '~/data-provider';
|
||||
import { useLocalize, useAuthContext } from '~/hooks';
|
||||
|
||||
export type FileView = 'all' | 'images' | 'documents';
|
||||
|
||||
export const FILE_VIEWS: Array<{ value: FileView; labelKey: TranslationKeys }> = [
|
||||
{ value: 'all', labelKey: 'com_ui_all_proper' },
|
||||
{ value: 'images', labelKey: 'com_ui_composer_files_images' },
|
||||
{ value: 'documents', labelKey: 'com_ui_composer_files_documents' },
|
||||
];
|
||||
|
||||
const isImage = (file: TFile) => file.type?.startsWith('image/') === true;
|
||||
|
||||
/** Images, audio and video are media; everything else is a document. */
|
||||
const isDocument = (file: TFile) =>
|
||||
!isImage(file) &&
|
||||
file.type?.startsWith('audio/') !== true &&
|
||||
file.type?.startsWith('video/') !== true;
|
||||
|
||||
/** What a card's preview button opens, if anything: images in the message
|
||||
* image viewer, PDFs in the message file preview. */
|
||||
function previewOf(file: TFile): 'image' | 'pdf' | null {
|
||||
if (isImage(file)) {
|
||||
return 'image';
|
||||
}
|
||||
return getPreviewKind(file.filename ?? '', file.type ?? undefined, file.source) === 'pdf'
|
||||
? 'pdf'
|
||||
: null;
|
||||
}
|
||||
|
||||
function formatDate(file: TFile): string {
|
||||
const raw = file.updatedAt ?? file.createdAt;
|
||||
if (raw == null) {
|
||||
return '';
|
||||
}
|
||||
return new Date(raw).toLocaleDateString(undefined, {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
/** The image itself for images, so the card is recognisable at a glance; the
|
||||
* file-type tile otherwise, or when the image cannot be loaded. */
|
||||
function Thumbnail({ file }: { file: TFile }) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
if (isImage(file) && !failed && file.filepath) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="bg-surface-tertiary size-10 shrink-0 overflow-hidden rounded-xl"
|
||||
>
|
||||
<img
|
||||
src={toAbsoluteFilePath(file.filepath, apiBaseUrl())}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
onError={() => setFailed(true)}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span aria-hidden="true" className="shrink-0">
|
||||
<FilePreview file={file} fileType={getFileType(file.type)} className="size-10 rounded-xl" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
interface FileCardProps {
|
||||
file: TFile;
|
||||
onAttach: (file: TFile) => void;
|
||||
onPreview: (file: TFile, trigger: HTMLButtonElement) => void;
|
||||
}
|
||||
|
||||
/** Laid out like the skill and MCP cards: the card is the attach action, and
|
||||
* the corner holds the one secondary action, previewing, where they keep the
|
||||
* favourite star. */
|
||||
const FileCard = memo(function FileCard({ file, onAttach, onPreview }: FileCardProps) {
|
||||
const localize = useLocalize();
|
||||
const name = file.filename ?? '';
|
||||
const details = [
|
||||
getDisplayType(localize, file.type ?? undefined, name),
|
||||
formatBytes(file.bytes ?? 0),
|
||||
];
|
||||
const canPreview = previewOf(file) != null;
|
||||
|
||||
return (
|
||||
<div className="group border-border-light hover:border-border-medium hover:bg-surface-tertiary relative flex h-28 w-full flex-col overflow-hidden rounded-2xl border bg-transparent hover:shadow-xs">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onAttach(file)}
|
||||
className="focus-visible:ring-ring-primary flex h-full w-full cursor-pointer flex-col gap-2 rounded-2xl p-4 text-left focus:outline-hidden focus-visible:ring-2"
|
||||
>
|
||||
<span className="flex w-full min-w-0 items-start gap-3">
|
||||
<Thumbnail file={file} />
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="text-text-primary truncate text-sm font-semibold">{name}</span>
|
||||
<span className="text-text-secondary truncate text-xs">{details.join(' · ')}</span>
|
||||
</span>
|
||||
</span>
|
||||
<span className="text-text-secondary mt-auto text-xs">{formatDate(file)}</span>
|
||||
</button>
|
||||
{canPreview && (
|
||||
<span className="absolute right-2 bottom-2">
|
||||
<IconButton
|
||||
size="xs"
|
||||
shape="square"
|
||||
label={localize('com_ui_composer_preview_file', { 0: name })}
|
||||
onClick={(event) => onPreview(file, event.currentTarget)}
|
||||
>
|
||||
<Eye className="text-text-secondary h-4 w-4" aria-hidden="true" />
|
||||
</IconButton>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
/** What the grid shows in place of cards: still loading, the list failed to
|
||||
* load, or nothing matches the search and view. */
|
||||
function EmptyState({
|
||||
loading,
|
||||
failed,
|
||||
onRetry,
|
||||
}: {
|
||||
loading: boolean;
|
||||
failed: boolean;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
if (loading) {
|
||||
return (
|
||||
<div role="status" className="text-text-secondary flex items-center justify-center py-16">
|
||||
<Spinner size={24} />
|
||||
<span className="sr-only">{localize('com_ui_loading')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (failed) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
|
||||
<p role="alert" className="text-text-secondary text-sm">
|
||||
{localize('com_ui_error_connection')}
|
||||
</p>
|
||||
{/* The files query does not refetch on mount, focus or reconnect, so
|
||||
reopening the dialog would not recover without this. */}
|
||||
<Button type="button" variant="outline" size="sm" onClick={onRetry}>
|
||||
{localize('com_ui_retry')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div role="status" className="flex flex-col items-center justify-center py-16 text-center">
|
||||
<Search className="text-text-tertiary size-8 opacity-40" aria-hidden="true" />
|
||||
<p className="text-text-secondary mt-3 text-sm">{localize('com_ui_composer_no_results')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface FileGridProps {
|
||||
query: string;
|
||||
view: FileView;
|
||||
onAttach: (file: TFile) => void;
|
||||
}
|
||||
|
||||
/** The user's files as cards, filtered by name and kind, with a preview for
|
||||
* anything the message viewers can show. */
|
||||
export default function FileGrid({ query, view, onAttach }: FileGridProps) {
|
||||
const localize = useLocalize();
|
||||
const { data: files = [], isLoading, isError, refetch } = useGetFiles<TFile[]>();
|
||||
const [previewing, setPreviewing] = useState<TFile | null>(null);
|
||||
/** The Preview button that opened the viewer, where focus returns on close. */
|
||||
const previewTriggerRef = useRef<HTMLButtonElement | null>(null);
|
||||
const openPreview = (file: TFile, trigger: HTMLButtonElement) => {
|
||||
previewTriggerRef.current = trigger;
|
||||
setPreviewing(file);
|
||||
};
|
||||
|
||||
const visible = useMemo(
|
||||
() =>
|
||||
files.filter((file) => {
|
||||
if (query !== '' && file.filename?.toLowerCase().includes(query) !== true) {
|
||||
return false;
|
||||
}
|
||||
if (view === 'images') {
|
||||
return isImage(file);
|
||||
}
|
||||
if (view === 'documents') {
|
||||
return isDocument(file);
|
||||
}
|
||||
return true;
|
||||
}),
|
||||
[files, query, view],
|
||||
);
|
||||
|
||||
const previewKind = previewing != null ? previewOf(previewing) : null;
|
||||
|
||||
/* The image is fetched through the backend by id, as the PDF preview is,
|
||||
rather than from its stored link: a signed storage link can expire between
|
||||
the list refreshing it and the preview opening. The link is the fallback. */
|
||||
const { user } = useAuthContext();
|
||||
const { refetch: fetchPreview } = useFilePreviewBlob(user?.id, previewing?.file_id);
|
||||
const { showToast } = useToastContext();
|
||||
/* Read through a ref: `showToast` is a new function each render, and the
|
||||
preview effect must not refetch because of it. */
|
||||
const previewFailedRef = useRef<(file: TFile) => void>(() => undefined);
|
||||
previewFailedRef.current = (file: TFile) => {
|
||||
showToast({
|
||||
message: localize('com_ui_composer_preview_failed', { 0: file.filename ?? '' }),
|
||||
status: 'error',
|
||||
});
|
||||
setPreviewing(null);
|
||||
};
|
||||
const [imageUrl, setImageUrl] = useState<string>();
|
||||
useEffect(() => {
|
||||
if (previewKind !== 'image' || previewing == null) {
|
||||
return;
|
||||
}
|
||||
let objectUrl: string | undefined;
|
||||
let cancelled = false;
|
||||
void fetchPreview().then(({ data }) => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
if (data != null) {
|
||||
objectUrl = URL.createObjectURL(data);
|
||||
setImageUrl(objectUrl);
|
||||
return;
|
||||
}
|
||||
/* Nothing to show: stay on the grid and say so, rather than open an
|
||||
empty viewer or let the click appear to do nothing. */
|
||||
const fail = () => previewFailedRef.current(previewing);
|
||||
if (!previewing.filepath) {
|
||||
fail();
|
||||
return;
|
||||
}
|
||||
/* A stored link can be expired: open only once it actually loads. */
|
||||
const fallback = toAbsoluteFilePath(previewing.filepath, apiBaseUrl());
|
||||
const probe = new Image();
|
||||
probe.onload = () => !cancelled && setImageUrl(fallback);
|
||||
probe.onerror = () => !cancelled && fail();
|
||||
probe.src = fallback;
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (objectUrl != null) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
setImageUrl(undefined);
|
||||
};
|
||||
}, [previewKind, previewing, fetchPreview]);
|
||||
|
||||
const closePreview = (open: boolean) => {
|
||||
if (!open) {
|
||||
setPreviewing(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{visible.length === 0 ? (
|
||||
<EmptyState
|
||||
loading={isLoading}
|
||||
failed={isError && files.length === 0}
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
) : (
|
||||
<ul
|
||||
className="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3"
|
||||
aria-label={localize('com_ui_composer_files')}
|
||||
>
|
||||
{visible.map((file) => (
|
||||
<li key={file.file_id}>
|
||||
<FileCard file={file} onAttach={onAttach} onPreview={openPreview} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<DialogImage
|
||||
isOpen={previewKind === 'image' && imageUrl != null}
|
||||
onOpenChange={closePreview}
|
||||
src={imageUrl}
|
||||
triggerRef={previewTriggerRef}
|
||||
showDetails={false}
|
||||
title={previewing?.filename ?? undefined}
|
||||
downloadImage={() => {
|
||||
if (imageUrl != null) {
|
||||
triggerDownload(imageUrl, previewing?.filename ?? 'image');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<FilePreviewDialog
|
||||
open={previewKind === 'pdf'}
|
||||
onOpenChange={closePreview}
|
||||
fileName={previewing?.filename ?? ''}
|
||||
fileId={previewing?.file_id}
|
||||
filePath={previewing?.filepath}
|
||||
fileType={previewing?.type ?? undefined}
|
||||
fileSource={previewing?.source}
|
||||
fileSize={previewing?.bytes}
|
||||
deliveryPath={previewing?.llmDeliveryPath}
|
||||
triggerRef={previewTriggerRef}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -11,7 +11,7 @@ import { useSetAtom } from 'jotai';
|
|||
import * as Ariakit from '@ariakit/react';
|
||||
import { AutoSizer, List } from 'react-virtualized';
|
||||
import { Star, Plus, Search, ChevronDown } from 'lucide-react';
|
||||
import { FileUpload, IconButton, TooltipAnchor } from '@librechat/client';
|
||||
import { Button, FileUpload, IconButton, TooltipAnchor, useMediaQuery } from '@librechat/client';
|
||||
import type {
|
||||
TFile,
|
||||
TConversation,
|
||||
|
|
@ -21,6 +21,7 @@ import type {
|
|||
import type { PaletteEntry, PaletteSection } from '~/hooks/Input/usePaletteEntries';
|
||||
import type { AttachEntry } from '~/hooks/Input/useAttachItems';
|
||||
import type { ExtendedFile, FileSetter } from '~/common';
|
||||
import type { CatalogSection } from './Catalog';
|
||||
import type { TranslationKeys } from '~/hooks';
|
||||
import FilePreview from '~/components/Chat/Input/Files/FilePreview';
|
||||
import { SharePointPickerDialog } from '~/components/SharePoint';
|
||||
|
|
@ -35,8 +36,14 @@ import { isMacPlatform } from '~/utils/shortcuts';
|
|||
import { useBadgeRowContext } from '~/Providers';
|
||||
import { composerLiftFamily } from './state';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import Catalog from './Catalog';
|
||||
|
||||
const HEADER_HEIGHT = 26;
|
||||
/** A header carrying its section's "Show all" button, which is taller than the
|
||||
* label alone. */
|
||||
const HEADER_ACTION_HEIGHT = 32;
|
||||
/** Rows a capped section shows before the rest move behind "Show all". */
|
||||
const SECTION_LIMIT = 5;
|
||||
const ROW_HEIGHT = 34;
|
||||
const ROW_HEIGHT_DESC = 46;
|
||||
/* Kept short enough that the popup clears the space below the composer, so it
|
||||
|
|
@ -92,13 +99,13 @@ const SECTION_LABEL: Record<PaletteSection, TranslationKeys> = {
|
|||
};
|
||||
|
||||
type PaletteRow =
|
||||
| { type: 'header'; key: string; label: string }
|
||||
| { type: 'header'; key: string; label: string; showAll?: CatalogSection }
|
||||
| { type: 'attach'; key: string; entry: AttachEntry }
|
||||
| { type: 'more'; key: string; label: string }
|
||||
| { type: 'file'; key: string; file: TFile }
|
||||
| { type: 'entry'; key: string; entry: PaletteEntry; isFavorite: boolean };
|
||||
|
||||
const isSelectable = (row: PaletteRow) => row.type !== 'header';
|
||||
const isSelectable = (row: PaletteRow) => row.type !== 'header' || row.showAll != null;
|
||||
|
||||
/** Ranks a match so exact prefixes float above incidental description hits. */
|
||||
function scoreEntry(label: string, description: string | undefined, query: string): number {
|
||||
|
|
@ -130,7 +137,7 @@ function formatFileDate(file: TFile): string {
|
|||
|
||||
function rowHeight(row: PaletteRow): number {
|
||||
if (row.type === 'header') {
|
||||
return HEADER_HEIGHT;
|
||||
return row.showAll != null ? HEADER_ACTION_HEIGHT : HEADER_HEIGHT;
|
||||
}
|
||||
if (row.type === 'entry' && row.entry.description != null && row.entry.description !== '') {
|
||||
return ROW_HEIGHT_DESC;
|
||||
|
|
@ -211,14 +218,14 @@ function Palette({
|
|||
with the controlled form, hide-on-interact-outside fired on mousedown and
|
||||
the disclosure's own click re-opened it, so clicking `+` while the palette
|
||||
was up reopened it instead of closing it. */
|
||||
const popover = Ariakit.usePopoverStore({ placement: 'bottom-start' });
|
||||
/* Above the composer on a phone, where the composer sits at the bottom of the
|
||||
screen; the lift below exists only to make room for the downward popup. */
|
||||
const opensUp = useMediaQuery('(max-width: 767px)');
|
||||
const popover = Ariakit.usePopoverStore({ placement: opensUp ? 'top-start' : 'bottom-start' });
|
||||
const open = popover.useState('open');
|
||||
const context = useBadgeRowContext();
|
||||
const mcpManager = context?.mcpServerManager;
|
||||
const configDialogOpen = mcpManager?.getConfigDialogProps()?.isOpen === true;
|
||||
useMCPRefresh({
|
||||
enabled: (open || configDialogOpen) && (mcpManager?.availableMCPServers.length ?? 0) > 0,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
onOpened?.();
|
||||
|
|
@ -230,6 +237,20 @@ function Palette({
|
|||
to a tool once will do it again, and re-expanding every time is the cost of
|
||||
hiding it. */
|
||||
const [showAllAttach, setShowAllAttach] = useState(false);
|
||||
/** The section whose "Show all" dialog is open, if any. */
|
||||
const [catalog, setCatalog] = useState<CatalogSection | null>(null);
|
||||
/** Set while the palette closes to hand over to a dialog, so its close does
|
||||
* not pull focus back into the composer from under the dialog. */
|
||||
const openingCatalogRef = useRef(false);
|
||||
/** Where focus lands when a "Show all" dialog closes. */
|
||||
const catalogReturnRef = useRef<HTMLElement | null>(null);
|
||||
/* The MCP catalog shows the same live statuses as the palette rows, so it
|
||||
keeps the refresh running after the palette hands over to it. */
|
||||
useMCPRefresh({
|
||||
enabled:
|
||||
(open || configDialogOpen || catalog === 'mcp') &&
|
||||
(mcpManager?.availableMCPServers.length ?? 0) > 0,
|
||||
});
|
||||
/* Closing runs in two beats, so the rows below never slide up through a hole
|
||||
where the folded destinations used to be: they fade where they stand, and
|
||||
only once they are gone does the list close over them. */
|
||||
|
|
@ -326,7 +347,7 @@ function Palette({
|
|||
useEffect(() => () => applyLift(0), [applyLift]);
|
||||
const baselineRef = useRef<number | null>(null);
|
||||
const updateLift = useCallback(() => {
|
||||
if (!mounted) {
|
||||
if (!mounted || opensUp) {
|
||||
baselineRef.current = null;
|
||||
applyLift(0);
|
||||
return;
|
||||
|
|
@ -347,7 +368,7 @@ function Palette({
|
|||
viewport != null ? viewport.offsetTop + viewport.height : window.innerHeight;
|
||||
applyLift(Math.max(0, Math.ceil(needed - (viewportBottom - baselineRef.current))));
|
||||
follow();
|
||||
}, [mounted, popupHeight, applyLift, anchorRef, follow]);
|
||||
}, [mounted, opensUp, popupHeight, applyLift, anchorRef, follow]);
|
||||
|
||||
useLayoutEffect(updateLift, [updateLift]);
|
||||
|
||||
|
|
@ -482,12 +503,17 @@ function Palette({
|
|||
if (list.length === 0) {
|
||||
return;
|
||||
}
|
||||
/* Tools are a short fixed set; skills and servers run to hundreds, so
|
||||
the palette keeps a handful and the dialog holds the rest. */
|
||||
const capped = section !== 'tool';
|
||||
next.push({
|
||||
type: 'header',
|
||||
key: `h:${section}`,
|
||||
label: localize(SECTION_LABEL[section]),
|
||||
showAll: capped ? section : undefined,
|
||||
});
|
||||
for (const entry of list) {
|
||||
const shown = capped ? list.slice(0, SECTION_LIMIT) : list;
|
||||
for (const entry of shown) {
|
||||
next.push({ type: 'entry', key: entry.key, entry, isFavorite: false });
|
||||
}
|
||||
};
|
||||
|
|
@ -497,8 +523,13 @@ function Palette({
|
|||
pushSection('mcp');
|
||||
|
||||
if (canAttach && recent.files.length > 0) {
|
||||
next.push({ type: 'header', key: 'h:files', label: localize('com_ui_composer_files') });
|
||||
for (const file of recent.files) {
|
||||
next.push({
|
||||
type: 'header',
|
||||
key: 'h:files',
|
||||
label: localize('com_ui_composer_files'),
|
||||
showAll: 'files',
|
||||
});
|
||||
for (const file of recent.files.slice(0, SECTION_LIMIT)) {
|
||||
next.push({ type: 'file', key: `file:${file.file_id}`, file });
|
||||
}
|
||||
}
|
||||
|
|
@ -631,7 +662,12 @@ function Palette({
|
|||
return () => window.clearTimeout(timer);
|
||||
}, [collapsing]);
|
||||
|
||||
const firstSelectable = useMemo(() => rows.findIndex(isSelectable), [rows]);
|
||||
/* A section's "Show all" is reachable by the arrows, but never the resting
|
||||
highlight: Enter straight after opening should pick a row, not a dialog. */
|
||||
const firstSelectable = useMemo(() => {
|
||||
const firstRow = rows.findIndex((row) => row.type !== 'header');
|
||||
return firstRow === -1 ? rows.findIndex(isSelectable) : firstRow;
|
||||
}, [rows]);
|
||||
|
||||
/** Where the active row sits now, falling back to the first row that can be
|
||||
* chosen once the query has filtered the old one away. */
|
||||
|
|
@ -654,12 +690,17 @@ function Palette({
|
|||
|
||||
/* Cleared on unmount rather than on close: the popup stays up through its
|
||||
leave animation, so clearing on close emptied the field and repopulated the
|
||||
list in full view of the user. */
|
||||
list in full view of the user.
|
||||
The highlight goes with it. It follows the pointer as well as the arrows,
|
||||
so keeping it made the next opening light up whatever row or "Show all"
|
||||
the pointer last crossed, wherever the pointer now is. */
|
||||
const [wasMounted, setWasMounted] = useState(false);
|
||||
if (mounted !== wasMounted) {
|
||||
setWasMounted(mounted);
|
||||
if (!mounted) {
|
||||
setSearch('');
|
||||
setActiveKey('');
|
||||
setScrollToActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -684,7 +725,18 @@ function Palette({
|
|||
const activate = useCallback(
|
||||
(index: number) => {
|
||||
const row = rows[index];
|
||||
if (!row || row.type === 'header') {
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
if (row.type === 'header') {
|
||||
if (row.showAll == null) {
|
||||
return;
|
||||
}
|
||||
openingCatalogRef.current = true;
|
||||
catalogReturnRef.current =
|
||||
anchorRef.current?.querySelector<HTMLElement>('[data-testid="text-input"]') ?? null;
|
||||
popover.hide();
|
||||
setCatalog(row.showAll);
|
||||
return;
|
||||
}
|
||||
if (row.type === 'attach') {
|
||||
|
|
@ -715,7 +767,7 @@ function Palette({
|
|||
a file picker, dismisses it. */
|
||||
row.entry.onSelect();
|
||||
},
|
||||
[rows, popover, recent, showAllAttach],
|
||||
[rows, popover, recent, showAllAttach, anchorRef],
|
||||
);
|
||||
|
||||
/**
|
||||
|
|
@ -815,6 +867,32 @@ function Palette({
|
|||
>
|
||||
{row.label}
|
||||
</div>
|
||||
{row.showAll != null && (
|
||||
<div
|
||||
id={paletteRowId(row.key)}
|
||||
role="gridcell"
|
||||
aria-selected={index === activeIndex}
|
||||
onMouseEnter={() => {
|
||||
setActiveKey(row.key);
|
||||
setScrollToActive(false);
|
||||
}}
|
||||
className={cn(
|
||||
'text-text-secondary flex shrink-0 items-end self-end rounded-md',
|
||||
index === activeIndex && 'bg-surface-hover',
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
tabIndex={-1}
|
||||
aria-label={localize('com_ui_composer_show_all_label', { 0: row.label })}
|
||||
onClick={(event) => handleRowClick(event, index)}
|
||||
>
|
||||
{localize('com_ui_show_all')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -941,6 +1019,7 @@ function Palette({
|
|||
const departing = row.type === 'attach' && row.entry.primary !== true && collapsing;
|
||||
const { label, icon } = row.entry;
|
||||
const description = isEntry ? row.entry.description : undefined;
|
||||
const status = isEntry ? row.entry.status : undefined;
|
||||
const checked = isEntry ? row.entry.active : false;
|
||||
const favorited = isEntry && row.isFavorite;
|
||||
const canFavorite = isEntry && row.entry.favoritable !== false;
|
||||
|
|
@ -989,11 +1068,24 @@ function Palette({
|
|||
}
|
||||
className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-lg px-2 text-left"
|
||||
>
|
||||
<span className="shrink-0" aria-hidden="true">
|
||||
<span className="relative flex shrink-0" aria-hidden="true">
|
||||
{icon}
|
||||
{status != null && (
|
||||
/* Sits on the icon's corner like the MCP menu's server items;
|
||||
the ring takes the popup's surface so the dot reads as cut
|
||||
out of the glyph. */
|
||||
<span
|
||||
className={cn(
|
||||
'border-presentation absolute -right-1 -bottom-1 size-2.5 rounded-full border-2',
|
||||
status.tone,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col justify-center">
|
||||
<span className={cn('truncate', checked && 'font-medium')}>{label}</span>
|
||||
{/* The dot is color only, so the status is still said aloud. */}
|
||||
{status != null && <span className="sr-only">{status.label}</span>}
|
||||
{description != null && description !== '' && (
|
||||
<span className="text-text-secondary truncate text-xs opacity-80">
|
||||
{description}
|
||||
|
|
@ -1010,6 +1102,7 @@ function Palette({
|
|||
<IconButton
|
||||
size="xs"
|
||||
shape="square"
|
||||
variant="row-action"
|
||||
label={mode.label}
|
||||
className="group"
|
||||
onClick={(event) => {
|
||||
|
|
@ -1053,6 +1146,7 @@ function Palette({
|
|||
<IconButton
|
||||
size="xs"
|
||||
shape="square"
|
||||
variant="row-action"
|
||||
label={localize(favorited ? 'com_ui_unfavorite' : 'com_ui_favorite')}
|
||||
aria-pressed={favorited}
|
||||
onClick={(event) => {
|
||||
|
|
@ -1065,7 +1159,7 @@ function Palette({
|
|||
className={cn(
|
||||
'h-4 w-4',
|
||||
favorited
|
||||
? 'text-accent-primary group-hover:text-accent-primary-hover'
|
||||
? 'text-series-4 group-hover:text-series-4'
|
||||
: 'text-text-secondary group-hover:text-text-primary',
|
||||
)}
|
||||
fill={favorited ? 'currentColor' : 'none'}
|
||||
|
|
@ -1098,8 +1192,9 @@ function Palette({
|
|||
return (
|
||||
<>
|
||||
<FileUpload ref={attach.inputRef} handleFileChange={attach.onFileChange}>
|
||||
{/* Opens downward like the thinking popup; Ariakit flips it above on
|
||||
its own once the composer sits too low for it to fit below. */}
|
||||
{/* Opens downward like the thinking popup on wider screens, and above
|
||||
on a phone; Ariakit flips a downward one above on its own once the
|
||||
composer sits too low for it to fit below. */}
|
||||
<Ariakit.PopoverProvider store={popover}>
|
||||
{/* The disclosure is the outer component and the tooltip is what it
|
||||
renders through, not the other way round: passing a
|
||||
|
|
@ -1180,8 +1275,10 @@ function Palette({
|
|||
onClose={() => {
|
||||
window.requestAnimationFrame(() => {
|
||||
/* Reopened within the frame: that session owns the input and
|
||||
the field must not take focus from it. */
|
||||
if (popover.getState().open) {
|
||||
the field must not take focus from it. Handed over to a
|
||||
"Show all" dialog: the dialog owns focus now. */
|
||||
if (popover.getState().open || openingCatalogRef.current) {
|
||||
openingCatalogRef.current = false;
|
||||
return;
|
||||
}
|
||||
const touch =
|
||||
|
|
@ -1318,6 +1415,16 @@ function Palette({
|
|||
downloadProgress={attach.downloadProgress}
|
||||
maxSelectionCount={attach.maxSelectionCount}
|
||||
/>
|
||||
<Catalog
|
||||
section={catalog}
|
||||
onClose={() => setCatalog(null)}
|
||||
entries={entries}
|
||||
returnFocusRef={catalogReturnRef}
|
||||
onAttach={(file) => {
|
||||
setCatalog(null);
|
||||
recent.attach(file);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import { memo, useRef, useMemo, useState, useLayoutEffect } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { TooltipAnchor } from '@librechat/client';
|
||||
import { TooltipAnchor, useMediaQuery } from '@librechat/client';
|
||||
import type { SettingDefinition, TConversation, TReasoningOverride } from 'librechat-data-provider';
|
||||
import { ReasoningControl, useComposerReasoning } from '../Reasoning';
|
||||
import Effort, { resolveEffortLabel } from './Effort';
|
||||
import Effort, { effortRank, resolveEffortLabel } from './Effort';
|
||||
import { useGetStartupConfig } from '~/data-provider';
|
||||
import { useChatContext } from '~/Providers';
|
||||
import { cn, getModelSpec } from '~/utils';
|
||||
|
|
@ -32,7 +32,10 @@ function ThinkingControl({
|
|||
with the controlled form, hide-on-interact-outside fired on mousedown and
|
||||
the disclosure's own click re-opened it, so a second click never closed the
|
||||
popup. */
|
||||
const popover = Ariakit.usePopoverStore({ placement: 'bottom' });
|
||||
/* Above the composer on a phone, where the composer sits at the bottom of the
|
||||
screen and a popup below it would open off the edge or under the keyboard. */
|
||||
const isMobile = useMediaQuery('(max-width: 767px)');
|
||||
const popover = Ariakit.usePopoverStore({ placement: isMobile ? 'top' : 'bottom' });
|
||||
const open = popover.useState('open');
|
||||
const disclosureRef = useRef<HTMLButtonElement>(null);
|
||||
const ghostsRef = useRef<HTMLSpanElement>(null);
|
||||
|
|
@ -53,6 +56,29 @@ function ThinkingControl({
|
|||
? localize('com_ui_auto')
|
||||
: resolveEffortLabel(setting, currentValue, localize);
|
||||
|
||||
/* The word on the button moves with the level: up for a higher one, down for
|
||||
a lower one, the outgoing word staying behind as a blurred ghost until it
|
||||
has cleared. `turn` restarts the animation for each change. */
|
||||
const rank = effortRank(setting, currentValue);
|
||||
const [label, setLabel] = useState({
|
||||
text: display,
|
||||
rank,
|
||||
previous: null as string | null,
|
||||
up: true,
|
||||
turn: 0,
|
||||
});
|
||||
if (label.text !== display) {
|
||||
setLabel({
|
||||
text: display,
|
||||
rank,
|
||||
previous: label.text,
|
||||
up: rank >= label.rank,
|
||||
turn: label.turn + 1,
|
||||
});
|
||||
}
|
||||
const clearPrevious = (turn: number) =>
|
||||
setLabel((state) => (state.turn === turn ? { ...state, previous: null } : state));
|
||||
|
||||
/* Every label this button can show, in the active language. All of them get
|
||||
measured rather than picking by character count: the longest string is not
|
||||
the widest one in a proportional font, and even less so across languages. */
|
||||
|
|
@ -83,8 +109,8 @@ function ThinkingControl({
|
|||
}
|
||||
}, [open, display, optionLabels]);
|
||||
|
||||
/* Opens downward; Ariakit flips it above on its own once the composer sits
|
||||
low enough in the viewport that there is no room below. */
|
||||
/* Opens downward on wider screens; Ariakit flips it above on its own once
|
||||
the composer sits low enough in the viewport that there is no room below. */
|
||||
return (
|
||||
<Ariakit.PopoverProvider store={popover}>
|
||||
{/* Named on hover like the mic and send buttons: closed, the trigger shows
|
||||
|
|
@ -115,8 +141,9 @@ function ThinkingControl({
|
|||
{/* Closed, the button hugs its label so it takes no more room in the bar
|
||||
than it needs. Open, it widens to the longest label and the text
|
||||
centres, so changing levels while the popup is up never shifts the
|
||||
row. The label itself swaps plainly: a keyed crossfade dipped it to
|
||||
transparent mid-change, which read as a flicker rather than polish. */}
|
||||
row. A level change never dips the label to transparent (a plain
|
||||
keyed crossfade did, and read as a flicker): the new word arrives
|
||||
while the old one is still leaving, so one is always legible. */}
|
||||
<span
|
||||
/* `composer-slot-resize` runs on `animate-composer-popover`'s clock,
|
||||
so the button and the popup resize together. */
|
||||
|
|
@ -144,7 +171,30 @@ function ThinkingControl({
|
|||
{/* Always centred: flipping alignment as the width animated made the
|
||||
label jump sideways mid-transition. Closed the slot is exactly the
|
||||
label's width, so centred and left are identical anyway. */}
|
||||
<span className="block text-center whitespace-nowrap">{display}</span>
|
||||
<span className="grid text-center whitespace-nowrap">
|
||||
{label.previous != null && (
|
||||
<span
|
||||
key={`out-${label.turn}`}
|
||||
aria-hidden="true"
|
||||
onAnimationEnd={() => clearPrevious(label.turn)}
|
||||
className={cn(
|
||||
'col-start-1 row-start-1',
|
||||
label.up ? 'composer-label-out-up' : 'composer-label-out-down',
|
||||
)}
|
||||
>
|
||||
{label.previous}
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
key={`in-${label.turn}`}
|
||||
className={cn(
|
||||
'col-start-1 row-start-1',
|
||||
label.turn > 0 && (label.up ? 'composer-label-in-up' : 'composer-label-in-down'),
|
||||
)}
|
||||
>
|
||||
{display}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
{/* Turns to point at the popup, which is the only cue that the button
|
||||
and the panel below it are one control. */}
|
||||
|
|
@ -164,6 +214,21 @@ function ThinkingControl({
|
|||
click immediately re-opened it. Excluding the trigger leaves a single
|
||||
clean toggle. */
|
||||
hideOnInteractOutside={(event) => !disclosureRef.current?.contains(event.target as Node)}
|
||||
/* On a phone the button sits inside the composer, so opening above the
|
||||
button alone would cover the message field. It rises from the
|
||||
composer's top edge instead, still centred over its button. */
|
||||
getAnchorRect={
|
||||
isMobile
|
||||
? (anchor) => {
|
||||
const button = anchor?.getBoundingClientRect();
|
||||
const composer = anchor?.closest('form')?.getBoundingClientRect();
|
||||
if (button == null || composer == null) {
|
||||
return null;
|
||||
}
|
||||
return { x: button.x, y: composer.y, width: button.width, height: 0 };
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
aria-label={localize('com_ui_composer_thinking_value', { 0: display })}
|
||||
/* `border-light` resolves to the same value as `surface-tertiary`, so
|
||||
the edge was invisible against the popup's own background. */
|
||||
|
|
|
|||
|
|
@ -1,9 +1,19 @@
|
|||
import { memo } from 'react';
|
||||
import { memo, useRef, useEffect } from 'react';
|
||||
import useReducedMotion from '~/hooks/Generic/useReducedMotion';
|
||||
import useElementSize from '~/hooks/Generic/useElementSize';
|
||||
import useAudioLevels from '~/hooks/Input/useAudioLevels';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
/** Bars never collapse to nothing, so silence still reads as a live line. */
|
||||
const MIN_BAR = 0.1;
|
||||
/** One loudness sample per this many ms; each becomes a bar. */
|
||||
const SAMPLE_MS = 55;
|
||||
const BAR_WIDTH = 3;
|
||||
/** One bar and the gap after it, in px. */
|
||||
const BAR_PITCH = 5;
|
||||
/** Silence still reads as a live line rather than as nothing. */
|
||||
const MIN_BAR_PX = 3;
|
||||
/** A frame this late (a backgrounded tab) restarts the clock instead of
|
||||
* replaying every missed sample at once. */
|
||||
const MAX_CATCH_UP_MS = 500;
|
||||
|
||||
interface WaveformProps {
|
||||
/** Whether the microphone is running; the levels are sampled from here. */
|
||||
|
|
@ -12,27 +22,79 @@ interface WaveformProps {
|
|||
}
|
||||
|
||||
/**
|
||||
* Live microphone trace. Spreads a fixed bar count across whatever width it is
|
||||
* given, so it fills its container rather than overflowing and being clipped.
|
||||
* Live microphone trace. Drawn on a canvas from an animation-frame loop, so
|
||||
* the bars glide left continuously between samples instead of stepping once
|
||||
* per sample, and nothing re-renders while it runs: the whole trace lives in
|
||||
* this effect. Newest on the right, as many bars as the width holds. Reduced
|
||||
* motion keeps the step.
|
||||
*
|
||||
* Samples the microphone itself rather than being handed the levels: at ~18
|
||||
* samples a second, holding them any higher up re-rendered the whole composer,
|
||||
* and every tool and skill row with it, to move these bars.
|
||||
* The bar color is the element's own `text-text-primary`, read from the
|
||||
* canvas every frame, so it follows the theme like any other text.
|
||||
*/
|
||||
function Waveform({ active, className }: WaveformProps) {
|
||||
const levels = useAudioLevels(active);
|
||||
const read = useAudioLevels(active);
|
||||
const reducedMotion = useReducedMotion();
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const { ref, width, height } = useElementSize<HTMLDivElement>();
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
const context = canvas?.getContext('2d');
|
||||
if (!active || canvas == null || context == null || width === 0 || height === 0) {
|
||||
return;
|
||||
}
|
||||
const ratio = window.devicePixelRatio || 1;
|
||||
canvas.width = Math.round(width * ratio);
|
||||
canvas.height = Math.round(height * ratio);
|
||||
context.setTransform(ratio, 0, 0, ratio, 0, 0);
|
||||
/* Live: read per frame so a theme switch mid-dictation recolors the bars. */
|
||||
const style = getComputedStyle(canvas);
|
||||
|
||||
const capacity = Math.ceil(width / BAR_PITCH) + 2;
|
||||
const levels: number[] = new Array(capacity).fill(0);
|
||||
let sampledAt = performance.now();
|
||||
let frame = 0;
|
||||
|
||||
const draw = (now: number) => {
|
||||
if (now - sampledAt > MAX_CATCH_UP_MS) {
|
||||
sampledAt = now;
|
||||
}
|
||||
while (now - sampledAt >= SAMPLE_MS) {
|
||||
sampledAt += SAMPLE_MS;
|
||||
levels.push(read() ?? 0);
|
||||
levels.shift();
|
||||
}
|
||||
/* How far the newest bar has slid in since it was sampled. */
|
||||
const progress = reducedMotion ? 1 : (now - sampledAt) / SAMPLE_MS;
|
||||
|
||||
context.clearRect(0, 0, width, height);
|
||||
context.fillStyle = style.color;
|
||||
context.beginPath();
|
||||
for (let age = 0; age < capacity; age++) {
|
||||
const x = width - BAR_WIDTH - (age - 1 + progress) * BAR_PITCH;
|
||||
if (x > width) {
|
||||
continue;
|
||||
}
|
||||
if (x < -BAR_WIDTH) {
|
||||
break;
|
||||
}
|
||||
const barHeight = Math.max(MIN_BAR_PX, levels[capacity - 1 - age] * height);
|
||||
context.roundRect(x, (height - barHeight) / 2, BAR_WIDTH, barHeight, BAR_WIDTH / 2);
|
||||
}
|
||||
context.fill();
|
||||
frame = requestAnimationFrame(draw);
|
||||
};
|
||||
frame = requestAnimationFrame(draw);
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
context.clearRect(0, 0, width, height);
|
||||
};
|
||||
}, [active, width, height, read, reducedMotion]);
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className={cn('flex w-full items-center justify-between overflow-hidden', className)}
|
||||
>
|
||||
{levels.map((level, index) => (
|
||||
<span
|
||||
key={index}
|
||||
style={{ height: `${Math.max(MIN_BAR, level) * 100}%` }}
|
||||
className="bg-text-primary w-[3px] shrink-0 rounded-full opacity-70 transition-all duration-100 ease-out motion-reduce:transition-none"
|
||||
/>
|
||||
))}
|
||||
<div ref={ref} aria-hidden="true" className={cn('overflow-hidden', className)}>
|
||||
<canvas ref={canvasRef} className="text-text-primary block h-full w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,5 @@
|
|||
import type { PaletteEntry } from '~/hooks/Input/usePaletteEntries';
|
||||
import {
|
||||
PINNED_MCP_KEY,
|
||||
chipMenuModes,
|
||||
chipsFitInline,
|
||||
formatElapsed,
|
||||
projectBarEntries,
|
||||
} from '../Bar';
|
||||
import { chipMenuModes, chipsFitInline, formatElapsed, projectBarEntries } from '../Bar';
|
||||
|
||||
/** Pure decisions behind the bar's tool projection, layout and elapsed time. */
|
||||
|
||||
|
|
@ -32,66 +26,6 @@ describe('projectBarEntries', () => {
|
|||
|
||||
expect(projectBarEntries([active, pinned, inactive, skill])).toEqual([active, pinned]);
|
||||
});
|
||||
|
||||
it('keeps a pinned MCP menu alongside selected server chips', () => {
|
||||
const github = entry('mcp:github', {
|
||||
itemType: 'mcp',
|
||||
itemId: 'github',
|
||||
section: 'mcp',
|
||||
});
|
||||
const pinnedMcp = entry(PINNED_MCP_KEY, {
|
||||
itemType: 'mcp',
|
||||
itemId: 'mcp',
|
||||
section: 'mcp',
|
||||
active: true,
|
||||
pinned: true,
|
||||
});
|
||||
|
||||
const projected = projectBarEntries([github], pinnedMcp);
|
||||
expect(projected).toHaveLength(1);
|
||||
expect(projected[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
key: PINNED_MCP_KEY,
|
||||
modes: [expect.objectContaining({ id: 'github', label: 'mcp:github', active: false })],
|
||||
}),
|
||||
);
|
||||
|
||||
const selected = { ...github, active: true };
|
||||
const selectedProjection = projectBarEntries([selected], pinnedMcp);
|
||||
expect(selectedProjection).toHaveLength(2);
|
||||
expect(selectedProjection[0]).toBe(selected);
|
||||
expect(selectedProjection[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
key: PINNED_MCP_KEY,
|
||||
modes: [expect.objectContaining({ id: 'github', active: true })],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
/* Chip keys are React keys and packing-width slots: two entries sharing one
|
||||
would let a chip or its menu be measured as the other. A server may be
|
||||
named anything, including the word the aggregate pin used to key on. */
|
||||
it('keeps the aggregate MCP chip distinct from a server named pinned', () => {
|
||||
const server = entry('mcp:pinned', {
|
||||
itemType: 'mcp',
|
||||
itemId: 'pinned',
|
||||
section: 'mcp',
|
||||
active: true,
|
||||
});
|
||||
const aggregate = entry(PINNED_MCP_KEY, {
|
||||
itemType: 'mcp',
|
||||
itemId: 'mcp',
|
||||
section: 'mcp',
|
||||
active: true,
|
||||
pinned: true,
|
||||
});
|
||||
|
||||
const projected = projectBarEntries([server], aggregate);
|
||||
const keys = projected.map((projectedEntry) => projectedEntry.key);
|
||||
|
||||
expect(keys).toEqual(['mcp:pinned', PINNED_MCP_KEY]);
|
||||
expect(new Set(keys).size).toBe(keys.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe('chipMenuModes', () => {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,159 @@
|
|||
import React from 'react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import type { TFile } from 'librechat-data-provider';
|
||||
import FileGrid from '../Files';
|
||||
|
||||
const file = (over: Partial<TFile> & Pick<TFile, 'file_id' | 'filename'>): TFile =>
|
||||
({
|
||||
bytes: 2048,
|
||||
type: 'text/plain',
|
||||
filepath: `/uploads/${over.filename}`,
|
||||
source: 'local',
|
||||
createdAt: '2026-09-27T10:00:00.000Z',
|
||||
...over,
|
||||
}) as TFile;
|
||||
|
||||
let mockFiles: TFile[] | undefined = [];
|
||||
let mockQueryState = { isLoading: false, isError: false };
|
||||
const mockRefetch = jest.fn();
|
||||
const mockFetchPreview = jest.fn();
|
||||
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useGetFiles: () => ({ data: mockFiles, refetch: mockRefetch, ...mockQueryState }),
|
||||
useFilePreviewBlob: () => ({ refetch: mockFetchPreview }),
|
||||
useFilePreview: () => ({ refetch: jest.fn() }),
|
||||
useFileDownload: () => ({ refetch: jest.fn() }),
|
||||
useSharedFileDownload: () => ({ refetch: jest.fn() }),
|
||||
}));
|
||||
|
||||
const mockShowToast = jest.fn();
|
||||
jest.mock('@librechat/client', () => ({
|
||||
...jest.requireActual('@librechat/client'),
|
||||
useToastContext: () => ({ showToast: mockShowToast }),
|
||||
}));
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string, options?: Record<string, string | number>) =>
|
||||
options ? `${key}:${options['0']}` : key,
|
||||
useAuthContext: () => ({ user: { id: 'user-1' } }),
|
||||
}));
|
||||
|
||||
const renderGrid = (props: Partial<React.ComponentProps<typeof FileGrid>> = {}) => {
|
||||
const onAttach = jest.fn();
|
||||
render(
|
||||
<RecoilRoot>
|
||||
<FileGrid query="" view="all" onAttach={onAttach} {...props} />
|
||||
</RecoilRoot>,
|
||||
);
|
||||
return { onAttach };
|
||||
};
|
||||
|
||||
describe('FileGrid', () => {
|
||||
beforeEach(() => {
|
||||
mockFetchPreview.mockReset().mockResolvedValue({ data: undefined });
|
||||
mockQueryState = { isLoading: false, isError: false };
|
||||
mockFiles = [
|
||||
file({ file_id: 'img', filename: 'photo.png', type: 'image/png' }),
|
||||
file({ file_id: 'pdf', filename: 'report.pdf', type: 'application/pdf' }),
|
||||
file({ file_id: 'txt', filename: 'notes.txt' }),
|
||||
];
|
||||
});
|
||||
|
||||
it('shows every file as a card with its kind and size', () => {
|
||||
renderGrid();
|
||||
const cards = within(screen.getByRole('list')).getAllByRole('listitem');
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(cards[1]).toHaveTextContent('report.pdf');
|
||||
expect(cards[1]).toHaveTextContent('PDF · 2.0 KB');
|
||||
});
|
||||
|
||||
it('offers a preview for images and PDFs only', () => {
|
||||
renderGrid();
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'com_ui_composer_preview_file:photo.png' }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'com_ui_composer_preview_file:report.pdf' }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'com_ui_composer_preview_file:notes.txt' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('filters by kind and by name', () => {
|
||||
renderGrid({ view: 'images' });
|
||||
expect(within(screen.getByRole('list')).getAllByRole('listitem')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps audio and video out of the documents view', () => {
|
||||
mockFiles = [
|
||||
...(mockFiles ?? []),
|
||||
file({ file_id: 'mp3', filename: 'memo.mp3', type: 'audio/mpeg' }),
|
||||
file({ file_id: 'mp4', filename: 'clip.mp4', type: 'video/mp4' }),
|
||||
];
|
||||
renderGrid({ view: 'documents' });
|
||||
const list = within(screen.getByRole('list'));
|
||||
expect(list.getAllByRole('listitem')).toHaveLength(2);
|
||||
expect(list.queryByText('memo.mp3')).not.toBeInTheDocument();
|
||||
expect(list.queryByText('clip.mp4')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('matches a search against the file name', () => {
|
||||
renderGrid({ query: 'repo' });
|
||||
const cards = within(screen.getByRole('list')).getAllByRole('listitem');
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]).toHaveTextContent('report.pdf');
|
||||
});
|
||||
|
||||
it('says so when nothing matches', () => {
|
||||
renderGrid({ query: 'nothing-here' });
|
||||
expect(screen.getByRole('status')).toHaveTextContent('com_ui_composer_no_results');
|
||||
});
|
||||
|
||||
it('shows loading rather than no matches while the files are fetched', () => {
|
||||
mockFiles = undefined;
|
||||
mockQueryState = { isLoading: true, isError: false };
|
||||
renderGrid();
|
||||
expect(screen.getByRole('status')).toHaveTextContent('com_ui_loading');
|
||||
expect(screen.queryByText('com_ui_composer_no_results')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reports a failed fetch rather than an empty list', () => {
|
||||
mockFiles = undefined;
|
||||
mockQueryState = { isLoading: false, isError: true };
|
||||
renderGrid();
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('com_ui_error_connection');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));
|
||||
expect(mockRefetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stays on the grid when an image has nothing to preview', async () => {
|
||||
mockFiles = [file({ file_id: 'bare', filename: 'bare.png', type: 'image/png', filepath: '' })];
|
||||
renderGrid();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_composer_preview_file:bare.png' }));
|
||||
await waitFor(() => expect(mockFetchPreview).toHaveBeenCalledTimes(1));
|
||||
await waitFor(() =>
|
||||
expect(mockShowToast).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'com_ui_composer_preview_failed:bare.png',
|
||||
status: 'error',
|
||||
}),
|
||||
),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'com_ui_composer_preview_file:bare.png' }),
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('attaches a file when its card is chosen, not when it is previewed', () => {
|
||||
const { onAttach } = renderGrid();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'com_ui_composer_preview_file:photo.png' }));
|
||||
expect(onAttach).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByText('notes.txt'));
|
||||
expect(onAttach).toHaveBeenCalledWith(expect.objectContaining({ file_id: 'txt' }));
|
||||
});
|
||||
});
|
||||
|
|
@ -83,6 +83,8 @@ jest.mock('~/Providers', () => ({
|
|||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string, options?: Record<string, string | number>) =>
|
||||
options ? `${key}:${options['0'] ?? options.count}` : key,
|
||||
useAuthContext: () => ({ user: { id: 'user-1' } }),
|
||||
useToolFavorites: () => ({ favoriteKeys: new Set<string>(), toggle: jest.fn() }),
|
||||
}));
|
||||
|
||||
let mockFavoriteKeys: string[] = [];
|
||||
|
|
@ -185,7 +187,9 @@ const rows = () =>
|
|||
/** Just the section headers, which is what carries the order. */
|
||||
const headers = () =>
|
||||
Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[id^="composer-palette-list"] [data-row-key^="h:"]'),
|
||||
document.querySelectorAll<HTMLElement>(
|
||||
'[id^="composer-palette-list"] [data-row-key^="h:"] [role="columnheader"]',
|
||||
),
|
||||
).map((row) => row.textContent?.trim() ?? '');
|
||||
|
||||
/** Row identities in list order, which is what the model actually decides. */
|
||||
|
|
@ -312,6 +316,105 @@ describe('Palette', () => {
|
|||
);
|
||||
});
|
||||
|
||||
describe('show all', () => {
|
||||
const many = (section: 'skill' | 'mcp', count: number) =>
|
||||
Array.from({ length: count }, (_, i) =>
|
||||
entry({ key: `${section}:item${i}`, itemId: `item${i}`, label: `item${i}`, section }),
|
||||
);
|
||||
|
||||
it('caps skills, servers and files at five rows each', () => {
|
||||
mockRecentFiles = Array.from({ length: 7 }, (_, i) => ({
|
||||
file_id: `f${i}`,
|
||||
filename: `file${i}.pdf`,
|
||||
type: 'application/pdf',
|
||||
}));
|
||||
/* Rendered one section at a time: the list is virtualized, so rows past
|
||||
its height are not in the DOM to count. */
|
||||
const { unmount } = renderPalette({ entries: [...many('skill', 8), ...many('mcp', 8)] });
|
||||
const listed = keys();
|
||||
expect(listed.filter((key) => key.startsWith('skill:'))).toHaveLength(5);
|
||||
expect(listed.filter((key) => key.startsWith('mcp:'))).toHaveLength(5);
|
||||
unmount();
|
||||
renderPalette({ entries: [] });
|
||||
expect(keys().filter((key) => key.startsWith('file:'))).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('keeps the resting highlight on a row, not on a header action', () => {
|
||||
renderPalette({ canAttach: false, entries: many('mcp', 2) });
|
||||
expect(screen.getByTestId('composer-palette-search')).toHaveAttribute(
|
||||
'aria-activedescendant',
|
||||
expect.stringContaining(
|
||||
Array.from('mcp:item0', (c) => c.charCodeAt(0).toString(16).padStart(4, '0')).join(''),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('opens the section dialog, whose cards toggle the same entries', async () => {
|
||||
const servers = many('mcp', 7);
|
||||
renderPalette({ entries: servers });
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: 'com_ui_composer_show_all_label:com_ui_composer_mcp' }),
|
||||
);
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(dialog).toHaveTextContent('com_ui_mcp_servers');
|
||||
fireEvent.click(screen.getByRole('button', { name: /item6/ }));
|
||||
expect(servers[6].onSelect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('shows each server status on its row and on its card', async () => {
|
||||
const servers = [
|
||||
entry({
|
||||
key: 'mcp:up',
|
||||
itemId: 'up',
|
||||
label: 'Up server',
|
||||
section: 'mcp',
|
||||
status: { label: 'Connected', tone: 'bg-status-success' },
|
||||
}),
|
||||
entry({
|
||||
key: 'mcp:auth',
|
||||
itemId: 'auth',
|
||||
label: 'Auth server',
|
||||
section: 'mcp',
|
||||
status: { label: 'Needs Auth', tone: 'bg-status-warning' },
|
||||
}),
|
||||
];
|
||||
renderPalette({ entries: servers });
|
||||
expect(rows()).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining('Up serverConnected'),
|
||||
expect.stringContaining('Auth serverNeeds Auth'),
|
||||
]),
|
||||
);
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: 'com_ui_composer_show_all_label:com_ui_composer_mcp' }),
|
||||
);
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
const cards = Array.from(dialog.querySelectorAll('li')).map((card) => card.textContent);
|
||||
expect(cards).toEqual([
|
||||
expect.stringContaining('Connected'),
|
||||
expect.stringContaining('Needs Auth'),
|
||||
]);
|
||||
});
|
||||
|
||||
it('narrows the dialog to servers the user made', async () => {
|
||||
const servers = many('mcp', 7).map((server, i) => ({ ...server, ownedByUser: i < 2 }));
|
||||
renderPalette({ entries: servers });
|
||||
fireEvent.click(
|
||||
screen.getByRole('button', { name: 'com_ui_composer_show_all_label:com_ui_composer_mcp' }),
|
||||
);
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
const cards = () =>
|
||||
Array.from(dialog.querySelectorAll('li > div > button[aria-pressed]')).map(
|
||||
(card) => card.textContent?.match(/item\d/)?.[0],
|
||||
);
|
||||
expect(cards()).toHaveLength(7);
|
||||
fireEvent.click(screen.getByText('com_ui_tools_view_made_by_you'));
|
||||
expect(cards()).toEqual(['item0', 'item1']);
|
||||
fireEvent.click(screen.getByText('com_ui_tools_view_favorites'));
|
||||
expect(cards()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('section order', () => {
|
||||
it('reads attach, tools, skills, servers, files', () => {
|
||||
mockRecentFiles = [{ file_id: 'f1', filename: 'notes.pdf', type: 'application/pdf' }];
|
||||
|
|
@ -592,6 +695,26 @@ describe('Palette', () => {
|
|||
);
|
||||
});
|
||||
|
||||
/* The highlight follows the pointer too, so a kept one lit up whatever the
|
||||
pointer last crossed (a star's row, "Show all") on the next opening. */
|
||||
it('starts each opening fresh rather than where the last one was left', async () => {
|
||||
renderPalette();
|
||||
const input = screen.getByTestId('composer-palette-search');
|
||||
const first = input.getAttribute('aria-activedescendant');
|
||||
const webRow = document.querySelector('[data-row-key="web_search"]');
|
||||
fireEvent.mouseEnter(webRow as Element);
|
||||
expect(input.getAttribute('aria-activedescendant')).not.toBe(first);
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' });
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('composer-palette-search')).not.toBeInTheDocument(),
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('composer-palette-button'));
|
||||
|
||||
const reopened = await screen.findByTestId('composer-palette-search');
|
||||
expect(reopened.getAttribute('aria-activedescendant')).toBe(first);
|
||||
});
|
||||
|
||||
/* An id that names nothing is the failure mode here: screen readers lose
|
||||
the active option entirely and announce nothing in its place. */
|
||||
it('always points at a row that is in the document', () => {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { ReasoningEffort } from 'librechat-data-provider';
|
|||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { SettingDefinition, TConversation, TReasoningOverride } from 'librechat-data-provider';
|
||||
import type * as ReasoningModule from '../../Reasoning';
|
||||
import { effortRank, leanFor } from '../Effort';
|
||||
import Thinking from '../Thinking';
|
||||
|
||||
const mockSetValue = jest.fn();
|
||||
|
|
@ -127,6 +128,42 @@ describe('Thinking', () => {
|
|||
expect(mockSetValue).toHaveBeenLastCalledWith({ key: 'thinkingBudget', value: 4224 });
|
||||
});
|
||||
|
||||
it('moves the label up for a higher level and down for a lower one', () => {
|
||||
const { rerenderConversation } = renderInComposer();
|
||||
const button = screen.getByTestId('composer-thinking-button');
|
||||
expect(button.querySelector('[class*="composer-label-"]')).toBeNull();
|
||||
|
||||
mockPendingOverride = { key: 'reasoning_effort', value: ReasoningEffort.high };
|
||||
rerenderConversation();
|
||||
expect(button.querySelector('.composer-label-in-up')).toHaveTextContent('High');
|
||||
expect(button.querySelector('.composer-label-out-up')).toHaveTextContent('Low');
|
||||
|
||||
mockPendingOverride = { key: 'reasoning_effort', value: ReasoningEffort.unset };
|
||||
rerenderConversation();
|
||||
expect(button).toHaveTextContent('Auto');
|
||||
expect(button.querySelector('.composer-label-in-down')).toHaveTextContent('Auto');
|
||||
expect(button.querySelector('.composer-label-out-down')).toHaveTextContent('High');
|
||||
});
|
||||
|
||||
it('ranks the separate mode below every level', () => {
|
||||
expect(effortRank(mockSetting, 'auto')).toBe(-1);
|
||||
expect(effortRank(mockSetting, undefined)).toBe(-1);
|
||||
expect(effortRank(mockSetting, 'low')).toBe(0);
|
||||
expect(effortRank(mockSetting, 'high')).toBe(1);
|
||||
});
|
||||
|
||||
it('leans toward the pointer with growing resistance, never past its limit', () => {
|
||||
expect(leanFor(0)).toBe(0);
|
||||
const small = leanFor(5);
|
||||
const larger = leanFor(40);
|
||||
expect(small).toBeGreaterThan(0);
|
||||
expect(larger).toBeGreaterThan(small);
|
||||
/* Resistance: the second 35px buys less than the first 5px did per px. */
|
||||
expect((larger - small) / 35).toBeLessThan(small / 5);
|
||||
expect(leanFor(10_000)).toBeLessThan(10);
|
||||
expect(leanFor(-40)).toBeCloseTo(-larger);
|
||||
});
|
||||
|
||||
it('shows staged one-shot effort without mutating the conversation', () => {
|
||||
mockPendingOverride = { key: 'reasoning_effort', value: ReasoningEffort.high };
|
||||
renderInComposer();
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ export default function DialogImage({
|
|||
downloadImage,
|
||||
args,
|
||||
triggerRef,
|
||||
showDetails = true,
|
||||
title,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
|
|
@ -36,6 +38,10 @@ export default function DialogImage({
|
|||
[key: string]: unknown;
|
||||
};
|
||||
triggerRef?: React.RefObject<HTMLButtonElement>;
|
||||
/** Off for an uploaded file, which has no generation details to show. */
|
||||
showDetails?: boolean;
|
||||
/** Names the dialog and the image for assistive tech, e.g. the file name. */
|
||||
title?: string;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const [isPromptOpen, setIsPromptOpen] = useState(false);
|
||||
|
|
@ -254,11 +260,11 @@ export default function DialogImage({
|
|||
<DialogPrimitive.Root open={isOpen} onOpenChange={onOpenChange}>
|
||||
<DialogPrimitive.Portal>
|
||||
<DialogPrimitive.Overlay
|
||||
className="fixed inset-0 z-[100] bg-black/90"
|
||||
className="fixed inset-0 z-[250] bg-black/90"
|
||||
onClick={handleBackgroundClick}
|
||||
/>
|
||||
<DialogPrimitive.Content
|
||||
className="fixed inset-0 z-[100] flex items-center justify-center outline-hidden"
|
||||
className="fixed inset-0 z-[250] flex items-center justify-center outline-hidden"
|
||||
onOpenAutoFocus={(e) => {
|
||||
e.preventDefault();
|
||||
closeButtonRef.current?.focus();
|
||||
|
|
@ -270,6 +276,9 @@ export default function DialogImage({
|
|||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onClick={handleBackgroundClick}
|
||||
>
|
||||
{title != null && (
|
||||
<DialogPrimitive.Title className="sr-only">{title}</DialogPrimitive.Title>
|
||||
)}
|
||||
{/* Close button - top left */}
|
||||
<div className="absolute top-4 left-4 z-20">
|
||||
<TooltipAnchor
|
||||
|
|
@ -320,22 +329,24 @@ export default function DialogImage({
|
|||
</Button>
|
||||
}
|
||||
/>
|
||||
<TooltipAnchor
|
||||
description={imageDetailsLabel}
|
||||
render={
|
||||
<Button
|
||||
onClick={() => setIsPromptOpen(!isPromptOpen)}
|
||||
variant="ghost"
|
||||
className="h-10 w-10 p-0 text-white hover:bg-white/10"
|
||||
aria-label={imageDetailsLabel}
|
||||
>
|
||||
<MorphIcon
|
||||
icon={isPromptOpen ? PanelLeftOpen : PanelLeftClose}
|
||||
className="size-5"
|
||||
/>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{showDetails && (
|
||||
<TooltipAnchor
|
||||
description={imageDetailsLabel}
|
||||
render={
|
||||
<Button
|
||||
onClick={() => setIsPromptOpen(!isPromptOpen)}
|
||||
variant="ghost"
|
||||
className="h-10 w-10 p-0 text-white hover:bg-white/10"
|
||||
aria-label={imageDetailsLabel}
|
||||
>
|
||||
<MorphIcon
|
||||
icon={isPromptOpen ? PanelLeftOpen : PanelLeftClose}
|
||||
className="size-5"
|
||||
/>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Image container - centered */}
|
||||
|
|
@ -364,7 +375,7 @@ export default function DialogImage({
|
|||
<img
|
||||
ref={imageRef}
|
||||
src={src}
|
||||
alt="Image"
|
||||
alt={title ?? 'Image'}
|
||||
decoding="async"
|
||||
className="block max-h-[85vh] object-contain"
|
||||
style={{
|
||||
|
|
@ -377,76 +388,80 @@ export default function DialogImage({
|
|||
</div>
|
||||
|
||||
{/* Side Panel */}
|
||||
<div
|
||||
data-side-panel
|
||||
className={`bg-surface-primary fixed top-0 right-0 z-30 h-full w-80 transform border-l border-white/10 shadow-2xl transition-transform duration-300 ${
|
||||
isPromptOpen ? 'translate-x-0' : 'translate-x-full'
|
||||
}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="h-full overflow-y-auto p-6">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-text-primary text-lg font-semibold">
|
||||
{localize('com_ui_image_details')}
|
||||
</h3>
|
||||
<Button
|
||||
onClick={() => setIsPromptOpen(false)}
|
||||
variant="ghost"
|
||||
className="h-10 w-10 p-0 sm:hidden"
|
||||
>
|
||||
<X className="size-5" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="bg-border-medium mb-4 h-px"></div>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Prompt Section */}
|
||||
<div>
|
||||
<h4 className="text-text-primary mb-2 text-sm font-medium">
|
||||
{localize('com_ui_prompt')}
|
||||
</h4>
|
||||
<div className="bg-surface-tertiary rounded-md p-3">
|
||||
<p className="text-text-primary text-sm leading-relaxed">
|
||||
{args?.prompt || 'No prompt available'}
|
||||
</p>
|
||||
</div>
|
||||
{showDetails && (
|
||||
<div
|
||||
data-side-panel
|
||||
className={`bg-surface-primary fixed top-0 right-0 z-30 h-full w-80 transform border-l border-white/10 shadow-2xl transition-transform duration-300 ${
|
||||
isPromptOpen ? 'translate-x-0' : 'translate-x-full'
|
||||
}`}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="h-full overflow-y-auto p-6">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h3 className="text-text-primary text-lg font-semibold">
|
||||
{localize('com_ui_image_details')}
|
||||
</h3>
|
||||
<Button
|
||||
onClick={() => setIsPromptOpen(false)}
|
||||
variant="ghost"
|
||||
className="h-10 w-10 p-0 sm:hidden"
|
||||
>
|
||||
<X className="size-5" aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="bg-border-medium mb-4 h-px"></div>
|
||||
|
||||
{/* Generation Settings */}
|
||||
<div>
|
||||
<h4 className="text-text-primary mb-3 text-sm font-medium">
|
||||
{localize('com_ui_generation_settings')}
|
||||
</h4>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-text-primary text-sm">{localize('com_ui_size')}:</span>
|
||||
<span className="text-text-primary text-sm font-medium">
|
||||
{args?.size || 'Unknown'}
|
||||
</span>
|
||||
<div className="space-y-6">
|
||||
{/* Prompt Section */}
|
||||
<div>
|
||||
<h4 className="text-text-primary mb-2 text-sm font-medium">
|
||||
{localize('com_ui_prompt')}
|
||||
</h4>
|
||||
<div className="bg-surface-tertiary rounded-md p-3">
|
||||
<p className="text-text-primary text-sm leading-relaxed">
|
||||
{args?.prompt || 'No prompt available'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-text-primary text-sm">
|
||||
{localize('com_ui_quality')}:
|
||||
</span>
|
||||
<span
|
||||
className={`rounded px-2 py-1 text-xs font-medium capitalize ${getQualityStyles(args?.quality || '')}`}
|
||||
>
|
||||
{args?.quality || 'Standard'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-text-primary text-sm">
|
||||
{localize('com_ui_file_size')}:
|
||||
</span>
|
||||
<span className="text-text-primary text-sm font-medium">
|
||||
{imageSize || 'Loading...'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Generation Settings */}
|
||||
<div>
|
||||
<h4 className="text-text-primary mb-3 text-sm font-medium">
|
||||
{localize('com_ui_generation_settings')}
|
||||
</h4>
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-text-primary text-sm">
|
||||
{localize('com_ui_size')}:
|
||||
</span>
|
||||
<span className="text-text-primary text-sm font-medium">
|
||||
{args?.size || 'Unknown'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-text-primary text-sm">
|
||||
{localize('com_ui_quality')}:
|
||||
</span>
|
||||
<span
|
||||
className={`rounded px-2 py-1 text-xs font-medium capitalize ${getQualityStyles(args?.quality || '')}`}
|
||||
>
|
||||
{args?.quality || 'Standard'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-text-primary text-sm">
|
||||
{localize('com_ui_file_size')}:
|
||||
</span>
|
||||
<span className="text-text-primary text-sm font-medium">
|
||||
{imageSize || 'Loading...'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPrimitive.Portal>
|
||||
</DialogPrimitive.Root>
|
||||
|
|
|
|||
|
|
@ -42,10 +42,12 @@ interface FilePreviewDialogProps {
|
|||
fileSource?: string;
|
||||
fileSize?: number;
|
||||
deliveryPath?: TFile['llmDeliveryPath'];
|
||||
/** Where focus returns on close when the dialog is opened without a trigger. */
|
||||
triggerRef?: React.RefObject<HTMLElement | null>;
|
||||
}
|
||||
|
||||
/** Formats bytes with unit suffix (differs from ~/utils/formatBytes which returns a raw number). */
|
||||
function formatBytes(bytes: number): string {
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes >= 1048576) {
|
||||
return `${(bytes / 1048576).toFixed(1)} MB`;
|
||||
}
|
||||
|
|
@ -55,25 +57,31 @@ function formatBytes(bytes: number): string {
|
|||
return `${bytes} B`;
|
||||
}
|
||||
|
||||
function getDisplayType(fileType?: string, fileName?: string): string {
|
||||
/** A file's kind for display: acronyms and extensions as they are, words
|
||||
* through the locale. */
|
||||
export function getDisplayType(
|
||||
localize: ReturnType<typeof useLocalize>,
|
||||
fileType?: string,
|
||||
fileName?: string,
|
||||
): string {
|
||||
if (fileType) {
|
||||
if (fileType.includes('pdf')) {
|
||||
return 'PDF';
|
||||
}
|
||||
if (fileType.includes('word') || fileType.includes('document')) {
|
||||
return 'Document';
|
||||
return localize('com_ui_file_type_document');
|
||||
}
|
||||
if (fileType.includes('spreadsheet') || fileType.includes('excel')) {
|
||||
return 'Spreadsheet';
|
||||
return localize('com_ui_file_type_spreadsheet');
|
||||
}
|
||||
if (fileType.includes('presentation') || fileType.includes('powerpoint')) {
|
||||
return 'Presentation';
|
||||
return localize('com_ui_file_type_presentation');
|
||||
}
|
||||
if (fileType.includes('image')) {
|
||||
return 'Image';
|
||||
return localize('com_ui_file_type_image');
|
||||
}
|
||||
if (fileType.startsWith('text/')) {
|
||||
return fileType.split('/')[1]?.toUpperCase() || 'Text';
|
||||
return fileType.split('/')[1]?.toUpperCase() || localize('com_ui_file_type_text');
|
||||
}
|
||||
if (fileType.includes('json')) {
|
||||
return 'JSON';
|
||||
|
|
@ -83,7 +91,7 @@ function getDisplayType(fileType?: string, fileName?: string): string {
|
|||
}
|
||||
}
|
||||
const ext = fileName ? getFileExtension(fileName) : '';
|
||||
return ext ? ext.toUpperCase() : 'File';
|
||||
return ext ? ext.toUpperCase() : localize('com_ui_file');
|
||||
}
|
||||
|
||||
export default function FilePreviewDialog({
|
||||
|
|
@ -98,6 +106,7 @@ export default function FilePreviewDialog({
|
|||
fileSource,
|
||||
fileSize,
|
||||
deliveryPath,
|
||||
triggerRef,
|
||||
}: FilePreviewDialogProps) {
|
||||
const localize = useLocalize();
|
||||
const user = useRecoilValue(store.user);
|
||||
|
|
@ -231,7 +240,10 @@ export default function FilePreviewDialog({
|
|||
setTimeout(() => setIsCopied(false), 3000);
|
||||
}, [displayedText]);
|
||||
|
||||
const displayType = useMemo(() => getDisplayType(fileType, fileName), [fileType, fileName]);
|
||||
const displayType = useMemo(
|
||||
() => getDisplayType(localize, fileType, fileName),
|
||||
[localize, fileType, fileName],
|
||||
);
|
||||
const sortedPages = useMemo(
|
||||
() => (pages && pageRelevance ? sortPagesByRelevance(pages, pageRelevance) : pages),
|
||||
[pages, pageRelevance],
|
||||
|
|
@ -249,7 +261,7 @@ export default function FilePreviewDialog({
|
|||
}
|
||||
|
||||
return (
|
||||
<OGDialog open={open} onOpenChange={onOpenChange}>
|
||||
<OGDialog open={open} onOpenChange={onOpenChange} triggerRef={triggerRef}>
|
||||
<OGDialogContent
|
||||
className="flex w-full max-w-4xl flex-col !overflow-hidden p-0"
|
||||
showCloseButton={true}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Search } from 'lucide-react';
|
||||
import { Skeleton } from '@librechat/client';
|
||||
import type { AgentItem, ItemFilter } from './items/types';
|
||||
import type { AgentItem, ItemFilter, ItemStatus } from './items/types';
|
||||
import type { TranslationKeys } from '~/hooks/useLocalize';
|
||||
import { itemKey } from './items/selectors';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
|
@ -23,6 +23,8 @@ interface MarketplaceCatalogProps {
|
|||
emptyKey?: TranslationKeys;
|
||||
/** Accessible label for the grid; defaults to the marketplace label. */
|
||||
ariaLabel?: string;
|
||||
/** Live state per item, such as an MCP server's connection. */
|
||||
statusFor?: (item: AgentItem) => ItemStatus | undefined;
|
||||
}
|
||||
|
||||
const SKELETON_COUNT = 3;
|
||||
|
|
@ -35,7 +37,7 @@ const EMPTY_COPY_KEYS: Record<View, TranslationKeys> = {
|
|||
|
||||
function ToolCardSkeleton() {
|
||||
return (
|
||||
<div className="flex h-32 w-full flex-col gap-2 rounded-2xl border border-border-light p-4">
|
||||
<div className="border-border-light flex h-32 w-full flex-col gap-2 rounded-2xl border p-4">
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<Skeleton className="h-10 w-10 shrink-0 rounded-xl" />
|
||||
<div className="min-w-0 flex-1 space-y-1.5">
|
||||
|
|
@ -61,15 +63,16 @@ export default function MarketplaceCatalog({
|
|||
onToggleFavorite,
|
||||
emptyKey,
|
||||
ariaLabel,
|
||||
statusFor,
|
||||
}: MarketplaceCatalogProps) {
|
||||
const localize = useLocalize();
|
||||
const showSkeletons = isLoadingSkills && skillsInView;
|
||||
|
||||
if (items.length === 0 && !showSkeletons) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-16 text-center">
|
||||
<Search className="size-8 text-text-tertiary opacity-40" aria-hidden="true" />
|
||||
<p className="mt-3 text-sm text-text-secondary">
|
||||
<div role="status" className="flex flex-col items-center justify-center py-16 text-center">
|
||||
<Search className="text-text-tertiary size-8 opacity-40" aria-hidden="true" />
|
||||
<p className="text-text-secondary mt-3 text-sm">
|
||||
{localize(emptyKey ?? EMPTY_COPY_KEYS[view])}
|
||||
</p>
|
||||
</div>
|
||||
|
|
@ -91,6 +94,7 @@ export default function MarketplaceCatalog({
|
|||
onConfigure={onConfigure}
|
||||
isFavorited={favoriteKeys?.has(itemKey(item)) ?? false}
|
||||
onToggleFavorite={onToggleFavorite}
|
||||
status={statusFor?.(item)}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { memo, useState } from 'react';
|
|||
import { VerifiedIcon } from '@librechat/client';
|
||||
import { Check, Globe, Info, Settings, Star, User } from 'lucide-react';
|
||||
import type { TranslationKeys } from '~/hooks/useLocalize';
|
||||
import type { AgentItem } from './items/types';
|
||||
import type { AgentItem, ItemStatus } from './items/types';
|
||||
import { hasConfigurableSettings } from './items/configurable';
|
||||
import { useLocalize, useAuthContext } from '~/hooks';
|
||||
import { getIconForItem } from './items/icons';
|
||||
|
|
@ -15,6 +15,9 @@ interface ToolCardProps {
|
|||
onConfigure?: (item: AgentItem) => void;
|
||||
isFavorited?: boolean;
|
||||
onToggleFavorite?: (item: AgentItem) => void;
|
||||
/** A live state, such as an MCP server's connection, shown in place of the
|
||||
* kind label, which is redundant wherever every card shares one kind. */
|
||||
status?: ItemStatus;
|
||||
}
|
||||
|
||||
function useDisplayStrings(item: AgentItem): { name: string; description: string } {
|
||||
|
|
@ -86,6 +89,7 @@ function ToolCardImpl({
|
|||
onConfigure,
|
||||
isFavorited = false,
|
||||
onToggleFavorite,
|
||||
status,
|
||||
}: ToolCardProps) {
|
||||
const localize = useLocalize();
|
||||
const { name, description } = useDisplayStrings(item);
|
||||
|
|
@ -148,9 +152,19 @@ function ToolCardImpl({
|
|||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-text-secondary truncate text-[11px] tracking-wide uppercase">
|
||||
{kindLabel}
|
||||
</p>
|
||||
{status != null ? (
|
||||
<p className="text-text-secondary flex min-w-0 items-center gap-1.5 text-xs">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn('size-2 shrink-0 rounded-full', status.tone)}
|
||||
/>
|
||||
<span className="truncate">{status.label}</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-text-secondary truncate text-[11px] tracking-wide uppercase">
|
||||
{kindLabel}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{description ? (
|
||||
|
|
|
|||
|
|
@ -80,6 +80,13 @@ export interface ActionItem extends ItemBase {
|
|||
|
||||
export type AgentItem = BuiltinItem | ToolItem | McpItem | SkillItem | ActionItem;
|
||||
|
||||
/** A live state shown beside an item, such as an MCP server's connection. */
|
||||
export interface ItemStatus {
|
||||
label: string;
|
||||
/** Semantic `bg-status-*` fill for the dot that accompanies the label. */
|
||||
tone: string;
|
||||
}
|
||||
|
||||
export type ItemFilter = {
|
||||
search?: string;
|
||||
kind?: AgentItemKind | 'all';
|
||||
|
|
|
|||
27
client/src/hooks/Input/__tests__/useAudioLevels.spec.ts
Normal file
27
client/src/hooks/Input/__tests__/useAudioLevels.spec.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { frameLevel } from '../useAudioLevels';
|
||||
|
||||
/** A time-domain frame of a sine at the given peak amplitude (0-1). */
|
||||
const sine = (amplitude: number, length = 1024) =>
|
||||
Uint8Array.from({ length }, (_, i) =>
|
||||
Math.round(128 + 127 * amplitude * Math.sin((2 * Math.PI * i) / 64)),
|
||||
);
|
||||
|
||||
describe('frameLevel', () => {
|
||||
it('reads silence as an empty bar', () => {
|
||||
expect(frameLevel(new Uint8Array(1024).fill(128))).toBe(0);
|
||||
expect(frameLevel(new Uint8Array(0))).toBe(0);
|
||||
});
|
||||
|
||||
it('draws ordinary speech mid-range rather than as a dot', () => {
|
||||
/* Conversational speech peaks around 3-10% of full scale. */
|
||||
const quiet = frameLevel(sine(0.03));
|
||||
const normal = frameLevel(sine(0.1));
|
||||
expect(quiet).toBeGreaterThan(0.3);
|
||||
expect(normal).toBeGreaterThan(quiet);
|
||||
expect(normal).toBeLessThan(1);
|
||||
});
|
||||
|
||||
it('saturates at full scale without exceeding it', () => {
|
||||
expect(frameLevel(sine(1))).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,15 +1,52 @@
|
|||
import { useRef, useState, useEffect } from 'react';
|
||||
import { useRef, useEffect, useCallback } from 'react';
|
||||
|
||||
/** Bars kept on screen; the newest sample is appended and the oldest drops.
|
||||
* Sized for a waveform spanning the composer rather than a small pill. */
|
||||
const BAR_COUNT = 96;
|
||||
/** Sampling cadence. Fast enough to feel live, slow enough not to thrash. */
|
||||
const SAMPLE_MS = 55;
|
||||
|
||||
const SILENT: number[] = new Array(BAR_COUNT).fill(0);
|
||||
/** Loudness that draws an empty bar, and loudness that draws a full one. Room
|
||||
* noise sits near the floor and ordinary speech lands mid-range, which a
|
||||
* linear scale could not do: speech is a few percent of full scale. */
|
||||
const FLOOR_DB = -55;
|
||||
const CEILING_DB = -12;
|
||||
|
||||
/**
|
||||
* Rolling loudness history of the microphone, for drawing a live waveform.
|
||||
* The visualiser's microphone is left unprocessed. Automatic gain starts low
|
||||
* and ramps over the first seconds, which drew the opening words as a flat
|
||||
* line, and noise suppression holds back speech while it learns the room. The
|
||||
* recording sent for transcription opens its own stream with its own settings.
|
||||
*/
|
||||
const RAW_AUDIO: MediaTrackConstraints = {
|
||||
autoGainControl: false,
|
||||
noiseSuppression: false,
|
||||
echoCancellation: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Loudness of one time-domain frame on a 0-1 scale. RMS around the 128
|
||||
* midpoint, then decibels, because hearing is logarithmic and a linear mapping
|
||||
* left speech drawn as a row of dots.
|
||||
*/
|
||||
export function frameLevel(buffer: Uint8Array): number {
|
||||
if (buffer.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
let sum = 0;
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
const deviation = (buffer[i] - 128) / 128;
|
||||
sum += deviation * deviation;
|
||||
}
|
||||
const rms = Math.sqrt(sum / buffer.length);
|
||||
const db = 20 * Math.log10(Math.max(rms, 1e-6));
|
||||
return Math.min(1, Math.max(0, (db - FLOOR_DB) / (CEILING_DB - FLOOR_DB)));
|
||||
}
|
||||
|
||||
interface Tap {
|
||||
analyser: AnalyserNode;
|
||||
buffer: Uint8Array<ArrayBuffer>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The microphone's current loudness, read on demand. Returns a reader rather
|
||||
* than a stream of values so the caller samples on its own animation frame and
|
||||
* nothing re-renders per sample; the reader answers `null` until the
|
||||
* microphone is open.
|
||||
*
|
||||
* Deliberately opens its own stream rather than reaching into the speech hooks:
|
||||
* the browser and external transcription paths are completely different (the
|
||||
|
|
@ -17,27 +54,23 @@ const SILENT: number[] = new Array(BAR_COUNT).fill(0);
|
|||
* interfering with either. The stream is torn down the moment `active` goes
|
||||
* false, so the recording indicator does not linger.
|
||||
*/
|
||||
export default function useAudioLevels(active: boolean): number[] {
|
||||
const [levels, setLevels] = useState<number[]>(SILENT);
|
||||
const levelsRef = useRef<number[]>(SILENT);
|
||||
export default function useAudioLevels(active: boolean): () => number | null {
|
||||
const tapRef = useRef<Tap | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) {
|
||||
levelsRef.current = SILENT;
|
||||
setLevels(SILENT);
|
||||
return;
|
||||
}
|
||||
|
||||
let stream: MediaStream | undefined;
|
||||
let context: AudioContext | undefined;
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
let cancelled = false;
|
||||
|
||||
const start = async () => {
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
stream = await navigator.mediaDevices.getUserMedia({ audio: RAW_AUDIO });
|
||||
} catch {
|
||||
/* Permission denied or no device: the bar still works, just flat. */
|
||||
/* Permission denied or no device: the trace still draws, just flat. */
|
||||
return;
|
||||
}
|
||||
if (cancelled) {
|
||||
|
|
@ -46,40 +79,34 @@ export default function useAudioLevels(active: boolean): number[] {
|
|||
}
|
||||
|
||||
context = new AudioContext();
|
||||
/* Created after the permission prompt resolved, which is outside the click
|
||||
that started recording, so the browser may hand it over suspended; a
|
||||
suspended graph reads as silence forever. */
|
||||
if (context.state === 'suspended') {
|
||||
void context.resume();
|
||||
}
|
||||
const analyser = context.createAnalyser();
|
||||
analyser.fftSize = 1024;
|
||||
context.createMediaStreamSource(stream).connect(analyser);
|
||||
const buffer = new Uint8Array(analyser.frequencyBinCount);
|
||||
|
||||
timer = setInterval(() => {
|
||||
analyser.getByteTimeDomainData(buffer);
|
||||
/* RMS around the 128 midpoint, scaled so ordinary speech lands near the
|
||||
top of the range without clipping every bar to full height. */
|
||||
let sum = 0;
|
||||
for (let i = 0; i < buffer.length; i++) {
|
||||
const deviation = (buffer[i] - 128) / 128;
|
||||
sum += deviation * deviation;
|
||||
}
|
||||
const rms = Math.sqrt(sum / buffer.length);
|
||||
const level = Math.min(1, rms * 3.2);
|
||||
levelsRef.current = [...levelsRef.current.slice(1), level];
|
||||
setLevels(levelsRef.current);
|
||||
}, SAMPLE_MS);
|
||||
tapRef.current = { analyser, buffer: new Uint8Array(analyser.fftSize) };
|
||||
};
|
||||
|
||||
void start();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (timer != null) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
tapRef.current = null;
|
||||
stream?.getTracks().forEach((track) => track.stop());
|
||||
void context?.close();
|
||||
};
|
||||
}, [active]);
|
||||
|
||||
return levels;
|
||||
return useCallback(() => {
|
||||
const tap = tapRef.current;
|
||||
if (tap == null) {
|
||||
return null;
|
||||
}
|
||||
tap.analyser.getByteTimeDomainData(tap.buffer);
|
||||
return frameLevel(tap.buffer);
|
||||
}, []);
|
||||
}
|
||||
|
||||
export { BAR_COUNT };
|
||||
|
|
|
|||
|
|
@ -15,13 +15,17 @@ import {
|
|||
AuthType,
|
||||
Permissions,
|
||||
ArtifactModes,
|
||||
PermissionBits,
|
||||
PermissionTypes,
|
||||
hasPermissions,
|
||||
SkillsScope,
|
||||
isEphemeralAgentId,
|
||||
defaultAgentCapabilities,
|
||||
resolveAgentSkillsScope,
|
||||
} from 'librechat-data-provider';
|
||||
import type { TSkillSummary, TToolFavoriteType } from 'librechat-data-provider';
|
||||
import type { ItemStatus } from '~/components/SidePanel/Agents/Tools/items/types';
|
||||
import type { TranslationKeys } from '~/hooks/useLocalize';
|
||||
import {
|
||||
useHasAccess,
|
||||
useAuthContext,
|
||||
|
|
@ -29,6 +33,7 @@ import {
|
|||
useAgentCapabilities,
|
||||
useSkillActiveState,
|
||||
} from '~/hooks';
|
||||
import { getStatusColor, getStatusTextKey } from '~/components/MCP/mcpServerUtils';
|
||||
import { filterSkillsForPopover } from '~/components/Chat/Input/SkillsCommand';
|
||||
import { useAgentsMapContext, useBadgeRowContext } from '~/Providers';
|
||||
import { useSkillsInfiniteQuery } from '~/data-provider';
|
||||
|
|
@ -73,6 +78,15 @@ export interface PaletteEntry {
|
|||
/** Refinements of this tool, rendered as inline pills on the row while it is
|
||||
* on. Not separately favouritable: they only exist within the parent. */
|
||||
modes?: PaletteMode[];
|
||||
/** The catalog record behind a skill row, for the "Show all" dialog's card. */
|
||||
skill?: TSkillSummary;
|
||||
/** A server's own branding, for the "Show all" dialog's card. */
|
||||
iconUrl?: string;
|
||||
/** Authored (skill) or owned (MCP server) by the signed-in user, for the
|
||||
* "Show all" dialog's "Made by you" view. */
|
||||
ownedByUser?: boolean;
|
||||
/** Connection state of an MCP server, drawn on the row and its card. */
|
||||
status?: ItemStatus;
|
||||
}
|
||||
|
||||
/** Accumulates skill pages so client-side search covers the full catalog. */
|
||||
|
|
@ -440,6 +454,8 @@ export default function usePaletteEntries({
|
|||
active: staged.has(skill.name),
|
||||
pinned: false,
|
||||
onSelect: () => toggleSkill(skill.name),
|
||||
skill,
|
||||
ownedByUser: user?.id != null && skill.author === user.id,
|
||||
});
|
||||
}
|
||||
/* Skills staged by name (the slash command, or a draft restored before
|
||||
|
|
@ -470,8 +486,21 @@ export default function usePaletteEntries({
|
|||
toggleServerSelection,
|
||||
connectionStatus,
|
||||
initializeServer,
|
||||
isInitializing,
|
||||
getServerStatusIconProps,
|
||||
} = mcpServerManager ?? {};
|
||||
/* The same vocabulary as the MCP menu this palette replaced. Its
|
||||
"connecting" string takes the server name, which the row already shows. */
|
||||
const getServerStatus = (serverName: string): ItemStatus => {
|
||||
const key = getStatusTextKey(serverName, connectionStatus, isInitializing);
|
||||
return {
|
||||
label:
|
||||
key === 'com_nav_mcp_status_connecting'
|
||||
? localize('com_ui_connecting')
|
||||
: localize(key as TranslationKeys),
|
||||
tone: getStatusColor(serverName, connectionStatus, isInitializing),
|
||||
};
|
||||
};
|
||||
if (toolsEnabled && canUseMcp && selectableServers) {
|
||||
const selected = new Set(mcpValues ?? []);
|
||||
const syntheticClick = {
|
||||
|
|
@ -564,6 +593,11 @@ export default function usePaletteEntries({
|
|||
pinned: false,
|
||||
onSelect: selectServer,
|
||||
modes: getServerModes(),
|
||||
iconUrl: server.config?.iconPath,
|
||||
/* Only the owner role carries Share, so it separates a server this
|
||||
user made from one merely shared with them. */
|
||||
ownedByUser: hasPermissions(server.effectivePermissions, PermissionBits.SHARE),
|
||||
status: getServerStatus(server.serverName),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -591,5 +625,6 @@ export default function usePaletteEntries({
|
|||
artifactsEnabled,
|
||||
canUseFileSearch,
|
||||
fileSearchEnabled,
|
||||
user?.id,
|
||||
]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1304,6 +1304,9 @@
|
|||
"com_ui_composer_effort_faster": "Faster",
|
||||
"com_ui_composer_effort_smarter": "Smarter",
|
||||
"com_ui_composer_files": "Your files",
|
||||
"com_ui_composer_files_documents": "Documents",
|
||||
"com_ui_composer_files_filter": "Filter files",
|
||||
"com_ui_composer_files_images": "Images",
|
||||
"com_ui_composer_hint_answer": "Answering. Esc to dismiss",
|
||||
"com_ui_composer_hint_attach": "+ to attach",
|
||||
"com_ui_composer_hint_interrupt": "interrupt & send",
|
||||
|
|
@ -1323,10 +1326,17 @@
|
|||
"com_ui_composer_hint_uploading": "Uploading {{count}} files…",
|
||||
"com_ui_composer_hint_uploading_one": "Uploading {{count}} file…",
|
||||
"com_ui_composer_mcp": "MCP Servers",
|
||||
"com_ui_composer_mcp_filter": "Filter MCP servers",
|
||||
"com_ui_composer_no_results": "No matches",
|
||||
"com_ui_composer_palette": "Attach and tools",
|
||||
"com_ui_composer_palette_help": "Use the arrow keys to browse, Enter to select, and {{0}}+D to favorite.",
|
||||
"com_ui_composer_palette_search": "Search tools, skills and servers",
|
||||
"com_ui_composer_preview_failed": "Couldn't load a preview of {{0}}",
|
||||
"com_ui_composer_preview_file": "Preview {{0}}",
|
||||
"com_ui_composer_search_files": "Search files",
|
||||
"com_ui_composer_search_mcp": "Search MCP servers",
|
||||
"com_ui_composer_search_skills": "Search skills",
|
||||
"com_ui_composer_show_all_label": "Show all {{0}}",
|
||||
"com_ui_composer_staged_context": "Staged context",
|
||||
"com_ui_composer_thinking": "Thinking",
|
||||
"com_ui_composer_thinking_value": "Thinking: {{0}}",
|
||||
|
|
@ -1630,6 +1640,11 @@
|
|||
"com_ui_file_size": "File Size",
|
||||
"com_ui_file_token_limit": "File Token Limit",
|
||||
"com_ui_file_token_limit_desc": "Set maximum token limit for file processing to control costs and resource usage",
|
||||
"com_ui_file_type_document": "Document",
|
||||
"com_ui_file_type_image": "Image",
|
||||
"com_ui_file_type_presentation": "Presentation",
|
||||
"com_ui_file_type_spreadsheet": "Spreadsheet",
|
||||
"com_ui_file_type_text": "Text",
|
||||
"com_ui_filter": "Filter",
|
||||
"com_ui_filter_and_sort_chats": "Filter and sort chats",
|
||||
"com_ui_filter_by": "Filter by {{title}}",
|
||||
|
|
|
|||
|
|
@ -2657,9 +2657,102 @@ html[data-input-modality='keyboard']
|
|||
scrollbar-color: rgb(var(--border-medium) / var(--border-medium-alpha, 1)) transparent;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
/**
|
||||
* The thinking-level slider's stops. Position and size glide on a spring with a
|
||||
* slight overshoot, so the thumb and the fill settle onto a stop rather than
|
||||
* stopping dead; both share the curve, so the fill's end stays under the thumb
|
||||
* throughout. Custom CSS because the overshoot curve has no theme token.
|
||||
*/
|
||||
.composer-effort-glide {
|
||||
transition-property: left, width, height;
|
||||
transition-duration: 280ms;
|
||||
transition-timing-function: cubic-bezier(0.34, 1.36, 0.64, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* The held thumb leaning toward the pointer (set on the track as
|
||||
* `--effort-lean`, stretched along the pull and squashed across it). It tracks
|
||||
* the pointer directly while held and springs back on release.
|
||||
*/
|
||||
.composer-effort-thumb {
|
||||
transform: translateX(var(--effort-lean, 0px))
|
||||
scale(var(--effort-stretch, 1), var(--effort-squash, 1));
|
||||
transition: transform 320ms cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
}
|
||||
.composer-effort-thumb[data-dragging] {
|
||||
transition-duration: 60ms;
|
||||
transition-timing-function: linear;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fill follows the thumb's lean, so pulling toward a higher level stretches
|
||||
* the fill along with the thumb instead of leaving its end behind, uncovered,
|
||||
* as the thumb leans away. Same clocks as the thumb.
|
||||
*/
|
||||
.composer-effort-fill {
|
||||
width: calc(100% + var(--effort-lean, 0px));
|
||||
transition:
|
||||
width 320ms cubic-bezier(0.34, 1.56, 0.64, 1),
|
||||
opacity 100ms ease-out;
|
||||
}
|
||||
.composer-effort-fill[data-dragging] {
|
||||
transition:
|
||||
width 60ms linear,
|
||||
opacity 100ms ease-out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The thinking button's label changing level: the old word blurs out in the
|
||||
* direction of the change while the new one arrives from the other side,
|
||||
* overlapping it briefly, like an odometer. `-up` for a higher level.
|
||||
*/
|
||||
@keyframes composer-label-out-up {
|
||||
to {
|
||||
transform: translateY(-70%);
|
||||
opacity: 0;
|
||||
filter: blur(3px);
|
||||
}
|
||||
}
|
||||
@keyframes composer-label-out-down {
|
||||
to {
|
||||
transform: translateY(70%);
|
||||
opacity: 0;
|
||||
filter: blur(3px);
|
||||
}
|
||||
}
|
||||
@keyframes composer-label-in-up {
|
||||
from {
|
||||
transform: translateY(70%);
|
||||
opacity: 0;
|
||||
filter: blur(3px);
|
||||
}
|
||||
}
|
||||
@keyframes composer-label-in-down {
|
||||
from {
|
||||
transform: translateY(-70%);
|
||||
opacity: 0;
|
||||
filter: blur(3px);
|
||||
}
|
||||
}
|
||||
.composer-label-out-up {
|
||||
animation: composer-label-out-up 220ms cubic-bezier(0.32, 0.72, 0, 1) forwards;
|
||||
}
|
||||
.composer-label-out-down {
|
||||
animation: composer-label-out-down 220ms cubic-bezier(0.32, 0.72, 0, 1) forwards;
|
||||
}
|
||||
.composer-label-in-up {
|
||||
animation: composer-label-in-up 280ms cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
.composer-label-in-down {
|
||||
animation: composer-label-in-down 280ms cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
|
||||
/** Trigger glyphs that turn as their popover opens, on the same curve. */
|
||||
.animate-composer-icon {
|
||||
transition: transform 260ms cubic-bezier(0.32, 0.72, 0, 1);
|
||||
/* Tailwind v4's rotate-* utilities set `rotate`, not `transform`. */
|
||||
transition-property: transform, rotate;
|
||||
transition-duration: 260ms;
|
||||
transition-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -2710,11 +2803,18 @@ html[data-input-modality='keyboard']
|
|||
.animate-composer-popover[data-leave],
|
||||
.animate-composer-icon,
|
||||
.composer-slot-resize,
|
||||
.composer-effort-glide,
|
||||
.composer-effort-thumb,
|
||||
.composer-effort-fill,
|
||||
.composer-palette-rows .ReactVirtualized__Grid {
|
||||
transition-duration: 1ms;
|
||||
}
|
||||
.animate-composer-palette-row,
|
||||
.animate-composer-palette-row-out {
|
||||
.animate-composer-palette-row-out,
|
||||
.composer-label-out-up,
|
||||
.composer-label-out-down,
|
||||
.composer-label-in-up,
|
||||
.composer-label-in-down {
|
||||
animation-duration: 1ms;
|
||||
}
|
||||
.animate-composer-popover,
|
||||
|
|
|
|||
448
e2e/specs/mock/scenarios/palette-show-all.spec.ts
Normal file
448
e2e/specs/mock/scenarios/palette-show-all.spec.ts
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
import { expect, test } from '@playwright/test';
|
||||
import type { Locator, Page } from '@playwright/test';
|
||||
import {
|
||||
MOCK_ENDPOINTS,
|
||||
NEW_CHAT_PATH,
|
||||
enableSkills,
|
||||
getAccessToken,
|
||||
requestJson,
|
||||
selectMockEndpoint,
|
||||
uniqueName,
|
||||
} from '../helpers';
|
||||
|
||||
const PALETTE_NAME = 'Attach and tools';
|
||||
const MESSAGE_INPUT_NAME = 'Message input';
|
||||
const SKILL_DESCRIPTION =
|
||||
'Created by palette-show-all.spec.ts for the composer palette Show all coverage.';
|
||||
|
||||
// Valid 16x16 PNG (spec-conformant chunk CRCs, matching the fixture chat.spec.ts uses).
|
||||
const PNG_BASE64 =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAAHUlEQVQ4jWNwaDjwnxLMMGrA/9EwODAaBg3DIgwACY9/HwbtciYAAAAASUVORK5CYII=';
|
||||
|
||||
/** A one-page PDF small enough to inline; the preview only needs it to parse. */
|
||||
const MINIMAL_PDF = [
|
||||
'%PDF-1.4',
|
||||
'1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj',
|
||||
'2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj',
|
||||
'3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 200 200]>>endobj',
|
||||
'trailer<</Root 1 0 R>>',
|
||||
'%%EOF',
|
||||
].join('\n');
|
||||
|
||||
const paletteButton = (page: Page) => page.getByRole('button', { name: PALETTE_NAME, exact: true });
|
||||
const palette = (page: Page) => page.getByRole('dialog', { name: PALETTE_NAME, exact: true });
|
||||
const messageInput = (page: Page) => page.getByRole('textbox', { name: MESSAGE_INPUT_NAME });
|
||||
|
||||
async function gotoMockChat(page: Page) {
|
||||
await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
|
||||
}
|
||||
|
||||
async function useMockEndpoint(page: Page) {
|
||||
await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
|
||||
await expect(messageInput(page)).toBeVisible();
|
||||
}
|
||||
|
||||
async function openPalette(page: Page) {
|
||||
await expect(paletteButton(page)).toBeVisible();
|
||||
await paletteButton(page).click();
|
||||
await expect(palette(page)).toBeVisible();
|
||||
}
|
||||
|
||||
async function openShowAll(page: Page, sectionLabel: string, dialogName: string): Promise<Locator> {
|
||||
const showAllButton = palette(page).getByRole('button', {
|
||||
name: `Show all ${sectionLabel}`,
|
||||
exact: true,
|
||||
});
|
||||
await expect(showAllButton).toBeVisible({ timeout: 20000 });
|
||||
await showAllButton.click();
|
||||
const dialog = page.getByRole('dialog', { name: dialogName, exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(palette(page)).toBeHidden();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
async function closeShowAll(page: Page, dialog: Locator) {
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(dialog).toBeHidden();
|
||||
}
|
||||
|
||||
type SkillSummary = { _id: string; name: string; description: string };
|
||||
|
||||
async function createSkill(page: Page, token: string, name: string): Promise<SkillSummary> {
|
||||
return requestJson<SkillSummary>(page, {
|
||||
path: '/api/skills',
|
||||
token,
|
||||
method: 'POST',
|
||||
body: {
|
||||
name,
|
||||
description: SKILL_DESCRIPTION,
|
||||
body: `# ${name}\n\nUsed by palette-show-all.spec.ts.`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function createSkills(
|
||||
page: Page,
|
||||
token: string,
|
||||
count: number,
|
||||
prefix: string,
|
||||
): Promise<SkillSummary[]> {
|
||||
const created: SkillSummary[] = [];
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
created.push(await createSkill(page, token, uniqueName(`${prefix}-${index}`)));
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
async function deleteSkills(page: Page, token: string, skillIds: string[]): Promise<void> {
|
||||
const results = await Promise.allSettled(
|
||||
skillIds.map((skillId) =>
|
||||
requestJson(page, {
|
||||
path: `/api/skills/${encodeURIComponent(skillId)}`,
|
||||
token,
|
||||
method: 'DELETE',
|
||||
}),
|
||||
),
|
||||
);
|
||||
const failed = results.find(
|
||||
(result): result is PromiseRejectedResult => result.status === 'rejected',
|
||||
);
|
||||
if (failed) {
|
||||
throw failed.reason;
|
||||
}
|
||||
}
|
||||
|
||||
/** An image upload posts to `/api/files/images` rather than plain `/api/files`
|
||||
* (the client reads its dimensions before choosing the endpoint), so the
|
||||
* match has to cover both rather than the exact-path form the shared
|
||||
* `waitForUpload` helper uses for non-image attachments. */
|
||||
function waitForFilesResponse(page: Page) {
|
||||
return page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/api/files') &&
|
||||
response.request().method() === 'POST' &&
|
||||
response.status() === 200,
|
||||
{ timeout: 30000 },
|
||||
);
|
||||
}
|
||||
|
||||
/** Attaches a file through the palette's unified upload row with a real binary
|
||||
* buffer, so an image fixture is not mangled the way a utf8-decoded string
|
||||
* content would mangle it. */
|
||||
async function uploadFile(
|
||||
page: Page,
|
||||
file: { name: string; mimeType: string; buffer: Buffer },
|
||||
): Promise<void> {
|
||||
const uploadResponse = waitForFilesResponse(page);
|
||||
await openPalette(page);
|
||||
const sourceRow = palette(page).getByRole('button', {
|
||||
name: /^(From Local Computer|Upload to Provider)$/,
|
||||
});
|
||||
await expect(sourceRow).toBeVisible();
|
||||
const [fileChooser] = await Promise.all([page.waitForEvent('filechooser'), sourceRow.click()]);
|
||||
await fileChooser.setFiles(file);
|
||||
await uploadResponse;
|
||||
await expect(palette(page)).toBeHidden();
|
||||
}
|
||||
|
||||
test.describe('composer palette show all', () => {
|
||||
test('caps long sections with Show all and leaves Tools uncapped @scenario:palette-caps-long-sections-with-show-all', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60000);
|
||||
await gotoMockChat(page);
|
||||
const token = await getAccessToken(page);
|
||||
const prefix = uniqueName('palette-cap');
|
||||
const skills = await createSkills(page, token, 6, prefix);
|
||||
|
||||
try {
|
||||
await useMockEndpoint(page);
|
||||
await enableSkills(page);
|
||||
await openPalette(page);
|
||||
|
||||
const skillsHeader = palette(page).getByRole('columnheader', { name: 'Skills', exact: true });
|
||||
await expect(skillsHeader).toBeVisible({ timeout: 20000 });
|
||||
const skillRows = palette(page).locator('[data-row-key^="skill:"]');
|
||||
await expect(skillRows).toHaveCount(5, { timeout: 20000 });
|
||||
await expect(
|
||||
palette(page).getByRole('button', { name: 'Show all Skills', exact: true }),
|
||||
).toBeVisible();
|
||||
|
||||
await expect(
|
||||
palette(page).getByRole('columnheader', { name: 'Tools', exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
palette(page).getByRole('button', { name: 'Show all Tools', exact: true }),
|
||||
).toHaveCount(0);
|
||||
} finally {
|
||||
await deleteSkills(
|
||||
page,
|
||||
token,
|
||||
skills.map((skill) => skill._id),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('show all skills dialog searches, filters by ownership and toggles a skill @scenario:show-all-skills-searches-and-toggles', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60000);
|
||||
await gotoMockChat(page);
|
||||
const token = await getAccessToken(page);
|
||||
const prefix = uniqueName('palette-search');
|
||||
const skills = await createSkills(page, token, 6, prefix);
|
||||
const target = skills[0];
|
||||
|
||||
try {
|
||||
await useMockEndpoint(page);
|
||||
await enableSkills(page);
|
||||
await openPalette(page);
|
||||
|
||||
const dialog = await openShowAll(page, 'Skills', 'Skills');
|
||||
const list = dialog.getByRole('list', { name: 'Skills', exact: true });
|
||||
await expect
|
||||
.poll(() => list.getByRole('listitem').count(), { timeout: 20000 })
|
||||
.toBeGreaterThan(5);
|
||||
|
||||
const search = dialog.getByRole('searchbox', { name: 'Search skills', exact: true });
|
||||
await search.fill(target.name);
|
||||
await expect(list.getByRole('listitem')).toHaveCount(1);
|
||||
|
||||
const card = dialog.getByRole('button', { name: target.name });
|
||||
await expect(card).toBeVisible();
|
||||
await expect(card).toHaveAttribute('aria-pressed', 'false');
|
||||
|
||||
const filter = dialog.getByRole('radiogroup', { name: 'Filter skills', exact: true });
|
||||
await filter.getByRole('radio', { name: 'Made by you', exact: true }).click();
|
||||
await expect(card).toBeVisible();
|
||||
|
||||
/* An empty result is announced from the search field, not only drawn. */
|
||||
await search.fill(`${prefix}-nothing-matches`);
|
||||
await expect(dialog.getByRole('status').filter({ hasText: 'No matches' })).toBeVisible();
|
||||
await search.fill(target.name);
|
||||
|
||||
await card.click();
|
||||
await expect(card).toHaveAttribute('aria-pressed', 'true');
|
||||
/* Individual skill selections stage as a "Staged context" chip in the
|
||||
* tray (`composer-chip-skill`), not the bar's active-builtin row: the
|
||||
* bar's chip row explicitly excludes the skill section. */
|
||||
await expect(
|
||||
page.getByTestId('composer-chip-skill').filter({ hasText: target.name }),
|
||||
).toBeVisible();
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(messageInput(page)).toBeFocused();
|
||||
} finally {
|
||||
await deleteSkills(
|
||||
page,
|
||||
token,
|
||||
skills.map((skill) => skill._id),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('show all files dialog filters by kind, searches and attaches a document @scenario:show-all-files-filters-and-attaches', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60000);
|
||||
await gotoMockChat(page);
|
||||
await useMockEndpoint(page);
|
||||
|
||||
const imageName = `${uniqueName('palette-image')}.png`;
|
||||
const docName = `${uniqueName('palette-doc')}.txt`;
|
||||
await uploadFile(page, {
|
||||
name: imageName,
|
||||
mimeType: 'image/png',
|
||||
buffer: Buffer.from(PNG_BASE64, 'base64'),
|
||||
});
|
||||
await uploadFile(page, {
|
||||
name: docName,
|
||||
mimeType: 'text/plain',
|
||||
buffer: Buffer.from('Composer palette Show all files coverage.\n', 'utf8'),
|
||||
});
|
||||
|
||||
await openPalette(page);
|
||||
const dialog = await openShowAll(page, 'Your files', 'Your files');
|
||||
const views = dialog.getByRole('radiogroup', { name: 'Filter files', exact: true });
|
||||
|
||||
await views.getByRole('radio', { name: 'Images', exact: true }).click();
|
||||
await expect(dialog.locator('li', { hasText: imageName })).toHaveCount(1);
|
||||
await expect(dialog.locator('li', { hasText: docName })).toHaveCount(0);
|
||||
|
||||
await views.getByRole('radio', { name: 'Documents', exact: true }).click();
|
||||
await expect(dialog.locator('li', { hasText: docName })).toHaveCount(1);
|
||||
await expect(dialog.locator('li', { hasText: imageName })).toHaveCount(0);
|
||||
|
||||
await views.getByRole('radio', { name: 'All', exact: true }).click();
|
||||
const search = dialog.getByRole('searchbox', { name: 'Search files', exact: true });
|
||||
await search.fill(docName);
|
||||
await expect(dialog.locator('li', { hasText: docName })).toHaveCount(1);
|
||||
await expect(dialog.locator('li', { hasText: imageName })).toHaveCount(0);
|
||||
|
||||
await dialog.locator('li', { hasText: docName }).getByRole('button').first().click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(
|
||||
page.getByTestId('composer-tray').getByRole('button', { name: docName, exact: true }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test('previews an image over the show all files dialog @scenario:show-all-files-previews-image-over-dialog', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60000);
|
||||
await gotoMockChat(page);
|
||||
await useMockEndpoint(page);
|
||||
|
||||
const imageName = `${uniqueName('palette-preview')}.png`;
|
||||
await uploadFile(page, {
|
||||
name: imageName,
|
||||
mimeType: 'image/png',
|
||||
buffer: Buffer.from(PNG_BASE64, 'base64'),
|
||||
});
|
||||
|
||||
await openPalette(page);
|
||||
const dialog = await openShowAll(page, 'Your files', 'Your files');
|
||||
|
||||
const previewButton = dialog.getByRole('button', {
|
||||
name: `Preview ${imageName}`,
|
||||
exact: true,
|
||||
});
|
||||
await expect(previewButton).toBeVisible();
|
||||
await previewButton.click();
|
||||
|
||||
/* The image viewer is a second, unnamed dialog portalled on top of the
|
||||
* "Your files" dialog. Its Download control is unique to it, which is
|
||||
* what tells the two apart: both would otherwise answer to a bare
|
||||
* `getByRole('dialog')` and to "Close", which the Show all dialog's own
|
||||
* corner button also carries. */
|
||||
const imageDialog = page
|
||||
.getByRole('dialog')
|
||||
.filter({ has: page.getByRole('button', { name: 'Download', exact: true }) });
|
||||
await expect(imageDialog).toBeVisible();
|
||||
/* Named by the file, so a screen reader says which image is open. */
|
||||
await expect(page.getByRole('dialog', { name: imageName, exact: true })).toBeVisible();
|
||||
await expect(imageDialog.getByRole('img', { name: imageName, exact: true })).toBeVisible();
|
||||
await expect(imageDialog.locator('img')).toHaveAttribute('src', /^(blob:|https?:|\/)/);
|
||||
/* An uploaded file has no generation prompt, size or quality to show. */
|
||||
await expect(imageDialog.getByRole('button', { name: /image details/i })).toHaveCount(0);
|
||||
await expect(page.getByText('Image details', { exact: true })).toHaveCount(0);
|
||||
|
||||
const closeButton = imageDialog.getByRole('button', { name: 'Close', exact: true });
|
||||
await expect(closeButton).toBeVisible();
|
||||
await expect(closeButton).toBeEnabled();
|
||||
await closeButton.click();
|
||||
|
||||
await expect(imageDialog).toBeHidden();
|
||||
await expect(dialog).toBeVisible();
|
||||
await expect(previewButton).toBeFocused();
|
||||
|
||||
/* A PDF opens the message file preview instead; closing it by keyboard
|
||||
* returns focus to its own Preview button too. */
|
||||
await closeShowAll(page, dialog);
|
||||
const pdfName = `${uniqueName('palette-preview')}.pdf`;
|
||||
await uploadFile(page, {
|
||||
name: pdfName,
|
||||
mimeType: 'application/pdf',
|
||||
buffer: Buffer.from(MINIMAL_PDF, 'utf8'),
|
||||
});
|
||||
await openPalette(page);
|
||||
const reopened = await openShowAll(page, 'Your files', 'Your files');
|
||||
const pdfPreview = reopened.getByRole('button', { name: `Preview ${pdfName}`, exact: true });
|
||||
await pdfPreview.focus();
|
||||
await page.keyboard.press('Enter');
|
||||
const pdfDialog = page.getByRole('dialog', { name: pdfName, exact: true });
|
||||
await expect(pdfDialog).toBeVisible();
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(pdfDialog).toBeHidden();
|
||||
await expect(reopened).toBeVisible();
|
||||
await expect(pdfPreview).toBeFocused();
|
||||
});
|
||||
|
||||
test.describe('on a touch screen', () => {
|
||||
test.use({ viewport: { width: 390, height: 844 }, hasTouch: true });
|
||||
|
||||
test('closing Show all by tap leaves the keyboard down @scenario:show-all-tap-close-keeps-keyboard-down', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60000);
|
||||
await gotoMockChat(page);
|
||||
await useMockEndpoint(page);
|
||||
|
||||
await paletteButton(page).tap();
|
||||
await expect(palette(page)).toBeVisible();
|
||||
const showAll = palette(page).getByRole('button', { name: /^Show all /, exact: false });
|
||||
await expect(showAll.first()).toBeVisible({ timeout: 20000 });
|
||||
await showAll.first().tap();
|
||||
const dialog = page.getByRole('dialog').filter({ has: page.getByRole('radiogroup') });
|
||||
await expect(dialog).toBeVisible();
|
||||
|
||||
await dialog.getByRole('button', { name: 'Close', exact: true }).tap();
|
||||
await expect(dialog).toBeHidden();
|
||||
/* Focusing the message field would raise the on-screen keyboard. */
|
||||
await expect(messageInput(page)).not.toBeFocused();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('on a phone', () => {
|
||||
test.use({ viewport: { width: 390, height: 844 } });
|
||||
|
||||
test('opens above the composer on mobile @scenario:palette-opens-above-composer-on-mobile', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60000);
|
||||
const width = page.viewportSize()?.width ?? 0;
|
||||
expect(width).toBeLessThan(768);
|
||||
|
||||
await gotoMockChat(page);
|
||||
await useMockEndpoint(page);
|
||||
await openPalette(page);
|
||||
|
||||
const TOLERANCE = 2;
|
||||
const composerBox = await page.locator('[data-testid="composer-surface"]').boundingBox();
|
||||
const paletteBox = await palette(page).boundingBox();
|
||||
expect(composerBox).not.toBeNull();
|
||||
expect(paletteBox).not.toBeNull();
|
||||
|
||||
const viewport = page.viewportSize();
|
||||
expect(viewport).not.toBeNull();
|
||||
|
||||
// Opens upward: the popup's bottom sits at or above the composer's top.
|
||||
expect(paletteBox!.y + paletteBox!.height).toBeLessThanOrEqual(composerBox!.y + TOLERANCE);
|
||||
// Fully on screen.
|
||||
expect(paletteBox!.x).toBeGreaterThanOrEqual(0);
|
||||
expect(paletteBox!.y).toBeGreaterThanOrEqual(0);
|
||||
expect(paletteBox!.x + paletteBox!.width).toBeLessThanOrEqual(viewport!.width + TOLERANCE);
|
||||
expect(paletteBox!.y + paletteBox!.height).toBeLessThanOrEqual(viewport!.height + TOLERANCE);
|
||||
});
|
||||
});
|
||||
|
||||
test('the row highlight resets to the first row on close, not the last one navigated to @scenario:palette-highlight-resets-on-close', async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60000);
|
||||
await gotoMockChat(page);
|
||||
await useMockEndpoint(page);
|
||||
await openPalette(page);
|
||||
|
||||
const search = palette(page).getByRole('combobox');
|
||||
await expect(palette(page).locator('[data-row-key]').first()).toBeVisible();
|
||||
const initialActive = await search.getAttribute('aria-activedescendant');
|
||||
expect(initialActive).not.toBeNull();
|
||||
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
const movedActive = await search.getAttribute('aria-activedescendant');
|
||||
expect(movedActive).not.toBe(initialActive);
|
||||
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(palette(page)).toBeHidden();
|
||||
|
||||
await openPalette(page);
|
||||
await expect(palette(page).locator('[data-row-key]').first()).toBeVisible();
|
||||
const reopenedActive = await search.getAttribute('aria-activedescendant');
|
||||
expect(reopenedActive).toBe(initialActive);
|
||||
expect(reopenedActive).not.toBe(movedActive);
|
||||
});
|
||||
});
|
||||
|
|
@ -5,7 +5,15 @@ import { composerSubmitClasses } from '~/utils/composer';
|
|||
import { cn } from '~/utils';
|
||||
|
||||
type IconButtonVariantProps = {
|
||||
variant?: 'default' | 'primary' | 'secondary' | 'ghost' | 'destructive' | 'submit' | null;
|
||||
variant?:
|
||||
| 'default'
|
||||
| 'primary'
|
||||
| 'secondary'
|
||||
| 'ghost'
|
||||
| 'row-action'
|
||||
| 'destructive'
|
||||
| 'submit'
|
||||
| null;
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg' | 'theme' | null;
|
||||
shape?: 'round' | 'square' | 'theme' | null;
|
||||
};
|
||||
|
|
@ -19,6 +27,9 @@ const iconButtonVariants: (props?: IconButtonVariantProps & ClassProp) => string
|
|||
primary: 'bg-surface-inverted text-text-inverted hover:bg-surface-inverted-hover',
|
||||
secondary: 'border border-border-light bg-surface-secondary hover:bg-surface-hover',
|
||||
ghost: 'bg-transparent hover:bg-surface-hover',
|
||||
/** An action inside a list row whose highlight is already `surface-hover`,
|
||||
* so its own hover takes the active fill to stay visible on top of it. */
|
||||
'row-action': 'bg-transparent hover:bg-surface-active',
|
||||
destructive:
|
||||
'bg-surface-destructive text-text-on-status hover:bg-surface-destructive-hover',
|
||||
/** The composer's submit slot: send, stop and the during-run send share it. */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue