LibreChat/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx

254 lines
7.4 KiB
TypeScript
Raw Normal View History

🧩 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
import { useState, useEffect, useRef, useCallback } from 'react';
📦 feat: Move Shared Components to `@librechat/client` (#8685) * feat: init @librechat/client * feat: Add common types and interfaces for accessibility, agents, artifacts, assistants, and tools * feat: Add jotai as a peer dependency * fix build client package * feat: cleanup unused types from common/index.ts - Remove 104 unused type exports from packages/client/src/common/index.ts - Keep only 7 actually used exports (93% reduction) - Add cleanup script with enhanced import pattern detection - Support both named imports and namespace imports (* as t) - Create automatic backups and comprehensive documentation - Maintain type safety with build verification - No breaking changes to existing code Kept exports: - TShowToast, Option, OptionWithIcon, DropdownValueSetter - MentionOption, NotificationSeverity, MenuItemProps Scripts: cleanup-common-types-safe.js, README-CLEANUP.md * fix: cleanup * fix: package; refactor: tsconfig * feat: add back `recoil` * fix: move dependencies to peerDependencies in client package * feat: add @librechat/client as a dependency in package.json and package-lock.json * feat: update client package configuration and dependencies - Added new dependencies for Rollup plugins and updated existing ones in package.json and package-lock.json. - Introduced a new Rollup configuration file for building the client package. - Refactored build scripts to include a dedicated build command for the client. - Updated TypeScript configuration for improved module resolution and type declaration output. - Integrated a Toast component from the client package into the main App component. * feat: enhance Rollup configuration for client package - Updated terser plugin settings to preserve directives like 'use client'. - Added custom warning handler to ignore "use client" directive warnings during the build process. * chore: rename package/client build script command * feat: update client package dependencies and Rollup configuration - Added rollup-plugin-postcss to package.json and updated package-lock.json. - Enhanced Rollup configuration to include postcss plugin for CSS handling. - Updated index.ts to export all components from the components directory for better modularity. * feat: add client package directory to update configuration - Included the 'client' package directory in the update.js configuration to ensure it is recognized during updates. * feat: export Toast component in client package - Added export for the Toast component in index.ts to enhance modularity and accessibility of components. * feat: /client transition to @librechat/client * chore: fixed formatting issues * fix: update peer dependencies in @librechat/client to prevent bundling them * fix: correct useSprings implementation in SplitText component * fix: circular dependencies in DataTable * fix: add remaining peer dependencies and match actual versions previously used in `client/package.json` * fix: correct frontend:ci script to include client package build * chore: enhance unused package detection for @librechat/client and improve dependency extraction * fix: add missing peer dependency for @radix-ui/react-collapsible * chore: include "packages/client" in unused i18next keys detection * test: update AgentFooter tests to use document.querySelector for spinner checks test: mock window.matchMedia in setupTests.js for consistent test environment * feat: add react-hook-form dependency and update FormInput component to use its types * chore: linting * refactor: remove unused defaultSelectedValues prop from MCPSelect and MultiSelect components * chore: linting * feat: update GitHub Actions workflow to publish @librechat/client * chore: update GitHub Actions workflow to install and build data-provider and client dependencies * chore: add missing @testing-library/react dependency to client package * chore: update tsconfig.json to exclude additional test files * chore: fix build issues, resolve latest LC changes * chore: move MCP components outside of `~/components/ui` * feat: implement dynamic theme system with environment variable support and Tailwind CSS integration * chore: remove unnecessary logging of sttExternal and ttsExternal in Speech component * chore: squashed cleanup commits chore: move @tanstack/react-virtual to dependencies and remove recoil from package.json chore: move dependencies to peerDependencies in package.json feat: update package.json and rollup.config.js to include jotai and enhance bundling configuration feat: update package.json and rollup.config.js to include jotai and enhance bundling configuration refactor: reorganize exports in index.ts for improved clarity refactor: remove unused types and interfaces from common files refactor: update peer dependencies and improve component typings - Removed duplicate peer dependencies from package.json and organized them. - Updated rollup.config.js to disable TypeScript checking during the build process. - Modified AnimatedTabs component to use React.ReactNode for label and content types, and added TypeScript workarounds for compatibility. - Enhanced Label and Separator components to accept an optional className prop and improved prop spreading. - Updated Slider component to include an optional className prop and refined prop handling for better type safety. refactor: clean up client workflow and update package dependencies refactor: update package dependencies and improve PostCSS and Rollup configurations chore: bump version to 0.1.2 in package.json chore: bump client version to 0.1.2 in package-lock.json chore: bump client version to 0.1.3 and update dependencies chore: bump client version to 0.1.4 and update @react-spring dependencies chore: update package version to 0.1.5 and adjust peer dependencies - Bump version in package.json from 0.1.4 to 0.1.5. - Update peer dependency for @tanstack/react-query to allow version 5.0.0. - Add @tanstack/react-table and @tanstack/react-virtual as dependencies. - Update various dependencies to their latest compatible versions. - Simplify postcss.config.js by removing unnecessary options. - Clean up rollup.config.js by removing ignored PostCSS warnings. - Update CheckboxButton component to cast icon as React JSX element. - Adjust Combobox component's class names for better styling. - Change DropdownPopup component to use React's namespace import. - Modify InputOTP component to use 'any' type for OTPInputContext. - Ensure displayLabel and value in ModelParameters are converted to strings. - Update MultiSearch component's placeholder to ensure it's a string. - Cast selectIcon in MultiSelect as React JSX element for consistency. - Update OGDialogTemplate to cast selectText as React JSX element. - Initialize animationRef in PixelCard with undefined for clarity. - Add TypeScript ignore comments in Select and SelectDropDown components for Radix UI type conflicts. - Ensure title in SelectDropDown is a string and adjust rendering of options. - Update useLocalize hook to cast options as any for compatibility. refactor: code structure; chore: translations cleanup chore: remove unused imports and clean up code in NewChat component refactor: enhance Menu component to support custom render functions for menu items style: update itemClassName in ToolsDropdown for improved UI consistency fix: merge conflicts chore: update @radix-ui/react-accordion to version 1.2.11 * refactor: remove unnecessary TypeScript type assertions in AnimatedTabs, Label, Separator, and Slider components * feat: enhance theme system with localStorage persistence and new theme atoms * chore: bump version of @librechat/client to 0.1.7 * chore: fix ci/cd warnings/errors related to linting and unused localization keys * chore: update dependencies for class-variance-authority, clsx, and match-sorter * chore: bump @librechat/client to v0.1.8 * feat: add utility colors for theme customization and remove unused tailwindConfig * v0.1.9 --------- Co-authored-by: Marco Beretta <81851188+berry-13@users.noreply.github.com>
2025-07-27 12:19:01 -04:00
import { PixelCard } from '@librechat/client';
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';
🧩 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
import { ToolIcon, isError } from '~/components/Chat/Messages/Content/ToolOutput';
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
import Image from '~/components/Chat/Messages/Content/Image';
🧩 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
import { useProgress, useLocalize } from '~/hooks';
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
import ProgressText from './ProgressText';
🧩 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
import { AGENT_STYLE_TOOLS } from '.';
import { scaleImage } from '~/utils';
function computeCancelled(
isSubmitting: boolean | undefined,
initialProgress: number,
hasError: boolean,
): boolean {
if (isSubmitting !== undefined) {
return (!isSubmitting && initialProgress < 1) || hasError;
}
// Legacy path: in-progress (0 < progress < 1) is never cancelled
// because legacy image gen lacks a submitting signal.
if (initialProgress < 1 && initialProgress > 0) {
return false;
}
return hasError;
}
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
export default function OpenAIImageGen({
initialProgress = 0.1,
isSubmitting,
toolName,
args: _args = '',
output,
attachments,
}: {
initialProgress: number;
🧩 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
isSubmitting?: boolean;
toolName?: string;
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
args: string | Record<string, unknown>;
output?: string | null;
attachments?: TAttachment[];
}) {
🧩 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
const localize = useLocalize();
const isAgentStyle = toolName != null && AGENT_STYLE_TOOLS.has(toolName);
const [agentProgress, setAgentProgress] = useState(initialProgress);
const legacyProgress = useProgress(isAgentStyle ? 1 : initialProgress);
const progress = isAgentStyle ? agentProgress : legacyProgress;
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
const intervalRef = useRef<NodeJS.Timeout | null>(null);
🧩 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
const hasError = typeof output === 'string' && isError(output);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
🧩 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
/**
* Determines if the image generation was cancelled.
* - Agent path (isSubmitting defined): cancelled if not submitting + incomplete, or on error.
* - Legacy path (isSubmitting undefined): in-progress (0 < progress < 1) is never cancelled
* because legacy image gen lacks a submitting signal only errors cancel.
*/
const cancelled = computeCancelled(isSubmitting, initialProgress, hasError);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
🧩 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
let width: number | undefined;
let height: number | undefined;
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
let quality: 'low' | 'medium' | 'high' = 'high';
🧩 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
let parsedArgs: Record<string, unknown> = {};
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
try {
parsedArgs = typeof _args === 'string' ? JSON.parse(_args) : _args;
🧩 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
} catch {
parsedArgs = {};
}
🧩 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
try {
const argsObj = parsedArgs;
if (argsObj && typeof argsObj.size === 'string') {
const [w, h] = argsObj.size.split('x').map((v: string) => parseInt(v, 10));
if (!isNaN(w) && !isNaN(h)) {
width = w;
height = h;
}
} else if (argsObj && (typeof argsObj.size !== 'string' || !argsObj.size)) {
width = undefined;
height = undefined;
}
if (argsObj && typeof argsObj.quality === 'string') {
const q = argsObj.quality.toLowerCase();
if (q === 'low' || q === 'medium' || q === 'high') {
quality = q;
}
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
}
🧩 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
} catch {
width = undefined;
height = undefined;
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
}
const attachment = attachments?.[0];
🎞️ refactor: Image Rendering with Preview Caching and Layout Reservation (#12114) * refactor: Update Image Component to Remove Lazy Loading and Enhance Rendering - Removed the react-lazy-load-image-component dependency from the Image component, simplifying the image loading process. - Updated the Image component to use a standard <img> tag with async decoding for improved performance and user experience. - Adjusted related tests to reflect changes in image rendering behavior and ensure proper functionality without lazy loading. * refactor: Enhance Image Handling and Caching Across Components - Introduced a new previewCache utility for managing local blob preview URLs, improving image loading efficiency. - Updated the Image component and related parts (FileRow, Files, Part, ImageAttachment, LogContent) to utilize cached previews, enhancing rendering performance and user experience. - Added width and height properties to the Image component for better layout management and consistency across different usages. - Improved file handling logic in useFileHandling to cache previews during file uploads, ensuring quick access to image data. - Enhanced overall code clarity and maintainability by streamlining image rendering logic and reducing redundancy. * refactor: Enhance OpenAIImageGen Component with Image Dimensions - Added width and height properties to the OpenAIImageGen component for improved image rendering and layout management. - Updated the Image component usage within OpenAIImageGen to utilize the new dimensions, enhancing visual consistency and performance. - Improved code clarity by destructuring additional properties from the attachment object, streamlining the component's logic. * refactor: Implement Image Size Caching in DialogImage Component - Introduced an imageSizeCache to store and retrieve image sizes, enhancing performance by reducing redundant fetch requests. - Updated the getImageSize function to first check the cache before making network requests, improving efficiency in image handling. - Added decoding attribute to the image element for optimized rendering behavior. * refactor: Enhance UserAvatar Component with Avatar Caching and Error Handling - Introduced avatar caching logic to optimize avatar resolution based on user ID and avatar source, improving performance and reducing redundant image loads. - Implemented error handling for failed image loads, allowing for fallback to a default avatar when necessary. - Updated UserAvatar props to streamline the interface by removing the user object and directly accepting avatar-related properties. - Enhanced overall code clarity and maintainability by refactoring the component structure and logic. * fix: Layout Shift in Message and Placeholder Components for Consistent Height Management - Adjusted the height of the PlaceholderRow and related message components to ensure consistent rendering with a minimum height of 31px. - Updated the MessageParts and ContentRender components to utilize a minimum height for better layout stability. - Enhanced overall code clarity by standardizing the structure of message-related components. * tests: Update FileRow Component to Prefer Cached Previews for Image Rendering - Modified the image URL selection logic in the FileRow component to prioritize cached previews over file paths when uploads are complete, enhancing rendering performance and user experience. - Updated related tests to reflect changes in image URL handling, ensuring accurate assertions for both preview and file path scenarios. - Introduced a fallback mechanism to use file paths when no preview exists, improving robustness in file handling. * fix: Image cache lifecycle and dialog decoding - Add deletePreview/clearPreviewCache to previewCache.ts for blob URL cleanup - Wire deletePreview into useFileDeletion to revoke blobs on file delete - Move dimensionCache.set into useMemo to avoid side effects during render - Extract IMAGE_MAX_W_PX constant (512) to document coupling with max-w-lg - Export _resetImageCaches for test isolation - Change DialogImage decoding from "sync" to "async" to avoid blocking main thread * fix: Avatar cache invalidation and cleanup - Include avatarSrc in cache invalidation to prevent stale avatars - Remove unused username parameter from resolveAvatar - Skip caching when userId is empty to prevent cache key collisions * test: Fix test isolation and type safety - Reset module-level dimensionCache/paintedUrls in beforeEach via _resetImageCaches - Replace any[] with typed mock signature in cn mock for both test files * chore: Code quality improvements from review - Use barrel imports for previewCache in Files.tsx and Part.tsx - Single Map.get with truthy check instead of has+get in useEventHandlers - Add JSDoc comments explaining EmptyText margin removal and PlaceholderRow height - Fix FileRow toast showing "Deleting file" when file isn't actually deleted (progress < 1) * fix: Address remaining review findings (R1-R3) - Add deletePreview calls to deleteFiles batch path to prevent blob URL leaks - Change useFileDeletion import from deep path to barrel (~/utils) - Change useMemo to useEffect for dimensionCache.set (side effect, not derived value) * fix: Address audit comments 2, 5, and 7 - Fix files preservation to distinguish null (missing) from [] (empty) in finalHandler - Add auto-revoke on overwrite in cachePreview to prevent leaked blobs - Add removePreviewEntry for key transfer without revoke - Clean up stale temp_file_id cache entry after promotion to permanent file_id
2026-03-06 19:09:52 -05:00
const {
🧩 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
width: imageWidth,
height: imageHeight,
🎞️ refactor: Image Rendering with Preview Caching and Layout Reservation (#12114) * refactor: Update Image Component to Remove Lazy Loading and Enhance Rendering - Removed the react-lazy-load-image-component dependency from the Image component, simplifying the image loading process. - Updated the Image component to use a standard <img> tag with async decoding for improved performance and user experience. - Adjusted related tests to reflect changes in image rendering behavior and ensure proper functionality without lazy loading. * refactor: Enhance Image Handling and Caching Across Components - Introduced a new previewCache utility for managing local blob preview URLs, improving image loading efficiency. - Updated the Image component and related parts (FileRow, Files, Part, ImageAttachment, LogContent) to utilize cached previews, enhancing rendering performance and user experience. - Added width and height properties to the Image component for better layout management and consistency across different usages. - Improved file handling logic in useFileHandling to cache previews during file uploads, ensuring quick access to image data. - Enhanced overall code clarity and maintainability by streamlining image rendering logic and reducing redundancy. * refactor: Enhance OpenAIImageGen Component with Image Dimensions - Added width and height properties to the OpenAIImageGen component for improved image rendering and layout management. - Updated the Image component usage within OpenAIImageGen to utilize the new dimensions, enhancing visual consistency and performance. - Improved code clarity by destructuring additional properties from the attachment object, streamlining the component's logic. * refactor: Implement Image Size Caching in DialogImage Component - Introduced an imageSizeCache to store and retrieve image sizes, enhancing performance by reducing redundant fetch requests. - Updated the getImageSize function to first check the cache before making network requests, improving efficiency in image handling. - Added decoding attribute to the image element for optimized rendering behavior. * refactor: Enhance UserAvatar Component with Avatar Caching and Error Handling - Introduced avatar caching logic to optimize avatar resolution based on user ID and avatar source, improving performance and reducing redundant image loads. - Implemented error handling for failed image loads, allowing for fallback to a default avatar when necessary. - Updated UserAvatar props to streamline the interface by removing the user object and directly accepting avatar-related properties. - Enhanced overall code clarity and maintainability by refactoring the component structure and logic. * fix: Layout Shift in Message and Placeholder Components for Consistent Height Management - Adjusted the height of the PlaceholderRow and related message components to ensure consistent rendering with a minimum height of 31px. - Updated the MessageParts and ContentRender components to utilize a minimum height for better layout stability. - Enhanced overall code clarity by standardizing the structure of message-related components. * tests: Update FileRow Component to Prefer Cached Previews for Image Rendering - Modified the image URL selection logic in the FileRow component to prioritize cached previews over file paths when uploads are complete, enhancing rendering performance and user experience. - Updated related tests to reflect changes in image URL handling, ensuring accurate assertions for both preview and file path scenarios. - Introduced a fallback mechanism to use file paths when no preview exists, improving robustness in file handling. * fix: Image cache lifecycle and dialog decoding - Add deletePreview/clearPreviewCache to previewCache.ts for blob URL cleanup - Wire deletePreview into useFileDeletion to revoke blobs on file delete - Move dimensionCache.set into useMemo to avoid side effects during render - Extract IMAGE_MAX_W_PX constant (512) to document coupling with max-w-lg - Export _resetImageCaches for test isolation - Change DialogImage decoding from "sync" to "async" to avoid blocking main thread * fix: Avatar cache invalidation and cleanup - Include avatarSrc in cache invalidation to prevent stale avatars - Remove unused username parameter from resolveAvatar - Skip caching when userId is empty to prevent cache key collisions * test: Fix test isolation and type safety - Reset module-level dimensionCache/paintedUrls in beforeEach via _resetImageCaches - Replace any[] with typed mock signature in cn mock for both test files * chore: Code quality improvements from review - Use barrel imports for previewCache in Files.tsx and Part.tsx - Single Map.get with truthy check instead of has+get in useEventHandlers - Add JSDoc comments explaining EmptyText margin removal and PlaceholderRow height - Fix FileRow toast showing "Deleting file" when file isn't actually deleted (progress < 1) * fix: Address remaining review findings (R1-R3) - Add deletePreview calls to deleteFiles batch path to prevent blob URL leaks - Change useFileDeletion import from deep path to barrel (~/utils) - Change useMemo to useEffect for dimensionCache.set (side effect, not derived value) * fix: Address audit comments 2, 5, and 7 - Fix files preservation to distinguish null (missing) from [] (empty) in finalHandler - Add auto-revoke on overwrite in cachePreview to prevent leaked blobs - Add removePreviewEntry for key transfer without revoke - Clean up stale temp_file_id cache entry after promotion to permanent file_id
2026-03-06 19:09:52 -05:00
filepath = null,
filename = '',
} = (attachment as TFile & TAttachmentMetadata) || {};
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
🧩 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
let origWidth = width ?? imageWidth;
let origHeight = height ?? imageHeight;
if (origWidth === undefined || origHeight === undefined) {
origWidth = 1024;
origHeight = 1024;
}
const [dimensions, setDimensions] = useState({ width: 'auto', height: 'auto' });
const containerRef = useRef<HTMLDivElement>(null);
const updateDimensions = useCallback(() => {
if (origWidth && origHeight && containerRef.current) {
const scaled = scaleImage({
originalWidth: origWidth,
originalHeight: origHeight,
containerRef,
});
setDimensions(scaled);
}
}, [origWidth, origHeight]);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
useEffect(() => {
🧩 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
if (!isAgentStyle) {
return;
}
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
if (isSubmitting) {
🧩 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
setAgentProgress(initialProgress);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
let baseDuration = 20000;
if (quality === 'low') {
baseDuration = 10000;
} else if (quality === 'high') {
baseDuration = 50000;
}
const jitter = Math.floor(baseDuration * 0.3);
const totalDuration = Math.floor(Math.random() * jitter) + baseDuration;
const updateInterval = 200;
const totalSteps = totalDuration / updateInterval;
let currentStep = 0;
intervalRef.current = setInterval(() => {
currentStep++;
if (currentStep >= totalSteps) {
clearInterval(intervalRef.current as NodeJS.Timeout);
🧩 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
setAgentProgress(0.9);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
} else {
const progressRatio = currentStep / totalSteps;
let mapRatio: number;
if (progressRatio < 0.8) {
mapRatio = Math.pow(progressRatio, 1.1);
} else {
const sub = (progressRatio - 0.8) / 0.2;
mapRatio = 0.8 + (1 - Math.pow(1 - sub, 2)) * 0.2;
}
const scaledProgress = 0.1 + mapRatio * 0.8;
🧩 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
setAgentProgress(scaledProgress);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
}
}, updateInterval);
}
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
};
🧩 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
}, [isSubmitting, initialProgress, quality, isAgentStyle]);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
useEffect(() => {
🧩 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
if (!isAgentStyle) {
return;
}
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
if (initialProgress >= 1 || cancelled) {
🧩 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
setAgentProgress(initialProgress);
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
}
🧩 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
}, [initialProgress, cancelled, isAgentStyle]);
useEffect(() => {
updateDimensions();
const resizeObserver = new ResizeObserver(() => {
updateDimensions();
});
if (containerRef.current) {
resizeObserver.observe(containerRef.current);
}
return () => {
resizeObserver.disconnect();
};
}, [updateDimensions]);
const isInProgress = progress < 1 && !cancelled;
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
return (
<>
🧩 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
<span className="sr-only" aria-live="polite" aria-atomic="true">
{(() => {
if (progress < 1 && !cancelled) {
return '';
}
if (cancelled && hasError) {
return localize('com_ui_image_gen_failed');
}
if (cancelled) {
return localize('com_ui_cancelled');
}
return localize('com_ui_image_created');
})()}
</span>
<div className="relative my-1 flex h-5 shrink-0 items-center gap-2">
<ToolIcon type="image_gen" isAnimating={isInProgress} />
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
<ProgressText progress={progress} error={cancelled} toolName={toolName} />
</div>
🧩 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
{isAgentStyle && (
<div className="relative mb-2 flex w-full justify-start">
<div ref={containerRef} className="w-full max-w-lg">
{dimensions.width !== 'auto' && progress < 1 && (
<PixelCard
variant="default"
progress={progress}
randomness={0.6}
width={dimensions.width}
height={dimensions.height}
/>
)}
<Image
altText={filename}
imagePath={filepath ?? ''}
width={Number(dimensions.width?.split('px')[0])}
height={Number(dimensions.height?.split('px')[0])}
args={parsedArgs}
/>
</div>
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
</div>
🧩 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
)}
🖼️ feat: Tool Call and Loading UI Refresh, Image Resize Config (#7086) * ✨ feat: Enhance Spinner component with customizable properties and improved animation * 🔧 fix: Replace Loader with Spinner in RunCode component and update FilePreview to use Spinner for progress indication * ✨ feat: Refactor icons in CodeProgress and CancelledIcon components; enhance animation and styling in ExecuteCode and ProgressText components * ✨ feat: Refactor attachment handling in ExecuteCode component; replace individual attachment rendering with AttachmentGroup for improved structure * ✨ feat: Refactor dialog components for improved accessibility and styling; integrate Skeleton loading state in Image component * ✨ feat: Refactor ToolCall component to use ToolCallInfo for better structure; replace ToolPopover with AttachmentGroup; enhance ProgressText with error handling and improved UI elements * 🔧 fix: Remove unnecessary whitespace in ProgressText * 🔧 fix: Remove unnecessary margin from AgentFooter and AgentPanel components; clean up SidePanel imports * ✨ feat: Enhance ToolCall and ToolCallInfo components with improved styling; update translations and add warning text color to Tailwind config * 🔧 fix: Update import statement for useLocalize in ToolCallInfo component; fix: chatform transition * ✨ feat: Refactor ToolCall and ToolCallInfo components for improved structure and styling; add optimized code block for better output display * ✨ feat: Implement OpenAI image generation component; add progress tracking and localization for user feedback * 🔧 fix: Adjust base duration values for image generation; optimize timing for quality settings * chore: remove unnecessary space * ✨ feat: Enhance OpenAI image generation with editing capabilities; update localization for progress feedback * ✨ feat: Add download functionality to images; enhance DialogImage component with download button * ✨ feat: Enhance image resizing functionality; support custom percentage and pixel dimensions in resizeImageBuffer
2025-05-16 17:50:18 +02:00
</>
);
}