LibreChat/api/server/services/Files/Citations/index.js

163 lines
5.4 KiB
JavaScript
Raw Normal View History

const { nanoid } = require('nanoid');
const { checkAccess } = require('@librechat/api');
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
const { logger } = require('@librechat/data-schemas');
const {
Tools,
Permissions,
FileSources,
EModelEndpoint,
PermissionTypes,
} = require('librechat-data-provider');
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830) * chore: move database model methods to /packages/data-schemas * chore: add TypeScript ESLint rule to warn on unused variables * refactor: model imports to streamline access - Consolidated model imports across various files to improve code organization and reduce redundancy. - Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path. - Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact. - Enhanced test files to align with the new import paths, maintaining test coverage and integrity. * chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas * test: update agent model mocks in unit tests - Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality. - Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication. - Ensured consistency in agent mock implementations across test files. * fix: update types in data-schemas * refactor: enhance type definitions in transaction and spending methods - Updated type definitions in `checkBalance.ts` to use specific request and response types. - Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety. - Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods. - Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness. * refactor: streamline model imports and enhance code organization - Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy. - Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact. - Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods. * feat: implement loadAddedAgent and refactor agent loading logic - Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution. - Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`. - Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`. - Enhanced type definitions and improved error handling in the agent loading process. - Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage. * refactor: enhance balance handling with new update interface - Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase. - Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety. - Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities. - Enhanced overall code clarity and maintainability by refining type definitions related to balance operations. * feat: add unit tests for loadAgent functionality and enhance agent loading logic - Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks. - Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality. - Improved test coverage for agent loading, including handling of non-existent agents and user permissions. * chore: reorder memory method exports for consistency - Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
const { getRoleByName, getFiles } = require('~/models');
/**
* Process file search results from tool calls
* @param {Object} options
* @param {IUser} options.user - The user object
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
* @param {AppConfig} options.appConfig - The app configuration object
* @param {GraphRunnableConfig['configurable']} options.metadata - The metadata
* @param {{ [Tools.file_search]: { sources: Object[]; fileCitations: boolean } }} options.toolArtifact - The tool artifact containing structured data
* @param {string} options.toolCallId - The tool call ID
* @returns {Promise<Object|null>} The file search attachment or null
*/
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
async function processFileCitations({ user, appConfig, toolArtifact, toolCallId, metadata }) {
try {
if (!toolArtifact?.[Tools.file_search]?.sources) {
return null;
}
if (user) {
try {
const hasFileCitationsAccess =
toolArtifact?.[Tools.file_search]?.fileCitations ??
(await checkAccess({
user,
permissionType: PermissionTypes.FILE_CITATIONS,
permissions: [Permissions.USE],
getRoleByName,
}));
if (!hasFileCitationsAccess) {
logger.debug(
`[processFileCitations] User ${user.id} does not have FILE_CITATIONS permission`,
);
return null;
}
} catch (error) {
logger.error(
`[processFileCitations] Permission check failed for FILE_CITATIONS: ${error.message}`,
);
🧩 feat: Redesign Tool Call UI with Contextual Icons, Smart Grouping, and Rich Output Rendering (#12163) * feat: redesign tool call UI with type-specific icons, smart grouping, and rich output rendering Replace the generic spinner/checkmark tool call UI with a modern, Cursor-inspired design: - Add per-tool-type icons (Plug for MCP, Terminal for code, Globe for web search, etc.) - Group 2+ consecutive tool calls into collapsible "Used N tools" sections - Stack unique tool icons in grouped headers with overlapping circle design - Replace raw JSON output with intelligent renderers (table, error, text) - Restructure ToolCallInfo: output first, parameters collapsible at bottom - Add shared useExpandCollapse hook for consistent animations - Add CodeWindowHeader for ExecuteCode windowed view - Remove FinishedIcon (purple checkmark) entirely * feat: display custom MCP server icons in tool calls Add useMCPIconMap hook to resolve MCP server names to their configured icon paths. ToolIcon and StackedToolIcons now accept custom icon URLs, showing actual server logos (e.g., Home Assistant, GitHub) instead of the generic Plug icon for MCP tool calls. * refactor: unify container styling across code blocks, mermaid, and tool output Replace hardcoded gray colors with theme tokens throughout: - CodeBlock: bg-gray-900/700 -> bg-surface-secondary/tertiary + border-border-light - Mermaid dialog: bg-gray-700 -> bg-surface-secondary, text-gray-200 -> text-text-secondary - Mermaid containers: rounded-xl -> rounded-lg, remove shadow-md for consistency - ResultSwitcher: bg-gray-700 -> bg-surface-secondary with border separator - RunCode: hover:bg-gray-700 -> hover:bg-surface-hover - ErrorOutput: add border for visual consistency - MermaidHeader/CodeWindowHeader: consistent focus outlines using border-heavy * refactor: simplify tool output to plain text, remove custom renderers Remove over-engineered tool output system (TableOutput, ErrorOutput, detectOutputType) in favor of simple text extraction. Tool output now extracts the text content from MCP content blocks and displays it as clean readable text — no tables, no error styling, no JSON formatting. Parameters only show key-value badges for simple objects; complex JSON is hidden instead of dumped raw. Matches Cursor-style simplicity. * fix: handle error messages and format JSON arrays in tool output - Strip verbose MCP error prefixes (Error: [MCP][server][tool] tool call failed: Error POSTing...) and show just the meaningful error message - Display errors in red text - Format uniform JSON arrays as readable lists (name — path) instead of raw JSON dumps - Format plain JSON objects as key: value lines * feat: improve JSON display in tool call output and parameters - Replace flat formatObject with recursive formatValue for proper indented display of nested JSON structures - Add ComplexInput component for tool parameters with nested objects, arrays, or long strings (previously hidden) - Broaden hasParams check to show parameters for all object types - Add font-mono to output renderer for better alignment * feat: add localization keys for tool errors, web search, and code UI * refactor: move Mermaid components into dedicated directory module * refactor: extract CodeBar, FloatingCodeBar, and copy utilities from CodeBlock * feat: replace manual SVG icons with @icons-pack/react-simple-icons Supports 50+ programming languages with tree-shaken brand icons instead of hand-crafted SVGs for 19 languages. * refactor: simplify code execution UI with persistent code toggle * refactor: use useExpandCollapse hook in Thinking and Reasoning * feat: improve tool call error states, subtitles, and group summaries * feat: redesign web search with inline source display * feat: improve agent handoff with keyboard accessibility * feat: reorganize exports order in hooks and utils * refactor: unify CopyCodeButton with animated icon transitions and iconOnly support * feat: add run code state machine with animated success/error feedback * refactor: improve ResultSwitcher with lucide icons and accessibility * refactor: update CopyButton component * refactor: replace CopyCodeButton with CopyButton component across multiple files * test: add ImageGen test stubs * test: add RetrievalCall test stubs * feat: merge ImageGen with ToolIcon and localized progress text * feat: modernize RetrievalCall with ToolIcon and collapsible output * test: add getToolIconType action delimiter tests * test: add ImageGen collapsible output tests * feat: add action ToolIcon type with Zap icon * fix: replace AgentHandoff div with semantic button * feat: add aria-live regions to tool components * feat: redesign execute_code tool UI with syntax highlighting and language icons - Remove filename labels (script.py, main.rs) and line counter from CodeWindowHeader - Replace generic FileCode icon with language-specific LangIcon - Add syntax highlighting via highlight.js to code blocks - Add SquareTerminal icon to ExecuteCode progress text - Use shared CopyButton component in CodeWindowHeader - Remove active:scale-95 press animation from CopyButton and RunCode * feat: dynamic tool status text sizing based on markdown font-size variable - Add tool-status-text CSS class using calc(0.9 * --markdown-font-size) - Update progress-text-wrapper to use dynamic sizing instead of base size - Apply tool-status-text to WebSearch, ToolCallGroup, AgentHandoff, ImageGen - Replace hardcoded text-sm/text-xs with dynamic class across all tools - Animate chevron rotation in ProgressText and ToolCallGroup - Update subtitle text color from tertiary to secondary * fix: consistent spacing and text styles across all tool components - Standardize tool status row spacing to my-1/my-1.5 across all components - Update ToolCallInfo text from tertiary to secondary, add vertical padding - Animate ToolCallInfo parameters chevron rotation - Update OutputRenderer link colors from tertiary to secondary * feat: unify tool call grouping for all tool types All consecutive tool calls (MCP, execute_code, web_search, image_gen, file_search, code_interpreter) are now grouped under a single collapsible "Used N tools" header instead of only grouping generic tool calls. - Remove SPECIAL_TOOL_NAMES blacklist from groupToolCalls - Replace getToolCallData with getToolMeta to handle all tool types - Use renderPart callback in ToolCallGroup for proper component routing - Add file_search and code_interpreter mappings to getToolIconType * feat: friendly tool group labels, more icons, and output copy button - Show friendly names in group summary (Code, Web Search, Image Generation) instead of raw tool names - Display MCP server names instead of individual function names - Deduplicate labels and show up to 3 with +N overflow - Increase stacked icons from 3 to 4 - Add icon-only copy button to tool output (OutputRenderer) * fix: execute_code spacing and syntax-highlighted code visibility Match ToolCall spacing by using my-1.5 on status line and moving my-2 inside overflow-hidden. Replace broken hljs.highlight() with lowlight (same engine used by rehype-highlight for markdown code blocks) to render syntax-highlighted code as React elements. Handle object args in useParseArgs to support both string and Record arg formats. * feat: replace showCode with auto-expand tools setting Replace the execute_code-only "Always show code when using code interpreter" global toggle with a new "Auto-expand tool details" setting that controls all tool types. Each tool instance now uses independent local state initialized from the setting, so expanding one tool no longer affects others. Applies to ToolCall, ExecuteCode, ToolCallGroup, and CodeAnalyze components. * fix: apply auto-expand tools setting to WebSearch and RetrievalCall * fix: only auto-expand tools when content is available Defer auto-expansion until tool output or content arrives, preventing empty bordered containers from showing while tools are still running. Uses useEffect to expand when output becomes available during streaming. * feat: redesign file_search tool output, citations, and file preview - Redesign RetrievalCall with per-file cards using OutputRenderer (truncated content with show more/less, copy button) matching MCP tool pattern - Route file_search tool calls from Agents API to RetrievalCall instead of generic ToolCall - Add FilePreviewDialog for viewing files (PDF iframe, text content) with download option, opened from clickable filenames - Redesign file citations: FileText icon in badge, relevance and page numbers in hovercard, click opens file preview instead of downloading - Add file preview to message file attachments (Files.tsx) - Fix hovercard animation to slide top-to-bottom and dismiss instantly on file click to prevent glitching over dialog - Add localization keys for relevance, extracted content, preview - Add top margin to ToolCallGroup * chore: remove leftover .planning files * fix: polish FilePreviewDialog, CodeBlock, LangIcon, and Sources * fix: prevent keyboard focus on collapsed tool content Add inert attribute to all expand/collapse wrapper divs so collapsed content is removed from tab order and hidden from assistive technology. Skip disabled ProgressText buttons from tab order with tabIndex={-1}. * feat: integrate file metadata into file_search UI Pass fileType (MIME) and fileBytes from backend file records through to the frontend. Add file-type-specific icons, file size display, pages sorted by relevance, multi-snippet content per file, smart preview detection by MIME type, and copy button in file preview dialog. * fix: review fixes — inverted type check, wrong dimension, missing import, fail-open perms, timer leaks, dead code cleanup * fix: update CodeBlock styling for improved visual consistency * fix(chat): open composite file citations in preview * fix(chat): restore file previews for parsed search results * chore(git): ignore bg-shell artifacts * fix(chat): restore readable code content in light theme * style(chat): align code and output surfaces by theme * chore(i18n): remove 6 unused translation keys * fix(deps): replace private registry URL with public npm registry in lockfile * fix: CI lint, build, and test failures - Add missing scaleImage utility (fixes Vite build error) - Export scaleImage from utils/index.ts - Remove unused imports from Part.tsx (FunctionToolCall, CodeToolCall, Agents) - Fix prettier formatting in Part.tsx (multi-line → single-line imports, conditions) - Remove excess blank lines in Part.tsx - Remove unused CodeEditorRef import from Artifacts.tsx - Add useProgress mock to OpenAIImageGen.test.tsx - Add scaleImage mock to OpenAIImageGen.test.tsx - Update OpenAIImageGen tests to match redesigned component structure - Remove dead collapsible output panel tests from ImageGen.test.tsx - Add @icons-pack/react-simple-icons to Jest transformIgnorePatterns (ESM fix) * refactor: reorganize imports order across multiple components for consistency * fix: add scaleImage tests, delete dead ImageGen wrapper, wire up onUIAction in ToolCallInfo - Add 7 unit tests for scaleImage utility covering null ref, scaling, no-upscale, height clamping, landscape, and panoramic images - Delete unused Content/ImageGen.tsx re-export wrapper (ImageGen is imported from Parts/OpenAIImageGen via the Parts barrel) - Wire up onUIAction in ToolCallInfo to use handleUIAction + ask from useMessagesOperations, matching UIResourceCarousel's behavior (was previously a silent no-op) * refactor: optimize imports and enhance lazy loading for language icons * fix: address review findings for tool call UI redesign - Fix unstable array-index keys in ToolCallGroup (streaming state corruption) - Add plain-text fallback in InputRenderer for non-JSON tool args - Localize FRIENDLY_NAMES via translation keys instead of hardcoded English - Guard autoCollapse against user-initiated manual expansion - Fix CODE_INTERPRETER hasOutput to check actual outputs instead of hardcoding true - Add logger.warn for Citations fail-closed behavior on permission errors - Add Terminal icon to CodeAnalyze ProgressText for visual consistency - Fix getMCPServerName to use indexOf instead of fragile split - Use useLayoutEffect for inert attribute in useExpandCollapse (a11y) - Memoize style object in useExpandCollapse to avoid defeating React.memo - Memoize groupSequentialToolCalls in ContentParts to avoid recomputation - Use source.link as stable key instead of array index in WebSearch - Hoist rehypePlugins outside CodeMarkdown to prevent per-render recreation * fix: revert useMemo after conditional returns in ContentParts The useMemo placed after early returns violated React Rules of Hooks — hook call count would change when transitioning between edit/view mode. Reverted to the original plain forEach which is correct and equally performant since content changes on every streaming token anyway. * chore: remove unused com_ui_variables_info translation key * fix: update tests and jest config for ESM compatibility after rebase - Add ESM-only packages to transformIgnorePatterns (@dicebear, unified ecosystem, react-dnd, lowlight, etc.) to fix Jest parse failures introduced by dev rebase - Update ToolCall.test.tsx to match new component API (CSS expand/collapse instead of conditional rendering, simplified props) - Update ToolCallInfo.test.tsx to mock OutputRenderer (avoids ESM chain), align with current component interface (input/output/attachments) * refactor: replace @icons-pack/react-simple-icons with inline SVGs Inline the 51 Simple Icons SVG paths used by LangIcon directly into langIconPaths.ts, eliminating the runtime dependency on @icons-pack/react-simple-icons (which requires Node >= 24). - LangIcon now renders a plain <svg> with the path data instead of lazy-loading React components from the package - Removes Suspense/React.lazy overhead for code block language icons - SVG paths sourced from Simple Icons (CC0 1.0 license) - Package kept in package.json for now (will be removed separately) * fix: replace Plug icon with Wrench for MCP tools, remove unused i18n keys - MCP tools without a custom iconPath now show Wrench instead of Plug, matching the generic tool fallback and avoiding the "plugin" metaphor - Remove unused translation keys: com_assistants_action_attempt, com_assistants_attempt_info, com_assistants_domain_info, com_ui_ui_resources * fix: address second review findings - Combine 3x getToolMeta loop into single toolMetadata pass (ToolCallGroup) - Extract sortPagesByRelevance to shared util (was duplicated in FilePreviewDialog and RetrievalCall) - Deduplicate AGENT_STYLE_TOOLS Set (export from OpenAIImageGen/index.ts) - Localize "source/sources" in WebSearch aria-label - Add autoExpand useEffect to CodeAnalyze for live setting changes - Log download errors in FilePreviewDialog instead of silently swallowing - Replace @ts-ignore with @ts-expect-error + explanation in Code.tsx - Remove dead currentContent alias in CodeMarkdown * chore: remove @icons-pack/react-simple-icons dependency from package.json and package-lock.json - Deleted the @icons-pack/react-simple-icons entry from both package.json and package-lock.json, following the previous refactor to use inline SVGs for icons. * fix: address triage audit findings - Remove unused gIdx variable (ESLint error) - Fix singular/plural in web search sources aria-label - Separate inline type import in ToolCallGroup per AGENTS.md * fix: remove invalid placeholderDimensions prop from Image component * chore: import order * chore: import order * fix: resolve TypeScript errors in PR-touched files - Remove non-existent placeholderDimensions prop from Image in Files.tsx - Fix localize count param type (number, not string) in WebSearch.tsx - Pass full resource object instead of partial in UIResourceCarousel.tsx - Add 'as const' to toggleSwitchConfigs localizationKey in General.tsx - Fix SearchResultData type in Citation.test.tsx - Fix TAttachment and UIResource test fixture types across test files * docs: document formatBytes difference in FilePreviewDialog The local formatBytes returns a human-readable string with units ("1.5 MB"), while ~/utils/formatBytes returns a raw number. They serve different purposes, so the local copy is retained with a JSDoc comment explaining the distinction. * fix: address remaining review items - Replace cancelled IIFE with documented ternary in OpenAIImageGen, explaining the agent vs legacy path distinction - Add .catch() fallback to loadLowlight() in useLazyHighlight — falls back to plain text if the chunk fails to load - Fix import ordering in ToolCallGroup.tsx (type imports grouped before local value imports per AGENTS.md) * fix: blob URL leak and useGetFiles over-fetch - FilePreviewDialog: add cancelledRef guard to loadPreview so blob URLs are never created after the dialog closes (prevents orphaned object URLs on unmount during async PDF fetch) - RetrievalCall: filter useGetFiles by fileIds from fileSources instead of fetching the entire user file corpus for display-only name matching * chore: fix com_nav_auto_expand_tools alphabetical order in translation.json * fix: render non-object JSON params instead of returning null in InputRenderer * refactor: render JSON tool output as syntax-highlighted code block Replace the custom YAML-ish formatValue/formatObjectArray rendering with JSON.stringify + hljs language-json styling. Structured API responses (like GitHub search results) now display as proper syntax-highlighted JSON with indentation instead of a flat key-value text dump. - Remove formatValue, formatObjectArray, isUniformObjectArray helpers - Add isJson flag to extractText return type - JSON output rendered in <code class="hljs language-json"> block - Text content blocks (type: "text") still extracted and rendered as plain text - Error output unchanged * fix: extract cancelled IIFE to named function in OpenAIImageGen Replace nested ternary with a named computeCancelled() function that documents the agent vs legacy path branching. Resolves eslint no-nested-ternary warning. --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2026-03-25 12:31:39 -04:00
logger.warn(
'[processFileCitations] Returning null citations due to permission check error — citations will not be shown for this message',
);
return null;
}
}
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
const maxCitations = appConfig.endpoints?.[EModelEndpoint.agents]?.maxCitations ?? 30;
const maxCitationsPerFile =
appConfig.endpoints?.[EModelEndpoint.agents]?.maxCitationsPerFile ?? 5;
const minRelevanceScore =
appConfig.endpoints?.[EModelEndpoint.agents]?.minRelevanceScore ?? 0.45;
const sources = toolArtifact[Tools.file_search].sources || [];
const filteredSources = sources.filter((source) => source.relevance >= minRelevanceScore);
if (filteredSources.length === 0) {
logger.debug(
`[processFileCitations] No sources above relevance threshold of ${minRelevanceScore}`,
);
return null;
}
const selectedSources = applyCitationLimits(filteredSources, maxCitations, maxCitationsPerFile);
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
const enhancedSources = await enhanceSourcesWithMetadata(selectedSources, appConfig);
if (enhancedSources.length > 0) {
const fileSearchAttachment = {
type: Tools.file_search,
[Tools.file_search]: { sources: enhancedSources },
toolCallId: toolCallId,
messageId: metadata.run_id,
conversationId: metadata.thread_id,
name: `${Tools.file_search}_file_search_results_${nanoid()}`,
};
return fileSearchAttachment;
}
return null;
} catch (error) {
logger.error('[processFileCitations] Error processing file citations:', error);
return null;
}
}
/**
* Apply citation limits to sources
* @param {Array} sources - All sources
* @param {number} maxCitations - Maximum total citations
* @param {number} maxCitationsPerFile - Maximum citations per file
* @returns {Array} Selected sources
*/
function applyCitationLimits(sources, maxCitations, maxCitationsPerFile) {
const byFile = {};
sources.forEach((source) => {
if (!byFile[source.fileId]) {
byFile[source.fileId] = [];
}
byFile[source.fileId].push(source);
});
const representatives = [];
for (const fileId in byFile) {
const fileSources = byFile[fileId].sort((a, b) => b.relevance - a.relevance);
const selectedFromFile = fileSources.slice(0, maxCitationsPerFile);
representatives.push(...selectedFromFile);
}
return representatives.sort((a, b) => b.relevance - a.relevance).slice(0, maxCitations);
}
/**
* Enhance sources with file metadata from database
* @param {Array} sources - Selected sources
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
* @param {AppConfig} appConfig - Custom configuration
* @returns {Promise<Array>} Enhanced sources
*/
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
async function enhanceSourcesWithMetadata(sources, appConfig) {
const fileIds = [...new Set(sources.map((source) => source.fileId))];
let fileMetadataMap = {};
try {
📦 refactor: Consolidate DB models, encapsulating Mongoose usage in `data-schemas` (#11830) * chore: move database model methods to /packages/data-schemas * chore: add TypeScript ESLint rule to warn on unused variables * refactor: model imports to streamline access - Consolidated model imports across various files to improve code organization and reduce redundancy. - Updated imports for models such as Assistant, Message, Conversation, and others to a unified import path. - Adjusted middleware and service files to reflect the new import structure, ensuring functionality remains intact. - Enhanced test files to align with the new import paths, maintaining test coverage and integrity. * chore: migrate database models to packages/data-schemas and refactor all direct Mongoose Model usage outside of data-schemas * test: update agent model mocks in unit tests - Added `getAgent` mock to `client.test.js` to enhance test coverage for agent-related functionality. - Removed redundant `getAgent` and `getAgents` mocks from `openai.spec.js` and `responses.unit.spec.js` to streamline test setup and reduce duplication. - Ensured consistency in agent mock implementations across test files. * fix: update types in data-schemas * refactor: enhance type definitions in transaction and spending methods - Updated type definitions in `checkBalance.ts` to use specific request and response types. - Refined `spendTokens.ts` to utilize a new `SpendTxData` interface for better clarity and type safety. - Improved transaction handling in `transaction.ts` by introducing `TransactionResult` and `TxData` interfaces, ensuring consistent data structures across methods. - Adjusted unit tests in `transaction.spec.ts` to accommodate new type definitions and enhance robustness. * refactor: streamline model imports and enhance code organization - Consolidated model imports across various controllers and services to a unified import path, improving code clarity and reducing redundancy. - Updated multiple files to reflect the new import structure, ensuring all functionalities remain intact. - Enhanced overall code organization by removing duplicate import statements and optimizing the usage of model methods. * feat: implement loadAddedAgent and refactor agent loading logic - Introduced `loadAddedAgent` function to handle loading agents from added conversations, supporting multi-convo parallel execution. - Created a new `load.ts` file to encapsulate agent loading functionalities, including `loadEphemeralAgent` and `loadAgent`. - Updated the `index.ts` file to export the new `load` module instead of the deprecated `loadAgent`. - Enhanced type definitions and improved error handling in the agent loading process. - Adjusted unit tests to reflect changes in the agent loading structure and ensure comprehensive coverage. * refactor: enhance balance handling with new update interface - Introduced `IBalanceUpdate` interface to streamline balance update operations across the codebase. - Updated `upsertBalanceFields` method signatures in `balance.ts`, `transaction.ts`, and related tests to utilize the new interface for improved type safety. - Adjusted type imports in `balance.spec.ts` to include `IBalanceUpdate`, ensuring consistency in balance management functionalities. - Enhanced overall code clarity and maintainability by refining type definitions related to balance operations. * feat: add unit tests for loadAgent functionality and enhance agent loading logic - Introduced comprehensive unit tests for the `loadAgent` function, covering various scenarios including null and empty agent IDs, loading of ephemeral agents, and permission checks. - Enhanced the `initializeClient` function by moving `getConvoFiles` to the correct position in the database method exports, ensuring proper functionality. - Improved test coverage for agent loading, including handling of non-existent agents and user permissions. * chore: reorder memory method exports for consistency - Moved `deleteAllUserMemories` to the correct position in the exported memory methods, ensuring a consistent and logical order of method exports in `memory.ts`.
2026-02-17 18:23:44 -05:00
const files = await getFiles({ file_id: { $in: fileIds } });
fileMetadataMap = files.reduce((map, file) => {
map[file.file_id] = file;
return map;
}, {});
} catch (error) {
logger.error('[enhanceSourcesWithMetadata] Error looking up file metadata:', error);
}
return sources.map((source) => {
const fileRecord = fileMetadataMap[source.fileId] || {};
🛜 refactor: Streamline App Config Usage (#9234) * WIP: app.locals refactoring WIP: appConfig fix: update memory configuration retrieval to use getAppConfig based on user role fix: update comment for AppConfig interface to clarify purpose 🏷️ refactor: Update tests to use getAppConfig for endpoint configurations ci: Update AppService tests to initialize app config instead of app.locals ci: Integrate getAppConfig into remaining tests refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests refactor: Rename initializeAppConfig to setAppConfig and update related tests ci: Mock getAppConfig in various tests to provide default configurations refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests chore: rename `Config/getAppConfig` -> `Config/app` fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters chore: correct parameter documentation for imageOutputType in ToolService.js refactor: remove `getCustomConfig` dependency in config route refactor: update domain validation to use appConfig for allowed domains refactor: use appConfig registration property chore: remove app parameter from AppService invocation refactor: update AppConfig interface to correct registration and turnstile configurations refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration ci: update related tests refactor: update getAppConfig call in getCustomConfigSpeech to include user role fix: update appConfig usage to access allowedDomains from actions instead of registration refactor: enhance AppConfig to include fileStrategies and update related file strategy logic refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions chore: remove deprecated unused RunManager refactor: get balance config primarily from appConfig refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic refactor: remove getCustomConfig usage and use app config in file citations refactor: consolidate endpoint loading logic into loadEndpoints function refactor: update appConfig access to use endpoints structure across various services refactor: implement custom endpoints configuration and streamline endpoint loading logic refactor: update getAppConfig call to include user role parameter refactor: streamline endpoint configuration and enhance appConfig usage across services refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file refactor: add type annotation for loadedEndpoints in loadEndpoints function refactor: move /services/Files/images/parse to TS API chore: add missing FILE_CITATIONS permission to IRole interface refactor: restructure toolkits to TS API refactor: separate manifest logic into its own module refactor: consolidate tool loading logic into a new tools module for startup logic refactor: move interface config logic to TS API refactor: migrate checkEmailConfig to TypeScript and update imports refactor: add FunctionTool interface and availableTools to AppConfig refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig` WIP: fix tests * fix: rebase conflicts * refactor: remove app.locals references * refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware * refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients * test: add balance configuration to titleConvo method in AgentClient tests * chore: remove unused `openai-chat-tokens` package * chore: remove unused imports in initializeMCPs.js * refactor: update balance configuration to use getAppConfig instead of getBalanceConfig * refactor: integrate configMiddleware for centralized configuration handling * refactor: optimize email domain validation by removing unnecessary async calls * refactor: simplify multer storage configuration by removing async calls * refactor: reorder imports for better readability in user.js * refactor: replace getAppConfig calls with req.config for improved performance * chore: replace getAppConfig calls with req.config in tests for centralized configuration handling * chore: remove unused override config * refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config * chore: remove customConfig parameter from TTSService constructor * refactor: pass appConfig from request to processFileCitations for improved configuration handling * refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config` * test: add mockAppConfig to processFileCitations tests for improved configuration handling * fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor * fix: type safety in useExportConversation * refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached * chore: change `MongoUser` typedef to `IUser` * fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest * fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00
const configuredStorageType = fileRecord.source || appConfig?.fileStrategy || FileSources.local;
return {
...source,
fileName: fileRecord.filename || source.fileName || 'Unknown File',
metadata: {
...source.metadata,
storageType: configuredStorageType,
🧩 feat: Redesign Tool Call UI with Contextual Icons, Smart Grouping, and Rich Output Rendering (#12163) * feat: redesign tool call UI with type-specific icons, smart grouping, and rich output rendering Replace the generic spinner/checkmark tool call UI with a modern, Cursor-inspired design: - Add per-tool-type icons (Plug for MCP, Terminal for code, Globe for web search, etc.) - Group 2+ consecutive tool calls into collapsible "Used N tools" sections - Stack unique tool icons in grouped headers with overlapping circle design - Replace raw JSON output with intelligent renderers (table, error, text) - Restructure ToolCallInfo: output first, parameters collapsible at bottom - Add shared useExpandCollapse hook for consistent animations - Add CodeWindowHeader for ExecuteCode windowed view - Remove FinishedIcon (purple checkmark) entirely * feat: display custom MCP server icons in tool calls Add useMCPIconMap hook to resolve MCP server names to their configured icon paths. ToolIcon and StackedToolIcons now accept custom icon URLs, showing actual server logos (e.g., Home Assistant, GitHub) instead of the generic Plug icon for MCP tool calls. * refactor: unify container styling across code blocks, mermaid, and tool output Replace hardcoded gray colors with theme tokens throughout: - CodeBlock: bg-gray-900/700 -> bg-surface-secondary/tertiary + border-border-light - Mermaid dialog: bg-gray-700 -> bg-surface-secondary, text-gray-200 -> text-text-secondary - Mermaid containers: rounded-xl -> rounded-lg, remove shadow-md for consistency - ResultSwitcher: bg-gray-700 -> bg-surface-secondary with border separator - RunCode: hover:bg-gray-700 -> hover:bg-surface-hover - ErrorOutput: add border for visual consistency - MermaidHeader/CodeWindowHeader: consistent focus outlines using border-heavy * refactor: simplify tool output to plain text, remove custom renderers Remove over-engineered tool output system (TableOutput, ErrorOutput, detectOutputType) in favor of simple text extraction. Tool output now extracts the text content from MCP content blocks and displays it as clean readable text — no tables, no error styling, no JSON formatting. Parameters only show key-value badges for simple objects; complex JSON is hidden instead of dumped raw. Matches Cursor-style simplicity. * fix: handle error messages and format JSON arrays in tool output - Strip verbose MCP error prefixes (Error: [MCP][server][tool] tool call failed: Error POSTing...) and show just the meaningful error message - Display errors in red text - Format uniform JSON arrays as readable lists (name — path) instead of raw JSON dumps - Format plain JSON objects as key: value lines * feat: improve JSON display in tool call output and parameters - Replace flat formatObject with recursive formatValue for proper indented display of nested JSON structures - Add ComplexInput component for tool parameters with nested objects, arrays, or long strings (previously hidden) - Broaden hasParams check to show parameters for all object types - Add font-mono to output renderer for better alignment * feat: add localization keys for tool errors, web search, and code UI * refactor: move Mermaid components into dedicated directory module * refactor: extract CodeBar, FloatingCodeBar, and copy utilities from CodeBlock * feat: replace manual SVG icons with @icons-pack/react-simple-icons Supports 50+ programming languages with tree-shaken brand icons instead of hand-crafted SVGs for 19 languages. * refactor: simplify code execution UI with persistent code toggle * refactor: use useExpandCollapse hook in Thinking and Reasoning * feat: improve tool call error states, subtitles, and group summaries * feat: redesign web search with inline source display * feat: improve agent handoff with keyboard accessibility * feat: reorganize exports order in hooks and utils * refactor: unify CopyCodeButton with animated icon transitions and iconOnly support * feat: add run code state machine with animated success/error feedback * refactor: improve ResultSwitcher with lucide icons and accessibility * refactor: update CopyButton component * refactor: replace CopyCodeButton with CopyButton component across multiple files * test: add ImageGen test stubs * test: add RetrievalCall test stubs * feat: merge ImageGen with ToolIcon and localized progress text * feat: modernize RetrievalCall with ToolIcon and collapsible output * test: add getToolIconType action delimiter tests * test: add ImageGen collapsible output tests * feat: add action ToolIcon type with Zap icon * fix: replace AgentHandoff div with semantic button * feat: add aria-live regions to tool components * feat: redesign execute_code tool UI with syntax highlighting and language icons - Remove filename labels (script.py, main.rs) and line counter from CodeWindowHeader - Replace generic FileCode icon with language-specific LangIcon - Add syntax highlighting via highlight.js to code blocks - Add SquareTerminal icon to ExecuteCode progress text - Use shared CopyButton component in CodeWindowHeader - Remove active:scale-95 press animation from CopyButton and RunCode * feat: dynamic tool status text sizing based on markdown font-size variable - Add tool-status-text CSS class using calc(0.9 * --markdown-font-size) - Update progress-text-wrapper to use dynamic sizing instead of base size - Apply tool-status-text to WebSearch, ToolCallGroup, AgentHandoff, ImageGen - Replace hardcoded text-sm/text-xs with dynamic class across all tools - Animate chevron rotation in ProgressText and ToolCallGroup - Update subtitle text color from tertiary to secondary * fix: consistent spacing and text styles across all tool components - Standardize tool status row spacing to my-1/my-1.5 across all components - Update ToolCallInfo text from tertiary to secondary, add vertical padding - Animate ToolCallInfo parameters chevron rotation - Update OutputRenderer link colors from tertiary to secondary * feat: unify tool call grouping for all tool types All consecutive tool calls (MCP, execute_code, web_search, image_gen, file_search, code_interpreter) are now grouped under a single collapsible "Used N tools" header instead of only grouping generic tool calls. - Remove SPECIAL_TOOL_NAMES blacklist from groupToolCalls - Replace getToolCallData with getToolMeta to handle all tool types - Use renderPart callback in ToolCallGroup for proper component routing - Add file_search and code_interpreter mappings to getToolIconType * feat: friendly tool group labels, more icons, and output copy button - Show friendly names in group summary (Code, Web Search, Image Generation) instead of raw tool names - Display MCP server names instead of individual function names - Deduplicate labels and show up to 3 with +N overflow - Increase stacked icons from 3 to 4 - Add icon-only copy button to tool output (OutputRenderer) * fix: execute_code spacing and syntax-highlighted code visibility Match ToolCall spacing by using my-1.5 on status line and moving my-2 inside overflow-hidden. Replace broken hljs.highlight() with lowlight (same engine used by rehype-highlight for markdown code blocks) to render syntax-highlighted code as React elements. Handle object args in useParseArgs to support both string and Record arg formats. * feat: replace showCode with auto-expand tools setting Replace the execute_code-only "Always show code when using code interpreter" global toggle with a new "Auto-expand tool details" setting that controls all tool types. Each tool instance now uses independent local state initialized from the setting, so expanding one tool no longer affects others. Applies to ToolCall, ExecuteCode, ToolCallGroup, and CodeAnalyze components. * fix: apply auto-expand tools setting to WebSearch and RetrievalCall * fix: only auto-expand tools when content is available Defer auto-expansion until tool output or content arrives, preventing empty bordered containers from showing while tools are still running. Uses useEffect to expand when output becomes available during streaming. * feat: redesign file_search tool output, citations, and file preview - Redesign RetrievalCall with per-file cards using OutputRenderer (truncated content with show more/less, copy button) matching MCP tool pattern - Route file_search tool calls from Agents API to RetrievalCall instead of generic ToolCall - Add FilePreviewDialog for viewing files (PDF iframe, text content) with download option, opened from clickable filenames - Redesign file citations: FileText icon in badge, relevance and page numbers in hovercard, click opens file preview instead of downloading - Add file preview to message file attachments (Files.tsx) - Fix hovercard animation to slide top-to-bottom and dismiss instantly on file click to prevent glitching over dialog - Add localization keys for relevance, extracted content, preview - Add top margin to ToolCallGroup * chore: remove leftover .planning files * fix: polish FilePreviewDialog, CodeBlock, LangIcon, and Sources * fix: prevent keyboard focus on collapsed tool content Add inert attribute to all expand/collapse wrapper divs so collapsed content is removed from tab order and hidden from assistive technology. Skip disabled ProgressText buttons from tab order with tabIndex={-1}. * feat: integrate file metadata into file_search UI Pass fileType (MIME) and fileBytes from backend file records through to the frontend. Add file-type-specific icons, file size display, pages sorted by relevance, multi-snippet content per file, smart preview detection by MIME type, and copy button in file preview dialog. * fix: review fixes — inverted type check, wrong dimension, missing import, fail-open perms, timer leaks, dead code cleanup * fix: update CodeBlock styling for improved visual consistency * fix(chat): open composite file citations in preview * fix(chat): restore file previews for parsed search results * chore(git): ignore bg-shell artifacts * fix(chat): restore readable code content in light theme * style(chat): align code and output surfaces by theme * chore(i18n): remove 6 unused translation keys * fix(deps): replace private registry URL with public npm registry in lockfile * fix: CI lint, build, and test failures - Add missing scaleImage utility (fixes Vite build error) - Export scaleImage from utils/index.ts - Remove unused imports from Part.tsx (FunctionToolCall, CodeToolCall, Agents) - Fix prettier formatting in Part.tsx (multi-line → single-line imports, conditions) - Remove excess blank lines in Part.tsx - Remove unused CodeEditorRef import from Artifacts.tsx - Add useProgress mock to OpenAIImageGen.test.tsx - Add scaleImage mock to OpenAIImageGen.test.tsx - Update OpenAIImageGen tests to match redesigned component structure - Remove dead collapsible output panel tests from ImageGen.test.tsx - Add @icons-pack/react-simple-icons to Jest transformIgnorePatterns (ESM fix) * refactor: reorganize imports order across multiple components for consistency * fix: add scaleImage tests, delete dead ImageGen wrapper, wire up onUIAction in ToolCallInfo - Add 7 unit tests for scaleImage utility covering null ref, scaling, no-upscale, height clamping, landscape, and panoramic images - Delete unused Content/ImageGen.tsx re-export wrapper (ImageGen is imported from Parts/OpenAIImageGen via the Parts barrel) - Wire up onUIAction in ToolCallInfo to use handleUIAction + ask from useMessagesOperations, matching UIResourceCarousel's behavior (was previously a silent no-op) * refactor: optimize imports and enhance lazy loading for language icons * fix: address review findings for tool call UI redesign - Fix unstable array-index keys in ToolCallGroup (streaming state corruption) - Add plain-text fallback in InputRenderer for non-JSON tool args - Localize FRIENDLY_NAMES via translation keys instead of hardcoded English - Guard autoCollapse against user-initiated manual expansion - Fix CODE_INTERPRETER hasOutput to check actual outputs instead of hardcoding true - Add logger.warn for Citations fail-closed behavior on permission errors - Add Terminal icon to CodeAnalyze ProgressText for visual consistency - Fix getMCPServerName to use indexOf instead of fragile split - Use useLayoutEffect for inert attribute in useExpandCollapse (a11y) - Memoize style object in useExpandCollapse to avoid defeating React.memo - Memoize groupSequentialToolCalls in ContentParts to avoid recomputation - Use source.link as stable key instead of array index in WebSearch - Hoist rehypePlugins outside CodeMarkdown to prevent per-render recreation * fix: revert useMemo after conditional returns in ContentParts The useMemo placed after early returns violated React Rules of Hooks — hook call count would change when transitioning between edit/view mode. Reverted to the original plain forEach which is correct and equally performant since content changes on every streaming token anyway. * chore: remove unused com_ui_variables_info translation key * fix: update tests and jest config for ESM compatibility after rebase - Add ESM-only packages to transformIgnorePatterns (@dicebear, unified ecosystem, react-dnd, lowlight, etc.) to fix Jest parse failures introduced by dev rebase - Update ToolCall.test.tsx to match new component API (CSS expand/collapse instead of conditional rendering, simplified props) - Update ToolCallInfo.test.tsx to mock OutputRenderer (avoids ESM chain), align with current component interface (input/output/attachments) * refactor: replace @icons-pack/react-simple-icons with inline SVGs Inline the 51 Simple Icons SVG paths used by LangIcon directly into langIconPaths.ts, eliminating the runtime dependency on @icons-pack/react-simple-icons (which requires Node >= 24). - LangIcon now renders a plain <svg> with the path data instead of lazy-loading React components from the package - Removes Suspense/React.lazy overhead for code block language icons - SVG paths sourced from Simple Icons (CC0 1.0 license) - Package kept in package.json for now (will be removed separately) * fix: replace Plug icon with Wrench for MCP tools, remove unused i18n keys - MCP tools without a custom iconPath now show Wrench instead of Plug, matching the generic tool fallback and avoiding the "plugin" metaphor - Remove unused translation keys: com_assistants_action_attempt, com_assistants_attempt_info, com_assistants_domain_info, com_ui_ui_resources * fix: address second review findings - Combine 3x getToolMeta loop into single toolMetadata pass (ToolCallGroup) - Extract sortPagesByRelevance to shared util (was duplicated in FilePreviewDialog and RetrievalCall) - Deduplicate AGENT_STYLE_TOOLS Set (export from OpenAIImageGen/index.ts) - Localize "source/sources" in WebSearch aria-label - Add autoExpand useEffect to CodeAnalyze for live setting changes - Log download errors in FilePreviewDialog instead of silently swallowing - Replace @ts-ignore with @ts-expect-error + explanation in Code.tsx - Remove dead currentContent alias in CodeMarkdown * chore: remove @icons-pack/react-simple-icons dependency from package.json and package-lock.json - Deleted the @icons-pack/react-simple-icons entry from both package.json and package-lock.json, following the previous refactor to use inline SVGs for icons. * fix: address triage audit findings - Remove unused gIdx variable (ESLint error) - Fix singular/plural in web search sources aria-label - Separate inline type import in ToolCallGroup per AGENTS.md * fix: remove invalid placeholderDimensions prop from Image component * chore: import order * chore: import order * fix: resolve TypeScript errors in PR-touched files - Remove non-existent placeholderDimensions prop from Image in Files.tsx - Fix localize count param type (number, not string) in WebSearch.tsx - Pass full resource object instead of partial in UIResourceCarousel.tsx - Add 'as const' to toggleSwitchConfigs localizationKey in General.tsx - Fix SearchResultData type in Citation.test.tsx - Fix TAttachment and UIResource test fixture types across test files * docs: document formatBytes difference in FilePreviewDialog The local formatBytes returns a human-readable string with units ("1.5 MB"), while ~/utils/formatBytes returns a raw number. They serve different purposes, so the local copy is retained with a JSDoc comment explaining the distinction. * fix: address remaining review items - Replace cancelled IIFE with documented ternary in OpenAIImageGen, explaining the agent vs legacy path distinction - Add .catch() fallback to loadLowlight() in useLazyHighlight — falls back to plain text if the chunk fails to load - Fix import ordering in ToolCallGroup.tsx (type imports grouped before local value imports per AGENTS.md) * fix: blob URL leak and useGetFiles over-fetch - FilePreviewDialog: add cancelledRef guard to loadPreview so blob URLs are never created after the dialog closes (prevents orphaned object URLs on unmount during async PDF fetch) - RetrievalCall: filter useGetFiles by fileIds from fileSources instead of fetching the entire user file corpus for display-only name matching * chore: fix com_nav_auto_expand_tools alphabetical order in translation.json * fix: render non-object JSON params instead of returning null in InputRenderer * refactor: render JSON tool output as syntax-highlighted code block Replace the custom YAML-ish formatValue/formatObjectArray rendering with JSON.stringify + hljs language-json styling. Structured API responses (like GitHub search results) now display as proper syntax-highlighted JSON with indentation instead of a flat key-value text dump. - Remove formatValue, formatObjectArray, isUniformObjectArray helpers - Add isJson flag to extractText return type - JSON output rendered in <code class="hljs language-json"> block - Text content blocks (type: "text") still extracted and rendered as plain text - Error output unchanged * fix: extract cancelled IIFE to named function in OpenAIImageGen Replace nested ternary with a named computeCancelled() function that documents the agent vs legacy path branching. Resolves eslint no-nested-ternary warning. --------- Co-authored-by: Danny Avila <danny@librechat.ai>
2026-03-25 12:31:39 -04:00
fileType: fileRecord.type || undefined,
fileBytes: fileRecord.bytes || undefined,
},
};
});
}
module.exports = {
applyCitationLimits,
processFileCitations,
enhanceSourcesWithMetadata,
};