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: Download Code Blocks as Files (#13715)

Anubhav Anandd513e55a62bd
diff --git a/client/src/components/Messages/Content/ActionButton.tsx b/client/src/components/Messages/Content/ActionButton.tsx
new file mode 100644
index 0000000000..96f463bb20
--- /dev/null
+++ b/client/src/components/Messages/Content/ActionButton.tsx
@@ -0,0 +1,102 @@
+import React from 'react';
+import { Check } from 'lucide-react';
+import { TooltipAnchor } from '@librechat/client';
+import type { LucideIcon } from 'lucide-react';
+import cn from '~/utils/cn';
+
+interface ActionButtonProps {
+ icon: LucideIcon;
+ isActive: boolean;
+ label: string;
+ activeLabel: string;
+ iconOnly?: boolean;
+ onClick: () => void;
+ tabIndex?: number;
+ className?: string;
+ portalElement?: HTMLElement | null;
+}
+
+const ActionButton = React.forwardRef<HTMLButtonElement, ActionButtonProps>(
+ (
+ {
+ icon: Icon,
+ isActive,
+ label,
+ activeLabel,
+ iconOnly = false,
+ onClick,
+ tabIndex,
+ className,
+ portalElement,
+ },
+ ref,
+ ) => {
+ const currentLabel = isActive ? activeLabel : label;
+
+ 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',
+ className,
+ )}
+ >
+ <span className="relative flex size-[18px] items-center justify-center" aria-hidden="true">
+ <Icon
+ size={18}
+ className={cn(
+ 'absolute transition-all duration-300 ease-out',
+ isActive ? 'rotate-[-90deg] scale-0 opacity-0' : 'rotate-0 scale-100 opacity-100',
+ )}
+ />
+ <Check
+ size={18}
+ className={cn(
+ 'transition-all duration-300 ease-out',
+ isActive ? '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',
+ isActive ? '-translate-y-full opacity-0' : 'translate-y-0 opacity-100',
+ )}
+ >
+ {label}
+ </span>
+ <span
+ className={cn(
+ 'absolute inset-0 transition-all duration-300 ease-out',
+ isActive ? 'translate-y-0 opacity-100' : 'translate-y-full opacity-0',
+ )}
+ >
+ {activeLabel}
+ </span>
+ </span>
+ )}
+ </button>
+ );
+
+ if (iconOnly) {
+ return (
+ <TooltipAnchor description={currentLabel} portalElement={portalElement} render={button} />
+ );
+ }
+
+ return button;
+ },
+);
+
+ActionButton.displayName = 'ActionButton';
+
+export default ActionButton;
diff --git a/client/src/components/Messages/Content/CodeBar.tsx b/client/src/components/Messages/Content/CodeBar.tsx
index 1d8b7465b6..7dfc283c61 100644
--- a/client/src/components/Messages/Content/CodeBar.tsx
+++ b/client/src/components/Messages/Content/CodeBar.tsx
@@ -1,6 +1,8 @@
import React from 'react';
import { InfoIcon } from 'lucide-react';
import type { CodeBarProps } from '~/common';
+import useDownloadCode from '~/components/Messages/Content/useDownloadCode';
+import DownloadButton from '~/components/Messages/Content/DownloadButton';
import useCopyCode from '~/components/Messages/Content/useCopyCode';
import CopyButton from '~/components/Messages/Content/CopyButton';
import LangIcon from '~/components/Messages/Content/LangIcon';
@@ -11,6 +13,7 @@ const CodeBar: React.FC<CodeBarProps> = React.memo(
({ lang, error, codeRef, blockIndex, plugin = null, allowExecution = true }) => {
const localize = useLocalize();
const { isCopied, handleCopy } = useCopyCode(codeRef);
+ const { isDownloaded, handleDownload } = useDownloadCode(codeRef, lang);
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 [.user-turn_&]:bg-surface-code">
@@ -26,11 +29,20 @@ const CodeBar: React.FC<CodeBarProps> = React.memo(
<RunCode lang={lang} codeRef={codeRef} blockIndex={blockIndex} />
)}
{error !== true && (
- <CopyButton
- isCopied={isCopied}
- onClick={handleCopy}
- label={localize('com_ui_copy_code')}
- />
+ <>
+ <DownloadButton
+ isDownloaded={isDownloaded}
+ iconOnly
+ onClick={handleDownload}
+ label={localize('com_ui_download_code')}
+ />
+ <CopyButton
+ isCopied={isCopied}
+ iconOnly
+ onClick={handleCopy}
+ label={localize('com_ui_copy_code')}
+ />
+ </>
)}
</div>
)}
diff --git a/client/src/components/Messages/Content/CopyButton.tsx b/client/src/components/Messages/Content/CopyButton.tsx
index 96be2d0be3..1cbaf0d0ca 100644
--- a/client/src/components/Messages/Content/CopyButton.tsx
+++ b/client/src/components/Messages/Content/CopyButton.tsx
@@ -1,8 +1,7 @@
import React from 'react';
-import { Copy, Check } from 'lucide-react';
-import { TooltipAnchor } from '@librechat/client';
+import { Copy } from 'lucide-react';
+import ActionButton from '~/components/Messages/Content/ActionButton';
import { useLocalize } from '~/hooks';
-import cn from '~/utils/cn';
interface CopyButtonProps {
isCopied: boolean;
@@ -21,72 +20,21 @@ const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(
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
+ return (
+ <ActionButton
ref={ref}
- type="button"
+ icon={Copy}
+ isActive={isCopied}
+ label={label ?? localize('com_ui_copy')}
+ activeLabel={copiedLabel ?? localize('com_ui_copied')}
+ iconOnly={iconOnly}
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>
+ className={className}
+ portalElement={portalElement}
+ />
);
-
- if (iconOnly) {
- return (
- <TooltipAnchor description={currentLabel} portalElement={portalElement} render={button} />
- );
- }
-
- return button;
},
);
diff --git a/client/src/components/Messages/Content/DownloadButton.tsx b/client/src/components/Messages/Content/DownloadButton.tsx
new file mode 100644
index 0000000000..85cdf2a62c
--- /dev/null
+++ b/client/src/components/Messages/Content/DownloadButton.tsx
@@ -0,0 +1,41 @@
+import React from 'react';
+import { Download } from 'lucide-react';
+import ActionButton from '~/components/Messages/Content/ActionButton';
+import { useLocalize } from '~/hooks';
+
+interface DownloadButtonProps {
+ isDownloaded: boolean;
+ iconOnly?: boolean;
+ onClick: () => void;
+ tabIndex?: number;
+ className?: string;
+ label?: string;
+ downloadedLabel?: string;
+}
+
+const DownloadButton = React.forwardRef<HTMLButtonElement, DownloadButtonProps>(
+ (
+ { isDownloaded, iconOnly = false, onClick, tabIndex, className, label, downloadedLabel },
+ ref,
+ ) => {
+ const localize = useLocalize();
+
+ return (
+ <ActionButton
+ ref={ref}
+ icon={Download}
+ isActive={isDownloaded}
+ label={label ?? localize('com_ui_download')}
+ activeLabel={downloadedLabel ?? localize('com_ui_downloaded')}
+ iconOnly={iconOnly}
+ onClick={onClick}
+ tabIndex={tabIndex}
+ className={className}
+ />
+ );
+ },
+);
+
+DownloadButton.displayName = 'DownloadButton';
+
+export default DownloadButton;
diff --git a/client/src/components/Messages/Content/FloatingCodeBar.tsx b/client/src/components/Messages/Content/FloatingCodeBar.tsx
index 2929709309..08995c0383 100644
--- a/client/src/components/Messages/Content/FloatingCodeBar.tsx
+++ b/client/src/components/Messages/Content/FloatingCodeBar.tsx
@@ -1,6 +1,8 @@
import React from 'react';
import { InfoIcon } from 'lucide-react';
import type { CodeBarProps } from '~/common';
+import useDownloadCode from '~/components/Messages/Content/useDownloadCode';
+import DownloadButton from '~/components/Messages/Content/DownloadButton';
import useCopyCode from '~/components/Messages/Content/useCopyCode';
import CopyButton from '~/components/Messages/Content/CopyButton';
import RunCode from '~/components/Messages/Content/RunCode';
@@ -11,8 +13,13 @@ interface FloatingCodeBarProps extends CodeBarProps {
}
const FloatingCodeBar: React.FC<FloatingCodeBarProps> = React.memo(
- ({ lang, codeRef, blockIndex, plugin = null, allowExecution = true, isVisible }) => {
+ ({ lang, error, codeRef, blockIndex, plugin = null, allowExecution = true, isVisible }) => {
const { isCopied, buttonRef, handleCopy } = useCopyCode(codeRef);
+ const {
+ isDownloaded,
+ buttonRef: downloadButtonRef,
+ handleDownload,
+ } = useDownloadCode(codeRef, lang);
return (
<div
@@ -28,6 +35,15 @@ const FloatingCodeBar: React.FC<FloatingCodeBarProps> = React.memo(
{allowExecution === true && (
<RunCode lang={lang} codeRef={codeRef} blockIndex={blockIndex} iconOnly />
)}
+ {error !== true && (
+ <DownloadButton
+ ref={downloadButtonRef}
+ isDownloaded={isDownloaded}
+ iconOnly
+ tabIndex={isVisible ? 0 : -1}
+ onClick={handleDownload}
+ />
+ )}
<CopyButton
ref={buttonRef}
isCopied={isCopied}
diff --git a/client/src/components/Messages/Content/RunCode.tsx b/client/src/components/Messages/Content/RunCode.tsx
index 15c31bb85b..d8c8e36921 100644
--- a/client/src/components/Messages/Content/RunCode.tsx
+++ b/client/src/components/Messages/Content/RunCode.tsx
@@ -6,9 +6,9 @@ import { TerminalSquareIcon, Check, X } from 'lucide-react';
import { Spinner, TooltipAnchor, useToastContext } from '@librechat/client';
import type { CodeBarProps } from '~/common';
import { useToolCallMutation } from '~/data-provider';
-import { useLocalize } from '~/hooks';
import { cn, normalizeLanguage } from '~/utils';
import { useMessageContext } from '~/Providers';
+import { useLocalize } from '~/hooks';
import store from '~/store';
type RunState = 'idle' | 'loading' | 'success' | 'error';
@@ -119,7 +119,9 @@ const RunCode: React.FC<CodeBarProps & { iconOnly?: boolean }> = React.memo(
'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',
+ iconOnly
+ ? 'rounded-lg p-1.5'
+ : 'ml-auto gap-2 rounded-lg p-1.5 md:rounded-md md:px-2 md:py-1',
)}
>
<span className="relative flex size-[18px] items-center justify-center" aria-hidden="true">
@@ -136,7 +138,7 @@ const RunCode: React.FC<CodeBarProps & { iconOnly?: boolean }> = React.memo(
<X size={18} className={iconClass(isError)} />
</span>
{!iconOnly && (
- <span className="relative overflow-hidden">
+ <span className="relative hidden overflow-hidden md:block">
<span
className={cn(
'block whitespace-nowrap transition-all duration-300 ease-out',
@@ -174,7 +176,7 @@ const RunCode: React.FC<CodeBarProps & { iconOnly?: boolean }> = React.memo(
</button>
);
- return iconOnly ? <TooltipAnchor description={label} render={button} /> : button;
+ return <TooltipAnchor description={label} render={button} />;
},
);
diff --git a/client/src/components/Messages/Content/useDownloadCode.ts b/client/src/components/Messages/Content/useDownloadCode.ts
new file mode 100644
index 0000000000..b7447209b2
--- /dev/null
+++ b/client/src/components/Messages/Content/useDownloadCode.ts
@@ -0,0 +1,38 @@
+import { useRef, useState, useCallback, useEffect } from 'react';
+import { getCodeBlockFilename, triggerDownload } from '~/utils';
+
+export default function useDownloadCode(
+ codeRef: React.RefObject<HTMLElement | null>,
+ lang?: string,
+) {
+ const [isDownloaded, setIsDownloaded] = useState(false);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ const timerRef = useRef<ReturnType<typeof setTimeout>>();
+
+ useEffect(() => {
+ return () => clearTimeout(timerRef.current);
+ }, []);
+
+ const handleDownload = useCallback(() => {
+ const codeString = codeRef.current?.textContent;
+ if (codeString == null || codeString === '') {
+ return;
+ }
+
+ const wasFocused = document.activeElement === buttonRef.current;
+ setIsDownloaded(true);
+ const blob = new Blob([codeString], { type: 'text/plain' });
+ triggerDownload(URL.createObjectURL(blob), getCodeBlockFilename(lang));
+
+ if (wasFocused) {
+ requestAnimationFrame(() => buttonRef.current?.focus());
+ }
+
+ clearTimeout(timerRef.current);
+ timerRef.current = setTimeout(() => {
+ setIsDownloaded(false);
+ }, 3000);
+ }, [codeRef, lang]);
+
+ return { isDownloaded, buttonRef, handleDownload };
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 91eb780e29..1b3b800f1f 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1156,8 +1156,10 @@
"com_ui_download_artifact": "Download Artifact",
"com_ui_download_backup": "Download Backup Codes",
"com_ui_download_backup_tooltip": "Before you continue, download your backup codes. You will need them to regain access if you lose your authenticator device",
+ "com_ui_download_code": "Download code",
"com_ui_download_error": "Error downloading file. The file may have been deleted.",
"com_ui_download_error_logs": "Download error logs",
+ "com_ui_downloaded": "Downloaded!",
"com_ui_drag_drop": "Drop any file here to add it to the conversation",
"com_ui_dropdown_variables": "Dropdown variables:",
"com_ui_duplicate": "Duplicate",
diff --git a/client/src/utils/__tests__/downloadFile.test.ts b/client/src/utils/__tests__/downloadFile.test.ts
index 9b80b2c424..ed11c3df85 100644
--- a/client/src/utils/__tests__/downloadFile.test.ts
+++ b/client/src/utils/__tests__/downloadFile.test.ts
@@ -1,4 +1,4 @@
-import { isHttpDownloadTarget, triggerDownload } from '../downloadFile';
+import { getCodeBlockFilename, isHttpDownloadTarget, triggerDownload } from '../downloadFile';
describe('downloadFile utilities', () => {
let clickSpy: jest.SpyInstance;
@@ -69,3 +69,47 @@ describe('downloadFile utilities', () => {
expect(revokeSpy).toHaveBeenCalledWith('blob:https://app.example.com/download-id');
});
});
+
+describe('getCodeBlockFilename', () => {
+ it('maps common language names to their extension', () => {
+ expect(getCodeBlockFilename('python')).toBe('code.py');
+ expect(getCodeBlockFilename('javascript')).toBe('code.js');
+ expect(getCodeBlockFilename('typescript')).toBe('code.ts');
+ expect(getCodeBlockFilename('csharp')).toBe('code.cs');
+ expect(getCodeBlockFilename('c++')).toBe('code.cpp');
+ expect(getCodeBlockFilename('bash')).toBe('code.sh');
+ expect(getCodeBlockFilename('shell')).toBe('code.sh');
+ expect(getCodeBlockFilename('powershell')).toBe('code.ps1');
+ expect(getCodeBlockFilename('markdown')).toBe('code.md');
+ });
+
+ it('is case-insensitive and trims whitespace', () => {
+ expect(getCodeBlockFilename('Python')).toBe('code.py');
+ expect(getCodeBlockFilename(' RUST ')).toBe('code.rs');
+ });
+
+ it('maps alphanumeric language aliases instead of treating them as extensions', () => {
+ expect(getCodeBlockFilename('python3')).toBe('code.py');
+ expect(getCodeBlockFilename('nodejs')).toBe('code.js');
+ expect(getCodeBlockFilename('node')).toBe('code.js');
+ expect(getCodeBlockFilename('golang')).toBe('code.go');
+ });
+
+ it('passes extension-like hints through unchanged', () => {
+ expect(getCodeBlockFilename('py')).toBe('code.py');
+ expect(getCodeBlockFilename('tsx')).toBe('code.tsx');
+ expect(getCodeBlockFilename('json')).toBe('code.json');
+ expect(getCodeBlockFilename('svg')).toBe('code.svg');
+ expect(getCodeBlockFilename('html')).toBe('code.html');
+ expect(getCodeBlockFilename('toml')).toBe('code.toml');
+ });
+
+ it('falls back to .txt for missing or unusable hints', () => {
+ expect(getCodeBlockFilename(undefined)).toBe('code.txt');
+ expect(getCodeBlockFilename(null)).toBe('code.txt');
+ expect(getCodeBlockFilename('')).toBe('code.txt');
+ expect(getCodeBlockFilename('plaintext')).toBe('code.txt');
+ expect(getCodeBlockFilename('not a language')).toBe('code.txt');
+ expect(getCodeBlockFilename('../../etc/passwd')).toBe('code.txt');
+ });
+});
diff --git a/client/src/utils/downloadFile.ts b/client/src/utils/downloadFile.ts
index 3ee164fccd..ddccc53a2e 100644
--- a/client/src/utils/downloadFile.ts
+++ b/client/src/utils/downloadFile.ts
@@ -1,6 +1,64 @@
export const isHttpDownloadTarget = (target?: string | null): boolean =>
/^https?:\/\//i.test(target ?? '');
+/**
+ * Maps a fenced-block language hint to a file extension. Used to name
+ * downloads of chat code blocks (`code.<ext>`). Only languages whose common
+ * name differs from their extension need an entry; hints that already look
+ * like an extension (`py`, `ts`, `json`) pass through unchanged.
+ */
+const LANGUAGE_TO_EXTENSION: Record<string, string> = {
+ javascript: 'js',
+ node: 'js',
+ nodejs: 'js',
+ typescript: 'ts',
+ python: 'py',
+ python3: 'py',
+ golang: 'go',
+ ruby: 'rb',
+ perl: 'pl',
+ rust: 'rs',
+ 'c++': 'cpp',
+ csharp: 'cs',
+ 'c#': 'cs',
+ objectivec: 'm',
+ kotlin: 'kt',
+ julia: 'jl',
+ elixir: 'ex',
+ erlang: 'erl',
+ haskell: 'hs',
+ clojure: 'clj',
+ fsharp: 'fs',
+ 'f#': 'fs',
+ bash: 'sh',
+ shell: 'sh',
+ zsh: 'sh',
+ powershell: 'ps1',
+ batch: 'bat',
+ graphql: 'graphql',
+ protobuf: 'proto',
+ markdown: 'md',
+ yaml: 'yaml',
+ yml: 'yaml',
+ plaintext: 'txt',
+ text: 'txt',
+};
+
+/**
+ * Builds a download filename for a chat code block from its fenced-block
+ * language hint. Unknown-but-extension-like hints are used verbatim so a
+ * ```` ```toml ```` block still downloads as `code.toml`; anything else
+ * falls back to `code.txt`.
+ */
+export function getCodeBlockFilename(lang?: string | null): string {
+ const hint = (lang ?? '').trim().toLowerCase();
+ const mapped = Object.prototype.hasOwnProperty.call(LANGUAGE_TO_EXTENSION, hint)
+ ? LANGUAGE_TO_EXTENSION[hint]
+ : undefined;
+ const extension = mapped ?? (/^[a-z0-9]{1,11}$/.test(hint) ? hint : 'txt');
+ return `code.${extension}`;
+}
+
export function triggerDownload(target: string, filename: string): void {
const isBlob = target.startsWith('blob:');
const link = document.createElement('a');