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
🧰 feat: Redesign Agent Builder with Unified Tools Marketplace, Skills & Orchestration (#13952)
Marco Berettaedd614bbff96
diff --git a/api/server/routes/settings.js b/api/server/routes/settings.jsindex c6b7c84b2c..38b353d560 100644--- a/api/server/routes/settings.js+++ b/api/server/routes/settings.js@@ -1,4 +1,5 @@const express = require('express');+const { createToolFavoritesHandlers } = require('@librechat/api');const {updateFavoritesController,getFavoritesController,@@ -8,9 +9,23 @@ const {updateSkillStatesController,} = require('~/server/controllers/SkillStatesController');const { requireJwtAuth } = require('~/server/middleware');+const { getToolFavorites, addToolFavorite, removeToolFavorite } = require('~/models');const router = express.Router();+const toolFavorites = createToolFavoritesHandlers({+ getToolFavorites,+ addToolFavorite,+ removeToolFavorite,+});++router.get('/favorites/tools', requireJwtAuth, toolFavorites.listToolFavorites);+router.put('/favorites/tools/:itemType/:itemId', requireJwtAuth, toolFavorites.addToolFavorite);+router.delete(+ '/favorites/tools/:itemType/:itemId',+ requireJwtAuth,+ toolFavorites.removeToolFavorite,+);router.get('/favorites', requireJwtAuth, getFavoritesController);router.post('/favorites', requireJwtAuth, updateFavoritesController);router.get('/skills/active', requireJwtAuth, getSkillStatesController);diff --git a/client/src/App.jsx b/client/src/App.jsxindex 78ed8438b0..5d20a99200 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -4,8 +4,8 @@ import { DndProvider } from 'react-dnd';import { RouterProvider } from 'react-router-dom';import * as RadixToast from '@radix-ui/react-toast';import { HTML5Backend } from 'react-dnd-html5-backend';-import { Toast, ThemeProvider, ToastProvider } from '@librechat/client';import { QueryClient, QueryClientProvider, QueryCache } from '@tanstack/react-query';+import { Toast, ThemeProvider, ToastProvider, useInputModality } from '@librechat/client';import { ScreenshotProvider, useApiErrorBoundary } from './hooks';import WakeLockManager from '~/components/System/WakeLockManager';import QueryDevtoolsGate from '~/components/QueryDevtoolsGate';@@ -17,6 +17,7 @@ import { router } from './routes';const App = () => {const { setError } = useApiErrorBoundary();+ useInputModality();const queryClient = new QueryClient({defaultOptions: {diff --git a/client/src/Providers/AgentPanelContext.tsx b/client/src/Providers/AgentPanelContext.tsxindex b0d74374b4..f465165e28 100644--- a/client/src/Providers/AgentPanelContext.tsx+++ b/client/src/Providers/AgentPanelContext.tsx@@ -42,13 +42,16 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })const { data: regularTools } = useAvailableToolsQuery(EModelEndpoint.agents);- const { data: mcpData } = useMCPToolsQuery({+ const { data: mcpData, isFetching: mcpToolsFetching } = useMCPToolsQuery({enabled:!isEphemeralAgent(agent_id) &&!isLoading &&availableMCPServers != null &&availableMCPServers.length > 0,});+ /** Tools are still arriving when the query is in flight and nothing is cached+ * yet (e.g., right after a hard refresh). Lets the MCP dialog show a skeleton. */+ const mcpToolsLoading = mcpToolsFetching && mcpData == null;const { agentsConfig, endpointsConfig } = useGetAgentsConfig();const mcpServerNames = useMemo(@@ -148,6 +151,7 @@ export function AgentPanelProvider({ children }: { children: React.ReactNode })agentsConfig,startupConfig,mcpServersMap,+ mcpToolsLoading,setActivePanel,endpointsConfig,setCurrentAgentId,diff --git a/client/src/common/types.ts b/client/src/common/types.tsindex a27743a8f0..66e145fa61 100644--- a/client/src/common/types.ts+++ b/client/src/common/types.ts@@ -233,6 +233,9 @@ export type AgentPanelContextType = {endpointsConfig?: t.TEndpointsConfig | null;/** Pre-computed MCP server information indexed by server key */mcpServersMap: Map<string, MCPServerInfo>;+ /** True while the MCP tools list is being fetched and no data has arrived yet,+ * so consumers can show a skeleton instead of an empty "no tools" state. */+ mcpToolsLoading: boolean;availableMCPServers: MCPServerDefinition[];availableMCPServersMap: t.MCPServersListResponse | undefined;};diff --git a/client/src/components/MCP/McpOAuthDialog.tsx b/client/src/components/MCP/McpOAuthDialog.tsxnew file mode 100644index 0000000000..873478b184--- /dev/null+++ b/client/src/components/MCP/McpOAuthDialog.tsx@@ -0,0 +1,156 @@+import { useState } from 'react';+import { QRCodeSVG } from 'qrcode.react';+import { QrCode, ExternalLink } from 'lucide-react';+import {+ Input,+ Button,+ OGDialog,+ OGDialogTitle,+ OGDialogContent,+ OGDialogDescription,+} from '@librechat/client';+import CopyButton from '~/components/Messages/Content/CopyButton';+import { useLocalize, useCopyToClipboard } from '~/hooks';+import { cn } from '~/utils';++interface McpOAuthDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ serverName: string;+ oauthUrl: string;+ /** The MCP server's icon, shown beside the title when the server provides one. */+ iconUrl?: string;+}++/**+ * Dedicated second dialog, opened ONLY when connecting an MCP server requires+ * OAuth. Offers three ways to finish: continue in this browser, copy the+ * authorization URL to open elsewhere, or reveal a QR code to scan on a phone.+ * Auto-closes once the server connects (the caller derives `open` from+ * connection state).+ */+export default function McpOAuthDialog({+ open,+ onOpenChange,+ serverName,+ oauthUrl,+ iconUrl,+}: McpOAuthDialogProps) {+ const localize = useLocalize();+ const [isCopying, setIsCopying] = useState(false);+ const [showQR, setShowQR] = useState(false);+ const [iconError, setIconError] = useState(false);+ const copyUrl = useCopyToClipboard({ text: oauthUrl });++ if (!oauthUrl) {+ return null;+ }++ return (+ <OGDialog open={open} onOpenChange={onOpenChange}>+ <OGDialogContent className="w-11/12 max-w-md overflow-hidden rounded-2xl">+ <div className="flex items-center gap-2">+ {iconUrl && !iconError && (+ <span+ className="flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-md bg-white"+ aria-hidden="true"+ >+ <img+ src={iconUrl}+ alt=""+ className="h-full w-full object-cover"+ loading="lazy"+ onError={() => setIconError(true)}+ />+ </span>+ )}+ <OGDialogTitle className="text-base font-semibold leading-6 text-text-primary">+ {localize('com_nav_mcp_connect_server', { 0: serverName })}+ </OGDialogTitle>+ </div>+ <OGDialogDescription className="text-sm text-text-secondary">+ {localize('com_ui_mcp_oauth_description')}+ </OGDialogDescription>++ <div className="flex flex-col gap-3 p-1">+ {/* Auto-height reveal via grid-template-rows 0fr -> 1fr so the QR slides+ * open smoothly without a hardcoded height, matching MCPToolItem. */}+ <div+ className={cn(+ 'grid transition-[grid-template-rows] [transition-duration:var(--resize-dur)] [transition-timing-function:var(--resize-ease)] motion-reduce:transition-none',+ showQR ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]',+ )}+ >+ <div className="min-h-0 overflow-hidden">+ <div+ className={cn(+ 'flex flex-col items-center gap-2 pb-1 transition-opacity duration-200 ease-out motion-reduce:transition-none',+ showQR ? 'opacity-100' : 'opacity-0',+ )}+ >+ <div className="rounded-2xl bg-white p-4 shadow-lg">+ <QRCodeSVG+ value={oauthUrl}+ size={180}+ marginSize={2}+ title={localize('com_ui_mcp_oauth_qr_code_description')}+ />+ </div>+ <span className="text-xs text-text-secondary">+ {localize('com_ui_mcp_oauth_scan_qr')}+ </span>+ </div>+ </div>+ </div>++ <div className="relative">+ <Input+ type="text"+ readOnly+ dir="ltr"+ value={oauthUrl}+ aria-label={localize('com_ui_copy_link')}+ onFocus={(event) => event.currentTarget.select()}+ className="pr-10 text-text-secondary"+ data-testid="mcp-oauth-url"+ />+ <CopyButton+ iconOnly+ isCopied={isCopying}+ label={localize('com_ui_copy_link')}+ onClick={() => {+ if (!isCopying) {+ copyUrl(setIsCopying);+ }+ }}+ className="absolute right-1 top-1/2 -translate-y-1/2"+ />+ </div>++ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="outline"+ size="icon"+ className="shrink-0"+ aria-expanded={showQR}+ aria-label={showQR ? localize('com_ui_hide_qr') : localize('com_ui_show_qr')}+ onClick={() => setShowQR((value) => !value)}+ >+ <QrCode className="size-4" aria-hidden="true" />+ </Button>+ <Button+ type="button"+ variant="submit"+ className="flex-1"+ onClick={() => window.open(oauthUrl, '_blank', 'noopener,noreferrer')}+ >+ {localize('com_ui_continue_oauth')}+ <ExternalLink className="size-4" aria-hidden="true" />+ </Button>+ </div>+ </div>+ </OGDialogContent>+ </OGDialog>+ );+}diff --git a/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsx b/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsxnew file mode 100644index 0000000000..1a747ca32f--- /dev/null+++ b/client/src/components/MCP/__tests__/McpOAuthDialog.spec.tsx@@ -0,0 +1,100 @@+import type { ReactNode } from 'react';+import '@testing-library/jest-dom/extend-expect';+import { render, screen, fireEvent } from '@testing-library/react';+import McpOAuthDialog from '../McpOAuthDialog';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useCopyToClipboard: () => jest.fn(),+}));++jest.mock('~/components/Messages/Content/CopyButton', () => ({+ __esModule: true,+ default: ({ onClick }: { onClick: () => void }) => (+ <button type="button" data-testid="copy-url" onClick={onClick} />+ ),+}));++jest.mock('@librechat/client', () => {+ const React = jest.requireActual('react');+ const Pass = ({ children }: { children?: ReactNode }) =>+ React.createElement('div', null, children);+ return {+ OGDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>+ open ? React.createElement('div', null, children) : null,+ OGDialogContent: Pass,+ OGDialogTitle: Pass,+ OGDialogDescription: Pass,+ Input: ({+ value,+ 'data-testid': testId,+ 'aria-label': ariaLabel,+ }: {+ value?: string;+ 'data-testid'?: string;+ 'aria-label'?: string;+ }) =>+ React.createElement('input', {+ readOnly: true,+ value,+ 'data-testid': testId,+ 'aria-label': ariaLabel,+ }),+ Button: ({+ children,+ onClick,+ 'aria-label': ariaLabel,+ 'aria-expanded': ariaExpanded,+ }: {+ children?: ReactNode;+ onClick?: () => void;+ 'aria-label'?: string;+ 'aria-expanded'?: boolean;+ }) =>+ React.createElement(+ 'button',+ { type: 'button', onClick, 'aria-label': ariaLabel, 'aria-expanded': ariaExpanded },+ children,+ ),+ };+});++const baseProps = {+ open: true,+ onOpenChange: jest.fn(),+ serverName: 'srv',+ oauthUrl: 'https://oauth.example/authorize?x=1',+};++describe('McpOAuthDialog', () => {+ test('renders the continue button, copyable URL, and a QR toggle (collapsed by default)', () => {+ render(<McpOAuthDialog {...baseProps} />);+ expect(screen.getByText('com_ui_continue_oauth')).toBeInTheDocument();+ expect(screen.getByTestId('mcp-oauth-url')).toHaveValue(baseProps.oauthUrl);+ expect(screen.getByTestId('copy-url')).toBeInTheDocument();+ const toggle = screen.getByLabelText('com_ui_show_qr');+ expect(toggle).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByLabelText('com_ui_hide_qr')).not.toBeInTheDocument();+ });++ test('toggling flips the QR label and aria-expanded', () => {+ render(<McpOAuthDialog {...baseProps} />);+ fireEvent.click(screen.getByLabelText('com_ui_show_qr'));+ const toggle = screen.getByLabelText('com_ui_hide_qr');+ expect(toggle).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('com_ui_mcp_oauth_scan_qr')).toBeInTheDocument();+ });++ test('Continue opens the OAuth URL in a new tab', () => {+ const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);+ render(<McpOAuthDialog {...baseProps} />);+ fireEvent.click(screen.getByText('com_ui_continue_oauth'));+ expect(openSpy).toHaveBeenCalledWith(baseProps.oauthUrl, '_blank', 'noopener,noreferrer');+ openSpy.mockRestore();+ });++ test('renders nothing without an OAuth URL', () => {+ const { container } = render(<McpOAuthDialog {...baseProps} oauthUrl="" />);+ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/components/Plugins/Store/PluginAuthForm.tsx b/client/src/components/Plugins/Store/PluginAuthForm.tsxindex effc3643c3..3bf7b20a1e 100644--- a/client/src/components/Plugins/Store/PluginAuthForm.tsx+++ b/client/src/components/Plugins/Store/PluginAuthForm.tsx@@ -1,125 +1,219 @@-import { Save } from 'lucide-react';-import { useForm } from 'react-hook-form';-import { HoverCard, HoverCardTrigger, SecretInput } from '@librechat/client';-import { TPlugin, TPluginAuthConfig, TPluginAction } from 'librechat-data-provider';+import { useForm, useWatch } from 'react-hook-form';+import {+ Input,+ Label,+ Button,+ Spinner,+ HoverCard,+ SecretInput,+ HoverCardTrigger,+} from '@librechat/client';+import type { TPlugin, TPluginAuthConfig, TPluginAction } from 'librechat-data-provider';+import type { RegisterOptions } from 'react-hook-form';import PluginTooltip from './PluginTooltip';import { useLocalize } from '~/hooks';+/**+ * Format-hint placeholders per credential, keyed by the primary `authField`+ * (the part before any `||` alternates). These are literal format tokens+ * (e.g. an OpenAI key's `sk-` prefix), not translatable copy, so they are not+ * localized. Fields without a recognizable format fall through to no+ * placeholder.+ */+const AUTH_PLACEHOLDERS: Record<string, string> = {+ // OpenAI-issued keys start with "sk-"+ OPENAI_API_KEY: 'sk-...',+ DALLE_API_KEY: 'sk-...',+ DALLE2_API_KEY: 'sk-...',+ DALLE3_API_KEY: 'sk-...',+ IMAGE_GEN_OAI_API_KEY: 'sk-...',+ // Google AI / Cloud keys start with "AIza"+ GEMINI_API_KEY: 'AIza...',+ GOOGLE_KEY: 'AIza...',+ GOOGLE_SEARCH_API_KEY: 'AIza...',+ GOOGLE_CSE_ID: 'a1b2c3d4e5f6g7h8i',+ // Tavily keys start with "tvly-"+ TAVILY_API_KEY: 'tvly-...',+ // Wolfram AppID format+ WOLFRAM_APP_ID: 'XXXXXX-XXXXXXXXXX',+ // URL / endpoint / index-name fields+ SD_WEBUI_URL: 'http://localhost:7860',+ AZURE_AI_SEARCH_SERVICE_ENDPOINT: 'https://<service>.search.windows.net',+ AZURE_AI_SEARCH_INDEX_NAME: 'my-index',+};++/**+ * Endpoint/URL fields, keyed by primary `authField`. These get a hard validation+ * rule: a value that isn't a valid http(s) URL blocks submission.+ */+const URL_FIELDS = new Set<string>(['SD_WEBUI_URL', 'AZURE_AI_SEARCH_SERVICE_ENDPOINT']);++/**+ * Known credential prefixes per primary `authField`. A value missing its expected+ * prefix surfaces a non-blocking hint, never an error — key formats drift over+ * time, so we guide without trapping a key that just doesn't match.+ */+const AUTH_PREFIXES: Record<string, string> = {+ OPENAI_API_KEY: 'sk-',+ DALLE_API_KEY: 'sk-',+ DALLE2_API_KEY: 'sk-',+ DALLE3_API_KEY: 'sk-',+ IMAGE_GEN_OAI_API_KEY: 'sk-',+ GEMINI_API_KEY: 'AIza',+ GOOGLE_KEY: 'AIza',+ GOOGLE_SEARCH_API_KEY: 'AIza',+ TAVILY_API_KEY: 'tvly-',+};++const isValidUrl = (value: string): boolean => {+ try {+ const { protocol } = new URL(value);+ return protocol === 'http:' || protocol === 'https:';+ } catch {+ return false;+ }+};+type TPluginAuthFormProps = {plugin: TPlugin | undefined;onSubmit: (installActionData: TPluginAction) => void;isEntityTool?: boolean;+ /** External in-flight state (e.g. a mutation) so the button reflects the real save. */+ isSaving?: boolean;+ /** When provided, renders a Cancel button (used when re-editing saved credentials). */+ onCancel?: () => void;};-function PluginAuthForm({ plugin, onSubmit, isEntityTool }: TPluginAuthFormProps) {+function PluginAuthForm({+ plugin,+ onSubmit,+ isEntityTool,+ isSaving,+ onCancel,+}: TPluginAuthFormProps) {const {register,+ control,handleSubmit,formState: { errors, isDirty, isValid, isSubmitting },- } = useForm();+ } = useForm({ mode: 'onChange' });const localize = useLocalize();+ const watchedValues = useWatch({ control });const authConfig = plugin?.authConfig ?? [];const allFieldsOptional = authConfig.length > 0 && authConfig.every((c) => c.optional === true);+ const saving = isSubmitting || isSaving === true;++ const submit = handleSubmit((auth) =>+ onSubmit({+ pluginKey: plugin?.pluginKey ?? '',+ action: 'install',+ auth,+ isEntityTool,+ }),+ );return (- <div className="flex w-full flex-col items-center gap-2">- <div className="grid w-full gap-6 sm:grid-cols-2">- <form- className="col-span-1 flex w-full flex-col items-start justify-start gap-2"- method="POST"- onSubmit={handleSubmit((auth) =>- onSubmit({- pluginKey: plugin?.pluginKey ?? '',- action: 'install',- auth,- isEntityTool,- }),- )}- >- {authConfig.map((config: TPluginAuthConfig, i: number) => {- const authField = config.authField.split('||')[0];- const isOptional = config.optional === true;- const inputClassName =- 'flex h-10 max-h-10 w-full resize-none rounded-md border border-gray-200 bg-transparent px-3 py-2 text-sm text-gray-700 shadow-[0_0_10px_rgba(0,0,0,0.05)] outline-none placeholder:text-gray-400 focus:border-gray-400 focus:bg-gray-50 focus:outline-none focus:ring-0 focus:ring-gray-400 focus:ring-opacity-0 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-500 dark:bg-gray-700 dark:text-gray-50 dark:shadow-[0_0_15px_rgba(0,0,0,0.10)] dark:focus:border-gray-400 focus:dark:bg-gray-600 dark:focus:outline-none dark:focus:ring-0 dark:focus:ring-gray-400 dark:focus:ring-offset-0';- const sharedProps = {- id: authField,- 'aria-invalid': !!errors[authField],- 'aria-describedby': `${authField}-error`,- 'aria-label': config.label,- 'aria-required': !isOptional,- /* autoFocus is generally disorienting, but here the required field must be navigated to- * anyway, and the form emulates a modal opening where users expect focus to shift. */- autoFocus: i === 0,- className: inputClassName,- ...register(- authField,- isOptional- ? {}- : {- required: `${config.label} is required.`,- minLength: {- value: 1,- message: `${config.label} must be at least 1 character long`,- },- },- ),+ <form className="flex w-full flex-col" method="POST" onSubmit={submit}>+ <div className="flex max-h-[40vh] flex-col gap-4 overflow-y-auto pr-1">+ {authConfig.map((config: TPluginAuthConfig, i: number) => {+ const authField = config.authField.split('||')[0];+ const isOptional = config.optional === true;+ const rules: RegisterOptions = {};+ if (!isOptional) {+ rules.required = `${config.label} is required.`;+ rules.minLength = {+ value: 1,+ message: `${config.label} must be at least 1 character long`,};- return (- <div key={`${authField}-${i}`} className="flex w-full flex-col gap-1">- <label- htmlFor={authField}- className="mb-1 text-left text-sm font-medium text-gray-700/70 dark:text-gray-50/70"- >- {config.label}- </label>- <HoverCard openDelay={300}>- <HoverCardTrigger className="grid w-full items-center gap-2">- {config.sensitive === false ? (- <input type="text" autoComplete="off" {...sharedProps} />- ) : (- <SecretInput- autoComplete="new-password"- data-lpignore="true"- data-1p-ignore="true"- controlsOnHover- {...sharedProps}- />- )}- </HoverCardTrigger>- <PluginTooltip content={config.description} position="right" />- </HoverCard>- {errors[authField] && (- <span role="alert" className="mt-1 text-sm text-red-400">- {String(errors?.[authField]?.message ?? '')}- </span>- )}- </div>- );- })}- <button- disabled={allFieldsOptional ? isSubmitting : !isDirty || !isValid || isSubmitting}- type="button"- className="btn btn-primary relative"- onClick={() => {- handleSubmit((auth) =>- onSubmit({- pluginKey: plugin?.pluginKey ?? '',- action: 'install',- auth,- isEntityTool,- }),- )();- }}- >- <div className="flex items-center justify-center gap-2">- {localize('com_ui_save')}- <Save className="flex h-4 w-4 items-center stroke-2" aria-hidden="true" />+ }+ if (URL_FIELDS.has(authField)) {+ rules.validate = (value: string) =>+ !value || isValidUrl(value) || localize('com_ui_auth_invalid_url');+ }+ const hasError = !!errors[authField];+ const expectedPrefix = AUTH_PREFIXES[authField];+ const value = String(watchedValues?.[authField] ?? '');+ const showHint =+ !hasError && !!expectedPrefix && value.length > 0 && !value.startsWith(expectedPrefix);+ const describedBy = showHint+ ? `${authField}-error ${authField}-hint`+ : `${authField}-error`;+ const reserveMessage = !isOptional || URL_FIELDS.has(authField) || !!expectedPrefix;+ const sharedProps = {+ id: authField,+ placeholder: AUTH_PLACEHOLDERS[authField],+ 'aria-invalid': hasError,+ 'aria-describedby': describedBy,+ 'aria-label': config.label,+ 'aria-required': !isOptional,+ /* autoFocus is generally disorienting, but here the required field must be navigated to+ * anyway, and the form emulates a modal opening where users expect focus to shift. */+ autoFocus: i === 0,+ className:+ 'hover:border-border-light focus-visible:border-border-light focus-visible:ring-2 focus-visible:ring-ring-primary',+ ...register(authField, rules),+ };+ return (+ <div key={`${authField}-${i}`} className="flex w-full flex-col gap-1.5">+ <Label htmlFor={authField} className="text-sm font-medium text-text-secondary">+ {config.label}+ </Label>+ <HoverCard openDelay={300}>+ <HoverCardTrigger className="block w-full">+ {config.sensitive === false ? (+ <Input type="text" autoComplete="off" {...sharedProps} />+ ) : (+ <SecretInput+ autoComplete="new-password"+ data-lpignore="true"+ data-1p-ignore="true"+ controlsOnHover+ {...sharedProps}+ />+ )}+ </HoverCardTrigger>+ <PluginTooltip content={config.description} position="right" />+ </HoverCard>+ {reserveMessage && (+ <div className="min-h-4 text-xs leading-4">+ {hasError && (+ <span id={`${authField}-error`} role="alert" className="text-red-500">+ {String(errors?.[authField]?.message ?? '')}+ </span>+ )}+ {showHint && (+ <span+ id={`${authField}-hint`}+ aria-live="polite"+ className="text-amber-600 dark:text-amber-500"+ >+ {localize('com_ui_auth_format_hint', { 0: expectedPrefix })}+ </span>+ )}+ </div>+ )}</div>- </button>- </form>+ );+ })}+ </div>+ <div className="mt-4 flex justify-end gap-2">+ {onCancel && (+ <Button type="button" variant="outline" disabled={saving} onClick={onCancel}>+ {localize('com_ui_cancel')}+ </Button>+ )}+ <Button+ type="button"+ variant="submit"+ disabled={allFieldsOptional ? saving : !isDirty || !isValid || saving}+ onClick={submit}+ >+ {saving && <Spinner className="size-4" aria-hidden="true" />}+ {saving ? localize('com_ui_saving') : localize('com_ui_save')}+ </Button></div>- </div>+ </form>);}diff --git a/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsx b/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsxindex d80e99e04e..0b3c7402cc 100644--- a/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsx+++ b/client/src/components/Plugins/Store/__tests__/PluginAuthForm.spec.tsx@@ -1,5 +1,5 @@-import { render, screen } from 'test/layout-test-utils';import userEvent from '@testing-library/user-event';+import { render, screen } from 'test/layout-test-utils';import PluginAuthForm from '../PluginAuthForm';describe('PluginAuthForm', () => {@@ -48,6 +48,17 @@ describe('PluginAuthForm', () => {expect(urlField.parentElement?.querySelector('button')).toBeNull();});+ it('shows a format-hint placeholder for recognized credential fields', () => {+ const openAiPlugin = {+ pluginKey: 'dalle',+ authConfig: [{ authField: 'DALLE3_API_KEY||DALLE_API_KEY', label: 'OpenAI API Key' }],+ };+ //@ts-ignore - dont need all props of plugin+ render(<PluginAuthForm plugin={openAiPlugin} onSubmit={onSubmit} />);++ expect(screen.getByLabelText('OpenAI API Key')).toHaveAttribute('placeholder', 'sk-...');+ });+it('calls the onSubmit function with the form data when submitted', async () => {//@ts-ignore - dont need all props of pluginrender(<PluginAuthForm plugin={plugin} onSubmit={onSubmit} />);@@ -65,4 +76,29 @@ describe('PluginAuthForm', () => {},});});++ it('reflects an external saving state as a disabled, in-progress submit button', () => {+ //@ts-ignore - dont need all props of plugin+ render(<PluginAuthForm plugin={plugin} onSubmit={onSubmit} isSaving />);++ const button = screen.getByRole('button', { name: 'Saving...' });+ expect(button).toBeDisabled();+ expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument();+ });++ it('renders a Cancel button when onCancel is provided and invokes it on click', async () => {+ const onCancel = jest.fn();+ //@ts-ignore - dont need all props of plugin+ render(<PluginAuthForm plugin={plugin} onSubmit={onSubmit} onCancel={onCancel} />);++ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(onCancel).toHaveBeenCalledTimes(1);+ expect(onSubmit).not.toHaveBeenCalled();+ });++ it('does not render a Cancel button by default', () => {+ //@ts-ignore - dont need all props of plugin+ render(<PluginAuthForm plugin={plugin} onSubmit={onSubmit} />);+ expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument();+ });});diff --git a/client/src/components/SidePanel/Agents/ActionsInput.tsx b/client/src/components/SidePanel/Agents/ActionsInput.tsxindex 82b7c7f07b..4311311734 100644--- a/client/src/components/SidePanel/Agents/ActionsInput.tsx+++ b/client/src/components/SidePanel/Agents/ActionsInput.tsx@@ -1,12 +1,23 @@import { useState, useEffect } from 'react';import debounce from 'lodash/debounce';+import { Maximize2 } from 'lucide-react';import { useFormContext } from 'react-hook-form';-import { Spinner, useToastContext } from '@librechat/client';import {validateAndParseOpenAPISpec,openapiToFunction,AuthTypeEnum,} from 'librechat-data-provider';+import {+ Button,+ Spinner,+ Textarea,+ OGDialog,+ OGDialogTitle,+ OGDialogHeader,+ OGDialogContent,+ OGDialogDescription,+ useToastContext,+} from '@librechat/client';import type {Action,FunctionTool,@@ -15,8 +26,8 @@ import type {} from 'librechat-data-provider';import type { ActionAuthForm } from '~/common';import type { Spec } from './ActionsTable';+import { ActionsTable, ActionsTableSkeleton, columns } from './ActionsTable';import ActionCallback from '~/components/SidePanel/Builder/ActionCallback';-import { ActionsTable, columns } from './ActionsTable';import { useUpdateAgentAction } from '~/data-provider';import { useLocalize } from '~/hooks';import { logger } from '~/utils';@@ -29,19 +40,25 @@ const debouncedValidation = debounce(800,);+/** Placeholder rows shaped like the "Available actions" table (Name / Method / Path). */export default function ActionsInput({action,agent_id,setAction,+ onCreated,+ footerStart,}: {action?: Action;agent_id?: string;setAction: React.Dispatch<React.SetStateAction<Action | undefined>>;+ onCreated?: () => void;+ footerStart?: React.ReactNode;}) {const handleResult = (result: ValidationResult) => {if (!result.status) {setData(null);setFunctions(null);+ setIsValidating(false);}setValidationResult(result);};@@ -51,6 +68,8 @@ export default function ActionsInput({const { handleSubmit, reset } = useFormContext<ActionAuthForm>();const [validationResult, setValidationResult] = useState<null | ValidationResult>(null);const [inputValue, setInputValue] = useState('');+ const [isValidating, setIsValidating] = useState(false);+ const [isSchemaDialogOpen, setIsSchemaDialogOpen] = useState(false);const [data, setData] = useState<Spec[] | null>(null);const [functions, setFunctions] = useState<FunctionTool[] | null>(null);@@ -61,7 +80,8 @@ export default function ActionsInput({return;}setInputValue(rawSpec);- debouncedValidation(rawSpec, handleResult);+ setIsValidating(true);+ handleResult(validateAndParseOpenAPISpec(rawSpec));}, [action?.metadata.raw_spec]);useEffect(() => {@@ -82,16 +102,21 @@ export default function ActionsInput({setData(specs);setValidationResult(null);setFunctions(functionSignatures.map((f) => f.toObjectTool()));+ setIsValidating(false);}, [validationResult]);const updateAgentAction = useUpdateAgentAction({onSuccess(data) {+ const wasCreate = !action?.action_id;showToast({message: localize('com_assistants_update_actions_success'),status: 'success',});reset();setAction(data[1]);+ if (wasCreate) {+ onCreated?.();+ }},onError(error) {showToast({@@ -183,8 +208,10 @@ export default function ActionsInput({if (!newValue) {setData(null);setFunctions(null);+ setIsValidating(false);return setValidationResult(null);}+ setIsValidating(true);debouncedValidation(newValue, handleResult);};@@ -200,72 +227,103 @@ export default function ActionsInput({return localize('com_ui_create');};+ const validationError =+ validationResult && validationResult.message !== 'OpenAPI spec is valid.'+ ? validationResult.message+ : null;+ const showSkeleton = isValidating && !data;+return (<>- <div className="flex min-h-0 flex-1 flex-col">- <div className="mb-1 flex flex-wrap items-center justify-between gap-4">+ <div className="flex shrink-0 flex-col">+ <div className="mb-1 flex flex-wrap items-center justify-between gap-2"><labelhtmlFor="schemaInput"- className="text-token-text-primary whitespace-nowrap text-sm font-medium"+ className="whitespace-nowrap text-sm font-medium text-text-primary">{localize('com_ui_schema')}</label>+ <button+ type="button"+ onClick={() => setIsSchemaDialogOpen(true)}+ aria-label={localize('com_ui_expand_editor')}+ title={localize('com_ui_expand_editor')}+ className="inline-flex h-7 w-7 items-center justify-center rounded-lg text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <Maximize2 className="h-4 w-4" strokeWidth={1.75} aria-hidden={true} />+ </button></div>- <div className="border-token-border-medium bg-token-surface-primary hover:border-token-border-hover mb-4 flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border ring-0">- <div className="relative flex min-h-0 flex-1 flex-col">- <textarea- id="schemaInput"- value={inputValue}- onChange={handleInputChange}- spellCheck="false"- placeholder={localize('com_ui_enter_openapi_schema')}- className="text-token-text-primary block min-h-[12rem] flex-1 resize-y bg-transparent p-2 font-mono text-xs outline-none focus:ring-1 focus:ring-border-light"- />+ <Textarea+ id="schemaInput"+ value={inputValue}+ onChange={handleInputChange}+ spellCheck="false"+ placeholder={localize('com_ui_enter_openapi_schema')}+ className="block min-h-[12rem] w-full resize-y rounded-lg border border-border-light bg-transparent p-3 font-mono text-xs leading-relaxed transition-colors focus-visible:border-border-heavy focus-visible:ring-0"+ />+ {validationError && (+ <div className="mt-1.5 text-xs text-red-500">+ {validationError.split('\n').map((line: string, i: number) => (+ <div key={i}>{line}</div>+ ))}</div>- {validationResult && validationResult.message !== 'OpenAPI spec is valid.' && (- <div className="border-token-border-light border-t p-2 text-red-500">- {validationResult.message.split('\n').map((line: string, i: number) => (- <div key={i}>{line}</div>- ))}- </div>- )}- </div>+ )}</div>- {!!data && (- <div className="my-2">- <div className="flex items-center">- <label className="text-token-text-primary block text-sm font-medium">- {localize('com_assistants_available_actions')}- </label>+ {(data || showSkeleton) && (+ <div className="mt-4 flex min-h-0 flex-1 flex-col">+ <label className="mb-1 block shrink-0 text-sm font-medium text-text-primary">+ {localize('com_assistants_available_actions')}+ </label>+ <div className="min-h-0 flex-1 overflow-y-auto">+ {data ? <ActionsTable columns={columns} data={data} /> : <ActionsTableSkeleton />}</div>- <ActionsTable columns={columns} data={data} /></div>)}- <div className="relative my-1">+ <div className="mt-4 shrink-0"><ActionCallback action_id={action?.action_id} />- <div className="mb-1.5 flex items-center">- <label className="text-token-text-primary block text-sm font-medium">- {localize('com_ui_privacy_policy_url')}- </label>- </div>- <div className="border-token-border-medium bg-token-surface-primary hover:border-token-border-hover flex h-9 w-full rounded-lg border">- <input- type="text"- placeholder="https://api.example-weather-app.com/privacy"- className="flex-1 rounded-lg bg-transparent px-3 py-1.5 text-sm outline-none placeholder:text-text-secondary-alt focus:ring-1 focus:ring-border-light"- />- </div></div>- <div className="mt-auto flex items-center justify-end pt-2">- <button- disabled={!functions || !functions.length}- onClick={saveAction}- className="focus:shadow-outline flex min-w-[100px] items-center justify-center rounded bg-green-500 px-4 py-2 font-semibold text-white hover:bg-green-400 focus:border-green-500 focus:outline-none focus:ring-0 disabled:bg-green-400"+ <div className="flex shrink-0 items-center justify-between gap-2 pt-4">+ <div className="flex items-center">{footerStart}</div>+ <Buttontype="button"+ variant="submit"+ onClick={saveAction}+ disabled={!functions || !functions.length}+ className="min-w-[100px]">{getButtonContent()}- </button>+ </Button></div>++ <OGDialog open={isSchemaDialogOpen} onOpenChange={setIsSchemaDialogOpen}>+ <OGDialogContent className="flex h-[85vh] max-h-[85vh] w-11/12 max-w-5xl flex-col gap-3 p-5">+ <OGDialogHeader className="space-y-0 pr-10">+ <OGDialogTitle className="text-left text-sm font-medium text-text-primary">+ {localize('com_ui_schema')}+ </OGDialogTitle>+ <OGDialogDescription className="sr-only">+ {localize('com_ui_enter_openapi_schema')}+ </OGDialogDescription>+ </OGDialogHeader>+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-border-medium bg-surface-secondary focus-within:border-border-heavy">+ <Textarea+ value={inputValue}+ onChange={handleInputChange}+ spellCheck="false"+ placeholder={localize('com_ui_enter_openapi_schema')}+ aria-label={localize('com_ui_schema')}+ className="min-h-0 flex-1 resize-none border-0 bg-transparent p-4 font-mono text-[13px] leading-relaxed focus-visible:ring-0"+ />+ </div>+ {validationError && (+ <div className="max-h-24 shrink-0 overflow-y-auto text-xs text-red-500">+ {validationError.split('\n').map((line: string, i: number) => (+ <div key={i}>{line}</div>+ ))}+ </div>+ )}+ </OGDialogContent>+ </OGDialog></>);}diff --git a/client/src/components/SidePanel/Agents/ActionsPanel.tsx b/client/src/components/SidePanel/Agents/ActionsPanel.tsxdeleted file mode 100644index ec080cf9cb..0000000000--- a/client/src/components/SidePanel/Agents/ActionsPanel.tsx+++ /dev/null@@ -1,167 +0,0 @@-import { useEffect } from 'react';-import { ChevronLeft } from 'lucide-react';-import { useForm, FormProvider } from 'react-hook-form';-import {- AuthTypeEnum,- AuthorizationTypeEnum,- TokenExchangeMethodEnum,-} from 'librechat-data-provider';-import {- Label,- OGDialog,- TrashIcon,- OGDialogTrigger,- useToastContext,- OGDialogTemplate,-} from '@librechat/client';-import type { ActionAuthForm } from '~/common';-import ActionsAuth from '~/components/SidePanel/Builder/ActionsAuth';-import { useAgentPanelContext } from '~/Providers/AgentPanelContext';-import { useDeleteAgentAction } from '~/data-provider';-import { Panel, isEphemeralAgent } from '~/common';-import ActionsInput from './ActionsInput';-import { useLocalize } from '~/hooks';--export default function ActionsPanel() {- const localize = useLocalize();- const { showToast } = useToastContext();- const { setActivePanel, action, setAction, agent_id } = useAgentPanelContext();- const deleteAgentAction = useDeleteAgentAction({- onSuccess: () => {- showToast({- message: localize('com_assistants_delete_actions_success'),- status: 'success',- });- setActivePanel(Panel.builder);- setAction(undefined);- },- onError(error) {- showToast({- message: (error as Error).message ?? localize('com_assistants_delete_actions_error'),- status: 'error',- });- },- });-- const methods = useForm<ActionAuthForm>({- defaultValues: {- /* General */- type: AuthTypeEnum.None,- saved_auth_fields: false,- /* API key */- api_key: '',- authorization_type: AuthorizationTypeEnum.Basic,- custom_auth_header: '',- /* OAuth */- oauth_client_id: '',- oauth_client_secret: '',- authorization_url: '',- client_url: '',- scope: '',- token_exchange_method: TokenExchangeMethodEnum.DefaultPost,- },- });-- const { reset } = methods;-- useEffect(() => {- if (action?.metadata.auth) {- reset({- type: action.metadata.auth.type || AuthTypeEnum.None,- saved_auth_fields: false,- api_key: action.metadata.api_key ?? '',- authorization_type: action.metadata.auth.authorization_type || AuthorizationTypeEnum.Basic,- oauth_client_id: action.metadata.oauth_client_id ?? '',- oauth_client_secret: action.metadata.oauth_client_secret ?? '',- authorization_url: action.metadata.auth.authorization_url ?? '',- client_url: action.metadata.auth.client_url ?? '',- scope: action.metadata.auth.scope ?? '',- token_exchange_method:- action.metadata.auth.token_exchange_method ?? TokenExchangeMethodEnum.DefaultPost,- });- }- }, [action, reset]);-- return (- <FormProvider {...methods}>- <form className="h-full grow overflow-hidden">- <div className="h-full overflow-auto px-2 text-sm">- <div className="flex min-h-full flex-col pb-3">- <div>- <div className="relative flex flex-col items-center px-16 pt-2 text-center">- <div className="absolute left-0 top-6">- <button- type="button"- className="btn btn-neutral relative"- onClick={() => {- setActivePanel(Panel.builder);- setAction(undefined);- }}- >- <div className="flex w-full items-center justify-center gap-2">- <ChevronLeft />- </div>- </button>- </div>-- {!!action && (- <OGDialog>- <OGDialogTrigger asChild>- <div className="absolute right-0 top-6">- <button- type="button"- disabled={isEphemeralAgent(agent_id) || !action.action_id}- className="btn btn-neutral border-token-border-light relative h-9 rounded-lg font-medium"- >- <TrashIcon className="text-red-500" />- </button>- </div>- </OGDialogTrigger>- <OGDialogTemplate- showCloseButton={false}- title={localize('com_ui_delete_action')}- className="max-w-[450px]"- main={- <Label className="text-left text-sm font-medium">- {localize('com_ui_delete_action_confirm')}- </Label>- }- selection={{- selectHandler: () => {- if (isEphemeralAgent(agent_id)) {- return showToast({- message: localize('com_agents_no_agent_id_error'),- status: 'error',- });- }- deleteAgentAction.mutate({- action_id: action.action_id,- agent_id: agent_id || '',- });- },- selectClasses:- 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',- selectText: localize('com_ui_delete'),- }}- />- </OGDialog>- )}-- <div className="text-xl font-medium">- {(action ? 'Edit' : 'Add') + ' ' + 'actions'}- </div>- <div className="text-xs text-text-secondary">- {localize('com_assistants_actions_info')}- </div>- </div>- <ActionsAuth />- </div>- <div className="flex flex-1 flex-col">- <ActionsInput action={action} agent_id={agent_id} setAction={setAction} />- </div>- </div>- </div>- </form>- </FormProvider>- );-}diff --git a/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx b/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsxindex 23d491f8c7..6aa881100c 100644--- a/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx+++ b/client/src/components/SidePanel/Agents/ActionsTable/Columns.tsx@@ -1,4 +1,7 @@import type { ColumnDef } from '@tanstack/react-table';+import type { TranslationKeys } from '~/hooks';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';export type Spec = {name: string;@@ -7,48 +10,49 @@ export type Spec = {domain: string;};-export const fakeData: Spec[] = [- {- name: 'listPets',- method: 'get',- path: '/pets',- domain: 'petstore.swagger.io',- },- {- name: 'createPets',- method: 'post',- path: '/pets',- domain: 'petstore.swagger.io',- },- {- name: 'showPetById',- method: 'get',- path: '/pets/{petId}',- domain: 'petstore.swagger.io',- },-];+/** Color-codes the HTTP verb the way API docs do, so the method reads at a glance. */+const METHOD_STYLES: Record<string, string> = {+ get: 'bg-sky-500/10 text-sky-600 dark:text-sky-400',+ post: 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400',+ put: 'bg-amber-500/10 text-amber-600 dark:text-amber-400',+ patch: 'bg-violet-500/10 text-violet-600 dark:text-violet-400',+ delete: 'bg-red-500/10 text-red-600 dark:text-red-400',+};++function HeaderCell({ labelKey }: { labelKey: TranslationKeys }) {+ const localize = useLocalize();+ return <>{localize(labelKey)}</>;+}++function MethodBadge({ method }: { method: string }) {+ return (+ <span+ className={cn(+ 'inline-flex items-center rounded-md px-1.5 py-0.5 font-mono text-[11px] font-semibold uppercase tracking-wide',+ METHOD_STYLES[method.toLowerCase()] ?? 'bg-surface-secondary text-text-secondary',+ )}+ >+ {method}+ </span>+ );+}export const columns: ColumnDef<Spec>[] = [{- header: 'Name',accessorKey: 'name',+ header: () => <HeaderCell labelKey="com_ui_name" />,+ cell: ({ row }) => <span className="font-medium text-text-primary">{row.original.name}</span>,},{- header: 'Method',accessorKey: 'method',+ header: () => <HeaderCell labelKey="com_ui_method" />,+ cell: ({ row }) => <MethodBadge method={row.original.method} />,},{- header: 'Path',accessorKey: 'path',+ header: () => <HeaderCell labelKey="com_ui_path" />,+ cell: ({ row }) => (+ <span className="break-all font-mono text-xs text-text-secondary">{row.original.path}</span>+ ),},- // {- // header: '',- // accessorKey: 'action',- // // eslint-disable-next-line @typescript-eslint/no-unused-vars- // cell: ({ row: _row }) => (- // <button className="btn relative btn-neutral h-8 rounded-lg border-token-border-light font-medium">- // <div className="flex w-full gap-2 items-center justify-center">Test</div>- // </button>- // ),- // },];diff --git a/client/src/components/SidePanel/Agents/ActionsTable/Skeleton.tsx b/client/src/components/SidePanel/Agents/ActionsTable/Skeleton.tsxnew file mode 100644index 0000000000..de929635f1--- /dev/null+++ b/client/src/components/SidePanel/Agents/ActionsTable/Skeleton.tsx@@ -0,0 +1,45 @@+import { Skeleton } from '@librechat/client';+import { useLocalize } from '~/hooks';++const SKELETON_ROWS = 3;+const HEADER_KEYS = ['com_ui_name', 'com_ui_method', 'com_ui_path'] as const;++/**+ * Loading state for the actions table. Mirrors the table's chrome (eyebrow header,+ * row dividers, a badge-shaped method cell) so the swap to real rows doesn't shift+ * the layout. The headers are real since they never change.+ */+export default function ActionsTableSkeleton() {+ const localize = useLocalize();+ return (+ <table className="w-full table-auto text-sm" aria-busy="true" aria-live="polite">+ <thead>+ <tr className="border-b border-border-light">+ {HEADER_KEYS.map((key) => (+ <th+ key={key}+ className="py-2 pr-3 text-left text-[11px] font-medium uppercase tracking-wide text-text-secondary"+ >+ {localize(key)}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {Array.from({ length: SKELETON_ROWS }, (_, row) => (+ <tr key={row} className="border-b border-border-light last:border-0">+ <td className="py-2.5 pr-3">+ <Skeleton className="h-4 w-24 rounded" />+ </td>+ <td className="py-2.5 pr-3">+ <Skeleton className="h-5 w-12 rounded-md" />+ </td>+ <td className="py-2.5 pr-3">+ <Skeleton className="h-4 w-32 rounded" />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ );+}diff --git a/client/src/components/SidePanel/Agents/ActionsTable/Table.tsx b/client/src/components/SidePanel/Agents/ActionsTable/Table.tsxindex 231badf53a..710d3ca915 100644--- a/client/src/components/SidePanel/Agents/ActionsTable/Table.tsx+++ b/client/src/components/SidePanel/Agents/ActionsTable/Table.tsx@@ -14,15 +14,15 @@ export default function DataTable<TData, TValue>({ columns, data }: DataTablePro});return (- <table className="w-full text-sm">+ <table className="w-full table-auto text-sm"><thead>- {table.getHeaderGroups().map((headerGroup, i) => (- <tr- key={i}- className="border-token-border-light text-token-text-tertiary border-b text-left text-xs"- >- {headerGroup.headers.map((header, j) => (- <th key={j} className="py-1 font-normal text-text-secondary-alt">+ {table.getHeaderGroups().map((headerGroup) => (+ <tr key={headerGroup.id}>+ {headerGroup.headers.map((header) => (+ <th+ key={header.id}+ className="sticky top-0 z-10 border-b border-border-light bg-background py-2 pr-3 text-left text-[11px] font-medium uppercase tracking-wide text-text-secondary"+ >{header.isPlaceholder? null: flexRender(header.column.columnDef.header, header.getContext())}@@ -32,10 +32,13 @@ export default function DataTable<TData, TValue>({ columns, data }: DataTablePro))}</thead><tbody>- {table.getRowModel().rows.map((row, i) => (- <tr key={i} className="border-token-border-light border-b">- {row.getVisibleCells().map((cell, j) => (- <td key={j} className="py-2">+ {table.getRowModel().rows.map((row) => (+ <tr+ key={row.id}+ className="border-b border-border-light transition-colors last:border-0 hover:bg-surface-secondary"+ >+ {row.getVisibleCells().map((cell) => (+ <td key={cell.id} className="py-2 pr-3 align-middle">{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>))}diff --git a/client/src/components/SidePanel/Agents/ActionsTable/index.ts b/client/src/components/SidePanel/Agents/ActionsTable/index.tsindex 0280dcde08..6f28a8671e 100644--- a/client/src/components/SidePanel/Agents/ActionsTable/index.ts+++ b/client/src/components/SidePanel/Agents/ActionsTable/index.ts@@ -1,2 +1,3 @@export { default as ActionsTable } from './Table';+export { default as ActionsTableSkeleton } from './Skeleton';export * from './Columns';diff --git a/client/src/components/SidePanel/Agents/Advanced/AdvancedButton.tsx b/client/src/components/SidePanel/Agents/Advanced/AdvancedButton.tsxindex 8ce635d6a8..70129839e1 100644--- a/client/src/components/SidePanel/Agents/Advanced/AdvancedButton.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AdvancedButton.tsx@@ -1,6 +1,5 @@import React from 'react';import { Settings2 } from 'lucide-react';-import { Button } from '@librechat/client';import { useLocalize } from '~/hooks';import { Panel } from '~/common';@@ -12,16 +11,15 @@ const AdvancedButton: React.FC<AdvancedButtonProps> = ({ setActivePanel }) => {const localize = useLocalize();return (- <Button- size={'sm'}- variant={'outline'}- className="btn btn-neutral border-token-border-light relative h-9 w-full gap-1 rounded-lg font-medium focus:outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-text-primary"+ <button+ type="button"onClick={() => setActivePanel(Panel.advanced)}aria-label={localize('com_ui_advanced')}+ className="inline-flex h-9 w-full items-center justify-center gap-2 rounded-xl border border-border-light bg-transparent px-3 text-sm font-medium text-text-primary transition-colors hover:bg-surface-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary">- <Settings2 className="h-4 w-4 cursor-pointer" aria-hidden="true" />+ <Settings2 className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />{localize('com_ui_advanced')}- </Button>+ </button>);};diff --git a/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsx b/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsxindex 913b0ce49b..ba3abe1afa 100644--- a/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AdvancedPanel.tsx@@ -1,73 +1,95 @@-import { useMemo } from 'react';-import { ChevronLeft } from 'lucide-react';-import { AgentCapabilities } from 'librechat-data-provider';-import { useFormContext, Controller } from 'react-hook-form';+import { useMemo, useState } from 'react';+import { useFormContext } from 'react-hook-form';+import { useToastContext } from '@librechat/client';+import { ChevronLeft, Check, Copy } from 'lucide-react';+import { AgentCapabilities, PermissionTypes, Permissions } from 'librechat-data-provider';import type { AgentForm } from '~/common';+import { sectionLabelClass, groupHeadingClass } from './ui';+import { useLocalize, useHasAccess } from '~/hooks';import { useAgentPanelContext } from '~/Providers';-import AgentSubagents from './AgentSubagents';+import OrchestrationHub from './OrchestrationHub';import MaxAgentSteps from './MaxAgentSteps';-import AgentHandoffs from './AgentHandoffs';-import { useLocalize } from '~/hooks';-import AgentChain from './AgentChain';+import SkillsToggle from './SkillsToggle';import { Panel } from '~/common';export default function AdvancedPanel() {const localize = useLocalize();- const methods = useFormContext<AgentForm>();- const { control, watch } = methods;+ const { showToast } = useToastContext();+ const { watch } = useFormContext<AgentForm>();const currentAgentId = watch('id');+ const [copied, setCopied] = useState(false);const { agentsConfig, setActivePanel } = useAgentPanelContext();- const chainEnabled = useMemo(- () => agentsConfig?.capabilities.includes(AgentCapabilities.chain) ?? false,- [agentsConfig],- );- const subagentsEnabled = useMemo(- () => agentsConfig?.capabilities.includes(AgentCapabilities.subagents) ?? false,++ const handleCopyAgentId = async () => {+ if (!currentAgentId) return;+ try {+ await navigator.clipboard.writeText(currentAgentId);+ setCopied(true);+ showToast({ message: localize('com_ui_agent_id_copied'), status: 'success' });+ setTimeout(() => setCopied(false), 1500);+ } catch {+ showToast({ message: localize('com_ui_error'), status: 'error' });+ }+ };++ const skillsEnabled = useMemo(+ () => agentsConfig?.capabilities.includes(AgentCapabilities.skills) ?? false,[agentsConfig],);+ const hasSkillsAccess = useHasAccess({+ permissionType: PermissionTypes.SKILLS,+ permission: Permissions.USE,+ });+ const showSkillsKillSwitch = skillsEnabled && hasSkillsAccess;return (- <div className="mb-1 flex w-full flex-col gap-2 text-sm">- <div className="advanced-panel relative flex flex-col items-center px-16 pt-2 text-center">- <div className="absolute left-0 top-4">- <button- type="button"- className="btn btn-neutral relative"- onClick={() => {- setActivePanel(Panel.builder);- }}- aria-label={localize('com_ui_back_to_builder')}- >- <div className="advanced-panel-content flex w-full items-center justify-center gap-2">- <ChevronLeft aria-hidden="true" />- </div>- </button>- </div>- <div className="mb-2 mt-2 text-xl font-medium">{localize('com_ui_advanced_settings')}</div>- </div>- <div className="flex flex-col gap-4 px-2 pb-2">- <MaxAgentSteps />- {subagentsEnabled && (- <Controller- name="subagents"- control={control}- render={({ field }) => <AgentSubagents field={field} currentAgentId={currentAgentId} />}- />- )}- <Controller- name="edges"- control={control}- defaultValue={[]}- render={({ field }) => <AgentHandoffs field={field} currentAgentId={currentAgentId} />}- />- {chainEnabled && (- <Controller- name="agent_ids"- control={control}- defaultValue={[]}- render={({ field }) => <AgentChain field={field} currentAgentId={currentAgentId} />}- />+ <div className="mb-1 flex w-full flex-col gap-4 text-sm">+ <header className="grid grid-cols-[auto_1fr_auto] items-center gap-2 pt-1">+ <button+ type="button"+ onClick={() => setActivePanel(Panel.builder)}+ aria-label={localize('com_ui_back_to_builder')}+ className="inline-flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-border-light text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <ChevronLeft className="h-5 w-5" strokeWidth={1.75} aria-hidden="true" />+ </button>+ <h2 className="text-center text-base font-semibold text-text-primary">+ {localize('com_ui_advanced_settings')}+ </h2>+ <span aria-hidden="true" className="h-10 w-10" />+ </header>++ <div className="flex flex-col gap-5 px-2 pb-2">+ <section className="flex flex-col gap-3">+ <span className={groupHeadingClass}>{localize('com_ui_essentials')}</span>+ <MaxAgentSteps />+ {showSkillsKillSwitch && <SkillsToggle />}+ </section>++ <OrchestrationHub currentAgentId={currentAgentId} />++ {currentAgentId && (+ <div className="flex items-center justify-between gap-2 border-t border-border-light pt-3">+ <span className={sectionLabelClass}>{localize('com_ui_agent_id')}</span>+ <button+ type="button"+ onClick={handleCopyAgentId}+ title={currentAgentId}+ aria-label={localize('com_ui_agent_id_copy')}+ className="inline-flex items-center gap-1.5 rounded-lg px-2 py-1 text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <code className="max-w-[150px] truncate font-mono text-xs">{currentAgentId}</code>+ <span className="t-icon-swap" data-state={copied ? 'b' : 'a'} aria-hidden="true">+ <span className="t-icon" data-icon="a">+ <Copy className="h-3.5 w-3.5" aria-hidden="true" />+ </span>+ <span className="t-icon" data-icon="b">+ <Check className="h-3.5 w-3.5 text-green-500" aria-hidden="true" />+ </span>+ </span>+ </button>+ </div>)}</div></div>diff --git a/client/src/components/SidePanel/Agents/Advanced/AgentChain.tsx b/client/src/components/SidePanel/Agents/Advanced/AgentChain.tsxindex 7bbf194f7c..9744a8f8c1 100644--- a/client/src/components/SidePanel/Agents/Advanced/AgentChain.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AgentChain.tsx@@ -1,21 +1,18 @@-import { X, Link2, PlusCircle } from 'lucide-react';-import { EModelEndpoint } from 'librechat-data-provider';-import React, { useState, useMemo, useCallback, useEffect } from 'react';-import {- ControlCombobox,- HoverCard,- HoverCardPortal,- HoverCardContent,- HoverCardTrigger,- CircleHelpIcon,-} from '@librechat/client';+import React, { useState, useMemo, useEffect } from 'react';+import { Link2, ListOrdered } from 'lucide-react';import type { ControllerRenderProps } from 'react-hook-form';-import type { TMessage } from 'librechat-data-provider';-import type { AgentForm, OptionWithIcon } from '~/common';-import MessageIcon from '~/components/Share/MessageIcon';-import { useAgentsMapContext } from '~/Providers';+import type { AgentForm } from '~/common';+import {+ AgentGlyph,+ AgentRow,+ agentIcon,+ AddAgentSelect,+ AgentSelectInline,+ useSelectableAgents,+} from './AgentList';+import OrchestrationPattern from './OrchestrationPattern';import { useLocalize } from '~/hooks';-import { ESide } from '~/common';+import { CountPill } from './ui';interface AgentChainProps {field: ControllerRenderProps<AgentForm, 'agent_ids'>;@@ -25,40 +22,16 @@ interface AgentChainProps {/** TODO: make configurable */const MAX_AGENTS = 10;+const Connector = () => (+ <Link2 className="mx-auto text-text-tertiary" size={14} aria-hidden="true" />+);+const AgentChain: React.FC<AgentChainProps> = ({ field, currentAgentId }) => {const localize = useLocalize();const [newAgentId, setNewAgentId] = useState('');- const agentsMap = useAgentsMapContext() || {};- const agentIds = field.value || [];+ const agentIds = useMemo(() => field.value ?? [], [field.value]);- const agents = useMemo(() => Object.values(agentsMap), [agentsMap]);-- const selectableAgents = useMemo(- () =>- agents- .filter((agent) => agent?.id !== currentAgentId)- .map(- (agent) =>- ({- label: agent?.name || '',- value: agent?.id,- icon: (- <MessageIcon- message={- {- endpoint: EModelEndpoint.agents,- isCreatedByUser: false,- } as TMessage- }- agent={agent}- />- ),- }) as OptionWithIcon,- ),- [agents, currentAgentId],- );-- const getAgentDetails = useCallback((id: string) => agentsMap[id], [agentsMap]);+ const { options, getAgent } = useSelectableAgents({ currentAgentId });useEffect(() => {if (newAgentId && agentIds.length < MAX_AGENTS) {@@ -77,102 +50,64 @@ const AgentChain: React.FC<AgentChainProps> = ({ field, currentAgentId }) => {field.onChange(updated);};+ const currentAgent = currentAgentId ? getAgent(currentAgentId) : undefined;+ const currentName = currentAgent?.name?.trim();+return (- <HoverCard openDelay={50}>- <div className="flex items-center justify-between gap-2">- <div className="flex items-center gap-2">- <label className="font-semibold text-text-primary">- {localize('com_ui_agent_chain')}- </label>- <HoverCardTrigger>- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </HoverCardTrigger>- </div>- <div className="text-xs text-text-secondary">+ <OrchestrationPattern+ icon={<ListOrdered className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />}+ title={localize('com_ui_agent_chain')}+ subtitle={localize('com_ui_agent_chain_subtitle')}+ info={<p className="text-sm text-text-secondary">{localize('com_ui_agent_chain_info')}</p>}+ trailing={+ <CountPill>{agentIds.length} / {MAX_AGENTS}+ </CountPill>+ }+ >+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-2 px-1 py-1">+ {currentName ? (+ <>+ <AgentGlyph agent={currentAgent} />+ <span className="truncate text-sm font-medium text-text-primary">{currentName}</span>+ </>+ ) : (+ <span className="text-sm font-medium text-text-secondary">+ {localize('com_ui_agent_chain_self')}+ </span>+ )}</div>- </div>- <div className="space-y-1">- {/* Current fixed agent */}- <div className="flex h-9 items-center justify-between rounded-md border border-border-medium bg-surface-primary-contrast px-3 py-2">- <div className="flex items-center gap-2">- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">- <MessageIcon- message={- {- endpoint: EModelEndpoint.agents,- isCreatedByUser: false,- } as TMessage- }- agent={currentAgentId ? agentsMap[currentAgentId] : undefined}- />- </div>- <div className="font-medium text-text-primary">- {getAgentDetails(currentAgentId)?.name}- </div>- </div>- </div>- {<Link2 className="mx-auto text-text-secondary" size={14} />}+{agentIds.map((agentId, idx) => (- <React.Fragment key={agentId}>- <div className="flex h-9 items-center gap-2 rounded-md border border-border-medium bg-surface-tertiary pr-2">- <ControlCombobox- isCollapsed={false}- ariaLabel={localize('com_ui_agent_var', { 0: localize('com_ui_select') })}+ <React.Fragment key={`${agentId}-${idx}`}>+ <Connector />+ <AgentRow+ onRemove={() => removeAgentAt(idx)}+ removeLabel={localize('com_ui_remove_agent_from_chain', {+ 0: getAgent(agentId)?.name || localize('com_ui_agent'),+ })}+ >+ <AgentSelectInline+ options={options}selectedValue={agentId}- setValue={(id) => updateAgentAt(idx, id)}- selectPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_select') })}- searchPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_search') })}- items={selectableAgents}- displayValue={getAgentDetails(agentId)?.name ?? ''}- SelectIcon={- <MessageIcon- message={- {- endpoint: EModelEndpoint.agents,- isCreatedByUser: false,- } as TMessage- }- agent={agentId ? agentsMap[agentId] : undefined}- />- }- className="flex-1 border-border-heavy"- containerClassName="px-0"+ onChange={(id) => updateAgentAt(idx, id)}+ displayValue={getAgent(agentId)?.name ?? ''}+ icon={agentIcon(getAgent(agentId))}+ ariaLabel={localize('com_ui_agent_var', { 0: localize('com_ui_select') })}/>- {/* Future Settings button? */}- {/* <button className="hover:bg-surface-hover p-1 rounded transition">- <Settings size={16} className="text-text-secondary" />- </button> */}- <button- className="rounded-xl p-1 transition hover:bg-surface-hover"- onClick={() => removeAgentAt(idx)}- aria-label={localize('com_ui_remove_agent_from_chain', {- 0: getAgentDetails(agentId)?.name || localize('com_ui_agent'),- })}- >- <X size={18} className="text-text-secondary" aria-hidden="true" />- </button>- </div>- {idx < agentIds.length - 1 && (- <Link2 className="mx-auto text-text-secondary" size={14} />- )}+ </AgentRow></React.Fragment>))}{agentIds.length < MAX_AGENTS && (<>- {agentIds.length > 0 && <Link2 className="mx-auto text-text-secondary" size={14} />}- <ControlCombobox- isCollapsed={false}+ <Connector />+ <AddAgentSelect+ options={options}+ onSelect={setNewAgentId}+ placeholder={localize('com_ui_agent_var', { 0: localize('com_ui_add') })}ariaLabel={localize('com_ui_agent_var', { 0: localize('com_ui_add') })}- selectedValue=""- setValue={setNewAgentId}- selectPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_add') })}- searchPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_search') })}- items={selectableAgents}- className="h-9 w-full border-dashed border-border-heavy text-center text-text-secondary hover:text-text-primary"- containerClassName="px-0"- SelectIcon={<PlusCircle size={16} className="text-text-secondary" />}/></>)}@@ -183,14 +118,7 @@ const AgentChain: React.FC<AgentChainProps> = ({ field, currentAgentId }) => {</p>)}</div>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">{localize('com_ui_agent_chain_info')}</p>- </div>- </HoverCardContent>- </HoverCardPortal>- </HoverCard>+ </OrchestrationPattern>);};diff --git a/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsx b/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsxindex d19fee0af9..0a3c798b48 100644--- a/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AgentHandoffs.tsx@@ -1,24 +1,19 @@-import React, { useState, useMemo, useCallback, useEffect } from 'react';-import { EModelEndpoint } from 'librechat-data-provider';-import { X, Waypoints, PlusCircle, ChevronDown } from 'lucide-react';-import {- Label,- Input,- Textarea,- HoverCard,- CircleHelpIcon,- HoverCardPortal,- ControlCombobox,- HoverCardContent,- HoverCardTrigger,-} from '@librechat/client';-import type { TMessage, GraphEdge } from 'librechat-data-provider';+import React, { useState, useMemo, useEffect } from 'react';+import { Waypoints, ChevronDown } from 'lucide-react';+import { Label, Input, Textarea } from '@librechat/client';import type { ControllerRenderProps } from 'react-hook-form';-import type { AgentForm, OptionWithIcon } from '~/common';-import MessageIcon from '~/components/Share/MessageIcon';-import { useAgentsMapContext } from '~/Providers';+import type { GraphEdge } from 'librechat-data-provider';+import type { AgentForm } from '~/common';+import {+ AgentRow,+ agentIcon,+ AddAgentSelect,+ AgentSelectInline,+ useSelectableAgents,+} from './AgentList';+import OrchestrationPattern from './OrchestrationPattern';import { useLocalize } from '~/hooks';-import { ESide } from '~/common';+import { CountPill } from './ui';interface AgentHandoffsProps {field: ControllerRenderProps<AgentForm, 'edges'>;@@ -28,50 +23,23 @@ interface AgentHandoffsProps {/** TODO: make configurable */const MAX_HANDOFFS = 10;+const Connector = () => (+ <Waypoints className="mx-auto text-text-tertiary" size={14} aria-hidden="true" />+);++const getTargetAgentId = (to: string | string[]): string => (Array.isArray(to) ? to[0] : to);+const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId }) => {const localize = useLocalize();const [newAgentId, setNewAgentId] = useState('');const [expandedIndices, setExpandedIndices] = useState<Set<number>>(new Set());- const agentsMap = useAgentsMapContext();- const edgesValue = field.value;- const edges = useMemo(() => edgesValue || [], [edgesValue]);-- const agents = useMemo(() => (agentsMap ? Object.values(agentsMap) : []), [agentsMap]);+ const edges = useMemo(() => field.value ?? [], [field.value]);- const selectableAgents = useMemo(- () =>- agents- .filter((agent) => agent?.id !== currentAgentId)- .map(- (agent) =>- ({- label: agent?.name || '',- value: agent?.id || '',- icon: (- <MessageIcon- message={- {- endpoint: EModelEndpoint.agents,- isCreatedByUser: false,- } as TMessage- }- agent={agent}- />- ),- }) as OptionWithIcon,- ),- [agents, currentAgentId],- );-- const getAgentDetails = useCallback((id: string) => agentsMap?.[id], [agentsMap]);+ const { options, getAgent } = useSelectableAgents({ currentAgentId });useEffect(() => {if (newAgentId && edges.length < MAX_HANDOFFS) {- const newEdge: GraphEdge = {- from: currentAgentId,- to: newAgentId,- edgeType: 'handoff',- };+ const newEdge: GraphEdge = { from: currentAgentId, to: newAgentId, edgeType: 'handoff' };field.onChange([...edges, newEdge]);setNewAgentId('');}@@ -79,11 +47,10 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })const removeHandoffAt = (index: number) => {field.onChange(edges.filter((_, i) => i !== index));- // Also remove from expanded setsetExpandedIndices((prev) => {- const newSet = new Set(prev);- newSet.delete(index);- return newSet;+ const next = new Set(prev);+ next.delete(index);+ return next;});};@@ -101,99 +68,73 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })const toggleExpanded = (index: number) => {setExpandedIndices((prev) => {- const newSet = new Set(prev);- if (newSet.has(index)) {- newSet.delete(index);+ const next = new Set(prev);+ if (next.has(index)) {+ next.delete(index);} else {- newSet.add(index);+ next.add(index);}- return newSet;+ return next;});};- const getTargetAgentId = (to: string | string[]): string => {- return Array.isArray(to) ? to[0] : to;- };-return (- <HoverCard openDelay={50}>- <div className="flex items-center justify-between gap-2">- <div className="flex items-center gap-2">- <label className="font-semibold text-text-primary">- {localize('com_ui_agent_handoffs')}- </label>- <HoverCardTrigger>- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </HoverCardTrigger>- </div>- <div className="flex items-center gap-3">- <div className="rounded-full border border-purple-600/40 bg-purple-500/10 px-2 py-0.5 text-xs font-medium text-purple-700 hover:bg-purple-700/10 dark:text-purple-400">- {localize('com_ui_beta')}- </div>- <div className="text-xs text-text-secondary">- {edges.length} / {MAX_HANDOFFS}- </div>- </div>- </div>- <div className="space-y-1">+ <OrchestrationPattern+ icon={<Waypoints className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />}+ title={localize('com_ui_agent_handoffs')}+ subtitle={localize('com_ui_agent_handoffs_subtitle')}+ beta+ info={+ <>+ <p className="text-sm text-text-secondary">{localize('com_ui_agent_handoff_info')}</p>+ <p className="text-sm text-text-secondary">{localize('com_ui_agent_handoff_info_2')}</p>+ </>+ }+ trailing={+ <CountPill>+ {edges.length} / {MAX_HANDOFFS}+ </CountPill>+ }+ >+ <div className="flex flex-col gap-1.5">{edges.map((edge, idx) => {const targetAgentId = getTargetAgentId(edge.to);const isExpanded = expandedIndices.has(idx);+ const targetName = getAgent(targetAgentId)?.name ?? localize('com_ui_agent');return (<React.Fragment key={idx}>- <div className="space-y-1">- <div className="flex h-9 items-center gap-2 rounded-md border border-border-medium bg-surface-tertiary pr-2">- <ControlCombobox- isCollapsed={false}- ariaLabel={localize('com_ui_agent_var', { 0: localize('com_ui_select') })}+ {idx > 0 && <Connector />}+ <div className="flex flex-col gap-1.5">+ <AgentRow+ onRemove={() => removeHandoffAt(idx)}+ removeLabel={localize('com_ui_agent_handoff_remove', { 0: targetName })}+ >+ <AgentSelectInline+ options={options}selectedValue={targetAgentId}- setValue={(id) => updateHandoffAt(idx, id)}- selectPlaceholder={localize('com_ui_agent_var', {- 0: localize('com_ui_select'),- })}- searchPlaceholder={localize('com_ui_agent_var', {- 0: localize('com_ui_search'),- })}- items={selectableAgents}- displayValue={getAgentDetails(targetAgentId)?.name ?? ''}- SelectIcon={- <MessageIcon- message={- {- endpoint: EModelEndpoint.agents,- isCreatedByUser: false,- } as TMessage- }- agent={targetAgentId && agentsMap ? agentsMap[targetAgentId] : undefined}- />- }- className="flex-1 border-border-heavy"- containerClassName="px-0"+ onChange={(id) => updateHandoffAt(idx, id)}+ displayValue={getAgent(targetAgentId)?.name ?? ''}+ icon={agentIcon(getAgent(targetAgentId))}+ ariaLabel={localize('com_ui_agent_var', { 0: localize('com_ui_select') })}/><buttontype="button"- className="rounded p-1 transition hover:bg-surface-hover"+ className="flex-shrink-0 rounded-lg p-1 text-text-secondary transition hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"onClick={() => toggleExpanded(idx)}+ aria-expanded={isExpanded}+ aria-label={localize(isExpanded ? 'com_ui_collapse' : 'com_ui_expand')}><ChevronDownsize={16}- className={`text-text-secondary transition-transform ${- isExpanded ? 'rotate-180' : ''- }`}+ className={`transition-transform ${isExpanded ? 'rotate-180' : ''}`}+ aria-hidden="true"/></button>- <button- type="button"- className="rounded-xl p-1 transition hover:bg-surface-hover"- onClick={() => removeHandoffAt(idx)}- >- <X size={18} className="text-text-secondary" />- </button>- </div>+ </AgentRow>{isExpanded && (- <div className="space-y-3 rounded-md border border-border-light bg-surface-primary p-3">+ <div className="ml-1.5 flex flex-col gap-2.5 border-l border-border-light pl-3"><div><LabelhtmlFor={`handoff-desc-${idx}`}@@ -210,7 +151,7 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })description: e.target.value === '' ? undefined : e.target.value,})}- className="mt-1 h-8 text-sm"+ className="mt-1 h-9 text-sm"/></div>@@ -230,7 +171,7 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })prompt: e.target.value === '' ? undefined : e.target.value,})}- className="mt-1 h-20 resize-none text-sm"+ className="mt-1 h-16 resize-none text-sm"/></div>@@ -251,34 +192,25 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })promptKey: e.target.value === '' ? undefined : e.target.value,})}- className="mt-1 h-8 text-sm"+ className="mt-1 h-9 text-sm"/></div>)}</div>)}</div>- {idx < edges.length - 1 && (- <Waypoints className="mx-auto text-text-secondary" size={14} />- )}</React.Fragment>);})}{edges.length < MAX_HANDOFFS && (<>- {edges.length > 0 && <Waypoints className="mx-auto text-text-secondary" size={14} />}- <ControlCombobox- isCollapsed={false}+ {edges.length > 0 && <Connector />}+ <AddAgentSelect+ options={options}+ onSelect={setNewAgentId}+ placeholder={localize('com_ui_agent_handoff_add')}ariaLabel={localize('com_ui_agent_var', { 0: localize('com_ui_add') })}- selectedValue=""- setValue={setNewAgentId}- selectPlaceholder={localize('com_ui_agent_handoff_add')}- searchPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_search') })}- items={selectableAgents}- className="h-9 w-full border-dashed border-border-heavy text-center text-text-secondary hover:text-text-primary"- containerClassName="px-0"- SelectIcon={<PlusCircle size={16} className="text-text-secondary" />}/></>)}@@ -289,15 +221,7 @@ const AgentHandoffs: React.FC<AgentHandoffsProps> = ({ field, currentAgentId })</p>)}</div>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">{localize('com_ui_agent_handoff_info')}</p>- <p className="text-sm text-text-secondary">{localize('com_ui_agent_handoff_info_2')}</p>- </div>- </HoverCardContent>- </HoverCardPortal>- </HoverCard>+ </OrchestrationPattern>);};diff --git a/client/src/components/SidePanel/Agents/Advanced/AgentList.tsx b/client/src/components/SidePanel/Agents/Advanced/AgentList.tsxnew file mode 100644index 0000000000..e3785b8764--- /dev/null+++ b/client/src/components/SidePanel/Agents/Advanced/AgentList.tsx@@ -0,0 +1,198 @@+import { useMemo } from 'react';+import { X, PlusCircle } from 'lucide-react';+import { ControlCombobox } from '@librechat/client';+import { EModelEndpoint } from 'librechat-data-provider';+import type { Agent, TMessage } from 'librechat-data-provider';+import type { ReactNode } from 'react';+import type { OptionWithIcon } from '~/common';+import MessageIcon from '~/components/Share/MessageIcon';+import { useAgentsMapContext } from '~/Providers';+import { useLocalize } from '~/hooks';++const AGENT_MESSAGE = { endpoint: EModelEndpoint.agents, isCreatedByUser: false } as TMessage;++/** Renders an agent's avatar/icon as used in combobox options and select triggers. */+export const agentIcon = (agent?: Agent | false): ReactNode => (+ <MessageIcon message={AGENT_MESSAGE} agent={agent} />+);++/** Fixed-size circular agent avatar for list rows. */+export function AgentGlyph({ agent }: { agent?: Agent }) {+ return (+ <div className="flex h-6 w-6 flex-shrink-0 items-center justify-center overflow-hidden rounded-full">+ {agentIcon(agent)}+ </div>+ );+}++interface UseSelectableAgentsParams {+ currentAgentId: string;+ /** Agent ids to omit from the options (e.g. already-selected ones). */+ exclude?: string[];+}++/**+ * Builds the list of agents this agent can collaborate with (everything except+ * itself and any excluded ids), plus a lookup for a single agent's details.+ */+export function useSelectableAgents({ currentAgentId, exclude }: UseSelectableAgentsParams) {+ const agentsMap = useAgentsMapContext();+ const excludeKey = (exclude ?? []).join(',');++ const options = useMemo<OptionWithIcon[]>(() => {+ const excludeSet = new Set(exclude ?? []);+ const agents = agentsMap ? Object.values(agentsMap) : [];+ return agents+ .filter((agent) => {+ if (!agent?.id) return false;+ if (agent.id === currentAgentId) return false;+ return !excludeSet.has(agent.id);+ })+ .map(+ (agent) =>+ ({+ label: agent?.name || '',+ value: agent?.id || '',+ icon: agentIcon(agent),+ }) as OptionWithIcon,+ );+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [agentsMap, currentAgentId, excludeKey]);++ const getAgent = (id: string): Agent | undefined => agentsMap?.[id];++ return { options, getAgent };+}++interface AddAgentSelectProps {+ options: OptionWithIcon[];+ onSelect: (id: string) => void;+ placeholder: string;+ ariaLabel: string;+}++/** Dashed "+ Add agent" combobox shared by every orchestration pattern. */+export function AddAgentSelect({ options, onSelect, placeholder, ariaLabel }: AddAgentSelectProps) {+ const localize = useLocalize();+ return (+ <ControlCombobox+ isCollapsed={false}+ ariaLabel={ariaLabel}+ selectedValue=""+ setValue={onSelect}+ selectPlaceholder={placeholder}+ searchPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_search') })}+ items={options}+ className="h-9 w-full border-dashed border-border-heavy text-center text-text-secondary hover:text-text-primary"+ containerClassName="px-0"+ SelectIcon={<PlusCircle size={16} className="text-text-secondary" />}+ />+ );+}++interface AgentSelectInlineProps {+ options: OptionWithIcon[];+ selectedValue: string;+ onChange: (id: string) => void;+ displayValue: string;+ icon: ReactNode;+ ariaLabel: string;+}++/** Inline combobox to change which agent a row points at (chain, handoffs). */+export function AgentSelectInline({+ options,+ selectedValue,+ onChange,+ displayValue,+ icon,+ ariaLabel,+}: AgentSelectInlineProps) {+ const localize = useLocalize();+ return (+ <ControlCombobox+ isCollapsed={false}+ ariaLabel={ariaLabel}+ selectedValue={selectedValue}+ setValue={onChange}+ selectPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_select') })}+ searchPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_search') })}+ items={options}+ displayValue={displayValue}+ SelectIcon={icon}+ className="h-9 flex-1 border-border-light"+ containerClassName="px-0"+ />+ );+}++interface RemoveButtonProps {+ onClick: () => void;+ label: string;+}++/** Ghost remove (×) button shared by agent rows. */+export function RemoveButton({ onClick, label }: RemoveButtonProps) {+ return (+ <button+ type="button"+ className="flex-shrink-0 rounded-lg p-1 text-text-secondary transition hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ onClick={onClick}+ aria-label={label}+ >+ <X size={16} aria-hidden="true" />+ </button>+ );+}++interface AgentRowProps {+ children: ReactNode;+ onRemove: () => void;+ removeLabel: string;+}++/** Borderless row laying out an editable control plus a remove button. */+export function AgentRow({ children, onRemove, removeLabel }: AgentRowProps) {+ return (+ <div className="flex items-center gap-1">+ {children}+ <RemoveButton onClick={onRemove} label={removeLabel} />+ </div>+ );+}++interface StaticAgentRowProps {+ agent?: Agent;+ name: string;+ onRemove: () => void;+ removeLabel: string;+}++/** Borderless display row for a selected agent (avatar, name, remove). */+export function StaticAgentRow({ agent, name, onRemove, removeLabel }: StaticAgentRowProps) {+ return (+ <div className="flex items-center gap-2 rounded-lg px-1 py-1 transition hover:bg-surface-secondary">+ <AgentGlyph agent={agent} />+ <span className="min-w-0 flex-1 truncate text-sm text-text-primary">{name}</span>+ <RemoveButton onClick={onRemove} label={removeLabel} />+ </div>+ );+}++interface ListMetaProps {+ label: string;+ count: number;+ max: number;+}++/** "Agents 2 / 10" sub-header used above an agent list. */+export function ListMeta({ label, count, max }: ListMetaProps) {+ return (+ <div className="flex items-center justify-between gap-2">+ <span className="text-xs font-medium text-text-secondary">{label}</span>+ <span className="whitespace-nowrap text-[10px] font-medium tabular-nums text-text-tertiary">+ {count} / {max}+ </span>+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx b/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsxindex c3488b0c86..6ed69cf1c5 100644--- a/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx@@ -1,22 +1,13 @@import React, { useCallback, useEffect, useMemo, useState } from 'react';-import { MAX_SUBAGENTS, EModelEndpoint } from 'librechat-data-provider';-import { X, PlusCircle, Users } from 'lucide-react';-import {- Switch,- HoverCard,- CircleHelpIcon,- HoverCardPortal,- ControlCombobox,- HoverCardContent,- HoverCardTrigger,-} from '@librechat/client';-import type { TMessage } from 'librechat-data-provider';+import { Switch } from '@librechat/client';+import { Network, Users } from 'lucide-react';+import { MAX_SUBAGENTS } from 'librechat-data-provider';import type { ControllerRenderProps } from 'react-hook-form';-import type { AgentForm, OptionWithIcon } from '~/common';-import MessageIcon from '~/components/Share/MessageIcon';-import { useAgentsMapContext } from '~/Providers';+import type { AgentForm } from '~/common';+import { StaticAgentRow, AddAgentSelect, ListMeta, useSelectableAgents } from './AgentList';+import OrchestrationPattern from './OrchestrationPattern';import { useLocalize } from '~/hooks';-import { ESide } from '~/common';+import { ToggleSetting } from './ui';interface AgentSubagentsProps {field: ControllerRenderProps<AgentForm, 'subagents'>;@@ -25,7 +16,6 @@ interface AgentSubagentsProps {const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId }) => {const localize = useLocalize();- const agentsMap = useAgentsMapContext();const [newAgentId, setNewAgentId] = useState('');const fieldValue = field.value;@@ -34,25 +24,19 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId }const allowSelf = value.allowSelf !== false;const agentIds = useMemo(() => value.agent_ids ?? [], [value.agent_ids]);+ const { options, getAgent } = useSelectableAgents({ currentAgentId, exclude: agentIds });+const setEnabled = useCallback((next: boolean) => {- if (!next) {- /**- * Persist `{ enabled: false }` (with the existing selections preserved)- * rather than `undefined`. The backend's `removeNullishValues` strips- * undefined fields from PATCH payloads, so setting the whole object to- * undefined would leave the server copy enabled. An explicit- * `enabled: false` flows through as a real update.- */- field.onChange({- enabled: false,- allowSelf: value.allowSelf ?? true,- agent_ids: value.agent_ids ?? [],- });- return;- }+ /**+ * Persist `{ enabled: false }` (with the existing selections preserved)+ * rather than `undefined`. The backend's `removeNullishValues` strips+ * undefined fields from PATCH payloads, so setting the whole object to+ * undefined would leave the server copy enabled. An explicit+ * `enabled: false` flows through as a real update.+ */field.onChange({- enabled: true,+ enabled: next,allowSelf: value.allowSelf ?? true,agent_ids: value.agent_ids ?? [],});@@ -62,11 +46,7 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId }const setAllowSelf = useCallback((next: boolean) => {- field.onChange({- ...value,- enabled: true,- allowSelf: next,- });+ field.onChange({ ...value, enabled: true, allowSelf: next });},[field, value],);@@ -83,38 +63,6 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId }[field, value],);- const agents = useMemo(() => (agentsMap ? Object.values(agentsMap) : []), [agentsMap]);-- const selectableAgents = useMemo<OptionWithIcon[]>(() => {- const selectedSet = new Set(agentIds);- return agents- .filter((agent) => {- if (!agent?.id) return false;- if (agent.id === currentAgentId) return false;- return !selectedSet.has(agent.id);- })- .map(- (agent) =>- ({- label: agent?.name || '',- value: agent?.id || '',- icon: (- <MessageIcon- message={- {- endpoint: EModelEndpoint.agents,- isCreatedByUser: false,- } as TMessage- }- agent={agent}- />- ),- }) as OptionWithIcon,- );- }, [agents, currentAgentId, agentIds]);-- const getAgentDetails = useCallback((id: string) => agentsMap?.[id], [agentsMap]);-useEffect(() => {if (newAgentId && agentIds.length < MAX_SUBAGENTS && !agentIds.includes(newAgentId)) {setAgentIds([...agentIds, newAgentId]);@@ -128,110 +76,71 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId }setAgentIds(agentIds.filter((_, i) => i !== index));};- const enableId = 'subagents-enable-toggle';const selfId = 'subagents-self-toggle';const nothingToSpawn = enabled && !allowSelf && agentIds.length === 0;return (- <HoverCard openDelay={50}>- <div className="flex items-center justify-between gap-2">- <div className="flex items-center gap-2">- <label htmlFor={enableId} className="font-semibold text-text-primary">- {localize('com_ui_agent_subagents')}- </label>- <HoverCardTrigger>- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </HoverCardTrigger>- </div>- <div className="flex items-center gap-3">- <div className="rounded-full border border-purple-600/40 bg-purple-500/10 px-2 py-0.5 text-xs font-medium text-purple-700 hover:bg-purple-700/10 dark:text-purple-400">- {localize('com_ui_beta')}- </div>- <Switch- id={enableId}- checked={enabled}- onCheckedChange={setEnabled}- aria-label={localize('com_ui_agent_subagents_enable')}- />- </div>- </div>-+ <OrchestrationPattern+ icon={<Network className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />}+ title={localize('com_ui_agent_subagents')}+ subtitle={localize('com_ui_agent_subagents_subtitle')}+ beta+ info={+ <>+ <p className="text-sm text-text-secondary">{localize('com_ui_agent_subagents_info')}</p>+ <p className="text-sm text-text-secondary">{localize('com_ui_agent_subagents_info_2')}</p>+ </>+ }+ trailing={+ <Switch+ checked={enabled}+ onCheckedChange={setEnabled}+ aria-label={localize('com_ui_agent_subagents_enable')}+ />+ }+ >{enabled && (- <div className="mt-2 space-y-3">- <div className="flex items-center justify-between gap-2 rounded-md border border-border-light bg-surface-primary p-3">- <div className="flex flex-col">- <label htmlFor={selfId} className="text-sm font-medium text-text-primary">- {localize('com_ui_agent_subagents_allow_self')}- </label>- <span className="text-xs text-text-secondary">+ <>+ <ToggleSetting+ id={selfId}+ label={localize('com_ui_agent_subagents_allow_self')}+ checked={allowSelf}+ onCheckedChange={setAllowSelf}+ info={+ <p className="text-sm text-text-secondary">{localize('com_ui_agent_subagents_allow_self_info')}- </span>- </div>- <Switch- id={selfId}- checked={allowSelf}- onCheckedChange={setAllowSelf}- aria-label={localize('com_ui_agent_subagents_allow_self')}- />- </div>+ </p>+ }+ />- <div className="space-y-1">- <div className="flex items-center justify-between gap-2">- <span className="text-xs font-medium text-text-secondary">- {localize('com_ui_agent_subagents_agents')}- </span>- <span className="text-xs text-text-secondary">- {agentIds.length} / {MAX_SUBAGENTS}- </span>- </div>+ <div className="flex flex-col gap-0.5">+ <ListMeta+ label={localize('com_ui_agent_subagents_agents')}+ count={agentIds.length}+ max={MAX_SUBAGENTS}+ />{agentIds.map((agentId, idx) => {- const details = getAgentDetails(agentId);+ const details = getAgent(agentId);return (- <div+ <StaticAgentRowkey={agentId}- className="flex h-9 items-center gap-2 rounded-md border border-border-medium bg-surface-tertiary pl-2 pr-2"- >- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">- <MessageIcon- message={- {- endpoint: EModelEndpoint.agents,- isCreatedByUser: false,- } as TMessage- }- agent={details}- />- </div>- <div className="flex-1 truncate text-sm text-text-primary">- {details?.name ?? agentId}- </div>- <button- type="button"- className="rounded-xl p-1 transition hover:bg-surface-hover"- onClick={() => removeAgentAt(idx)}- aria-label={localize('com_ui_agent_subagents_remove', {- 0: details?.name ?? agentId,- })}- >- <X size={18} className="text-text-secondary" aria-hidden="true" />- </button>- </div>+ agent={details}+ name={details?.name ?? agentId}+ onRemove={() => removeAgentAt(idx)}+ removeLabel={localize('com_ui_agent_subagents_remove', {+ 0: details?.name ?? agentId,+ })}+ />);})}{agentIds.length < MAX_SUBAGENTS && (- <ControlCombobox- isCollapsed={false}+ <AddAgentSelect+ options={options}+ onSelect={setNewAgentId}+ placeholder={localize('com_ui_agent_subagents_add')}ariaLabel={localize('com_ui_agent_subagents_add')}- selectedValue=""- setValue={setNewAgentId}- selectPlaceholder={localize('com_ui_agent_subagents_add')}- searchPlaceholder={localize('com_ui_agent_var', { 0: localize('com_ui_search') })}- items={selectableAgents}- className="h-9 w-full border-dashed border-border-heavy text-center text-text-secondary hover:text-text-primary"- containerClassName="px-0"- SelectIcon={<PlusCircle size={16} className="text-text-secondary" />}/>)}@@ -248,20 +157,9 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId }{localize('com_ui_agent_subagents_empty')}</p>)}- </div>+ </>)}-- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">{localize('com_ui_agent_subagents_info')}</p>- <p className="text-sm text-text-secondary">- {localize('com_ui_agent_subagents_info_2')}- </p>- </div>- </HoverCardContent>- </HoverCardPortal>- </HoverCard>+ </OrchestrationPattern>);};diff --git a/client/src/components/SidePanel/Agents/Advanced/MaxAgentSteps.tsx b/client/src/components/SidePanel/Agents/Advanced/MaxAgentSteps.tsxindex 09af3fd154..65e6b2b8d7 100644--- a/client/src/components/SidePanel/Agents/Advanced/MaxAgentSteps.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/MaxAgentSteps.tsx@@ -1,50 +1,52 @@import { useFormContext, Controller } from 'react-hook-form';-import {- HoverCard,- FormInput,- HoverCardPortal,- HoverCardContent,- HoverCardTrigger,- CircleHelpIcon,-} from '@librechat/client';+import { Input, HoverCard, HoverCardPortal, HoverCardContent } from '@librechat/client';import type { AgentForm } from '~/common';import { useLocalize } from '~/hooks';+import { InfoTrigger } from './ui';import { ESide } from '~/common';-export default function AdvancedPanel() {+export default function MaxAgentSteps() {const localize = useLocalize();- const methods = useFormContext<AgentForm>();- const { control } = methods;+ const { control } = useFormContext<AgentForm>();return (<HoverCard openDelay={50}>- <Controller- name="recursion_limit"- control={control}- render={({ field }) => (- <FormInput- field={field}- containerClass="w-1/2"- inputClass="w-full"- label={localize('com_ui_agent_recursion_limit')}- placeholder={localize('com_nav_theme_system')}- type="number"- labelClass="w-fit"- labelAdjacent={- <HoverCardTrigger>- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </HoverCardTrigger>- }- />- )}- />+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-1.5">+ <label htmlFor="recursion_limit" className="text-[13px] font-medium text-text-primary">+ {localize('com_ui_agent_recursion_limit')}+ </label>+ <InfoTrigger />+ </div>+ <Controller+ name="recursion_limit"+ control={control}+ render={({ field }) => (+ <Input+ id="recursion_limit"+ type="number"+ inputMode="numeric"+ value={field.value ?? ''}+ onChange={(e) => {+ const value = e.target.value;+ if (value === '') {+ field.onChange('');+ } else if (!isNaN(Number(value))) {+ field.onChange(Number(value));+ }+ }}+ placeholder={localize('com_nav_theme_system')}+ aria-label={localize('com_ui_agent_recursion_limit')}+ className="h-9 w-full"+ />+ )}+ />+ </div><HoverCardPortal><HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">- {localize('com_ui_agent_recursion_limit_info')}- </p>- </div>+ <p className="text-sm text-text-secondary">+ {localize('com_ui_agent_recursion_limit_info')}+ </p></HoverCardContent></HoverCardPortal></HoverCard>diff --git a/client/src/components/SidePanel/Agents/Advanced/OrchestrationHub.tsx b/client/src/components/SidePanel/Agents/Advanced/OrchestrationHub.tsxnew file mode 100644index 0000000000..1a70fa6362--- /dev/null+++ b/client/src/components/SidePanel/Agents/Advanced/OrchestrationHub.tsx@@ -0,0 +1,66 @@+import { useMemo } from 'react';+import { AgentCapabilities } from 'librechat-data-provider';+import { useFormContext, Controller } from 'react-hook-form';+import type { AgentForm } from '~/common';+import { useAgentPanelContext } from '~/Providers';+import AgentSubagents from './AgentSubagents';+import AgentHandoffs from './AgentHandoffs';+import { groupHeadingClass } from './ui';+import AgentChain from './AgentChain';+import { useLocalize } from '~/hooks';++interface OrchestrationHubProps {+ currentAgentId: string;+}++/**+ * Unifies the multi-agent collaboration patterns (delegate / hand off / chain)+ * into a single hub with one shared visual language. Each pattern is gated by+ * the agent endpoint's enabled capabilities; handoffs are always available.+ */+export default function OrchestrationHub({ currentAgentId }: OrchestrationHubProps) {+ const localize = useLocalize();+ const { control } = useFormContext<AgentForm>();+ const { agentsConfig } = useAgentPanelContext();++ const subagentsEnabled = useMemo(+ () => agentsConfig?.capabilities.includes(AgentCapabilities.subagents) ?? false,+ [agentsConfig],+ );+ const chainEnabled = useMemo(+ () => agentsConfig?.capabilities.includes(AgentCapabilities.chain) ?? false,+ [agentsConfig],+ );++ return (+ <section className="flex flex-col gap-1">+ <div className="flex flex-col gap-0.5">+ <span className={groupHeadingClass}>{localize('com_ui_agent_orchestration')}</span>+ <p className="text-xs text-text-secondary">{localize('com_ui_agent_orchestration_hint')}</p>+ </div>+ <div className="divide-y divide-border-light">+ {subagentsEnabled && (+ <Controller+ name="subagents"+ control={control}+ render={({ field }) => <AgentSubagents field={field} currentAgentId={currentAgentId} />}+ />+ )}+ <Controller+ name="edges"+ control={control}+ defaultValue={[]}+ render={({ field }) => <AgentHandoffs field={field} currentAgentId={currentAgentId} />}+ />+ {chainEnabled && (+ <Controller+ name="agent_ids"+ control={control}+ defaultValue={[]}+ render={({ field }) => <AgentChain field={field} currentAgentId={currentAgentId} />}+ />+ )}+ </div>+ </section>+ );+}diff --git a/client/src/components/SidePanel/Agents/Advanced/OrchestrationPattern.tsx b/client/src/components/SidePanel/Agents/Advanced/OrchestrationPattern.tsxnew file mode 100644index 0000000000..d73e9d3e11--- /dev/null+++ b/client/src/components/SidePanel/Agents/Advanced/OrchestrationPattern.tsx@@ -0,0 +1,63 @@+import { HoverCard, HoverCardPortal, HoverCardContent } from '@librechat/client';+import type { ReactNode } from 'react';+import { BetaPill, InfoTrigger } from './ui';+import { ESide } from '~/common';++interface OrchestrationPatternProps {+ icon: ReactNode;+ title: string;+ subtitle: string;+ info: ReactNode;+ beta?: boolean;+ /** Right-aligned status slot: a switch, count pill, etc. */+ trailing?: ReactNode;+ children?: ReactNode;+}++/**+ * One collaboration pattern inside the orchestration hub, rendered as a flat+ * section (no surrounding card): a leading topology icon, a title with optional+ * Beta tag and info popover, a one-line purpose, a trailing status slot, and the+ * pattern's inline configuration body. Sections are separated by dividers, not+ * nested cards.+ */+export default function OrchestrationPattern({+ icon,+ title,+ subtitle,+ info,+ beta,+ trailing,+ children,+}: OrchestrationPatternProps) {+ return (+ <HoverCard openDelay={50}>+ <div className="flex flex-col gap-3 py-4">+ <div className="flex items-start justify-between gap-3">+ <div className="flex min-w-0 items-start gap-2.5">+ <span className="mt-0.5 flex-shrink-0 text-text-secondary" aria-hidden="true">+ {icon}+ </span>+ <div className="flex min-w-0 flex-col gap-0.5">+ <div className="flex items-center gap-1.5">+ <span className="text-sm font-medium text-text-primary">{title}</span>+ {beta && <BetaPill />}+ <InfoTrigger />+ </div>+ <p className="text-xs text-text-secondary">{subtitle}</p>+ </div>+ </div>+ {trailing != null && (+ <div className="flex flex-shrink-0 items-center gap-2">{trailing}</div>+ )}+ </div>+ {children != null && <div className="flex flex-col gap-3">{children}</div>}+ </div>+ <HoverCardPortal>+ <HoverCardContent side={ESide.Top} className="w-80">+ <div className="space-y-2">{info}</div>+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCard>+ );+}diff --git a/client/src/components/SidePanel/Agents/Advanced/SkillsToggle.tsx b/client/src/components/SidePanel/Agents/Advanced/SkillsToggle.tsxnew file mode 100644index 0000000000..0b8040b57e--- /dev/null+++ b/client/src/components/SidePanel/Agents/Advanced/SkillsToggle.tsx@@ -0,0 +1,31 @@+import { useFormContext, Controller } from 'react-hook-form';+import type { AgentForm } from '~/common';+import { useLocalize } from '~/hooks';+import { ToggleSetting } from './ui';++const id = 'skills_enabled_killswitch';++export default function SkillsToggle() {+ const localize = useLocalize();+ const { control } = useFormContext<AgentForm>();++ return (+ <Controller+ name="skills_enabled"+ control={control}+ render={({ field }) => (+ <ToggleSetting+ id={id}+ label={localize('com_ui_tools_skills_enabled_kill_switch')}+ checked={field.value === true}+ onCheckedChange={(value) => field.onChange(Boolean(value))}+ info={+ <p className="text-sm text-text-secondary">+ {localize('com_ui_tools_skills_enabled_kill_switch_hint')}+ </p>+ }+ />+ )}+ />+ );+}diff --git a/client/src/components/SidePanel/Agents/Advanced/ui.tsx b/client/src/components/SidePanel/Agents/Advanced/ui.tsxnew file mode 100644index 0000000000..56944b5f41--- /dev/null+++ b/client/src/components/SidePanel/Agents/Advanced/ui.tsx@@ -0,0 +1,98 @@+import {+ Switch,+ HoverCard,+ CircleHelpIcon,+ HoverCardPortal,+ HoverCardContent,+ HoverCardTrigger,+} from '@librechat/client';+import type { ReactNode } from 'react';+import { useLocalize } from '~/hooks';+import { ESide } from '~/common';++export const sectionLabelClass =+ 'text-[11px] font-medium uppercase tracking-wide text-text-secondary';++/** Prominent heading for a top-level settings group (Essentials, Orchestration). */+export const groupHeadingClass = 'text-sm font-semibold text-text-primary';++/** Small count chip, e.g. "2 / 10". */+export function CountPill({ children }: { children: ReactNode }) {+ return (+ <span className="inline-flex h-4 items-center justify-center whitespace-nowrap rounded-full bg-surface-tertiary px-1.5 text-[10px] font-medium tabular-nums text-text-secondary">+ {children}+ </span>+ );+}++/** "Beta" accent pill. */+export function BetaPill() {+ const localize = useLocalize();+ return (+ <span className="rounded-full border border-purple-600/40 bg-purple-500/10 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-purple-700 dark:text-purple-400">+ {localize('com_ui_beta')}+ </span>+ );+}++/**+ * Focusable help trigger for an info HoverCard. Must be rendered inside a+ * `HoverCard` so the popover opens on hover or keyboard focus.+ */+export function InfoTrigger() {+ const localize = useLocalize();+ return (+ <HoverCardTrigger asChild>+ <button+ type="button"+ aria-label={localize('com_ui_more_info')}+ className="flex h-4 w-4 flex-shrink-0 items-center justify-center rounded text-text-tertiary transition-colors hover:text-text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <CircleHelpIcon className="h-3.5 w-3.5" aria-hidden={true} />+ </button>+ </HoverCardTrigger>+ );+}++interface ToggleSettingProps {+ id: string;+ label: string;+ checked: boolean;+ onCheckedChange: (value: boolean) => void;+ /** Optional explanation shown in a `?` popover next to the label. */+ info?: ReactNode;+}++/**+ * A subordinate on/off setting: a small secondary label, an optional info+ * popover, and a switch on the right. Sits below a pattern title without+ * competing with it for visual weight.+ */+export function ToggleSetting({ id, label, checked, onCheckedChange, info }: ToggleSettingProps) {+ const row = (+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-1.5">+ <label htmlFor={id} className="truncate text-[13px] font-medium text-text-primary">+ {label}+ </label>+ {info != null && <InfoTrigger />}+ </div>+ <Switch id={id} checked={checked} onCheckedChange={onCheckedChange} aria-label={label} />+ </div>+ );++ if (info == null) {+ return row;+ }++ return (+ <HoverCard openDelay={50}>+ {row}+ <HoverCardPortal>+ <HoverCardContent side={ESide.Top} className="w-80">+ <div className="space-y-2 text-sm text-text-secondary">{info}</div>+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCard>+ );+}diff --git a/client/src/components/SidePanel/Agents/AgentAvatar.tsx b/client/src/components/SidePanel/Agents/AgentAvatar.tsxindex 6b778f6515..7625c9a896 100644--- a/client/src/components/SidePanel/Agents/AgentAvatar.tsx+++ b/client/src/components/SidePanel/Agents/AgentAvatar.tsx@@ -78,24 +78,31 @@ function Avatar({ avatar }: { avatar: AgentAvatar | null }) {const canReset = hasIcon;return (- <>- <div className="flex w-full items-center justify-center gap-4">- <AvatarMenu- trigger={- <button- type="button"- className="f h-20 w-20 outline-none ring-offset-0 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"- aria-label={localize('com_ui_upload_agent_avatar_label')}- >- {avatarPreview ? <AgentAvatarRender url={avatarPreview} /> : <NoImage />}- </button>- }- handleFileChange={handleFileChange}- onReset={handleReset}- canReset={canReset}- />- </div>- </>+ <AvatarMenu+ trigger={+ <button+ type="button"+ className="h-14 w-14 overflow-hidden rounded-full outline-none ring-offset-0 transition-shadow focus:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ aria-label={localize('com_ui_upload_agent_avatar_label')}+ >+ <span+ className="t-icon-swap block h-full w-full"+ data-state={avatarPreview ? 'a' : 'b'}+ aria-hidden="true"+ >+ <span className="t-icon block h-full w-full" data-icon="a">+ <AgentAvatarRender url={avatarPreview} />+ </span>+ <span className="t-icon block h-full w-full" data-icon="b">+ <NoImage />+ </span>+ </span>+ </button>+ }+ handleFileChange={handleFileChange}+ onReset={handleReset}+ canReset={canReset}+ />);}diff --git a/client/src/components/SidePanel/Agents/AgentConfig.tsx b/client/src/components/SidePanel/Agents/AgentConfig.tsxindex b5c6973c38..927fc1a5bd 100644--- a/client/src/components/SidePanel/Agents/AgentConfig.tsx+++ b/client/src/components/SidePanel/Agents/AgentConfig.tsx@@ -1,85 +1,26 @@-import React, { useState, useMemo, useCallback } from 'react';-import { X } from 'lucide-react';-import { useQueries } from '@tanstack/react-query';-import { Switch, useToastContext } from '@librechat/client';+import { Input } from '@librechat/client';import { Controller, useWatch, useFormContext } from 'react-hook-form';-import {- EModelEndpoint,- PermissionTypes,- Permissions,- QueryKeys,- dataService,- getEndpointField,-} from 'librechat-data-provider';+import { EModelEndpoint, getEndpointField } from 'librechat-data-provider';import type { AgentForm, IconComponentTypes } from '~/common';-import {- removeFocusOutlines,- processAgentOption,- defaultTextProps,- validateEmail,- getIconKey,- cn,-} from '~/utils';-import {- useLocalize,- useVisibleTools,- useHasAccess,- useHasMemoryAccess,- useAuthContext,-} from '~/hooks';-import { ToolSelectDialog, MCPToolSelectDialog } from '~/components/Tools';-import useAgentCapabilities from '~/hooks/Agents/useAgentCapabilities';-import { useListSkillsQuery, useGetAgentFiles } from '~/data-provider';-import { useFileMapContext, useAgentPanelContext } from '~/Providers';-import { SkillSelectDialog } from '~/components/Skills/dialogs';import AgentCategorySelector from './AgentCategorySelector';-import Action from '~/components/SidePanel/Builder/Action';-import { Panel, isEphemeralAgent } from '~/common';+import { useLocalize, useAgentCapabilities } from '~/hooks';+import { validateEmail, getIconKey, cn } from '~/utils';+import { useAgentFileEntries } from './Tools/hooks';+import { useAgentPanelContext } from '~/Providers';+import ToolsSection from './Tools/ToolsSection';import { icons } from '~/hooks/Endpoint/Icons';import Instructions from './Instructions';-import AgentAvatar from './AgentAvatar';import FileContext from './FileContext';-import SearchForm from './Search/Form';-import FileSearch from './FileSearch';-import Artifacts from './Artifacts';-import AgentTool from './AgentTool';-import CodeForm from './Code/Form';-import MCPTools from './MCPTools';-import Memory from './Memory';--/** A skill lookup only counts as a confirmed miss on 404/403 — deleted or no- * longer shared. Transient/network/server errors must not present a valid- * configured skill as removable. */-const isConfirmedSkillMiss = (error: unknown): boolean => {- const status = (error as { response?: { status?: number } } | null)?.response?.status;- return status === 404 || status === 403;-};+import AgentAvatar from './AgentAvatar';+import { Panel } from '~/common';-const labelClass = 'mb-2 text-token-text-primary block text-sm font-medium';-const inputClass = cn(- defaultTextProps,- 'flex w-full px-3 py-2 border-border-light bg-surface-secondary focus-visible:ring-2 focus-visible:ring-ring-primary',- removeFocusOutlines,-);+const fieldClass = 'h-9';export default function AgentConfig() {const localize = useLocalize();- const fileMap = useFileMapContext();- const { showToast } = useToastContext();const methods = useFormContext<AgentForm>();- const [showToolDialog, setShowToolDialog] = useState(false);- const [showMCPToolDialog, setShowMCPToolDialog] = useState(false);- const [showSkillDialog, setShowSkillDialog] = useState(false);- const {- actions,- setAction,- regularTools,- agentsConfig,- availableMCPServers,- mcpServersMap,- setActivePanel,- endpointsConfig,- } = useAgentPanelContext();+ const { setActivePanel, endpointsConfig, agentsConfig } = useAgentPanelContext();+ const { contextEnabled } = useAgentCapabilities(agentsConfig?.capabilities);const {control,@@ -88,166 +29,8 @@ export default function AgentConfig() {const provider = useWatch({ control, name: 'provider' });const model = useWatch({ control, name: 'model' });const agent = useWatch({ control, name: 'agent' });- const tools = useWatch({ control, name: 'tools' });- const skills = useWatch({ control, name: 'skills' });- const skillsActive = useWatch({ control, name: 'skills_enabled' });const agent_id = useWatch({ control, name: 'id' });-- let skillsHintKey:- | 'com_ui_skills_disabled_hint'- | 'com_ui_skills_enabled_allowlist_hint'- | 'com_ui_skills_enabled_all_hint' = 'com_ui_skills_disabled_hint';- if (skillsActive === true) {- skillsHintKey =- (skills ?? []).length > 0- ? 'com_ui_skills_enabled_allowlist_hint'- : 'com_ui_skills_enabled_all_hint';- }-- const {- codeEnabled,- toolsEnabled,- memoryEnabled,- contextEnabled,- actionsEnabled,- skillsEnabled,- artifactsEnabled,- webSearchEnabled,- fileSearchEnabled,- } = useAgentCapabilities(agentsConfig?.capabilities);-- const hasSkillsAccess = useHasAccess({- permissionType: PermissionTypes.SKILLS,- permission: Permissions.USE,- });- const { user } = useAuthContext();- const hasMemoryAccess = useHasMemoryAccess();- /** Mirror the chat memory badge's opt-out gate: a user who disabled memory in- * personalization can't use the inline tools, so the builder toggle is inert- * for them and must be hidden too. */- const showMemory = hasMemoryAccess && memoryEnabled && user?.personalization?.memories !== false;- const showSkills = hasSkillsAccess && skillsEnabled;- const { data: skillsData } = useListSkillsQuery({ limit: 100 }, { enabled: showSkills });- const skillsMap = useMemo(() => {- const map = new Map<string, string>();- for (const skill of skillsData?.skills ?? []) {- map.set(skill._id, skill.name);- }- return map;- }, [skillsData?.skills]);-- /** Allowlist ids missing from the first catalog page (`limit: 100`) are- * resolved individually — a cache miss alone must never present a valid- * configured skill as unavailable and invite its removal. */- const unresolvedSkillIds = useMemo(- () => (skillsData === undefined ? [] : (skills ?? []).filter((id) => !skillsMap.has(id))),- [skills, skillsMap, skillsData],- );- const unresolvedSkillQueries = useQueries({- queries: unresolvedSkillIds.map((skillId) => ({- queryKey: [QueryKeys.skill, skillId],- queryFn: () => dataService.getSkill(skillId),- retry: false,- refetchOnMount: false,- refetchOnReconnect: false,- refetchOnWindowFocus: false,- })),- });- const unresolvedSkills = useMemo(() => {- const map = new Map<string, { name?: string; missing: boolean }>();- unresolvedSkillIds.forEach((skillId, index) => {- const query = unresolvedSkillQueries[index];- if (query?.isError === true && isConfirmedSkillMiss(query.error)) {- map.set(skillId, { missing: true });- } else if (query?.data?.name) {- map.set(skillId, { name: query.data.name, missing: false });- }- });- return map;- }, [unresolvedSkillIds, unresolvedSkillQueries]);-- const { data: agentFiles = [] } = useGetAgentFiles(agent_id);-- const mergedFileMap = useMemo(() => {- const newFileMap = { ...fileMap };- agentFiles.forEach((file) => {- if (file.file_id) {- newFileMap[file.file_id] = file;- }- });- return newFileMap;- }, [fileMap, agentFiles]);-- const context_files = useMemo(() => {- if (typeof agent === 'string') {- return [];- }-- if (agent?.id !== agent_id) {- return [];- }-- if (agent.context_files) {- return agent.context_files;- }-- const _agent = processAgentOption({- agent,- fileMap: mergedFileMap,- });- return _agent.context_files ?? [];- }, [agent, agent_id, mergedFileMap]);-- const knowledge_files = useMemo(() => {- if (typeof agent === 'string') {- return [];- }-- if (agent?.id !== agent_id) {- return [];- }-- if (agent.knowledge_files) {- return agent.knowledge_files;- }-- const _agent = processAgentOption({- agent,- fileMap: mergedFileMap,- });- return _agent.knowledge_files ?? [];- }, [agent, agent_id, mergedFileMap]);-- const code_files = useMemo(() => {- if (typeof agent === 'string') {- return [];- }-- if (agent?.id !== agent_id) {- return [];- }-- if (agent.code_files) {- return agent.code_files;- }-- const _agent = processAgentOption({- agent,- fileMap: mergedFileMap,- });- return _agent.code_files ?? [];- }, [agent, agent_id, mergedFileMap]);-- const handleAddActions = useCallback(() => {- if (isEphemeralAgent(agent_id)) {- showToast({- message: localize('com_assistants_actions_disabled'),- status: 'warning',- });- return;- }- setActivePanel(Panel.actions);- }, [agent_id, setActivePanel, showToast, localize]);+ const { contextFiles } = useAgentFileEntries();const providerValue = typeof provider === 'string' ? provider : provider?.value;let Icon: IconComponentTypes | null | undefined;@@ -267,29 +50,25 @@ export default function AgentConfig() {Icon = icons[iconKey];}- const { toolIds, mcpServerNames } = useVisibleTools(tools, regularTools, mcpServersMap);-return (- <>- <div className="h-auto pt-1">- {/* Avatar & Name */}- <div className="mb-4">+ <div className="h-auto pt-1">+ {/* IDENTITY — flat header, always visible, avatar inline */}+ <div className="mb-3 mt-1 flex items-center gap-3">+ <div className="flex-shrink-0"><AgentAvatar avatar={agent?.['avatar'] ?? null} />- <label className={labelClass} htmlFor="name">- {localize('com_ui_name')}- <span className="text-red-500">*</span>- </label>+ </div>+ <div className="flex min-w-0 flex-1 flex-col gap-2"><Controllername="name"rules={{ required: localize('com_ui_agent_name_is_required') }}control={control}render={({ field }) => (- <>- <input+ <div className="flex flex-col">+ <Input{...field}value={field.value ?? ''}maxLength={256}- className={inputClass}+ className={cn(fieldClass, 'font-medium')}id="name"type="text"placeholder={localize('com_agents_name_placeholder')}@@ -298,41 +77,22 @@ export default function AgentConfig() {aria-describedby={errors.name ? 'agent-name-error' : undefined}/>{errors.name && (- <div- id="agent-name-error"- className="mt-1 w-56 text-sm text-red-500"- role="alert"- >+ <div id="agent-name-error" className="mt-1 text-xs text-red-500" role="alert">{errors.name.message}</div>)}- </>- )}- />- <Controller- name="id"- control={control}- render={({ field }) => (- <p className="h-3 text-xs italic text-text-secondary" aria-live="polite">- {field.value}- </p>+ </div>)}/>- </div>- {/* Description */}- <div className="mb-4">- <label className={labelClass} htmlFor="description">- {localize('com_ui_description')}- </label><Controllername="description"control={control}render={({ field }) => (- <input+ <Input{...field}value={field.value ?? ''}maxLength={512}- className={inputClass}+ className={fieldClass}id="description"type="text"placeholder={localize('com_agents_description_placeholder')}@@ -341,26 +101,27 @@ export default function AgentConfig() {)}/></div>- {/* Category */}- <div className="mb-4">- <label className={labelClass} htmlFor="category-selector">- {localize('com_ui_category')} <span className="text-red-500">*</span>- </label>- <AgentCategorySelector className="w-full" />- </div>- {/* Instructions */}- <Instructions />- {/* Model and Provider */}- <div className="mb-4">- <label className={labelClass} htmlFor="provider">+ </div>++ {/* MODEL + CATEGORY — balanced 2-column grid */}+ <div className="mb-3 grid grid-cols-2 gap-2">+ <div className="flex min-w-0 flex-col">+ <label+ className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-text-secondary"+ htmlFor="provider"+ >{localize('com_ui_model')} <span className="text-red-500">*</span></label><buttontype="button"onClick={() => setActivePanel(Panel.model)}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"+ title={model || undefined}+ className={cn(+ 'relative flex h-9 w-full min-w-0 items-center overflow-hidden rounded-lg border border-border-light bg-surface-secondary text-sm font-medium text-text-primary transition-colors hover:bg-surface-tertiary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',+ model != null && model ? 'px-1' : 'px-3',+ )}>- <div className="flex w-full items-center gap-2">+ <div className="flex w-full min-w-0 items-center gap-2">{Icon && (<div className="shadow-stroke relative flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-white text-black dark:bg-white"><Icon@@ -371,326 +132,112 @@ export default function AgentConfig() {/></div>)}- <span>{model != null && model ? model : localize('com_ui_select_model')}</span>+ <span className="truncate">+ {model != null && model ? model : localize('com_ui_select_model')}+ </span></div></button></div>- {(codeEnabled ||- fileSearchEnabled ||- artifactsEnabled ||- contextEnabled ||- showMemory ||- webSearchEnabled) && (- <div className="mb-4 flex w-full flex-col items-start gap-3">- <label className="text-token-text-primary block text-sm font-medium">- {localize('com_assistants_capabilities')}- </label>- {/* Code Execution */}- {codeEnabled && <CodeForm agent_id={agent_id} files={code_files} />}- {/* Web Search */}- {webSearchEnabled && <SearchForm />}- {/* File Context */}- {contextEnabled && <FileContext agent_id={agent_id} files={context_files} />}- {/* Artifacts */}- {artifactsEnabled && <Artifacts />}- {/* File Search */}- {fileSearchEnabled && <FileSearch agent_id={agent_id} files={knowledge_files} />}- {/* Memory */}- {showMemory && <Memory />}- </div>- )}- {/* MCP Section */}- {availableMCPServers != null && availableMCPServers.length > 0 && (- <MCPTools- agentId={agent_id}- mcpServerNames={mcpServerNames}- setShowMCPToolDialog={setShowMCPToolDialog}- />- )}+ <div className="flex flex-col">+ <label+ className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-text-secondary"+ htmlFor="category-selector"+ >+ {localize('com_ui_category')} <span className="text-red-500">*</span>+ </label>+ <AgentCategorySelector className="w-full rounded-lg" />+ </div>+ </div>- {showSkills && (- <div className="mb-4">- <div className="mb-2 flex items-center justify-between">- <label- htmlFor="skills_enabled"- className="text-token-text-primary block text-sm font-medium"- >- {localize('com_ui_skills')}- </label>- <Controller- name="skills_enabled"- control={control}- render={({ field }) => (- <Switch- id="skills_enabled"- checked={field.value === true}- onCheckedChange={(value: boolean) => field.onChange(Boolean(value))}- data-testid="skills_enabled"- aria-label={localize('com_ui_skills_enable_toggle')}- />- )}- />- </div>- <p className="mb-2 text-xs text-text-secondary">{localize(skillsHintKey)}</p>- <div- className={skillsActive === true ? undefined : 'pointer-events-none opacity-50'}- aria-disabled={skillsActive !== true}- >- <div className="mb-1">- {(skills ?? []).map((skillId) => {- const skillName = skillsMap.get(skillId) ?? unresolvedSkills.get(skillId)?.name;- /** Hide chips while the catalog page or per-id lookup is in- * flight. Once the backend confirms a miss (deleted or no- * longer shared), the id must stay visible and removable —- * otherwise the allowlist silently scopes the agent to- * zero skills with no way to fix it in the UI. */- if (!skillName && unresolvedSkills.get(skillId)?.missing !== true) {- return null;- }- const isUnavailable = !skillName;- return (- <div- key={skillId}- className="mb-1 flex items-center justify-between rounded-md border border-border-light px-3 py-2 text-sm"- >- <span- className={- isUnavailable- ? 'truncate italic text-text-secondary'- : 'truncate text-text-primary'- }- title={isUnavailable ? skillId : undefined}- >- {skillName ?? localize('com_ui_skill_unavailable')}- </span>- <button- type="button"- onClick={() => {- const current: string[] = methods.getValues('skills') ?? [];- methods.setValue(- 'skills',- current.filter((id) => id !== skillId),- { shouldDirty: true },- );- }}- className="ml-2 flex-shrink-0 text-text-secondary transition-colors hover:text-text-primary"- aria-label={localize('com_ui_remove_skill_var', {- 0: skillName ?? skillId,- })}- disabled={skillsActive !== true}- >- <X className="h-4 w-4" aria-hidden="true" />- </button>- </div>- );- })}- </div>- <div className="mt-2">- <button- type="button"- onClick={() => setShowSkillDialog(true)}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"- aria-haspopup="dialog"- disabled={skillsActive !== true}- >- <div className="flex w-full items-center justify-center gap-2">- {localize('com_ui_add_skills')}- </div>- </button>- </div>- </div>- </div>- )}+ {/* INSTRUCTIONS */}+ <Instructions />- {/* Agent Tools & Actions */}- <div className="mb-4">- <label className={labelClass}>- {(() => {- if (toolsEnabled === true && actionsEnabled === true) {- return localize('com_ui_tools_and_actions');- }- if (toolsEnabled === true) {- return localize('com_ui_tools');- }- if (actionsEnabled === true) {- return localize('com_assistants_actions');- }- return '';- })()}- </label>- <div>- <div className="mb-1">- {/* Render all visible IDs */}- {toolIds.map((toolId, i) => {- const tool = regularTools?.find((t) => t.pluginKey === toolId);- if (!tool) return null;- return (- <AgentTool- key={`${toolId}-${i}-${agent_id}`}- tool={toolId}- regularTools={regularTools}- agent_id={agent_id}- />- );- })}- </div>- <div className="flex flex-col gap-1">- {(actions ?? [])- .filter((action) => action.agent_id === agent_id)- .map((action, i) => (- <Action- key={i}- action={action}- onClick={() => {- setAction(action);- setActivePanel(Panel.actions);- }}- />- ))}- </div>- <div className="mt-2 flex space-x-2">- {(toolsEnabled ?? false) && (- <button- type="button"- onClick={() => setShowToolDialog(true)}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"- aria-haspopup="dialog"- >- <div className="flex w-full items-center justify-center gap-2">- {localize('com_assistants_add_tools')}- </div>- </button>- )}- {(actionsEnabled ?? false) && (- <button- type="button"- disabled={isEphemeralAgent(agent_id)}- onClick={handleAddActions}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"- aria-haspopup="dialog"- >- <div className="flex w-full items-center justify-center gap-2">- {localize('com_assistants_add_actions')}- </div>- </button>- )}- </div>- </div>+ {/* TOOLS — unified built-ins / tools / actions / mcp / skills */}+ <ToolsSection agentId={agent_id} />++ {/* FILE CONTEXT — standalone section, separate from the tool library */}+ {contextEnabled && (+ <div className="mb-3">+ <FileContext agent_id={agent_id} files={contextFiles} /></div>- {/* Support Contact (Optional) */}- <div className="mb-4">- <div className="mb-1.5 flex items-center gap-2">- <span>- <label className="text-token-text-primary block text-sm font-medium">- {localize('com_ui_support_contact')}- </label>- </span>- </div>- <div className="space-y-3">- {/* Support Contact Name */}- <div className="flex flex-col">- <label- className="mb-1 flex items-center justify-between"- htmlFor="support-contact-name"- >- <span className="text-sm">{localize('com_ui_support_contact_name')}</span>- </label>- <Controller- name="support_contact.name"- control={control}- rules={{- minLength: {- value: 3,- message: localize('com_ui_support_contact_name_min_length', { minLength: 3 }),- },- }}- render={({ field, fieldState: { error } }) => (- <>- <input- {...field}- value={field.value ?? ''}- className={cn(inputClass, error ? 'border-2 border-red-500' : '')}- id="support-contact-name"- type="text"- placeholder={localize('com_ui_support_contact_name_placeholder')}- aria-label={localize('com_ui_support_contact_name')}- aria-invalid={error ? 'true' : 'false'}- aria-describedby={error ? 'support-contact-name-error' : undefined}- />- {error && (- <span- id="support-contact-name-error"- className="text-sm text-red-500 transition duration-300 ease-in-out"- role="alert"- aria-live="polite"- >- {error.message}- </span>- )}- </>+ )}++ {/* SUPPORT CONTACT */}+ <div className="mb-3 flex flex-col">+ <label className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-text-secondary">+ {localize('com_ui_support_contact')}+ </label>+ <div className="space-y-2">+ <Controller+ name="support_contact.name"+ control={control}+ rules={{+ minLength: {+ value: 3,+ message: localize('com_ui_support_contact_name_min_length', { minLength: 3 }),+ },+ }}+ render={({ field, fieldState: { error } }) => (+ <div className="flex flex-col">+ <Input+ {...field}+ value={field.value ?? ''}+ className={cn(fieldClass, error && 'border-2 border-red-500')}+ id="support-contact-name"+ type="text"+ placeholder={localize('com_ui_support_contact_name_placeholder')}+ aria-label={localize('com_ui_support_contact_name')}+ aria-invalid={error ? 'true' : 'false'}+ aria-describedby={error ? 'support-contact-name-error' : undefined}+ />+ {error && (+ <span+ id="support-contact-name-error"+ className="mt-1 text-xs text-red-500"+ role="alert"+ aria-live="polite"+ >+ {error.message}+ </span>)}- />- </div>- {/* Support Contact Email */}- <div className="flex flex-col">- <label- className="mb-1 flex items-center justify-between"- htmlFor="support-contact-email"- >- <span className="text-sm">{localize('com_ui_support_contact_email')}</span>- </label>- <Controller- name="support_contact.email"- control={control}- rules={{- validate: (value) =>- validateEmail(value ?? '', localize('com_ui_support_contact_email_invalid')),- }}- render={({ field, fieldState: { error } }) => (- <>- <input- {...field}- value={field.value ?? ''}- className={cn(inputClass, error ? 'border-2 border-red-500' : '')}- id="support-contact-email"- type="email"- placeholder={localize('com_ui_support_contact_email_placeholder')}- aria-label={localize('com_ui_support_contact_email')}- aria-invalid={error ? 'true' : 'false'}- aria-describedby={error ? 'support-contact-email-error' : undefined}- />- {error && (- <span- id="support-contact-email-error"- className="text-sm text-red-500 transition duration-300 ease-in-out"- role="alert"- aria-live="polite"- >- {error.message}- </span>- )}- </>+ </div>+ )}+ />+ <Controller+ name="support_contact.email"+ control={control}+ rules={{+ validate: (value) =>+ validateEmail(value ?? '', localize('com_ui_support_contact_email_invalid')),+ }}+ render={({ field, fieldState: { error } }) => (+ <div className="flex flex-col">+ <Input+ {...field}+ value={field.value ?? ''}+ className={cn(fieldClass, error && 'border-2 border-red-500')}+ id="support-contact-email"+ type="email"+ placeholder={localize('com_ui_support_contact_email_placeholder')}+ aria-label={localize('com_ui_support_contact_email')}+ aria-invalid={error ? 'true' : 'false'}+ aria-describedby={error ? 'support-contact-email-error' : undefined}+ />+ {error && (+ <span+ id="support-contact-email-error"+ className="mt-1 text-xs text-red-500"+ role="alert"+ aria-live="polite"+ >+ {error.message}+ </span>)}- />- </div>- </div>+ </div>+ )}+ /></div></div>- <ToolSelectDialog- isOpen={showToolDialog}- setIsOpen={setShowToolDialog}- endpoint={EModelEndpoint.agents}- />- {availableMCPServers != null && availableMCPServers.length > 0 && (- <MCPToolSelectDialog- agentId={agent_id}- isOpen={showMCPToolDialog}- mcpServerNames={mcpServerNames}- setIsOpen={setShowMCPToolDialog}- endpoint={EModelEndpoint.agents}- />- )}- {showSkills && <SkillSelectDialog isOpen={showSkillDialog} setIsOpen={setShowSkillDialog} />}- </>+ </div>);}diff --git a/client/src/components/SidePanel/Agents/AgentFooter.tsx b/client/src/components/SidePanel/Agents/AgentFooter.tsxindex ff98f7c48b..806ea36048 100644--- a/client/src/components/SidePanel/Agents/AgentFooter.tsx+++ b/client/src/components/SidePanel/Agents/AgentFooter.tsx@@ -61,24 +61,28 @@ export default function AgentFooter({const canDeleteThisAgent = hasPermission(PermissionBits.DELETE);const canShareRemoteAgent = hasRemoteAgentPermission(PermissionBits.SHARE);const isSaving = createMutation.isLoading || updateMutation.isLoading || isAvatarUploading;- const renderSaveButton = () => {- if (isSaving) {- return <Spinner className="icon-md" aria-hidden="true" />;- }-- if (agent_id) {- return localize('com_ui_save');- }-- return localize('com_ui_create');- };+ const saveLabel = agent_id ? localize('com_ui_save') : localize('com_ui_create');+ const renderSaveButton = () => (+ <span className="t-icon-swap" data-state={isSaving ? 'b' : 'a'} aria-hidden={false}>+ <span className="t-icon" data-icon="a">+ {saveLabel}+ </span>+ <span className="t-icon" data-icon="b">+ <Spinner className="icon-md" aria-hidden="true" />+ </span>+ </span>+ );const showButtons = activePanel === Panel.builder;return (<div className="mb-1 flex w-full flex-col gap-2">- {showButtons && <AdvancedButton setActivePanel={setActivePanel} />}- {showButtons && agent_id && <VersionButton setActivePanel={setActivePanel} />}+ {showButtons && (+ <div className={`grid gap-2 ${agent_id ? 'grid-cols-2' : 'grid-cols-1'}`}>+ <AdvancedButton setActivePanel={setActivePanel} />+ {!!agent_id && <VersionButton setActivePanel={setActivePanel} />}+ </div>+ )}{user?.role === SystemRoles.ADMIN && showButtons && <AdminSettings />}{/* Context Button */}<div className="flex items-center justify-end gap-2">diff --git a/client/src/components/SidePanel/Agents/AgentPanelSkeleton.tsx b/client/src/components/SidePanel/Agents/AgentPanelSkeleton.tsxindex 743f01ae30..80c2aa43ce 100644--- a/client/src/components/SidePanel/Agents/AgentPanelSkeleton.tsx+++ b/client/src/components/SidePanel/Agents/AgentPanelSkeleton.tsx@@ -1,69 +1,51 @@-import React from 'react';import { Skeleton } from '@librechat/client';export default function AgentPanelSkeleton() {return (- <div className="h-auto bg-white dark:bg-transparent">- {/* Avatar */}- <div className="mb-4">- <div className="flex w-full items-center justify-center gap-4">- <Skeleton className="relative h-20 w-20 rounded-full" />+ <div className="h-auto pt-1" aria-hidden="true">+ {/* IDENTITY — inline avatar + name/description */}+ <div className="mb-3 mt-1 flex items-center gap-3">+ <Skeleton className="h-16 w-16 flex-shrink-0 rounded-full" />+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <Skeleton className="h-9 w-full rounded-xl" />+ <Skeleton className="h-9 w-full rounded-xl" /></div>- {/* Name */}- <Skeleton className="mb-2 h-5 w-1/5 rounded-lg" />- <Skeleton className="mb-1 h-9 w-full rounded-lg" />- <Skeleton className="h-3 w-1/4 rounded-lg" /></div>- {/* Description */}- <div className="mb-4">- <Skeleton className="mb-2 h-5 w-1/4 rounded-lg" />- <Skeleton className="h-9 w-full rounded-lg" />- </div>-- {/* Instructions */}- <div className="mb-6">- <Skeleton className="mb-2 h-5 w-1/4 rounded-lg" />- <Skeleton className="h-[100px] w-full rounded-lg" />- </div>-- {/* Model and Provider */}- <div className="mb-6">- <Skeleton className="mb-2 h-5 w-1/4 rounded-lg" />- <Skeleton className="h-9 w-full rounded-lg" />+ {/* MODEL + CATEGORY — 2-column grid */}+ <div className="mb-3 grid grid-cols-2 gap-2">+ <div className="flex flex-col">+ <Skeleton className="mb-1 h-3 w-12 rounded" />+ <Skeleton className="h-9 w-full rounded-xl" />+ </div>+ <div className="flex flex-col">+ <Skeleton className="mb-1 h-3 w-16 rounded" />+ <Skeleton className="h-9 w-full rounded-xl" />+ </div></div>- {/* Capabilities */}- <div className="mb-6">- <Skeleton className="mb-2 h-5 w-1/4 rounded-lg" />- <Skeleton className="mb-2 h-5 w-36 rounded-lg" />- <Skeleton className="mb-4 h-[35px] w-full rounded-lg" />- <Skeleton className="mb-2 h-5 w-24 rounded-lg" />- <Skeleton className="h-[35px] w-full rounded-lg" />+ {/* INSTRUCTIONS */}+ <div className="mb-3 flex flex-col">+ <Skeleton className="mb-1 h-3 w-20 rounded" />+ <Skeleton className="h-[88px] w-full rounded-xl" /></div>- {/* Tools & Actions */}- <div className="mb-6">- <Skeleton className="mb-2 h-5 w-1/4 rounded-lg" />- <Skeleton className="mb-2 h-[35px] w-full rounded-lg" />- <Skeleton className="mb-2 h-[35px] w-full rounded-lg" />- <div className="flex space-x-2">- <Skeleton className="h-8 w-1/2 rounded-lg" />- <Skeleton className="h-8 w-1/2 rounded-lg" />+ {/* TOOLS — header + a couple of rows */}+ <div className="mb-3 flex flex-col">+ <Skeleton className="mb-1 h-3 w-16 rounded" />+ <div className="flex flex-col gap-1.5">+ <Skeleton className="h-10 w-full rounded-lg" />+ <Skeleton className="h-10 w-full rounded-lg" /></div></div>- {/* Admin Settings */}- <div className="mb-6">- <Skeleton className="h-[35px] w-full rounded-lg" />- </div>-- {/* Bottom Buttons */}- <div className="flex items-center justify-end gap-2">- <Skeleton className="h-[35px] w-16 rounded-lg" />- <Skeleton className="h-[35px] w-16 rounded-lg" />- <Skeleton className="h-[35px] w-16 rounded-lg" />- <Skeleton className="h-[35px] w-full rounded-lg" />+ {/* SUPPORT CONTACT */}+ <div className="mb-3 flex flex-col">+ <Skeleton className="mb-1 h-3 w-24 rounded" />+ <div className="space-y-2">+ <Skeleton className="h-9 w-full rounded-xl" />+ <Skeleton className="h-9 w-full rounded-xl" />+ </div></div></div>);diff --git a/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsx b/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsxindex bfa148b3ab..dfb2a27996 100644--- a/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsx+++ b/client/src/components/SidePanel/Agents/AgentPanelSwitch.tsx@@ -3,7 +3,6 @@ import { useRecoilValue } from 'recoil';import { AgentPanelProvider, useAgentPanelContext } from '~/Providers/AgentPanelContext';import { Panel, isEphemeralAgent } from '~/common';import VersionPanel from './Version/VersionPanel';-import ActionsPanel from './ActionsPanel';import AgentPanel from './AgentPanel';import store from '~/store';@@ -26,9 +25,6 @@ function AgentPanelSwitchWithContext() {}}, [setCurrentAgentId, agentId]);- if (activePanel === Panel.actions) {- return <ActionsPanel />;- }if (activePanel === Panel.version) {return <VersionPanel />;}diff --git a/client/src/components/SidePanel/Agents/AgentTool.tsx b/client/src/components/SidePanel/Agents/AgentTool.tsxindex 5685506fe2..69b3b32fa3 100644--- a/client/src/components/SidePanel/Agents/AgentTool.tsx+++ b/client/src/components/SidePanel/Agents/AgentTool.tsx@@ -1,4 +1,5 @@import React, { useState } from 'react';+import { Wrench } from 'lucide-react';import { useFormContext } from 'react-hook-form';import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';import {@@ -73,8 +74,8 @@ export default function AgentTool({}}><div className="flex grow items-center">- {currentTool.icon && (- <div className="flex h-8 w-8 items-center justify-center overflow-hidden rounded-full">+ <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center overflow-hidden rounded-full">+ {currentTool.icon ? (<divclassName="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full bg-center bg-no-repeat dark:bg-white/20"style={{@@ -82,8 +83,12 @@ export default function AgentTool({backgroundSize: 'cover',}}/>- </div>- )}+ ) : (+ <div className="flex h-6 w-6 items-center justify-center rounded-md bg-surface-secondary text-text-secondary">+ <Wrench className="h-3.5 w-3.5" aria-hidden="true" />+ </div>+ )}+ </div><divclassName="grow px-2 py-1.5"style={{ textOverflow: 'ellipsis', wordBreak: 'break-all', overflow: 'hidden' }}diff --git a/client/src/components/SidePanel/Agents/Artifacts.tsx b/client/src/components/SidePanel/Agents/Artifacts.tsxdeleted file mode 100644index d985e8730d..0000000000--- a/client/src/components/SidePanel/Agents/Artifacts.tsx+++ /dev/null@@ -1,125 +0,0 @@-import { useFormContext } from 'react-hook-form';-import { ArtifactModes, AgentCapabilities } from 'librechat-data-provider';-import {- Switch,- HoverCard,- HoverCardPortal,- HoverCardContent,- HoverCardTrigger,- CircleHelpIcon,-} from '@librechat/client';-import type { AgentForm } from '~/common';-import { useLocalize } from '~/hooks';-import { ESide } from '~/common';--export default function Artifacts() {- const localize = useLocalize();- const methods = useFormContext<AgentForm>();- const { setValue, watch } = methods;-- const artifactsMode = watch(AgentCapabilities.artifacts);-- const handleArtifactsChange = (value: boolean) => {- setValue(AgentCapabilities.artifacts, value ? ArtifactModes.DEFAULT : '', {- shouldDirty: true,- });- };-- const handleShadcnuiChange = (value: boolean) => {- setValue(AgentCapabilities.artifacts, value ? ArtifactModes.SHADCNUI : ArtifactModes.DEFAULT, {- shouldDirty: true,- });- };-- const handleCustomModeChange = (value: boolean) => {- setValue(AgentCapabilities.artifacts, value ? ArtifactModes.CUSTOM : ArtifactModes.DEFAULT, {- shouldDirty: true,- });- };-- const isEnabled = artifactsMode !== undefined && artifactsMode !== '';- const isCustomEnabled = artifactsMode === ArtifactModes.CUSTOM;- const isShadcnEnabled = artifactsMode === ArtifactModes.SHADCNUI;-- return (- <div className="w-full">- <div className="mb-1.5 flex items-center gap-2">- <span>- <label className="text-token-text-primary block text-sm font-medium">- {localize('com_ui_artifacts')}- </label>- </span>- </div>- <div className="flex flex-col gap-3">- <SwitchItem- id="artifacts"- label={localize('com_ui_artifacts_toggle_agent')}- checked={isEnabled}- onCheckedChange={handleArtifactsChange}- hoverCardText={localize('com_nav_info_code_artifacts_agent')}- />- <SwitchItem- id="includeShadcnui"- label={localize('com_ui_include_shadcnui')}- checked={isShadcnEnabled}- onCheckedChange={handleShadcnuiChange}- hoverCardText={localize('com_nav_info_include_shadcnui')}- disabled={!isEnabled || isCustomEnabled}- />- <SwitchItem- id="customPromptMode"- label={localize('com_ui_custom_prompt_mode')}- checked={isCustomEnabled}- onCheckedChange={handleCustomModeChange}- hoverCardText={localize('com_nav_info_custom_prompt_mode')}- disabled={!isEnabled}- />- </div>- </div>- );-}--function SwitchItem({- id,- label,- checked,- onCheckedChange,- hoverCardText,- disabled = false,-}: {- id: string;- label: string;- checked: boolean;- onCheckedChange: (value: boolean) => void;- hoverCardText: string;- disabled?: boolean;-}) {- return (- <HoverCard openDelay={50}>- <div className="flex items-center justify-between">- <div className="flex items-center space-x-2">- <div className={disabled ? 'text-sm text-text-tertiary' : 'text-sm'}>{label}</div>- <HoverCardTrigger>- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </HoverCardTrigger>- </div>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">{hoverCardText}</p>- </div>- </HoverCardContent>- </HoverCardPortal>- <Switch- id={id}- checked={checked}- onCheckedChange={onCheckedChange}- className="ml-4"- data-testid={id}- disabled={disabled}- aria-label={label}- />- </div>- </HoverCard>- );-}diff --git a/client/src/components/SidePanel/Agents/Code/Action.tsx b/client/src/components/SidePanel/Agents/Code/Action.tsxdeleted file mode 100644index 187331307d..0000000000--- a/client/src/components/SidePanel/Agents/Code/Action.tsx+++ /dev/null@@ -1,68 +0,0 @@-import { AgentCapabilities } from 'librechat-data-provider';-import { useFormContext, Controller } from 'react-hook-form';-import {- Checkbox,- HoverCard,- CircleHelpIcon,- HoverCardContent,- HoverCardPortal,- HoverCardTrigger,-} from '@librechat/client';-import type { AgentForm } from '~/common';-import { useLocalize } from '~/hooks';-import { ESide } from '~/common';--export default function Action() {- const localize = useLocalize();- const methods = useFormContext<AgentForm>();- const { control, setValue } = methods;-- return (- <HoverCard openDelay={50}>- <div className="flex items-center">- <Controller- name={AgentCapabilities.execute_code}- control={control}- render={({ field }) => (- <Checkbox- {...field}- id="execute-code-checkbox"- checked={!!field.value}- onCheckedChange={(checked) =>- setValue(AgentCapabilities.execute_code, checked === true, { shouldDirty: true })- }- className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"- value={field.value.toString()}- aria-labelledby="execute-code-label"- />- )}- />- <label- id="execute-code-label"- htmlFor="execute-code-checkbox"- className="form-check-label text-token-text-primary cursor-pointer text-sm"- >- {localize('com_ui_run_code')}- </label>- <div className="ml-2 flex gap-2">- <HoverCardTrigger asChild>- <button- type="button"- className="inline-flex items-center"- aria-label={localize('com_ui_run_code')}- >- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </button>- </HoverCardTrigger>- </div>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">{localize('com_agents_run_code_info')}</p>- </div>- </HoverCardContent>- </HoverCardPortal>- </div>- </HoverCard>- );-}diff --git a/client/src/components/SidePanel/Agents/Code/Files.tsx b/client/src/components/SidePanel/Agents/Code/Files.tsxindex 8be03a60c8..7c86fc4d37 100644--- a/client/src/components/SidePanel/Agents/Code/Files.tsx+++ b/client/src/components/SidePanel/Agents/Code/Files.tsx@@ -1,10 +1,10 @@import { memo, useMemo, useRef, useState } from 'react';import { useFormContext } from 'react-hook-form';-import { AttachmentIcon } from '@librechat/client';import { EToolResources, EModelEndpoint, AgentCapabilities } from 'librechat-data-provider';import type { ExtendedFile, AgentForm } from '~/common';import { useFileHandlingNoChatContext } from '~/hooks/Files/useFileHandling';import { useAgentFileConfig, useLocalize, useLazyEffect } from '~/hooks';+import DropzoneContent, { dropzoneClassName } from '../UploadDropzone';import FileRow from '~/components/Chat/Input/Files/FileRow';import { isEphemeralAgent } from '~/common';@@ -18,7 +18,7 @@ function Files({files?: [string, ExtendedFile][];}) {const localize = useLocalize();- const { watch } = useFormContext<AgentForm>();+ const { setValue } = useFormContext<AgentForm>();const fileInputRef = useRef<HTMLInputElement>(null);const [files, setFiles] = useState<Map<string, ExtendedFile>>(new Map());const fileHandlingState = useMemo(() => ({ files, setFiles, conversation: null }), [files]);@@ -44,8 +44,18 @@ function Files({750,);- const codeChecked = watch(AgentCapabilities.execute_code);const isUploadDisabled = endpointFileConfig?.disabled ?? false;+ const uploadDisabled = isEphemeralAgent(agent_id);++ const enableExecuteCode = () =>+ setValue(AgentCapabilities.execute_code, true, { shouldDirty: true });++ const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {+ if (event.target.files && event.target.files.length > 0) {+ enableExecuteCode();+ }+ handleFileChange(event);+ };if (isUploadDisabled) {return null;@@ -76,24 +86,24 @@ function Files({<div><buttontype="button"- disabled={isEphemeralAgent(agent_id) || codeChecked === false}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg text-sm font-medium"+ disabled={uploadDisabled}+ className={dropzoneClassName}onClick={handleButtonClick}>- <div className="flex w-full items-center justify-center gap-1">- <input- multiple={true}- type="file"- style={{ display: 'none' }}- tabIndex={-1}- ref={fileInputRef}- disabled={isEphemeralAgent(agent_id) || codeChecked === false}- onChange={handleFileChange}- />- <AttachmentIcon className="text-token-text-primary h-4 w-4" />- {localize('com_ui_upload_code_environment')}- </div>+ <DropzoneContent+ label={localize('com_ui_upload_code_environment')}+ hint={localize('com_ui_upload_files_hint')}+ /></button>+ <input+ multiple={true}+ type="file"+ style={{ display: 'none' }}+ tabIndex={-1}+ ref={fileInputRef}+ disabled={uploadDisabled}+ onChange={handleFileUpload}+ /></div></div></div>diff --git a/client/src/components/SidePanel/Agents/Code/Form.tsx b/client/src/components/SidePanel/Agents/Code/Form.tsxdeleted file mode 100644index 2c1615c94f..0000000000--- a/client/src/components/SidePanel/Agents/Code/Form.tsx+++ /dev/null@@ -1,28 +0,0 @@-import type { ExtendedFile } from '~/common';-import { useLocalize } from '~/hooks';-import Action from './Action';-import Files from './Files';--export default function CodeForm({- agent_id,- files,-}: {- agent_id: string;- files?: [string, ExtendedFile][];-}) {- const localize = useLocalize();-- return (- <div className="w-full">- <div className="mb-1.5 flex items-center gap-2">- <span className="text-token-text-primary block text-sm font-medium">- {localize('com_ui_run_code')}- </span>- </div>- <div className="flex flex-col items-start gap-2">- <Action />- <Files agent_id={agent_id} files={files} />- </div>- </div>- );-}diff --git a/client/src/components/SidePanel/Agents/FileContext.tsx b/client/src/components/SidePanel/Agents/FileContext.tsxindex b216ab3404..83cf7df88f 100644--- a/client/src/components/SidePanel/Agents/FileContext.tsx+++ b/client/src/components/SidePanel/Agents/FileContext.tsx@@ -1,17 +1,8 @@import { memo, useMemo, useRef, useState } from 'react';-import { Folder } from 'lucide-react';import * as Ariakit from '@ariakit/react';+import { Folder, Plus, Info } from 'lucide-react';import { EModelEndpoint, EToolResources } from 'librechat-data-provider';-import {- HoverCard,- DropdownPopup,- AttachmentIcon,- CircleHelpIcon,- SharePointIcon,- HoverCardPortal,- HoverCardContent,- HoverCardTrigger,-} from '@librechat/client';+import { DropdownPopup, SharePointIcon, TooltipAnchor } from '@librechat/client';import type { ExtendedFile } from '~/common';import { useSharePointFileHandlingNoChatContext } from '~/hooks/Files/useSharePointFileHandling';import { useFileHandlingNoChatContext } from '~/hooks/Files/useFileHandling';@@ -19,14 +10,23 @@ import { useAgentFileConfig, useLocalize, useLazyEffect } from '~/hooks';import { SharePointPickerDialog } from '~/components/SharePoint';import FileRow from '~/components/Chat/Input/Files/FileRow';import { useGetStartupConfig } from '~/data-provider';-import { ESide, isEphemeralAgent } from '~/common';+import { isEphemeralAgent } from '~/common';+import { cn } from '~/utils';++const addButtonClassName = cn(+ 'inline-flex h-7 shrink-0 items-center gap-1.5 rounded-lg px-2 text-xs font-medium text-text-secondary transition-colors',+ 'hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',+ 'disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent disabled:hover:text-text-secondary',+);function FileContext({agent_id,files: _files,+ showHeader = true,}: {agent_id: string;files?: [string, ExtendedFile][];+ showHeader?: boolean;}) {const localize = useLocalize();const fileInputRef = useRef<HTMLInputElement>(null);@@ -51,7 +51,7 @@ function FileContext({const { handleSharePointFiles, isProcessing, downloadProgress } =useSharePointFileHandlingNoChatContext({- additionalMetadata: { agent_id, tool_resource: EToolResources.file_search },+ additionalMetadata: { agent_id, tool_resource: EToolResources.context },endpointOverride,endpointTypeOverride: endpointType,fileSetter: setFiles,@@ -68,6 +68,7 @@ function FileContext({750,);const isUploadDisabled = endpointFileConfig?.disabled ?? false;+ const disabledUploadButton = isEphemeralAgent(agent_id);const handleSharePointFilesSelected = async (sharePointFiles: any[]) => {try {await handleSharePointFiles(sharePointFiles);@@ -99,39 +100,76 @@ function FileContext({icon: <SharePointIcon className="icon-md" />,},];- const menuTrigger = (- <Ariakit.MenuButton className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg text-sm font-medium">- <div className="flex w-full items-center justify-center gap-1">- <AttachmentIcon className="text-token-text-primary h-4 w-4" />- {localize('com_ui_upload_file_context')}- </div>- </Ariakit.MenuButton>++ const addLabel = localize('com_ui_upload_file_context');+ const fileCount = files.size;++ const addControl = sharePointEnabled ? (+ <DropdownPopup+ gutter={2}+ menuId="file-context-upload-menu"+ isOpen={isPopoverActive}+ setIsOpen={setIsPopoverActive}+ trigger={+ <Ariakit.MenuButton+ disabled={disabledUploadButton}+ aria-label={addLabel}+ className={addButtonClassName}+ >+ <Plus className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden="true" />+ {localize('com_ui_add')}+ </Ariakit.MenuButton>+ }+ items={dropdownItems}+ modal={true}+ unmountOnHide={true}+ />+ ) : (+ <button+ type="button"+ disabled={disabledUploadButton}+ aria-label={addLabel}+ className={addButtonClassName}+ onClick={handleLocalFileClick}+ >+ <Plus className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden="true" />+ {localize('com_ui_add')}+ </button>);+return (- <div className="w-full">- <HoverCard openDelay={50}>- <div className="mb-2 flex items-center gap-2">- <HoverCardTrigger asChild>- <span className="flex items-center gap-2">- <label className="text-token-text-primary block text-sm font-medium">- {localize('com_agents_file_context_label')}- </label>- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ {showHeader ? (+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="truncate text-[11px] font-medium uppercase tracking-wide text-text-secondary">+ {localize('com_agents_file_context_label')}</span>- </HoverCardTrigger>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">- {localize('com_agents_file_context_description')}- </p>- </div>- </HoverCardContent>- </HoverCardPortal>- </div>- </HoverCard>- <div className="flex flex-col gap-3">- {/* File Context Files */}+ <TooltipAnchor+ description={localize('com_agents_file_context_description')}+ side="top"+ render={+ <button+ type="button"+ aria-label={localize('com_agents_file_context_description')}+ className="flex size-4 shrink-0 items-center justify-center rounded text-text-tertiary transition-colors hover:text-text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <Info className="size-3.5" aria-hidden="true" />+ </button>+ }+ />+ {fileCount > 0 && (+ <span className="inline-flex h-4 min-w-[16px] items-center justify-center rounded-full bg-surface-tertiary px-1.5 text-[10px] font-medium text-text-secondary">+ {fileCount}+ </span>+ )}+ </div>+ ) : (+ <span />+ )}+ {addControl}+ </div>+ {fileCount > 0 && (<FileRowfiles={files}setFiles={setFiles}@@ -139,51 +177,21 @@ function FileContext({tool_resource={EToolResources.context}Wrapper={({ children }) => <div className="flex flex-wrap gap-2">{children}</div>}/>- <div>- {sharePointEnabled ? (- <>- <DropdownPopup- gutter={2}- menuId="file-search-upload-menu"- isOpen={isPopoverActive}- setIsOpen={setIsPopoverActive}- trigger={menuTrigger}- items={dropdownItems}- modal={true}- unmountOnHide={true}- />- </>- ) : (- <button- type="button"- disabled={isEphemeralAgent(agent_id)}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg text-sm font-medium"- onClick={handleLocalFileClick}- >- <div className="flex w-full items-center justify-center gap-1">- <AttachmentIcon className="text-token-text-primary h-4 w-4" />-- {localize('com_ui_upload_file_context')}- </div>- </button>- )}- <input- multiple={true}- type="file"- style={{ display: 'none' }}- tabIndex={-1}- ref={fileInputRef}- disabled={isEphemeralAgent(agent_id)}- onChange={handleFileChange}- />- </div>- {/* Disabled Message */}- {agent_id ? null : (- <div className="text-xs text-text-secondary">- {localize('com_agents_file_context_disabled')}- </div>- )}- </div>+ )}+ {!agent_id && (+ <p className="text-[11px] leading-snug text-text-secondary">+ {localize('com_agents_file_context_disabled')}+ </p>+ )}+ <input+ multiple={true}+ type="file"+ style={{ display: 'none' }}+ tabIndex={-1}+ ref={fileInputRef}+ disabled={disabledUploadButton}+ onChange={handleFileChange}+ /><SharePointPickerDialogisOpen={isSharePointDialogOpen}onOpenChange={setIsSharePointDialogOpen}diff --git a/client/src/components/SidePanel/Agents/FileSearch.tsx b/client/src/components/SidePanel/Agents/FileSearch.tsxindex d4917c492d..f967ac9e2f 100644--- a/client/src/components/SidePanel/Agents/FileSearch.tsx+++ b/client/src/components/SidePanel/Agents/FileSearch.tsx@@ -2,27 +2,30 @@ import { memo, useMemo, useRef, useState } from 'react';import { Folder } from 'lucide-react';import * as Ariakit from '@ariakit/react';import { useFormContext } from 'react-hook-form';-import { SharePointIcon, AttachmentIcon, DropdownPopup } from '@librechat/client';+import { SharePointIcon, DropdownPopup } from '@librechat/client';import { EModelEndpoint, EToolResources, AgentCapabilities } from 'librechat-data-provider';import type { ExtendedFile, AgentForm } from '~/common';import { useSharePointFileHandlingNoChatContext } from '~/hooks/Files/useSharePointFileHandling';import { useFileHandlingNoChatContext } from '~/hooks/Files/useFileHandling';import { useAgentFileConfig, useLocalize, useLazyEffect } from '~/hooks';+import DropzoneContent, { dropzoneClassName } from './UploadDropzone';import { SharePointPickerDialog } from '~/components/SharePoint';import FileRow from '~/components/Chat/Input/Files/FileRow';import { useGetStartupConfig } from '~/data-provider';-import FileSearchCheckbox from './FileSearchCheckbox';+import SectionHeader from './SectionHeader';import { isEphemeralAgent } from '~/common';function FileSearch({agent_id,files: _files,+ showHeader = true,}: {agent_id: string;files?: [string, ExtendedFile][];+ showHeader?: boolean;}) {const localize = useLocalize();- const { watch } = useFormContext<AgentForm>();+ const { setValue } = useFormContext<AgentForm>();const fileInputRef = useRef<HTMLInputElement>(null);const [files, setFiles] = useState<Map<string, ExtendedFile>>(new Map());const fileHandlingState = useMemo(() => ({ files, setFiles, conversation: null }), [files]);@@ -65,15 +68,26 @@ function FileSearch({750,);- const fileSearchChecked = watch(AgentCapabilities.file_search);const isUploadDisabled = endpointFileConfig?.disabled ?? false;-const sharePointEnabled = startupConfig?.sharePointFilePickerEnabled;- const disabledUploadButton = isEphemeralAgent(agent_id) || fileSearchChecked === false;+ const disabledUploadButton = isEphemeralAgent(agent_id);++ const enableFileSearch = () =>+ setValue(AgentCapabilities.file_search, true, { shouldDirty: true });++ const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {+ if (event.target.files && event.target.files.length > 0) {+ enableFileSearch();+ }+ handleFileChange(event);+ };const handleSharePointFilesSelected = async (sharePointFiles: any[]) => {try {await handleSharePointFiles(sharePointFiles);+ if (sharePointFiles.length > 0) {+ enableFileSearch();+ }setIsSharePointDialogOpen(false);} catch (error) {console.error('SharePoint file processing error:', error);@@ -83,15 +97,8 @@ function FileSearch({return null;}- const handleButtonClick = () => {- // necessary to reset the input- if (fileInputRef.current) {- fileInputRef.current.value = '';- }- fileInputRef.current?.click();- };-const handleLocalFileClick = () => {+ // necessary to reset the inputif (fileInputRef.current) {fileInputRef.current.value = '';}@@ -111,28 +118,23 @@ function FileSearch({},];+ const dropzoneLabel = localize('com_ui_upload_file_search');+ const dropzoneHint = localize('com_ui_upload_files_hint');+const menuTrigger = (- <Ariakit.MenuButton- disabled={disabledUploadButton}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg text-sm font-medium"- >- <div className="flex w-full items-center justify-center gap-1">- <AttachmentIcon className="text-token-text-primary h-4 w-4" />- {localize('com_ui_upload_file_search')}- </div>+ <Ariakit.MenuButton disabled={disabledUploadButton} className={dropzoneClassName}>+ <DropzoneContent label={dropzoneLabel} hint={dropzoneHint} /></Ariakit.MenuButton>);return (<div className="w-full">- <div className="mb-1.5 flex items-center gap-2">- <span>- <label className="text-token-text-primary block text-sm font-medium">- {localize('com_assistants_file_search')}- </label>- </span>- </div>- <FileSearchCheckbox />+ {showHeader && (+ <SectionHeader+ title={localize('com_assistants_file_search')}+ info={localize('com_agents_file_search_info')}+ />+ )}<div className="flex flex-col gap-3">{/* File Search (RAG API) Files */}<FileRow@@ -158,13 +160,10 @@ function FileSearch({<buttontype="button"disabled={disabledUploadButton}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg text-sm font-medium"- onClick={handleButtonClick}+ className={dropzoneClassName}+ onClick={handleLocalFileClick}>- <div className="flex w-full items-center justify-center gap-1">- <AttachmentIcon className="text-token-text-primary h-4 w-4" />- {localize('com_ui_upload_file_search')}- </div>+ <DropzoneContent label={dropzoneLabel} hint={dropzoneHint} /></button>)}<input@@ -174,7 +173,7 @@ function FileSearch({tabIndex={-1}ref={fileInputRef}disabled={disabledUploadButton}- onChange={handleFileChange}+ onChange={handleFileUpload}/></div>{/* Disabled Message */}diff --git a/client/src/components/SidePanel/Agents/FileSearchCheckbox.tsx b/client/src/components/SidePanel/Agents/FileSearchCheckbox.tsxdeleted file mode 100644index e7c1d1171e..0000000000--- a/client/src/components/SidePanel/Agents/FileSearchCheckbox.tsx+++ /dev/null@@ -1,71 +0,0 @@-import { memo } from 'react';-import { AgentCapabilities } from 'librechat-data-provider';-import { useFormContext, Controller } from 'react-hook-form';-import {- Checkbox,- HoverCard,- HoverCardContent,- HoverCardPortal,- HoverCardTrigger,- CircleHelpIcon,-} from '@librechat/client';-import type { AgentForm } from '~/common';-import { useLocalize } from '~/hooks';-import { ESide } from '~/common';--function FileSearchCheckbox() {- const localize = useLocalize();- const methods = useFormContext<AgentForm>();- const { control } = methods;-- return (- <>- <HoverCard openDelay={50}>- <div className="my-2 flex items-center">- <Controller- name={AgentCapabilities.file_search}- control={control}- render={({ field }) => (- <Checkbox- {...field}- id="file-search-checkbox"- checked={field.value}- onCheckedChange={field.onChange}- className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"- value={field.value.toString()}- aria-labelledby="file-search-label"- />- )}- />- <label- id="file-search-label"- htmlFor="file-search-checkbox"- className="form-check-label text-token-text-primary cursor-pointer text-sm"- >- {localize('com_agents_enable_file_search')}- </label>- <HoverCardTrigger asChild className="ml-2">- <button- type="button"- className="inline-flex items-center"- aria-label={localize('com_agents_file_search_info')}- >- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </button>- </HoverCardTrigger>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">- {localize('com_agents_file_search_info')}- </p>- </div>- </HoverCardContent>- </HoverCardPortal>- </div>- </HoverCard>- </>- );-}--export default memo(FileSearchCheckbox);diff --git a/client/src/components/SidePanel/Agents/Images.tsx b/client/src/components/SidePanel/Agents/Images.tsxindex 23ac59e279..6318993419 100644--- a/client/src/components/SidePanel/Agents/Images.tsx+++ b/client/src/components/SidePanel/Agents/Images.tsx@@ -32,26 +32,26 @@ export const AgentAvatarRender = ({ url }: { url?: string }) => {setIsLoaded(false);}, [url]);+ if (!url) {+ return <div className="h-full w-full rounded-full" aria-hidden="true" />;+ }+return (- <div>- <div className="relative h-20 w-20 overflow-hidden rounded-full">- <img- src={url}- className="bg-token-surface-secondary dark:bg-token-surface-tertiary h-full w-full rounded-full object-cover"- alt="Agent avatar"- width="80"- height="80"- loading="lazy"- key={url || 'default-key'}- onLoad={() => setIsLoaded(true)}- onError={() => setIsLoaded(false)}- style={{- opacity: isLoaded ? 1 : 0,- transition: 'opacity 0.2s ease-in-out',- }}- />- {!isLoaded && <Skeleton className="absolute inset-0 rounded-full" aria-hidden="true" />}- </div>+ <div className="relative h-full w-full overflow-hidden rounded-full">+ <img+ src={url}+ className="bg-token-surface-secondary dark:bg-token-surface-tertiary h-full w-full rounded-full object-cover"+ alt="Agent avatar"+ loading="lazy"+ key={url}+ onLoad={() => setIsLoaded(true)}+ onError={() => setIsLoaded(false)}+ style={{+ opacity: isLoaded ? 1 : 0,+ transition: 'opacity 0.2s ease-in-out',+ }}+ />+ {!isLoaded && <Skeleton className="absolute inset-0 rounded-full" aria-hidden="true" />}</div>);};diff --git a/client/src/components/SidePanel/Agents/Instructions.tsx b/client/src/components/SidePanel/Agents/Instructions.tsxindex 6dff669376..7b91d64478 100644--- a/client/src/components/SidePanel/Agents/Instructions.tsx+++ b/client/src/components/SidePanel/Agents/Instructions.tsx@@ -1,19 +1,24 @@-import React, { useState, useId } from 'react';-import { PlusCircle } from 'lucide-react';+import { useState, useId } from 'react';import * as Menu from '@ariakit/react/menu';-import { DropdownPopup } from '@librechat/client';+import { PlusCircle, Maximize2 } from 'lucide-react';import { specialVariables } from 'librechat-data-provider';import { Controller, useFormContext } from 'react-hook-form';+import {+ Button,+ DropdownPopup,+ OGDialog,+ OGDialogClose,+ OGDialogContent,+ OGDialogHeader,+ OGDialogTitle,+} from '@librechat/client';import type { TSpecialVarLabel } from 'librechat-data-provider';import type { AgentForm } from '~/common';-import { cn, defaultTextProps, removeFocusOutlines } from '~/utils';import { useLocalize } from '~/hooks';+import { cn } from '~/utils';-const inputClass = cn(- defaultTextProps,- 'flex w-full px-3 py-2 border-border-light bg-surface-secondary focus-visible:ring-2 focus-visible:ring-ring-primary',- removeFocusOutlines,-);+const textareaClass =+ 'lc-field flex w-full rounded-lg border border-border-light bg-surface-secondary px-3 py-2 text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:border-border-medium focus-visible:ring-2 focus-visible:ring-ring-primary disabled:cursor-not-allowed disabled:opacity-50';interface VariableOption {label: TSpecialVarLabel;@@ -27,11 +32,14 @@ const variableOptions: VariableOption[] = Object.keys(specialVariables).map((keyexport default function Instructions() {const menuId = useId();+ const dialogMenuId = useId();const localize = useLocalize();const methods = useFormContext<AgentForm>();const { control, setValue, getValues } = methods;const [isMenuOpen, setIsMenuOpen] = useState(false);+ const [isDialogMenuOpen, setIsDialogMenuOpen] = useState(false);+ const [isDialogOpen, setIsDialogOpen] = useState(false);const handleAddVariable = (label: TSpecialVarLabel, value: string) => {const currentInstructions = getValues('instructions') || '';@@ -39,18 +47,24 @@ export default function Instructions() {const prefix = localize(label);setValue('instructions', currentInstructions + spacer + prefix + ': ' + value);setIsMenuOpen(false);+ setIsDialogMenuOpen(false);};+ const variableItems = variableOptions.map((option) => ({+ label: localize(option.label) || option.label,+ onClick: () => handleAddVariable(option.label, option.value),+ }));+return (- <div className="mb-4">- <div className="mb-2 flex items-center">+ <div className="mb-3 flex flex-col">+ <div className="mb-1 flex items-center justify-between"><label- className="text-token-text-primary flex-grow text-sm font-medium"+ className="block text-[11px] font-medium uppercase tracking-wide text-text-secondary"htmlFor="instructions">{localize('com_ui_instructions')}</label>- <div className="ml-auto" title="Add variables to instructions">+ <div className="flex items-center gap-0.5"><DropdownPopupportal={true}mountByState={true}@@ -61,20 +75,26 @@ export default function Instructions() {trigger={<Menu.MenuButtonid="variables-menu-button"- aria-label="Add variable to instructions"- className="flex h-7 items-center gap-1 rounded-md border border-border-medium bg-surface-secondary px-2 py-0 text-sm text-text-primary transition-colors duration-200 hover:bg-surface-tertiary"+ aria-label={localize('com_ui_variables')}+ title={localize('com_ui_variables')}+ className="inline-flex h-7 w-7 items-center justify-center rounded-lg text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary">- <PlusCircle className="mr-1 h-3 w-3 text-text-secondary" aria-hidden={true} />- {localize('com_ui_variables')}+ <PlusCircle className="h-4 w-4" strokeWidth={1.75} aria-hidden={true} /></Menu.MenuButton>}- items={variableOptions.map((option) => ({- label: localize(option.label) || option.label,- onClick: () => handleAddVariable(option.label, option.value),- }))}+ items={variableItems}menuId={menuId}- className="z-30"+ className="pointer-events-auto z-30"/>+ <button+ type="button"+ onClick={() => setIsDialogOpen(true)}+ aria-label={localize('com_ui_expand_editor')}+ title={localize('com_ui_expand_editor')}+ className="inline-flex h-7 w-7 items-center justify-center rounded-lg text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <Maximize2 className="h-4 w-4" strokeWidth={1.75} aria-hidden={true} />+ </button></div></div><Controller@@ -85,17 +105,17 @@ export default function Instructions() {<textarea{...field}value={field.value ?? ''}- className={cn(inputClass, 'min-h-[100px] resize-y')}+ className={cn(textareaClass, 'min-h-[88px] resize-y text-sm')}id="instructions"placeholder={localize('com_agents_instructions_placeholder')}rows={3}- aria-label="Agent instructions"+ aria-label={localize('com_ui_instructions')}aria-required="true"aria-invalid={error ? 'true' : 'false'}/>{error && (<span- className="text-sm text-red-500 transition duration-300 ease-in-out"+ className="mt-1 text-xs text-red-500 transition duration-300 ease-in-out"role="alert">{localize('com_ui_field_required')}@@ -104,6 +124,62 @@ export default function Instructions() {</>)}/>++ <OGDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>+ <OGDialogContent+ className="flex h-[85vh] max-h-[85vh] w-11/12 max-w-6xl flex-col gap-4 p-6"+ showCloseButton={false}+ >+ <OGDialogHeader className="mb-2 pr-14">+ <OGDialogTitle className="text-left text-2xl font-semibold">+ {localize('com_ui_instructions')}+ </OGDialogTitle>+ </OGDialogHeader>+ <Controller+ name="instructions"+ control={control}+ render={({ field }) => (+ <textarea+ {...field}+ value={field.value ?? ''}+ className={cn(+ textareaClass,+ 'min-h-0 flex-1 resize-none text-base leading-relaxed',+ )}+ placeholder={localize('com_agents_instructions_placeholder')}+ aria-label={localize('com_ui_instructions')}+ />+ )}+ />+ <div className="flex items-center justify-between">+ <DropdownPopup+ portal={true}+ mountByState={true}+ unmountOnHide={true}+ preserveTabOrder={true}+ isOpen={isDialogMenuOpen}+ setIsOpen={setIsDialogMenuOpen}+ trigger={+ <Menu.MenuButton+ id="variables-menu-button-dialog"+ render={+ <Button variant="outline" className="gap-1.5">+ <PlusCircle className="h-4 w-4" strokeWidth={1.75} aria-hidden={true} />+ {localize('com_ui_variables')}+ </Button>+ }+ />+ }+ items={variableItems}+ menuId={dialogMenuId}+ className="pointer-events-auto z-[200]"+ />+ <OGDialogClose asChild>+ <Button>{localize('com_ui_done')}</Button>+ </OGDialogClose>+ </div>+ </OGDialogContent>+ </OGDialog></div>);}diff --git a/client/src/components/SidePanel/Agents/MCPTool.tsx b/client/src/components/SidePanel/Agents/MCPTool.tsxdeleted file mode 100644index 127fe55e60..0000000000--- a/client/src/components/SidePanel/Agents/MCPTool.tsx+++ /dev/null@@ -1,364 +0,0 @@-import React, { useState } from 'react';-import { useFormContext } from 'react-hook-form';-import { Constants } from 'librechat-data-provider';-import { ChevronDown, Clock, Code2 } from 'lucide-react';-import * as AccordionPrimitive from '@radix-ui/react-accordion';-import {- Label,- Checkbox,- OGDialog,- Accordion,- TrashIcon,- TooltipAnchor,- AccordionItem,- OGDialogTrigger,- AccordionContent,- OGDialogTemplate,-} from '@librechat/client';-import type { AgentForm, MCPServerInfo } from '~/common';-import {- useAgentCapabilities,- useMCPServerManager,- useGetAgentsConfig,- useMCPToolOptions,- useRemoveMCPTool,- useLocalize,-} from '~/hooks';-import MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';-import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';-import MCPToolItem from './MCPToolItem';-import { cn } from '~/utils';--export default function MCPTool({ serverInfo }: { serverInfo?: MCPServerInfo }) {- const localize = useLocalize();- const { removeTool } = useRemoveMCPTool();- const { getValues, setValue } = useFormContext<AgentForm>();- const { getServerStatusIconProps, getConfigDialogProps } = useMCPServerManager();- const { agentsConfig } = useGetAgentsConfig();- const { deferredToolsEnabled, programmaticToolsEnabled } = useAgentCapabilities(- agentsConfig?.capabilities,- );-- const {- isToolDeferred,- isToolProgrammatic,- toggleToolDefer,- toggleToolProgrammatic,- areAllToolsDeferred,- areAllToolsProgrammatic,- toggleDeferAll,- toggleProgrammaticAll,- } = useMCPToolOptions();-- const [isFocused, setIsFocused] = useState(false);- const [isHovering, setIsHovering] = useState(false);- const [accordionValue, setAccordionValue] = useState<string>('');-- if (!serverInfo) {- return null;- }-- const currentServerName = serverInfo.serverName;- const tools = serverInfo.tools || [];-- const getSelectedTools = () => {- const formTools = getValues('tools') || [];- return tools.filter((t) => formTools.includes(t.tool_id)).map((t) => t.tool_id);- };-- const updateFormTools = (newSelectedTools: string[]) => {- const currentTools = getValues('tools') || [];- const otherTools = currentTools.filter((t: string) => !tools.some((st) => st.tool_id === t));- setValue('tools', [...otherTools, ...newSelectedTools]);- };-- const toggleToolSelect = (toolId: string) => {- const selectedTools = getSelectedTools();- const newSelectedTools = selectedTools.includes(toolId)- ? selectedTools.filter((t) => t !== toolId)- : [...selectedTools, toolId];- updateFormTools(newSelectedTools);- };-- const selectedTools = getSelectedTools();- const isExpanded = accordionValue === currentServerName;- const allDeferred = areAllToolsDeferred(tools);- const allProgrammatic = areAllToolsProgrammatic(tools);-- const statusIconProps = getServerStatusIconProps(currentServerName);- const configDialogProps = getConfigDialogProps();-- const statusIcon = statusIconProps && (- <div- onClick={(e) => e.stopPropagation()}- className="cursor-pointer rounded p-0.5 hover:bg-surface-secondary"- >- <MCPServerStatusIcon {...statusIconProps} />- </div>- );-- return (- <OGDialog>- <Accordion type="single" value={accordionValue} onValueChange={setAccordionValue} collapsible>- <AccordionItem value={currentServerName} className="group relative w-full border-none">- <div- className="relative flex w-full items-center gap-1 rounded-lg p-1 text-sm focus-within:bg-surface-primary-alt hover:bg-surface-primary-alt"- onMouseEnter={() => setIsHovering(true)}- onMouseLeave={() => setIsHovering(false)}- onFocus={() => setIsFocused(true)}- onBlur={(e) => {- if (!e.currentTarget.contains(e.relatedTarget)) {- setIsFocused(false);- }- }}- >- <AccordionPrimitive.Header asChild>- <div- className="flex grow cursor-pointer select-none items-center gap-1 rounded bg-transparent p-0 text-left transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"- onClick={() => setAccordionValue((prev) => (prev ? '' : currentServerName))}- >- {statusIcon && <div className="flex items-center">{statusIcon}</div>}-- {serverInfo.metadata.icon && (- <div className="flex h-8 w-8 items-center justify-center overflow-hidden rounded-full">- <div- className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full bg-center bg-no-repeat dark:bg-white/20"- style={{- backgroundImage: `url(${serverInfo.metadata.icon})`,- backgroundSize: 'cover',- }}- />- </div>- )}- <div- className="grow px-2 py-1.5"- style={{ textOverflow: 'ellipsis', wordBreak: 'break-all', overflow: 'hidden' }}- >- {currentServerName}- </div>- <div className="flex items-center">- <div className="relative flex items-center">- <div- className={cn(- 'absolute right-0 rounded-md bg-surface-primary-alt py-0.5 pl-1 transition-all duration-300',- isHovering || isFocused- ? 'translate-x-0 opacity-100'- : 'translate-x-8 opacity-0',- )}- >- <div className="flex items-center gap-2">- <div- data-checkbox-container- onClick={(e) => e.stopPropagation()}- className="mt-1"- >- <Checkbox- id={`select-all-${currentServerName}`}- checked={- selectedTools.length === tools.length && selectedTools.length > 0- }- onCheckedChange={(checked) => {- const newSelectedTools = checked- ? tools.map((t) => t.tool_id)- : [- `${Constants.mcp_server}${Constants.mcp_delimiter}${currentServerName}`,- ];- updateFormTools(newSelectedTools);- }}- className={cn(- 'h-4 w-4 rounded border border-border-medium transition-all duration-200 hover:border-border-heavy',- isExpanded ? 'visible' : 'pointer-events-none invisible',- )}- onClick={(e) => e.stopPropagation()}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- e.stopPropagation();- const checkbox = e.currentTarget as HTMLButtonElement;- checkbox.click();- }- }}- tabIndex={isExpanded ? 0 : -1}- aria-label={- selectedTools.length === tools.length && selectedTools.length > 0- ? localize('com_ui_deselect_all')- : localize('com_ui_select_all')- }- />- </div>-- {deferredToolsEnabled && (- <TooltipAnchor- description={- allDeferred- ? localize('com_ui_mcp_undefer_all')- : localize('com_ui_mcp_defer_all')- }- side="top"- role="button"- tabIndex={isExpanded ? 0 : -1}- aria-label={- allDeferred- ? localize('com_ui_mcp_undefer_all')- : localize('com_ui_mcp_defer_all')- }- aria-pressed={allDeferred}- className={cn(- 'flex h-7 w-7 items-center justify-center rounded transition-colors duration-200',- 'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1',- isExpanded ? 'visible' : 'pointer-events-none invisible',- allDeferred- ? 'bg-amber-500/20 text-amber-500 hover:bg-amber-500/30'- : 'text-text-tertiary hover:bg-surface-hover hover:text-text-primary',- )}- onClick={(e) => {- e.stopPropagation();- toggleDeferAll(tools);- }}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- e.stopPropagation();- toggleDeferAll(tools);- }- }}- >- <Clock className={cn('h-4 w-4', allDeferred && 'fill-amber-500/30')} />- </TooltipAnchor>- )}-- {programmaticToolsEnabled && (- <TooltipAnchor- description={- allProgrammatic- ? localize('com_ui_mcp_unprogrammatic_all')- : localize('com_ui_mcp_programmatic_all')- }- side="top"- role="button"- tabIndex={isExpanded ? 0 : -1}- aria-label={- allProgrammatic- ? localize('com_ui_mcp_unprogrammatic_all')- : localize('com_ui_mcp_programmatic_all')- }- aria-pressed={allProgrammatic}- className={cn(- 'flex h-7 w-7 items-center justify-center rounded transition-colors duration-200',- 'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1',- isExpanded ? 'visible' : 'pointer-events-none invisible',- allProgrammatic- ? 'bg-violet-500/20 text-violet-500 hover:bg-violet-500/30'- : 'text-text-tertiary hover:bg-surface-hover hover:text-text-primary',- )}- onClick={(e) => {- e.stopPropagation();- toggleProgrammaticAll(tools);- }}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- e.stopPropagation();- toggleProgrammaticAll(tools);- }- }}- >- <Code2- className={cn('h-4 w-4', allProgrammatic && 'fill-violet-500/30')}- />- </TooltipAnchor>- )}-- <div className="flex items-center gap-1">- <AccordionPrimitive.Trigger asChild>- <button- type="button"- onClick={(e) => e.stopPropagation()}- className={cn(- 'flex h-7 w-7 items-center justify-center rounded transition-colors duration-200 hover:bg-surface-active-alt focus:translate-x-0 focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1',- isExpanded && 'bg-surface-active-alt',- )}- aria-label={- isExpanded- ? localize('com_ui_tool_list_collapse', {- serverName: currentServerName,- })- : localize('com_ui_tool_list_expand', {- serverName: currentServerName,- })- }- aria-expanded={isExpanded}- tabIndex={0}- onFocus={() => setIsFocused(true)}- >- <ChevronDown- className={cn(- 'h-4 w-4 transition-transform duration-200',- isExpanded && 'rotate-180',- )}- />- </button>- </AccordionPrimitive.Trigger>-- <OGDialogTrigger asChild>- <button- type="button"- className="flex h-7 w-7 items-center justify-center rounded transition-colors duration-200 hover:bg-surface-active-alt focus:translate-x-0 focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1"- onClick={(e) => e.stopPropagation()}- aria-label={`Delete ${currentServerName}`}- tabIndex={0}- onFocus={() => setIsFocused(true)}- >- <TrashIcon className="h-4 w-4" />- </button>- </OGDialogTrigger>- </div>- </div>- </div>- </div>- </div>- </div>- </AccordionPrimitive.Header>- </div>-- <AccordionContent className="relative ml-1 pt-1 before:absolute before:bottom-2 before:left-0 before:top-0 before:w-0.5 before:bg-border-medium">- <div className="space-y-1">- {tools.map((tool) => (- <MCPToolItem- key={tool.tool_id}- tool={tool}- isSelected={selectedTools.includes(tool.tool_id)}- isDeferred={deferredToolsEnabled && isToolDeferred(tool.tool_id)}- isProgrammatic={programmaticToolsEnabled && isToolProgrammatic(tool.tool_id)}- deferredToolsEnabled={deferredToolsEnabled}- programmaticToolsEnabled={programmaticToolsEnabled}- onToggleSelect={() => toggleToolSelect(tool.tool_id)}- onToggleDefer={() => toggleToolDefer(tool.tool_id)}- onToggleProgrammatic={() => toggleToolProgrammatic(tool.tool_id)}- />- ))}- </div>- </AccordionContent>- </AccordionItem>- </Accordion>- <OGDialogTemplate- showCloseButton={false}- title={localize('com_ui_delete_tool')}- mainClassName="px-0"- className="max-w-[450px]"- main={- <Label className="text-left text-sm font-medium">- {localize('com_ui_delete_tool_confirm')}- </Label>- }- selection={{- selectHandler: () => removeTool(currentServerName),- selectClasses:- 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',- selectText: localize('com_ui_delete'),- }}- />- {configDialogProps && <MCPConfigDialog {...configDialogProps} />}- </OGDialog>- );-}diff --git a/client/src/components/SidePanel/Agents/MCPToolItem.tsx b/client/src/components/SidePanel/Agents/MCPToolItem.tsxindex e2fbd79802..d3a4930839 100644--- a/client/src/components/SidePanel/Agents/MCPToolItem.tsx+++ b/client/src/components/SidePanel/Agents/MCPToolItem.tsx@@ -1,14 +1,6 @@-import React from 'react';-import { Clock, MoreHorizontal, Code2 } from 'lucide-react';-import {- Checkbox,- DropdownMenu,- DropdownMenuLabel,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuSeparator,- DropdownMenuCheckboxItem,-} from '@librechat/client';+import { useState } from 'react';+import { TooltipAnchor } from '@librechat/client';+import { Check, Clock, Code2, Info } from 'lucide-react';import type { AgentToolType } from 'librechat-data-provider';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -25,18 +17,8 @@ interface MCPToolItemProps {onToggleProgrammatic: () => void;}-function getToolItemStyle(isDeferred: boolean, isProgrammatic: boolean): string {- if (isDeferred && isProgrammatic) {- return 'border-purple-500/50 bg-purple-500/5 hover:bg-purple-500/10';- }- if (isDeferred) {- return 'border-amber-500/50 bg-amber-500/5 hover:bg-amber-500/10';- }- if (isProgrammatic) {- return 'border-violet-500/50 bg-violet-500/5 hover:bg-violet-500/10';- }- return 'border-token-border-light hover:bg-token-surface-secondary';-}+const iconButton =+ 'flex size-6 items-center justify-center rounded-md transition-colors hover:bg-surface-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary';export default function MCPToolItem({tool,@@ -50,103 +32,116 @@ export default function MCPToolItem({programmaticToolsEnabled,}: MCPToolItemProps) {const localize = useLocalize();- const hasOptions = isDeferred || isProgrammatic;+ const [expanded, setExpanded] = useState(false);++ const description = tool.metadata.description?.trim();+ const detailsId = `mcp-tool-details-${tool.tool_id}`;return (- <div- className={cn(- 'group/item flex cursor-pointer items-center rounded-lg border p-2',- 'ml-2 mr-1 focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 focus-within:ring-offset-background',- getToolItemStyle(isDeferred, isProgrammatic),- )}- onClick={(e) => e.stopPropagation()}- onKeyDown={(e) => e.stopPropagation()}- >- <Checkbox- id={tool.tool_id}- checked={isSelected}- onCheckedChange={onToggleSelect}- onKeyDown={(e) => {- e.stopPropagation();- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- const checkbox = e.currentTarget as HTMLButtonElement;- checkbox.click();- }- }}- onClick={(e) => e.stopPropagation()}- className="relative mr-2 inline-flex h-4 w-4 shrink-0 cursor-pointer rounded border border-border-medium transition-[border-color] duration-200 hover:border-border-heavy focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:ring-offset-background"- aria-label={tool.metadata.name}- />- <span className="text-token-text-primary min-w-0 flex-1 select-none truncate">- {tool.metadata.name}- </span>- <div className="ml-2 flex shrink-0 items-center gap-1.5">- {isDeferred && <Clock className="h-3.5 w-3.5 text-amber-500" aria-hidden="true" />}- {isProgrammatic && <Code2 className="h-3.5 w-3.5 text-violet-500" aria-hidden="true" />}- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- className={cn(- 'flex h-6 w-6 items-center justify-center rounded transition-all duration-200',- 'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1',- hasOptions- ? 'text-text-secondary hover:bg-surface-hover hover:text-text-primary'- : 'text-text-tertiary opacity-0 hover:bg-surface-hover hover:text-text-primary group-focus-within/item:opacity-100 group-hover/item:opacity-100',- )}- onClick={(e) => e.stopPropagation()}- aria-label={localize('com_ui_mcp_tool_options')}- >- <MoreHorizontal className="h-4 w-4" />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent- align="end"- side="left"- className="w-80"- onClick={(e) => e.stopPropagation()}+ <div className="overflow-hidden rounded-lg">+ <div className="flex items-center gap-1 rounded-lg pr-1 transition-colors hover:bg-surface-secondary">+ <button+ type="button"+ onClick={onToggleSelect}+ aria-pressed={isSelected}+ aria-label={tool.metadata.name}+ className={cn(+ 'flex min-w-0 flex-1 items-center gap-2.5 rounded-lg p-2 text-left',+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',+ )}+ >+ <span+ aria-hidden="true"+ className={cn(+ 'flex size-4 shrink-0 items-center justify-center rounded border border-border-medium transition-colors',+ isSelected && 'bg-primary text-primary-foreground',+ )}>- <DropdownMenuLabel className="text-xs font-normal text-text-primary">- {tool.metadata.description || localize('com_ui_mcp_no_description')}- </DropdownMenuLabel>- <DropdownMenuSeparator />- {deferredToolsEnabled && (- <DropdownMenuCheckboxItem- checked={isDeferred}- onCheckedChange={onToggleDefer}- className="cursor-pointer"- >- <div className="flex items-center gap-2">- <Clock className="h-4 w-4 text-amber-500" />- <div className="flex flex-col">- <span>{localize('com_ui_mcp_defer_loading')}</span>- <span className="text-xs text-text-secondary">- {localize('com_ui_mcp_click_to_defer')}- </span>- </div>- </div>- </DropdownMenuCheckboxItem>+ {isSelected && <Check className="size-4" />}+ </span>+ <span className="min-w-0 flex-1 truncate text-sm text-text-primary">+ {tool.metadata.name}+ </span>+ </button>+ <div className="flex shrink-0 items-center gap-0.5">+ {deferredToolsEnabled && (+ <TooltipAnchor+ description={localize('com_ui_mcp_click_to_defer')}+ side="top"+ render={+ <button+ type="button"+ onClick={onToggleDefer}+ aria-pressed={isDeferred}+ aria-label={localize('com_ui_mcp_defer_loading')}+ className={cn(+ iconButton,+ isDeferred ? 'text-amber-500' : 'text-text-secondary hover:text-text-primary',+ )}+ >+ <Clock className="size-4" aria-hidden="true" />+ </button>+ }+ />+ )}+ {programmaticToolsEnabled && (+ <TooltipAnchor+ description={localize('com_ui_mcp_click_to_programmatic')}+ side="top"+ render={+ <button+ type="button"+ onClick={onToggleProgrammatic}+ aria-pressed={isProgrammatic}+ aria-label={localize('com_ui_mcp_programmatic')}+ className={cn(+ iconButton,+ isProgrammatic+ ? 'text-violet-500'+ : 'text-text-secondary hover:text-text-primary',+ )}+ >+ <Code2 className="size-4" aria-hidden="true" />+ </button>+ }+ />+ )}+ <button+ type="button"+ onClick={() => setExpanded((value) => !value)}+ aria-expanded={expanded}+ aria-controls={detailsId}+ aria-label={localize('com_ui_tools_info')}+ className={cn(+ iconButton,+ expanded ? 'text-text-primary' : 'text-text-secondary hover:text-text-primary',)}- {programmaticToolsEnabled && (- <DropdownMenuCheckboxItem- checked={isProgrammatic}- onCheckedChange={onToggleProgrammatic}- className="cursor-pointer"- >- <div className="flex items-center gap-2">- <Code2 className="h-4 w-4 text-violet-500" />- <div className="flex flex-col">- <span>{localize('com_ui_mcp_programmatic')}</span>- <span className="text-xs text-text-secondary">- {localize('com_ui_mcp_click_to_programmatic')}- </span>- </div>- </div>- </DropdownMenuCheckboxItem>+ >+ <Info className="size-4" aria-hidden="true" />+ </button>+ </div>+ </div>+ {/* Auto-height reveal via grid-template-rows 0fr -> 1fr so the panel — and+ the auto-sized dialog around it — grow/shrink smoothly instead of jumping. */}+ <div+ id={detailsId}+ className={cn(+ 'grid transition-[grid-template-rows] [transition-duration:var(--resize-dur)] [transition-timing-function:var(--resize-ease)] motion-reduce:transition-none',+ expanded ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]',+ )}+ >+ <div className="min-h-0 overflow-hidden">+ <div+ className={cn(+ 'border-t border-border-light px-3 py-3 transition-opacity duration-200 ease-out motion-reduce:transition-none',+ expanded ? 'opacity-100' : 'opacity-0',)}- </DropdownMenuContent>- </DropdownMenu>+ >+ <p className="max-h-44 overflow-y-auto whitespace-pre-wrap text-xs leading-relaxed text-text-secondary">+ {description || localize('com_ui_mcp_no_description')}+ </p>+ </div>+ </div></div></div>);diff --git a/client/src/components/SidePanel/Agents/MCPTools.tsx b/client/src/components/SidePanel/Agents/MCPTools.tsxdeleted file mode 100644index 1d5059889d..0000000000--- a/client/src/components/SidePanel/Agents/MCPTools.tsx+++ /dev/null@@ -1,78 +0,0 @@-import React from 'react';-import { PermissionTypes, Permissions } from 'librechat-data-provider';-import UninitializedMCPTool from './UninitializedMCPTool';-import UnconfiguredMCPTool from './UnconfiguredMCPTool';-import { useHasAccess, useLocalize } from '~/hooks';-import { useAgentPanelContext } from '~/Providers';-import MCPTool from './MCPTool';--export default function MCPTools({- agentId,- mcpServerNames,- setShowMCPToolDialog,-}: {- agentId: string;- mcpServerNames?: string[];- setShowMCPToolDialog: React.Dispatch<React.SetStateAction<boolean>>;-}) {- const localize = useLocalize();- const { mcpServersMap } = useAgentPanelContext();- const hasMcpAccess = useHasAccess({- permissionType: PermissionTypes.MCP_SERVERS,- permission: Permissions.USE,- });- if (!hasMcpAccess) {- return null;- }- return (- <div className="mb-4">- <label className="text-token-text-primary mb-2 block text-sm font-medium">- {localize('com_ui_mcp_servers')}- </label>- <div>- <div className="mb-1">- {/* Render servers with selected tools */}- {mcpServerNames?.map((mcpServerName) => {- const serverInfo = mcpServersMap.get(mcpServerName);- if (!serverInfo?.isConfigured) {- return (- <UnconfiguredMCPTool- key={`${mcpServerName}-${agentId}`}- serverName={mcpServerName}- />- );- }- if (!serverInfo) {- return null;- }-- if (serverInfo?.tools?.length && serverInfo.tools.length > 0) {- return (- <MCPTool key={`${serverInfo.serverName}-${agentId}`} serverInfo={serverInfo} />- );- }-- return (- <UninitializedMCPTool- key={`${serverInfo.serverName}-${agentId}`}- serverInfo={serverInfo}- />- );- })}- </div>- <div className="mt-2">- <button- type="button"- onClick={() => setShowMCPToolDialog(true)}- className="btn btn-neutral border-token-border-light relative h-9 w-full rounded-lg font-medium"- aria-haspopup="dialog"- >- <div className="flex w-full items-center justify-center gap-2">- {localize('com_assistants_add_mcp_server_tools')}- </div>- </button>- </div>- </div>- </div>- );-}diff --git a/client/src/components/SidePanel/Agents/ModelPanel.tsx b/client/src/components/SidePanel/Agents/ModelPanel.tsxindex d1bf137505..3cdecaf408 100644--- a/client/src/components/SidePanel/Agents/ModelPanel.tsx+++ b/client/src/components/SidePanel/Agents/ModelPanel.tsx@@ -3,7 +3,6 @@ import keyBy from 'lodash/keyBy';import { ControlCombobox } from '@librechat/client';import { ChevronLeft, RotateCcw } from 'lucide-react';import { useFormContext, useWatch, Controller } from 'react-hook-form';-import { componentMapping } from '~/components/SidePanel/Parameters/components';import {alternateName,getSettingsKeys,@@ -15,6 +14,7 @@ import {} from 'librechat-data-provider';import type * as t from 'librechat-data-provider';import type { AgentForm, AgentModelPanelProps, StringOption } from '~/common';+import { componentMapping } from '~/components/SidePanel/Parameters/components';import { useGetEndpointsQuery } from '~/data-provider';import { useLiveAnnouncer } from '~/Providers';import { useLocalize } from '~/hooks';@@ -103,31 +103,27 @@ export default function ModelPanel({};return (- <div className="mb-1 flex w-full flex-col gap-2 text-sm">- <div className="model-panel relative flex flex-col items-center px-16 pt-2 text-center">- <div className="absolute left-0 top-4">- <button- type="button"- className="btn btn-neutral relative"- onClick={() => {- setActivePanel(Panel.builder);- }}- aria-label={localize('com_ui_back_to_builder')}- >- <div className="model-panel-content flex w-full items-center justify-center gap-2">- <ChevronLeft />- </div>- </button>- </div>-- <div className="mb-2 mt-2 text-xl font-medium">{localize('com_ui_model_parameters')}</div>- </div>+ <div className="mb-1 flex w-full flex-col gap-3 text-sm">+ <header className="grid grid-cols-[auto_1fr_auto] items-center gap-2 pt-1">+ <button+ type="button"+ onClick={() => setActivePanel(Panel.builder)}+ aria-label={localize('com_ui_back_to_builder')}+ className="inline-flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-border-light text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <ChevronLeft className="h-5 w-5" strokeWidth={1.75} aria-hidden="true" />+ </button>+ <h2 className="text-center text-base font-semibold text-text-primary">+ {localize('com_ui_model_parameters')}+ </h2>+ <span aria-hidden="true" className="h-10 w-10" />+ </header><div>{/* Endpoint aka Provider for Agents */}- <div className="mb-4">+ <div className="mb-3"><labelid="provider-label"- className="text-token-text-primary model-panel-label mb-2 block text-sm font-medium"+ className="mb-1 block text-[11px] font-medium uppercase tracking-wide text-text-secondary"htmlFor="provider">{localize('com_ui_provider')} <span className="text-red-500">*</span>@@ -164,7 +160,7 @@ export default function ModelPanel({showCarat={true}/>{error && (- <span className="model-panel-error text-sm text-red-500 transition duration-300 ease-in-out">+ <span className="mt-1 text-xs text-red-500" role="alert">{localize('com_ui_field_required')}</span>)}@@ -174,12 +170,12 @@ export default function ModelPanel({/></div>{/* Model */}- <div className="model-panel-section mb-4">+ <div className="mb-3"><labelid="model-label"className={cn(- 'text-token-text-primary model-panel-label mb-2 block text-sm font-medium',- !provider && 'text-gray-500 dark:text-gray-400',+ 'mb-1 block text-[11px] font-medium uppercase tracking-wide text-text-secondary',+ !provider && 'opacity-60',)}htmlFor="model">@@ -212,7 +208,7 @@ export default function ModelPanel({showCarat={true}/>{provider && error && (- <span className="text-sm text-red-500 transition duration-300 ease-in-out">+ <span className="mt-1 text-xs text-red-500" role="alert">{localize('com_ui_field_required')}</span>)}@@ -225,7 +221,7 @@ export default function ModelPanel({{/* Model Parameters */}{parameters && (<div className="h-auto max-w-full">- <div className="grid grid-cols-2 gap-4">+ <div className="grid grid-cols-2 gap-3">{/* This is the parent element containing all settings */}{/* Below is an example of an applied dynamic setting, each be contained by a div with the column span specified */}{parameters.map((setting) => {@@ -257,9 +253,9 @@ export default function ModelPanel({<buttontype="button"onClick={handleResetParameters}- className="btn btn-neutral my-1 flex w-full items-center justify-center gap-2 px-4 py-2 text-sm"+ className="mt-2 inline-flex h-9 w-full items-center justify-center gap-2 rounded-xl border border-border-light bg-transparent px-4 text-sm font-medium text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary">- <RotateCcw className="h-4 w-4" aria-hidden="true" />+ <RotateCcw className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />{localize('com_ui_reset_var', { 0: localize('com_ui_model_parameters') })}</button></div>diff --git a/client/src/components/SidePanel/Agents/Retrieval.tsx b/client/src/components/SidePanel/Agents/Retrieval.tsxdeleted file mode 100644index d4df0c3f46..0000000000--- a/client/src/components/SidePanel/Agents/Retrieval.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { useEffect, useMemo } from 'react';-import { Capabilities } from 'librechat-data-provider';-import { useFormContext, Controller, useWatch } from 'react-hook-form';-import {- Checkbox,- HoverCard,- CircleHelpIcon,- HoverCardContent,- HoverCardPortal,- HoverCardTrigger,-} from '@librechat/client';-import type { AssistantForm } from '~/common';-import OptionHover from '~/components/SidePanel/Parameters/OptionHover';-import { useLocalize } from '~/hooks';-import { ESide } from '~/common';-import { cn } from '~/utils/';--export default function Retrieval({ retrievalModels }: { retrievalModels: Set<string> }) {- const localize = useLocalize();- const methods = useFormContext<AssistantForm>();- const { control, setValue, getValues } = methods;- const model = useWatch({ control, name: 'model' });-- const isDisabled = useMemo(() => !retrievalModels.has(model), [model, retrievalModels]);-- useEffect(() => {- if (model && isDisabled) {- setValue(Capabilities.retrieval, false);- }- }, [model, setValue, isDisabled]);-- return (- <>- <HoverCard openDelay={50}>- <div className="flex items-center">- <Controller- name={Capabilities.retrieval}- control={control}- render={({ field }) => (- <Checkbox- {...field}- checked={field.value}- disabled={isDisabled}- onCheckedChange={field.onChange}- className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"- value={field.value?.toString()}- aria-labelledby="retrieval-label"- />- )}- />- <div className="flex items-center space-x-2">- <label- id="retrieval-label"- className={cn(- 'form-check-label text-token-text-primary w-full select-none',- isDisabled ? 'cursor-no-drop opacity-50' : 'cursor-pointer',- )}- htmlFor={Capabilities.retrieval}- onClick={() =>- retrievalModels.has(model) &&- setValue(Capabilities.retrieval, !getValues(Capabilities.retrieval), {- shouldDirty: true,- })- }- >- {localize('com_assistants_file_search')}- </label>- <HoverCardTrigger>- <CircleHelpIcon className="h-5 w-5 text-gray-500" />- </HoverCardTrigger>- </div>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} disabled={isDisabled} className="ml-16 w-80">- <div className="space-y-2">- <p className="text-sm text-gray-600 dark:text-gray-300">- {/* // TODO: Add description for file search */}- </p>- </div>- </HoverCardContent>- </HoverCardPortal>- <OptionHover- side={ESide.Top}- disabled={!isDisabled}- description="com_assistants_non_retrieval_model"- langCode={true}- sideOffset={20}- className="ml-16"- />- </div>- </HoverCard>- </>- );-}diff --git a/client/src/components/SidePanel/Agents/Search/Action.tsx b/client/src/components/SidePanel/Agents/Search/Action.tsxindex b79a188814..5cd627393b 100644--- a/client/src/components/SidePanel/Agents/Search/Action.tsx+++ b/client/src/components/SidePanel/Agents/Search/Action.tsx@@ -1,20 +1,11 @@-import { KeyRoundIcon } from 'lucide-react';import { useRef } from 'react';+import { Button } from '@librechat/client';+import { useFormContext } from 'react-hook-form';+import { KeyRound, CircleCheck } from 'lucide-react';import { AuthType, AgentCapabilities } from 'librechat-data-provider';-import { useFormContext, Controller, useWatch } from 'react-hook-form';-import {- CircleHelpIcon,- Checkbox,- HoverCard,- HoverCardContent,- HoverCardPortal,- HoverCardTrigger,-} from '@librechat/client';import type { AgentForm } from '~/common';import { useLocalize, useSearchApiKeyForm } from '~/hooks';import ApiKeyDialog from './ApiKeyDialog';-import { ESide } from '~/common';-import { cn } from '~/utils';export default function Action({authTypes = [],@@ -24,8 +15,7 @@ export default function Action({isToolAuthenticated?: boolean;}) {const localize = useLocalize();- const methods = useFormContext<AgentForm>();- const { control, setValue } = methods;+ const { setValue } = useFormContext<AgentForm>();const apiKeyButtonRef = useRef<HTMLButtonElement>(null);const {onSubmit,@@ -44,82 +34,33 @@ export default function Action({},});- const webSearchIsEnabled = useWatch({ control, name: AgentCapabilities.web_search });const isUserProvided = authTypes?.some(([, authType]) => authType === AuthType.USER_PROVIDED);- const handleCheckboxChange = (checked: boolean) => {- if (isToolAuthenticated) {- setValue(AgentCapabilities.web_search, checked, { shouldDirty: true });- } else if (webSearchIsEnabled) {- setValue(AgentCapabilities.web_search, false, { shouldDirty: true });- } else {- setIsDialogOpen(true);- }- };+ if (!isUserProvided) {+ return null;+ }return (<>- <HoverCard openDelay={50}>- <div className="flex items-center">- <Controller- name={AgentCapabilities.web_search}- control={control}- render={({ field }) => (- <Checkbox- {...field}- id="web-search-checkbox"- checked={- webSearchIsEnabled ? webSearchIsEnabled : isToolAuthenticated && field.value- }- onCheckedChange={handleCheckboxChange}- className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"- value={field.value.toString()}- disabled={webSearchIsEnabled ? false : !isToolAuthenticated}- aria-labelledby="web-search-label"- />- )}- />- <label- id="web-search-label"- htmlFor="web-search-checkbox"- className={cn(- 'form-check-label text-token-text-primary text-sm',- (webSearchIsEnabled || isToolAuthenticated) && 'cursor-pointer',- )}- >- {localize('com_ui_web_search')}- </label>- <div className="ml-2 flex gap-2">- {isUserProvided && (- <button- ref={apiKeyButtonRef}- type="button"- onClick={() => setIsDialogOpen(true)}- aria-label={localize('com_ui_add_web_search_api_keys')}- aria-haspopup="dialog"- >- <KeyRoundIcon className="h-5 w-5 text-text-primary" />- </button>- )}- <HoverCardTrigger asChild>- <button- type="button"- className="inline-flex items-center"- aria-label={localize('com_agents_search_info')}- >- <CircleHelpIcon className="h-4 w-4 text-text-tertiary" />- </button>- </HoverCardTrigger>- </div>- <HoverCardPortal>- <HoverCardContent side={ESide.Top} className="w-80">- <div className="space-y-2">- <p className="text-sm text-text-secondary">{localize('com_agents_search_info')}</p>- </div>- </HoverCardContent>- </HoverCardPortal>- </div>- </HoverCard>+ <Button+ ref={apiKeyButtonRef}+ type="button"+ variant="outline"+ onClick={() => setIsDialogOpen(true)}+ aria-haspopup="dialog"+ className="w-full justify-center gap-2"+ >+ {isToolAuthenticated ? (+ <CircleCheck className="h-4 w-4 text-green-500" aria-hidden="true" />+ ) : (+ <KeyRound className="h-4 w-4" aria-hidden="true" />+ )}+ {localize(+ isToolAuthenticated+ ? 'com_ui_manage_web_search_api_keys'+ : 'com_ui_add_web_search_api_keys',+ )}+ </Button><ApiKeyDialogonSubmit={onSubmit}authTypes={authTypes}diff --git a/client/src/components/SidePanel/Agents/Search/Form.tsx b/client/src/components/SidePanel/Agents/Search/Form.tsxdeleted file mode 100644index b25eb13258..0000000000--- a/client/src/components/SidePanel/Agents/Search/Form.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { Tools } from 'librechat-data-provider';-import { useVerifyAgentToolAuth } from '~/data-provider';-import { useLocalize } from '~/hooks';-import Action from './Action';--export default function SearchForm() {- const localize = useLocalize();- const { data } = useVerifyAgentToolAuth(- { toolId: Tools.web_search },- {- retry: 1,- },- );-- return (- <div className="w-full">- <div className="mb-1.5 flex items-center gap-2">- <div className="flex flex-row items-center gap-1">- <div className="flex items-center gap-1">- <span className="text-token-text-primary block text-sm font-medium">- {localize('com_ui_web_search')}- </span>- </div>- </div>- </div>- <div className="flex flex-col items-start gap-2">- <Action authTypes={data?.authTypes} isToolAuthenticated={data?.authenticated} />- </div>- </div>- );-}diff --git a/client/src/components/SidePanel/Agents/SectionHeader.tsx b/client/src/components/SidePanel/Agents/SectionHeader.tsxnew file mode 100644index 0000000000..5bd2497051--- /dev/null+++ b/client/src/components/SidePanel/Agents/SectionHeader.tsx@@ -0,0 +1,13 @@+import { memo } from 'react';++function SectionHeader({ title, info }: { title: string; info: string }) {+ return (+ <div className="mb-3">+ <h3 className="text-sm font-semibold text-text-primary">{title}</h3>+ <p className="mt-1 text-sm leading-relaxed text-text-secondary">{info}</p>+ <div className="mt-3 h-px w-full bg-border-light" aria-hidden="true" />+ </div>+ );+}++export default memo(SectionHeader);diff --git a/client/src/components/SidePanel/Agents/Tools/ActionEditor.tsx b/client/src/components/SidePanel/Agents/Tools/ActionEditor.tsxnew file mode 100644index 0000000000..5b6c63f9a6--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ActionEditor.tsx@@ -0,0 +1,156 @@+import { useEffect } from 'react';+import { useForm, FormProvider } from 'react-hook-form';+import {+ AuthTypeEnum,+ AuthorizationTypeEnum,+ TokenExchangeMethodEnum,+} from 'librechat-data-provider';+import {+ Label,+ Button,+ OGDialog,+ TrashIcon,+ OGDialogTrigger,+ useToastContext,+ OGDialogTemplate,+} from '@librechat/client';+import type { ActionAuthForm } from '~/common';+import ActionsAuth from '~/components/SidePanel/Builder/ActionsAuth';+import { useAgentPanelContext } from '~/Providers/AgentPanelContext';+import { useDeleteAgentAction } from '~/data-provider';+import { isEphemeralAgent } from '~/common';+import ActionsInput from '../ActionsInput';+import { useLocalize } from '~/hooks';++interface ActionEditorProps {+ agentId: string;+ onClose: () => void;+ onDeleted?: () => void;+ onCreated?: () => void;+}++export default function ActionEditor({+ agentId,+ onClose,+ onDeleted,+ onCreated,+}: ActionEditorProps) {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const { action, setAction } = useAgentPanelContext();++ const deleteAgentAction = useDeleteAgentAction({+ onSuccess: () => {+ showToast({+ message: localize('com_assistants_delete_actions_success'),+ status: 'success',+ });+ onDeleted?.();+ onClose();+ },+ onError(error) {+ showToast({+ message: (error as Error).message ?? localize('com_assistants_delete_actions_error'),+ status: 'error',+ });+ },+ });++ const methods = useForm<ActionAuthForm>({+ defaultValues: {+ /* General */+ type: AuthTypeEnum.None,+ saved_auth_fields: false,+ /* API key */+ api_key: '',+ authorization_type: AuthorizationTypeEnum.Basic,+ custom_auth_header: '',+ /* OAuth */+ oauth_client_id: '',+ oauth_client_secret: '',+ authorization_url: '',+ client_url: '',+ scope: '',+ token_exchange_method: TokenExchangeMethodEnum.DefaultPost,+ },+ });++ const { reset } = methods;++ useEffect(() => {+ if (action?.metadata.auth) {+ reset({+ type: action.metadata.auth.type || AuthTypeEnum.None,+ saved_auth_fields: false,+ api_key: action.metadata.api_key ?? '',+ authorization_type: action.metadata.auth.authorization_type || AuthorizationTypeEnum.Basic,+ oauth_client_id: action.metadata.oauth_client_id ?? '',+ oauth_client_secret: action.metadata.oauth_client_secret ?? '',+ authorization_url: action.metadata.auth.authorization_url ?? '',+ client_url: action.metadata.auth.client_url ?? '',+ scope: action.metadata.auth.scope ?? '',+ token_exchange_method:+ action.metadata.auth.token_exchange_method ?? TokenExchangeMethodEnum.DefaultPost,+ });+ }+ }, [action, reset]);++ const deleteButton = action ? (+ <OGDialog>+ <OGDialogTrigger asChild>+ <Button+ type="button"+ variant="destructive"+ size="icon"+ disabled={isEphemeralAgent(agentId) || !action.action_id}+ aria-label={localize('com_ui_delete_action')}+ title={localize('com_ui_delete_action')}+ >+ <TrashIcon className="h-4 w-4" />+ </Button>+ </OGDialogTrigger>+ <OGDialogTemplate+ showCloseButton={false}+ title={localize('com_ui_delete_action')}+ className="max-w-[450px]"+ main={+ <Label className="text-left text-sm font-medium">+ {localize('com_ui_delete_action_confirm')}+ </Label>+ }+ selection={{+ selectHandler: () => {+ if (isEphemeralAgent(agentId)) {+ return showToast({+ message: localize('com_agents_no_agent_id_error'),+ status: 'error',+ });+ }+ deleteAgentAction.mutate({+ action_id: action.action_id,+ agent_id: agentId,+ });+ },+ selectClasses:+ 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',+ selectText: localize('com_ui_delete'),+ }}+ />+ </OGDialog>+ ) : null;++ return (+ <FormProvider {...methods}>+ <form className="flex min-h-0 flex-1 flex-col text-sm">+ <ActionsAuth />+ <ActionsInput+ action={action}+ agent_id={agentId}+ setAction={setAction}+ onCreated={onCreated}+ footerStart={deleteButton}+ />+ </form>+ </FormProvider>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/CategoryFilter.tsx b/client/src/components/SidePanel/Agents/Tools/CategoryFilter.tsxnew file mode 100644index 0000000000..804eae8dae--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/CategoryFilter.tsx@@ -0,0 +1,79 @@+import { useState, useMemo } from 'react';+import * as Ariakit from '@ariakit/react/menu';+import { ChevronDown, Filter } from 'lucide-react';+import { Button, DropdownPopup } from '@librechat/client';+import type { ReactNode } from 'react';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++export interface CategoryOption {+ value: string;+ label: string;+ icon?: ReactNode;+}++interface Props {+ options: CategoryOption[];+ value: string | 'all';+ onChange: (next: string | 'all') => void;+}++export default function CategoryFilter({ options, value, onChange }: Props) {+ const localize = useLocalize();+ const [open, setOpen] = useState(false);++ const items = useMemo(+ () => [+ {+ label: localize('com_ui_all_proper'),+ icon: <Filter className="size-4" aria-hidden="true" />,+ onClick: () => onChange('all'),+ },+ ...options.map((opt) => ({+ label: opt.label,+ icon: opt.icon,+ onClick: () => onChange(opt.value),+ })),+ ],+ [localize, options, onChange],+ );++ if (options.length === 0) {+ return null;+ }++ const active = options.find((o) => o.value === value);+ const label = active ? active.label : localize('com_ui_all_proper');+ const isFiltered = value !== 'all';++ return (+ <DropdownPopup+ portal={true}+ mountByState={true}+ unmountOnHide={true}+ isOpen={open}+ setIsOpen={setOpen}+ menuId="marketplace-category-filter"+ trigger={+ <Ariakit.MenuButton+ render={+ <Button+ variant="outline"+ size="default"+ className={cn(+ 'h-10 gap-1.5 px-3 text-sm font-normal',+ isFiltered && 'border-emerald-500/50 text-text-primary',+ )}+ aria-label={localize('com_ui_category')}+ >+ <Filter className="size-4 text-text-tertiary" aria-hidden="true" />+ <span className="max-w-[10ch] truncate">{label}</span>+ <ChevronDown className="size-3.5 text-text-tertiary" aria-hidden="true" />+ </Button>+ }+ />+ }+ items={items}+ />+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/AddMcpServerDialog.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/AddMcpServerDialog.tsxnew file mode 100644index 0000000000..ee68e392fa--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/AddMcpServerDialog.tsx@@ -0,0 +1,10 @@+import MCPServerDialog from '~/components/SidePanel/MCPBuilder/MCPServerDialog';++interface Props {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export default function AddMcpServerDialog({ open, onOpenChange }: Props) {+ return <MCPServerDialog open={open} onOpenChange={onOpenChange} />;+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialog.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialog.tsxnew file mode 100644index 0000000000..5d96880ebb--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialog.tsx@@ -0,0 +1,42 @@+import { OGDialog, OGDialogContent } from '@librechat/client';+import type { AgentItem } from '../items/types';+import ItemDialogHeader from './ItemDialogHeader';+import ItemDialogBody from './ItemDialogBody';+import { cn } from '~/utils';++interface Props {+ item: AgentItem | null;+ agentId: string;+ onClose: () => void;+}++export default function ItemDialog({ item, agentId, onClose }: Props) {+ const isAction = item?.kind === 'action';+ return (+ <OGDialog open={item !== null} onOpenChange={(next) => !next && onClose()}>+ <OGDialogContent+ className={cn(+ 'w-11/12 gap-0 overflow-hidden rounded-2xl p-0 md:max-h-[85vh]',+ isAction ? 'max-w-5xl' : 'max-w-[560px]',+ )}+ data-testid="item-dialog"+ >+ {item && (+ <div className="flex max-h-[85vh] flex-col">+ <ItemDialogHeader item={item} />+ <div+ className={cn(+ 'px-6 pb-6 pt-2',+ isAction+ ? 'flex min-h-0 flex-1 flex-col overflow-hidden'+ : 'flex-1 overflow-y-auto',+ )}+ >+ <ItemDialogBody item={item} agentId={agentId} onClose={onClose} />+ </div>+ </div>+ )}+ </OGDialogContent>+ </OGDialog>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialogBody.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialogBody.tsxnew file mode 100644index 0000000000..a05ba866d9--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialogBody.tsx@@ -0,0 +1,40 @@+import type { AgentItem } from '../items/types';+import BuiltinSection from './sections/BuiltinSection';+import ActionSection from './sections/ActionSection';+import SkillSection from './sections/SkillSection';+import ToolSection from './sections/ToolSection';+import McpSection from './sections/McpSection';+import { useAgentFileEntries } from '../hooks';++interface Props {+ item: AgentItem;+ agentId: string;+ onClose: () => void;+}++export default function ItemDialogBody({ item, agentId, onClose }: Props) {+ const { contextFiles, knowledgeFiles, codeFiles } = useAgentFileEntries();++ if (item.kind === 'builtin') {+ return (+ <BuiltinSection+ builtinId={item.id}+ agentId={agentId}+ contextFiles={contextFiles}+ knowledgeFiles={knowledgeFiles}+ codeFiles={codeFiles}+ description={item.description}+ />+ );+ }+ if (item.kind === 'tool') {+ return <ToolSection item={item} />;+ }+ if (item.kind === 'skill') {+ return <SkillSection item={item} />;+ }+ if (item.kind === 'mcp') {+ return <McpSection item={item} />;+ }+ return <ActionSection item={item} agentId={agentId} onClose={onClose} />;+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialogHeader.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialogHeader.tsxnew file mode 100644index 0000000000..3869d3dc52--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/ItemDialogHeader.tsx@@ -0,0 +1,66 @@+import { useState } from 'react';+import { OGDialogHeader, OGDialogTitle, OGDialogDescription } from '@librechat/client';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { AgentItem } from '../items/types';+import { getIconForItem } from '../items/icons';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++const KIND_LABEL_KEYS: Record<AgentItem['kind'], TranslationKeys> = {+ builtin: 'com_ui_tools_kind_official',+ tool: 'com_ui_tools_kind_tools',+ skill: 'com_ui_tools_kind_skills',+ mcp: 'com_ui_tools_kind_mcp',+ action: 'com_ui_tools_kind_actions',+};++function HeaderIcon({ item }: { item: AgentItem }) {+ const { Icon, colorClass, iconUrl } = getIconForItem(item);+ const [imgError, setImgError] = useState(false);++ if (iconUrl && !imgError) {+ return (+ <span+ className="flex size-12 shrink-0 items-center justify-center overflow-hidden rounded-2xl bg-white"+ aria-hidden="true"+ >+ <img+ src={iconUrl}+ alt=""+ className="h-full w-full object-cover"+ loading="lazy"+ onError={() => setImgError(true)}+ />+ </span>+ );+ }++ return (+ <span+ className={cn('flex size-12 shrink-0 items-center justify-center rounded-2xl', colorClass)}+ aria-hidden="true"+ >+ <Icon className="size-5" strokeWidth={1.75} />+ </span>+ );+}++export default function ItemDialogHeader({ item }: { item: AgentItem }) {+ const localize = useLocalize();+ const displayName = item.kind === 'builtin' ? localize(item.name as TranslationKeys) : item.name;+ const kindLabel = localize(KIND_LABEL_KEYS[item.kind]);++ return (+ <OGDialogHeader className="flex flex-row items-center gap-3 space-y-0 px-6 pb-4 pt-5 text-left">+ <HeaderIcon item={item} />+ <div className="min-w-0 flex-1">+ <OGDialogTitle className="truncate text-base font-semibold text-text-primary">+ {displayName}+ </OGDialogTitle>+ <OGDialogDescription className="m-0 text-[11px] uppercase tracking-wide text-text-secondary">+ {kindLabel}+ </OGDialogDescription>+ </div>+ </OGDialogHeader>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/ItemDialog.spec.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/ItemDialog.spec.tsxnew file mode 100644index 0000000000..65687f2d5d--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/ItemDialog.spec.tsx@@ -0,0 +1,87 @@+import '@testing-library/jest-dom/extend-expect';+import { fireEvent, render, screen } from '@testing-library/react';+import type { AgentItem } from '../../items/types';+import ItemDialog from '../ItemDialog';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('react-hook-form', () => ({+ useFormContext: () => ({ control: {}, getValues: () => undefined, setValue: jest.fn() }),+ useWatch: () => undefined,+}));++jest.mock('@librechat/client', () => {+ const React = jest.requireActual('react');+ return {+ OGDialog: ({+ children,+ open,+ onOpenChange,+ }: {+ children: React.ReactNode;+ open: boolean;+ onOpenChange?: (next: boolean) => void;+ }) =>+ open+ ? React.createElement(+ 'div',+ { role: 'dialog' },+ children,+ React.createElement(+ 'button',+ {+ type: 'button',+ onClick: () => onOpenChange?.(false),+ 'data-testid': 'mock-close',+ },+ 'close',+ ),+ )+ : null,+ OGDialogContent: ({ children, ...rest }: { children: React.ReactNode }) =>+ React.createElement('div', rest, children),+ OGDialogHeader: ({ children, ...rest }: { children: React.ReactNode }) =>+ React.createElement('div', rest, children),+ OGDialogTitle: ({ children, ...rest }: { children: React.ReactNode }) =>+ React.createElement('h2', rest, children),+ OGDialogDescription: ({ children, ...rest }: { children: React.ReactNode }) =>+ React.createElement('p', rest, children),+ };+});++jest.mock('../ItemDialogBody', () => ({+ __esModule: true,+ default: ({ item }: { item: AgentItem }) => <div data-testid="item-dialog-body">{item.id}</div>,+}));++const skill: AgentItem = {+ kind: 'skill',+ id: 's1',+ name: 'Reviewer',+ description: 'Review PRs',+ iconKey: 'skill',+ skill: { _id: 's1', name: 'Reviewer' } as never,+};++describe('ItemDialog', () => {+ test('renders nothing when item is null', () => {+ render(<ItemDialog item={null} agentId="a1" onClose={jest.fn()} />);+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ });++ test('renders header and body when an item is provided', () => {+ render(<ItemDialog item={skill} agentId="a1" onClose={jest.fn()} />);+ expect(screen.getByRole('dialog')).toBeInTheDocument();+ expect(screen.getByTestId('item-dialog-body')).toHaveTextContent('s1');+ expect(screen.getByText('Reviewer')).toBeInTheDocument();+ });++ test('calls onClose when the dialog requests to close', () => {+ const onClose = jest.fn();+ render(<ItemDialog item={skill} agentId="a1" onClose={onClose} />);+ fireEvent.click(screen.getByTestId('mock-close'));+ expect(onClose).toHaveBeenCalled();+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/ItemDialogBody.spec.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/ItemDialogBody.spec.tsxnew file mode 100644index 0000000000..122484ff96--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/ItemDialogBody.spec.tsx@@ -0,0 +1,96 @@+import '@testing-library/jest-dom/extend-expect';+import { render, screen } from '@testing-library/react';+import type { AgentItem } from '../../items/types';+import ItemDialogBody from '../ItemDialogBody';++jest.mock('react-hook-form', () => ({+ useFormContext: () => ({ control: {}, getValues: () => undefined, setValue: jest.fn() }),+ useWatch: () => undefined,+}));++jest.mock('../../hooks', () => ({+ useAgentFileEntries: () => ({ contextFiles: [], knowledgeFiles: [], codeFiles: [] }),+}));++jest.mock('../sections/BuiltinSection', () => ({+ __esModule: true,+ default: ({ builtinId }: { builtinId: string }) => (+ <div data-testid="builtin-section">{builtinId}</div>+ ),+}));+jest.mock('../sections/ToolSection', () => ({+ __esModule: true,+ default: () => <div data-testid="tool-section" />,+}));+jest.mock('../sections/SkillSection', () => ({+ __esModule: true,+ default: () => <div data-testid="skill-section" />,+}));+jest.mock('../sections/McpSection', () => ({+ __esModule: true,+ default: () => <div data-testid="mcp-section" />,+}));+jest.mock('../sections/ActionSection', () => ({+ __esModule: true,+ default: () => <div data-testid="action-section" />,+}));++const baseProps = {+ agentId: 'a1',+ onClose: jest.fn(),+};++const skill: AgentItem = {+ kind: 'skill',+ id: 's1',+ name: 'Reviewer',+ description: 'desc',+ iconKey: 'skill',+ skill: { _id: 's1', name: 'Reviewer' } as never,+};+const tool: AgentItem = {+ kind: 'tool',+ id: 't1',+ name: 'Tool',+ description: 'desc',+ iconKey: 'tool',+ plugin: { pluginKey: 't1', name: 'Tool' } as never,+};+const mcp: AgentItem = {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: '',+ iconKey: 'mcp',+ server: { serverName: 'srv', isConfigured: true, tools: [] } as never,+ toolCount: 0,+};+const action: AgentItem = {+ kind: 'action',+ id: 'a1',+ name: 'action',+ description: '',+ iconKey: 'action',+ action: { action_id: 'a1', agent_id: 'a1' } as never,+ endpointCount: 1,+};+const builtin: AgentItem = {+ kind: 'builtin',+ id: 'execute_code',+ name: 'Code',+ description: '',+ iconKey: 'execute_code',+};++describe('ItemDialogBody', () => {+ test.each([+ ['builtin', builtin, 'builtin-section'],+ ['tool', tool, 'tool-section'],+ ['skill', skill, 'skill-section'],+ ['mcp', mcp, 'mcp-section'],+ ['action', action, 'action-section'],+ ])('renders the %s section', (_kind, item, testId) => {+ render(<ItemDialogBody item={item} {...baseProps} />);+ expect(screen.getByTestId(testId)).toBeInTheDocument();+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsxnew file mode 100644index 0000000000..345fe8a357--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/__tests__/McpSection.spec.tsx@@ -0,0 +1,215 @@+import '@testing-library/jest-dom/extend-expect';+import { fireEvent, render, screen } from '@testing-library/react';+import type { ReactNode } from 'react';+import type { McpItem } from '../../items/types';+import McpSection from '../sections/McpSection';++const mockSetValue = jest.fn();+const mockGetValues = jest.fn((): string[] => []);+const mockInitializeServer = jest.fn();++jest.mock('react-hook-form', () => ({+ useFormContext: () => ({ control: {}, setValue: mockSetValue, getValues: mockGetValues }),+ useWatch: () => mockGetValues(),+}));++jest.mock('~/Providers', () => ({+ useAgentPanelContext: () => ({ mcpServersMap: new Map() }),+}));++jest.mock('~/components/ui', () => ({+ Collapse: ({ open, children }: { open: boolean; children: ReactNode }) =>+ open ? children : null,+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useCopyToClipboard: () => jest.fn(),+ useAgentCapabilities: () => ({+ deferredToolsEnabled: false,+ programmaticToolsEnabled: false,+ }),+ useGetAgentsConfig: () => ({ agentsConfig: { capabilities: [] } }),+ useMCPServerManager: () => ({+ getServerStatusIconProps: () => null,+ getConfigDialogProps: () => null,+ initializeServer: mockInitializeServer,+ getOAuthUrl: () => undefined,+ isCancellable: () => false,+ cancelOAuthFlow: jest.fn(),+ }),+ useMCPToolOptions: () => ({+ isToolDeferred: () => false,+ isToolProgrammatic: () => false,+ toggleToolDefer: jest.fn(),+ toggleToolProgrammatic: jest.fn(),+ areAllToolsDeferred: () => false,+ areAllToolsProgrammatic: () => false,+ toggleDeferAll: jest.fn(),+ toggleProgrammaticAll: jest.fn(),+ }),+}));++jest.mock('../../../MCPToolItem', () => ({+ __esModule: true,+ default: ({+ tool,+ isSelected,+ onToggleSelect,+ }: {+ tool: { tool_id: string; name?: string };+ isSelected: boolean;+ onToggleSelect: () => void;+ }) => (+ <button+ type="button"+ data-testid={`tool-${tool.tool_id}`}+ aria-pressed={isSelected}+ onClick={onToggleSelect}+ >+ {tool.name || tool.tool_id}+ </button>+ ),+}));++jest.mock('~/components/MCP/MCPConfigDialog', () => ({+ __esModule: true,+ default: () => null,+}));+jest.mock('~/components/MCP/MCPServerStatusIcon', () => ({+ __esModule: true,+ default: () => null,+}));+jest.mock('~/components/MCP/McpOAuthDialog', () => ({+ __esModule: true,+ default: ({ open, oauthUrl }: { open: boolean; oauthUrl: string }) =>+ open ? <div data-testid="oauth-dialog">{oauthUrl}</div> : null,+}));++jest.mock('@librechat/client', () => {+ const React = jest.requireActual('react');+ return {+ Button: ({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) =>+ React.createElement('button', { type: 'button', onClick }, children),+ Checkbox: ({+ checked,+ onCheckedChange,+ 'aria-label': ariaLabel,+ }: {+ checked: boolean;+ onCheckedChange: (next: boolean) => void;+ 'aria-label': string;+ }) =>+ React.createElement('input', {+ type: 'checkbox',+ checked,+ 'aria-label': ariaLabel,+ onChange: (e: { target: { checked: boolean } }) => onCheckedChange(e.target.checked),+ }),+ };+});++const item: McpItem = {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: 'desc',+ iconKey: 'mcp',+ server: {+ serverName: 'srv',+ isConfigured: true,+ tools: [+ { tool_id: 'mcp:srv:a', name: 'A' },+ { tool_id: 'mcp:srv:b', name: 'B' },+ ],+ metadata: { description: 'desc' },+ } as never,+ toolCount: 2,+};++describe('McpSection', () => {+ beforeEach(() => {+ mockSetValue.mockClear();+ mockGetValues.mockReturnValue([]);+ mockInitializeServer.mockReset();+ });++ test('renders one row per tool', () => {+ render(<McpSection item={item} />);+ expect(screen.getByTestId('tool-mcp:srv:a')).toBeInTheDocument();+ expect(screen.getByTestId('tool-mcp:srv:b')).toBeInTheDocument();+ });++ test('toggling a tool writes its id plus the server token into agent.tools', () => {+ render(<McpSection item={item} />);+ fireEvent.click(screen.getByTestId('tool-mcp:srv:a'));+ expect(mockSetValue).toHaveBeenCalledWith(+ 'tools',+ ['sys__server__sys_mcp_srv', 'mcp:srv:a'],+ expect.objectContaining({ shouldDirty: true }),+ );+ });++ test('select-all writes every tool id', () => {+ render(<McpSection item={item} />);+ fireEvent.click(screen.getByLabelText('com_ui_tools_mcp_select_all'));+ expect(mockSetValue).toHaveBeenCalledWith(+ 'tools',+ expect.arrayContaining(['mcp:srv:a', 'mcp:srv:b']),+ expect.objectContaining({ shouldDirty: true }),+ );+ });++ test('deselect-all strips every tool id but keeps the server attached via its token', () => {+ mockGetValues.mockReturnValue(['mcp:srv:a', 'mcp:srv:b', 'sys__server__sys_mcp_srv']);+ render(<McpSection item={item} />);+ fireEvent.click(screen.getByLabelText('com_ui_tools_mcp_deselect_all'));+ expect(mockSetValue).toHaveBeenCalledWith(+ 'tools',+ ['sys__server__sys_mcp_srv'],+ expect.objectContaining({ shouldDirty: true }),+ );+ });++ test('selection state tracks the watched tools field (re-render on toggle)', () => {+ mockGetValues.mockReturnValue(['mcp:srv:a']);+ render(<McpSection item={item} />);+ expect(screen.getByTestId('tool-mcp:srv:a')).toHaveAttribute('aria-pressed', 'true');+ expect(screen.getByTestId('tool-mcp:srv:b')).toHaveAttribute('aria-pressed', 'false');+ });++ test('renders an inline Connect button when the server is not connected', () => {+ render(<McpSection item={item} />);+ expect(screen.getByText('com_nav_mcp_connect_server')).toBeInTheDocument();+ });++ test('clicking Connect initializes the server without auto-opening OAuth', () => {+ mockInitializeServer.mockResolvedValue({ success: true });+ render(<McpSection item={item} />);+ fireEvent.click(screen.getByText('com_nav_mcp_connect_server'));+ expect(mockInitializeServer).toHaveBeenCalledWith('srv', false);+ });++ test('opens the OAuth dialog only when initialize reports oauthRequired', async () => {+ mockInitializeServer.mockResolvedValue({+ success: true,+ oauthRequired: true,+ oauthUrl: 'https://oauth.example/authorize?x=1',+ });+ render(<McpSection item={item} />);+ fireEvent.click(screen.getByText('com_nav_mcp_connect_server'));+ expect(await screen.findByTestId('oauth-dialog')).toHaveTextContent(+ 'https://oauth.example/authorize?x=1',+ );+ });++ test('shows empty hint when the server exposes no tools', () => {+ const empty: McpItem = {+ ...item,+ server: { ...item.server, tools: [] } as never,+ toolCount: 0,+ };+ render(<McpSection item={empty} />);+ expect(screen.getByText('com_ui_tools_mcp_no_tools')).toBeInTheDocument();+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ActionSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ActionSection.tsxnew file mode 100644index 0000000000..5d34c3ad4e--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ActionSection.tsx@@ -0,0 +1,32 @@+import { useEffect } from 'react';+import type { ActionItem } from '../../items/types';+import { useAgentPanelContext } from '~/Providers';+import { NEW_ACTION_ID } from '../../items/types';+import ActionEditor from '../../ActionEditor';++interface Props {+ item: ActionItem;+ agentId: string;+ onClose: () => void;+}++export default function ActionSection({ item, agentId, onClose }: Props) {+ const { setAction } = useAgentPanelContext();+ const isCreate = item.id === NEW_ACTION_ID;++ useEffect(() => {+ setAction(isCreate ? undefined : item.action);+ return () => setAction(undefined);+ }, [isCreate, item.action, setAction]);++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <ActionEditor+ agentId={agentId}+ onClose={onClose}+ onDeleted={onClose}+ onCreated={isCreate ? onClose : undefined}+ />+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/BuiltinSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/BuiltinSection.tsxnew file mode 100644index 0000000000..f3b3e9dae3--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/BuiltinSection.tsx@@ -0,0 +1,124 @@+import { Radio } from '@librechat/client';+import { useFormContext, useWatch } from 'react-hook-form';+import { Tools, ArtifactModes, AgentCapabilities } from 'librechat-data-provider';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { AgentForm, ExtendedFile } from '~/common';+import type { BuiltinId } from '../../items/types';+import { useVerifyAgentToolAuth } from '~/data-provider';+import SearchAction from '../../../Search/Action';+import FileContext from '../../../FileContext';+import FileSearch from '../../../FileSearch';+import CodeFiles from '../../../Code/Files';+import { useLocalize } from '~/hooks';++interface Props {+ builtinId: BuiltinId;+ agentId: string;+ contextFiles: Array<[string, ExtendedFile]>;+ knowledgeFiles: Array<[string, ExtendedFile]>;+ codeFiles: Array<[string, ExtendedFile]>;+ description?: string;+}++const ARTIFACT_MODES: Array<{+ value: string;+ labelKey: TranslationKeys;+ infoKey?: TranslationKeys;+}> = [+ {+ value: ArtifactModes.DEFAULT,+ labelKey: 'com_ui_artifacts_mode_default',+ infoKey: 'com_ui_artifacts_mode_default_info',+ },+ {+ value: ArtifactModes.SHADCNUI,+ labelKey: 'com_ui_artifacts_mode_shadcn',+ infoKey: 'com_ui_artifacts_mode_shadcn_info',+ },+ {+ value: ArtifactModes.CUSTOM,+ labelKey: 'com_ui_artifacts_mode_custom',+ infoKey: 'com_ui_artifacts_mode_custom_info',+ },+];++interface ArtifactsConfigProps {+ value: string;+ onChange: (next: string) => void;+}++function ArtifactsConfig({ value, onChange }: ArtifactsConfigProps) {+ const localize = useLocalize();+ const options = ARTIFACT_MODES.map((mode) => ({+ value: mode.value,+ label: localize(mode.labelKey),+ }));+ const active = ARTIFACT_MODES.find((mode) => mode.value === value);++ return (+ <div className="flex flex-col gap-3">+ <span id="artifacts-mode-label" className="text-sm font-medium text-text-primary">+ {localize('com_ui_artifacts_mode')}+ </span>+ <Radio+ options={options}+ value={value}+ onChange={onChange}+ fullWidth+ aria-labelledby="artifacts-mode-label"+ />+ {active?.infoKey ? (+ <p className="text-sm leading-relaxed text-text-secondary">{localize(active.infoKey)}</p>+ ) : null}+ </div>+ );+}++function WebSearchConfig() {+ const { data } = useVerifyAgentToolAuth({ toolId: Tools.web_search }, { retry: 1 });+ return <SearchAction authTypes={data?.authTypes} isToolAuthenticated={data?.authenticated} />;+}++export default function BuiltinSection({+ builtinId,+ agentId,+ contextFiles,+ knowledgeFiles,+ codeFiles,+ description,+}: Props) {+ const localize = useLocalize();+ const { control, setValue } = useFormContext<AgentForm>();++ const artifactsValue = (useWatch({ control, name: AgentCapabilities.artifacts }) ?? '') as string;++ let body: React.ReactNode = null;++ if (builtinId === 'execute_code') {+ body = <CodeFiles agent_id={agentId} files={codeFiles} />;+ } else if (builtinId === 'web_search') {+ body = <WebSearchConfig />;+ } else if (builtinId === 'file_search') {+ body = <FileSearch agent_id={agentId} files={knowledgeFiles} showHeader={false} />;+ } else if (builtinId === 'artifacts') {+ body = (+ <ArtifactsConfig+ value={artifactsValue}+ onChange={(next) => setValue(AgentCapabilities.artifacts, next, { shouldDirty: true })}+ />+ );+ } else if (builtinId === 'context') {+ body = <FileContext agent_id={agentId} files={contextFiles} showHeader={false} />;+ }++ const localizedDescription = description ? localize(description as TranslationKeys) : '';++ return (+ <div className="flex flex-col gap-5">+ {localizedDescription && (+ <p className="text-sm leading-relaxed text-text-secondary">{localizedDescription}</p>+ )}+ {body}+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsxnew file mode 100644index 0000000000..660c669c28--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/McpSection.tsx@@ -0,0 +1,380 @@+import { useState, useMemo, useEffect, useCallback } from 'react';+import { Clock, Code2 } from 'lucide-react';+import { useFormContext, useWatch } from 'react-hook-form';+import { Button, Spinner, Checkbox, Skeleton, TooltipAnchor } from '@librechat/client';+import type { MouseEvent } from 'react';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { McpItem } from '../../items/types';+import type { AgentForm } from '~/common';+import {+ useAgentCapabilities,+ useGetAgentsConfig,+ useMCPServerManager,+ useMCPToolOptions,+} from '~/hooks';+import MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';+import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';+import McpOAuthDialog from '~/components/MCP/McpOAuthDialog';+import { mcpServerToken } from '../../items/selectors';+import { useAgentPanelContext } from '~/Providers';+import { getIconForItem } from '../../items/icons';+import MCPToolItem from '../../../MCPToolItem';+import { Collapse } from '~/components/ui';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++interface StatusDisplay {+ labelKey: TranslationKeys;+ dotClass: string;+}++function getStatusDisplay(+ connectionState: string | undefined,+ isInitializing: boolean,+ isConfigured: boolean,+): StatusDisplay {+ if (isInitializing || connectionState === 'connecting') {+ return {+ labelKey: 'com_nav_mcp_status_initializing',+ dotClass: 'bg-blue-500 animate-pulse',+ };+ }+ if (connectionState === 'connected') {+ return { labelKey: 'com_nav_mcp_status_connected', dotClass: 'bg-emerald-500' };+ }+ if (connectionState === 'error') {+ return { labelKey: 'com_nav_mcp_status_error', dotClass: 'bg-red-500' };+ }+ if (connectionState === 'disconnected') {+ return { labelKey: 'com_nav_mcp_status_disconnected', dotClass: 'bg-amber-500' };+ }+ if (!isConfigured) {+ return { labelKey: 'com_ui_tools_mcp_status_unconfigured', dotClass: 'bg-gray-400' };+ }+ return { labelKey: 'com_nav_mcp_status_unknown', dotClass: 'bg-gray-400' };+}++interface Props {+ item: McpItem;+}++export default function McpSection({ item }: Props) {+ const localize = useLocalize();+ const { control, getValues, setValue } = useFormContext<AgentForm>();+ const { getServerStatusIconProps, getConfigDialogProps, initializeServer, getOAuthUrl } =+ useMCPServerManager();+ const [oauthOpen, setOauthOpen] = useState(false);+ const [oauthUrl, setOauthUrl] = useState<string | null>(null);+ const [prevConnected, setPrevConnected] = useState(false);+ const [autoSelectPending, setAutoSelectPending] = useState(false);+ const { mcpServersMap, mcpToolsLoading } = useAgentPanelContext();+ const { agentsConfig } = useGetAgentsConfig();+ const { deferredToolsEnabled, programmaticToolsEnabled } = useAgentCapabilities(+ agentsConfig?.capabilities,+ );+ const {+ isToolDeferred,+ isToolProgrammatic,+ toggleToolDefer,+ toggleToolProgrammatic,+ areAllToolsDeferred,+ areAllToolsProgrammatic,+ toggleDeferAll,+ toggleProgrammaticAll,+ } = useMCPToolOptions();++ const serverName = item.server.serverName;+ const serverToken = mcpServerToken(serverName);+ /** Live server data — `item.server` is a snapshot from card click and goes stale once+ * the MCP query refetches (e.g., after a server connects), so read from the live map. */+ const liveServer = mcpServersMap.get(serverName) ?? item.server;+ const tools = useMemo(() => liveServer.tools ?? [], [liveServer.tools]);+ const hasTools = tools.length > 0;++ /** Subscribe to the tools field so selection toggles re-render this section.+ * `getValues` is a non-reactive read and left the checkboxes visually stale. */+ const formTools = (useWatch({ control, name: 'tools' }) ?? []) as string[];++ const getSelectedTools = (): string[] =>+ tools.filter((t) => formTools.includes(t.tool_id)).map((t) => t.tool_id);++ /** Replace this server's tool selection while keeping the server attached: the+ * placeholder token is always rewritten, so deselect-all leaves the server+ * pinned with zero tools; only an explicit remove detaches it. */+ const updateFormTools = useCallback(+ (next: string[]) => {+ const current = (getValues('tools') ?? []) as string[];+ const otherTools = current.filter(+ (t) => t !== serverToken && !tools.some((st) => st.tool_id === t),+ );+ setValue('tools', [...otherTools, serverToken, ...next], { shouldDirty: true });+ },+ [getValues, setValue, serverToken, tools],+ );++ const toggleToolSelect = (toolId: string) => {+ const selected = getSelectedTools();+ const next = selected.includes(toolId)+ ? selected.filter((t) => t !== toolId)+ : [...selected, toolId];+ updateFormTools(next);+ };++ const toggleAll = (checked: boolean) => {+ updateFormTools(checked ? tools.map((t) => t.tool_id) : []);+ };++ const selectedTools = getSelectedTools();+ const allSelected = hasTools && selectedTools.length === tools.length;+ const allDeferred = areAllToolsDeferred(tools);+ const allProgrammatic = areAllToolsProgrammatic(tools);+ const statusIconProps = getServerStatusIconProps(serverName);+ const configDialogProps = getConfigDialogProps();+ const connectionState = statusIconProps?.serverStatus?.connectionState;+ const isInitializing = statusIconProps?.isInitializing ?? false;+ const statusDisplay = getStatusDisplay(connectionState, isInitializing, liveServer.isConfigured);+ /** A connected server's tools arrive with the (cold-cache) MCP tools fetch, and+ * the server is also briefly toolless while initializing — show a skeleton in+ * both cases instead of a misleading "no tools" message. */+ const toolsLoading =+ !hasTools && (mcpToolsLoading || isInitializing || connectionState === 'connecting');+ const isConnected = connectionState === 'connected';+ const isBusy = isInitializing || connectionState === 'connecting';++ /** Close + clear the OAuth dialog once the server connects, and don't let it+ * reopen on its own if the connection later drops. No useEffect — adjust state+ * during render by comparing against the previous connection result. */+ if (prevConnected !== isConnected) {+ setPrevConnected(isConnected);+ if (isConnected) {+ setOauthOpen(false);+ setOauthUrl(null);+ }+ }++ /** Connecting from this dialog implies the user wants the server's tools:+ * once the connection settles and the tools arrive (query refetch for direct+ * connects, polling for OAuth), select them all — an effect because both+ * signals come from external systems, not from anything rendered here. */+ useEffect(() => {+ if (!autoSelectPending || !isConnected || !hasTools) {+ return;+ }+ setAutoSelectPending(false);+ updateFormTools(tools.map((t) => t.tool_id));+ }, [autoSelectPending, isConnected, hasTools, tools, updateFormTools]);++ /** Connect inline from this first dialog. Servers with custom user variables are+ * routed to the config dialog (which sets the vars and initializes); others+ * connect directly. `autoOpenOAuth=false` surfaces the URL in our OAuth dialog+ * (continue / copy / QR) instead of the browser silently opening a tab. */+ const handleConnect = async (e: MouseEvent) => {+ setAutoSelectPending(true);+ if (statusIconProps != null && statusIconProps.hasCustomUserVars) {+ statusIconProps.onConfigClick(e);+ return;+ }+ try {+ const res = await initializeServer(serverName, false);+ if (res == null || !res.success) {+ setAutoSelectPending(false);+ return;+ }+ if (res.oauthRequired && res.oauthUrl) {+ setOauthUrl(res.oauthUrl);+ setOauthOpen(true);+ }+ } catch {+ setAutoSelectPending(false);+ }+ };++ return (+ <div className="flex flex-col gap-5">+ {item.description && (+ <p className="text-sm leading-relaxed text-text-secondary">{item.description}</p>+ )}++ <div className="flex flex-col">+ <div className="flex items-center justify-between rounded-xl border border-border-light bg-surface-secondary px-3 py-2.5">+ <div className="flex items-center gap-2">+ <span+ className={cn('size-2.5 rounded-full', statusDisplay.dotClass)}+ aria-hidden="true"+ />+ <span className="text-sm font-medium text-text-primary">+ {localize(statusDisplay.labelKey)}+ </span>+ </div>+ {isConnected && statusIconProps && <MCPServerStatusIcon {...statusIconProps} />}+ </div>++ {/* Connect collapses smoothly once connected. Its top spacing lives inside+ * the reveal so the parent's flex gap never leaves a hole when it's gone,+ * and the auto-height dialog follows the grid-rows tween in one motion. */}+ <div+ className={cn(+ 'grid transition-[grid-template-rows] [transition-duration:var(--resize-dur)] [transition-timing-function:var(--resize-ease)] motion-reduce:transition-none',+ isConnected ? 'grid-rows-[0fr]' : 'grid-rows-[1fr]',+ )}+ >+ <div className="min-h-0 overflow-hidden">+ <Button+ type="button"+ variant="submit"+ className="mt-5 w-full gap-2"+ disabled={isBusy}+ tabIndex={isConnected ? -1 : undefined}+ aria-hidden={isConnected || undefined}+ onClick={handleConnect}+ >+ {isBusy && <Spinner className="size-4" />}+ {localize('com_nav_mcp_connect_server', { 0: serverName })}+ </Button>+ </div>+ </div>+ </div>++ <div className="flex flex-col gap-2">+ <div className="flex min-h-7 items-center justify-between">+ <span className="text-[11px] font-medium uppercase tracking-wide text-text-secondary">+ {localize('com_ui_tools_mcp_tools_section')}+ </span>+ {hasTools && (+ <div className="flex items-center gap-0.5">+ {deferredToolsEnabled && (+ <TooltipAnchor+ description={+ allDeferred+ ? localize('com_ui_mcp_undefer_all')+ : localize('com_ui_mcp_defer_all')+ }+ side="top"+ render={+ <button+ type="button"+ onClick={() => toggleDeferAll(tools)}+ aria-pressed={allDeferred}+ aria-label={+ allDeferred+ ? localize('com_ui_mcp_undefer_all')+ : localize('com_ui_mcp_defer_all')+ }+ className={cn(+ 'flex size-7 items-center justify-center rounded-md transition-colors',+ 'hover:bg-surface-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',+ allDeferred+ ? 'text-amber-600 dark:text-amber-500'+ : 'text-text-secondary hover:text-text-primary',+ )}+ >+ <Clock className="size-4" aria-hidden="true" />+ </button>+ }+ />+ )}+ {programmaticToolsEnabled && (+ <TooltipAnchor+ description={+ allProgrammatic+ ? localize('com_ui_mcp_unprogrammatic_all')+ : localize('com_ui_mcp_programmatic_all')+ }+ side="top"+ render={+ <button+ type="button"+ onClick={() => toggleProgrammaticAll(tools)}+ aria-pressed={allProgrammatic}+ aria-label={+ allProgrammatic+ ? localize('com_ui_mcp_unprogrammatic_all')+ : localize('com_ui_mcp_programmatic_all')+ }+ className={cn(+ 'flex size-7 items-center justify-center rounded-md transition-colors',+ 'hover:bg-surface-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',+ allProgrammatic+ ? 'text-violet-600 dark:text-violet-500'+ : 'text-text-secondary hover:text-text-primary',+ )}+ >+ <Code2 className="size-4" aria-hidden="true" />+ </button>+ }+ />+ )}+ {(deferredToolsEnabled || programmaticToolsEnabled) && (+ <span className="mx-1 h-4 w-px bg-border-light" aria-hidden="true" />+ )}+ <label className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-xs text-text-secondary">+ <Checkbox+ checked={allSelected}+ onCheckedChange={(checked) => toggleAll(checked === true)}+ aria-label={+ allSelected+ ? localize('com_ui_tools_mcp_deselect_all')+ : localize('com_ui_tools_mcp_select_all')+ }+ className="size-4 rounded border border-border-medium"+ />+ <span>+ {allSelected+ ? localize('com_ui_tools_mcp_deselect_all')+ : localize('com_ui_tools_mcp_select_all')}+ </span>+ </label>+ </div>+ )}+ </div>+ {/* Loading skeleton, tool list, and empty state share one slot and+ * cross-swap via stacked collapses so their differing heights morph+ * smoothly; the dialog's auto-height follows in a single motion. */}+ <div>+ <Collapse open={hasTools}>+ <div className="flex flex-col gap-1">+ {tools.map((tool) => (+ <MCPToolItem+ key={tool.tool_id}+ tool={tool}+ isSelected={selectedTools.includes(tool.tool_id)}+ isDeferred={deferredToolsEnabled && isToolDeferred(tool.tool_id)}+ isProgrammatic={programmaticToolsEnabled && isToolProgrammatic(tool.tool_id)}+ deferredToolsEnabled={deferredToolsEnabled}+ programmaticToolsEnabled={programmaticToolsEnabled}+ onToggleSelect={() => toggleToolSelect(tool.tool_id)}+ onToggleDefer={() => toggleToolDefer(tool.tool_id)}+ onToggleProgrammatic={() => toggleToolProgrammatic(tool.tool_id)}+ />+ ))}+ </div>+ </Collapse>+ <Collapse open={!hasTools && toolsLoading}>+ <div className="flex flex-col gap-1" aria-busy="true" aria-live="polite">+ {['w-3/5', 'w-1/2', 'w-2/5'].map((width) => (+ <div key={width} className="flex items-center gap-2.5 rounded-lg px-2 py-2">+ <Skeleton className="size-4 shrink-0 rounded" />+ <Skeleton className={cn('h-4 rounded', width)} />+ </div>+ ))}+ </div>+ </Collapse>+ <Collapse open={!hasTools && !toolsLoading}>+ <p className="rounded-xl border border-dashed border-border-light p-3 text-center text-xs text-text-tertiary">+ {localize('com_ui_tools_mcp_no_tools')}+ </p>+ </Collapse>+ </div>+ </div>++ {configDialogProps && <MCPConfigDialog {...configDialogProps} />}+ <McpOAuthDialog+ open={oauthOpen && !isConnected}+ onOpenChange={setOauthOpen}+ serverName={serverName}+ oauthUrl={oauthUrl ?? getOAuthUrl(serverName) ?? ''}+ iconUrl={getIconForItem(item).iconUrl}+ />+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/SkillSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/SkillSection.tsxnew file mode 100644index 0000000000..ee064f4c35--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/SkillSection.tsx@@ -0,0 +1,27 @@+import type { SkillItem } from '../../items/types';+import { useLocalize } from '~/hooks';++interface Props {+ item: SkillItem;+}++export default function SkillSection({ item }: Props) {+ const localize = useLocalize();+ return (+ <div className="flex flex-col gap-5">+ {item.description ? (+ <p className="text-sm leading-relaxed text-text-secondary">{item.description}</p>+ ) : (+ <p className="text-sm italic text-text-tertiary">+ {localize('com_ui_tools_no_description')}+ </p>+ )}+ <div className="rounded-xl border border-border-light bg-surface-secondary px-4 py-3 text-xs text-text-secondary">+ <span className="block font-medium uppercase tracking-wide text-text-tertiary">+ {localize('com_ui_tools_info_identifier')}+ </span>+ <span className="block truncate font-mono text-text-primary">{item.id}</span>+ </div>+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ToolSection.tsx b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ToolSection.tsxnew file mode 100644index 0000000000..c4e974ffa7--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ItemDialog/sections/ToolSection.tsx@@ -0,0 +1,97 @@+import { useState } from 'react';+import { CheckCircle2 } from 'lucide-react';+import { useFormContext } from 'react-hook-form';+import { useToastContext } from '@librechat/client';+import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';+import type { TError, TPluginAction } from 'librechat-data-provider';+import type { ToolItem } from '../../items/types';+import type { AgentForm } from '~/common';+import PluginAuthForm from '~/components/Plugins/Store/PluginAuthForm';+import { pluginNeedsAuth } from '../../items/auth';+import { useLocalize } from '~/hooks';++interface Props {+ item: ToolItem;+}++export default function ToolSection({ item }: Props) {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const { getValues, setValue } = useFormContext<AgentForm>();+ const updateUserPlugins = useUpdateUserPluginsMutation();++ const requiresAuth = pluginNeedsAuth(item.plugin);+ const [savedAuth, setSavedAuth] = useState(false);+ const [editing, setEditing] = useState(false);++ const showForm = requiresAuth && (!savedAuth || editing);+ const showConfigured = requiresAuth && savedAuth && !editing;++ /** Add this tool's pluginKey to the agent's tools so it becomes usable. */+ const enableTool = () => {+ const current = (getValues('tools') ?? []) as string[];+ if (!current.includes(item.id)) {+ setValue('tools', [...current, item.id], { shouldDirty: true });+ }+ };++ const handleSubmit = (data: TPluginAction) => {+ const hasAuth = data.auth != null && Object.keys(data.auth).length > 0;+ if (!hasAuth) {+ enableTool();+ setSavedAuth(true);+ setEditing(false);+ return;+ }+ updateUserPlugins.mutate(data, {+ onError: (error: unknown) => {+ showToast({+ message: (error as TError)?.message || localize('com_nav_plugin_auth_error'),+ status: 'error',+ });+ },+ onSuccess: () => {+ enableTool();+ setSavedAuth(true);+ setEditing(false);+ showToast({ message: localize('com_ui_tool_credentials_saved'), status: 'success' });+ },+ });+ };++ return (+ <div className="flex flex-col gap-5">+ {item.description ? (+ <p className="text-sm leading-relaxed text-text-secondary">{item.description}</p>+ ) : (+ <p className="text-sm italic text-text-tertiary">+ {localize('com_ui_tools_no_description')}+ </p>+ )}+ {showConfigured && (+ <div className="flex items-center justify-between rounded-xl border border-border-light bg-surface-secondary px-3 py-2.5">+ <span className="flex items-center gap-2 text-sm font-medium text-text-primary">+ <CheckCircle2 className="size-4 text-emerald-500" aria-hidden="true" />+ {localize('com_ui_tools_info_configured')}+ </span>+ <button+ type="button"+ onClick={() => setEditing(true)}+ className="rounded-md px-2 py-1 text-xs font-medium text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ {localize('com_ui_edit')}+ </button>+ </div>+ )}+ {showForm && (+ <PluginAuthForm+ plugin={item.plugin}+ isEntityTool+ isSaving={updateUserPlugins.isLoading}+ onCancel={editing ? () => setEditing(false) : undefined}+ onSubmit={handleSubmit}+ />+ )}+ </div>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/MarketplaceCatalog.tsx b/client/src/components/SidePanel/Agents/Tools/MarketplaceCatalog.tsxnew file mode 100644index 0000000000..5d719984e1--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/MarketplaceCatalog.tsx@@ -0,0 +1,105 @@+import { Search } from 'lucide-react';+import { Skeleton } from '@librechat/client';+import type { AgentItem, ItemFilter } from './items/types';+import type { TranslationKeys } from '~/hooks/useLocalize';+import { itemKey } from './items/selectors';+import { useLocalize } from '~/hooks';+import ToolCard from './ToolCard';++type View = NonNullable<ItemFilter['view']>;++interface MarketplaceCatalogProps {+ items: AgentItem[];+ selectedIds: Set<string>;+ onToggle: (item: AgentItem) => void;+ onConfigure?: (item: AgentItem) => void;+ view?: View;+ isLoadingSkills?: boolean;+ skillsInView?: boolean;+ /** Compound `kind:id` keys of the user's favorited items. */+ favoriteKeys?: Set<string>;+ onToggleFavorite?: (item: AgentItem) => void;+ /** Overrides the default per-view empty message (e.g. "No skills found"). */+ emptyKey?: TranslationKeys;+ /** Accessible label for the grid; defaults to the marketplace label. */+ ariaLabel?: string;+}++const SKELETON_COUNT = 3;++const EMPTY_COPY_KEYS: Record<View, TranslationKeys> = {+ marketplace: 'com_ui_tools_search_no_results',+ mine: 'com_ui_tools_view_mine_empty',+ favorites: 'com_ui_tools_view_favorites_empty',+};++function ToolCardSkeleton() {+ return (+ <div className="flex h-32 w-full flex-col gap-2 rounded-2xl border border-border-light p-4">+ <div className="flex w-full items-start gap-3">+ <Skeleton className="h-10 w-10 shrink-0 rounded-xl" />+ <div className="min-w-0 flex-1 space-y-1.5">+ <Skeleton className="h-4 w-2/3" />+ <Skeleton className="h-3 w-1/3" />+ </div>+ </div>+ <Skeleton className="h-3 w-full" />+ <Skeleton className="h-3 w-4/5" />+ </div>+ );+}++export default function MarketplaceCatalog({+ items,+ selectedIds,+ onToggle,+ onConfigure,+ view = 'marketplace',+ isLoadingSkills = false,+ skillsInView = false,+ favoriteKeys,+ onToggleFavorite,+ emptyKey,+ ariaLabel,+}: MarketplaceCatalogProps) {+ const localize = useLocalize();+ const showSkeletons = isLoadingSkills && skillsInView;++ if (items.length === 0 && !showSkeletons) {+ return (+ <div className="flex flex-col items-center justify-center py-16 text-center">+ <Search className="size-8 text-text-tertiary opacity-40" aria-hidden="true" />+ <p className="mt-3 text-sm text-text-secondary">+ {localize(emptyKey ?? EMPTY_COPY_KEYS[view])}+ </p>+ </div>+ );+ }++ return (+ <ul+ className="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3"+ aria-label={ariaLabel ?? localize('com_ui_tools_marketplace')}+ aria-busy={showSkeletons}+ >+ {items.map((item) => (+ <li key={itemKey(item)}>+ <ToolCard+ item={item}+ selected={selectedIds.has(itemKey(item))}+ onToggle={onToggle}+ onConfigure={onConfigure}+ isFavorited={favoriteKeys?.has(itemKey(item)) ?? false}+ onToggleFavorite={onToggleFavorite}+ />+ </li>+ ))}+ {showSkeletons &&+ Array.from({ length: SKELETON_COUNT }, (_, index) => (+ <li key={`skeleton:${index}`} aria-hidden="true">+ <ToolCardSkeleton />+ </li>+ ))}+ </ul>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/MarketplaceSidebar.tsx b/client/src/components/SidePanel/Agents/Tools/MarketplaceSidebar.tsxnew file mode 100644index 0000000000..e4f3f8f338--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/MarketplaceSidebar.tsx@@ -0,0 +1,201 @@+import { useState, useMemo } from 'react';+import * as Ariakit from '@ariakit/react/menu';+import { Button, DropdownPopup } from '@librechat/client';+import { Permissions, PermissionTypes, AgentCapabilities } from 'librechat-data-provider';+import { LayoutGrid, ListFilter, Wrench, Server, Workflow, Star, User, Plus } from 'lucide-react';+import type { ReactNode } from 'react';+import type { AgentItemKind, ItemFilter } from './items/types';+import { useLocalize, useHasAccess } from '~/hooks';+import { useAgentPanelContext } from '~/Providers';+import { cn } from '~/utils';++type View = NonNullable<ItemFilter['view']>;+type Kind = AgentItemKind | 'all';++interface MarketplaceSidebarProps {+ activeView: View;+ activeKind: Kind;+ onSelectView: (view: View) => void;+ onSelectKind: (kind: Kind) => void;+ counts: Record<AgentItemKind, number>;+ totalCount: number;+ onCreateNew?: (kind: 'mcp' | 'action') => void;+}++interface SidebarItemProps {+ icon: ReactNode;+ label: string;+ active: boolean;+ onClick: () => void;+ count?: number;+}++function SidebarItem({ icon, label, active, onClick, count }: SidebarItemProps) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-pressed={active}+ className={cn(+ 'flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors',+ active+ ? 'bg-surface-active font-medium text-text-primary'+ : 'text-text-secondary hover:bg-surface-hover hover:text-text-primary',+ )}+ >+ <span className="flex size-4 shrink-0 items-center justify-center">{icon}</span>+ <span className="flex-1 truncate">{label}</span>+ {count !== undefined && count > 0 && (+ <span className="text-[11px] tabular-nums text-text-secondary">{count}</span>+ )}+ </button>+ );+}++export default function MarketplaceSidebar({+ activeView,+ activeKind,+ onSelectView,+ onSelectKind,+ counts,+ totalCount,+ onCreateNew,+}: MarketplaceSidebarProps) {+ const localize = useLocalize();+ const [createOpen, setCreateOpen] = useState(false);+ const { agentsConfig } = useAgentPanelContext();+ const hasMcpCreateAccess = useHasAccess({+ permissionType: PermissionTypes.MCP_SERVERS,+ permission: Permissions.CREATE,+ });+ const actionsEnabled = useMemo(+ () => agentsConfig?.capabilities?.includes(AgentCapabilities.actions) ?? false,+ [agentsConfig],+ );++ const createItems = useMemo(() => {+ const items: Array<{ label: string; icon: ReactNode; onClick: () => void }> = [];+ if (hasMcpCreateAccess) {+ items.push({+ label: localize('com_ui_tools_kind_mcp'),+ icon: <Server className="size-4" aria-hidden="true" />,+ onClick: () => onCreateNew?.('mcp'),+ });+ }+ if (actionsEnabled) {+ items.push({+ label: localize('com_ui_tools_kind_actions'),+ icon: <Workflow className="size-4" aria-hidden="true" />,+ onClick: () => onCreateNew?.('action'),+ });+ }+ return items;+ }, [localize, onCreateNew, hasMcpCreateAccess, actionsEnabled]);++ return (+ <aside className="flex w-56 shrink-0 flex-col gap-0.5 border-r border-border-light bg-surface-primary-alt p-3">+ <h2 className="px-2.5 pb-1 pt-1 text-base font-bold text-text-primary">+ {localize('com_ui_tools_marketplace')}+ </h2>++ {createItems.length > 0 && (+ <DropdownPopup+ portal={true}+ mountByState={true}+ unmountOnHide={true}+ isOpen={createOpen}+ setIsOpen={setCreateOpen}+ menuId="marketplace-create-new"+ className="pointer-events-auto"+ trigger={+ <Ariakit.MenuButton+ render={+ <Button+ variant="outline"+ size="sm"+ className="mb-2 mt-1 w-full justify-center gap-1.5"+ >+ <Plus className="size-4" aria-hidden="true" />+ <span className="truncate">{localize('com_ui_tools_create_new')}</span>+ </Button>+ }+ />+ }+ items={createItems}+ />+ )}++ <SidebarItem+ icon={<LayoutGrid className="size-4" />}+ label={localize('com_ui_all_proper')}+ active={activeKind === 'all' && activeView === 'marketplace'}+ onClick={() => {+ onSelectView('marketplace');+ onSelectKind('all');+ }}+ count={totalCount}+ />+ <SidebarItem+ icon={<ListFilter className="size-4" />}+ label={localize('com_ui_tools_kind_official')}+ active={activeKind === 'builtin' && activeView === 'marketplace'}+ onClick={() => {+ onSelectView('marketplace');+ onSelectKind('builtin');+ }}+ count={counts.builtin}+ />+ <SidebarItem+ icon={<Wrench className="size-4" />}+ label={localize('com_ui_tools_kind_tools')}+ active={activeKind === 'tool' && activeView === 'marketplace'}+ onClick={() => {+ onSelectView('marketplace');+ onSelectKind('tool');+ }}+ count={counts.tool}+ />+ <SidebarItem+ icon={<Server className="size-4" />}+ label={localize('com_ui_tools_kind_mcp')}+ active={activeKind === 'mcp' && activeView === 'marketplace'}+ onClick={() => {+ onSelectView('marketplace');+ onSelectKind('mcp');+ }}+ count={counts.mcp}+ />+ <SidebarItem+ icon={<Workflow className="size-4" />}+ label={localize('com_ui_tools_kind_actions')}+ active={activeKind === 'action' && activeView === 'marketplace'}+ onClick={() => {+ onSelectView('marketplace');+ onSelectKind('action');+ }}+ count={counts.action}+ />++ <div className="mx-2 my-3 h-px bg-border-light" />++ <SidebarItem+ icon={<User className="size-4" />}+ label={localize('com_ui_tools_view_made_by_you')}+ active={activeView === 'mine'}+ onClick={() => {+ onSelectView('mine');+ onSelectKind('all');+ }}+ />+ <SidebarItem+ icon={<Star className="size-4" />}+ label={localize('com_ui_tools_view_favorites')}+ active={activeView === 'favorites'}+ onClick={() => {+ onSelectView('favorites');+ onSelectKind('all');+ }}+ />+ </aside>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/SkillsDialog.tsx b/client/src/components/SidePanel/Agents/Tools/SkillsDialog.tsxnew file mode 100644index 0000000000..ab9610c852--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/SkillsDialog.tsx@@ -0,0 +1,238 @@+import { useMemo, useState, useCallback } from 'react';+import { Plus, Search } from 'lucide-react';+import { useFormContext, useWatch } from 'react-hook-form';+import { PermissionTypes, Permissions } from 'librechat-data-provider';+import {+ Radio,+ Input,+ Button,+ OGDialog,+ OGDialogTitle,+ OGDialogContent,+ OGDialogDescription,+} from '@librechat/client';+import type { TSkill } from 'librechat-data-provider';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { CategoryOption } from './CategoryFilter';+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 { skillsEnabledTransition } from './items/mutations';+import MarketplaceCatalog from './MarketplaceCatalog';+import { useListSkillsQuery } from '~/data-provider';+import { CategoryIcon } from '~/components/Prompts';+import { buildSkillItems } from './items/catalog';+import ItemDialog from './ItemDialog/ItemDialog';+import { applyFilter } from './items/filtering';+import CategoryFilter from './CategoryFilter';+import { itemKey } from './items/selectors';++interface SkillsDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ agentId: string;+}++type SkillView = 'marketplace' | 'mine' | 'favorites';++const VIEWS: Array<{ value: SkillView; labelKey: TranslationKeys }> = [+ { value: 'marketplace', labelKey: 'com_ui_all_proper' },+ { value: 'mine', labelKey: 'com_ui_tools_view_made_by_you' },+ { value: 'favorites', labelKey: 'com_ui_tools_view_favorites' },+];++export default function SkillsDialog({ open, onOpenChange, agentId }: SkillsDialogProps) {+ const localize = useLocalize();+ const { user } = useAuthContext();+ const { control, getValues, setValue } = useFormContext<AgentForm>();++ const hasSkillsAccess = useHasAccess({+ permissionType: PermissionTypes.SKILLS,+ permission: Permissions.USE,+ });+ const hasCreateAccess = useHasAccess({+ permissionType: PermissionTypes.SKILLS,+ permission: Permissions.CREATE,+ });+ const { data: skillsData, isLoading: isLoadingSkills } = useListSkillsQuery(+ { limit: 100 },+ { enabled: hasSkillsAccess },+ );+ const { favoriteKeys, toggle: toggleFavorite } = useToolFavorites();++ const skillsField = useWatch({ control, name: 'skills' });+ const selectedIds = useMemo(+ () => new Set(((skillsField ?? []) as string[]).map((id) => itemKey({ kind: 'skill', id }))),+ [skillsField],+ );++ const [view, setView] = useState<SkillView>('marketplace');+ const [search, setSearch] = useState('');+ const [category, setCategory] = useState<string | 'all'>('all');+ const [createOpen, setCreateOpen] = useState(false);+ const [detailItem, setDetailItem] = useState<AgentItem | null>(null);++ const catalog = useMemo(+ () => buildSkillItems(skillsData?.skills ?? [], user?.id),+ [skillsData, user?.id],+ );++ const categoryOptions = useMemo<CategoryOption[]>(() => {+ const seen = new Set<string>();+ const options: CategoryOption[] = [];+ for (const item of catalog) {+ if (item.kind !== 'skill') {+ continue;+ }+ const value = item.skill.category;+ if (!value || seen.has(value)) {+ continue;+ }+ seen.add(value);+ options.push({+ value,+ label: value,+ icon: <CategoryIcon category={value} className="size-4" />,+ });+ }+ return options;+ }, [catalog]);++ const filtered = useMemo(+ () =>+ applyFilter(+ catalog,+ { search, kind: 'skill', category, view },+ { favoritedIds: favoriteKeys },+ ),+ [catalog, search, category, view, favoriteKeys],+ );++ const applySkillsSelection = useCallback(+ (next: string[]) => {+ const current = (getValues('skills') ?? []) as string[];+ setValue('skills', next, { shouldDirty: true });+ const flag = skillsEnabledTransition(current, next, getValues('skills_enabled'));+ if (flag !== undefined) {+ setValue('skills_enabled', flag, { shouldDirty: true });+ }+ },+ [getValues, setValue],+ );++ const handleSkillCreated = useCallback(+ (skill: TSkill) => {+ const current = (getValues('skills') ?? []) as string[];+ applySkillsSelection(Array.from(new Set([...current, skill._id])));+ setView('mine');+ },+ [getValues, applySkillsSelection],+ );++ const handleToggle = useCallback(+ (item: AgentItem) => {+ const current = (getValues('skills') ?? []) as string[];+ if (selectedIds.has(itemKey(item))) {+ applySkillsSelection(current.filter((id) => id !== item.id));+ return;+ }+ applySkillsSelection(Array.from(new Set([...current, item.id])));+ },+ [getValues, applySkillsSelection, selectedIds],+ );++ const viewOptions = useMemo(+ () => VIEWS.map((option) => ({ value: option.value, label: localize(option.labelKey) })),+ [localize],+ );++ const emptyKey: TranslationKeys | undefined =+ !search.trim() && category === 'all' && view === 'marketplace'+ ? 'com_ui_no_skills_found'+ : undefined;++ return (+ <OGDialog open={open} onOpenChange={onOpenChange}>+ <OGDialogContent className="w-11/12 max-w-[900px] overflow-hidden rounded-2xl border-border-medium p-0 shadow-xl md:max-h-[92vh]">+ <OGDialogDescription className="sr-only">+ {localize('com_ui_skills_dialog_description')}+ </OGDialogDescription>+ <div className="flex h-[80vh] max-h-[760px] flex-col">+ <div className="flex flex-col gap-3 border-b border-border-light px-6 pb-4 pt-5">+ <div className="flex items-center gap-2 pr-10">+ <OGDialogTitle className="text-base font-semibold text-text-primary">+ {localize('com_ui_skills')}+ </OGDialogTitle>+ </div>++ <div className="flex items-center gap-2">+ {hasCreateAccess && (+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => setCreateOpen(true)}+ aria-label={localize('com_ui_create_skill')}+ className="h-[42px] w-[42px] shrink-0 p-0"+ >+ <Plus className="size-4" aria-hidden="true" />+ </Button>+ )}+ <div className="relative min-w-0 flex-1">+ <Search+ className="pointer-events-none absolute left-3 top-1/2 z-[1] size-4 -translate-y-1/2 text-text-tertiary"+ aria-hidden="true"+ />+ <Input+ type="text"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={localize('com_ui_search_skills')}+ aria-label={localize('com_ui_search_skills')}+ className="h-[42px] bg-transparent pl-9"+ />+ </div>+ <CategoryFilter options={categoryOptions} value={category} onChange={setCategory} />+ <label id="skills-view-label" className="sr-only">+ {localize('com_ui_skills_filter')}+ </label>+ <Radio+ options={viewOptions}+ value={view}+ onChange={(value) => {+ setView(value as SkillView);+ setCategory('all');+ }}+ className="flex-shrink-0 p-1"+ aria-labelledby="skills-view-label"+ />+ </div>+ </div>++ <div className="flex-1 overflow-y-auto px-6 py-4">+ <MarketplaceCatalog+ items={filtered}+ selectedIds={selectedIds}+ onToggle={handleToggle}+ onConfigure={setDetailItem}+ view={view}+ isLoadingSkills={isLoadingSkills}+ skillsInView={view !== 'mine'}+ favoriteKeys={favoriteKeys}+ onToggleFavorite={toggleFavorite}+ emptyKey={emptyKey}+ ariaLabel={localize('com_ui_skills')}+ />+ </div>+ </div>+ <ItemDialog item={detailItem} agentId={agentId} onClose={() => setDetailItem(null)} />+ <CreateSkillDialog+ isOpen={createOpen}+ setIsOpen={setCreateOpen}+ onCreated={handleSkillCreated}+ />+ </OGDialogContent>+ </OGDialog>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ToolCard.tsx b/client/src/components/SidePanel/Agents/Tools/ToolCard.tsxnew file mode 100644index 0000000000..6bb5779db6--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ToolCard.tsx@@ -0,0 +1,243 @@+import { memo, useState } from 'react';+import { BadgeCheck, Check, Globe, Info, Settings, Star, User } from 'lucide-react';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { AgentItem } from './items/types';+import { hasConfigurableSettings } from './items/configurable';+import { useLocalize, useAuthContext } from '~/hooks';+import { getIconForItem } from './items/icons';+import { cn } from '~/utils';++interface ToolCardProps {+ item: AgentItem;+ selected: boolean;+ onToggle: (item: AgentItem) => void;+ onConfigure?: (item: AgentItem) => void;+ isFavorited?: boolean;+ onToggleFavorite?: (item: AgentItem) => void;+}++function useDisplayStrings(item: AgentItem): { name: string; description: string } {+ const localize = useLocalize();+ if (item.kind === 'builtin') {+ return {+ name: localize(item.name as TranslationKeys),+ description: item.description ? localize(item.description as TranslationKeys) : '',+ };+ }+ return { name: item.name, description: item.description ?? '' };+}++const KIND_LABEL_KEYS: Record<AgentItem['kind'], TranslationKeys> = {+ builtin: 'com_ui_tools_kind_official',+ tool: 'com_ui_tools_kind_tools',+ skill: 'com_ui_tools_kind_skills',+ mcp: 'com_ui_tools_kind_mcp',+ action: 'com_ui_tools_kind_actions',+};++interface ItemIconProps {+ item: AgentItem;+ size: 'sm' | 'md';+}++function ItemIconView({ item, size }: ItemIconProps) {+ const { Icon, colorClass, iconUrl } = getIconForItem(item);+ const [imgError, setImgError] = useState(false);++ const tileClasses =+ size === 'md' ? 'h-10 w-10 rounded-xl text-base' : 'h-9 w-9 rounded-lg text-sm';+ const iconClasses = size === 'md' ? 'h-[18px] w-[18px]' : 'h-[18px] w-[18px]';++ if (iconUrl && !imgError) {+ return (+ <span+ className={cn(+ 'flex shrink-0 items-center justify-center overflow-hidden bg-white',+ tileClasses,+ )}+ aria-hidden="true"+ >+ <img+ src={iconUrl}+ alt=""+ className="h-full w-full object-cover"+ loading="lazy"+ onError={() => setImgError(true)}+ />+ </span>+ );+ }++ return (+ <span+ className={cn('flex shrink-0 items-center justify-center', tileClasses, colorClass)}+ aria-hidden="true"+ >+ <Icon className={iconClasses} strokeWidth={1.75} />+ </span>+ );+}++function ToolCardImpl({+ item,+ selected,+ onToggle,+ onConfigure,+ isFavorited = false,+ onToggleFavorite,+}: ToolCardProps) {+ const localize = useLocalize();+ const { name, description } = useDisplayStrings(item);+ const { user } = useAuthContext();+ const isNative = item.kind === 'builtin';+ const kindLabel = localize(KIND_LABEL_KEYS[item.kind]);+ const canFavorite = onToggleFavorite !== undefined && item.kind !== 'action';+ const canConfigure = hasConfigurableSettings(item) && onConfigure !== undefined;+ const skill = item.kind === 'skill' ? item.skill : undefined;+ const isPublicSkill = skill?.isPublic === true;+ const isSharedSkill = skill != null && skill.author !== user?.id && Boolean(skill.authorName);+ const showInfoOnly =+ item.kind === 'builtin' &&+ item.id === 'web_search' &&+ !canConfigure &&+ onConfigure !== undefined;+ const DetailIcon = canConfigure ? Settings : Info;++ return (+ <div+ className={cn(+ 'group relative flex h-32 w-full flex-col overflow-hidden rounded-2xl border',+ selected+ ? 'border-emerald-500/60 bg-emerald-500/[0.06] shadow-sm'+ : 'border-border-light bg-transparent hover:border-border-medium hover:bg-surface-tertiary hover:shadow-sm',+ )}+ >+ <button+ type="button"+ onClick={() => onToggle(item)}+ aria-pressed={selected}+ className={cn(+ 'flex h-full w-full cursor-pointer flex-col gap-2 rounded-2xl p-4 text-left',+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',+ )}+ >+ <div className="flex w-full items-start gap-3">+ <ItemIconView item={item} size="md" />+ <div className="min-w-0 flex-1">+ <div className="flex items-start gap-1.5">+ <p className="flex min-w-0 flex-1 items-center gap-1 text-sm font-semibold text-text-primary">+ <span className="truncate">{name}</span>+ {isNative && (+ <BadgeCheck+ className="size-4 shrink-0 fill-emerald-500 text-white dark:text-surface-primary"+ strokeWidth={2}+ aria-label={localize('com_ui_tools_native')}+ />+ )}+ </p>+ {selected && (+ <span+ className="flex size-5 shrink-0 items-center justify-center rounded-full bg-emerald-500 text-white"+ aria-hidden="true"+ >+ <Check className="size-3" strokeWidth={3} />+ </span>+ )}+ </div>+ <p className="truncate text-[11px] uppercase tracking-wide text-text-secondary">+ {kindLabel}+ </p>+ </div>+ </div>+ {description ? (+ <p className="line-clamp-3 text-xs leading-snug text-text-secondary">{description}</p>+ ) : (+ <p className="line-clamp-3 text-xs italic leading-snug text-text-tertiary">+ {isNative ? localize('com_ui_tools_native_short') : kindLabel}+ </p>+ )}+ {(item.kind === 'action' && item.endpointCount > 0) || isPublicSkill || isSharedSkill ? (+ <div className="mt-auto flex w-full flex-wrap items-center gap-1.5">+ {item.kind === 'action' && item.endpointCount > 0 && (+ <span className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-2 py-0.5 text-[10px] text-text-tertiary">+ {localize(+ item.endpointCount === 1+ ? 'com_ui_tools_endpoint_count_one'+ : 'com_ui_tools_endpoint_count',+ { count: item.endpointCount },+ )}+ </span>+ )}+ {isSharedSkill && skill && (+ <span+ className="inline-flex max-w-[60%] items-center gap-1 rounded-full bg-surface-tertiary px-2 py-0.5 text-[10px] text-text-tertiary"+ title={localize('com_ui_tools_shared_by', { name: skill.authorName })}+ aria-label={localize('com_ui_tools_shared_by', { name: skill.authorName })}+ >+ <User className="size-2.5 shrink-0" aria-hidden="true" />+ <span className="truncate">{skill.authorName}</span>+ </span>+ )}+ {isPublicSkill && (+ <span+ className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-1.5 py-0.5 text-[10px] text-text-tertiary"+ title={localize('com_ui_sr_public_skill')}+ aria-label={localize('com_ui_sr_public_skill')}+ >+ <Globe className="size-2.5" aria-hidden="true" />+ </span>+ )}+ </div>+ ) : null}+ </button>+ {(canFavorite || canConfigure || showInfoOnly) && (+ <div className="absolute bottom-2 right-2 flex items-center gap-1">+ {(canConfigure || showInfoOnly) && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onConfigure?.(item);+ }}+ aria-label={+ canConfigure ? localize('com_ui_tools_configure') : localize('com_ui_tools_info')+ }+ className={cn(+ 'flex size-7 items-center justify-center rounded-lg text-text-secondary',+ 'opacity-0 transition duration-150 hover:bg-surface-hover hover:text-text-primary',+ 'group-focus-within:opacity-100 group-hover:opacity-100',+ 'focus:outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring-primary',+ )}+ >+ <DetailIcon className="size-4" aria-hidden="true" />+ </button>+ )}+ {canFavorite && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onToggleFavorite?.(item);+ }}+ aria-pressed={isFavorited}+ aria-label={localize(isFavorited ? 'com_ui_unfavorite' : 'com_ui_favorite')}+ className={cn(+ 'flex size-7 items-center justify-center rounded-lg text-text-secondary',+ 'opacity-0 transition duration-150 hover:bg-surface-hover hover:text-text-primary',+ 'group-focus-within:opacity-100 group-hover:opacity-100',+ 'focus:outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring-primary',+ isFavorited &&+ 'text-amber-600 opacity-100 hover:text-amber-500 dark:text-amber-500 dark:hover:text-amber-400',+ )}+ >+ <Star className={cn('size-4', isFavorited && 'fill-current')} aria-hidden="true" />+ </button>+ )}+ </div>+ )}+ </div>+ );+}++const ToolCard = memo(ToolCardImpl);+export default ToolCard;diff --git a/client/src/components/SidePanel/Agents/Tools/ToolRow.tsx b/client/src/components/SidePanel/Agents/Tools/ToolRow.tsxnew file mode 100644index 0000000000..7c2412674c--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ToolRow.tsx@@ -0,0 +1,113 @@+import { memo, useState } from 'react';+import { Info, Settings, X } from 'lucide-react';+import type { TranslationKeys } from '~/hooks/useLocalize';+import type { AgentItem } from './items/types';+import { hasConfigurableSettings } from './items/configurable';+import { getIconForItem } from './items/icons';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++interface Props {+ item: AgentItem;+ onInfo: (item: AgentItem) => void;+ onRemove: (item: AgentItem) => void;+}++function getSuffix(item: AgentItem): string | null {+ if (item.kind === 'mcp' && item.toolCount > 0) return `· ${item.toolCount}`;+ if (item.kind === 'action' && item.endpointCount > 0) return `· ${item.endpointCount}`;+ return null;+}++function RowIcon({ item }: { item: AgentItem }) {+ const { Icon, colorClass, iconUrl } = getIconForItem(item);+ const [imgError, setImgError] = useState(false);++ if (iconUrl && !imgError) {+ return (+ <span+ className="flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-md bg-white"+ aria-hidden="true"+ >+ <img+ src={iconUrl}+ alt=""+ className="h-full w-full object-cover"+ loading="lazy"+ onError={() => setImgError(true)}+ />+ </span>+ );+ }++ return (+ <span+ className={cn('flex size-7 shrink-0 items-center justify-center rounded-md', colorClass)}+ aria-hidden="true"+ >+ <Icon className="size-3.5" strokeWidth={1.75} />+ </span>+ );+}++function ToolRowImpl({ item, onInfo, onRemove }: Props) {+ const localize = useLocalize();+ const suffix = getSuffix(item);+ const displayName = item.kind === 'builtin' ? localize(item.name as TranslationKeys) : item.name;+ const configurable = hasConfigurableSettings(item);+ const DetailIcon = configurable ? Settings : Info;++ return (+ <div className="group relative flex w-full items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-surface-secondary">+ <div className="flex min-w-0 flex-1 items-center gap-2.5">+ <RowIcon item={item} />+ <span className="flex min-w-0 items-center gap-1 truncate text-sm text-text-primary">+ <span className="truncate font-medium">{displayName}</span>+ {suffix && <span className="text-text-secondary">{suffix}</span>}+ </span>+ </div>+ {item.status === 'needs_setup' && (+ <span role="status" className="flex shrink-0 items-center">+ <span className="size-1.5 rounded-full bg-red-500" aria-hidden="true" />+ <span className="sr-only">{localize('com_ui_tools_needs_setup')}</span>+ </span>+ )}+ <div+ className={cn(+ 'flex shrink-0 items-center gap-0.5 opacity-0',+ 'group-focus-within:opacity-100 group-hover:opacity-100',+ )}+ >+ <button+ type="button"+ onClick={() => onInfo(item)}+ aria-label={+ configurable ? localize('com_ui_tools_configure') : localize('com_ui_tools_info')+ }+ className={cn(+ 'flex size-6 items-center justify-center rounded-md text-text-secondary',+ 'hover:bg-surface-hover hover:text-text-primary',+ 'focus:outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring-primary',+ )}+ >+ <DetailIcon className="size-3.5" aria-hidden="true" />+ </button>+ <button+ type="button"+ onClick={() => onRemove(item)}+ aria-label={localize('com_ui_tools_remove')}+ className={cn(+ 'flex size-6 items-center justify-center rounded-md text-text-secondary',+ 'hover:bg-surface-hover hover:text-text-primary',+ 'focus:outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring-primary',+ )}+ >+ <X className="size-3.5" aria-hidden="true" />+ </button>+ </div>+ </div>+ );+}++const ToolRow = memo(ToolRowImpl);+export default ToolRow;diff --git a/client/src/components/SidePanel/Agents/Tools/ToolsMarketplaceDialog.tsx b/client/src/components/SidePanel/Agents/Tools/ToolsMarketplaceDialog.tsxnew file mode 100644index 0000000000..a1427b10f0--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ToolsMarketplaceDialog.tsx@@ -0,0 +1,234 @@+import { useState, useMemo, useCallback } from 'react';+import { Search } from 'lucide-react';+import { useFormContext } from 'react-hook-form';+import {+ Input,+ OGDialog,+ OGDialogTitle,+ OGDialogContent,+ OGDialogDescription,+ useToastContext,+} from '@librechat/client';+import type { AgentItem, AgentItemKind, ItemFilter } from './items/types';+import type { AgentForm } from '~/common';+import { itemKey, mcpServerToken, matchesMcpServer } from './items/selectors';+import { useAgentItems, useUninstallToolCredentials } from './hooks';+import AddMcpServerDialog from './ItemDialog/AddMcpServerDialog';+import { computeToggleAction } from './items/mutations';+import { useLocalize, useToolFavorites } from '~/hooks';+import MarketplaceSidebar from './MarketplaceSidebar';+import MarketplaceCatalog from './MarketplaceCatalog';+import ItemDialog from './ItemDialog/ItemDialog';+import { applyFilter } from './items/filtering';+import { NEW_ACTION_ID } from './items/types';+import { isEphemeralAgent } from '~/common';++interface ToolsMarketplaceDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ agentId: string;+}++type View = NonNullable<ItemFilter['view']>;+type Kind = AgentItemKind | 'all';++export default function ToolsMarketplaceDialog({+ open,+ onOpenChange,+ agentId,+}: ToolsMarketplaceDialogProps) {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const { getValues, setValue } = useFormContext<AgentForm>();+ const uninstallToolCredentials = useUninstallToolCredentials();++ /** Skills are excluded here — they have their own picker (`SkillsDialog`). */+ const { catalog, selected: selectedItems } = useAgentItems({ agentId });++ const { favoriteKeys, toggle: toggleFavorite } = useToolFavorites();++ const [view, setView] = useState<View>('marketplace');+ const [kind, setKind] = useState<Kind>('all');+ const [search, setSearch] = useState('');+ const [detailItem, setDetailItem] = useState<AgentItem | null>(null);+ const [addMcpOpen, setAddMcpOpen] = useState(false);++ const handleCreateNew = useCallback(+ (createKind: 'mcp' | 'action') => {+ if (createKind === 'mcp') {+ setAddMcpOpen(true);+ return;+ }+ /** Actions are persisted against the agent id, so an unsaved agent has+ * nothing to attach them to — surface the save-first error instead of+ * letting the editor fail on submit. */+ if (isEphemeralAgent(agentId)) {+ showToast({ message: localize('com_agents_no_agent_id_error'), status: 'error' });+ return;+ }+ setDetailItem({+ kind: 'action',+ id: NEW_ACTION_ID,+ name: localize('com_ui_new_action'),+ description: '',+ iconKey: 'action',+ endpointCount: 0,+ });+ },+ [agentId, localize, showToast],+ );++ const selectedIds = useMemo(() => new Set(selectedItems.map(itemKey)), [selectedItems]);++ const counts = useMemo(+ () => ({+ builtin: catalog.filter((i) => i.kind === 'builtin').length,+ tool: catalog.filter((i) => i.kind === 'tool').length,+ mcp: catalog.filter((i) => i.kind === 'mcp').length,+ skill: 0,+ action: catalog.filter((i) => i.kind === 'action').length,+ }),+ [catalog],+ );++ const filtered = useMemo(+ () =>+ applyFilter(catalog, { search, kind, category: 'all', view }, { favoritedIds: favoriteKeys }),+ [catalog, search, kind, view, favoriteKeys],+ );++ const handleToggle = useCallback(+ (item: AgentItem) => {+ const patch = computeToggleAction(item, { selected: selectedIds.has(itemKey(item)) });+ switch (patch.type) {+ case 'builtin':+ setValue(patch.field as keyof AgentForm, patch.value as never, { shouldDirty: true });+ break;+ case 'tool-add': {+ const current = (getValues('tools') ?? []) as string[];+ setValue('tools', Array.from(new Set([...current, patch.id])), { shouldDirty: true });+ break;+ }+ case 'tool-remove': {+ const current = (getValues('tools') ?? []) as string[];+ setValue(+ 'tools',+ current.filter((t) => t !== patch.id),+ { shouldDirty: true },+ );+ uninstallToolCredentials(patch.id);+ break;+ }+ case 'mcp-add': {+ if (item.kind !== 'mcp') break;+ const toolIds = (item.server.tools ?? []).map((t) => t.tool_id);+ const current = (getValues('tools') ?? []) as string[];+ setValue(+ 'tools',+ Array.from(new Set([...current, mcpServerToken(item.id), ...toolIds])),+ { shouldDirty: true },+ );+ break;+ }+ case 'mcp-remove': {+ if (item.kind !== 'mcp') break;+ const toolIds = new Set((item.server.tools ?? []).map((t) => t.tool_id));+ const current = (getValues('tools') ?? []) as string[];+ setValue(+ 'tools',+ current.filter((t) => !matchesMcpServer(t, item.id) && !toolIds.has(t)),+ { shouldDirty: true },+ );+ break;+ }+ default:+ break;+ }+ },+ [getValues, setValue, selectedIds, uninstallToolCredentials],+ );++ const handleCardClick = useCallback(+ (item: AgentItem) => {+ /** Actions have no simple enable toggle — clicking always opens the editor. */+ if (item.kind === 'action') {+ setDetailItem(item);+ return;+ }+ if (item.kind === 'builtin' && item.id === 'context') {+ setDetailItem(item);+ return;+ }+ /** An MCP server with no exposed tools yet can't be enabled in place — open+ * its dialog so it can be connected/configured first. */+ if (item.kind === 'mcp' && item.toolCount === 0) {+ setDetailItem(item);+ return;+ }+ const wasSelected = selectedIds.has(itemKey(item));+ if (!wasSelected && item.status === 'needs_setup') {+ setDetailItem(item);+ return;+ }+ handleToggle(item);+ },+ [handleToggle, selectedIds],+ );++ const handleConfigure = useCallback((item: AgentItem) => {+ setDetailItem(item);+ }, []);++ return (+ <OGDialog open={open} onOpenChange={onOpenChange}>+ <OGDialogContent className="w-11/12 max-w-[1200px] overflow-hidden rounded-2xl border-border-medium p-0 shadow-xl md:max-h-[92vh]">+ <OGDialogTitle className="sr-only">{localize('com_ui_tools_marketplace')}</OGDialogTitle>+ <OGDialogDescription className="sr-only">+ {localize('com_ui_tools_marketplace_description')}+ </OGDialogDescription>+ <div className="flex h-[88vh] max-h-[840px]">+ <MarketplaceSidebar+ activeView={view}+ activeKind={kind}+ onSelectView={setView}+ onSelectKind={setKind}+ counts={counts}+ totalCount={catalog.length}+ onCreateNew={handleCreateNew}+ />+ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex items-center gap-2 px-6 py-4 pr-12">+ <div className="relative flex-1">+ <Search+ className="pointer-events-none absolute left-3 top-1/2 z-[1] size-4 -translate-y-1/2 text-text-tertiary"+ aria-hidden="true"+ />+ <Input+ type="text"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder={localize('com_ui_tools_marketplace_search')}+ aria-label={localize('com_ui_tools_marketplace_search')}+ className="bg-transparent pl-9"+ />+ </div>+ </div>+ <div className="flex-1 overflow-y-auto p-4">+ <MarketplaceCatalog+ items={filtered}+ selectedIds={selectedIds}+ onToggle={handleCardClick}+ onConfigure={handleConfigure}+ view={view}+ favoriteKeys={favoriteKeys}+ onToggleFavorite={toggleFavorite}+ />+ </div>+ </div>+ </div>+ <ItemDialog item={detailItem} agentId={agentId} onClose={() => setDetailItem(null)} />+ <AddMcpServerDialog open={addMcpOpen} onOpenChange={setAddMcpOpen} />+ </OGDialogContent>+ </OGDialog>+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx b/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsxnew file mode 100644index 0000000000..901953f855--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/ToolsSection.tsx@@ -0,0 +1,368 @@+import { useState, useMemo, useCallback } from 'react';+import { Plus } from 'lucide-react';+import { useFormContext } from 'react-hook-form';+import { Label, OGDialog, OGDialogTemplate, useToastContext } from '@librechat/client';+import { PermissionTypes, Permissions, AgentCapabilities } from 'librechat-data-provider';+import type { TPlugin } from 'librechat-data-provider';+import type { AgentItem } from './items/types';+import type { AgentForm } from '~/common';+import {+ useAgentItems,+ useResolvedSkills,+ useAgentFileEntries,+ useUninstallToolCredentials,+} from './hooks';+import { computeToggleAction, skillsEnabledTransition } from './items/mutations';+import { useListSkillsQuery, useDeleteAgentAction } from '~/data-provider';+import { useRemoveMCPTool, useVisibleTools } from '~/hooks/MCP';+import ToolsMarketplaceDialog from './ToolsMarketplaceDialog';+import { useLocalize, useHasAccess } from '~/hooks';+import { useAgentPanelContext } from '~/Providers';+import ItemDialog from './ItemDialog/ItemDialog';+import { isEphemeralAgent } from '~/common';+import SkillsDialog from './SkillsDialog';+import ToolRow from './ToolRow';++interface Props {+ agentId: string;+}++export default function ToolsSection({ agentId }: Props) {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const [open, setOpen] = useState(false);+ const [skillsOpen, setSkillsOpen] = useState(false);+ const [dialogItem, setDialogItem] = useState<AgentItem | null>(null);+ const [pendingActionRemoval, setPendingActionRemoval] = useState<string | null>(null);+ const [pendingMcpRemoval, setPendingMcpRemoval] = useState<string | null>(null);++ const { getValues, setValue } = useFormContext<AgentForm>();+ const { agentsConfig, regularTools, mcpServersMap } = useAgentPanelContext();+ const { removeTool: removeMCPTool } = useRemoveMCPTool();+ const deleteAgentAction = useDeleteAgentAction({+ onSuccess: () => {+ showToast({+ message: localize('com_assistants_delete_actions_success'),+ status: 'success',+ });+ },+ onError: (error) => {+ showToast({+ message: (error as Error).message || localize('com_assistants_delete_actions_error'),+ status: 'error',+ });+ },+ });++ const hasSkillsAccess = useHasAccess({+ permissionType: PermissionTypes.SKILLS,+ permission: Permissions.USE,+ });+ const skillsEnabled = useMemo(+ () => agentsConfig?.capabilities?.includes(AgentCapabilities.skills) ?? false,+ [agentsConfig],+ );+ const showSkills = hasSkillsAccess && skillsEnabled;+ const { data: skillsData } = useListSkillsQuery({ limit: 100 }, { enabled: showSkills });+ const resolvedSkills = useResolvedSkills(skillsData?.skills);++ const uninstallToolCredentials = useUninstallToolCredentials();+ const { knowledgeFiles, codeFiles } = useAgentFileEntries();++ const { selected, tools } = useAgentItems({+ agentId,+ skills: resolvedSkills,+ skillsPermission: showSkills,+ });++ /** File-backed built-ins stay selected while they hold files, so flipping+ * the capability flag off would leave the row visible. Route their removal+ * to the config dialog (where files are managed) instead, mirroring the+ * file-only `context` built-in. */+ const opensFileManagerOnRemove = useCallback(+ (item: AgentItem): boolean => {+ if (item.kind !== 'builtin') {+ return false;+ }+ if (item.id === 'context') {+ return true;+ }+ if (item.id === 'execute_code') {+ return codeFiles.length > 0;+ }+ if (item.id === 'file_search') {+ return knowledgeFiles.length > 0;+ }+ return false;+ },+ [codeFiles, knowledgeFiles],+ );++ const handleQuickRemove = useCallback(+ (item: AgentItem) => {+ if (opensFileManagerOnRemove(item)) {+ setDialogItem(item);+ return;+ }+ const patch = computeToggleAction(item, { selected: true });+ switch (patch.type) {+ case 'builtin':+ setValue(patch.field as keyof AgentForm, patch.value as never, { shouldDirty: true });+ break;+ case 'tool-remove': {+ const current = (getValues('tools') ?? []) as string[];+ setValue(+ 'tools',+ current.filter((t) => t !== patch.id),+ { shouldDirty: true },+ );+ uninstallToolCredentials(patch.id);+ break;+ }+ case 'skill-remove': {+ const current = (getValues('skills') ?? []) as string[];+ const next = current.filter((s) => s !== patch.id);+ setValue('skills', next, { shouldDirty: true });+ const flag = skillsEnabledTransition(current, next, getValues('skills_enabled'));+ if (flag !== undefined) {+ setValue('skills_enabled', flag, { shouldDirty: true });+ }+ break;+ }+ case 'mcp-remove':+ setPendingMcpRemoval(patch.serverName);+ break;+ case 'action-remove':+ setPendingActionRemoval(patch.actionId);+ break;+ default:+ break;+ }+ },+ [getValues, setValue, uninstallToolCredentials, opensFileManagerOnRemove],+ );++ const confirmMcpRemoval = useCallback(() => {+ if (pendingMcpRemoval == null) {+ return;+ }+ removeMCPTool(pendingMcpRemoval);+ setPendingMcpRemoval(null);+ }, [pendingMcpRemoval, removeMCPTool]);++ const confirmActionRemoval = useCallback(() => {+ if (pendingActionRemoval == null) {+ return;+ }+ if (isEphemeralAgent(agentId)) {+ showToast({+ message: localize('com_agents_no_agent_id_error'),+ status: 'error',+ });+ setPendingActionRemoval(null);+ return;+ }+ deleteAgentAction.mutate({ action_id: pendingActionRemoval, agent_id: agentId });+ setPendingActionRemoval(null);+ }, [pendingActionRemoval, agentId, deleteAgentAction, showToast, localize]);++ const { mcpServerNames: attachedMcpServers } = useVisibleTools(+ tools,+ regularTools ?? undefined,+ mcpServersMap ?? new Map(),+ );++ /** MCP servers still referenced by the agent's tools but absent from the available+ * servers map (removed from config, or a legacy server-only token). The catalog is+ * built from available servers, so these would otherwise be invisible and+ * unremovable — surface them as removable "needs setup" rows, mirroring the old+ * UnconfiguredMCPTool. */+ const orphanedMcpItems = useMemo<AgentItem[]>(+ () =>+ attachedMcpServers+ .filter((name) => mcpServersMap?.has(name) !== true)+ .map((name) => ({+ kind: 'mcp',+ id: name,+ name,+ description: '',+ iconKey: 'mcp',+ status: 'needs_setup',+ toolCount: 0,+ server: {+ serverName: name,+ tools: [],+ isConfigured: false,+ isConnected: false,+ metadata: { name, pluginKey: name, description: '' } as TPlugin,+ },+ })),+ [attachedMcpServers, mcpServersMap],+ );++ /** MCP rows show how many of the server's tools are enabled for this agent, not+ * the total the server exposes, so the count reflects what the agent can use. */+ const toolItems = useMemo(() => {+ const enabled = new Set(tools);+ const withCounts = selected+ .filter((item) => item.kind !== 'skill')+ .map((item) =>+ item.kind === 'mcp'+ ? {+ ...item,+ toolCount: (item.server.tools ?? []).filter((t) => enabled.has(t.tool_id)).length,+ }+ : item,+ );+ return [...withCounts, ...orphanedMcpItems];+ }, [selected, orphanedMcpItems, tools]);+ const skillItems = useMemo(() => selected.filter((item) => item.kind === 'skill'), [selected]);++ return (+ <>+ <SelectedSection+ title={localize('com_ui_tools_section_title')}+ addLabel={localize('com_ui_add_tools')}+ emptyLabel={localize('com_ui_tools_empty')}+ emptyHint={localize('com_ui_tools_empty_hint')}+ items={toolItems}+ onAdd={() => setOpen(true)}+ onInfo={setDialogItem}+ 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')}+ items={skillItems}+ onAdd={() => setSkillsOpen(true)}+ onInfo={setDialogItem}+ onRemove={handleQuickRemove}+ />+ )}+ {open && <ToolsMarketplaceDialog open={open} onOpenChange={setOpen} agentId={agentId} />}+ {skillsOpen && (+ <SkillsDialog open={skillsOpen} onOpenChange={setSkillsOpen} agentId={agentId} />+ )}+ <ItemDialog item={dialogItem} agentId={agentId} onClose={() => setDialogItem(null)} />+ <OGDialog+ open={pendingActionRemoval != null}+ onOpenChange={(value) => {+ if (!value) {+ setPendingActionRemoval(null);+ }+ }}+ >+ <OGDialogTemplate+ showCloseButton={false}+ title={localize('com_ui_delete_action')}+ className="max-w-[450px]"+ main={+ <Label className="text-left text-sm font-medium">+ {localize('com_ui_delete_action_confirm')}+ </Label>+ }+ selection={{+ selectHandler: confirmActionRemoval,+ selectClasses:+ 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',+ selectText: localize('com_ui_delete'),+ }}+ />+ </OGDialog>+ <OGDialog+ open={pendingMcpRemoval != null}+ onOpenChange={(value) => {+ if (!value) {+ setPendingMcpRemoval(null);+ }+ }}+ >+ <OGDialogTemplate+ showCloseButton={false}+ title={localize('com_ui_delete_tool')}+ className="max-w-[450px]"+ main={+ <Label className="text-left text-sm font-medium">+ {localize('com_ui_delete_tool_confirm')}+ </Label>+ }+ selection={{+ selectHandler: confirmMcpRemoval,+ selectClasses:+ 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',+ selectText: localize('com_ui_delete'),+ }}+ />+ </OGDialog>+ </>+ );+}++interface SelectedSectionProps {+ title: string;+ addLabel: string;+ emptyLabel: string;+ emptyHint: string;+ items: AgentItem[];+ onAdd: () => void;+ onInfo: (item: AgentItem) => void;+ onRemove: (item: AgentItem) => void;+}++function SelectedSection({+ title,+ addLabel,+ emptyLabel,+ emptyHint,+ items,+ onAdd,+ onInfo,+ onRemove,+}: SelectedSectionProps) {+ const localize = useLocalize();+ return (+ <div className="mb-3 flex flex-col">+ <div className="mb-1 flex items-center justify-between">+ <label className="block text-[11px] font-medium uppercase tracking-wide text-text-secondary">+ {title}+ {items.length > 0 && (+ <span className="ml-1.5 inline-flex h-4 min-w-[16px] items-center justify-center rounded-full bg-surface-tertiary px-1.5 text-[10px] font-medium normal-case tracking-normal text-text-secondary">+ {items.length}+ </span>+ )}+ </label>+ <button+ type="button"+ onClick={onAdd}+ aria-label={addLabel}+ className="inline-flex h-7 items-center gap-1.5 rounded-lg px-2 text-xs font-medium text-text-secondary transition-colors 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>+ {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__/MarketplaceCatalog.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/MarketplaceCatalog.spec.tsxnew file mode 100644index 0000000000..f2ba35325b--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/MarketplaceCatalog.spec.tsx@@ -0,0 +1,60 @@+import '@testing-library/jest-dom/extend-expect';+import { fireEvent, render, screen } from '@testing-library/react';+import type { AgentItem } from '../items/types';+import MarketplaceCatalog from '../MarketplaceCatalog';+import { itemKey } from '../items/selectors';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useAuthContext: () => ({ user: { id: 'u1' } }),+}));++const items: AgentItem[] = [+ {+ kind: 'builtin',+ id: 'execute_code',+ name: 'Code',+ description: 'Run',+ iconKey: 'execute_code',+ },+ {+ kind: 'tool',+ id: 'dalle',+ name: 'DALL-E',+ description: 'Images',+ iconKey: 'tool',+ plugin: { pluginKey: 'dalle' } as never,+ },+];++describe('MarketplaceCatalog', () => {+ test('renders one card per item', () => {+ render(<MarketplaceCatalog items={items} selectedIds={new Set()} onToggle={jest.fn()} />);+ expect(screen.getByText('Code')).toBeInTheDocument();+ expect(screen.getByText('DALL-E')).toBeInTheDocument();+ });++ test('clicking a card calls onToggle with the item', () => {+ const onToggle = jest.fn();+ render(<MarketplaceCatalog items={items} selectedIds={new Set()} onToggle={onToggle} />);+ fireEvent.click(screen.getByRole('button', { name: /DALL-E/ }));+ expect(onToggle).toHaveBeenCalledWith(items[1]);+ });++ test('selected ids mark cards aria-pressed=true', () => {+ render(+ <MarketplaceCatalog+ items={items}+ selectedIds={new Set([itemKey(items[1])])}+ onToggle={jest.fn()}+ />,+ );+ expect(screen.getByRole('button', { name: /DALL-E/ })).toHaveAttribute('aria-pressed', 'true');+ expect(screen.getByRole('button', { name: /^Code/ })).toHaveAttribute('aria-pressed', 'false');+ });++ test('empty catalog shows "no results" message', () => {+ render(<MarketplaceCatalog items={[]} selectedIds={new Set()} onToggle={jest.fn()} />);+ expect(screen.getByText('com_ui_tools_search_no_results')).toBeInTheDocument();+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/MarketplaceSidebar.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/MarketplaceSidebar.spec.tsxnew file mode 100644index 0000000000..ef175f86f1--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/MarketplaceSidebar.spec.tsx@@ -0,0 +1,151 @@+import React from 'react';+import '@testing-library/jest-dom/extend-expect';+import { fireEvent, render, screen } from '@testing-library/react';+import MarketplaceSidebar from '../MarketplaceSidebar';++let mockHasMcpCreateAccess = true;+let mockCapabilities: string[] = ['actions'];++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useHasAccess: () => mockHasMcpCreateAccess,+}));++jest.mock('~/Providers', () => ({+ useAgentPanelContext: () => ({ agentsConfig: { capabilities: mockCapabilities } }),+}));++jest.mock('@ariakit/react/menu', () => ({+ MenuButton: ({ render: rendered }: { render: React.ReactNode }) => rendered,+}));++jest.mock('@librechat/client', () => {+ const ReactActual = jest.requireActual('react');+ return {+ Button: ({ children, ...rest }: React.ComponentProps<'button'>) =>+ ReactActual.createElement('button', { type: 'button', ...rest }, children),+ DropdownPopup: ({+ trigger,+ items,+ }: {+ trigger: React.ReactNode;+ items: Array<{ label: string; onClick: () => void }>;+ }) =>+ ReactActual.createElement(+ 'div',+ null,+ trigger,+ items.map((item) =>+ ReactActual.createElement(+ 'button',+ {+ key: item.label,+ type: 'button',+ 'data-testid': 'create-item',+ onClick: item.onClick,+ },+ item.label,+ ),+ ),+ ),+ };+});++describe('MarketplaceSidebar', () => {+ const defaultProps = {+ activeView: 'marketplace' as const,+ activeKind: 'all' as const,+ onSelectView: jest.fn(),+ onSelectKind: jest.fn(),+ counts: { tool: 2, skill: 3, mcp: 1, action: 0, builtin: 5 },+ totalCount: 11,+ };++ beforeEach(() => {+ mockHasMcpCreateAccess = true;+ mockCapabilities = ['actions'];+ });++ test('shows the All entry with total count', () => {+ render(<MarketplaceSidebar {...defaultProps} />);+ expect(screen.getByText('com_ui_all_proper')).toBeInTheDocument();+ expect(screen.getByText('11')).toBeInTheDocument();+ });++ test('clicking a kind filter calls onSelectKind', () => {+ const onSelectKind = jest.fn();+ render(<MarketplaceSidebar {...defaultProps} onSelectKind={onSelectKind} />);+ fireEvent.click(screen.getByText('com_ui_tools_kind_tools'));+ expect(onSelectKind).toHaveBeenCalledWith('tool');+ });++ test('does not render a Skills kind filter', () => {+ render(<MarketplaceSidebar {...defaultProps} />);+ expect(screen.queryByText('com_ui_tools_kind_skills')).not.toBeInTheDocument();+ });++ test('clicking favorites switches the view filter', () => {+ const onSelectView = jest.fn();+ render(<MarketplaceSidebar {...defaultProps} onSelectView={onSelectView} />);+ fireEvent.click(screen.getByText('com_ui_tools_view_favorites'));+ expect(onSelectView).toHaveBeenCalledWith('favorites');+ });++ test('clicking All resets both kind and view', () => {+ const onSelectKind = jest.fn();+ const onSelectView = jest.fn();+ render(+ <MarketplaceSidebar+ {...defaultProps}+ activeKind="builtin"+ onSelectKind={onSelectKind}+ onSelectView={onSelectView}+ />,+ );+ fireEvent.click(screen.getByText('com_ui_all_proper'));+ expect(onSelectKind).toHaveBeenCalledWith('all');+ expect(onSelectView).toHaveBeenCalledWith('marketplace');+ });++ describe('create menu gating', () => {+ test('offers MCP and Actions entries when both are permitted', () => {+ render(<MarketplaceSidebar {...defaultProps} onCreateNew={jest.fn()} />);+ expect(screen.getAllByTestId('create-item').map((el) => el.textContent)).toEqual([+ 'com_ui_tools_kind_mcp',+ 'com_ui_tools_kind_actions',+ ]);+ });++ test('clicking a create entry forwards its kind', () => {+ const onCreateNew = jest.fn();+ render(<MarketplaceSidebar {...defaultProps} onCreateNew={onCreateNew} />);+ const [mcpEntry] = screen.getAllByTestId('create-item');+ fireEvent.click(mcpEntry);+ expect(onCreateNew).toHaveBeenCalledWith('mcp');+ });++ test('hides the MCP entry without the MCP create permission', () => {+ mockHasMcpCreateAccess = false;+ render(<MarketplaceSidebar {...defaultProps} onCreateNew={jest.fn()} />);+ expect(screen.getAllByTestId('create-item').map((el) => el.textContent)).toEqual([+ 'com_ui_tools_kind_actions',+ ]);+ });++ test('hides the Actions entry when the actions capability is disabled', () => {+ mockCapabilities = [];+ render(<MarketplaceSidebar {...defaultProps} onCreateNew={jest.fn()} />);+ expect(screen.getAllByTestId('create-item').map((el) => el.textContent)).toEqual([+ 'com_ui_tools_kind_mcp',+ ]);+ });++ test('hides the Create New button entirely when nothing can be created', () => {+ mockHasMcpCreateAccess = false;+ mockCapabilities = [];+ render(<MarketplaceSidebar {...defaultProps} onCreateNew={jest.fn()} />);+ expect(screen.queryByText('com_ui_tools_create_new')).not.toBeInTheDocument();+ expect(screen.queryAllByTestId('create-item')).toHaveLength(0);+ });+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/ToolCard.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolCard.spec.tsxnew file mode 100644index 0000000000..3c45b1abfa--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolCard.spec.tsx@@ -0,0 +1,177 @@+import '@testing-library/jest-dom/extend-expect';+import { fireEvent, render, screen } from '@testing-library/react';+import type { AgentItem } from '../items/types';+import ToolCard from '../ToolCard';++jest.mock('~/hooks', () => ({+ useLocalize:+ () =>+ (key: string, options?: Record<string, unknown>): string => {+ if (!options) return key;+ const parts = Object.entries(options).map(([name, value]) => `${name}=${String(value)}`);+ return `${key}[${parts.join(',')}]`;+ },+ useAuthContext: () => ({ user: { id: 'u1' } }),+}));++const skill: AgentItem = {+ kind: 'skill',+ id: 's1',+ name: 'Reviewer',+ description: 'Review PRs',+ iconKey: 'skill',+ skill: { _id: 's1', name: 'Reviewer' } as never,+};++describe('ToolCard', () => {+ test('renders item name and description', () => {+ render(<ToolCard item={skill} selected={false} onToggle={jest.fn()} />);+ expect(screen.getByText('Reviewer')).toBeInTheDocument();+ expect(screen.getByText('Review PRs')).toBeInTheDocument();+ });++ test('clicking the card invokes onToggle with the item', () => {+ const onToggle = jest.fn();+ render(<ToolCard item={skill} selected={false} onToggle={onToggle} />);+ fireEvent.click(screen.getByRole('button', { name: /Reviewer/ }));+ expect(onToggle).toHaveBeenCalledWith(skill);+ });++ test('selected cards expose aria-pressed=true', () => {+ render(<ToolCard item={skill} selected onToggle={jest.fn()} />);+ expect(screen.getByRole('button', { name: /Reviewer/ })).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );+ });++ test('renders a verified badge for built-ins', () => {+ const builtin: AgentItem = {+ kind: 'builtin',+ id: 'execute_code',+ name: 'Code Interpreter',+ description: 'Run Python',+ iconKey: 'execute_code',+ };+ render(<ToolCard item={builtin} selected={false} onToggle={jest.fn()} />);+ expect(screen.getByLabelText('com_ui_tools_native')).toBeInTheDocument();+ });++ test('does not render the tool-count pill for MCP cards', () => {+ const mcp: AgentItem = {+ kind: 'mcp',+ id: 'everything',+ name: 'Everything',+ description: '',+ iconKey: 'mcp',+ server: { serverName: 'everything', isConfigured: true, tools: [] } as never,+ toolCount: 14,+ };+ render(<ToolCard item={mcp} selected={false} onToggle={jest.fn()} />);+ expect(screen.queryByText('com_ui_tools_count[count=14]')).not.toBeInTheDocument();+ });++ test('renders public and shared-author badges for another user public skill', () => {+ const shared: AgentItem = {+ kind: 'skill',+ id: 's2',+ name: 'Shared',+ description: '',+ iconKey: 'skill',+ skill: {+ _id: 's2',+ name: 'Shared',+ author: 'u2',+ authorName: 'Alice',+ isPublic: true,+ } as never,+ };+ render(<ToolCard item={shared} selected={false} onToggle={jest.fn()} />);+ expect(screen.getByText('Alice')).toBeInTheDocument();+ expect(screen.getByLabelText('com_ui_sr_public_skill')).toBeInTheDocument();+ });++ test('omits the author badge for the current user own skill', () => {+ const own: AgentItem = {+ kind: 'skill',+ id: 's3',+ name: 'Mine',+ description: '',+ iconKey: 'skill',+ skill: { _id: 's3', name: 'Mine', author: 'u1', authorName: 'Me', isPublic: false } as never,+ };+ render(<ToolCard item={own} selected={false} onToggle={jest.fn()} />);+ expect(screen.queryByText('Me')).not.toBeInTheDocument();+ });++ describe('favorite star', () => {+ test('renders with add label and aria-pressed=false when not favorited', () => {+ render(+ <ToolCard+ item={skill}+ selected={false}+ onToggle={jest.fn()}+ onToggleFavorite={jest.fn()}+ />,+ );+ const star = screen.getByRole('button', { name: 'com_ui_favorite' });+ expect(star).toHaveAttribute('aria-pressed', 'false');+ });++ test('clicking the star calls onToggleFavorite without toggling the card', () => {+ const onToggle = jest.fn();+ const onToggleFavorite = jest.fn();+ render(+ <ToolCard+ item={skill}+ selected={false}+ onToggle={onToggle}+ onToggleFavorite={onToggleFavorite}+ />,+ );+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_favorite' }));+ expect(onToggleFavorite).toHaveBeenCalledWith(skill);+ expect(onToggle).not.toHaveBeenCalled();+ });++ test('a favorited card keeps the star visible with the remove label', () => {+ render(+ <ToolCard+ item={skill}+ selected={false}+ onToggle={jest.fn()}+ isFavorited+ onToggleFavorite={jest.fn()}+ />,+ );+ const star = screen.getByRole('button', { name: 'com_ui_unfavorite' });+ expect(star).toHaveAttribute('aria-pressed', 'true');+ expect(star).toHaveClass('opacity-100');+ });++ test('renders no star without an onToggleFavorite handler', () => {+ render(<ToolCard item={skill} selected={false} onToggle={jest.fn()} />);+ expect(screen.queryByRole('button', { name: 'com_ui_favorite' })).not.toBeInTheDocument();+ });++ test('renders no star for action items', () => {+ const action: AgentItem = {+ kind: 'action',+ id: 'a1',+ name: 'My Action',+ description: '',+ iconKey: 'action',+ endpointCount: 0,+ };+ render(+ <ToolCard+ item={action}+ selected={false}+ onToggle={jest.fn()}+ onToggleFavorite={jest.fn()}+ />,+ );+ expect(screen.queryByRole('button', { name: 'com_ui_favorite' })).not.toBeInTheDocument();+ });+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsMarketplaceDialog.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsMarketplaceDialog.spec.tsxnew file mode 100644index 0000000000..404963505e--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsMarketplaceDialog.spec.tsx@@ -0,0 +1,221 @@+import '@testing-library/jest-dom/extend-expect';+import { fireEvent, render, screen } from '@testing-library/react';+import ToolsMarketplaceDialog from '../ToolsMarketplaceDialog';++const mockSetValue = jest.fn();+const mockGetValues = jest.fn(() => []);++jest.mock('react-hook-form', () => ({+ useFormContext: () => ({+ control: {},+ getValues: mockGetValues,+ setValue: mockSetValue,+ }),+ useWatch: ({ name }: { name: string }) => {+ const map: Record<string, unknown> = {+ tools: [],+ skills: [],+ execute_code: false,+ web_search: false,+ file_search: false,+ artifacts: '',+ context_files: [],+ knowledge_files: [],+ code_files: [],+ };+ return map[name];+ },+}));++jest.mock('~/Providers', () => ({+ useAgentPanelContext: () => ({+ agentsConfig: { capabilities: ['execute_code', 'tools'] },+ regularTools: [{ pluginKey: 'dalle', name: 'DALL-E', description: 'Images' }],+ mcpServersMap: new Map(),+ actions: [],+ }),+}));++const mockToggleFavorite = jest.fn();+let mockFavoriteKeys = new Set<string>();++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useHasAccess: () => true,+ useCategories: () => ({ categories: [] }),+ useAuthContext: () => ({ user: { id: 'u1' } }),+ useToolFavorites: () => ({+ favoriteKeys: mockFavoriteKeys,+ toggle: mockToggleFavorite,+ isFavorite: (item: { kind: string; id: string }) =>+ mockFavoriteKeys.has(`${item.kind}:${item.id}`),+ isLoading: false,+ }),+}));++jest.mock('@ariakit/react/menu', () => ({+ MenuButton: ({ render }: { render: React.ReactNode }) => render,+}));++jest.mock('~/data-provider', () => ({+ useListSkillsQuery: () => ({ data: { skills: [] }, isLoading: false }),+ useGetToolFavoritesQuery: () => ({ data: [] }),+}));++jest.mock('react-router-dom', () => ({+ useNavigate: () => jest.fn(),+}));++jest.mock('../hooks', () => {+ const { buildCatalog } = jest.requireActual('../items/catalog');+ const { deriveSelectedItems } = jest.requireActual('../items/selectors');+ return {+ useUninstallToolCredentials: () => jest.fn(),+ /** Mirrors the real pipeline over the mocked panel context + form watches. */+ useAgentItems: ({ agentId }: { agentId: string }) => {+ const { useAgentPanelContext } = jest.requireMock('~/Providers');+ const { useWatch } = jest.requireMock('react-hook-form');+ const { agentsConfig, regularTools, mcpServersMap, actions } = useAgentPanelContext();+ const agentActions = (actions ?? []).filter(+ (a: { agent_id: string }) => a.agent_id === agentId,+ );+ const tools = (useWatch({ name: 'tools' }) ?? []) as string[];+ const catalog = buildCatalog({+ agentsConfig: { capabilities: agentsConfig?.capabilities ?? [] },+ regularTools: regularTools ?? [],+ mcpServersMap: mcpServersMap ?? new Map(),+ skills: [],+ actions: agentActions,+ permissions: { mcp: true, skills: false },+ });+ const selected = deriveSelectedItems(+ {+ execute_code: (useWatch({ name: 'execute_code' }) ?? false) as boolean,+ web_search: (useWatch({ name: 'web_search' }) ?? false) as boolean,+ file_search: (useWatch({ name: 'file_search' }) ?? false) as boolean,+ memory: false,+ artifacts: (useWatch({ name: 'artifacts' }) ?? '') as string,+ tools,+ skills: [],+ context_files: [],+ knowledge_files: [],+ code_files: [],+ },+ catalog,+ agentActions,+ );+ return { catalog, selected, tools };+ },+ };+});++jest.mock('@librechat/client', () => {+ const React = jest.requireActual('react');+ const passthrough =+ (tag: string) =>+ ({ children, asChild, ...rest }: any) =>+ React.createElement(asChild ? React.Fragment : tag, asChild ? null : rest, children);+ return {+ Button: ({ children, onClick, asChild, ...rest }: any) =>+ asChild+ ? React.createElement(React.Fragment, null, children)+ : React.createElement('button', { onClick, type: 'button', ...rest }, children),+ Input: React.forwardRef((props: any, ref: any) =>+ React.createElement('input', { ...props, ref }),+ ),+ DropdownPopup: ({ trigger }: { trigger: React.ReactNode }) =>+ React.createElement('div', null, trigger),+ OGDialog: ({ children, open }: { children: React.ReactNode; open?: boolean }) =>+ open ? React.createElement('div', null, children) : null,+ OGDialogContent: passthrough('div'),+ OGDialogHeader: passthrough('div'),+ OGDialogTitle: passthrough('h2'),+ OGDialogDescription: passthrough('p'),+ OGDialogClose: ({ children, asChild }: any) =>+ asChild+ ? React.createElement(React.Fragment, null, children)+ : React.createElement('button', { type: 'button' }, children),+ useToastContext: () => ({ showToast: jest.fn() }),+ };+});++jest.mock('../ItemDialog/ItemDialog', () => ({+ __esModule: true,+ default: ({ item }: { item: unknown }) => (item ? <div data-testid="item-dialog" /> : null),+}));+jest.mock('../ItemDialog/AddMcpServerDialog', () => ({+ __esModule: true,+ default: ({ open }: { open: boolean }) => (open ? <div data-testid="add-mcp-dialog" /> : null),+}));++describe('ToolsMarketplaceDialog', () => {+ beforeEach(() => {+ mockSetValue.mockClear();+ mockGetValues.mockClear();+ mockGetValues.mockReturnValue([]);+ mockToggleFavorite.mockClear();+ mockFavoriteKeys = new Set<string>();+ });++ test('renders cards from catalog when open', () => {+ render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);+ expect(screen.getByText('DALL-E')).toBeInTheDocument();+ });++ test('does not render anything when closed', () => {+ const { container } = render(+ <ToolsMarketplaceDialog open={false} onOpenChange={jest.fn()} agentId="a1" />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ test('clicking a tool card calls setValue on tools array with the id appended', () => {+ render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);+ fireEvent.click(screen.getByRole('button', { name: /DALL-E/ }));+ expect(mockSetValue).toHaveBeenCalledWith(+ 'tools',+ expect.arrayContaining(['dalle']),+ expect.objectContaining({ shouldDirty: true }),+ );+ });++ test('typing in search input filters the catalog', () => {+ render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);+ const input = screen.getByPlaceholderText('com_ui_tools_marketplace_search');+ fireEvent.change(input, { target: { value: 'zzz' } });+ expect(screen.getByText('com_ui_tools_search_no_results')).toBeInTheDocument();+ });++ test('clicking an unselected tool card toggles it without opening the detail pane', () => {+ mockSetValue.mockClear();+ render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);+ fireEvent.click(screen.getByRole('button', { name: /DALL-E/ }));+ expect(screen.queryByTestId('item-dialog')).not.toBeInTheDocument();+ expect(mockSetValue).toHaveBeenCalledWith(+ 'tools',+ expect.arrayContaining(['dalle']),+ expect.objectContaining({ shouldDirty: true }),+ );+ });++ test('clicking a card star toggles the favorite without selecting the tool', () => {+ render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);+ fireEvent.click(screen.getAllByRole('button', { name: 'com_ui_favorite' })[0]);+ expect(mockToggleFavorite).toHaveBeenCalledTimes(1);+ expect(mockSetValue).not.toHaveBeenCalled();+ });++ test('the Favorites view shows only favorited items', () => {+ mockFavoriteKeys = new Set(['tool:dalle']);+ render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);+ fireEvent.click(screen.getByRole('button', { name: /com_ui_tools_view_favorites/ }));+ expect(screen.getByText('DALL-E')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_run_code')).not.toBeInTheDocument();+ });++ test('the Favorites view is empty without favorites', () => {+ render(<ToolsMarketplaceDialog open onOpenChange={jest.fn()} agentId="a1" />);+ fireEvent.click(screen.getByRole('button', { name: /com_ui_tools_view_favorites/ }));+ expect(screen.getByText('com_ui_tools_view_favorites_empty')).toBeInTheDocument();+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsSection.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsSection.spec.tsxnew file mode 100644index 0000000000..87f4d3242e--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/ToolsSection.spec.tsx@@ -0,0 +1,139 @@+import React from 'react';+import '@testing-library/jest-dom/extend-expect';+import { render, screen, fireEvent } from '@testing-library/react';+import type { AgentItem } from '../items/types';+import ToolsSection from '../ToolsSection';++let mockSelected: AgentItem[] = [];+let mockFileEntries: {+ contextFiles: unknown[];+ knowledgeFiles: unknown[];+ codeFiles: unknown[];+} = { contextFiles: [], knowledgeFiles: [], codeFiles: [] };+const mockSetValue = jest.fn();++jest.mock('react-hook-form', () => ({+ useFormContext: () => ({+ control: {},+ getValues: () => [],+ setValue: mockSetValue,+ }),+ useWatch: () => undefined,+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useHasAccess: () => true,+}));++jest.mock('~/Providers', () => ({+ useAgentPanelContext: () => ({+ agentsConfig: { capabilities: ['skills'] },+ regularTools: [],+ mcpServersMap: new Map(),+ actions: [],+ }),+}));++jest.mock('~/data-provider', () => ({+ useListSkillsQuery: () => ({ data: { skills: [] } }),+ useDeleteAgentAction: () => ({ mutate: jest.fn() }),+}));++jest.mock('~/hooks/MCP', () => ({+ useRemoveMCPTool: () => ({ removeTool: jest.fn() }),+ useVisibleTools: () => ({ toolIds: [], mcpServerNames: [] }),+}));++jest.mock('../hooks', () => ({+ useAgentItems: () => ({ catalog: [], selected: mockSelected, tools: [] }),+ useResolvedSkills: (skills?: unknown[]) => skills,+ useAgentFileEntries: () => mockFileEntries,+ useUninstallToolCredentials: () => jest.fn(),+}));++jest.mock('../ToolRow', () => ({+ __esModule: true,+ default: ({ item, onRemove }: { item: AgentItem; onRemove: (item: AgentItem) => void }) => (+ <button type="button" aria-label={`remove-${item.id}`} onClick={() => onRemove(item)}>+ {item.id}+ </button>+ ),+}));++jest.mock('../ItemDialog/ItemDialog', () => ({+ __esModule: true,+ default: ({ item }: { item: AgentItem | null }) =>+ item ? <div data-testid="item-dialog">{item.id}</div> : null,+}));++jest.mock('@librechat/client', () => ({+ useToastContext: () => ({ showToast: jest.fn() }),+ Label: ({ children }: { children?: React.ReactNode }) => <span>{children}</span>,+ OGDialog: ({ open, children }: { open?: boolean; children?: React.ReactNode }) =>+ open ? <div>{children}</div> : null,+ OGDialogTemplate: () => null,+}));++jest.mock('../ToolsMarketplaceDialog', () => ({+ __esModule: true,+ default: ({ open }: { open: boolean }) => (open ? <div data-testid="marketplace-open" /> : null),+}));++const fileSearchItem: AgentItem = {+ kind: 'builtin',+ id: 'file_search',+ name: 'com_assistants_file_search',+ description: '',+ iconKey: 'file_search',+};++beforeEach(() => {+ mockSelected = [];+ mockFileEntries = { contextFiles: [], knowledgeFiles: [], codeFiles: [] };+ mockSetValue.mockClear();+});++describe('ToolsSection', () => {+ test('renders Tools header', () => {+ render(<ToolsSection agentId="a" />);+ expect(screen.getByText('com_ui_tools_section_title')).toBeInTheDocument();+ });++ test('renders a separate Skills section', () => {+ render(<ToolsSection agentId="a" />);+ expect(screen.getByText('com_ui_skills')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'com_ui_add_skills' })).toBeInTheDocument();+ });++ test('renders Add button that opens the marketplace dialog', () => {+ render(<ToolsSection agentId="a" />);+ const addButton = screen.getByRole('button', { name: 'com_ui_add_tools' });+ fireEvent.click(addButton);+ expect(screen.getByTestId('marketplace-open')).toBeInTheDocument();+ });++ test('renders empty state for both sections 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('opens the config dialog instead of toggling when a file-backed built-in holds files', () => {+ mockSelected = [fileSearchItem];+ mockFileEntries = { contextFiles: [], knowledgeFiles: [['f1', {}]], codeFiles: [] };+ render(<ToolsSection agentId="a" />);+ fireEvent.click(screen.getByRole('button', { name: 'remove-file_search' }));+ expect(screen.getByTestId('item-dialog')).toHaveTextContent('file_search');+ expect(mockSetValue).not.toHaveBeenCalledWith('file_search', false, expect.anything());+ });++ test('toggles the flag off when a file-backed built-in has no files', () => {+ mockSelected = [fileSearchItem];+ mockFileEntries = { contextFiles: [], knowledgeFiles: [], codeFiles: [] };+ render(<ToolsSection agentId="a" />);+ fireEvent.click(screen.getByRole('button', { name: 'remove-file_search' }));+ expect(screen.queryByTestId('item-dialog')).not.toBeInTheDocument();+ expect(mockSetValue).toHaveBeenCalledWith('file_search', false, { shouldDirty: true });+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/useBuiltinAuthMap.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/useBuiltinAuthMap.spec.tsxnew file mode 100644index 0000000000..1600295edd--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/useBuiltinAuthMap.spec.tsx@@ -0,0 +1,78 @@+import React from 'react';+import { renderHook, waitFor } from '@testing-library/react';+import { AuthType, AgentCapabilities } from 'librechat-data-provider';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { VerifyToolAuthResponse } from 'librechat-data-provider';+import { useBuiltinAuthMap } from '../hooks';++const mockVerify = jest.fn();++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getVerifyAgentToolAuth: () => mockVerify(),+ },+ };+});++jest.mock('librechat-data-provider/react-query', () => ({+ useUpdateUserPluginsMutation: () => ({ mutate: jest.fn() }),+}));++jest.mock('@librechat/client', () => ({ useToastContext: () => ({ showToast: jest.fn() }) }));+jest.mock('~/hooks', () => ({+ useLocalize: () => (k: string) => k,+ useHasAccess: () => true,+ useHasMemoryAccess: () => true,+}));+jest.mock('~/hooks/AuthContext', () => ({ useAuthContext: () => ({ user: { id: 'u1' } }) }));+jest.mock('~/Providers', () => ({ useAgentPanelContext: () => ({}) }));++function wrapper() {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;+ };+}++const WEB_SEARCH = AgentCapabilities.web_search;++describe('useBuiltinAuthMap', () => {+ beforeEach(() => mockVerify.mockReset());++ test('flags web_search needs_setup while verification is still loading', () => {+ mockVerify.mockReturnValue(new Promise<VerifyToolAuthResponse>(() => undefined));+ const { result } = renderHook(() => useBuiltinAuthMap(), { wrapper: wrapper() });+ expect(result.current.get(WEB_SEARCH)).toBe(true);+ });++ test('keeps the flag for an unsatisfied user-provided key', async () => {+ mockVerify.mockResolvedValue({+ authenticated: false,+ authTypes: [['serpapi', AuthType.USER_PROVIDED]],+ });+ const { result } = renderHook(() => useBuiltinAuthMap(), { wrapper: wrapper() });+ await waitFor(() => expect(result.current.get(WEB_SEARCH)).toBe(true));+ });++ test('clears the flag once a user-provided key is satisfied', async () => {+ mockVerify.mockResolvedValue({+ authenticated: true,+ authTypes: [['serpapi', AuthType.USER_PROVIDED]],+ });+ const { result } = renderHook(() => useBuiltinAuthMap(), { wrapper: wrapper() });+ await waitFor(() => expect(result.current.has(WEB_SEARCH)).toBe(false));+ });++ test('clears the flag for a system-defined deployment (no key needed)', async () => {+ mockVerify.mockResolvedValue({+ authenticated: true,+ authTypes: [['serpapi', AuthType.SYSTEM_DEFINED]],+ });+ const { result } = renderHook(() => useBuiltinAuthMap(), { wrapper: wrapper() });+ await waitFor(() => expect(result.current.has(WEB_SEARCH)).toBe(false));+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/__tests__/useResolvedSkills.spec.tsx b/client/src/components/SidePanel/Agents/Tools/__tests__/useResolvedSkills.spec.tsxnew file mode 100644index 0000000000..66963593fb--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/__tests__/useResolvedSkills.spec.tsx@@ -0,0 +1,124 @@+import React from 'react';+import { useForm, FormProvider } from 'react-hook-form';+import { renderHook, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { TSkillSummary } from 'librechat-data-provider';+import { makeSkill } from 'test/itemFactories';+import { useResolvedSkills } from '../hooks';++const mockGetSkill = jest.fn();++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getSkill: (id: string) => mockGetSkill(id),+ },+ };+});++jest.mock('librechat-data-provider/react-query', () => ({+ useUpdateUserPluginsMutation: () => ({ mutate: jest.fn() }),+}));++jest.mock('@librechat/client', () => ({+ useToastContext: () => ({ showToast: jest.fn() }),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useHasAccess: () => true,+ useHasMemoryAccess: () => true,+}));++jest.mock('~/hooks/AuthContext', () => ({+ useAuthContext: () => ({ user: { id: 'u1' } }),+}));++jest.mock('~/Providers', () => ({+ useAgentPanelContext: () => ({}),+}));++jest.mock('~/data-provider', () => ({+ useVerifyAgentToolAuth: () => ({ data: undefined }),+}));++function makeWrapper(skillIds: string[]) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return function Wrapper({ children }: { children: React.ReactNode }) {+ const methods = useForm({ defaultValues: { skills: skillIds } });+ return (+ <QueryClientProvider client={queryClient}>+ <FormProvider {...methods}>{children}</FormProvider>+ </QueryClientProvider>+ );+ };+}++function renderResolvedSkills(skillIds: string[], pageSkills?: TSkillSummary[]) {+ return renderHook((props: TSkillSummary[] | undefined) => useResolvedSkills(props), {+ wrapper: makeWrapper(skillIds),+ initialProps: pageSkills,+ });+}++describe('useResolvedSkills', () => {+ beforeEach(() => {+ mockGetSkill.mockReset();+ });++ test('returns undefined while the catalog page has not loaded', () => {+ const { result } = renderResolvedSkills(['s1']);+ expect(result.current).toBeUndefined();+ expect(mockGetSkill).not.toHaveBeenCalled();+ });++ test('passes the page through untouched when every allowlist id is on it', () => {+ const page = [makeSkill({ _id: 's1' }), makeSkill({ _id: 's2' })];+ const { result } = renderResolvedSkills(['s1', 's2'], page);+ expect(result.current).toBe(page);+ expect(mockGetSkill).not.toHaveBeenCalled();+ });++ test('resolves an allowlist id missing from the page individually and appends it', async () => {+ const page = [makeSkill({ _id: 's1' })];+ const offPage = makeSkill({ _id: 'off-page', name: 'Off Page Skill' });+ mockGetSkill.mockResolvedValue(offPage);++ const { result } = renderResolvedSkills(['s1', 'off-page'], page);++ await waitFor(() => {+ expect(result.current?.map((skill) => skill._id)).toEqual(['s1', 'off-page']);+ });+ expect(mockGetSkill).toHaveBeenCalledWith('off-page');+ expect(result.current?.[1].name).toBe('Off Page Skill');+ });++ test('keeps a confirmed miss (404) visible under a placeholder name', async () => {+ mockGetSkill.mockRejectedValue({ response: { status: 404 } });++ const { result } = renderResolvedSkills(['gone'], []);++ await waitFor(() => {+ expect(result.current).toHaveLength(1);+ });+ expect(result.current?.[0]._id).toBe('gone');+ expect(result.current?.[0].name).toBe('com_ui_skill_unavailable');+ });++ test('keeps a transient lookup error visible under the same placeholder', async () => {+ mockGetSkill.mockRejectedValue({ response: { status: 500 } });++ const { result } = renderResolvedSkills(['flaky'], []);++ await waitFor(() => {+ expect(result.current).toHaveLength(1);+ });+ expect(result.current?.[0]._id).toBe('flaky');+ expect(result.current?.[0].name).toBe('com_ui_skill_unavailable');+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/hooks.ts b/client/src/components/SidePanel/Agents/Tools/hooks.tsnew file mode 100644index 0000000000..5f7e14a53c--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/hooks.ts@@ -0,0 +1,341 @@+import { useMemo, useCallback } from 'react';+import { useQueries } from '@tanstack/react-query';+import { useToastContext } from '@librechat/client';+import { useFormContext, useWatch } from 'react-hook-form';+import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';+import {+ Tools,+ AuthType,+ QueryKeys,+ Permissions,+ dataService,+ PermissionTypes,+ AgentCapabilities,+} from 'librechat-data-provider';+import type { TSkillSummary } from 'librechat-data-provider';+import type { AgentForm, ExtendedFile } from '~/common';+import type { AgentItem } from './items/types';+import { useVerifyAgentToolAuth, useGetAgentFiles } from '~/data-provider';+import { useLocalize, useHasAccess, useHasMemoryAccess } from '~/hooks';+import { useFileMapContext, useAgentPanelContext } from '~/Providers';+import { deriveSelectedItems } from './items/selectors';+import { useAuthContext } from '~/hooks/AuthContext';+import { buildCatalog } from './items/catalog';+import { processAgentOption } from '~/utils';++/**+ * Maps builtin capability ids to whether they still need setup (USER_PROVIDED auth+ * not yet satisfied). Threaded into `buildCatalog` as `builtinAuthMap` so the+ * marketplace marks the capability `needs_setup` and routes its toggle to the+ * config dialog instead of silently enabling it without credentials. Only+ * `web_search` currently carries a user-provided key with an in-dialog entry point.+ *+ * While verification is still loading we don't yet know whether a user-provided+ * key is required, so `web_search` is treated as `needs_setup`: a click routes to+ * the config dialog rather than enabling it without the key on a slow connection.+ * Once the query resolves, only an unsatisfied user-provided key keeps the flag —+ * a system-defined deployment or a satisfied key clears it for a direct toggle.+ */+export function useBuiltinAuthMap(): Map<string, boolean> {+ const { data, isLoading } = useVerifyAgentToolAuth({ toolId: Tools.web_search }, { retry: 1 });+ return useMemo(() => {+ const map = new Map<string, boolean>();+ const isUserProvided =+ data?.authTypes?.some(([, authType]) => authType === AuthType.USER_PROVIDED) ?? false;+ if (isLoading || (isUserProvided && data?.authenticated !== true)) {+ map.set(AgentCapabilities.web_search, true);+ }+ return map;+ }, [data, isLoading]);+}++/**+ * Whether `web_search` uses USER_PROVIDED auth (a user-managed key). When false+ * the deployment uses SYSTEM_DEFINED keys, so there is nothing for the user to+ * configure. Shares the `useBuiltinAuthMap` React Query key, so it adds no+ * request. Threaded into `buildCatalog` so the card/row affordance is decided+ * synchronously (cog vs info) without a per-row hook.+ */+export function useWebSearchUserProvided(): boolean {+ const { data } = useVerifyAgentToolAuth({ toolId: Tools.web_search }, { retry: 1 });+ return useMemo(+ () => data?.authTypes?.some(([, authType]) => authType === AuthType.USER_PROVIDED) ?? false,+ [data],+ );+}++/**+ * Resolves whether the Memory capability should be offered in the builder.+ * Mirrors the legacy `AgentConfig` gate: the admin must enable the `memory`+ * capability, the user must hold the memory permission, and the user must not+ * have opted out of memories in personalization. Collapsed into one flag here+ * so both the selected list (`ToolsSection`) and the marketplace+ * (`ToolsMarketplaceDialog`) gate the catalog item identically.+ */+export function useShowMemory(): boolean {+ const { agentsConfig } = useAgentPanelContext();+ const hasMemoryAccess = useHasMemoryAccess();+ const { user } = useAuthContext();+ return useMemo(() => {+ const memoryEnabled = agentsConfig?.capabilities?.includes(AgentCapabilities.memory) ?? false;+ return hasMemoryAccess && memoryEnabled && user?.personalization?.memories !== false;+ }, [agentsConfig, hasMemoryAccess, user]);+}++export interface AgentFileEntries {+ contextFiles: Array<[string, ExtendedFile]>;+ knowledgeFiles: Array<[string, ExtendedFile]>;+ codeFiles: Array<[string, ExtendedFile]>;+}++const NO_FILES: Array<[string, ExtendedFile]> = [];++/**+ * File entries for the agent's builtin file tools (File Context, File Search,+ * Code Interpreter). Agents loaded from the API carry only+ * `tool_resources.*.file_ids` — the client-side entry arrays exist on the form+ * `agent` object only after an in-session upload. Reading them directly would+ * show an existing agent's attachments as empty, so this derives the missing+ * arrays by merging the agent files query into the file map, exactly like the+ * legacy `AgentConfig` hydration. Must be rendered inside the agent form's+ * `FormProvider` and the file map context.+ */+export function useAgentFileEntries(): AgentFileEntries {+ const { control } = useFormContext<AgentForm>();+ const agent = useWatch({ control, name: 'agent' });+ const agentId = useWatch({ control, name: 'id' });+ const fileMap = useFileMapContext();+ const { data: agentFiles = [] } = useGetAgentFiles(agentId);++ return useMemo(() => {+ if (agent == null || agent.id !== agentId) {+ return { contextFiles: NO_FILES, knowledgeFiles: NO_FILES, codeFiles: NO_FILES };+ }+ const needsHydration =+ agent.context_files == null || agent.knowledge_files == null || agent.code_files == null;+ let processed: ReturnType<typeof processAgentOption> | null = null;+ if (needsHydration) {+ const mergedFileMap = { ...fileMap };+ for (const file of agentFiles) {+ if (file.file_id) {+ mergedFileMap[file.file_id] = file;+ }+ }+ processed = processAgentOption({ agent, fileMap: mergedFileMap });+ }+ return {+ contextFiles: agent.context_files ?? processed?.context_files ?? NO_FILES,+ knowledgeFiles: agent.knowledge_files ?? processed?.knowledge_files ?? NO_FILES,+ codeFiles: agent.code_files ?? processed?.code_files ?? NO_FILES,+ };+ }, [agent, agentId, fileMap, agentFiles]);+}++interface UseAgentItemsOptions {+ agentId: string;+ /** Skills to include in the catalog; omit to exclude the skill kind entirely. */+ skills?: TSkillSummary[];+ skillsPermission?: boolean;+}++export interface AgentItemsResult {+ catalog: AgentItem[];+ selected: AgentItem[];+ tools: string[];+}++const NO_SKILLS: TSkillSummary[] = [];++/**+ * Single catalog + selection pipeline over the agent form, shared by the+ * selected list (`ToolsSection`) and the marketplace (`ToolsMarketplaceDialog`)+ * so the two can never diverge on gating or selection semantics. Must be+ * rendered inside the agent form's `FormProvider` and `AgentPanelContext`.+ */+export function useAgentItems({+ agentId,+ skills = NO_SKILLS,+ skillsPermission = false,+}: UseAgentItemsOptions): AgentItemsResult {+ const { control } = useFormContext<AgentForm>();+ const { agentsConfig, regularTools, mcpServersMap, actions } = useAgentPanelContext();+ const hasMcpAccess = useHasAccess({+ permissionType: PermissionTypes.MCP_SERVERS,+ permission: Permissions.USE,+ });+ const showMemory = useShowMemory();+ const webSearchUserProvided = useWebSearchUserProvided();+ const builtinAuthMap = useBuiltinAuthMap();++ const toolsField = useWatch({ control, name: 'tools' });+ const skillsWatch = useWatch({ control, name: 'skills' });+ const tools = useMemo(() => (toolsField ?? []) as string[], [toolsField]);+ const skillsField = useMemo(() => (skillsWatch ?? []) as string[], [skillsWatch]);+ const executeCode = (useWatch({ control, name: 'execute_code' }) ?? false) as boolean;+ const webSearch = (useWatch({ control, name: 'web_search' }) ?? false) as boolean;+ const fileSearch = (useWatch({ control, name: 'file_search' }) ?? false) as boolean;+ const memory = (useWatch({ control, name: 'memory' }) ?? false) as boolean;+ const artifacts = (useWatch({ control, name: 'artifacts' }) ?? '') as string;+ const { contextFiles, knowledgeFiles, codeFiles } = useAgentFileEntries();++ const agentActions = useMemo(+ () => (actions ?? []).filter((a) => a.agent_id === agentId),+ [actions, agentId],+ );++ const catalog = useMemo(+ () =>+ buildCatalog({+ agentsConfig: { capabilities: agentsConfig?.capabilities ?? [] },+ regularTools: regularTools ?? [],+ mcpServersMap: mcpServersMap ?? new Map(),+ skills,+ actions: agentActions,+ permissions: { mcp: hasMcpAccess, skills: skillsPermission },+ showMemory,+ webSearchUserProvided,+ builtinAuthMap,+ }),+ [+ agentsConfig,+ regularTools,+ mcpServersMap,+ skills,+ agentActions,+ hasMcpAccess,+ skillsPermission,+ showMemory,+ webSearchUserProvided,+ builtinAuthMap,+ ],+ );++ const selected = useMemo(+ () =>+ deriveSelectedItems(+ {+ execute_code: executeCode,+ web_search: webSearch,+ file_search: fileSearch,+ memory,+ artifacts,+ tools,+ skills: skillsField,+ context_files: contextFiles,+ knowledge_files: knowledgeFiles,+ code_files: codeFiles,+ },+ catalog,+ agentActions,+ ),+ [+ executeCode,+ webSearch,+ fileSearch,+ memory,+ artifacts,+ tools,+ skillsField,+ contextFiles,+ knowledgeFiles,+ codeFiles,+ catalog,+ agentActions,+ ],+ );++ return { catalog, selected, tools };+}++/**+ * Resolves agent allowlist skill ids missing from the first catalog page+ * (`limit: 100`) individually — a cache miss alone must never drop a+ * configured skill from the selected list, where it could no longer be+ * inspected or removed. Any settled lookup failure (deleted, no longer+ * shared, or a transient error with no retry pending) keeps a placeholder+ * entry so the allowlist id stays visible and removable; only in-flight+ * lookups are briefly hidden. Must be rendered inside the agent form's+ * `FormProvider`.+ */+export function useResolvedSkills(pageSkills?: TSkillSummary[]): TSkillSummary[] | undefined {+ const localize = useLocalize();+ const { control } = useFormContext<AgentForm>();+ const skillsWatch = useWatch({ control, name: 'skills' });+ const unresolvedIds = useMemo(() => {+ if (pageSkills === undefined) {+ return [];+ }+ const known = new Set(pageSkills.map((skill) => skill._id));+ return ((skillsWatch ?? []) as string[]).filter((id) => !known.has(id));+ }, [pageSkills, skillsWatch]);++ const lookups = useQueries({+ queries: unresolvedIds.map((skillId) => ({+ queryKey: [QueryKeys.skill, skillId],+ queryFn: () => dataService.getSkill(skillId),+ retry: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ refetchOnWindowFocus: false,+ })),+ });++ return useMemo(() => {+ if (pageSkills === undefined) {+ return undefined;+ }+ if (unresolvedIds.length === 0) {+ return pageSkills;+ }+ const extras: TSkillSummary[] = [];+ for (let i = 0; i < unresolvedIds.length; i++) {+ const lookup = lookups[i];+ if (lookup?.data != null) {+ extras.push(lookup.data);+ continue;+ }+ if (lookup?.isError === true) {+ extras.push({+ _id: unresolvedIds[i],+ name: localize('com_ui_skill_unavailable'),+ description: '',+ author: '',+ authorName: '',+ version: 0,+ source: 'inline',+ fileCount: 0,+ createdAt: '',+ updatedAt: '',+ });+ }+ }+ return extras.length > 0 ? [...pageSkills, ...extras] : pageSkills;+ }, [pageSkills, unresolvedIds, lookups, localize]);+}++/**+ * Returns a callback that revokes a tool's stored user credentials when it is+ * removed from an agent, mirroring the legacy `AgentTool` removal. Without it,+ * removing a tool only drops it from the form and leaves the saved credentials+ * orphaned server-side. Fired unconditionally — a no-op for tools without creds.+ */+export function useUninstallToolCredentials(): (toolId: string) => void {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const updateUserPlugins = useUpdateUserPluginsMutation();+ return useCallback(+ (toolId: string) => {+ if (!toolId) {+ return;+ }+ updateUserPlugins.mutate(+ { pluginKey: toolId, action: 'uninstall', auth: {}, isEntityTool: true },+ {+ onError: () =>+ showToast({ message: localize('com_ui_delete_tool_error'), status: 'error' }),+ },+ );+ },+ [updateUserPlugins, showToast, localize],+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/auth.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/auth.spec.tsnew file mode 100644index 0000000000..8da55c8d01--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/auth.spec.ts@@ -0,0 +1,30 @@+import type { TPlugin } from 'librechat-data-provider';+import { pluginNeedsAuth } from '../auth';++const base: TPlugin = { name: 'Tool', pluginKey: 'tool' };++describe('pluginNeedsAuth', () => {+ it('returns true when auth fields are declared and not authenticated', () => {+ expect(+ pluginNeedsAuth({+ ...base,+ authConfig: [{ authField: 'API_KEY', label: 'Key', description: '' }],+ }),+ ).toBe(true);+ });++ it('returns false when already authenticated', () => {+ expect(+ pluginNeedsAuth({+ ...base,+ authConfig: [{ authField: 'API_KEY', label: 'Key', description: '' }],+ authenticated: true,+ }),+ ).toBe(false);+ });++ it('returns false when no auth fields are declared', () => {+ expect(pluginNeedsAuth(base)).toBe(false);+ expect(pluginNeedsAuth({ ...base, authConfig: [] })).toBe(false);+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/catalog.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/catalog.spec.tsnew file mode 100644index 0000000000..91db59db56--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/catalog.spec.ts@@ -0,0 +1,237 @@+import { AgentCapabilities } from 'librechat-data-provider';+import type { BuildCatalogInputs } from '../catalog';+import { makePlugin, makeSkill, makeAction } from 'test/itemFactories';+import { buildCatalog } from '../catalog';++const emptyInputs: BuildCatalogInputs = {+ agentsConfig: { capabilities: [] },+ regularTools: [],+ mcpServersMap: new Map(),+ skills: [],+ actions: [],+ permissions: { mcp: true, skills: true },+};++const toolInputs: BuildCatalogInputs = {+ ...emptyInputs,+ agentsConfig: { capabilities: [AgentCapabilities.tools] },+};++describe('buildCatalog', () => {+ test('returns empty when nothing is enabled', () => {+ expect(buildCatalog(emptyInputs)).toEqual([]);+ });++ test('emits built-in items only for capabilities the admin enabled', () => {+ const items = buildCatalog({+ ...emptyInputs,+ agentsConfig: {+ capabilities: [AgentCapabilities.execute_code, AgentCapabilities.web_search],+ },+ });+ expect(items.filter((i) => i.kind === 'builtin').map((i) => i.id)).toEqual([+ AgentCapabilities.execute_code,+ AgentCapabilities.web_search,+ ]);+ });++ test('emits the memory builtin only when showMemory is set', () => {+ const memoryId = (i: { kind: string; id: string }) =>+ i.kind === 'builtin' && i.id === AgentCapabilities.memory;+ expect(buildCatalog(emptyInputs).find(memoryId)).toBeUndefined();+ expect(buildCatalog({ ...emptyInputs, showMemory: true }).find(memoryId)).toBeDefined();+ });++ test('flags web_search userProvidedAuth from the webSearchUserProvided input', () => {+ const findWebSearch = (inputs: BuildCatalogInputs) =>+ buildCatalog(inputs).find(+ (i) => i.kind === 'builtin' && i.id === AgentCapabilities.web_search,+ );+ const base = {+ ...emptyInputs,+ agentsConfig: { capabilities: [AgentCapabilities.web_search] },+ };+ const userProvided = findWebSearch({ ...base, webSearchUserProvided: true });+ const systemDefined = findWebSearch({ ...base, webSearchUserProvided: false });+ expect(userProvided?.kind === 'builtin' && userProvided.userProvidedAuth).toBe(true);+ expect(systemDefined?.kind === 'builtin' && systemDefined.userProvidedAuth).toBe(false);+ });++ test('hides MCP items when the user lacks MCP permission', () => {+ const map = new Map();+ map.set('srv', { serverName: 'srv', isConfigured: true, tools: [] });+ const items = buildCatalog({+ ...emptyInputs,+ mcpServersMap: map,+ permissions: { mcp: false, skills: true },+ });+ expect(items.find((i) => i.kind === 'mcp')).toBeUndefined();+ });++ test('emits MCP items with tool counts', () => {+ const map = new Map();+ map.set('everything', {+ serverName: 'everything',+ isConfigured: true,+ tools: [{}, {}, {}],+ });+ const items = buildCatalog({ ...emptyInputs, mcpServersMap: map });+ const mcp = items.find((i) => i.kind === 'mcp');+ expect(mcp).toBeDefined();+ if (mcp?.kind === 'mcp') {+ expect(mcp.toolCount).toBe(3);+ expect(mcp.id).toBe('everything');+ }+ });++ test('excludes consume-only MCP servers from the catalog', () => {+ const map = new Map();+ map.set('attachable', { serverName: 'attachable', isConfigured: true, tools: [] });+ map.set('chat-only', {+ serverName: 'chat-only',+ isConfigured: true,+ tools: [],+ consumeOnly: true,+ });+ const items = buildCatalog({ ...emptyInputs, mcpServersMap: map });+ expect(items.filter((i) => i.kind === 'mcp').map((i) => i.id)).toEqual(['attachable']);+ });++ test('emits skill items when permission granted', () => {+ const items = buildCatalog({+ ...emptyInputs,+ skills: [+ makeSkill({ _id: 's1', name: 'Reviewer', description: 'Reviews', category: 'code' }),+ ],+ });+ const skill = items.find((i) => i.kind === 'skill');+ expect(skill?.name).toBe('Reviewer');+ });++ test('emits tool items when the tools capability is enabled', () => {+ const items = buildCatalog({+ ...toolInputs,+ regularTools: [makePlugin({ pluginKey: 'dalle', name: 'DALL-E', description: 'Images' })],+ });+ const tool = items.find((i) => i.kind === 'tool');+ expect(tool?.id).toBe('dalle');+ });++ test('hides tool items when the admin disabled the tools capability', () => {+ const items = buildCatalog({+ ...emptyInputs,+ regularTools: [makePlugin({ pluginKey: 'dalle', name: 'DALL-E', description: 'Images' })],+ });+ expect(items.find((i) => i.kind === 'tool')).toBeUndefined();+ });++ test('marks an auth-requiring, unauthenticated tool as needs_setup', () => {+ const items = buildCatalog({+ ...toolInputs,+ regularTools: [+ makePlugin({+ pluginKey: 'serpapi',+ name: 'SerpApi',+ description: 'Search',+ authConfig: [{ authField: 'SERPAPI_API_KEY', label: 'Key', description: '' }],+ authenticated: false,+ }),+ ],+ });+ const tool = items.find((i) => i.kind === 'tool');+ expect(tool?.status).toBe('needs_setup');+ });++ test('leaves status undefined for an authenticated auth-requiring tool', () => {+ const items = buildCatalog({+ ...toolInputs,+ regularTools: [+ makePlugin({+ pluginKey: 'serpapi',+ name: 'SerpApi',+ description: 'Search',+ authConfig: [{ authField: 'SERPAPI_API_KEY', label: 'Key', description: '' }],+ authenticated: true,+ }),+ ],+ });+ const tool = items.find((i) => i.kind === 'tool');+ expect(tool?.status).toBeUndefined();+ });++ test('leaves status undefined for a tool with no authConfig', () => {+ const items = buildCatalog({+ ...toolInputs,+ regularTools: [makePlugin({ pluginKey: 'dalle', name: 'DALL-E', description: 'Images' })],+ });+ const tool = items.find((i) => i.kind === 'tool');+ expect(tool?.status).toBeUndefined();+ });++ test('flags builtin status from builtinAuthMap', () => {+ const items = buildCatalog({+ ...emptyInputs,+ agentsConfig: { capabilities: [AgentCapabilities.web_search] },+ builtinAuthMap: new Map([[AgentCapabilities.web_search, true]]),+ });+ const builtin = items.find((i) => i.kind === 'builtin');+ expect(builtin?.status).toBe('needs_setup');+ });++ test('marks a skill authored by the current user as ownedByUser', () => {+ const items = buildCatalog({+ ...emptyInputs,+ currentUserId: 'u1',+ skills: [+ makeSkill({ _id: 's1', name: 'Mine', description: '', category: 'code', author: 'u1' }),+ makeSkill({ _id: 's2', name: 'Theirs', description: '', category: 'code', author: 'u2' }),+ ],+ });+ const skills = items.filter((i) => i.kind === 'skill');+ expect(skills.find((s) => s.id === 's1')?.ownedByUser).toBe(true);+ expect(skills.find((s) => s.id === 's2')?.ownedByUser).toBe(false);+ });++ test('leaves ownedByUser false when no currentUserId is provided', () => {+ const items = buildCatalog({+ ...emptyInputs,+ skills: [makeSkill({ _id: 's1', name: 'S1', description: '', author: 'u1' })],+ });+ const skill = items.find((i) => i.kind === 'skill');+ expect(skill?.ownedByUser).toBe(false);+ });++ test('emits action items with endpoint counts', () => {+ const items = buildCatalog({+ ...emptyInputs,+ actions: [+ makeAction({+ action_id: 'a1',+ metadata: { domain: 'linear.app', oauth_client_id: 'x' },+ settings: { paths: { '/issues': {}, '/teams': {} } },+ }),+ ],+ });+ const action = items.find((i) => i.kind === 'action');+ expect(action?.id).toBe('a1');+ if (action?.kind === 'action') {+ expect(action.endpointCount).toBe(2);+ }+ });++ test('returns items in stable order: builtin -> mcp -> tool -> skill -> action', () => {+ const map = new Map();+ map.set('srv', { serverName: 'srv', isConfigured: true, tools: [] });+ const items = buildCatalog({+ ...emptyInputs,+ agentsConfig: { capabilities: [AgentCapabilities.execute_code, AgentCapabilities.tools] },+ regularTools: [makePlugin({ pluginKey: 't1', name: 'T1', description: '' })],+ mcpServersMap: map,+ skills: [makeSkill({ _id: 's1', name: 'S1', description: '' })],+ actions: [+ makeAction({ action_id: 'a1', metadata: { domain: 'd' }, settings: { paths: {} } }),+ ],+ });+ expect(items.map((i) => i.kind)).toEqual(['builtin', 'mcp', 'tool', 'skill', 'action']);+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/configurable.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/configurable.spec.tsnew file mode 100644index 0000000000..aa12b7c3d9--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/configurable.spec.ts@@ -0,0 +1,82 @@+import type { AgentItem } from '../types';+import { makePlugin, makeMcpServer, makeSkill, makeAction } from 'test/itemFactories';+import { hasConfigurableSettings } from '../configurable';++const builtin = (id: string, extra: Record<string, unknown> = {}): AgentItem =>+ ({ kind: 'builtin', id, name: '', description: '', iconKey: id, ...extra }) as AgentItem;++describe('hasConfigurableSettings', () => {+ test('artifacts, file_search, and context builtins are configurable', () => {+ expect(hasConfigurableSettings(builtin('artifacts'))).toBe(true);+ expect(hasConfigurableSettings(builtin('file_search'))).toBe(true);+ expect(hasConfigurableSettings(builtin('context'))).toBe(true);+ });++ test('execute_code and memory builtins are not configurable', () => {+ expect(hasConfigurableSettings(builtin('execute_code'))).toBe(false);+ expect(hasConfigurableSettings(builtin('memory'))).toBe(false);+ });++ test('web_search is configurable only when auth is user-provided', () => {+ expect(hasConfigurableSettings(builtin('web_search'))).toBe(false);+ expect(hasConfigurableSettings(builtin('web_search', { userProvidedAuth: false }))).toBe(false);+ expect(hasConfigurableSettings(builtin('web_search', { userProvidedAuth: true }))).toBe(true);+ });++ test('mcp and action are always configurable; skills never are', () => {+ const mcp: AgentItem = {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: '',+ iconKey: 'mcp',+ server: makeMcpServer({ serverName: 'srv' }),+ toolCount: 0,+ };+ const action: AgentItem = {+ kind: 'action',+ id: 'a1',+ name: 'a1',+ description: '',+ iconKey: 'action',+ action: makeAction({ action_id: 'a1' }),+ endpointCount: 0,+ };+ const skill: AgentItem = {+ kind: 'skill',+ id: 's1',+ name: 's1',+ description: '',+ iconKey: 'skill',+ skill: makeSkill({ _id: 's1' }),+ };+ expect(hasConfigurableSettings(mcp)).toBe(true);+ expect(hasConfigurableSettings(action)).toBe(true);+ expect(hasConfigurableSettings(skill)).toBe(false);+ });++ test('a regular tool is configurable only when it needs auth', () => {+ const noAuth: AgentItem = {+ kind: 'tool',+ id: 'dalle',+ name: 'DALL-E',+ description: '',+ iconKey: 'tool',+ plugin: makePlugin({ pluginKey: 'dalle' }),+ };+ const needsAuth: AgentItem = {+ kind: 'tool',+ id: 'serpapi',+ name: 'SerpApi',+ description: '',+ iconKey: 'tool',+ plugin: makePlugin({+ pluginKey: 'serpapi',+ authConfig: [{ authField: 'SERPAPI_API_KEY', label: 'Key', description: '' }],+ authenticated: false,+ }),+ };+ expect(hasConfigurableSettings(noAuth)).toBe(false);+ expect(hasConfigurableSettings(needsAuth)).toBe(true);+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/filtering.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/filtering.spec.tsnew file mode 100644index 0000000000..7e87b3653a--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/filtering.spec.ts@@ -0,0 +1,164 @@+import type { AgentItem } from '../types';+import { makePlugin, makeSkill } from 'test/itemFactories';+import { applyFilter, matchesView } from '../filtering';++const items: AgentItem[] = [+ {+ kind: 'builtin',+ id: 'execute_code',+ name: 'Code Interpreter',+ description: 'Run Python',+ iconKey: 'execute_code',+ },+ {+ kind: 'tool',+ id: 'dalle',+ name: 'DALL-E',+ description: 'Generate images',+ iconKey: 'tool',+ plugin: makePlugin({ pluginKey: 'dalle' }),+ },+ {+ kind: 'skill',+ id: 's1',+ name: 'Code Reviewer',+ description: 'Review PRs',+ iconKey: 'skill',+ skill: makeSkill({ _id: 's1', name: 'Code Reviewer', category: 'code' }),+ ownedByUser: true,+ },+ {+ kind: 'skill',+ id: 's2',+ name: 'Marketing Email',+ description: 'Write emails',+ iconKey: 'skill',+ skill: makeSkill({ _id: 's2', name: 'Marketing Email', category: 'marketing' }),+ ownedByUser: false,+ },+];++describe('applyFilter', () => {+ test('no filter returns all items', () => {+ expect(applyFilter(items, {}).length).toBe(4);+ });++ test('search filters by name', () => {+ const result = applyFilter(items, { search: 'code' });+ expect(result.map((i) => i.id)).toEqual(['execute_code', 's1']);+ });++ test('search is case-insensitive across name and description', () => {+ const result = applyFilter(items, { search: 'IMAGES' });+ expect(result.map((i) => i.id)).toEqual(['dalle']);+ });++ test('kind filter restricts to one type', () => {+ const result = applyFilter(items, { kind: 'skill' });+ expect(result.map((i) => i.id)).toEqual(['s1', 's2']);+ });++ test('"all" kind is equivalent to no filter', () => {+ expect(applyFilter(items, { kind: 'all' }).length).toBe(4);+ });++ test('category filters skills by their category', () => {+ const result = applyFilter(items, { category: 'marketing' });+ expect(result.map((i) => i.id)).toEqual(['s2']);+ });++ test('combined filters apply intersection', () => {+ const result = applyFilter(items, { kind: 'skill', search: 'code' });+ expect(result.map((i) => i.id)).toEqual(['s1']);+ });++ test('marketplace view returns all items', () => {+ expect(applyFilter(items, { view: 'marketplace' }).length).toBe(4);+ });++ test('"mine" view returns only items owned by the user', () => {+ const result = applyFilter(items, { view: 'mine' });+ expect(result.map((i) => i.id)).toEqual(['s1']);+ });++ test('"favorites" view returns only items matching compound kind:id keys', () => {+ const result = applyFilter(+ items,+ { view: 'favorites' },+ { favoritedIds: new Set(['tool:dalle']) },+ );+ expect(result.map((i) => i.id)).toEqual(['dalle']);+ });++ test('"favorites" view does not match bare ids (cross-kind collision guard)', () => {+ const result = applyFilter(items, { view: 'favorites' }, { favoritedIds: new Set(['dalle']) });+ expect(result.length).toBe(0);+ });++ test('"favorites" view distinguishes the same id across kinds', () => {+ const collision: AgentItem[] = [+ {+ kind: 'tool',+ id: 'shared-id',+ name: 'Tool',+ description: '',+ iconKey: 'tool',+ plugin: makePlugin({ pluginKey: 'shared-id' }),+ },+ {+ kind: 'skill',+ id: 'shared-id',+ name: 'Skill',+ description: '',+ iconKey: 'skill',+ skill: makeSkill({ _id: 'shared-id' }),+ },+ ];+ const result = applyFilter(+ collision,+ { view: 'favorites' },+ { favoritedIds: new Set(['skill:shared-id']) },+ );+ expect(result.map((i) => i.kind)).toEqual(['skill']);+ });++ test('"favorites" view with no favorited set returns nothing', () => {+ expect(applyFilter(items, { view: 'favorites' }).length).toBe(0);+ });++ test('view filter intersects with kind and search', () => {+ const result = applyFilter(items, { view: 'mine', kind: 'skill', search: 'reviewer' });+ expect(result.map((i) => i.id)).toEqual(['s1']);+ });+});++describe('matchesView', () => {+ const ownedSkill = items[2];+ const unownedSkill = items[3];+ const tool = items[1];++ test('marketplace view matches everything', () => {+ expect(matchesView(tool, 'marketplace', {})).toBe(true);+ expect(matchesView(ownedSkill, 'marketplace', {})).toBe(true);+ });++ test('undefined view matches everything', () => {+ expect(matchesView(tool, undefined, {})).toBe(true);+ });++ test('"mine" matches only items flagged ownedByUser', () => {+ expect(matchesView(ownedSkill, 'mine', {})).toBe(true);+ expect(matchesView(unownedSkill, 'mine', {})).toBe(false);+ expect(matchesView(tool, 'mine', {})).toBe(false);+ });++ test('"favorites" matches only compound keys in the favorited set', () => {+ const context = { favoritedIds: new Set(['skill:s1']) };+ expect(matchesView(ownedSkill, 'favorites', context)).toBe(true);+ expect(matchesView(unownedSkill, 'favorites', context)).toBe(false);+ });++ test('"favorites" matches nothing without a favorited set', () => {+ expect(matchesView(ownedSkill, 'favorites', {})).toBe(false);+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/icons.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/icons.spec.tsnew file mode 100644index 0000000000..7743fe00b3--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/icons.spec.ts@@ -0,0 +1,84 @@+import type { AgentItem } from '../types';+import { makePlugin, makeSkill, makeMcpServer, makeAction } from 'test/itemFactories';+import { getIconForItem } from '../icons';++describe('getIconForItem', () => {+ test('returns icon + color for built-in execute_code', () => {+ const item: AgentItem = {+ kind: 'builtin',+ id: 'execute_code',+ name: 'Code',+ description: '',+ iconKey: 'execute_code',+ };+ const result = getIconForItem(item);+ expect(result.Icon).toBeDefined();+ expect(result.colorClass).toMatch(/emerald|green/);+ });++ test('returns the Brain icon + indigo color for built-in memory', () => {+ const item: AgentItem = {+ kind: 'builtin',+ id: 'memory',+ name: 'Memory',+ description: '',+ iconKey: 'memory',+ };+ const result = getIconForItem(item);+ expect(result.Icon).toBeDefined();+ expect(result.colorClass).toMatch(/indigo/);+ });++ test('returns a distinct color class per kind', () => {+ const items: AgentItem[] = [+ {+ kind: 'tool',+ id: 'x',+ name: 'x',+ description: '',+ iconKey: 'fallback',+ plugin: makePlugin(),+ },+ {+ kind: 'mcp',+ id: 'x',+ name: 'x',+ description: '',+ iconKey: 'fallback',+ server: makeMcpServer(),+ toolCount: 0,+ },+ {+ kind: 'skill',+ id: 'x',+ name: 'x',+ description: '',+ iconKey: 'fallback',+ skill: makeSkill(),+ },+ {+ kind: 'action',+ id: 'x',+ name: 'x',+ description: '',+ iconKey: 'fallback',+ action: makeAction(),+ endpointCount: 0,+ },+ ];+ const colors = items.map((item) => getIconForItem(item).colorClass);+ expect(new Set(colors).size).toBe(items.length);+ });++ test('falls back to a generic icon for an unmapped built-in iconKey', () => {+ const item: AgentItem = {+ kind: 'builtin',+ id: 'execute_code',+ name: 'X',+ description: '',+ iconKey: 'unknown_capability',+ };+ const result = getIconForItem(item);+ expect(result.Icon).toBeDefined();+ });+});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.tsnew file mode 100644index 0000000000..7db3648af1--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts@@ -0,0 +1,159 @@+import { AgentCapabilities, ArtifactModes } from 'librechat-data-provider';+import type { AgentItem } from '../types';+import { makePlugin, makeSkill, makeMcpServer, makeAction } from 'test/itemFactories';+import { computeToggleAction, skillsEnabledTransition } from '../mutations';++const builtinCode: AgentItem = {+ kind: 'builtin',+ id: 'execute_code',+ name: 'Code',+ description: '',+ iconKey: 'execute_code',+};++const builtinArtifacts: AgentItem = {+ kind: 'builtin',+ id: 'artifacts',+ name: 'Art',+ description: '',+ iconKey: 'artifacts',+};++const tool: AgentItem = {+ kind: 'tool',+ id: 'dalle',+ name: 'DALL-E',+ description: '',+ iconKey: 'tool',+ plugin: makePlugin({ pluginKey: 'dalle' }),+};++const skill: AgentItem = {+ kind: 'skill',+ id: 's1',+ name: 'Skill',+ description: '',+ iconKey: 'skill',+ skill: makeSkill({ _id: 's1' }),+};++const mcp: AgentItem = {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: '',+ iconKey: 'mcp',+ server: makeMcpServer({ serverName: 'srv' }),+ toolCount: 0,+};++const action: AgentItem = {+ kind: 'action',+ id: 'a1',+ name: 'A1',+ description: '',+ iconKey: 'action',+ action: makeAction({ action_id: 'a1', agent_id: 'agt' }),+ endpointCount: 1,+};++describe('computeToggleAction', () => {+ test('toggling execute_code on writes the boolean flag', () => {+ expect(computeToggleAction(builtinCode, { selected: false })).toEqual({+ type: 'builtin',+ field: AgentCapabilities.execute_code,+ value: true,+ });+ });++ test('toggling execute_code off writes false', () => {+ expect(computeToggleAction(builtinCode, { selected: true })).toEqual({+ type: 'builtin',+ field: AgentCapabilities.execute_code,+ value: false,+ });+ });++ test('toggling artifacts on writes the default mode', () => {+ expect(computeToggleAction(builtinArtifacts, { selected: false })).toEqual({+ type: 'builtin',+ field: AgentCapabilities.artifacts,+ value: ArtifactModes.DEFAULT,+ });+ });++ test('toggling artifacts off writes empty string', () => {+ expect(computeToggleAction(builtinArtifacts, { selected: true })).toEqual({+ type: 'builtin',+ field: AgentCapabilities.artifacts,+ value: '',+ });+ });++ test('toggling a tool emits a tools-array patch', () => {+ expect(computeToggleAction(tool, { selected: false })).toEqual({+ type: 'tool-add',+ id: 'dalle',+ });+ expect(computeToggleAction(tool, { selected: true })).toEqual({+ type: 'tool-remove',+ id: 'dalle',+ });+ });++ test('toggling a skill emits a skills-array patch', () => {+ expect(computeToggleAction(skill, { selected: false })).toEqual({+ type: 'skill-add',+ id: 's1',+ });+ });++ test('toggling an MCP server emits add/remove patches keyed by server name', () => {+ expect(computeToggleAction(mcp, { selected: false })).toEqual({+ type: 'mcp-add',+ serverName: 'srv',+ });+ expect(computeToggleAction(mcp, { selected: true })).toEqual({+ type: 'mcp-remove',+ serverName: 'srv',+ });+ });++ test('toggling an action emits add/remove patches keyed by action id', () => {+ expect(computeToggleAction(action, { selected: false })).toEqual({+ type: 'action-add',+ actionId: 'a1',+ });+ expect(computeToggleAction(action, { selected: true })).toEqual({+ type: 'action-remove',+ actionId: 'a1',+ });+ });+});++describe('skillsEnabledTransition', () => {+ test('adding the first skill turns the master flag on', () => {+ expect(skillsEnabledTransition([], ['s1'], undefined)).toBe(true);+ expect(skillsEnabledTransition([], ['s1'], false)).toBe(true);+ });++ test('adding the first skill leaves an already-on flag alone', () => {+ expect(skillsEnabledTransition([], ['s1'], true)).toBeUndefined();+ });++ test('removing the last skill turns the master flag off', () => {+ expect(skillsEnabledTransition(['s1'], [], true)).toBe(false);+ });++ test('removing the last skill leaves an off flag alone', () => {+ expect(skillsEnabledTransition(['s1'], [], false)).toBeUndefined();+ expect(skillsEnabledTransition(['s1'], [], undefined)).toBeUndefined();+ });++ test('edits within a non-empty selection never touch the flag', () => {+ expect(skillsEnabledTransition(['s1'], ['s1', 's2'], true)).toBeUndefined();+ expect(skillsEnabledTransition(['s1'], ['s1', 's2'], false)).toBeUndefined();+ expect(skillsEnabledTransition(['s1', 's2'], ['s1'], true)).toBeUndefined();+ expect(skillsEnabledTransition(['s1', 's2'], ['s1'], false)).toBeUndefined();+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.tsnew file mode 100644index 0000000000..e315507eef--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts@@ -0,0 +1,226 @@+import { AgentCapabilities, Constants } from 'librechat-data-provider';+import type { AgentItem } from '../types';+import { makePlugin, makeSkill, makeMcpServer, makeAction } from 'test/itemFactories';+import { deriveSelectedItems, matchesMcpServer } from '../selectors';++const mcpServerToken = (serverName: string) =>+ `${Constants.mcp_server}${Constants.mcp_delimiter}${serverName}`;+const mcpToolToken = (toolName: string, serverName: string) =>+ `${toolName}${Constants.mcp_delimiter}${serverName}`;++const sampleCatalog: AgentItem[] = [+ { kind: 'builtin', id: 'execute_code', name: 'Code', description: '', iconKey: 'execute_code' },+ { kind: 'builtin', id: 'web_search', name: 'Web', description: '', iconKey: 'web_search' },+ { kind: 'builtin', id: 'artifacts', name: 'Art', description: '', iconKey: 'artifacts' },+ { kind: 'builtin', id: 'context', name: 'Ctx', description: '', iconKey: 'context' },+ { kind: 'builtin', id: 'file_search', name: 'FS', description: '', iconKey: 'file_search' },+ { kind: 'builtin', id: 'memory', name: 'Memory', description: '', iconKey: 'memory' },+ {+ kind: 'tool',+ id: 'dalle',+ name: 'DALL-E',+ description: '',+ iconKey: 'tool',+ plugin: makePlugin({ pluginKey: 'dalle' }),+ },+ {+ kind: 'skill',+ id: 's1',+ name: 'Skill1',+ description: '',+ iconKey: 'skill',+ skill: makeSkill({ _id: 's1', name: 'Skill1' }),+ },+];++const emptyFormState = {+ execute_code: false,+ web_search: false,+ file_search: false,+ memory: false,+ artifacts: '',+ tools: [] as string[],+ skills: [] as string[],+ context_files: [] as Array<[string, unknown]>,+ knowledge_files: [] as Array<[string, unknown]>,+ code_files: [] as Array<[string, unknown]>,+};++describe('deriveSelectedItems', () => {+ test('returns nothing when nothing is selected', () => {+ expect(deriveSelectedItems(emptyFormState, sampleCatalog, [])).toEqual([]);+ });++ test('selects built-in capabilities by their flags', () => {+ const result = deriveSelectedItems(+ { ...emptyFormState, execute_code: true, artifacts: 'default' },+ sampleCatalog,+ [],+ );+ const ids = result.map((i) => i.id);+ expect(ids).toContain(AgentCapabilities.execute_code);+ expect(ids).toContain(AgentCapabilities.artifacts);+ expect(ids).not.toContain(AgentCapabilities.web_search);+ });++ test('selects the memory builtin by its flag', () => {+ const result = deriveSelectedItems({ ...emptyFormState, memory: true }, sampleCatalog, []);+ expect(result.map((i) => i.id)).toContain(AgentCapabilities.memory);+ });++ test('treats non-empty knowledge_files as file_search selected even without an explicit flag', () => {+ const result = deriveSelectedItems(+ { ...emptyFormState, knowledge_files: [['f', {}]] },+ sampleCatalog,+ [],+ );+ expect(result.find((i) => i.id === AgentCapabilities.file_search)).toBeDefined();+ });++ test('treats non-empty context_files as context selected even without an explicit flag', () => {+ const result = deriveSelectedItems(+ { ...emptyFormState, context_files: [['f', {}]] },+ sampleCatalog,+ [],+ );+ expect(result.find((i) => i.id === AgentCapabilities.context)).toBeDefined();+ });++ test('selects tools, skills, and MCP servers based on form arrays', () => {+ const catalog: AgentItem[] = [+ ...sampleCatalog,+ {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: '',+ iconKey: 'mcp',+ server: makeMcpServer({ serverName: 'srv' }),+ toolCount: 0,+ },+ ];+ const result = deriveSelectedItems(+ { ...emptyFormState, tools: ['dalle', 'mcp_srv'], skills: ['s1'] },+ catalog,+ [],+ );+ const kinds = result.map((i) => i.kind);+ expect(kinds).toContain('tool');+ expect(kinds).toContain('skill');+ expect(kinds).toContain('mcp');+ });++ test('treats a per-tool MCP token as selecting the server', () => {+ const catalog: AgentItem[] = [+ ...sampleCatalog,+ {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: '',+ iconKey: 'mcp',+ server: makeMcpServer({ serverName: 'srv' }),+ toolCount: 0,+ },+ ];+ const result = deriveSelectedItems(+ { ...emptyFormState, tools: [mcpToolToken('search', 'srv')] },+ catalog,+ [],+ );+ expect(result.find((i) => i.kind === 'mcp')?.id).toBe('srv');+ });++ test('treats a server represented only by its server token as attached', () => {+ const catalog: AgentItem[] = [+ ...sampleCatalog,+ {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: '',+ iconKey: 'mcp',+ server: makeMcpServer({ serverName: 'srv' }),+ toolCount: 0,+ },+ ];+ const result = deriveSelectedItems(+ { ...emptyFormState, tools: [mcpServerToken('srv')] },+ catalog,+ [],+ );+ expect(result.find((i) => i.kind === 'mcp')?.id).toBe('srv');+ });++ test('deselect-all (empty tools) leaves no MCP server selected', () => {+ const catalog: AgentItem[] = [+ ...sampleCatalog,+ {+ kind: 'mcp',+ id: 'srv',+ name: 'srv',+ description: '',+ iconKey: 'mcp',+ server: makeMcpServer({ serverName: 'srv' }),+ toolCount: 0,+ },+ ];+ const result = deriveSelectedItems({ ...emptyFormState, tools: [] }, catalog, []);+ expect(result.find((i) => i.kind === 'mcp')).toBeUndefined();+ });++ test('selects all agent actions passed in', () => {+ const catalog: AgentItem[] = [+ ...sampleCatalog,+ {+ kind: 'action',+ id: 'a1',+ name: 'A1',+ description: '',+ iconKey: 'action',+ action: makeAction({ action_id: 'a1', agent_id: 'agt' }),+ endpointCount: 1,+ },+ ];+ const result = deriveSelectedItems(emptyFormState, catalog, [makeAction({ action_id: 'a1' })]);+ expect(result.find((i) => i.kind === 'action')?.id).toBe('a1');+ });++ test('selected items preserve stable kind ordering (builtin → mcp → tool → skill → action)', () => {+ const result = deriveSelectedItems(+ { ...emptyFormState, execute_code: true, tools: ['dalle'], skills: ['s1'] },+ sampleCatalog,+ [],+ );+ const kindOrder = result.map((i) => i.kind);+ expect(kindOrder.indexOf('builtin')).toBeLessThan(kindOrder.indexOf('tool'));+ expect(kindOrder.indexOf('tool')).toBeLessThan(kindOrder.indexOf('skill'));+ });+});++describe('matchesMcpServer', () => {+ test('matches every persisted token format for the server', () => {+ expect(matchesMcpServer(`${Constants.mcp_server}${Constants.mcp_delimiter}srv`, 'srv')).toBe(+ true,+ );+ expect(matchesMcpServer('srv', 'srv')).toBe(true);+ expect(matchesMcpServer('mcp_srv', 'srv')).toBe(true);+ expect(matchesMcpServer('search_mcp_srv', 'srv')).toBe(true);+ expect(matchesMcpServer(`sys__all__sys${Constants.mcp_delimiter}srv`, 'srv')).toBe(true);+ });++ test('does not match tokens for other servers or plain tool ids', () => {+ expect(matchesMcpServer('mcp_other', 'srv')).toBe(false);+ expect(matchesMcpServer('search_mcp_other', 'srv')).toBe(false);+ expect(matchesMcpServer('dalle', 'srv')).toBe(false);+ expect(matchesMcpServer('srv2', 'srv')).toBe(false);+ });++ test('never claims a longer server name sharing the prefix', () => {+ expect(matchesMcpServer('mcp_github_extra', 'github')).toBe(false);+ expect(matchesMcpServer('github_extra', 'github')).toBe(false);+ expect(matchesMcpServer('search_mcp_github_extra', 'github')).toBe(false);+ expect(matchesMcpServer('mcp_github_extra', 'github_extra')).toBe(true);+ expect(matchesMcpServer('search_mcp_github_extra', 'github_extra')).toBe(true);+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/types.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/types.spec.tsnew file mode 100644index 0000000000..13e747813a--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/types.spec.ts@@ -0,0 +1,43 @@+import type { AgentItem, AgentItemKind } from '../types';++describe('AgentItem types', () => {+ test('discriminator narrows the union', () => {+ const builtin: AgentItem = {+ kind: 'builtin',+ id: 'execute_code',+ name: 'Code Interpreter',+ description: 'Run Python',+ iconKey: 'execute_code',+ };++ expect(builtin.kind).toBe('builtin');+ if (builtin.kind === 'builtin') {+ expect(builtin.id).toBe('execute_code');+ }+ });++ test('every AgentItemKind is exhaustively handled (type-level + runtime)', () => {+ const label = (k: AgentItemKind): string => {+ switch (k) {+ case 'builtin':+ return 'builtin';+ case 'tool':+ return 'tool';+ case 'mcp':+ return 'mcp';+ case 'skill':+ return 'skill';+ case 'action':+ return 'action';+ default: {+ const _exhaustive: never = k;+ return _exhaustive;+ }+ }+ };++ const kinds: AgentItemKind[] = ['builtin', 'tool', 'mcp', 'skill', 'action'];+ expect(kinds.map(label)).toEqual(['builtin', 'tool', 'mcp', 'skill', 'action']);+ expect(new Set(kinds).size).toBe(5);+ });+});diff --git a/client/src/components/SidePanel/Agents/Tools/items/auth.ts b/client/src/components/SidePanel/Agents/Tools/items/auth.tsnew file mode 100644index 0000000000..995de8a814--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/auth.ts@@ -0,0 +1,10 @@+import type { TPlugin } from 'librechat-data-provider';++/** A tool requires auth when it declares credential fields and isn't authenticated yet. */+export function pluginNeedsAuth(plugin: TPlugin): boolean {+ return (+ Array.isArray(plugin.authConfig) &&+ plugin.authConfig.length > 0 &&+ plugin.authenticated !== true+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/catalog.ts b/client/src/components/SidePanel/Agents/Tools/items/catalog.tsnew file mode 100644index 0000000000..e471828146--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/catalog.ts@@ -0,0 +1,182 @@+import { AgentCapabilities } from 'librechat-data-provider';+import type { TPlugin, TSkillSummary, Action } from 'librechat-data-provider';+import type { AgentItem, SkillItem, BuiltinId } from './types';+import type { MCPServerInfo } from '~/common';+import { pluginNeedsAuth } from './auth';++/** Maps skill summaries to catalog items, flagging the current user's own skills. */+export function buildSkillItems(skills: TSkillSummary[], currentUserId?: string): SkillItem[] {+ return skills.map((skill) => ({+ kind: 'skill',+ id: skill._id,+ name: skill.name,+ description: skill.description ?? '',+ iconKey: 'skill',+ skill,+ ownedByUser: currentUserId != null && skill.author === currentUserId,+ }));+}++export interface BuildCatalogInputs {+ agentsConfig: { capabilities: string[] };+ regularTools: TPlugin[];+ mcpServersMap: Map<string, MCPServerInfo>;+ skills: TSkillSummary[];+ actions: Action[];+ permissions: { mcp: boolean; skills: boolean };+ /**+ * Id of the signed-in user. When provided, skills authored by this user are+ * flagged `ownedByUser` so the "Made by you" view can surface them. Optional+ * to keep existing callers working; absent means no item is owned.+ */+ currentUserId?: string;+ /**+ * Maps a builtin capability id (e.g. `web_search`, `execute_code`) to whether+ * it still needs setup (USER_PROVIDED + unauthenticated). Threaded from+ * `useVerifyAgentToolAuth` by the caller. Absent entries leave `status`+ * undefined, so builtins are treated as ready until proven otherwise.+ */+ builtinAuthMap?: Map<string, boolean>;+ /**+ * Whether the Memory capability should be offered. Unlike the other builtins,+ * Memory is gated by permission and user personalization in addition to the+ * admin-enabled capability, so the caller collapses all of that into a single+ * flag (see `showMemory` in `ToolsSection`) instead of deriving it from+ * `agentsConfig.capabilities` here.+ */+ showMemory?: boolean;+ /**+ * Whether `web_search` uses USER_PROVIDED auth (a user-managed key). Drives the+ * cog-vs-info affordance on the web_search card/row: configurable only when a+ * user key exists; SYSTEM_DEFINED deployments have nothing to configure.+ */+ webSearchUserProvided?: boolean;+}++interface BuiltinDef {+ id: BuiltinId;+ iconKey: string;+ nameKey: string;+ descriptionKey: string;+}++const BUILTIN_DEFINITIONS: BuiltinDef[] = [+ {+ id: AgentCapabilities.execute_code,+ iconKey: 'execute_code',+ nameKey: 'com_ui_run_code',+ descriptionKey: 'com_agents_run_code_info',+ },+ {+ id: AgentCapabilities.web_search,+ iconKey: 'web_search',+ nameKey: 'com_ui_web_search',+ descriptionKey: 'com_agents_search_info',+ },+ {+ id: AgentCapabilities.artifacts,+ iconKey: 'artifacts',+ nameKey: 'com_ui_artifacts',+ descriptionKey: 'com_ui_artifacts_subtext',+ },+ {+ id: AgentCapabilities.file_search,+ iconKey: 'file_search',+ nameKey: 'com_assistants_file_search',+ descriptionKey: 'com_agents_file_search_info',+ },+];++function countEndpoints(settings: Action['settings']): number {+ if (settings == null) {+ return 0;+ }+ const paths = (settings as { paths?: unknown }).paths;+ if (paths == null || typeof paths !== 'object') {+ return 0;+ }+ return Object.keys(paths).length;+}++export function buildCatalog(inputs: BuildCatalogInputs): AgentItem[] {+ const items: AgentItem[] = [];++ const enabled = new Set(inputs.agentsConfig.capabilities);+ for (const def of BUILTIN_DEFINITIONS) {+ if (!enabled.has(def.id)) {+ continue;+ }+ items.push({+ kind: 'builtin',+ id: def.id,+ iconKey: def.iconKey,+ name: def.nameKey,+ description: def.descriptionKey,+ status: inputs.builtinAuthMap?.get(def.id) === true ? 'needs_setup' : undefined,+ userProvidedAuth:+ def.id === AgentCapabilities.web_search ? inputs.webSearchUserProvided === true : undefined,+ });+ }++ if (inputs.showMemory) {+ items.push({+ kind: 'builtin',+ id: AgentCapabilities.memory,+ iconKey: 'memory',+ name: 'com_ui_memory',+ description: 'com_agents_memory_info',+ });+ }++ if (inputs.permissions.mcp) {+ for (const [name, server] of inputs.mcpServersMap) {+ /** Consume-only servers are provided to chat by the deployment and can't+ * be attached to an agent, so they never belong in the catalog. */+ if (server.consumeOnly === true) {+ continue;+ }+ items.push({+ kind: 'mcp',+ id: name,+ name,+ description: server.metadata?.description ?? '',+ iconKey: 'mcp',+ server,+ toolCount: server.tools?.length ?? 0,+ status: server.isConfigured === false ? 'needs_setup' : undefined,+ });+ }+ }++ if (enabled.has(AgentCapabilities.tools)) {+ for (const plugin of inputs.regularTools) {+ items.push({+ kind: 'tool',+ id: plugin.pluginKey,+ name: plugin.name ?? plugin.pluginKey,+ description: plugin.description ?? '',+ iconKey: 'tool',+ plugin,+ status: pluginNeedsAuth(plugin) ? 'needs_setup' : undefined,+ });+ }+ }++ if (inputs.permissions.skills) {+ items.push(...buildSkillItems(inputs.skills, inputs.currentUserId));+ }++ for (const action of inputs.actions) {+ items.push({+ kind: 'action',+ id: action.action_id,+ name: action.metadata?.domain ?? action.action_id,+ description: '',+ iconKey: 'action',+ action,+ endpointCount: countEndpoints(action.settings),+ });+ }++ return items;+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/configurable.ts b/client/src/components/SidePanel/Agents/Tools/items/configurable.tsnew file mode 100644index 0000000000..07bbdfecb6--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/configurable.ts@@ -0,0 +1,29 @@+import type { AgentItem } from './types';+import { pluginNeedsAuth } from './auth';++/**+ * Whether an item's detail dialog exposes configurable controls (credentials,+ * tool selection, server/action settings) beyond a plain description. Drives the+ * Settings-vs-Info affordance: a configurable item gets a cog button, an+ * informational one gets an info icon.+ */+export function hasConfigurableSettings(item: AgentItem): boolean {+ switch (item.kind) {+ case 'builtin':+ return (+ item.id === 'artifacts' ||+ item.id === 'file_search' ||+ item.id === 'context' ||+ (item.id === 'web_search' && item.userProvidedAuth === true)+ );+ case 'tool':+ return pluginNeedsAuth(item.plugin);+ case 'mcp':+ case 'action':+ return true;+ case 'skill':+ return false;+ default:+ return false;+ }+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/filtering.ts b/client/src/components/SidePanel/Agents/Tools/items/filtering.tsnew file mode 100644index 0000000000..ede1e4e374--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/filtering.ts@@ -0,0 +1,68 @@+import type { AgentItem, ItemFilter } from './types';+import { itemKey } from './selectors';++/**+ * Extra, non-serializable inputs the view filter needs. Kept out of+ * `ItemFilter` (which models the persisted filter UI state) so live query data+ * — like the set of favorited ids — can be threaded in by callers.+ */+export interface FilterContext {+ /**+ * Compound `kind:id` keys (the `itemKey` format) of the user's favorited+ * items; required for the `favorites` view. Compound keys prevent an item+ * of one kind from matching a favorite of another kind with the same id.+ */+ favoritedIds?: Set<string>;+}++function getCategory(item: AgentItem): string | undefined {+ if (item.kind === 'skill') {+ return item.skill.category;+ }+ return undefined;+}++function matchesSearch(item: AgentItem, search: string): boolean {+ if (!search) return true;+ const term = search.toLowerCase();+ return item.name.toLowerCase().includes(term) || item.description.toLowerCase().includes(term);+}++function matchesKind(item: AgentItem, kind: ItemFilter['kind']): boolean {+ if (!kind || kind === 'all') return true;+ return item.kind === kind;+}++function matchesCategory(item: AgentItem, category: ItemFilter['category']): boolean {+ if (!category || category === 'all') return true;+ return getCategory(item) === category;+}++export function matchesView(+ item: AgentItem,+ view: ItemFilter['view'],+ context: FilterContext,+): boolean {+ switch (view) {+ case 'mine':+ return item.ownedByUser === true;+ case 'favorites':+ return context.favoritedIds?.has(itemKey(item)) === true;+ default:+ return true;+ }+}++export function applyFilter(+ items: AgentItem[],+ filter: ItemFilter,+ context: FilterContext = {},+): AgentItem[] {+ return items.filter(+ (item) =>+ matchesSearch(item, filter.search ?? '') &&+ matchesKind(item, filter.kind) &&+ matchesCategory(item, filter.category) &&+ matchesView(item, filter.view, context),+ );+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/icons.ts b/client/src/components/SidePanel/Agents/Tools/items/icons.tsnew file mode 100644index 0000000000..632346700e--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/icons.ts@@ -0,0 +1,92 @@+import {+ Code,+ Globe,+ Brain,+ Sparkles,+ FileText,+ FileSearch,+ Wrench,+ Server,+ Workflow,+ Zap,+ Layers,+} from 'lucide-react';+import type { LucideIcon } from 'lucide-react';+import type { AgentItem } from './types';++export interface ItemIcon {+ Icon: LucideIcon;+ colorClass: string;+ iconUrl?: string;+}++const BUILTIN_ICONS: Record<string, ItemIcon> = {+ execute_code: {+ Icon: Code,+ colorClass: 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-300',+ },+ web_search: {+ Icon: Globe,+ colorClass: 'bg-blue-500/15 text-blue-600 dark:text-blue-300',+ },+ artifacts: {+ Icon: Sparkles,+ colorClass: 'bg-purple-500/15 text-purple-600 dark:text-purple-300',+ },+ context: {+ Icon: FileText,+ colorClass: 'bg-amber-500/15 text-amber-600 dark:text-amber-300',+ },+ file_search: {+ Icon: FileSearch,+ colorClass: 'bg-pink-500/15 text-pink-600 dark:text-pink-300',+ },+ memory: {+ Icon: Brain,+ colorClass: 'bg-indigo-500/15 text-indigo-600 dark:text-indigo-300',+ },+};++const KIND_FALLBACK_ICONS: Record<AgentItem['kind'], ItemIcon> = {+ builtin: {+ Icon: Layers,+ colorClass: 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-300',+ },+ tool: {+ Icon: Wrench,+ colorClass: 'bg-sky-500/15 text-sky-600 dark:text-sky-300',+ },+ mcp: {+ Icon: Server,+ colorClass: 'bg-violet-500/15 text-violet-600 dark:text-violet-300',+ },+ skill: {+ Icon: Zap,+ colorClass: 'bg-amber-500/15 text-amber-600 dark:text-amber-300',+ },+ action: {+ Icon: Workflow,+ colorClass: 'bg-rose-500/15 text-rose-600 dark:text-rose-300',+ },+};++function extractIconUrl(item: AgentItem): string | undefined {+ if (item.kind === 'tool') {+ const url = item.plugin?.icon;+ return typeof url === 'string' && url.length > 0 ? url : undefined;+ }+ if (item.kind === 'mcp') {+ const url = item.server?.metadata?.icon;+ return typeof url === 'string' && url.length > 0 ? url : undefined;+ }+ return undefined;+}++export function getIconForItem(item: AgentItem): ItemIcon {+ if (item.kind === 'builtin') {+ return BUILTIN_ICONS[item.iconKey] ?? KIND_FALLBACK_ICONS.builtin;+ }+ const base = KIND_FALLBACK_ICONS[item.kind];+ const iconUrl = extractIconUrl(item);+ return iconUrl ? { ...base, iconUrl } : base;+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/mutations.ts b/client/src/components/SidePanel/Agents/Tools/items/mutations.tsnew file mode 100644index 0000000000..b65d844978--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/mutations.ts@@ -0,0 +1,71 @@+import { AgentCapabilities, ArtifactModes } from 'librechat-data-provider';+import type { AgentItem } from './types';++export type TogglePatch =+ | { type: 'builtin'; field: AgentCapabilities; value: boolean | string }+ | { type: 'tool-add'; id: string }+ | { type: 'tool-remove'; id: string }+ | { type: 'skill-add'; id: string }+ | { type: 'skill-remove'; id: string }+ | { type: 'mcp-add'; serverName: string }+ | { type: 'mcp-remove'; serverName: string }+ | { type: 'action-add'; actionId: string }+ | { type: 'action-remove'; actionId: string };++function builtinTogglePatch(id: string, selected: boolean): TogglePatch {+ // Every BuiltinId string equals its AgentCapabilities enum value, so the id+ // is already the form field name.+ const field = id as AgentCapabilities;+ if (id === 'artifacts') {+ return { type: 'builtin', field, value: selected ? '' : ArtifactModes.DEFAULT };+ }+ return { type: 'builtin', field, value: !selected };+}++export function computeToggleAction(item: AgentItem, state: { selected: boolean }): TogglePatch {+ if (item.kind === 'builtin') {+ return builtinTogglePatch(item.id, state.selected);+ }+ if (item.kind === 'tool') {+ return state.selected+ ? { type: 'tool-remove', id: item.id }+ : { type: 'tool-add', id: item.id };+ }+ if (item.kind === 'skill') {+ return state.selected+ ? { type: 'skill-remove', id: item.id }+ : { type: 'skill-add', id: item.id };+ }+ if (item.kind === 'mcp') {+ return state.selected+ ? { type: 'mcp-remove', serverName: item.id }+ : { type: 'mcp-add', serverName: item.id };+ }+ return state.selected+ ? { type: 'action-remove', actionId: item.id }+ : { type: 'action-add', actionId: item.id };+}++/**+ * `skills_enabled` is the master opt-in for the skill allowlist, and an empty+ * allowlist with the flag on means the FULL accessible catalog. Selection+ * edits therefore sync the flag on empty/non-empty transitions: picking the+ * first skill turns it on so the choice takes effect, and removing the last+ * one turns it off so the agent doesn't silently escalate to every skill.+ * Edits within a non-empty selection return `undefined` (leave the flag+ * alone), preserving the Advanced kill switch's disable-without-clearing+ * behavior.+ */+export function skillsEnabledTransition(+ current: string[],+ next: string[],+ enabled: boolean | undefined,+): boolean | undefined {+ if (current.length === 0 && next.length > 0 && enabled !== true) {+ return true;+ }+ if (current.length > 0 && next.length === 0 && enabled === true) {+ return false;+ }+ return undefined;+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/selectors.ts b/client/src/components/SidePanel/Agents/Tools/items/selectors.tsnew file mode 100644index 0000000000..93b9670242--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/selectors.ts@@ -0,0 +1,116 @@+import { Constants } from 'librechat-data-provider';+import type { Action } from 'librechat-data-provider';+import type { AgentItem, AgentItemKind } from './types';++export interface FormSelection {+ execute_code: boolean;+ web_search: boolean;+ file_search: boolean;+ memory: boolean;+ artifacts: string | undefined;+ tools: string[];+ skills: string[];+ context_files: Array<[string, unknown]>;+ knowledge_files: Array<[string, unknown]>;+ code_files: Array<[string, unknown]>;+}++const KIND_ORDER: AgentItemKind[] = ['builtin', 'mcp', 'tool', 'skill', 'action'];+const MCP_PREFIX = 'mcp_';++/**+ * Stable identity for a catalog item across kinds. IDs come from disjoint+ * namespaces (capability ids, MCP server names, pluginKeys, skill ids, action+ * ids), so selection sets must key on `kind:id` to avoid cross-kind collisions.+ */+export function itemKey(item: Pick<AgentItem, 'kind' | 'id'>): string {+ return `${item.kind}:${item.id}`;+}++function isBuiltinSelected(item: AgentItem, form: FormSelection): boolean {+ if (item.kind !== 'builtin') return false;+ switch (item.id) {+ case 'execute_code':+ return form.execute_code || form.code_files.length > 0;+ case 'web_search':+ return form.web_search;+ case 'file_search':+ return form.file_search || form.knowledge_files.length > 0;+ case 'memory':+ return form.memory;+ case 'artifacts':+ return Boolean(form.artifacts);+ case 'context':+ return form.context_files.length > 0;+ default:+ return false;+ }+}++function isToolSelected(item: AgentItem, form: FormSelection): boolean {+ if (item.kind !== 'tool') return false;+ return form.tools.includes(item.id);+}++/**+ * Server-level placeholder token (`sys__server__sys_mcp_<serverName>`). It pins+ * the server's attachment independently of tool selection, so a server stays+ * attached even with zero tools selected (deselect-all keeps the token); only+ * an explicit remove strips it.+ */+export function mcpServerToken(serverName: string): string {+ return `${Constants.mcp_server}${Constants.mcp_delimiter}${serverName}`;+}++/**+ * Whether a form `tools` token references the given MCP server, across every+ * format ever persisted: the server placeholder token, the raw server name,+ * the exact `mcp_<server>` pluginKey form, and delimiter-suffixed per-tool+ * ids (`<tool>_mcp_<server>`). All checks are exact or delimiter-bounded —+ * server names may contain underscores, so a bare prefix match would claim+ * `mcp_github_extra` for a server named `github`. Selection and removal must+ * share this predicate: anything the selection logic counts as attached, an+ * explicit remove must also strip, or a legacy token leaves the server+ * permanently selected.+ */+export function matchesMcpServer(token: string, serverName: string): boolean {+ const prefixed = `${MCP_PREFIX}${serverName}`;+ return (+ token === mcpServerToken(serverName) ||+ token === serverName ||+ token === prefixed ||+ token.endsWith(`_${prefixed}`)+ );+}++function isMcpSelected(item: AgentItem, form: FormSelection): boolean {+ if (item.kind !== 'mcp') return false;+ return form.tools.some((t) => matchesMcpServer(t, item.id));+}++function isSkillSelected(item: AgentItem, form: FormSelection): boolean {+ if (item.kind !== 'skill') return false;+ return form.skills.includes(item.id);+}++function isActionSelected(item: AgentItem, agentActions: Action[]): boolean {+ if (item.kind !== 'action') return false;+ return agentActions.some((a) => a.action_id === item.id);+}++export function deriveSelectedItems(+ form: FormSelection,+ catalog: AgentItem[],+ agentActions: Action[],+): AgentItem[] {+ const selected = catalog.filter((item) => {+ if (item.kind === 'builtin') return isBuiltinSelected(item, form);+ if (item.kind === 'tool') return isToolSelected(item, form);+ if (item.kind === 'mcp') return isMcpSelected(item, form);+ if (item.kind === 'skill') return isSkillSelected(item, form);+ if (item.kind === 'action') return isActionSelected(item, agentActions);+ return false;+ });++ return selected.sort((a, b) => KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind));+}diff --git a/client/src/components/SidePanel/Agents/Tools/items/types.ts b/client/src/components/SidePanel/Agents/Tools/items/types.tsnew file mode 100644index 0000000000..26ac623226--- /dev/null+++ b/client/src/components/SidePanel/Agents/Tools/items/types.ts@@ -0,0 +1,88 @@+import type { TPlugin, TSkillSummary, Action, AgentCapabilities } from 'librechat-data-provider';+import type { MCPServerInfo } from '~/common';++export type AgentItemKind = 'builtin' | 'tool' | 'mcp' | 'skill' | 'action';++/**+ * Literal IDs for the built-in agent capabilities surfaced in the catalog.+ * Derived from `AgentCapabilities` so a renamed or removed enum member breaks+ * the build here instead of drifting silently.+ */+export type BuiltinId =+ | `${AgentCapabilities.execute_code}`+ | `${AgentCapabilities.web_search}`+ | `${AgentCapabilities.file_search}`+ | `${AgentCapabilities.artifacts}`+ | `${AgentCapabilities.memory}`+ | `${AgentCapabilities.context}`;++export type AgentItemStatus = 'needs_setup';++interface ItemBase {+ id: string;+ name: string;+ description: string;+ iconKey: string;+ status?: AgentItemStatus;+ /**+ * True when the catalog item was authored by the current user. Drives the+ * "Made by you" sidebar view. Only kinds carrying an author signal can set+ * this (today: skills, via `TSkillSummary.author`); all other kinds default+ * to `false` since they expose no per-user ownership.+ */+ ownedByUser?: boolean;+}++export interface BuiltinItem extends ItemBase {+ kind: 'builtin';+ id: BuiltinId;+ /**+ * True when `web_search` auth is USER_PROVIDED (a user-managed key exists to+ * configure). Undefined/false means SYSTEM_DEFINED — nothing to configure, so+ * the card/row shows an info icon instead of a settings cog.+ */+ userProvidedAuth?: boolean;+}++export interface ToolItem extends ItemBase {+ kind: 'tool';+ plugin: TPlugin;+}++export interface McpItem extends ItemBase {+ kind: 'mcp';+ server: MCPServerInfo;+ toolCount: number;+}++export interface SkillItem extends ItemBase {+ kind: 'skill';+ skill: TSkillSummary;+}++export interface ActionItem extends ItemBase {+ kind: 'action';+ /**+ * The persisted action. Absent for the marketplace "create new action" flow,+ * which is discriminated by a sentinel `id` (see `NEW_ACTION_ID`); the editor+ * never reads `action` in that mode.+ */+ action?: Action;+ endpointCount: number;+}++export type AgentItem = BuiltinItem | ToolItem | McpItem | SkillItem | ActionItem;++export type ItemFilter = {+ search?: string;+ kind?: AgentItemKind | 'all';+ category?: string | 'all';+ view?: 'marketplace' | 'favorites' | 'mine';+};++/**+ * Sentinel `ActionItem.id` marking the ItemDialog as a create-new-action flow:+ * the marketplace opens the dialog with this id and no `action`, and+ * `ActionSection` renders an empty editor for it.+ */+export const NEW_ACTION_ID = '__new_action__';diff --git a/client/src/components/SidePanel/Agents/UnconfiguredMCPTool.tsx b/client/src/components/SidePanel/Agents/UnconfiguredMCPTool.tsxdeleted file mode 100644index 6d18814776..0000000000--- a/client/src/components/SidePanel/Agents/UnconfiguredMCPTool.tsx+++ /dev/null@@ -1,84 +0,0 @@-import React, { useState } from 'react';-import { CircleX } from 'lucide-react';-import { Label, OGDialog, TrashIcon, OGDialogTrigger, OGDialogTemplate } from '@librechat/client';-import { useLocalize, useRemoveMCPTool } from '~/hooks';-import { cn } from '~/utils';--export default function UnconfiguredMCPTool({ serverName }: { serverName?: string }) {- const localize = useLocalize();- const { removeTool } = useRemoveMCPTool();-- const [isFocused, setIsFocused] = useState(false);- const [isHovering, setIsHovering] = useState(false);-- if (!serverName) {- return null;- }-- return (- <OGDialog>- <div- className="group relative flex w-full items-center gap-1 rounded-lg p-1 text-sm hover:bg-surface-primary-alt"- onMouseEnter={() => setIsHovering(true)}- onMouseLeave={() => setIsHovering(false)}- onFocus={() => setIsFocused(true)}- onBlur={(e) => {- if (!e.currentTarget.contains(e.relatedTarget)) {- setIsFocused(false);- }- }}- >- <div className="flex items-center">- <div className="flex h-6 w-6 items-center justify-center rounded p-1">- <CircleX className="h-4 w-4 text-red-500" />- </div>- </div>-- <div className="flex grow cursor-not-allowed items-center gap-1 rounded bg-transparent p-0 text-left transition-colors">- <div- className="grow select-none px-2 py-1.5"- style={{ textOverflow: 'ellipsis', wordBreak: 'break-all', overflow: 'hidden' }}- >- {serverName}- <span className="ml-2 text-xs text-text-secondary">- {' - '}- {localize('com_ui_unavailable')}- </span>- </div>- </div>-- <OGDialogTrigger asChild>- <button- type="button"- className={cn(- 'flex h-7 w-7 items-center justify-center rounded transition-all duration-200 hover:bg-surface-active-alt focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1',- isHovering || isFocused ? 'opacity-100' : 'pointer-events-none opacity-0',- )}- aria-label={`Delete ${serverName}`}- tabIndex={0}- onFocus={() => setIsFocused(true)}- >- <TrashIcon className="h-4 w-4" />- </button>- </OGDialogTrigger>- </div>- <OGDialogTemplate- showCloseButton={false}- title={localize('com_ui_delete_tool')}- mainClassName="px-0"- className="max-w-[450px]"- main={- <Label className="text-left text-sm font-medium">- {localize('com_ui_delete_tool_confirm')}- </Label>- }- selection={{- selectHandler: () => removeTool(serverName || ''),- selectClasses:- 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',- selectText: localize('com_ui_delete'),- }}- />- </OGDialog>- );-}diff --git a/client/src/components/SidePanel/Agents/UninitializedMCPTool.tsx b/client/src/components/SidePanel/Agents/UninitializedMCPTool.tsxdeleted file mode 100644index 24d45d4681..0000000000--- a/client/src/components/SidePanel/Agents/UninitializedMCPTool.tsx+++ /dev/null@@ -1,139 +0,0 @@-import React, { useState } from 'react';-import { Label, OGDialog, TrashIcon, OGDialogTrigger, OGDialogTemplate } from '@librechat/client';-import type { MCPServerInfo } from '~/common';-import { useLocalize, useMCPServerManager, useRemoveMCPTool } from '~/hooks';-import MCPServerStatusIcon from '~/components/MCP/MCPServerStatusIcon';-import MCPConfigDialog from '~/components/MCP/MCPConfigDialog';-import { cn } from '~/utils';--export default function UninitializedMCPTool({ serverInfo }: { serverInfo?: MCPServerInfo }) {- const localize = useLocalize();- const { removeTool } = useRemoveMCPTool();-- const [isFocused, setIsFocused] = useState(false);- const [isHovering, setIsHovering] = useState(false);-- const { initializeServer, isInitializing, getServerStatusIconProps, getConfigDialogProps } =- useMCPServerManager();-- if (!serverInfo) {- return null;- }-- const serverName = serverInfo.serverName;- const isServerInitializing = isInitializing(serverName);- const statusIconProps = getServerStatusIconProps(serverName);- const configDialogProps = getConfigDialogProps();-- const statusIcon = statusIconProps && (- <div- onClick={(e) => {- e.stopPropagation();- }}- className="cursor-pointer rounded p-0.5 hover:bg-surface-secondary"- >- <MCPServerStatusIcon {...statusIconProps} />- </div>- );-- return (- <OGDialog>- <div- className="group relative flex w-full items-center gap-1 rounded-lg p-1 text-sm hover:bg-surface-primary-alt"- onMouseEnter={() => setIsHovering(true)}- onMouseLeave={() => setIsHovering(false)}- onFocus={() => setIsFocused(true)}- onBlur={(e) => {- if (!e.currentTarget.contains(e.relatedTarget)) {- setIsFocused(false);- }- }}- >- <div- className="flex grow cursor-pointer items-center gap-1 rounded bg-transparent p-0 text-left transition-colors"- onClick={(e) => {- if ((e.target as HTMLElement).closest('[data-status-icon]')) {- return;- }- if (!isServerInitializing) {- initializeServer(serverName);- }- }}- role="button"- tabIndex={0}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- if (!isServerInitializing) {- initializeServer(serverName);- }- }- }}- aria-disabled={isServerInitializing}- >- {statusIcon && (- <div className="flex items-center" data-status-icon>- {statusIcon}- </div>- )}-- {serverInfo.metadata.icon && (- <div className="flex h-8 w-8 items-center justify-center overflow-hidden rounded-full">- <div- className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full bg-center bg-no-repeat dark:bg-white/20"- style={{- backgroundImage: `url(${serverInfo.metadata.icon})`,- backgroundSize: 'cover',- }}- />- </div>- )}- <div- className="grow px-2 py-1.5"- style={{ textOverflow: 'ellipsis', wordBreak: 'break-all', overflow: 'hidden' }}- >- {serverName}- {isServerInitializing && (- <span className="ml-2 text-xs text-text-secondary">- {localize('com_ui_initializing')}- </span>- )}- </div>- </div>-- <OGDialogTrigger asChild>- <button- type="button"- className={cn(- 'flex h-7 w-7 items-center justify-center rounded transition-all duration-200 hover:bg-surface-active-alt focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1',- isHovering || isFocused ? 'opacity-100' : 'pointer-events-none opacity-0',- )}- aria-label={`Delete ${serverName}`}- tabIndex={0}- onFocus={() => setIsFocused(true)}- >- <TrashIcon className="h-4 w-4" />- </button>- </OGDialogTrigger>- </div>- <OGDialogTemplate- showCloseButton={false}- title={localize('com_ui_delete_tool')}- mainClassName="px-0"- className="max-w-[450px]"- main={- <Label className="text-left text-sm font-medium">- {localize('com_ui_delete_tool_confirm')}- </Label>- }- selection={{- selectHandler: () => removeTool(serverName),- selectClasses:- 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',- selectText: localize('com_ui_delete'),- }}- />- {configDialogProps && <MCPConfigDialog {...configDialogProps} />}- </OGDialog>- );-}diff --git a/client/src/components/SidePanel/Agents/UploadDropzone.tsx b/client/src/components/SidePanel/Agents/UploadDropzone.tsxnew file mode 100644index 0000000000..7d3e1d2616--- /dev/null+++ b/client/src/components/SidePanel/Agents/UploadDropzone.tsx@@ -0,0 +1,24 @@+import { Upload } from 'lucide-react';++export const dropzoneClassName =+ 'group flex w-full flex-col items-center justify-center gap-2.5 rounded-xl border border-dashed border-border-medium bg-surface-secondary px-4 py-7 text-sm font-medium text-text-secondary transition-colors hover:border-border-heavy hover:bg-surface-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:border-border-medium disabled:hover:bg-surface-secondary disabled:hover:text-text-secondary';++function DropzoneContent({ label, hint }: { label: string; hint?: string }) {+ return (+ <span className="pointer-events-none flex flex-col items-center justify-center gap-2 text-center">+ <span className="flex h-9 w-9 items-center justify-center rounded-full bg-surface-tertiary text-text-secondary transition-colors group-hover:text-text-primary">+ <Upload className="h-[18px] w-[18px]" strokeWidth={2} aria-hidden="true" />+ </span>+ <span className="flex flex-col gap-0.5">+ <span className="text-sm font-medium text-text-primary">{label}</span>+ {hint ? (+ <span className="text-xs font-normal text-text-secondary transition-colors group-hover:text-text-primary">+ {hint}+ </span>+ ) : null}+ </span>+ </span>+ );+}++export default DropzoneContent;diff --git a/client/src/components/SidePanel/Agents/Version/VersionButton.tsx b/client/src/components/SidePanel/Agents/Version/VersionButton.tsxindex 0288c2f705..f9ecb7e540 100644--- a/client/src/components/SidePanel/Agents/Version/VersionButton.tsx+++ b/client/src/components/SidePanel/Agents/Version/VersionButton.tsx@@ -1,5 +1,4 @@import { History } from 'lucide-react';-import { Button } from '@librechat/client';import { useLocalize } from '~/hooks';import { Panel } from '~/common';@@ -11,16 +10,15 @@ const VersionButton = ({ setActivePanel }: VersionButtonProps) => {const localize = useLocalize();return (- <Button- size={'sm'}- variant={'outline'}- className="btn btn-neutral border-token-border-light relative h-9 w-full gap-1 rounded-lg font-medium"+ <button+ type="button"onClick={() => setActivePanel(Panel.version)}aria-label={localize('com_ui_agent_version')}+ className="inline-flex h-9 w-full items-center justify-center gap-2 rounded-xl border border-border-light bg-transparent px-3 text-sm font-medium text-text-primary transition-colors hover:bg-surface-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary">- <History className="h-4 w-4 cursor-pointer" aria-hidden="true" />+ <History className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />{localize('com_ui_agent_version')}- </Button>+ </button>);};diff --git a/client/src/components/SidePanel/Agents/Version/VersionContent.tsx b/client/src/components/SidePanel/Agents/Version/VersionContent.tsxindex f2f449cb1f..4047d3037d 100644--- a/client/src/components/SidePanel/Agents/Version/VersionContent.tsx+++ b/client/src/components/SidePanel/Agents/Version/VersionContent.tsx@@ -1,4 +1,5 @@import { Spinner } from '@librechat/client';+import { History, AlertCircle, UserX } from 'lucide-react';import type { VersionContext } from './types';import VersionItem from './VersionItem';import { useLocalize } from '~/hooks';@@ -11,6 +12,51 @@ type VersionContentProps = {onRestore: (index: number) => void;};+function EmptyState({+ icon,+ title,+ tone = 'default',+}: {+ icon: React.ReactNode;+ title: string;+ tone?: 'default' | 'danger';+}) {+ const iconWrapBase = 'mb-3 flex h-12 w-12 items-center justify-center rounded-full border';+ const iconWrapTone =+ tone === 'danger'+ ? 'border-red-200 bg-red-50 text-red-500 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-400'+ : 'border-border-light bg-surface-secondary text-text-secondary';+ const textTone = tone === 'danger' ? 'text-red-600 dark:text-red-400' : 'text-text-secondary';++ return (+ <div className="flex flex-col items-center justify-center px-4 py-12 text-center">+ <div className={`${iconWrapBase} ${iconWrapTone}`} aria-hidden="true">+ {icon}+ </div>+ <p className={`max-w-xs text-sm ${textTone}`}>{title}</p>+ </div>+ );+}++function VersionListSkeleton() {+ return (+ <ul aria-hidden="true" className="flex flex-col">+ {[0, 1, 2].map((i) => (+ <li key={i} className="relative flex items-stretch">+ <div className="relative flex w-6 shrink-0 justify-center">+ {i < 2 && <div className="absolute -bottom-3 top-0 w-px bg-border-light" />}+ <div className="relative z-10 mt-4 size-5 shrink-0 rounded-full border-2 border-border-light bg-surface-secondary" />+ </div>+ <div className="mb-2 ml-2 flex flex-1 flex-col gap-2 rounded-xl border border-border-light bg-transparent p-3">+ <div className="h-3 w-24 animate-pulse rounded bg-surface-secondary" />+ <div className="h-3 w-40 animate-pulse rounded bg-surface-secondary" />+ </div>+ </li>+ ))}+ </ul>+ );+}+export default function VersionContent({selectedAgentId,isLoading,@@ -23,29 +69,38 @@ export default function VersionContent({if (!selectedAgentId) {return (- <div className="py-8 text-center text-text-secondary">- {localize('com_ui_agent_version_no_agent')}- </div>+ <EmptyState+ icon={<UserX className="h-5 w-5" />}+ title={localize('com_ui_agent_version_no_agent')}+ />);}if (isLoading) {return (- <div className="flex items-center justify-center py-8">- <Spinner className="h-6 w-6" />+ <div className="flex flex-col gap-4">+ <div className="flex items-center justify-center py-2" role="status" aria-live="polite">+ <Spinner className="h-5 w-5" />+ <span className="sr-only">{localize('com_ui_loading')}</span>+ </div>+ <VersionListSkeleton /></div>);}if (error) {return (- <div className="py-8 text-center text-red-500">{localize('com_ui_agent_version_error')}</div>+ <EmptyState+ icon={<AlertCircle className="h-5 w-5" />}+ title={localize('com_ui_agent_version_error')}+ tone="danger"+ />);}if (versionIds.length > 0) {return (- <div className="flex flex-col gap-2">+ <ul aria-label={localize('com_ui_agent_version_history')} className="flex flex-col">{versionIds.map(({ id, version, isActive }) => (<VersionItemkey={id}@@ -56,13 +111,14 @@ export default function VersionContent({onRestore={onRestore}/>))}- </div>+ </ul>);}return (- <div className="py-8 text-center text-text-secondary">- {localize('com_ui_agent_version_empty')}- </div>+ <EmptyState+ icon={<History className="h-5 w-5" />}+ title={localize('com_ui_agent_version_empty')}+ />);}diff --git a/client/src/components/SidePanel/Agents/Version/VersionItem.tsx b/client/src/components/SidePanel/Agents/Version/VersionItem.tsxindex 931eb09a80..407860caa8 100644--- a/client/src/components/SidePanel/Agents/Version/VersionItem.tsx+++ b/client/src/components/SidePanel/Agents/Version/VersionItem.tsx@@ -1,5 +1,16 @@-import { useLocalize } from '~/hooks';+import { useState } from 'react';+import { formatDistanceToNow } from 'date-fns';+import { Check, RotateCcw, Circle } from 'lucide-react';+import {+ Label,+ OGDialog,+ OGDialogTrigger,+ OGDialogTemplate,+ TooltipAnchor,+} from '@librechat/client';import type { VersionRecord } from './types';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';type VersionItemProps = {version: VersionRecord;@@ -9,6 +20,22 @@ type VersionItemProps = {onRestore: (index: number) => void;};+function getTimestampDate(version: VersionRecord): Date | null {+ const value = version.updatedAt ?? version.createdAt;+ if (!value) {+ return null;+ }+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) {+ return null;+ }+ return date;+}++function countItems(value: unknown): number {+ return Array.isArray(value) ? value.length : 0;+}+export default function VersionItem({version,index,@@ -17,51 +44,206 @@ export default function VersionItem({onRestore,}: VersionItemProps) {const localize = useLocalize();+ const [open, setOpen] = useState(false);++ const versionNumber = versionsLength - index;+ const isLatest = index === 0;+ const isLast = index === versionsLength - 1;- const getVersionTimestamp = (version: VersionRecord): string => {- const timestamp = version.updatedAt || version.createdAt;+ const date = getTimestampDate(version);+ const hasUpdatedAt = version.updatedAt != null;+ const hasCreatedAt = version.createdAt != null;+ const fallbackDateLabel = localize(+ hasUpdatedAt || hasCreatedAt+ ? 'com_ui_agent_version_unknown_date'+ : 'com_ui_agent_version_no_date',+ );+ const relativeLabel = date ? formatDistanceToNow(date, { addSuffix: true }) : fallbackDateLabel;+ const absoluteLabel = date ? date.toLocaleString() : relativeLabel;- if (timestamp) {- try {- const date = new Date(timestamp);- if (isNaN(date.getTime()) || date.toString() === 'Invalid Date') {- return localize('com_ui_agent_version_unknown_date');- }- return date.toLocaleString();- } catch (error) {- return localize('com_ui_agent_version_unknown_date');- }- }+ const toolsCount = countItems(version.tools);+ const capabilitiesCount = countItems(version.capabilities);+ const summaryChips: Array<{ key: string; label: string }> = [];+ if (toolsCount > 0) {+ summaryChips.push({+ key: 'tools',+ label: localize(toolsCount === 1 ? 'com_ui_tools_count_one' : 'com_ui_tools_count', {+ count: toolsCount,+ }),+ });+ }+ if (capabilitiesCount > 0) {+ summaryChips.push({+ key: 'capabilities',+ label: localize(+ capabilitiesCount === 1 ? 'com_ui_capabilities_count_one' : 'com_ui_capabilities_count',+ { count: capabilitiesCount },+ ),+ });+ }- return localize('com_ui_agent_version_no_date');- };+ const versionName = typeof version.name === 'string' ? version.name : null;+ const versionTitle = localize('com_ui_agent_version_title', { versionNumber });return (- <div className="rounded-md border border-border-light p-3">- <div className="flex items-center justify-between font-medium">- <span>- {localize('com_ui_agent_version_title', { versionNumber: versionsLength - index })}- </span>- {isActive && (- <span className="rounded-full border border-green-600 bg-green-600/20 px-2 py-0.5 text-xs font-medium text-green-700 dark:border-green-500 dark:bg-green-500/30 dark:text-green-300">- {localize('com_ui_agent_version_active')}- </span>+ <li className="relative flex items-stretch" aria-current={isActive ? 'true' : undefined}>+ {/* Timeline rail */}+ <div className="relative flex w-6 shrink-0 justify-center">+ {!isLast && (+ <div+ className={cn(+ 'absolute -bottom-3 top-0 w-px',+ isActive ? 'bg-green-500/40' : 'bg-border-light',+ )}+ />)}- </div>- <div className="text-sm text-text-secondary">{getVersionTimestamp(version)}</div>- {!isActive && (- <button- className="mt-2 text-sm text-blue-500 hover:text-blue-600"- onClick={() => {- if (window.confirm(localize('com_ui_agent_version_restore_confirm'))) {- onRestore(index);- }- }}- aria-label={localize('com_ui_agent_version_restore')}+ <div+ className={cn(+ 'relative z-10 mt-4 flex size-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors',+ isActive+ ? 'border-green-500 bg-green-500 text-white'+ : 'border-border-medium bg-surface-primary text-text-secondary',+ )}+ aria-hidden="true">- {localize('com_ui_agent_version_restore')}- </button>- )}- </div>+ {isActive ? (+ <Check className="size-3" strokeWidth={3} />+ ) : (+ <Circle className="size-1.5" fill="currentColor" />+ )}+ </div>+ </div>++ {/* Card */}+ <div+ className={cn(+ 'group relative mb-2 ml-2 flex flex-1 flex-col rounded-xl border p-3 transition-colors',+ isActive+ ? 'border-green-500/40 bg-green-50/60 dark:border-green-500/30 dark:bg-green-950/20'+ : 'border-border-light bg-transparent hover:border-border-medium hover:bg-surface-secondary',+ )}+ >+ <div className="flex items-start justify-between gap-2">+ <div className="flex min-w-0 flex-col">+ <div className="flex items-center gap-2">+ <span+ className={cn(+ 'truncate text-sm font-semibold',+ isActive ? 'text-green-700 dark:text-green-300' : 'text-text-primary',+ )}+ >+ {versionTitle}+ </span>+ {isActive && (+ <span className="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-green-700 dark:text-green-300">+ <span className="size-1.5 rounded-full bg-green-500" aria-hidden="true" />+ {localize('com_ui_agent_version_current')}+ </span>+ )}+ {!isActive && isLatest && (+ <span className="rounded-full bg-surface-tertiary px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-text-secondary">+ {localize('com_ui_latest')}+ </span>+ )}+ </div>+ {versionName && (+ <span className="mt-0.5 truncate text-xs text-text-secondary" title={versionName}>+ {versionName}+ </span>+ )}+ </div>+ {!isActive && (+ <OGDialog open={open} onOpenChange={setOpen}>+ <OGDialogTrigger asChild>+ <TooltipAnchor+ description={localize('com_ui_agent_version_restore')}+ side="left"+ render={+ <button+ type="button"+ aria-label={localize('com_ui_agent_version_restore')}+ className="inline-flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-lg border border-border-light text-text-secondary opacity-0 transition-all hover:border-border-medium hover:bg-surface-hover hover:text-text-primary focus:outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring-primary group-hover:opacity-100"+ >+ <RotateCcw className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden="true" />+ </button>+ }+ />+ </OGDialogTrigger>+ <OGDialogTemplate+ title={localize('com_ui_agent_version_restore_confirm')}+ className="max-w-[450px]"+ main={+ <div className="flex w-full flex-col gap-3 text-sm">+ <Label className="text-left font-medium text-text-primary">+ {localize('com_ui_agent_version_restore_description')}+ </Label>+ <div className="rounded-lg border border-border-light bg-surface-secondary px-3 py-2">+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-semibold text-text-primary">+ {versionTitle}+ </span>+ <time+ className="text-xs text-text-secondary"+ dateTime={date?.toISOString()}+ >+ {absoluteLabel}+ </time>+ </div>+ {versionName && (+ <div className="mt-1 truncate text-xs text-text-secondary">+ {versionName}+ </div>+ )}+ </div>+ </div>+ }+ selection={{+ selectHandler: () => onRestore(index),+ selectClasses:+ 'bg-green-600 hover:bg-green-700 dark:hover:bg-green-700 text-white',+ selectText: localize('com_ui_agent_version_restore'),+ }}+ />+ </OGDialog>+ )}+ </div>++ <div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1">+ {date ? (+ <TooltipAnchor+ description={absoluteLabel}+ side="bottom"+ render={+ <time+ dateTime={date.toISOString()}+ className="cursor-help text-xs text-text-secondary"+ >+ {relativeLabel}+ </time>+ }+ />+ ) : (+ <span className="text-xs text-text-secondary">{relativeLabel}</span>+ )}+ {summaryChips.length > 0 && (+ <>+ <span aria-hidden="true" className="text-text-tertiary">+ ·+ </span>+ {summaryChips.map((chip, i) => (+ <span key={chip.key} className="flex items-center gap-1.5">+ {i > 0 && (+ <span aria-hidden="true" className="text-text-tertiary">+ ·+ </span>+ )}+ <span className="text-xs text-text-secondary">{chip.label}</span>+ </span>+ ))}+ </>+ )}+ </div>+ </div>+ </li>);}diff --git a/client/src/components/SidePanel/Agents/Version/VersionPanel.tsx b/client/src/components/SidePanel/Agents/Version/VersionPanel.tsxindex 0bf3749c46..874931679c 100644--- a/client/src/components/SidePanel/Agents/Version/VersionPanel.tsx+++ b/client/src/components/SidePanel/Agents/Version/VersionPanel.tsx@@ -129,27 +129,39 @@ export default function VersionPanel() {[revertAgentVersion, selectedAgentId, versionIds],);+ const versionCount = versionIds.length;+ const countLabel =+ versionCount > 0+ ? localize(+ versionCount === 1 ? 'com_ui_agent_version_count_one' : 'com_ui_agent_version_count',+ { count: versionCount },+ )+ : null;+return (<div className="scrollbar-gutter-stable h-full min-h-[40vh] overflow-auto pb-12 text-sm">- <div className="version-panel relative flex flex-col items-center px-16 py-4 text-center">- <div className="absolute left-0 top-4">- <button- type="button"- className="btn btn-neutral relative"- onClick={() => {- setActivePanel(Panel.builder);- }}- >- <div className="version-panel-content flex w-full items-center justify-center gap-2">- <ChevronLeft />- </div>- </button>+ <header className="grid grid-cols-[auto_1fr_auto] items-center gap-2 px-2 pb-2 pt-1">+ <button+ type="button"+ onClick={() => setActivePanel(Panel.builder)}+ aria-label={localize('com_ui_back_to_builder')}+ className="inline-flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-border-light text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <ChevronLeft className="h-5 w-5" strokeWidth={1.75} aria-hidden="true" />+ </button>+ <div className="flex flex-col items-center">+ <h2 className="text-base font-semibold text-text-primary">+ {localize('com_ui_agent_version_history')}+ </h2>+ {countLabel && (+ <p className="text-xs text-text-secondary" aria-live="polite">+ {countLabel}+ </p>+ )}</div>- <div className="mb-2 mt-2 text-xl font-medium">- {localize('com_ui_agent_version_history')}- </div>- </div>- <div className="flex flex-col gap-4 px-2">+ <span aria-hidden="true" className="h-10 w-10" />+ </header>+ <div className="flex flex-col px-2 pt-2"><VersionContentselectedAgentId={selectedAgentId}isLoading={isLoading}diff --git a/client/src/components/SidePanel/Agents/Version/__tests__/VersionItem.spec.tsx b/client/src/components/SidePanel/Agents/Version/__tests__/VersionItem.spec.tsxindex f6798fd025..4cdd5db215 100644--- a/client/src/components/SidePanel/Agents/Version/__tests__/VersionItem.spec.tsx+++ b/client/src/components/SidePanel/Agents/Version/__tests__/VersionItem.spec.tsx@@ -4,21 +4,44 @@ import type { VersionRecord } from '../types';import VersionItem from '../VersionItem';jest.mock('~/hooks', () => ({- useLocalize: jest.fn().mockImplementation(() => (key, params) => {- const translations = {- com_ui_agent_version_title: params?.versionNumber- ? `Version ${params.versionNumber}`- : 'Version',- com_ui_agent_version_active: 'Active Version',- com_ui_agent_version_restore: 'Restore',- com_ui_agent_version_restore_confirm: 'Are you sure you want to restore this version?',- com_ui_agent_version_unknown_date: 'Unknown date',- com_ui_agent_version_no_date: 'No date',- };- return translations[key] || key;- }),+ useLocalize: jest+ .fn()+ .mockImplementation(() => (key: string, params?: Record<string, unknown>) => {+ const translations: Record<string, string> = {+ com_ui_agent_version_title: params?.versionNumber+ ? `Version ${params.versionNumber}`+ : 'Version',+ com_ui_agent_version_current: 'Current',+ com_ui_agent_version_restore: 'Restore',+ com_ui_agent_version_restore_confirm: 'Are you sure you want to restore this version?',+ com_ui_agent_version_restore_description: 'This will replace your current configuration.',+ com_ui_agent_version_unknown_date: 'Unknown date',+ com_ui_agent_version_no_date: 'No date',+ com_ui_latest: 'Latest',+ };+ return translations[key] || key;+ }),}));+jest.mock('@librechat/client', () => {+ const React = jest.requireActual('react');+ return {+ Label: ({ children, ...rest }: any) => React.createElement('label', rest, children),+ TooltipAnchor: ({ render }: { render: React.ReactNode }) => render,+ OGDialog: ({ children }: any) => React.createElement(React.Fragment, null, children),+ OGDialogTrigger: ({ children }: any) => children,+ OGDialogTemplate: ({ selection }: any) =>+ React.createElement(+ 'button',+ {+ 'data-testid': 'restore-confirm-button',+ onClick: selection?.selectHandler,+ },+ selection?.selectText ?? 'Confirm',+ ),+ };+});+describe('VersionItem', () => {const mockVersion: VersionRecord = {name: 'Test Agent',@@ -37,51 +60,39 @@ describe('VersionItem', () => {beforeEach(() => {jest.clearAllMocks();- window.confirm = jest.fn().mockImplementation(() => true);});- test('renders version number and timestamp', () => {+ test('renders version number', () => {render(<VersionItem {...defaultProps} />);expect(screen.getByText('Version 2')).toBeInTheDocument();- const date = new Date('2023-01-01T00:00:00Z').toLocaleString();- expect(screen.getByText(date)).toBeInTheDocument();});- test('active version badge and no restore button when active', () => {+ test('active version shows current badge and no restore action', () => {render(<VersionItem {...defaultProps} isActive={true} />);- expect(screen.getByText('Active Version')).toBeInTheDocument();- expect(screen.queryByText('Restore')).not.toBeInTheDocument();+ expect(screen.getByText('Current')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Restore' })).not.toBeInTheDocument();});- test('restore button and no active badge when not active', () => {+ test('inactive version renders restore trigger and no current badge', () => {render(<VersionItem {...defaultProps} isActive={false} />);- expect(screen.queryByText('Active Version')).not.toBeInTheDocument();- expect(screen.getByText('Restore')).toBeInTheDocument();+ expect(screen.queryByText('Current')).not.toBeInTheDocument();+ expect(screen.getAllByLabelText('Restore').length).toBeGreaterThan(0);});- test('restore confirmation flow - confirmed', () => {+ test('restoring through dialog confirmation invokes onRestore with index', () => {render(<VersionItem {...defaultProps} />);- fireEvent.click(screen.getByText('Restore'));- expect(window.confirm).toHaveBeenCalledWith('Are you sure you want to restore this version?');+ fireEvent.click(screen.getByTestId('restore-confirm-button'));expect(defaultProps.onRestore).toHaveBeenCalledWith(1);});- test('restore confirmation flow - canceled', () => {- window.confirm = jest.fn().mockImplementation(() => false);- render(<VersionItem {...defaultProps} />);- fireEvent.click(screen.getByText('Restore'));- expect(window.confirm).toHaveBeenCalled();- expect(defaultProps.onRestore).not.toHaveBeenCalled();- });-- test('handles invalid timestamp', () => {+ test('handles invalid timestamp gracefully', () => {render(<VersionItem {...defaultProps} version={{ ...mockVersion, updatedAt: 'invalid-date' }} />,);expect(screen.getByText('Unknown date')).toBeInTheDocument();});- test('handles missing timestamps', () => {+ test('handles missing timestamps with no-date fallback', () => {render(<VersionItem{...defaultProps}@@ -91,34 +102,13 @@ describe('VersionItem', () => {expect(screen.getByText('No date')).toBeInTheDocument();});- test('prefers updatedAt over createdAt when both exist', () => {- const versionWithBothDates = {- ...mockVersion,- updatedAt: '2023-01-02T00:00:00Z',- createdAt: '2023-01-01T00:00:00Z',- };- render(<VersionItem {...defaultProps} version={versionWithBothDates} />);- const updatedDate = new Date('2023-01-02T00:00:00Z').toLocaleString();- expect(screen.getByText(updatedDate)).toBeInTheDocument();- });-- test('falls back to createdAt when updatedAt is missing', () => {- render(- <VersionItem- {...defaultProps}- version={{- ...mockVersion,- updatedAt: undefined,- createdAt: '2023-01-01T00:00:00Z',- }}- />,- );- const createdDate = new Date('2023-01-01T00:00:00Z').toLocaleString();- expect(screen.getByText(createdDate)).toBeInTheDocument();- });-test('handles empty version object', () => {render(<VersionItem {...defaultProps} version={{}} />);expect(screen.getByText('No date')).toBeInTheDocument();});++ test('marks the most recent inactive version as latest', () => {+ render(<VersionItem {...defaultProps} index={0} isActive={false} />);+ expect(screen.getByText('Latest')).toBeInTheDocument();+ });});diff --git a/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsxindex c164cc3ad7..e2e2b9f705 100644--- a/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsx+++ b/client/src/components/SidePanel/Agents/__tests__/AgentFooter.spec.tsx@@ -264,7 +264,7 @@ describe('AgentFooter', () => {describe('Main Functionality', () => {test('renders with standard components based on default state', () => {- render(<AgentFooter {...defaultProps} />);+ const { container } = render(<AgentFooter {...defaultProps} />);expect(screen.getByText('Save')).toBeInTheDocument();expect(screen.getByTestId('advanced-button')).toBeInTheDocument();expect(screen.getByTestId('version-button')).toBeInTheDocument();@@ -272,15 +272,17 @@ describe('AgentFooter', () => {expect(screen.queryByTestId('admin-settings')).not.toBeInTheDocument();expect(screen.getByTestId('grant-access-dialog-agent')).toBeInTheDocument();expect(screen.getByTestId('duplicate-button')).toBeInTheDocument();- expect(screen.queryByTestId('spinner')).not.toBeInTheDocument();+ // The icon-swap always renders both label and spinner; the visible state+ // is driven by data-state ('a' = idle/label, 'b' = saving/spinner).+ expect(container.querySelector('.t-icon-swap')).toHaveAttribute('data-state', 'a');});test('handles loading states for createMutation', () => {- const { unmount } = render(+ const { container, unmount } = render(<AgentFooter {...defaultProps} createMutation={createBaseMutation(true)} />,);expect(screen.getByTestId('spinner')).toBeInTheDocument();- expect(screen.queryByText('Save')).not.toBeInTheDocument();+ expect(container.querySelector('.t-icon-swap')).toHaveAttribute('data-state', 'b');// Find the submit button (the one with aria-busy attribute)const buttons = screen.getAllByRole('button');const submitButton = buttons.find((button) => button.getAttribute('type') === 'submit');@@ -290,9 +292,11 @@ describe('AgentFooter', () => {});test('handles loading states for updateMutation', () => {- render(<AgentFooter {...defaultProps} updateMutation={createBaseMutation(true)} />);+ const { container } = render(+ <AgentFooter {...defaultProps} updateMutation={createBaseMutation(true)} />,+ );expect(screen.getByTestId('spinner')).toBeInTheDocument();- expect(screen.queryByText('Save')).not.toBeInTheDocument();+ expect(container.querySelector('.t-icon-swap')).toHaveAttribute('data-state', 'b');});test('handles loading state when avatar upload is in progress', () => {diff --git a/client/src/components/SidePanel/Agents/__tests__/FileContext.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/FileContext.spec.tsxindex f99d71d2b7..e6c1d74392 100644--- a/client/src/components/SidePanel/Agents/__tests__/FileContext.spec.tsx+++ b/client/src/components/SidePanel/Agents/__tests__/FileContext.spec.tsx@@ -56,11 +56,11 @@ jest.mock('@ariakit/react', () => ({}));jest.mock('@librechat/client', () => ({- HoverCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ SharePointIcon: () => <span />,DropdownPopup: () => null,- AttachmentIcon: () => <span />,+ TooltipAnchor: ({ render }: { render: React.ReactElement }) => render,CircleHelpIcon: () => <span />,- SharePointIcon: () => <span />,+ HoverCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,HoverCardPortal: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,HoverCardContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,HoverCardTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,diff --git a/client/src/components/SidePanel/Agents/__tests__/FileSearch.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/FileSearch.spec.tsxindex 003388f5d8..d3aff49ae5 100644--- a/client/src/components/SidePanel/Agents/__tests__/FileSearch.spec.tsx+++ b/client/src/components/SidePanel/Agents/__tests__/FileSearch.spec.tsx@@ -48,7 +48,6 @@ jest.mock('~/components/SharePoint', () => ({}));jest.mock('~/components/Chat/Input/Files/FileRow', () => () => null);-jest.mock('../FileSearchCheckbox', () => () => null);jest.mock('@ariakit/react', () => ({MenuButton: ({ children, ...props }: { children: React.ReactNode }) => (@@ -58,8 +57,12 @@ jest.mock('@ariakit/react', () => ({jest.mock('@librechat/client', () => ({SharePointIcon: () => <span />,- AttachmentIcon: () => <span />,DropdownPopup: () => null,+ CircleHelpIcon: () => <span />,+ HoverCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ HoverCardPortal: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ HoverCardContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ HoverCardTrigger: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,}));function Wrapper({ provider, children }: { provider?: string; children: React.ReactNode }) {diff --git a/client/src/components/SidePanel/Agents/__tests__/MCPToolItem.spec.tsx b/client/src/components/SidePanel/Agents/__tests__/MCPToolItem.spec.tsxnew file mode 100644index 0000000000..6b6c131a4e--- /dev/null+++ b/client/src/components/SidePanel/Agents/__tests__/MCPToolItem.spec.tsx@@ -0,0 +1,94 @@+import '@testing-library/jest-dom/extend-expect';+import { fireEvent, render, screen } from '@testing-library/react';+import type { AgentToolType } from 'librechat-data-provider';+import MCPToolItem from '../MCPToolItem';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('@librechat/client', () => ({+ TooltipAnchor: ({ render }: { render: React.ReactElement }) => render,+}));++const tool = {+ tool_id: 'mcp:srv:execute',+ metadata: { name: 'execute', description: 'Runs JavaScript code against the API.' },+} as unknown as AgentToolType;++function setup(overrides: Partial<React.ComponentProps<typeof MCPToolItem>> = {}) {+ const props = {+ tool,+ isSelected: false,+ isDeferred: false,+ isProgrammatic: false,+ deferredToolsEnabled: false,+ programmaticToolsEnabled: false,+ onToggleSelect: jest.fn(),+ onToggleDefer: jest.fn(),+ onToggleProgrammatic: jest.fn(),+ ...overrides,+ };+ render(<MCPToolItem {...props} />);+ return props;+}++describe('MCPToolItem', () => {+ test('clicking the row (not just a checkbox) toggles selection', () => {+ const props = setup();+ fireEvent.click(screen.getByRole('button', { name: 'execute' }));+ expect(props.onToggleSelect).toHaveBeenCalledTimes(1);+ });++ test('reflects selection via aria-pressed', () => {+ setup({ isSelected: true });+ expect(screen.getByRole('button', { name: 'execute' })).toHaveAttribute('aria-pressed', 'true');+ });++ test('the info button toggles the description panel via aria-expanded', () => {+ setup();+ const infoButton = screen.getByRole('button', { name: 'com_ui_tools_info' });+ expect(infoButton).toHaveAttribute('aria-expanded', 'false');+ // The description is always rendered (the panel animates open/closed), so it stays queryable.+ expect(screen.getByText('Runs JavaScript code against the API.')).toBeInTheDocument();+ fireEvent.click(infoButton);+ expect(infoButton).toHaveAttribute('aria-expanded', 'true');+ });++ test('detail button is an info affordance when no options are enabled', () => {+ setup();+ expect(screen.getByRole('button', { name: 'com_ui_tools_info' })).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: 'com_ui_mcp_tool_options' }),+ ).not.toBeInTheDocument();+ });++ test('detail button stays an info affordance (never a cog) when options exist', () => {+ setup({ deferredToolsEnabled: true, programmaticToolsEnabled: true });+ expect(screen.getByRole('button', { name: 'com_ui_tools_info' })).toBeInTheDocument();+ expect(+ screen.queryByRole('button', { name: 'com_ui_mcp_tool_options' }),+ ).not.toBeInTheDocument();+ });++ test('defer loading is an inline button (left of the cog) that toggles defer', () => {+ const props = setup({ deferredToolsEnabled: true });+ const deferButton = screen.getByRole('button', { name: 'com_ui_mcp_defer_loading' });+ fireEvent.click(deferButton);+ expect(props.onToggleDefer).toHaveBeenCalledTimes(1);+ });++ test('defer button is absent when deferred tools are disabled', () => {+ setup();+ expect(+ screen.queryByRole('button', { name: 'com_ui_mcp_defer_loading' }),+ ).not.toBeInTheDocument();+ });++ test('programmatic is an inline button rendered only when enabled', () => {+ const props = setup({ programmaticToolsEnabled: true });+ const programmaticButton = screen.getByRole('button', { name: 'com_ui_mcp_programmatic' });+ fireEvent.click(programmaticButton);+ expect(props.onToggleProgrammatic).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/components/SidePanel/Builder/ActionCallback.tsx b/client/src/components/SidePanel/Builder/ActionCallback.tsxindex e319a81dca..bf676acdb2 100644--- a/client/src/components/SidePanel/Builder/ActionCallback.tsx+++ b/client/src/components/SidePanel/Builder/ActionCallback.tsx@@ -1,65 +1,45 @@import { useState } from 'react';-import { Copy, CopyCheck } from 'lucide-react';import { useFormContext } from 'react-hook-form';+import { Input, Label } from '@librechat/client';import { AuthTypeEnum } from 'librechat-data-provider';-import { Button, useToastContext } from '@librechat/client';+import CopyButton from '~/components/Messages/Content/CopyButton';import { useLocalize, useCopyToClipboard } from '~/hooks';-import { cn } from '~/utils';export default function ActionCallback({ action_id }: { action_id?: string }) {const localize = useLocalize();const { watch } = useFormContext();- const { showToast } = useToastContext();- const [isCopying, setIsCopying] = useState(false);+ const [isCopied, setIsCopied] = useState(false);+const callbackURL = `${window.location.protocol}//${window.location.host}/api/actions/${action_id}/oauth/callback`;- const copyLink = useCopyToClipboard({ text: callbackURL });+ const copyCallbackURL = useCopyToClipboard({ text: callbackURL });- if (!action_id) {- return null;- }- const type = watch('type');- if (type !== AuthTypeEnum.OAuth) {+ if (!action_id || watch('type') !== AuthTypeEnum.OAuth) {return null;}+return (- <div className="mb-1.5 flex flex-col space-y-2">- <label className="font-semibold">{localize('com_ui_callback_url')}</label>- <div className="relative flex items-center">- <div className="border-token-border-medium bg-token-surface-primary hover:border-token-border-hover flex h-10 w-full rounded-lg border">- <div className="flex-1 overflow-hidden">- <div className="relative w-full">- <input- type="text"- readOnly- value={callbackURL}- className="w-full border-0 bg-transparent px-3 py-2 pr-12 text-sm text-text-secondary-alt focus:outline-none"- style={{ direction: 'rtl' }}- />- </div>- </div>- <div className="absolute right-0 flex h-full items-center pr-1">- <Button- size="sm"- variant="ghost"- type="button"- onClick={() => {- if (isCopying) {- return;- }- showToast({ message: localize('com_ui_copied_to_clipboard') });- copyLink(setIsCopying);- }}- className={cn('h-8 rounded-md px-2', isCopying ? 'cursor-default' : '')}- aria-label={localize('com_ui_copy_link')}- >- {isCopying ? (- <CopyCheck className="size-4" aria-hidden="true" />- ) : (- <Copy className="size-4" aria-hidden="true" />- )}- </Button>- </div>- </div>+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="oauth-callback-url" className="text-sm font-medium text-text-primary">+ {localize('com_ui_callback_url')}+ </Label>+ <div className="relative">+ <Input+ id="oauth-callback-url"+ type="text"+ readOnly+ dir="ltr"+ value={callbackURL}+ aria-label={localize('com_ui_callback_url')}+ onFocus={(event) => event.currentTarget.select()}+ className="pr-10 text-text-secondary"+ />+ <CopyButton+ iconOnly+ isCopied={isCopied}+ onClick={() => copyCallbackURL(setIsCopied)}+ label={localize('com_ui_copy_link')}+ className="absolute right-1 top-1/2 -translate-y-1/2"+ /></div></div>);diff --git a/client/src/components/SidePanel/Builder/ActionsAuth.tsx b/client/src/components/SidePanel/Builder/ActionsAuth.tsxindex 46d1cbeaaa..34be0eb6cc 100644--- a/client/src/components/SidePanel/Builder/ActionsAuth.tsx+++ b/client/src/components/SidePanel/Builder/ActionsAuth.tsx@@ -1,391 +1,316 @@-import { useState } from 'react';+import { useRef, useState, useLayoutEffect } from 'react';+import { motion } from 'framer-motion';import { useFormContext } from 'react-hook-form';-import * as RadioGroup from '@radix-ui/react-radio-group';+import { ChevronRight, KeyRound, ShieldCheck, ShieldOff } from 'lucide-react';import {AuthTypeEnum,AuthorizationTypeEnum,TokenExchangeMethodEnum,} from 'librechat-data-provider';import {+ Input,+ Radio,+ Button,OGDialog,- OGDialogClose,+ SecretInput,OGDialogTitle,OGDialogHeader,OGDialogContent,OGDialogTrigger,- SecretInput,} from '@librechat/client';-import { TranslationKeys, useLocalize } from '~/hooks';-import { cn } from '~/utils';+import type { LucideIcon } from 'lucide-react';+import type { ReactNode } from 'react';+import type { TranslationKeys } from '~/hooks';+import { useLocalize } from '~/hooks';++interface AuthMethod {+ value: AuthTypeEnum;+ icon: LucideIcon;+ titleKey: TranslationKeys;+ descKey: TranslationKeys;+}++const AUTH_METHODS: AuthMethod[] = [+ {+ value: AuthTypeEnum.None,+ icon: ShieldOff,+ titleKey: 'com_ui_none',+ descKey: 'com_ui_auth_none_desc',+ },+ {+ value: AuthTypeEnum.ServiceHttp,+ icon: KeyRound,+ titleKey: 'com_ui_api_key',+ descKey: 'com_ui_auth_apikey_desc',+ },+ {+ value: AuthTypeEnum.OAuth,+ icon: ShieldCheck,+ titleKey: 'com_ui_oauth',+ descKey: 'com_ui_auth_oauth_desc',+ },+];export default function ActionsAuth({ disableOAuth }: { disableOAuth?: boolean }) {const localize = useLocalize();const [openAuthDialog, setOpenAuthDialog] = useState(false);const { watch, setValue, trigger } = useFormContext();const type = watch('type');+ const current = AUTH_METHODS.find((method) => method.value === type) ?? AUTH_METHODS[0];+ const authOptions = AUTH_METHODS.filter(+ (method) => !(method.value === AuthTypeEnum.OAuth && disableOAuth === true),+ ).map((method) => ({+ value: method.value,+ label: localize(method.titleKey),+ icon: <method.icon className="size-4" aria-hidden={true} />,+ }));- const renderAuthFields = () => {- if (type === AuthTypeEnum.None) {- return null;- }-- if (type === AuthTypeEnum.ServiceHttp) {- return <ApiKey />;- }-- return <OAuth />;+ const handleSave = async () => {+ const result = await trigger(undefined, { shouldFocus: true });+ setValue('saved_auth_fields', result);+ setOpenAuthDialog(!result);};return (<OGDialog open={openAuthDialog} onOpenChange={setOpenAuthDialog}>- <OGDialogTrigger asChild>- <div className="relative mb-4">- <div className="mb-1.5 flex items-center">- <label className="text-token-text-primary block font-medium">- {localize('com_ui_authentication')}- </label>- </div>- <div className="border-token-border-medium flex rounded-lg border text-sm hover:cursor-pointer">- <div className="h-9 grow px-3 py-2">{localize(getAuthLocalizationKey(type))}</div>- <div className="bg-token-border-medium w-px"></div>- <button type="button" color="neutral" className="flex items-center gap-2 px-3">- <svg- width="24"- height="24"- viewBox="0 0 24 24"- fill="none"- xmlns="http://www.w3.org/2000/svg"- className="icon-sm"- >- <path- d="M11.6439 3C10.9352 3 10.2794 3.37508 9.92002 3.98596L9.49644 4.70605C8.96184 5.61487 7.98938 6.17632 6.93501 6.18489L6.09967 6.19168C5.39096 6.19744 4.73823 6.57783 4.38386 7.19161L4.02776 7.80841C3.67339 8.42219 3.67032 9.17767 4.01969 9.7943L4.43151 10.5212C4.95127 11.4386 4.95127 12.5615 4.43151 13.4788L4.01969 14.2057C3.67032 14.8224 3.67339 15.5778 4.02776 16.1916L4.38386 16.8084C4.73823 17.4222 5.39096 17.8026 6.09966 17.8083L6.93502 17.8151C7.98939 17.8237 8.96185 18.3851 9.49645 19.294L9.92002 20.014C10.2794 20.6249 10.9352 21 11.6439 21H12.3561C13.0648 21 13.7206 20.6249 14.08 20.014L14.5035 19.294C15.0381 18.3851 16.0106 17.8237 17.065 17.8151L17.9004 17.8083C18.6091 17.8026 19.2618 17.4222 19.6162 16.8084L19.9723 16.1916C20.3267 15.5778 20.3298 14.8224 19.9804 14.2057L19.5686 13.4788C19.0488 12.5615 19.0488 11.4386 19.5686 10.5212L19.9804 9.7943C20.3298 9.17767 20.3267 8.42219 19.9723 7.80841L19.6162 7.19161C19.2618 6.57783 18.6091 6.19744 17.9004 6.19168L17.065 6.18489C16.0106 6.17632 15.0382 5.61487 14.5036 4.70605L14.08 3.98596C13.7206 3.37508 13.0648 3 12.3561 3H11.6439Z"- stroke="currentColor"- strokeWidth="2"- strokeLinejoin="round"- />- <circle cx="12" cy="12" r="2.5" stroke="currentColor" strokeWidth="2" />- </svg>- </button>- </div>- </div>- </OGDialogTrigger>- <OGDialogContent className="w-full max-w-md border-none bg-surface-primary text-text-primary">- <OGDialogHeader className="border-b border-border-light sm:p-3">- <OGDialogTitle>{localize('com_ui_authentication')}</OGDialogTitle>+ <div className="mb-4">+ <label className="mb-1.5 block font-medium text-text-primary">+ {localize('com_ui_authentication')}+ </label>+ <OGDialogTrigger asChild>+ <button+ type="button"+ className="group flex w-full items-center gap-3 rounded-xl border border-border-light bg-transparent px-3 py-2.5 text-left transition-colors hover:bg-surface-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"+ >+ <current.icon className="size-5 shrink-0 text-text-secondary" aria-hidden={true} />+ <span className="min-w-0 flex-1">+ <span className="block text-sm font-medium text-text-primary">+ {localize(current.titleKey)}+ </span>+ <span className="block truncate text-xs text-text-secondary">+ {localize(current.descKey)}+ </span>+ </span>+ <ChevronRight className="size-4 shrink-0 text-text-secondary" aria-hidden={true} />+ </button>+ </OGDialogTrigger>+ </div>+ <OGDialogContent className="w-full max-w-lg bg-surface-primary text-text-primary">+ <OGDialogHeader>+ <OGDialogTitle className="text-lg font-semibold">+ {localize('com_ui_authentication')}+ </OGDialogTitle></OGDialogHeader>- <div className="p-4 sm:p-6 sm:pt-0">- <div className="mb-4">- <label className="mb-1 block text-sm font-medium">- {localize('com_ui_authentication_type')}- </label>- <RadioGroup.Root- defaultValue={AuthTypeEnum.None}- onValueChange={(value) => setValue('type', value)}- value={type}- role="radiogroup"- aria-required="false"- dir="ltr"- className="flex gap-4"- style={{ outline: 'none' }}- >- <div className="flex items-center gap-2">- <label htmlFor=":rf8:" className="flex cursor-pointer items-center gap-1">- <RadioGroup.Item- type="button"- role="radio"- value={AuthTypeEnum.None}- id=":rf8:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_none')}- </label>- </div>- <div className="flex items-center gap-2">- <label htmlFor=":rfa:" className="flex cursor-pointer items-center gap-1">- <RadioGroup.Item- type="button"- role="radio"- value={AuthTypeEnum.ServiceHttp}- id=":rfa:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_api_key')}- </label>- </div>- <div className="flex items-center gap-2">- <label- htmlFor=":rfc:"- className={cn(- 'flex items-center gap-1',- disableOAuth === true ? 'cursor-not-allowed' : 'cursor-pointer',- )}- >- <RadioGroup.Item- type="button"- role="radio"- disabled={disableOAuth}- value={AuthTypeEnum.OAuth}- id=":rfc:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- disableOAuth === true ? 'cursor-not-allowed' : '',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_oauth')}- </label>- </div>- </RadioGroup.Root>- </div>- {renderAuthFields()}- {/* Cancel/Save */}- <div className="mt-5 flex flex-col gap-3 sm:mt-4 sm:flex-row-reverse">- <button- className="btn relative bg-surface-submit text-primary-foreground hover:bg-surface-submit-hover"- onClick={async () => {- const result = await trigger(undefined, { shouldFocus: true });- setValue('saved_auth_fields', result);- setOpenAuthDialog(!result);- }}- >- <div className="flex w-full items-center justify-center gap-2 text-white">- {localize('com_ui_save')}- </div>- </button>- <OGDialogClose className="btn btn-neutral relative">- <div className="flex w-full items-center justify-center gap-2">- {localize('com_ui_cancel')}- </div>- </OGDialogClose>- </div>+ <div>+ <span id="auth-method-label" className="sr-only">+ {localize('com_ui_authentication_type')}+ </span>+ <Radio+ options={authOptions}+ value={type}+ onChange={(value) => setValue('type', value)}+ fullWidth+ aria-labelledby="auth-method-label"+ />+ <AnimatedAuthFields type={type} />+ </div>+ <div className="flex justify-end">+ <Button variant="default" onClick={handleSave}>+ {localize('com_ui_done')}+ </Button></div></OGDialogContent></OGDialog>);}+/**+ * Animates the auth fields' height to their measured content height. Animating to+ * a measured pixel value (instead of `height: 'auto'`) is what lets the+ * ApiKey <-> OAuth swap tween between two different heights — `auto` never changes,+ * so it would jump. The content swaps instantly; only the container height eases.+ */+function AnimatedAuthFields({ type }: { type: AuthTypeEnum }) {+ const innerRef = useRef<HTMLDivElement>(null);+ const [height, setHeight] = useState<number | 'auto'>(type === AuthTypeEnum.None ? 0 : 'auto');++ useLayoutEffect(() => {+ const el = innerRef.current;+ if (!el) {+ return;+ }+ const measure = () => setHeight(type === AuthTypeEnum.None ? 0 : el.scrollHeight);+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, [type]);++ let fields: ReactNode = null;+ if (type === AuthTypeEnum.ServiceHttp) {+ fields = <ApiKey />;+ } else if (type === AuthTypeEnum.OAuth) {+ fields = <OAuth />;+ }++ return (+ <motion.div+ initial={false}+ animate={{ height, opacity: type === AuthTypeEnum.None ? 0 : 1 }}+ transition={{ duration: 0.25, ease: [0.22, 1, 0.36, 1] }}+ className="overflow-hidden"+ >+ <div ref={innerRef} className="space-y-4 pt-4">+ {fields}+ </div>+ </motion.div>+ );+}++function Field({+ htmlFor,+ label,+ children,+}: {+ htmlFor: string;+ label: string;+ children: ReactNode;+}) {+ return (+ <div className="space-y-1.5">+ <label htmlFor={htmlFor} className="block text-xs font-medium text-text-secondary">+ {label}+ </label>+ {children}+ </div>+ );+}++function SegmentedField({+ id,+ label,+ value,+ onValueChange,+ options,+}: {+ id: string;+ label: string;+ value: string;+ onValueChange: (value: string) => void;+ options: Array<{ value: string; labelKey: TranslationKeys }>;+}) {+ const localize = useLocalize();+ return (+ <div className="space-y-1.5">+ <label id={id} className="block text-xs font-medium text-text-secondary">+ {label}+ </label>+ <Radio+ options={options.map((option) => ({+ value: option.value,+ label: localize(option.labelKey),+ }))}+ value={value}+ onChange={onValueChange}+ fullWidth+ aria-labelledby={id}+ />+ </div>+ );+}+const ApiKey = () => {const localize = useLocalize();const { register, watch, setValue } = useFormContext();const authorization_type = watch('authorization_type');const type = watch('type');- const inputClasses = cn(- 'mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm',- 'border-border-medium bg-surface-primary outline-none',- 'focus:ring-2 focus:ring-ring',- );-return (<>- <label className="mb-1 block text-sm font-medium">{localize('com_ui_api_key')}</label>- <SecretInput- placeholder="<HIDDEN>"- autoComplete="new-password"- controlsOnHover- className={inputClasses}- {...register('api_key', { required: type === AuthTypeEnum.ServiceHttp })}- />- <label className="mb-1 block text-sm font-medium">{localize('com_ui_auth_type')}</label>- <RadioGroup.Root- defaultValue={AuthorizationTypeEnum.Basic}- onValueChange={(value) => setValue('authorization_type', value)}+ <Field htmlFor="auth-api-key" label={localize('com_ui_api_key')}>+ <SecretInput+ id="auth-api-key"+ autoComplete="new-password"+ controlsOnHover+ placeholder="<HIDDEN>"+ {...register('api_key', { required: type === AuthTypeEnum.ServiceHttp })}+ />+ </Field>+ <SegmentedField+ id="auth-type-label"+ label={localize('com_ui_auth_type')}value={authorization_type}- role="radiogroup"- aria-required="true"- dir="ltr"- className="mb-2 flex gap-6 overflow-hidden rounded-lg"- style={{ outline: 'none' }}- >- <div className="flex items-center gap-2">- <label htmlFor=":rfu:" className="flex cursor-pointer items-center gap-1">- <RadioGroup.Item- type="button"- role="radio"- value={AuthorizationTypeEnum.Basic}- id=":rfu:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_basic')}- </label>- </div>- <div className="flex items-center gap-2">- <label htmlFor=":rg0:" className="flex cursor-pointer items-center gap-1">- <RadioGroup.Item- type="button"- role="radio"- value={AuthorizationTypeEnum.Bearer}- id=":rg0:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_bearer')}- </label>- </div>- <div className="flex items-center gap-2">- <label htmlFor=":rg2:" className="flex cursor-pointer items-center gap-1">- <RadioGroup.Item- type="button"- role="radio"- value={AuthorizationTypeEnum.Custom}- id=":rg2:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_custom')}- </label>- </div>- </RadioGroup.Root>+ onValueChange={(value) => setValue('authorization_type', value)}+ options={[+ { value: AuthorizationTypeEnum.Basic, labelKey: 'com_ui_basic' },+ { value: AuthorizationTypeEnum.Bearer, labelKey: 'com_ui_bearer' },+ { value: AuthorizationTypeEnum.Custom, labelKey: 'com_ui_custom' },+ ]}+ />{authorization_type === AuthorizationTypeEnum.Custom && (- <div className="mt-2">- <label className="mb-1 block text-sm font-medium">- {localize('com_ui_custom_header_name')}- </label>- <input- className={cn(- 'mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm',- 'border-border-medium bg-surface-primary outline-none',- 'focus:ring-2 focus:ring-ring',- )}+ <Field htmlFor="auth-custom-header" label={localize('com_ui_custom_header_name')}>+ <Input+ id="auth-custom-header"placeholder="X-Api-Key"{...register('custom_auth_header', {required: authorization_type === AuthorizationTypeEnum.Custom,})}/>- </div>+ </Field>)}</>);};-/** Returns the appropriate localization key for authentication type */-function getAuthLocalizationKey(type: AuthTypeEnum): TranslationKeys {- switch (type) {- case AuthTypeEnum.ServiceHttp:- return 'com_ui_api_key';- case AuthTypeEnum.OAuth:- return 'com_ui_oauth';- default:- return 'com_ui_none';- }-}-const OAuth = () => {const localize = useLocalize();const { register, watch, setValue } = useFormContext();const token_exchange_method = watch('token_exchange_method');const type = watch('type');-- const inputClasses = cn(- 'mb-2 h-9 w-full resize-none overflow-y-auto rounded-lg border px-3 py-2 text-sm',- 'border-border-medium bg-surface-primary outline-none',- 'focus:ring-2 focus:ring-ring',- );-return (<>- <label className="mb-1 block text-sm font-medium">{localize('com_ui_client_id')}</label>- <SecretInput- placeholder="<HIDDEN>"- autoComplete="new-password"- controlsOnHover- className={inputClasses}- {...register('oauth_client_id', { required: false })}- />- <label className="mb-1 block text-sm font-medium">{localize('com_ui_client_secret')}</label>- <SecretInput- placeholder="<HIDDEN>"- autoComplete="new-password"- controlsOnHover- className={inputClasses}- {...register('oauth_client_secret', { required: false })}- />- <label className="mb-1 block text-sm font-medium">{localize('com_ui_auth_url')}</label>- <input- className={inputClasses}- {...register('authorization_url', { required: type === AuthTypeEnum.OAuth })}- />- <label className="mb-1 block text-sm font-medium">{localize('com_ui_token_url')}</label>- <input- className={inputClasses}- {...register('client_url', { required: type === AuthTypeEnum.OAuth })}- />- <label className="mb-1 block text-sm font-medium">{localize('com_ui_scope')}</label>- <input- className={inputClasses}- {...register('scope', { required: type === AuthTypeEnum.OAuth })}- />- <label className="mb-1 block text-sm font-medium">- {localize('com_ui_token_exchange_method')}- </label>- <RadioGroup.Root- defaultValue={AuthorizationTypeEnum.Basic}- onValueChange={(value) => setValue('token_exchange_method', value)}+ <Field htmlFor="auth-client-id" label={localize('com_ui_client_id')}>+ <SecretInput+ id="auth-client-id"+ autoComplete="new-password"+ controlsOnHover+ placeholder="<HIDDEN>"+ {...register('oauth_client_id', { required: false })}+ />+ </Field>+ <Field htmlFor="auth-client-secret" label={localize('com_ui_client_secret')}>+ <SecretInput+ id="auth-client-secret"+ autoComplete="new-password"+ controlsOnHover+ placeholder="<HIDDEN>"+ {...register('oauth_client_secret', { required: false })}+ />+ </Field>+ <Field htmlFor="auth-authorization-url" label={localize('com_ui_auth_url')}>+ <Input+ id="auth-authorization-url"+ {...register('authorization_url', { required: type === AuthTypeEnum.OAuth })}+ />+ </Field>+ <Field htmlFor="auth-token-url" label={localize('com_ui_token_url')}>+ <Input+ id="auth-token-url"+ {...register('client_url', { required: type === AuthTypeEnum.OAuth })}+ />+ </Field>+ <Field htmlFor="auth-scope" label={localize('com_ui_scope')}>+ <Input id="auth-scope" {...register('scope', { required: type === AuthTypeEnum.OAuth })} />+ </Field>+ <SegmentedField+ id="auth-token-exchange-label"+ label={localize('com_ui_token_exchange_method')}value={token_exchange_method}- role="radiogroup"- aria-required="true"- dir="ltr"- style={{ outline: 'none' }}- >- <div className="flex items-center gap-2">- <label htmlFor=":rj1:" className="flex cursor-pointer items-center gap-1">- <RadioGroup.Item- type="button"- role="radio"- value={TokenExchangeMethodEnum.DefaultPost}- id=":rj1:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_default_post_request')}- </label>- </div>- <div className="flex items-center gap-2">- <label htmlFor=":rj3:" className="flex cursor-pointer items-center gap-1">- <RadioGroup.Item- type="button"- role="radio"- value={TokenExchangeMethodEnum.BasicAuthHeader}- id=":rj3:"- className={cn(- 'mr-1 flex h-5 w-5 items-center justify-center rounded-full border',- 'border-border-heavy bg-surface-primary',- )}- >- <RadioGroup.Indicator className="h-2 w-2 rounded-full bg-text-primary" />- </RadioGroup.Item>- {localize('com_ui_basic_auth_header')}- </label>- </div>- </RadioGroup.Root>+ onValueChange={(value) => setValue('token_exchange_method', value)}+ options={[+ { value: TokenExchangeMethodEnum.DefaultPost, labelKey: 'com_ui_default_post_request' },+ { value: TokenExchangeMethodEnum.BasicAuthHeader, labelKey: 'com_ui_basic_auth_header' },+ ]}+ /></>);};diff --git a/client/src/components/SidePanel/Builder/ActionsPanel.tsx b/client/src/components/SidePanel/Builder/ActionsPanel.tsxindex 13b605bc8a..d6d0d4d725 100644--- a/client/src/components/SidePanel/Builder/ActionsPanel.tsx+++ b/client/src/components/SidePanel/Builder/ActionsPanel.tsx@@ -71,7 +71,7 @@ export default function ActionsPanel({},});- const { reset, watch } = methods;+ const { reset } = methods;useEffect(() => {if (action?.metadata?.auth) {@@ -95,72 +95,72 @@ export default function ActionsPanel({<FormProvider {...methods}><form className="h-full grow overflow-hidden"><div className="h-full overflow-auto px-2 pb-12 text-sm">- <div className="relative flex flex-col items-center px-16 py-6 text-center">- <div className="absolute left-0 top-6">+ <div className="flex flex-col py-3">+ <header className="grid grid-cols-[auto_1fr_auto] items-center gap-2 pt-1"><buttontype="button"- className="btn btn-neutral relative"onClick={() => {setActivePanel(Panel.builder);setAction(undefined);}}+ aria-label={localize('com_ui_back_to_builder')}+ className="inline-flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-border-light text-text-secondary transition-colors hover:bg-surface-secondary hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary">- <div className="flex w-full items-center justify-center gap-2">- <ChevronLeft />- </div>+ <ChevronLeft className="h-5 w-5" strokeWidth={1.75} aria-hidden="true" /></button>- </div>-- {!!action && (- <OGDialog>- <OGDialogTrigger asChild>- <div className="absolute right-0 top-6">+ <h2 className="text-center text-base font-semibold text-text-primary">+ {localize(action ? 'com_assistants_edit_actions' : 'com_assistants_add_actions')}+ </h2>+ {action ? (+ <OGDialog>+ <OGDialogTrigger asChild><buttontype="button"disabled={!(assistant_id ?? '') || !action.action_id}- className="btn btn-neutral border-token-border-light relative h-9 rounded-lg font-medium"+ aria-label={localize('com_ui_delete_action')}+ className="inline-flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-border-light text-red-500 transition-colors hover:bg-surface-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary disabled:opacity-50">- <TrashIcon className="text-red-500" />+ <TrashIcon className="h-4 w-4" /></button>- </div>- </OGDialogTrigger>- <OGDialogTemplate- showCloseButton={false}- title={localize('com_ui_delete_action')}- className="max-w-[450px]"- main={- <Label className="text-left text-sm font-medium">- {localize('com_ui_delete_action_confirm')}- </Label>- }- selection={{- selectHandler: () => {- const currentId = assistant_id ?? '';- if (!currentId) {- return showToast({- message: 'No assistant_id found, is the assistant created?',- status: 'error',+ </OGDialogTrigger>+ <OGDialogTemplate+ showCloseButton={false}+ title={localize('com_ui_delete_action')}+ className="max-w-[450px]"+ main={+ <Label className="text-left text-sm font-medium">+ {localize('com_ui_delete_action_confirm')}+ </Label>+ }+ selection={{+ selectHandler: () => {+ const currentId = assistant_id ?? '';+ if (!currentId) {+ return showToast({+ message: 'No assistant_id found, is the assistant created?',+ status: 'error',+ });+ }+ deleteAction.mutate({+ model: assistantMap?.[endpoint][currentId].model ?? '',+ action_id: action.action_id,+ assistant_id: currentId,+ endpoint,});- }- deleteAction.mutate({- model: assistantMap?.[endpoint][currentId].model ?? '',- action_id: action.action_id,- assistant_id: currentId,- endpoint,- });- },- selectClasses:- 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',- selectText: localize('com_ui_delete'),- }}- />- </OGDialog>- )}-- <div className="text-xl font-medium">{(action ? 'Edit' : 'Add') + ' ' + 'actions'}</div>- <div className="text-xs text-text-secondary">+ },+ selectClasses:+ 'bg-red-700 dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-800 transition-color duration-200 text-white',+ selectText: localize('com_ui_delete'),+ }}+ />+ </OGDialog>+ ) : (+ <span aria-hidden="true" className="h-10 w-10" />+ )}+ </header>+ <p className="mt-1 text-center text-xs text-text-secondary">{localize('com_assistants_actions_info')}- </div>+ </p>{/* <div className="text-sm text-text-secondary"><a href="https://help.openai.com/en/articles/8554397-creating-a-gpt" target="_blank" rel="noreferrer" className="font-medium">Learn more.</a></div> */}diff --git a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/AuthSection.tsx b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/AuthSection.tsxindex fb31c95949..216a68151e 100644--- a/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/AuthSection.tsx+++ b/client/src/components/SidePanel/MCPBuilder/MCPServerDialog/sections/AuthSection.tsx@@ -3,9 +3,10 @@ import { Copy, CopyCheck } from 'lucide-react';import { useFormContext, useWatch } from 'react-hook-form';import { Permissions, PermissionTypes } from 'librechat-data-provider';import { Label, Input, Checkbox, SecretInput, Radio, useToastContext } from '@librechat/client';-import { AuthTypeEnum, AuthorizationTypeEnum } from '../hooks/useMCPServerForm';import type { MCPServerFormData } from '../hooks/useMCPServerForm';+import { AuthTypeEnum, AuthorizationTypeEnum } from '../hooks/useMCPServerForm';import { useLocalize, useCopyToClipboard, useHasAccess } from '~/hooks';+import { Collapse } from '~/components/ui';import { cn } from '~/utils';interface AuthSectionProps {@@ -83,7 +84,7 @@ export default function AuthSection({ isEditMode, serverName }: AuthSectionProps);return (- <div className="space-y-3">+ <div>{/* Auth Type Radio */}<fieldset className="space-y-1.5"><legend>@@ -102,78 +103,82 @@ export default function AuthSection({ isEditMode, serverName }: AuthSectionProps</fieldset>{/* API Key Fields */}- {authType === AuthTypeEnum.ServiceHttp && (+ <Collapse open={authType === AuthTypeEnum.ServiceHttp} className="pt-3"><div className="space-y-3 rounded-lg border border-border-light p-3">- {/* User provides own key checkbox */}- <div className="flex items-center gap-2">- <Checkbox- id="user_provides_key"- checked={apiKeySource === 'user'}- onCheckedChange={(checked) =>- setValue('auth.api_key_source', checked ? 'user' : 'admin')- }- aria-labelledby="user_provides_key_label"- />- <label- id="user_provides_key_label"- htmlFor="user_provides_key"- className="cursor-pointer text-sm"- >- {localize('com_ui_user_provides_key')}- </label>- </div>-- {/* API Key input - only when admin provides */}- {apiKeySource !== 'user' && (- <div className="space-y-1.5">- <Label htmlFor="api_key" className="text-sm font-medium">- {localize('com_ui_api_key')}- </Label>- <SecretInput- id="api_key"- placeholder="sk-..."- controlsOnHover- {...register('auth.api_key')}+ {/* User provides own key checkbox + admin-provided key */}+ <div>+ <div className="flex items-center gap-2">+ <Checkbox+ id="user_provides_key"+ checked={apiKeySource === 'user'}+ onCheckedChange={(checked) =>+ setValue('auth.api_key_source', checked ? 'user' : 'admin')+ }+ aria-labelledby="user_provides_key_label"/>+ <label+ id="user_provides_key_label"+ htmlFor="user_provides_key"+ className="cursor-pointer text-sm"+ >+ {localize('com_ui_user_provides_key')}+ </label></div>- )}- {/* Header Format Radio */}- <fieldset className="space-y-1.5">- <legend>- <Label id="header-format-label" className="text-sm font-medium">- {localize('com_ui_header_format')}- </Label>- </legend>- <Radio- options={headerFormatOptions}- value={authorizationType || AuthorizationTypeEnum.Bearer}- onChange={(val) =>- setValue('auth.api_key_authorization_type', val as AuthorizationTypeEnum)- }- fullWidth- aria-labelledby="header-format-label"- />- </fieldset>+ {/* API Key input - only when admin provides */}+ <Collapse open={apiKeySource !== 'user'} className="pt-3">+ <div className="space-y-1.5">+ <Label htmlFor="api_key" className="text-sm font-medium">+ {localize('com_ui_api_key')}+ </Label>+ <SecretInput+ id="api_key"+ placeholder="sk-..."+ controlsOnHover+ {...register('auth.api_key')}+ />+ </div>+ </Collapse>+ </div>- {/* Custom header name */}- {authorizationType === AuthorizationTypeEnum.Custom && (- <div className="space-y-1.5">- <Label htmlFor="custom_header" className="text-sm font-medium">- {localize('com_ui_custom_header_name')}- </Label>- <Input- id="custom_header"- placeholder="X-Api-Key"- {...register('auth.api_key_custom_header')}+ {/* Header format + custom header name */}+ <div>+ <fieldset className="space-y-1.5">+ <legend>+ <Label id="header-format-label" className="text-sm font-medium">+ {localize('com_ui_header_format')}+ </Label>+ </legend>+ <Radio+ options={headerFormatOptions}+ value={authorizationType || AuthorizationTypeEnum.Bearer}+ onChange={(val) =>+ setValue('auth.api_key_authorization_type', val as AuthorizationTypeEnum)+ }+ fullWidth+ aria-labelledby="header-format-label"/>- </div>- )}+ </fieldset>++ {/* Custom header name */}+ <Collapse open={authorizationType === AuthorizationTypeEnum.Custom} className="pt-3">+ <div className="space-y-1.5">+ <Label htmlFor="custom_header" className="text-sm font-medium">+ {localize('com_ui_custom_header_name')}+ </Label>+ <Input+ id="custom_header"+ placeholder="X-Api-Key"+ {...register('auth.api_key_custom_header')}+ />+ </div>+ </Collapse>+ </div></div>- )}+ </Collapse>{/* OAuth Fields */}- {authType === AuthTypeEnum.OAuth && (+ <Collapse open={authType === AuthTypeEnum.OAuth} className="pt-3"><div className="space-y-3 rounded-lg border border-border-light p-3">{/* Client ID & Secret in a grid */}<div className="grid grid-cols-2 gap-3">@@ -200,7 +205,9 @@ export default function AuthSection({ isEditMode, serverName }: AuthSectionPropsaria-describedby={errors.auth?.oauth_client_id ? 'oauth-client-id-error' : undefined}- {...register('auth.oauth_client_id', { required: !isEditMode })}+ {...register('auth.oauth_client_id', {+ required: !isEditMode && authType === AuthTypeEnum.OAuth,+ })}className={cn(errors.auth?.oauth_client_id && 'border-border-destructive')}/>{errors.auth?.oauth_client_id && (@@ -288,10 +295,10 @@ export default function AuthSection({ isEditMode, serverName }: AuthSectionProps</div>)}</div>- )}+ </Collapse>{/* OBO Fields */}- {authType === AuthTypeEnum.OBO && (+ <Collapse open={authType === AuthTypeEnum.OBO} className="pt-3"><div className="space-y-3 rounded-lg border border-border-light p-3"><div className="space-y-1.5"><Label htmlFor="obo_scopes" className="text-sm font-medium">@@ -330,7 +337,7 @@ export default function AuthSection({ isEditMode, serverName }: AuthSectionProps)}</div></div>- )}+ </Collapse></div>);}diff --git a/client/src/components/SidePanel/Parameters/DynamicInput.tsx b/client/src/components/SidePanel/Parameters/DynamicInput.tsxindex 85ead9fc34..cdc6f3a452 100644--- a/client/src/components/SidePanel/Parameters/DynamicInput.tsx+++ b/client/src/components/SidePanel/Parameters/DynamicInput.tsx@@ -2,10 +2,10 @@ import { OptionTypes } from 'librechat-data-provider';import { Label, Input, HoverCard, HoverCardTrigger } from '@librechat/client';import type { DynamicSettingProps } from 'librechat-data-provider';import { useLocalize, useDebouncedInput, useParameterEffects, TranslationKeys } from '~/hooks';+import { cn, sanitizeIntegerInput } from '~/utils';import { useChatContext } from '~/Providers';import OptionHover from './OptionHover';import { ESide } from '~/common';-import { cn } from '~/utils';function DynamicInput({label = '',@@ -15,6 +15,8 @@ function DynamicInput({columnSpan,setOption,optionType,+ type,+ range,placeholder = '',readonly = false,showDefault = false,@@ -43,6 +45,19 @@ function DynamicInput({});const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ if (type === 'number') {+ // Integer params: strip thousands separators so "120,000" / "120.000"+ // become 120000 instead of being truncated to 120 downstream by parseInt.+ // Keep a leading minus for fields whose range permits negatives (e.g.+ // Google thinkingBudget, where -1 selects dynamic/auto thinking).+ const allowNegative = range != null && range.min < 0;+ const sanitized = sanitizeIntegerInput(e.target.value, allowNegative);+ // A lone "-" is an in-progress negative; keep it as a string so the field+ // shows the sign instead of coercing Number("-") to NaN. It resolves to a+ // number as soon as a digit is typed.+ setInputValue(sanitized, sanitized !== '-');+ return;+ }setInputValue(e, !isNaN(Number(e.target.value)));};@@ -78,6 +93,7 @@ function DynamicInput({<Inputid={`${settingKey}-dynamic-input`}disabled={readonly}+ inputMode={type === 'number' ? 'numeric' : undefined}value={inputValue ?? defaultValue ?? ''}onChange={handleInputChange}placeholder={placeholderText}diff --git a/client/src/components/Skills/dialogs/CreateSkillDialog.tsx b/client/src/components/Skills/dialogs/CreateSkillDialog.tsxindex ed8041423d..ac32a2f13e 100644--- a/client/src/components/Skills/dialogs/CreateSkillDialog.tsx+++ b/client/src/components/Skills/dialogs/CreateSkillDialog.tsx@@ -12,6 +12,7 @@ import {SKILL_NAME_MAX_LENGTH,SKILL_DESCRIPTION_MAX_LENGTH,} from 'librechat-data-provider';+import type { TSkill } from 'librechat-data-provider';import { useCreateSkillMutation } from '~/data-provider';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -22,6 +23,12 @@ interface CreateSkillDialogProps {defaultName?: string;defaultDescription?: string;defaultBody?: string;+ /**+ * Called with the created skill instead of navigating to its page. Lets the+ * dialog be reused in-context (e.g. the agent-builder skill picker) so creating+ * a skill keeps the user in place rather than routing to `/skills/:id`.+ */+ onCreated?: (skill: TSkill) => void;}interface FormValues {@@ -40,6 +47,7 @@ export default function CreateSkillDialog({defaultName = '',defaultDescription = '',defaultBody = '',+ onCreated,}: CreateSkillDialogProps) {const localize = useLocalize();const navigate = useNavigate();@@ -60,6 +68,10 @@ export default function CreateSkillDialog({showToast({ status: 'success', message: localize('com_ui_skill_created') });setIsOpen(false);reset();+ if (onCreated) {+ onCreated(skill);+ return;+ }navigate(`/skills/${skill._id}`);},onError: (error: unknown) => {@@ -90,7 +102,7 @@ export default function CreateSkillDialog({return (<OGDialog open={isOpen} onOpenChange={setIsOpen}>- <OGDialogContent className="w-11/12 max-w-5xl overflow-hidden">+ <OGDialogContent className="w-11/12 max-w-5xl overflow-hidden" showCloseButton={false}><formonSubmit={handleSubmit(onSubmit)}className="flex max-h-[80vh] min-w-0 flex-col gap-3 overflow-hidden p-1 sm:gap-4 sm:p-2"diff --git a/client/src/components/Skills/dialogs/SkillSelectDialog.tsx b/client/src/components/Skills/dialogs/SkillSelectDialog.tsxdeleted file mode 100644index 5fd4fa3f42..0000000000--- a/client/src/components/Skills/dialogs/SkillSelectDialog.tsx+++ /dev/null@@ -1,367 +0,0 @@-import { useState, useMemo, useCallback } from 'react';-import { Search, Check, EarthIcon, User, Plus, Star, ListFilter, X } from 'lucide-react';-import { useFormContext, useWatch } from 'react-hook-form';-import { useNavigate } from 'react-router-dom';-import { OGDialog, OGDialogContent } from '@librechat/client';-import { PermissionTypes, Permissions, SystemCategories } from 'librechat-data-provider';-import type { TSkillSummary } from 'librechat-data-provider';-import type { AgentForm } from '~/common';-import {- useLocalize,- useAuthContext,- useCategories,- useHasAccess,- useSkillFavorites,-} from '~/hooks';-import { useListSkillsQuery } from '~/data-provider';-import { CategoryIcon } from '~/components/Prompts';-import { cn } from '~/utils';--interface SkillSelectDialogProps {- isOpen: boolean;- setIsOpen: (open: boolean) => void;-}--interface SkillCategory {- value: string;- label: string;- icon?: React.ReactNode;-}--const SKILL_MY = '__skill_filter_my__';-const SKILL_FAVORITES = '__skill_filter_favorites__';-const LIST_QUERY_OPTIONS = { limit: 100 } as const;--interface SidebarItemProps {- value: string;- label: string;- icon: React.ReactNode;- active: boolean;- onSelect: (value: string) => void;-}--function SidebarItem({ value, label, icon, active, onSelect }: SidebarItemProps) {- return (- <button- type="button"- onClick={() => onSelect(value)}- className={cn(- 'flex w-full items-center gap-2 rounded-lg px-2.5 py-1.5 text-left text-sm transition-colors',- active- ? 'bg-surface-active text-text-primary'- : 'text-text-secondary hover:bg-surface-hover hover:text-text-primary',- )}- aria-pressed={active}- >- <span className="flex size-4 shrink-0 items-center justify-center">{icon}</span>- <span className="truncate">{label}</span>- </button>- );-}--interface SkillCardProps {- skill: TSkillSummary;- selected: boolean;- isFavorite: boolean;- isShared: boolean;- isPublic: boolean;- onToggle: (skillId: string) => void;- onToggleFavorite: (skillId: string) => void;- localize: ReturnType<typeof useLocalize>;-}--function SkillCard({- skill,- selected,- isFavorite,- isShared,- isPublic,- onToggle,- onToggleFavorite,- localize,-}: SkillCardProps) {- return (- <button- type="button"- onClick={() => onToggle(skill._id)}- onMouseDown={(e) => e.preventDefault()}- aria-pressed={selected}- className={cn(- 'group relative flex h-32 cursor-pointer flex-col rounded-xl border p-3.5 text-left transition-all duration-200',- 'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary',- selected- ? 'border-green-500/70 bg-green-500/[0.06]'- : 'border-border-light hover:border-border-medium hover:bg-surface-tertiary',- )}- >- <div className="flex w-full items-start gap-2">- <p className="min-w-0 flex-1 truncate pr-1 text-sm font-semibold text-text-primary">- {skill.name}- </p>- <span- role="button"- tabIndex={0}- onClick={(e) => {- e.stopPropagation();- onToggleFavorite(skill._id);- }}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- e.stopPropagation();- onToggleFavorite(skill._id);- }- }}- className={cn(- 'flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-lg transition-colors',- isFavorite- ? 'text-yellow-500 hover:bg-yellow-500/10'- : 'text-text-tertiary opacity-0 hover:bg-surface-hover hover:text-text-primary group-hover:opacity-100 group-focus-visible:opacity-100',- )}- aria-label={isFavorite ? localize('com_ui_unfavorite') : localize('com_ui_favorite')}- aria-pressed={isFavorite}- >- <Star className={cn('size-4', isFavorite && 'fill-current')} aria-hidden="true" />- </span>- </div>- {skill.description && (- <p className="mt-1 line-clamp-2 text-xs leading-relaxed text-text-secondary">- {skill.description}- </p>- )}- <div className="mt-auto flex w-full items-center gap-1.5 pt-2">- {skill.category && (- <span className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-2 py-0.5 text-[10px] text-text-tertiary">- <CategoryIcon category={skill.category} className="size-2.5" />- {skill.category}- </span>- )}- {isShared && (- <span- className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-1.5 py-0.5 text-text-tertiary"- title={skill.authorName}- aria-label={skill.authorName}- >- <User className="size-2.5" aria-hidden="true" />- </span>- )}- {isPublic && (- <span- className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-1.5 py-0.5 text-text-tertiary"- title={localize('com_ui_sr_public_skill')}- aria-label={localize('com_ui_sr_public_skill')}- >- <EarthIcon className="size-2.5" aria-hidden="true" />- </span>- )}- <span- className={cn(- 'ml-auto flex size-5 shrink-0 items-center justify-center rounded-full transition-all duration-200',- selected ? 'scale-100 bg-green-500 text-white opacity-100' : 'scale-75 opacity-0',- )}- aria-hidden="true"- >- <Check className="size-3" strokeWidth={3} />- </span>- </div>- </button>- );-}--function SkillSelectDialog({ isOpen, setIsOpen }: SkillSelectDialogProps) {- const localize = useLocalize();- const navigate = useNavigate();- const { user } = useAuthContext();- const { control, setValue } = useFormContext<AgentForm>();- const [searchValue, setSearchValue] = useState('');- const [activeFilter, setActiveFilter] = useState<string>(SystemCategories.ALL);- const { isFavorite: isFavoriteSkill, toggle: toggleFavoriteSkill } = useSkillFavorites();-- const hasCreateAccess = useHasAccess({- permissionType: PermissionTypes.SKILLS,- permission: Permissions.CREATE,- });-- const { data: skillsData } = useListSkillsQuery(LIST_QUERY_OPTIONS);- const { categories } = useCategories({ className: 'size-4', hasAccess: true });- const typedCategories = categories as SkillCategory[] | undefined;-- const allSkills = useMemo(() => skillsData?.skills ?? [], [skillsData?.skills]);-- const watchedSkills = useWatch({ control, name: 'skills' });- const selectedSet = useMemo(- () => new Set<string>(Array.isArray(watchedSkills) ? watchedSkills : []),- [watchedSkills],- );-- const handleToggleSkill = useCallback(- (skillId: string) => {- const current = Array.isArray(watchedSkills) ? watchedSkills : [];- if (current.includes(skillId)) {- setValue(- 'skills',- current.filter((id) => id !== skillId),- { shouldDirty: true },- );- } else {- setValue('skills', [...current, skillId], { shouldDirty: true });- }- },- [watchedSkills, setValue],- );-- const handleClose = useCallback(() => {- setIsOpen(false);- setSearchValue('');- setActiveFilter(SystemCategories.ALL);- }, [setIsOpen]);-- const handleCreate = useCallback(() => {- setIsOpen(false);- navigate('/skills/new');- }, [navigate, setIsOpen]);-- const visibleSkills = useMemo(() => {- const term = searchValue.toLowerCase();- const result: TSkillSummary[] = [];- for (const skill of allSkills) {- if (activeFilter === SKILL_MY) {- if (skill.author !== user?.id) continue;- } else if (activeFilter === SKILL_FAVORITES) {- if (!isFavoriteSkill(skill._id)) continue;- } else if (activeFilter === SystemCategories.NO_CATEGORY) {- if (skill.category) continue;- } else if (activeFilter !== SystemCategories.ALL) {- if (skill.category !== activeFilter) continue;- }- if (term && !skill.name.toLowerCase().includes(term)) continue;- result.push(skill);- }- return result;- }, [allSkills, activeFilter, searchValue, user?.id, isFavoriteSkill]);-- return (- <OGDialog open={isOpen} onOpenChange={setIsOpen}>- <OGDialogContent- className="w-11/12 max-w-[1024px] overflow-hidden rounded-2xl border-border-medium p-0 shadow-xl md:max-h-[85vh]"- showCloseButton={false}- >- <div className="flex h-[80vh] max-h-[720px]">- <aside className="flex w-56 shrink-0 flex-col gap-1 border-r border-border-light bg-surface-primary-alt p-3">- <h2 className="px-2.5 pb-1.5 pt-1 text-base font-bold text-text-primary">- {localize('com_ui_add_skills')}- </h2>- {hasCreateAccess && (- <button- type="button"- onClick={handleCreate}- className="mb-1 flex w-full items-center justify-center gap-2 rounded-lg border border-border-light bg-transparent px-2.5 py-1.5 text-center text-sm text-text-primary transition-colors hover:border-border-medium hover:bg-surface-hover"- aria-label={localize('com_ui_create_skill')}- >- <Plus className="size-4 shrink-0" aria-hidden="true" />- <span className="truncate">{localize('com_ui_create_skill')}</span>- </button>- )}- <SidebarItem- value={SKILL_MY}- label={localize('com_ui_my_skills')}- icon={<User className="size-4 text-text-secondary" />}- active={activeFilter === SKILL_MY}- onSelect={setActiveFilter}- />- <SidebarItem- value={SKILL_FAVORITES}- label={localize('com_ui_favorites')}- icon={<Star className="size-4 text-text-secondary" />}- active={activeFilter === SKILL_FAVORITES}- onSelect={setActiveFilter}- />- <div className="my-2 h-px bg-border-light" />- <SidebarItem- value={SystemCategories.ALL}- label={localize('com_ui_all_proper')}- icon={<ListFilter className="size-4 text-text-secondary" />}- active={activeFilter === SystemCategories.ALL}- onSelect={setActiveFilter}- />- {typedCategories?.map((category) => {- if (!category.value) {- return null;- }- return (- <SidebarItem- key={category.value}- value={category.value}- label={category.label}- icon={category.icon ?? <ListFilter className="size-4 text-text-secondary" />}- active={activeFilter === category.value}- onSelect={setActiveFilter}- />- );- })}- </aside>-- <div className="flex min-w-0 flex-1 flex-col">- <div className="flex items-center gap-2 px-6 py-4">- <div className="relative flex-1">- <Search- className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-text-tertiary"- aria-hidden="true"- />- <input- type="text"- value={searchValue}- onChange={(e) => setSearchValue(e.target.value)}- placeholder={localize('com_ui_search_skills')}- aria-label={localize('com_ui_search_skills')}- className="h-10 w-full rounded-xl border border-border-light bg-transparent pl-9 pr-3 text-sm text-text-primary placeholder:text-text-tertiary focus:border-border-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary"- />- </div>- <button- type="button"- onClick={handleClose}- className="flex size-10 shrink-0 items-center justify-center rounded-xl border border-border-light bg-transparent text-text-secondary transition-colors hover:border-border-medium hover:bg-surface-hover hover:text-text-primary"- aria-label={localize('com_ui_close')}- >- <X className="size-4" aria-hidden="true" />- </button>- </div>-- <div- className="flex-1 overflow-y-auto p-4"- role="group"- aria-label={localize('com_ui_add_skills')}- >- {visibleSkills.length > 0 ? (- <div className="grid grid-cols-2 gap-2">- {visibleSkills.map((skill) => (- <SkillCard- key={skill._id}- skill={skill}- selected={selectedSet.has(skill._id)}- isFavorite={isFavoriteSkill(skill._id)}- isShared={skill.author !== user?.id && Boolean(skill.authorName)}- isPublic={skill.isPublic === true}- onToggle={handleToggleSkill}- onToggleFavorite={toggleFavoriteSkill}- localize={localize}- />- ))}- </div>- ) : (- <div className="flex flex-col items-center justify-center py-16 text-center">- <Search className="size-8 text-text-tertiary opacity-40" aria-hidden="true" />- <p className="mt-3 text-sm text-text-secondary">- {localize('com_ui_no_skills_found')}- </p>- </div>- )}- </div>- </div>- </div>- </OGDialogContent>- </OGDialog>- );-}--export default SkillSelectDialog;diff --git a/client/src/components/Skills/dialogs/index.ts b/client/src/components/Skills/dialogs/index.tsindex e992915c90..9be56edaee 100644--- a/client/src/components/Skills/dialogs/index.ts+++ b/client/src/components/Skills/dialogs/index.ts@@ -1,4 +1,3 @@export { default as CreateSkillDialog } from './CreateSkillDialog';export { default as DeleteSkill } from './DeleteSkill';-export { default as SkillSelectDialog } from './SkillSelectDialog';export { default as UploadSkillDialog } from './UploadSkillDialog';diff --git a/client/src/components/Tools/MCPToolItem.tsx b/client/src/components/Tools/MCPToolItem.tsxdeleted file mode 100644index 7e9012e8ce..0000000000--- a/client/src/components/Tools/MCPToolItem.tsx+++ /dev/null@@ -1,115 +0,0 @@-import { XCircle, PlusCircleIcon, Wrench } from 'lucide-react';-import type { AgentToolType } from 'librechat-data-provider';-import { useLocalize } from '~/hooks';--type MCPToolItemProps = {- tool: AgentToolType;- onAddTool: () => void;- onRemoveTool: () => void;- isInstalled?: boolean;- isConfiguring?: boolean;- isInitializing?: boolean;-};--function MCPToolItem({- tool,- onAddTool,- onRemoveTool,- isInstalled = false,- isConfiguring = false,- isInitializing = false,-}: MCPToolItemProps) {- const localize = useLocalize();- const handleClick = () => {- if (isInstalled) {- onRemoveTool();- } else {- onAddTool();- }- };-- const name = tool.metadata?.name || tool.tool_id;- const description = tool.metadata?.description || '';- const icon = tool.metadata?.icon;-- // Determine button state and text- const getButtonState = () => {- if (isInstalled) {- return {- text: localize('com_nav_tool_remove'),- icon: <XCircle className="flex h-4 w-4 items-center stroke-2" aria-hidden="true" />,- className: 'btn btn-neutral border-token-border-light relative',- disabled: false,- };- }-- if (isConfiguring) {- return {- text: localize('com_ui_confirm'),- icon: <PlusCircleIcon className="flex h-4 w-4 items-center stroke-2" aria-hidden="true" />,- className: 'btn btn-primary relative',- disabled: false,- };- }-- if (isInitializing) {- return {- text: localize('com_ui_initializing'),- icon: <Wrench className="flex h-4 w-4 items-center stroke-2" aria-hidden="true" />,- className: 'btn btn-primary relative opacity-75 cursor-not-allowed',- disabled: true,- };- }-- return {- text: localize('com_ui_add'),- icon: <PlusCircleIcon className="flex h-4 w-4 items-center stroke-2" aria-hidden="true" />,- className: 'btn btn-primary relative',- disabled: false,- };- };-- const buttonState = getButtonState();-- return (- <div className="flex flex-col gap-4 rounded border border-border-medium bg-transparent p-6">- <div className="flex gap-4">- <div className="h-[70px] w-[70px] shrink-0">- <div className="relative h-full w-full">- {icon ? (- <img- src={icon}- alt={localize('com_ui_logo', { 0: name })}- className="h-full w-full rounded-[5px] bg-white"- />- ) : (- <div className="flex h-full w-full items-center justify-center rounded-[5px] border border-border-medium bg-transparent">- <Wrench className="h-8 w-8 text-text-secondary" />- </div>- )}- <div className="absolute inset-0 rounded-[5px] ring-1 ring-inset ring-black/10"></div>- </div>- </div>- <div className="flex min-w-0 flex-col items-start justify-between">- <div className="mb-2 line-clamp-1 max-w-full text-lg leading-5 text-text-primary">- {name}- </div>- <button- className={buttonState.className}- aria-label={`${buttonState.text} ${name}`}- onClick={handleClick}- disabled={buttonState.disabled}- >- <div className="flex w-full items-center justify-center gap-2">- {buttonState.text}- {buttonState.icon}- </div>- </button>- </div>- </div>- <div className="line-clamp-3 h-[60px] text-sm text-text-secondary">{description}</div>- </div>- );-}--export default MCPToolItem;diff --git a/client/src/components/Tools/MCPToolSelectDialog.tsx b/client/src/components/Tools/MCPToolSelectDialog.tsxdeleted file mode 100644index a27484d4e8..0000000000--- a/client/src/components/Tools/MCPToolSelectDialog.tsx+++ /dev/null@@ -1,379 +0,0 @@-import { useEffect, useState, useMemo } from 'react';-import { Search, X } from 'lucide-react';-import { useFormContext } from 'react-hook-form';-import { useQueryClient } from '@tanstack/react-query';-import { Constants, EModelEndpoint, QueryKeys } from 'librechat-data-provider';-import { Dialog, DialogPanel, DialogTitle, Description } from '@headlessui/react';-import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';-import type { TError, AgentToolType } from 'librechat-data-provider';-import type { AgentForm, ToolDialogProps } from '~/common';-import {- usePluginDialogHelpers,- useMCPServerManager,- useRemoveMCPTool,- useLocalize,-} from '~/hooks';-import CustomUserVarsSection from '~/components/MCP/CustomUserVarsSection';-import { PluginPagination } from '~/components/Plugins/Store';-import { useAgentPanelContext } from '~/Providers';-import { useMCPToolsQuery } from '~/data-provider';-import MCPToolItem from './MCPToolItem';--function MCPToolSelectDialog({- isOpen,- agentId,- setIsOpen,- mcpServerNames,-}: ToolDialogProps & {- agentId: string;- mcpServerNames?: string[];- endpoint: EModelEndpoint.agents;-}) {- const localize = useLocalize();- const queryClient = useQueryClient();- const { initializeServer } = useMCPServerManager();- const { getValues, setValue } = useFormContext<AgentForm>();- const { removeTool } = useRemoveMCPTool({ showToast: false });- const { mcpServersMap, availableMCPServersMap } = useAgentPanelContext();- const { refetch: refetchMCPTools } = useMCPToolsQuery({- enabled: mcpServersMap.size > 0,- });-- const [isSavingCustomVars, setIsSavingCustomVars] = useState(false);- const [isInitializing, setIsInitializing] = useState<string | null>(null);- const [configuringServer, setConfiguringServer] = useState<string | null>(null);-- const {- maxPage,- setMaxPage,- currentPage,- setCurrentPage,- itemsPerPage,- searchChanged,- setSearchChanged,- searchValue,- setSearchValue,- gridRef,- handleSearch,- handleChangePage,- error,- setError,- errorMessage,- setErrorMessage,- } = usePluginDialogHelpers();-- const updateUserPlugins = useUpdateUserPluginsMutation();-- const handleInstallError = (error: TError) => {- setError(true);- const errorMessage = error.response?.data?.message ?? '';- if (errorMessage) {- setErrorMessage(errorMessage);- }- setTimeout(() => {- setError(false);- setErrorMessage('');- }, 5000);- };-- const handleDirectAdd = async (serverName: string, authData?: Record<string, string>) => {- try {- setIsInitializing(serverName);-- // First, save auth if provided- if (authData && Object.keys(authData).length > 0) {- await updateUserPlugins.mutateAsync({- pluginKey: `${Constants.mcp_prefix}${serverName}`,- action: 'install',- auth: authData,- isEntityTool: true,- });-- // Invalidate auth values query to ensure fresh data- await queryClient.invalidateQueries([QueryKeys.mcpAuthValues, serverName]);-- // Small delay to ensure backend has processed the auth- await new Promise((resolve) => setTimeout(resolve, 500));- }-- // Only initialize if no cached tools exist; skip if tools are already available from DB- const serverInfo = mcpServersMap.get(serverName);- if (!serverInfo?.tools?.length) {- const result = await initializeServer(serverName);- if (result?.oauthRequired && result.oauthUrl) {- setIsInitializing(null);- return; // OAuth flow must complete first- }- }-- // Add tools to form (refetches from backend's persisted cache)- await addToolsToForm(serverName);- setIsInitializing(null);- } catch (error) {- console.error('Error adding MCP server:', error);- handleInstallError(error as TError);- setIsInitializing(null);- }- };-- const addToolsToForm = async (serverName: string) => {- const { data: updatedMCPData } = await refetchMCPTools();-- const currentTools = getValues('tools') || [];- const toolsToAdd: string[] = [`${Constants.mcp_server}${Constants.mcp_delimiter}${serverName}`];-- if (updatedMCPData?.servers?.[serverName]) {- const serverData = updatedMCPData.servers[serverName];- serverData.tools.forEach((tool) => {- toolsToAdd.push(tool.pluginKey);- });- }-- const newTools = toolsToAdd.filter((tool) => !currentTools.includes(tool));- if (newTools.length > 0) {- setValue('tools', [...currentTools, ...newTools]);- }- };-- const handleSaveCustomVars = async (serverName: string, authData: Record<string, string>) => {- try {- setIsSavingCustomVars(true);-- // Filter out empty values to avoid overwriting existing values with empty ones- const filteredAuthData: Record<string, string> = {};- Object.entries(authData).forEach(([key, value]) => {- if (value && value.trim()) {- filteredAuthData[key] = value.trim();- }- });-- // Always add the tool, but only pass auth data if there are values to save- // Empty auth data is fine - the tool can work without credentials- await handleDirectAdd(- serverName,- Object.keys(filteredAuthData).length > 0 ? filteredAuthData : undefined,- );- setConfiguringServer(null);- } catch (error) {- console.error('Error saving custom vars:', error);- handleInstallError(error as TError);- } finally {- setIsSavingCustomVars(false);- }- };-- const handleRevokeCustomVars = (serverName: string) => {- setIsSavingCustomVars(true);- updateUserPlugins.mutate(- {- pluginKey: `${Constants.mcp_prefix}${serverName}`,- action: 'uninstall',- auth: {},- isEntityTool: true,- },- {- onError: (error: unknown) => {- handleInstallError(error as TError);- setIsSavingCustomVars(false);- },- onSuccess: async () => {- setConfiguringServer(null);- setIsSavingCustomVars(false);- },- },- );- };-- const onAddTool = async (serverName: string) => {- if (configuringServer === serverName) {- setConfiguringServer(null);- await handleDirectAdd(serverName);- return;- }-- const serverConfig = availableMCPServersMap?.[serverName];- const hasCustomUserVars =- serverConfig?.customUserVars && Object.keys(serverConfig.customUserVars).length > 0;-- if (hasCustomUserVars) {- setConfiguringServer(serverName);- } else {- await handleDirectAdd(serverName);- }- };-- const installedToolsSet = useMemo(() => {- return new Set(mcpServerNames);- }, [mcpServerNames]);-- const mcpServers = useMemo(() => {- const servers = Array.from(mcpServersMap.values()).filter((s) => !s.consumeOnly);- return servers.sort((a, b) => a.serverName.localeCompare(b.serverName));- }, [mcpServersMap]);-- const filteredServers = useMemo(() => {- if (!searchValue) {- return mcpServers;- }- return mcpServers.filter((serverInfo) =>- serverInfo.serverName.toLowerCase().includes(searchValue.toLowerCase()),- );- }, [mcpServers, searchValue]);-- useEffect(() => {- setMaxPage(Math.ceil(filteredServers.length / itemsPerPage));- if (searchChanged) {- setCurrentPage(1);- setSearchChanged(false);- }- }, [- setMaxPage,- itemsPerPage,- searchChanged,- setCurrentPage,- setSearchChanged,- filteredServers.length,- ]);-- return (- <Dialog- open={isOpen}- onClose={() => {- setIsOpen(false);- setCurrentPage(1);- setSearchValue('');- setConfiguringServer(null);- setIsInitializing(null);- }}- className="relative z-[102]"- >- <div className="fixed inset-0 bg-surface-primary opacity-60 transition-opacity dark:opacity-80" />- <div className="fixed inset-0 flex items-center justify-center p-4">- <DialogPanel- className="relative max-h-[90vh] w-full transform overflow-hidden overflow-y-auto rounded-lg bg-surface-secondary text-left shadow-xl transition-all max-sm:h-full sm:mx-7 sm:my-8 sm:max-w-2xl lg:max-w-5xl xl:max-w-7xl"- style={{ minHeight: '610px' }}- >- <div className="flex items-center justify-between border-b-[1px] border-border-medium px-4 pb-4 pt-5 sm:p-6">- <div className="flex items-center">- <div className="text-center sm:text-left">- <DialogTitle className="text-lg font-medium leading-6 text-text-primary">- {localize('com_nav_tool_dialog_mcp_server_tools')}- </DialogTitle>- <Description className="text-sm text-text-secondary">- {localize('com_nav_tool_dialog_description')}- </Description>- </div>- </div>- <div>- <button- onClick={() => {- setIsOpen(false);- setCurrentPage(1);- setConfiguringServer(null);- setIsInitializing(null);- }}- className="inline-block rounded-full text-text-secondary transition-colors hover:text-text-primary"- aria-label="Close dialog"- type="button"- >- <X aria-hidden="true" />- </button>- </div>- </div>-- {error && (- <div- className="relative m-4 rounded border border-red-400 bg-red-100 px-4 py-3 text-red-700"- role="alert"- >- {localize('com_nav_plugin_auth_error')} {errorMessage}- </div>- )}-- {configuringServer && (- <div className="p-4 sm:p-6 sm:pt-4">- <div className="mb-4">- <p className="text-sm text-text-secondary">- {localize('com_ui_mcp_configure_server_description', { 0: configuringServer })}- </p>- </div>- <CustomUserVarsSection- serverName={configuringServer}- isSubmitting={isSavingCustomVars}- fields={availableMCPServersMap?.[configuringServer]?.customUserVars || {}}- onSave={(authData) => handleSaveCustomVars(configuringServer, authData)}- onRevoke={() => handleRevokeCustomVars(configuringServer)}- />- </div>- )}-- <div className="p-4 sm:p-6 sm:pt-4">- <div className="mt-4 flex flex-col gap-4">- <div- className="flex items-center justify-center space-x-4"- onClick={() => setConfiguringServer(null)}- >- <Search className="h-6 w-6 text-text-tertiary" />- <input- type="text"- value={searchValue}- onChange={handleSearch}- placeholder={localize('com_nav_tool_search')}- className="w-64 rounded border border-border-medium bg-transparent px-2 py-1 text-text-primary focus:outline-none"- />- </div>-- <div- ref={gridRef}- className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"- style={{ minHeight: '410px' }}- >- {filteredServers- .slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage)- .map((serverInfo) => {- const isInstalled = installedToolsSet.has(serverInfo.serverName);- const isConfiguring = configuringServer === serverInfo.serverName;- const isServerInitializing = isInitializing === serverInfo.serverName;-- const tool: AgentToolType = {- agent_id: agentId,- tool_id: serverInfo.serverName,- metadata: {- ...serverInfo.metadata,- },- };-- return (- <MCPToolItem- tool={tool}- isInstalled={isInstalled}- key={serverInfo.serverName}- isConfiguring={isConfiguring}- isInitializing={isServerInitializing}- onAddTool={() => onAddTool(serverInfo.serverName)}- onRemoveTool={() => removeTool(serverInfo.serverName)}- />- );- })}- </div>- </div>-- <div className="mt-2 flex flex-col items-center gap-2 sm:flex-row sm:justify-between">- {maxPage > 0 ? (- <PluginPagination- currentPage={currentPage}- maxPage={maxPage}- onChangePage={handleChangePage}- />- ) : (- <div style={{ height: '21px' }}></div>- )}- </div>- </div>- </DialogPanel>- </div>- </Dialog>- );-}--export default MCPToolSelectDialog;diff --git a/client/src/components/Tools/ToolSelectDialog.tsx b/client/src/components/Tools/ToolSelectDialog.tsxdeleted file mode 100644index 1fb28c7413..0000000000--- a/client/src/components/Tools/ToolSelectDialog.tsx+++ /dev/null@@ -1,259 +0,0 @@-import { useEffect } from 'react';-import { Search, X } from 'lucide-react';-import { useFormContext } from 'react-hook-form';-import { isAgentsEndpoint } from 'librechat-data-provider';-import { Dialog, DialogPanel, DialogTitle, Description } from '@headlessui/react';-import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';-import type {- AssistantsEndpoint,- EModelEndpoint,- TPluginAction,- TPlugin,- TError,-} from 'librechat-data-provider';-import type { AgentForm, ToolDialogProps } from '~/common';-import { PluginPagination, PluginAuthForm } from '~/components/Plugins/Store';-import { useAgentPanelContext } from '~/Providers/AgentPanelContext';-import { useLocalize, usePluginDialogHelpers } from '~/hooks';-import ToolItem from './ToolItem';--function ToolSelectDialog({- isOpen,- endpoint,- setIsOpen,-}: ToolDialogProps & {- endpoint: AssistantsEndpoint | EModelEndpoint.agents;-}) {- const localize = useLocalize();- const isAgentTools = isAgentsEndpoint(endpoint);- const { getValues, setValue } = useFormContext<AgentForm>();- // Only use regular tools, not MCP tools- const { regularTools } = useAgentPanelContext();-- const {- maxPage,- setMaxPage,- currentPage,- setCurrentPage,- itemsPerPage,- searchChanged,- setSearchChanged,- searchValue,- setSearchValue,- gridRef,- handleSearch,- handleChangePage,- error,- setError,- errorMessage,- setErrorMessage,- showPluginAuthForm,- setShowPluginAuthForm,- selectedPlugin,- setSelectedPlugin,- } = usePluginDialogHelpers();-- const updateUserPlugins = useUpdateUserPluginsMutation();- const handleInstallError = (error: TError) => {- setError(true);- const errorMessage = error.response?.data?.message ?? '';- if (errorMessage) {- setErrorMessage(errorMessage);- }- setTimeout(() => {- setError(false);- setErrorMessage('');- }, 5000);- };-- const handleInstall = (pluginAction: TPluginAction) => {- const addFunction = () => {- const installedToolIds: string[] = getValues('tools') || [];- installedToolIds.push(pluginAction.pluginKey);- setValue('tools', Array.from(new Set(installedToolIds)));- };-- if (!pluginAction.auth) {- return addFunction();- }-- updateUserPlugins.mutate(pluginAction, {- onError: (error: unknown) => {- handleInstallError(error as TError);- },- onSuccess: addFunction,- });-- setShowPluginAuthForm(false);- };-- const onRemoveTool = (toolId: string) => {- updateUserPlugins.mutate(- { pluginKey: toolId, action: 'uninstall', auth: {}, isEntityTool: true },- {- onError: (error: unknown) => handleInstallError(error as TError),- onSuccess: () => {- const remainingToolIds = getValues('tools')?.filter((id) => id !== toolId) || [];- setValue('tools', remainingToolIds);- },- },- );- };-- const onAddTool = (pluginKey: string) => {- setShowPluginAuthForm(false);- // Find the tool in regularTools- const availablePluginFromKey = regularTools?.find((p) => p.pluginKey === pluginKey);- setSelectedPlugin(availablePluginFromKey);-- const { authConfig, authenticated = false } = availablePluginFromKey ?? {};- if (authConfig && authConfig.length > 0 && !authenticated) {- setShowPluginAuthForm(true);- } else {- handleInstall({- pluginKey,- action: 'install',- auth: {},- });- }- };-- const filteredTools = (regularTools || []).filter((tool: TPlugin) => {- return tool.name?.toLowerCase().includes(searchValue.toLowerCase());- });-- useEffect(() => {- if (filteredTools) {- setMaxPage(Math.ceil(filteredTools.length / itemsPerPage));- if (searchChanged) {- setCurrentPage(1);- setSearchChanged(false);- }- }- }, [- searchValue,- itemsPerPage,- filteredTools,- searchChanged,- setMaxPage,- setCurrentPage,- setSearchChanged,- ]);-- return (- <Dialog- open={isOpen}- onClose={() => {- setIsOpen(false);- setCurrentPage(1);- setSearchValue('');- }}- className="relative z-[102]"- >- {/* The backdrop, rendered as a fixed sibling to the panel container */}- <div className="fixed inset-0 bg-surface-primary opacity-60 transition-opacity dark:opacity-80" />- {/* Full-screen container to center the panel */}- <div className="fixed inset-0 flex items-center justify-center p-4">- <DialogPanel- className="relative max-h-[90vh] w-full transform overflow-hidden overflow-y-auto rounded-lg bg-surface-secondary text-left shadow-xl transition-all max-sm:h-full sm:mx-7 sm:my-8 sm:max-w-2xl lg:max-w-5xl xl:max-w-7xl"- style={{ minHeight: '610px' }}- >- <div className="flex items-center justify-between border-b-[1px] border-border-medium px-4 pb-4 pt-5 sm:p-6">- <div className="flex items-center">- <div className="text-center sm:text-left">- <DialogTitle className="text-lg font-medium leading-6 text-text-primary">- {isAgentTools- ? localize('com_nav_tool_dialog_agents')- : localize('com_nav_tool_dialog')}- </DialogTitle>- <Description className="text-sm text-text-secondary">- {localize('com_nav_tool_dialog_description')}- </Description>- </div>- </div>- <div>- <div className="sm:mt-0">- <button- onClick={() => {- setIsOpen(false);- setCurrentPage(1);- }}- className="inline-block rounded-full text-text-secondary transition-colors hover:text-text-primary"- aria-label="Close dialog"- type="button"- >- <X aria-hidden="true" />- </button>- </div>- </div>- </div>- {error && (- <div- className="relative m-4 rounded border border-red-400 bg-red-100 px-4 py-3 text-red-700"- role="alert"- >- {localize('com_nav_plugin_auth_error')} {errorMessage}- </div>- )}- {showPluginAuthForm && (- <div className="p-4 sm:p-6 sm:pt-4">- <PluginAuthForm- plugin={selectedPlugin}- onSubmit={(installActionData: TPluginAction) => handleInstall(installActionData)}- isEntityTool={true}- />- </div>- )}- <div className="p-4 sm:p-6 sm:pt-4">- <div className="mt-4 flex flex-col gap-4">- <div className="flex items-center justify-center space-x-4">- <Search className="h-6 w-6 text-text-tertiary" />- <input- type="text"- value={searchValue}- onChange={handleSearch}- placeholder={localize('com_nav_tool_search')}- className="w-64 rounded border border-border-medium bg-transparent px-2 py-1 text-text-primary focus:outline-none"- />- </div>- <div- ref={gridRef}- className="grid grid-cols-1 grid-rows-2 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"- style={{ minHeight: '410px' }}- >- {filteredTools &&- filteredTools- .slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage)- .map((tool, index) => (- <ToolItem- key={index}- tool={{- tool_id: tool.pluginKey,- metadata: tool,- }}- isInstalled={getValues('tools')?.includes(tool.pluginKey) || false}- onAddTool={() => onAddTool(tool.pluginKey)}- onRemoveTool={() => onRemoveTool(tool.pluginKey)}- />- ))}- </div>- </div>- <div className="mt-2 flex flex-col items-center gap-2 sm:flex-row sm:justify-between">- {maxPage > 0 ? (- <PluginPagination- currentPage={currentPage}- maxPage={maxPage}- onChangePage={handleChangePage}- />- ) : (- <div style={{ height: '21px' }}></div>- )}- </div>- </div>- </DialogPanel>- </div>- </Dialog>- );-}--export default ToolSelectDialog;diff --git a/client/src/components/Tools/index.ts b/client/src/components/Tools/index.tsindex cb3f0b464e..d62248d2b3 100644--- a/client/src/components/Tools/index.ts+++ b/client/src/components/Tools/index.ts@@ -1,3 +1 @@-export { default as MCPToolSelectDialog } from './MCPToolSelectDialog';-export { default as ToolSelectDialog } from './ToolSelectDialog';export { default as ToolItem } from './ToolItem';diff --git a/client/src/components/ui/Collapse.tsx b/client/src/components/ui/Collapse.tsxnew file mode 100644index 0000000000..9ddcb69155--- /dev/null+++ b/client/src/components/ui/Collapse.tsx@@ -0,0 +1,41 @@+import type { ReactNode } from 'react';+import { cn } from '~/utils';++interface CollapseProps {+ open: boolean;+ children: ReactNode;+ className?: string;+}++/**+ * Auto-height reveal via grid-template-rows 0fr -> 1fr, matching MCPToolItem and+ * the OAuth QR. The parent's content-driven height follows the tween in a single+ * motion, so stacked collapses (e.g. a loading skeleton swapping to a list) can+ * cross-fade smoothly without a measuring wrapper fighting nested reveals.+ * Content fades to soften the swap; while closed it is `inert` (removed from tab+ * order and the a11y tree) so collapsed form fields can't be focused or read.+ */+export default function Collapse({ open, children, className }: CollapseProps) {+ return (+ <div+ aria-hidden={!open || undefined}+ inert={!open ? '' : undefined}+ className={cn(+ 'grid transition-[grid-template-rows] [transition-duration:var(--resize-dur)] [transition-timing-function:var(--resize-ease)] motion-reduce:transition-none',+ open ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]',+ )}+ >+ <div className="min-h-0 overflow-hidden">+ <div+ className={cn(+ 'transition-opacity duration-200 ease-out motion-reduce:transition-none',+ open ? 'opacity-100' : 'opacity-0',+ className,+ )}+ >+ {children}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/ui/__tests__/Collapse.spec.tsx b/client/src/components/ui/__tests__/Collapse.spec.tsxnew file mode 100644index 0000000000..59144e6048--- /dev/null+++ b/client/src/components/ui/__tests__/Collapse.spec.tsx@@ -0,0 +1,28 @@+import '@testing-library/jest-dom/extend-expect';+import { render, screen } from '@testing-library/react';+import Collapse from '../Collapse';++describe('Collapse', () => {+ test('reveals its content when open', () => {+ const { container } = render(+ <Collapse open={true}>+ <span data-testid="child" />+ </Collapse>,+ );+ expect(screen.getByTestId('child')).toBeInTheDocument();+ const root = container.firstChild as HTMLElement;+ expect(root).toHaveClass('grid-rows-[1fr]');+ expect(root).not.toHaveAttribute('aria-hidden');+ });++ test('collapses and hides from assistive tech when closed', () => {+ const { container } = render(+ <Collapse open={false}>+ <span data-testid="child" />+ </Collapse>,+ );+ const root = container.firstChild as HTMLElement;+ expect(root).toHaveClass('grid-rows-[0fr]');+ expect(root).toHaveAttribute('aria-hidden', 'true');+ });+});diff --git a/client/src/components/ui/index.ts b/client/src/components/ui/index.tsindex 1412cf4aff..295a1921a0 100644--- a/client/src/components/ui/index.ts+++ b/client/src/components/ui/index.ts@@ -1,4 +1,5 @@export { Button } from '@librechat/client';+export { default as Collapse } from './Collapse';export { default as TermsAndConditionsModal } from './TermsAndConditionsModal';export { default as AdminSettingsDialog } from './AdminSettingsDialog';export type { PermissionConfig, AdminSettingsDialogProps } from './AdminSettingsDialog';diff --git a/client/src/data-provider/Favorites.ts b/client/src/data-provider/Favorites.tsindex 19571a1887..17b53513b5 100644--- a/client/src/data-provider/Favorites.ts+++ b/client/src/data-provider/Favorites.ts@@ -1,8 +1,12 @@import { dataService, QueryKeys } from 'librechat-data-provider';import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';import type { UseQueryOptions } from '@tanstack/react-query';+import type { TToolFavorite } from 'librechat-data-provider';import type { FavoritesState } from '~/store/favorites';+const sameFavorite = (a: TToolFavorite, b: TToolFavorite) =>+ a.itemType === b.itemType && a.itemId === b.itemId;+export const useGetFavoritesQuery = (config?: Omit<UseQueryOptions<FavoritesState, Error>, 'queryKey' | 'queryFn'>,) => {@@ -40,12 +44,12 @@ export const useUpdateFavoritesMutation = () => {);};-export const useGetSkillFavoritesQuery = (- config?: Omit<UseQueryOptions<string[], Error>, 'queryKey' | 'queryFn'>,+export const useGetToolFavoritesQuery = (+ config?: Omit<UseQueryOptions<TToolFavorite[], Error>, 'queryKey' | 'queryFn'>,) => {- return useQuery<string[], Error>(- [QueryKeys.skillFavorites],- () => dataService.getSkillFavorites() as Promise<string[]>,+ return useQuery<TToolFavorite[], Error>(+ [QueryKeys.toolFavorites],+ () => dataService.getToolFavorites(),{refetchOnWindowFocus: false,refetchOnReconnect: false,@@ -55,23 +59,61 @@ export const useGetSkillFavoritesQuery = ();};-export const useUpdateSkillFavoritesMutation = () => {+export const useAddToolFavoriteMutation = () => {const queryClient = useQueryClient();- return useMutation(- (skillFavorites: string[]) =>- dataService.updateSkillFavorites(skillFavorites) as Promise<string[]>,- {- onMutate: async (newFavorites) => {- await queryClient.cancelQueries([QueryKeys.skillFavorites]);- const previous = queryClient.getQueryData<string[]>([QueryKeys.skillFavorites]);- queryClient.setQueryData([QueryKeys.skillFavorites], newFavorites);- return { previous };- },- onError: (_err, _newFavorites, context) => {- if (context?.previous !== undefined) {- queryClient.setQueryData([QueryKeys.skillFavorites], context.previous);- }- },+ return useMutation((favorite: TToolFavorite) => dataService.addToolFavorite(favorite), {+ /** Optimistic writes only apply over known server data. Before the list+ * query has populated, seeding the cache from `[]` would make the toggled+ * item look like the user's only favorite (and `cancelQueries` kills the+ * initial fetch that would correct it) — so skip the write and let+ * `onSettled` refetch the authoritative list instead. */+ onMutate: async (favorite) => {+ await queryClient.cancelQueries([QueryKeys.toolFavorites]);+ const previous = queryClient.getQueryData<TToolFavorite[]>([QueryKeys.toolFavorites]);+ if (previous !== undefined) {+ queryClient.setQueryData<TToolFavorite[]>(+ [QueryKeys.toolFavorites],+ previous.some((f) => sameFavorite(f, favorite)) ? previous : [...previous, favorite],+ );+ }+ return { previous };},- );+ onError: (_err, _favorite, context) => {+ if (context?.previous !== undefined) {+ queryClient.setQueryData([QueryKeys.toolFavorites], context.previous);+ }+ },+ onSettled: (_data, _err, _favorite, context) => {+ if (context?.previous === undefined) {+ queryClient.invalidateQueries([QueryKeys.toolFavorites]);+ }+ },+ });+};++export const useRemoveToolFavoriteMutation = () => {+ const queryClient = useQueryClient();+ return useMutation((favorite: TToolFavorite) => dataService.removeToolFavorite(favorite), {+ onMutate: async (favorite) => {+ await queryClient.cancelQueries([QueryKeys.toolFavorites]);+ const previous = queryClient.getQueryData<TToolFavorite[]>([QueryKeys.toolFavorites]);+ if (previous !== undefined) {+ queryClient.setQueryData<TToolFavorite[]>(+ [QueryKeys.toolFavorites],+ previous.filter((f) => !sameFavorite(f, favorite)),+ );+ }+ return { previous };+ },+ onError: (_err, _favorite, context) => {+ if (context?.previous !== undefined) {+ queryClient.setQueryData([QueryKeys.toolFavorites], context.previous);+ }+ },+ onSettled: (_data, _err, _favorite, context) => {+ if (context?.previous === undefined) {+ queryClient.invalidateQueries([QueryKeys.toolFavorites]);+ }+ },+ });};diff --git a/client/src/hooks/MCP/__tests__/useRemoveMCPTool.spec.tsx b/client/src/hooks/MCP/__tests__/useRemoveMCPTool.spec.tsxnew file mode 100644index 0000000000..296856b8c2--- /dev/null+++ b/client/src/hooks/MCP/__tests__/useRemoveMCPTool.spec.tsx@@ -0,0 +1,76 @@+import React from 'react';+import { Constants } from 'librechat-data-provider';+import { useForm, FormProvider } from 'react-hook-form';+import { renderHook, act } from '@testing-library/react';+import { useRemoveMCPTool } from '../useRemoveMCPTool';++const mockShowToast = jest.fn();++jest.mock('@librechat/client', () => ({+ useToastContext: () => ({ showToast: mockShowToast }),+}));++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++function makeWrapper(tools: string[], onTools: (next: string[]) => void) {+ return function Wrapper({ children }: { children: React.ReactNode }) {+ const methods = useForm({ defaultValues: { tools } });+ const original = methods.setValue;+ methods.setValue = ((name: 'tools', value: string[], options?: object) => {+ if (name === 'tools') {+ onTools(value);+ }+ return original(name, value, options);+ }) as typeof methods.setValue;+ return <FormProvider {...methods}>{children}</FormProvider>;+ };+}++describe('useRemoveMCPTool', () => {+ beforeEach(() => {+ mockShowToast.mockClear();+ });++ test('strips every token format the selection logic counts as the server', () => {+ const tools = [+ `${Constants.mcp_server}${Constants.mcp_delimiter}srv`,+ 'srv',+ 'mcp_srv',+ `search${Constants.mcp_delimiter}srv`,+ `sys__all__sys${Constants.mcp_delimiter}srv`,+ 'dalle',+ `search${Constants.mcp_delimiter}other`,+ ];+ let next: string[] = [];+ const { result } = renderHook(() => useRemoveMCPTool(), {+ wrapper: makeWrapper(tools, (value) => {+ next = value;+ }),+ });++ act(() => {+ result.current.removeTool('srv');+ });++ expect(next).toEqual(['dalle', `search${Constants.mcp_delimiter}other`]);+ expect(mockShowToast).toHaveBeenCalledTimes(1);+ });++ test('ignores an empty server name', () => {+ let called = false;+ const { result } = renderHook(() => useRemoveMCPTool(), {+ wrapper: makeWrapper(['srv'], () => {+ called = true;+ }),+ });++ act(() => {+ result.current.removeTool('');+ });++ expect(called).toBe(false);+ expect(mockShowToast).not.toHaveBeenCalled();+ });+});diff --git a/client/src/hooks/MCP/useRemoveMCPTool.ts b/client/src/hooks/MCP/useRemoveMCPTool.tsindex 1f35e25c37..696db01b94 100644--- a/client/src/hooks/MCP/useRemoveMCPTool.ts+++ b/client/src/hooks/MCP/useRemoveMCPTool.ts@@ -1,13 +1,12 @@import { useCallback } from 'react';import { useFormContext } from 'react-hook-form';-import { Constants } from 'librechat-data-provider';import { useToastContext } from '@librechat/client';import type { AgentForm } from '~/common';+import { matchesMcpServer } from '~/components/SidePanel/Agents/Tools/items/selectors';import { useLocalize } from '~/hooks';/**- * Hook for removing MCP tools/servers from an agent- * Provides unified logic for MCPTool, UninitializedMCPTool, and UnconfiguredMCPTool components+ * Hook for removing an MCP server (and all of its tools) from the agent form.* Note: This only removes the tool from the form, it does not delete associated auth credentials*/export function useRemoveMCPTool(options?: { showToast?: boolean }) {@@ -23,12 +22,11 @@ export function useRemoveMCPTool(options?: { showToast?: boolean }) {}const currentTools = getValues('tools');+ /** Strip every token format the selection logic counts as this server —+ * removal lagging behind `matchesMcpServer` leaves the row permanently+ * selected with no way to clean it up. */const remainingToolIds =- currentTools?.filter(- (currentToolId) =>- currentToolId !== serverName &&- !currentToolId.endsWith(`${Constants.mcp_delimiter}${serverName}`),- ) || [];+ currentTools?.filter((currentToolId) => !matchesMcpServer(currentToolId, serverName)) || [];setValue('tools', remainingToolIds, { shouldDirty: true });if (shouldShowToast) {diff --git a/client/src/hooks/__tests__/useToolFavorites.spec.tsx b/client/src/hooks/__tests__/useToolFavorites.spec.tsxnew file mode 100644index 0000000000..eb6ddf15ff--- /dev/null+++ b/client/src/hooks/__tests__/useToolFavorites.spec.tsx@@ -0,0 +1,136 @@+import React from 'react';+import { renderHook, act, waitFor } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { TToolFavorite } from 'librechat-data-provider';+import useToolFavorites from '../useToolFavorites';++const mockShowToast = jest.fn();+const mockGetToolFavorites = jest.fn();+const mockAddToolFavorite = jest.fn();+const mockRemoveToolFavorite = jest.fn();++jest.mock('librechat-data-provider', () => {+ const actual = jest.requireActual('librechat-data-provider');+ return {+ ...actual,+ dataService: {+ ...actual.dataService,+ getToolFavorites: (...args: unknown[]) => mockGetToolFavorites(...args),+ addToolFavorite: (...args: unknown[]) => mockAddToolFavorite(...args),+ removeToolFavorite: (...args: unknown[]) => mockRemoveToolFavorite(...args),+ },+ };+});++jest.mock('@librechat/client', () => ({+ useToastContext: () => ({ showToast: mockShowToast }),+}));++jest.mock('../useLocalize', () => ({+ __esModule: true,+ default:+ () =>+ (key: string, options?: Record<string, unknown>): string =>+ options ? `${key}[${Object.values(options).join(',')}]` : key,+}));++function createWrapper() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ logger: { log: () => {}, warn: () => {}, error: () => {} },+ });+ return function Wrapper({ children }: { children: React.ReactNode }) {+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;+ };+}++const seeded: TToolFavorite[] = [+ { itemType: 'tool', itemId: 'dalle' },+ { itemType: 'mcp', itemId: 'everything' },+];++beforeEach(() => {+ jest.clearAllMocks();+ mockGetToolFavorites.mockResolvedValue(seeded);+ mockAddToolFavorite.mockImplementation((favorite) => Promise.resolve(favorite));+ mockRemoveToolFavorite.mockResolvedValue({ ok: true });+});++describe('useToolFavorites', () => {+ test('exposes favorites as compound kind:id keys', async () => {+ const { result } = renderHook(() => useToolFavorites(), { wrapper: createWrapper() });+ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(result.current.favoriteKeys).toEqual(new Set(['tool:dalle', 'mcp:everything']));+ expect(result.current.isFavorite({ kind: 'tool', id: 'dalle' })).toBe(true);+ expect(result.current.isFavorite({ kind: 'skill', id: 'dalle' })).toBe(false);+ });++ test('toggle adds an unfavorited item and removes a favorited one', async () => {+ const { result } = renderHook(() => useToolFavorites(), { wrapper: createWrapper() });+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ await act(async () => {+ await result.current.toggle({ kind: 'skill', id: 's1' });+ });+ expect(mockAddToolFavorite).toHaveBeenCalledWith({ itemType: 'skill', itemId: 's1' });+ await waitFor(() => expect(result.current.isFavorite({ kind: 'skill', id: 's1' })).toBe(true));++ await act(async () => {+ await result.current.toggle({ kind: 'tool', id: 'dalle' });+ });+ expect(mockRemoveToolFavorite).toHaveBeenCalledWith({ itemType: 'tool', itemId: 'dalle' });+ await waitFor(() =>+ expect(result.current.isFavorite({ kind: 'tool', id: 'dalle' })).toBe(false),+ );+ });++ test('never favorites actions', async () => {+ const { result } = renderHook(() => useToolFavorites(), { wrapper: createWrapper() });+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ await act(async () => {+ await result.current.toggle({ kind: 'action', id: 'a1' });+ });+ expect(mockAddToolFavorite).not.toHaveBeenCalled();+ expect(result.current.isFavorite({ kind: 'action', id: 'a1' })).toBe(false);+ });++ test('starring before the list loads refetches instead of hiding existing favorites', async () => {+ mockGetToolFavorites+ .mockImplementationOnce(() => new Promise<TToolFavorite[]>(() => undefined))+ .mockResolvedValueOnce([...seeded, { itemType: 'skill', itemId: 's1' }]);++ const { result } = renderHook(() => useToolFavorites(), { wrapper: createWrapper() });++ await act(async () => {+ await result.current.toggle({ kind: 'skill', id: 's1' });+ });++ await waitFor(() =>+ expect(result.current.favoriteKeys).toEqual(+ new Set(['tool:dalle', 'mcp:everything', 'skill:s1']),+ ),+ );+ expect(mockGetToolFavorites).toHaveBeenCalledTimes(2);+ });++ test('shows the item-worded cap toast and rolls back on rejection', async () => {+ mockAddToolFavorite.mockRejectedValue({+ response: { data: { code: 'MAX_FAVORITES_EXCEEDED', limit: 100 } },+ });+ const { result } = renderHook(() => useToolFavorites(), { wrapper: createWrapper() });+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ await act(async () => {+ await result.current.toggle({ kind: 'skill', id: 's1' });+ });+ expect(mockShowToast).toHaveBeenCalledWith({+ message: 'com_ui_max_favorites_reached_items[100]',+ status: 'error',+ });+ await waitFor(() => expect(result.current.isFavorite({ kind: 'skill', id: 's1' })).toBe(false));+ });+});diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.tsindex 87c62f1728..b24e3a6aac 100644--- a/client/src/hooks/index.ts+++ b/client/src/hooks/index.ts@@ -29,7 +29,7 @@ export { default as useNewConvo } from './useNewConvo';export { default as useLocalize } from './useLocalize';export { default as useFocusTrap } from './useFocusTrap';export { default as useFavorites } from './useFavorites';-export { default as useSkillFavorites } from './useSkillFavorites';+export { default as useToolFavorites } from './useToolFavorites';export { default as useChatBadges } from './useChatBadges';export { default as useScrollToRef } from './useScrollToRef';export { default as useIsActiveItem } from './useIsActiveItem';diff --git a/client/src/hooks/useSkillFavorites.ts b/client/src/hooks/useSkillFavorites.tsdeleted file mode 100644index b88c15df18..0000000000--- a/client/src/hooks/useSkillFavorites.ts+++ /dev/null@@ -1,96 +0,0 @@-import { useCallback, useMemo } from 'react';-import { useToastContext } from '@librechat/client';-import { useGetSkillFavoritesQuery, useUpdateSkillFavoritesMutation } from '~/data-provider';-import { getFavoritesErrorMessage, logger } from '~/utils';-import { useLocalize } from '~/hooks';--/** Maximum number of skills a user can favorite (must match backend MAX_SKILL_FAVORITES). */-const MAX_SKILL_FAVORITES = 50;-const EMPTY_FAVORITES: string[] = [];--/**- * Hook for managing user skill favorites.- *- * Skill favorites are a flat array of skill ObjectId strings, persisted via- * `/api/user/settings/favorites/skills`. React Query is the single source of- * truth — toggling drives an optimistic mutation that updates the cache,- * eliminating the need for a separate atom mirror.- */-export default function useSkillFavorites() {- const localize = useLocalize();- const { showToast } = useToastContext();- const getQuery = useGetSkillFavoritesQuery();- const updateMutation = useUpdateSkillFavoritesMutation();-- const favorites = useMemo(- () => (Array.isArray(getQuery.data) ? getQuery.data : EMPTY_FAVORITES),- [getQuery.data],- );-- const favoriteSet = useMemo(() => new Set(favorites), [favorites]);-- const save = useCallback(- async (next: string[]) => {- const deduped = Array.from(new Set(next));- try {- await updateMutation.mutateAsync(deduped);- } catch (error) {- logger.error('Error updating skill favorites:', error);- showToast({- message: getFavoritesErrorMessage(error, localize, MAX_SKILL_FAVORITES),- status: 'error',- });- }- },- [updateMutation, showToast, localize],- );-- const isFavorite = useCallback(- (skillId: string | undefined | null): boolean => {- if (!skillId) {- return false;- }- return favoriteSet.has(skillId);- },- [favoriteSet],- );-- const add = useCallback(- (skillId: string) => {- if (favoriteSet.has(skillId)) {- return;- }- save([...favorites, skillId]);- },- [favorites, favoriteSet, save],- );-- const remove = useCallback(- (skillId: string) => {- save(favorites.filter((id) => id !== skillId));- },- [favorites, save],- );-- const toggle = useCallback(- (skillId: string) => {- if (favoriteSet.has(skillId)) {- remove(skillId);- } else {- add(skillId);- }- },- [favoriteSet, add, remove],- );-- return {- favorites,- isFavorite,- add,- remove,- toggle,- isLoading: getQuery.isLoading,- isError: getQuery.isError,- isUpdating: updateMutation.isLoading,- };-}diff --git a/client/src/hooks/useToolFavorites.ts b/client/src/hooks/useToolFavorites.tsnew file mode 100644index 0000000000..f84dcb63a3--- /dev/null+++ b/client/src/hooks/useToolFavorites.ts@@ -0,0 +1,90 @@+import { useMemo, useCallback } from 'react';+import { useToastContext } from '@librechat/client';+import type { TToolFavorite, TToolFavoriteType } from 'librechat-data-provider';+import {+ useGetToolFavoritesQuery,+ useAddToolFavoriteMutation,+ useRemoveToolFavoriteMutation,+} from '~/data-provider';+import { getFavoritesErrorMessage, logger } from '~/utils';+import useLocalize from './useLocalize';++export const MAX_TOOL_FAVORITES = 100;++const EMPTY_FAVORITES: TToolFavorite[] = [];++interface FavoritableItem {+ kind: string;+ id: string;+}++const toFavorite = (item: FavoritableItem): TToolFavorite => ({+ itemType: item.kind as TToolFavoriteType,+ itemId: item.id,+});++/**+ * Favorites for marketplace items (built-in capabilities, plugin tools, MCP+ * servers, skills), persisted per user server-side. React Query is the source+ * of truth; `favoriteKeys` uses the marketplace `itemKey` format+ * (`kind:id`), so it plugs directly into the catalog filter context. Actions+ * are per-agent and not favoritable — `isFavorite`/`toggle` guard them.+ */+export default function useToolFavorites() {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const getQuery = useGetToolFavoritesQuery();+ const addMutation = useAddToolFavoriteMutation();+ const removeMutation = useRemoveToolFavoriteMutation();++ const favorites = useMemo(+ () => (Array.isArray(getQuery.data) ? getQuery.data : EMPTY_FAVORITES),+ [getQuery.data],+ );++ const favoriteKeys = useMemo(+ () => new Set(favorites.map((f) => `${f.itemType}:${f.itemId}`)),+ [favorites],+ );++ const isFavorite = useCallback(+ (item: FavoritableItem): boolean =>+ item.kind !== 'action' && favoriteKeys.has(`${item.kind}:${item.id}`),+ [favoriteKeys],+ );++ const toggle = useCallback(+ async (item: FavoritableItem) => {+ if (item.kind === 'action') {+ return;+ }+ const favorite = toFavorite(item);+ const mutation = favoriteKeys.has(`${item.kind}:${item.id}`) ? removeMutation : addMutation;+ try {+ await mutation.mutateAsync(favorite);+ } catch (error) {+ logger.error('Error updating tool favorites:', error);+ showToast({+ message: getFavoritesErrorMessage(+ error,+ localize,+ MAX_TOOL_FAVORITES,+ 'com_ui_max_favorites_reached_items',+ ),+ status: 'error',+ });+ }+ },+ [favoriteKeys, addMutation, removeMutation, showToast, localize],+ );++ return {+ favorites,+ favoriteKeys,+ isFavorite,+ toggle,+ isLoading: getQuery.isLoading,+ isError: getQuery.isError,+ isUpdating: addMutation.isLoading || removeMutation.isLoading,+ };+}diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex e7a79878cb..735f62daeb 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -38,9 +38,8 @@"com_agents_create_error": "There was an error creating your agent.","com_agents_created_by": "by","com_agents_description_card": "Description: {{description}}",- "com_agents_description_placeholder": "Optional: Describe your Agent here",+ "com_agents_description_placeholder": "What this agent does","com_agents_empty_state_heading": "No agents found",- "com_agents_enable_file_search": "Enable File Search","com_agents_enable_memory": "Enable Memory","com_agents_error_bad_request_message": "The request could not be processed.","com_agents_error_bad_request_suggestion": "Please check your input and try again.",@@ -65,11 +64,11 @@"com_agents_error_timeout_suggestion": "Please check your internet connection and try again.","com_agents_error_timeout_title": "Connection Timeout","com_agents_error_title": "Something went wrong",- "com_agents_file_context_description": "Files uploaded as \"Context\" are parsed as text to supplement the Agent's instructions. If OCR is available, or if configured for the uploaded filetype, the process is used to extract text. Ideal for documents, images with text, or PDFs where you need the full text content of a file",+ "com_agents_file_context_description": "Includes the full text of these files in the agent's context on every message. Best for a few key documents the agent should always reference.","com_agents_file_context_disabled": "Agent must be created before uploading files for File Context.","com_agents_file_context_label": "File Context","com_agents_file_search_disabled": "Agent must be created before uploading files for File Search.",- "com_agents_file_search_info": "When enabled, the agent will be informed of the exact filenames listed below, allowing it to retrieve relevant context from these files.",+ "com_agents_file_search_info": "Turns uploaded files into a searchable knowledge base. The agent retrieves the most relevant passages on demand, so it works well even with large document sets.","com_agents_grid_announcement": "Showing {{count}} agents in {{category}} category","com_agents_instructions_placeholder": "The system instructions that the agent uses","com_agents_link_copied": "Link copied",@@ -85,7 +84,7 @@"com_agents_memory_info": "When enabled, the agent can save, update, and delete memories about the user during the conversation using the set_memory and delete_memory tools.","com_agents_missing_name": "Please type in a name before creating an agent.","com_agents_missing_provider_model": "Please select a provider and model before creating an agent.",- "com_agents_name_placeholder": "Optional: The name of the agent",+ "com_agents_name_placeholder": "Agent name","com_agents_no_access": "You don't have access to edit this agent.","com_agents_no_agent_id_error": "No agent ID found. Please ensure the agent is created first.","com_agents_no_contact_available": "No contact available",@@ -94,10 +93,10 @@"com_agents_recommended": "Our recommended agents","com_agents_results_for": "Results for '{{query}}'","com_agents_run_code_files": "Files below are for Code Environment only:",- "com_agents_run_code_info": "When enabled, allows your agent to run generated code securely, including file processing.",+ "com_agents_run_code_info": "Lets the agent write and run code in a secure sandbox to handle calculations, data analysis, and file processing.","com_agents_search_aria": "Search for agents","com_agents_search_empty_heading": "No search results",- "com_agents_search_info": "When enabled, allows your agent to search the web for up-to-date information. Requires a valid API key.",+ "com_agents_search_info": "Lets the agent search the web for current information and cite its sources. Requires a configured search provider.","com_agents_search_instructions": "Type to search agents by name or description","com_agents_search_name": "Search agents by name","com_agents_search_no_results": "No agents found for \"{{query}}\"",@@ -110,7 +109,6 @@"com_assistants_actions_disabled": "You need to create an assistant before adding actions.","com_assistants_actions_info": "Let your Assistant retrieve information or take actions via API's","com_assistants_add_actions": "Add Actions",- "com_assistants_add_mcp_server_tools": "Add MCP Server Tools","com_assistants_add_tools": "Add Tools","com_assistants_allow_sites_you_trust": "Only allow sites you trust.","com_assistants_append_date": "Append Current Date & Time",@@ -129,6 +127,7 @@"com_assistants_delete_actions_error": "There was an error deleting the action.","com_assistants_delete_actions_success": "Successfully deleted Action from Assistant","com_assistants_description_placeholder": "Optional: Describe your Assistant here",+ "com_assistants_edit_actions": "Edit Actions","com_assistants_file_search": "File Search","com_assistants_file_search_info": "File search enables the assistant with knowledge from files that you or your users upload. Once a file is uploaded, the assistant automatically decides when to retrieve content based on user requests. Attaching vector stores for File Search is not yet supported. You can attach them from the Provider Playground or attach files to messages for file search on a thread basis.","com_assistants_function_use": "Assistant used {{0}}",@@ -507,14 +506,10 @@"com_nav_help": "Help","com_nav_help_faq": "Help & FAQ","com_nav_info_balance": "Balance shows how many token credits you have left to use. Token credits translate to monetary value (e.g., 1000 credits = $0.001 USD)",- "com_nav_info_code_artifacts": "Enables the display of experimental code artifacts next to the chat",- "com_nav_info_code_artifacts_agent": "Enables the use of code artifacts for this agent. By default, additional instructions specific to the use of artifacts are added, unless \"Custom Prompt Mode\" is enabled.",- "com_nav_info_custom_prompt_mode": "When enabled, the default artifacts system prompt will not be included. All artifact-generating instructions must be provided manually in this mode.","com_nav_info_default_temporary_chat": "When enabled, new chats will start with temporary chat mode activated by default. Temporary chats are not saved to your history.","com_nav_info_enter_to_send": "When enabled, pressing `ENTER` will send your message. When disabled, pressing Enter will add a new line, and you'll need to press `CTRL + ENTER` / `⌘ + ENTER` to send your message.","com_nav_info_fork_change_default": "`Visible messages only` includes just the direct path to the selected message. `Include related branches` adds branches along the path. `Include all to/from here` includes all connected messages and branches.","com_nav_info_fork_split_target_setting": "When enabled, forking will commence from the target message to the latest message in the conversation, according to the behavior selected.",- "com_nav_info_include_shadcnui": "When enabled, instructions for using shadcn/ui components will be included. shadcn/ui is a collection of re-usable components built using Radix UI and Tailwind CSS. Note: these are lengthy instructions, you should only enable if informing the LLM of the correct imports and components is important to you. For more information about these components, visit: https://ui.shadcn.com/","com_nav_info_latex_parsing": "When enabled, LaTeX code in messages will be rendered as mathematical equations. Disabling this may improve performance if you don't need LaTeX rendering.","com_nav_info_save_badges_state": "When enabled, the state of the chat badges will be saved. This means that if you create a new chat, the badges will remain in the same state as the previous chat. If you disable this option, the badges will reset to their default state every time you create a new chat","com_nav_info_save_draft": "When enabled, the text and attachments you enter in the chat form will be automatically saved locally as drafts. These drafts will be available even if you reload the page or switch to a different conversation. Drafts are stored locally on your device and are deleted once the message is sent.",@@ -619,7 +614,6 @@"com_nav_tool_dialog": "Assistant Tools","com_nav_tool_dialog_agents": "Agent Tools","com_nav_tool_dialog_description": "Assistant must be saved to persist tool selections.",- "com_nav_tool_dialog_mcp_server_tools": "MCP Server Tools","com_nav_tool_remove": "Remove","com_nav_tool_search": "Search tools","com_nav_user": "USER",@@ -721,6 +715,7 @@"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","com_ui_add_web_search_api_keys": "Add Web Search API Keys","com_ui_adding_details": "Adding details","com_ui_additional_details": "Additional Details",@@ -741,9 +736,11 @@"com_ui_agent_category_rd": "R&D","com_ui_agent_category_sales": "Sales","com_ui_agent_category_selector_aria": "Agent's category selector",- "com_ui_agent_chain": "Agent Chain (Mixture-of-Agents)",+ "com_ui_agent_chain": "Chain","com_ui_agent_chain_info": "Enables creating sequences of agents. Each agent can access outputs from previous agents in the chain. Based on the \"Mixture-of-Agents\" architecture where agents use previous outputs as auxiliary information.","com_ui_agent_chain_max": "You have reached the maximum of {{0}} agents.",+ "com_ui_agent_chain_self": "This agent",+ "com_ui_agent_chain_subtitle": "Run a fixed sequence of agents, one after another.","com_ui_agent_delete_error": "There was an error deleting the agent","com_ui_agent_deleted": "Successfully deleted agent","com_ui_agent_description": "Agent description",@@ -751,17 +748,24 @@"com_ui_agent_duplicated": "Agent duplicated successfully","com_ui_agent_handoff_add": "Add handoff agent","com_ui_agent_handoff_description": "Handoff description",- "com_ui_agent_handoff_description_placeholder": "e.g., Transfer to data analyst for statistical analysis",+ "com_ui_agent_handoff_description_placeholder": "Transfer to data analyst for statistical analysis","com_ui_agent_handoff_info": "Configure agents that this agent can transfer conversations to when specific expertise is needed.","com_ui_agent_handoff_info_2": "Each handoff creates a transfer tool that enables seamless routing to specialist agents with context.","com_ui_agent_handoff_max": "Maximum {{0}} handoff agents reached.","com_ui_agent_handoff_prompt": "Passthrough content","com_ui_agent_handoff_prompt_key": "Content parameter name (default: 'instructions')","com_ui_agent_handoff_prompt_key_placeholder": "Label the content passed (default: 'instructions')",- "com_ui_agent_handoff_prompt_placeholder": "Tell this agent what content to generate and pass to the handoff agent. You need to add something here to enable this feature",- "com_ui_agent_handoffs": "Agent Handoffs",+ "com_ui_agent_handoff_prompt_placeholder": "What to generate and pass to the handoff agent",+ "com_ui_agent_handoff_remove": "Remove handoff to {{0}}",+ "com_ui_agent_handoffs": "Handoffs",+ "com_ui_agent_handoffs_subtitle": "Transfer the conversation to a specialist agent.",+ "com_ui_agent_id": "Agent ID",+ "com_ui_agent_id_copied": "Agent ID copied to clipboard",+ "com_ui_agent_id_copy": "Copy agent ID","com_ui_agent_name": "Agent name","com_ui_agent_name_is_required": "Agent name is required",+ "com_ui_agent_orchestration": "Multi-agent orchestration",+ "com_ui_agent_orchestration_hint": "Choose how this agent works with other agents.","com_ui_agent_recursion_limit": "Max Agent Steps","com_ui_agent_recursion_limit_info": "Limits how many steps the agent can take in a run before giving a final response. Default is 25 steps. A step is either an AI API request or a tool usage round. For example, a basic tool interaction takes 3 steps: initial request, tool usage, and follow-up request.","com_ui_agent_subagents": "Subagents",@@ -775,10 +779,13 @@"com_ui_agent_subagents_info_2": "Enabling with no agents listed still allows self-spawn, so this agent can delegate focused subtasks to a fresh copy of itself.","com_ui_agent_subagents_max": "Maximum {{0}} subagents reached.","com_ui_agent_subagents_remove": "Remove {{0}} from subagents",+ "com_ui_agent_subagents_subtitle": "Spin up helper agents to handle subtasks.","com_ui_agent_url_copied": "Agent URL copied to clipboard","com_ui_agent_var": "{{0}} agent","com_ui_agent_version": "Version",- "com_ui_agent_version_active": "Active Version",+ "com_ui_agent_version_count": "{{count}} versions",+ "com_ui_agent_version_count_one": "{{count}} version",+ "com_ui_agent_version_current": "Current","com_ui_agent_version_empty": "No versions available","com_ui_agent_version_error": "Error fetching versions","com_ui_agent_version_history": "Version History",@@ -786,6 +793,7 @@"com_ui_agent_version_no_date": "Date not available","com_ui_agent_version_restore": "Restore","com_ui_agent_version_restore_confirm": "Are you sure you want to restore this version?",+ "com_ui_agent_version_restore_description": "This will replace your current configuration with this version's saved state.","com_ui_agent_version_restore_error": "Failed to restore version","com_ui_agent_version_restore_success": "Version restored successfully","com_ui_agent_version_title": "Version {{versionNumber}}",@@ -838,9 +846,15 @@"com_ui_artifact_click": "Click to open","com_ui_artifact_preview_pending": "_Preview not available yet — click **Download** to view the file._","com_ui_artifacts": "Artifacts",+ "com_ui_artifacts_mode": "Mode",+ "com_ui_artifacts_mode_custom": "Custom",+ "com_ui_artifacts_mode_custom_info": "Keeps artifact rendering on but injects no built-in instructions. Write your own in the agent's instructions for full control.",+ "com_ui_artifacts_mode_default": "Normal",+ "com_ui_artifacts_mode_default_info": "Standard artifact instructions: the agent renders React, HTML, SVG, Markdown, and Mermaid inline.",+ "com_ui_artifacts_mode_shadcn": "shadcn/ui",+ "com_ui_artifacts_mode_shadcn_info": "Adds shadcn/ui component-library instructions so the agent can build polished interfaces from prebuilt components.","com_ui_artifacts_options": "Artifacts Options",- "com_ui_artifacts_toggle": "Toggle Artifacts UI",- "com_ui_artifacts_toggle_agent": "Enable Artifacts",+ "com_ui_artifacts_subtext": "Lets the agent render React, HTML, SVG, Markdown, and Mermaid as interactive artifacts in a side panel instead of plain code blocks.","com_ui_ascending": "Asc","com_ui_assistant": "Assistant","com_ui_assistant_delete_error": "There was an error deleting the assistant",@@ -858,6 +872,11 @@"com_ui_attach_remove": "Remove file","com_ui_attach_warn_endpoint": "Non-Assistant files may be ignored without a compatible tool","com_ui_attachment": "Attachment",+ "com_ui_auth_apikey_desc": "Send a key or token with each request",+ "com_ui_auth_format_hint": "This usually starts with \"{{0}}\"",+ "com_ui_auth_invalid_url": "Enter a valid URL, including http:// or https://",+ "com_ui_auth_none_desc": "No authentication required",+ "com_ui_auth_oauth_desc": "Authorize through an OAuth 2.0 provider","com_ui_auth_type": "Auth Type","com_ui_auth_url": "Authorization URL","com_ui_authenticate": "Authenticate",@@ -909,6 +928,8 @@"com_ui_callback_url": "Callback URL","com_ui_cancel": "Cancel","com_ui_cancelled": "Cancelled",+ "com_ui_capabilities_count": "{{count}} capabilities",+ "com_ui_capabilities_count_one": "{{count}} capability","com_ui_category": "Category","com_ui_change_project": "Change project","com_ui_change_version": "Change Version",@@ -1040,6 +1061,7 @@"com_ui_date_today": "Today","com_ui_date_yesterday": "Yesterday","com_ui_decline": "I do not accept",+ "com_ui_default": "Default","com_ui_default_post_request": "Default (POST request)","com_ui_delete": "Delete","com_ui_delete_action": "Delete Action",@@ -1067,6 +1089,7 @@"com_ui_delete_success": "Successfully deleted","com_ui_delete_tool": "Delete Tool","com_ui_delete_tool_confirm": "Are you sure you want to delete this tool?",+ "com_ui_delete_tool_error": "Error removing the tool's saved credentials.","com_ui_delete_tool_save_reminder": "Tool removed. Save the agent to apply changes.","com_ui_deleted": "Deleted","com_ui_deleting": "Deleting...",@@ -1075,9 +1098,9 @@"com_ui_descending": "Desc","com_ui_description": "Description","com_ui_description_placeholder": "Optional: Enter a description to display for the prompt",- "com_ui_deselect_all": "Deselect All","com_ui_detailed": "Detailed","com_ui_details": "Details",+ "com_ui_disabled": "Disabled","com_ui_disabling": "Disabling...","com_ui_done": "Done","com_ui_download": "Download",@@ -1122,16 +1145,17 @@"com_ui_error_try_following_prefix": "Please try one of the following","com_ui_error_unexpected": "Oops! Something Unexpected Occurred","com_ui_error_updating_preferences": "Error updating preferences",+ "com_ui_essentials": "Essentials","com_ui_estimated": "Estimated from message history","com_ui_everyone_permission_level": "Everyone's permission level","com_ui_examples": "Examples","com_ui_expand": "Expand","com_ui_expand_chat": "Expand Chat",+ "com_ui_expand_editor": "Expand editor","com_ui_expand_thoughts": "Expand Thoughts","com_ui_export_convo_modal": "Export Conversation Modal","com_ui_failed": "Failed","com_ui_favorite": "Add to favorites",- "com_ui_favorites": "Favorites","com_ui_feedback_more": "More...","com_ui_feedback_more_information": "Provide additional feedback","com_ui_feedback_negative": "Needs improvement",@@ -1228,7 +1252,6 @@"com_ui_import_conversation_upload_error": "Error uploading file. Please try again.","com_ui_importing": "Importing","com_ui_include_shadcnui": "Include shadcn/ui components instructions",- "com_ui_initializing": "Initializing...","com_ui_input": "Input","com_ui_instructions": "Instructions","com_ui_invalid_json": "Invalid JSON",@@ -1262,17 +1285,17 @@"com_ui_low": "Low","com_ui_make_production": "Make Production","com_ui_manage": "Manage",+ "com_ui_manage_web_search_api_keys": "Manage Web Search API Keys","com_ui_marketplace": "Marketplace","com_ui_marketplace_allow_use": "Allow using Marketplace","com_ui_max": "Max","com_ui_max_favorites_reached": "Maximum pinned items reached ({{0}}). Unpin an item to add more.",+ "com_ui_max_favorites_reached_items": "Maximum favorites reached ({{0}}). Remove a favorite to add more.","com_ui_max_file_size": "PNG, JPG or JPEG (max {{0}})","com_ui_max_tags": "Maximum number allowed is {{0}}, using latest values.","com_ui_mcp_authenticated_success": "MCP server '{{0}}' authenticated successfully",- "com_ui_mcp_click_to_defer": "Click to defer - tool will be discoverable via search but not loaded until needed",- "com_ui_mcp_click_to_programmatic": "Enable programmatic calling - tool can only be invoked via code execution",- "com_ui_mcp_configure_server": "Configure {{0}}",- "com_ui_mcp_configure_server_description": "Configure custom variables for {{0}}",+ "com_ui_mcp_click_to_defer": "Loads this tool only when the agent needs it instead of keeping it active the whole time. Useful when a server has many tools.",+ "com_ui_mcp_click_to_programmatic": "The agent calls this tool by writing code, not as a direct tool call. Best for tools meant to run in code.","com_ui_mcp_defer": "Defer","com_ui_mcp_defer_all": "Defer all tools","com_ui_mcp_defer_loading": "Defer loading",@@ -1285,6 +1308,9 @@"com_ui_mcp_invalid_url": "Please enter a valid URL","com_ui_mcp_no_description": "No description available","com_ui_mcp_oauth_cancelled": "OAuth login cancelled for {{0}}",+ "com_ui_mcp_oauth_description": "Continue to authenticate, or copy the link to open it on another device.",+ "com_ui_mcp_oauth_qr_code_description": "QR code to open the OAuth login on another device",+ "com_ui_mcp_oauth_scan_qr": "Scan to open on your phone","com_ui_mcp_oauth_timeout": "OAuth login timed out for {{0}}","com_ui_mcp_programmatic": "Programmatic","com_ui_mcp_programmatic_all": "Mark all as programmatic",@@ -1348,6 +1374,7 @@"com_ui_message_nav_go_to_user": "Go to user message: {{0}}","com_ui_message_nav_next": "Navigate to next message","com_ui_message_nav_previous": "Navigate to previous message",+ "com_ui_method": "Method","com_ui_microphone_unavailable": "Microphone is not available","com_ui_min_tags": "Cannot remove more values, a minimum of {{0}} are required.","com_ui_minimal": "Minimal",@@ -1367,6 +1394,7 @@"com_ui_name_sort": "Sort by Name","com_ui_navigate_results": "Navigate results","com_ui_new": "New",+ "com_ui_new_action": "New action","com_ui_new_chat": "New chat","com_ui_new_chat_in_project": "New chat in {{name}}","com_ui_new_conversation_title": "New Conversation Title",@@ -1429,6 +1457,7 @@"com_ui_page": "Page","com_ui_pagination": "Pagination","com_ui_parameters": "Parameters",+ "com_ui_path": "Path","com_ui_people": "people","com_ui_people_picker": "People Picker","com_ui_people_picker_allow_view_groups": "Allow viewing groups",@@ -1750,11 +1779,10 @@"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_command_placeholder": "Select a Skill by name",- "com_ui_skills_disabled_hint": "Skills are off for this agent. Enable to allow the model to use your skills catalog.",+ "com_ui_skills_dialog_description": "Browse and add skills to your agent.","com_ui_skills_empty": "No skills yet",- "com_ui_skills_enable_toggle": "Enable skills for this agent",- "com_ui_skills_enabled_all_hint": "Enabled. The full accessible catalog is available; narrow it below if you want to limit which skills this agent can use.",- "com_ui_skills_enabled_allowlist_hint": "Enabled. Limited to the skills selected below.",+ "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_queued": "Skills queued for next submission",@@ -1825,9 +1853,8 @@"com_ui_token_url": "Token URL","com_ui_tokens": "tokens","com_ui_tool_collection_prefix": "A collection of tools from",+ "com_ui_tool_credentials_saved": "Credentials saved","com_ui_tool_failed": "failed",- "com_ui_tool_list_collapse": "Collapse {{serverName}} tool list",- "com_ui_tool_list_expand": "Expand {{serverName}} tool list","com_ui_tool_name_code": "Code","com_ui_tool_name_code_analysis": "Code Analysis","com_ui_tool_name_file_search": "File Search",@@ -1836,7 +1863,44 @@"com_ui_tool_name_web_search": "Web Search","com_ui_tool_response_placeholder": "Type a substitute result to return to the agent","com_ui_tools": "Tools",- "com_ui_tools_and_actions": "Tools and Actions",+ "com_ui_tools_configure": "Configure",+ "com_ui_tools_count": "{{count}} tools",+ "com_ui_tools_count_one": "{{count}} tool",+ "com_ui_tools_create_new": "Create new…",+ "com_ui_tools_empty": "No tools yet",+ "com_ui_tools_empty_hint": "Add a tool to give your agent extra abilities.",+ "com_ui_tools_endpoint_count": "{{count}} endpoints",+ "com_ui_tools_endpoint_count_one": "{{count}} endpoint",+ "com_ui_tools_info": "Tool details",+ "com_ui_tools_info_configured": "Configured",+ "com_ui_tools_info_identifier": "Identifier",+ "com_ui_tools_kind_actions": "Actions",+ "com_ui_tools_kind_mcp": "MCP servers",+ "com_ui_tools_kind_official": "Native",+ "com_ui_tools_kind_skills": "Skills",+ "com_ui_tools_kind_tools": "Tools",+ "com_ui_tools_marketplace": "Tool Library",+ "com_ui_tools_marketplace_description": "Browse and add tools, MCP servers, and actions to your agent.",+ "com_ui_tools_marketplace_search": "Search tools…",+ "com_ui_tools_mcp_deselect_all": "Deselect all",+ "com_ui_tools_mcp_no_tools": "This server has not exposed any tools yet.",+ "com_ui_tools_mcp_select_all": "Select all",+ "com_ui_tools_mcp_status_unconfigured": "Needs configuration",+ "com_ui_tools_mcp_tools_section": "Tools in this server",+ "com_ui_tools_native": "Native",+ "com_ui_tools_native_short": "Built into LibreChat",+ "com_ui_tools_needs_setup": "Needs setup",+ "com_ui_tools_no_description": "No description provided.",+ "com_ui_tools_remove": "Remove from agent",+ "com_ui_tools_search_no_results": "Nothing matched your search",+ "com_ui_tools_section_title": "Tools",+ "com_ui_tools_shared_by": "Shared by {{name}}",+ "com_ui_tools_skills_enabled_kill_switch": "Agent skills",+ "com_ui_tools_skills_enabled_kill_switch_hint": "Master switch for this agent's skills. When off, the agent ignores every skill you've selected, letting you disable them all at once without clearing your selection.",+ "com_ui_tools_view_favorites": "Favorites",+ "com_ui_tools_view_favorites_empty": "You haven't favorited anything yet",+ "com_ui_tools_view_made_by_you": "Made by you",+ "com_ui_tools_view_mine_empty": "You haven't created anything yet","com_ui_transferred_to": "Transferred to","com_ui_travel": "Travel","com_ui_trust_app": "I trust this application",@@ -1847,7 +1911,6 @@"com_ui_unarchive_conversation": "Unarchive conversation","com_ui_unarchive_error": "Failed to unarchive conversation","com_ui_unassigned": "Unassigned",- "com_ui_unavailable": "Unavailable","com_ui_unfavorite": "Remove from favorites","com_ui_unknown": "Unknown","com_ui_unknown_file_type": "Unknown file type",@@ -1869,6 +1932,7 @@"com_ui_upload_file_context": "Upload File Context","com_ui_upload_file_search": "Upload for File Search","com_ui_upload_files": "Upload files",+ "com_ui_upload_files_hint": "Click to browse and upload","com_ui_upload_icon": "Upload icon image","com_ui_upload_image": "Upload an image","com_ui_upload_image_input": "Upload Image",diff --git a/client/src/style.css b/client/src/style.cssindex 17fa19f7c6..91b4a47561 100644--- a/client/src/style.css+++ b/client/src/style.css@@ -66,6 +66,73 @@--font-size-xl: 1.25rem;--markdown-font-size: 1rem;}++/* transitions-dev tokens — semantic names shared by every t-* class below. */+:root {+ --resize-dur: 300ms;+ --resize-ease: cubic-bezier(0.22, 1, 0.36, 1);+ --icon-swap-dur: 200ms;+ --icon-swap-blur: 2px;+ --icon-swap-start-scale: 0.25;+ --icon-swap-ease: ease-in-out;+ --avatar-lift: -3px;+ --avatar-dur: 280ms;+ --avatar-scale: 1.04;+ --avatar-falloff: 0.45;+ --avatar-ease-in: cubic-bezier(0.22, 1, 0.36, 1);+ --avatar-ease-out: cubic-bezier(0.34, 3.85, 0.64, 1);+}++/* Icon swap — cross-fade two icons sharing a slot. */+.t-icon-swap {+ position: relative;+ display: inline-grid;+}+.t-icon-swap .t-icon {+ grid-area: 1 / 1;+ transition:+ opacity var(--icon-swap-dur) var(--icon-swap-ease),+ filter var(--icon-swap-dur) var(--icon-swap-ease),+ transform var(--icon-swap-dur) var(--icon-swap-ease);+ will-change: opacity, filter, transform;+}+.t-icon-swap[data-state='a'] .t-icon[data-icon='a'],+.t-icon-swap[data-state='b'] .t-icon[data-icon='b'] {+ opacity: 1;+ filter: blur(0);+ transform: scale(1);+}+.t-icon-swap[data-state='a'] .t-icon[data-icon='b'],+.t-icon-swap[data-state='b'] .t-icon[data-icon='a'] {+ opacity: 0;+ filter: blur(var(--icon-swap-blur));+ transform: scale(var(--icon-swap-start-scale));+ pointer-events: none;+}+@media (prefers-reduced-motion: reduce) {+ .t-icon-swap .t-icon {+ transition: none !important;+ }+}++/* Avatar group hover — distance-falloff lift on a horizontal row. */+.t-avatar {+ transform-origin: center;+ transform: translateY(var(--shift, 0px)) scale(var(--scale-active, 1));+ transition:+ transform var(--avatar-dur) var(--avatar-ease-in),+ background-color 150ms ease,+ color 150ms ease,+ border-color 150ms ease;+ will-change: transform;+}+@media (prefers-reduced-motion: reduce) {+ .t-avatar {+ transition: none !important;+ transform: none !important;+ }+}+html {--brand-purple: #ab68ff;--presentation: var(--white);@@ -2646,13 +2713,12 @@ html {box-shadow:0 10px 15px -3px rgb(0 0 0 / 0.1),0 4px 6px -4px rgb(0 0 0 / 0.1);- transform-origin: top;+ transform-origin: var(--popover-transform-origin, top);opacity: 0;- transition-property: opacity, scale, translate;+ transition-property: opacity, scale;transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);transition-duration: 150ms;scale: 0.95;- translate: 0 -0.5rem;margin-top: 4px;margin-right: -2px;}@@ -2706,7 +2772,6 @@ html {.popover-ui[data-enter] {opacity: 1;scale: 1;- translate: 0;}.popover-ui.popover-from-left {diff --git a/client/src/utils/favoritesError.ts b/client/src/utils/favoritesError.tsindex b9dcb279d1..ac19fccf35 100644--- a/client/src/utils/favoritesError.ts+++ b/client/src/utils/favoritesError.ts@@ -10,19 +10,21 @@ const isApiError = (error: unknown): error is ApiErrorShape =>typeof error === 'object' && error !== null && 'response' in error;/**- * Builds a localized error message from an axios-shaped favorites/skill-favorites- * mutation rejection. Recognizes the `MAX_*_EXCEEDED` codes the backend emits and- * falls back to the generic error string otherwise.+ * Builds a localized error message from an axios-shaped favorites mutation+ * rejection. Recognizes the `MAX_*_EXCEEDED` codes the backend emits and falls+ * back to the generic error string otherwise. `messageKey` lets callers pick+ * wording that fits their surface (pinned items vs. starred marketplace items).*/export function getFavoritesErrorMessage(error: unknown,localize: LocalizeFn,defaultLimit: number,+ messageKey: TranslationKeys = 'com_ui_max_favorites_reached',): string {if (isApiError(error)) {const { code, limit } = error.response?.data ?? {};if (code === 'MAX_FAVORITES_EXCEEDED' || code === 'MAX_SKILL_FAVORITES_EXCEEDED') {- return localize('com_ui_max_favorites_reached', {+ return localize(messageKey, {0: String(limit ?? defaultLimit),});}diff --git a/client/src/utils/index.ts b/client/src/utils/index.tsindex 43dc5baeea..80454beab6 100644--- a/client/src/utils/index.ts+++ b/client/src/utils/index.ts@@ -39,6 +39,7 @@ export * from './groupToolCalls';export * from './toolLabels';export * from './favoritesError';export * from './approval';+export * from './numbers';export { default as cn } from './cn';export { default as logger } from './logger';export { default as getLoginError } from './getLoginError';diff --git a/client/src/utils/numbers.spec.ts b/client/src/utils/numbers.spec.tsnew file mode 100644index 0000000000..fb6d333296--- /dev/null+++ b/client/src/utils/numbers.spec.ts@@ -0,0 +1,54 @@+import { sanitizeIntegerInput } from './numbers';++describe('sanitizeIntegerInput', () => {+ test('strips US-style thousands separators', () => {+ expect(sanitizeIntegerInput('120,000')).toBe('120000');+ });++ test('strips EU-style thousands separators', () => {+ expect(sanitizeIntegerInput('120.000')).toBe('120000');+ });++ test('strips spaces and other grouping characters', () => {+ expect(sanitizeIntegerInput('1 200 000')).toBe('1200000');+ });++ test('drops stray non-numeric characters', () => {+ expect(sanitizeIntegerInput('12a3')).toBe('123');+ expect(sanitizeIntegerInput('abc')).toBe('');+ });++ test('preserves an empty string so the field can be cleared', () => {+ expect(sanitizeIntegerInput('')).toBe('');+ });++ test('leaves a clean integer untouched', () => {+ expect(sanitizeIntegerInput('120000')).toBe('120000');+ });++ test('strips a leading minus by default', () => {+ expect(sanitizeIntegerInput('-1')).toBe('1');+ });++ describe('with allowNegative', () => {+ test('preserves a leading minus', () => {+ expect(sanitizeIntegerInput('-1', true)).toBe('-1');+ });++ test('keeps a lone minus so the sign can be typed before the digits', () => {+ expect(sanitizeIntegerInput('-', true)).toBe('-');+ });++ test('only honors a leading minus, not stray ones', () => {+ expect(sanitizeIntegerInput('1-2', true)).toBe('12');+ });++ test('still strips grouping separators around a negative value', () => {+ expect(sanitizeIntegerInput('-12,000', true)).toBe('-12000');+ });++ test('leaves a positive value unsigned', () => {+ expect(sanitizeIntegerInput('120000', true)).toBe('120000');+ });+ });+});diff --git a/client/src/utils/numbers.ts b/client/src/utils/numbers.tsnew file mode 100644index 0000000000..245bede8da--- /dev/null+++ b/client/src/utils/numbers.ts@@ -0,0 +1,21 @@+/**+ * Normalize a human-typed integer for a numeric input field.+ *+ * Strips thousands separators and any stray characters so values like+ * `"120,000"` (US) or `"120.000"` (EU) collapse to `"120000"` instead of being+ * silently truncated to `120` by a downstream `parseInt`. Both `,` and `.` are+ * treated as grouping separators, so this is locale-agnostic.+ *+ * When `allowNegative` is set (for fields whose range permits negatives, e.g.+ * Google `thinkingBudget` where `-1` selects dynamic/auto thinking), a single+ * leading minus is preserved; a lone `"-"` is kept so the sign can be typed+ * before the digits. An empty result is preserved so the field can be cleared,+ * which unsets the value and falls back to the model/server default.+ */+export function sanitizeIntegerInput(value: string, allowNegative = false): string {+ const digits = value.replace(/\D/g, '');+ if (allowNegative && value.trimStart().startsWith('-')) {+ return `-${digits}`;+ }+ return digits;+}diff --git a/client/test/itemFactories.ts b/client/test/itemFactories.tsnew file mode 100644index 0000000000..6478099de6--- /dev/null+++ b/client/test/itemFactories.ts@@ -0,0 +1,44 @@+import type { TPlugin, TSkillSummary, Action } from 'librechat-data-provider';+import type { MCPServerInfo } from '~/common';++/**+ * Typed fixture factories for the agent tools catalog specs. They fill every+ * required field so tests can pass only the properties they care about while+ * still validating overrides against the real data-provider contracts (instead+ * of erasing the shape with `as never`).+ */++export function makePlugin(overrides: Partial<TPlugin> = {}): TPlugin {+ return { name: 'Tool', pluginKey: 'tool', ...overrides };+}++export function makeSkill(overrides: Partial<TSkillSummary> = {}): TSkillSummary {+ return {+ _id: 's1',+ name: 'skill',+ description: '',+ author: 'u1',+ authorName: 'User',+ version: 1,+ source: 'inline',+ fileCount: 0,+ createdAt: '2024-01-01T00:00:00.000Z',+ updatedAt: '2024-01-01T00:00:00.000Z',+ ...overrides,+ };+}++export function makeMcpServer(overrides: Partial<MCPServerInfo> = {}): MCPServerInfo {+ return {+ serverName: 'srv',+ tools: [],+ isConfigured: true,+ isConnected: true,+ metadata: makePlugin({ name: 'srv', pluginKey: 'srv' }),+ ...overrides,+ };+}++export function makeAction(overrides: Partial<Action> = {}): Action {+ return { action_id: 'a1', metadata: {}, version: 1, agent_id: 'agent1', ...overrides } as Action;+}diff --git a/e2e/specs/mock/agents.spec.ts b/e2e/specs/mock/agents.spec.tsindex 8130a2ed68..9a1fd8cfb0 100644--- a/e2e/specs/mock/agents.spec.ts+++ b/e2e/specs/mock/agents.spec.ts@@ -132,7 +132,7 @@ test.describe('agent builder', () => {await form.getByLabel('Agent name').fill(agentName);await form.getByLabel('Agent description').fill(DESCRIPTION);- await form.getByLabel('Agent instructions').fill(INSTRUCTIONS);+ await form.getByLabel('Instructions').fill(INSTRUCTIONS);await selectMockModel(page);await fillAnthropicStyleModelParameters(page);@@ -179,7 +179,7 @@ test.describe('agent builder', () => {await expect(form.getByLabel('Agent name')).toHaveValue(agentName);await expect(form.getByLabel('Agent description')).toHaveValue(DESCRIPTION);- await expect(form.getByLabel('Agent instructions')).toHaveValue(INSTRUCTIONS);+ await expect(form.getByLabel('Instructions')).toHaveValue(INSTRUCTIONS);await form.locator('label[for="provider"] + button').click();await expectAnthropicStyleModelParameters(page);diff --git a/e2e/specs/mock/mcp.spec.ts b/e2e/specs/mock/mcp.spec.tsindex 0a2b4fd466..632bf2c5c7 100644--- a/e2e/specs/mock/mcp.spec.ts+++ b/e2e/specs/mock/mcp.spec.ts@@ -11,7 +11,6 @@ import {import { MOCK_ENDPOINTS, fetchJson, getAccessToken, mockReply, sendMessage } from './helpers';const MCP_SERVER_NAME = 'e2e-memory';-const MCP_SERVER_TITLE = 'E2E Memory';const MCP_TOOL_NAME = 'remember_fact';const MCP_SERVER_TOOL_ID = `sys__server__sys_mcp_${MCP_SERVER_NAME}`;const MCP_TOOL_ID = `${MCP_TOOL_NAME}_mcp_${MCP_SERVER_NAME}`;@@ -53,30 +52,26 @@ async function waitForMCPTools(page: Page) {}async function addMCPServerTools(page: Page, form: Locator) {- await expect(form.getByText('MCP Servers', { exact: true })).toBeVisible();- await form.getByRole('button', { name: 'Add MCP Server Tools' }).click();+ await expect(form.getByText('Tools', { exact: true })).toBeVisible();+ await form.getByRole('button', { name: 'Add tools' }).click();- const dialogTitle = page.getByText('MCP Server Tools', { exact: true });- await expect(dialogTitle).toBeVisible();- await expect(page.getByText(MCP_SERVER_TITLE, { exact: true })).toBeVisible();+ const dialog = page.getByRole('dialog', { name: 'Tool Library' });+ await expect(dialog).toBeVisible();- await page.getByRole('button', { name: `Add ${MCP_SERVER_TITLE}` }).click();- await expect(page.getByRole('button', { name: `Remove ${MCP_SERVER_TITLE}` })).toBeVisible({- timeout: 30000,- });+ await dialog.getByRole('textbox', { name: 'Search tools…' }).fill(MCP_SERVER_NAME);+ const serverCard = dialog.getByRole('button', { name: new RegExp(MCP_SERVER_NAME) }).first();+ await expect(serverCard).toBeVisible();- await page.getByRole('button', { name: 'Close dialog' }).click();- await expect(dialogTitle).toBeHidden();+ await serverCard.click();+ await expect(serverCard).toHaveAttribute('aria-pressed', 'true');+ await dialog.getByRole('button', { name: /^Close( dialog)?$/ }).click();+ await expect(dialog).toBeHidden();await expect(form.getByText(MCP_SERVER_NAME, { exact: true })).toBeVisible();- await form.getByText(MCP_SERVER_NAME, { exact: true }).click();- await expect(form.getByLabel(MCP_TOOL_NAME)).toBeVisible();}async function expectSelectedMCPServerTools(form: Locator) {await expect(form.getByText(MCP_SERVER_NAME, { exact: true })).toBeVisible();- await form.getByText(MCP_SERVER_NAME, { exact: true }).click();- await expect(form.getByLabel(MCP_TOOL_NAME)).toBeVisible();}test.describe('agent builder MCP tools', () => {@@ -92,7 +87,7 @@ test.describe('agent builder MCP tools', () => {await form.getByLabel('Agent name').fill(agentName);await form.getByLabel('Agent description').fill(DESCRIPTION);- await form.getByLabel('Agent instructions').fill(INSTRUCTIONS);+ await form.getByLabel('Instructions').fill(INSTRUCTIONS);await selectMockModel(page, true);await addMCPServerTools(page, form);@@ -135,7 +130,7 @@ test.describe('agent builder MCP tools', () => {await expect(reopenedForm.getByLabel('Agent name')).toHaveValue(agentName);await expect(reopenedForm.getByLabel('Agent description')).toHaveValue(DESCRIPTION);- await expect(reopenedForm.getByLabel('Agent instructions')).toHaveValue(INSTRUCTIONS);+ await expect(reopenedForm.getByLabel('Instructions')).toHaveValue(INSTRUCTIONS);await expectSelectedMCPServerTools(reopenedForm);await reopenedForm.getByRole('button', { name: 'Select Agent' }).click();diff --git a/packages/api/src/favorites/handlers.spec.ts b/packages/api/src/favorites/handlers.spec.tsnew file mode 100644index 0000000000..487ab939d0--- /dev/null+++ b/packages/api/src/favorites/handlers.spec.ts@@ -0,0 +1,178 @@+import type { Response } from 'express';+import type { ServerRequest } from '~/types';+import { createToolFavoritesHandlers } from './handlers';++function mockReq(overrides = {}) {+ return {+ user: { id: 'u1' },+ params: {},+ body: {},+ query: {},+ ...overrides,+ } as Partial<ServerRequest> as ServerRequest;+}++interface MockRes {+ statusCode: number;+ body: undefined | Record<string, unknown> | unknown[];+ status: jest.Mock;+ json: jest.Mock;+}++function mockRes() {+ const res: MockRes = {+ statusCode: 200,+ body: undefined,+ status: jest.fn((code: number) => {+ res.statusCode = code;+ return res;+ }),+ json: jest.fn((data: MockRes['body']) => {+ res.body = data;+ return res;+ }),+ };+ return res as Partial<Response> as Response & MockRes;+}++function createHandlers(overrides = {}) {+ const deps = {+ getToolFavorites: jest.fn().mockResolvedValue([{ itemType: 'tool', itemId: 'dalle' }]),+ addToolFavorite: jest.fn().mockResolvedValue({ ok: true, added: true }),+ removeToolFavorite: jest.fn().mockResolvedValue({ ok: true, removed: true }),+ ...overrides,+ };+ const handlers = createToolFavoritesHandlers(deps);+ return { handlers, deps };+}++describe('createToolFavoritesHandlers', () => {+ describe('listToolFavorites', () => {+ it('returns the favorites for the authenticated user', async () => {+ const { handlers, deps } = createHandlers();+ const res = mockRes();+ await handlers.listToolFavorites(mockReq(), res);+ expect(deps.getToolFavorites).toHaveBeenCalledWith('u1');+ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual([{ itemType: 'tool', itemId: 'dalle' }]);+ });++ it('returns 401 without an authenticated user', async () => {+ const { handlers, deps } = createHandlers();+ const res = mockRes();+ await handlers.listToolFavorites(mockReq({ user: undefined }), res);+ expect(res.statusCode).toBe(401);+ expect(deps.getToolFavorites).not.toHaveBeenCalled();+ });++ it('returns 500 when the dep throws', async () => {+ const { handlers } = createHandlers({+ getToolFavorites: jest.fn().mockRejectedValue(new Error('boom')),+ });+ const res = mockRes();+ await handlers.listToolFavorites(mockReq(), res);+ expect(res.statusCode).toBe(500);+ });+ });++ describe('addToolFavorite', () => {+ it('adds a favorite from validated params', async () => {+ const { handlers, deps } = createHandlers();+ const res = mockRes();+ await handlers.addToolFavorite(+ mockReq({ params: { itemType: 'mcp', itemId: 'everything' } }),+ res,+ );+ expect(deps.addToolFavorite).toHaveBeenCalledWith({+ userId: 'u1',+ itemType: 'mcp',+ itemId: 'everything',+ });+ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ itemType: 'mcp', itemId: 'everything' });+ });++ it('rejects an unknown itemType with 400 before calling deps', async () => {+ const { handlers, deps } = createHandlers();+ const res = mockRes();+ await handlers.addToolFavorite(mockReq({ params: { itemType: 'agent', itemId: 'x' } }), res);+ expect(res.statusCode).toBe(400);+ expect((res.body as Record<string, unknown>).code).toBe('INVALID_ITEM_TYPE');+ expect(deps.addToolFavorite).not.toHaveBeenCalled();+ });++ it.each([+ ['empty', ''],+ ['oversized', 'x'.repeat(257)],+ ])('rejects an %s itemId with 400', async (_label, itemId) => {+ const { handlers, deps } = createHandlers();+ const res = mockRes();+ await handlers.addToolFavorite(mockReq({ params: { itemType: 'tool', itemId } }), res);+ expect(res.statusCode).toBe(400);+ expect((res.body as Record<string, unknown>).code).toBe('INVALID_ITEM_ID');+ expect(deps.addToolFavorite).not.toHaveBeenCalled();+ });++ it('propagates the cap error code and limit as 400', async () => {+ const capError = Object.assign(new Error('Maximum of 100 favorites reached'), {+ code: 'MAX_FAVORITES_EXCEEDED',+ limit: 100,+ });+ const { handlers } = createHandlers({+ addToolFavorite: jest.fn().mockRejectedValue(capError),+ });+ const res = mockRes();+ await handlers.addToolFavorite(+ mockReq({ params: { itemType: 'skill', itemId: 'abc' } }),+ res,+ );+ expect(res.statusCode).toBe(400);+ expect(res.body).toEqual({+ code: 'MAX_FAVORITES_EXCEEDED',+ message: 'Maximum of 100 favorites reached',+ limit: 100,+ });+ });++ it('returns 500 on unexpected dep failure', async () => {+ const { handlers } = createHandlers({+ addToolFavorite: jest.fn().mockRejectedValue(new Error('boom')),+ });+ const res = mockRes();+ await handlers.addToolFavorite(+ mockReq({ params: { itemType: 'builtin', itemId: 'web_search' } }),+ res,+ );+ expect(res.statusCode).toBe(500);+ });+ });++ describe('removeToolFavorite', () => {+ it('removes a favorite from validated params', async () => {+ const { handlers, deps } = createHandlers();+ const res = mockRes();+ await handlers.removeToolFavorite(+ mockReq({ params: { itemType: 'tool', itemId: 'dalle' } }),+ res,+ );+ expect(deps.removeToolFavorite).toHaveBeenCalledWith({+ userId: 'u1',+ itemType: 'tool',+ itemId: 'dalle',+ });+ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ ok: true });+ });++ it('rejects an unknown itemType with 400', async () => {+ const { handlers, deps } = createHandlers();+ const res = mockRes();+ await handlers.removeToolFavorite(+ mockReq({ params: { itemType: 'nope', itemId: 'x' } }),+ res,+ );+ expect(res.statusCode).toBe(400);+ expect(deps.removeToolFavorite).not.toHaveBeenCalled();+ });+ });+});diff --git a/packages/api/src/favorites/handlers.ts b/packages/api/src/favorites/handlers.tsnew file mode 100644index 0000000000..378d4fa645--- /dev/null+++ b/packages/api/src/favorites/handlers.ts@@ -0,0 +1,126 @@+import { logger, FAVORITE_ITEM_TYPES } from '@librechat/data-schemas';+import type {+ FavoriteItemType,+ IToolFavoriteLean,+ AddToolFavoriteResult,+ RemoveToolFavoriteResult,+} from '@librechat/data-schemas';+import type { Response } from 'express';+import type { ServerRequest } from '~/types';++const MAX_ITEM_ID_LENGTH = 256;++/** Thin error shape `addToolFavorite` throws when the per-user cap is reached. */+type FavoriteCapError = Error & { code?: string; limit?: number };++export interface ToolFavoritesHandlersDeps {+ /** Tool favorite CRUD — from `@librechat/data-schemas` `createMethods` output. */+ getToolFavorites: (userId: string) => Promise<IToolFavoriteLean[]>;+ addToolFavorite: (params: {+ userId: string;+ itemType: FavoriteItemType;+ itemId: string;+ }) => Promise<AddToolFavoriteResult>;+ removeToolFavorite: (params: {+ userId: string;+ itemType: FavoriteItemType;+ itemId: string;+ }) => Promise<RemoveToolFavoriteResult>;+}++interface ValidatedParams {+ itemType: FavoriteItemType;+ itemId: string;+}++function validateParams(req: ServerRequest, res: Response): ValidatedParams | null {+ const { itemType, itemId } = req.params as { itemType?: string; itemId?: string };++ if (!FAVORITE_ITEM_TYPES.includes(itemType as FavoriteItemType)) {+ res.status(400).json({+ code: 'INVALID_ITEM_TYPE',+ message: `itemType must be one of: ${FAVORITE_ITEM_TYPES.join(', ')}`,+ });+ return null;+ }++ if (typeof itemId !== 'string' || itemId.length === 0 || itemId.length > MAX_ITEM_ID_LENGTH) {+ res.status(400).json({+ code: 'INVALID_ITEM_ID',+ message: `itemId must be a non-empty string of at most ${MAX_ITEM_ID_LENGTH} characters`,+ });+ return null;+ }++ return { itemType: itemType as FavoriteItemType, itemId };+}++export function createToolFavoritesHandlers(deps: ToolFavoritesHandlersDeps): {+ listToolFavorites: (req: ServerRequest, res: Response) => Promise<Response>;+ addToolFavorite: (req: ServerRequest, res: Response) => Promise<Response>;+ removeToolFavorite: (req: ServerRequest, res: Response) => Promise<Response>;+} {+ async function listToolFavorites(req: ServerRequest, res: Response): Promise<Response> {+ const userId = req.user?.id;+ if (!userId) {+ return res.status(401).json({ message: 'Unauthorized' });+ }+ try {+ const favorites = await deps.getToolFavorites(userId);+ return res.status(200).json(favorites);+ } catch (error) {+ logger.error('[ToolFavorites] Error listing favorites:', error);+ return res.status(500).json({ message: 'Failed to retrieve favorites' });+ }+ }++ async function addToolFavorite(req: ServerRequest, res: Response): Promise<Response> {+ const userId = req.user?.id;+ if (!userId) {+ return res.status(401).json({ message: 'Unauthorized' });+ }+ const params = validateParams(req, res);+ if (params == null) {+ return res;+ }+ try {+ await deps.addToolFavorite({ userId, ...params });+ return res.status(200).json(params);+ } catch (error) {+ const capError = error as FavoriteCapError;+ if (capError.code === 'MAX_FAVORITES_EXCEEDED') {+ return res.status(400).json({+ code: capError.code,+ message: capError.message,+ limit: capError.limit,+ });+ }+ logger.error('[ToolFavorites] Error adding favorite:', error);+ return res.status(500).json({ message: 'Failed to add favorite' });+ }+ }++ async function removeToolFavorite(req: ServerRequest, res: Response): Promise<Response> {+ const userId = req.user?.id;+ if (!userId) {+ return res.status(401).json({ message: 'Unauthorized' });+ }+ const params = validateParams(req, res);+ if (params == null) {+ return res;+ }+ try {+ await deps.removeToolFavorite({ userId, ...params });+ return res.status(200).json({ ok: true });+ } catch (error) {+ logger.error('[ToolFavorites] Error removing favorite:', error);+ return res.status(500).json({ message: 'Failed to remove favorite' });+ }+ }++ return {+ listToolFavorites,+ addToolFavorite,+ removeToolFavorite,+ };+}diff --git a/packages/api/src/favorites/index.ts b/packages/api/src/favorites/index.tsnew file mode 100644index 0000000000..6c6f862d01--- /dev/null+++ b/packages/api/src/favorites/index.ts@@ -0,0 +1 @@+export * from './handlers';diff --git a/packages/api/src/index.ts b/packages/api/src/index.tsindex ead04e0b87..fff580d06f 100644--- a/packages/api/src/index.ts+++ b/packages/api/src/index.ts@@ -51,6 +51,7 @@ export * from './prompts';export * from './projects';/* Skills */export * from './skills';+export * from './favorites';/* Endpoints */export * from './endpoints';/* Files */diff --git a/packages/client/src/components/Button.tsx b/packages/client/src/components/Button.tsxindex 53150bde5a..a486221b91 100644--- a/packages/client/src/components/Button.tsx+++ b/packages/client/src/components/Button.tsx@@ -30,6 +30,8 @@ const buttonVariants: ('bg-surface-destructive text-destructive-foreground hover:bg-surface-destructive-hover',outline:'text-text-primary border border-border-light bg-transparent hover:bg-accent hover:text-accent-foreground',+ subtle:+ 'rounded-xl border border-border-light bg-transparent text-text-primary hover:bg-surface-secondary focus-visible:ring-ring-primary focus-visible:ring-offset-0',secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',ghost: 'hover:bg-surface-hover hover:text-accent-foreground',link: 'text-primary underline-offset-4 hover:underline',diff --git a/packages/client/src/components/ControlCombobox.tsx b/packages/client/src/components/ControlCombobox.tsxindex b23d8d622d..3286bdafc2 100644--- a/packages/client/src/components/ControlCombobox.tsx+++ b/packages/client/src/components/ControlCombobox.tsx@@ -4,6 +4,7 @@ import { matchSorter } from 'match-sorter';import { Search, ChevronDown } from 'lucide-react';import { SelectRenderer } from '@ariakit/react-components/select/select-renderer';import type { OptionWithIcon } from '~/common';+import { usePopoverZIndex } from './OriginalDialog';import './AnimatePopover.css';import { JSX } from 'react/jsx-runtime';import { cn } from '~/utils';@@ -52,6 +53,7 @@ function ControlCombobox({const [searchValue, setSearchValue] = useState('');const buttonRef = useRef<HTMLButtonElement>(null);const [buttonWidth, setButtonWidth] = useState<number | null>(null);+ const popoverZIndex = usePopoverZIndex();const getItem = (option: OptionWithIcon) => ({id: `item-${option.value}`,@@ -142,7 +144,10 @@ function ControlCombobox({)}{!isCollapsed && (<>- <span className="flex-grow truncate text-left">+ <span+ className="flex-grow truncate text-left"+ title={(displayValue != null ? displayValue : selectedValue) || undefined}+ >{displayValue != null? displayValue || selectPlaceholder: selectedValue || selectPlaceholder}@@ -159,9 +164,9 @@ function ControlCombobox({gutter={4}portalclassName={cn(- 'animate-popover z-40 overflow-hidden rounded-xl border border-border-light bg-surface-secondary shadow-lg',+ 'animate-popover overflow-hidden rounded-xl border border-border-light bg-surface-secondary shadow-lg',)}- style={{ width: isCollapsed ? '300px' : (buttonWidth ?? '300px') }}+ style={{ zIndex: popoverZIndex, width: isCollapsed ? '300px' : (buttonWidth ?? '300px') }}><div className="py-1.5"><div className="relative">diff --git a/packages/client/src/components/Dropdown.css b/packages/client/src/components/Dropdown.cssindex e529af953f..9b3026f7e5 100644--- a/packages/client/src/components/Dropdown.css+++ b/packages/client/src/components/Dropdown.css@@ -14,13 +14,12 @@box-shadow:0 10px 15px -3px rgb(0 0 0 / 0.1),0 4px 6px -4px rgb(0 0 0 / 0.1);- transform-origin: top;+ transform-origin: var(--popover-transform-origin, top);opacity: 0;- transition-property: opacity, scale, translate;+ transition-property: opacity, scale;transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);transition-duration: 150ms;scale: 0.95;- translate: 0 -0.5rem;margin-top: 4px;margin-right: -2px;}@@ -74,5 +73,4 @@.popover-ui[data-enter] {opacity: 1;scale: 1;- translate: 0;}diff --git a/packages/client/src/components/DropdownMenu.tsx b/packages/client/src/components/DropdownMenu.tsxindex a73fe6e7c1..c3bd816de9 100644--- a/packages/client/src/components/DropdownMenu.tsx+++ b/packages/client/src/components/DropdownMenu.tsx@@ -2,6 +2,7 @@ import * as React from 'react';import { JSX } from 'react/jsx-runtime';import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';+import { usePopoverZIndex } from './OriginalDialog';import { cn } from '~/utils';function DropdownMenu({@@ -25,15 +26,18 @@ function DropdownMenuTrigger({function DropdownMenuContent({className,sideOffset = 4,+ style,...props}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>): JSX.Element {+ const zIndex = usePopoverZIndex();return (<DropdownMenuPrimitive.Portal><DropdownMenuPrimitive.Contentdata-slot="dropdown-menu-content"sideOffset={sideOffset}+ style={{ zIndex, ...style }}className={cn(- 'max-h-(--radix-dropdown-menu-content-available-height) origin-(--radix-dropdown-menu-content-transform-origin) z-40 min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border border-border-medium bg-surface-primary p-1 text-text-primary shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',+ 'max-h-(--radix-dropdown-menu-content-available-height) origin-(--radix-dropdown-menu-content-transform-origin) min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border border-border-medium bg-surface-primary p-1 text-text-primary shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',className,)}{...props}@@ -199,13 +203,16 @@ function DropdownMenuSubTrigger({function DropdownMenuSubContent({className,+ style,...props}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>): JSX.Element {+ const zIndex = usePopoverZIndex();return (<DropdownMenuPrimitive.SubContentdata-slot="dropdown-menu-sub-content"+ style={{ zIndex, ...style }}className={cn(- 'origin-(--radix-dropdown-menu-content-transform-origin) z-40 min-w-[8rem] overflow-hidden rounded-md border border-border-medium bg-surface-primary p-1 text-text-primary shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',+ 'origin-(--radix-dropdown-menu-content-transform-origin) min-w-[8rem] overflow-hidden rounded-md border border-border-medium bg-surface-primary p-1 text-text-primary shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',className,)}{...props}diff --git a/packages/client/src/components/DropdownPopup.tsx b/packages/client/src/components/DropdownPopup.tsxindex fa628ce89f..dacac8de3e 100644--- a/packages/client/src/components/DropdownPopup.tsx+++ b/packages/client/src/components/DropdownPopup.tsx@@ -1,6 +1,7 @@import React from 'react';import * as Ariakit from '@ariakit/react';import type * as t from '~/common';+import { usePopoverZIndex } from './OriginalDialog';import { cn } from '~/utils';import './Dropdown.css';@@ -71,10 +72,12 @@ const Menu: React.FC<MenuProps> = ({finalFocus,unmountOnHide,preserveTabOrder,+ style,...props}) => {const menuStore = Ariakit.useMenuStore();const menu = Ariakit.useMenuContext();+ const zIndex = usePopoverZIndex();return (<Ariakit.Menuid={menuId}@@ -85,7 +88,8 @@ const Menu: React.FC<MenuProps> = ({finalFocus={finalFocus}unmountOnHide={unmountOnHide}preserveTabOrder={preserveTabOrder}- className={cn('popover-ui z-40', className)}+ style={{ zIndex, ...style }}+ className={cn('popover-ui', className)}{...props}>{itemsdiff --git a/packages/client/src/components/Field.css b/packages/client/src/components/Field.cssnew file mode 100644index 0000000000..049a0591ac--- /dev/null+++ b/packages/client/src/components/Field.css@@ -0,0 +1,11 @@+/* Shared Input/Textarea (.lc-field): show the focus ring for keyboard users+ only. Text inputs match :focus-visible on pointer focus too (a UA heuristic+ CSS cannot distinguish), so the ring is gated on the input modality tracked+ by useInputModality (mount it once near the app root). Without the hook the+ attribute is absent and the ring always shows — the safe fallback. */+html[data-input-modality='pointer'] .lc-field:focus,+html[data-input-modality='pointer'] .lc-field:focus-visible {+ border-color: var(--border-light);+ box-shadow: none;+ outline: none;+}diff --git a/packages/client/src/components/Input.tsx b/packages/client/src/components/Input.tsxindex 6f502e08aa..a55a5c0486 100644--- a/packages/client/src/components/Input.tsx+++ b/packages/client/src/components/Input.tsx@@ -1,5 +1,6 @@import * as React from 'react';import { cn } from '~/utils';+import './Field.css';export type InputProps = React.InputHTMLAttributes<HTMLInputElement>;@@ -8,7 +9,7 @@ const Input: React.ForwardRefExoticComponent<InputProps & React.RefAttributes<HTreturn (<inputclassName={cn(- 'flex h-10 w-full rounded-lg border border-border-light bg-transparent px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',+ 'lc-field flex h-10 w-full rounded-lg border border-border-light bg-transparent px-3 py-2 text-sm text-text-primary ring-offset-background placeholder:text-text-secondary focus-visible:border-border-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary disabled:cursor-not-allowed disabled:opacity-50',className ?? '',)}ref={ref}diff --git a/packages/client/src/components/OriginalDialog.tsx b/packages/client/src/components/OriginalDialog.tsxindex 70a19e3433..9d17779bed 100644--- a/packages/client/src/components/OriginalDialog.tsx+++ b/packages/client/src/components/OriginalDialog.tsx@@ -6,6 +6,22 @@ import { cn } from '~/utils';const DialogDepthContext = React.createContext(0);+/** Current OGDialog nesting depth (0 when rendered outside any dialog). */+export const useDialogDepth = (): number => React.useContext(DialogDepthContext);++/**+ * z-index for a portaled popover so it renders above the dialog it lives in.+ * Outside any dialog (depth 0) it falls back to a low default (50).+ */+export const usePopoverZIndex = (): number => {+ const depth = useDialogDepth();+ if (depth <= 0) {+ return 50;+ }+ const contentZIndex = 140 + (depth - 1) * 60;+ return contentZIndex + 10;+};+interface OGDialogProps extends DialogPrimitive.DialogProps {triggerRef?: React.RefObject<HTMLButtonElement | HTMLInputElement | HTMLDivElement | null>;triggerRefs?: React.RefObject<HTMLButtonElement | HTMLInputElement | HTMLDivElement | null>[];diff --git a/packages/client/src/components/Radio.tsx b/packages/client/src/components/Radio.tsxindex 0115c6b9d5..9c40ade362 100644--- a/packages/client/src/components/Radio.tsx+++ b/packages/client/src/components/Radio.tsx@@ -1,4 +1,4 @@-import React, { useState, useRef, useLayoutEffect, useEffect, useCallback, memo } from 'react';+import React, { useState, useRef, useLayoutEffect, useCallback, memo } from 'react';import { useLocalize } from '~/hooks';interface Option {@@ -29,6 +29,7 @@ const Radio: React.NamedExoticComponent<RadioProps> = memo(function Radio({'aria-labelledby': ariaLabelledBy,}: RadioProps) {const localize = useLocalize();+ const containerRef = useRef<HTMLDivElement | null>(null);const buttonRefs = useRef<(HTMLButtonElement | null)[]>([]);const [isMounted, setIsMounted] = useState(false);const [currentValue, setCurrentValue] = useState<string>(value ?? '');@@ -41,36 +42,33 @@ const Radio: React.NamedExoticComponent<RadioProps> = memo(function Radio({const updateBackgroundStyle = useCallback(() => {const selectedIndex = options.findIndex((opt) => opt.value === currentValue);- if (selectedIndex >= 0 && buttonRefs.current[selectedIndex]) {- const selectedButton = buttonRefs.current[selectedIndex];- const container = selectedButton?.parentElement;- if (selectedButton && container) {- const containerRect = container.getBoundingClientRect();- const buttonRect = selectedButton.getBoundingClientRect();- const offsetLeft = buttonRect.left - containerRect.left;- setBackgroundStyle({- width: `${buttonRect.width}px`,- transform: `translateX(${offsetLeft}px)`,- });- }+ const selectedButton = buttonRefs.current[selectedIndex];+ if (selectedIndex < 0 || !selectedButton) {+ return;}+ // offsetWidth/offsetLeft are layout metrics: unlike getBoundingClientRect they+ // are not distorted by the dialog's open transform (scale), and they resolve to+ // whole pixels, so the indicator matches its segment and keeps crisp borders.+ setBackgroundStyle({+ width: `${selectedButton.offsetWidth}px`,+ transform: `translateX(${selectedButton.offsetLeft}px)`,+ });}, [currentValue, options]);- // Mark as mounted after dialog animations settle- // Timeout ensures we wait for CSS transitions to complete- useEffect(() => {- const timeout = setTimeout(() => {- setIsMounted(true);- }, 50);-- return () => clearTimeout(timeout);- }, []);-+ // Measure before paint and re-measure on any later layout change (the dialog's+ // open animation settling, a window resize). A fixed timeout previously raced+ // the dialog transition and left the indicator mis-sized.useLayoutEffect(() => {- if (isMounted) {- updateBackgroundStyle();+ const container = containerRef.current;+ if (!container) {+ return;}- }, [isMounted, updateBackgroundStyle]);+ updateBackgroundStyle();+ setIsMounted(true);+ const observer = new ResizeObserver(() => updateBackgroundStyle());+ observer.observe(container);+ return () => observer.disconnect();+ }, [updateBackgroundStyle]);useLayoutEffect(() => {if (value !== undefined) {@@ -96,13 +94,14 @@ const Radio: React.NamedExoticComponent<RadioProps> = memo(function Radio({return (<div- className={`relative ${fullWidth ? 'flex' : 'inline-flex'} items-center rounded-lg bg-muted ${className}`}+ ref={containerRef}+ className={`relative ${fullWidth ? 'flex' : 'inline-flex'} items-center rounded-lg bg-muted px-1 ${className}`}role="radiogroup"aria-labelledby={ariaLabelledBy}>{selectedIndex >= 0 && isMounted && (<div- className="pointer-events-none absolute inset-y-0 rounded-md border border-border/50 bg-background shadow-sm transition-all duration-300 ease-out"+ className="pointer-events-none absolute inset-y-1 left-0 rounded-md border border-border bg-background shadow-sm transition-all duration-300 ease-out"style={backgroundStyle}/>)}@@ -118,7 +117,7 @@ const Radio: React.NamedExoticComponent<RadioProps> = memo(function Radio({onClick={() => handleChange(option.value)}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-ring ${- currentValue === option.value ? 'text-foreground' : 'text-foreground'+ currentValue === option.value ? 'text-text-primary' : 'text-text-secondary'} ${disabled ? 'cursor-not-allowed opacity-50' : ''} ${fullWidth ? 'flex-1' : ''} ${buttonClassName}`}>{option.icon && (diff --git a/packages/client/src/components/Textarea.tsx b/packages/client/src/components/Textarea.tsxindex 0ad61c8786..57a2483578 100644--- a/packages/client/src/components/Textarea.tsx+++ b/packages/client/src/components/Textarea.tsx@@ -2,6 +2,7 @@import * as React from 'react';import TextareaAutosize from 'react-textarea-autosize';import { cn } from '~/utils';+import './Field.css';export interface TextareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}@@ -11,7 +12,7 @@ const Textarea: React.ForwardRefExoticComponent<return (<textareaclassName={cn(- 'flex h-20 w-full resize-none rounded-md border border-gray-300 bg-transparent px-3 py-2 text-sm placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:text-gray-50 dark:focus:ring-gray-400 dark:focus:ring-offset-gray-900',+ 'lc-field flex min-h-20 w-full resize-none rounded-lg border border-border-light bg-surface-secondary px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:border-border-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring-primary disabled:cursor-not-allowed disabled:opacity-50',className,)}ref={ref}diff --git a/packages/client/src/components/Tooltip.tsx b/packages/client/src/components/Tooltip.tsxindex 21457c9435..4d5fcc4bbd 100644--- a/packages/client/src/components/Tooltip.tsx+++ b/packages/client/src/components/Tooltip.tsx@@ -9,6 +9,7 @@ import {import DOMPurify from 'dompurify';import * as Ariakit from '@ariakit/react';import { AnimatePresence, motion } from 'framer-motion';+import { useDialogDepth, usePopoverZIndex } from './OriginalDialog';import { cn } from '~/utils';import './Tooltip.css';@@ -35,6 +36,11 @@ const TooltipPopup = memo(function TooltipPopup({}) {const mounted = Ariakit.useStoreState(store, (state) => state.mounted);const placement = Ariakit.useStoreState(store, (state) => state.placement);+ /** Tooltips portal to body at z-150, which nested dialogs (z 200+) cover —+ * inside a dialog, borrow the popover's depth-aware z-index; outside, keep+ * the stylesheet default so tooltips never outrank freshly opened dialogs. */+ const dialogDepth = useDialogDepth();+ const popoverZIndex = usePopoverZIndex();const sanitizer = useMemo(() => {const instance = DOMPurify();@@ -89,6 +95,7 @@ const TooltipPopup = memo(function TooltipPopup({className="tooltip"render={<motion.div+ style={dialogDepth > 0 ? { zIndex: popoverZIndex } : undefined}initial={{ opacity: 0, x, y }}animate={{ opacity: 1, x: 0, y: 0 }}exit={{ opacity: 0, x, y }}diff --git a/packages/client/src/hooks/index.ts b/packages/client/src/hooks/index.tsindex 9a140087ca..43d89d1e24 100644--- a/packages/client/src/hooks/index.ts+++ b/packages/client/src/hooks/index.ts@@ -8,4 +8,5 @@ export { default as useCombobox } from './useCombobox';export { default as useLocalize } from './useLocalize';export { default as useMediaQuery } from './useMediaQuery';export { default as useDelayedRender } from './useDelayedRender';+export { default as useInputModality } from './useInputModality';export { default as useOnClickOutside } from './useOnClickOutside';diff --git a/packages/client/src/hooks/useInputModality.ts b/packages/client/src/hooks/useInputModality.tsnew file mode 100644index 0000000000..837610fd00--- /dev/null+++ b/packages/client/src/hooks/useInputModality.ts@@ -0,0 +1,54 @@+import { useEffect } from 'react';++type Modality = 'keyboard' | 'pointer';++let refCount = 0;+let current: Modality | null = null;++function apply(modality: Modality) {+ if (current === modality) {+ return;+ }+ current = modality;+ document.documentElement.dataset.inputModality = modality;+}++function handlePointer() {+ apply('pointer');+}++function handleKeydown(event: KeyboardEvent) {+ if (event.key === 'Tab') {+ apply('keyboard');+ }+}++/**+ * Tracks whether the user is currently interacting via pointer or keyboard and+ * reflects it on `document.documentElement` as `data-input-modality`. Lets CSS+ * gate focus styling so text inputs only show a focus ring for keyboard users+ * (text inputs match `:focus-visible` on pointer focus too, which CSS alone+ * cannot distinguish). Ref-counted so concurrent mounts share one listener set.+ */+export default function useInputModality(): void {+ useEffect(() => {+ if (typeof document === 'undefined') {+ return;+ }+ if (refCount === 0) {+ apply('pointer');+ window.addEventListener('pointerdown', handlePointer, true);+ window.addEventListener('keydown', handleKeydown, true);+ }+ refCount += 1;+ return () => {+ refCount -= 1;+ if (refCount === 0) {+ window.removeEventListener('pointerdown', handlePointer, true);+ window.removeEventListener('keydown', handleKeydown, true);+ delete document.documentElement.dataset.inputModality;+ current = null;+ }+ };+ }, []);+}diff --git a/packages/data-provider/src/api-endpoints.ts b/packages/data-provider/src/api-endpoints.tsindex 4cc2fd1c47..b08e9c5106 100644--- a/packages/data-provider/src/api-endpoints.ts+++ b/packages/data-provider/src/api-endpoints.ts@@ -438,6 +438,11 @@ export const skillTree = ({ skillId, path = '' }: { skillId: string; path?: stri/* Skill active states (per-user overrides) */export const skillStates = () => `${BASE_URL}/api/user/settings/skills/active`;+/* Tool favorites (starred marketplace items) */+export const toolFavorites = () => `${BASE_URL}/api/user/settings/favorites/tools`;+export const toolFavorite = (itemType: string, itemId: string) =>+ `${toolFavorites()}/${itemType}/${encodeURIComponent(itemId)}`;+/* Roles */export const roles = () => `${BASE_URL}/api/roles`;export const adminRoles = () => `${BASE_URL}/api/admin/roles`;diff --git a/packages/data-provider/src/data-service.ts b/packages/data-provider/src/data-service.tsindex 87d216e27f..d06c138e0d 100644--- a/packages/data-provider/src/data-service.ts+++ b/packages/data-provider/src/data-service.ts@@ -35,17 +35,17 @@ export function updateFavorites(favorites: q.TUserFavorite[]): Promise<q.TUserFareturn request.post(`${endpoints.apiBaseUrl()}/api/user/settings/favorites`, { favorites });}-/**- * Skill favorites (star-a-skill). The backend route is phase 2 — see the- * original UI PR for the client surface. Until then, these resolve with- * an empty list so the UI hooks compile and the Star button is a no-op.- */-export function getSkillFavorites(): Promise<string[]> {- return Promise.resolve([] as string[]);+/** Tool favorites — starred marketplace items (builtins, tools, MCP servers, skills). */+export function getToolFavorites(): Promise<q.TToolFavorite[]> {+ return request.get(endpoints.toolFavorites());+}++export function addToolFavorite(favorite: q.TToolFavorite): Promise<q.TToolFavorite> {+ return request.put(endpoints.toolFavorite(favorite.itemType, favorite.itemId));}-export function updateSkillFavorites(skillFavorites: string[]): Promise<string[]> {- return Promise.resolve(skillFavorites);+export function removeToolFavorite(favorite: q.TToolFavorite): Promise<{ ok: boolean }> {+ return request.delete(endpoints.toolFavorite(favorite.itemType, favorite.itemId));}/** Per-user skill active/inactive overrides. */diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex 26eed7462a..22b9ee959a 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -79,8 +79,8 @@ export enum QueryKeys {/* Skill tree (phase 2 — filesystem-style node view) */skillTree = 'skillTree',skillNodeContent = 'skillNodeContent',- /* Skill favorites (star a skill in the sidebar) */- skillFavorites = 'skillFavorites',+ /* Tool favorites (starred marketplace items) */+ toolFavorites = 'toolFavorites',/* Per-user skill active/inactive overrides */skillStates = 'skillStates',/* General user favorites */diff --git a/packages/data-provider/src/types/queries.ts b/packages/data-provider/src/types/queries.tsindex abe773fce2..f763632d81 100644--- a/packages/data-provider/src/types/queries.ts+++ b/packages/data-provider/src/types/queries.ts@@ -228,8 +228,18 @@ export type TUserFavorite = {model?: string;endpoint?: string;spec?: string;- /** Phase 2 — skill favoriting isn't persisted yet, but the shape is reserved. */- skillId?: string;+};++/**+ * Tool favorites — starred marketplace items (built-in capabilities, plugin+ * tools, MCP servers, skills). Identity is the compound (itemType, itemId)+ * pair, matching the marketplace `itemKey` format `itemType:itemId`.+ */+export type TToolFavoriteType = 'builtin' | 'tool' | 'mcp' | 'skill';++export type TToolFavorite = {+ itemType: TToolFavoriteType;+ itemId: string;};/* SharePoint Graph API Token */diff --git a/packages/data-schemas/src/index.ts b/packages/data-schemas/src/index.tsindex ee393b2de4..85ff1b86fc 100644--- a/packages/data-schemas/src/index.ts+++ b/packages/data-schemas/src/index.ts@@ -28,7 +28,9 @@ export {MAX_AUDIT_EXPORT_ROWS,MAX_AUDIT_LOG_LIMIT,MAX_AUDIT_VERIFY_ROWS,+ MAX_TOOL_FAVORITES,} from './methods';+export { FAVORITE_ITEM_TYPES } from './types/favorite';export type * from './types';export type * from './methods';export {diff --git a/packages/data-schemas/src/methods/favorite.spec.ts b/packages/data-schemas/src/methods/favorite.spec.tsnew file mode 100644index 0000000000..e4306ac3e4--- /dev/null+++ b/packages/data-schemas/src/methods/favorite.spec.ts@@ -0,0 +1,153 @@+import mongoose from 'mongoose';+import { logger, createModels } from '..';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { createToolFavoriteMethods, MAX_TOOL_FAVORITES } from './favorite';++logger.silent = true;++let ToolFavorite: mongoose.Model<unknown>;+let methods: ReturnType<typeof createToolFavoriteMethods>;+let mongoServer: MongoMemoryServer;++const userA = new mongoose.Types.ObjectId().toString();+const userB = new mongoose.Types.ObjectId().toString();++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ await mongoose.connect(mongoServer.getUri());+ createModels(mongoose);+ ToolFavorite = mongoose.models.ToolFavorite;+ await ToolFavorite.syncIndexes();+ methods = createToolFavoriteMethods(mongoose);+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+});++beforeEach(async () => {+ await ToolFavorite.deleteMany({});+});++describe('addToolFavorite', () => {+ test('persists a favorite and getToolFavorites returns the lean projection', async () => {+ const result = await methods.addToolFavorite({+ userId: userA,+ itemType: 'mcp',+ itemId: 'everything',+ });+ expect(result).toEqual({ ok: true, added: true });++ const favorites = await methods.getToolFavorites(userA);+ expect(favorites).toEqual([{ itemType: 'mcp', itemId: 'everything' }]);+ });++ test('is idempotent: double-add keeps one doc and reports added: false', async () => {+ await methods.addToolFavorite({ userId: userA, itemType: 'tool', itemId: 'dalle' });+ const second = await methods.addToolFavorite({+ userId: userA,+ itemType: 'tool',+ itemId: 'dalle',+ });+ expect(second).toEqual({ ok: true, added: false });+ expect(await ToolFavorite.countDocuments({ user: userA })).toBe(1);+ });++ test('rejects an itemType outside the enum', async () => {+ await expect(+ methods.addToolFavorite({+ userId: userA,+ itemType: 'agent' as never,+ itemId: 'x',+ }),+ ).rejects.toThrow();+ });++ test('rejects an itemId longer than 256 characters', async () => {+ await expect(+ methods.addToolFavorite({ userId: userA, itemType: 'tool', itemId: 'x'.repeat(257) }),+ ).rejects.toThrow();+ });++ test('throws a coded error at the cap, but re-adding an existing favorite still succeeds', async () => {+ const docs = Array.from({ length: MAX_TOOL_FAVORITES }, (_, i) => ({+ user: userA,+ itemType: 'tool',+ itemId: `tool-${i}`,+ }));+ await ToolFavorite.insertMany(docs);++ const rejection = methods.addToolFavorite({+ userId: userA,+ itemType: 'tool',+ itemId: 'one-too-many',+ });+ await expect(rejection).rejects.toMatchObject({+ code: 'MAX_FAVORITES_EXCEEDED',+ limit: MAX_TOOL_FAVORITES,+ });++ const existing = await methods.addToolFavorite({+ userId: userA,+ itemType: 'tool',+ itemId: 'tool-0',+ });+ expect(existing).toEqual({ ok: true, added: false });+ });++ test('concurrent duplicate adds do not throw (unique index backstop)', async () => {+ const params = { userId: userA, itemType: 'skill', itemId: 'abc123' } as const;+ const results = await Promise.all([+ methods.addToolFavorite(params),+ methods.addToolFavorite(params),+ methods.addToolFavorite(params),+ ]);+ expect(results.every((r) => r.ok)).toBe(true);+ expect(await ToolFavorite.countDocuments({ user: userA })).toBe(1);+ });+});++describe('removeToolFavorite', () => {+ test('removes a favorite and is idempotent', async () => {+ await methods.addToolFavorite({ userId: userA, itemType: 'builtin', itemId: 'web_search' });++ const removed = await methods.removeToolFavorite({+ userId: userA,+ itemType: 'builtin',+ itemId: 'web_search',+ });+ expect(removed).toEqual({ ok: true, removed: true });++ const again = await methods.removeToolFavorite({+ userId: userA,+ itemType: 'builtin',+ itemId: 'web_search',+ });+ expect(again).toEqual({ ok: true, removed: false });+ expect(await methods.getToolFavorites(userA)).toEqual([]);+ });+});++describe('getToolFavorites', () => {+ test('is isolated per user', async () => {+ await methods.addToolFavorite({ userId: userA, itemType: 'tool', itemId: 'dalle' });+ await methods.addToolFavorite({ userId: userB, itemType: 'mcp', itemId: 'everything' });++ expect(await methods.getToolFavorites(userA)).toEqual([{ itemType: 'tool', itemId: 'dalle' }]);+ expect(await methods.getToolFavorites(userB)).toEqual([+ { itemType: 'mcp', itemId: 'everything' },+ ]);+ });++ test('does not distinguish same itemId across kinds (compound identity)', async () => {+ await methods.addToolFavorite({ userId: userA, itemType: 'tool', itemId: 'shared-id' });+ await methods.addToolFavorite({ userId: userA, itemType: 'skill', itemId: 'shared-id' });++ const favorites = await methods.getToolFavorites(userA);+ expect(favorites).toHaveLength(2);+ expect(new Set(favorites.map((f) => `${f.itemType}:${f.itemId}`))).toEqual(+ new Set(['tool:shared-id', 'skill:shared-id']),+ );+ });+});diff --git a/packages/data-schemas/src/methods/favorite.ts b/packages/data-schemas/src/methods/favorite.tsnew file mode 100644index 0000000000..10e1544f20--- /dev/null+++ b/packages/data-schemas/src/methods/favorite.ts@@ -0,0 +1,90 @@+import type * as t from '~/types';++export const MAX_TOOL_FAVORITES = 100;++const DUPLICATE_KEY_ERROR = 11000;++function isDuplicateKeyError(error: unknown): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ (error as { code?: number }).code === DUPLICATE_KEY_ERROR+ );+}++function capError(): Error {+ const error = new Error(`Maximum of ${MAX_TOOL_FAVORITES} favorites reached`);+ (error as Error & { code: string; limit: number }).code = 'MAX_FAVORITES_EXCEEDED';+ (error as Error & { code: string; limit: number }).limit = MAX_TOOL_FAVORITES;+ return error;+}++export function createToolFavoriteMethods(mongoose: typeof import('mongoose')): {+ getToolFavorites: (userId: string) => Promise<t.IToolFavoriteLean[]>;+ addToolFavorite: (params: t.ToolFavoriteParams) => Promise<t.AddToolFavoriteResult>;+ removeToolFavorite: (params: t.ToolFavoriteParams) => Promise<t.RemoveToolFavoriteResult>;+} {+ async function getToolFavorites(userId: string): Promise<t.IToolFavoriteLean[]> {+ const ToolFavorite = mongoose.models.ToolFavorite;+ return ToolFavorite.find({ user: userId })+ .select('itemType itemId -_id')+ .sort({ createdAt: 1 })+ .lean<t.IToolFavoriteLean[]>();+ }++ /**+ * Idempotent add. The unique `{ user, itemType, itemId }` index is the+ * concurrency backstop: a duplicate-key rejection from a racing insert is+ * treated as success. The cap check is read-then-write and may transiently+ * overshoot by one or two under concurrency — acceptable for a soft UX cap.+ */+ async function addToolFavorite({+ userId,+ itemType,+ itemId,+ }: t.ToolFavoriteParams): Promise<t.AddToolFavoriteResult> {+ const ToolFavorite = mongoose.models.ToolFavorite;+ const filter = { user: userId, itemType, itemId };++ const existing = await ToolFavorite.exists(filter);+ if (existing != null) {+ return { ok: true, added: false };+ }++ const count = await ToolFavorite.countDocuments({ user: userId });+ if (count >= MAX_TOOL_FAVORITES) {+ throw capError();+ }++ try {+ await ToolFavorite.updateOne(+ filter,+ { $setOnInsert: filter },+ { upsert: true, runValidators: true },+ );+ } catch (error) {+ if (!isDuplicateKeyError(error)) {+ throw error;+ }+ }+ return { ok: true, added: true };+ }++ async function removeToolFavorite({+ userId,+ itemType,+ itemId,+ }: t.ToolFavoriteParams): Promise<t.RemoveToolFavoriteResult> {+ const ToolFavorite = mongoose.models.ToolFavorite;+ const result = await ToolFavorite.deleteOne({ user: userId, itemType, itemId });+ return { ok: true, removed: result.deletedCount > 0 };+ }++ return {+ getToolFavorites,+ addToolFavorite,+ removeToolFavorite,+ };+}++export type ToolFavoriteMethods = ReturnType<typeof createToolFavoriteMethods>;diff --git a/packages/data-schemas/src/methods/index.ts b/packages/data-schemas/src/methods/index.tsindex dca2915379..c3c02492b4 100644--- a/packages/data-schemas/src/methods/index.ts+++ b/packages/data-schemas/src/methods/index.ts@@ -7,6 +7,12 @@ import { createRoleMethods, RoleConflictError } from './role';import { createKeyMethods, type KeyMethods } from './key';/* Memories */import { createMemoryMethods, type MemoryMethods } from './memory';+/* Tool Favorites */+import {+ createToolFavoriteMethods,+ MAX_TOOL_FAVORITES,+ type ToolFavoriteMethods,+} from './favorite';/* Agent Categories */import { createAgentCategoryMethods, type AgentCategoryMethods } from './agentCategory';/* Agent API Keys */@@ -110,6 +116,7 @@ export {inferSkillFileCategory,};export { AUDIT_SCHEMA_VERSION, MAX_AUDIT_EXPORT_ROWS, MAX_AUDIT_LOG_LIMIT, MAX_AUDIT_VERIFY_ROWS };+export { MAX_TOOL_FAVORITES };export type AllMethods = UserMethods &SessionMethods &@@ -118,6 +125,7 @@ export type AllMethods = UserMethods &KeyMethods &FileMethods &MemoryMethods &+ ToolFavoriteMethods &AgentCategoryMethods &AgentApiKeyMethods &MCPServerMethods &@@ -246,6 +254,7 @@ export function createMethods(...createKeyMethods(mongoose),...createFileMethods(mongoose),...createMemoryMethods(mongoose),+ ...createToolFavoriteMethods(mongoose),...createAgentCategoryMethods(mongoose),...createAgentApiKeyMethods(mongoose),...createMCPServerMethods(mongoose),@@ -291,6 +300,7 @@ export type {FileMethods,FileOwnerScope,MemoryMethods,+ ToolFavoriteMethods,AgentCategoryMethods,AgentApiKeyMethods,MCPServerMethods,diff --git a/packages/data-schemas/src/models/favorite.ts b/packages/data-schemas/src/models/favorite.tsnew file mode 100644index 0000000000..0b3b4369f4--- /dev/null+++ b/packages/data-schemas/src/models/favorite.ts@@ -0,0 +1,12 @@+import { Model } from 'mongoose';+import type { IToolFavorite } from '~/types/favorite';+import { applyTenantIsolation } from '~/models/plugins/tenantIsolation';+import toolFavoriteSchema from '~/schema/favorite';++export function createToolFavoriteModel(mongoose: typeof import('mongoose')): Model<IToolFavorite> {+ applyTenantIsolation(toolFavoriteSchema);+ return (+ mongoose.models.ToolFavorite ||+ mongoose.model<IToolFavorite>('ToolFavorite', toolFavoriteSchema)+ );+}diff --git a/packages/data-schemas/src/models/index.ts b/packages/data-schemas/src/models/index.tsindex 6493013f2c..440106f2e0 100644--- a/packages/data-schemas/src/models/index.ts+++ b/packages/data-schemas/src/models/index.ts@@ -10,6 +10,7 @@ import { createSystemGrantModel } from './systemGrant';import { createPluginAuthModel } from './pluginAuth';import { createSharedLinkModel } from './sharedLink';import { createAccessRoleModel } from './accessRole';+import { createToolFavoriteModel } from './favorite';import { createMCPServerModel } from './mcpServer';import { createAssistantModel } from './assistant';import { createSkillFileModel } from './skillFile';@@ -69,6 +70,7 @@ export function createModels(mongoose: typeof import('mongoose')): {SharedLink: ReturnType<typeof createSharedLinkModel>;ToolCall: ReturnType<typeof createToolCallModel>;MemoryEntry: ReturnType<typeof createMemoryModel>;+ ToolFavorite: ReturnType<typeof createToolFavoriteModel>;AccessRole: ReturnType<typeof createAccessRoleModel>;AclEntry: ReturnType<typeof createAclEntryModel>;SystemGrant: ReturnType<typeof createSystemGrantModel>;@@ -107,6 +109,7 @@ export function createModels(mongoose: typeof import('mongoose')): {SharedLink: createSharedLinkModel(mongoose),ToolCall: createToolCallModel(mongoose),MemoryEntry: createMemoryModel(mongoose),+ ToolFavorite: createToolFavoriteModel(mongoose),AccessRole: createAccessRoleModel(mongoose),AclEntry: createAclEntryModel(mongoose),SystemGrant: createSystemGrantModel(mongoose),diff --git a/packages/data-schemas/src/schema/favorite.ts b/packages/data-schemas/src/schema/favorite.tsnew file mode 100644index 0000000000..7efafec438--- /dev/null+++ b/packages/data-schemas/src/schema/favorite.ts@@ -0,0 +1,40 @@+import { Schema } from 'mongoose';+import type { IToolFavorite } from '~/types/favorite';+import { FAVORITE_ITEM_TYPES } from '~/types/favorite';++const toolFavoriteSchema: Schema<IToolFavorite> = new Schema(+ {+ user: {+ type: Schema.Types.ObjectId,+ ref: 'User',+ required: true,+ index: true,+ },+ itemType: {+ type: String,+ required: true,+ enum: FAVORITE_ITEM_TYPES,+ },+ itemId: {+ type: String,+ required: true,+ maxlength: 256,+ },+ tenantId: {+ type: String,+ index: true,+ },+ },+ { timestamps: true },+);++/**+ * One doc per (user, itemType, itemId): the unique index makes favorite/unfavorite+ * idempotent and race-free under concurrent toggles. It deliberately excludes+ * `tenantId` — user ObjectIds are globally unique, so the triple can never+ * legitimately collide across tenants, and tenant-scoped reads are still served+ * by this user-prefixed index.+ */+toolFavoriteSchema.index({ user: 1, itemType: 1, itemId: 1 }, { unique: true });++export default toolFavoriteSchema;diff --git a/packages/data-schemas/src/schema/index.ts b/packages/data-schemas/src/schema/index.tsindex a71591844f..e6ac941d00 100644--- a/packages/data-schemas/src/schema/index.ts+++ b/packages/data-schemas/src/schema/index.ts@@ -27,6 +27,7 @@ export { default as toolCallSchema } from './toolCall';export { default as transactionSchema } from './transaction';export { default as userSchema } from './user';export { default as memorySchema } from './memory';+export { default as toolFavoriteSchema } from './favorite';export { default as groupSchema } from './group';export { default as systemGrantSchema } from './systemGrant';export { default as auditLogSchema } from './auditLog';diff --git a/packages/data-schemas/src/types/favorite.ts b/packages/data-schemas/src/types/favorite.tsnew file mode 100644index 0000000000..ca8a01ebda--- /dev/null+++ b/packages/data-schemas/src/types/favorite.ts@@ -0,0 +1,35 @@+import type { Types, Document } from 'mongoose';++export const FAVORITE_ITEM_TYPES = ['builtin', 'tool', 'mcp', 'skill'] as const;++export type FavoriteItemType = (typeof FAVORITE_ITEM_TYPES)[number];++export interface IToolFavorite extends Document {+ user: Types.ObjectId;+ itemType: FavoriteItemType;+ itemId: string;+ tenantId?: string;+ createdAt?: Date;+ updatedAt?: Date;+}++export interface IToolFavoriteLean {+ itemType: FavoriteItemType;+ itemId: string;+}++export interface ToolFavoriteParams {+ userId: string | Types.ObjectId;+ itemType: FavoriteItemType;+ itemId: string;+}++export interface AddToolFavoriteResult {+ ok: boolean;+ added: boolean;+}++export interface RemoveToolFavoriteResult {+ ok: boolean;+ removed: boolean;+}diff --git a/packages/data-schemas/src/types/index.ts b/packages/data-schemas/src/types/index.tsindex f185ebf625..878c093a98 100644--- a/packages/data-schemas/src/types/index.ts+++ b/packages/data-schemas/src/types/index.ts@@ -23,6 +23,7 @@ export * from './share';export * from './pluginAuth';/* Memories */export * from './memory';+export * from './favorite';/* Prompts */export * from './prompts';/* Skills */