Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🎛 refactor: Replace Agent Skills Toggles With a Three-Way Mode Control (#15520)
Marco Beretta971e076015ca
diff --git a/client/src/components/SidePanel/Agents/AgentSelect.tsx b/client/src/components/SidePanel/Agents/AgentSelect.tsxindex 21190c5f3b..27814c6d0c 100644--- a/client/src/components/SidePanel/Agents/AgentSelect.tsx+++ b/client/src/components/SidePanel/Agents/AgentSelect.tsx@@ -171,11 +171,17 @@ function AgentSelect({* the flag). The builder has no control left for it and the runtime* treats it as "no skills", yet the section would render the selection* as active. Normalize to enabled so the form matches what the UI- * shows and a later save persists the displayed behavior. */+ * shows and a later save persists the displayed behavior.+ *+ * An explicit `skills_scope` is exempt: `none` deliberately keeps the+ * allowlist so returning to `selected` restores it, and flipping the+ * flag there would persist skills-enabled on an agent shown as Off,+ * which `skillDeps` reads as permission to inject authoring tools. */if (Array.isArray(formValues.skills) &&formValues.skills.length > 0 &&- formValues.skills_enabled !== true+ formValues.skills_enabled !== true &&+ formValues.skills_scope === undefined) {formValues.skills_enabled = true;}diff --git a/client/src/components/SidePanel/Agents/Tools/SkillsDialog.tsx b/client/src/components/SidePanel/Agents/Tools/SkillsDialog.tsxindex dbcdc906bc..92e343fd8e 100644--- a/client/src/components/SidePanel/Agents/Tools/SkillsDialog.tsx+++ b/client/src/components/SidePanel/Agents/Tools/SkillsDialog.tsx@@ -19,7 +19,6 @@ import type { AgentItem } from './items/types';import type { AgentForm } from '~/common';import { useLocalize, useHasAccess, useAuthContext, useToolFavorites } from '~/hooks';import { CreateSkillDialog } from '~/components/Skills/dialogs';-import { skillsSelectionTransition } from './items/mutations';import { useSkillsInfiniteQuery } from '~/data-provider';import MarketplaceCatalog from './MarketplaceCatalog';import { CategoryIcon } from '~/components/Prompts';@@ -140,26 +139,14 @@ export default function SkillsDialog({ open, onOpenChange, agentId }: SkillsDial[catalog, search, category, view, favoriteKeys],);+ /** Only the allowlist changes here: the section's mode control owns+ * `skills_enabled` and `skills_scope`, and the picker is reachable only from+ * `selected` mode. */const applySkillsSelection = useCallback((next: string[]) => {setValue('skills', next, { shouldDirty: true });- const transition = skillsSelectionTransition(- next,- getValues('skills_enabled'),- getValues('skill_authoring_enabled'),- getValues('skills_scope'),- );- if (transition.enabled !== undefined) {- setValue('skills_enabled', transition.enabled, { shouldDirty: true });- }- if (transition.authoringEnabled !== undefined) {- setValue('skill_authoring_enabled', transition.authoringEnabled, { shouldDirty: true });- }- if (transition.scope !== undefined) {- setValue('skills_scope', transition.scope, { shouldDirty: true });- }},- [getValues, setValue],+ [setValue],);const handleSkillCreated = useCallback(diff --git a/client/src/components/SidePanel/Agents/Tools/SkillsSection.tsx b/client/src/components/SidePanel/Agents/Tools/SkillsSection.tsxnew file mode 100644index 0000000000..5e961ffe34--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/SkillsSection.tsx@@ -0,0 +1,430 @@+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { Button, Radio } from '@librechat/client';+import { ChevronRight, Plus, X } from 'lucide-react';+import { useFormContext, useWatch } from 'react-hook-form';+import { SkillsScope, resolveAgentSkillsScope } from 'librechat-data-provider';+import type { TSkillSummary } from 'librechat-data-provider';+import type { ReactNode } from 'react';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { AgentItem } from './items/types';+import type { AgentForm } from '~/common';+import { useLocalize, useAuthContext, useSkillActiveState } from '~/hooks';+import { useSkillsInfiniteQuery } from '~/data-provider';+import { buildSkillItems } from './items/catalog';+import { getIconForItem } from './items/icons';+import { cn } from '~/utils';++interface Props {+ /** Selected skills, resolved to catalog items by the parent's shared lookup. */+ items: AgentItem[];+ onInfo: (item: AgentItem) => void;+ onRemove: (item: AgentItem) => void;+ onAdd: () => void;+}++/** Segment order is fixed: least to most exposure. */+const MODES = [SkillsScope.none, SkillsScope.all, SkillsScope.selected] as const;++const MODE_LABELS: Record<SkillsScope, TranslationKeys> = {+ [SkillsScope.none]: 'com_ui_skills_mode_off',+ [SkillsScope.all]: 'com_ui_skills_mode_all',+ [SkillsScope.selected]: 'com_ui_skills_mode_selected',+};++const ROW = 'flex items-center gap-2.5 px-3 py-2.5';+const CHIP = 'flex size-[26px] shrink-0 items-center justify-center rounded-md';++/**+ * Which count phrasing the header row uses.+ *+ * While pages remain the number describes what has been loaded, not a floor on+ * what is available. `hasNextPage` tracks raw pagination, and the rows are+ * filtered to the runtime-active ones, so the later pages may add nothing: 30+ * active skills followed only by deactivated ones would read as "30++ * available" while 30 is the true total. Reporting the loaded count instead+ * cannot overstate the catalog.+ */+function availableCountKey(count: number, hasMore: boolean): TranslationKeys {+ if (hasMore) {+ return count === 1+ ? 'com_ui_skills_available_count_loaded_one'+ : 'com_ui_skills_available_count_loaded';+ }+ return count === 1 ? 'com_ui_skills_available_count_one' : 'com_ui_skills_available_count';+}++function SkillIcon({ item }: { item: AgentItem }) {+ const { Icon, colorClass } = getIconForItem(item);+ return (+ <span className={cn(CHIP, colorClass)} aria-hidden="true">+ <Icon className="size-3.5" />+ </span>+ );+}++/**+ * Height-morphing reveal. `Collapse` tweens `grid-template-rows` between `0fr`+ * and `1fr`, which animates opening and closing but snaps whenever the content+ * itself changes size — so swapping All for Selected jumped straight to the new+ * height. Measuring the content and driving an explicit height makes every+ * change a single tween, including a mode swap and the available-skills expand.+ */+function MorphHeight({ open, children }: { open: boolean; children: ReactNode }) {+ const contentRef = useRef<HTMLDivElement | null>(null);+ const [height, setHeight] = useState(0);+ /** Held off for one frame so a section that mounts already open lands at its+ * height instead of animating up from zero. */+ const [animate, setAnimate] = useState(false);++ useLayoutEffect(() => {+ const el = contentRef.current;+ if (el == null) {+ return;+ }+ setHeight(el.offsetHeight);+ const frame = requestAnimationFrame(() => setAnimate(true));+ if (typeof ResizeObserver === 'undefined') {+ return () => cancelAnimationFrame(frame);+ }+ const observer = new ResizeObserver(() => setHeight(el.offsetHeight));+ observer.observe(el);+ return () => {+ cancelAnimationFrame(frame);+ observer.disconnect();+ };+ }, []);++ return (+ <div+ aria-hidden={!open || undefined}+ inert={!open ? '' : undefined}+ style={{ height: open ? height : 0 }}+ className={cn(+ 'overflow-hidden',+ animate &&+ 'transition-[height] [transition-duration:var(--resize-dur)] [transition-timing-function:var(--resize-ease)] motion-reduce:transition-none',+ )}+ >+ {/** Spacing lives inside the measured box so it collapses away with it. */}+ <div ref={contentRef} className="pt-2">+ {children}+ </div>+ </div>+ );+}++export default function SkillsSection({ items, onInfo, onRemove, onAdd }: Props) {+ const localize = useLocalize();+ const { user } = useAuthContext();+ /** The count is only as trustworthy as the per-user overrides behind it:+ * until they resolve the hook reports every skill active, which would list+ * a deliberately deactivated owned or deployment skill as available. */+ const {+ isActive,+ isLoading: statesLoading,+ isError: statesError,+ refetch: refetchStates,+ } = useSkillActiveState();+ const { setValue, control } = useFormContext<AgentForm>();+ const [allExpanded, setAllExpanded] = useState(false);++ const skillsValue = useWatch({ control, name: 'skills' });+ const skillsEnabledValue = useWatch({ control, name: 'skills_enabled' });+ const skillsScopeValue = useWatch({ control, name: 'skills_scope' });+ /** Legacy agents persist no explicit scope; the shared resolver maps their+ * enabled + allowlist shape onto one of the three modes. */+ const mode = resolveAgentSkillsScope(skillsValue, skillsEnabledValue, skillsScopeValue);++ /** Which body the single collapse holds. It lags `none` on purpose: only one+ * wrapper animates, so switching All <-> Selected swaps content at a fixed+ * height with no vertical motion, while Off still tweens open and closed+ * with the outgoing body still mounted to collapse against. */+ const [bodyMode, setBodyMode] = useState(mode === SkillsScope.none ? SkillsScope.selected : mode);+ if (mode !== SkillsScope.none && mode !== bodyMode) {+ setBodyMode(mode);+ }++ const authoringEnabledValue = useWatch({ control, name: 'skill_authoring_enabled' });++ /** Two shapes the section has to reconcile with what it displays. Neither+ * dirties the form: they are normalizations the user did not ask for, and+ * they must not light up Save on an untouched agent.+ *+ * 1. `skills_enabled` with no explicit scope, where the meaning depends on+ * whether the allowlist is empty. Pin the resolved scope so the next+ * save persists the new shape.+ * 2. Either capability flag left on under a resolved Off, which+ * `skills_enabled: true` with `skills_scope: none` produces through the+ * API. `skillDeps` exposes the skill-authoring tools for either flag, so+ * that shape runs with skills the section reports as disabled, and+ * clicking the already-selected Off segment cannot clear it. Off means+ * no skills at all, which is what selecting Off already writes. */+ useEffect(() => {+ if (skillsEnabledValue === true && skillsScopeValue === undefined) {+ setValue('skills_scope', mode, { shouldDirty: false });+ }+ if (mode !== SkillsScope.none) {+ return;+ }+ if (skillsEnabledValue === true) {+ setValue('skills_enabled', false, { shouldDirty: false });+ }+ if (authoringEnabledValue === true) {+ setValue('skill_authoring_enabled', false, { shouldDirty: false });+ }+ }, [mode, skillsEnabledValue, skillsScopeValue, authoringEnabledValue, setValue]);++ /** Only `all` needs the deployment-wide catalog, for the count and the+ * read-only list. Other modes never fetch it. Shares its cache with the+ * picker, which uses the same query key. */+ const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isError, refetch } =+ useSkillsInfiniteQuery({ limit: 100 }, { enabled: mode === SkillsScope.all });++ /** The first page is enough for the collapsed header; the rest is only worth+ * fetching once the list is open. The accessible catalog is unbounded and+ * the endpoint caps a page at 100, so paging it eagerly would cost a serial+ * request per 100 skills merely to view an All-scoped agent. */+ useEffect(() => {+ if (isError || mode !== SkillsScope.all || !allExpanded) {+ return;+ }+ if (hasNextPage && !isFetchingNextPage) {+ fetchNextPage();+ }+ }, [mode, allExpanded, hasNextPage, isFetchingNextPage, isError, fetchNextPage]);++ /** The list endpoint returns every skill the user can VIEW, but the runtime+ * injects only the ones `resolveSkillActive` keeps: a per-user override in+ * `skillStates`, else the owner/`defaultActiveOnShare` default. Counting the+ * raw list would promise skills the agent will never receive, so this shares+ * the same `isActive` predicate the chat-side picker filters on. */+ const availableSkills = useMemo(() => {+ const all: TSkillSummary[] = [];+ const seen = new Set<string>();+ for (const page of data?.pages ?? []) {+ for (const skill of page.skills) {+ if (seen.has(skill._id) || !isActive(skill)) {+ continue;+ }+ seen.add(skill._id);+ all.push(skill);+ }+ }+ return buildSkillItems(all, user?.id);+ }, [data?.pages, user?.id, isActive]);++ /** The mode is the single source of truth for catalog exposure, so each+ * segment writes it outright. `skills` is deliberately left alone: `all` and+ * `off` ignore the allowlist at runtime, which is what lets a return to+ * `selected` restore the previous picks. */+ const handleModeChange = useCallback(+ (next: string) => {+ const scope = next as SkillsScope;+ /** Compared against the resolved mode, not the persisted scope: a+ * disabled agent that kept `skills_scope: all` renders as Off, and+ * matching on the raw field would swallow the click that re-enables it+ * while `Radio` moved its own selection. */+ if (scope === mode) {+ return;+ }+ setValue('skills_enabled', scope !== SkillsScope.none, { shouldDirty: true });+ setValue('skills_scope', scope, { shouldDirty: true });+ /** Authoring is a separate capability, but `off` must mean no skills at+ * all — leaving it set would still inject the skill-authoring tools. */+ if (scope === SkillsScope.none) {+ setValue('skill_authoring_enabled', false, { shouldDirty: true });+ }+ },+ [mode, setValue],+ );++ const modeOptions = useMemo(+ () => MODES.map((value) => ({ value, label: localize(MODE_LABELS[value]) })),+ [localize],+ );++ /** Both requests have to land before the catalog can be described: the+ * skills themselves, and the overrides that decide which of them the+ * runtime would actually inject. */+ const catalogError = isError || statesError === true;+ const catalogLoading = data == null || statesLoading === true;+ const count = availableSkills.length;+ const countLabel = catalogLoading+ ? localize('com_ui_loading')+ : localize(availableCountKey(count, hasNextPage === true), { count });++ const handleRetry = useCallback(() => {+ void refetch();+ void refetchStates?.();+ }, [refetch, refetchStates]);++ /** Once something is selected the list carries its own affordance in the+ * header, so the dashed card is only the empty state. */+ const showAddInHeader = mode === SkillsScope.selected && items.length > 0;++ return (+ <div className="mb-3 flex w-full flex-col">+ <div className="flex items-center justify-between gap-3">+ <span+ id="skills-mode-label"+ className="block text-xs font-medium uppercase tracking-wide text-text-secondary"+ >+ {localize('com_ui_skills')}+ </span>+ <div className="flex shrink-0 items-center gap-1.5">+ {showAddInHeader && (+ <button+ type="button"+ onClick={onAdd}+ aria-label={localize('com_ui_skills_add_row')}+ className="flex size-7 items-center justify-center rounded-lg text-text-secondary transition hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <Plus className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />+ </button>+ )}+ <Radio+ options={modeOptions}+ value={mode}+ onChange={handleModeChange}+ buttonClassName="!h-7 !px-2.5 !text-xs"+ aria-labelledby="skills-mode-label"+ />+ </div>+ </div>++ {/** One animator for the whole body: opening from Off, swapping All for+ * Selected, and expanding the available list all tween the same+ * measured height. */}+ <MorphHeight open={mode !== SkillsScope.none}>+ {bodyMode === SkillsScope.all && catalogError && (+ <>+ {/** A failed catalog request must not read as an empty catalog: the+ * agent still uses every skill it can reach at runtime, so report+ * the failure and offer a retry instead of a count derived from+ * missing data. Mirrors the picker's alert. */}+ <div+ role="alert"+ className={cn(+ ROW,+ 'justify-between rounded-lg border-[0.5px] border-border-light text-sm text-text-secondary',+ )}+ >+ <span className="truncate">{localize('com_ui_skills_load_error')}</span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={handleRetry}+ className="shrink-0"+ >+ {localize('com_ui_retry')}+ </Button>+ </div>+ </>+ )}+ {bodyMode === SkillsScope.all && !catalogError && (+ <div className="overflow-hidden rounded-lg border-[0.5px] border-border-light">+ <button+ type="button"+ onClick={() => setAllExpanded((prev) => !prev)}+ aria-expanded={allExpanded}+ aria-controls="skills-all-list"+ className={cn(+ ROW,+ 'w-full text-left transition-colors hover:bg-surface-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring-primary',+ )}+ >+ <ChevronRight+ className={cn(+ 'size-4 shrink-0 text-text-secondary transition-transform',+ allExpanded && 'rotate-90',+ )}+ aria-hidden="true"+ />+ <span className="truncate text-sm text-text-primary">{countLabel}</span>+ </button>+ {/** Mounted only while expanded: an always-present wrapper left the+ * container's divider stacked on its bottom border. */}+ {allExpanded && (+ <ul+ id="skills-all-list"+ className="divide-y-[0.5px] divide-border-light border-t-[0.5px] border-border-light"+ >+ {availableSkills.map((item) => (+ <li key={item.id}>+ <button+ type="button"+ onClick={() => onInfo(item)}+ className={cn(+ ROW,+ // `transition-none` beats the global `all` transition, so+ // the highlight lands on the frame the pointer enters.+ 'w-full text-left transition-none hover:bg-surface-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring-primary',+ )}+ >+ <SkillIcon item={item} />+ <span className="truncate text-sm text-text-secondary">{item.name}</span>+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ {bodyMode !== SkillsScope.all && (+ <div className="flex flex-col gap-1.5">+ {/** Rows own their hover so the whole item highlights, not just the+ * name. `has-[...]` drops it while the remove button is hovered,+ * leaving only that button lit. */}+ {items.length > 0 && (+ <ul className="divide-y-[0.5px] divide-border-light overflow-hidden rounded-lg border-[0.5px] border-border-light">+ {items.map((item) => (+ <li+ key={item.id}+ className="flex items-center transition-colors hover:bg-surface-secondary has-[[data-skill-remove]:hover]:bg-transparent"+ >+ <button+ type="button"+ onClick={() => onInfo(item)}+ className={cn(+ ROW,+ 'min-w-0 flex-1 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring-primary',+ )}+ >+ <SkillIcon item={item} />+ <span className="truncate text-sm text-text-primary">{item.name}</span>+ </button>+ <button+ type="button"+ data-skill-remove=""+ onClick={() => onRemove(item)}+ aria-label={localize('com_ui_skills_remove', { name: item.name })}+ className="mr-2 flex size-6 shrink-0 items-center justify-center rounded-md text-text-secondary transition-colors hover:bg-surface-tertiary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <X className="size-3.5" aria-hidden="true" />+ </button>+ </li>+ ))}+ </ul>+ )}+ {/** Same dashed card `dev` and `main` use for "No skills yet". Only+ * the empty state: once rows exist, Add lives in the header. */}+ {items.length === 0 && (+ <button+ type="button"+ onClick={onAdd}+ className="flex w-full flex-col items-center gap-1 rounded-xl border border-dashed border-border-light px-2 py-4 text-text-secondary transition-colors hover:border-border-medium hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <Plus className="h-4 w-4" aria-hidden="true" />+ <span className="text-xs">{localize('com_ui_skills_add_row')}</span>+ <span className="text-[11px] text-text-secondary">+ {localize('com_ui_skills_empty_hint')}+ </span>+ </button>+ )}+ </div>+ )}+ </MorphHeight>+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx b/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsxindex 46c0a4a5fd..43bfa0b199 100644--- a/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx+++ b/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx@@ -1,16 +1,7 @@-import { useState, useMemo, useCallback, useRef } from 'react';+import { useState, useMemo, useCallback } from 'react';import { Plus } from 'lucide-react';import { useFormContext, useWatch } from 'react-hook-form';-import {- Label,- Switch,- OGDialog,- HoverCard,- HoverCardPortal,- HoverCardContent,- OGDialogTemplate,- useToastContext,-} from '@librechat/client';+import { Label, OGDialog, OGDialogTemplate, useToastContext } from '@librechat/client';import {PermissionTypes,Permissions,@@ -20,7 +11,6 @@ import {removeCodeExecutionCaller,} from 'librechat-data-provider';import type { TPlugin } from 'librechat-data-provider';-import type { ReactNode } from 'react';import type { CapabilityFileCounts } from './items/capabilities';import type { AgentItem } from './items/types';import type { AgentForm } from '~/common';@@ -30,21 +20,19 @@ import {useResolvedSkills,useUninstallToolCredentials,} from './hooks';-import { computeToggleAction, skillsSelectionTransition } from './items/mutations';-import { useListSkillsQuery, useDeleteAgentAction } from '~/data-provider';+import { useSkillsInfiniteQuery, useDeleteAgentAction } from '~/data-provider';import { requiresFileManagerRemoval } from './items/capabilities';import { useRemoveMCPTool, useVisibleTools } from '~/hooks/MCP';import ToolsMarketplaceDialog from './ToolsMarketplaceDialog';+import { computeToggleAction } from './items/mutations';import { useLocalize, useHasAccess } from '~/hooks';import { useAgentPanelContext } from '~/Providers';-import { isEphemeralAgent, ESide } from '~/common';import ItemDialog from './ItemDialog/ItemDialog';import { mcpAllToken } from './items/selectors';-import { InfoTrigger } from '../Advanced/ui';-import { Collapse } from '~/components/ui';+import { isEphemeralAgent } from '~/common';+import SkillsSection from './SkillsSection';import SkillsDialog from './SkillsDialog';import ToolRow from './ToolRow';-import { cn } from '~/utils';interface Props {agentId: string;@@ -87,95 +75,26 @@ export default function ToolsSection({ agentId }: Props) {[agentsConfig],);const showSkills = hasSkillsAccess && skillsEnabled;- const { data: skillsData } = useListSkillsQuery({ limit: 100 }, { enabled: showSkills });- const resolvedSkills = useResolvedSkills(skillsData?.skills);-+ /** The same infinite query the section and the picker use, so all three+ * consumers share one cache entry and one request. A plain list query hits+ * the same endpoint under a different key, which React Query cannot+ * deduplicate: the first page would be fetched twice. Only the first page+ * is needed here, and pagination stays driven by whoever opens a list. */+ const { data: skillsData } = useSkillsInfiniteQuery({ limit: 100 }, { enabled: showSkills });+ /** `undefined` until the first page lands: `useResolvedSkills` treats it as+ * "not loaded yet" and skips its per-id fallback lookups. */+ const skillSummaries = useMemo(+ () => (skillsData ? skillsData.pages.flatMap((page) => page.skills) : undefined),+ [skillsData],+ );const skillsValue = useWatch({ control, name: 'skills' });const skillsEnabledValue = useWatch({ control, name: 'skills_enabled' });- const skillAuthoringEnabledValue = useWatch({ control, name: 'skill_authoring_enabled' });const skillsScopeValue = useWatch({ control, name: 'skills_scope' });- const explicitSkillsEnabled = skillsEnabledValue === true;- const skillsCapabilityEnabled = explicitSkillsEnabled || skillAuthoringEnabledValue === true;- const effectiveSkillsScope = resolveAgentSkillsScope(- skillsValue,- skillsEnabledValue,- skillsScopeValue,- );- const useAllSkills = explicitSkillsEnabled && effectiveSkillsScope === SkillsScope.all;- /** Selection stashed when "use all skills" turns on, so turning it back off- * restores the previous picks instead of destroying them. Cleared when the- * agent changes — the section isn't remounted on switch (only the form- * resets), so a stale stash could otherwise restore one agent's allowlist- * into another. */- const stashedSkillsRef = useRef<string[]>([]);- const [prevAgentId, setPrevAgentId] = useState(agentId);- if (prevAgentId !== agentId) {- setPrevAgentId(agentId);- stashedSkillsRef.current = [];- }-- const handleSkillsEnabledChange = useCallback(- (checked: boolean) => {- if (!checked) {- setValue('skills_enabled', false, { shouldDirty: true });- setValue('skill_authoring_enabled', false, { shouldDirty: true });- return;- }- const current = (getValues('skills') ?? []) as string[];- if (current.length === 0 && getValues('skills_scope') === SkillsScope.all) {- setValue('skills_enabled', true, { shouldDirty: true });- setValue('skill_authoring_enabled', false, { shouldDirty: true });- return;- }- const transition = skillsSelectionTransition(- current,- getValues('skills_enabled'),- getValues('skill_authoring_enabled'),- getValues('skills_scope'),- );- if (transition.enabled !== undefined) {- setValue('skills_enabled', transition.enabled, { shouldDirty: true });- }- if (transition.authoringEnabled !== undefined) {- setValue('skill_authoring_enabled', transition.authoringEnabled, { shouldDirty: true });- }- if (transition.scope !== undefined) {- setValue('skills_scope', transition.scope, { shouldDirty: true });- }- },- [getValues, setValue],- );-- const handleUseAllSkillsChange = useCallback(- (checked: boolean) => {- if (checked) {- stashedSkillsRef.current = (getValues('skills') ?? []) as string[];- setValue('skills', [], { shouldDirty: true });- setValue('skills_enabled', true, { shouldDirty: true });- setValue('skill_authoring_enabled', false, { shouldDirty: true });- setValue('skills_scope', SkillsScope.all, { shouldDirty: true });- return;- }- const restored = stashedSkillsRef.current;- setValue('skills', restored, { shouldDirty: true });- const transition = skillsSelectionTransition(- restored,- getValues('skills_enabled'),- getValues('skill_authoring_enabled'),- getValues('skills_scope'),- );- if (transition.enabled !== undefined) {- setValue('skills_enabled', transition.enabled, { shouldDirty: true });- }- if (transition.authoringEnabled !== undefined) {- setValue('skill_authoring_enabled', transition.authoringEnabled, { shouldDirty: true });- }- if (transition.scope !== undefined) {- setValue('skills_scope', transition.scope, { shouldDirty: true });- }- },- [getValues, setValue],- );+ /** Only Selected renders allowlist rows, so the per-id fallback lookups are+ * worth issuing only there. An All-scoped agent keeps its previous picks,+ * which would otherwise cost one request per retained id on every view. */+ const skillsMode = resolveAgentSkillsScope(skillsValue, skillsEnabledValue, skillsScopeValue);+ const resolvedSkills = useResolvedSkills(skillSummaries, skillsMode === SkillsScope.selected);const uninstallToolCredentials = useUninstallToolCredentials();@@ -224,26 +143,14 @@ export default function ToolsSection({ agentId }: Props) {break;}case 'skill-remove': {+ /** The mode is explicit, so emptying the allowlist stays in+ * `selected` rather than silently disabling skills. */const current = (getValues('skills') ?? []) as string[];- const next = current.filter((s) => s !== patch.id);- setValue('skills', next, { shouldDirty: true });- const transition = skillsSelectionTransition(- next,- getValues('skills_enabled'),- getValues('skill_authoring_enabled'),- getValues('skills_scope'),+ setValue(+ 'skills',+ current.filter((s) => s !== patch.id),+ { shouldDirty: true },);- if (transition.enabled !== undefined) {- setValue('skills_enabled', transition.enabled, { shouldDirty: true });- }- if (transition.authoringEnabled !== undefined) {- setValue('skill_authoring_enabled', transition.authoringEnabled, {- shouldDirty: true,- });- }- if (transition.scope !== undefined) {- setValue('skills_scope', transition.scope, { shouldDirty: true });- }break;}case 'mcp-remove':@@ -350,73 +257,12 @@ export default function ToolsSection({ agentId }: Props) {onRemove={handleQuickRemove}/>{showSkills && (- <SelectedSection- title={localize('com_ui_skills')}- addLabel={localize('com_ui_add_skills')}- emptyLabel={localize('com_ui_skills_empty')}- emptyHint={localize('com_ui_skills_empty_hint')}+ <SkillsSectionitems={skillItems}onAdd={() => setSkillsOpen(true)}onInfo={setDialogItem}onRemove={handleQuickRemove}- badgeText={useAllSkills ? localize('com_ui_all_proper') : undefined}- showAdd={skillsCapabilityEnabled && !useAllSkills}- showBody={skillsCapabilityEnabled && !useAllSkills}- >- <div className="mb-1.5 flex items-center justify-between gap-3 px-1">- <div className="flex min-w-0 items-center gap-1.5">- <span- id="skills-enabled-label"- className="truncate text-[13px] font-medium text-text-primary"- >- {localize('com_ui_skills_enable')}- </span>- <HoverCard openDelay={50}>- <InfoTrigger />- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <p className="text-sm text-text-secondary">- {localize('com_ui_skills_enable_hint')}- </p>- </HoverCardContent>- </HoverCardPortal>- </HoverCard>- </div>- <Switch- id="skills-enabled"- checked={skillsCapabilityEnabled}- onCheckedChange={handleSkillsEnabledChange}- aria-labelledby="skills-enabled-label"- />- </div>- <div className="mb-1.5 flex items-center justify-between gap-3 px-1">- <div className="flex min-w-0 items-center gap-1.5">- <span- id="use-all-skills-label"- className="truncate text-[13px] font-medium text-text-primary"- >- {localize('com_ui_skills_use_all')}- </span>- <HoverCard openDelay={50}>- <InfoTrigger />- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <p className="text-sm text-text-secondary">- {localize('com_ui_skills_use_all_hint')}- </p>- </HoverCardContent>- </HoverCardPortal>- </HoverCard>- </div>- <Switch- id="use-all-skills"- checked={useAllSkills}- disabled={!skillsCapabilityEnabled}- onCheckedChange={handleUseAllSkillsChange}- aria-labelledby="use-all-skills-label"- />- </div>- </SelectedSection>+ />)}{open && <ToolsMarketplaceDialog open={open} onOpenChange={setOpen} agentId={agentId} />}{skillsOpen && (@@ -486,12 +332,6 @@ interface SelectedSectionProps {onAdd: () => void;onInfo: (item: AgentItem) => void;onRemove: (item: AgentItem) => void;- /** Replaces the item-count badge next to the title. */- badgeText?: string;- showAdd?: boolean;- showBody?: boolean;- /** Rendered between the header and the item list / empty state. */- children?: ReactNode;}function SelectedSection({@@ -503,13 +343,9 @@ function SelectedSection({onAdd,onInfo,onRemove,- badgeText,- showAdd = true,- showBody = true,- children,}: SelectedSectionProps) {const localize = useLocalize();- const badge = badgeText ?? (items.length > 0 ? String(items.length) : undefined);+ const badge = items.length > 0 ? String(items.length) : undefined;return (<div className="mb-3 flex flex-col"><div className="mb-1 flex items-center justify-between">@@ -525,39 +361,31 @@ function SelectedSection({type="button"onClick={onAdd}aria-label={addLabel}- aria-hidden={!showAdd || undefined}- tabIndex={showAdd ? 0 : -1}- className={cn(- 'inline-flex h-7 items-center gap-1.5 rounded-lg px-2 text-xs font-medium text-text-secondary transition hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',- !showAdd && 'pointer-events-none opacity-0',- )}+ className="inline-flex h-7 items-center gap-1.5 rounded-lg px-2 text-xs font-medium text-text-secondary transition hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"><Plus className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden="true" />{localize('com_ui_add')}</button></div>- {children}- <Collapse open={showBody}>- {items.length === 0 ? (- <button- type="button"- onClick={onAdd}- className="flex w-full flex-col items-center gap-1 rounded-xl border border-dashed border-border-light px-2 py-4 text-text-secondary transition-colors hover:border-border-medium hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"- >- <Plus className="h-4 w-4" aria-hidden="true" />- <span className="text-xs">{emptyLabel}</span>- <span className="text-[11px] text-text-secondary">{emptyHint}</span>- </button>- ) : (- <ul className="flex flex-col gap-1.5">- {items.map((item) => (- <li key={`${item.kind}:${item.id}`}>- <ToolRow item={item} onInfo={onInfo} onRemove={onRemove} />- </li>- ))}- </ul>- )}- </Collapse>+ {items.length === 0 ? (+ <button+ type="button"+ onClick={onAdd}+ className="flex w-full flex-col items-center gap-1 rounded-xl border border-dashed border-border-light px-2 py-4 text-text-secondary transition-colors hover:border-border-medium hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <Plus className="h-4 w-4" aria-hidden="true" />+ <span className="text-xs">{emptyLabel}</span>+ <span className="text-[11px] text-text-secondary">{emptyHint}</span>+ </button>+ ) : (+ <ul className="flex flex-col gap-1.5">+ {items.map((item) => (+ <li key={`${item.kind}:${item.id}`}>+ <ToolRow item={item} onInfo={onInfo} onRemove={onRemove} />+ </li>+ ))}+ </ul>+ )}</div>);}diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/SkillsSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/SkillsSection.spec.tsxnew file mode 100644index 0000000000..14c9c8b420--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/SkillsSection.spec.tsx@@ -0,0 +1,662 @@+import React from 'react';+import '@testing-library/jest-dom/extend-expect';+import { SkillsScope } from 'librechat-data-provider';+import { fireEvent, render, screen, within } from '@testing-library/react';+import type { TSkillSummary } from 'librechat-data-provider';+import type { AgentItem } from '../items/types';+import SkillsSection from '../SkillsSection';++let mockFormValues: Record<string, unknown> = {};+const mockSetValue = jest.fn();+const mockUseSkillsInfiniteQuery = jest.fn();+/** Every fixture skill is runtime-active unless a test says otherwise. */+const mockIsActive = jest.fn((_skill: { _id: string }) => true);+const mockRefetchStates = jest.fn();+let mockStatesResult: { isLoading: boolean; isError: boolean };++let mockInfiniteResult: {+ data: { pages: Array<{ skills: TSkillSummary[] }> };+ fetchNextPage: jest.Mock;+ refetch: jest.Mock;+ hasNextPage: boolean;+ isFetchingNextPage: boolean;+ isError: boolean;+};++jest.mock('react-hook-form', () => ({+ useFormContext: () => ({+ control: {},+ getValues: (name: string) => mockFormValues[name],+ setValue: mockSetValue,+ }),+ useWatch: ({ name }: { name: string }) => mockFormValues[name],+}));+jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useAuthContext: () => ({ user: { id: 'user-1' } }),+ useSkillActiveState: () => ({+ isActive: (skill: { _id: string }) => mockIsActive(skill),+ isLoading: mockStatesResult.isLoading,+ isError: mockStatesResult.isError,+ refetch: mockRefetchStates,+ }),+}));++jest.mock('~/data-provider', () => ({+ useSkillsInfiniteQuery: (...args: unknown[]) => mockUseSkillsInfiniteQuery(...args),+}));++function makeSkill(id: string, name: string): TSkillSummary {+ return {+ _id: id,+ name,+ description: `${name} description`,+ author: 'user-1',+ authorName: 'Test User',+ version: 1,+ source: 'inline',+ fileCount: 0,+ createdAt: '2026-07-24T00:00:00.000Z',+ updatedAt: '2026-07-24T00:00:00.000Z',+ };+}++function makeItem(id: string, name: string): AgentItem {+ const skill = makeSkill(id, name);+ return {+ kind: 'skill',+ id,+ name,+ description: skill.description ?? '',+ iconKey: 'skill',+ skill,+ };+}++function setAvailableSkills(pages: TSkillSummary[][]) {+ mockInfiniteResult = {+ data: { pages: pages.map((skills) => ({ skills })) },+ fetchNextPage: jest.fn(),+ refetch: jest.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ isError: false,+ };+}++type Callbacks = {+ onInfo: (item: AgentItem) => void;+ onRemove: (item: AgentItem) => void;+ onAdd: () => void;+};++function renderSection(items: AgentItem[] = [], callbacks?: Partial<Callbacks>) {+ const props = {+ items,+ onInfo: callbacks?.onInfo ?? jest.fn(),+ onRemove: callbacks?.onRemove ?? jest.fn(),+ onAdd: callbacks?.onAdd ?? jest.fn(),+ };+ return render(<SkillsSection {...props} />);+}++function getRadio(label: string) {+ return screen.getByRole('radio', { name: label });+}++function expectNoFieldWrite(field: string) {+ expect(mockSetValue.mock.calls.some(([name]) => name === field)).toBe(false);+}++beforeEach(() => {+ mockFormValues = {};+ mockSetValue.mockClear();+ mockUseSkillsInfiniteQuery.mockClear();+ mockIsActive.mockReset();+ mockIsActive.mockReturnValue(true);+ mockRefetchStates.mockClear();+ mockStatesResult = { isLoading: false, isError: false };+ setAvailableSkills([]);+ mockUseSkillsInfiniteQuery.mockImplementation(() => mockInfiniteResult);+});++describe('SkillsSection mode derivation', () => {+ test.each([+ ['false', false],+ ['undefined', undefined],+ ])('checks Off and renders no body when skills_enabled is %s', (_label, enabled) => {+ mockFormValues = {+ skills_enabled: enabled,+ skills_scope: SkillsScope.selected,+ skills: ['s1'],+ };++ renderSection([makeItem('s1', 'Selected skill')]);++ expect(getRadio('com_ui_skills_mode_off')).toHaveAttribute('aria-checked', 'true');+ // Both bodies stay mounted so mode switches can tween; the inactive one is+ // inert and aria-hidden, so nothing in it is reachable.+ expect(screen.queryByRole('list')).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'com_ui_skills_add_row' })).not.toBeInTheDocument();+ });++ test('checks All for an explicitly all-scoped agent', () => {+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(getRadio('com_ui_skills_mode_all')).toHaveAttribute('aria-checked', 'true');+ });++ test('checks Selected for an explicitly selected-scoped agent', () => {+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.selected, skills: ['s1'] };++ renderSection([makeItem('s1', 'Selected skill')]);++ expect(getRadio('com_ui_skills_mode_selected')).toHaveAttribute('aria-checked', 'true');+ });++ test('uses All for a legacy enabled agent with an empty allowlist', () => {+ mockFormValues = { skills_enabled: true, skills: [] };++ renderSection();++ expect(getRadio('com_ui_skills_mode_all')).toHaveAttribute('aria-checked', 'true');+ });++ test('uses Selected for a legacy enabled agent with an allowlist', () => {+ mockFormValues = { skills_enabled: true, skills: ['s1'] };++ renderSection([makeItem('s1', 'Selected skill')]);++ expect(getRadio('com_ui_skills_mode_selected')).toHaveAttribute('aria-checked', 'true');+ });++ test('normalizes an ambiguous legacy scope without dirtying the form', () => {+ mockFormValues = { skills_enabled: true, skills: ['s1'] };++ renderSection([makeItem('s1', 'Selected skill')]);++ expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.selected, {+ shouldDirty: false,+ });+ });++ test('clears authoring left on under a resolved Off', () => {+ /** `skillDeps` enables the authoring tools for either flag, so this shape+ * would run with skills the section reports as disabled. */+ mockFormValues = {+ skills_enabled: false,+ skill_authoring_enabled: true,+ skills_scope: SkillsScope.none,+ skills: ['s1'],+ };++ renderSection([makeItem('s1', 'Selected skill')]);++ expect(getRadio('com_ui_skills_mode_off')).toHaveAttribute('aria-checked', 'true');+ expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', false, {+ shouldDirty: false,+ });+ });++ test('leaves authoring alone while skills are enabled', () => {+ mockFormValues = {+ skills_enabled: true,+ skill_authoring_enabled: true,+ skills_scope: SkillsScope.all,+ skills: [],+ };++ renderSection();++ expect(getRadio('com_ui_skills_mode_all')).toHaveAttribute('aria-checked', 'true');+ expectNoFieldWrite('skill_authoring_enabled');+ });++ test('clears the master flag when an explicit none scope resolves to Off', () => {+ /** A valid API shape: enabled with `skills_scope: none`. The section shows+ * Off, but `skillDeps` reads the master flag alone as permission to+ * expose the authoring tools, and clicking Off cannot clear it. */+ mockFormValues = {+ skills_enabled: true,+ skills_scope: SkillsScope.none,+ skills: ['s1'],+ };++ renderSection([makeItem('s1', 'Selected skill')]);++ expect(getRadio('com_ui_skills_mode_off')).toHaveAttribute('aria-checked', 'true');+ expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', false, { shouldDirty: false });+ });++ test('leaves the master flag alone while a catalog mode is active', () => {+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(getRadio('com_ui_skills_mode_all')).toHaveAttribute('aria-checked', 'true');+ expectNoFieldWrite('skills_enabled');+ });+});++describe('SkillsSection mode writes', () => {+ test('clicking All from Off enables skills without changing the allowlist', () => {+ mockFormValues = { skills: ['s1'], skills_enabled: false, skills_scope: SkillsScope.none };++ renderSection([makeItem('s1', 'Selected skill')]);+ fireEvent.click(getRadio('com_ui_skills_mode_all'));++ expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', true, { shouldDirty: true });+ expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.all, {+ shouldDirty: true,+ });+ expectNoFieldWrite('skills');+ });++ test('clicking Off disables skills and skill authoring', () => {+ mockFormValues = {+ skills: ['s1'],+ skills_enabled: true,+ skills_scope: SkillsScope.selected,+ skill_authoring_enabled: true,+ };++ renderSection([makeItem('s1', 'Selected skill')]);+ fireEvent.click(getRadio('com_ui_skills_mode_off'));++ expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', false, { shouldDirty: true });+ expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.none, {+ shouldDirty: true,+ });+ expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', false, {+ shouldDirty: true,+ });+ });++ test('clicking Selected enables skills without changing the allowlist', () => {+ mockFormValues = { skills: ['s1'], skills_enabled: false, skills_scope: SkillsScope.none };++ renderSection([makeItem('s1', 'Selected skill')]);+ fireEvent.click(getRadio('com_ui_skills_mode_selected'));++ expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', true, { shouldDirty: true });+ expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.selected, {+ shouldDirty: true,+ });+ expectNoFieldWrite('skills');+ });++ test('round-tripping through All preserves the prior selection', () => {+ mockFormValues = { skills: ['s1'], skills_enabled: true, skills_scope: SkillsScope.selected };+ const { rerender } = renderSection([makeItem('s1', 'Selected skill')]);++ fireEvent.click(getRadio('com_ui_skills_mode_all'));+ expectNoFieldWrite('skills');++ mockFormValues = { skills: ['s1'], skills_enabled: true, skills_scope: SkillsScope.all };+ rerender(+ <SkillsSection+ items={[makeItem('s1', 'Selected skill')]}+ onInfo={jest.fn()}+ onRemove={jest.fn()}+ onAdd={jest.fn()}+ />,+ );+ mockSetValue.mockClear();+ fireEvent.click(getRadio('com_ui_skills_mode_selected'));++ expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', true, { shouldDirty: true });+ expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.selected, {+ shouldDirty: true,+ });+ expectNoFieldWrite('skills');+ });++ test('clicking the active segment writes nothing', () => {+ mockFormValues = { skills: [], skills_enabled: true, skills_scope: SkillsScope.all };++ renderSection();+ fireEvent.click(getRadio('com_ui_skills_mode_all'));++ expect(mockSetValue).not.toHaveBeenCalled();+ });++ test('re-enables an agent whose disabled state kept a stale scope', () => {+ /** Produced by the old Off handler, which never rewrote `skills_scope`.+ * The section resolves it to Off, so clicking the retained scope has to+ * write, not match the raw field and no-op while `Radio` moves anyway. */+ mockFormValues = { skills: [], skills_enabled: false, skills_scope: SkillsScope.all };++ renderSection();+ expect(getRadio('com_ui_skills_mode_off')).toHaveAttribute('aria-checked', 'true');+ fireEvent.click(getRadio('com_ui_skills_mode_all'));++ expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', true, { shouldDirty: true });+ expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.all, {+ shouldDirty: true,+ });+ });++ test('arrow keys move the checked radio and write the next scope', () => {+ mockFormValues = { skills: [], skills_enabled: false, skills_scope: SkillsScope.none };++ renderSection();+ fireEvent.keyDown(getRadio('com_ui_skills_mode_off'), { key: 'ArrowRight' });++ expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', true, { shouldDirty: true });+ expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.all, {+ shouldDirty: true,+ });+ expect(getRadio('com_ui_skills_mode_all')).toHaveAttribute('aria-checked', 'true');+ });+});++describe('SkillsSection All mode body', () => {+ test('renders the plural available count from paginated skills', () => {+ setAvailableSkills([[makeSkill('s1', 'First skill')], [makeSkill('s2', 'Second skill')]]);+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByText('com_ui_skills_available_count')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_skills_available_count_one')).not.toBeInTheDocument();+ });++ test('uses the singular available count for one skill', () => {+ setAvailableSkills([[makeSkill('s1', 'Only skill')]]);+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByText('com_ui_skills_available_count_one')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_skills_available_count')).not.toBeInTheDocument();+ });++ test('expands the available skills list from its header button', () => {+ setAvailableSkills([[makeSkill('s1', 'First skill')], [makeSkill('s2', 'Second skill')]]);+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();+ const header = screen.getByRole('button', { name: /com_ui_skills_available_count/ });++ expect(header).toHaveAttribute('aria-expanded', 'false');+ expect(header).toHaveAttribute('aria-controls', 'skills-all-list');+ fireEvent.click(header);++ expect(header).toHaveAttribute('aria-expanded', 'true');+ expect(document.querySelector('#skills-all-list')).toBeInTheDocument();+ expect(screen.getByText('First skill')).toBeInTheDocument();+ expect(screen.getByText('Second skill')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /com_ui_skills_remove/ })).not.toBeInTheDocument();+ });++ test('opens details from an available skill row, which is never removable', () => {+ setAvailableSkills([[makeSkill('s1', 'First skill')]]);+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };+ const onInfo = jest.fn();++ renderSection([], { onInfo });+ fireEvent.click(screen.getByRole('button', { name: /com_ui_skills_available_count/ }));+ fireEvent.click(screen.getByRole('button', { name: 'First skill' }));++ expect(onInfo).toHaveBeenCalledTimes(1);+ expect(onInfo.mock.calls[0][0]).toMatchObject({ id: 's1', name: 'First skill' });+ expect(screen.queryByRole('button', { name: /com_ui_skills_remove/ })).not.toBeInTheDocument();+ });++ test('reports what is loaded, not a lower bound, while more pages remain', () => {+ /** `hasNextPage` tracks raw pagination and the rows are filtered to the+ * active ones, so the remaining pages may add nothing. Claiming "+ more+ * available" would overstate the catalog in that case. */+ setAvailableSkills([[makeSkill('s1', 'First skill')]]);+ mockInfiniteResult.hasNextPage = true;+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByText('com_ui_skills_available_count_loaded_one')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_skills_available_count')).not.toBeInTheDocument();+ expect(screen.queryByText('com_ui_skills_available_count_one')).not.toBeInTheDocument();+ });++ test('uses the plural loaded phrasing for several loaded skills', () => {+ setAvailableSkills([[makeSkill('s1', 'First skill'), makeSkill('s2', 'Second skill')]]);+ mockInfiniteResult.hasNextPage = true;+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByText('com_ui_skills_available_count_loaded')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_skills_available_count_loaded_one')).not.toBeInTheDocument();+ });++ test('leaves the rest of the catalog unfetched until the list is expanded', () => {+ setAvailableSkills([[makeSkill('s1', 'First skill')]]);+ mockInfiniteResult.hasNextPage = true;+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(mockInfiniteResult.fetchNextPage).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: /com_ui_skills_available_count/ }));++ expect(mockInfiniteResult.fetchNextPage).toHaveBeenCalled();+ });++ test('reports a failed catalog request instead of an empty one', () => {+ setAvailableSkills([]);+ mockInfiniteResult.isError = true;+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByRole('alert')).toHaveTextContent('com_ui_skills_load_error');+ expect(screen.queryByText('com_ui_skills_available_count')).not.toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: /com_ui_skills_available_count/ }),+ ).not.toBeInTheDocument();+ });++ test('retries the catalog request from the error state', () => {+ setAvailableSkills([]);+ mockInfiniteResult.isError = true;+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));++ expect(mockInfiniteResult.refetch).toHaveBeenCalledTimes(1);+ });++ test('reports loading rather than an empty catalog before the first page lands', () => {+ setAvailableSkills([]);+ mockInfiniteResult.data = undefined as never;+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByText('com_ui_loading')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_skills_available_count')).not.toBeInTheDocument();+ });++ test('counts and lists only the skills the runtime would inject', () => {+ /** The list endpoint returns everything the user can VIEW; a shared skill+ * left inactive is not part of the agent's catalog. */+ setAvailableSkills([[makeSkill('s1', 'Active skill'), makeSkill('s2', 'Inactive skill')]]);+ mockIsActive.mockImplementation((skill: { _id: string }) => skill._id === 's1');+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByText('com_ui_skills_available_count_one')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: /com_ui_skills_available_count/ }));++ expect(screen.getByText('Active skill')).toBeInTheDocument();+ expect(screen.queryByText('Inactive skill')).not.toBeInTheDocument();+ });++ test('waits for the skill states before describing the catalog', () => {+ /** The hook reports every skill active until the overrides land, so a+ * count taken then could list a deactivated skill as available. */+ setAvailableSkills([[makeSkill('s1', 'First skill')]]);+ mockStatesResult = { isLoading: true, isError: false };+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByText('com_ui_loading')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_skills_available_count_one')).not.toBeInTheDocument();+ });++ test('reports an error when the skill states fail, not an unfiltered count', () => {+ setAvailableSkills([[makeSkill('s1', 'First skill')]]);+ mockStatesResult = { isLoading: false, isError: true };+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();++ expect(screen.getByRole('alert')).toHaveTextContent('com_ui_skills_load_error');+ expect(+ screen.queryByRole('button', { name: /com_ui_skills_available_count/ }),+ ).not.toBeInTheDocument();+ });++ test('retries both the catalog and the skill states', () => {+ setAvailableSkills([]);+ mockInfiniteResult.isError = true;+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };++ renderSection();+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_retry' }));++ expect(mockInfiniteResult.refetch).toHaveBeenCalledTimes(1);+ expect(mockRefetchStates).toHaveBeenCalledTimes(1);+ });+});++describe('SkillsSection Selected mode body', () => {+ test('renders one removable row per selected item and removes the clicked item', () => {+ const first = makeItem('s1', 'First skill');+ const second = makeItem('s2', 'Second skill');+ const onRemove = jest.fn();+ mockFormValues = {+ skills_enabled: true,+ skills_scope: SkillsScope.selected,+ skills: ['s1', 's2'],+ };++ renderSection([first, second], { onRemove });++ const removeButtons = screen.getAllByRole('button', { name: 'com_ui_skills_remove' });+ expect(removeButtons).toHaveLength(2);+ fireEvent.click(removeButtons[1]);++ expect(onRemove).toHaveBeenCalledWith(second);+ });++ test('opens item details when a selected row name is clicked', () => {+ const item = makeItem('s1', 'Selected skill');+ const onInfo = jest.fn();+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.selected, skills: ['s1'] };++ renderSection([item], { onInfo });+ fireEvent.click(screen.getByRole('button', { name: 'Selected skill' }));++ expect(onInfo).toHaveBeenCalledWith(item);+ });++ test('moves Add into the header, before the mode control, once rows exist', () => {+ const items = [makeItem('s1', 'First skill'), makeItem('s2', 'Second skill')];+ const onAdd = jest.fn();+ mockFormValues = {+ skills_enabled: true,+ skills_scope: SkillsScope.selected,+ skills: ['s1', 's2'],+ };++ renderSection(items, { onAdd });++ const rows = within(screen.getByRole('list')).getAllByRole('listitem');+ expect(rows).toHaveLength(2);++ // Exactly one Add affordance, and it is the header button rather than the+ // dashed empty-state card.+ const add = screen.getByRole('button', { name: /com_ui_skills_add_row/ });+ expect(add).not.toHaveTextContent('com_ui_skills_add_row');+ expect(+ add.compareDocumentPosition(screen.getByRole('radiogroup')) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ expect(add.compareDocumentPosition(rows[0]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();++ fireEvent.click(add);+ expect(onAdd).toHaveBeenCalledTimes(1);+ });++ test('has no header Add button while the selection is empty', () => {+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.selected, skills: [] };++ renderSection([]);++ // The only affordance is the dashed card, identified by its visible text.+ const add = screen.getByRole('button', { name: /com_ui_skills_add_row/ });+ expect(add).toHaveTextContent('com_ui_skills_add_row');+ });++ test('renders only the Add card, with its hint, when no skills are selected', () => {+ const onAdd = jest.fn();+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.selected, skills: [] };++ renderSection([], { onAdd });++ expect(screen.queryByRole('list')).not.toBeInTheDocument();+ const add = screen.getByRole('button', { name: /com_ui_skills_add_row/ });+ expect(add).toHaveTextContent('com_ui_skills_empty_hint');+ fireEvent.click(add);+ expect(onAdd).toHaveBeenCalledTimes(1);+ });++ test('drops the Add card hint once something is selected', () => {+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.selected, skills: ['s1'] };++ renderSection([makeItem('s1', 'First skill')]);++ expect(screen.getByRole('button', { name: /com_ui_skills_add_row/ })).not.toHaveTextContent(+ 'com_ui_skills_empty_hint',+ );+ });++ test('has exactly one Add affordance in Selected and none in Off or All', () => {+ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.selected, skills: [] };+ const { rerender } = renderSection();++ expect(screen.getAllByRole('button', { name: /com_ui_skills_add_row/ })).toHaveLength(1);++ mockFormValues = { skills_enabled: false, skills_scope: SkillsScope.none, skills: [] };+ rerender(+ <SkillsSection items={[]} onInfo={jest.fn()} onRemove={jest.fn()} onAdd={jest.fn()} />,+ );+ expect(screen.queryByRole('button', { name: /com_ui_skills_add_row/ })).not.toBeInTheDocument();++ mockFormValues = { skills_enabled: true, skills_scope: SkillsScope.all, skills: [] };+ rerender(+ <SkillsSection items={[]} onInfo={jest.fn()} onRemove={jest.fn()} onAdd={jest.fn()} />,+ );+ expect(screen.queryByRole('button', { name: /com_ui_skills_add_row/ })).not.toBeInTheDocument();+ });+});++describe('SkillsSection accessibility', () => {+ test('exposes one radiogroup with exactly three radio segments', () => {+ mockFormValues = { skills_enabled: false, skills_scope: SkillsScope.none, skills: [] };++ renderSection();++ expect(screen.getAllByRole('radiogroup')).toHaveLength(1);+ expect(screen.getAllByRole('radio')).toHaveLength(3);+ expect(screen.getByRole('radiogroup')).toHaveAttribute('aria-labelledby', 'skills-mode-label');+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsSection.spec.tsxindex 75f8bff4db..cf7a6bef04 100644--- a/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsSection.spec.tsx+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsSection.spec.tsx@@ -1,8 +1,8 @@import React from 'react';import '@testing-library/jest-dom/extend-expect';-import { SkillsScope } from 'librechat-data-provider';import { render, screen, fireEvent } from '@testing-library/react';import type { AgentItem } from '../items/types';+import { makeSkill } from 'test/itemFactories';import ToolsSection from '../ToolsSection';let mockSelected: AgentItem[] = [];@@ -39,7 +39,7 @@ jest.mock('~/Providers', () => ({}));jest.mock('~/data-provider', () => ({- useListSkillsQuery: () => ({ data: { skills: [] } }),+ useSkillsInfiniteQuery: () => ({ data: { pages: [{ skills: [] }] } }),useDeleteAgentAction: () => ({ mutate: jest.fn() }),}));@@ -65,6 +65,36 @@ jest.mock('../ToolRow', () => ({),}));+jest.mock('../SkillsSection', () => ({+ __esModule: true,+ default: ({+ items,+ onAdd,+ onRemove,+ }: {+ items: AgentItem[];+ onAdd: () => void;+ onRemove: (item: AgentItem) => void;+ }) => (+ <div data-testid="skills-section">+ <button type="button" aria-label="skills-add" onClick={onAdd} />+ {items[0] && (+ <button+ type="button"+ aria-label={`skills-remove-${items[0].id}`}+ onClick={() => onRemove(items[0])}+ />+ )}+ </div>+ ),+}));++jest.mock('../SkillsDialog', () => ({+ __esModule: true,+ default: ({ open }: { open: boolean }) =>+ open ? <div data-testid="skills-dialog-open" /> : null,+}));+jest.mock('../ItemDialog/ItemDialog', () => ({__esModule: true,default: ({ item }: { item: AgentItem | null }) =>@@ -129,6 +159,14 @@ const fileSearchItem: AgentItem = {description: '',iconKey: 'file_search',};+const skillItem: AgentItem = {+ kind: 'skill',+ id: 's1',+ name: 'Skill',+ description: '',+ iconKey: 'skill',+ skill: makeSkill({ _id: 's1', name: 'Skill' }),+};beforeEach(() => {mockSelected = [];@@ -144,12 +182,10 @@ describe('ToolsSection', () => {expect(screen.getByText('com_ui_tools_section_title')).toBeInTheDocument();});- test('renders a separate Skills section', () => {+ test('renders the SkillsSection component', () => {render(<ToolsSection agentId="a" />);- expect(screen.getByText('com_ui_skills')).toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'com_ui_add_skills' })).not.toBeInTheDocument();+ expect(screen.getByTestId('skills-section')).toBeInTheDocument();});-test('renders Add button that opens the marketplace dialog', () => {render(<ToolsSection agentId="a" />);const addButton = screen.getByRole('button', { name: 'com_ui_add_tools' });@@ -157,10 +193,41 @@ describe('ToolsSection', () => {expect(screen.getByTestId('marketplace-open')).toBeInTheDocument();});- test('renders empty state for both sections when nothing is selected', () => {+ test('wires SkillsSection add and remove callbacks', () => {+ mockSelected = [skillItem];+ mockFormValues = {+ skills: ['s1'],+ skills_enabled: true,+ skills_scope: 'selected',+ skill_authoring_enabled: true,+ };+ render(<ToolsSection agentId="a" />);+ fireEvent.click(screen.getByRole('button', { name: 'skills-add' }));+ expect(screen.getByTestId('skills-dialog-open')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'skills-remove-s1' }));++ expect(mockSetValue).toHaveBeenCalledWith('skills', [], { shouldDirty: true });+ expect(mockSetValue).not.toHaveBeenCalledWith(+ 'skills_enabled',+ expect.anything(),+ expect.anything(),+ );+ expect(mockSetValue).not.toHaveBeenCalledWith(+ 'skills_scope',+ expect.anything(),+ expect.anything(),+ );+ expect(mockSetValue).not.toHaveBeenCalledWith(+ 'skill_authoring_enabled',+ expect.anything(),+ expect.anything(),+ );+ });++ test('renders the Tools empty state when nothing is selected', () => {render(<ToolsSection agentId="a" />);expect(screen.getByText('com_ui_tools_empty')).toBeInTheDocument();- expect(screen.getByText('com_ui_skills_empty')).toBeInTheDocument();});test('counts every enumerable MCP tool when the server is attached by wildcard', () => {@@ -237,141 +304,3 @@ describe('ToolsSection', () => {);});});--describe('use all skills toggle', () => {- const enableSwitch = () => screen.getByRole('switch', { name: 'com_ui_skills_enable' });- const useAllSwitch = () => screen.getByRole('switch', { name: 'com_ui_skills_use_all' });-- test('renders both controls off inside the Skills section by default', () => {- render(<ToolsSection agentId="a" />);- expect(screen.getByText('com_ui_skills_enable')).toBeInTheDocument();- expect(screen.getByText('com_ui_skills_enable_hint')).toBeInTheDocument();- expect(screen.getByText('com_ui_skills_use_all')).toBeInTheDocument();- expect(screen.getByText('com_ui_skills_use_all_hint')).toBeInTheDocument();- expect(enableSwitch()).toHaveAttribute('aria-checked', 'false');- expect(useAllSwitch()).toHaveAttribute('aria-checked', 'false');- expect(useAllSwitch()).toBeDisabled();- });-- test('enables skills with an empty authoring-only catalog', () => {- render(<ToolsSection agentId="a" />);- fireEvent.click(enableSwitch());- expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', false, { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', true, {- shouldDirty: true,- });- expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.none, {- shouldDirty: true,- });- });-- test('restores the full catalog when the master switch is re-enabled', () => {- mockFormValues = {- skills: [],- skills_enabled: false,- skill_authoring_enabled: false,- skills_scope: SkillsScope.all,- };- render(<ToolsSection agentId="a" />);- fireEvent.click(enableSwitch());- expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', true, { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', false, {- shouldDirty: true,- });- expect(mockSetValue).not.toHaveBeenCalledWith(- 'skills_scope',- expect.anything(),- expect.anything(),- );- });-- test('turning it on clears the selection and enables the master flag', () => {- mockFormValues = {- skills: ['s1'],- skills_enabled: true,- skills_scope: SkillsScope.selected,- };- render(<ToolsSection agentId="a" />);- fireEvent.click(useAllSwitch());- expect(mockSetValue).toHaveBeenCalledWith('skills', [], { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', true, { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', false, {- shouldDirty: true,- });- expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.all, {- shouldDirty: true,- });- });-- test('while on, hides Add and the skill list and shows the All badge', () => {- mockFormValues = { skills: [], skills_enabled: true, skills_scope: SkillsScope.all };- render(<ToolsSection agentId="a" />);- expect(useAllSwitch()).toHaveAttribute('aria-checked', 'true');- expect(screen.queryByRole('button', { name: 'com_ui_add_skills' })).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: /com_ui_skills_empty/ })).not.toBeInTheDocument();- expect(screen.getByText('com_ui_all_proper')).toBeInTheDocument();- });-- test('clicking the label does not toggle the switch', () => {- render(<ToolsSection agentId="a" />);- fireEvent.click(screen.getByText('com_ui_skills_use_all'));- expect(mockSetValue).not.toHaveBeenCalled();- });-- test('turning it off restores the previously selected skills', () => {- mockFormValues = {- skills: ['s1'],- skills_enabled: true,- skills_scope: SkillsScope.selected,- };- const { rerender } = render(<ToolsSection agentId="a" />);- fireEvent.click(useAllSwitch());- mockFormValues = { skills: [], skills_enabled: true, skills_scope: SkillsScope.all };- rerender(<ToolsSection agentId="a" />);- mockSetValue.mockClear();- fireEvent.click(useAllSwitch());- expect(mockSetValue).toHaveBeenCalledWith('skills', ['s1'], { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', false, {- shouldDirty: true,- });- expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.selected, {- shouldDirty: true,- });- });-- test('does not restore a stash from a different agent', () => {- mockFormValues = {- skills: ['s1'],- skills_enabled: true,- skills_scope: SkillsScope.selected,- };- const { rerender } = render(<ToolsSection agentId="a" />);- fireEvent.click(useAllSwitch());- mockFormValues = { skills: [], skills_enabled: true, skills_scope: SkillsScope.all };- rerender(<ToolsSection agentId="b" />);- mockSetValue.mockClear();- fireEvent.click(useAllSwitch());- expect(mockSetValue).toHaveBeenCalledWith('skills', [], { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', false, { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', true, {- shouldDirty: true,- });- expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.none, {- shouldDirty: true,- });- });-- test('turning use-all off with nothing stashed keeps authoring enabled', () => {- mockFormValues = { skills: [], skills_enabled: true, skills_scope: SkillsScope.all };- render(<ToolsSection agentId="a" />);- fireEvent.click(useAllSwitch());- expect(mockSetValue).toHaveBeenCalledWith('skills', [], { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skills_enabled', false, { shouldDirty: true });- expect(mockSetValue).toHaveBeenCalledWith('skill_authoring_enabled', true, {- shouldDirty: true,- });- expect(mockSetValue).toHaveBeenCalledWith('skills_scope', SkillsScope.none, {- shouldDirty: true,- });- });-});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/useResolvedSkills.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/useResolvedSkills.spec.tsxindex 66963593fb..b44ab198f1 100644--- a/client/src/components/SidePanel/Agents/Tools/__tests__/useResolvedSkills.spec.tsx+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/useResolvedSkills.spec.tsx@@ -59,11 +59,18 @@ function makeWrapper(skillIds: string[]) {};}-function renderResolvedSkills(skillIds: string[], pageSkills?: TSkillSummary[]) {- return renderHook((props: TSkillSummary[] | undefined) => useResolvedSkills(props), {- wrapper: makeWrapper(skillIds),- initialProps: pageSkills,- });+function renderResolvedSkills(+ skillIds: string[],+ pageSkills?: TSkillSummary[],+ resolveAllowlist = true,+) {+ return renderHook(+ (props: TSkillSummary[] | undefined) => useResolvedSkills(props, resolveAllowlist),+ {+ wrapper: makeWrapper(skillIds),+ initialProps: pageSkills,+ },+ );}describe('useResolvedSkills', () => {@@ -98,6 +105,16 @@ describe('useResolvedSkills', () => {expect(result.current?.[1].name).toBe('Off Page Skill');});+ test('skips the per-id lookups when the caller is not rendering allowlist rows', () => {+ /** Off and All keep the allowlist but never show it, so resolving ids the+ * first page missed would be one request each for a list nobody sees. */+ const page = [makeSkill({ _id: 's1' })];+ const { result } = renderResolvedSkills(['s1', 'off-page'], page, false);++ expect(result.current).toBe(page);+ expect(mockGetSkill).not.toHaveBeenCalled();+ });+test('keeps a confirmed miss (404) visible under a placeholder name', async () => {mockGetSkill.mockRejectedValue({ response: { status: 404 } });diff --git a/client/src/components/SidePanel/Agents/Tools/hooks.ts b/client/src/components/SidePanel/Agents/Tools/hooks.tsindex 5f7e14a53c..3da0549de7 100644--- a/client/src/components/SidePanel/Agents/Tools/hooks.ts+++ b/client/src/components/SidePanel/Agents/Tools/hooks.ts@@ -257,17 +257,23 @@ export function useAgentItems({* lookups are briefly hidden. Must be rendered inside the agent form's* `FormProvider`.*/-export function useResolvedSkills(pageSkills?: TSkillSummary[]): TSkillSummary[] | undefined {+export function useResolvedSkills(+ pageSkills?: TSkillSummary[],+ /** Off and All never render allowlist rows, so resolving ids the first+ * catalog page missed would be one `getSkill` request per retained id for+ * a list nobody sees. Callers pass `false` outside Selected. */+ resolveAllowlist = true,+): TSkillSummary[] | undefined {const localize = useLocalize();const { control } = useFormContext<AgentForm>();const skillsWatch = useWatch({ control, name: 'skills' });const unresolvedIds = useMemo(() => {- if (pageSkills === undefined) {+ if (pageSkills === undefined || !resolveAllowlist) {return [];}const known = new Set(pageSkills.map((skill) => skill._id));return ((skillsWatch ?? []) as string[]).filter((id) => !known.has(id));- }, [pageSkills, skillsWatch]);+ }, [pageSkills, skillsWatch, resolveAllowlist]);const lookups = useQueries({queries: unresolvedIds.map((skillId) => ({diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.tsindex 3ec316e0e6..aa6f535b7e 100644--- a/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts@@ -1,7 +1,7 @@-import { SkillsScope, AgentCapabilities, ArtifactModes } from 'librechat-data-provider';+import { AgentCapabilities, ArtifactModes } from 'librechat-data-provider';import type { AgentItem } from '../types';import { makePlugin, makeSkill, makeMcpServer, makeAction } from 'test/itemFactories';-import { computeToggleAction, skillsSelectionTransition } from '../mutations';+import { computeToggleAction } from '../mutations';const builtinCode: AgentItem = {kind: 'builtin',@@ -131,37 +131,6 @@ describe('computeToggleAction', () => {});});-describe('skillsSelectionTransition', () => {- test('a non-empty selection enables skills and selects the allowlist scope', () => {- expect(skillsSelectionTransition(['s1'], undefined, undefined, undefined)).toEqual({- enabled: true,- authoringEnabled: false,- scope: SkillsScope.selected,- });- expect(skillsSelectionTransition(['s1', 's2'], false, true, SkillsScope.none)).toEqual({- enabled: true,- authoringEnabled: false,- scope: SkillsScope.selected,- });- });-- test('an existing matching selection state needs no writes', () => {- expect(skillsSelectionTransition(['s1'], true, false, SkillsScope.selected)).toEqual({});- });-- test('clearing the selection keeps the capability enabled in authoring-only mode', () => {- expect(skillsSelectionTransition([], true, false, SkillsScope.selected)).toEqual({- enabled: false,- authoringEnabled: true,- scope: SkillsScope.none,- });- expect(skillsSelectionTransition([], false, false, undefined)).toEqual({- authoringEnabled: true,- scope: SkillsScope.none,- });- });-});-describe('computeToggleAction — ask_user_question builtin', () => {const item = {kind: 'builtin',diff --git a/client/src/components/SidePanel/Agents/Tools/items/mutations.ts b/client/src/components/SidePanel/Agents/Tools/items/mutations.tsindex 50b6e3afff..b20002b00d 100644--- a/client/src/components/SidePanel/Agents/Tools/items/mutations.ts+++ b/client/src/components/SidePanel/Agents/Tools/items/mutations.ts@@ -1,4 +1,4 @@-import { SkillsScope, AgentCapabilities, ArtifactModes } from 'librechat-data-provider';+import { AgentCapabilities, ArtifactModes } from 'librechat-data-provider';import type { AgentItem } from './types';export type TogglePatch =@@ -50,26 +50,3 @@ export function computeToggleAction(item: AgentItem, state: { selected: boolean? { type: 'action-remove', actionId: item.id }: { type: 'action-add', actionId: item.id };}--/**- * Selection edits enable the capability and move its catalog between an- * explicit allowlist and an authoring-only empty scope. They never produce- * the full-catalog state; only the "use all skills" control can do that.- */-export function skillsSelectionTransition(- next: string[],- enabled: boolean | undefined,- authoringEnabled: boolean | undefined,- scope: SkillsScope | undefined,-): { enabled?: boolean; authoringEnabled?: boolean; scope?: SkillsScope } {- const nextEnabled = next.length > 0;- const nextAuthoringEnabled = !nextEnabled;- const nextScope = next.length > 0 ? SkillsScope.selected : SkillsScope.none;- return {- ...(enabled === nextEnabled ? {} : { enabled: nextEnabled }),- ...(authoringEnabled === nextAuthoringEnabled- ? {}- : { authoringEnabled: nextAuthoringEnabled }),- ...(scope === nextScope ? {} : { scope: nextScope }),- };-}diff --git a/client/src/hooks/Skills/useSkillActiveState.ts b/client/src/hooks/Skills/useSkillActiveState.tsindex 4026af6c31..84b8f9ee2f 100644--- a/client/src/hooks/Skills/useSkillActiveState.ts+++ b/client/src/hooks/Skills/useSkillActiveState.ts@@ -212,13 +212,28 @@ export default function useSkillActiveState() {[queryClient, userId, defaultActiveOnShare, canToggle, flush],);+ /** Both dependencies feed `isActive`: the override map and the interface+ * config behind `defaultActiveOnShare`. Until each resolves the map reads+ * empty and the default reads `false`, so they are reported as one signal.+ * A consumer gating on `isLoading`/`isError` then cannot silently miss a+ * dependency, and `isActive` is trustworthy exactly when both are clear. */+ const isLoading = getQuery.isLoading || configQuery.isLoading;+ const isError = getQuery.isError || configQuery.isError;+ const refetchStates = getQuery.refetch;+ const refetchConfig = configQuery.refetch;+ const refetch = useCallback(async () => {+ await Promise.all([refetchStates(), refetchConfig()]);+ }, [refetchStates, refetchConfig]);+return {skillStates,defaultActiveOnShare,isActive,toggle,- isLoading: getQuery.isLoading,- isError: getQuery.isError,+ isLoading,+ isError,+ /** Lets a consumer that gates its own UI on resolved states retry both. */+ refetch,isUpdating: updateMutation.isLoading,};}diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 34a86710b0..42cd94e5ee 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -768,7 +768,6 @@"com_ui_add_mcp_server": "Add MCP Server","com_ui_add_model_preset": "Add a model or preset for an additional response","com_ui_add_multi_conversation": "Add multi-conversation",- "com_ui_add_skills": "Add Skills","com_ui_add_special_variables": "Add Special Variables","com_ui_add_to_chat": "Add to chat","com_ui_add_tools": "Add tools",@@ -2142,24 +2141,29 @@"com_ui_skill_warnings": "Heads up","com_ui_skill_write_instructions": "Write skill instructions","com_ui_skills": "Skills",+ "com_ui_skills_add_row": "Add skill","com_ui_skills_allow_create": "Allow creating Skills","com_ui_skills_allow_share": "Allow sharing Skills","com_ui_skills_allow_share_public": "Allow sharing Skills publicly","com_ui_skills_allow_use": "Allow using Skills","com_ui_skills_always_apply_invoked": "Auto-applied skills","com_ui_skills_always_apply_pin_title": "Always-applied skill (auto-primed on every turn)",+ "com_ui_skills_available_count": "{{count}} skills available",+ "com_ui_skills_available_count_loaded": "{{count}} skills loaded",+ "com_ui_skills_available_count_loaded_one": "{{count}} skill loaded",+ "com_ui_skills_available_count_one": "{{count}} skill available","com_ui_skills_command_placeholder": "Select a Skill by name","com_ui_skills_dialog_description": "Browse and add skills to your agent.",- "com_ui_skills_enable": "Enable skills",- "com_ui_skills_enable_hint": "Allow the agent to use attached skills and, when permitted, create skills at runtime.","com_ui_skills_empty": "No skills yet","com_ui_skills_empty_hint": "Add a skill to give your agent reusable instructions.","com_ui_skills_filter": "Filter skills","com_ui_skills_load_error": "Failed to load skills","com_ui_skills_manual_invoked": "Manually invoked skills",+ "com_ui_skills_mode_all": "All",+ "com_ui_skills_mode_off": "Off",+ "com_ui_skills_mode_selected": "Selected","com_ui_skills_queued": "Skills queued for next submission",- "com_ui_skills_use_all": "Use all skills",- "com_ui_skills_use_all_hint": "The agent can use every skill available to you, including skills added in the future.",+ "com_ui_skills_remove": "Remove {{name}}","com_ui_skip": "Skip","com_ui_something_else": "Something else...","com_ui_sort_chats_by": "Sort chats by",diff --git a/e2e/specs/mock/agent-skills.spec.ts b/e2e/specs/mock/agent-skills.spec.tsindex 2b5c56be8c..0f888b3bae 100644--- a/e2e/specs/mock/agent-skills.spec.ts+++ b/e2e/specs/mock/agent-skills.spec.ts@@ -35,12 +35,14 @@ type SkillSummary = {type SkillAgentDetail = AgentDetail & {skills?: string[];skills_enabled?: boolean;+ skills_scope?: string;};type AgentSkillPayload = {name?: string;skills?: string[];skills_enabled?: boolean;+ skills_scope?: string;manualSkills?: string[];};@@ -138,12 +140,12 @@ async function settleCleanup(tasks: Promise<unknown>[]): Promise<void> {}async function openSkillsDialog(page: Page, form: Locator): Promise<Locator> {- const enableSkillsSwitch = form.getByRole('switch', { name: 'Enable skills' });- if ((await enableSkillsSwitch.getAttribute('aria-checked')) !== 'true') {- await enableSkillsSwitch.click();- await expect(enableSkillsSwitch).toHaveAttribute('aria-checked', 'true');+ const selectedSkillsRadio = form.getByRole('radio', { name: 'Selected', exact: true });+ if ((await selectedSkillsRadio.getAttribute('aria-checked')) !== 'true') {+ await selectedSkillsRadio.click();+ await expect(selectedSkillsRadio).toHaveAttribute('aria-checked', 'true');}- await form.getByRole('button', { name: 'Add Skills', exact: true }).click();+ await form.getByRole('button', { name: /Add skill/ }).click();const dialog = page.getByRole('dialog').filter({ hasText: 'Browse and add skills to your agent.' });@@ -410,7 +412,7 @@ test.describe('Agent Builder skills', () => {const deploymentRow = form.locator('li').filter({ hasText: DEPLOYMENT_SKILL_NAME });await expect(deploymentRow).toHaveCount(1);await deploymentRow.hover();- await deploymentRow.getByRole('button', { name: 'Remove from agent' }).click();+ await deploymentRow.getByRole('button', { name: /^Remove / }).click();await expect(form.getByText(DEPLOYMENT_SKILL_NAME, { exact: true })).toBeHidden();const updateResponsePromise = waitForAgentMutation(page, 'PATCH', createdAgentId);@@ -440,25 +442,29 @@ test.describe('Agent Builder skills', () => {const finalSkillRow = form.locator('li').filter({ hasText: inlineSkillName });await expect(finalSkillRow).toHaveCount(1);await finalSkillRow.hover();- await finalSkillRow.getByRole('button', { name: 'Remove from agent' }).click();+ await finalSkillRow.getByRole('button', { name: /^Remove / }).click();await expect(form.getByText(inlineSkillName, { exact: true })).toBeHidden();- const disableResponsePromise = waitForAgentMutation(page, 'PATCH', createdAgentId);+ /** Emptying the allowlist stays in Selected: the mode is explicit now, so+ * removing the last skill no longer infers Off. Only `skills` is written,+ * and an explicit Selected with nothing selected resolves to no skills at+ * runtime, which the picker and the run below both confirm. */+ const emptiedResponsePromise = waitForAgentMutation(page, 'PATCH', createdAgentId);await form.getByRole('button', { name: 'Save', exact: true }).click();- const disableResponse = await disableResponsePromise;- expect(disableResponse.status(), await disableResponse.text()).toBe(200);- expect(disableResponse.request().postDataJSON()).toMatchObject({+ const emptiedResponse = await emptiedResponsePromise;+ expect(emptiedResponse.status(), await emptiedResponse.text()).toBe(200);+ expect(emptiedResponse.request().postDataJSON()).toMatchObject({skills: [],- skills_enabled: false,});- const disabledAgent = await fetchJson<SkillAgentDetail>(+ const emptiedAgent = await fetchJson<SkillAgentDetail>(page,`/api/agents/${encodeURIComponent(createdAgentId)}/expanded`,token,);- expect(disabledAgent.skills).toEqual([]);- expect(disabledAgent.skills_enabled).toBe(false);+ expect(emptiedAgent.skills).toEqual([]);+ expect(emptiedAgent.skills_enabled).toBe(true);+ expect(emptiedAgent.skills_scope).toBe('selected');form = await openAgentBuilder(page);await selectAgent(page, form, agentName);@@ -508,17 +514,19 @@ test.describe('Agent Builder skills', () => {await selectMockModel(page, true);form = page.getByRole('form', { name: 'Agent configuration form' });- const enableSkillsSwitch = form.getByRole('switch', { name: 'Enable skills' });- const useAllSwitch = form.getByRole('switch', { name: 'Use all skills' });- await expect(enableSkillsSwitch).toHaveAttribute('aria-checked', 'false');- await expect(useAllSwitch).toHaveAttribute('aria-checked', 'false');- await expect(useAllSwitch).toBeDisabled();- await enableSkillsSwitch.click();- await expect(enableSkillsSwitch).toHaveAttribute('aria-checked', 'true');- await expect(useAllSwitch).toBeEnabled();- await useAllSwitch.click();- await expect(useAllSwitch).toHaveAttribute('aria-checked', 'true');- await expect(form.getByRole('button', { name: 'Add Skills', exact: true })).toHaveCount(0);+ const offSkillsRadio = form.getByRole('radio', { name: 'Off', exact: true });+ const allSkillsRadio = form.getByRole('radio', { name: 'All', exact: true });+ await expect(offSkillsRadio).toHaveAttribute('aria-checked', 'true');+ await expect(allSkillsRadio).toHaveAttribute('aria-checked', 'false');+ await allSkillsRadio.click();+ await expect(allSkillsRadio).toHaveAttribute('aria-checked', 'true');+ await expect(offSkillsRadio).toHaveAttribute('aria-checked', 'false');+ const allSkillsSummary = form.getByRole('button', { name: /\d+ skills? available/ });+ await expect(allSkillsSummary).toBeVisible();+ await expect(allSkillsSummary).toHaveAttribute('aria-expanded', 'false');+ // The Selected body stays mounted so mode switches tween; it is inert and+ // aria-hidden while All is active, so its Add row must not be reachable.+ await expect(form.getByRole('button', { name: /Add skill/ })).toBeHidden();const createResponsePromise = waitForAgentMutation(page, 'POST');await form.getByRole('button', { name: 'Create', exact: true }).click();@@ -528,15 +536,18 @@ test.describe('Agent Builder skills', () => {const createdAgent = (await createResponse.json()) as SkillAgentDetail;createdAgentId = createdAgent.id;const createPayload = createResponse.request().postDataJSON() as AgentSkillPayload;+ /** All writes the mode outright and deliberately leaves `skills` alone, so+ * a fresh agent sends no allowlist at all rather than an empty one. That+ * is what lets a later return to Selected restore previous picks. */expect(createPayload).toMatchObject({- skills: [],skills_enabled: true,+ skills_scope: 'all',});expect(createdAgent).toMatchObject({id: createdAgentId,- skills: [],skills_enabled: true,+ skills_scope: 'all',});const persistedAgent = (await waitForPersistedAgent(@@ -544,16 +555,17 @@ test.describe('Agent Builder skills', () => {agentName,agentDescription,)) as SkillAgentDetail;- expect(persistedAgent.skills).toEqual([]);expect(persistedAgent.skills_enabled).toBe(true);+ expect(persistedAgent.skills_scope).toBe('all');form = await openAgentBuilder(page);await selectAgent(page, form, agentName);- await expect(form.getByRole('switch', { name: 'Use all skills' })).toHaveAttribute(+ await expect(form.getByRole('radio', { name: 'All', exact: true })).toHaveAttribute('aria-checked','true',);- await expect(form.getByRole('button', { name: 'Add Skills', exact: true })).toHaveCount(0);+ await expect(form.getByRole('button', { name: /\d+ skills? available/ })).toBeVisible();+ await expect(form.getByRole('button', { name: /Add skill/ })).toBeHidden();futureSkill = await createInlineSkill(page, token, futureSkillName);await form.getByRole('button', { name: 'Select Agent' }).click();@@ -577,18 +589,20 @@ test.describe('Agent Builder skills', () => {form = await openAgentBuilder(page);await selectAgent(page, form, agentName);- const persistedUseAllSwitch = form.getByRole('switch', { name: 'Use all skills' });- await persistedUseAllSwitch.click();- await expect(persistedUseAllSwitch).toHaveAttribute('aria-checked', 'false');- await expect(form.getByRole('button', { name: 'Add Skills', exact: true })).toBeVisible();+ const persistedOffSkillsRadio = form.getByRole('radio', { name: 'Off', exact: true });+ await persistedOffSkillsRadio.click();+ await expect(persistedOffSkillsRadio).toHaveAttribute('aria-checked', 'true');+ await expect(form.getByRole('button', { name: /Add skill/ })).toBeHidden();const updateResponsePromise = waitForAgentMutation(page, 'PATCH', createdAgentId);await form.getByRole('button', { name: 'Save', exact: true }).click();const updateResponse = await updateResponsePromise;expect(updateResponse.status(), await updateResponse.text()).toBe(200);+ /** Off writes the mode and both capability flags, and still leaves the+ * allowlist untouched. */expect(updateResponse.request().postDataJSON()).toMatchObject({- skills: [],skills_enabled: false,+ skills_scope: 'none',});const disabledAgent = await fetchJson<SkillAgentDetail>(@@ -596,16 +610,16 @@ test.describe('Agent Builder skills', () => {`/api/agents/${encodeURIComponent(createdAgentId)}/expanded`,token,);- expect(disabledAgent.skills).toEqual([]);expect(disabledAgent.skills_enabled).toBe(false);+ expect(disabledAgent.skills_scope).toBe('none');form = await openAgentBuilder(page);await selectAgent(page, form, agentName);- await expect(form.getByRole('switch', { name: 'Use all skills' })).toHaveAttribute(+ await expect(form.getByRole('radio', { name: 'Off', exact: true })).toHaveAttribute('aria-checked',- 'false',+ 'true',);- await expect(form.getByRole('button', { name: 'Add Skills', exact: true })).toBeVisible();+ await expect(form.getByRole('button', { name: /Add skill/ })).toBeHidden();await form.getByRole('button', { name: 'Select Agent' }).click();const disabledPickerSearch = await openSkillPicker(page);diff --git a/packages/client/src/components/Radio.spec.tsx b/packages/client/src/components/Radio.spec.tsxindex 274e19ec8b..c518aa95e7 100644--- a/packages/client/src/components/Radio.spec.tsx+++ b/packages/client/src/components/Radio.spec.tsx@@ -1,4 +1,5 @@-import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { createEvent, fireEvent, render, screen } from '@testing-library/react';import Radio from './Radio';jest.mock('react-i18next', () => ({@@ -41,3 +42,151 @@ describe('Radio', () => {expect(group().className).toContain('flex-wrap');});});++describe('Radio keyboard navigation', () => {+ it('uses a roving tabIndex and focuses the first option when no value matches', () => {+ const { rerender } = render(<Radio options={FIVE} value="weekly" />);+ const radios = screen.getAllByRole('radio');++ expect(radios[0]).toHaveAttribute('tabIndex', '-1');+ expect(radios[3]).toHaveAttribute('tabIndex', '0');+ expect(radios[4]).toHaveAttribute('tabIndex', '-1');++ rerender(<Radio options={FIVE} value="missing" />);+ expect(screen.getAllByRole('radio')[0]).toHaveAttribute('tabIndex', '0');+ expect(screen.getAllByRole('radio')[1]).toHaveAttribute('tabIndex', '-1');+ });++ it('moves forward with ArrowRight and ArrowDown, moving focus to the new selection', () => {+ const onChange = jest.fn();+ render(<Radio options={FIVE} value="daily" onChange={onChange} />);++ const daily = screen.getByRole('radio', { name: 'Daily' });+ const weekdays = screen.getByRole('radio', { name: 'Weekdays' });+ daily.focus();++ const arrowRight = createEvent.keyDown(daily, { key: 'ArrowRight' });+ fireEvent(daily, arrowRight);++ expect(arrowRight.defaultPrevented).toBe(true);+ expect(onChange).toHaveBeenCalledWith('weekdays');+ expect(weekdays).toHaveAttribute('aria-checked', 'true');+ expect(document.activeElement).toBe(weekdays);++ daily.focus();+ fireEvent.keyDown(daily, { key: 'ArrowDown' });+ expect(onChange).toHaveBeenLastCalledWith('weekdays');+ expect(document.activeElement).toBe(weekdays);+ });++ it('moves backward with ArrowLeft and ArrowUp, wrapping in both directions', () => {+ const onChange = jest.fn();+ render(<Radio options={FIVE} value="daily" onChange={onChange} />);++ const first = screen.getByRole('radio', { name: 'Hourly' });+ const daily = screen.getByRole('radio', { name: 'Daily' });+ const last = screen.getByRole('radio', { name: 'Custom' });++ daily.focus();+ fireEvent.keyDown(daily, { key: 'ArrowLeft' });+ expect(onChange).toHaveBeenLastCalledWith('hourly');+ expect(document.activeElement).toBe(first);++ daily.focus();+ fireEvent.keyDown(daily, { key: 'ArrowUp' });+ expect(onChange).toHaveBeenLastCalledWith('hourly');+ expect(document.activeElement).toBe(first);++ first.focus();+ fireEvent.keyDown(first, { key: 'ArrowLeft' });+ expect(onChange).toHaveBeenLastCalledWith('cron');+ expect(document.activeElement).toBe(last);++ last.focus();+ fireEvent.keyDown(last, { key: 'ArrowRight' });+ expect(onChange).toHaveBeenLastCalledWith('hourly');+ expect(document.activeElement).toBe(first);+ });++ it('moves to the first and last options with Home and End', async () => {+ const user = userEvent.setup();+ const onChange = jest.fn();+ render(<Radio options={FIVE} value="weekdays" onChange={onChange} />);++ const first = screen.getByRole('radio', { name: 'Hourly' });+ const middle = screen.getByRole('radio', { name: 'Weekdays' });+ const last = screen.getByRole('radio', { name: 'Custom' });++ middle.focus();+ await user.keyboard('{Home}');+ expect(onChange).toHaveBeenLastCalledWith('hourly');+ expect(document.activeElement).toBe(first);++ first.focus();+ await user.keyboard('{End}');+ expect(onChange).toHaveBeenLastCalledWith('cron');+ expect(document.activeElement).toBe(last);+ });++ it('does not fire onChange when Home lands on the already-checked first option', async () => {+ const user = userEvent.setup();+ const onChange = jest.fn();+ render(<Radio options={FIVE} value="hourly" onChange={onChange} />);++ const first = screen.getByRole('radio', { name: 'Hourly' });+ first.focus();+ await user.keyboard('{Home}');++ expect(onChange).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(first);+ });++ it('does not fire onChange when End lands on the already-checked last option', async () => {+ const user = userEvent.setup();+ const onChange = jest.fn();+ render(<Radio options={FIVE} value="cron" onChange={onChange} />);++ const last = screen.getByRole('radio', { name: 'Custom' });+ last.focus();+ await user.keyboard('{End}');++ expect(onChange).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(last);+ });++ it('ignores keys other than the six navigation keys', async () => {+ const user = userEvent.setup();+ const onChange = jest.fn();+ render(<Radio options={FIVE} value="daily" onChange={onChange} />);++ const daily = screen.getByRole('radio', { name: 'Daily' });+ daily.focus();+ await user.keyboard('{Escape}');++ expect(onChange).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(daily);+ });++ it('does nothing when disabled or when there is only one option', () => {+ const disabledOnChange = jest.fn();+ const { unmount } = render(+ <Radio options={FIVE} value="daily" onChange={disabledOnChange} disabled />,+ );+ const disabledDaily = screen.getByRole('radio', { name: 'Daily' });++ fireEvent.keyDown(disabledDaily, { key: 'ArrowRight' });+ expect(disabledOnChange).not.toHaveBeenCalled();+ unmount();++ const singleOnChange = jest.fn();+ render(+ <Radio options={[{ value: 'only', label: 'Only' }]} value="only" onChange={singleOnChange} />,+ );+ const only = screen.getByRole('radio', { name: 'Only' });+ only.focus();++ fireEvent.keyDown(only, { key: 'ArrowRight' });+ expect(singleOnChange).not.toHaveBeenCalled();+ expect(document.activeElement).toBe(only);+ });+});diff --git a/packages/client/src/components/Radio.tsx b/packages/client/src/components/Radio.tsxindex c03ed6d17c..ed7e2a9029 100644--- a/packages/client/src/components/Radio.tsx+++ b/packages/client/src/components/Radio.tsx@@ -50,6 +50,41 @@ const Radio: React.NamedExoticComponent<RadioProps> = memo(function Radio({onChange?.(newValue);};+ /** A radiogroup is a single tab stop: the roving `tabIndex` puts focus on the+ * checked segment and the arrows move the selection, per WAI-ARIA. Without+ * this every segment was its own tab stop and keyboard users could focus a+ * segment but never reach the others' selection behavior. */+ const handleKeyDown = (event: React.KeyboardEvent, index: number) => {+ if (disabled || options.length < 2) {+ return;+ }+ const moves: Record<string, number> = {+ ArrowRight: index + 1,+ ArrowDown: index + 1,+ ArrowLeft: index - 1,+ ArrowUp: index - 1,+ Home: 0,+ End: options.length - 1,+ };+ const target = moves[event.key];+ if (target == null) {+ return;+ }+ event.preventDefault();+ // Wraps, so holding ArrowRight from the last segment returns to the first.+ const next = (target + options.length) % options.length;+ const nextValue = options[next].value;+ // Focus follows the key unconditionally; the selection only changes when it+ // actually moves. Home on the first segment and End on the last land where+ // they started, and firing `onChange` there would dirty a form for a+ // selection that never changed.+ buttonRefs.current[next]?.focus();+ if (nextValue === currentValue) {+ return;+ }+ handleChange(nextValue);+ };+const updateBackgroundStyle = useCallback(() => {const selectedIndex = options.findIndex((opt) => opt.value === currentValue);const selectedButton = buttonRefs.current[selectedIndex];@@ -142,7 +177,9 @@ const Radio: React.NamedExoticComponent<RadioProps> = memo(function Radio({type="button"role="radio"aria-checked={currentValue === option.value}+ tabIndex={selectedIndex === index || (selectedIndex < 0 && index === 0) ? 0 : -1}onClick={() => handleChange(option.value)}+ onKeyDown={(event) => handleKeyDown(event, index)}disabled={disabled}className={`relative z-10 flex h-[34px] items-center justify-center gap-2 rounded-md px-4 text-sm font-medium transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary ${currentValue === option.value ? 'text-text-primary' : 'text-text-secondary'diff --git a/packages/data-schemas/src/methods/agent.spec.ts b/packages/data-schemas/src/methods/agent.spec.tsindex 22fa721d80..b54dcd0b25 100644--- a/packages/data-schemas/src/methods/agent.spec.ts+++ b/packages/data-schemas/src/methods/agent.spec.ts@@ -778,6 +778,76 @@ describe('Agent Methods', () => {expect(newAgent.skills).toEqual([realSkill._id.toString()]);});+ test('should preserve skills enabled when pruning empties the allowlist on create with all scope', async () => {+ const { agentId, authorId } = createTestIds();+ const danglingId = new mongoose.Types.ObjectId().toString();++ const newAgent = await createAgent({+ id: agentId,+ name: 'All Scope Create Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills: [danglingId],+ skills_enabled: true,+ skills_scope: SkillsScope.all,+ });++ const reloadedAgent = await getAgent({ id: agentId });++ expect(newAgent.skills).toEqual([]);+ expect(newAgent.skills_enabled).toBe(true);+ expect(newAgent.skills_scope).toBe(SkillsScope.all);+ expect(reloadedAgent!.skills).toEqual([]);+ expect(reloadedAgent!.skills_enabled).toBe(true);+ expect(reloadedAgent!.skills_scope).toBe(SkillsScope.all);+ });++ test('should fail closed when pruning empties the allowlist on create', async () => {+ const { agentId, authorId } = createTestIds();+ const danglingId = new mongoose.Types.ObjectId().toString();++ const newAgent = await createAgent({+ id: agentId,+ name: 'Legacy Create Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills: [danglingId],+ skills_enabled: true,+ });++ const reloadedAgent = await getAgent({ id: agentId });++ expect(newAgent.skills).toEqual([]);+ expect(newAgent.skills_enabled).toBe(false);+ expect(reloadedAgent!.skills).toEqual([]);+ expect(reloadedAgent!.skills_enabled).toBe(false);+ });++ test('should fail closed when pruning empties the allowlist on create with none scope', async () => {+ const { agentId, authorId } = createTestIds();+ const danglingId = new mongoose.Types.ObjectId().toString();++ const newAgent = await createAgent({+ id: agentId,+ name: 'None Scope Create Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills: [danglingId],+ skills_enabled: true,+ skills_scope: SkillsScope.none,+ });++ const reloadedAgent = await getAgent({ id: agentId });++ expect(newAgent.skills).toEqual([]);+ expect(newAgent.skills_enabled).toBe(false);+ expect(reloadedAgent!.skills).toEqual([]);+ expect(reloadedAgent!.skills_enabled).toBe(false);+ expect(reloadedAgent!.skills_scope).toBe(SkillsScope.none);+ });test('should preserve external skill ids on create', async () => {const { agentId, authorId } = createTestIds();@@ -876,6 +946,73 @@ describe('Agent Methods', () => {expect(updatedAgent!.skills_enabled).toBe(false);});+ test('should preserve skills when pruning empties the allowlist for an agent with all scope', async () => {+ const { agentId, authorId } = createTestIds();+ const danglingId = new mongoose.Types.ObjectId().toString();++ await createAgent({+ id: agentId,+ name: 'All Scope Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills_enabled: true,+ skills_scope: SkillsScope.all,+ });++ const updatedAgent = await updateAgent({ id: agentId }, { skills: [danglingId] });++ expect(updatedAgent!.skills).toEqual([]);+ expect(updatedAgent!.skills_enabled).toBe(true);+ expect(updatedAgent!.skills_scope).toBe(SkillsScope.all);+ });++ test('should preserve skills when pruning empties the allowlist for an update-scoped legacy agent', async () => {+ const { agentId, authorId } = createTestIds();+ const danglingId = new mongoose.Types.ObjectId().toString();++ await createAgent({+ id: agentId,+ name: 'Selected Scope Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills_enabled: true,+ });++ const updatedAgent = await updateAgent(+ { id: agentId },+ { skills: [danglingId], skills_scope: SkillsScope.selected },+ );++ expect(updatedAgent!.skills).toEqual([]);+ expect(updatedAgent!.skills_enabled).toBe(true);+ });++ test('should fail closed when pruning empties the allowlist for a none-scoped agent', async () => {+ const { agentId, authorId } = createTestIds();+ const danglingId = new mongoose.Types.ObjectId().toString();++ /** An explicit `none` carrying a true master flag is contradictory: it+ * renders as Off while `skillDeps` still exposes the authoring tools,+ * so it must not opt out of the fail-closed branch. */+ await createAgent({+ id: agentId,+ name: 'None Scope Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills_enabled: true,+ skills_scope: SkillsScope.none,+ });++ const updatedAgent = await updateAgent({ id: agentId }, { skills: [danglingId] });++ expect(updatedAgent!.skills).toEqual([]);+ expect(updatedAgent!.skills_enabled).toBe(false);+ expect(updatedAgent!.skills_scope).toBe(SkillsScope.none);+ });+test('should keep full-catalog semantics for an explicit empty allowlist on update', async () => {const { agentId, authorId } = createTestIds();@@ -2743,6 +2880,78 @@ describe('Agent Methods', () => {);reserveSpy.mockRestore();});+ test('should preserve skills enabled when pruning deleted ids on an all-scoped revert', async () => {+ const agentId = `agent_${uuidv4()}`;+ const authorId = new mongoose.Types.ObjectId();+ const Skill = mongoose.models.Skill;+ const skill = await Skill.create({+ name: 'revert-all-scope-prune-skill',+ description: 'Skill backing the all-scoped revert pruning test.',+ author: authorId,+ authorName: 'Test Author',+ });+ const skillId = skill._id.toString();++ await createAgent({+ id: agentId,+ name: 'All Scope Revert Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills: [skillId],+ skills_enabled: true,+ skills_scope: SkillsScope.all,+ });++ await updateAgent({ id: agentId }, { skills: [], name: 'No Skills Anymore' });+ await Skill.deleteOne({ _id: skill._id });++ const revertedAgent = await revertAgentVersion({ id: agentId }, 0);+ const reloadedAgent = await getAgent({ id: agentId });++ expect(revertedAgent.skills).toEqual([]);+ expect(revertedAgent.skills_enabled).toBe(true);+ expect(revertedAgent.skills_scope).toBe(SkillsScope.all);+ expect(reloadedAgent!.skills).toEqual([]);+ expect(reloadedAgent!.skills_enabled).toBe(true);+ expect(reloadedAgent!.skills_scope).toBe(SkillsScope.all);+ });++ test('should fail closed when pruning deleted ids on a legacy revert', async () => {+ const agentId = `agent_${uuidv4()}`;+ const authorId = new mongoose.Types.ObjectId();+ const Skill = mongoose.models.Skill;+ const skill = await Skill.create({+ name: 'revert-legacy-prune-skill',+ description: 'Skill backing the legacy revert pruning test.',+ author: authorId,+ authorName: 'Test Author',+ });+ const skillId = skill._id.toString();++ await createAgent({+ id: agentId,+ name: 'Legacy Revert Skill Heal Agent',+ provider: 'test',+ model: 'test-model',+ author: authorId,+ skills: [skillId],+ skills_enabled: true,+ });++ await updateAgent({ id: agentId }, { skills: [], name: 'No Skills Anymore' });+ await Skill.deleteOne({ _id: skill._id });++ const revertedAgent = await revertAgentVersion({ id: agentId }, 0);+ const reloadedAgent = await getAgent({ id: agentId });++ expect(revertedAgent.skills).toEqual([]);+ expect(revertedAgent.skills_enabled).toBe(false);+ expect(revertedAgent.skills_scope).toBeUndefined();+ expect(reloadedAgent!.skills).toEqual([]);+ expect(reloadedAgent!.skills_enabled).toBe(false);+ expect(reloadedAgent!.skills_scope).toBeUndefined();+ });test('should prune deleted skill ids when reverting to an older version', async () => {const agentId = `agent_${uuidv4()}`;diff --git a/packages/data-schemas/src/methods/agent.ts b/packages/data-schemas/src/methods/agent.tsindex 5306ca1bb8..10fba14005 100644--- a/packages/data-schemas/src/methods/agent.ts+++ b/packages/data-schemas/src/methods/agent.ts@@ -3,6 +3,7 @@ import {Constants,EToolResources,ResourceType,+ SkillsScope,actionDelimiter,isActionTool,} from 'librechat-data-provider';@@ -15,6 +16,21 @@ import logger from '~/config/winston';const { mcp_delimiter } = Constants;+/**+ * Whether emptying an allowlist has to fall back to disabling skills.+ *+ * An explicit `all` or `selected` scope already defines what an empty+ * allowlist means, so neither is inferred from the array: `all` is the full+ * catalog on purpose, and `selected` with nothing selected resolves to no+ * skills on its own. Every other shape is: a missing scope, which is the+ * legacy form whose meaning came from the array, and an explicit `none`+ * carrying a true master flag, which the API accepts and which `skillDeps`+ * reads as standing permission to expose the skill-authoring tools.+ */+function requiresSkillsDisable(scope: unknown): boolean {+ return scope !== SkillsScope.all && scope !== SkillsScope.selected;+}+/*** Mirrors `TOOL_RESOURCE_KEYS` in `@librechat/api` — the subset of* `EToolResources` that actually carries `file_ids` on an agent document.@@ -610,9 +626,10 @@ export function createAgentMethods(isExternalSkillId,);agentData.skills = prunedSkills;- /** Fail closed when pruning empties a non-empty allowlist — empty +- * enabled means the full catalog, and hygiene must never widen scope. */- if (prunedSkills.length === 0) {+ /** Fail closed when pruning empties a non-empty allowlist: empty ++ * enabled means the full catalog, and hygiene must never widen scope.+ * See `requiresSkillsDisable` for which scopes opt out. */+ if (prunedSkills.length === 0 && requiresSkillsDisable(agentData.skills_scope)) {agentData.skills_enabled = false;}}@@ -755,12 +772,16 @@ export function createAgentMethods(/** Self-heal: drop allowlist ids whose skill no longer exists in the* database or the external registry.* A dangling id keeps the allowlist non-empty while scoping the- * runtime catalog to an empty intersection — silently disabling+ * runtime catalog to an empty intersection, silently disabling* skills for the agent. When pruning empties a non-empty allowlist,* fail closed and disable skills: empty + enabled means the full* catalog, and hygiene must never widen scope. (An explicit user* `skills: []` submission skips this branch and keeps the- * full-catalog semantics.) */+ * full-catalog semantics.)+ *+ * An `all` or `selected` scope opts out, from the payload or the+ * stored document, because it already defines what an empty allowlist+ * means. See `requiresSkillsDisable`. */if (Array.isArray(directUpdates.skills) && directUpdates.skills.length > 0) {const prunedSkills = await filterExistingSkillIds(mongoose,@@ -769,7 +790,9 @@ export function createAgentMethods();directUpdates.skills = prunedSkills;updateData.skills = prunedSkills;- if (prunedSkills.length === 0) {+ const effectiveScope =+ (directUpdates as Record<string, unknown>).skills_scope ?? currentObject.skills_scope;+ if (prunedSkills.length === 0 && requiresSkillsDisable(effectiveScope)) {directUpdates.skills_enabled = false;updateData.skills_enabled = false;}@@ -1403,7 +1426,10 @@ export function createAgentMethods(isExternalSkillId,);revertToVersion.skills = prunedSkills;- if (prunedSkills.length === 0) {+ /** The snapshot carries its own scope, and an All-scoped version keeps+ * its allowlist, so failing closed here would restore the version as+ * Off. See `requiresSkillsDisable`. */+ if (prunedSkills.length === 0 && requiresSkillsDisable(revertToVersion.skills_scope)) {revertToVersion.skills_enabled = false;}}diff --git a/packages/data-schemas/src/methods/skill.spec.ts b/packages/data-schemas/src/methods/skill.spec.tsindex 46707acd5e..2ca08cd2f8 100644--- a/packages/data-schemas/src/methods/skill.spec.ts+++ b/packages/data-schemas/src/methods/skill.spec.ts@@ -821,6 +821,70 @@ describe('Skill CRUD methods', () => {expect(agentAfter?.skills_enabled).toBe(false);});+ it('deleteSkill keeps skills enabled when the entire allowlist is deleted from an all-scoped agent', async () => {+ const { skill } = await methods.createSkill(makeSkillInput({ name: 'all-scoped-only-skill' }));+ const Agent = mongoose.models.Agent;+ const agent = await Agent.create(makeAgentDoc([skill._id.toString()], { skills_scope: 'all' }));++ const res = await methods.deleteSkill(skill._id.toString());+ expect(res.deleted).toBe(true);++ const agentAfter = (await Agent.findById(agent._id).lean()) as {+ skills?: string[];+ skills_enabled?: boolean;+ skills_scope?: string;+ } | null;+ expect(agentAfter?.skills).toEqual([]);+ expect(agentAfter?.skills_enabled).toBe(true);+ expect(agentAfter?.skills_scope).toBe('all');+ });++ it('deleteSkill keeps skills enabled when the entire allowlist is deleted from a selected-scoped agent', async () => {+ const { skill } = await methods.createSkill(+ makeSkillInput({ name: 'selected-scoped-only-skill' }),+ );+ const Agent = mongoose.models.Agent;+ const agent = await Agent.create(+ makeAgentDoc([skill._id.toString()], { skills_scope: 'selected' }),+ );++ const res = await methods.deleteSkill(skill._id.toString());+ expect(res.deleted).toBe(true);++ const agentAfter = (await Agent.findById(agent._id).lean()) as {+ skills?: string[];+ skills_enabled?: boolean;+ skills_scope?: string;+ } | null;+ expect(agentAfter?.skills).toEqual([]);+ expect(agentAfter?.skills_enabled).toBe(true);+ expect(agentAfter?.skills_scope).toBe('selected');+ });++ it('deleteSkill disables skills when the entire allowlist is deleted from a none-scoped agent', async () => {+ /** `skills_enabled: true` with `skills_scope: none` is a shape the API+ * accepts. It renders as Off, and `skillDeps` reads the master flag on+ * its own as permission to expose the authoring tools, so cleanup has to+ * clear it rather than treat the explicit scope as an opt-out. */+ const { skill } = await methods.createSkill(makeSkillInput({ name: 'none-scoped-only-skill' }));+ const Agent = mongoose.models.Agent;+ const agent = await Agent.create(+ makeAgentDoc([skill._id.toString()], { skills_scope: 'none' }),+ );++ const res = await methods.deleteSkill(skill._id.toString());+ expect(res.deleted).toBe(true);++ const agentAfter = (await Agent.findById(agent._id).lean()) as {+ skills?: string[];+ skills_enabled?: boolean;+ skills_scope?: string;+ } | null;+ expect(agentAfter?.skills).toEqual([]);+ expect(agentAfter?.skills_enabled).toBe(false);+ expect(agentAfter?.skills_scope).toBe('none');+ });+it('deleteSkill prunes the deleted id from agent skill allowlists', async () => {const { skill: doomed } = await methods.createSkill(makeSkillInput({ name: 'doomed-skill' }));const { skill: kept } = await methods.createSkill(makeSkillInput({ name: 'kept-skill' }));diff --git a/packages/data-schemas/src/methods/skill.ts b/packages/data-schemas/src/methods/skill.tsindex 7db2efba01..8d03bc16c0 100644--- a/packages/data-schemas/src/methods/skill.ts+++ b/packages/data-schemas/src/methods/skill.ts@@ -1,5 +1,6 @@import {ResourceType,+ SkillsScope,SKILL_NAME_MAX_LENGTH,SKILL_DESCRIPTION_MAX_LENGTH,SKILL_DESCRIPTION_SHORT_THRESHOLD as SKILL_DESCRIPTION_SHORT_THRESHOLD_SHARED,@@ -1650,6 +1651,12 @@ export function createSkillMethods(* accessible catalog at runtime, so a plain `$pull` would silently widen* a deliberately restricted agent. Disabling skills preserves the* restriction until an author makes a new explicit choice.+ *+ * That inference only applies to agents with no explicit `skills_scope`.+ * With a scope persisted, the field already says what an empty allowlist+ * means -- `selected` resolves to no skills on its own, and `all` means the+ * full catalog on purpose -- so disabling them would turn skills off behind+ * the author's back.*/async function removeSkillsFromAgentAllowlists(skillIds: string[]): Promise<void> {if (skillIds.length === 0) {@@ -1659,7 +1666,16 @@ export function createSkillMethods(const Agent = mongoose.models.Agent as Model<IAgent>;try {await Agent.updateMany(- { skills: { $in: ids, $not: { $elemMatch: { $nin: ids } } } },+ {+ skills: { $in: ids, $not: { $elemMatch: { $nin: ids } } },+ /** Only `all` and `selected` opt out: each already defines what an+ * empty allowlist means. A missing field (matched here because+ * `$nin` also matches absent) is the legacy shape, and an explicit+ * `none` with the master flag still true is a contradictory shape+ * the API accepts, which `skillDeps` would otherwise keep reading+ * as permission to expose the skill-authoring tools. */+ skills_scope: { $nin: [SkillsScope.all, SkillsScope.selected] },+ },{ $set: { skills: [], skills_enabled: false } },{ timestamps: false },);