Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧩 feat: Redesign Tool Call UI with Contextual Icons, Smart Grouping, and Rich Output Rendering (#12163)

Marco Beretta0c66823c26b3
diff --git a/.gitignore b/.gitignore
index ff2ae59633..e302d15a46 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,6 +63,7 @@ bower_components/
.clineignore
.cursor
.aider*
+.bg-shell/
# Floobits
.floo
@@ -129,6 +130,7 @@ helm/**/charts/
helm/**/.values.yaml
!/client/src/@types/i18next.d.ts
+!/client/src/@types/react.d.ts
# SAML Idp cert
*.cert
@@ -143,7 +145,6 @@ helm/**/.values.yaml
/.codeium
*.local.md
-
# Removed Windows wrapper files per user request
hive-mind-prompt-*.txt
@@ -175,3 +176,4 @@ claude-flow
# Removed Windows wrapper files per user request
hive-mind-prompt-*.txt
CLAUDE.md
+.gsd
diff --git a/api/server/services/Files/Citations/index.js b/api/server/services/Files/Citations/index.js
index 008e21d7c4..a1d9322467 100644
--- a/api/server/services/Files/Citations/index.js
+++ b/api/server/services/Files/Citations/index.js
@@ -47,7 +47,10 @@ async function processFileCitations({ user, appConfig, toolArtifact, toolCallId,
logger.error(
`[processFileCitations] Permission check failed for FILE_CITATIONS: ${error.message}`,
);
- logger.debug(`[processFileCitations] Proceeding with citations due to permission error`);
+ logger.warn(
+ '[processFileCitations] Returning null citations due to permission check error — citations will not be shown for this message',
+ );
+ return null;
}
}
@@ -145,6 +148,8 @@ async function enhanceSourcesWithMetadata(sources, appConfig) {
metadata: {
...source.metadata,
storageType: configuredStorageType,
+ fileType: fileRecord.type || undefined,
+ fileBytes: fileRecord.bytes || undefined,
},
};
});
diff --git a/client/jest.config.cjs b/client/jest.config.cjs
index 4d9087bff7..375e4418a7 100644
--- a/client/jest.config.cjs
+++ b/client/jest.config.cjs
@@ -41,7 +41,9 @@ module.exports = {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'jest-file-loader',
},
- transformIgnorePatterns: ['node_modules/?!@zattoo/use-double-click'],
+ transformIgnorePatterns: [
+ '/node_modules/(?!(@zattoo/use-double-click|@dicebear|@react-dnd|react-dnd.*|dnd-core|filenamify|filename-reserved-regex|heic-to|lowlight|highlight\\.js|fault|react-markdown|unified|bail|trough|devlop|is-.*|parse-entities|stringify-entities|character-.*|trim-lines|style-to-object|inline-style-parser|html-url-attributes|escape-string-regexp|longest-streak|zwitch|ccount|markdown-table|comma-separated-tokens|space-separated-tokens|web-namespaces|property-information|remark-.*|rehype-.*|recma-.*|hast.*|mdast-.*|unist-.*|vfile.*|micromark.*|estree-util-.*|decode-named-character-reference)/)/',
+ ],
setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect', '<rootDir>/test/setupTests.js'],
clearMocks: true,
};
diff --git a/client/src/@types/react.d.ts b/client/src/@types/react.d.ts
new file mode 100644
index 0000000000..edf0b7af3f
--- /dev/null
+++ b/client/src/@types/react.d.ts
@@ -0,0 +1,8 @@
+import 'react';
+
+declare module 'react' {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ interface HTMLAttributes<T> {
+ inert?: boolean | '' | undefined;
+ }
+}
diff --git a/client/src/components/Artifacts/Artifacts.tsx b/client/src/components/Artifacts/Artifacts.tsx
index 776f689f08..e2a322b1ad 100644
--- a/client/src/components/Artifacts/Artifacts.tsx
+++ b/client/src/components/Artifacts/Artifacts.tsx
@@ -1,15 +1,16 @@
-import { useRef, useState, useEffect } from 'react';
+import { useRef, useState, useEffect, useCallback } from 'react';
+import copy from 'copy-to-clipboard';
import * as Tabs from '@radix-ui/react-tabs';
import { Code, Play, RefreshCw, X } from 'lucide-react';
import { useSetRecoilState, useResetRecoilState } from 'recoil';
import { Button, Spinner, useMediaQuery, Radio } from '@librechat/client';
import type { SandpackPreviewRef } from '@codesandbox/sandpack-react';
+import CopyButton from '~/components/Messages/Content/CopyButton';
import { useShareContext, useMutationState } from '~/Providers';
import useArtifacts from '~/hooks/Artifacts/useArtifacts';
import DownloadArtifact from './DownloadArtifact';
import ArtifactVersion from './ArtifactVersion';
import ArtifactTabs from './ArtifactTabs';
-import { CopyCodeButton } from './Code';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import store from '~/store';
@@ -30,6 +31,7 @@ export default function Artifacts() {
const [height, setHeight] = useState(90);
const [isDragging, setIsDragging] = useState(false);
const [blurAmount, setBlurAmount] = useState(0);
+ const [isCopied, setIsCopied] = useState(false);
const dragStartY = useRef(0);
const dragStartHeight = useRef(90);
const setArtifactsVisible = useSetRecoilState(store.artifactsVisibility);
@@ -86,6 +88,16 @@ export default function Artifacts() {
setCurrentArtifactId,
} = useArtifacts();
+ const handleCopyArtifact = useCallback(() => {
+ const content = currentArtifact?.content ?? '';
+ if (!content) {
+ return;
+ }
+ copy(content, { format: 'text/plain' });
+ setIsCopied(true);
+ setTimeout(() => setIsCopied(false), 3000);
+ }, [currentArtifact?.content]);
+
const handleDragStart = (e: React.PointerEvent) => {
setIsDragging(true);
dragStartY.current = e.clientY;
@@ -281,7 +293,7 @@ export default function Artifacts() {
}}
/>
)}
- <CopyCodeButton content={currentArtifact.content ?? ''} />
+ <CopyButton isCopied={isCopied} iconOnly onClick={handleCopyArtifact} />
<DownloadArtifact artifact={currentArtifact} />
<Button
size="icon"
diff --git a/client/src/components/Artifacts/Code.tsx b/client/src/components/Artifacts/Code.tsx
index 61d86262f6..225c94b014 100644
--- a/client/src/components/Artifacts/Code.tsx
+++ b/client/src/components/Artifacts/Code.tsx
@@ -1,9 +1,8 @@
-import React, { memo, useState } from 'react';
-import copy from 'copy-to-clipboard';
-import { Button } from '@librechat/client';
-import { Copy, CircleCheckBig } from 'lucide-react';
-import { handleDoubleClick } from '~/utils';
-import { useLocalize } from '~/hooks';
+import React, { memo, useEffect, useRef, useState } from 'react';
+import rehypeKatex from 'rehype-katex';
+import ReactMarkdown from 'react-markdown';
+import rehypeHighlight from 'rehype-highlight';
+import { handleDoubleClick, langSubset } from '~/utils';
type TCodeProps = {
inline: boolean;
@@ -26,29 +25,70 @@ export const code: React.ElementType = memo(({ inline, className, children }: TC
return <code className={`hljs language-${lang} !whitespace-pre`}>{children}</code>;
});
-export const CopyCodeButton: React.FC<{ content: string }> = ({ content }) => {
- const localize = useLocalize();
- const [isCopied, setIsCopied] = useState(false);
-
- const handleCopy = () => {
- copy(content, { format: 'text/plain' });
- setIsCopied(true);
- setTimeout(() => setIsCopied(false), 3000);
- };
-
- return (
- <Button
- size="icon"
- variant="ghost"
- className="h-9 w-9"
- onClick={handleCopy}
- aria-label={isCopied ? localize('com_ui_copied') : localize('com_ui_copy_code')}
- >
- {isCopied ? (
- <CircleCheckBig size={16} aria-hidden="true" />
- ) : (
- <Copy size={16} aria-hidden="true" />
- )}
- </Button>
- );
-};
+const rehypePlugins = [
+ [rehypeKatex],
+ [
+ rehypeHighlight,
+ {
+ detect: true,
+ ignoreMissing: true,
+ subset: langSubset,
+ },
+ ],
+];
+
+export const CodeMarkdown = memo(
+ ({ content = '', isSubmitting }: { content: string; isSubmitting: boolean }) => {
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const [userScrolled, setUserScrolled] = useState(false);
+
+ useEffect(() => {
+ const scrollContainer = scrollRef.current;
+ if (!scrollContainer) {
+ return;
+ }
+
+ const handleScroll = () => {
+ const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
+ const isNearBottom = scrollHeight - scrollTop - clientHeight < 50;
+
+ if (!isNearBottom) {
+ setUserScrolled(true);
+ } else {
+ setUserScrolled(false);
+ }
+ };
+
+ scrollContainer.addEventListener('scroll', handleScroll);
+
+ return () => {
+ scrollContainer.removeEventListener('scroll', handleScroll);
+ };
+ }, []);
+
+ useEffect(() => {
+ const scrollContainer = scrollRef.current;
+ if (!scrollContainer || !isSubmitting || userScrolled) {
+ return;
+ }
+
+ scrollContainer.scrollTop = scrollContainer.scrollHeight;
+ }, [content, isSubmitting, userScrolled]);
+
+ return (
+ <div ref={scrollRef} className="max-h-full overflow-y-auto">
+ <ReactMarkdown
+ /* @ts-expect-error — rehypePlugins type mismatch between react-markdown and unified PluggableList */
+ rehypePlugins={rehypePlugins}
+ components={
+ { code } as {
+ [key: string]: React.ElementType;
+ }
+ }
+ >
+ {content}
+ </ReactMarkdown>
+ </div>
+ );
+ },
+);
diff --git a/client/src/components/Chat/Messages/Content/AgentHandoff.tsx b/client/src/components/Chat/Messages/Content/AgentHandoff.tsx
index f5fa162ff2..5a5505ee60 100644
--- a/client/src/components/Chat/Messages/Content/AgentHandoff.tsx
+++ b/client/src/components/Chat/Messages/Content/AgentHandoff.tsx
@@ -1,24 +1,23 @@
import React, { useMemo, useState } from 'react';
-import { EModelEndpoint, Constants } from 'librechat-data-provider';
import { ChevronDown } from 'lucide-react';
+import { EModelEndpoint, Constants } from 'librechat-data-provider';
import type { TMessage } from 'librechat-data-provider';
import MessageIcon from '~/components/Share/MessageIcon';
+import { useLocalize, useExpandCollapse } from '~/hooks';
import { useAgentsMapContext } from '~/Providers';
-import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
interface AgentHandoffProps {
name: string;
args: string | Record<string, unknown>;
- output?: string | null;
}
const AgentHandoff: React.FC<AgentHandoffProps> = ({ name, args: _args = '' }) => {
const localize = useLocalize();
const agentsMap = useAgentsMapContext();
const [showInfo, setShowInfo] = useState(false);
+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo);
- /** Extracted agent ID from tool name (e.g., "lc_transfer_to_agent_gUV0wMb7zHt3y3Xjz-8_4" -> "agent_gUV0wMb7zHt3y3Xjz-8_4") */
const targetAgentId = useMemo(() => {
if (typeof name !== 'string' || !name.startsWith(Constants.LC_TRANSFER_TO_)) {
return null;
@@ -44,19 +43,24 @@ const AgentHandoff: React.FC<AgentHandoffProps> = ({ name, args: _args = '' }) =
}
}, [_args]) as string;
- /** Requires more than 2 characters as can be an empty object: `{}` */
const hasInfo = useMemo(() => (args?.trim()?.length ?? 0) > 2, [args]);
return (
- <div className="my-3">
- <div
+ <div className="my-1">
+ <button
+ type="button"
className={cn(
- 'flex items-center gap-2.5 text-sm text-text-secondary',
- hasInfo && 'cursor-pointer transition-colors hover:text-text-primary',
+ 'tool-status-text flex appearance-none items-center gap-2.5 bg-transparent text-text-secondary',
+ hasInfo
+ ? 'transition-colors hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy'
+ : 'pointer-events-none',
)}
- onClick={() => hasInfo && setShowInfo(!showInfo)}
+ disabled={!hasInfo}
+ onClick={hasInfo ? () => setShowInfo(!showInfo) : undefined}
+ aria-expanded={hasInfo ? showInfo : undefined}
+ aria-label={`${localize('com_ui_transferred_to')} ${targetAgent?.name || localize('com_ui_agent')}`}
>
- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
+ <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full ring-1 ring-border-light">
<MessageIcon
message={
{
@@ -77,15 +81,19 @@ const AgentHandoff: React.FC<AgentHandoffProps> = ({ name, args: _args = '' }) =
aria-hidden="true"
/>
)}
- </div>
- {hasInfo && showInfo && (
- <div className="ml-8 mt-2 rounded-md bg-surface-secondary p-3 text-xs">
- <div className="mb-1 font-medium text-text-secondary">
- {localize('com_ui_handoff_instructions')}:
- </div>
- <pre className="overflow-x-auto whitespace-pre-wrap text-text-primary">{args}</pre>
+ </button>
+ <div style={expandStyle}>
+ <div className="overflow-hidden" ref={expandRef}>
+ {hasInfo && (
+ <div className="ml-8 mt-2 rounded-lg border border-border-light bg-surface-secondary p-3 text-xs">
+ <div className="mb-1 font-medium text-text-secondary">
+ {localize('com_ui_handoff_instructions')}:
+ </div>
+ <pre className="overflow-x-auto whitespace-pre-wrap text-text-primary">{args}</pre>
+ </div>
+ )}
</div>
- )}
+ </div>
</div>
);
};
diff --git a/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx b/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx
index 139496c621..3d4fdee1c9 100644
--- a/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx
+++ b/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx
@@ -1,8 +1,10 @@
-import { useState } from 'react';
+import { useState, useEffect } from 'react';
import { useRecoilValue } from 'recoil';
+import { Terminal } from 'lucide-react';
import { useProgress, useLocalize } from '~/hooks';
import ProgressText from './ProgressText';
import MarkdownLite from './MarkdownLite';
+import { cn } from '~/utils';
import store from '~/store';
export default function CodeAnalyze({
@@ -16,8 +18,14 @@ export default function CodeAnalyze({
}) {
const localize = useLocalize();
const progress = useProgress(initialProgress);
- const showAnalysisCode = useRecoilValue(store.showCode);
- const [showCode, setShowCode] = useState(showAnalysisCode);
+ const autoExpand = useRecoilValue(store.autoExpandTools);
+ const [showCode, setShowCode] = useState(autoExpand);
+
+ useEffect(() => {
+ if (autoExpand) {
+ setShowCode(true);
+ }
+ }, [autoExpand]);
const logs = outputs.reduce((acc, output) => {
if (output['logs']) {
@@ -28,7 +36,10 @@ export default function CodeAnalyze({
return (
<>
- <div className="my-2.5 flex items-center gap-2.5">
+ <span className="sr-only" aria-live="polite" aria-atomic="true">
+ {progress < 1 ? localize('com_ui_analyzing') : localize('com_ui_analyzing_finished')}
+ </span>
+ <div className="my-1 flex items-center gap-2.5">
<ProgressText
progress={progress}
onClick={() => setShowCode((prev) => !prev)}
@@ -36,6 +47,12 @@ export default function CodeAnalyze({
finishedText={localize('com_ui_analyzing_finished')}
hasInput={!!code.length}
isExpanded={showCode}
+ icon={
+ <Terminal
+ className={cn('size-4 shrink-0 text-text-secondary', progress < 1 && 'animate-pulse')}
+ aria-hidden="true"
+ />
+ }
/>
</div>
{showCode && (
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index 4b431d7a98..65ebc66908 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -6,12 +6,12 @@ import type {
TAttachment,
Agents,
} from 'librechat-data-provider';
-import { MessageContext, SearchContext } from '~/Providers';
import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';
-import { mapAttachments } from '~/utils';
+import { mapAttachments, groupSequentialToolCalls } from '~/utils';
+import { MessageContext, SearchContext } from '~/Providers';
import { EditTextPart, EmptyText } from './Parts';
import MemoryArtifacts from './MemoryArtifacts';
-import Sources from '~/components/Web/Sources';
+import ToolCallGroup from './ToolCallGroup';
import Container from './Container';
import Part from './Part';
@@ -160,10 +160,10 @@ const ContentParts = memo(function ContentParts({
}
const isTextPart =
part?.type === ContentTypes.TEXT ||
- typeof (part as unknown as Agents.MessageContentText)?.text !== 'string';
+ typeof (part as unknown as Agents.MessageContentText)?.text === 'string';
const isThinkPart =
part?.type === ContentTypes.THINK ||
- typeof (part as unknown as Agents.ReasoningDeltaUpdate)?.think !== 'string';
+ typeof (part as unknown as Agents.ReasoningDeltaUpdate)?.think === 'string';
if (!isTextPart && !isThinkPart) {
return null;
}
@@ -216,17 +216,32 @@ const ContentParts = memo(function ContentParts({
sequentialParts.push({ part, idx });
}
});
+ const groupedParts = groupSequentialToolCalls(sequentialParts);
return (
<SearchContext.Provider value={{ searchResults }}>
<MemoryArtifacts attachments={attachments} />
- <Sources messageId={messageId} conversationId={conversationId || undefined} />
{showEmptyCursor && (
<Container>
<EmptyText />
</Container>
)}
- {sequentialParts.map(({ part, idx }) => renderPart(part, idx, idx === lastContentIdx))}
+ {groupedParts.map((group) => {
+ if (group.type === 'single') {
+ const { part, idx } = group.part;
+ return renderPart(part, idx, idx === lastContentIdx);
+ }
+ return (
+ <ToolCallGroup
+ key={`tool-group-${group.parts[0].idx}`}
+ parts={group.parts}
+ isSubmitting={effectiveIsSubmitting}
+ isLast={group.parts.some((p) => p.idx === lastContentIdx)}
+ renderPart={renderPart}
+ lastContentIdx={lastContentIdx}
+ />
+ );
+ })}
</SearchContext.Provider>
);
});
diff --git a/client/src/components/Chat/Messages/Content/FilePreviewDialog.tsx b/client/src/components/Chat/Messages/Content/FilePreviewDialog.tsx
new file mode 100644
index 0000000000..c02e2fee4b
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/FilePreviewDialog.tsx
@@ -0,0 +1,344 @@
+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
+import copy from 'copy-to-clipboard';
+import { useRecoilValue } from 'recoil';
+import { Download } from 'lucide-react';
+import { OGDialog, OGDialogContent, OGDialogTitle, OGDialogDescription } from '@librechat/client';
+import CopyButton from '~/components/Messages/Content/CopyButton';
+import { logger, sortPagesByRelevance } from '~/utils';
+import { useFileDownload } from '~/data-provider';
+import { useLocalize } from '~/hooks';
+import store from '~/store';
+
+interface FilePreviewDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ fileName: string;
+ fileId?: string;
+ relevance?: number;
+ pages?: number[];
+ pageRelevance?: Record<number, number>;
+ fileType?: string;
+ fileSize?: number;
+}
+
+function getFileExtension(filename: string): string {
+ const dot = filename.lastIndexOf('.');
+ return dot > 0 ? filename.slice(dot + 1).toLowerCase() : '';
+}
+
+function canPreviewByMime(mime?: string): 'pdf' | 'text' | false {
+ if (!mime) {
+ return false;
+ }
+ if (mime.includes('pdf')) {
+ return 'pdf';
+ }
+ if (
+ mime.startsWith('text/') ||
+ mime.includes('json') ||
+ mime.includes('xml') ||
+ mime.includes('javascript') ||
+ mime.includes('typescript') ||
+ mime.includes('yaml') ||
+ mime.includes('csv')
+ ) {
+ return 'text';
+ }
+ return false;
+}
+
+function canPreviewByExt(filename: string): 'pdf' | 'text' | false {
+ const ext = getFileExtension(filename);
+ if (ext === 'pdf') {
+ return 'pdf';
+ }
+ const textExts = new Set([
+ 'txt',
+ 'md',
+ 'csv',
+ 'json',
+ 'xml',
+ 'yaml',
+ 'yml',
+ 'html',
+ 'css',
+ 'js',
+ 'ts',
+ 'jsx',
+ 'tsx',
+ 'py',
+ 'rb',
+ 'java',
+ 'c',
+ 'cpp',
+ 'h',
+ 'go',
+ 'rs',
+ 'sh',
+ 'sql',
+ 'log',
+ ]);
+ return textExts.has(ext) ? 'text' : false;
+}
+
+/** Formats bytes with unit suffix (differs from ~/utils/formatBytes which returns a raw number). */
+function formatBytes(bytes: number): string {
+ if (bytes >= 1048576) {
+ return `${(bytes / 1048576).toFixed(1)} MB`;
+ }
+ if (bytes >= 1024) {
+ return `${(bytes / 1024).toFixed(1)} KB`;
+ }
+ return `${bytes} B`;
+}
+
+function getDisplayType(fileType?: string, fileName?: string): string {
+ if (fileType) {
+ if (fileType.includes('pdf')) {
+ return 'PDF';
+ }
+ if (fileType.includes('word') || fileType.includes('document')) {
+ return 'Document';
+ }
+ if (fileType.includes('spreadsheet') || fileType.includes('excel')) {
+ return 'Spreadsheet';
+ }
+ if (fileType.includes('presentation') || fileType.includes('powerpoint')) {
+ return 'Presentation';
+ }
+ if (fileType.includes('image')) {
+ return 'Image';
+ }
+ if (fileType.startsWith('text/')) {
+ return fileType.split('/')[1]?.toUpperCase() || 'Text';
+ }
+ if (fileType.includes('json')) {
+ return 'JSON';
+ }
+ if (fileType.includes('xml')) {
+ return 'XML';
+ }
+ }
+ const ext = fileName ? getFileExtension(fileName) : '';
+ return ext ? ext.toUpperCase() : 'File';
+}
+
+export default function FilePreviewDialog({
+ open,
+ onOpenChange,
+ fileName,
+ fileId,
+ relevance,
+ pages,
+ pageRelevance,
+ fileType,
+ fileSize,
+}: FilePreviewDialogProps) {
+ const localize = useLocalize();
+ const user = useRecoilValue(store.user);
+ const { refetch: downloadFile } = useFileDownload(user?.id ?? '', fileId);
+
+ const [fileContent, setFileContent] = useState<string | null>(null);
+ const [fileBlobUrl, setFileBlobUrl] = useState<string | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [previewError, setPreviewError] = useState(false);
+ const [isCopied, setIsCopied] = useState(false);
+ const loadingRef = useRef(false);
+
+ const previewKind = canPreviewByMime(fileType) || canPreviewByExt(fileName);
+
+ const cancelledRef = useRef(false);
+
+ const loadPreview = useCallback(async () => {
+ if (!fileId || !previewKind || loadingRef.current) {
+ return;
+ }
+ loadingRef.current = true;
+ cancelledRef.current = false;
+ setLoading(true);
+ setPreviewError(false);
+
+ try {
+ const result = await downloadFile();
+ if (cancelledRef.current || !result.data) {
+ if (!cancelledRef.current) {
+ setPreviewError(true);
+ }
+ return;
+ }
+
+ const resp = await fetch(result.data);
+ const blob = await resp.blob();
+
+ if (cancelledRef.current) {
+ return;
+ }
+
+ if (previewKind === 'text') {
+ setFileContent(await blob.text());
+ } else {
+ const typed = new Blob([blob], { type: 'application/pdf' });
+ setFileBlobUrl(URL.createObjectURL(typed));
+ }
+ } catch {
+ if (!cancelledRef.current) {
+ setPreviewError(true);
+ }
+ } finally {
+ loadingRef.current = false;
+ if (!cancelledRef.current) {
+ setLoading(false);
+ }
+ }
+ }, [fileId, previewKind, downloadFile]);
+
+ const handleDownload = useCallback(async () => {
+ if (!fileId) {
+ return;
+ }
+ try {
+ const result = await downloadFile();
+ if (!result.data) {
+ return;
+ }
+ const a = document.createElement('a');
+ a.href = result.data;
+ a.setAttribute('download', fileName);
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ setTimeout(() => URL.revokeObjectURL(result.data), 1000);
+ } catch (err) {
+ logger.error('[FilePreviewDialog] Download failed:', err);
+ }
+ }, [downloadFile, fileId, fileName]);
+
+ useEffect(() => {
+ if (open && previewKind && !fileContent && !fileBlobUrl) {
+ loadPreview();
+ }
+ }, [open, previewKind, fileContent, fileBlobUrl, loadPreview]);
+
+ useEffect(() => {
+ return () => {
+ if (fileBlobUrl) {
+ URL.revokeObjectURL(fileBlobUrl);
+ }
+ };
+ }, [fileBlobUrl]);
+
+ useEffect(() => {
+ if (!open) {
+ cancelledRef.current = true;
+ setFileContent(null);
+ setFileBlobUrl(null);
+ setPreviewError(false);
+ setLoading(false);
+ setIsCopied(false);
+ }
+ }, [open]);
+
+ const handleCopy = useCallback(() => {
+ if (!fileContent) {
+ return;
+ }
+ copy(fileContent, { format: 'text/plain' });
+ setIsCopied(true);
+ setTimeout(() => setIsCopied(false), 3000);
+ }, [fileContent]);
+
+ const displayType = useMemo(() => getDisplayType(fileType, fileName), [fileType, fileName]);
+ const sortedPages = useMemo(
+ () => (pages && pageRelevance ? sortPagesByRelevance(pages, pageRelevance) : pages),
+ [pages, pageRelevance],
+ );
+
+ const metaParts: string[] = [displayType];
+ if (relevance != null && relevance > 0) {
+ metaParts.push(`${localize('com_ui_relevance')}: ${Math.round(relevance * 100)}%`);
+ }
+ if (fileSize != null && fileSize > 0) {
+ metaParts.push(formatBytes(fileSize));
+ }
+ if (sortedPages && sortedPages.length > 0) {
+ metaParts.push(localize('com_file_pages', { pages: sortedPages.join(', ') }));
+ }
+
+ return (
+ <OGDialog open={open} onOpenChange={onOpenChange}>
+ <OGDialogContent
+ className="flex w-full max-w-4xl flex-col !overflow-hidden p-0"
+ showCloseButton={true}
+ >
+ <div className="shrink-0 px-6 pr-12 pt-6">
+ <OGDialogTitle className="truncate text-base">{fileName}</OGDialogTitle>
+ <div className="mt-0.5 flex items-center gap-3">
+ <OGDialogDescription className="min-w-0 truncate">
+ {metaParts.join(' · ')}
+ </OGDialogDescription>
+ {fileId && (
+ <button
+ type="button"
+ onClick={handleDownload}
+ className="inline-flex shrink-0 items-center gap-1 text-xs text-text-secondary transition-colors hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"
+ aria-label={`${localize('com_ui_download')} ${fileName}`}
+ >
+ <Download className="size-3" aria-hidden="true" />
+ {localize('com_ui_download')}
+ </button>
+ )}
+ </div>
+ </div>
+
+ <div className="relative min-h-0 flex-1 overflow-y-auto px-6 pb-6 pt-4">
+ {loading && (
+ <div className="flex h-60 items-center justify-center rounded-lg bg-surface-secondary">
+ <span className="shimmer text-sm text-text-secondary">
+ {localize('com_ui_loading')}
+ </span>
+ </div>
+ )}
+ {previewError && (
+ <div className="flex h-32 items-center justify-center rounded-lg bg-surface-secondary">
+ <span className="text-sm text-text-secondary">
+ {localize('com_ui_preview_unavailable')}
+ </span>
+ </div>
+ )}
+ {fileBlobUrl && (
+ <iframe
+ src={fileBlobUrl}
+ title={`${localize('com_ui_preview')}: ${fileName}`}
+ className="h-[70vh] w-full rounded-lg border border-border-light"
+ />
+ )}
+ {fileContent && (
+ <>
+ <div className="pointer-events-none sticky top-0 z-10 flex justify-end pr-1">
+ <CopyButton
+ isCopied={isCopied}
+ onClick={handleCopy}
+ iconOnly
+ label={localize('com_ui_copy')}
+ className="pointer-events-auto rounded-lg bg-surface-secondary"
+ />
+ </div>
+ <div className="-mt-8 rounded-lg bg-surface-secondary p-4">
+ <pre className="whitespace-pre-wrap break-words pr-8 font-mono text-sm leading-6 text-text-primary">
+ {fileContent}
+ </pre>
+ </div>
+ </>
+ )}
+ {!previewKind && !loading && (
+ <div className="flex h-32 items-center justify-center rounded-lg bg-surface-secondary">
+ <span className="text-sm text-text-secondary">
+ {localize('com_ui_preview_unavailable')}
+ </span>
+ </div>
+ )}
+ </div>
+ </OGDialogContent>
+ </OGDialog>
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/Files.tsx b/client/src/components/Chat/Messages/Content/Files.tsx
index 504e48e883..176507edc1 100644
--- a/client/src/components/Chat/Messages/Content/Files.tsx
+++ b/client/src/components/Chat/Messages/Content/Files.tsx
@@ -1,7 +1,7 @@
-import { useMemo, memo } from 'react';
+import { useMemo, useState, useCallback, memo } from 'react';
import type { TFile, TMessage } from 'librechat-data-provider';
import FileContainer from '~/components/Chat/Input/Files/FileContainer';
-import { getCachedPreview } from '~/utils';
+import FilePreviewDialog from './FilePreviewDialog';
import Image from './Image';
const Files = ({ message }: { message?: TMessage }) => {
@@ -10,26 +10,45 @@ const Files = ({ message }: { message?: TMessage }) => {
}, [message?.files]);
const otherFiles = useMemo(() => {
- return message?.files?.filter((file) => !(file.type?.startsWith('image/') === true)) || [];
+ return message?.files?.filter((file) => !file.type?.startsWith('image/')) || [];
}, [message?.files]);
+ const [selectedFile, setSelectedFile] = useState<Partial<TFile> | null>(null);
+
+ const handleClose = useCallback((open: boolean) => {
+ if (!open) {
+ setSelectedFile(null);
+ }
+ }, []);
+
return (
<>
{otherFiles.length > 0 &&
- otherFiles.map((file) => <FileContainer key={file.file_id} file={file as TFile} />)}
+ otherFiles.map((file) => (
+ <FileContainer
+ key={file.file_id}
+ file={file as TFile}
+ onClick={() => setSelectedFile(file)}
+ />
+ ))}
{imageFiles.length > 0 &&
- imageFiles.map((file) => {
- const cached = file.file_id ? getCachedPreview(file.file_id) : undefined;
- return (
- <Image
- key={file.file_id}
- width={file.width}
- height={file.height}
- altText={file.filename ?? 'Uploaded Image'}
- imagePath={cached ?? file.preview ?? file.filepath ?? ''}
- />
- );
- })}
+ imageFiles.map((file) => (
+ <Image
+ key={file.file_id}
+ imagePath={file.preview ?? file.filepath ?? ''}
+ height={file.height ?? 1920}
+ width={file.width ?? 1080}
+ altText={file.filename ?? 'Uploaded Image'}
+ />
+ ))}
+ <FilePreviewDialog
+ open={selectedFile !== null}
+ onOpenChange={handleClose}
+ fileName={selectedFile?.filename ?? ''}
+ fileId={selectedFile?.file_id}
+ fileType={selectedFile?.type ?? undefined}
+ fileSize={(selectedFile as TFile)?.bytes}
+ />
</>
);
};
diff --git a/client/src/components/Chat/Messages/Content/FinishedIcon.tsx b/client/src/components/Chat/Messages/Content/FinishedIcon.tsx
deleted file mode 100644
index 48660f8757..0000000000
--- a/client/src/components/Chat/Messages/Content/FinishedIcon.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-export default function FinishedIcon() {
- return (
- <div
- className="flex size-4 items-center justify-center rounded-full bg-brand-purple text-white"
- data-projection-id="162"
- >
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" fill="none" width="8" height="8">
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M7.66607 0.376042C8.01072 0.605806 8.10385 1.07146 7.87408 1.4161L3.54075 7.9161C3.40573 8.11863 3.18083 8.24304 2.93752 8.24979C2.69421 8.25654 2.46275 8.1448 2.31671 7.95008L0.150044 5.06119C-0.098484 4.72982 -0.0313267 4.25972 0.300044 4.01119C0.631415 3.76266 1.10152 3.82982 1.35004 4.16119L2.88068 6.20204L6.62601 0.584055C6.85577 0.239408 7.32142 0.146278 7.66607 0.376042Z"
- fill="currentColor"
- />
- </svg>
- </div>
- );
-}
diff --git a/client/src/components/Chat/Messages/Content/ImageGen.tsx b/client/src/components/Chat/Messages/Content/ImageGen.tsx
deleted file mode 100644
index 080a153fb5..0000000000
--- a/client/src/components/Chat/Messages/Content/ImageGen.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { useState } from 'react';
-import ProgressCircle from './ProgressCircle';
-import ProgressText from './ProgressText';
-import { useProgress } from '~/hooks';
-
-export default function ImageGen({
- initialProgress = 0.1,
- args = '',
-}: {
- initialProgress: number;
- args: string;
-}) {
- const progress = useProgress(initialProgress);
- const radius = 56.08695652173913;
- const circumference = 2 * Math.PI * radius;
-
- const offset = circumference - progress * circumference;
- const [showDetails, setShowDetails] = useState(false);
-
- // const [translate, setTranslate] = useState(0);
- // useEffect(() => {
- // const timer = setInterval(() => {
- // setTranslate((prevTranslate) => (prevTranslate + 1) % 360);
- // }, 20);
- // return () => clearInterval(timer);
- // }, []);
- // if (progress >= 1) {
- // return null;
- // }
-
- return (
- <div className="my-2.5 flex items-center gap-2.5">
- <div className="relative h-5 w-5 shrink-0">
- <div
- className="absolute left-0 top-0 flex h-full w-full items-center justify-center rounded-full bg-transparent text-white"
- style={{ opacity: 1, transform: 'none' }}
- data-projection-id="106"
- >
- <div>
- <svg
- xmlns="http://www.w3.org/2000/svg"
- xmlnsXlink="http://www.w3.org/1999/xlink"
- viewBox="0 0 20 20"
- width="20"
- height="20"
- style={{ width: '100%', height: '100%', transform: 'translate3d(0px, 0px, 0px)' }}
- preserveAspectRatio="xMidYMid meet"
- >
- <g className="move-up">
- <path
- fill="rgb(177,98,253)"
- fillOpacity="1"
- d="M11.812616,5.914505C11.535567,5.360465,10.744857,5.360465,10.467807,5.914505C9.369731,8.110632,8.271654,10.306758,7.173676,12.502885C6.923041,13.002725,7.286122,13.590845,7.844972,13.590845C10.041112,13.590845,12.237252,13.590845,14.433392,13.590845C14.992292,13.590845,15.355792,13.002725,15.105892,12.502885C14.007888,10.306758,12.909805,8.110632,11.812616,5.914505C11.812616,5.914505,11.812616,5.914505,11.812616,5.914505C11.812616,5.914505,11.812616,5.914505,11.812616,5.914505M7.216073,8.914505C6.939024,8.360465,6.148304,8.360465,5.871264,8.914505C5.274365,10.10828,4.677499,11.302055,4.080601,12.495835C3.83003,12.99568,4.193122,13.58379,4.751975,13.58379C5.946767,13.58379,7.14156,13.58379,8.336353,13.58379C8.895213,13.58379,9.258683,12.99568,9.008763,12.495835C8.411867,11.302055,7.81497,10.10828,7.216073,8.914505C7.216073,8.914505,7.216073,8.914505,7.216073,8.914505C7.216073,8.914505,7.216073,8.914505,7.216073,8.914505"
- />
- </g>
- <g
- style={{ display: 'block' }}
- transform="matrix(-1,0,0,-1,10,10)"
- opacity="1"
- className="moon-rise"
- >
- <g opacity="1" transform="matrix(1,0,0,1,3.75,5.5)">
- <path
- fill="rgb(177,98,253)"
- fillOpacity="1"
- d=" M2.660290002822876,2.2502501010894775 C2.7567598819732666,2.2502501010894775 2.850860118865967,2.241950035095215 2.9425699710845947,2.225330114364624 C3.034290075302124,2.208709955215454 3.1081299781799316,2.1867599487304688 3.164109945297241,2.1594600677490234 C3.239150047302246,2.120300054550171 3.305850028991699,2.100709915161133 3.364219903945923,2.100709915161133 C3.405900001525879,2.100709915161133 3.438659906387329,2.113770008087158 3.462480068206787,2.1398799419403076 C3.487489938735962,2.165990114212036 3.5,2.2009999752044678 3.5,2.2449100017547607 C3.5,2.2698400020599365 3.4958300590515137,2.2983200550079346 3.487489938735962,2.3303699493408203 C3.4803500175476074,2.362410068511963 3.468440055847168,2.3968300819396973 3.4517600536346436,2.433619976043701 C3.3803000450134277,2.5950300693511963 3.287990093231201,2.7410099506378174 3.1748299598693848,2.871570110321045 C3.0628700256347656,3.002120018005371 2.9348299503326416,3.1142799854278564 2.790709972381592,3.2080399990081787 C2.646589994430542,3.3029799461364746 2.4905600547790527,3.375380039215088 2.3226099014282227,3.425230026245117 C2.15585994720459,3.4750800132751465 1.9825600385665894,3.5 1.8027100563049316,3.5 C1.5430500507354736,3.5 1.3036400079727173,3.4554901123046875 1.0844800472259521,3.3664801120758057 C0.8653200268745422,3.2786500453948975 0.6741499900817871,3.1540400981903076 0.5109699964523315,2.9926199913024902 C0.34898999333381653,2.831209897994995 0.22333000600337982,2.641319990158081 0.1340000033378601,2.4229400157928467 C0.04467000067234039,2.2045600414276123 0,1.9660099744796753 0,1.7072700262069702 C0,1.4639699459075928 0.04645000025629997,1.2325400114059448 0.1393599957227707,1.012969970703125 C0.23226000368595123,0.7922199964523315 0.3626900017261505,0.5975800156593323 0.5306299924850464,0.4290440082550049 C0.6997600197792053,0.2593249976634979 0.8968899846076965,0.12877200543880463 1.121999979019165,0.03738600015640259 C1.1541600227355957,0.024329999461770058 1.1833399534225464,0.01483600027859211 1.2095500230789185,0.008901000022888184 C1.2369400262832642,0.0029670000076293945 1.2631399631500244,2.220446049250313e-16 1.288159966468811,2.220446049250313e-16 C1.335800051689148,2.220446049250313e-16 1.3733199834823608,0.014241999946534634 1.4007099866867065,0.042725998908281326 C1.4292999505996704,0.07121100276708603 1.4435900449752808,0.10681600123643875 1.4435900449752808,0.14954200387001038 C1.4435900449752808,0.1780260056257248 1.438230037689209,0.2076980024576187 1.4275100231170654,0.23855499923229218 C1.41798996925354,0.2682270109653473 1.404289960861206,0.2996779978275299 1.3864200115203857,0.3329089879989624 C1.3625999689102173,0.3768230080604553 1.3423500061035156,0.4302310049533844 1.3256800174713135,0.493133008480072 C1.309000015258789,0.5548499822616577 1.296489953994751,0.6225000023841858 1.288159966468811,0.6960800290107727 C1.2798199653625488,0.7684800028800964 1.2756500244140625,0.8414700031280518 1.2756500244140625,0.9150599837303162 C1.2756500244140625,1.1215699911117554 1.3072099685668945,1.3073099851608276 1.3703399896621704,1.4722800254821777 C1.4346599578857422,1.6372499465942383 1.5269700288772583,1.7778899669647217 1.6472699642181396,1.8941999673843384 C1.7675700187683105,2.0093300342559814 1.9128799438476562,2.097749948501587 2.083209991455078,2.1594600677490234 C2.2547199726104736,2.2199900150299072 2.44707989692688,2.2502501010894775 2.660290002822876,2.2502501010894775 C2.660290002822876,2.2502501010894775 2.660290002822876,2.2502501010894775 2.660290002822876,2.2502501010894775 C2.660290002822876,2.2502501010894775 2.660290002822876,2.2502501010894775 2.660290002822876,2.2502501010894775"
- />
- </g>
- </g>
- </svg>
- </div>
- <ProgressCircle radius={radius} circumference={circumference} offset={offset} />
- </div>
- </div>
- <ProgressText
- progress={progress}
- onClick={() => setShowDetails((prev) => !prev)}
- inProgressText="Creating Image"
- finishedText="Finished."
- hasInput={false}
- />
- </div>
- );
-}
diff --git a/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx b/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx
index 1c5369955d..2a47af30e4 100644
--- a/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx
+++ b/client/src/components/Chat/Messages/Content/MarkdownComponents.tsx
@@ -2,9 +2,8 @@ import React, { memo, useMemo, useRef, useEffect } from 'react';
import { useRecoilValue } from 'recoil';
import { useToastContext } from '@librechat/client';
import { PermissionTypes, Permissions, apiBaseUrl } from 'librechat-data-provider';
-import MermaidErrorBoundary from '~/components/Messages/Content/MermaidErrorBoundary';
+import Mermaid, { MermaidErrorBoundary } from '~/components/Messages/Content/Mermaid';
import CodeBlock from '~/components/Messages/Content/CodeBlock';
-import Mermaid from '~/components/Messages/Content/Mermaid';
import useHasAccess from '~/hooks/Roles/useHasAccess';
import { useFileDownload } from '~/data-provider';
import { useCodeBlockContext } from '~/Providers';
diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx
index d0c7d2af37..1b4b9057f6 100644
--- a/client/src/components/Chat/Messages/Content/Part.tsx
+++ b/client/src/components/Chat/Messages/Content/Part.tsx
@@ -1,3 +1,4 @@
+import { memo } from 'react';
import {
Tools,
Constants,
@@ -6,17 +7,8 @@ import {
imageGenTools,
isImageVisionTool,
} from 'librechat-data-provider';
-import { memo } from 'react';
import type { TMessageContentParts, TAttachment } from 'librechat-data-provider';
-import {
- OpenAIImageGen,
- ExecuteCode,
- AgentUpdate,
- EmptyText,
- Reasoning,
- Summary,
- Text,
-} from './Parts';
+import { ImageGen, ExecuteCode, AgentUpdate, EmptyText, Reasoning, Summary, Text } from './Parts';
import { ErrorMessage } from './MessageContent';
import RetrievalCall from './RetrievalCall';
import { getCachedPreview } from '~/utils';
@@ -25,7 +17,6 @@ import CodeAnalyze from './CodeAnalyze';
import Container from './Container';
import WebSearch from './WebSearch';
import ToolCall from './ToolCall';
-import ImageGen from './ImageGen';
import Image from './Image';
type PartProps = {
@@ -138,7 +129,7 @@ const Part = memo(function Part({
isSubmitting={isSubmitting}
output={toolCall.output ?? ''}
initialProgress={toolCall.progress ?? 0.1}
- args={typeof toolCall.args === 'string' ? toolCall.args : ''}
+ args={toolCall.args}
/>
);
} else if (
@@ -148,7 +139,7 @@ const Part = memo(function Part({
toolCall.name === 'gemini_image_gen')
) {
return (
- <OpenAIImageGen
+ <ImageGen
initialProgress={toolCall.progress ?? 0.1}
isSubmitting={isSubmitting}
toolName={toolCall.name}
@@ -167,14 +158,17 @@ const Part = memo(function Part({
isLast={isLast}
/>
);
- } else if (isToolCall && toolCall.name?.startsWith(Constants.LC_TRANSFER_TO_)) {
+ } else if (isToolCall && (toolCall.name === 'file_search' || toolCall.name === 'retrieval')) {
return (
- <AgentHandoff
- args={toolCall.args ?? ''}
- name={toolCall.name || ''}
- output={toolCall.output ?? ''}
+ <RetrievalCall
+ initialProgress={toolCall.progress ?? 0.1}
+ isSubmitting={isSubmitting}
+ output={toolCall.output ?? undefined}
+ attachments={attachments}
/>
);
+ } else if (isToolCall && toolCall.name?.startsWith(Constants.LC_TRANSFER_TO_)) {
+ return <AgentHandoff args={toolCall.args ?? ''} name={toolCall.name || ''} />;
} else if (isToolCall) {
return (
<ToolCall
@@ -185,7 +179,6 @@ const Part = memo(function Part({
isSubmitting={isSubmitting}
attachments={attachments}
auth={toolCall.auth}
- expires_at={toolCall.expires_at}
isLast={isLast}
/>
);
@@ -203,7 +196,12 @@ const Part = memo(function Part({
toolCall.type === ToolCallTypes.FILE_SEARCH
) {
return (
- <RetrievalCall initialProgress={toolCall.progress ?? 0.1} isSubmitting={isSubmitting} />
+ <RetrievalCall
+ initialProgress={toolCall.progress ?? 0.1}
+ isSubmitting={isSubmitting}
+ output={(toolCall as { output?: string }).output}
+ attachments={attachments}
+ />
);
} else if (
toolCall.type === ToolCallTypes.FUNCTION &&
@@ -214,6 +212,9 @@ const Part = memo(function Part({
<ImageGen
initialProgress={toolCall.progress ?? 0.1}
args={toolCall.function.arguments as string}
+ isSubmitting={isSubmitting}
+ toolName={toolCall.function.name}
+ output={toolCall.function.output ?? ''}
/>
);
} else if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {
diff --git a/client/src/components/Chat/Messages/Content/Parts/CodeWindowHeader.tsx b/client/src/components/Chat/Messages/Content/Parts/CodeWindowHeader.tsx
new file mode 100644
index 0000000000..a65fe5ca5f
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/CodeWindowHeader.tsx
@@ -0,0 +1,35 @@
+import { useRef, useState, useCallback, useEffect } from 'react';
+import copy from 'copy-to-clipboard';
+import CopyButton from '~/components/Messages/Content/CopyButton';
+import LangIcon from '~/components/Messages/Content/LangIcon';
+import { useLocalize } from '~/hooks';
+
+interface CodeWindowHeaderProps {
+ language: string;
+ code: string;
+}
+
+export default function CodeWindowHeader({ language, code }: CodeWindowHeaderProps) {
+ const localize = useLocalize();
+ const [isCopied, setIsCopied] = useState(false);
+ const timerRef = useRef<ReturnType<typeof setTimeout>>();
+
+ useEffect(() => () => clearTimeout(timerRef.current), []);
+
+ const handleCopy = useCallback(() => {
+ setIsCopied(true);
+ copy(code.trim(), { format: 'text/plain' });
+ clearTimeout(timerRef.current);
+ timerRef.current = setTimeout(() => setIsCopied(false), 3000);
+ }, [code]);
+
+ return (
+ <div className="flex items-center justify-between bg-surface-primary-alt px-1.5 py-1.5 font-sans text-xs text-text-secondary dark:bg-transparent">
+ <span className="flex items-center gap-1.5 text-xs font-medium">
+ <LangIcon lang={language} className="size-3.5 shrink-0" />
+ {language}
+ </span>
+ <CopyButton isCopied={isCopied} onClick={handleCopy} label={localize('com_ui_copy_code')} />
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx
index 2f14ac0f13..20298f5c0b 100644
--- a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx
@@ -1,9 +1,10 @@
-import React, { useMemo, useState, useRef, useEffect } from 'react';
+import React, { useMemo, useState, useEffect, useCallback, useRef } from 'react';
import { useRecoilValue } from 'recoil';
+import { SquareTerminal } from 'lucide-react';
import type { TAttachment } from 'librechat-data-provider';
import ProgressText from '~/components/Chat/Messages/Content/ProgressText';
-import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
-import { useProgress, useLocalize } from '~/hooks';
+import { useProgress, useLocalize, useExpandCollapse } from '~/hooks';
+import CodeWindowHeader from './CodeWindowHeader';
import { AttachmentGroup } from './Attachment';
import Stdout from './Stdout';
import { cn } from '~/utils';
@@ -14,8 +15,115 @@ interface ParsedArgs {
code?: string;
}
-export function useParseArgs(args?: string): ParsedArgs | null {
+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<LowlightModule> | null = null;
+let lowlightModule: LowlightModule | null = null;
+
+function loadLowlight(): Promise<LowlightModule> {
+ 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<React.ReactNode[] | null>(() => {
+ 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<string, unknown>): ParsedArgs | null {
return useMemo(() => {
+ if (typeof args === 'object' && args !== null) {
+ return { lang: String(args.lang ?? ''), code: String(args.code ?? '') };
+ }
let parsedArgs: ParsedArgs | string | undefined | null = args;
try {
parsedArgs = JSON.parse(args || '');
@@ -44,6 +152,8 @@ export function useParseArgs(args?: string): ParsedArgs | null {
}, [args]);
}
+const ERROR_PATTERNS = /^(Traceback|Error:|Exception:|.*Error:)/m;
+
export default function ExecuteCode({
isSubmitting,
initialProgress = 0.1,
@@ -53,170 +163,88 @@ export default function ExecuteCode({
}: {
initialProgress: number;
isSubmitting: boolean;
- args?: string;
+ args?: string | Record<string, unknown>;
output?: string;
attachments?: TAttachment[];
}) {
const localize = useLocalize();
const hasOutput = output.length > 0;
- const outputRef = useRef<string>(output);
- const codeContentRef = useRef<HTMLDivElement>(null);
- const [isAnimating, setIsAnimating] = useState(false);
- const showAnalysisCode = useRecoilValue(store.showCode);
- const [showCode, setShowCode] = useState(showAnalysisCode);
- const [contentHeight, setContentHeight] = useState<number | undefined>(0);
-
- const prevShowCodeRef = useRef<boolean>(showCode);
- const { lang = 'py', code } = useParseArgs(args) ?? ({} as ParsedArgs);
- const progress = useProgress(initialProgress);
-
- useEffect(() => {
- if (output !== outputRef.current) {
- outputRef.current = output;
-
- if (showCode && codeContentRef.current) {
- setTimeout(() => {
- if (codeContentRef.current) {
- const newHeight = codeContentRef.current.scrollHeight;
- setContentHeight(newHeight);
- }
- }, 10);
- }
- }
- }, [output, showCode]);
-
- useEffect(() => {
- if (showCode !== prevShowCodeRef.current) {
- prevShowCodeRef.current = showCode;
-
- if (showCode && codeContentRef.current) {
- setIsAnimating(true);
- requestAnimationFrame(() => {
- if (codeContentRef.current) {
- const height = codeContentRef.current.scrollHeight;
- setContentHeight(height);
- }
-
- const timer = setTimeout(() => {
- setIsAnimating(false);
- }, 500);
-
- return () => clearTimeout(timer);
- });
- } else if (!showCode) {
- setIsAnimating(true);
- setContentHeight(0);
-
- const timer = setTimeout(() => {
- setIsAnimating(false);
- }, 500);
+ const autoExpand = useRecoilValue(store.autoExpandTools);
- return () => clearTimeout(timer);
- }
- }
- }, [showCode]);
+ 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 (!codeContentRef.current) {
- return;
+ if (autoExpand && hasContent) {
+ setShowCode(true);
}
+ }, [autoExpand, hasContent]);
+ const progress = useProgress(initialProgress);
- const resizeObserver = new ResizeObserver((entries) => {
- if (showCode && !isAnimating) {
- for (const entry of entries) {
- if (entry.target === codeContentRef.current) {
- setContentHeight(entry.contentRect.height);
- }
- }
- }
- });
+ const highlighted = useLazyHighlight(code, lang);
- resizeObserver.observe(codeContentRef.current);
+ const outputHasError = useMemo(() => ERROR_PATTERNS.test(output), [output]);
- return () => {
- resizeObserver.disconnect();
- };
- }, [showCode, isAnimating]);
+ const toggleCode = useCallback(() => setShowCode((prev) => !prev), [setShowCode]);
const cancelled = !isSubmitting && progress < 1;
return (
<>
- <div className="relative my-2.5 flex size-5 shrink-0 items-center gap-2.5">
+ <div className="relative my-1.5 flex size-5 shrink-0 items-center gap-2.5">
<ProgressText
progress={progress}
- onClick={() => setShowCode((prev) => !prev)}
+ onClick={toggleCode}
inProgressText={localize('com_ui_analyzing')}
finishedText={
cancelled ? localize('com_ui_cancelled') : localize('com_ui_analyzing_finished')
}
+ icon={
+ <SquareTerminal
+ className={cn(
+ 'size-4 shrink-0 text-text-secondary',
+ progress < 1 && !cancelled && 'animate-pulse',
+ )}
+ aria-hidden="true"
+ />
+ }
hasInput={!!code?.length}
isExpanded={showCode}
error={cancelled}
/>
</div>
- <div
- className="relative mb-2"
- style={{
- height: showCode ? contentHeight : 0,
- overflow: 'hidden',
- transition:
- 'height 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- opacity: showCode ? 1 : 0,
- transformOrigin: 'top',
- willChange: 'height, opacity',
- perspective: '1000px',
- backfaceVisibility: 'hidden',
- WebkitFontSmoothing: 'subpixel-antialiased',
- }}
- >
- <div
- className={cn(
- 'code-analyze-block mt-0.5 overflow-hidden rounded-xl bg-surface-primary',
- showCode && 'shadow-lg',
- )}
- ref={codeContentRef}
- style={{
- transform: showCode ? 'translateY(0) scale(1)' : 'translateY(-8px) scale(0.98)',
- opacity: showCode ? 1 : 0,
- transition:
- 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- }}
- >
- {showCode && (
- <div
- style={{
- transform: showCode ? 'translateY(0)' : 'translateY(-4px)',
- opacity: showCode ? 1 : 0,
- transition:
- 'transform 0.35s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.35s cubic-bezier(0.16, 1, 0.3, 1)',
- }}
- >
- <MarkdownLite
- content={code ? `\`\`\`${lang}\n${code}\n\`\`\`` : ''}
- codeExecution={false}
- />
- </div>
- )}
- {hasOutput && (
- <div
- className={cn(
- 'bg-surface-tertiary p-4 text-xs',
- showCode ? 'border-t border-surface-primary-contrast' : '',
- )}
- style={{
- transform: showCode ? 'translateY(0)' : 'translateY(-6px)',
- opacity: showCode ? 1 : 0,
- transition:
- 'transform 0.45s cubic-bezier(0.16, 1, 0.3, 1) 0.05s, opacity 0.45s cubic-bezier(0.19, 1, 0.22, 1) 0.05s',
- boxShadow: showCode ? '0 -1px 0 rgba(0,0,0,0.05)' : 'none',
- }}
- >
- <div className="prose flex flex-col-reverse">
- <Stdout output={output} />
+ <div style={expandStyle}>
+ <div className="overflow-hidden" ref={expandRef}>
+ <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">
+ {code && <CodeWindowHeader language={lang} code={code} />}
+ {code && (
+ <pre className="max-h-[300px] overflow-auto bg-surface-chat p-4 font-mono text-xs dark:bg-surface-primary-alt">
+ <code className={`hljs language-${lang} !whitespace-pre`}>{highlighted}</code>
+ </pre>
+ )}
+ {hasOutput && (
+ <div
+ className={cn(
+ 'bg-surface-primary-alt p-4 text-xs dark:bg-transparent',
+ code && 'border-t border-border-light',
+ )}
+ >
+ <div className="mb-1.5 text-[10px] font-medium uppercase tracking-wide text-text-secondary">
+ {localize('com_ui_output')}
+ </div>
+ <div
+ className={cn(
+ 'max-h-[200px] overflow-auto',
+ outputHasError ? 'text-red-600 dark:text-red-400' : 'text-text-primary',
+ )}
+ >
+ <Stdout output={output} />
+ </div>
</div>
- </div>
- )}
+ )}
+ </div>
</div>
</div>
{attachments && attachments.length > 0 && <AttachmentGroup attachments={attachments} />}
diff --git a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx
index bdce6d3209..f47c9c56c3 100644
--- a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx
@@ -1,12 +1,28 @@
-import { useState, useEffect, useRef } from 'react';
+import { useState, useEffect, useRef, useCallback } from 'react';
import { PixelCard } from '@librechat/client';
import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';
+import { ToolIcon, isError } from '~/components/Chat/Messages/Content/ToolOutput';
import Image from '~/components/Chat/Messages/Content/Image';
+import { useProgress, useLocalize } from '~/hooks';
import ProgressText from './ProgressText';
-import { cn } from '~/utils';
-
-const IMAGE_MAX_H = 'max-h-[45vh]' as const;
-const IMAGE_FULL_H = 'h-[45vh]' as const;
+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;
+}
export default function OpenAIImageGen({
initialProgress = 0.1,
@@ -17,49 +33,102 @@ export default function OpenAIImageGen({
attachments,
}: {
initialProgress: number;
- isSubmitting: boolean;
- toolName: string;
+ isSubmitting?: boolean;
+ toolName?: string;
args: string | Record<string, unknown>;
output?: string | null;
attachments?: TAttachment[];
}) {
- const [progress, setProgress] = useState(initialProgress);
+ 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;
const intervalRef = useRef<NodeJS.Timeout | null>(null);
- const error =
- typeof output === 'string' && output.toLowerCase().includes('error processing tool');
+ const hasError = typeof output === 'string' && isError(output);
- const cancelled = (!isSubmitting && initialProgress < 1) || error === true;
+ /**
+ * 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);
+ let width: number | undefined;
+ let height: number | undefined;
let quality: 'low' | 'medium' | 'high' = 'high';
- // Parse args if it's a string
- let parsedArgs;
+ let parsedArgs: Record<string, unknown> = {};
try {
parsedArgs = typeof _args === 'string' ? JSON.parse(_args) : _args;
- } catch (error) {
- console.error('Error parsing args:', error);
+ } catch {
parsedArgs = {};
}
- if (parsedArgs && typeof parsedArgs.quality === 'string') {
- const q = parsedArgs.quality.toLowerCase();
- if (q === 'low' || q === 'medium' || q === 'high') {
- quality = q;
+ 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;
+ }
}
+ } catch {
+ width = undefined;
+ height = undefined;
}
const attachment = attachments?.[0];
const {
+ width: imageWidth,
+ height: imageHeight,
filepath = null,
filename = '',
- width: imgWidth,
- height: imgHeight,
} = (attachment as TFile & TAttachmentMetadata) || {};
+ 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]);
+
useEffect(() => {
+ if (!isAgentStyle) {
+ return;
+ }
+
if (isSubmitting) {
- setProgress(initialProgress);
+ setAgentProgress(initialProgress);
if (intervalRef.current) {
clearInterval(intervalRef.current);
@@ -71,7 +140,6 @@ export default function OpenAIImageGen({
} else if (quality === 'high') {
baseDuration = 50000;
}
- // adding some jitter (±30% of base)
const jitter = Math.floor(baseDuration * 0.3);
const totalDuration = Math.floor(Math.random() * jitter) + baseDuration;
const updateInterval = 200;
@@ -83,7 +151,7 @@ export default function OpenAIImageGen({
if (currentStep >= totalSteps) {
clearInterval(intervalRef.current as NodeJS.Timeout);
- setProgress(0.9);
+ setAgentProgress(0.9);
} else {
const progressRatio = currentStep / totalSteps;
let mapRatio: number;
@@ -95,7 +163,7 @@ export default function OpenAIImageGen({
}
const scaledProgress = 0.1 + mapRatio * 0.8;
- setProgress(scaledProgress);
+ setAgentProgress(scaledProgress);
}
}, updateInterval);
}
@@ -105,35 +173,81 @@ export default function OpenAIImageGen({
clearInterval(intervalRef.current);
}
};
- }, [isSubmitting, initialProgress, quality]);
+ }, [isSubmitting, initialProgress, quality, isAgentStyle]);
useEffect(() => {
+ if (!isAgentStyle) {
+ return;
+ }
+
if (initialProgress >= 1 || cancelled) {
- setProgress(initialProgress);
+ setAgentProgress(initialProgress);
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
}
- }, [initialProgress, cancelled]);
+ }, [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;
return (
<>
- <div className="relative my-2.5 flex size-5 shrink-0 items-center gap-2.5">
+ <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} />
<ProgressText progress={progress} error={cancelled} toolName={toolName} />
</div>
- <div className={cn('relative mb-2 flex w-full max-w-lg justify-start', IMAGE_MAX_H)}>
- <div className={cn('overflow-hidden', progress < 1 ? [IMAGE_FULL_H, 'w-full'] : 'w-auto')}>
- {progress < 1 && <PixelCard variant="default" progress={progress} randomness={0.6} />}
- <Image
- width={imgWidth}
- args={parsedArgs}
- height={imgHeight}
- altText={filename}
- imagePath={filepath ?? ''}
- className={progress < 1 ? 'invisible absolute' : ''}
- />
+ {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>
</div>
- </div>
+ )}
</>
);
}
diff --git a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx
index 85e8566f6a..c0c6b128f3 100644
--- a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx
@@ -1,20 +1,21 @@
+import { AGENT_STYLE_TOOLS } from '.';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
export default function ProgressText({
progress,
error,
- toolName = 'image_gen_oai',
+ toolName = '',
}: {
progress: number;
error?: boolean;
- toolName: string;
+ toolName?: string;
}) {
const localize = useLocalize();
const getText = () => {
if (error) {
- return localize('com_ui_error');
+ return localize('com_ui_image_gen_failed');
}
if (toolName === 'image_edit_oai') {
@@ -33,7 +34,6 @@ export default function ProgressText({
return localize('com_ui_getting_started');
}
- // Gemini image generation
if (toolName === 'gemini_image_gen') {
if (progress >= 1) {
return localize('com_ui_image_created');
@@ -50,30 +50,38 @@ export default function ProgressText({
return localize('com_ui_getting_started');
}
+ if (AGENT_STYLE_TOOLS.has(toolName)) {
+ if (progress >= 1) {
+ return localize('com_ui_image_created');
+ }
+ if (progress >= 0.7) {
+ return localize('com_ui_final_touch');
+ }
+ if (progress >= 0.5) {
+ return localize('com_ui_adding_details');
+ }
+ if (progress >= 0.3) {
+ return localize('com_ui_creating_image');
+ }
+ return localize('com_ui_getting_started');
+ }
+
if (progress >= 1) {
return localize('com_ui_image_created');
}
- if (progress >= 0.7) {
- return localize('com_ui_final_touch');
- }
- if (progress >= 0.5) {
- return localize('com_ui_adding_details');
- }
- if (progress >= 0.3) {
- return localize('com_ui_creating_image');
- }
- return localize('com_ui_getting_started');
+ return localize('com_ui_generating_image');
};
const text = getText();
return (
- <div
+ <span
className={cn(
- 'progress-text-content pointer-events-none absolute left-0 top-0 inline-flex w-full items-center gap-2 overflow-visible whitespace-nowrap',
+ 'progress-text-content tool-status-text whitespace-nowrap font-medium',
+ progress < 1 && 'shimmer',
)}
>
- <span className={`font-medium ${progress < 1 ? 'shimmer' : ''}`}>{text}</span>
- </div>
+ {text}
+ </span>
);
}
diff --git a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/index.ts b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/index.ts
index c5f60526f5..5841d574cb 100644
--- a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/index.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/index.ts
@@ -1 +1,4 @@
+export { default as ImageGen } from './OpenAIImageGen';
export { default as OpenAIImageGen } from './OpenAIImageGen';
+
+export const AGENT_STYLE_TOOLS = new Set(['image_gen_oai', 'image_edit_oai', 'gemini_image_gen']);
diff --git a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
index 44d646fcd8..6c059af06c 100644
--- a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
@@ -1,11 +1,11 @@
import { memo, useMemo, useState, useCallback, useRef, useId } from 'react';
-import { useAtom } from 'jotai';
-import type { MouseEvent, FocusEvent } from 'react';
+import { useAtomValue } from 'jotai';
import { ContentTypes } from 'librechat-data-provider';
+import type { MouseEvent, FocusEvent } from 'react';
import { ThinkingContent, ThinkingButton, FloatingThinkingBar } from './Thinking';
+import { useLocalize, useExpandCollapse } from '~/hooks';
import { showThinkingAtom } from '~/store/showThinking';
import { useMessageContext } from '~/Providers';
-import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
type ReasoningProps = {
@@ -38,10 +38,11 @@ type ReasoningProps = {
const Reasoning = memo(({ reasoning, isLast }: ReasoningProps) => {
const contentId = useId();
const localize = useLocalize();
- const [showThinking] = useAtom(showThinkingAtom);
+ const showThinking = useAtomValue(showThinkingAtom);
const [isExpanded, setIsExpanded] = useState(showThinking);
const [isBarVisible, setIsBarVisible] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);
const { isSubmitting, isLatestMessage, nextType } = useMessageContext();
// Strip <think> tags from the reasoning content (modern format)
@@ -113,15 +114,10 @@ const Reasoning = memo(({ reasoning, isLast }: ReasoningProps) => {
role="group"
aria-label={label}
aria-hidden={!isExpanded || undefined}
- className={cn(
- 'grid transition-all duration-300 ease-out',
- nextType !== ContentTypes.THINK && isExpanded && 'mb-4',
- )}
- style={{
- gridTemplateRows: isExpanded ? '1fr' : '0fr',
- }}
+ className={cn(nextType !== ContentTypes.THINK && isExpanded && 'mb-4')}
+ style={expandStyle}
>
- <div className="relative overflow-hidden">
+ <div className="relative overflow-hidden" ref={expandRef}>
<ThinkingContent>{reasoningText}</ThinkingContent>
<FloatingThinkingBar
isVisible={isBarVisible && isExpanded}
diff --git a/client/src/components/Chat/Messages/Content/Parts/Stdout.tsx b/client/src/components/Chat/Messages/Content/Parts/Stdout.tsx
index 562d85489a..93b28d8341 100644
--- a/client/src/components/Chat/Messages/Content/Parts/Stdout.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/Stdout.tsx
@@ -1,26 +1,25 @@
-import React, { useMemo } from 'react';
+import { useMemo } from 'react';
interface StdoutProps {
output?: string;
}
-const Stdout: React.FC<StdoutProps> = ({ output = '' }) => {
+export default function Stdout({ output = '' }: StdoutProps) {
const processedContent = useMemo(() => {
if (!output) {
return '';
}
-
const parts = output.split('Generated files:');
return parts[0].trim();
}, [output]);
+ if (!processedContent) {
+ return null;
+ }
+
return (
- processedContent && (
- <pre className="shrink-0">
- <div className="text-text-primary">{processedContent}</div>
- </pre>
- )
+ <pre className="shrink-0 whitespace-pre-wrap break-words font-mono text-text-primary">
+ {processedContent}
+ </pre>
);
-};
-
-export default Stdout;
+}
diff --git a/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx b/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx
index 7641738c15..39240af3d0 100644
--- a/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx
@@ -1,11 +1,11 @@
import { useState, useMemo, memo, useCallback, useRef, useId, type MouseEvent } from 'react';
import { useAtomValue } from 'jotai';
-import { Clipboard, CheckMark, TooltipAnchor } from '@librechat/client';
import { Lightbulb, ChevronDown, ChevronUp } from 'lucide-react';
+import { Clipboard, CheckMark, TooltipAnchor } from '@librechat/client';
import type { FocusEvent, FC } from 'react';
+import { useLocalize, useExpandCollapse } from '~/hooks';
import { showThinkingAtom } from '~/store/showThinking';
import { fontSizeAtom } from '~/store/fontSize';
-import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
/**
@@ -18,7 +18,7 @@ export const ThinkingContent: FC<{
const fontSize = useAtomValue(fontSizeAtom);
return (
- <div className="relative rounded-3xl border border-border-medium bg-surface-tertiary p-4 pb-10 text-text-secondary">
+ <div className="relative rounded-lg border border-border-light bg-surface-secondary p-3 pb-8 text-text-secondary">
<p className={cn('whitespace-pre-wrap leading-[26px]', fontSize)}>{children}</p>
</div>
);
@@ -184,7 +184,7 @@ export const FloatingThinkingBar = memo(
aria-expanded={isExpanded}
aria-controls={contentId}
className={cn(
- 'flex items-center justify-center rounded-lg bg-surface-secondary p-1.5 text-text-secondary-alt shadow-sm',
+ 'flex items-center justify-center rounded p-1.5 text-text-tertiary',
'hover:bg-surface-hover hover:text-text-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',
)}
@@ -207,7 +207,7 @@ export const FloatingThinkingBar = memo(
onClick={handleCopy}
aria-label={copyTooltip}
className={cn(
- 'flex items-center justify-center rounded-lg bg-surface-secondary p-1.5 text-text-secondary-alt shadow-sm',
+ 'flex items-center justify-center rounded p-1.5 text-text-tertiary',
'hover:bg-surface-hover hover:text-text-primary',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',
)}
@@ -248,6 +248,7 @@ const Thinking: React.ElementType = memo(({ children }: { children: React.ReactN
const [isBarVisible, setIsBarVisible] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const contentId = useId();
+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);
const handleClick = useCallback((e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
@@ -311,12 +312,10 @@ const Thinking: React.ElementType = memo(({ children }: { children: React.ReactN
role="group"
aria-label={label}
aria-hidden={!isExpanded || undefined}
- className={cn('grid transition-all duration-300 ease-out', isExpanded && 'mb-8')}
- style={{
- gridTemplateRows: isExpanded ? '1fr' : '0fr',
- }}
+ className={cn(isExpanded && 'mb-8')}
+ style={expandStyle}
>
- <div className="relative overflow-hidden">
+ <div className="relative overflow-hidden" ref={expandRef}>
<ThinkingContent>{children}</ThinkingContent>
<FloatingThinkingBar
isVisible={isBarVisible && isExpanded}
diff --git a/client/src/components/Chat/Messages/Content/ProgressText.tsx b/client/src/components/Chat/Messages/Content/ProgressText.tsx
index b10edf120d..60a1e651ae 100644
--- a/client/src/components/Chat/Messages/Content/ProgressText.tsx
+++ b/client/src/components/Chat/Messages/Content/ProgressText.tsx
@@ -1,8 +1,6 @@
+import { ChevronDown } from 'lucide-react';
import * as Popover from '@radix-ui/react-popover';
-import { Spinner } from '@librechat/client';
-import { ChevronDown, ChevronUp } from 'lucide-react';
import CancelledIcon from './CancelledIcon';
-import FinishedIcon from './FinishedIcon';
import { cn } from '~/utils';
const wrapperClass =
@@ -16,7 +14,6 @@ const Wrapper = ({ popover, children }: { popover: boolean; children: React.Reac
<div
className="progress-text-content absolute left-0 top-0 overflow-visible whitespace-nowrap"
style={{ opacity: 1, transform: 'none' }}
- data-projection-id="78"
>
{children}
</div>
@@ -30,7 +27,6 @@ const Wrapper = ({ popover, children }: { popover: boolean; children: React.Reac
<div
className="progress-text-content absolute left-0 top-0 overflow-visible whitespace-nowrap"
style={{ opacity: 1, transform: 'none' }}
- data-projection-id="78"
>
{children}
</div>
@@ -44,6 +40,9 @@ export default function ProgressText({
inProgressText,
finishedText,
authText,
+ icon: iconProp,
+ subtitle,
+ errorSuffix,
hasInput = true,
popover = false,
isExpanded = false,
@@ -54,6 +53,9 @@ export default function ProgressText({
inProgressText: string;
finishedText: string;
authText?: string;
+ icon?: React.ReactNode;
+ subtitle?: string;
+ errorSuffix?: string;
hasInput?: boolean;
popover?: boolean;
isExpanded?: boolean;
@@ -70,13 +72,10 @@ export default function ProgressText({
};
const getIcon = () => {
- if (error) {
+ if (error && !errorSuffix) {
return <CancelledIcon />;
}
- if (progress < 1) {
- return <Spinner />;
- }
- return <FinishedIcon />;
+ return iconProp ?? null;
};
const text = getText();
@@ -89,20 +88,30 @@ export default function ProgressText({
type="button"
className={cn(
'inline-flex w-full items-center gap-2',
- hasInput ? '' : 'pointer-events-none',
+ hasInput
+ ? 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy'
+ : 'pointer-events-none',
)}
disabled={!hasInput}
+ tabIndex={hasInput ? 0 : -1}
onClick={hasInput ? onClick : undefined}
aria-expanded={hasInput ? isExpanded : undefined}
>
{icon}
- <span className={showShimmer ? 'shimmer' : ''}>{text}</span>
- {hasInput &&
- (isExpanded ? (
- <ChevronUp className="size-4 shrink-0 translate-y-[1px]" aria-hidden="true" />
- ) : (
- <ChevronDown className="size-4 shrink-0 translate-y-[1px]" aria-hidden="true" />
- ))}
+ <span className={cn(showShimmer ? 'shimmer' : '', 'font-medium')}>{text}</span>
+ {subtitle && <span className="font-normal text-text-secondary">{subtitle}</span>}
+ {errorSuffix && (
+ <span className="font-normal text-red-600 dark:text-red-400">— {errorSuffix}</span>
+ )}
+ {hasInput && (
+ <ChevronDown
+ className={cn(
+ 'size-4 shrink-0 translate-y-[1px] transition-transform duration-200 ease-out',
+ isExpanded && 'rotate-180',
+ )}
+ aria-hidden="true"
+ />
+ )}
</button>
</Wrapper>
);
diff --git a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx b/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
index 4c2465f3c3..f367f07feb 100644
--- a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
+++ b/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
@@ -1,52 +1,475 @@
-import ProgressCircle from './ProgressCircle';
-import InProgressCall from './InProgressCall';
-import RetrievalIcon from './RetrievalIcon';
-import CancelledIcon from './CancelledIcon';
+import { useMemo, useState, useEffect, useCallback } from 'react';
+import { useRecoilValue } from 'recoil';
+import { Tools } from 'librechat-data-provider';
+import { TooltipAnchor } from '@librechat/client';
+import { FileText, FileSpreadsheet, FileCode, FileImage, File } from 'lucide-react';
+import type { TAttachment, TFile } from 'librechat-data-provider';
+import { useLocalize, useProgress, useExpandCollapse } from '~/hooks';
+import { ToolIcon, OutputRenderer, isError } from './ToolOutput';
+import FilePreviewDialog from './FilePreviewDialog';
+import { sortPagesByRelevance, cn } from '~/utils';
+import { useGetFiles } from '~/data-provider';
import ProgressText from './ProgressText';
-import FinishedIcon from './FinishedIcon';
-import { useProgress } from '~/hooks';
+import store from '~/store';
+
+interface FileSource {
+ fileId: string;
+ fileName: string;
+ relevance: number;
+ content: string;
+ pages: number[];
+ pageRelevance: Record<number, number>;
+ fileType?: string;
+ fileBytes?: number;
+ metadata?: Record<string, unknown>;
+}
+
+function extractFileSources(attachments?: TAttachment[]): FileSource[] {
+ if (!attachments) {
+ return [];
+ }
+
+ const deduped = new Map<string, FileSource>();
+
+ for (const att of attachments) {
+ if (att.type !== Tools.file_search || !att[Tools.file_search]) {
+ continue;
+ }
+
+ const raw = att[Tools.file_search] as { sources?: FileSource[] };
+ if (!raw.sources) {
+ continue;
+ }
+
+ for (const source of raw.sources) {
+ const key = source.fileId;
+ const existing = deduped.get(key);
+ const meta = source.metadata as Record<string, unknown> | undefined;
+
+ if (existing) {
+ const mergedPages = [...new Set([...existing.pages, ...(source.pages || [])])];
+ existing.pages = mergedPages;
+ existing.relevance = Math.max(existing.relevance, source.relevance || 0);
+ existing.pageRelevance = { ...existing.pageRelevance, ...source.pageRelevance };
+ if (source.content && existing.content) {
+ existing.content += '\n\n' + source.content;
+ } else if (source.content) {
+ existing.content = source.content;
+ }
+ } else {
+ deduped.set(key, {
+ fileId: source.fileId,
+ fileName: source.fileName,
+ relevance: source.relevance || 0,
+ content: source.content || '',
+ pages: source.pages || [],
+ pageRelevance: source.pageRelevance || {},
+ fileType: (meta?.fileType as string) || undefined,
+ fileBytes: (meta?.fileBytes as number) || undefined,
+ metadata: meta,
+ });
+ }
+ }
+ }
+
+ return Array.from(deduped.values()).sort((a, b) => b.relevance - a.relevance);
+}
+
+interface ParsedResult {
+ filename: string;
+ relevance: number;
+ content: string;
+}
+
+interface DisplayResult {
+ fileId?: string;
+ fileName: string;
+ relevance: number;
+ content: string;
+ pages?: number[];
+ pageRelevance?: Record<number, number>;
+ fileType?: string;
+ fileBytes?: number;
+}
+
+interface FileMatch {
+ fileId: string;
+ fileName: string;
+ fileType?: string;
+ fileBytes?: number;
+}
+
+function normalizeFilename(filename: string): string {
+ return filename.toLowerCase().replace(/[^a-z0-9.]/g, '');
+}
+
+function addFileMatch(
+ lookup: Map<string, FileMatch | null>,
+ fileName: string | undefined,
+ match: FileMatch,
+): void {
+ if (!fileName) {
+ return;
+ }
+
+ const key = normalizeFilename(fileName);
+ if (key.length === 0) {
+ return;
+ }
+
+ const existing = lookup.get(key);
+ if (!existing) {
+ lookup.set(key, match);
+ return;
+ }
+
+ if (existing.fileId !== match.fileId) {
+ lookup.set(key, null);
+ }
+}
+
+function buildFileLookup(
+ fileSources: FileSource[],
+ files?: TFile[],
+): Map<string, FileMatch | null> {
+ const lookup = new Map<string, FileMatch | null>();
+
+ for (const source of fileSources) {
+ addFileMatch(lookup, source.fileName, {
+ fileId: source.fileId,
+ fileName: source.fileName,
+ fileType: source.fileType,
+ fileBytes: source.fileBytes,
+ });
+ }
+
+ for (const file of files ?? []) {
+ if (!file.file_id || !file.filename) {
+ continue;
+ }
+
+ const key = normalizeFilename(file.filename);
+ if (lookup.has(key)) {
+ continue;
+ }
+
+ addFileMatch(lookup, file.filename, {
+ fileId: file.file_id,
+ fileName: file.filename,
+ fileType: file.type ?? undefined,
+ fileBytes: file.bytes,
+ });
+ }
+
+ return lookup;
+}
+
+function mergeRetrievalResults(
+ fileSources: FileSource[],
+ parsedResults: ParsedResult[],
+ files?: TFile[],
+): DisplayResult[] {
+ if (parsedResults.length === 0) {
+ return fileSources.map((source) => ({
+ fileId: source.fileId,
+ fileName: source.fileName,
+ relevance: source.relevance,
+ content: source.content,
+ pages: source.pages,
+ pageRelevance: source.pageRelevance,
+ fileType: source.fileType,
+ fileBytes: source.fileBytes,
+ }));
+ }
+
+ const fileLookup = buildFileLookup(fileSources, files);
+
+ return parsedResults.map((result) => {
+ const key = normalizeFilename(result.filename);
+ const match = fileLookup.get(key) ?? undefined;
+
+ return {
+ fileId: match?.fileId,
+ fileName: match?.fileName ?? result.filename,
+ relevance: result.relevance,
+ content: result.content,
+ fileType: match?.fileType,
+ fileBytes: match?.fileBytes,
+ };
+ });
+}
+
+function parseRetrievalOutput(raw: string): ParsedResult[] {
+ const sections = raw.split('\n---\n');
+ const results: ParsedResult[] = [];
+
+ for (const section of sections) {
+ const trimmed = section.trim();
+ if (!trimmed) {
+ continue;
+ }
+
+ let filename = '';
+ let relevance = 0;
+ const contentLines: string[] = [];
+ let inContent = false;
+
+ for (const line of trimmed.split('\n')) {
+ if (inContent) {
+ contentLines.push(line);
+ continue;
+ }
+
+ if (line.startsWith('File: ')) {
+ filename = line.slice(6).trim();
+ } else if (line.startsWith('Relevance: ')) {
+ relevance = parseFloat(line.slice(11).trim()) || 0;
+ } else if (line.startsWith('Content: ')) {
+ inContent = true;
+ contentLines.push(line.slice(9));
+ }
+ }
+
+ if (filename) {
+ results.push({ filename, relevance, content: contentLines.join('\n').trim() });
+ }
+ }
+
+ return results;
+}
+
+function getFileIcon(mimeType?: string): React.ComponentType<{ className?: string }> {
+ if (!mimeType) {
+ return FileText;
+ }
+ if (mimeType.includes('spreadsheet') || mimeType.includes('excel') || mimeType.includes('csv')) {
+ return FileSpreadsheet;
+ }
+ if (mimeType.includes('image')) {
+ return FileImage;
+ }
+ if (
+ mimeType.includes('javascript') ||
+ mimeType.includes('typescript') ||
+ mimeType.includes('json') ||
+ mimeType.includes('xml') ||
+ mimeType.includes('html')
+ ) {
+ return FileCode;
+ }
+ if (mimeType.includes('pdf') || mimeType.includes('text') || mimeType.includes('word')) {
+ return FileText;
+ }
+ return File;
+}
+
+function FileHeader({
+ fileName,
+ relevance,
+ pages,
+ pageRelevance,
+ fileType,
+ onOpenPreview,
+}: {
+ fileName: string;
+ relevance: number;
+ pages?: number[];
+ pageRelevance?: Record<number, number>;
+ fileType?: string;
+ onOpenPreview?: () => void;
+}) {
+ const localize = useLocalize();
+ const IconComponent = getFileIcon(fileType);
+ const sortedPages = pages && pageRelevance ? sortPagesByRelevance(pages, pageRelevance) : pages;
+
+ return (
+ <div className="flex items-center gap-2 px-3 py-2">
+ <IconComponent className="size-3.5 shrink-0 text-text-secondary" aria-hidden="true" />
+ {onOpenPreview ? (
+ <button
+ type="button"
+ onClick={onOpenPreview}
+ className="min-w-0 truncate text-left text-xs font-medium text-text-primary underline decoration-border-medium underline-offset-2 transition-colors hover:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy focus-visible:ring-offset-1"
+ aria-label={`${localize('com_ui_preview')}: ${fileName}`}
+ >
+ {fileName}
+ </button>
+ ) : (
+ <span className="min-w-0 truncate text-xs font-medium text-text-primary">{fileName}</span>
+ )}
+ {relevance > 0 && (
+ <TooltipAnchor
+ description={localize('com_ui_relevance')}
+ side="top"
+ className="flex items-center"
+ >
+ <span
+ className="shrink-0 rounded bg-surface-tertiary px-1.5 py-0.5 text-[11px] tabular-nums leading-none text-text-secondary"
+ aria-label={`${localize('com_ui_relevance')}: ${Math.round(relevance * 100)}%`}
+ >
+ {Math.round(relevance * 100)}%
+ </span>
+ </TooltipAnchor>
+ )}
+ <span className="flex-1" />
+ {sortedPages && sortedPages.length > 0 && (
+ <span className="shrink-0 text-[11px] text-text-secondary">
+ {localize('com_file_pages', { pages: sortedPages.join(', ') })}
+ </span>
+ )}
+ </div>
+ );
+}
export default function RetrievalCall({
initialProgress = 0.1,
isSubmitting,
+ output,
+ attachments,
}: {
initialProgress: number;
isSubmitting: boolean;
+ output?: string;
+ attachments?: TAttachment[];
}) {
const progress = useProgress(initialProgress);
- const radius = 56.08695652173913;
- const circumference = 2 * Math.PI * radius;
- const offset = circumference - progress * circumference;
- const error = progress >= 2;
+ const localize = useLocalize();
+
+ const errorState = typeof output === 'string' && isError(output);
+ const cancelled = !isSubmitting && initialProgress < 1 && !errorState;
+ const hasOutput = !!output && !isError(output);
+ const autoExpand = useRecoilValue(store.autoExpandTools);
+ const [showOutput, setShowOutput] = useState(() => autoExpand && hasOutput);
+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(showOutput);
+
+ const fileSources = useMemo(() => extractFileSources(attachments), [attachments]);
+ const parsedResults = useMemo(
+ () => (hasOutput && output ? parseRetrievalOutput(output) : []),
+ [hasOutput, output],
+ );
+ const fileIds = useMemo(
+ () => new Set(fileSources.map((s) => s.fileId).filter(Boolean)),
+ [fileSources],
+ );
+ const { data: availableFiles = [] } = useGetFiles<TFile[]>({
+ enabled: hasOutput && parsedResults.length > 0 && fileIds.size > 0,
+ select: (files) => files.filter((f) => fileIds.has(f.file_id)),
+ });
+ const displayResults = useMemo(
+ () => mergeRetrievalResults(fileSources, parsedResults, availableFiles),
+ [availableFiles, fileSources, parsedResults],
+ );
+
+ const hasResults = displayResults.length > 0;
+
+ const [previewIndex, setPreviewIndex] = useState<number | null>(null);
+
+ const openPreview = useCallback((index: number) => {
+ setPreviewIndex(index);
+ }, []);
+
+ const closePreview = useCallback((open: boolean) => {
+ if (!open) {
+ setPreviewIndex(null);
+ }
+ }, []);
+
+ const previewData = useMemo(() => {
+ if (previewIndex === null) {
+ return null;
+ }
+
+ const result = displayResults[previewIndex];
+ if (!result?.fileId) {
+ return null;
+ }
+
+ return {
+ fileName: result.fileName,
+ fileId: result.fileId,
+ relevance: result.relevance,
+ pages: result.pages,
+ pageRelevance: result.pageRelevance,
+ fileType: result.fileType,
+ };
+ }, [displayResults, previewIndex]);
+
+ useEffect(() => {
+ if (autoExpand && hasOutput) {
+ setShowOutput(true);
+ }
+ }, [autoExpand, hasOutput]);
return (
- <div className="my-2.5 flex items-center gap-2.5">
- <div className="relative h-5 w-5 shrink-0">
- {progress < 1 ? (
- <InProgressCall progress={progress} isSubmitting={isSubmitting} error={error}>
- <div
- className="absolute left-0 top-0 flex h-full w-full items-center justify-center rounded-full bg-transparent text-white"
- style={{ opacity: 1, transform: 'none' }}
- >
- <div>
- <RetrievalIcon />
- </div>
- <ProgressCircle radius={radius} circumference={circumference} offset={offset} />
+ <div className="my-1">
+ <span className="sr-only" aria-live="polite" aria-atomic="true">
+ {(() => {
+ if (progress < 1 && !cancelled) {
+ return localize('com_ui_searching_files');
+ }
+ if (cancelled) {
+ return localize('com_ui_cancelled');
+ }
+ return localize('com_ui_retrieved_files');
+ })()}
+ </span>
+ <div className="relative my-1 flex h-5 shrink-0 items-center gap-2.5">
+ <ProgressText
+ progress={progress}
+ onClick={hasOutput ? () => setShowOutput((prev) => !prev) : undefined}
+ inProgressText={localize('com_ui_searching_files')}
+ finishedText={localize('com_ui_retrieved_files')}
+ errorSuffix={errorState && !cancelled ? localize('com_ui_tool_failed') : undefined}
+ icon={
+ <ToolIcon type="file_search" isAnimating={progress < 1 && !cancelled && !errorState} />
+ }
+ hasInput={hasOutput}
+ isExpanded={showOutput}
+ error={cancelled}
+ />
+ </div>
+ <div style={expandStyle}>
+ <div className="overflow-hidden" ref={expandRef}>
+ {hasOutput && hasResults && (
+ <div className="my-2 flex flex-col gap-2">
+ {displayResults.map((item, i) => {
+ return (
+ <div
+ key={`${item.fileId ?? item.fileName}-${i}`}
+ className={cn(
+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',
+ )}
+ >
+ <FileHeader
+ fileName={item.fileName}
+ relevance={item.relevance}
+ pages={item.pages}
+ pageRelevance={item.pageRelevance}
+ fileType={item.fileType}
+ onOpenPreview={item.fileId ? () => openPreview(i) : undefined}
+ />
+ {item.content && (
+ <div className="border-t border-border-light px-3 py-3">
+ <OutputRenderer text={item.content} />
+ </div>
+ )}
+ </div>
+ );
+ })}
</div>
- </InProgressCall>
- ) : error ? (
- <CancelledIcon />
- ) : (
- <FinishedIcon />
- )}
+ )}
+ </div>
</div>
- <ProgressText
- progress={progress}
- onClick={() => ({})}
- inProgressText={'Searching my knowledge'}
- finishedText={'Used Retrieval'}
- hasInput={false}
- popover={false}
+
+ <FilePreviewDialog
+ open={previewData !== null}
+ onOpenChange={closePreview}
+ fileName={previewData?.fileName ?? ''}
+ fileId={previewData?.fileId}
+ relevance={previewData?.relevance}
+ pages={previewData?.pages}
+ pageRelevance={previewData?.pageRelevance}
+ fileType={previewData?.fileType}
/>
</div>
);
diff --git a/client/src/components/Chat/Messages/Content/SearchContent.tsx b/client/src/components/Chat/Messages/Content/SearchContent.tsx
index 81752ddf9c..325aae89c8 100644
--- a/client/src/components/Chat/Messages/Content/SearchContent.tsx
+++ b/client/src/components/Chat/Messages/Content/SearchContent.tsx
@@ -10,7 +10,6 @@ import type {
TMessageContentParts,
} from 'librechat-data-provider';
import { UnfinishedMessage } from './MessageContent';
-import Sources from '~/components/Web/Sources';
import { cn, mapAttachments } from '~/utils';
import { SearchContext } from '~/Providers';
import MarkdownLite from './MarkdownLite';
@@ -34,7 +33,6 @@ const SearchContent = ({
if (Array.isArray(message.content) && message.content.length > 0) {
return (
<SearchContext.Provider value={{ searchResults }}>
- <Sources />
{message.content
.filter((part: TMessageContentParts | undefined) => part)
.map((part: TMessageContentParts | undefined, idx: number) => {
@@ -44,14 +42,14 @@ const SearchContent = ({
const toolCallId =
(part?.[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined)?.id ?? '';
- const attachments = attachmentMap[toolCallId];
+ const partAttachments = attachmentMap[toolCallId];
return (
<Part
key={`display-${messageId}-${idx}`}
showCursor={false}
isSubmitting={false}
isCreatedByUser={message.isCreatedByUser}
- attachments={attachments}
+ attachments={partAttachments}
part={part}
/>
);
diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx
index c807288b46..5abdd45f98 100644
--- a/client/src/components/Chat/Messages/Content/ToolCall.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx
@@ -1,4 +1,5 @@
-import { useMemo, useState, useEffect, useRef, useCallback, useLayoutEffect } from 'react';
+import { useMemo, useState, useEffect, useCallback } from 'react';
+import { useRecoilValue } from 'recoil';
import { Button } from '@librechat/client';
import { TriangleAlert } from 'lucide-react';
import {
@@ -8,11 +9,14 @@ import {
actionDomainSeparator,
} from 'librechat-data-provider';
import type { TAttachment } from 'librechat-data-provider';
-import { useLocalize, useProgress } from '~/hooks';
+import { useLocalize, useProgress, useExpandCollapse } from '~/hooks';
+import { ToolIcon, getToolIconType, isError } from './ToolOutput';
+import { useMCPIconMap } from '~/hooks/MCP';
import { AttachmentGroup } from './Parts';
import ToolCallInfo from './ToolCallInfo';
import ProgressText from './ProgressText';
-import { logger, cn } from '~/utils';
+import { logger } from '~/utils';
+import store from '~/store';
export default function ToolCall({
initialProgress = 0.1,
@@ -32,14 +36,18 @@ export default function ToolCall({
output?: string | null;
attachments?: TAttachment[];
auth?: string;
- expires_at?: number;
}) {
const localize = useLocalize();
- const [showInfo, setShowInfo] = useState(false);
- const contentRef = useRef<HTMLDivElement>(null);
- const [contentHeight, setContentHeight] = useState<number | undefined>(0);
- const [isAnimating, setIsAnimating] = useState(false);
- const prevShowInfoRef = useRef<boolean>(showInfo);
+ const autoExpand = useRecoilValue(store.autoExpandTools);
+ const hasOutput = (output?.length ?? 0) > 0;
+ const [showInfo, setShowInfo] = useState(() => autoExpand && hasOutput);
+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo);
+
+ useEffect(() => {
+ if (autoExpand && hasOutput) {
+ setShowInfo(true);
+ }
+ }, [autoExpand, hasOutput]);
const { function_name, domain, isMCPToolCall, mcpServerName } = useMemo(() => {
if (typeof name !== 'string') {
@@ -65,6 +73,10 @@ export default function ToolCall({
};
}, [name]);
+ const toolIconType = useMemo(() => getToolIconType(name), [name]);
+ const mcpIconMap = useMCPIconMap();
+ const mcpIconUrl = isMCPToolCall ? mcpIconMap.get(mcpServerName) : undefined;
+
const actionId = useMemo(() => {
if (isMCPToolCall || !auth) {
return '';
@@ -95,8 +107,9 @@ export default function ToolCall({
window.open(auth, '_blank', 'noopener,noreferrer');
}, [auth, isMCPToolCall, mcpServerName, actionId]);
- const error =
- typeof output === 'string' && output.toLowerCase().includes('error processing tool');
+ const hasError = typeof output === 'string' && isError(output);
+ const cancelled = !isSubmitting && initialProgress < 1 && !hasError;
+ const errorState = hasError;
const args = useMemo(() => {
if (typeof _args === 'string') {
@@ -136,7 +149,17 @@ export default function ToolCall({
}, [auth]);
const progress = useProgress(initialProgress);
- const cancelled = (!isSubmitting && progress < 1) || error === true;
+ const showCancelled = cancelled || (errorState && !output);
+
+ const subtitle = useMemo(() => {
+ if (isMCPToolCall && mcpServerName) {
+ return localize('com_ui_via_server', { 0: mcpServerName });
+ }
+ if (domain && domain.length !== Constants.ENCODED_DOMAIN_LENGTH) {
+ return localize('com_ui_via_server', { 0: domain });
+ }
+ return undefined;
+ }, [isMCPToolCall, mcpServerName, domain, localize]);
const getFinishedText = () => {
if (cancelled) {
@@ -151,56 +174,23 @@ export default function ToolCall({
return localize('com_assistants_completed_function', { 0: function_name });
};
- useLayoutEffect(() => {
- if (showInfo !== prevShowInfoRef.current) {
- prevShowInfoRef.current = showInfo;
- setIsAnimating(true);
-
- if (showInfo && contentRef.current) {
- requestAnimationFrame(() => {
- if (contentRef.current) {
- const height = contentRef.current.scrollHeight;
- setContentHeight(height + 4);
- }
- });
- } else {
- setContentHeight(0);
- }
-
- const timer = setTimeout(() => {
- setIsAnimating(false);
- }, 400);
-
- return () => clearTimeout(timer);
- }
- }, [showInfo]);
-
- useEffect(() => {
- if (!contentRef.current) {
- return;
- }
- const resizeObserver = new ResizeObserver((entries) => {
- if (showInfo && !isAnimating) {
- for (const entry of entries) {
- if (entry.target === contentRef.current) {
- setContentHeight(entry.contentRect.height + 4);
- }
- }
- }
- });
- resizeObserver.observe(contentRef.current);
- return () => {
- resizeObserver.disconnect();
- };
- }, [showInfo, isAnimating]);
-
if (!isLast && (!function_name || function_name.length === 0) && !output) {
return null;
}
return (
<>
- <div className="relative my-2.5 flex h-5 shrink-0 items-center gap-2.5">
+ <span className="sr-only" aria-live="polite" aria-atomic="true">
+ {(() => {
+ if (progress < 1 && !showCancelled) {
+ return function_name
+ ? localize('com_assistants_running_var', { 0: function_name })
+ : localize('com_assistants_running_action');
+ }
+ return getFinishedText();
+ })()}
+ </span>
+ <div className="relative my-1.5 flex h-5 shrink-0 items-center gap-2.5">
<ProgressText
progress={progress}
onClick={() => setShowInfo((prev) => !prev)}
@@ -210,61 +200,37 @@ export default function ToolCall({
: localize('com_assistants_running_action')
}
authText={
- !cancelled && authDomain.length > 0 ? localize('com_ui_requires_auth') : undefined
+ !showCancelled && authDomain.length > 0 ? localize('com_ui_requires_auth') : undefined
}
finishedText={getFinishedText()}
+ subtitle={subtitle}
+ errorSuffix={errorState && !cancelled ? localize('com_ui_tool_failed') : undefined}
+ icon={
+ <ToolIcon
+ type={toolIconType}
+ iconUrl={mcpIconUrl}
+ isAnimating={progress < 1 && !showCancelled && !errorState}
+ />
+ }
hasInput={hasInfo}
isExpanded={showInfo}
- error={cancelled}
+ error={showCancelled}
/>
</div>
- <div
- className="relative"
- style={{
- height: showInfo ? contentHeight : 0,
- overflow: 'hidden',
- transition:
- 'height 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- opacity: showInfo ? 1 : 0,
- transformOrigin: 'top',
- willChange: 'height, opacity',
- perspective: '1000px',
- backfaceVisibility: 'hidden',
- WebkitFontSmoothing: 'subpixel-antialiased',
- }}
- >
- <div
- className={cn(
- 'overflow-hidden rounded-xl border border-border-light bg-surface-secondary shadow-md',
- showInfo && 'shadow-lg',
+ <div style={expandStyle}>
+ <div className="overflow-hidden" ref={expandRef}>
+ {hasInfo && (
+ <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">
+ <ToolCallInfo input={args ?? ''} output={output} attachments={attachments} />
+ </div>
)}
- style={{
- transform: showInfo ? 'translateY(0) scale(1)' : 'translateY(-8px) scale(0.98)',
- opacity: showInfo ? 1 : 0,
- transition:
- 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1)',
- }}
- >
- <div ref={contentRef}>
- {showInfo && hasInfo && (
- <ToolCallInfo
- key="tool-call-info"
- input={args ?? ''}
- output={output}
- domain={authDomain || (domain ?? '')}
- function_name={function_name}
- pendingAuth={authDomain.length > 0 && !cancelled && progress < 1}
- attachments={attachments}
- />
- )}
- </div>
</div>
</div>
- {auth != null && auth && progress < 1 && !cancelled && (
+ {auth != null && auth && progress < 1 && !showCancelled && (
<div className="flex w-full flex-col gap-2.5">
<div className="mb-1 mt-2">
<Button
- className="font-mediu inline-flex items-center justify-center rounded-xl px-4 py-2 text-sm"
+ className="inline-flex items-center justify-center rounded-xl px-4 py-2 text-sm font-medium"
variant="default"
rel="noopener noreferrer"
onClick={handleOAuthClick}
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
new file mode 100644
index 0000000000..c66ecc24fa
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -0,0 +1,178 @@
+import { useState, useMemo, useEffect, useCallback } from 'react';
+import { useRecoilValue } from 'recoil';
+import { ChevronDown } from 'lucide-react';
+import { ContentTypes, ToolCallTypes } from 'librechat-data-provider';
+import type { TMessageContentParts, Agents, FunctionToolCall } from 'librechat-data-provider';
+import type { PartWithIndex } from './ParallelContent';
+import type { TranslationKeys } from '~/hooks';
+import { StackedToolIcons, getMCPServerName } from './ToolOutput';
+import { useLocalize, useExpandCollapse } from '~/hooks';
+import { useMCPIconMap } from '~/hooks/MCP';
+import { cn } from '~/utils';
+import store from '~/store';
+
+/** Maps tool names to translation keys — resolved via localize() at render time. */
+const FRIENDLY_NAME_KEYS: Record<string, TranslationKeys> = {
+ execute_code: 'com_ui_tool_name_code',
+ run_tools_with_code: 'com_ui_tool_name_code',
+ web_search: 'com_ui_tool_name_web_search',
+ image_gen_oai: 'com_ui_tool_name_image_gen',
+ image_edit_oai: 'com_ui_tool_name_image_edit',
+ gemini_image_gen: 'com_ui_tool_name_image_gen',
+ file_search: 'com_ui_tool_name_file_search',
+ code_interpreter: 'com_ui_tool_name_code_analysis',
+ retrieval: 'com_ui_tool_name_file_search',
+};
+
+interface ToolMeta {
+ name: string;
+ hasOutput: boolean;
+}
+
+function getToolMeta(part: TMessageContentParts): ToolMeta | null {
+ if (part.type !== ContentTypes.TOOL_CALL) {
+ return null;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL];
+ if (!toolCall) {
+ return null;
+ }
+
+ const isStandard =
+ 'args' in toolCall && (!toolCall.type || toolCall.type === ToolCallTypes.TOOL_CALL);
+ if (isStandard) {
+ const tc = toolCall as Agents.ToolCall;
+ return { name: tc.name ?? '', hasOutput: !!tc.output };
+ }
+
+ if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {
+ const ci = (toolCall as { code_interpreter?: { outputs?: unknown[] } }).code_interpreter;
+ return { name: 'code_interpreter', hasOutput: (ci?.outputs?.length ?? 0) > 0 };
+ }
+
+ if (toolCall.type === ToolCallTypes.RETRIEVAL || toolCall.type === ToolCallTypes.FILE_SEARCH) {
+ return { name: 'file_search', hasOutput: !!(toolCall as { output?: string }).output };
+ }
+
+ if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {
+ const fn = (toolCall as FunctionToolCall).function;
+ return { name: fn.name, hasOutput: !!fn.output };
+ }
+
+ return null;
+}
+
+interface ToolCallGroupProps {
+ parts: PartWithIndex[];
+ isSubmitting: boolean;
+ isLast: boolean;
+ renderPart: (part: TMessageContentParts, idx: number, isLastPart: boolean) => React.ReactNode;
+ lastContentIdx: number;
+}
+
+export default function ToolCallGroup({
+ parts,
+ isSubmitting,
+ isLast,
+ renderPart,
+ lastContentIdx,
+}: ToolCallGroupProps) {
+ const localize = useLocalize();
+ const mcpIconMap = useMCPIconMap();
+ const count = parts.length;
+
+ const toolMetadata = useMemo(() => parts.map((p) => getToolMeta(p.part)), [parts]);
+ const allCompleted = useMemo(
+ () => toolMetadata.every((m) => m?.hasOutput === true),
+ [toolMetadata],
+ );
+ const toolNames = useMemo(() => toolMetadata.map((m) => m?.name ?? ''), [toolMetadata]);
+
+ const toolNameSummary = useMemo(() => {
+ const seen = new Set<string>();
+ const labels: string[] = [];
+ for (const rawName of toolNames) {
+ if (!rawName) {
+ continue;
+ }
+ const serverName = getMCPServerName(rawName);
+ const nameKey = FRIENDLY_NAME_KEYS[rawName];
+ const label = serverName || (nameKey ? localize(nameKey) : rawName);
+ if (!seen.has(label)) {
+ seen.add(label);
+ labels.push(label);
+ }
+ }
+ if (labels.length <= 3) {
+ return labels.join(', ');
+ }
+ return `${labels.slice(0, 3).join(', ')}, +${labels.length - 3}`;
+ }, [toolNames, localize]);
+
+ const autoExpand = useRecoilValue(store.autoExpandTools);
+ const autoCollapse = !autoExpand && count >= 2 && allCompleted;
+ const [isExpanded, setIsExpanded] = useState(autoExpand || !autoCollapse);
+ const [userOverride, setUserOverride] = useState(false);
+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);
+
+ useEffect(() => {
+ if (autoCollapse && !userOverride) {
+ setIsExpanded(false);
+ }
+ }, [autoCollapse, userOverride]);
+
+ const handleToggle = useCallback(() => {
+ setUserOverride(true);
+ setIsExpanded((prev) => !prev);
+ }, []);
+
+ const hasActiveToolCall = useMemo(
+ () => isSubmitting && toolMetadata.some((m) => m && !m.hasOutput),
+ [toolMetadata, isSubmitting],
+ );
+
+ useEffect(() => {
+ if (hasActiveToolCall) {
+ setIsExpanded(true);
+ }
+ }, [hasActiveToolCall]);
+
+ return (
+ <div className="mb-2 mt-1">
+ <button
+ type="button"
+ className="inline-flex w-full items-center gap-2 py-1 text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"
+ onClick={handleToggle}
+ aria-expanded={isExpanded}
+ aria-label={localize('com_ui_used_n_tools', { 0: String(count) })}
+ >
+ <StackedToolIcons
+ toolNames={toolNames}
+ mcpIconMap={mcpIconMap}
+ maxIcons={4}
+ isAnimating={!allCompleted && isSubmitting}
+ />
+ <span className="tool-status-text font-medium">
+ {localize('com_ui_used_n_tools', { 0: String(count) })}
+ </span>
+ {toolNameSummary && (
+ <span className="text-xs font-normal text-text-secondary">— {toolNameSummary}</span>
+ )}
+ <ChevronDown
+ className={cn(
+ 'size-4 shrink-0 text-text-secondary transition-transform duration-200 ease-out',
+ isExpanded && 'rotate-180',
+ )}
+ aria-hidden="true"
+ />
+ </button>
+ <div style={expandStyle}>
+ <div className="overflow-hidden" ref={expandRef}>
+ <div className="py-0.5 pl-4">
+ {parts.map(({ part, idx }) => renderPart(part, idx, isLast && idx === lastContentIdx))}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx b/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx
index 7d9a941d19..59a564be4d 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallInfo.tsx
@@ -1,61 +1,125 @@
-import React from 'react';
-import { useLocalize } from '~/hooks';
+import { useState, useMemo } from 'react';
+import { ChevronDown } from 'lucide-react';
import { Tools } from 'librechat-data-provider';
import { UIResourceRenderer } from '@mcp-ui/client';
-import UIResourceCarousel from './UIResourceCarousel';
import type { TAttachment, UIResource } from 'librechat-data-provider';
+import { useLocalize, useExpandCollapse } from '~/hooks';
+import UIResourceCarousel from './UIResourceCarousel';
+import { useMessagesOperations } from '~/Providers';
+import { OutputRenderer } from './ToolOutput';
+import { handleUIAction, cn } from '~/utils';
-function OptimizedCodeBlock({ text, maxHeight = 320 }: { text: string; maxHeight?: number }) {
+function isSimpleObject(obj: unknown): obj is Record<string, string | number | boolean | null> {
+ if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
+ return false;
+ }
+ const entries = Object.entries(obj);
+ if (entries.length === 0 || entries.length > 8) {
+ return false;
+ }
+ return entries.every(
+ ([, v]) =>
+ v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean',
+ );
+}
+
+function KeyValueInput({ data }: { data: Record<string, string | number | boolean | null> }) {
return (
- <div
- className="rounded-lg bg-surface-tertiary p-2 text-xs text-text-primary"
- style={{
- position: 'relative',
- maxHeight,
- overflow: 'auto',
- }}
- >
- <pre className="m-0 whitespace-pre-wrap break-words" style={{ overflowWrap: 'break-word' }}>
- <code>{text}</code>
- </pre>
+ <div className="flex flex-wrap gap-x-4 gap-y-1.5 text-xs">
+ {Object.entries(data).map(([key, value]) => (
+ <div key={key} className="flex items-baseline gap-1.5">
+ <span className="font-medium text-text-secondary">{key}</span>
+ <span className="rounded bg-surface-tertiary px-1.5 py-0.5 text-text-primary">
+ {String(value ?? 'null')}
+ </span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function formatParamValue(value: unknown): string {
+ if (value === null || value === undefined) {
+ return '';
+ }
+ if (typeof value === 'string') {
+ return value.length > 200 ? value.slice(0, 200) + '...' : value;
+ }
+ if (typeof value !== 'object') {
+ return String(value);
+ }
+ const str = JSON.stringify(value);
+ return str.length > 200 ? str.slice(0, 200) + '...' : str;
+}
+
+function ComplexInput({ data }: { data: Record<string, unknown> }) {
+ return (
+ <div className="flex flex-wrap gap-x-4 gap-y-1.5 text-xs">
+ {Object.entries(data).map(([key, value]) => (
+ <div key={key} className="flex items-baseline gap-1.5">
+ <span className="font-medium text-text-secondary">{key}</span>
+ <span className="max-w-[300px] overflow-hidden truncate rounded bg-surface-tertiary px-1.5 py-0.5 font-mono text-text-primary">
+ {formatParamValue(value)}
+ </span>
+ </div>
+ ))}
</div>
);
}
+function InputRenderer({ input }: { input: string }) {
+ if (!input || input.trim().length === 0) {
+ return null;
+ }
+
+ try {
+ const parsed = JSON.parse(input);
+ if (isSimpleObject(parsed)) {
+ return <KeyValueInput data={parsed} />;
+ }
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
+ return <ComplexInput data={parsed as Record<string, unknown>} />;
+ }
+ // Valid JSON but not a plain object (array, string, number, boolean) — render formatted
+ return (
+ <pre className="whitespace-pre-wrap text-xs text-text-primary">
+ {typeof parsed === 'string' ? parsed : JSON.stringify(parsed, null, 2)}
+ </pre>
+ );
+ } catch {
+ // Not JSON — render as plain text
+ return <pre className="whitespace-pre-wrap text-xs text-text-primary">{input}</pre>;
+ }
+}
+
export default function ToolCallInfo({
input,
output,
- domain,
- function_name,
- pendingAuth,
attachments,
}: {
input: string;
- function_name: string;
output?: string | null;
- domain?: string;
- pendingAuth?: boolean;
attachments?: TAttachment[];
}) {
const localize = useLocalize();
- const formatText = (text: string) => {
+ const { ask } = useMessagesOperations();
+ const [showParams, setShowParams] = useState(false);
+ const { style: paramsExpandStyle, ref: paramsExpandRef } = useExpandCollapse(showParams);
+
+ const hasParams = useMemo(() => {
+ if (!input || input.trim().length === 0) {
+ return false;
+ }
try {
- return JSON.stringify(JSON.parse(text), null, 2);
+ const parsed = JSON.parse(input);
+ if (typeof parsed === 'object' && parsed !== null) {
+ return Object.keys(parsed).length > 0;
+ }
} catch {
- return text;
+ // Not JSON
}
- };
-
- let title =
- domain != null && domain
- ? localize('com_assistants_domain_info', { 0: domain })
- : localize('com_assistants_function_use', { 0: function_name });
- if (pendingAuth === true) {
- title =
- domain != null && domain
- ? localize('com_assistants_action_attempt', { 0: domain })
- : localize('com_assistants_attempt_info');
- }
+ return input.trim().length > 0;
+ }, [input]);
const uiResources: UIResource[] =
attachments
@@ -65,43 +129,51 @@ export default function ToolCallInfo({
}) ?? [];
return (
- <div className="w-full p-2">
- <div style={{ opacity: 1 }}>
- <div className="mb-2 text-sm font-medium text-text-primary">{title}</div>
- <div>
- <OptimizedCodeBlock text={formatText(input)} maxHeight={250} />
- </div>
- {output && (
- <>
- <div className="my-2 text-sm font-medium text-text-primary">
- {localize('com_ui_result')}
- </div>
- <div>
- <OptimizedCodeBlock text={formatText(output)} maxHeight={250} />
- </div>
- {uiResources.length > 0 && (
- <div className="my-2 text-sm font-medium text-text-primary">
- {localize('com_ui_ui_resources')}
- </div>
+ <div className="w-full px-3 py-3.5">
+ {output && <OutputRenderer text={output} />}
+ {output && hasParams && <div className="my-2 border-t border-border-light" />}
+ {hasParams && (
+ <>
+ <button
+ type="button"
+ className={cn(
+ 'inline-flex items-center gap-1 text-xs text-text-secondary',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',
)}
- <div>
- {uiResources.length > 1 && <UIResourceCarousel uiResources={uiResources} />}
-
- {uiResources.length === 1 && (
- <UIResourceRenderer
- resource={uiResources[0]}
- onUIAction={async (result) => {
- console.log('Action:', result);
- }}
- htmlProps={{
- autoResizeIframe: { width: true, height: true },
- }}
- />
+ onClick={() => setShowParams((prev) => !prev)}
+ aria-expanded={showParams}
+ >
+ <span>{localize('com_ui_parameters')}</span>
+ <ChevronDown
+ className={cn(
+ 'size-3 shrink-0 transition-transform duration-200 ease-out',
+ showParams && 'rotate-180',
)}
+ aria-hidden="true"
+ />
+ </button>
+ <div style={paramsExpandStyle}>
+ <div className="overflow-hidden pt-1" ref={paramsExpandRef}>
+ <InputRenderer input={input} />
</div>
- </>
- )}
- </div>
+ </div>
+ </>
+ )}
+ {uiResources.length > 0 && (
+ <>
+ {(hasParams || output) && <div className="my-2 border-t border-border-light" />}
+ {uiResources.length > 1 && <UIResourceCarousel uiResources={uiResources} />}
+ {uiResources.length === 1 && (
+ <UIResourceRenderer
+ resource={uiResources[0]}
+ onUIAction={async (result) => handleUIAction(result, ask)}
+ htmlProps={{
+ autoResizeIframe: { width: true, height: true },
+ }}
+ />
+ )}
+ </>
+ )}
</div>
);
}
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx
new file mode 100644
index 0000000000..5b7130f38e
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx
@@ -0,0 +1,168 @@
+import { useState, useMemo, useCallback } from 'react';
+import copy from 'copy-to-clipboard';
+import CopyButton from '~/components/Messages/Content/CopyButton';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface ContentBlock {
+ type?: string;
+ text?: string;
+}
+
+const ERROR_PREFIX = /^Error:\s*(\[.*?\]\s*)*tool call failed:\s*/i;
+const ERROR_INNER = /^Error\s+\w+ing to endpoint\s*\(HTTP \d+\):\s*/i;
+
+function cleanError(text: string): string {
+ let cleaned = text.replace(ERROR_PREFIX, '').trim();
+ cleaned = cleaned.replace(ERROR_INNER, '').trim();
+ if (cleaned.endsWith('Please fix your mistakes.')) {
+ cleaned = cleaned.slice(0, -'Please fix your mistakes.'.length).trim();
+ }
+ return cleaned;
+}
+
+export function isError(text: string): boolean {
+ return ERROR_PREFIX.test(text) || text.startsWith('Error processing tool');
+}
+
+function isStructuredText(text: string): boolean {
+ return text.includes('\n') || text.includes('{') || text.includes(':');
+}
+
+interface ExtractedText {
+ text: string;
+ rawError: string;
+ error: boolean;
+ /** When true, `text` contains raw JSON that should be rendered as a highlighted code block. */
+ isJson: boolean;
+}
+
+function extractText(raw: string): ExtractedText {
+ const trimmed = raw.trim();
+ if (!trimmed) {
+ return { text: '', rawError: '', error: false, isJson: false };
+ }
+
+ if (isError(trimmed)) {
+ return { text: cleanError(trimmed), rawError: trimmed, error: true, isJson: false };
+ }
+
+ if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+
+ if (Array.isArray(parsed)) {
+ const textBlocks = parsed.filter(
+ (b: ContentBlock) => typeof b === 'object' && b !== null && typeof b.text === 'string',
+ );
+ if (textBlocks.length > 0) {
+ const joined = (textBlocks as ContentBlock[])
+ .map((b) => b.text)
+ .join('\n')
+ .trim();
+ if (isError(joined)) {
+ return { text: cleanError(joined), rawError: joined, error: true, isJson: false };
+ }
+ return { text: joined, rawError: '', error: false, isJson: false };
+ }
+ }
+
+ // Render structured JSON as a highlighted code block
+ return {
+ text: JSON.stringify(parsed, null, 2),
+ rawError: '',
+ error: false,
+ isJson: true,
+ };
+ } catch {
+ // Not JSON
+ }
+ }
+
+ return { text: trimmed, rawError: '', error: false, isJson: false };
+}
+
+const TRUNCATE_LINES = 20;
+const VISIBLE_LINES = 15;
+
+interface OutputRendererProps {
+ text: string;
+}
+
+export default function OutputRenderer({ text }: OutputRendererProps) {
+ const localize = useLocalize();
+ const { text: displayText, rawError, error, isJson } = useMemo(() => extractText(text), [text]);
+ const [isExpanded, setIsExpanded] = useState(false);
+ const [showErrorDetails, setShowErrorDetails] = useState(false);
+ const [isCopied, setIsCopied] = useState(false);
+
+ const handleCopy = useCallback(() => {
+ setIsCopied(true);
+ copy(displayText, { format: 'text/plain' });
+ setTimeout(() => setIsCopied(false), 3000);
+ }, [displayText]);
+
+ if (!displayText) {
+ return null;
+ }
+
+ const lines = displayText.split('\n');
+ const needsTruncation = lines.length > TRUNCATE_LINES;
+ const visibleText =
+ needsTruncation && !isExpanded ? lines.slice(0, VISIBLE_LINES).join('\n') : displayText;
+ const structured = !isJson && isStructuredText(displayText);
+
+ return (
+ <div className="relative">
+ {isJson ? (
+ <pre className="max-h-[300px] overflow-auto rounded text-xs">
+ <code className="hljs language-json !whitespace-pre-wrap !break-words">
+ {visibleText}
+ </code>
+ </pre>
+ ) : (
+ <pre
+ className={cn(
+ 'max-h-[300px] overflow-auto whitespace-pre-wrap break-words text-xs',
+ error && 'font-mono text-red-600 dark:text-red-400',
+ !error && structured && 'font-mono text-text-secondary',
+ !error && !structured && 'font-sans text-sm text-text-primary',
+ )}
+ >
+ {visibleText}
+ </pre>
+ )}
+ <div className="absolute bottom-0 right-0">
+ <CopyButton
+ isCopied={isCopied}
+ onClick={handleCopy}
+ iconOnly
+ label={localize('com_ui_copy')}
+ />
+ </div>
+ {needsTruncation && (
+ <button
+ type="button"
+ className="mt-1 text-xs text-text-secondary underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"
+ onClick={() => setIsExpanded((prev) => !prev)}
+ >
+ {isExpanded ? localize('com_ui_show_less') : localize('com_ui_show_more')}
+ </button>
+ )}
+ {error && rawError && rawError !== displayText && (
+ <button
+ type="button"
+ className="mt-1 block text-xs text-text-secondary underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"
+ onClick={() => setShowErrorDetails((prev) => !prev)}
+ >
+ {localize('com_ui_details')}
+ </button>
+ )}
+ {showErrorDetails && rawError && (
+ <pre className="mt-2 max-h-[200px] overflow-auto whitespace-pre-wrap break-words font-mono text-xs text-red-600 dark:text-red-400">
+ {rawError}
+ </pre>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/StackedToolIcons.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/StackedToolIcons.tsx
new file mode 100644
index 0000000000..c7be3adc25
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/StackedToolIcons.tsx
@@ -0,0 +1,84 @@
+import { useMemo } from 'react';
+import ToolIcon, { getToolIconType, getMCPServerName } from './ToolIcon';
+import type { ToolIconType } from './ToolIcon';
+import { cn } from '~/utils';
+
+interface ResolvedIcon {
+ key: string;
+ type: ToolIconType;
+ iconUrl?: string;
+}
+
+interface StackedToolIconsProps {
+ toolNames: string[];
+ mcpIconMap?: Map<string, string>;
+ maxIcons?: number;
+ isAnimating?: boolean;
+}
+
+export default function StackedToolIcons({
+ toolNames,
+ mcpIconMap,
+ maxIcons = 3,
+ isAnimating = false,
+}: StackedToolIconsProps) {
+ const uniqueIcons = useMemo(() => {
+ const seen = new Set<string>();
+ const result: ResolvedIcon[] = [];
+ for (const name of toolNames) {
+ const type = getToolIconType(name);
+ const serverName = getMCPServerName(name);
+ const iconUrl = serverName ? mcpIconMap?.get(serverName) : undefined;
+ const key = iconUrl ? `mcp-${serverName}` : type;
+ if (!seen.has(key)) {
+ seen.add(key);
+ result.push({ key, type, iconUrl });
+ }
+ }
+ return result;
+ }, [toolNames, mcpIconMap]);
+
+ const visibleIcons = uniqueIcons.slice(0, maxIcons);
+ const overflowCount = uniqueIcons.length - visibleIcons.length;
+
+ if (visibleIcons.length <= 1) {
+ const icon = visibleIcons[0];
+ return (
+ <ToolIcon type={icon?.type ?? 'generic'} iconUrl={icon?.iconUrl} isAnimating={isAnimating} />
+ );
+ }
+
+ return (
+ <div className="flex items-center" aria-hidden="true">
+ {visibleIcons.map((icon, index) => (
+ <div
+ key={icon.key}
+ className={cn(
+ 'relative flex items-center justify-center rounded-full border border-border-medium bg-surface-secondary',
+ 'h-[22px] w-[22px]',
+ index > 0 && '-ml-2.5',
+ )}
+ style={{ zIndex: visibleIcons.length - index }}
+ >
+ <ToolIcon
+ type={icon.type}
+ iconUrl={icon.iconUrl}
+ isAnimating={isAnimating}
+ className="size-3"
+ />
+ </div>
+ ))}
+ {overflowCount > 0 && (
+ <div
+ className={cn(
+ 'relative flex items-center justify-center rounded-full border border-border-medium bg-surface-tertiary',
+ '-ml-2.5 h-[22px] w-[22px] text-xs font-medium text-text-secondary',
+ )}
+ style={{ zIndex: 0 }}
+ >
+ +{overflowCount}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
new file mode 100644
index 0000000000..bc8f94c450
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
@@ -0,0 +1,101 @@
+import { Constants, actionDelimiter } from 'librechat-data-provider';
+import { Terminal, Globe, ImageIcon, ArrowRightLeft, FileSearch, Zap, Wrench } from 'lucide-react';
+import { cn } from '~/utils';
+
+export type ToolIconType =
+ | 'mcp'
+ | 'execute_code'
+ | 'web_search'
+ | 'image_gen'
+ | 'agent_handoff'
+ | 'file_search'
+ | 'action'
+ | 'generic';
+
+const ICON_MAP: Record<ToolIconType, React.ComponentType<{ className?: string }>> = {
+ mcp: Wrench,
+ execute_code: Terminal,
+ web_search: Globe,
+ image_gen: ImageIcon,
+ agent_handoff: ArrowRightLeft,
+ file_search: FileSearch,
+ action: Zap,
+ generic: Wrench,
+};
+
+export function getToolIconType(name: string): ToolIconType {
+ if (!name) {
+ return 'generic';
+ }
+ if (name.includes(Constants.mcp_delimiter)) {
+ return 'mcp';
+ }
+ if (name === 'execute_code' || name === Constants.PROGRAMMATIC_TOOL_CALLING) {
+ return 'execute_code';
+ }
+ if (name === 'web_search') {
+ return 'web_search';
+ }
+ if (name === 'image_gen_oai' || name === 'image_edit_oai' || name === 'gemini_image_gen') {
+ return 'image_gen';
+ }
+ if (name === 'file_search' || name === 'retrieval') {
+ return 'file_search';
+ }
+ if (name === 'code_interpreter') {
+ return 'execute_code';
+ }
+ if (name.startsWith(Constants.LC_TRANSFER_TO_)) {
+ return 'agent_handoff';
+ }
+ if (name.includes(actionDelimiter)) {
+ return 'action';
+ }
+ return 'generic';
+}
+
+/** Extracts the MCP server name from a tool name with format `tool<delimiter>server`. */
+export function getMCPServerName(toolName: string): string {
+ const idx = toolName.indexOf(Constants.mcp_delimiter);
+ if (idx < 0) {
+ return '';
+ }
+ const afterDelimiter = toolName.slice(idx + Constants.mcp_delimiter.length);
+ return afterDelimiter || '';
+}
+
+interface ToolIconProps {
+ type: ToolIconType;
+ iconUrl?: string;
+ isAnimating?: boolean;
+ className?: string;
+}
+
+export default function ToolIcon({ type, iconUrl, isAnimating = false, className }: ToolIconProps) {
+ if (iconUrl) {
+ return (
+ <img
+ src={iconUrl}
+ alt=""
+ className={cn(
+ 'size-4 shrink-0 rounded-full object-cover',
+ isAnimating && 'animate-pulse',
+ className,
+ )}
+ aria-hidden="true"
+ />
+ );
+ }
+
+ const IconComponent = ICON_MAP[type];
+ return (
+ <IconComponent
+ className={cn(
+ 'size-4 shrink-0 text-text-secondary',
+ isAnimating && 'animate-pulse',
+ className,
+ )}
+ aria-hidden="true"
+ />
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/index.ts b/client/src/components/Chat/Messages/Content/ToolOutput/index.ts
new file mode 100644
index 0000000000..fbac042099
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/index.ts
@@ -0,0 +1,4 @@
+export type { ToolIconType } from './ToolIcon';
+export { default as StackedToolIcons } from './StackedToolIcons';
+export { default as OutputRenderer, isError } from './OutputRenderer';
+export { default as ToolIcon, getToolIconType, getMCPServerName } from './ToolIcon';
diff --git a/client/src/components/Chat/Messages/Content/UIResourceCarousel.tsx b/client/src/components/Chat/Messages/Content/UIResourceCarousel.tsx
index 15c420755b..c0829e5ad9 100644
--- a/client/src/components/Chat/Messages/Content/UIResourceCarousel.tsx
+++ b/client/src/components/Chat/Messages/Content/UIResourceCarousel.tsx
@@ -109,11 +109,7 @@ const UIResourceCarousel: React.FC<UIResourceCarouselProps> = React.memo(({ uiRe
>
<div className="flex h-full flex-col">
<UIResourceRenderer
- resource={{
- uri: uiResource.uri,
- mimeType: uiResource.mimeType,
- text: uiResource.text,
- }}
+ resource={uiResource}
onUIAction={async (result) => handleUIAction(result, ask)}
htmlProps={{
autoResizeIframe: { width: true, height: true },
diff --git a/client/src/components/Chat/Messages/Content/WebSearch.tsx b/client/src/components/Chat/Messages/Content/WebSearch.tsx
index afcd3bc2d8..62f2805a64 100644
--- a/client/src/components/Chat/Messages/Content/WebSearch.tsx
+++ b/client/src/components/Chat/Messages/Content/WebSearch.tsx
@@ -1,9 +1,14 @@
-import { useMemo } from 'react';
-import type { TAttachment } from 'librechat-data-provider';
+import { useMemo, useState, useEffect } from 'react';
+import { useRecoilValue } from 'recoil';
+import { Tools } from 'librechat-data-provider';
+import { Globe, ChevronDown } from 'lucide-react';
+import type { TAttachment, ValidSource, SearchResultData } from 'librechat-data-provider';
+import { FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';
import { StackedFavicons } from '~/components/Web/Sources';
+import { useLocalize, useExpandCollapse } from '~/hooks';
import { useSearchContext } from '~/Providers';
-import ProgressText from './ProgressText';
-import { useLocalize } from '~/hooks';
+import cn from '~/utils/cn';
+import store from '~/store';
type ProgressKeys =
| 'com_ui_web_searching'
@@ -11,11 +16,72 @@ type ProgressKeys =
| 'com_ui_web_search_processing'
| 'com_ui_web_search_reading';
+const MAX_VISIBLE_FAVICONS = 3;
+
+function collectSources(results: Record<string, SearchResultData>): ValidSource[] {
+ const sourceMap = new Map<string, ValidSource>();
+ for (const result of Object.values(results)) {
+ if (!result) {
+ continue;
+ }
+ result.organic?.forEach((s) => {
+ if (s.link) {
+ sourceMap.set(s.link, s);
+ }
+ });
+ result.topStories?.forEach((s) => {
+ if (s.link) {
+ sourceMap.set(s.link, s);
+ }
+ });
+ }
+ return Array.from(sourceMap.values());
+}
+
+function getUniqueDomainSources(sources: ValidSource[], max: number): ValidSource[] {
+ const seen = new Set<string>();
+ const result: ValidSource[] = [];
+ for (const source of sources) {
+ const domain = getCleanDomain(source.link);
+ if (seen.has(domain)) {
+ continue;
+ }
+ seen.add(domain);
+ result.push(source);
+ if (result.length >= max) {
+ break;
+ }
+ }
+ return result;
+}
+
+function SourceFaviconStack({ sources }: { sources: ValidSource[] }) {
+ const visible = getUniqueDomainSources(sources, MAX_VISIBLE_FAVICONS);
+ return (
+ <div className="flex items-center" aria-hidden="true">
+ {visible.map((source, i) => (
+ <div
+ key={source.link}
+ className={cn(
+ 'relative flex items-center justify-center rounded-full border border-border-medium bg-surface-secondary',
+ 'h-[22px] w-[22px]',
+ i > 0 && '-ml-2.5',
+ )}
+ style={{ zIndex: MAX_VISIBLE_FAVICONS - i }}
+ >
+ <FaviconImage domain={getCleanDomain(source.link)} className="size-3 rounded-full" />
+ </div>
+ ))}
+ </div>
+ );
+}
+
export default function WebSearch({
initialProgress: progress = 0.1,
isSubmitting,
isLast,
output,
+ attachments,
}: {
isLast?: boolean;
isSubmitting: boolean;
@@ -30,14 +96,39 @@ export default function WebSearch({
const complete = !isLast && progress === 1;
const finalizing = isSubmitting && isLast && progress === 1;
+
+ const allSources = useMemo((): ValidSource[] => {
+ if (searchResults && Object.keys(searchResults).length > 0) {
+ return collectSources(searchResults);
+ }
+ if (attachments) {
+ const turnMap: Record<string, SearchResultData> = {};
+ for (const att of attachments) {
+ if (att.type === Tools.web_search && att[Tools.web_search]) {
+ const data = att[Tools.web_search];
+ const key = typeof data.turn === 'number' ? String(data.turn) : '0';
+ turnMap[key] = data;
+ }
+ }
+ if (Object.keys(turnMap).length > 0) {
+ return collectSources(turnMap);
+ }
+ }
+ return [];
+ }, [searchResults, attachments]);
+
const processedSources = useMemo(() => {
if (complete && !finalizing) {
return [];
}
- if (!searchResults) return [];
+ if (!searchResults) {
+ return [];
+ }
const values = Object.values(searchResults);
const result = values[values.length - 1];
- if (!result) return [];
+ if (!result) {
+ return [];
+ }
if (finalizing) {
return [...(result.organic || []), ...(result.topStories || [])];
}
@@ -45,18 +136,23 @@ export default function WebSearch({
(source) => source.processed === true,
);
}, [searchResults, complete, finalizing]);
- const turns = useMemo(() => {
- if (!searchResults) return 0;
- return Object.values(searchResults).length;
- }, [searchResults]);
- const clampedProgress = useMemo(() => {
- return Math.min(progress, 0.99);
- }, [progress]);
+ const ownTurn = useMemo(() => {
+ if (!attachments) {
+ return 0;
+ }
+ for (const att of attachments) {
+ if (att.type === Tools.web_search && att[Tools.web_search]) {
+ const turn = att[Tools.web_search].turn;
+ return typeof turn === 'number' ? turn : 0;
+ }
+ }
+ return 0;
+ }, [attachments]);
const showSources = processedSources.length > 0;
const progressText = useMemo(() => {
- let text: ProgressKeys = turns > 1 ? 'com_ui_web_searching_again' : 'com_ui_web_searching';
+ let text: ProgressKeys = ownTurn > 0 ? 'com_ui_web_searching_again' : 'com_ui_web_searching';
if (showSources) {
text = 'com_ui_web_search_processing';
}
@@ -64,28 +160,108 @@ export default function WebSearch({
text = 'com_ui_web_search_reading';
}
return localize(text);
- }, [turns, localize, showSources, finalizing]);
+ }, [ownTurn, localize, showSources, finalizing]);
- if (complete || cancelled) {
+ const autoExpand = useRecoilValue(store.autoExpandTools);
+ const sourceCount = allSources.length;
+ const [showSourceList, setShowSourceList] = useState(() => autoExpand && sourceCount > 0);
+ const { style: sourceExpandStyle, ref: sourceExpandRef } = useExpandCollapse(showSourceList);
+
+ useEffect(() => {
+ if (autoExpand && sourceCount > 0) {
+ setShowSourceList(true);
+ }
+ }, [autoExpand, sourceCount]);
+
+ if (cancelled) {
return null;
}
- return (
- <>
- <div className="relative my-2.5 flex size-5 shrink-0 items-center gap-2.5">
- {showSources && (
- <div className="mr-2">
- <StackedFavicons sources={processedSources} start={-5} />
+
+ if (complete) {
+ const hasSourceData = sourceCount > 0;
+ const completedText = localize('com_ui_web_searched');
+
+ return (
+ <div className="mb-2">
+ <span className="sr-only" aria-live="polite" aria-atomic="true">
+ {completedText}
+ </span>
+ <button
+ type="button"
+ className={cn(
+ 'tool-status-text group flex items-center gap-2 rounded-full py-1 transition-colors',
+ hasSourceData
+ ? 'text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy'
+ : 'pointer-events-none text-text-secondary',
+ )}
+ disabled={!hasSourceData}
+ onClick={hasSourceData ? () => setShowSourceList((prev) => !prev) : undefined}
+ aria-expanded={hasSourceData ? showSourceList : undefined}
+ aria-label={
+ hasSourceData
+ ? `${completedText} - ${localize(sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources', { count: sourceCount })}`
+ : completedText
+ }
+ >
+ {hasSourceData ? (
+ <SourceFaviconStack sources={allSources} />
+ ) : (
+ <Globe className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ )}
+ <span className="font-medium">{completedText}</span>
+ {hasSourceData && (
+ <ChevronDown
+ className={cn(
+ 'size-3.5 shrink-0 text-text-secondary transition-transform duration-200',
+ showSourceList && 'rotate-180',
+ )}
+ aria-hidden="true"
+ />
+ )}
+ </button>
+ {hasSourceData && (
+ <div style={sourceExpandStyle}>
+ <div className="overflow-hidden" ref={sourceExpandRef}>
+ <div className="my-2 max-h-[280px] overflow-y-auto rounded-lg border border-border-light">
+ {allSources.map((source, i) => {
+ const domain = getCleanDomain(source.link);
+ return (
+ <a
+ key={source.link}
+ href={source.link}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={cn(
+ 'flex items-center gap-2.5 px-3 py-2 transition-colors hover:bg-surface-hover',
+ i > 0 && 'border-t border-border-light',
+ )}
+ >
+ <FaviconImage domain={domain} className="size-4 shrink-0 rounded-sm" />
+ <span className="min-w-0 flex-1 truncate text-xs font-medium text-text-primary">
+ {source.title || domain}
+ </span>
+ <span className="shrink-0 text-[11px] text-text-secondary">{domain}</span>
+ </a>
+ );
+ })}
+ </div>
+ </div>
</div>
)}
- <ProgressText
- finishedText=""
- hasInput={false}
- error={cancelled}
- isExpanded={false}
- progress={clampedProgress}
- inProgressText={progressText}
- />
</div>
- </>
+ );
+ }
+
+ return (
+ <div className="my-1 flex items-center gap-2.5">
+ <span className="sr-only" aria-live="polite" aria-atomic="true">
+ {progressText}
+ </span>
+ {showSources && <StackedFavicons sources={processedSources} start={-5} />}
+ <Globe className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <span className="tool-status-text shimmer font-medium text-text-secondary">
+ {progressText}
+ </span>
+ </div>
);
}
diff --git a/client/src/components/Chat/Messages/Content/__tests__/AgentHandoff.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AgentHandoff.test.tsx
new file mode 100644
index 0000000000..7a68d0a182
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/AgentHandoff.test.tsx
@@ -0,0 +1,97 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { render, screen } from '@testing-library/react';
+import AgentHandoff from '../AgentHandoff';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => {
+ const translations: Record<string, string> = {
+ com_ui_transferred_to: 'Transferred to',
+ com_ui_agent: 'Agent',
+ com_ui_handoff_instructions: 'Handoff instructions',
+ };
+ return translations[key] || key;
+ },
+ useExpandCollapse: (isExpanded: boolean) => ({
+ style: {
+ display: 'grid',
+ gridTemplateRows: isExpanded ? '1fr' : '0fr',
+ opacity: isExpanded ? 1 : 0,
+ },
+ ref: { current: null },
+ }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useAgentsMapContext: () => ({
+ 'agent-123': { name: 'Test Agent' },
+ }),
+}));
+
+jest.mock('~/components/Share/MessageIcon', () => ({
+ __esModule: true,
+ default: () => <div data-testid="message-icon" />,
+}));
+
+jest.mock('lucide-react', () => ({
+ ChevronDown: () => <span data-testid="chevron-down" />,
+}));
+
+jest.mock('~/utils', () => ({
+ cn: (...classes: (string | boolean | undefined)[]) => classes.filter(Boolean).join(' '),
+}));
+
+const renderAgentHandoff = (props: {
+ name: string;
+ args: string | Record<string, unknown>;
+ output?: string | null;
+}) =>
+ render(
+ <RecoilRoot>
+ <AgentHandoff {...props} />
+ </RecoilRoot>,
+ );
+
+describe('AgentHandoff - A11Y accessibility stubs', () => {
+ it('A11Y-01: renders a semantic button element when hasInfo is true', () => {
+ renderAgentHandoff({
+ name: 'lc_transfer_to_agent-123',
+ args: '{"key":"value"}',
+ });
+
+ const button = screen.getByRole('button');
+ expect(button.tagName).toBe('BUTTON');
+ });
+
+ it('A11Y-02: button has aria-label describing the handoff target', () => {
+ renderAgentHandoff({
+ name: 'lc_transfer_to_agent-123',
+ args: '{"key":"value"}',
+ });
+
+ const button = screen.getByRole('button');
+ expect(button).toHaveAttribute('aria-label');
+ expect(button.getAttribute('aria-label')).toContain('Transferred to');
+ expect(button.getAttribute('aria-label')).toContain('Test Agent');
+ });
+
+ it('A11Y-03: button has focus-visible ring classes', () => {
+ renderAgentHandoff({
+ name: 'lc_transfer_to_agent-123',
+ args: '{"key":"value"}',
+ });
+
+ const button = screen.getByRole('button');
+ expect(button.className).toContain('focus-visible:ring-2');
+ });
+
+ it('A11Y-03: disabled button is rendered when hasInfo is false', () => {
+ renderAgentHandoff({
+ name: 'lc_transfer_to_agent-123',
+ args: '',
+ });
+
+ const button = screen.getByRole('button');
+ expect(button).toBeDisabled();
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ImageGen.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ImageGen.test.tsx
new file mode 100644
index 0000000000..4dc809e1fa
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/ImageGen.test.tsx
@@ -0,0 +1,215 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { render, screen } from '@testing-library/react';
+import ImageGen from '../Parts/OpenAIImageGen/OpenAIImageGen';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => {
+ const translations: Record<string, string> = {
+ com_ui_generating_image: 'Generating image...',
+ com_ui_image_created: 'Image created',
+ com_ui_image_gen_failed: 'Image generation failed',
+ com_ui_getting_started: 'Getting started',
+ com_ui_creating_image: 'Creating image',
+ com_ui_adding_details: 'Adding details',
+ com_ui_final_touch: 'Final touch',
+ com_ui_error: 'Error',
+ };
+ return translations[key] || key;
+ },
+ useProgress: (initialProgress: number) => (initialProgress >= 1 ? 1 : initialProgress),
+}));
+
+const getProgressLabel = (progress: number) =>
+ progress >= 1 ? 'Image created' : 'Generating image...';
+
+jest.mock('../Parts/OpenAIImageGen/ProgressText', () => ({
+ __esModule: true,
+ default: ({
+ toolName,
+ progress,
+ error,
+ onClick,
+ hasInput,
+ isExpanded,
+ }: {
+ toolName: string;
+ progress: number;
+ error?: boolean;
+ onClick?: () => void;
+ hasInput?: boolean;
+ isExpanded?: boolean;
+ }) => (
+ <button
+ data-testid="progress-text"
+ data-tool-name={toolName}
+ data-progress={progress}
+ data-error={error}
+ data-has-input={hasInput}
+ data-is-expanded={isExpanded}
+ onClick={onClick}
+ type="button"
+ >
+ {error ? 'Error' : getProgressLabel(progress)}
+ </button>
+ ),
+}));
+
+jest.mock('@librechat/client', () => ({
+ PixelCard: (props: Record<string, unknown>) => (
+ <div data-testid="pixel-card" data-progress={props.progress} />
+ ),
+}));
+
+jest.mock('~/components/Chat/Messages/Content/Image', () => ({
+ __esModule: true,
+ default: () => <div data-testid="image" />,
+}));
+
+jest.mock('../ToolOutput', () => ({
+ ToolIcon: ({ type, isAnimating }: { type: string; isAnimating?: boolean }) => (
+ <span data-testid="tool-icon" data-type={type} data-animating={isAnimating} />
+ ),
+ isError: (output: string) => typeof output === 'string' && output.toLowerCase().includes('error'),
+}));
+
+jest.mock('~/utils', () => ({
+ scaleImage: () => ({ width: '512px', height: '512px' }),
+ logger: { error: jest.fn(), debug: jest.fn() },
+ cn: (...classes: (string | boolean | undefined)[]) => classes.filter(Boolean).join(' '),
+}));
+
+const defaultProps = {
+ initialProgress: 1,
+ isSubmitting: false,
+ toolName: 'image_gen_oai',
+ args: '{}',
+ output: '',
+};
+
+const renderImageGen = (props: Partial<typeof defaultProps> = {}) =>
+ render(
+ <RecoilRoot>
+ <ImageGen {...defaultProps} {...props} />
+ </RecoilRoot>,
+ );
+
+describe('ImageGen - LGCY-01: Modern visual patterns', () => {
+ it('renders ToolIcon with type="image_gen" for agent-style tools', () => {
+ renderImageGen({
+ toolName: 'image_gen_oai',
+ isSubmitting: false,
+ initialProgress: 1,
+ args: '{}',
+ output: '',
+ });
+
+ const icon = screen.queryByTestId('tool-icon');
+ expect(icon).toBeInTheDocument();
+ expect(icon).toHaveAttribute('data-type', 'image_gen');
+ });
+
+ it('renders ToolIcon with type="image_gen" for legacy tools', () => {
+ renderImageGen({
+ initialProgress: 1,
+ args: '{"prompt":"test"}',
+ });
+
+ const icon = screen.queryByTestId('tool-icon');
+ expect(icon).toBeInTheDocument();
+ });
+
+ it('does not render ProgressCircle', () => {
+ renderImageGen();
+
+ expect(screen.queryByTestId('progress-circle')).not.toBeInTheDocument();
+ expect(document.querySelector('.progress-circle')).toBeNull();
+ });
+
+ it('renders PixelCard during agent-style image generation', () => {
+ renderImageGen({
+ isSubmitting: true,
+ initialProgress: 0.5,
+ toolName: 'image_gen_oai',
+ args: '{"size":"1024x1024"}',
+ });
+
+ expect(screen.getByTestId('pixel-card')).toBeInTheDocument();
+ });
+});
+
+describe('ImageGen - LGCY-01: Legacy and agent-style unification', () => {
+ it('accepts legacy props (initialProgress + args only)', () => {
+ const { container } = render(
+ <RecoilRoot>
+ <ImageGen
+ initialProgress={1}
+ isSubmitting={false}
+ toolName=""
+ args='{"prompt":"a cat"}'
+ output=""
+ />
+ </RecoilRoot>,
+ );
+
+ expect(container).toBeTruthy();
+ });
+
+ it('accepts agent-style props (full set)', () => {
+ const { container } = renderImageGen({
+ initialProgress: 1,
+ isSubmitting: false,
+ toolName: 'image_gen_oai',
+ args: '{"prompt":"a cat","size":"1024x1024"}',
+ output: 'https://example.com/image.png',
+ });
+
+ expect(container).toBeTruthy();
+ });
+
+ it('handles history reload state (initialProgress=1, no isSubmitting)', () => {
+ renderImageGen({
+ initialProgress: 1,
+ isSubmitting: false,
+ });
+
+ const progressText = screen.getByTestId('progress-text');
+ expect(progressText).toHaveTextContent('Image created');
+ });
+});
+
+describe('ImageGen - LGCY-03: Localization', () => {
+ it('does not contain hardcoded "Creating Image" text', () => {
+ const { container } = renderImageGen({
+ isSubmitting: true,
+ initialProgress: 0.5,
+ args: '{}',
+ });
+
+ expect(container.textContent).not.toContain('Creating Image');
+ });
+
+ it('does not contain hardcoded "Finished." text', () => {
+ const { container } = renderImageGen({
+ initialProgress: 1,
+ isSubmitting: false,
+ });
+
+ expect(container.textContent).not.toContain('Finished.');
+ });
+});
+
+describe('ImageGen - A11Y-04: screen reader status announcements', () => {
+ it('includes sr-only aria-live region for status announcements', () => {
+ renderImageGen({
+ initialProgress: 1,
+ isSubmitting: false,
+ args: '{"prompt":"test"}',
+ output: '',
+ });
+
+ const liveRegion = document.querySelector('[aria-live="polite"]');
+ expect(liveRegion).not.toBeNull();
+ expect(liveRegion!.className).toContain('sr-only');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/OpenAIImageGen.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/OpenAIImageGen.test.tsx
index ef8ac2807a..188dff5a09 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/OpenAIImageGen.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/OpenAIImageGen.test.tsx
@@ -3,6 +3,7 @@ import { render, screen } from '@testing-library/react';
import OpenAIImageGen from '../Parts/OpenAIImageGen/OpenAIImageGen';
jest.mock('~/utils', () => ({
+ scaleImage: () => ({ width: '512px', height: '512px' }),
cn: (...classes: (string | boolean | undefined | null)[]) =>
classes
.flat(Infinity)
@@ -12,25 +13,13 @@ jest.mock('~/utils', () => ({
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
+ useProgress: (initialProgress: number) => (initialProgress >= 1 ? 1 : initialProgress),
}));
jest.mock('~/components/Chat/Messages/Content/Image', () => ({
__esModule: true,
- default: ({
- altText,
- imagePath,
- className,
- }: {
- altText: string;
- imagePath: string;
- className?: string;
- }) => (
- <div
- data-testid="image-component"
- data-alt={altText}
- data-src={imagePath}
- className={className}
- />
+ default: ({ altText, imagePath }: { altText: string; imagePath: string }) => (
+ <div data-testid="image-component" data-alt={altText} data-src={imagePath} />
),
}));
@@ -40,6 +29,13 @@ jest.mock('@librechat/client', () => ({
),
}));
+jest.mock('../ToolOutput', () => ({
+ ToolIcon: ({ type, isAnimating }: { type: string; isAnimating?: boolean }) => (
+ <span data-testid="tool-icon" data-type={type} data-animating={isAnimating} />
+ ),
+ isError: (output: string) => typeof output === 'string' && output.toLowerCase().includes('error'),
+}));
+
jest.mock('../Parts/OpenAIImageGen/ProgressText', () => ({
__esModule: true,
default: ({ progress, error }: { progress: number; error: boolean }) => (
@@ -72,14 +68,7 @@ describe('OpenAIImageGen', () => {
expect(screen.getByTestId('image-component')).toBeInTheDocument();
});
- it('hides Image with invisible absolute while progress < 1', () => {
- render(<OpenAIImageGen {...defaultProps} initialProgress={0.5} />);
- const image = screen.getByTestId('image-component');
- expect(image.className).toContain('invisible');
- expect(image.className).toContain('absolute');
- });
-
- it('shows Image without hiding classes when progress >= 1', () => {
+ it('shows Image when progress >= 1', () => {
render(
<OpenAIImageGen
{...defaultProps}
@@ -94,9 +83,7 @@ describe('OpenAIImageGen', () => {
]}
/>,
);
- const image = screen.getByTestId('image-component');
- expect(image.className).not.toContain('invisible');
- expect(image.className).not.toContain('absolute');
+ expect(screen.getByTestId('image-component')).toBeInTheDocument();
});
});
@@ -112,26 +99,23 @@ describe('OpenAIImageGen', () => {
});
});
- describe('layout classes', () => {
- it('applies max-h-[45vh] to the outer container', () => {
- const { container } = render(<OpenAIImageGen {...defaultProps} />);
- const outerDiv = container.querySelector('[class*="max-h-"]');
- expect(outerDiv?.className).toContain('max-h-[45vh]');
+ describe('ToolIcon', () => {
+ it('renders ToolIcon with type="image_gen"', () => {
+ render(<OpenAIImageGen {...defaultProps} />);
+ const icon = screen.getByTestId('tool-icon');
+ expect(icon).toHaveAttribute('data-type', 'image_gen');
});
- it('applies h-[45vh] w-full to inner container during loading', () => {
- const { container } = render(<OpenAIImageGen {...defaultProps} initialProgress={0.5} />);
- const innerDiv = container.querySelector('[class*="h-[45vh]"]');
- expect(innerDiv).not.toBeNull();
- expect(innerDiv?.className).toContain('w-full');
+ it('sets isAnimating when in progress', () => {
+ render(<OpenAIImageGen {...defaultProps} initialProgress={0.5} />);
+ const icon = screen.getByTestId('tool-icon');
+ expect(icon).toHaveAttribute('data-animating', 'true');
});
- it('applies w-auto to inner container when complete', () => {
- const { container } = render(
- <OpenAIImageGen {...defaultProps} initialProgress={1} isSubmitting={false} />,
- );
- const overflowDiv = container.querySelector('[class*="overflow-hidden"]');
- expect(overflowDiv?.className).toContain('w-auto');
+ it('sets isAnimating=false when complete', () => {
+ render(<OpenAIImageGen {...defaultProps} initialProgress={1} isSubmitting={false} />);
+ const icon = screen.getByTestId('tool-icon');
+ expect(icon).toHaveAttribute('data-animating', 'false');
});
});
@@ -142,10 +126,8 @@ describe('OpenAIImageGen', () => {
});
it('handles invalid JSON args gracefully', () => {
- const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
render(<OpenAIImageGen {...defaultProps} args="invalid json" />);
expect(screen.getByTestId('image-component')).toBeInTheDocument();
- consoleSpy.mockRestore();
});
it('handles object args', () => {
diff --git a/client/src/components/Chat/Messages/Content/__tests__/RetrievalCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/RetrievalCall.test.tsx
new file mode 100644
index 0000000000..6df45a3210
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/RetrievalCall.test.tsx
@@ -0,0 +1,276 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { render, screen, fireEvent } from '@testing-library/react';
+import type { TAttachment } from 'librechat-data-provider';
+import RetrievalCall from '../RetrievalCall';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => {
+ const translations: Record<string, string> = {
+ com_ui_searching_files: 'Searching files...',
+ com_ui_retrieved_files: 'Retrieved files',
+ com_ui_retrieval_failed: 'failed',
+ com_ui_tool_failed: 'failed',
+ com_ui_preview: 'Preview',
+ com_ui_relevance: 'Relevance',
+ com_file_pages: 'Pages',
+ };
+ return translations[key] || key;
+ },
+ useProgress: (initialProgress: number) => (initialProgress >= 1 ? 1 : initialProgress),
+ useExpandCollapse: (isExpanded: boolean) => ({
+ style: isExpanded
+ ? { display: 'grid', gridTemplateRows: '1fr', opacity: 1 }
+ : { display: 'grid', gridTemplateRows: '0fr', opacity: 0 },
+ ref: { current: null },
+ }),
+}));
+
+jest.mock('../ProgressText', () => ({
+ __esModule: true,
+ default: ({
+ onClick,
+ inProgressText,
+ finishedText,
+ icon,
+ hasInput,
+ isExpanded,
+ error,
+ errorSuffix,
+ }: {
+ onClick?: () => void;
+ inProgressText: string;
+ finishedText: string;
+ icon?: React.ReactNode;
+ hasInput?: boolean;
+ isExpanded?: boolean;
+ error?: boolean;
+ errorSuffix?: string;
+ }) => (
+ <div
+ onClick={onClick}
+ data-testid="progress-text"
+ data-in-progress={inProgressText}
+ data-finished={finishedText}
+ data-has-input={hasInput}
+ data-expanded={isExpanded}
+ data-error={error}
+ data-error-suffix={errorSuffix}
+ >
+ {icon}
+ {finishedText || inProgressText}
+ </div>
+ ),
+}));
+
+jest.mock('../ToolOutput', () => ({
+ ToolIcon: ({ type, isAnimating }: { type: string; isAnimating?: boolean }) => (
+ <span data-testid="tool-icon" data-type={type} data-animating={isAnimating} />
+ ),
+ OutputRenderer: ({ text }: { text: string }) => <pre data-testid="output-renderer">{text}</pre>,
+ isError: (output: string) => typeof output === 'string' && output.toLowerCase().includes('error'),
+}));
+
+jest.mock('~/utils', () => ({
+ cn: (...classes: (string | boolean | undefined)[]) => classes.filter(Boolean).join(' '),
+ logger: { error: jest.fn(), debug: jest.fn() },
+}));
+
+jest.mock('~/data-provider', () => ({
+ useGetFiles: jest.fn(() => ({ data: [] })),
+}));
+
+jest.mock('../FilePreviewDialog', () => ({
+ __esModule: true,
+ default: ({ open, fileId, fileName }: { open: boolean; fileId?: string; fileName: string }) =>
+ open ? (
+ <div data-testid="file-preview-dialog" data-file-id={fileId}>
+ {fileName}
+ </div>
+ ) : null,
+}));
+
+const defaultProps = {
+ initialProgress: 1,
+ isSubmitting: false,
+};
+
+const renderRetrievalCall = (
+ props: Partial<typeof defaultProps & { output?: string; attachments?: TAttachment[] }> = {},
+) =>
+ render(
+ <RecoilRoot>
+ <RetrievalCall {...defaultProps} {...props} />
+ </RecoilRoot>,
+ );
+
+const mockedUseGetFiles = jest.requireMock('~/data-provider').useGetFiles as jest.Mock;
+
+beforeEach(() => {
+ mockedUseGetFiles.mockReturnValue({ data: [] });
+});
+
+describe('RetrievalCall - LGCY-02: Modern visual patterns', () => {
+ it('renders ToolIcon with type="file_search"', () => {
+ renderRetrievalCall({ initialProgress: 1, isSubmitting: false });
+
+ const icon = screen.getByTestId('tool-icon');
+ expect(icon).toBeInTheDocument();
+ expect(icon).toHaveAttribute('data-type', 'file_search');
+ });
+
+ it('does not render ProgressCircle', () => {
+ renderRetrievalCall();
+
+ expect(screen.queryByTestId('progress-circle')).not.toBeInTheDocument();
+ });
+
+ it('does not render InProgressCall', () => {
+ renderRetrievalCall();
+
+ expect(screen.queryByTestId('in-progress-call')).not.toBeInTheDocument();
+ });
+
+ it('does not render RetrievalIcon', () => {
+ renderRetrievalCall();
+
+ expect(screen.queryByTestId('retrieval-icon')).not.toBeInTheDocument();
+ });
+});
+
+describe('RetrievalCall - LGCY-02: Collapsible output panel', () => {
+ it('shows collapsible panel when output exists and is clicked', () => {
+ renderRetrievalCall({
+ output: 'File: notes.txt\nRelevance: 0.8\nContent: file results here',
+ initialProgress: 1,
+ isSubmitting: false,
+ });
+
+ const progressText = screen.getByTestId('progress-text');
+ fireEvent.click(progressText);
+
+ expect(screen.getByText('file results here')).toBeInTheDocument();
+ });
+
+ it('does not show panel when output is undefined', () => {
+ renderRetrievalCall({ initialProgress: 1, isSubmitting: false });
+
+ expect(screen.queryByText('file results here')).not.toBeInTheDocument();
+ });
+
+ it('does not show panel when output contains error', () => {
+ renderRetrievalCall({
+ output: 'error processing tool',
+ initialProgress: 1,
+ isSubmitting: false,
+ });
+
+ expect(screen.queryByText('error processing tool')).not.toBeInTheDocument();
+ });
+});
+
+describe('RetrievalCall - LGCY-03: Localization', () => {
+ it('uses localized in-progress text', () => {
+ renderRetrievalCall({ initialProgress: 0.5, isSubmitting: true });
+
+ const progressText = screen.getByTestId('progress-text');
+ expect(progressText).toHaveAttribute('data-in-progress', 'Searching files...');
+ });
+
+ it('uses localized finished text', () => {
+ renderRetrievalCall({ initialProgress: 1, isSubmitting: false });
+
+ const progressText = screen.getByTestId('progress-text');
+ expect(progressText).toHaveAttribute('data-finished', 'Retrieved files');
+ });
+
+ it('does not contain hardcoded "Searching my knowledge" text', () => {
+ const { container } = renderRetrievalCall({ initialProgress: 0.5, isSubmitting: true });
+
+ expect(container.textContent).not.toContain('Searching my knowledge');
+ });
+
+ it('does not contain hardcoded "Used Retrieval" text', () => {
+ const { container } = renderRetrievalCall({ initialProgress: 1, isSubmitting: false });
+
+ expect(container.textContent).not.toContain('Used Retrieval');
+ });
+});
+
+describe('RetrievalCall - A11Y-04: screen reader status announcements', () => {
+ it('includes sr-only aria-live region for status announcements', () => {
+ renderRetrievalCall({
+ initialProgress: 1,
+ isSubmitting: false,
+ output: 'files found',
+ });
+
+ const liveRegion = document.querySelector('[aria-live="polite"]');
+ expect(liveRegion).not.toBeNull();
+ expect(liveRegion!.className).toContain('sr-only');
+ });
+});
+
+describe('RetrievalCall - file preview resolution', () => {
+ it('resolves parsed filenames against known files and opens preview', () => {
+ mockedUseGetFiles.mockReturnValue({
+ data: [
+ {
+ file_id: 'file-123',
+ filename: 'Tutorial Imazing.pdf',
+ bytes: 2048,
+ type: 'application/pdf',
+ },
+ ],
+ });
+
+ renderRetrievalCall({
+ initialProgress: 1,
+ isSubmitting: false,
+ output:
+ 'File: Tutorial_Imazing.pdf\nRelevance: 0.4442\nContent: Example content from parsed output',
+ });
+
+ fireEvent.click(screen.getByTestId('progress-text'));
+ fireEvent.click(screen.getByRole('button', { name: 'Preview: Tutorial Imazing.pdf' }));
+
+ expect(screen.getByTestId('file-preview-dialog')).toHaveAttribute('data-file-id', 'file-123');
+ });
+
+ it('keeps multiple parsed results clickable when only one attachment source is available', () => {
+ renderRetrievalCall({
+ initialProgress: 1,
+ isSubmitting: false,
+ output:
+ 'File: Tutorial_Imazing.pdf\nRelevance: 0.4843\nContent: First result\n---\nFile: Tutorial_Imazing.pdf\nRelevance: 0.3751\nContent: Second result',
+ attachments: [
+ {
+ type: 'file_search',
+ toolCallId: 'call-1',
+ file_search: {
+ sources: [
+ {
+ fileId: 'file-123',
+ fileName: 'Tutorial Imazing.pdf',
+ relevance: 0.4843,
+ content: 'First result',
+ pages: [1],
+ pageRelevance: { 1: 0.4843 },
+ metadata: {
+ fileType: 'application/pdf',
+ fileBytes: 2048,
+ },
+ },
+ ],
+ },
+ },
+ ] as any,
+ });
+
+ fireEvent.click(screen.getByTestId('progress-text'));
+
+ expect(screen.getAllByRole('button', { name: 'Preview: Tutorial Imazing.pdf' })).toHaveLength(
+ 2,
+ );
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
index d1f4f89213..41356412f6 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
@@ -1,7 +1,7 @@
import React from 'react';
-import { render, screen, fireEvent } from '@testing-library/react';
import { RecoilRoot } from 'recoil';
import { Tools } from 'librechat-data-provider';
+import { render, screen, fireEvent } from '@testing-library/react';
import ToolCall from '../ToolCall';
// Mock dependencies
@@ -17,10 +17,24 @@ jest.mock('~/hooks', () => ({
com_ui_cancelled: 'Cancelled',
com_ui_requires_auth: 'Requires authentication',
com_assistants_allow_sites_you_trust: 'Only allow sites you trust',
+ com_ui_via_server: `via ${values?.[0]}`,
+ com_ui_tool_failed: 'failed',
};
return translations[key] || key;
},
useProgress: (initialProgress: number) => (initialProgress >= 1 ? 1 : initialProgress),
+ useExpandCollapse: (isExpanded: boolean) => ({
+ style: {
+ display: 'grid',
+ gridTemplateRows: isExpanded ? '1fr' : '0fr',
+ opacity: isExpanded ? 1 : 0,
+ },
+ ref: { current: null },
+ }),
+}));
+
+jest.mock('~/hooks/MCP', () => ({
+ useMCPIconMap: () => new Map(),
}));
jest.mock('~/components/Chat/Messages/Content/MessageContent', () => ({
@@ -40,7 +54,9 @@ jest.mock('../ToolCallInfo', () => ({
jest.mock('../ProgressText', () => ({
__esModule: true,
default: ({ onClick, inProgressText, finishedText, _error, _hasInput, _isExpanded }: any) => (
- <div onClick={onClick}>{finishedText || inProgressText}</div>
+ <div data-testid="progress-text" onClick={onClick}>
+ {finishedText || inProgressText}
+ </div>
),
}));
@@ -50,7 +66,7 @@ jest.mock('../Parts', () => ({
),
}));
-jest.mock('~/components/ui', () => ({
+jest.mock('@librechat/client', () => ({
Button: ({ children, onClick, ...props }: any) => (
<button onClick={onClick} {...props}>
{children}
@@ -102,9 +118,9 @@ describe('ToolCall', () => {
},
];
- renderWithRecoil(<ToolCall {...mockProps} attachments={attachments} />);
+ renderWithRecoil(<ToolCall {...mockProps} attachments={attachments as any} />);
- fireEvent.click(screen.getByText('Completed testFunction'));
+ fireEvent.click(screen.getByTestId('progress-text'));
const toolCallInfo = screen.getByTestId('tool-call-info');
expect(toolCallInfo).toBeInTheDocument();
@@ -116,7 +132,7 @@ describe('ToolCall', () => {
it('should pass empty array when no attachments', () => {
renderWithRecoil(<ToolCall {...mockProps} />);
- fireEvent.click(screen.getByText('Completed testFunction'));
+ fireEvent.click(screen.getByTestId('progress-text'));
const toolCallInfo = screen.getByTestId('tool-call-info');
const attachmentsData = toolCallInfo.getAttribute('data-attachments');
@@ -145,9 +161,9 @@ describe('ToolCall', () => {
},
];
- renderWithRecoil(<ToolCall {...mockProps} attachments={attachments} />);
+ renderWithRecoil(<ToolCall {...mockProps} attachments={attachments as any} />);
- fireEvent.click(screen.getByText('Completed testFunction'));
+ fireEvent.click(screen.getByTestId('progress-text'));
const toolCallInfo = screen.getByTestId('tool-call-info');
const attachmentsData = toolCallInfo.getAttribute('data-attachments');
@@ -169,7 +185,7 @@ describe('ToolCall', () => {
},
];
- renderWithRecoil(<ToolCall {...mockProps} attachments={attachments} />);
+ renderWithRecoil(<ToolCall {...mockProps} attachments={attachments as any} />);
const attachmentGroup = screen.getByTestId('attachment-group');
expect(attachmentGroup).toBeInTheDocument();
@@ -190,54 +206,30 @@ describe('ToolCall', () => {
});
describe('tool call info visibility', () => {
- it('should toggle tool call info when clicking header', () => {
+ it('should toggle tool call info expand/collapse when clicking header', () => {
renderWithRecoil(<ToolCall {...mockProps} />);
- // Initially closed
- expect(screen.queryByTestId('tool-call-info')).not.toBeInTheDocument();
+ // ToolCallInfo is always in the DOM (CSS expand/collapse), but initially collapsed
+ const toolCallInfo = screen.getByTestId('tool-call-info');
+ expect(toolCallInfo).toBeInTheDocument();
+
+ // The expand wrapper starts collapsed (showInfo=false, autoExpand=false)
+ const expandWrapper = toolCallInfo.closest('[style]')?.parentElement;
+ expect(expandWrapper).toBeDefined();
- // Click to open
- fireEvent.click(screen.getByText('Completed testFunction'));
+ // Click to expand
+ fireEvent.click(screen.getByTestId('progress-text'));
expect(screen.getByTestId('tool-call-info')).toBeInTheDocument();
-
- // Click to close
- fireEvent.click(screen.getByText('Completed testFunction'));
- expect(screen.queryByTestId('tool-call-info')).not.toBeInTheDocument();
});
- it('should pass all required props to ToolCallInfo', () => {
- const attachments = [
- {
- type: Tools.ui_resources,
- messageId: 'msg123',
- toolCallId: 'tool456',
- conversationId: 'conv789',
- [Tools.ui_resources]: {
- '0': { type: 'button', label: 'Test' },
- },
- },
- ];
-
- // Use a name with domain separator (_action_) and domain separator (---)
- const propsWithDomain = {
- ...mockProps,
- name: 'testFunction_action_test---domain---com', // domain will be extracted and --- replaced with dots
- attachments,
- };
-
- renderWithRecoil(<ToolCall {...propsWithDomain} />);
-
- fireEvent.click(screen.getByText('Completed action on test.domain.com'));
+ it('should pass input and output props to ToolCallInfo', () => {
+ renderWithRecoil(<ToolCall {...mockProps} />);
const toolCallInfo = screen.getByTestId('tool-call-info');
const props = JSON.parse(toolCallInfo.textContent!);
expect(props.input).toBe('{"test": "input"}');
expect(props.output).toBe('Test output');
- expect(props.function_name).toBe('testFunction');
- // Domain is extracted from name and --- are replaced with dots
- expect(props.domain).toBe('test.domain.com');
- expect(props.pendingAuth).toBe(false);
});
});
@@ -268,35 +260,17 @@ describe('ToolCall', () => {
window.open = originalOpen;
});
- it('should pass pendingAuth as true when auth is pending', () => {
- renderWithRecoil(
- <ToolCall
- {...mockProps}
- auth="https://auth.example.com" // Need auth URL to extract domain
- initialProgress={0.5} // Less than 1
- isSubmitting={true} // Still submitting
- />,
- );
-
- fireEvent.click(screen.getByText('Completed testFunction'));
-
- const toolCallInfo = screen.getByTestId('tool-call-info');
- const props = JSON.parse(toolCallInfo.textContent!);
- expect(props.pendingAuth).toBe(true);
- });
-
it('should not show auth section when cancelled', () => {
renderWithRecoil(
<ToolCall
{...mockProps}
auth="https://auth.example.com"
- authDomain="example.com"
- progress={0.5}
- cancelled={true}
+ initialProgress={0.5}
+ isSubmitting={false} // Not submitting + progress < 1 = cancelled
/>,
);
- expect(screen.queryByText('Sign in to example.com')).not.toBeInTheDocument();
+ expect(screen.queryByText('Sign in to auth.example.com')).not.toBeInTheDocument();
});
it('should not show auth section when progress is complete', () => {
@@ -304,21 +278,18 @@ describe('ToolCall', () => {
<ToolCall
{...mockProps}
auth="https://auth.example.com"
- authDomain="example.com"
- progress={1}
- cancelled={false}
+ initialProgress={1}
+ isSubmitting={false}
/>,
);
- expect(screen.queryByText('Sign in to example.com')).not.toBeInTheDocument();
+ expect(screen.queryByText('Sign in to auth.example.com')).not.toBeInTheDocument();
});
});
describe('edge cases', () => {
it('should handle undefined args', () => {
- renderWithRecoil(<ToolCall {...mockProps} args={undefined} />);
-
- fireEvent.click(screen.getByText('Completed testFunction'));
+ renderWithRecoil(<ToolCall {...mockProps} args={undefined as any} />);
const toolCallInfo = screen.getByTestId('tool-call-info');
const props = JSON.parse(toolCallInfo.textContent!);
@@ -328,21 +299,16 @@ describe('ToolCall', () => {
it('should handle null output', () => {
renderWithRecoil(<ToolCall {...mockProps} output={null} />);
- fireEvent.click(screen.getByText('Completed testFunction'));
-
const toolCallInfo = screen.getByTestId('tool-call-info');
const props = JSON.parse(toolCallInfo.textContent!);
expect(props.output).toBeNull();
});
- it('should handle missing domain', () => {
- renderWithRecoil(<ToolCall {...mockProps} domain={undefined} authDomain={undefined} />);
-
- fireEvent.click(screen.getByText('Completed testFunction'));
+ it('should handle simple function name without domain', () => {
+ renderWithRecoil(<ToolCall {...mockProps} name="simpleName" />);
const toolCallInfo = screen.getByTestId('tool-call-info');
- const props = JSON.parse(toolCallInfo.textContent!);
- expect(props.domain).toBe('');
+ expect(toolCallInfo).toBeInTheDocument();
});
it('should handle complex nested attachments', () => {
@@ -367,9 +333,9 @@ describe('ToolCall', () => {
},
];
- renderWithRecoil(<ToolCall {...mockProps} attachments={complexAttachments} />);
+ renderWithRecoil(<ToolCall {...mockProps} attachments={complexAttachments as any} />);
- fireEvent.click(screen.getByText('Completed testFunction'));
+ fireEvent.click(screen.getByTestId('progress-text'));
const toolCallInfo = screen.getByTestId('tool-call-info');
const attachmentsData = toolCallInfo.getAttribute('data-attachments');
@@ -379,4 +345,22 @@ describe('ToolCall', () => {
expect(JSON.parse(attachmentGroup.textContent!)).toEqual(complexAttachments);
});
});
+
+ describe('A11Y-04: screen reader status announcements', () => {
+ it('includes sr-only aria-live region for status announcements', () => {
+ renderWithRecoil(
+ <ToolCall
+ {...mockProps}
+ initialProgress={1}
+ isSubmitting={false}
+ name="test_func"
+ output="result"
+ />,
+ );
+
+ const liveRegion = document.querySelector('[aria-live="polite"]');
+ expect(liveRegion).not.toBeNull();
+ expect(liveRegion!.className).toContain('sr-only');
+ });
+ });
});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsx
index 3e74504fc2..4a4d80ae8d 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallInfo.test.tsx
@@ -1,24 +1,33 @@
import React from 'react';
import { Tools } from 'librechat-data-provider';
import { UIResourceRenderer } from '@mcp-ui/client';
-import { render, screen } from '@testing-library/react';
+import { render, screen, fireEvent } from '@testing-library/react';
import type { TAttachment } from 'librechat-data-provider';
import UIResourceCarousel from '~/components/Chat/Messages/Content/UIResourceCarousel';
import ToolCallInfo from '~/components/Chat/Messages/Content/ToolCallInfo';
// Mock the dependencies
jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string, values?: any) => {
+ useLocalize: () => (key: string) => {
const translations: Record<string, string> = {
- com_assistants_domain_info: `Used ${values?.[0]}`,
- com_assistants_function_use: `Used ${values?.[0]}`,
- com_assistants_action_attempt: `Attempted to use ${values?.[0]}`,
- com_assistants_attempt_info: 'Attempted to use function',
- com_ui_result: 'Result',
- com_ui_ui_resources: 'UI Resources',
+ com_ui_parameters: 'Parameters',
};
return translations[key] || key;
},
+ useExpandCollapse: (isExpanded: boolean) => ({
+ style: {
+ display: 'grid',
+ gridTemplateRows: isExpanded ? '1fr' : '0fr',
+ opacity: isExpanded ? 1 : 0,
+ },
+ ref: { current: null },
+ }),
+}));
+
+jest.mock('~/Providers', () => ({
+ useMessagesOperations: () => ({
+ ask: jest.fn(),
+ }),
}));
jest.mock('@mcp-ui/client', () => ({
@@ -30,18 +39,22 @@ jest.mock('../UIResourceCarousel', () => ({
default: jest.fn(() => null),
}));
-// Add TextEncoder/TextDecoder polyfill for Jest environment
-import { TextEncoder, TextDecoder } from 'util';
+jest.mock('../ToolOutput', () => ({
+ OutputRenderer: ({ text }: { text: string }) => <div data-testid="output-renderer">{text}</div>,
+}));
-if (typeof global.TextEncoder === 'undefined') {
- global.TextEncoder = TextEncoder as any;
- global.TextDecoder = TextDecoder as any;
-}
+jest.mock('~/utils', () => ({
+ handleUIAction: jest.fn(),
+ cn: (...classes: any[]) => classes.filter(Boolean).join(' '),
+}));
+
+jest.mock('lucide-react', () => ({
+ ChevronDown: () => <span>{'ChevronDown'}</span>,
+}));
describe('ToolCallInfo', () => {
const mockProps = {
input: '{"test": "input"}',
- function_name: 'testFunction',
};
beforeEach(() => {
@@ -61,11 +74,10 @@ describe('ToolCallInfo', () => {
messageId: 'msg123',
toolCallId: 'tool456',
conversationId: 'conv789',
- [Tools.ui_resources]: [uiResource],
+ [Tools.ui_resources]: [uiResource] as any,
},
];
- // Need output for ui_resources to render
render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);
// Should render UIResourceRenderer for single resource
@@ -85,7 +97,6 @@ describe('ToolCallInfo', () => {
});
it('should render carousel for multiple ui_resources from attachments', () => {
- // To test multiple resources, we can use a single attachment with multiple resources
const attachments: TAttachment[] = [
{
type: Tools.ui_resources,
@@ -96,11 +107,10 @@ describe('ToolCallInfo', () => {
{ type: 'text', data: 'Resource 1' },
{ type: 'text', data: 'Resource 2' },
{ type: 'text', data: 'Resource 3' },
- ],
+ ] as any,
},
];
- // Need output for ui_resources to render
render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);
// Should render carousel for multiple resources
@@ -119,50 +129,15 @@ describe('ToolCallInfo', () => {
expect(UIResourceRenderer).not.toHaveBeenCalled();
});
- it('should handle attachments with normal output', () => {
- const attachments: TAttachment[] = [
- {
- type: Tools.ui_resources,
- messageId: 'msg123',
- toolCallId: 'tool456',
- conversationId: 'conv789',
- [Tools.ui_resources]: [{ type: 'text', data: 'UI Resource' }],
- },
- ];
-
- const output = JSON.stringify([
- { type: 'text', text: 'Regular output 1' },
- { type: 'text', text: 'Regular output 2' },
- ]);
-
- const { container } = render(
- <ToolCallInfo {...mockProps} output={output} attachments={attachments} />,
- );
-
- // Check that the output is displayed normally
- const codeBlocks = container.querySelectorAll('code');
- const outputCode = codeBlocks[1]?.textContent; // Second code block is the output
-
- expect(outputCode).toContain('Regular output 1');
- expect(outputCode).toContain('Regular output 2');
-
- // UI resources should be rendered via attachments
- expect(UIResourceRenderer).toHaveBeenCalled();
- });
-
it('should handle no attachments', () => {
- const output = JSON.stringify([{ type: 'text', text: 'Regular output' }]);
-
- render(<ToolCallInfo {...mockProps} output={output} />);
+ render(<ToolCallInfo {...mockProps} output="Some output" />);
expect(UIResourceRenderer).not.toHaveBeenCalled();
expect(UIResourceCarousel).not.toHaveBeenCalled();
});
it('should handle empty attachments array', () => {
- const attachments: TAttachment[] = [];
-
- render(<ToolCallInfo {...mockProps} attachments={attachments} />);
+ render(<ToolCallInfo {...mockProps} attachments={[]} />);
expect(UIResourceRenderer).not.toHaveBeenCalled();
expect(UIResourceCarousel).not.toHaveBeenCalled();
@@ -183,101 +158,65 @@ describe('ToolCallInfo', () => {
render(<ToolCallInfo {...mockProps} attachments={attachments} />);
- // Should not render UI resources components for non-ui_resources attachments
expect(UIResourceRenderer).not.toHaveBeenCalled();
expect(UIResourceCarousel).not.toHaveBeenCalled();
});
});
describe('rendering logic', () => {
- it('should render UI Resources heading when ui_resources exist in attachments', () => {
- const attachments: TAttachment[] = [
- {
- type: Tools.ui_resources,
- messageId: 'msg123',
- toolCallId: 'tool456',
- conversationId: 'conv789',
- [Tools.ui_resources]: [{ type: 'text', data: 'Test' }],
- },
- ];
+ it('should render output when provided', () => {
+ render(<ToolCallInfo {...mockProps} output="Some output" />);
- // Need output for ui_resources section to render
- render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);
+ expect(screen.getByTestId('output-renderer')).toBeInTheDocument();
+ expect(screen.getByTestId('output-renderer').textContent).toBe('Some output');
+ });
- expect(screen.getByText('UI Resources')).toBeInTheDocument();
+ it('should render parameters toggle when input has JSON content', () => {
+ render(<ToolCallInfo {...mockProps} output="Some output" />);
+
+ expect(screen.getByText('Parameters')).toBeInTheDocument();
});
- it('should not render UI Resources heading when no ui_resources in attachments', () => {
- render(<ToolCallInfo {...mockProps} />);
+ it('should not render parameters toggle when input is empty', () => {
+ render(<ToolCallInfo input="" output="Some output" />);
- expect(screen.queryByText('UI Resources')).not.toBeInTheDocument();
+ expect(screen.queryByText('Parameters')).not.toBeInTheDocument();
});
- it('should pass correct props to UIResourceRenderer', () => {
- const uiResource = {
- type: 'form',
- data: { fields: [{ name: 'test', type: 'text' }] },
- };
+ it('should toggle parameters visibility when clicking', () => {
+ render(<ToolCallInfo {...mockProps} output="Some output" />);
+
+ const paramsButton = screen.getByText('Parameters');
+ expect(paramsButton.closest('button')).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.click(paramsButton.closest('button')!);
+ expect(paramsButton.closest('button')).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('should render ui_resources section when attachments have ui_resources', () => {
const attachments: TAttachment[] = [
{
type: Tools.ui_resources,
messageId: 'msg123',
toolCallId: 'tool456',
conversationId: 'conv789',
- [Tools.ui_resources]: [uiResource],
+ [Tools.ui_resources]: [{ type: 'text', data: 'Test' }] as any,
},
];
- // Need output for ui_resources to render
render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);
expect(UIResourceRenderer).toHaveBeenCalledWith(
expect.objectContaining({
- resource: uiResource,
- onUIAction: expect.any(Function),
- htmlProps: {
- autoResizeIframe: { width: true, height: true },
- },
+ resource: { type: 'text', data: 'Test' },
}),
expect.any(Object),
);
});
-
- it('should console.log when UIAction is triggered', async () => {
- const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
-
- const attachments: TAttachment[] = [
- {
- type: Tools.ui_resources,
- messageId: 'msg123',
- toolCallId: 'tool456',
- conversationId: 'conv789',
- [Tools.ui_resources]: [{ type: 'text', data: 'Test' }],
- },
- ];
-
- // Need output for ui_resources to render
- render(<ToolCallInfo {...mockProps} output="Some output" attachments={attachments} />);
-
- const mockUIResourceRenderer = UIResourceRenderer as jest.MockedFunction<
- typeof UIResourceRenderer
- >;
- const onUIAction = mockUIResourceRenderer.mock.calls[0]?.[0]?.onUIAction;
- const testResult = { action: 'submit', data: { test: 'value' } };
-
- if (onUIAction) {
- await onUIAction(testResult as any);
- }
-
- expect(consoleSpy).toHaveBeenCalledWith('Action:', testResult);
-
- consoleSpy.mockRestore();
- });
});
describe('backward compatibility', () => {
- it('should handle output with ui_resources for backward compatibility', () => {
+ it('should handle output with ui_resources metadata (ignored — uses attachments)', () => {
const output = JSON.stringify([
{ type: 'text', text: 'Regular output' },
{
@@ -302,7 +241,7 @@ describe('ToolCallInfo', () => {
messageId: 'msg123',
toolCallId: 'tool456',
conversationId: 'conv789',
- [Tools.ui_resources]: [{ type: 'attachment', data: 'From attachments' }],
+ [Tools.ui_resources]: [{ type: 'attachment', data: 'From attachments' }] as any,
},
];
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolIcon.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolIcon.test.tsx
new file mode 100644
index 0000000000..7faf18ad8b
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolIcon.test.tsx
@@ -0,0 +1,28 @@
+import { Constants, actionDelimiter } from 'librechat-data-provider';
+import { getToolIconType } from '../ToolOutput/ToolIcon';
+
+describe('getToolIconType - ACTN-01: Action delimiter detection', () => {
+ it('returns "action" for tool name containing actionDelimiter', () => {
+ const toolName = `get_weather${actionDelimiter}weather---api---com`;
+ expect(getToolIconType(toolName)).toBe('action');
+ });
+
+ it('returns "mcp" when name has both mcp_delimiter and actionDelimiter', () => {
+ const toolName = `tool${Constants.mcp_delimiter}server`;
+ expect(getToolIconType(toolName)).toBe('mcp');
+ });
+
+ it('returns "generic" for plain tool name without delimiters', () => {
+ expect(getToolIconType('some_plain_tool')).toBe('generic');
+ });
+
+ it('returns correct types for existing tool names', () => {
+ expect(getToolIconType('execute_code')).toBe('execute_code');
+ expect(getToolIconType(Constants.PROGRAMMATIC_TOOL_CALLING)).toBe('execute_code');
+ expect(getToolIconType('web_search')).toBe('web_search');
+ expect(getToolIconType('image_gen_oai')).toBe('image_gen');
+ expect(getToolIconType('image_edit_oai')).toBe('image_gen');
+ expect(getToolIconType('gemini_image_gen')).toBe('image_gen');
+ expect(getToolIconType(`${Constants.LC_TRANSFER_TO_}agent1`)).toBe('agent_handoff');
+ });
+});
diff --git a/client/src/components/Messages/Content/CodeBar.tsx b/client/src/components/Messages/Content/CodeBar.tsx
new file mode 100644
index 0000000000..52c4060465
--- /dev/null
+++ b/client/src/components/Messages/Content/CodeBar.tsx
@@ -0,0 +1,42 @@
+import React from 'react';
+import { InfoIcon } from 'lucide-react';
+import type { CodeBarProps } from '~/common';
+import useCopyCode from '~/components/Messages/Content/useCopyCode';
+import CopyButton from '~/components/Messages/Content/CopyButton';
+import LangIcon from '~/components/Messages/Content/LangIcon';
+import RunCode from '~/components/Messages/Content/RunCode';
+import { useLocalize } from '~/hooks';
+
+const CodeBar: React.FC<CodeBarProps> = React.memo(
+ ({ lang, error, codeRef, blockIndex, plugin = null, allowExecution = true }) => {
+ const localize = useLocalize();
+ const { isCopied, handleCopy } = useCopyCode(codeRef);
+
+ return (
+ <div className="flex items-center justify-between bg-surface-primary-alt px-1.5 py-1.5 font-sans text-xs text-text-secondary dark:bg-transparent">
+ <span className="flex items-center gap-1.5 text-xs font-medium">
+ <LangIcon lang={lang} className="size-3.5" />
+ {lang}
+ </span>
+ {plugin === true ? (
+ <InfoIcon className="ml-auto flex h-4 w-4 gap-2 text-text-secondary" />
+ ) : (
+ <div className="flex items-center justify-center gap-2">
+ {allowExecution === true && (
+ <RunCode lang={lang} codeRef={codeRef} blockIndex={blockIndex} />
+ )}
+ {error !== true && (
+ <CopyButton
+ isCopied={isCopied}
+ onClick={handleCopy}
+ label={localize('com_ui_copy_code')}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ );
+ },
+);
+
+export default CodeBar;
diff --git a/client/src/components/Messages/Content/CodeBlock.tsx b/client/src/components/Messages/Content/CodeBlock.tsx
index 7407098c5e..1d1fe21b80 100644
--- a/client/src/components/Messages/Content/CodeBlock.tsx
+++ b/client/src/components/Messages/Content/CodeBlock.tsx
@@ -1,13 +1,11 @@
import React, { useRef, useState, useMemo, useEffect, useCallback } from 'react';
-import copy from 'copy-to-clipboard';
-import { InfoIcon } from 'lucide-react';
import { Tools } from 'librechat-data-provider';
-import { Clipboard, CheckMark, TooltipAnchor } from '@librechat/client';
import type { CodeBarProps } from '~/common';
+import FloatingCodeBar from '~/components/Messages/Content/FloatingCodeBar';
import ResultSwitcher from '~/components/Messages/Content/ResultSwitcher';
import { useToolCallsMapContext, useMessageContext } from '~/Providers';
import { LogContent } from '~/components/Chat/Messages/Content/Parts';
-import RunCode from '~/components/Messages/Content/RunCode';
+import CodeBar from '~/components/Messages/Content/CodeBar';
import { useLocalize } from '~/hooks';
import cn from '~/utils/cn';
@@ -19,143 +17,6 @@ type CodeBlockProps = Pick<
classProp?: string;
};
-interface FloatingCodeBarProps extends CodeBarProps {
- isVisible: boolean;
-}
-
-const CodeBar: React.FC<CodeBarProps> = React.memo(function CodeBar({
- lang,
- error,
- codeRef,
- blockIndex,
- plugin = null,
- allowExecution = true,
-}) {
- const localize = useLocalize();
- const [isCopied, setIsCopied] = useState(false);
- return (
- <div className="relative flex items-center justify-between rounded-tl-md rounded-tr-md bg-gray-700 px-4 py-2 font-sans text-xs text-gray-200 dark:bg-gray-700">
- <span className="">{lang}</span>
- {plugin === true ? (
- <InfoIcon className="ml-auto flex h-4 w-4 gap-2 text-white/50" />
- ) : (
- <div className="flex items-center justify-center gap-4">
- {allowExecution === true && (
- <RunCode lang={lang} codeRef={codeRef} blockIndex={blockIndex} />
- )}
- <button
- type="button"
- className={cn(
- 'ml-auto flex gap-2 rounded-sm focus:outline focus:outline-white',
- error === true ? 'h-4 w-4 items-start text-white/50' : '',
- )}
- onClick={async () => {
- const codeString = codeRef.current?.textContent;
- if (codeString != null) {
- setIsCopied(true);
- copy(codeString.trim(), { format: 'text/plain' });
-
- setTimeout(() => {
- setIsCopied(false);
- }, 3000);
- }
- }}
- >
- {isCopied ? <CheckMark className="h-[18px] w-[18px]" /> : <Clipboard />}
- {error !== true && (
- <span className="relative">
- <span className="invisible">{localize('com_ui_copy_code')}</span>
- <span className="absolute inset-0 flex items-center">
- {isCopied ? localize('com_ui_copied') : localize('com_ui_copy_code')}
- </span>
- </span>
- )}
- </button>
- </div>
- )}
- </div>
- );
-});
-CodeBar.displayName = 'CodeBar';
-
-const FloatingCodeBar: React.FC<FloatingCodeBarProps> = React.memo(function FloatingCodeBar({
- lang,
- error,
- codeRef,
- blockIndex,
- plugin = null,
- allowExecution = true,
- isVisible,
-}) {
- const localize = useLocalize();
- const [isCopied, setIsCopied] = useState(false);
- const copyButtonRef = useRef<HTMLButtonElement>(null);
-
- const handleCopy = useCallback(() => {
- const codeString = codeRef.current?.textContent;
- if (codeString != null) {
- const wasFocused = document.activeElement === copyButtonRef.current;
- setIsCopied(true);
- copy(codeString.trim(), { format: 'text/plain' });
- if (wasFocused) {
- requestAnimationFrame(() => {
- copyButtonRef.current?.focus();
- });
- }
-
- setTimeout(() => {
- const focusedElement = document.activeElement as HTMLElement | null;
- setIsCopied(false);
- requestAnimationFrame(() => {
- focusedElement?.focus();
- });
- }, 3000);
- }
- }, [codeRef]);
-
- return (
- <div
- className={cn(
- 'absolute bottom-2 right-2 flex items-center gap-2 font-sans text-xs text-gray-200 transition-opacity duration-150',
- isVisible ? 'opacity-100' : 'pointer-events-none opacity-0',
- )}
- >
- {plugin === true ? (
- <InfoIcon className="flex h-4 w-4 gap-2 text-white/50" />
- ) : (
- <>
- {allowExecution === true && (
- <RunCode lang={lang} codeRef={codeRef} blockIndex={blockIndex} iconOnly />
- )}
- <TooltipAnchor
- description={isCopied ? localize('com_ui_copied') : localize('com_ui_copy_code')}
- render={
- <button
- ref={copyButtonRef}
- type="button"
- tabIndex={isVisible ? 0 : -1}
- aria-label={isCopied ? localize('com_ui_copied') : localize('com_ui_copy_code')}
- className={cn(
- 'flex items-center justify-center rounded p-1.5 hover:bg-gray-700 focus:bg-gray-700 focus:outline focus:outline-white',
- error === true ? 'h-4 w-4 text-white/50' : '',
- )}
- onClick={handleCopy}
- >
- {isCopied ? (
- <CheckMark className="h-[18px] w-[18px]" aria-hidden="true" />
- ) : (
- <Clipboard aria-hidden="true" />
- )}
- </button>
- }
- />
- </>
- )}
- </div>
- );
-});
-FloatingCodeBar.displayName = 'FloatingCodeBar';
-
const CodeBlock: React.FC<CodeBlockProps> = ({
lang,
blockIndex,
@@ -165,9 +26,13 @@ const CodeBlock: React.FC<CodeBlockProps> = ({
plugin = null,
error,
}) => {
+ const localize = useLocalize();
const codeRef = useRef<HTMLElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
- const [isBarVisible, setIsBarVisible] = useState(false);
+ const codeBarRef = useRef<HTMLDivElement>(null);
+ const [isHovered, setIsHovered] = useState(false);
+ const [isCodeBarVisible, setIsCodeBarVisible] = useState(true);
+
const toolCallsMap = useToolCallsMapContext();
const { messageId, partIndex } = useMessageContext();
const key = allowExecution
@@ -185,67 +50,76 @@ const CodeBlock: React.FC<CodeBlockProps> = ({
}
}, [fetchedToolCalls]);
- // Handle focus within the container (for keyboard navigation)
- const handleFocus = useCallback(() => {
- setIsBarVisible(true);
+ useEffect(() => {
+ const el = codeBarRef.current;
+ if (!el) {
+ return;
+ }
+
+ const observer = new IntersectionObserver(
+ ([entry]) => setIsCodeBarVisible(entry.isIntersecting),
+ { root: null, threshold: 0 },
+ );
+ observer.observe(el);
+ return () => observer.disconnect();
}, []);
+ const handleFocus = useCallback(() => setIsHovered(true), []);
+
const handleBlur = useCallback((e: React.FocusEvent) => {
- // Check if focus is moving to another element within the container
if (!containerRef.current?.contains(e.relatedTarget as Node)) {
- setIsBarVisible(false);
+ setIsHovered(false);
}
}, []);
- const handleMouseEnter = useCallback(() => {
- setIsBarVisible(true);
- }, []);
+ const handleMouseEnter = useCallback(() => setIsHovered(true), []);
const handleMouseLeave = useCallback(() => {
- // Only hide if no element inside has focus
if (!containerRef.current?.contains(document.activeElement)) {
- setIsBarVisible(false);
+ setIsHovered(false);
}
}, []);
const currentToolCall = useMemo(() => toolCalls?.[currentIndex], [toolCalls, currentIndex]);
- const next = () => {
- if (!toolCalls) {
- return;
- }
- if (currentIndex < toolCalls.length - 1) {
+ const next = useCallback(() => {
+ if (toolCalls && currentIndex < toolCalls.length - 1) {
setCurrentIndex(currentIndex + 1);
}
- };
+ }, [toolCalls, currentIndex]);
- const previous = () => {
+ const previous = useCallback(() => {
if (currentIndex > 0) {
setCurrentIndex(currentIndex - 1);
}
- };
+ }, [currentIndex]);
const isNonCode = !!(plugin === true || error === true);
const language = isNonCode ? 'json' : lang;
+ const showFloating = isHovered && !isCodeBarVisible;
return (
<div
ref={containerRef}
- className="relative w-full rounded-md bg-gray-900 text-xs text-white/80"
+ className="relative w-full overflow-hidden rounded-xl border border-border-light text-xs"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onFocus={handleFocus}
onBlur={handleBlur}
>
- <CodeBar
- lang={lang}
- error={error}
- codeRef={codeRef}
- blockIndex={blockIndex}
- plugin={plugin === true}
- allowExecution={allowExecution}
- />
- <div className={cn(classProp, 'overflow-y-auto p-4')}>
+ <div ref={codeBarRef}>
+ <CodeBar
+ lang={lang}
+ error={error}
+ codeRef={codeRef}
+ blockIndex={blockIndex}
+ plugin={plugin === true}
+ allowExecution={allowExecution}
+ />
+ </div>
+ <div
+ className={cn(classProp, 'overflow-y-auto bg-surface-chat p-4 dark:bg-surface-primary-alt')}
+ >
<code
ref={codeRef}
className={cn(
@@ -262,17 +136,15 @@ const CodeBlock: React.FC<CodeBlockProps> = ({
blockIndex={blockIndex}
plugin={plugin === true}
allowExecution={allowExecution}
- isVisible={isBarVisible}
+ isVisible={showFloating}
/>
{allowExecution === true && toolCalls && toolCalls.length > 0 && (
<>
- <div className="bg-gray-700 p-4 text-xs">
- <div
- className="prose flex flex-col-reverse text-white"
- style={{
- color: 'white',
- }}
- >
+ <div className="border-t border-border-light bg-surface-primary-alt p-4 text-xs dark:bg-transparent">
+ <div className="mb-1 text-[10px] font-medium uppercase tracking-wide text-text-secondary">
+ {localize('com_ui_output')}
+ </div>
+ <div className="flex flex-col-reverse text-text-primary">
<pre className="shrink-0">
<LogContent
output={(currentToolCall?.result as string | undefined) ?? ''}
diff --git a/client/src/components/Messages/Content/CopyButton.tsx b/client/src/components/Messages/Content/CopyButton.tsx
new file mode 100644
index 0000000000..dedaa9c79e
--- /dev/null
+++ b/client/src/components/Messages/Content/CopyButton.tsx
@@ -0,0 +1,89 @@
+import React from 'react';
+import { Copy, Check } from 'lucide-react';
+import { TooltipAnchor } from '@librechat/client';
+import { useLocalize } from '~/hooks';
+import cn from '~/utils/cn';
+
+interface CopyButtonProps {
+ isCopied: boolean;
+ iconOnly?: boolean;
+ onClick: () => void;
+ tabIndex?: number;
+ className?: string;
+ label?: string;
+ copiedLabel?: string;
+}
+
+const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(
+ ({ isCopied, iconOnly = false, onClick, tabIndex, className, label, copiedLabel }, ref) => {
+ const localize = useLocalize();
+ const defaultLabel = label ?? localize('com_ui_copy');
+ const defaultCopiedLabel = copiedLabel ?? localize('com_ui_copied');
+ const currentLabel = isCopied ? defaultCopiedLabel : defaultLabel;
+
+ const button = (
+ <button
+ ref={ref}
+ type="button"
+ onClick={onClick}
+ tabIndex={tabIndex}
+ aria-label={currentLabel}
+ className={cn(
+ 'inline-flex select-none items-center justify-center text-text-secondary transition-all duration-200 ease-out',
+ 'hover:bg-surface-hover hover:text-text-primary',
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-border-heavy',
+ iconOnly ? 'rounded-lg p-1.5' : 'ml-auto gap-2 rounded-md px-2 py-1',
+ isCopied && 'text-text-secondary hover:text-text-primary',
+ className,
+ )}
+ >
+ <span className="relative flex size-[18px] items-center justify-center" aria-hidden="true">
+ <Copy
+ size={18}
+ className={cn(
+ 'absolute transition-all duration-300 ease-out',
+ isCopied ? 'rotate-[-90deg] scale-0 opacity-0' : 'rotate-0 scale-100 opacity-100',
+ )}
+ />
+ <Check
+ size={18}
+ className={cn(
+ 'transition-all duration-300 ease-out',
+ isCopied ? 'rotate-0 scale-100 opacity-100' : 'rotate-90 scale-0 opacity-0',
+ )}
+ />
+ </span>
+ {!iconOnly && (
+ <span className="relative overflow-hidden">
+ <span
+ className={cn(
+ 'block transition-all duration-300 ease-out',
+ isCopied ? '-translate-y-full opacity-0' : 'translate-y-0 opacity-100',
+ )}
+ >
+ {defaultLabel}
+ </span>
+ <span
+ className={cn(
+ 'absolute inset-0 transition-all duration-300 ease-out',
+ isCopied ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0',
+ )}
+ >
+ {defaultCopiedLabel}
+ </span>
+ </span>
+ )}
+ </button>
+ );
+
+ if (iconOnly) {
+ return <TooltipAnchor description={currentLabel} render={button} />;
+ }
+
+ return button;
+ },
+);
+
+CopyButton.displayName = 'CopyButton';
+
+export default CopyButton;
diff --git a/client/src/components/Messages/Content/FloatingCodeBar.tsx b/client/src/components/Messages/Content/FloatingCodeBar.tsx
new file mode 100644
index 0000000000..2929709309
--- /dev/null
+++ b/client/src/components/Messages/Content/FloatingCodeBar.tsx
@@ -0,0 +1,45 @@
+import React from 'react';
+import { InfoIcon } from 'lucide-react';
+import type { CodeBarProps } from '~/common';
+import useCopyCode from '~/components/Messages/Content/useCopyCode';
+import CopyButton from '~/components/Messages/Content/CopyButton';
+import RunCode from '~/components/Messages/Content/RunCode';
+import cn from '~/utils/cn';
+
+interface FloatingCodeBarProps extends CodeBarProps {
+ isVisible: boolean;
+}
+
+const FloatingCodeBar: React.FC<FloatingCodeBarProps> = React.memo(
+ ({ lang, codeRef, blockIndex, plugin = null, allowExecution = true, isVisible }) => {
+ const { isCopied, buttonRef, handleCopy } = useCopyCode(codeRef);
+
+ return (
+ <div
+ className={cn(
+ 'absolute bottom-2 right-2 flex items-center gap-2 font-sans text-xs text-text-secondary transition-opacity duration-150',
+ isVisible ? 'opacity-100' : 'pointer-events-none opacity-0',
+ )}
+ >
+ {plugin === true ? (
+ <InfoIcon className="flex h-4 w-4 gap-2 text-text-secondary" />
+ ) : (
+ <>
+ {allowExecution === true && (
+ <RunCode lang={lang} codeRef={codeRef} blockIndex={blockIndex} iconOnly />
+ )}
+ <CopyButton
+ ref={buttonRef}
+ isCopied={isCopied}
+ iconOnly
+ tabIndex={isVisible ? 0 : -1}
+ onClick={handleCopy}
+ />
+ </>
+ )}
+ </div>
+ );
+ },
+);
+
+export default FloatingCodeBar;
diff --git a/client/src/components/Messages/Content/LangIcon.tsx b/client/src/components/Messages/Content/LangIcon.tsx
new file mode 100644
index 0000000000..bebdad06b9
--- /dev/null
+++ b/client/src/components/Messages/Content/LangIcon.tsx
@@ -0,0 +1,104 @@
+import React from 'react';
+import { FileText } from 'lucide-react';
+import LANG_ICON_PATHS from './langIconPaths';
+
+interface LangIconProps {
+ lang: string;
+ className?: string;
+}
+
+const LANG_ALIASES: Record<string, string> = {
+ py: 'python',
+ js: 'javascript',
+ ts: 'typescript',
+ jsx: 'javascript',
+ tsx: 'typescript',
+ rs: 'rust',
+ golang: 'go',
+ rb: 'ruby',
+ sh: 'bash',
+ zsh: 'bash',
+ shell: 'bash',
+ powershell: 'bash',
+ cmd: 'bash',
+ 'c++': 'cpp',
+ 'c#': 'csharp',
+ cs: 'csharp',
+ dotnet: 'csharp',
+ htm: 'html',
+ html5: 'html',
+ css3: 'css',
+ scss: 'sass',
+ jsonc: 'json',
+ json5: 'json',
+ yml: 'yaml',
+ mysql: 'json',
+ postgresql: 'json',
+ sqlite: 'json',
+ sql: 'json',
+ kt: 'kotlin',
+ kts: 'kotlin',
+ ex: 'elixir',
+ exs: 'elixir',
+ erl: 'erlang',
+ hs: 'haskell',
+ pl: 'perl',
+ clj: 'clojure',
+ cljs: 'clojure',
+ cljc: 'clojure',
+ jl: 'julia',
+ ml: 'ocaml',
+ mli: 'ocaml',
+ fs: 'fsharp',
+ fsx: 'fsharp',
+ cr: 'crystal',
+ coffee: 'coffeescript',
+ sol: 'solidity',
+ wasm: 'webassembly',
+ wat: 'webassembly',
+ gql: 'graphql',
+ tex: 'latex',
+ md: 'markdown',
+ mdx: 'markdown',
+ pas: 'delphi',
+ pascal: 'delphi',
+ rkt: 'racket',
+ purs: 'purescript',
+};
+
+/** Map from alias used in LANG_ICON_PATHS to the name used in ICON_IMPORTS on the old code. */
+const NAME_MAP: Record<string, string> = {
+ java: 'openjdk',
+ c: 'c',
+ cpp: 'cplusplus',
+ csharp: 'dotnet',
+ html: 'html5',
+ bash: 'gnubash',
+ groovy: 'apachegroovy',
+};
+
+const LangIcon = React.memo(function LangIcon({ lang, className }: LangIconProps) {
+ const key = lang.toLowerCase();
+ if (key === 'txt' || key === 'text') {
+ return <FileText className={className} aria-hidden="true" />;
+ }
+ const resolved = LANG_ALIASES[key] ?? key;
+ const pathKey = NAME_MAP[resolved] ?? resolved;
+ const path = LANG_ICON_PATHS[pathKey];
+ if (!path) {
+ return null;
+ }
+ return (
+ <svg
+ role="img"
+ viewBox="0 0 24 24"
+ className={className}
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path d={path} />
+ </svg>
+ );
+});
+
+export default LangIcon;
diff --git a/client/src/components/Messages/Content/Mermaid.tsx b/client/src/components/Messages/Content/Mermaid.tsx
deleted file mode 100644
index 03037f4427..0000000000
--- a/client/src/components/Messages/Content/Mermaid.tsx
+++ /dev/null
@@ -1,850 +0,0 @@
-import React, { useEffect, useMemo, useState, useRef, useCallback, memo } from 'react';
-import copy from 'copy-to-clipboard';
-import { X, ZoomIn, ZoomOut, ChevronUp, RefreshCw, RotateCcw, ChevronDown } from 'lucide-react';
-import {
- Button,
- Spinner,
- OGDialog,
- Clipboard,
- CheckMark,
- OGDialogClose,
- OGDialogTitle,
- OGDialogContent,
-} from '@librechat/client';
-import { useLocalize, useDebouncedMermaid } from '~/hooks';
-import { fixSubgraphTitleContrast } from '~/utils/mermaid';
-import MermaidHeader from './MermaidHeader';
-import cn from '~/utils/cn';
-
-interface MermaidProps {
- /** Mermaid diagram content */
- children: string;
- /** Unique identifier */
- id?: string;
- /** Custom theme */
- theme?: string;
-}
-
-const MIN_ZOOM = 0.25;
-const MAX_ZOOM = 4;
-const ZOOM_STEP = 0.25;
-const MIN_CONTAINER_HEIGHT = 200;
-const MAX_CONTAINER_HEIGHT = 500;
-
-const Mermaid: React.FC<MermaidProps> = memo(({ children, id, theme }) => {
- const localize = useLocalize();
- const [blobUrl, setBlobUrl] = useState<string>('');
- const [showCode, setShowCode] = useState(false);
- const [retryCount, setRetryCount] = useState(0);
- const [isDialogOpen, setIsDialogOpen] = useState(false);
- // Separate showCode state for dialog to avoid re-renders
- const [dialogShowCode, setDialogShowCode] = useState(false);
- const lastValidSvgRef = useRef<string | null>(null);
- const expandButtonRef = useRef<HTMLButtonElement>(null);
- const dialogShowCodeButtonRef = useRef<HTMLButtonElement>(null);
- const dialogCopyButtonRef = useRef<HTMLButtonElement>(null);
- const zoomCopyButtonRef = useRef<HTMLButtonElement>(null);
- const dialogZoomCopyButtonRef = useRef<HTMLButtonElement>(null);
-
- const [svgDimensions, setSvgDimensions] = useState<{ width: number; height: number } | null>(
- null,
- );
- const [containerWidth, setContainerWidth] = useState(700);
- const [isHovered, setIsHovered] = useState(false);
- const [isFocusWithin, setIsFocusWithin] = useState(false);
- const [isTouchDevice, setIsTouchDevice] = useState(false);
- const [showMobileControls, setShowMobileControls] = useState(false);
-
- useEffect(() => {
- setIsTouchDevice('ontouchstart' in window || navigator.maxTouchPoints > 0);
- }, []);
-
- const [zoom, setZoom] = useState(1);
- // Dialog zoom and pan state (separate from inline view)
- const [dialogZoom, setDialogZoom] = useState(1);
- const [dialogPan, setDialogPan] = useState({ x: 0, y: 0 });
- const [isDialogPanning, setIsDialogPanning] = useState(false);
- const dialogPanStartRef = useRef({ x: 0, y: 0 });
- const [pan, setPan] = useState({ x: 0, y: 0 });
- const [isPanning, setIsPanning] = useState(false);
- const panStartRef = useRef({ x: 0, y: 0 });
- const containerRef = useRef<HTMLDivElement>(null);
- const streamingCodeRef = useRef<HTMLPreElement>(null);
-
- // Get SVG from debounced hook (handles streaming gracefully)
- const { svg, isLoading, error } = useDebouncedMermaid({
- content: children,
- id,
- theme,
- key: retryCount,
- });
-
- // Auto-scroll streaming code to bottom
- useEffect(() => {
- if (isLoading && streamingCodeRef.current) {
- streamingCodeRef.current.scrollTop = streamingCodeRef.current.scrollHeight;
- }
- }, [children, isLoading]);
-
- // Store last valid SVG for showing during updates
- useEffect(() => {
- if (svg) {
- lastValidSvgRef.current = svg;
- }
- }, [svg]);
-
- useEffect(() => {
- if (!containerRef.current) return;
-
- const observer = new ResizeObserver((entries) => {
- for (const entry of entries) {
- setContainerWidth(entry.contentRect.width);
- }
- });
-
- observer.observe(containerRef.current);
- return () => observer.disconnect();
- }, []);
-
- // Process SVG and extract dimensions
- const { processedSvg, parsedDimensions } = useMemo(() => {
- if (!svg) {
- return { processedSvg: null, parsedDimensions: null };
- }
-
- // Regex-based fallback for malformed or unparseable SVG
- const applyFallbackFixes = (svgString: string): string => {
- let finalSvg = svgString;
-
- // Firefox fix: Ensure viewBox is set correctly
- if (
- !svgString.includes('viewBox') &&
- svgString.includes('height=') &&
- svgString.includes('width=')
- ) {
- const widthMatch = svgString.match(/width="(\d+)"/);
- const heightMatch = svgString.match(/height="(\d+)"/);
-
- if (widthMatch && heightMatch) {
- const width = widthMatch[1];
- const height = heightMatch[1];
- finalSvg = finalSvg.replace('<svg', `<svg viewBox="0 0 ${width} ${height}"`);
- }
- }
-
- // Ensure SVG has proper XML namespace
- if (!finalSvg.includes('xmlns')) {
- finalSvg = finalSvg.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"');
- }
-
- return finalSvg;
- };
-
- const parser = new DOMParser();
- const doc = parser.parseFromString(svg, 'image/svg+xml');
-
- const parseError = doc.querySelector('parsererror');
- if (parseError) {
- return { processedSvg: applyFallbackFixes(svg), parsedDimensions: null };
- }
-
- const svgElement = doc.querySelector('svg');
-
- if (svgElement) {
- let width = parseFloat(svgElement.getAttribute('width') || '0');
- let height = parseFloat(svgElement.getAttribute('height') || '0');
-
- if (!width || !height) {
- const viewBox = svgElement.getAttribute('viewBox');
- if (viewBox) {
- const parts = viewBox.split(/[\s,]+/).map(Number);
- if (parts.length === 4) {
- width = parts[2];
- height = parts[3];
- }
- }
- }
-
- let dimensions: { width: number; height: number } | null = null;
- if (width > 0 && height > 0) {
- dimensions = { width, height };
-
- if (!svgElement.getAttribute('viewBox')) {
- svgElement.setAttribute('viewBox', `0 0 ${width} ${height}`);
- }
-
- svgElement.removeAttribute('width');
- svgElement.removeAttribute('height');
- svgElement.removeAttribute('style');
- }
-
- if (!svgElement.getAttribute('xmlns')) {
- svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
- }
-
- fixSubgraphTitleContrast(svgElement);
-
- return {
- processedSvg: new XMLSerializer().serializeToString(doc),
- parsedDimensions: dimensions,
- };
- }
-
- // Fallback: if svgElement is null
- return { processedSvg: applyFallbackFixes(svg), parsedDimensions: null };
- }, [svg]);
-
- // The svg dimension update needs to be in useEffect instead of useMemo to avoid re-render problems
- useEffect(() => {
- if (parsedDimensions) {
- setSvgDimensions(parsedDimensions);
- }
- }, [parsedDimensions]);
-
- useEffect(() => {
- if (!processedSvg) {
- return;
- }
-
- const blob = new Blob([processedSvg], { type: 'image/svg+xml' });
- const url = URL.createObjectURL(blob);
- setBlobUrl(url);
-
- return () => {
- if (url) {
- URL.revokeObjectURL(url);
- }
- };
- }, [processedSvg]);
-
- const { initialScale, calculatedHeight } = useMemo(() => {
- if (!svgDimensions) {
- return { initialScale: 1, calculatedHeight: MAX_CONTAINER_HEIGHT };
- }
-
- const padding = 32;
- const availableWidth = containerWidth - padding;
- const scaleX = availableWidth / svgDimensions.width;
- const scaleY = MAX_CONTAINER_HEIGHT / svgDimensions.height;
- const scale = Math.min(scaleX, scaleY, 1); // Cap at 1 to prevent small diagrams from being scaled up
- const height = Math.max(
- MIN_CONTAINER_HEIGHT,
- Math.min(MAX_CONTAINER_HEIGHT, svgDimensions.height * scale + padding),
- );
-
- return { initialScale: scale, calculatedHeight: height };
- }, [svgDimensions, containerWidth]);
-
- const [isDialogCopied, setIsDialogCopied] = useState(false);
- const handleDialogCopy = useCallback(() => {
- copy(children.trim(), { format: 'text/plain' });
- setIsDialogCopied(true);
- requestAnimationFrame(() => {
- dialogCopyButtonRef.current?.focus();
- });
- setTimeout(() => {
- setIsDialogCopied(false);
- requestAnimationFrame(() => {
- dialogCopyButtonRef.current?.focus();
- });
- }, 3000);
- }, [children]);
-
- // Zoom controls copy with focus restoration
- const [isZoomCopied, setIsZoomCopied] = useState(false);
- const handleZoomCopy = useCallback(() => {
- copy(children.trim(), { format: 'text/plain' });
- setIsZoomCopied(true);
- requestAnimationFrame(() => {
- zoomCopyButtonRef.current?.focus();
- });
- setTimeout(() => {
- setIsZoomCopied(false);
- requestAnimationFrame(() => {
- zoomCopyButtonRef.current?.focus();
- });
- }, 3000);
- }, [children]);
-
- // Dialog zoom controls copy
- const handleDialogZoomCopy = useCallback(() => {
- copy(children.trim(), { format: 'text/plain' });
- requestAnimationFrame(() => {
- dialogZoomCopyButtonRef.current?.focus();
- });
- }, [children]);
-
- const handleRetry = () => {
- setRetryCount((prev) => prev + 1);
- };
-
- const handleToggleCode = useCallback(() => {
- setShowCode((prev) => !prev);
- }, []);
-
- // Toggle dialog code with focus restoration
- const handleToggleDialogCode = useCallback(() => {
- setDialogShowCode((prev) => !prev);
- requestAnimationFrame(() => {
- dialogShowCodeButtonRef.current?.focus();
- });
- }, []);
-
- // Zoom handlers
- const handleZoomIn = useCallback(() => {
- setZoom((prev) => Math.min(prev + ZOOM_STEP, MAX_ZOOM));
- }, []);
-
- const handleZoomOut = useCallback(() => {
- setZoom((prev) => Math.max(prev - ZOOM_STEP, MIN_ZOOM));
- }, []);
-
- const handleResetZoom = useCallback(() => {
- setZoom(1);
- setPan({ x: 0, y: 0 });
- }, []);
-
- // Dialog zoom handlers
- const handleDialogZoomIn = useCallback(() => {
- setDialogZoom((prev) => Math.min(prev + ZOOM_STEP, MAX_ZOOM));
- }, []);
-
- const handleDialogZoomOut = useCallback(() => {
- setDialogZoom((prev) => Math.max(prev - ZOOM_STEP, MIN_ZOOM));
- }, []);
-
- const handleDialogResetZoom = useCallback(() => {
- setDialogZoom(1);
- setDialogPan({ x: 0, y: 0 });
- }, []);
-
- const handleDialogWheel = useCallback((e: React.WheelEvent) => {
- // In the expanded dialog, allow zooming without holding modifier key
- e.preventDefault();
- const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
- setDialogZoom((prev) => Math.min(Math.max(prev + delta, MIN_ZOOM), MAX_ZOOM));
- }, []);
-
- const handleDialogMouseDown = useCallback(
- (e: React.MouseEvent) => {
- const target = e.target as HTMLElement;
- const isButton = target.tagName === 'BUTTON' || target.closest('button');
- if (e.button === 0 && !isButton) {
- setIsDialogPanning(true);
- dialogPanStartRef.current = { x: e.clientX - dialogPan.x, y: e.clientY - dialogPan.y };
- }
- },
- [dialogPan],
- );
-
- const handleDialogMouseMove = useCallback(
- (e: React.MouseEvent) => {
- if (isDialogPanning) {
- setDialogPan({
- x: e.clientX - dialogPanStartRef.current.x,
- y: e.clientY - dialogPanStartRef.current.y,
- });
- }
- },
- [isDialogPanning],
- );
-
- const handleDialogMouseUp = useCallback(() => {
- setIsDialogPanning(false);
- }, []);
-
- const handleDialogMouseLeave = useCallback(() => {
- setIsDialogPanning(false);
- }, []);
-
- // Mouse wheel zoom
- useEffect(() => {
- const container = containerRef.current;
- if (!container) return;
-
- const handleWheelNative = (e: WheelEvent) => {
- if (e.ctrlKey || e.metaKey) {
- e.preventDefault();
- const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
- setZoom((prev) => Math.min(Math.max(prev + delta, MIN_ZOOM), MAX_ZOOM));
- }
- };
-
- // use native event listener with passive: false to prevent scroll
- container.addEventListener('wheel', handleWheelNative, { passive: false });
- return () => container.removeEventListener('wheel', handleWheelNative);
- }, [blobUrl]); // blobUrl dep (unused in callback) ensures listener re-attaches when container mounts
-
- const handleMouseDown = useCallback(
- (e: React.MouseEvent) => {
- // Only start panning on left click and not on buttons/icons inside buttons
- const target = e.target as HTMLElement;
- const isButton = target.tagName === 'BUTTON' || target.closest('button');
- if (e.button === 0 && !isButton) {
- setIsPanning(true);
- panStartRef.current = { x: e.clientX - pan.x, y: e.clientY - pan.y };
- }
- },
- [pan],
- );
-
- // Attach document-level listeners when panning starts
- useEffect(() => {
- if (!isPanning) return;
-
- const handleDocumentMouseMove = (e: MouseEvent) => {
- setPan({
- x: e.clientX - panStartRef.current.x,
- y: e.clientY - panStartRef.current.y,
- });
- };
-
- const handleDocumentMouseUp = () => {
- setIsPanning(false);
- };
-
- document.addEventListener('mousemove', handleDocumentMouseMove);
- document.addEventListener('mouseup', handleDocumentMouseUp);
-
- return () => {
- document.removeEventListener('mousemove', handleDocumentMouseMove);
- document.removeEventListener('mouseup', handleDocumentMouseUp);
- };
- }, [isPanning]);
-
- const showControls = isTouchDevice
- ? showMobileControls || showCode
- : isHovered || isFocusWithin || showCode;
-
- const handleContainerClick = useCallback(
- (e: React.MouseEvent | React.TouchEvent) => {
- if (!isTouchDevice) return;
- const target = e.target as HTMLElement;
- const isInteractive = target.closest('button, a, [role="button"]');
- if (!isInteractive) {
- setShowMobileControls((prev) => !prev);
- }
- },
- [isTouchDevice],
- );
-
- const handleExpand = useCallback(() => {
- setDialogShowCode(false);
- setDialogZoom(1);
- setDialogPan({ x: 0, y: 0 });
- setIsDialogOpen(true);
- }, []);
-
- const zoomControls = (
- <div
- className={cn(
- 'absolute bottom-2 right-2 z-10 flex items-center gap-1 rounded-md border border-border-light bg-surface-secondary p-1 shadow-lg transition-opacity duration-200',
- showControls ? 'opacity-100' : 'pointer-events-none opacity-0',
- )}
- >
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleZoomOut();
- }}
- disabled={zoom <= MIN_ZOOM}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"
- title={localize('com_ui_zoom_out')}
- >
- <ZoomOut className="h-4 w-4" />
- </button>
- <span className="min-w-[3rem] text-center text-xs text-text-secondary">
- {Math.round(zoom * 100)}%
- </span>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleZoomIn();
- }}
- disabled={zoom >= MAX_ZOOM}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"
- title={localize('com_ui_zoom_in')}
- >
- <ZoomIn className="h-4 w-4" />
- </button>
- <div className="mx-1 h-4 w-px bg-border-medium" />
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleResetZoom();
- }}
- disabled={zoom === 1 && pan.x === 0 && pan.y === 0}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"
- title={localize('com_ui_reset_zoom')}
- >
- <RotateCcw className="h-4 w-4" />
- </button>
- <div className="mx-1 h-4 w-px bg-border-medium" />
- <button
- ref={zoomCopyButtonRef}
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleZoomCopy();
- }}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover"
- title={localize('com_ui_copy_code')}
- >
- {isZoomCopied ? <CheckMark className="h-4 w-4" /> : <Clipboard className="h-4 w-4" />}
- </button>
- </div>
- );
-
- // Dialog zoom controls
- const dialogZoomControls = (
- <div className="absolute bottom-4 right-4 z-10 flex items-center gap-1 rounded-md border border-border-light bg-surface-secondary p-1 shadow-lg">
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleDialogZoomOut();
- }}
- disabled={dialogZoom <= MIN_ZOOM}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"
- title={localize('com_ui_zoom_out')}
- >
- <ZoomOut className="h-4 w-4" />
- </button>
- <span className="min-w-[3rem] text-center text-xs text-text-secondary">
- {Math.round(dialogZoom * 100)}%
- </span>
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleDialogZoomIn();
- }}
- disabled={dialogZoom >= MAX_ZOOM}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"
- title={localize('com_ui_zoom_in')}
- >
- <ZoomIn className="h-4 w-4" />
- </button>
- <div className="mx-1 h-4 w-px bg-border-medium" />
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleDialogResetZoom();
- }}
- disabled={dialogZoom === 1 && dialogPan.x === 0 && dialogPan.y === 0}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent"
- title={localize('com_ui_reset_zoom')}
- >
- <RotateCcw className="h-4 w-4" />
- </button>
- <div className="mx-1 h-4 w-px bg-border-medium" />
- <button
- ref={dialogZoomCopyButtonRef}
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- handleDialogZoomCopy();
- }}
- className="rounded p-1.5 text-text-secondary hover:bg-surface-hover"
- title={localize('com_ui_copy_code')}
- >
- <Clipboard className="h-4 w-4" />
- </button>
- </div>
- );
-
- // Full-screen dialog - rendered inline, not as function component to avoid recreation
- const expandedDialog = (
- <OGDialog open={isDialogOpen} onOpenChange={setIsDialogOpen} triggerRef={expandButtonRef}>
- <OGDialogContent
- showCloseButton={false}
- className="h-[85vh] max-h-[85vh] w-[90vw] max-w-[90vw] gap-0 overflow-hidden border-border-light bg-surface-primary-alt p-0"
- >
- <OGDialogTitle className="flex h-10 items-center justify-between bg-gray-700 px-4 font-sans text-xs text-gray-200">
- <span>{localize('com_ui_mermaid')}</span>
- <div className="flex gap-2">
- <Button
- ref={dialogShowCodeButtonRef}
- variant="ghost"
- size="sm"
- className="h-auto min-w-[6rem] gap-1 rounded-sm px-1 py-0 text-xs text-gray-200 hover:bg-gray-600 hover:text-white focus-visible:ring-white focus-visible:ring-offset-0"
- onClick={handleToggleDialogCode}
- >
- {dialogShowCode ? (
- <ChevronUp className="h-4 w-4" />
- ) : (
- <ChevronDown className="h-4 w-4" />
- )}
- {dialogShowCode ? localize('com_ui_hide_code') : localize('com_ui_show_code')}
- </Button>
- <Button
- ref={dialogCopyButtonRef}
- variant="ghost"
- size="sm"
- className="h-auto gap-1 rounded-sm px-1 py-0 text-xs text-gray-200 hover:bg-gray-600 hover:text-white focus-visible:ring-white focus-visible:ring-offset-0"
- onClick={handleDialogCopy}
- >
- {isDialogCopied ? <CheckMark className="h-[18px] w-[18px]" /> : <Clipboard />}
- {localize('com_ui_copy_code')}
- </Button>
- <OGDialogClose className="rounded-sm p-1 text-gray-200 hover:bg-gray-600 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white">
- <X className="h-4 w-4" />
- <span className="sr-only">{localize('com_ui_close')}</span>
- </OGDialogClose>
- </div>
- </OGDialogTitle>
- {dialogShowCode && (
- <div className="border-b border-border-medium bg-surface-secondary p-4">
- <pre className="max-h-[150px] overflow-auto whitespace-pre-wrap text-xs text-text-secondary">
- {children}
- </pre>
- </div>
- )}
- <div
- className={cn(
- 'relative flex-1 overflow-hidden p-4',
- 'bg-surface-primary-alt',
- isDialogPanning ? 'cursor-grabbing' : 'cursor-grab',
- )}
- style={{ height: dialogShowCode ? 'calc(85vh - 200px)' : 'calc(85vh - 50px)' }}
- onWheel={handleDialogWheel}
- onMouseDown={handleDialogMouseDown}
- onMouseMove={handleDialogMouseMove}
- onMouseUp={handleDialogMouseUp}
- onMouseLeave={handleDialogMouseLeave}
- >
- <div
- className="flex h-full w-full items-center justify-center"
- style={{
- transform: `translate(${dialogPan.x}px, ${dialogPan.y}px)`,
- transition: isDialogPanning ? 'none' : 'transform 0.1s ease-out',
- }}
- >
- <img
- src={blobUrl}
- alt="Mermaid diagram"
- className="max-h-full max-w-full select-none object-contain"
- style={{
- transform: `scale(${dialogZoom})`,
- transformOrigin: 'center center',
- }}
- draggable={false}
- />
- </div>
- {dialogZoomControls}
- </div>
- </OGDialogContent>
- </OGDialog>
- );
-
- // Loading state - show last valid diagram with loading indicator, or spinner
- if (isLoading) {
- // If we have a previous valid render, show it with a subtle loading indicator
- if (lastValidSvgRef.current && blobUrl) {
- return (
- <div
- className={cn(
- 'relative w-full overflow-hidden rounded-md border transition-all duration-200',
- showControls ? 'border-border-light' : 'border-transparent',
- )}
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={() => setIsHovered(false)}
- onFocus={() => setIsFocusWithin(true)}
- onBlur={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node)) {
- setIsFocusWithin(false);
- }
- }}
- onClick={handleContainerClick}
- >
- <MermaidHeader
- className={cn(
- 'absolute left-0 right-0 top-0 z-20',
- showControls ? 'opacity-100' : 'pointer-events-none opacity-0',
- )}
- codeContent={children}
- showCode={showCode}
- onToggleCode={handleToggleCode}
- />
- <div
- ref={containerRef}
- className={cn(
- 'relative overflow-hidden p-4 transition-colors duration-200',
- 'rounded-md',
- showControls ? 'bg-surface-primary-alt dark:bg-white/[0.03]' : 'bg-transparent',
- isPanning ? 'cursor-grabbing' : 'cursor-grab',
- )}
- style={{ height: `${calculatedHeight}px` }}
- onMouseDown={handleMouseDown}
- >
- <div className="absolute left-2 top-2 z-10 flex items-center gap-1 rounded border border-border-light bg-surface-secondary px-2 py-1 text-xs text-text-secondary">
- <Spinner className="h-3 w-3" />
- </div>
- <div
- className="absolute inset-0 flex items-center justify-center"
- style={{
- transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
- transition: isPanning ? 'none' : 'transform 0.1s ease-out',
- }}
- >
- <img
- src={blobUrl}
- alt="Mermaid diagram"
- className="select-none opacity-70"
- style={{
- width: svgDimensions ? `${svgDimensions.width * initialScale}px` : 'auto',
- height: svgDimensions ? `${svgDimensions.height * initialScale}px` : 'auto',
- }}
- draggable={false}
- />
- </div>
- {zoomControls}
- </div>
- </div>
- );
- }
-
- // No previous render, show streaming code
- return (
- <div className="w-full overflow-hidden rounded-md border border-border-light">
- <div className="flex items-center gap-2 rounded-t-md bg-gray-700 px-4 py-2 font-sans text-xs text-gray-200">
- <Spinner className="h-3 w-3 text-gray-200" />
- <span>{localize('com_ui_mermaid')}</span>
- </div>
- <pre
- ref={streamingCodeRef}
- className="max-h-[350px] min-h-[150px] overflow-auto whitespace-pre-wrap rounded-b-md bg-surface-primary-alt p-4 font-mono text-xs text-text-secondary"
- >
- {children}
- </pre>
- </div>
- );
- }
-
- // Error state
- if (error) {
- return (
- <div className="w-full overflow-hidden rounded-md border border-border-light">
- <MermaidHeader codeContent={children} showCode={showCode} onToggleCode={handleToggleCode} />
- <div className="rounded-b-md border-t border-red-500/30 bg-red-500/10 p-4">
- <div className="mb-2 flex items-center justify-between">
- <span className="font-semibold text-red-500 dark:text-red-400">
- {localize('com_ui_mermaid_failed')}
- </span>
- <button
- type="button"
- onClick={handleRetry}
- className="flex items-center gap-1 rounded px-2 py-1 text-xs text-text-secondary hover:bg-surface-hover"
- >
- <RefreshCw className="h-3 w-3" />
- {localize('com_ui_retry')}
- </button>
- </div>
- <pre className="overflow-auto text-xs text-red-600 dark:text-red-300">
- {error.message}
- </pre>
- {showCode && (
- <div className="mt-4 border-t border-border-medium pt-4">
- <div className="mb-2 text-xs text-text-secondary">
- {localize('com_ui_mermaid_source')}
- </div>
- <pre className="overflow-auto whitespace-pre-wrap text-xs text-text-secondary">
- {children}
- </pre>
- </div>
- )}
- </div>
- </div>
- );
- }
-
- // Success state
- if (!blobUrl) {
- return null;
- }
-
- return (
- <>
- {expandedDialog}
- <div
- className={cn(
- 'relative w-full overflow-hidden rounded-md border transition-all duration-200',
- showControls ? 'border-border-light' : 'border-transparent',
- )}
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={() => setIsHovered(false)}
- onFocus={() => setIsFocusWithin(true)}
- onBlur={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node)) {
- setIsFocusWithin(false);
- }
- }}
- onClick={handleContainerClick}
- >
- <MermaidHeader
- className={cn(
- 'absolute left-0 right-0 top-0 z-20',
- showControls ? 'opacity-100' : 'pointer-events-none opacity-0',
- )}
- codeContent={children}
- showCode={showCode}
- showExpandButton
- expandButtonRef={expandButtonRef}
- onExpand={handleExpand}
- onToggleCode={handleToggleCode}
- />
- {showCode && (
- <div
- className={cn(
- 'border-b border-border-medium bg-surface-secondary p-4 pt-12 transition-opacity duration-200',
- showControls ? 'opacity-100' : 'pointer-events-none opacity-0',
- )}
- >
- <pre className="overflow-auto whitespace-pre-wrap text-xs text-text-secondary">
- {children}
- </pre>
- </div>
- )}
- <div
- ref={containerRef}
- className={cn(
- 'relative overflow-hidden p-4 transition-colors duration-200',
- 'rounded-md',
- showControls ? 'bg-surface-primary-alt dark:bg-white/[0.03]' : 'bg-transparent',
- isPanning ? 'cursor-grabbing' : 'cursor-grab',
- )}
- style={{ height: `${calculatedHeight}px` }}
- onMouseDown={handleMouseDown}
- >
- <div
- className="absolute inset-0 flex items-center justify-center"
- style={{
- transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
- transition: isPanning ? 'none' : 'transform 0.1s ease-out',
- }}
- >
- <img
- src={blobUrl}
- alt="Mermaid diagram"
- className="select-none"
- style={{
- width: svgDimensions ? `${svgDimensions.width * initialScale}px` : 'auto',
- height: svgDimensions ? `${svgDimensions.height * initialScale}px` : 'auto',
- }}
- draggable={false}
- />
- </div>
- {zoomControls}
- </div>
- </div>
- </>
- );
-});
-
-Mermaid.displayName = 'Mermaid';
-
-export default Mermaid;
diff --git a/client/src/components/Messages/Content/Mermaid/Mermaid.tsx b/client/src/components/Messages/Content/Mermaid/Mermaid.tsx
new file mode 100644
index 0000000000..51e873f49a
--- /dev/null
+++ b/client/src/components/Messages/Content/Mermaid/Mermaid.tsx
@@ -0,0 +1,288 @@
+import React, { useEffect, useState, useRef, useCallback, memo } from 'react';
+import { RefreshCw } from 'lucide-react';
+import { Spinner } from '@librechat/client';
+import useSvgProcessing from './useSvgProcessing';
+import useMermaidZoom from './useMermaidZoom';
+import MermaidDialog from './MermaidDialog';
+import MermaidHeader from './MermaidHeader';
+import ZoomControls from './ZoomControls';
+import { useLocalize } from '~/hooks';
+import cn from '~/utils/cn';
+
+interface MermaidProps {
+ children: string;
+ id?: string;
+ theme?: string;
+}
+
+const Mermaid: React.FC<MermaidProps> = memo(({ children, id, theme }) => {
+ const localize = useLocalize();
+ const [showCode, setShowCode] = useState(false);
+ const [retryCount, setRetryCount] = useState(0);
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const [isHovered, setIsHovered] = useState(false);
+ const [isFocusWithin, setIsFocusWithin] = useState(false);
+ const [isTouchDevice, setIsTouchDevice] = useState(false);
+ const [showMobileControls, setShowMobileControls] = useState(false);
+ const expandButtonRef = useRef<HTMLButtonElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const streamingCodeRef = useRef<HTMLPreElement>(null);
+
+ useEffect(() => {
+ setIsTouchDevice('ontouchstart' in window || navigator.maxTouchPoints > 0);
+ }, []);
+
+ const {
+ blobUrl,
+ svgDimensions,
+ isLoading,
+ error,
+ lastValidSvgRef,
+ initialScale,
+ calculatedHeight,
+ } = useSvgProcessing({ content: children, id, theme, retryCount, containerRef });
+
+ const { zoom, pan, isPanning, handleZoomIn, handleZoomOut, handleResetZoom, handleMouseDown } =
+ useMermaidZoom({ containerRef, wheelDep: blobUrl });
+
+ useEffect(() => {
+ if (isLoading && streamingCodeRef.current) {
+ streamingCodeRef.current.scrollTop = streamingCodeRef.current.scrollHeight;
+ }
+ }, [children, isLoading]);
+
+ const handleToggleCode = useCallback(() => setShowCode((prev) => !prev), []);
+ const handleRetry = useCallback(() => setRetryCount((prev) => prev + 1), []);
+ const handleExpand = useCallback(() => setIsDialogOpen(true), []);
+
+ const handleContainerClick = useCallback(
+ (e: React.MouseEvent | React.TouchEvent) => {
+ if (!isTouchDevice) {
+ return;
+ }
+ const target = e.target as HTMLElement;
+ if (!target.closest('button, a, [role="button"]')) {
+ setShowMobileControls((prev) => !prev);
+ }
+ },
+ [isTouchDevice],
+ );
+
+ const showControls = isTouchDevice
+ ? showMobileControls || showCode
+ : isHovered || isFocusWithin || showCode;
+
+ const hoverHandlers = {
+ onMouseEnter: () => setIsHovered(true),
+ onMouseLeave: () => setIsHovered(false),
+ onFocus: () => setIsFocusWithin(true),
+ onBlur: (e: React.FocusEvent) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node)) {
+ setIsFocusWithin(false);
+ }
+ },
+ };
+
+ const diagramStyle = {
+ width: svgDimensions ? `${svgDimensions.width * initialScale}px` : 'auto',
+ height: svgDimensions ? `${svgDimensions.height * initialScale}px` : 'auto',
+ };
+
+ if (isLoading) {
+ if (lastValidSvgRef.current && blobUrl) {
+ return (
+ <div
+ className={cn(
+ 'relative w-full overflow-hidden rounded-lg border transition-all duration-200',
+ showControls ? 'border-border-light' : 'border-transparent',
+ )}
+ {...hoverHandlers}
+ onClick={handleContainerClick}
+ >
+ <MermaidHeader
+ className={cn(
+ 'absolute left-0 right-0 top-0 z-20',
+ showControls ? 'opacity-100' : 'pointer-events-none opacity-0',
+ )}
+ codeContent={children}
+ showCode={showCode}
+ onToggleCode={handleToggleCode}
+ />
+ <div
+ ref={containerRef}
+ className={cn(
+ 'relative overflow-hidden rounded-md p-4 transition-colors duration-200',
+ 'bg-surface-primary-alt dark:bg-white/[0.03]',
+ isPanning ? 'cursor-grabbing' : 'cursor-grab',
+ )}
+ style={{ height: `${calculatedHeight}px` }}
+ onMouseDown={handleMouseDown}
+ >
+ <div className="absolute left-2 top-2 z-10 flex items-center gap-1 rounded border border-border-light bg-surface-secondary px-2 py-1 text-xs text-text-secondary">
+ <Spinner className="h-3 w-3" />
+ </div>
+ <div
+ className="absolute inset-0 flex items-center justify-center"
+ style={{
+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
+ transition: isPanning ? 'none' : 'transform 0.1s ease-out',
+ }}
+ >
+ <img
+ src={blobUrl}
+ alt="Mermaid diagram"
+ className="select-none opacity-70"
+ style={diagramStyle}
+ draggable={false}
+ />
+ </div>
+ <ZoomControls
+ zoom={zoom}
+ pan={pan}
+ codeContent={children}
+ onZoomIn={handleZoomIn}
+ onZoomOut={handleZoomOut}
+ onReset={handleResetZoom}
+ className={cn(
+ 'absolute bottom-2 right-2 z-10 transition-opacity duration-200',
+ showControls ? 'opacity-100' : 'pointer-events-none opacity-0',
+ )}
+ />
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="w-full overflow-hidden rounded-lg border border-border-light">
+ <div className="flex items-center gap-2 border-b border-border-light bg-surface-secondary px-4 py-2 font-sans text-xs text-text-secondary">
+ <Spinner className="h-3 w-3" />
+ <span className="font-medium">{localize('com_ui_mermaid')}</span>
+ </div>
+ <pre
+ ref={streamingCodeRef}
+ className="max-h-[350px] min-h-[150px] overflow-auto whitespace-pre-wrap bg-surface-primary-alt p-4 font-mono text-xs text-text-secondary"
+ >
+ {children}
+ </pre>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="w-full overflow-hidden rounded-lg border border-border-light">
+ <MermaidHeader codeContent={children} showCode={showCode} onToggleCode={handleToggleCode} />
+ <div className="border-t border-border-light bg-surface-tertiary p-4">
+ <div className="mb-2 flex items-center justify-between">
+ <span className="font-semibold text-red-600 dark:text-red-400">
+ {localize('com_ui_mermaid_failed')}
+ </span>
+ <button
+ type="button"
+ onClick={handleRetry}
+ className="flex items-center gap-1 rounded px-2 py-1 text-xs text-text-secondary hover:bg-surface-hover"
+ >
+ <RefreshCw className="h-3 w-3" />
+ {localize('com_ui_retry')}
+ </button>
+ </div>
+ <pre className="overflow-auto text-xs text-red-600 dark:text-red-300">
+ {error.message}
+ </pre>
+ {showCode && (
+ <div className="mt-4 border-t border-border-light pt-4">
+ <div className="mb-2 text-xs text-text-secondary">
+ {localize('com_ui_mermaid_source')}
+ </div>
+ <pre className="overflow-auto whitespace-pre-wrap text-xs text-text-secondary">
+ {children}
+ </pre>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ if (!blobUrl) {
+ return null;
+ }
+
+ return (
+ <>
+ <MermaidDialog
+ open={isDialogOpen}
+ onOpenChange={setIsDialogOpen}
+ triggerRef={expandButtonRef}
+ blobUrl={blobUrl}
+ codeContent={children}
+ />
+ <div
+ className="relative w-full overflow-hidden rounded-lg border border-border-light transition-all duration-200"
+ {...hoverHandlers}
+ onClick={handleContainerClick}
+ >
+ <MermaidHeader
+ className="border-b border-border-light bg-surface-secondary"
+ actionsClassName="transition-opacity duration-200"
+ codeContent={children}
+ showCode={showCode}
+ showExpandButton
+ expandButtonRef={expandButtonRef}
+ onExpand={handleExpand}
+ onToggleCode={handleToggleCode}
+ />
+ {showCode && (
+ <div className="border-b border-border-light bg-surface-secondary p-4">
+ <pre className="overflow-auto whitespace-pre-wrap text-xs text-text-secondary">
+ {children}
+ </pre>
+ </div>
+ )}
+ <div
+ ref={containerRef}
+ className={cn(
+ 'relative overflow-hidden p-4 transition-colors duration-200',
+ 'bg-surface-primary-alt dark:bg-white/[0.03]',
+ isPanning ? 'cursor-grabbing' : 'cursor-grab',
+ )}
+ style={{ height: `${calculatedHeight}px` }}
+ onMouseDown={handleMouseDown}
+ >
+ <div
+ className="absolute inset-0 flex items-center justify-center"
+ style={{
+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
+ transition: isPanning ? 'none' : 'transform 0.1s ease-out',
+ }}
+ >
+ <img
+ src={blobUrl}
+ alt="Mermaid diagram"
+ className="select-none"
+ style={diagramStyle}
+ draggable={false}
+ />
+ </div>
+ <ZoomControls
+ zoom={zoom}
+ pan={pan}
+ codeContent={children}
+ onZoomIn={handleZoomIn}
+ onZoomOut={handleZoomOut}
+ onReset={handleResetZoom}
+ className={cn(
+ 'absolute bottom-2 right-2 z-10 transition-opacity duration-200',
+ showControls ? 'opacity-100' : 'pointer-events-none opacity-0',
+ )}
+ />
+ </div>
+ </div>
+ </>
+ );
+});
+
+Mermaid.displayName = 'Mermaid';
+
+export default Mermaid;
diff --git a/client/src/components/Messages/Content/Mermaid/MermaidDialog.tsx b/client/src/components/Messages/Content/Mermaid/MermaidDialog.tsx
new file mode 100644
index 0000000000..51cf355414
--- /dev/null
+++ b/client/src/components/Messages/Content/Mermaid/MermaidDialog.tsx
@@ -0,0 +1,156 @@
+import React, { memo, useState, useCallback, useRef, useEffect } from 'react';
+import copy from 'copy-to-clipboard';
+import { X, ChevronUp, ChevronDown } from 'lucide-react';
+import {
+ Button,
+ OGDialog,
+ Clipboard,
+ CheckMark,
+ OGDialogClose,
+ OGDialogTitle,
+ OGDialogContent,
+} from '@librechat/client';
+import useMermaidZoom from './useMermaidZoom';
+import ZoomControls from './ZoomControls';
+import { useLocalize } from '~/hooks';
+import cn from '~/utils/cn';
+
+interface MermaidDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ triggerRef: React.RefObject<HTMLButtonElement>;
+ blobUrl: string;
+ codeContent: string;
+}
+
+const MermaidDialog: React.FC<MermaidDialogProps> = memo(
+ ({ open, onOpenChange, triggerRef, blobUrl, codeContent }) => {
+ const localize = useLocalize();
+ const [showCode, setShowCode] = useState(false);
+ const [isCopied, setIsCopied] = useState(false);
+ const showCodeButtonRef = useRef<HTMLButtonElement>(null);
+ const copyButtonRef = useRef<HTMLButtonElement>(null);
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout>>();
+
+ const {
+ zoom,
+ pan,
+ isPanning,
+ handleZoomIn,
+ handleZoomOut,
+ handleResetZoom,
+ handleWheel,
+ handleMouseDown,
+ } = useMermaidZoom();
+
+ useEffect(() => {
+ if (open) {
+ setShowCode(false);
+ handleResetZoom();
+ }
+ }, [open, handleResetZoom]);
+
+ const handleToggleCode = useCallback(() => {
+ setShowCode((prev) => !prev);
+ requestAnimationFrame(() => showCodeButtonRef.current?.focus());
+ }, []);
+
+ const handleCopy = useCallback(() => {
+ copy(codeContent.trim(), { format: 'text/plain' });
+ setIsCopied(true);
+ requestAnimationFrame(() => copyButtonRef.current?.focus());
+ clearTimeout(copyTimerRef.current);
+ copyTimerRef.current = setTimeout(() => {
+ setIsCopied(false);
+ requestAnimationFrame(() => copyButtonRef.current?.focus());
+ }, 3000);
+ }, [codeContent]);
+
+ return (
+ <OGDialog open={open} onOpenChange={onOpenChange} triggerRef={triggerRef}>
+ <OGDialogContent
+ showCloseButton={false}
+ className="h-[85vh] max-h-[85vh] w-[90vw] max-w-[90vw] gap-0 overflow-hidden border-border-light bg-surface-primary-alt p-0"
+ >
+ <OGDialogTitle className="flex h-10 items-center justify-between border-b border-border-light bg-surface-secondary px-4 font-sans text-xs text-text-secondary">
+ <span>{localize('com_ui_mermaid')}</span>
+ <div className="flex gap-2">
+ <Button
+ ref={showCodeButtonRef}
+ variant="ghost"
+ size="sm"
+ className="h-auto min-w-[6rem] gap-1 rounded-sm px-1 py-0 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-border-heavy focus-visible:ring-offset-0"
+ onClick={handleToggleCode}
+ >
+ {showCode ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
+ {showCode ? localize('com_ui_hide_code') : localize('com_ui_show_code')}
+ </Button>
+ <Button
+ ref={copyButtonRef}
+ variant="ghost"
+ size="sm"
+ className="h-auto gap-1 rounded-sm px-1 py-0 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-border-heavy focus-visible:ring-offset-0"
+ onClick={handleCopy}
+ >
+ {isCopied ? <CheckMark className="h-[18px] w-[18px]" /> : <Clipboard />}
+ {localize('com_ui_copy_code')}
+ </Button>
+ <OGDialogClose className="rounded-sm p-1 text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy">
+ <X className="h-4 w-4" />
+ <span className="sr-only">{localize('com_ui_close')}</span>
+ </OGDialogClose>
+ </div>
+ </OGDialogTitle>
+ {showCode && (
+ <div className="border-b border-border-light bg-surface-secondary p-4">
+ <pre className="max-h-[150px] overflow-auto whitespace-pre-wrap text-xs text-text-secondary">
+ {codeContent}
+ </pre>
+ </div>
+ )}
+ <div
+ className={cn(
+ 'relative flex-1 overflow-hidden bg-surface-primary-alt p-4',
+ isPanning ? 'cursor-grabbing' : 'cursor-grab',
+ )}
+ style={{ height: showCode ? 'calc(85vh - 200px)' : 'calc(85vh - 50px)' }}
+ onWheel={handleWheel}
+ onMouseDown={handleMouseDown}
+ >
+ <div
+ className="flex h-full w-full items-center justify-center"
+ style={{
+ transform: `translate(${pan.x}px, ${pan.y}px)`,
+ transition: isPanning ? 'none' : 'transform 0.1s ease-out',
+ }}
+ >
+ <img
+ src={blobUrl}
+ alt="Mermaid diagram"
+ className="max-h-full max-w-full select-none object-contain"
+ style={{
+ transform: `scale(${zoom})`,
+ transformOrigin: 'center center',
+ }}
+ draggable={false}
+ />
+ </div>
+ <ZoomControls
+ zoom={zoom}
+ pan={pan}
+ codeContent={codeContent}
+ onZoomIn={handleZoomIn}
+ onZoomOut={handleZoomOut}
+ onReset={handleResetZoom}
+ className="absolute bottom-4 right-4 z-10"
+ />
+ </div>
+ </OGDialogContent>
+ </OGDialog>
+ );
+ },
+);
+
+MermaidDialog.displayName = 'MermaidDialog';
+
+export default MermaidDialog;
diff --git a/client/src/components/Messages/Content/MermaidErrorBoundary.tsx b/client/src/components/Messages/Content/Mermaid/MermaidErrorBoundary.tsx
similarity index 75%
rename from client/src/components/Messages/Content/MermaidErrorBoundary.tsx
rename to client/src/components/Messages/Content/Mermaid/MermaidErrorBoundary.tsx
index a2edca062c..1d71b927ad 100644
--- a/client/src/components/Messages/Content/MermaidErrorBoundary.tsx
+++ b/client/src/components/Messages/Content/Mermaid/MermaidErrorBoundary.tsx
@@ -2,7 +2,6 @@ import React from 'react';
interface MermaidErrorBoundaryProps {
children: React.ReactNode;
- /** The mermaid code to display as fallback */
code: string;
}
@@ -10,10 +9,6 @@ interface MermaidErrorBoundaryState {
hasError: boolean;
}
-/**
- * Error boundary specifically for Mermaid diagrams.
- * Falls back to displaying the raw mermaid code if rendering fails.
- */
class MermaidErrorBoundary extends React.Component<
MermaidErrorBoundaryProps,
MermaidErrorBoundaryState
@@ -32,7 +27,6 @@ class MermaidErrorBoundary extends React.Component<
}
componentDidUpdate(prevProps: MermaidErrorBoundaryProps) {
- // Reset error state if code changes (e.g., user edits the message)
if (prevProps.code !== this.props.code && this.state.hasError) {
this.setState({ hasError: false });
}
@@ -42,10 +36,10 @@ class MermaidErrorBoundary extends React.Component<
if (this.state.hasError) {
return (
<div className="w-full overflow-hidden rounded-md border border-border-light">
- <div className="rounded-t-md bg-gray-700 px-4 py-2 font-sans text-xs text-gray-200">
+ <div className="rounded-t-md bg-surface-secondary px-4 py-2 font-sans text-xs text-text-secondary">
{'mermaid'}
</div>
- <pre className="overflow-auto whitespace-pre-wrap rounded-b-md bg-gray-900 p-4 font-mono text-xs text-gray-300">
+ <pre className="overflow-auto whitespace-pre-wrap rounded-b-md bg-surface-primary-alt p-4 font-mono text-xs text-text-secondary">
{this.props.code}
</pre>
</div>
diff --git a/client/src/components/Messages/Content/Mermaid/MermaidHeader.tsx b/client/src/components/Messages/Content/Mermaid/MermaidHeader.tsx
new file mode 100644
index 0000000000..e3e71237fb
--- /dev/null
+++ b/client/src/components/Messages/Content/Mermaid/MermaidHeader.tsx
@@ -0,0 +1,104 @@
+import React, { memo, useState, useCallback, useRef, useEffect } from 'react';
+import copy from 'copy-to-clipboard';
+import { TooltipAnchor } from '@librechat/client';
+
+import { Expand, ChevronUp, ChevronDown } from 'lucide-react';
+import CopyButton from '~/components/Messages/Content/CopyButton';
+import { useLocalize } from '~/hooks';
+import cn from '~/utils/cn';
+
+interface MermaidHeaderProps {
+ className?: string;
+ actionsClassName?: string;
+ codeContent: string;
+ showCode: boolean;
+ showExpandButton?: boolean;
+ expandButtonRef?: React.RefObject<HTMLButtonElement>;
+ onExpand?: () => void;
+ onToggleCode: () => void;
+}
+
+const iconBtnClass =
+ 'flex items-center justify-center rounded-lg p-1.5 text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary focus-visible:outline focus-visible:outline-2 focus-visible:outline-border-heavy';
+
+const MermaidHeader: React.FC<MermaidHeaderProps> = memo(
+ ({
+ className,
+ actionsClassName,
+ codeContent,
+ showCode,
+ showExpandButton = false,
+ expandButtonRef,
+ onExpand,
+ onToggleCode,
+ }) => {
+ const localize = useLocalize();
+ const [isCopied, setIsCopied] = useState(false);
+ const copyButtonRef = useRef<HTMLButtonElement>(null);
+ const showCodeButtonRef = useRef<HTMLButtonElement>(null);
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout>>();
+
+ useEffect(() => {
+ return () => clearTimeout(copyTimerRef.current);
+ }, []);
+
+ const handleCopy = useCallback(() => {
+ copy(codeContent.trim(), { format: 'text/plain' });
+ setIsCopied(true);
+ clearTimeout(copyTimerRef.current);
+ copyTimerRef.current = setTimeout(() => setIsCopied(false), 3000);
+ }, [codeContent]);
+
+ const handleToggleCode = useCallback(() => {
+ onToggleCode();
+ requestAnimationFrame(() => {
+ showCodeButtonRef.current?.focus();
+ });
+ }, [onToggleCode]);
+
+ return (
+ <div className={cn('flex items-center justify-between gap-1 px-2 py-1', className)}>
+ <span className="rounded text-xs font-medium text-text-secondary">
+ {localize('com_ui_mermaid')}
+ </span>
+ <div className={cn('flex items-center gap-1', actionsClassName)}>
+ {showExpandButton && onExpand && (
+ <TooltipAnchor
+ description={localize('com_ui_expand')}
+ render={
+ <button
+ ref={expandButtonRef}
+ type="button"
+ aria-label={localize('com_ui_expand')}
+ className={iconBtnClass}
+ onClick={onExpand}
+ >
+ <Expand className="h-4 w-4" />
+ </button>
+ }
+ />
+ )}
+ <TooltipAnchor
+ description={showCode ? localize('com_ui_hide_code') : localize('com_ui_show_code')}
+ render={
+ <button
+ ref={showCodeButtonRef}
+ type="button"
+ aria-label={showCode ? localize('com_ui_hide_code') : localize('com_ui_show_code')}
+ className={iconBtnClass}
+ onClick={handleToggleCode}
+ >
+ {showCode ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
+ </button>
+ }
+ />
+ <CopyButton ref={copyButtonRef} isCopied={isCopied} iconOnly onClick={handleCopy} />
+ </div>
+ </div>
+ );
+ },
+);
+
+MermaidHeader.displayName = 'MermaidHeader';
+
+export default MermaidHeader;
diff --git a/client/src/components/Messages/Content/Mermaid/ZoomControls.tsx b/client/src/components/Messages/Content/Mermaid/ZoomControls.tsx
new file mode 100644
index 0000000000..ddb5bbb763
--- /dev/null
+++ b/client/src/components/Messages/Content/Mermaid/ZoomControls.tsx
@@ -0,0 +1,106 @@
+import React, { memo, useState, useCallback, useRef, useEffect } from 'react';
+import copy from 'copy-to-clipboard';
+import { ZoomIn, ZoomOut, RotateCcw } from 'lucide-react';
+import { Clipboard, CheckMark } from '@librechat/client';
+import { MIN_ZOOM, MAX_ZOOM } from './useMermaidZoom';
+import { useLocalize } from '~/hooks';
+import cn from '~/utils/cn';
+
+interface ZoomControlsProps {
+ zoom: number;
+ pan: { x: number; y: number };
+ codeContent: string;
+ onZoomIn: () => void;
+ onZoomOut: () => void;
+ onReset: () => void;
+ className?: string;
+}
+
+const btnClass =
+ 'rounded p-1.5 text-text-secondary hover:bg-surface-hover disabled:opacity-40 disabled:hover:bg-transparent';
+
+const ZoomControls: React.FC<ZoomControlsProps> = memo(
+ ({ zoom, pan, codeContent, onZoomIn, onZoomOut, onReset, className }) => {
+ const localize = useLocalize();
+ const [isCopied, setIsCopied] = useState(false);
+ const copyRef = useRef<HTMLButtonElement>(null);
+ const copyTimerRef = useRef<ReturnType<typeof setTimeout>>();
+
+ useEffect(() => {
+ return () => clearTimeout(copyTimerRef.current);
+ }, []);
+
+ const handleCopy = useCallback(() => {
+ copy(codeContent.trim(), { format: 'text/plain' });
+ setIsCopied(true);
+ requestAnimationFrame(() => copyRef.current?.focus());
+ clearTimeout(copyTimerRef.current);
+ copyTimerRef.current = setTimeout(() => {
+ setIsCopied(false);
+ requestAnimationFrame(() => copyRef.current?.focus());
+ }, 3000);
+ }, [codeContent]);
+
+ const stop =
+ (fn: () => void) =>
+ (e: React.MouseEvent): void => {
+ e.stopPropagation();
+ fn();
+ };
+
+ return (
+ <div
+ className={cn(
+ 'flex items-center gap-1 rounded-lg border border-border-light bg-surface-secondary p-1 shadow-md',
+ className,
+ )}
+ >
+ <button
+ type="button"
+ onClick={stop(onZoomOut)}
+ disabled={zoom <= MIN_ZOOM}
+ className={btnClass}
+ title={localize('com_ui_zoom_out')}
+ >
+ <ZoomOut className="h-4 w-4" />
+ </button>
+ <span className="min-w-[3rem] text-center text-xs text-text-secondary">
+ {Math.round(zoom * 100)}%
+ </span>
+ <button
+ type="button"
+ onClick={stop(onZoomIn)}
+ disabled={zoom >= MAX_ZOOM}
+ className={btnClass}
+ title={localize('com_ui_zoom_in')}
+ >
+ <ZoomIn className="h-4 w-4" />
+ </button>
+ <div className="mx-1 h-4 w-px bg-border-medium" />
+ <button
+ type="button"
+ onClick={stop(onReset)}
+ disabled={zoom === 1 && pan.x === 0 && pan.y === 0}
+ className={btnClass}
+ title={localize('com_ui_reset_zoom')}
+ >
+ <RotateCcw className="h-4 w-4" />
+ </button>
+ <div className="mx-1 h-4 w-px bg-border-medium" />
+ <button
+ ref={copyRef}
+ type="button"
+ onClick={stop(handleCopy)}
+ className="rounded p-1.5 text-text-secondary hover:bg-surface-hover"
+ title={localize('com_ui_copy_code')}
+ >
+ {isCopied ? <CheckMark className="h-4 w-4" /> : <Clipboard className="h-4 w-4" />}
+ </button>
+ </div>
+ );
+ },
+);
+
+ZoomControls.displayName = 'ZoomControls';
+
+export default ZoomControls;
diff --git a/client/src/components/Messages/Content/Mermaid/index.ts b/client/src/components/Messages/Content/Mermaid/index.ts
new file mode 100644
index 0000000000..5357be2c34
--- /dev/null
+++ b/client/src/components/Messages/Content/Mermaid/index.ts
@@ -0,0 +1,2 @@
+export { default } from './Mermaid';
+export { default as MermaidErrorBoundary } from './MermaidErrorBoundary';
diff --git a/client/src/components/Messages/Content/Mermaid/useMermaidZoom.ts b/client/src/components/Messages/Content/Mermaid/useMermaidZoom.ts
new file mode 100644
index 0000000000..37153e4003
--- /dev/null
+++ b/client/src/components/Messages/Content/Mermaid/useMermaidZoom.ts
@@ -0,0 +1,93 @@
+import { useState, useCallback, useEffect, useRef } from 'react';
+
+export const MIN_ZOOM = 0.25;
+export const MAX_ZOOM = 4;
+const ZOOM_STEP = 0.25;
+
+interface UseMermaidZoomOptions {
+ containerRef?: React.RefObject<HTMLDivElement | null>;
+ wheelDep?: unknown;
+}
+
+export default function useMermaidZoom({ containerRef, wheelDep }: UseMermaidZoomOptions = {}) {
+ const [zoom, setZoom] = useState(1);
+ const [pan, setPan] = useState({ x: 0, y: 0 });
+ const [isPanning, setIsPanning] = useState(false);
+ const panStartRef = useRef({ x: 0, y: 0 });
+
+ const handleZoomIn = useCallback(() => {
+ setZoom((prev) => Math.min(prev + ZOOM_STEP, MAX_ZOOM));
+ }, []);
+
+ const handleZoomOut = useCallback(() => {
+ setZoom((prev) => Math.max(prev - ZOOM_STEP, MIN_ZOOM));
+ }, []);
+
+ const handleResetZoom = useCallback(() => {
+ setZoom(1);
+ setPan({ x: 0, y: 0 });
+ }, []);
+
+ const handleWheel = useCallback((e: React.WheelEvent) => {
+ e.preventDefault();
+ const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
+ setZoom((prev) => Math.min(Math.max(prev + delta, MIN_ZOOM), MAX_ZOOM));
+ }, []);
+
+ const panRef = useRef(pan);
+ panRef.current = pan;
+
+ const handleMouseDown = useCallback((e: React.MouseEvent) => {
+ const target = e.target as HTMLElement;
+ if (e.button === 0 && target.tagName !== 'BUTTON' && !target.closest('button')) {
+ setIsPanning(true);
+ panStartRef.current = { x: e.clientX - panRef.current.x, y: e.clientY - panRef.current.y };
+ }
+ }, []);
+
+ useEffect(() => {
+ if (!isPanning) {
+ return;
+ }
+ const onMove = (e: MouseEvent) => {
+ setPan({
+ x: e.clientX - panStartRef.current.x,
+ y: e.clientY - panStartRef.current.y,
+ });
+ };
+ const onUp = () => setIsPanning(false);
+ document.addEventListener('mousemove', onMove);
+ document.addEventListener('mouseup', onUp);
+ return () => {
+ document.removeEventListener('mousemove', onMove);
+ document.removeEventListener('mouseup', onUp);
+ };
+ }, [isPanning]);
+
+ useEffect(() => {
+ const container = containerRef?.current;
+ if (!container) {
+ return;
+ }
+ const onWheel = (e: WheelEvent) => {
+ if (e.ctrlKey || e.metaKey) {
+ e.preventDefault();
+ const delta = e.deltaY > 0 ? -ZOOM_STEP : ZOOM_STEP;
+ setZoom((prev) => Math.min(Math.max(prev + delta, MIN_ZOOM), MAX_ZOOM));
+ }
+ };
+ container.addEventListener('wheel', onWheel, { passive: false });
+ return () => container.removeEventListener('wheel', onWheel);
+ }, [containerRef, wheelDep]);
+
+ return {
+ zoom,
+ pan,
+ isPanning,
+ handleZoomIn,
+ handleZoomOut,
+ handleResetZoom,
+ handleWheel,
+ handleMouseDown,
+ };
+}
diff --git a/client/src/components/Messages/Content/Mermaid/useSvgProcessing.ts b/client/src/components/Messages/Content/Mermaid/useSvgProcessing.ts
new file mode 100644
index 0000000000..22197977f3
--- /dev/null
+++ b/client/src/components/Messages/Content/Mermaid/useSvgProcessing.ts
@@ -0,0 +1,176 @@
+import { useEffect, useMemo, useState, useRef } from 'react';
+import { fixSubgraphTitleContrast } from '~/utils/mermaid';
+import { useDebouncedMermaid } from '~/hooks';
+
+const MIN_CONTAINER_HEIGHT = 200;
+const MAX_CONTAINER_HEIGHT = 500;
+
+interface UseSvgProcessingOptions {
+ content: string;
+ id?: string;
+ theme?: string;
+ retryCount: number;
+ containerRef: React.RefObject<HTMLDivElement | null>;
+}
+
+function applyFallbackFixes(svgString: string): string {
+ let finalSvg = svgString;
+
+ if (
+ !svgString.includes('viewBox') &&
+ svgString.includes('height=') &&
+ svgString.includes('width=')
+ ) {
+ const widthMatch = svgString.match(/width="(\d+)"/);
+ const heightMatch = svgString.match(/height="(\d+)"/);
+ if (widthMatch && heightMatch) {
+ finalSvg = finalSvg.replace('<svg', `<svg viewBox="0 0 ${widthMatch[1]} ${heightMatch[1]}"`);
+ }
+ }
+
+ if (!finalSvg.includes('xmlns')) {
+ finalSvg = finalSvg.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"');
+ }
+
+ return finalSvg;
+}
+
+function processSvgString(svg: string) {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(svg, 'image/svg+xml');
+
+ if (doc.querySelector('parsererror')) {
+ return { processedSvg: applyFallbackFixes(svg), parsedDimensions: null };
+ }
+
+ const svgElement = doc.querySelector('svg');
+ if (!svgElement) {
+ return { processedSvg: applyFallbackFixes(svg), parsedDimensions: null };
+ }
+
+ let width = parseFloat(svgElement.getAttribute('width') || '0');
+ let height = parseFloat(svgElement.getAttribute('height') || '0');
+
+ if (!width || !height) {
+ const viewBox = svgElement.getAttribute('viewBox');
+ if (viewBox) {
+ const parts = viewBox.split(/[\s,]+/).map(Number);
+ if (parts.length === 4) {
+ width = parts[2];
+ height = parts[3];
+ }
+ }
+ }
+
+ let dimensions: { width: number; height: number } | null = null;
+ if (width > 0 && height > 0) {
+ dimensions = { width, height };
+ if (!svgElement.getAttribute('viewBox')) {
+ svgElement.setAttribute('viewBox', `0 0 ${width} ${height}`);
+ }
+ svgElement.removeAttribute('width');
+ svgElement.removeAttribute('height');
+ svgElement.removeAttribute('style');
+ }
+
+ if (!svgElement.getAttribute('xmlns')) {
+ svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
+ }
+
+ fixSubgraphTitleContrast(svgElement);
+
+ return {
+ processedSvg: new XMLSerializer().serializeToString(doc),
+ parsedDimensions: dimensions,
+ };
+}
+
+export default function useSvgProcessing({
+ content,
+ id,
+ theme,
+ retryCount,
+ containerRef,
+}: UseSvgProcessingOptions) {
+ const [blobUrl, setBlobUrl] = useState('');
+ const [svgDimensions, setSvgDimensions] = useState<{ width: number; height: number } | null>(
+ null,
+ );
+ const [containerWidth, setContainerWidth] = useState(700);
+ const lastValidSvgRef = useRef<string | null>(null);
+
+ const { svg, isLoading, error } = useDebouncedMermaid({
+ content,
+ id,
+ theme,
+ key: retryCount,
+ });
+
+ useEffect(() => {
+ if (svg) {
+ lastValidSvgRef.current = svg;
+ }
+ }, [svg]);
+
+ useEffect(() => {
+ if (!containerRef.current) {
+ return;
+ }
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ setContainerWidth(entry.contentRect.width);
+ }
+ });
+ observer.observe(containerRef.current);
+ return () => observer.disconnect();
+ }, [containerRef]);
+
+ const { processedSvg, parsedDimensions } = useMemo(() => {
+ if (!svg) {
+ return { processedSvg: null, parsedDimensions: null };
+ }
+ return processSvgString(svg);
+ }, [svg]);
+
+ useEffect(() => {
+ if (parsedDimensions) {
+ setSvgDimensions(parsedDimensions);
+ }
+ }, [parsedDimensions]);
+
+ useEffect(() => {
+ if (!processedSvg) {
+ return;
+ }
+ const blob = new Blob([processedSvg], { type: 'image/svg+xml' });
+ const url = URL.createObjectURL(blob);
+ setBlobUrl(url);
+ return () => URL.revokeObjectURL(url);
+ }, [processedSvg]);
+
+ const { initialScale, calculatedHeight } = useMemo(() => {
+ if (!svgDimensions) {
+ return { initialScale: 1, calculatedHeight: MAX_CONTAINER_HEIGHT };
+ }
+ const padding = 32;
+ const availableWidth = containerWidth - padding;
+ const scaleX = availableWidth / svgDimensions.width;
+ const scaleY = MAX_CONTAINER_HEIGHT / svgDimensions.height;
+ const scale = Math.min(scaleX, scaleY, 1);
+ const height = Math.max(
+ MIN_CONTAINER_HEIGHT,
+ Math.min(MAX_CONTAINER_HEIGHT, svgDimensions.height * scale + padding),
+ );
+ return { initialScale: scale, calculatedHeight: height };
+ }, [svgDimensions, containerWidth]);
+
+ return {
+ blobUrl,
+ svgDimensions,
+ isLoading,
+ error,
+ lastValidSvgRef,
+ initialScale,
+ calculatedHeight,
+ };
+}
diff --git a/client/src/components/Messages/Content/MermaidHeader.tsx b/client/src/components/Messages/Content/MermaidHeader.tsx
deleted file mode 100644
index 2d3a416a5a..0000000000
--- a/client/src/components/Messages/Content/MermaidHeader.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import React, { memo, useState, useCallback, useRef } from 'react';
-import copy from 'copy-to-clipboard';
-import { Expand, ChevronUp, ChevronDown } from 'lucide-react';
-import { Clipboard, CheckMark, TooltipAnchor } from '@librechat/client';
-import { useLocalize } from '~/hooks';
-import cn from '~/utils/cn';
-
-interface MermaidHeaderProps {
- className?: string;
- codeContent: string;
- showCode: boolean;
- showExpandButton?: boolean;
- expandButtonRef?: React.RefObject<HTMLButtonElement>;
- onExpand?: () => void;
- onToggleCode: () => void;
-}
-
-const iconBtnClass =
- 'flex items-center justify-center rounded p-1.5 text-text-secondary hover:bg-surface-hover focus-visible:outline focus-visible:outline-white';
-
-const MermaidHeader: React.FC<MermaidHeaderProps> = memo(
- ({
- className,
- codeContent,
- showCode,
- showExpandButton = false,
- expandButtonRef,
- onExpand,
- onToggleCode,
- }) => {
- const localize = useLocalize();
- const [isCopied, setIsCopied] = useState(false);
- const copyButtonRef = useRef<HTMLButtonElement>(null);
- const showCodeButtonRef = useRef<HTMLButtonElement>(null);
-
- const handleCopy = useCallback(() => {
- copy(codeContent.trim(), { format: 'text/plain' });
- setIsCopied(true);
- setTimeout(() => setIsCopied(false), 3000);
- }, [codeContent]);
-
- const handleToggleCode = useCallback(() => {
- onToggleCode();
- requestAnimationFrame(() => {
- showCodeButtonRef.current?.focus();
- });
- }, [onToggleCode]);
-
- return (
- <div
- className={cn(
- 'flex items-center justify-end gap-1 px-2 py-1 transition-opacity duration-200',
- className,
- )}
- >
- {showExpandButton && onExpand && (
- <TooltipAnchor
- description={localize('com_ui_expand')}
- render={
- <button
- ref={expandButtonRef}
- type="button"
- aria-label={localize('com_ui_expand')}
- className={iconBtnClass}
- onClick={onExpand}
- >
- <Expand className="h-4 w-4" />
- </button>
- }
- />
- )}
- <TooltipAnchor
- description={showCode ? localize('com_ui_hide_code') : localize('com_ui_show_code')}
- render={
- <button
- ref={showCodeButtonRef}
- type="button"
- aria-label={showCode ? localize('com_ui_hide_code') : localize('com_ui_show_code')}
- className={iconBtnClass}
- onClick={handleToggleCode}
- >
- {showCode ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
- </button>
- }
- />
- <TooltipAnchor
- description={isCopied ? localize('com_ui_copied') : localize('com_ui_copy_code')}
- render={
- <button
- ref={copyButtonRef}
- type="button"
- aria-label={isCopied ? localize('com_ui_copied') : localize('com_ui_copy_code')}
- className={iconBtnClass}
- onClick={handleCopy}
- >
- {isCopied ? (
- <CheckMark className="h-[18px] w-[18px]" />
- ) : (
- <Clipboard className="h-4 w-4" />
- )}
- </button>
- }
- />
- </div>
- );
- },
-);
-
-MermaidHeader.displayName = 'MermaidHeader';
-
-export default MermaidHeader;
diff --git a/client/src/components/Messages/Content/ResultSwitcher.tsx b/client/src/components/Messages/Content/ResultSwitcher.tsx
index eb8c59b568..ee67e9b11a 100644
--- a/client/src/components/Messages/Content/ResultSwitcher.tsx
+++ b/client/src/components/Messages/Content/ResultSwitcher.tsx
@@ -1,3 +1,6 @@
+import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { useLocalize } from '~/hooks';
+
interface ResultSwitcherProps {
currentIndex: number;
totalCount: number;
@@ -5,65 +8,47 @@ interface ResultSwitcherProps {
onNext: () => void;
}
-const ResultSwitcher: React.FC<ResultSwitcherProps> = ({
+export default function ResultSwitcher({
currentIndex,
totalCount,
onPrevious,
onNext,
-}) => {
+}: ResultSwitcherProps) {
+ const localize = useLocalize();
+
if (totalCount <= 1) {
return null;
}
+ const atFirst = currentIndex === 0;
+ const atLast = currentIndex === totalCount - 1;
+
return (
- <div className="flex items-center justify-start gap-1 self-center bg-gray-700 pb-2 text-xs">
+ <nav
+ aria-label={localize('com_ui_navigate_results')}
+ className="flex items-center justify-center gap-1.5 border-t border-border-light px-3 py-1.5 text-xs"
+ >
<button
- className="hover-button rounded-md p-1 text-gray-400 hover:bg-gray-700 hover:text-gray-200 disabled:hover:text-gray-400"
type="button"
onClick={onPrevious}
- disabled={currentIndex === 0}
+ disabled={atFirst}
+ aria-label={localize('com_ui_prev_result')}
+ className="rounded p-0.5 text-text-tertiary transition-colors hover:bg-surface-hover hover:text-text-primary focus:outline focus:outline-2 focus:outline-border-heavy disabled:pointer-events-none disabled:opacity-30"
>
- <svg
- stroke="currentColor"
- fill="none"
- strokeWidth="1.5"
- viewBox="0 0 24 24"
- strokeLinecap="round"
- strokeLinejoin="round"
- className="h-4 w-4"
- height="1em"
- width="1em"
- xmlns="http://www.w3.org/2000/svg"
- >
- <polyline points="15 18 9 12 15 6" />
- </svg>
+ <ChevronLeft className="size-3.5" aria-hidden="true" />
</button>
- <span className="flex-shrink-0 tabular-nums">
- {currentIndex + 1} / {totalCount}
+ <span className="min-w-[3ch] select-none text-center tabular-nums text-text-secondary">
+ {currentIndex + 1}/{totalCount}
</span>
<button
- className="hover-button rounded-md p-1 text-gray-400 hover:bg-gray-700 hover:text-gray-200 disabled:hover:text-gray-400"
type="button"
onClick={onNext}
- disabled={currentIndex === totalCount - 1}
+ disabled={atLast}
+ aria-label={localize('com_ui_next_result')}
+ className="rounded p-0.5 text-text-tertiary transition-colors hover:bg-surface-hover hover:text-text-primary focus:outline focus:outline-2 focus:outline-border-heavy disabled:pointer-events-none disabled:opacity-30"
>
- <svg
- stroke="currentColor"
- fill="none"
- strokeWidth="1.5"
- viewBox="0 0 24 24"
- strokeLinecap="round"
- strokeLinejoin="round"
- className="h-4 w-4"
- height="1em"
- width="1em"
- xmlns="http://www.w3.org/2000/svg"
- >
- <polyline points="9 18 15 12 9 6" />
- </svg>
+ <ChevronRight className="size-3.5" aria-hidden="true" />
</button>
- </div>
+ </nav>
);
-};
-
-export default ResultSwitcher;
+}
diff --git a/client/src/components/Messages/Content/RunCode.tsx b/client/src/components/Messages/Content/RunCode.tsx
index 7398459639..31f4f6a668 100644
--- a/client/src/components/Messages/Content/RunCode.tsx
+++ b/client/src/components/Messages/Content/RunCode.tsx
@@ -1,14 +1,16 @@
-import React, { useMemo, useCallback, useEffect } from 'react';
+import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import debounce from 'lodash/debounce';
-import { TerminalSquareIcon } from 'lucide-react';
import { Tools, AuthType } from 'librechat-data-provider';
+import { TerminalSquareIcon, Check, X } from 'lucide-react';
import { Spinner, TooltipAnchor, useToastContext } from '@librechat/client';
import type { CodeBarProps } from '~/common';
import { useVerifyAgentToolAuth, useToolCallMutation } from '~/data-provider';
import ApiKeyDialog from '~/components/SidePanel/Agents/Code/ApiKeyDialog';
import { useLocalize, useCodeApiKeyForm } from '~/hooks';
-import { useMessageContext } from '~/Providers';
import { cn, normalizeLanguage } from '~/utils';
+import { useMessageContext } from '~/Providers';
+
+type RunState = 'idle' | 'loading' | 'success' | 'error';
const RunCode: React.FC<CodeBarProps & { iconOnly?: boolean }> = React.memo(
({ lang, codeRef, blockIndex, iconOnly = false }) => {
@@ -79,43 +81,108 @@ const RunCode: React.FC<CodeBarProps & { iconOnly?: boolean }> = React.memo(
};
}, [debouncedExecute]);
+ const [runState, setRunState] = useState<RunState>('idle');
+ const timerRef = useRef<ReturnType<typeof setTimeout>>();
+
+ useEffect(() => {
+ if (execute.isLoading) {
+ setRunState('loading');
+ } else if (runState === 'loading') {
+ const next: RunState = execute.isError ? 'error' : 'success';
+ setRunState(next);
+ timerRef.current = setTimeout(() => setRunState('idle'), next === 'error' ? 2000 : 1500);
+ }
+ return () => clearTimeout(timerRef.current);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [execute.isLoading, execute.isError]);
+
if (typeof normalizedLang !== 'string' || normalizedLang.length === 0) {
return null;
}
- const buttonContent = (
- <>
- {execute.isLoading ? (
- <Spinner className="animate-spin" size={18} />
- ) : (
- <TerminalSquareIcon size={18} aria-hidden="true" />
- )}
- {!iconOnly && localize('com_ui_run_code')}
- </>
- );
+ const isLoading = runState === 'loading';
+ const isSuccess = runState === 'success';
+ const isError = runState === 'error';
+ const isIdle = runState === 'idle';
+ const label = localize('com_ui_run_code');
+
+ const iconClass = (active: boolean) =>
+ cn(
+ 'absolute transition-all duration-300 ease-out',
+ active ? 'rotate-0 scale-100 opacity-100' : 'scale-0 opacity-0 rotate-90',
+ );
const button = (
<button
type="button"
+ onClick={debouncedExecute}
+ disabled={isLoading}
+ aria-label={label}
+ aria-busy={isLoading || undefined}
className={cn(
- 'flex items-center justify-center rounded-sm hover:bg-gray-700 focus:bg-gray-700 focus:outline focus:outline-white',
- iconOnly ? 'p-1.5' : 'ml-auto gap-2 px-2 py-1',
+ 'inline-flex select-none items-center justify-center text-text-secondary transition-all duration-200 ease-out',
+ 'hover:bg-surface-hover hover:text-text-primary',
+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-border-heavy',
+ 'disabled:pointer-events-none disabled:opacity-50',
+ isError && 'text-text-destructive hover:text-text-destructive',
+ iconOnly ? 'rounded-lg p-1.5' : 'ml-auto gap-2 rounded-md px-2 py-1',
)}
- onClick={debouncedExecute}
- disabled={execute.isLoading}
- aria-label={localize('com_ui_run_code')}
>
- {buttonContent}
+ <span className="relative flex size-[18px] items-center justify-center" aria-hidden="true">
+ <TerminalSquareIcon size={18} className={iconClass(isIdle)} />
+ <span
+ className={cn(
+ 'absolute transition-opacity duration-300',
+ isLoading ? 'opacity-100' : 'opacity-0',
+ )}
+ >
+ <Spinner className="animate-spin" size={18} />
+ </span>
+ <Check size={18} className={iconClass(isSuccess)} />
+ <X size={18} className={iconClass(isError)} />
+ </span>
+ {!iconOnly && (
+ <span className="relative overflow-hidden">
+ <span
+ className={cn(
+ 'block whitespace-nowrap transition-all duration-300 ease-out',
+ isIdle ? 'translate-y-0 opacity-100' : '-translate-y-full opacity-0',
+ )}
+ >
+ {localize('com_ui_run_code')}
+ </span>
+ <span
+ className={cn(
+ 'absolute inset-0 whitespace-nowrap transition-all duration-300 ease-out',
+ isLoading ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0',
+ )}
+ >
+ {localize('com_ui_running')}
+ </span>
+ <span
+ className={cn(
+ 'absolute inset-0 whitespace-nowrap transition-all duration-300 ease-out',
+ isSuccess ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0',
+ )}
+ >
+ {localize('com_ui_complete')}
+ </span>
+ <span
+ className={cn(
+ 'absolute inset-0 whitespace-nowrap transition-all duration-300 ease-out',
+ isError ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0',
+ )}
+ >
+ {localize('com_ui_failed')}
+ </span>
+ </span>
+ )}
</button>
);
return (
<>
- {iconOnly ? (
- <TooltipAnchor description={localize('com_ui_run_code')} render={button} />
- ) : (
- button
- )}
+ {iconOnly ? <TooltipAnchor description={label} render={button} /> : button}
<ApiKeyDialog
onSubmit={onSubmit}
isOpen={isDialogOpen}
diff --git a/client/src/components/Messages/Content/langIconPaths.ts b/client/src/components/Messages/Content/langIconPaths.ts
new file mode 100644
index 0000000000..79c5943411
--- /dev/null
+++ b/client/src/components/Messages/Content/langIconPaths.ts
@@ -0,0 +1,56 @@
+/** SVG path data sourced from Simple Icons (https://simpleicons.org). Licensed under CC0 1.0. */
+const LANG_ICON_PATHS: Record<string, string> = {
+ python: `M14.25.18l.9.2.73.26.59.3.45.32.34.34.25.34.16.33.1.3.04.26.02.2-.01.13V8.5l-.05.63-.13.55-.21.46-.26.38-.3.31-.33.25-.35.19-.35.14-.33.1-.3.07-.26.04-.21.02H8.77l-.69.05-.59.14-.5.22-.41.27-.33.32-.27.35-.2.36-.15.37-.1.35-.07.32-.04.27-.02.21v3.06H3.17l-.21-.03-.28-.07-.32-.12-.35-.18-.36-.26-.36-.36-.35-.46-.32-.59-.28-.73-.21-.88-.14-1.05-.05-1.23.06-1.22.16-1.04.24-.87.32-.71.36-.57.4-.44.42-.33.42-.24.4-.16.36-.1.32-.05.24-.01h.16l.06.01h8.16v-.83H6.18l-.01-2.75-.02-.37.05-.34.11-.31.17-.28.25-.26.31-.23.38-.2.44-.18.51-.15.58-.12.64-.1.71-.06.77-.04.84-.02 1.27.05zm-6.3 1.98l-.23.33-.08.41.08.41.23.34.33.22.41.09.41-.09.33-.22.23-.34.08-.41-.08-.41-.23-.33-.33-.22-.41-.09-.41.09zm13.09 3.95l.28.06.32.12.35.18.36.27.36.35.35.47.32.59.28.73.21.88.14 1.04.05 1.23-.06 1.23-.16 1.04-.24.86-.32.71-.36.57-.4.45-.42.33-.42.24-.4.16-.36.09-.32.05-.24.02-.16-.01h-8.22v.82h5.84l.01 2.76.02.36-.05.34-.11.31-.17.29-.25.25-.31.24-.38.2-.44.17-.51.15-.58.13-.64.09-.71.07-.77.04-.84.01-1.27-.04-1.07-.14-.9-.2-.73-.25-.59-.3-.45-.33-.34-.34-.25-.34-.16-.33-.1-.3-.04-.25-.02-.2.01-.13v-5.34l.05-.64.13-.54.21-.46.26-.38.3-.32.33-.24.35-.2.35-.14.33-.1.3-.06.26-.04.21-.02.13-.01h5.84l.69-.05.59-.14.5-.21.41-.28.33-.32.27-.35.2-.36.15-.36.1-.35.07-.32.04-.28.02-.21V6.07h2.09l.14.01zm-6.47 14.25l-.23.33-.08.41.08.41.23.33.33.23.41.08.41-.08.33-.23.23-.33.08-.41-.08-.41-.23-.33-.33-.23-.41-.08-.41.08z`,
+ javascript: `M0 0h24v24H0V0zm22.034 18.276c-.175-1.095-.888-2.015-3.003-2.873-.736-.345-1.554-.585-1.797-1.14-.091-.33-.105-.51-.046-.705.15-.646.915-.84 1.515-.66.39.12.75.42.976.9 1.034-.676 1.034-.676 1.755-1.125-.27-.42-.404-.601-.586-.78-.63-.705-1.469-1.065-2.834-1.034l-.705.089c-.676.165-1.32.525-1.71 1.005-1.14 1.291-.811 3.541.569 4.471 1.365 1.02 3.361 1.244 3.616 2.205.24 1.17-.87 1.545-1.966 1.41-.811-.18-1.26-.586-1.755-1.336l-1.83 1.051c.21.48.45.689.81 1.109 1.74 1.756 6.09 1.666 6.871-1.004.029-.09.24-.705.074-1.65l.046.067zm-8.983-7.245h-2.248c0 1.938-.009 3.864-.009 5.805 0 1.232.063 2.363-.138 2.711-.33.689-1.18.601-1.566.48-.396-.196-.597-.466-.83-.855-.063-.105-.11-.196-.127-.196l-1.825 1.125c.305.63.75 1.172 1.324 1.517.855.51 2.004.675 3.207.405.783-.226 1.458-.691 1.811-1.411.51-.93.402-2.07.397-3.346.012-2.054 0-4.109 0-6.179l.004-.056z`,
+ typescript: `M1.125 0C.502 0 0 .502 0 1.125v21.75C0 23.498.502 24 1.125 24h21.75c.623 0 1.125-.502 1.125-1.125V1.125C24 .502 23.498 0 22.875 0zm17.363 9.75c.612 0 1.154.037 1.627.111a6.38 6.38 0 0 1 1.306.34v2.458a3.95 3.95 0 0 0-.643-.361 5.093 5.093 0 0 0-.717-.26 5.453 5.453 0 0 0-1.426-.2c-.3 0-.573.028-.819.086a2.1 2.1 0 0 0-.623.242c-.17.104-.3.229-.393.374a.888.888 0 0 0-.14.49c0 .196.053.373.156.529.104.156.252.304.443.444s.423.276.696.41c.273.135.582.274.926.416.47.197.892.407 1.266.628.374.222.695.473.963.753.268.279.472.598.614.957.142.359.214.776.214 1.253 0 .657-.125 1.21-.373 1.656a3.033 3.033 0 0 1-1.012 1.085 4.38 4.38 0 0 1-1.487.596c-.566.12-1.163.18-1.79.18a9.916 9.916 0 0 1-1.84-.164 5.544 5.544 0 0 1-1.512-.493v-2.63a5.033 5.033 0 0 0 3.237 1.2c.333 0 .624-.03.872-.09.249-.06.456-.144.623-.25.166-.108.29-.234.373-.38a1.023 1.023 0 0 0-.074-1.089 2.12 2.12 0 0 0-.537-.5 5.597 5.597 0 0 0-.807-.444 27.72 27.72 0 0 0-1.007-.436c-.918-.383-1.602-.852-2.053-1.405-.45-.553-.676-1.222-.676-2.005 0-.614.123-1.141.369-1.582.246-.441.58-.804 1.004-1.089a4.494 4.494 0 0 1 1.47-.629 7.536 7.536 0 0 1 1.77-.201zm-15.113.188h9.563v2.166H9.506v9.646H6.789v-9.646H3.375z`,
+ rust: `M23.8346 11.7033l-1.0073-.6236a13.7268 13.7268 0 00-.0283-.2936l.8656-.8069a.3483.3483 0 00-.1154-.578l-1.1066-.414a8.4958 8.4958 0 00-.087-.2856l.6904-.9587a.3462.3462 0 00-.2257-.5446l-1.1663-.1894a9.3574 9.3574 0 00-.1407-.2622l.49-1.0761a.3437.3437 0 00-.0274-.3361.3486.3486 0 00-.3006-.154l-1.1845.0416a6.7444 6.7444 0 00-.1873-.2268l.2723-1.153a.3472.3472 0 00-.417-.4172l-1.1532.2724a14.0183 14.0183 0 00-.2278-.1873l.0415-1.1845a.3442.3442 0 00-.49-.328l-1.076.491c-.0872-.0476-.1742-.0952-.2623-.1407l-.1903-1.1673A.3483.3483 0 0016.256.955l-.9597.6905a8.4867 8.4867 0 00-.2855-.086l-.414-1.1066a.3483.3483 0 00-.5781-.1154l-.8069.8666a9.2936 9.2936 0 00-.2936-.0284L12.2946.1683a.3462.3462 0 00-.5892 0l-.6236 1.0073a13.7383 13.7383 0 00-.2936.0284L9.9803.3374a.3462.3462 0 00-.578.1154l-.4141 1.1065c-.0962.0274-.1903.0567-.2855.086L7.744.955a.3483.3483 0 00-.5447.2258L7.009 2.348a9.3574 9.3574 0 00-.2622.1407l-1.0762-.491a.3462.3462 0 00-.49.328l.0416 1.1845a7.9826 7.9826 0 00-.2278.1873L3.8413 3.425a.3472.3472 0 00-.4171.4171l.2713 1.1531c-.0628.075-.1255.1509-.1863.2268l-1.1845-.0415a.3462.3462 0 00-.328.49l.491 1.0761a9.167 9.167 0 00-.1407.2622l-1.1662.1894a.3483.3483 0 00-.2258.5446l.6904.9587a13.303 13.303 0 00-.087.2855l-1.1065.414a.3483.3483 0 00-.1155.5781l.8656.807a9.2936 9.2936 0 00-.0283.2935l-1.0073.6236a.3442.3442 0 000 .5892l1.0073.6236c.008.0982.0182.1964.0283.2936l-.8656.8079a.3462.3462 0 00.1155.578l1.1065.4141c.0273.0962.0567.1914.087.2855l-.6904.9587a.3452.3452 0 00.2268.5447l1.1662.1893c.0456.088.0922.1751.1408.2622l-.491 1.0762a.3462.3462 0 00.328.49l1.1834-.0415c.0618.0769.1235.1528.1873.2277l-.2713 1.1541a.3462.3462 0 00.4171.4161l1.153-.2713c.075.0638.151.1255.2279.1863l-.0415 1.1845a.3442.3442 0 00.49.327l1.0761-.49c.087.0486.1741.0951.2622.1407l.1903 1.1662a.3483.3483 0 00.5447.2268l.9587-.6904a9.299 9.299 0 00.2855.087l.414 1.1066a.3452.3452 0 00.5781.1154l.8079-.8656c.0972.0111.1954.0203.2936.0294l.6236 1.0073a.3472.3472 0 00.5892 0l.6236-1.0073c.0982-.0091.1964-.0183.2936-.0294l.8069.8656a.3483.3483 0 00.578-.1154l.4141-1.1066a8.4626 8.4626 0 00.2855-.087l.9587.6904a.3452.3452 0 00.5447-.2268l.1903-1.1662c.088-.0456.1751-.0931.2622-.1407l1.0762.49a.3472.3472 0 00.49-.327l-.0415-1.1845a6.7267 6.7267 0 00.2267-.1863l1.1531.2713a.3472.3472 0 00.4171-.416l-.2713-1.1542c.0628-.0749.1255-.1508.1863-.2278l1.1845.0415a.3442.3442 0 00.328-.49l-.49-1.076c.0475-.0872.0951-.1742.1407-.2623l1.1662-.1893a.3483.3483 0 00.2258-.5447l-.6904-.9587.087-.2855 1.1066-.414a.3462.3462 0 00.1154-.5781l-.8656-.8079c.0101-.0972.0202-.1954.0283-.2936l1.0073-.6236a.3442.3442 0 000-.5892zm-6.7413 8.3551a.7138.7138 0 01.2986-1.396.714.714 0 11-.2997 1.396zm-.3422-2.3142a.649.649 0 00-.7715.5l-.3573 1.6685c-1.1035.501-2.3285.7795-3.6193.7795a8.7368 8.7368 0 01-3.6951-.814l-.3574-1.6684a.648.648 0 00-.7714-.499l-1.473.3158a8.7216 8.7216 0 01-.7613-.898h7.1676c.081 0 .1356-.0141.1356-.088v-2.536c0-.074-.0536-.0881-.1356-.0881h-2.0966v-1.6077h2.2677c.2065 0 1.1065.0587 1.394 1.2088.0901.3533.2875 1.5044.4232 1.8729.1346.413.6833 1.2381 1.2685 1.2381h3.5716a.7492.7492 0 00.1296-.0131 8.7874 8.7874 0 01-.8119.9526zM6.8369 20.024a.714.714 0 11-.2997-1.396.714.714 0 01.2997 1.396zM4.1177 8.9972a.7137.7137 0 11-1.304.5791.7137.7137 0 011.304-.579zm-.8352 1.9813l1.5347-.6824a.65.65 0 00.33-.8585l-.3158-.7147h1.2432v5.6025H3.5669a8.7753 8.7753 0 01-.2834-3.348zm6.7343-.5437V8.7836h2.9601c.153 0 1.0792.1772 1.0792.8697 0 .575-.7107.7815-1.2948.7815zm10.7574 1.4862c0 .2187-.008.4363-.0243.651h-.9c-.09 0-.1265.0586-.1265.1477v.413c0 .973-.5487 1.1846-1.0296 1.2382-.4576.0517-.9648-.1913-1.0275-.4717-.2704-1.5186-.7198-1.8436-1.4305-2.4034.8817-.5599 1.799-1.386 1.799-2.4915 0-1.1936-.819-1.9458-1.3769-2.3153-.7825-.5163-1.6491-.6195-1.883-.6195H5.4682a8.7651 8.7651 0 014.907-2.7699l1.0974 1.151a.648.648 0 00.9182.0213l1.227-1.1743a8.7753 8.7753 0 016.0044 4.2762l-.8403 1.8982a.652.652 0 00.33.8585l1.6178.7188c.0283.2875.0425.577.0425.8717zm-9.3006-9.5993a.7128.7128 0 11.984 1.0316.7137.7137 0 01-.984-1.0316zm8.3389 6.71a.7107.7107 0 01.9395-.3625.7137.7137 0 11-.9405.3635z`,
+ go: `M1.811 10.231c-.047 0-.058-.023-.035-.059l.246-.315c.023-.035.081-.058.128-.058h4.172c.046 0 .058.035.035.07l-.199.303c-.023.036-.082.07-.117.07zM.047 11.306c-.047 0-.059-.023-.035-.058l.245-.316c.023-.035.082-.058.129-.058h5.328c.047 0 .07.035.058.07l-.093.28c-.012.047-.058.07-.105.07zm2.828 1.075c-.047 0-.059-.035-.035-.07l.163-.292c.023-.035.07-.07.117-.07h2.337c.047 0 .07.035.07.082l-.023.28c0 .047-.047.082-.082.082zm12.129-2.36c-.736.187-1.239.327-1.963.514-.176.046-.187.058-.34-.117-.174-.199-.303-.327-.548-.444-.737-.362-1.45-.257-2.115.175-.795.514-1.204 1.274-1.192 2.22.011.935.654 1.706 1.577 1.835.795.105 1.46-.175 1.987-.77.105-.13.198-.27.315-.434H10.47c-.245 0-.304-.152-.222-.35.152-.362.432-.97.596-1.274a.315.315 0 01.292-.187h4.253c-.023.316-.023.631-.07.947a4.983 4.983 0 01-.958 2.29c-.841 1.11-1.94 1.8-3.33 1.986-1.145.152-2.209-.07-3.143-.77-.865-.655-1.356-1.52-1.484-2.595-.152-1.274.222-2.419.993-3.424.83-1.086 1.928-1.776 3.272-2.02 1.098-.2 2.15-.07 3.096.571.62.41 1.063.97 1.356 1.648.07.105.023.164-.117.2m3.868 6.461c-1.064-.024-2.034-.328-2.852-1.029a3.665 3.665 0 01-1.262-2.255c-.21-1.32.152-2.489.947-3.529.853-1.122 1.881-1.706 3.272-1.95 1.192-.21 2.314-.095 3.33.595.923.63 1.496 1.484 1.648 2.605.198 1.578-.257 2.863-1.344 3.962-.771.783-1.718 1.273-2.805 1.495-.315.06-.63.07-.934.106zm2.78-4.72c-.011-.153-.011-.27-.034-.387-.21-1.157-1.274-1.81-2.384-1.554-1.087.245-1.788.935-2.045 2.033-.21.912.234 1.835 1.075 2.21.643.28 1.285.244 1.905-.07.923-.48 1.425-1.228 1.484-2.233z`,
+ openjdk: `M11.915 0 11.7.215C9.515 2.4 7.47 6.39 6.046 10.483c-1.064 1.024-3.633 2.81-3.711 3.551-.093.87 1.746 2.611 1.55 3.235-.198.625-1.304 1.408-1.014 1.939.1.188.823.011 1.277-.491a13.389 13.389 0 0 0-.017 2.14c.076.906.27 1.668.643 2.232.372.563.956.911 1.667.911.397 0 .727-.114 1.024-.264.298-.149.571-.33.91-.5.68-.34 1.634-.666 3.53-.604 1.903.062 2.872.39 3.559.704.687.314 1.15.664 1.925.664.767 0 1.395-.336 1.807-.9.412-.563.631-1.33.72-2.24.06-.623.055-1.32 0-2.066.454.45 1.117.604 1.213.424.29-.53-.816-1.314-1.013-1.937-.198-.624 1.642-2.366 1.549-3.236-.08-.748-2.707-2.568-3.748-3.586C16.428 6.374 14.308 2.394 12.13.215zm.175 6.038a2.95 2.95 0 0 1 2.943 2.942 2.95 2.95 0 0 1-2.943 2.943A2.95 2.95 0 0 1 9.148 8.98a2.95 2.95 0 0 1 2.942-2.942zM8.685 7.983a3.515 3.515 0 0 0-.145.997c0 1.951 1.6 3.55 3.55 3.55 1.95 0 3.55-1.598 3.55-3.55 0-.329-.046-.648-.132-.951.334.095.64.208.915.336a42.699 42.699 0 0 1 2.042 5.829c.678 2.545 1.01 4.92.846 6.607-.082.844-.29 1.51-.606 1.94-.315.431-.713.651-1.315.651-.593 0-.932-.27-1.673-.61-.741-.338-1.825-.694-3.792-.758-1.974-.064-3.073.293-3.821.669-.375.188-.659.373-.911.5s-.466.2-.752.2c-.53 0-.876-.209-1.16-.64-.285-.43-.474-1.101-.545-1.948-.141-1.693.176-4.069.823-6.614a43.155 43.155 0 0 1 1.934-5.783c.348-.167.749-.31 1.192-.425zm-3.382 4.362a.216.216 0 0 1 .13.031c-.166.56-.323 1.116-.463 1.665a33.849 33.849 0 0 0-.547 2.555 3.9 3.9 0 0 0-.2-.39c-.58-1.012-.914-1.642-1.16-2.08.315-.24 1.679-1.755 2.24-1.781zm13.394.01c.562.027 1.926 1.543 2.24 1.783-.246.438-.58 1.068-1.16 2.08a4.428 4.428 0 0 0-.163.309 32.354 32.354 0 0 0-.562-2.49 40.579 40.579 0 0 0-.482-1.652.216.216 0 0 1 .127-.03z`,
+ ruby: `M20.156.083c3.033.525 3.893 2.598 3.829 4.77L24 4.822 22.635 22.71 4.89 23.926h.016C3.433 23.864.15 23.729 0 19.139l1.645-3 2.819 6.586.503 1.172 2.805-9.144-.03.007.016-.03 9.255 2.956-1.396-5.431-.99-3.9 8.82-.569-.615-.51L16.5 2.114 20.159.073l-.003.01zM0 19.089zM5.13 5.073c3.561-3.533 8.157-5.621 9.922-3.84 1.762 1.777-.105 6.105-3.673 9.636-3.563 3.532-8.103 5.734-9.864 3.957-1.766-1.777.045-6.217 3.612-9.75l.003-.003z`,
+ c: `M16.5921 9.1962s-.354-3.298-3.627-3.39c-3.2741-.09-4.9552 2.474-4.9552 6.14 0 3.6651 1.858 6.5972 5.0451 6.5972 3.184 0 3.5381-3.665 3.5381-3.665l6.1041.365s.36 3.31-2.196 5.836c-2.552 2.5241-5.6901 2.9371-7.8762 2.9201-2.19-.017-5.2261.034-8.1602-2.97-2.938-3.0101-3.436-5.9302-3.436-8.8002 0-2.8701.556-6.6702 4.047-9.5502C7.444.72 9.849 0 12.254 0c10.0422 0 10.7172 9.2602 10.7172 9.2602z`,
+ cplusplus: `M22.394 6c-.167-.29-.398-.543-.652-.69L12.926.22c-.509-.294-1.34-.294-1.848 0L2.26 5.31c-.508.293-.923 1.013-.923 1.6v10.18c0 .294.104.62.271.91.167.29.398.543.652.69l8.816 5.09c.508.293 1.34.293 1.848 0l8.816-5.09c.254-.147.485-.4.652-.69.167-.29.27-.616.27-.91V6.91c.003-.294-.1-.62-.268-.91zM12 19.11c-3.92 0-7.109-3.19-7.109-7.11 0-3.92 3.19-7.11 7.11-7.11a7.133 7.133 0 016.156 3.553l-3.076 1.78a3.567 3.567 0 00-3.08-1.78A3.56 3.56 0 008.444 12 3.56 3.56 0 0012 15.555a3.57 3.57 0 003.08-1.778l3.078 1.78A7.135 7.135 0 0112 19.11zm7.11-6.715h-.79v.79h-.79v-.79h-.79v-.79h.79v-.79h.79v.79h.79zm2.962 0h-.79v.79h-.79v-.79h-.79v-.79h.79v-.79h.79v.79h.79z`,
+ dotnet: `M24 8.77h-2.468v7.565h-1.425V8.77h-2.462V7.53H24zm-6.852 7.565h-4.821V7.53h4.63v1.24h-3.205v2.494h2.953v1.234h-2.953v2.604h3.396zm-6.708 0H8.882L4.78 9.863a2.896 2.896 0 0 1-.258-.51h-.036c.032.189.048.592.048 1.21v5.772H3.157V7.53h1.659l3.965 6.32c.167.261.275.442.323.54h.024c-.04-.233-.06-.629-.06-1.185V7.529h1.372zm-8.703-.693a.868.829 0 0 1-.869.829.868.829 0 0 1-.868-.83.868.829 0 0 1 .868-.828.868.829 0 0 1 .869.829Z`,
+ html5: `M1.5 0h21l-1.91 21.563L11.977 24l-8.564-2.438L1.5 0zm7.031 9.75l-.232-2.718 10.059.003.23-2.622L5.412 4.41l.698 8.01h9.126l-.326 3.426-2.91.804-2.955-.81-.188-2.11H6.248l.33 4.171L12 19.351l5.379-1.443.744-8.157H8.531z`,
+ css: `M0 0v20.16A3.84 3.84 0 0 0 3.84 24h16.32A3.84 3.84 0 0 0 24 20.16V3.84A3.84 3.84 0 0 0 20.16 0Zm14.256 13.08c1.56 0 2.28 1.08 2.304 2.64h-1.608c.024-.288-.048-.6-.144-.84-.096-.192-.288-.264-.552-.264-.456 0-.696.264-.696.84-.024.576.288.888.768 1.08.72.288 1.608.744 1.92 1.296q.432.648.432 1.656c0 1.608-.912 2.592-2.496 2.592-1.656 0-2.4-1.032-2.424-2.688h1.68c0 .792.264 1.176.792 1.176.264 0 .456-.072.552-.24.192-.312.24-1.176-.048-1.512-.312-.408-.912-.6-1.32-.816q-.828-.396-1.224-.936c-.24-.36-.36-.888-.36-1.536 0-1.44.936-2.472 2.424-2.448m5.4 0c1.584 0 2.304 1.08 2.328 2.64h-1.608c0-.288-.048-.6-.168-.84-.096-.192-.264-.264-.528-.264-.48 0-.72.264-.72.84s.288.888.792 1.08c.696.288 1.608.744 1.92 1.296.264.432.408.984.408 1.656.024 1.608-.888 2.592-2.472 2.592-1.68 0-2.424-1.056-2.448-2.688h1.68c0 .744.264 1.176.792 1.176.264 0 .456-.072.552-.24.216-.312.264-1.176-.048-1.512-.288-.408-.888-.6-1.32-.816-.552-.264-.96-.576-1.2-.936s-.36-.888-.36-1.536c-.024-1.44.912-2.472 2.4-2.448m-11.031.018c.711-.006 1.419.198 1.839.63.432.432.672 1.128.648 1.992H9.336c.024-.456-.096-.792-.432-.96-.312-.144-.768-.048-.888.24-.12.264-.192.576-.168.864v3.504c0 .744.264 1.128.768 1.128a.65.65 0 0 0 .552-.264c.168-.24.192-.552.168-.84h1.776c.096 1.632-.984 2.712-2.568 2.688-1.536 0-2.496-.864-2.472-2.472v-4.032c0-.816.24-1.44.696-1.848.432-.408 1.146-.624 1.857-.63`,
+ php: `M7.01 10.207h-.944l-.515 2.648h.838c.556 0 .97-.105 1.242-.314.272-.21.455-.559.55-1.049.092-.47.05-.802-.124-.995-.175-.193-.523-.29-1.047-.29zM12 5.688C5.373 5.688 0 8.514 0 12s5.373 6.313 12 6.313S24 15.486 24 12c0-3.486-5.373-6.312-12-6.312zm-3.26 7.451c-.261.25-.575.438-.917.551-.336.108-.765.164-1.285.164H5.357l-.327 1.681H3.652l1.23-6.326h2.65c.797 0 1.378.209 1.744.628.366.418.476 1.002.33 1.752a2.836 2.836 0 0 1-.305.847c-.143.255-.33.49-.561.703zm4.024.715l.543-2.799c.063-.318.039-.536-.068-.651-.107-.116-.336-.174-.687-.174H11.46l-.704 3.625H9.388l1.23-6.327h1.367l-.327 1.682h1.218c.767 0 1.295.134 1.586.401s.378.7.263 1.299l-.572 2.944h-1.389zm7.597-2.265a2.782 2.782 0 0 1-.305.847c-.143.255-.33.49-.561.703a2.44 2.44 0 0 1-.917.551c-.336.108-.765.164-1.286.164h-1.18l-.327 1.682h-1.378l1.23-6.326h2.649c.797 0 1.378.209 1.744.628.366.417.477 1.001.331 1.751zM17.766 10.207h-.943l-.516 2.648h.838c.557 0 .971-.105 1.242-.314.272-.21.455-.559.551-1.049.092-.47.049-.802-.125-.995s-.524-.29-1.047-.29z`,
+ swift: `M7.508 0c-.287 0-.573 0-.86.002-.241.002-.483.003-.724.01-.132.003-.263.009-.395.015A9.154 9.154 0 0 0 4.348.15 5.492 5.492 0 0 0 2.85.645 5.04 5.04 0 0 0 .645 2.848c-.245.48-.4.972-.495 1.5-.093.52-.122 1.05-.136 1.576a35.2 35.2 0 0 0-.012.724C0 6.935 0 7.221 0 7.508v8.984c0 .287 0 .575.002.862.002.24.005.481.012.722.014.526.043 1.057.136 1.576.095.528.25 1.02.495 1.5a5.03 5.03 0 0 0 2.205 2.203c.48.244.97.4 1.498.495.52.093 1.05.124 1.576.138.241.007.483.009.724.01.287.002.573.002.86.002h8.984c.287 0 .573 0 .86-.002.241-.001.483-.003.724-.01a10.523 10.523 0 0 0 1.578-.138 5.322 5.322 0 0 0 1.498-.495 5.035 5.035 0 0 0 2.203-2.203c.245-.48.4-.972.495-1.5.093-.52.124-1.05.138-1.576.007-.241.009-.481.01-.722.002-.287.002-.575.002-.862V7.508c0-.287 0-.573-.002-.86a33.662 33.662 0 0 0-.01-.724 10.5 10.5 0 0 0-.138-1.576 5.328 5.328 0 0 0-.495-1.5A5.039 5.039 0 0 0 21.152.645 5.32 5.32 0 0 0 19.654.15a10.493 10.493 0 0 0-1.578-.138 34.98 34.98 0 0 0-.722-.01C17.067 0 16.779 0 16.492 0H7.508zm6.035 3.41c4.114 2.47 6.545 7.162 5.549 11.131-.024.093-.05.181-.076.272l.002.001c2.062 2.538 1.5 5.258 1.236 4.745-1.072-2.086-3.066-1.568-4.088-1.043a6.803 6.803 0 0 1-.281.158l-.02.012-.002.002c-2.115 1.123-4.957 1.205-7.812-.022a12.568 12.568 0 0 1-5.64-4.838c.649.48 1.35.902 2.097 1.252 3.019 1.414 6.051 1.311 8.197-.002C9.651 12.73 7.101 9.67 5.146 7.191a10.628 10.628 0 0 1-1.005-1.384c2.34 2.142 6.038 4.83 7.365 5.576C8.69 8.408 6.208 4.743 6.324 4.86c4.436 4.47 8.528 6.996 8.528 6.996.154.085.27.154.36.213.085-.215.16-.437.224-.668.708-2.588-.09-5.548-1.893-7.992z`,
+ kotlin: `M24 24H0V0h24L12 12Z`,
+ gnubash: `M21.038,4.9l-7.577-4.498C13.009,0.134,12.505,0,12,0c-0.505,0-1.009,0.134-1.462,0.403L2.961,4.9 C2.057,5.437,1.5,6.429,1.5,7.503v8.995c0,1.073,0.557,2.066,1.462,2.603l7.577,4.497C10.991,23.866,11.495,24,12,24 c0.505,0,1.009-0.134,1.461-0.402l7.577-4.497c0.904-0.537,1.462-1.529,1.462-2.603V7.503C22.5,6.429,21.943,5.437,21.038,4.9z M15.17,18.946l0.013,0.646c0.001,0.078-0.05,0.167-0.111,0.198l-0.383,0.22c-0.061,0.031-0.111-0.007-0.112-0.085L14.57,19.29 c-0.328,0.136-0.66,0.169-0.872,0.084c-0.04-0.016-0.057-0.075-0.041-0.142l0.139-0.584c0.011-0.046,0.036-0.092,0.069-0.121 c0.012-0.011,0.024-0.02,0.036-0.026c0.022-0.011,0.043-0.014,0.062-0.006c0.229,0.077,0.521,0.041,0.802-0.101 c0.357-0.181,0.596-0.545,0.592-0.907c-0.003-0.328-0.181-0.465-0.613-0.468c-0.55,0.001-1.064-0.107-1.072-0.917 c-0.007-0.667,0.34-1.361,0.889-1.8l-0.007-0.652c-0.001-0.08,0.048-0.168,0.111-0.2l0.37-0.236 c0.061-0.031,0.111,0.007,0.112,0.087l0.006,0.653c0.273-0.109,0.511-0.138,0.726-0.088c0.047,0.012,0.067,0.076,0.048,0.151 l-0.144,0.578c-0.011,0.044-0.036,0.088-0.065,0.116c-0.012,0.012-0.025,0.021-0.038,0.028c-0.019,0.01-0.038,0.013-0.057,0.009 c-0.098-0.022-0.332-0.073-0.699,0.113c-0.385,0.195-0.52,0.53-0.517,0.778c0.003,0.297,0.155,0.387,0.681,0.396 c0.7,0.012,1.003,0.318,1.01,1.023C16.105,17.747,15.736,18.491,15.17,18.946z M19.143,17.859c0,0.06-0.008,0.116-0.058,0.145 l-1.916,1.164c-0.05,0.029-0.09,0.004-0.09-0.056v-0.494c0-0.06,0.037-0.093,0.087-0.122l1.887-1.129 c0.05-0.029,0.09-0.004,0.09,0.056V17.859z M20.459,6.797l-7.168,4.427c-0.894,0.523-1.553,1.109-1.553,2.187v8.833 c0,0.645,0.26,1.063,0.66,1.184c-0.131,0.023-0.264,0.039-0.398,0.039c-0.42,0-0.833-0.114-1.197-0.33L3.226,18.64 c-0.741-0.44-1.201-1.261-1.201-2.142V7.503c0-0.881,0.46-1.702,1.201-2.142l7.577-4.498c0.363-0.216,0.777-0.33,1.197-0.33 c0.419,0,0.833,0.114,1.197,0.33l7.577,4.498c0.624,0.371,1.046,1.013,1.164,1.732C21.686,6.557,21.12,6.411,20.459,6.797z`,
+ json: `M12.043 23.968c.479-.004.953-.029 1.426-.094a11.805 11.805 0 003.146-.863 12.404 12.404 0 003.793-2.542 11.977 11.977 0 002.44-3.427 11.794 11.794 0 001.02-3.476c.149-1.16.135-2.346-.045-3.499a11.96 11.96 0 00-.793-2.788 11.197 11.197 0 00-.854-1.617c-1.168-1.837-2.861-3.314-4.81-4.3a12.835 12.835 0 00-2.172-.87h-.005c.119.063.24.132.345.201.12.074.239.146.351.225a8.93 8.93 0 011.559 1.33c1.063 1.145 1.797 2.548 2.218 4.041.284.982.434 1.998.495 3.017.044.743.044 1.491-.047 2.229-.149 1.27-.554 2.51-1.228 3.596a7.475 7.475 0 01-1.903 2.084c-1.244.928-2.877 1.482-4.436 1.114a3.916 3.916 0 01-.748-.258 4.692 4.692 0 01-.779-.45 6.08 6.08 0 01-1.244-1.105 6.507 6.507 0 01-1.049-1.747 7.366 7.366 0 01-.494-2.54c-.03-1.273.225-2.553.854-3.67a6.43 6.43 0 011.663-1.918c.225-.178.464-.333.704-.479l.016-.007a5.121 5.121 0 00-1.441-.12 4.963 4.963 0 00-1.228.24c-.359.12-.704.27-1.019.45a6.146 6.146 0 00-.733.494c-.211.18-.42.36-.615.555-1.123 1.153-1.768 2.682-2.022 4.256-.15.973-.15 1.96-.091 2.95.105 1.395.391 2.787.945 4.062a8.518 8.518 0 001.348 2.173 8.14 8.14 0 003.132 2.23 7.934 7.934 0 002.113.54c.074.015.149.015.209.015zm-2.934-.398a4.102 4.102 0 01-.45-.228 8.5 8.5 0 01-2.038-1.534c-1.094-1.137-1.827-2.566-2.247-4.08a15.184 15.184 0 01-.495-3.172 12.14 12.14 0 01.046-2.082c.135-1.257.495-2.501 1.124-3.58a6.889 6.889 0 011.783-2.053 6.23 6.23 0 011.633-.9 5.363 5.363 0 013.522-.045c.029 0 .029 0 .045.03.015.015.045.015.06.03.045.016.104.045.165.074.239.12.479.271.704.42a6.294 6.294 0 012.097 2.502c.42.914.615 1.934.631 2.938.014 1.079-.18 2.157-.645 3.146a6.42 6.42 0 01-2.638 2.832c.09.03.18.045.271.075.225.044.449.074.688.074 1.468.045 2.892-.66 3.94-1.647.195-.18.375-.375.54-.585.225-.27.435-.54.614-.823.239-.375.435-.75.614-1.154a8.112 8.112 0 00.509-1.664c.196-1.004.211-2.022.149-3.026-.135-2.022-.673-4.045-1.842-5.724a9.054 9.054 0 00-.555-.719 9.868 9.868 0 00-1.063-1.034 8.477 8.477 0 00-1.363-.915 9.927 9.927 0 00-1.692-.598l-.3-.06c-.209-.03-.42-.044-.634-.06a8.453 8.453 0 00-1.015.016c-.704.045-1.412.16-2.112.337C5.799 1.227 2.863 3.566 1.3 6.67A11.834 11.834 0 00.238 9.801a11.81 11.81 0 00-.104 3.775c.12 1.02.374 2.023.778 2.977.227.57.511 1.124.825 1.648 1.094 1.783 2.683 3.236 4.51 4.24.688.39 1.408.69 2.157.944.226.074.45.15.689.21z`,
+ r: `M12 2.746c-6.627 0-12 3.599-12 8.037 0 3.897 4.144 7.144 9.64 7.88V16.26c-2.924-.915-4.925-2.755-4.925-4.877 0-3.035 4.084-5.494 9.12-5.494 5.038 0 8.757 1.683 8.757 5.494 0 1.976-.999 3.379-2.662 4.272.09.066.174.128.258.216.169.149.25.363.372.544 2.128-1.45 3.44-3.437 3.44-5.631 0-4.44-5.373-8.038-12-8.038zm-2.111 4.99v13.516l4.093-.002-.002-5.291h1.1c.225 0 .321.066.549.25.272.22.715.982.715.982l2.164 4.063 4.627-.002-2.864-4.826s-.086-.193-.265-.383a2.22 2.22 0 00-.582-.416c-.422-.214-1.149-.434-1.149-.434s3.578-.264 3.578-3.826c0-3.562-3.744-3.63-3.744-3.63zm4.127 2.93l2.478.002s1.149-.062 1.149 1.127c0 1.165-1.149 1.17-1.149 1.17h-2.478zm1.754 6.119c-.494.049-1.012.079-1.54.088v1.807a16.622 16.622 0 002.37-.473l-.471-.891s-.108-.183-.248-.394c-.039-.054-.08-.098-.111-.137z`,
+ dart: `M4.105 4.105S9.158 1.58 11.684.316a3.079 3.079 0 0 1 1.481-.315c.766.047 1.677.788 1.677.788L24 9.948v9.789h-4.263V24H9.789l-9-9C.303 14.5 0 13.795 0 13.105c0-.319.18-.818.316-1.105l3.789-7.895zm.679.679v11.787c.002.543.021 1.024.498 1.508L10.204 23h8.533v-4.263L4.784 4.784zm12.055-.678c-.899-.896-1.809-1.78-2.74-2.643-.302-.267-.567-.468-1.07-.462-.37.014-.87.195-.87.195L6.341 4.105l10.498.001z`,
+ lua: `M.38 10.377l-.272-.037c-.048.344-.082.695-.101 1.041l.275.016c.018-.34.051-.682.098-1.02zM4.136 3.289l-.184-.205c-.258.232-.509.48-.746.734l.202.188c.231-.248.476-.49.728-.717zM5.769 2.059l-.146-.235c-.296.186-.586.385-.863.594l.166.219c.27-.203.554-.399.843-.578zM1.824 18.369c.185.297.384.586.593.863l.22-.164c-.205-.271-.399-.555-.58-.844l-.233.145zM1.127 16.402l-.255.104c.129.318.274.635.431.943l.005.01.245-.125-.005-.01c-.153-.301-.295-.611-.421-.922zM.298 9.309l.269.063c.076-.332.168-.664.272-.986l-.261-.087c-.108.332-.202.672-.28 1.01zM.274 12.42l-.275.01c.012.348.04.699.083 1.043l.273-.033c-.042-.336-.069-.68-.081-1.02zM.256 14.506c.073.34.162.682.264 1.014l.263-.08c-.1-.326-.187-.658-.258-.99l-.269.056zM11.573.275L11.563 0c-.348.012-.699.039-1.044.082l.034.273c.338-.041.68-.068 1.02-.08zM23.221 8.566c.1.326.186.66.256.992l.27-.059c-.072-.34-.16-.682-.262-1.014l-.264.081zM17.621 1.389c-.309-.164-.627-.314-.947-.449l-.107.252c.314.133.625.281.926.439l.128-.242zM15.693.572c-.332-.105-.67-.199-1.01-.277l-.063.268c.332.076.664.168.988.273l.085-.264zM6.674 1.545c.298-.15.606-.291.916-.418L7.486.873c-.317.127-.632.272-.937.428l-.015.008.125.244.015-.008zM23.727 11.588l.275-.01a11.797 11.797 0 0 0-.082-1.045l-.273.033c.041.338.068.682.08 1.022zM13.654.105c-.346-.047-.696-.08-1.043-.098l-.014.273c.339.018.683.051 1.019.098l.038-.273zM9.544.527l-.058-.27c-.34.072-.681.16-1.014.264l.081.262c.325-.099.659-.185.991-.256zM1.921 5.469l.231.15c.185-.285.384-.566.592-.834l-.217-.17c-.213.276-.417.563-.606.854zM.943 7.318l.253.107c.132-.313.28-.625.439-.924l-.243-.128c-.163.307-.314.625-.449.945zM18.223 21.943l.145.234c.295-.186.586-.385.863-.594l-.164-.219c-.272.204-.557.4-.844.579zM21.248 19.219l.217.17c.215-.273.418-.561.607-.854l-.23-.148c-.186.285-.385.564-.594.832zM19.855 20.715l.184.203c.258-.23.51-.479.746-.732l-.201-.188c-.23.248-.477.488-.729.717zM22.359 17.504l.244.129c.162-.307.314-.625.449-.945l-.254-.107a11.27 11.27 0 0 1-.439.923zM23.617 13.629l.273.039c.049-.346.082-.695.102-1.043l-.275-.014c-.018.338-.051.682-.1 1.018zM23.156 15.621l.264.086c.107-.332.201-.67.279-1.01l-.268-.063c-.077.333-.169.665-.275.987zM22.453 6.672c.154.303.297.617.424.932l.256-.104c-.131-.322-.277-.643-.436-.953l-.244.125zM8.296 23.418c.331.107.67.201 1.009.279l.062-.268c-.331-.076-.663-.168-.986-.273l-.085.262zM10.335 23.889c.345.049.696.082 1.043.102l.014-.275c-.339-.018-.682-.051-1.019-.098l-.038.271zM17.326 22.449c-.303.154-.613.297-.926.424l.104.256c.318-.131.639-.275.947-.434l.004-.002-.123-.246-.006.002zM4.613 21.467c.274.213.562.418.854.605l.149-.23c-.285-.184-.565-.385-.833-.592l-.17.217zM12.417 23.725l.009.275c.348-.014.699-.041 1.045-.084l-.035-.271c-.336.041-.68.068-1.019.08zM6.37 22.604c.307.162.625.314.946.449l.107-.254c-.313-.133-.624-.279-.924-.439l-.129.244zM3.083 20.041c.233.258.48.51.734.746l.188-.201c-.249-.23-.49-.477-.717-.729l-.205.184zM14.445 23.475l.059.27c.34-.074.68-.162 1.014-.266l-.082-.262c-.325.099-.659.185-.991.258zM21.18.129A2.689 2.689 0 1 0 21.18 5.507 2.689 2.689 0 1 0 21.18.129zM15.324 15.447c0 .471.314.66.852.66.67 0 1.297-.396 1.297-1.016v-.645c-.23.107-.379.141-1.107.24-.735.109-1.042.306-1.042.761zM12 2.818c-5.07 0-9.18 4.109-9.18 9.18 0 5.068 4.11 9.18 9.18 9.18 5.07 0 9.18-4.111 9.18-9.18 0-5.07-4.11-9.18-9.18-9.18zm-2.487 13.77H5.771v-6.023h.769v5.346h2.974v.677zm4.13 0h-.619v-.67c-.405.57-.811.793-1.446.793-.843 0-1.38-.463-1.38-1.182v-3.271h.686v3c0 .52.347.85.893.85.719 0 1.181-.578 1.181-1.461v-2.389h.686v4.33zm-.53-8.393c0-1.484 1.205-2.689 2.689-2.689s2.688 1.205 2.688 2.689-1.203 2.688-2.688 2.688-2.689-1.203-2.689-2.688zm5.567 7.856v.52c-.223.059-.33.074-.471.074-.34 0-.637-.238-.711-.57-.381.406-.918.637-1.471.637-.877 0-1.422-.463-1.422-1.248 0-.527.256-.916.76-1.123.266-.107.414-.141 1.389-.264.545-.066.719-.191.719-.48v-.182c0-.412-.348-.645-.967-.645-.645 0-.957.24-1.016.77h-.693c.041-1 .686-1.404 1.734-1.404 1.066 0 1.627.412 1.627 1.182v2.412c0 .215.133.338.373.338.041-.002.074-.002.149-.017z`,
+ elixir: `M19.793 16.575c0 3.752-2.927 7.426-7.743 7.426-5.249 0-7.843-3.71-7.843-8.29 0-5.21 3.892-12.952 8-15.647a.397.397 0 0 1 .61.371 9.716 9.716 0 0 0 1.694 6.518c.522.795 1.092 1.478 1.763 2.352.94 1.227 1.637 1.906 2.644 3.842l.015.028a7.107 7.107 0 0 1 .86 3.4z`,
+ haskell: `M0 3.535L5.647 12 0 20.465h4.235L9.883 12 4.235 3.535zm5.647 0L11.294 12l-5.647 8.465h4.235l3.53-5.29 3.53 5.29h4.234L9.883 3.535zm8.941 4.938l1.883 2.822H24V8.473zm2.824 4.232l1.882 2.822H24v-2.822z`,
+ scala: `M4.589 24c4.537 0 13.81-1.516 14.821-3v-5.729c-.957 1.408-10.284 2.912-14.821 2.912V24zM4.589 16.365c4.537 0 13.81-1.516 14.821-3V7.636c-.957 1.408-10.284 2.912-14.821 2.912v5.817zM4.589 8.729c4.537 0 13.81-1.516 14.821-3V0C18.453 1.408 9.126 2.912 4.589 2.912v5.817z`,
+ perl: `M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0m.157 1.103a10.91 10.91 0 0 1 9.214 5.404c-1.962.152-3.156 1.698-5.132 3.553-2.81 2.637-4.562.582-5.288-.898-.447-1.004-.847-2.117-1.544-2.769A.4.4 0 0 1 9.3 6.02l.08-.37a.083.083 0 0 0-.074-.1c-.33-.022-.601.093-.84.368a2.5 2.5 0 0 0-.375-.064c-.863-.093-1.036.345-1.873.345H5.81c-.758 0-1.391.361-1.7.892-.248.424-.257.884.15.93-.126.445.292.62 1.224.192 0 0 .733.421 1.749.421.549 0 .712.087.914.967.486 2.138 2.404 5.655 6.282 5.655l.118.166c.659.934.86 2.113.48 3.184-.307.867-.697 1.531-.697 1.531q.01.178.01.349c0 .81-.175 1.553-.387 2.23a10.91 10.91 0 0 1-11.989-6.342A10.91 10.91 0 0 1 7.608 2.01a10.9 10.9 0 0 1 4.55-.907M7.524 6.47c.288 0 .575.231.477.272a.4.4 0 0 1-.1.02.38.38 0 0 1-.375.327.384.384 0 0 1-.378-.326.4.4 0 0 1-.101-.02c-.098-.042.19-.273.477-.273m10.193 10.49q.05 0 .101.007.326.054.694.096.135.01.269.026a13.4 13.4 0 0 0 2.846-.007 10.9 10.9 0 0 1-2.007 2.705c-.11-.23-.547-1.19-.573-2.196q-.156-.01-.313-.026-.13-.014-.256-.022a18 18 0 0 1-.735-.102h-.003c-.032 0-.06.01-.074.035l-.003.012q-.081.265-.182.544c.428 1.084.652 2.078.652 2.078.14.22.258.432.363.64a11 11 0 0 1-2.168 1.264 11 11 0 0 1-1.205.426 13.3 13.3 0 0 1 1.055-2.531s.678-1.445 1.027-2.564v-.004a.55.55 0 0 1 .512-.38`,
+ clojure: `M11.503 12.216c-.119.259-.251.549-.387.858-.482 1.092-1.016 2.42-1.21 3.271a4.91 4.91 0 0 0-.112 1.096c0 .164.009.337.022.514.682.25 1.417.388 2.186.39a6.39 6.39 0 0 0 2.001-.326 3.808 3.808 0 0 1-.418-.441c-.854-1.089-1.329-2.682-2.082-5.362M8.355 6.813A6.347 6.347 0 0 0 5.657 12a6.347 6.347 0 0 0 2.625 5.134c.39-1.622 1.366-3.107 2.83-6.084-.087-.239-.186-.5-.297-.775-.406-1.018-.991-2.198-1.513-2.733a4.272 4.272 0 0 0-.947-.729M17.527 19.277c-.84-.105-1.533-.232-2.141-.446A7.625 7.625 0 0 1 4.376 12a7.6 7.6 0 0 1 2.6-5.73 5.582 5.582 0 0 0-1.324-.162c-2.236.02-4.597 1.258-5.58 4.602-.092.486-.07.854-.07 1.29 0 6.627 5.373 12 12 12 4.059 0 7.643-2.017 9.815-5.101-1.174.293-2.305.433-3.271.436-.362 0-.702-.02-1.019-.058M15.273 16.952c.074.036.242.097.475.163a6.354 6.354 0 0 0 2.6-5.115h-.002a6.354 6.354 0 0 0-6.345-6.345 6.338 6.338 0 0 0-1.992.324c1.289 1.468 1.908 3.566 2.507 5.862l.001.003c.001.002.192.637.518 1.48.326.842.789 1.885 1.293 2.645.332.51.697.876.945.983M12.001 0a11.98 11.98 0 0 0-9.752 5.013c1.134-.71 2.291-.967 3.301-.957 1.394.004 2.491.436 3.017.732.127.073.248.152.366.233A7.625 7.625 0 0 1 19.625 12a7.605 7.605 0 0 1-2.268 5.425c.344.038.709.063 1.084.061 1.328 0 2.766-.293 3.842-1.198.703-.592 1.291-1.458 1.617-2.757.065-.502.1-1.012.1-1.531 0-6.627-5.371-12-11.999-12`,
+ julia: `M11.138 17.569a5.569 5.569 0 1 1-11.138 0 5.569 5.569 0 1 1 11.138 0zm6.431-11.138a5.569 5.569 0 1 1-11.138 0 5.569 5.569 0 1 1 11.138 0zM24 17.569a5.569 5.569 0 1 1-11.138 0 5.569 5.569 0 1 1 11.138 0z`,
+ zig: `m23.53 1.02-7.686 3.45h-7.06l-2.98 3.452h7.173L.47 22.98l7.681-3.607h7.065v-.002l2.978-3.45-7.148-.001 12.482-14.9zM0 4.47v14.901h1.883l2.98-3.45H3.451v-8h.942l2.824-3.45H0zm22.117 0-2.98 3.608h1.412v7.844h-.942l-2.98 3.45H24V4.47h-1.883z`,
+ nim: `M12.095 3.2s-.92.778-1.857 1.55c-.964-.032-2.856.199-3.88.598C5.412 4.708 4.582 4 4.582 4s-.709 1.305-1.154 2.07c-.662.377-1.325.8-1.917 1.36C.824 7.14.026 6.782 0 6.77c.911 1.967 1.524 3.936 3.19 5.12 2.654-4.483 14.983-4.07 17.691-.025 1.75-.977 2.43-3.078 3.119-5.018-.075.026-1.012.362-1.619.61-.363-.423-1.217-1.072-1.702-1.385a96.008 96.008 0 00-1.131-2.122s-.794.632-1.715 1.322c-1.243-.246-2.747-.544-4.012-.47A52.988 52.988 0 0112.095 3.2zM.942 10.95l2.189 5.67c3.801 5.367 13.508 5.74 17.74.105 1.001-2.415 2.352-5.808 2.352-5.808-1.086 1.72-2.852 2.909-3.94 3.549-.774.453-2.558.727-2.558.727l-4.684-2.597-4.71 2.545s-1.761-.303-2.558-.701c-1.608-.92-2.69-2.004-3.83-3.49z`,
+ fortran: `M19.536 0H4.464A4.463 4.463 0 0 0 0 4.464v15.073A4.463 4.463 0 0 0 4.464 24h15.073A4.463 4.463 0 0 0 24 19.536V4.464A4.463 4.463 0 0 0 19.536 0zm1.193 6.493v3.871l-.922-.005c-.507-.003-.981-.021-1.052-.041-.128-.036-.131-.05-.192-.839-.079-1.013-.143-1.462-.306-2.136-.352-1.457-1.096-2.25-2.309-2.463-.509-.089-2.731-.176-4.558-.177L10.13 4.7v5.82l.662-.033c.757-.038 1.353-.129 1.64-.252.306-.131.629-.462.781-.799.158-.352.262-.815.345-1.542.033-.286.07-.572.083-.636.024-.116.028-.117 1.036-.117h1.012v9.3h-2.062l-.035-.536c-.063-.971-.252-1.891-.479-2.331-.311-.601-.922-.871-2.151-.95a11.422 11.422 0 0 1-.666-.059l-.172-.027.02 2.926c.021 3.086.03 3.206.265 3.465.241.266.381.284 2.827.368.05.002.065.246.065 1.041v1.039H3.271v-1.039c0-.954.007-1.039.091-1.041.05-.001.543-.023 1.097-.049.891-.042 1.033-.061 1.244-.167a.712.712 0 0 0 .345-.328c.106-.206.107-.254.107-6.78 0-6.133-.006-6.584-.09-6.737a.938.938 0 0 0-.553-.436c-.104-.032-.65-.07-1.215-.086l-1.026-.027V2.622h17.458v3.871z`,
+ erlang: `M8.859 7.889c.154-1.863 1.623-3.115 3.344-3.119 1.734.004 2.986 1.256 3.029 3.119zm12.11 11.707c.802-.86 1.52-1.872 2.172-3.03l-3.616-1.807c-1.27 2.064-3.127 3.965-5.694 3.977-3.738-.012-5.206-3.208-5.198-7.322h13.966c.019-.464.019-.68 0-.904.091-2.447-.558-4.504-1.737-6.106l-.007.005H24v15.186h-3.039zm-17.206-.001C1.901 17.62.811 14.894.813 11.64c-.002-2.877.902-5.35 2.456-7.232H0v15.187h3.761Z`,
+ fsharp: `M0 12 11.39.61v5.695L5.695 12l5.695 5.695v5.695L0 12zm7.322 0 4.068-4.068v8.136L7.322 12zM24 12 12.203.61v5.695L17.898 12l-5.695 5.695v5.695L24 12z`,
+ solidity: `M4.409 6.608L7.981.255l3.572 6.353H4.409zM8.411 0l3.569 6.348L15.552 0H8.411zm4.036 17.392l3.572 6.354 3.575-6.354h-7.147zm-.608-10.284h-7.43l3.715 6.605 3.715-6.605zm.428-.25h7.428L15.982.255l-3.715 6.603zM15.589 24l-3.569-6.349L8.448 24h7.141zm-3.856-6.858H4.306l3.712 6.603 3.715-6.603zm.428-.25h7.433l-3.718-6.605-3.715 6.605z`,
+ coffeescript: `M4.645 7.472c2.1.53 4.779.8 8.008.8 3.299 0 5.918-.27 8.008-.8 2.23-.52 3.299-1.22 3.299-1.88 0-.47-.48-.93-1.35-1.28.2.13.35.35.35.59 0 .67-1.01 1.22-3.039 1.68-1.88.41-4.279.7-7.198.7-2.82 0-5.329-.29-7.138-.68-1.95-.48-2.97-1-2.97-1.68 0-.28.13-.52.52-.8-1.22.47-1.88.87-1.88 1.47.07.68 1.16 1.36 3.39 1.88zm4.689-2.16c2.27-.2 2.929-1.659 5.588-1.899 1.31-.1 2.14.16 2.23.62.08.43-.57.72-1.36.78-1.09.11-1.54-.28-1.63-.65-.81.09-.94.43-.9.67.09.46 1.07.92 2.75.76 1.9-.15 2.54-.9 2.38-1.65-.2-.98-1.66-1.8-4.28-1.55-3.359.3-3.339 1.86-5.628 2.05-.94.09-1.46-.13-1.55-.5-.06-.37.4-.55.94-.59.5-.05 1.11.04 1.4.2.21-.11.28-.22.26-.35-.1-.35-.79-.5-1.66-.44-1.7.15-1.7.91-1.64 1.25.17.87 1.48 1.45 3.1 1.3zm11.417 3.84c-2.1.49-4.779.809-8.008.809-3.3 0-5.989-.34-8.078-.8-1.88-.48-2.88-1.01-3.23-1.56.18 1.23.49 2.42.89 3.55-.48.3-.91.67-1.3 1.17a4.519 4.519 0 00-1.019 3.098 3.6 3.599 0 001.42 2.62c.87.68 1.81.88 2.879.68.41-.07.87-.28 1.29-.42-.88 0-1.62-.28-2.36-.87a3.55 3.549 0 01-1.49-2.42c-.2-.94 0-1.81.53-2.579.12-.15.25-.28.39-.4.3.73.62 1.45.98 2.12.81 1.23 1.62 2.299 2.43 3.459.35.68.58 1.35.74 2.019a3.899 3.899 0 002.229 1.5c1.15.4 2.35.58 3.579.51h.13a10.197 10.197 0 003.689-.52 4.179 4.179 0 002.16-1.49h.07c.13-.67.35-1.34.67-2.02.799-1.17 1.619-2.229 2.419-3.458A20.995 20.993 0 0024 7.612c-.43.6-1.44 1.13-3.25 1.54z`,
+ ocaml: `M12.178 21.637c-.085-.17-.187-.524-.255-.676-.067-.135-.27-.506-.37-.625-.22-.253-.27-.27-.338-.608-.12-.574-.405-1.588-.76-2.296-.187-.372-.49-.677-.761-.947-.236-.236-.777-.624-.878-.607-.895.169-1.166 1.046-1.587 1.739-.237.388-.473.71-.66 1.115-.167.371-.151.793-.439 1.115a2.952 2.952 0 00-.624 1.097c-.034.084-.101.929-.186 1.131l1.318-.084c1.233.085.877.557 2.787.456l3.022-.1a5.376 5.376 0 00-.27-.71zM20.96 1.539H3.023A3.02 3.02 0 000 4.56v6.587c.44-.152 1.047-1.08 1.25-1.3.337-.389.405-.895.574-1.2.389-.709.456-1.215 1.334-1.215.406 0 .575.1.845.473.186.253.523.743.675 1.064.186.371.474.86.609.962.1.068.185.136.27.17.135.05.253-.051.354-.12.118-.1.17-.286.287-.556.17-.39.339-.827.44-.997.169-.27.236-.608.422-.76.27-.236.641-.253.743-.27.557-.118.81.27 1.08.507.186.168.423.49.609.91.135.339.304.661.388.846.068.185.237.49.338.86.101.322.337.575.44.744 0 0 .152.406 1.03.778a7.505 7.505 0 00.81.286c.39.135.76.12 1.233.068.338 0 .524-.49.676-.878.084-.237.185-.895.236-1.081.05-.185-.085-.32.034-.49.135-.186.22-.203.287-.439.17-.523 1.114-.54 1.655-.54.456 0 .389.44 1.149.287.439-.085.86.05 1.318.185.388.102.76.22.98.473.134.17.489.997.134 1.031.033.033.067.118.118.151-.085.322-.422.085-.625.051-.253-.05-.44 0-.693.118-.439.187-1.063.17-1.452.49-.32.271-.32.861-.473 1.2 0 0-.422 1.063-1.317 1.722-.237.17-.692.574-1.672.726-.44.068-.86.068-1.318.05-.22-.016-.438-.016-.658-.016-.136 0-.575-.017-.558.034l-.05.119a.6.6 0 00.033.169c.017.1.017.185.034.27 0 .185-.017.388 0 .574.017.388.17.743.186 1.148.017.44.236.913.456 1.267.085.135.203.152.254.32.067.186 0 .406.033.609.118.794.355 1.638.71 2.364v.017c.439-.067.895-.236 1.47-.32 1.063-.153 2.532-.085 3.478-.17 2.399-.22 3.7.98 5.844.49V4.562a3.045 3.045 0 00-3.04-3.023zm-8.951 14.187c0-.034 0-.034 0 0zm-6.47 2.769c.17-.372.271-.778.406-1.15.135-.354.337-.86.693-1.046-.05-.05-.744-.068-.929-.085a7.406 7.406 0 01-.608-.084 22.976 22.976 0 01-1.15-.236c-.22-.051-.979-.322-1.13-.39-.39-.168-.642-.658-.93-.607-.185.034-.37.101-.49.287-.1.152-.134.423-.202.608-.084.203-.22.405-.32.608-.238.354-.626.676-.795 1.03-.033.085-.05.169-.084.254v4.07c.202.034.405.068.624.135 1.69.456 2.095.49 3.75.304l.152-.017c.118-.27.22-1.165.304-1.435.067-.22.153-.39.187-.591.033-.203 0-.406-.017-.59-.034-.491.354-.661.54-1.065z`,
+ crystal: `M23.964 15.266l-8.687 8.669c-.034.035-.086.052-.121.035L3.29 20.79c-.052-.017-.087-.052-.087-.086L.007 8.856c-.018-.053 0-.087.035-.122L8.728.065c.035-.035.087-.052.121-.035l11.866 3.18c.052.017.087.052.087.086l3.18 11.848c.034.053.016.087-.018.122zm-11.64-9.433L.667 8.943c-.017 0-.035.034-.017.052l8.53 8.512c.017.017.052.017.052-.017l3.127-11.64c.017 0-.018-.035-.035-.017Z`,
+ apachegroovy: `M11.997 6.012S10.315 8.8 9.516 10.155c-.155.058-.172.041-.341.207-.41-.47-.897-.041-1.028.22-.057-.566-.151-.567-.279-.694.074-.496.316-1.305-.241-1.884-1.078-.727-2.326 1.05-3.021 1.982l-.375.622c-1.546-.032-2.763.008-4.231-.021 1.79.67 1.864.686 4.026 1.506 0 .066.161.372.34.552.147.15.308.234.389.284-.106.054-.32.138-.385.258-.292.546.139.672.418 1.107.315.568.382.944 1.126.625.254-.11.562-.148.758-.21-.693 1.094-.87 1.392-2.083 3.274l.012.004c4.85-1.893 4.974-1.942 7.373-2.89 3.448 1.338 3.646 1.448 7.432 2.891-.529-.826-.89-1.343-1.274-1.995.151-.013.483-.046.777-.233.213-.135.463-.288.688-.574.443-.565.551-1.277.39-2.166-.078-.423-.235-.834-.213-.85 2.061-.778 2.304-.862 4.226-1.587-2.31.034-2.422.01-4.591.016-.036-.414-.244-.627-.882-.606-.238.039-.389.12-.5.445-.357-.657-.85-.464-1.06-.14-.275-.282-.917-.377-1.24-.17-.238-.112-.514-.112-.757.177-.175-.146-.23-.188-.614-.342-.886-1.497-1.622-2.692-2.36-3.951zm.012.802c.35.535 1.552 2.61 1.849 3.074-.337.023-.668.202-.918.562-.217-.224-.47-.445-.917-.463-.544-.093-.834.148-1.2.568-.108-.365-.53-.45-.896-.28.327-.519 1.872-3.122 2.082-3.46zM7.45 9.128c-.05 1.434-1.068 2.712-1.798 2.245-.551-.449.149-1.584.59-1.985-.033.307.246.498.023.77-.446.543-.27.936-.078.996.513.162 1.004-1.227 1.004-2.201 0-.625-.366-.613-1.086.136-.983 1.022-1.513 2.012-1.16 2.69.197.38.485.651.959.594.925-.11 1.483-1.254 1.543-1.988.148-.003.109.01.148-.02 0 .129.177.755.317 1.166.183.702.964 2.11-1.369 2.658-.44.11-.614.148-1.05.32-.213-.443-.263-.585-.697-1.013.588-.205.593-.185.972-.317 1.467-.51 1.908-.947 1.857-1.57 0 0 .018-.32-.185-.588a2.613 2.613 0 0 1-.293.645c-.437.68-1.296 1.101-2.06.833-.417-.146-.596-.466-.596-1.015 0-.703 1.601-2.735 2.387-3.08.555-.165.579.293.571.724zm6.502 1.3c.26.006.543.133.735.34.594.64.529 1.417.163 1.905-.435.581-1.532.324-1.791-.488-.12-.378.095-1.312.475-1.624a.628.628 0 0 1 .418-.132zm-2.113.066a.502.502 0 0 1 .117.017c.503.03.61.313.701.56.231.626.173 1.212-.301 1.691-.711.719-1.54.401-1.536-.567.014-.69.443-1.715 1.02-1.7zm1.868.038c-.383.287-.432 1.023-.08 1.296.138.13.215.22.613.256.273.024.704-.253.725-.527.01-.125-.013-.333-.312-.67-.252-.283-.579-.349-.661-.3-.265.156.021.28.125.383.162.163.2.234.125.282a.447.447 0 0 1-.372.057c-.105-.049-.456-.246-.163-.777zm3.759.003c.167.26.215.316.402.965.24.838.546 1.163.816 1.01.74-.418.148-1.476-.113-1.974.167-.002.134.007.286.005.12.471.086.387.407 1.813.385 1.706.442 2.16-.528 2.926-.446.352-1.103.37-1.667.34l-.636-.095c.438-.287.545-.557.542-1.116 1.278.535 1.959.132 2.23-.526.132-.317.086-.735-.04-1.471.008.6-.005.71-.084 1.007-.158.595-.547.76-.812.34-.102-.163-.345-.702-.42-1.282-.075-.58-.132-1.395-.5-1.736.04-.08.082-.17.117-.206zm-1.247.01c.258.068.572.204.74.52.234.436.388.668.376 1.447-.014.832-.34 1.055-.557 1.086-.278.04-.762.034-1.049-1.598-.095-.541-.268-1.056-.45-1.224.09-.11.097-.096.165-.204.091.1.17.27.298.777.202.808.387.975.745 1.02.558.072.778-.78.318-1.391-.1-.134-.365-.307-.503-.236.008.236.113.162.114.318-.026.185-.053.219-.113.32-.142-.056-.21-.078-.334-.291-.157-.31-.055-.6.25-.544zm-4.597.076c-.263.185-.594.8-.304 1.35.143.205.297.372.638.3.245-.051.671-.34.73-.749.052-.35-.456-1.028-.738-.87-.327.183-.128.314.074.511.185.18.052.289-.077.342-.258.106-.403.003-.467-.203-.065-.205-.01-.38.144-.68zm-2.867.064c.056.172.1.402.218.624.028.023.132 0 .269-.157.086-.1.185-.238.357-.463.104.095.113.166.142.219.073.13.225.12.273.106.168-.167.195-.275.306-.29.01.216.021.35-.257.677a.535.535 0 0 1-.501.172c-.12-.034-.199-.108-.389-.205-.258.04-.19.315-.143.546.12.611.5.855.832.675.116-.062.09-.062.312-.153-.038.388-.06.463.01.896-.541.301-.982.25-1.102-.506-.091-.632-.261-1.4-.415-1.556-.145-.147-.205-.195-.205-.195l.293-.39zm-7.114.082c.753.01 1.602.01 2.506.017-.13.318-.175.54-.193.854-.422-.163-1.877-.684-2.313-.871zm20.723.01c-.997.359-1.715.637-2.677 1.004-.105-.45-.124-.588-.219-.994 1.601-.005 1.628-.002 2.896-.01zm-6.978 2.04c.105.43.253.641.253.641.202.348.454.545.84.645.085.136.115.163.148.236.037.457.01.514-.344.774-.209.204-.218.497-.003.769.231.22.474.298 1.375.064.174.3.418.653.776 1.217-1.206-.455-2.868-1.103-6.43-2.49 0 0-4.169 1.62-6.404 2.491.935-1.474 1.012-1.599 1.677-2.63.225-.089.149-.053.349-.155.459-.245.827-.61 1.028-1.145.368.83.779.925 1.636.655.177-.082.38-.2.424-.518.46.413 1.432.49 2.142-.382.612.717 2.001.785 2.533-.171zm2.157.865s.04.129.064.169c-.101.003-.213 0-.213 0a.905.905 0 0 0 .149-.17z`,
+ d: `M22.635 3.883a1.364 1.25 0 0 0-1.363 1.25 1.364 1.25 0 0 0 1.363 1.25A1.364 1.25 0 0 0 24 5.133a1.364 1.25 0 0 0-1.365-1.25zm-16.004.418-6.027.008c-.026 0-.051-.003-.076 0-.296.036-.527.273-.528.558l.018 14.574c0 .22.06.676.682.676l5.58-.021c1.595-.003 2.664-.031 3.3-.112h.016a11.43 11.43 0 0 0 1.955-.469c1.22-.38 2.3-.944 3.23-1.697a7.854 7.854 0 0 0 2.114-2.562 6.716 6.716 0 0 0 .646-1.987 4.244 3.89 0 0 0 .26.028 4.244 3.89 0 0 0 4.244-3.89 4.244 3.89 0 0 0-4.244-3.89 4.244 3.89 0 0 0-2.9 1.082 8.838 8.838 0 0 0-2.25-1.355c-1.536-.65-3.536-.948-6.02-.943zm-.262 3.004c1.215-.003 2.079.034 2.569.101a7.32 7.32 0 0 1 1.617.436c.57.218 1.068.483 1.496.814 1.177.915 1.732 1.999 1.734 3.432.003 1.468-.534 2.611-1.68 3.57a5.582 5.582 0 0 1-1.177.742c-.409.19-.942.355-1.615.496-.636.128-1.6.2-2.856.202l-2.673.004-.012-9.793 2.598-.004z`,
+ v: `M15.583 23.4965c.0673.1924-.0435.3484-.2472.3484h-6.262c-.4075 0-.8502-.3113-.9881-.6947L.0426.7837C-.105.3925.149.1152.5276.1599l6.393.6158c.4056.0391.8441.383.9787.7675l7.6837 21.9533zM23.4736.1599l-6.393.6159c-.4055.0391-.8436.3832-.9775.7678l-3.8275 10.9895 3.6784 10.5098L23.9586.7837c.1378-.3834-.0795-.663-.485-.6238z`,
+ odin: `M12 0A11.999 11.999 0 0 0 1.607 18c.001 0 .143.279.545.861.456.661.725.939.725.939L14.194.2s-.468-.09-1.17-.158C12.56-.002 12 0 12 0m4.184.755L4.35 21.248a12 12 0 0 0 1.652 1.144c5.734 3.312 13.078 1.342 16.39-4.394 3.31-5.735 1.342-13.08-4.394-16.39 0 0-.42-.236-.926-.479-.403-.193-.891-.373-.891-.373m-5.38 1.317L2.806 15.926A9.98 9.98 0 0 1 3.34 7a9.99 9.99 0 0 1 7.463-4.928M17 3.34c4.78 2.759 6.42 8.88 3.66 13.66-2.758 4.779-8.881 6.42-13.66 3.66z`,
+ delphi: `M23.922 10.66a11.925 11.925 0 0 0-1.93-5.299 12.002 12.002 0 0 0-1.362-1.692A11.993 11.993 0 0 0 15.271.455a11.916 11.916 0 0 0-2.88-.444c-.237-.005-.474-.015-.71-.004-.345.016-.69.036-1.033.077-.385.046-.77.108-1.15.182a11.947 11.947 0 0 0-4.906 2.297A12.012 12.012 0 0 0 .394 8.94a11.886 11.886 0 0 0-.393 2.883c-.009.51.016 1.019.073 1.526a11.954 11.954 0 0 0 3.103 6.79 11.982 11.982 0 0 0 8.442 3.858c.013 0 .818-.002.868-.004.518-.02 1.032-.076 1.543-.162a11.947 11.947 0 0 0 6.173-3.072 11.975 11.975 0 0 0 3.667-7.028c.053-.406.087-.815.113-1.224.038-.617.006-1.234-.062-1.848zM4.5 11.777c-.052.3-.094.601-.097.906-.003.253-.005.506.004.76.005.148.031.297.051.445.033.252-.067.455-.297.56a.473.473 0 0 1-.227.035c-.217-.019-.433-.05-.65-.077-.073-.01-.147-.017-.22-.03-.017-.003-.04-.025-.042-.041-.041-.249-.086-.497-.115-.747-.024-.206-.03-.413-.043-.62-.006-.118-.014-.236-.013-.355.002-.197.005-.394.017-.59.014-.218.034-.436.06-.653.02-.177.045-.355.083-.529.062-.29.134-.579.207-.867.07-.275.162-.542.273-.804.08-.187.15-.377.235-.56.09-.195.188-.387.295-.573.12-.21.251-.414.382-.619.083-.13.17-.259.26-.384.074-.102.155-.197.234-.295.072-.088.142-.178.217-.263a7.6 7.6 0 0 1 .25-.274c.123-.128.247-.254.373-.378.087-.085.176-.17.27-.248.173-.145.346-.293.528-.427.227-.168.46-.329.697-.483.186-.12.375-.235.572-.336.253-.129.513-.244.773-.359.159-.07.321-.133.486-.19a11.02 11.02 0 0 1 1.312-.359c.279-.05.56-.086.841-.12.194-.023.39-.042.586-.044.312-.003.625-.004.936.019.342.024.683.07 1.023.118.182.026.362.071.54.117.288.075.578.146.86.24.246.08.487.182.724.288.26.116.513.245.767.374.107.054.21.118.311.183.195.124.392.246.58.38.189.135.368.282.55.424.016.012.03.026.05.045-.165.109-.325.211-.481.318-.168.116-.334.235-.5.353-.105.073-.211.145-.315.219-.13.092-.258.187-.387.28l-.45.321c-.11.08-.218.162-.327.243-.129.096-.26.19-.387.288-.217.167-.443.138-.643.003a6.527 6.527 0 0 0-1.757-.83 5.884 5.884 0 0 0-1.33-.246c-.19-.013-.381-.018-.572-.025a4.367 4.367 0 0 0-.792.047 23.89 23.89 0 0 0-.62.105 5.084 5.084 0 0 0-.795.225 6.08 6.08 0 0 0-.527.218 7.22 7.22 0 0 0-.574.294c-.178.103-.347.222-.516.339-.108.073-.214.15-.313.233-.149.124-.292.255-.435.385-.26.235-.486.5-.697.778-.132.174-.25.36-.368.545a5.76 5.76 0 0 0-.489.967 6.298 6.298 0 0 0-.368 1.271zm13.278 5.496c-.175-.122-.353-.242-.527-.366a.5.5 0 0 1-.154-.237l-.222-.55-.21-.532c-.07-.17-.141-.34-.21-.512-.071-.176-.137-.355-.213-.53-.088-.204-.14-.427-.28-.606a4.738 4.738 0 0 0-.288-.337 2.613 2.613 0 0 0-.498-.413c-.14-.09-.298-.12-.457-.148-.449-.081-.896-.166-1.345-.248l-1.368-.246c-.39-.07-.78-.137-1.166-.218-.258-.054-.494.162-.518.407-.023.246.167.456.375.508.56.141 1.118.293 1.677.442.662.175 1.324.347 1.984.527.22.06.416.173.597.313.22.17.4.375.53.62.084.163.151.336.22.506.071.177.14.355.202.534.093.268.182.537.27.806.055.164.11.328.16.492.075.237.147.475.22.712.05.163.099.327.147.49l.184.638c.048.164.098.327.144.492.07.242.14.485.204.729.033.126-.065.268-.2.287-.273.038-.547.07-.821.104-.182.023-.364.043-.546.063l-.66.07c-.28.029-.558.06-.837.09-.118.012-.236.03-.355.028a1.03 1.03 0 0 1-.688-.261c-.144-.126-.223-.292-.316-.451-.078-.135-.152-.272-.235-.403a12.841 12.841 0 0 0-.398-.602c-.134-.187-.28-.365-.423-.544a6.035 6.035 0 0 0-.229-.265 6.95 6.95 0 0 0-.757-.737 8.876 8.876 0 0 0-.641-.488 5.608 5.608 0 0 0-1.755-.803c-.436-.112-.878-.195-1.333-.187a3.542 3.542 0 0 0-.678.07c-.16.034-.309.022-.441-.089-.073-.06-.104-.144-.146-.223-.017-.032-.027-.068-.044-.109.072-.02.143-.042.216-.058a1.93 1.93 0 0 1 .227-.042c.195-.023.39-.053.584-.058.281-.007.564-.01.844.012a7.816 7.816 0 0 1 1.592.321c.24.076.473.175.704.274.387.166.727.407 1.051.673.214.175.419.36.603.567.225.252.449.506.66.77.15.186.282.389.419.587.228.332.43.681.62 1.037.048.089.093.18.133.272.064.153.199.2.341.183l.572-.07.7-.08c.27-.028.54-.054.81-.084.208-.024.416-.05.624-.08.117-.018.202-.132.208-.254.006-.108-.045-.2-.077-.296-.089-.272-.184-.542-.276-.813-.09-.263-.177-.525-.266-.787-.092-.276-.183-.551-.277-.826-.064-.188-.131-.375-.196-.563-.054-.156-.104-.312-.16-.467-.067-.186-.137-.37-.208-.555-.037-.096-.074-.192-.12-.284a1.22 1.22 0 0 0-.482-.514c-.2-.12-.424-.159-.641-.22-.64-.18-1.28-.356-1.92-.533l-.825-.23c-.218-.06-.435-.129-.657-.177-.259-.057-.433-.212-.57-.427a1.32 1.32 0 0 1-.202-.583.867.867 0 0 1 .12-.546.919.919 0 0 1 .44-.382.7.7 0 0 1 .411-.041c.322.06.645.112.968.168.227.04.454.083.681.121.268.045.536.086.803.13.193.032.386.067.579.1.224.037.448.072.671.11.195.034.389.073.584.103.126.019.249.042.362.102.054.029.11.06.156.1.163.146.326.295.484.447.141.136.279.276.413.42a.945.945 0 0 1 .217.392c.033.115.077.227.117.34l.167.471.212.595c.062.178.122.356.185.534l.176.497.188.544.093.268-.013.01zm.708.363a3.104 3.104 0 0 1-.37-.169c-.03-.016-.039-.076-.054-.117-.07-.197-.138-.395-.206-.592l-.23-.664-.23-.653c-.094-.267-.185-.534-.279-.8a78.3 78.3 0 0 0-.2-.565c-.037-.101-.073-.203-.113-.304-.063-.161-.179-.285-.296-.407-.1-.104-.199-.209-.304-.306a18.166 18.166 0 0 0-.605-.537c-.149-.125-.334-.167-.522-.197a66.347 66.347 0 0 1-.603-.098c-.247-.04-.493-.083-.739-.125l-.665-.113-1.026-.172c-.279-.048-.557-.098-.836-.145-.197-.033-.393-.075-.591-.089-.11-.007-.226.026-.335.056a.939.939 0 0 0-.395.235c-.118.113-.21.247-.272.402-.12.306-.101.606.007.909.071.197.173.376.317.528.142.15.307.258.513.306.248.058.493.129.74.196.44.12.881.24 1.322.362l.842.233.841.235c.266.074.48.224.621.46.07.118.117.252.168.382.062.156.119.315.175.474.079.224.156.45.233.675l.194.567.163.489.167.477.19.562.278.816c.01.03.021.058.028.088.01.042-.015.066-.052.07-.167.02-.335.035-.503.054-.084.01-.169.023-.253.032-.177.02-.355.037-.532.058-.189.021-.377.046-.566.068l-.726.082a.5.5 0 0 1-.122.005.085.085 0 0 1-.057-.037c-.068-.127-.129-.257-.198-.382a12.05 12.05 0 0 0-.733-1.196 10.987 10.987 0 0 0-.99-1.204 7.197 7.197 0 0 0-.595-.552 5.461 5.461 0 0 0-.628-.452 3.313 3.313 0 0 0-.704-.345c-.288-.093-.568-.21-.859-.29-.288-.077-.586-.116-.879-.177-.277-.057-.558-.056-.838-.072-.125-.007-.251.003-.377.01-.143.008-.286.017-.428.031a2.592 2.592 0 0 0-.247.04c-.16.03-.318.062-.491.096-.051-.16-.107-.319-.154-.481a5.498 5.498 0 0 1-.2-1.027 5.23 5.23 0 0 1-.021-1.028c.033-.479.113-.951.258-1.41.095-.3.2-.599.344-.88.096-.187.191-.374.298-.554.08-.137.178-.265.271-.394.073-.1.146-.201.225-.297.07-.084.146-.165.223-.243.128-.13.257-.26.392-.383.09-.084.19-.159.288-.234.105-.08.21-.16.32-.232.148-.096.299-.187.45-.275.135-.078.27-.157.411-.22.211-.093.427-.176.643-.257a2.85 2.85 0 0 1 .383-.12c.247-.054.495-.104.744-.14.21-.03.423-.052.634-.052.27 0 .542.015.81.042.466.046.917.156 1.354.323a6.039 6.039 0 0 1 1.819 1.068c.207.175.409.356.583.564.196.231.388.466.57.708.056.074.081.174.112.266.072.213.141.428.208.643.086.274.167.55.252.824.064.208.133.414.198.622.072.231.14.464.211.696l.15.477.165.534c.05.163.103.325.153.489l.117.39c.037.118.077.236.114.355l.291.928.275.865c.01.035.024.07.035.105.02.065-.015.113-.076.09zm.157-12.752a.484.484 0 0 1-.272.408.062.062 0 0 1-.054-.005c-.077-.06-.148-.127-.227-.184-.237-.173-.471-.35-.716-.512a8.86 8.86 0 0 0-.706-.428c-.246-.132-.502-.244-.756-.358a5.709 5.709 0 0 0-.501-.201c-.28-.095-.563-.186-.848-.267a7.965 7.965 0 0 0-1.091-.215c-.3-.042-.6-.076-.903-.081-.176-.003-.352-.015-.528-.009-.28.01-.56.024-.84.047-.209.017-.416.05-.623.08-.289.04-.573.101-.852.183-.236.07-.471.14-.705.217a4.57 4.57 0 0 0-.422.16 10.614 10.614 0 0 0-1.438.718c-.18.107-.352.232-.525.354a7.506 7.506 0 0 0-.394.296 12.185 12.185 0 0 0-.962.865c-.114.115-.219.24-.325.363-.11.128-.223.254-.327.387a8.572 8.572 0 0 0-.653.956c-.098.164-.187.334-.276.503a8.949 8.949 0 0 0-.253.51c-.08.177-.147.358-.216.54a7.726 7.726 0 0 0-.311.986c-.074.335-.149.67-.2 1.01a10.101 10.101 0 0 0-.047 2.328c.028.268.073.534.11.805-.215 0-.4-.063-.512-.256a.766.766 0 0 1-.08-.242 7.924 7.924 0 0 1-.083-.53 12.5 12.5 0 0 1-.07-.702 8.464 8.464 0 0 1-.021-.723 10.525 10.525 0 0 1 .282-2.28c.092-.394.216-.778.363-1.153.078-.198.151-.398.242-.59.13-.273.268-.544.414-.81.105-.192.222-.38.346-.561.145-.214.3-.42.455-.627.102-.135.207-.268.317-.396.105-.121.217-.237.328-.353a9.419 9.419 0 0 1 .578-.56c.18-.155.359-.31.545-.456.145-.114.299-.216.45-.32.13-.09.258-.18.392-.26a13.292 13.292 0 0 1 .975-.531c.146-.07.297-.133.447-.196.116-.05.231-.101.35-.142.248-.084.497-.163.747-.24.137-.043.275-.084.416-.112.299-.062.598-.123.9-.17a7.19 7.19 0 0 1 .743-.078c.325-.016.65-.019.976-.015.216.003.433.022.648.045a9.735 9.735 0 0 1 2.377.532c.432.16.86.332 1.264.56.28.157.557.318.829.49.206.13.405.276.6.424.177.134.35.274.514.423a.43.43 0 0 1 .13.373z`,
+ racket: `M12 0a11.95 11.95 0 0 0-4.104.721c4.872 2.556 11.316 10.893 13.547 18.686A11.957 11.957 0 0 0 24 12c0-6.627-5.373-12-12-12zM4.093 2.974A11.971 11.971 0 0 0 0 12c0 3.026 1.12 5.789 2.968 7.9 1.629-4.894 4.691-9.611 7.313-12.246-1.872-2.016-3.968-3.618-6.188-4.68zm2.276 19.625A11.947 11.947 0 0 0 12 24c2.092 0 4.059-.536 5.772-1.478-.987-4.561-2.851-8.739-5.28-12.147-2.597 2.8-5.186 7.702-6.123 12.224z`,
+ purescript: `M19.166 4.6l-1.24 1.24 3.97 3.97-3.97 3.97 1.24 1.24 4.58-4.6a.87.87 0 0 0 0-1.23zM6.955 6.74l1.87 1.75h8.23l-1.87-1.75zm-2.1 2.24l-4.6 4.6a.87.87 0 0 0 0 1.23l4.6 4.59 1.23-1.24-3.97-3.97 3.97-3.97-1.24-1.24zm3.97 2.14l-1.87 1.76h8.23l1.87-1.76zm-1.87 4.39l1.87 1.75h8.23l-1.87-1.75z`,
+ sass: `M12 0c6.627 0 12 5.373 12 12s-5.373 12-12 12S0 18.627 0 12 5.373 0 12 0zM9.615 15.998c.175.645.156 1.248-.024 1.792l-.065.18c-.024.061-.052.12-.078.176-.14.29-.326.56-.555.81-.698.759-1.672 1.047-2.09.805-.45-.262-.226-1.335.584-2.19.871-.918 2.12-1.509 2.12-1.509v-.003l.108-.061zm9.911-10.861c-.542-2.133-4.077-2.834-7.422-1.645-1.989.707-4.144 1.818-5.693 3.267C4.568 8.48 4.275 9.98 4.396 10.607c.427 2.211 3.457 3.657 4.703 4.73v.006c-.367.18-3.056 1.529-3.686 2.925-.675 1.47.105 2.521.615 2.655 1.575.436 3.195-.36 4.065-1.649.84-1.261.766-2.881.404-3.676.496-.135 1.08-.195 1.83-.104 2.101.24 2.521 1.56 2.43 2.1-.09.539-.523.854-.674.944-.15.091-.195.12-.181.181.015.09.091.09.21.075.165-.03 1.096-.45 1.141-1.471.045-1.29-1.186-2.729-3.375-2.7-.9.016-1.471.091-1.875.256-.03-.045-.061-.075-.105-.105-1.35-1.455-3.855-2.475-3.75-4.41.03-.705.285-2.564 4.8-4.814 3.705-1.846 6.661-1.335 7.171-.21.733 1.604-1.576 4.59-5.431 5.024-1.47.165-2.235-.404-2.431-.615-.209-.225-.239-.24-.314-.194-.12.06-.045.255 0 .375.12.3.585.825 1.396 1.095.704.225 2.43.359 4.5-.45 2.324-.899 4.139-3.405 3.614-5.505l.073.067z`,
+ less: `M3.598 7.15a7.961 7.961 0 0 0-1.054.068c-.281.041-.52.124-.717.249a1.19 1.19 0 0 0-.45.497c-.098.208-.14.47-.14.802V10.3c0 .428-.084.732-.253.884-.169.166-.492.25-.984.25v1.16c.478 0 .815.083.984.249.169.166.253.47.253.912v1.548c0 .594.183 1.009.548 1.23.38.207.984.318 1.813.318v-1.078c-.393 0-.646-.07-.773-.194-.126-.124-.183-.373-.183-.746v-1.465c0-.373-.098-.663-.28-.87-.184-.208-.479-.374-.886-.484.393-.125.688-.29.871-.512.183-.22.281-.511.281-.87V9.167c0-.36.057-.608.183-.733.122-.12.412-.195.787-.2v4.547c0 .416.03.764.09 1.044.059.28.164.52.314.724.15.203.356.35.616.443.26.093.589.14.984.14.098 0 .205-.007.32-.02a5.336 5.336 0 0 0 .65-.107l-.036-.98c-.27.038-.492.057-.667.057-.353 0-.59-.092-.713-.276-.122-.183-.183-.534-.183-1.051V7.149H3.598zm16.818-.001v1.092c.393 0 .647.069.773.193.127.125.183.373.183.733v1.465c0 .359.098.65.28.87.184.222.479.387.872.512-.407.11-.702.276-.885.483-.183.208-.281.498-.281.871v1.465c0 .373-.057.622-.183.746-.126.125-.38.194-.773.194v1.078c.83 0 1.434-.11 1.813-.318.365-.221.548-.636.548-1.23v-1.548c0-.442.085-.746.253-.912.169-.166.506-.249.984-.249v-1.16c-.492 0-.815-.084-.984-.25-.168-.151-.253-.456-.253-.884V8.766c0-.332-.042-.594-.14-.801a1.19 1.19 0 0 0-.45-.498 1.828 1.828 0 0 0-.717-.249 7.252 7.252 0 0 0-1.04-.069zm-6.479 1.975c-.675 0-1.209.14-1.588.421-.38.281-.576.689-.576 1.209 0 .422.112.773.351 1.026s.618.478 1.152.688c.043.015.14.057.296.113.45.183.758.31.913.436a.592.592 0 0 1 .239.478c0 .224-.084.393-.253.506-.169.112-.408.168-.717.168-.295 0-.632-.056-.984-.155a3.901 3.901 0 0 1-.885-.337l-.14 1.04c.505.296 1.18.436 2.037.436.717 0 1.265-.155 1.659-.464.393-.309.59-.759.59-1.335 0-.436-.126-.787-.38-1.054-.252-.267-.632-.492-1.166-.689-.382-.15-.84-.277-1.209-.506a.465.465 0 0 1-.224-.421c0-.183.084-.324.239-.422.154-.098.365-.14.646-.14.506 0 1.026.126 1.574.379l.365-.956c-.562-.28-1.208-.421-1.939-.421zm4.512 0c-.675 0-1.21.14-1.589.421-.38.281-.576.689-.576 1.209 0 .422.112.773.351 1.026.24.253.619.478 1.153.688.042.015.14.057.295.113.45.183.759.31.914.436a.592.592 0 0 1 .238.478c0 .224-.084.393-.253.506-.168.112-.407.168-.716.168a3.72 3.72 0 0 1-.984-.155 3.904 3.904 0 0 1-.886-.337l-.14 1.04c.506.296 1.18.436 2.038.436.702 0 1.265-.155 1.686-.464.394-.309.59-.759.59-1.335 0-.436-.126-.787-.379-1.054s-.632-.492-1.166-.689c-.392-.153-.842-.277-1.209-.506a.465.465 0 0 1-.225-.421c0-.183.085-.324.24-.422.154-.098.364-.14.646-.14.506 0 1.026.126 1.574.379l.337-.956c-.562-.28-1.209-.421-1.94-.421zm-9.46.014c-.842 0-1.503.267-1.995.815-.492.548-.73 1.279-.73 2.192 0 .956.252 1.687.772 2.22.52.535 1.237.802 2.165.802.8 0 1.49-.183 2.08-.52l-.197-.984a3.66 3.66 0 0 1-1.813.492c-.492 0-.886-.155-1.167-.45-.28-.295-.435-.716-.45-1.25h3.852v-.591c0-.829-.225-1.49-.661-1.982-.45-.491-1.054-.744-1.855-.744zm-.013.983c.38 0 .674.127.885.38.211.253.323.618.323 1.082H7.67c.042-.492.182-.857.407-1.096.253-.239.548-.366.9-.366Z`,
+ markdown: `M22.27 19.385H1.73A1.73 1.73 0 010 17.655V6.345a1.73 1.73 0 011.73-1.73h20.54A1.73 1.73 0 0124 6.345v11.308a1.73 1.73 0 01-1.73 1.731zM5.769 15.923v-4.5l2.308 2.885 2.307-2.885v4.5h2.308V8.078h-2.308l-2.307 2.885-2.308-2.885H3.46v7.847zM21.232 12h-2.309V8.077h-2.307V12h-2.308l3.461 4.039z`,
+ yaml: `m0 .97 4.111 6.453v4.09h2.638v-4.09L11.053.969H8.214L5.58 5.125 2.965.969Zm12.093.024-4.47 10.544h2.114l.97-2.345h4.775l.804 2.345h2.26L14.255.994Zm1.133 2.225 1.463 3.87h-3.096zm3.06 9.475v10.29H24v-2.199h-5.454v-8.091zm-12.175.002v10.335h2.217v-7.129l2.32 4.792h1.746l2.4-4.96v7.295h2.127V12.696h-2.904L9.44 17.37l-2.455-4.674Z`,
+ toml: `M.014 0h5.34v2.652H2.888v18.681h2.468V24H.015V0Zm17.622 5.049v2.78h-4.274v12.935h-3.008V7.83H6.059V5.05h11.577ZM23.986 24h-5.34v-2.652h2.467V2.667h-2.468V0h5.34v24Z`,
+ xml: `M4.345 7.053c-.495.02-.44.725-.536 1.081-.157.583-.3 1.325-.347 1.926-.046.585-.008 1.127.066 1.719.058.46.191.767.07.89-.108.11-3.216 2.962-3.466 3.123-.26.169-.08.584.069.817.157.246.23.373.557.33.306-.042.405-.409.583-.606.228-.252 2.421-2.401 2.616-2.401.077.544.367 1.064.67 1.513.15.222.314.439.505.629.175.175.4.317.587.45.44.024.795-.301.35-.67-.17-.14-.735-.971-.927-1.43-.18-.43-.574-1.076-.146-1.428 1.494-1.23 3.72-2.262 4.247-2.313-.257 1.024-1.356 3.048-1.757 4.012-.14.333-.231.732-.185 1.094.055.434.383.774.587.806.417-.023.7-.387.946-.645.343-.357.634-.685.974-1.043.339-.356.672-.731.971-1.07.184-.207.674-.713.963-.713-.11.693-.716 1.552-.839 2.254-.125.716.531 1.596 1.217.956.623-.58 1.255-1.129 1.867-1.72.217-.208.175.037.224.242.05.208.176.91.275 1.1.18.346.496.592.897.598.362.006.727-.161.982-.414.19-.187.513-.699.154-.832-.23-.086-.217-.176-.495-.129-.172.029-.362.074-.507.179-.367-.003-.381-.89-.324-1.161.068-.327.207-.659.185-.998-.026-.418-.478-.69-.582-.72-.156-.076-.253.023-.458.212-.173.161-.363.332-.535.495-.34.322-.768.813-.942.813.305-.705.708-2.652-.643-2.48-.563.071-.95.377-1.394.71-.29.28-.683.641-.936.87-.236.216-.371.404-.496.404.132-.747 1.685-3.167.885-3.853-.158-.136-.313-.325-.515-.349a4.637 4.637 0 0 0-.833.19c-.565.18-2.78 1.28-4.19 2.289-.131.094-.214-.085-.231-.29-.087-1.058.199-2.19.496-3.188.208-.696-.557-1.225-.659-1.249zm18.177.874c-.166.364-.2.894-.248 1.319a24.307 24.307 0 0 0-1.246-.115c.238.296.691.588 1.056.724-.048.366-.434.67-.599 1.021.458-.127.676-.47.989-.821.362.22.791.627 1.26.636-.177-.376-.334-.695-.658-.966.269-.175.717-.362.924-.633-.345-.074-.718-.093-1.052-.015-.258-.284-.3-.772-.426-1.15zm-2.92.079c-.23.02-.613.49-.832.773-.807 1.039-1.542 3.15-1.661 3.542-.363 1.195-.502 2.672.28 3.722.456.612 1.258.66 2.041.434.405-.116.812-.406.95-.723.114-.263.174-.753-.404-.38-.224.145-.634.304-1.37.291-.247-.004-.651-.357-.76-.722-.192-.595-.11-1.393-.11-1.393.167-1.028.642-2.146 1.061-3.076.163-.36.658-1.259.842-1.546 0 0 .239-.373.131-.77-.031-.116-.091-.16-.168-.152zm3.072 2.976c-.12.264-.144.648-.18.956-.274-.031-.63-.066-.904-.083.172.215.501.426.766.525-.034.265-.314.486-.434.741.332-.092.49-.34.717-.596.263.16.575.456.914.462-.127-.273-.242-.504-.477-.701.195-.127.52-.262.67-.46a1.77 1.77 0 0 0-.763-.01c-.187-.206-.217-.56-.309-.834zm-1.123 2.422c-.083.183-.1.449-.125.662a12.6 12.6 0 0 0-.624-.058c.119.148.346.295.53.363-.025.184-.219.336-.301.513.23-.064.339-.236.496-.413.181.11.397.316.632.32-.088-.19-.168-.349-.33-.485.135-.087.36-.181.463-.317a1.22 1.22 0 0 0-.527-.008c-.13-.142-.151-.387-.214-.576z`,
+ graphql: `M12.002 0a2.138 2.138 0 1 0 0 4.277 2.138 2.138 0 1 0 0-4.277zm8.54 4.931a2.138 2.138 0 1 0 0 4.277 2.138 2.138 0 1 0 0-4.277zm0 9.862a2.138 2.138 0 1 0 0 4.277 2.138 2.138 0 1 0 0-4.277zm-8.54 4.931a2.138 2.138 0 1 0 0 4.276 2.138 2.138 0 1 0 0-4.276zm-8.542-4.93a2.138 2.138 0 1 0 0 4.276 2.138 2.138 0 1 0 0-4.277zm0-9.863a2.138 2.138 0 1 0 0 4.277 2.138 2.138 0 1 0 0-4.277zm8.542-3.378L2.953 6.777v10.448l9.049 5.224 9.047-5.224V6.777zm0 1.601 7.66 13.27H4.34zm-1.387.371L3.97 15.037V7.363zm2.774 0 6.646 3.838v7.674zM5.355 17.44h13.293l-6.646 3.836z`,
+ latex: `M2.176 2.814c.233.42.476.78.73 1.09.247-.013 1.132.456 1.312.523.508.282 1.063.63 1.567.966.505.337.96.662 1.272.9.156.12.278.218.352.286a.483.483 0 01.078.082.08.08 0 01.01.021.06.06 0 01-.004.047.057.057 0 01-.04.03.077.077 0 01-.028 0c-.057 0-.203-.163-.497-.415a23.474 23.474 0 00-2.759-1.827c-.504-.28-.956-.542-1.264-.613a2.322 2.322 0 00-.36-.025 2.706 2.706 0 00-.788.133c.494.414.91.716 1.28.949-.57-.182-1.182-.21-1.902.133.526.329.967.567 1.354.745 1.103.156 2.258.696 3.224 1.309.483.307.904.615 1.219.867.157.125.29.237.39.328.098.091.174.154.197.21.03.073-.019.104-.084.058-.032-.022-.088-.102-.184-.191a7.35 7.35 0 00-.384-.327c-.312-.25-.729-.552-1.209-.857-.893-.562-2.232-1.013-3.173-1.397-.602-.11-1.225-.06-1.906.39.449.2.837.349 1.182.463.812 0 1.892.365 2.935.922 1.042.556 2.04 1.214 2.523 1.774.066.077-.016.126-.074.07-.52-.495-1.463-1.204-2.498-1.756-.639-.337-2.153-1.01-2.886-1.01l.004.002c-.567.02-1.13.195-1.679.716.477.118.885.196 1.244.249-.44.088-.87.3-1.289.722.324.07.616.122.882.162-.328.159-.639.404-.923.78.373.03.703.042 1 .044-.36.166-.696.43-.996.85.533.027.98.025 1.364.003-.422.172-.812.464-1.145.968.662.01 1.188-.022 1.628-.076l-.006.002c.99-.073 2.297.127 2.962.847.052.057-.024.118-.072.074-.648-.58-1.493-.827-2.89-.921h-.002c-.543.149-1.046.446-1.46 1.074.536.008.982-.013 1.366-.05-.469.257-.873.644-1.139 1.306.483-.092.888-.19 1.237-.292-.363.265-.668.636-.873 1.194.324-.072.612-.146.871-.221a2.519 2.519 0 00-.513 1.095c.352-.13.655-.254.926-.377-.257.3-.453.681-.55 1.19.495-.199.899-.388 1.238-.568-.31.333-.543.76-.635 1.356a11.816 11.816 0 001.442-.744c-.433.362-.764.843-.879 1.587.788-.348 1.339-.663 1.767-.955-.184.372-.282.806-.235 1.348.762-.584 1.243-1.056 1.602-1.473-.024.269-.003.56.077.884.546-.939 1.089-1.212 1.65-1.526-.895.451-.762.79-.762 1.184.683-.72 1.635-1.482 1.927-1.96-.39.585-.547 1.14-.65 1.63-1.993 1.054-3.207 1.329-4.568 1.75.528.194 1.093.383.859.652l-.624.622c.399-.124.805-.3 1.158-.059-.035.327-.447.492-.8.683.621-.224.756-.172.92-.12.081.393-.203.603-.388.862 1.565-1.19 3.606-2.13 5.044-2.522 2.022-.681 4.63-1.389 5.339-3.115l.712-2.847-.004.004c-.111-.034-.246-.063-.35-.133a.651.651 0 01-.235-.297c-.252.065-.44.03-.56-.088-.117-.117-.167-.296-.203-.491-.203.041-.362.016-.467-.077-.116-.101-.17-.26-.198-.444l-.008-.039.037-.015a.842.842 0 00.302-.194.257.257 0 00.07-.225l-.006-.037.03-.016c.163-.093.345-.169.428-.28a.274.274 0 00.053-.21.88.88 0 00-.155-.357l-.027-.04.04-.027c.118-.09.244-.179.308-.26.032-.04.048-.076.047-.11 0-.033-.015-.07-.064-.117l-.098-.094.135.006c.213.01.395-.007.538-.053a.504.504 0 00.274-.197c-.007-.033-.02-.063-.02-.098a.484.484 0 01.967 0c0 .044-.015.084-.026.125.177.014.347.01.507-.06l.002.001.035-.013c.236-.085.334.045.72-.456-1.69-2.19-4.157-.635-4.977 1.622-.21.576-1.405.578-1.751 0-1.37-2.95-5.53-6.068-9.07-7.218zm.86 2.145c.906.293 1.913.782 2.77 1.328.43.273.813.543 1.114.779.301.236.566.473.62.575.054.102 0 .14-.082.06-.081-.078-.303-.32-.6-.553-.298-.234-.68-.505-1.106-.777-.775-.49-1.982-.958-2.716-1.412zm-1.7 2.7c1.116.014 2.35.447 3.434.997.541.275 1.023.567 1.395.83.372.263.672.524.734.657.061.134-.02.13-.087.055a4.401 4.401 0 00-.704-.626 11.47 11.47 0 00-1.385-.826C3.76 8.264 2.439 7.82 1.336 7.66zm14.916.772a.381.381 0 100 .762.381.381 0 000-.762zM1.7 8.478c.822.072 1.72.368 2.534.75 1.086.509 2.035 1.158 2.434 1.667.035.045-.014.131-.08.062-.428-.44-1.322-1.131-2.397-1.635-.913-.421-2.282-.87-3.262-.78.251-.03.497-.088.771-.064zm16.339.01c-.366.475-.53.423-.703.464.094.43.35.586.585.77l-.06.012c2.315-.447 4.186-.286 6.139-.236l-5.961-1.01zm-.178 1.246h-.002l-.004.016.006-.016zm-.625-.757c-.183.074-.373.076-.563.059a.477.477 0 01-.42.26.483.483 0 01-.435-.278.609.609 0 01-.274.188c-.139.045-.308.057-.493.055.02.035.054.068.055.104a.273.273 0 01-.069.174c-.073.092-.189.17-.295.248.087.141.137.26.149.362a.39.39 0 01-.07.284c-.106.14-.288.21-.439.293a.374.374 0 01-.09.268.89.89 0 01-.297.198c.027.156.074.283.154.354.086.076.211.103.425.047l.055-.014.01.055c.033.207.088.385.187.483.1.099.244.135.503.055l.049-.015.016.048c.05.142.12.223.209.282.087.06.247.112.358.147.798-.869 1.525-1.772 1.884-2.86-.225-.177-.506-.338-.609-.797zm-16.23.386c1.165-.08 2.283.196 3.202.626.92.43 1.658.939 1.974 1.307.075.087-.019.12-.072.072a8.187 8.187 0 00-1.947-1.29c-.904-.414-2.193-.644-3.157-.715zm.864.802c.61.02 1.24.155 1.806.352.756.262 1.421.614 1.747.98.045.05-.007.127-.074.069-.349-.304-.961-.693-1.706-.951-.574-.195-1.613-.369-2.268-.397.197-.022.292-.06.495-.053zm1.05 1.788c.423.034.886.133 1.341.407.043.026.049.136-.049.09-.856-.402-1.326-.49-2.457-.31.386-.128.74-.221 1.164-.187zm-.04.788c.4-.035.784-.002 1.297.204.044.018.08.126-.033.094-.857-.243-1.167-.328-2.287.104.28-.229.622-.366 1.023-.402zm1.285.687c.317-.023.635-.026.934.006.052.006.055.105-.006.102a7.87 7.87 0 00-1.837.115c-.243.046-.423.043-1.405.458.287-.233.794-.452 1.385-.56a8.91 8.91 0 01.93-.12zm1.28.49c.099.003.062.104.006.103-.728-.01-1.304.132-1.875.295a9.78 9.78 0 00-1.318.525c.283-.23.713-.457 1.291-.622.579-.166 1.248-.326 1.896-.302zm.528.398c.036-.005.105.084.018.1-.73.137-1.244.267-1.794.454-.216.074-.58.207-1.243.587.26-.269.656-.492 1.213-.68.558-.19 1.196-.37 1.806-.46zm.311.507c.075-.012.097.087.02.102-1.217.241-1.76.556-2.54 1.144.504-.523 1.297-1.051 2.52-1.246zm.595.448c.087-.013.11.087.021.1-.872.13-1.477.553-2.255 1.33.295-.493 1.004-1.24 2.234-1.43zm.372.39c.046-.006.114.073.023.1a2.634 2.634 0 00-.669.3c-.182.118-.3.2-.597.507.111-.245.296-.434.542-.59.247-.157.509-.293.7-.317z`,
+ webassembly: `M14.745,0c0,0.042,0,0.085,0,0.129c0,1.52-1.232,2.752-2.752,2.752c-1.52,0-2.752-1.232-2.752-2.752 c0-0.045,0-0.087,0-0.129H0v24h24V0H14.745z M11.454,21.431l-1.169-5.783h-0.02l-1.264,5.783H7.39l-1.824-8.497h1.59l1.088,5.783 h0.02l1.311-5.783h1.487l1.177,5.854h0.02l1.242-5.854h1.561l-2.027,8.497H11.454z M20.209,21.431l-0.542-1.891h-2.861l-0.417,1.891 h-1.59l2.056-8.497h2.509l2.5,8.497H20.209z M17.812,15.028l-0.694,3.118h2.159l-0.796-3.118H17.812z`,
+};
+
+export default LANG_ICON_PATHS;
diff --git a/client/src/components/Messages/Content/useCopyCode.ts b/client/src/components/Messages/Content/useCopyCode.ts
new file mode 100644
index 0000000000..6ab3eb0e11
--- /dev/null
+++ b/client/src/components/Messages/Content/useCopyCode.ts
@@ -0,0 +1,34 @@
+import { useRef, useState, useCallback, useEffect } from 'react';
+import copy from 'copy-to-clipboard';
+
+export default function useCopyCode(codeRef: React.RefObject<HTMLElement | null>) {
+ const [isCopied, setIsCopied] = useState(false);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ const timerRef = useRef<ReturnType<typeof setTimeout>>();
+
+ useEffect(() => {
+ return () => clearTimeout(timerRef.current);
+ }, []);
+
+ const handleCopy = useCallback(() => {
+ const codeString = codeRef.current?.textContent;
+ if (codeString == null) {
+ return;
+ }
+
+ const wasFocused = document.activeElement === buttonRef.current;
+ setIsCopied(true);
+ copy(codeString.trim(), { format: 'text/plain' });
+
+ if (wasFocused) {
+ requestAnimationFrame(() => buttonRef.current?.focus());
+ }
+
+ clearTimeout(timerRef.current);
+ timerRef.current = setTimeout(() => {
+ setIsCopied(false);
+ }, 3000);
+ }, [codeRef]);
+
+ return { isCopied, buttonRef, handleCopy };
+}
diff --git a/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx b/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx
index e68d008f3d..8d4f1817f3 100644
--- a/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx
+++ b/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx
@@ -50,11 +50,11 @@ const toggleSwitchConfigs = [
key: 'showThinking',
},
{
- stateAtom: store.showCode,
- localizationKey: 'com_nav_show_code' as const,
- switchId: 'showCode',
+ stateAtom: store.autoExpandTools,
+ localizationKey: 'com_nav_auto_expand_tools' as const,
+ switchId: 'autoExpandTools',
hoverCardText: undefined,
- key: 'showCode',
+ key: 'autoExpandTools',
},
{
stateAtom: store.LaTeXParsing,
diff --git a/client/src/components/Nav/SettingsTabs/General/General.tsx b/client/src/components/Nav/SettingsTabs/General/General.tsx
index f764357b5e..b86abc543e 100644
--- a/client/src/components/Nav/SettingsTabs/General/General.tsx
+++ b/client/src/components/Nav/SettingsTabs/General/General.tsx
@@ -10,21 +10,21 @@ import store from '~/store';
const toggleSwitchConfigs = [
{
stateAtom: store.enableUserMsgMarkdown,
- localizationKey: 'com_nav_user_msg_markdown',
+ localizationKey: 'com_nav_user_msg_markdown' as const,
switchId: 'enableUserMsgMarkdown',
hoverCardText: undefined,
key: 'enableUserMsgMarkdown',
},
{
stateAtom: store.autoScroll,
- localizationKey: 'com_nav_auto_scroll',
+ localizationKey: 'com_nav_auto_scroll' as const,
switchId: 'autoScroll',
hoverCardText: undefined,
key: 'autoScroll',
},
{
stateAtom: store.keepScreenAwake,
- localizationKey: 'com_nav_keep_screen_awake',
+ localizationKey: 'com_nav_keep_screen_awake' as const,
switchId: 'keepScreenAwake',
hoverCardText: undefined,
key: 'keepScreenAwake',
diff --git a/client/src/components/Web/Citation.tsx b/client/src/components/Web/Citation.tsx
index 933474ff82..90a620bf7e 100644
--- a/client/src/components/Web/Citation.tsx
+++ b/client/src/components/Web/Citation.tsx
@@ -1,12 +1,44 @@
import { memo, useState, useContext, useCallback } from 'react';
-import { useRecoilValue } from 'recoil';
-import { useToastContext } from '@librechat/client';
+import { Button } from '@librechat/client';
+import { ChevronLeft, ChevronRight, FileText } from 'lucide-react';
import type { CitationProps } from './types';
import { SourceHovercard, FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';
+import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog';
import { CitationContext, useCitation, useCompositeCitations } from './Context';
-import { useFileDownload } from '~/data-provider';
import { useLocalize } from '~/hooks';
-import store from '~/store';
+
+interface FileCitationMetadata {
+ fileBytes?: number;
+ fileType?: string;
+}
+
+interface FileCitationSource {
+ attribution?: string;
+ fileId?: string;
+ fileName?: string;
+ link?: string;
+ metadata?: FileCitationMetadata;
+ pageRelevance?: Record<number, number>;
+ pages?: number[];
+ refType?: string;
+ relevance?: number;
+ snippet?: string;
+ title?: string;
+}
+
+function getFileCitationData(source?: FileCitationSource) {
+ const isFileType = source?.refType === 'file' && source.fileId != null;
+
+ return {
+ isFileType,
+ fileId: isFileType ? source.fileId : undefined,
+ fileMeta: isFileType ? source.metadata : undefined,
+ fileName: isFileType ? source.fileName : undefined,
+ filePages: isFileType ? source.pages : undefined,
+ fileRelevance: isFileType ? source.relevance : undefined,
+ filePageRelevance: isFileType ? source.pageRelevance : undefined,
+ };
+}
interface CompositeCitationProps {
citationId?: string;
@@ -20,15 +52,20 @@ export function CompositeCitation(props: CompositeCitationProps) {
const { citations, citationId } = props.node?.properties ?? ({} as CitationProps);
const { setHoveredCitationId } = useContext(CitationContext);
const [currentPage, setCurrentPage] = useState(0);
+ const [showPreview, setShowPreview] = useState(false);
const sources = useCompositeCitations(citations || []);
- if (!sources || sources.length === 0) return null;
+ if (!sources || sources.length === 0) {
+ return null;
+ }
const totalPages = sources.length;
const getCitationLabel = () => {
- if (!sources || sources.length === 0) return localize('com_citation_source');
+ if (!sources || sources.length === 0) {
+ return localize('com_citation_source');
+ }
- const firstSource = sources[0];
+ const firstSource = sources[0] as FileCitationSource;
const remainingCount = sources.length - 1;
const attribution =
firstSource.attribution ||
@@ -55,56 +92,190 @@ export function CompositeCitation(props: CompositeCitationProps) {
}
};
- const currentSource = sources?.[currentPage];
+ const currentSource = sources[currentPage] as FileCitationSource;
+ const { isFileType, fileId, fileMeta, fileName, filePages, fileRelevance, filePageRelevance } =
+ getFileCitationData(currentSource);
+
+ const handleFileClick = (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (isFileType && fileId) {
+ setShowPreview(true);
+ }
+ };
return (
- <SourceHovercard
- source={currentSource}
- label={getCitationLabel()}
- onMouseEnter={() => setHoveredCitationId(citationId || null)}
- onMouseLeave={() => setHoveredCitationId(null)}
- >
- {totalPages > 1 && (
- <span className="mb-2 flex items-center justify-between border-b border-border-heavy pb-2">
- <span className="flex gap-2">
- <button
- onClick={handlePrevPage}
- disabled={currentPage === 0}
- style={{ opacity: currentPage === 0 ? 0.5 : 1 }}
- className="flex cursor-pointer items-center justify-center border-none bg-transparent p-0 text-base"
- >
- ←
- </button>
- <button
- onClick={handleNextPage}
- disabled={currentPage === totalPages - 1}
- style={{ opacity: currentPage === totalPages - 1 ? 0.5 : 1 }}
- className="flex cursor-pointer items-center justify-center border-none bg-transparent p-0 text-base"
- >
- →
- </button>
- </span>
- <span className="text-xs text-text-tertiary">
- {currentPage + 1}/{totalPages}
- </span>
- </span>
+ <>
+ <SourceHovercard
+ source={currentSource}
+ label={getCitationLabel()}
+ onMouseEnter={() => setHoveredCitationId(citationId || null)}
+ onMouseLeave={() => setHoveredCitationId(null)}
+ onClick={isFileType ? handleFileClick : undefined}
+ isFile={isFileType}
+ filePages={filePages}
+ fileRelevance={fileRelevance}
+ >
+ {isFileType ? (
+ <>
+ <div className="flex items-center gap-2">
+ <FileText className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <button
+ onClick={handleFileClick}
+ className="min-w-0 truncate text-sm font-medium text-text-primary hover:underline"
+ >
+ {fileName || currentSource.title || localize('com_file_source')}
+ </button>
+ </div>
+ {(fileRelevance != null || (filePages && filePages.length > 0)) && (
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1">
+ {fileRelevance != null && fileRelevance > 0 && (
+ <span className="text-xs text-text-secondary">
+ {localize('com_ui_relevance')}: {Math.round(fileRelevance * 100)}%
+ </span>
+ )}
+ {filePages && filePages.length > 0 && (
+ <span className="text-xs text-text-secondary">
+ {localize('com_file_pages', { pages: filePages.join(', ') })}
+ </span>
+ )}
+ </div>
+ )}
+ {currentSource.snippet && (
+ <p className="mt-1.5 line-clamp-3 break-words text-xs leading-relaxed text-text-secondary">
+ {currentSource.snippet}
+ </p>
+ )}
+ {totalPages > 1 && (
+ <div className="mt-2 flex items-center gap-1 border-t border-border-light pt-2">
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={handlePrevPage}
+ disabled={currentPage === 0}
+ className="size-7"
+ aria-label="Previous source"
+ >
+ <ChevronLeft className="size-3.5" aria-hidden="true" />
+ </Button>
+ {sources.map((source, i) => (
+ <button
+ key={i}
+ type="button"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setCurrentPage(i);
+ }}
+ className={`flex size-6 items-center justify-center rounded text-xs transition-colors ${
+ i === currentPage
+ ? 'bg-surface-hover font-medium text-text-primary'
+ : 'text-text-secondary hover:bg-surface-hover'
+ }`}
+ aria-label={`Source ${i + 1}`}
+ aria-current={i === currentPage ? 'true' : undefined}
+ >
+ {i + 1}
+ </button>
+ ))}
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={handleNextPage}
+ disabled={currentPage === totalPages - 1}
+ className="size-7"
+ aria-label="Next source"
+ >
+ <ChevronRight className="size-3.5" aria-hidden="true" />
+ </Button>
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ <div className="mb-1.5 overflow-hidden text-sm">
+ <FaviconImage
+ domain={getCleanDomain(currentSource.link || '')}
+ className="float-left mr-2 mt-0.5"
+ />
+ <span className="float-right ml-2 max-w-[40%] truncate text-xs text-text-secondary">
+ {getCleanDomain(currentSource.link || '')}
+ </span>
+ <a
+ href={currentSource.link}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-text-primary hover:underline"
+ >
+ {currentSource.title}
+ </a>
+ </div>
+ {currentSource.snippet && (
+ <p className="line-clamp-4 break-words text-xs text-text-secondary md:text-sm">
+ {currentSource.snippet}
+ </p>
+ )}
+ {totalPages > 1 && (
+ <div className="flex items-center gap-1 border-t border-border-light pt-2">
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={handlePrevPage}
+ disabled={currentPage === 0}
+ className="size-7"
+ aria-label="Previous source"
+ >
+ <ChevronLeft className="size-3.5" aria-hidden="true" />
+ </Button>
+ {sources.map((source, i) => (
+ <button
+ key={i}
+ type="button"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setCurrentPage(i);
+ }}
+ className={`flex size-6 items-center justify-center rounded text-xs transition-colors ${
+ i === currentPage
+ ? 'bg-surface-hover font-medium text-text-primary'
+ : 'text-text-secondary hover:bg-surface-hover'
+ }`}
+ aria-label={`Source ${i + 1}`}
+ aria-current={i === currentPage ? 'true' : undefined}
+ >
+ {i + 1}
+ </button>
+ ))}
+ <Button
+ size="icon"
+ variant="ghost"
+ onClick={handleNextPage}
+ disabled={currentPage === totalPages - 1}
+ className="size-7"
+ aria-label="Next source"
+ >
+ <ChevronRight className="size-3.5" aria-hidden="true" />
+ </Button>
+ </div>
+ )}
+ </>
+ )}
+ </SourceHovercard>
+ {isFileType && fileId && (
+ <FilePreviewDialog
+ open={showPreview}
+ onOpenChange={setShowPreview}
+ fileName={fileName || currentSource.title || ''}
+ fileId={fileId}
+ relevance={fileRelevance}
+ pages={filePages}
+ pageRelevance={filePageRelevance}
+ fileType={fileMeta?.fileType}
+ fileSize={fileMeta?.fileBytes}
+ />
)}
- <span className="mb-2 flex items-center">
- <FaviconImage domain={getCleanDomain(currentSource.link || '')} className="mr-2" />
- <a
- href={currentSource.link}
- target="_blank"
- rel="noopener noreferrer"
- className="line-clamp-2 cursor-pointer overflow-hidden text-sm font-bold text-[#0066cc] hover:underline dark:text-blue-400 md:line-clamp-3"
- >
- {currentSource.attribution}
- </a>
- </span>
- <h4 className="mb-1.5 mt-0 text-xs text-text-primary md:text-sm">{currentSource.title}</h4>
- <p className="my-2 text-ellipsis break-all text-xs text-text-secondary md:text-sm">
- {currentSource.snippet}
- </p>
- </SourceHovercard>
+ </>
);
}
@@ -118,69 +289,33 @@ interface CitationComponentProps {
export function Citation(props: CitationComponentProps) {
const localize = useLocalize();
- const user = useRecoilValue(store.user);
- const { showToast } = useToastContext();
const { citation, citationId } = props.node?.properties ?? {};
const { setHoveredCitationId } = useContext(CitationContext);
const refData = useCitation({
turn: citation?.turn || 0,
refType: citation?.refType,
index: citation?.index || 0,
- });
-
- // Setup file download hook
- const isFileType = refData?.refType === 'file' && (refData as any)?.fileId;
- const isLocalFile = isFileType && (refData as any)?.metadata?.storageType === 'local';
- const { refetch: downloadFile } = useFileDownload(
- user?.id ?? '',
- isFileType && !isLocalFile ? (refData as any).fileId : '',
- );
+ }) as FileCitationSource | undefined;
- const handleFileDownload = useCallback(
- async (e: React.MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
+ const { isFileType, fileId, fileMeta, fileName, filePages, fileRelevance, filePageRelevance } =
+ getFileCitationData(refData);
- if (!isFileType || !(refData as any)?.fileId) return;
+ const [showPreview, setShowPreview] = useState(false);
- // Don't allow download for local files
- if (isLocalFile) {
- showToast({
- status: 'error',
- message: localize('com_sources_download_local_unavailable'),
- });
- return;
- }
-
- try {
- const stream = await downloadFile();
- if (stream.data == null || stream.data === '') {
- console.error('Error downloading file: No data found');
- showToast({
- status: 'error',
- message: localize('com_ui_download_error'),
- });
- return;
- }
- const link = document.createElement('a');
- link.href = stream.data;
- link.setAttribute('download', (refData as any).fileName || 'file');
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- window.URL.revokeObjectURL(stream.data);
- } catch (error) {
- console.error('Error downloading file:', error);
- showToast({
- status: 'error',
- message: localize('com_ui_download_error'),
- });
+ const handleFileClick = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (isFileType && fileId) {
+ setShowPreview(true);
}
},
- [downloadFile, isFileType, isLocalFile, refData, localize, showToast],
+ [isFileType, fileId],
);
- if (!refData) return null;
+ if (!refData) {
+ return null;
+ }
const getCitationLabel = () => {
return (
@@ -192,15 +327,31 @@ export function Citation(props: CitationComponentProps) {
};
return (
- <SourceHovercard
- source={refData}
- label={getCitationLabel()}
- onMouseEnter={() => setHoveredCitationId(citationId || null)}
- onMouseLeave={() => setHoveredCitationId(null)}
- onClick={isFileType && !isLocalFile ? handleFileDownload : undefined}
- isFile={isFileType}
- isLocalFile={isLocalFile}
- />
+ <>
+ <SourceHovercard
+ source={refData}
+ label={getCitationLabel()}
+ onMouseEnter={() => setHoveredCitationId(citationId || null)}
+ onMouseLeave={() => setHoveredCitationId(null)}
+ onClick={isFileType ? handleFileClick : undefined}
+ isFile={isFileType}
+ filePages={filePages}
+ fileRelevance={fileRelevance}
+ />
+ {isFileType && fileId && (
+ <FilePreviewDialog
+ open={showPreview}
+ onOpenChange={setShowPreview}
+ fileName={fileName || refData.title || ''}
+ fileId={fileId}
+ relevance={fileRelevance}
+ pages={filePages}
+ pageRelevance={filePageRelevance}
+ fileType={fileMeta?.fileType}
+ fileSize={fileMeta?.fileBytes}
+ />
+ )}
+ </>
);
}
diff --git a/client/src/components/Web/SourceHovercard.tsx b/client/src/components/Web/SourceHovercard.tsx
index 242b35047f..3fe359ff1b 100644
--- a/client/src/components/Web/SourceHovercard.tsx
+++ b/client/src/components/Web/SourceHovercard.tsx
@@ -1,6 +1,6 @@
import React, { ReactNode } from 'react';
import * as Ariakit from '@ariakit/react';
-import { ChevronDown, Paperclip } from 'lucide-react';
+import { ChevronDown, FileText } from 'lucide-react';
import { VisuallyHidden } from '@ariakit/react';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -21,14 +21,14 @@ interface SourceHovercardProps {
isFile?: boolean;
isLocalFile?: boolean;
children?: ReactNode;
+ filePages?: number[];
+ fileRelevance?: number;
}
-/** Helper to get domain favicon */
function getFaviconUrl(domain: string) {
return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`;
}
-/** Helper to get clean domain name */
export function getCleanDomain(url: string) {
const domain = url.replace(/(^\w+:|^)\/\//, '').split('/')[0];
return domain.startsWith('www.') ? domain.substring(4) : domain;
@@ -36,11 +36,67 @@ export function getCleanDomain(url: string) {
export function FaviconImage({ domain, className = '' }: { domain: string; className?: string }) {
return (
- <div className={cn('relative size-4 flex-shrink-0 overflow-hidden rounded-full', className)}>
- <div className="absolute inset-0 rounded-full bg-white" />
- <img src={getFaviconUrl(domain)} alt={domain} className="relative size-full" />
- <div className="border-border-light/10 absolute inset-0 rounded-full border dark:border-transparent"></div>
- </div>
+ <img
+ src={getFaviconUrl(domain)}
+ alt={domain}
+ className={cn('size-4 shrink-0 rounded-full', className)}
+ loading="lazy"
+ />
+ );
+}
+
+const hovercardClass = cn(
+ 'z-[999] w-[320px] max-w-[calc(100vw-2rem)] rounded-xl border border-border-medium bg-surface-secondary p-3 text-text-primary shadow-lg',
+ 'origin-top -translate-y-1 opacity-0 transition-[opacity,transform] duration-150 ease-out',
+ 'data-[enter]:translate-y-0 data-[enter]:opacity-100',
+ 'data-[leave]:-translate-y-1 data-[leave]:opacity-0',
+);
+
+function FileHovercardContent({
+ source,
+ onClick,
+ filePages,
+ fileRelevance,
+}: {
+ source: SourceData;
+ onClick?: (e: React.MouseEvent) => void;
+ filePages?: number[];
+ fileRelevance?: number;
+}) {
+ const localize = useLocalize();
+ const fileName = source.attribution || source.title || localize('com_file_source');
+
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <FileText className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />
+ <button
+ onClick={onClick}
+ className="min-w-0 truncate text-sm font-medium text-text-primary hover:underline"
+ >
+ {fileName}
+ </button>
+ </div>
+ {(fileRelevance != null || (filePages && filePages.length > 0)) && (
+ <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1">
+ {fileRelevance != null && fileRelevance > 0 && (
+ <span className="text-xs text-text-secondary">
+ {localize('com_ui_relevance')}: {Math.round(fileRelevance * 100)}%
+ </span>
+ )}
+ {filePages && filePages.length > 0 && (
+ <span className="text-xs text-text-secondary">
+ {localize('com_file_pages', { pages: filePages.join(', ') })}
+ </span>
+ )}
+ </div>
+ )}
+ {source.snippet && (
+ <p className="mt-1.5 line-clamp-3 break-words text-xs leading-relaxed text-text-secondary">
+ {source.snippet}
+ </p>
+ )}
+ </>
);
}
@@ -53,26 +109,38 @@ export function SourceHovercard({
isFile = false,
isLocalFile = false,
children,
+ filePages,
+ fileRelevance,
}: SourceHovercardProps) {
const localize = useLocalize();
const domain = getCleanDomain(source.link || '');
+ const hovercard = Ariakit.useHovercardStore({ showTimeout: 150, hideTimeout: 150 });
+
+ const handleFileClick = React.useCallback(
+ (e: React.MouseEvent) => {
+ hovercard.hide();
+ onClick?.(e);
+ },
+ [hovercard, onClick],
+ );
return (
<span className="relative ml-0.5 inline-block">
- <Ariakit.HovercardProvider showTimeout={150} hideTimeout={150}>
+ <Ariakit.HovercardProvider store={hovercard}>
<span className="flex items-center">
<Ariakit.HovercardAnchor
render={
isFile ? (
<button
- onClick={onClick}
- className="ml-1 inline-block h-5 max-w-36 cursor-pointer items-center overflow-hidden text-ellipsis whitespace-nowrap rounded-xl border border-border-heavy bg-surface-secondary px-2 text-xs font-medium text-blue-600 no-underline transition-colors hover:bg-surface-hover dark:border-border-medium dark:text-blue-400 dark:hover:bg-surface-tertiary"
+ onClick={handleFileClick}
+ className="ml-1 inline-flex h-5 max-w-36 items-center gap-1 overflow-hidden text-ellipsis whitespace-nowrap rounded-xl border border-border-heavy bg-surface-secondary px-2 text-xs font-medium text-text-primary no-underline transition-colors hover:bg-surface-hover dark:border-border-medium dark:hover:bg-surface-tertiary"
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
title={
isLocalFile ? localize('com_sources_download_local_unavailable') : undefined
}
>
+ <FileText className="size-2.5 shrink-0 text-text-secondary" aria-hidden="true" />
{label}
</button>
) : (
@@ -96,62 +164,43 @@ export function SourceHovercard({
<Ariakit.Hovercard
gutter={16}
- className="dark:shadow-lg-dark z-[999] w-[300px] max-w-[calc(100vw-2rem)] rounded-xl border border-border-medium bg-surface-secondary p-3 text-text-primary shadow-lg"
+ className={hovercardClass}
portal={true}
unmountOnHide={true}
>
- {children}
- {!children && (
- <>
- <span className="mb-2 flex items-center">
- {isFile ? (
- <div className="mr-2 flex h-4 w-4 items-center justify-center">
- <Paperclip className="h-3 w-3 text-text-secondary" />
- </div>
- ) : (
- <FaviconImage domain={domain} className="mr-2" />
- )}
- {isFile ? (
- <button
- onClick={onClick}
- className="line-clamp-2 cursor-pointer overflow-hidden text-left text-sm font-bold text-[#0066cc] hover:underline dark:text-blue-400 md:line-clamp-3"
- >
- {source.attribution || source.title || localize('com_file_source')}
- </button>
- ) : (
- <a
- href={source.link}
- target="_blank"
- rel="noopener noreferrer"
- className="line-clamp-2 cursor-pointer overflow-hidden text-sm font-bold text-[#0066cc] hover:underline dark:text-blue-400 md:line-clamp-3"
- >
- {source.attribution || domain}
- </a>
- )}
- </span>
-
- {isFile ? (
- <>
- {source.snippet && (
- <span className="my-2 text-ellipsis break-all text-xs text-text-secondary md:text-sm">
- {source.snippet}
- </span>
- )}
- </>
+ <div>
+ {children ??
+ (isFile ? (
+ <FileHovercardContent
+ source={source}
+ onClick={handleFileClick}
+ filePages={filePages}
+ fileRelevance={fileRelevance}
+ />
) : (
<>
- <h4 className="mb-1.5 mt-0 text-xs text-text-primary md:text-sm">
- {source.title || source.link}
- </h4>
+ <div className="mb-1.5 overflow-hidden text-sm">
+ <FaviconImage domain={domain} className="float-left mr-2 mt-0.5" />
+ <span className="float-right ml-2 max-w-[40%] truncate text-xs text-text-secondary">
+ {domain}
+ </span>
+ <a
+ href={source.link}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium text-text-primary hover:underline"
+ >
+ {source.title || source.link}
+ </a>
+ </div>
{source.snippet && (
- <span className="my-2 text-ellipsis break-all text-xs text-text-secondary md:text-sm">
+ <p className="line-clamp-4 break-words text-xs text-text-secondary md:text-sm">
{source.snippet}
- </span>
+ </p>
)}
</>
- )}
- </>
- )}
+ ))}
+ </div>
</Ariakit.Hovercard>
</span>
</Ariakit.HovercardProvider>
diff --git a/client/src/components/Web/Sources.tsx b/client/src/components/Web/Sources.tsx
index 320cf348bc..97e646d5d0 100644
--- a/client/src/components/Web/Sources.tsx
+++ b/client/src/components/Web/Sources.tsx
@@ -19,6 +19,7 @@ import SourcesErrorBoundary from './SourcesErrorBoundary';
import { useFileDownload } from '~/data-provider';
import { useSearchContext } from '~/Providers';
import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
import store from '~/store';
interface SourceItemProps {
@@ -88,39 +89,45 @@ function SourceItem({ source, expanded = false }: SourceItemProps) {
</Ariakit.HovercardDisclosure>
<Ariakit.Hovercard
+ animated
gutter={16}
- className="dark:shadow-lg-dark z-[999] w-[300px] max-w-[calc(100vw-2rem)] rounded-xl border border-border-medium bg-surface-secondary p-3 text-text-primary shadow-lg"
+ className={cn(
+ 'z-[999] w-[320px] max-w-[calc(100vw-2rem)] rounded-xl border border-border-medium bg-surface-secondary p-3 text-text-primary shadow-lg',
+ 'origin-top-left scale-95 opacity-0 transition-[opacity,transform] duration-150 ease-out',
+ 'data-[enter]:scale-100 data-[enter]:opacity-100',
+ 'data-[leave]:scale-95 data-[leave]:opacity-0',
+ )}
portal={true}
unmountOnHide={true}
>
<div className="flex gap-3">
- <div className="flex-1">
- <div className="mb-2 flex items-center">
- <FaviconImage domain={domain} className="mr-2" />
+ <div className="min-w-0 flex-1">
+ <div className="mb-1.5 overflow-hidden text-sm">
+ <FaviconImage domain={domain} className="float-left mr-2 mt-0.5" />
+ <span className="float-right ml-2 max-w-[40%] truncate text-xs text-text-secondary">
+ {domain}
+ </span>
<a
href={source.link}
target="_blank"
rel="noopener noreferrer"
- className="line-clamp-2 cursor-pointer overflow-hidden text-sm font-bold text-[#0066cc] hover:underline dark:text-blue-400 md:line-clamp-3"
+ className="font-medium text-text-primary hover:underline"
>
- {source.attribution || domain}
+ {source.title || source.link}
</a>
</div>
- <h4 className="mb-1.5 mt-0 text-xs text-text-primary md:text-sm">
- {source.title || source.link}
- </h4>
{'snippet' in source && source.snippet && (
- <span className="my-2 text-ellipsis break-all text-xs text-text-secondary md:text-sm">
+ <p className="line-clamp-4 break-words text-xs text-text-secondary md:text-sm">
{source.snippet}
- </span>
+ </p>
)}
</div>
{'imageUrl' in source && source.imageUrl && (
- <div className="h-24 w-24 flex-shrink-0 overflow-hidden rounded-md">
+ <div className="size-24 shrink-0 overflow-hidden rounded-md">
<img
src={source.imageUrl}
alt={source.title || localize('com_sources_image_alt')}
- className="h-full w-full object-cover"
+ className="size-full object-cover"
/>
</div>
)}
@@ -298,10 +305,10 @@ const FileItem = React.memo(function FileItem({
<span className="truncate text-xs font-medium text-text-secondary">
{localize('com_sources_agent_file')}
</span>
- {!isLocalFile && <Download className="ml-auto h-3 w-3" aria-hidden="true" />}
+ {!isLocalFile && <Download className="ml-auto size-3" aria-hidden="true" />}
</div>
<div className="mt-1 min-w-0">
- <span className="line-clamp-2 break-all text-left text-sm font-medium text-text-primary md:line-clamp-3">
+ <span className="line-clamp-2 break-words text-left text-sm font-medium text-text-primary md:line-clamp-3">
{file.filename}
</span>
{file.pages && file.pages.length > 0 && (
@@ -337,10 +344,10 @@ const FileItem = React.memo(function FileItem({
<span className="truncate text-xs font-medium text-text-secondary">
{localize('com_sources_agent_file')}
</span>
- {!isLocalFile && <Download className="ml-auto h-3 w-3" aria-hidden="true" />}
+ {!isLocalFile && <Download className="ml-auto size-3" aria-hidden="true" />}
</div>
<div className="mt-1 min-w-0">
- <span className="line-clamp-2 break-all text-left text-sm font-medium text-text-primary md:line-clamp-3">
+ <span className="line-clamp-2 break-words text-left text-sm font-medium text-text-primary md:line-clamp-3">
{file.filename}
</span>
{file.pages && file.pages.length > 0 && (
@@ -428,7 +435,7 @@ const SourcesGroup = React.memo(function SourcesGroup({
className="rounded-full p-1 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"
aria-label={localize('com_ui_close')}
>
- <X className="h-4 w-4" aria-hidden="true" />
+ <X className="size-4" aria-hidden="true" />
</OGDialogClose>
</div>
<div className="flex-1 overflow-y-auto px-3 py-2">
@@ -506,7 +513,7 @@ function FilesGroup({ files, messageId, conversationId, limit = 3 }: FilesGroupP
<div className="flex items-center gap-2">
<div className="relative flex">
{remainingFiles.slice(0, 3).map((_, i) => (
- <File key={`file-icon-${i}`} className={`h-4 w-4 ${i > 0 ? 'ml-[-6px]' : ''}`} />
+ <File key={`file-icon-${i}`} className={`size-4 ${i > 0 ? 'ml-[-6px]' : ''}`} />
))}
</div>
<span className="truncate text-xs font-medium text-text-secondary">
@@ -524,7 +531,7 @@ function FilesGroup({ files, messageId, conversationId, limit = 3 }: FilesGroupP
className="rounded-full p-1 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"
aria-label={localize('com_ui_close')}
>
- <X className="h-4 w-4" aria-hidden="true" />
+ <X className="size-4" aria-hidden="true" />
</OGDialogClose>
</div>
<div className="flex-1 overflow-y-auto px-3 py-2">
diff --git a/client/src/components/Web/__tests__/Citation.test.tsx b/client/src/components/Web/__tests__/Citation.test.tsx
new file mode 100644
index 0000000000..6ec16d4c04
--- /dev/null
+++ b/client/src/components/Web/__tests__/Citation.test.tsx
@@ -0,0 +1,145 @@
+import React from 'react';
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import type { SearchResultData } from 'librechat-data-provider';
+import { Citation, CompositeCitation } from '~/components/Web/Citation';
+import { CitationContext } from '~/components/Web/Context';
+import { SearchContext } from '~/Providers';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, values?: { label?: string; pages?: string }) => {
+ if (key === 'com_citation_source') {
+ return 'Source';
+ }
+ if (key === 'com_citation_more_details') {
+ return `More details about ${values?.label ?? ''}`;
+ }
+ if (key === 'com_ui_relevance') {
+ return 'Relevance';
+ }
+ if (key === 'com_file_pages') {
+ return `Pages: ${values?.pages ?? ''}`;
+ }
+ if (key === 'com_file_source') {
+ return 'File source';
+ }
+ return key;
+ },
+}));
+
+jest.mock('~/components/Chat/Messages/Content/FilePreviewDialog', () => ({
+ __esModule: true,
+ default: ({ open, fileId, fileName }: { open: boolean; fileId?: string; fileName: string }) =>
+ open ? (
+ <div data-testid="file-preview-dialog" data-file-id={fileId}>
+ {fileName}
+ </div>
+ ) : null,
+}));
+
+jest.mock('@librechat/client', () => ({
+ Button: ({ children, onClick, ...props }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button onClick={onClick} {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+function renderWithProviders(
+ children: React.ReactNode,
+ searchResults: Record<string, SearchResultData>,
+) {
+ return render(
+ <SearchContext.Provider value={{ searchResults }}>
+ <CitationContext.Provider
+ value={{
+ hoveredCitationId: null,
+ setHoveredCitationId: jest.fn(),
+ }}
+ >
+ {children}
+ </CitationContext.Provider>
+ </SearchContext.Provider>,
+ );
+}
+
+describe('Citation', () => {
+ it('renders composite file citations as buttons and opens the preview dialog', () => {
+ const searchResults = {
+ '0': {
+ references: [
+ {
+ attribution: 'Tutorial Imazing.pdf',
+ fileId: 'file-123',
+ fileName: 'Tutorial Imazing.pdf',
+ link: '#file-123',
+ metadata: {
+ fileBytes: 2048,
+ fileType: 'application/pdf',
+ },
+ pageRelevance: { 1: 0.92 },
+ pages: [1],
+ relevance: 0.92,
+ title: 'Tutorial Imazing.pdf',
+ type: 'file',
+ },
+ ],
+ },
+ };
+
+ renderWithProviders(
+ <CompositeCitation
+ node={{
+ properties: {
+ citationId: 'cite-1',
+ citations: [{ turn: 0, refType: 'file', index: 0 }],
+ },
+ }}
+ />,
+ searchResults as any,
+ );
+
+ const fileButton = screen.getByRole('button', { name: 'Tutorial Imazing.pdf' });
+
+ expect(fileButton).toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Tutorial Imazing.pdf' })).not.toBeInTheDocument();
+
+ fireEvent.click(fileButton);
+
+ expect(screen.getByTestId('file-preview-dialog')).toHaveAttribute('data-file-id', 'file-123');
+ });
+
+ it('keeps standalone web citations as links', () => {
+ const searchResults = {
+ '0': {
+ organic: [
+ {
+ attribution: 'example.com',
+ link: 'https://example.com',
+ snippet: 'Example snippet',
+ title: 'Example',
+ },
+ ],
+ },
+ };
+
+ renderWithProviders(
+ <Citation
+ citationId="cite-2"
+ citationType="standalone"
+ node={{
+ properties: {
+ citation: { turn: 0, refType: 'search', index: 0 },
+ citationId: 'cite-2',
+ },
+ }}
+ />,
+ searchResults as any,
+ );
+
+ expect(screen.getByRole('link', { name: 'example.com' })).toHaveAttribute(
+ 'href',
+ 'https://example.com',
+ );
+ });
+});
diff --git a/client/src/hooks/MCP/index.ts b/client/src/hooks/MCP/index.ts
index 705ca58910..b53003f3ce 100644
--- a/client/src/hooks/MCP/index.ts
+++ b/client/src/hooks/MCP/index.ts
@@ -1,5 +1,7 @@
-export * from './useMCPConnectionStatus';
export * from './useMCPSelect';
export * from './useVisibleTools';
export * from './useMCPServerManager';
+export * from './useMCPConnectionStatus';
+
+export { useMCPIconMap } from './useMCPIconMap';
export { useRemoveMCPTool } from './useRemoveMCPTool';
diff --git a/client/src/hooks/MCP/useMCPIconMap.ts b/client/src/hooks/MCP/useMCPIconMap.ts
new file mode 100644
index 0000000000..43f109b68c
--- /dev/null
+++ b/client/src/hooks/MCP/useMCPIconMap.ts
@@ -0,0 +1,19 @@
+import { useMemo } from 'react';
+import { useMCPServersQuery } from '~/data-provider';
+
+export function useMCPIconMap(): Map<string, string> {
+ const { data: servers } = useMCPServersQuery();
+
+ return useMemo(() => {
+ const map = new Map<string, string>();
+ if (!servers) {
+ return map;
+ }
+ for (const [serverName, config] of Object.entries(servers)) {
+ if (config.iconPath) {
+ map.set(serverName, config.iconPath);
+ }
+ }
+ return map;
+ }, [servers]);
+}
diff --git a/client/src/hooks/Messages/index.ts b/client/src/hooks/Messages/index.ts
index a3fa65b133..a78a1ef553 100644
--- a/client/src/hooks/Messages/index.ts
+++ b/client/src/hooks/Messages/index.ts
@@ -1,10 +1,12 @@
export { default as useProgress } from './useProgress';
+export { EXPAND_TRANSITION } from './useExpandCollapse';
export { default as useAttachments } from './useAttachments';
export { default as useSubmitMessage } from './useSubmitMessage';
+export type { ContentMetadataResult } from './useContentMetadata';
+export { default as useExpandCollapse } from './useExpandCollapse';
export { default as useMessageActions } from './useMessageActions';
export { default as useMessageProcess } from './useMessageProcess';
export { default as useMessageHelpers } from './useMessageHelpers';
export { default as useCopyToClipboard } from './useCopyToClipboard';
-export { default as useMessageScrolling } from './useMessageScrolling';
export { default as useContentMetadata } from './useContentMetadata';
-export type { ContentMetadataResult } from './useContentMetadata';
+export { default as useMessageScrolling } from './useMessageScrolling';
diff --git a/client/src/hooks/Messages/useExpandCollapse.ts b/client/src/hooks/Messages/useExpandCollapse.ts
new file mode 100644
index 0000000000..dc298c7f6c
--- /dev/null
+++ b/client/src/hooks/Messages/useExpandCollapse.ts
@@ -0,0 +1,37 @@
+import { useRef, useLayoutEffect, useMemo } from 'react';
+import type { CSSProperties } from 'react';
+
+export const EXPAND_TRANSITION =
+ 'grid-template-rows 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1)';
+
+export default function useExpandCollapse(isExpanded: boolean): {
+ style: CSSProperties;
+ ref: React.RefObject<HTMLDivElement>;
+} {
+ const ref = useRef<HTMLDivElement>(null);
+
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) {
+ return;
+ }
+
+ if (isExpanded) {
+ el.removeAttribute('inert');
+ } else {
+ el.setAttribute('inert', '');
+ }
+ }, [isExpanded]);
+
+ const style = useMemo<CSSProperties>(
+ () => ({
+ display: 'grid',
+ gridTemplateRows: isExpanded ? '1fr' : '0fr',
+ transition: EXPAND_TRANSITION,
+ opacity: isExpanded ? 1 : 0,
+ }),
+ [isExpanded],
+ );
+
+ return { style, ref };
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 89cc21abc7..db194b9066 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -104,7 +104,6 @@
"com_agents_start_chat": "Start Chat",
"com_agents_top_picks": "Top Picks",
"com_agents_update_error": "There was an error updating your agent.",
- "com_assistants_action_attempt": "Assistant wants to talk to {{0}}",
"com_assistants_actions": "Actions",
"com_assistants_actions_disabled": "You need to create an assistant before adding actions.",
"com_assistants_actions_info": "Let your Assistant retrieve information or take actions via API's",
@@ -114,7 +113,6 @@
"com_assistants_allow_sites_you_trust": "Only allow sites you trust.",
"com_assistants_append_date": "Append Current Date & Time",
"com_assistants_append_date_tooltip": "When enabled, the current client date and time will be appended to the assistant system instructions.",
- "com_assistants_attempt_info": "Assistant wants to send the following:",
"com_assistants_available_actions": "Available Actions",
"com_assistants_capabilities": "Capabilities",
"com_assistants_code_interpreter": "Code Interpreter",
@@ -129,7 +127,6 @@
"com_assistants_delete_actions_error": "There was an error deleting the action.",
"com_assistants_delete_actions_success": "Successfully deleted Action from Assistant",
"com_assistants_description_placeholder": "Optional: Describe your Assistant here",
- "com_assistants_domain_info": "Assistant sent this info to {{0}}",
"com_assistants_file_search": "File Search",
"com_assistants_file_search_info": "File search enables the assistant with knowledge from files that you or your users upload. Once a file is uploaded, the assistant automatically decides when to retrieve content based on user requests. Attaching vector stores for File Search is not yet supported. You can attach them from the Provider Playground or attach files to messages for file search on a thread basis.",
"com_assistants_function_use": "Assistant used {{0}}",
@@ -411,6 +408,7 @@
"com_nav_at_command_description": "Toggle command \"@\" for switching endpoints, models, presets, etc.",
"com_nav_audio_play_error": "Error playing audio: {{0}}",
"com_nav_audio_process_error": "Error processing audio: {{0}}",
+ "com_nav_auto_expand_tools": "Auto-expand tool details",
"com_nav_auto_scroll": "Auto-Scroll to latest message on chat open",
"com_nav_auto_send_prompts": "Send prompts on select",
"com_nav_auto_send_prompts_desc": "Automatically submit prompt to chat when selected",
@@ -587,7 +585,6 @@
"com_nav_setting_speech": "Speech",
"com_nav_settings": "Settings",
"com_nav_shared_links": "Shared links",
- "com_nav_show_code": "Always show code when using code interpreter",
"com_nav_show_thinking": "Open Thinking Dropdowns by Default",
"com_nav_slash_command": "/-Command",
"com_nav_slash_command_description": "Toggle command \"/\" for selecting a prompt via keyboard",
@@ -839,6 +836,7 @@
"com_ui_collapse_thoughts": "Collapse Thoughts",
"com_ui_command_placeholder": "Optional: Enter a command for the prompt or name will be used",
"com_ui_command_usage_placeholder": "Select a Prompt by command or name",
+ "com_ui_complete": "Complete!",
"com_ui_complete_setup": "Complete Setup",
"com_ui_concise": "Concise",
"com_ui_configure": "Configure",
@@ -912,6 +910,7 @@
"com_ui_date_yesterday": "Yesterday",
"com_ui_decline": "I do not accept",
"com_ui_default_post_request": "Default (POST request)",
+ "com_ui_details": "Details",
"com_ui_delete": "Delete",
"com_ui_delete_action": "Delete Action",
"com_ui_delete_action_confirm": "Are you sure you want to delete this action?",
@@ -1009,8 +1008,10 @@
"com_ui_feedback_tag_not_matched": "Didn't match my request",
"com_ui_feedback_tag_other": "Other issue",
"com_ui_feedback_tag_unjustified_refusal": "Refused without reason",
+ "com_ui_failed": "Failed",
"com_ui_field_max_length": "{{field}} must be less than {{length}} characters",
"com_ui_field_required": "This field is required",
+ "com_ui_file": "File",
"com_ui_file_input_avatar_label": "File input for avatar",
"com_ui_file_size": "File Size",
"com_ui_file_token_limit": "File Token Limit",
@@ -1050,6 +1051,7 @@
"com_ui_fork_visible": "Visible messages only",
"com_ui_generate_qrcode": "Generate QR Code",
"com_ui_generating": "Generating...",
+ "com_ui_generating_image": "Generating image...",
"com_ui_generation_settings": "Generation Settings",
"com_ui_getting_started": "Getting Started",
"com_ui_global_group": "Global prompt",
@@ -1075,6 +1077,7 @@
"com_ui_image_details": "Image Details",
"com_ui_image_edited": "Image edited",
"com_ui_image_gen": "Image Gen",
+ "com_ui_image_gen_failed": "Image generation failed",
"com_ui_import": "Import",
"com_ui_import_conversation_error": "There was an error importing your conversations",
"com_ui_import_conversation_file_type_error": "Unsupported import type",
@@ -1200,10 +1203,12 @@
"com_ui_my_prompts": "My Prompts",
"com_ui_name": "Name",
"com_ui_name_sort": "Sort by Name",
+ "com_ui_navigate_results": "Navigate results",
"com_ui_new": "New",
"com_ui_new_chat": "New chat",
"com_ui_new_conversation_title": "New Conversation Title",
"com_ui_next": "Next",
+ "com_ui_next_result": "Next result",
"com_ui_no": "No",
"com_ui_no_api_keys": "No API keys yet. Create one to get started.",
"com_ui_no_auth": "None (Auto-detect)",
@@ -1249,6 +1254,7 @@
"com_ui_openai": "OpenAI",
"com_ui_optional": "(optional)",
"com_ui_options": "options",
+ "com_ui_output": "Output",
"com_ui_page": "Page",
"com_ui_pagination": "Pagination",
"com_ui_people": "people",
@@ -1262,7 +1268,9 @@
"com_ui_pin": "Pin",
"com_ui_preferences_updated": "Preferences updated successfully",
"com_ui_prev": "Prev",
+ "com_ui_prev_result": "Previous result",
"com_ui_preview": "Preview",
+ "com_ui_preview_unavailable": "Preview not available for this file type",
"com_ui_privacy_policy": "Privacy policy",
"com_ui_privacy_policy_url": "Privacy Policy URL",
"com_ui_production": "Production",
@@ -1298,6 +1306,7 @@
"com_ui_reference_saved_memories": "Reference saved memories",
"com_ui_reference_saved_memories_description": "Allow the assistant to reference and use your saved memories when responding",
"com_ui_refresh": "Refresh",
+ "com_ui_relevance": "Relevance",
"com_ui_refresh_link": "Refresh link",
"com_ui_refresh_page": "Refresh page",
"com_ui_regenerate": "Regenerate",
@@ -1334,6 +1343,7 @@
"com_ui_result": "Result",
"com_ui_result_found": "{{count}} result found",
"com_ui_results_found": "{{count}} results found",
+ "com_ui_retrieved_files": "Searched your files",
"com_ui_retry": "Retry",
"com_ui_revoke": "Revoke",
"com_ui_revoke_info": "Revoke all user provided credentials",
@@ -1358,6 +1368,7 @@
"com_ui_rotate_90": "Rotate 90 degrees",
"com_ui_run_code": "Run Code",
"com_ui_run_code_error": "There was an error running the code",
+ "com_ui_running": "Running...",
"com_ui_save": "Save",
"com_ui_save_badge_changes": "Save badge changes?",
"com_ui_save_changes": "Save Changes",
@@ -1377,6 +1388,7 @@
"com_ui_search_people_placeholder": "Search for people or groups by name or email",
"com_ui_search_result_count": "{{count}} result found",
"com_ui_search_results_count": "{{count}} results found",
+ "com_ui_searching_files": "Searching your files",
"com_ui_seconds": "seconds",
"com_ui_secret_key": "Secret Key",
"com_ui_select": "Select",
@@ -1412,6 +1424,8 @@
"com_ui_show_all": "Show All",
"com_ui_show_code": "Show Code",
"com_ui_show_image_details": "Show Image Details",
+ "com_ui_show_less": "Show less",
+ "com_ui_show_more": "Show more",
"com_ui_show_password": "Show password",
"com_ui_show_qr": "Show QR Code",
"com_ui_sign_in_to_domain": "Sign-in to {{0}}",
@@ -1459,9 +1473,16 @@
"com_ui_token_exchange_method": "Token Exchange Method",
"com_ui_token_url": "Token URL",
"com_ui_tokens": "tokens",
+ "com_ui_tool_failed": "failed",
"com_ui_tool_collection_prefix": "A collection of tools from",
"com_ui_tool_list_collapse": "Collapse {{serverName}} tool list",
"com_ui_tool_list_expand": "Expand {{serverName}} tool list",
+ "com_ui_tool_name_code": "Code",
+ "com_ui_tool_name_code_analysis": "Code Analysis",
+ "com_ui_tool_name_file_search": "File Search",
+ "com_ui_tool_name_image_edit": "Image Edit",
+ "com_ui_tool_name_image_gen": "Image Generation",
+ "com_ui_tool_name_web_search": "Web Search",
"com_ui_tools": "Tools",
"com_ui_tools_and_actions": "Tools and Actions",
"com_ui_transferred_to": "Transferred to",
@@ -1470,7 +1491,6 @@
"com_ui_try_adjusting_search": "Try adjusting your search terms",
"com_ui_ui_resource_error": "UI Resource Error ({{0}})",
"com_ui_ui_resource_not_found": "UI Resource not found (index: {{0}})",
- "com_ui_ui_resources": "UI Resources",
"com_ui_unarchive": "Unarchive",
"com_ui_unarchive_conversation": "Unarchive conversation",
"com_ui_unarchive_error": "Failed to unarchive conversation",
@@ -1508,12 +1528,15 @@
"com_ui_use_micrphone": "Use microphone",
"com_ui_use_prompt": "Use Prompt",
"com_ui_used": "Used",
+ "com_ui_used_n_tools": "Used {{0}} tools",
+ "com_ui_parameters": "Parameters",
"com_ui_user": "User",
"com_ui_user_group_permissions": "User & Group Permissions",
"com_ui_user_provides_key": "Each user provides their own key",
"com_ui_value": "Value",
"com_ui_variables": "Variables",
"com_ui_variable_with_options": "{{name}} variable with {{count}} options",
+ "com_ui_via_server": "in {{0}}",
"com_ui_verify": "Verify",
"com_ui_version_var": "Version {{0}}",
"com_ui_versions": "Versions",
@@ -1542,6 +1565,9 @@
"com_ui_web_search_scraper_serper_key": "Get your Serper API key",
"com_ui_web_search_searxng_api_key": "Enter SearXNG API Key (optional)",
"com_ui_web_search_searxng_instance_url": "SearXNG Instance URL",
+ "com_ui_web_search_source": "{{count}} source",
+ "com_ui_web_search_sources": "{{count}} sources",
+ "com_ui_web_searched": "Searched the web",
"com_ui_web_searching": "Searching the web",
"com_ui_web_searching_again": "Searching the web again",
"com_ui_weekend_morning": "Happy weekend",
diff --git a/client/src/store/settings.ts b/client/src/store/settings.ts
index cad3b4a151..2a2796ad59 100644
--- a/client/src/store/settings.ts
+++ b/client/src/store/settings.ts
@@ -31,7 +31,7 @@ const localStorageAtoms = {
enterToSend: atomWithLocalStorage('enterToSend', true),
maximizeChatSpace: atomWithLocalStorage('maximizeChatSpace', false),
chatDirection: atomWithLocalStorage('chatDirection', 'LTR'),
- showCode: atomWithLocalStorage(LocalStorageKeys.SHOW_ANALYSIS_CODE, true),
+ autoExpandTools: atomWithLocalStorage(LocalStorageKeys.AUTO_EXPAND_TOOLS, false),
saveDrafts: atomWithLocalStorage('saveDrafts', true),
showScrollButton: atomWithLocalStorage('showScrollButton', true),
forkSetting: atomWithLocalStorage('forkSetting', ''),
diff --git a/client/src/style.css b/client/src/style.css
index cf3ea50294..e934d241c1 100644
--- a/client/src/style.css
+++ b/client/src/style.css
@@ -1259,7 +1259,7 @@ code[class*='language-'],
pre[class*='language-'] {
word-wrap: normal;
background: none;
- color: #fff;
+ color: var(--gray-800);
-webkit-hyphens: none;
hyphens: none;
font-size: 0.85rem;
@@ -1281,27 +1281,27 @@ pre[class*='language-'] {
white-space: normal;
}
.hljs-comment {
- color: hsla(0, 0%, 100%, 0.5);
+ color: var(--gray-500);
}
.hljs-meta {
- color: hsla(0, 0%, 100%, 0.6);
+ color: var(--gray-600);
}
.hljs-built_in,
.hljs-class .hljs-title {
- color: #e9950c;
+ color: #9a6700;
}
.hljs-doctag,
.hljs-formula,
.hljs-keyword,
.hljs-literal {
- color: #2e95d3;
+ color: #0550ae;
}
.hljs-addition,
.hljs-attribute,
.hljs-meta-string,
.hljs-regexp,
.hljs-string {
- color: #00a67d;
+ color: #0a7b62;
}
.hljs-attr,
.hljs-number,
@@ -1311,13 +1311,58 @@ pre[class*='language-'] {
.hljs-template-variable,
.hljs-type,
.hljs-variable {
- color: #df3079;
+ color: #9a2f6a;
}
.hljs-bullet,
.hljs-link,
.hljs-selector-id,
.hljs-symbol,
.hljs-title {
+ color: #b42318;
+}
+.dark code.hljs,
+.dark code[class*='language-'],
+.dark pre[class*='language-'] {
+ color: #fff;
+}
+.dark .hljs-comment {
+ color: hsla(0, 0%, 100%, 0.5);
+}
+.dark .hljs-meta {
+ color: hsla(0, 0%, 100%, 0.6);
+}
+.dark .hljs-built_in,
+.dark .hljs-class .hljs-title {
+ color: #e9950c;
+}
+.dark .hljs-doctag,
+.dark .hljs-formula,
+.dark .hljs-keyword,
+.dark .hljs-literal {
+ color: #2e95d3;
+}
+.dark .hljs-addition,
+.dark .hljs-attribute,
+.dark .hljs-meta-string,
+.dark .hljs-regexp,
+.dark .hljs-string {
+ color: #00a67d;
+}
+.dark .hljs-attr,
+.dark .hljs-number,
+.dark .hljs-selector-attr,
+.dark .hljs-selector-class,
+.dark .hljs-selector-pseudo,
+.dark .hljs-template-variable,
+.dark .hljs-type,
+.dark .hljs-variable {
+ color: #df3079;
+}
+.dark .hljs-bullet,
+.dark .hljs-link,
+.dark .hljs-selector-id,
+.dark .hljs-symbol,
+.dark .hljs-title {
color: #f22c3d;
}
@@ -2532,7 +2577,7 @@ html {
}
.message-content pre code {
- font-size: calc(0.85 * var(--markdown-font-size, var(--font-size-base)));
+ font-size: calc(0.9 * var(--markdown-font-size, var(--font-size-base)));
}
.message-content pre {
@@ -2541,7 +2586,7 @@ html {
.code-analyze-block pre code,
.code-analyze-block .overflow-y-auto code {
- font-size: calc(0.85 * var(--markdown-font-size, var(--font-size-base)));
+ font-size: calc(0.9 * var(--markdown-font-size, var(--font-size-base)));
}
.code-analyze-block pre,
@@ -2549,9 +2594,14 @@ html {
font-size: var(--markdown-font-size, var(--font-size-base));
}
+.tool-status-text {
+ font-size: calc(0.9 * var(--markdown-font-size, var(--font-size-base)));
+ line-height: calc(1.25 * 0.9 * var(--markdown-font-size, var(--font-size-base)));
+}
+
.progress-text-wrapper {
- font-size: var(--markdown-font-size, var(--font-size-base));
- line-height: calc(1.25 * var(--markdown-font-size, var(--font-size-base)));
+ font-size: calc(0.9 * var(--markdown-font-size, var(--font-size-base)));
+ line-height: calc(1.25 * 0.9 * var(--markdown-font-size, var(--font-size-base)));
}
.progress-text-content {
diff --git a/client/src/utils/__tests__/scaleImage.test.ts b/client/src/utils/__tests__/scaleImage.test.ts
new file mode 100644
index 0000000000..95bdcf135c
--- /dev/null
+++ b/client/src/utils/__tests__/scaleImage.test.ts
@@ -0,0 +1,89 @@
+import { scaleImage } from '~/utils/scaleImage';
+import type { RefObject } from 'react';
+
+function makeContainerRef(clientWidth: number): RefObject<HTMLDivElement> {
+ return {
+ current: { clientWidth } as HTMLDivElement,
+ };
+}
+
+const originalInnerHeight = window.innerHeight;
+
+beforeEach(() => {
+ Object.defineProperty(window, 'innerHeight', { value: 1000, writable: true });
+});
+
+afterEach(() => {
+ Object.defineProperty(window, 'innerHeight', { value: originalInnerHeight, writable: true });
+});
+
+describe('scaleImage', () => {
+ it('returns auto dimensions when containerRef is null', () => {
+ const result = scaleImage({
+ originalWidth: 1024,
+ originalHeight: 1024,
+ containerRef: { current: null },
+ });
+ expect(result).toEqual({ width: 'auto', height: 'auto' });
+ });
+
+ it('scales a square image to fit container width, clamped by max height', () => {
+ // container=512, but 512px height exceeds 45vh (450px), so clamped
+ const result = scaleImage({
+ originalWidth: 1024,
+ originalHeight: 1024,
+ containerRef: makeContainerRef(512),
+ });
+ expect(result).toEqual({ width: '450px', height: '450px' });
+ });
+
+ it('scales to container width when height stays within max', () => {
+ const result = scaleImage({
+ originalWidth: 1024,
+ originalHeight: 1024,
+ containerRef: makeContainerRef(300),
+ });
+ expect(result).toEqual({ width: '300px', height: '300px' });
+ });
+
+ it('does not upscale when container is wider than the image', () => {
+ const result = scaleImage({
+ originalWidth: 256,
+ originalHeight: 256,
+ containerRef: makeContainerRef(800),
+ });
+ expect(result).toEqual({ width: '256px', height: '256px' });
+ });
+
+ it('constrains height to 45vh and adjusts width by aspect ratio', () => {
+ // window.innerHeight = 1000, so maxHeight = 450
+ const result = scaleImage({
+ originalWidth: 500,
+ originalHeight: 1000,
+ containerRef: makeContainerRef(600),
+ });
+ // container fits 500px width → height would be 1000, exceeds 450
+ // clamp: height=450, width=450*(500/1000)=225
+ expect(result).toEqual({ width: '225px', height: '450px' });
+ });
+
+ it('handles landscape images correctly', () => {
+ const result = scaleImage({
+ originalWidth: 1920,
+ originalHeight: 1080,
+ containerRef: makeContainerRef(800),
+ });
+ // width clamped to 800, height = 800 / (1920/1080) = 450, exactly maxHeight
+ expect(result).toEqual({ width: '800px', height: '450px' });
+ });
+
+ it('handles very wide panoramic images', () => {
+ const result = scaleImage({
+ originalWidth: 4000,
+ originalHeight: 500,
+ containerRef: makeContainerRef(600),
+ });
+ // width clamped to 600, height = 600 / (4000/500) = 75, well under maxHeight
+ expect(result).toEqual({ width: '600px', height: '75px' });
+ });
+});
diff --git a/client/src/utils/files.ts b/client/src/utils/files.ts
index be81a31b79..536b340bf3 100644
--- a/client/src/utils/files.ts
+++ b/client/src/utils/files.ts
@@ -317,3 +317,13 @@ export const validateFiles = ({
return true;
};
+
+export function sortPagesByRelevance(
+ pages: number[],
+ pageRelevance: Record<number, number>,
+): number[] {
+ if (!pageRelevance || Object.keys(pageRelevance).length === 0) {
+ return pages;
+ }
+ return [...pages].sort((a, b) => (pageRelevance[b] || 0) - (pageRelevance[a] || 0));
+}
diff --git a/client/src/utils/groupToolCalls.ts b/client/src/utils/groupToolCalls.ts
new file mode 100644
index 0000000000..406b686aad
--- /dev/null
+++ b/client/src/utils/groupToolCalls.ts
@@ -0,0 +1,51 @@
+import { Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
+import type { TMessageContentParts, Agents } from 'librechat-data-provider';
+import type { PartWithIndex } from '~/components/Chat/Messages/Content/ParallelContent';
+
+export type GroupedPart =
+ | { type: 'single'; part: PartWithIndex }
+ | { type: 'tool-group'; parts: PartWithIndex[] };
+
+function isGroupableToolCall(part: TMessageContentParts): boolean {
+ if (part.type !== ContentTypes.TOOL_CALL) {
+ return false;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined;
+ if (!toolCall) {
+ return false;
+ }
+ const isStandardToolCall =
+ 'args' in toolCall && (!toolCall.type || toolCall.type === ToolCallTypes.TOOL_CALL);
+ if (isStandardToolCall && toolCall.name?.startsWith(Constants.LC_TRANSFER_TO_)) {
+ return false;
+ }
+ return true;
+}
+
+export function groupSequentialToolCalls(parts: PartWithIndex[]): GroupedPart[] {
+ const result: GroupedPart[] = [];
+ let currentGroup: PartWithIndex[] = [];
+
+ const flushGroup = () => {
+ if (currentGroup.length >= 2) {
+ result.push({ type: 'tool-group', parts: [...currentGroup] });
+ } else {
+ for (const p of currentGroup) {
+ result.push({ type: 'single', part: p });
+ }
+ }
+ currentGroup = [];
+ };
+
+ for (const item of parts) {
+ if (isGroupableToolCall(item.part)) {
+ currentGroup.push(item);
+ } else {
+ flushGroup();
+ result.push({ type: 'single', part: item });
+ }
+ }
+ flushGroup();
+
+ return result;
+}
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index 468bc9444c..bba6b5dc78 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -3,31 +3,33 @@ import type { UIActionResult } from '@mcp-ui/client';
import { TAskFunction } from '~/common';
import logger from './logger';
-export * from './errors';
export * from './map';
export * from './json';
+export * from './email';
+export * from './share';
export * from './files';
export * from './latex';
export * from './forms';
+export * from './roles';
+export * from './errors';
export * from './agents';
export * from './drafts';
export * from './convos';
export * from './routes';
-export * from './redirect';
export * from './presets';
export * from './prompts';
export * from './textarea';
export * from './messages';
+export * from './redirect';
export * from './languages';
export * from './endpoints';
export * from './resources';
-export * from './roles';
+export * from './scaleImage';
+export * from './timestamps';
export * from './localStorage';
export * from './promptGroups';
export * from './previewCache';
-export * from './email';
-export * from './share';
-export * from './timestamps';
+export * from './groupToolCalls';
export { default as cn } from './cn';
export { default as logger } from './logger';
export { default as getLoginError } from './getLoginError';
diff --git a/client/src/utils/scaleImage.ts b/client/src/utils/scaleImage.ts
new file mode 100644
index 0000000000..fb0f2604d7
--- /dev/null
+++ b/client/src/utils/scaleImage.ts
@@ -0,0 +1,32 @@
+import type { RefObject } from 'react';
+
+const MAX_HEIGHT_VH = 0.45;
+
+export function scaleImage({
+ originalWidth,
+ originalHeight,
+ containerRef,
+}: {
+ originalWidth: number;
+ originalHeight: number;
+ containerRef: RefObject<HTMLDivElement | null>;
+}): { width: string; height: string } {
+ const container = containerRef.current;
+ if (!container) {
+ return { width: 'auto', height: 'auto' };
+ }
+
+ const containerWidth = container.clientWidth;
+ const maxHeight = window.innerHeight * MAX_HEIGHT_VH;
+ const aspectRatio = originalWidth / originalHeight;
+
+ let width = Math.min(originalWidth, containerWidth);
+ let height = width / aspectRatio;
+
+ if (height > maxHeight) {
+ height = maxHeight;
+ width = height * aspectRatio;
+ }
+
+ return { width: `${Math.round(width)}px`, height: `${Math.round(height)}px` };
+}
diff --git a/client/vite.config.ts b/client/vite.config.ts
index 58d4bc98f2..0422f8bd3d 100644
--- a/client/vite.config.ts
+++ b/client/vite.config.ts
@@ -273,6 +273,10 @@ export default defineConfig(({ command }) => ({
return 'headlessui';
}
+ if (normalizedId.includes('@icons-pack/react-simple-icons/icons/')) {
+ return;
+ }
+
// Everything else falls into a generic vendor chunk.
return 'vendor';
}
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 9bc3822c4b..e641d7b63a 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1857,8 +1857,8 @@ export enum LocalStorageKeys {
LAST_PROMPT_CATEGORY = 'lastPromptCategory',
/** Key for rendering User Messages as Markdown */
ENABLE_USER_MSG_MARKDOWN = 'enableUserMsgMarkdown',
- /** Key for displaying analysis tool code input */
- SHOW_ANALYSIS_CODE = 'showAnalysisCode',
+ /** Key for auto-expanding tool call details */
+ AUTO_EXPAND_TOOLS = 'autoExpandTools',
/** Last selected MCP values per conversation ID */
LAST_MCP_ = 'LAST_MCP_',
/** Last checked toggle for Code Interpreter API per conversation ID */