From 3b820415ad3632c1cb8affdbadc3bd8bc1206c3d Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Thu, 16 Apr 2026 15:09:53 -0400 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=AD=20feat:=20Custom=20UI=20Renderers?= =?UTF-8?q?=20for=20Skill=20Tool=20Calls=20(#12684)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Custom UI renderers for skill, read_file, and bash_tool Add specialized tool call components for the three skill tools, replacing the generic ToolCall fallback with contextual UI. * fix: Address review findings for skill tool UI renderers - Fix Codex P2: read skillName (camelCase) matching agent pipeline - Fix Codex P2: remove error regex from ReadFileCall to avoid false positives on normal file content containing "Error:" tokens - Extract useToolCallState hook to eliminate ~60% boilerplate duplication across SkillCall, ReadFileCall, and BashCall - Extract parseJsonField utility with consistent escaped-char-aware regex fallback, shared by all three components - Gate SkillCall bordered card on hasOutput to prevent empty card when expanded before output arrives - Skip highlightAuto for plaintext lang to avoid expensive auto-detection on files with unknown extensions - Expand LANG_MAP with php, cs, kt, swift, scss, less, lua, r; add FILENAME_MAP for Makefile and Dockerfile - Export langFromPath for testability - Add unit tests for parseJsonField, langFromPath, and ToolIcon skill type branches * refactor: Redesign BashCall as minimal terminal widget Replace the ExecuteCode-clone pattern with a purpose-built terminal UI: $ prompt prefix, dark background command zone, icon-only copy button, and raw monospace output. Drops useLazyHighlight, CodeWindowHeader, Stdout, and the "Output" label in favor of a cleaner two-zone layout that feels native to the terminal. * fix: parseJsonField unescape ordering and ReadFileCall empty card Replace the sequential .replace() chain in parseJsonField's regex fallback with a single-pass /\(.)/g replacement. The old chain processed \n before \, so \n (JSON-escaped literal backslash + n) was incorrectly decoded as a newline instead of \n. Gate ReadFileCall's bordered card on hasOutput (matching SkillCall's pattern) so the card does not render as an empty rounded box during streaming before output arrives. Add regression tests for \n decoding and unknown escape sequences. * fix: Followup review fixes - Refactor ExecuteCode to use shared useToolCallState hook, eliminating the last copy of the inline state machine - Escape regex metacharacters in parseJsonField to prevent injection from field names containing ., +, (, etc. - Fix contradictory test description in langFromPath tests * fix: Surface tool failure state in skill tool renderers Add error detection to useToolCallState via the shared isError check so tool calls that complete with an error prefix show a "failed" suffix instead of a success label. Prevents misleading users when read_file, skill, or bash_tool returns an error (e.g. file not found, skill not accessible). Matches the error handling pattern already used by the generic ToolCall component. * feat: Add bash syntax highlighting to BashCall command zone Reuse the shared useLazyHighlight singleton (already loaded by ReadFileCall and ExecuteCode) to highlight the command with bash grammar. Falls back to plain text while lowlight is loading. * fix: Align BashCall scrollbar to span full card width Move max-h/overflow-auto from the inner pre to the outer container so the scrollbar spans the full width like the output zone. Float the copy button with sticky positioning so it stays visible while scrolling long commands. * feat: Use GNU Bash icon for bash_tool progress header and ToolIcon Replace the generic SquareTerminal lucide icon with the GNU Bash logo (already in the project via LangIcon/langIconPaths) for both the BashCall progress header and the ToolIcon stacked icon mapping. * fix: Render raw content while highlighter loads, preserve command text on copy - ReadFileCall: fall back to raw output when useLazyHighlight returns null, preventing a blank code panel on first render before lowlight finishes its dynamic import - BashCall: drop .trim() from the copy handler so the clipboard receives exactly what's displayed (WYSIWYG copy) * fix: Alphabetize new translation keys within en/translation.json Relocate read_file, skill_finished, and skill_running into their correct alphabetical positions within the overall key list. * fix: Surface error state in ExecuteCode, fix BashCall import order - ExecuteCode now uses hasError from useToolCallState to show the "failed" suffix on failed code executions, matching the three new renderers - Reorder BashCall local imports to longest-to-shortest per project style --- .../components/Chat/Messages/Content/Part.tsx | 43 +++++- .../Chat/Messages/Content/Parts/BashCall.tsx | 111 ++++++++++++++ .../Messages/Content/Parts/ExecuteCode.tsx | 136 ++---------------- .../Messages/Content/Parts/ReadFileCall.tsx | 129 +++++++++++++++++ .../Chat/Messages/Content/Parts/SkillCall.tsx | 77 ++++++++++ .../Parts/__tests__/langFromPath.test.ts | 117 +++++++++++++++ .../Parts/__tests__/parseJsonField.test.ts | 103 +++++++++++++ .../Chat/Messages/Content/Parts/index.ts | 3 + .../Messages/Content/Parts/parseJsonField.ts | 26 ++++ .../Content/Parts/useLazyHighlight.ts | 109 ++++++++++++++ .../Content/Parts/useToolCallState.ts | 54 +++++++ .../Messages/Content/ToolOutput/ToolIcon.tsx | 32 ++++- .../Content/__tests__/ToolIcon.test.tsx | 26 ++++ client/src/locales/en/translation.json | 6 + .../data-provider/src/types/assistants.ts | 3 + 15 files changed, 846 insertions(+), 129 deletions(-) create mode 100644 client/src/components/Chat/Messages/Content/Parts/BashCall.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/langFromPath.test.ts create mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/parseJsonField.test.ts create mode 100644 client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts create mode 100644 client/src/components/Chat/Messages/Content/Parts/useLazyHighlight.ts create mode 100644 client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx index 1b4b9057f6..7478afbd0c 100644 --- a/client/src/components/Chat/Messages/Content/Part.tsx +++ b/client/src/components/Chat/Messages/Content/Part.tsx @@ -8,7 +8,18 @@ import { isImageVisionTool, } from 'librechat-data-provider'; import type { TMessageContentParts, TAttachment } from 'librechat-data-provider'; -import { ImageGen, ExecuteCode, AgentUpdate, EmptyText, Reasoning, Summary, Text } from './Parts'; +import { + ImageGen, + ExecuteCode, + AgentUpdate, + EmptyText, + Reasoning, + Summary, + Text, + SkillCall, + ReadFileCall, + BashCall, +} from './Parts'; import { ErrorMessage } from './MessageContent'; import RetrievalCall from './RetrievalCall'; import { getCachedPreview } from '~/utils'; @@ -148,6 +159,36 @@ const Part = memo(function Part({ attachments={attachments} /> ); + } else if (isToolCall && toolCall.name === 'skill') { + return ( + + ); + } else if (isToolCall && toolCall.name === 'read_file') { + return ( + + ); + } else if (isToolCall && toolCall.name === 'bash_tool') { + return ( + + ); } else if (isToolCall && toolCall.name === Tools.web_search) { return ( ; + output?: string; + attachments?: TAttachment[]; +}) { + const localize = useLocalize(); + const command = useMemo(() => parseJsonField(args, 'command'), [args]); + + const { showCode, toggleCode, expandStyle, expandRef, progress, cancelled, hasError, hasOutput } = + useToolCallState(initialProgress, isSubmitting, output, !!command); + + const highlighted = useLazyHighlight(command || undefined, 'bash'); + const outputHasError = useMemo(() => ERROR_PATTERNS.test(output), [output]); + + const [isCopied, setIsCopied] = useState(false); + const timerRef = useRef>(); + useEffect(() => () => clearTimeout(timerRef.current), []); + + const handleCopy = useCallback(() => { + setIsCopied(true); + copy(command, { format: 'text/plain' }); + clearTimeout(timerRef.current); + timerRef.current = setTimeout(() => setIsCopied(false), 3000); + }, [command]); + + return ( + <> +
+ + } + hasInput={!!command || hasOutput} + isExpanded={showCode} + error={cancelled} + /> +
+
+
+
+ {command && ( +
+ +
+                  
+                  {highlighted ?? command}
+                
+
+ )} + {hasOutput && ( +
+
+                  {output}
+                
+
+ )} +
+
+
+ {attachments && attachments.length > 0 && } + + ); +} diff --git a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx index 20298f5c0b..c3972c131b 100644 --- a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx @@ -1,124 +1,20 @@ -import React, { useMemo, useState, useEffect, useCallback, useRef } from 'react'; -import { useRecoilValue } from 'recoil'; +import { useMemo } from 'react'; import { SquareTerminal } from 'lucide-react'; import type { TAttachment } from 'librechat-data-provider'; import ProgressText from '~/components/Chat/Messages/Content/ProgressText'; -import { useProgress, useLocalize, useExpandCollapse } from '~/hooks'; +import useLazyHighlight from './useLazyHighlight'; +import useToolCallState from './useToolCallState'; import CodeWindowHeader from './CodeWindowHeader'; import { AttachmentGroup } from './Attachment'; +import { useLocalize } from '~/hooks'; import Stdout from './Stdout'; import { cn } from '~/utils'; -import store from '~/store'; interface ParsedArgs { lang?: string; code?: string; } -interface HastText { - type: 'text'; - value: string; -} - -interface HastElement { - type: 'element'; - tagName: string; - properties?: { className?: string[] }; - children?: HastNode[]; -} - -type HastNode = HastText | HastElement; - -function hastToReact(nodes: HastNode[]): React.ReactNode[] { - return nodes.map((node, i) => { - if (node.type === 'text') { - return node.value; - } - return React.createElement( - node.tagName, - { key: i, className: node.properties?.className?.join(' ') }, - node.children ? hastToReact(node.children) : undefined, - ); - }); -} - -type LowlightModule = typeof import('lowlight'); - -/** Lazy-loaded lowlight singleton — only fetched when syntax highlighting is first needed. */ -let lowlightPromise: Promise | null = null; -let lowlightModule: LowlightModule | null = null; - -function loadLowlight(): Promise { - if (lowlightModule) { - return Promise.resolve(lowlightModule); - } - if (!lowlightPromise) { - lowlightPromise = import('lowlight').then((mod) => { - lowlightModule = mod; - return mod; - }); - } - return lowlightPromise; -} - -function highlightCode(mod: LowlightModule, code: string, lang: string): React.ReactNode[] { - try { - const tree = mod.lowlight.registered(lang) - ? mod.lowlight.highlight(lang, code) - : mod.lowlight.highlightAuto(code); - return hastToReact(tree.children as HastNode[]); - } catch { - return [code]; - } -} - -/** Hook that lazily loads lowlight and returns highlighted nodes once ready. */ -function useLazyHighlight(code: string | undefined, lang: string): React.ReactNode[] | null { - const [highlighted, setHighlighted] = useState(() => { - if (!code || !lowlightModule) { - return null; - } - return highlightCode(lowlightModule, code, lang); - }); - const prevKey = useRef(''); - - useEffect(() => { - const key = `${lang}\0${code ?? ''}`; - if (key === prevKey.current) { - return; - } - prevKey.current = key; - - if (!code) { - setHighlighted(null); - return; - } - - if (lowlightModule) { - setHighlighted(highlightCode(lowlightModule, code, lang)); - return; - } - - let cancelled = false; - loadLowlight() - .then((mod) => { - if (!cancelled) { - setHighlighted(highlightCode(mod, code, lang)); - } - }) - .catch(() => { - if (!cancelled) { - setHighlighted([code]); - } - }); - return () => { - cancelled = true; - }; - }, [code, lang]); - - return highlighted; -} - export function useParseArgs(args?: string | Record): ParsedArgs | null { return useMemo(() => { if (typeof args === 'object' && args !== null) { @@ -152,7 +48,7 @@ export function useParseArgs(args?: string | Record): ParsedArg }, [args]); } -const ERROR_PATTERNS = /^(Traceback|Error:|Exception:|.*Error:)/m; +export const ERROR_PATTERNS = /^(Traceback|Error:|Exception:|.*Error:)/m; export default function ExecuteCode({ isSubmitting, @@ -168,29 +64,14 @@ export default function ExecuteCode({ attachments?: TAttachment[]; }) { const localize = useLocalize(); - const hasOutput = output.length > 0; - const autoExpand = useRecoilValue(store.autoExpandTools); - const { lang = 'py', code } = useParseArgs(args) ?? ({} as ParsedArgs); - const hasContent = !!code || hasOutput; - const [showCode, setShowCode] = useState(() => autoExpand && hasContent); - const { style: expandStyle, ref: expandRef } = useExpandCollapse(showCode); - useEffect(() => { - if (autoExpand && hasContent) { - setShowCode(true); - } - }, [autoExpand, hasContent]); - const progress = useProgress(initialProgress); + const { showCode, toggleCode, expandStyle, expandRef, progress, cancelled, hasError, hasOutput } = + useToolCallState(initialProgress, isSubmitting, output, !!code); const highlighted = useLazyHighlight(code, lang); - const outputHasError = useMemo(() => ERROR_PATTERNS.test(output), [output]); - const toggleCode = useCallback(() => setShowCode((prev) => !prev), [setShowCode]); - - const cancelled = !isSubmitting && progress < 1; - return ( <>
@@ -201,11 +82,12 @@ export default function ExecuteCode({ finishedText={ cancelled ? localize('com_ui_cancelled') : localize('com_ui_analyzing_finished') } + errorSuffix={hasError && !cancelled ? localize('com_ui_tool_failed') : undefined} icon={