Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: preview exported files inline instead of navigating away (#19727)

LiJian0359e9e55e35
diff --git a/locales/en-US/portal.json b/locales/en-US/portal.json
index 462eda1030b..2ea60ea72c3 100644
--- a/locales/en-US/portal.json
+++ b/locales/en-US/portal.json
@@ -1,4 +1,5 @@
{
+ "FilePreview.actions.download": "Download source file",
"FilePreview.tabs.chunk": "Chunk",
"FilePreview.tabs.file": "File",
"Plugins": "Skills",
diff --git a/locales/zh-CN/portal.json b/locales/zh-CN/portal.json
index d9b6220d924..ecd61bd2e97 100644
--- a/locales/zh-CN/portal.json
+++ b/locales/zh-CN/portal.json
@@ -1,4 +1,5 @@
{
+ "FilePreview.actions.download": "下载源文件",
"FilePreview.tabs.chunk": "分块",
"FilePreview.tabs.file": "文件",
"Plugins": "技能",
diff --git a/packages/locales/src/default/portal.ts b/packages/locales/src/default/portal.ts
index 9b2cf265494..b57efabf2b2 100644
--- a/packages/locales/src/default/portal.ts
+++ b/packages/locales/src/default/portal.ts
@@ -1,4 +1,5 @@
export default {
+ 'FilePreview.actions.download': 'Download source file',
'FilePreview.tabs.chunk': 'Chunk',
'FilePreview.tabs.file': 'File',
'Plugins': 'Skills',
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx
new file mode 100644
index 00000000000..badb41d9af6
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx
@@ -0,0 +1,103 @@
+'use client';
+
+import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
+import { A } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import type { MouseEvent } from 'react';
+import { memo, useCallback } from 'react';
+
+import FileIcon from '@/components/FileIcon';
+import { useChatStore } from '@/store/chat';
+
+import type { MarkdownElementProps } from '../type';
+
+interface FileLinkProperties {
+ fileId?: string;
+ linkHref?: string;
+ linkLabel?: string;
+}
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ icon: css`
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ `,
+ link: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ margin-inline: -2px;
+ padding-inline: 2px;
+ border-radius: ${cssVar.borderRadiusSM};
+
+ text-decoration: none;
+ vertical-align: -0.16em;
+
+ transition:
+ color 0.2s ${cssVar.motionEaseOut},
+ background 0.2s ${cssVar.motionEaseOut},
+ box-shadow 0.2s ${cssVar.motionEaseOut};
+
+ &:hover {
+ color: ${cssVar.colorLinkHover};
+ text-decoration: underline;
+ text-underline-offset: 2px;
+
+ background: ${cssVar.colorFillSecondary};
+ box-shadow: inset 0 0 0 1px ${cssVar.colorPrimaryBorder};
+ }
+
+ &:active {
+ color: ${cssVar.colorLinkActive};
+ background: ${cssVar.colorFill};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 2px;
+ }
+ `,
+}));
+
+const Render = memo<MarkdownElementProps<FileLinkProperties>>(({ node }) => {
+ const { fileId, linkHref, linkLabel } = node?.properties || {};
+ const openFilePreview = useChatStore((s) => s.openFilePreview);
+ const label = linkLabel || linkHref || '';
+
+ const handleClick = useCallback(
+ (event: MouseEvent<HTMLAnchorElement>) => {
+ if (!fileId) return;
+ if (event.button !== 0) return;
+
+ // Modifier/middle click keeps the native "open in a new tab" behavior.
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
+
+ event.preventDefault();
+ openFilePreview({ fileId });
+ },
+ [fileId, openFilePreview],
+ );
+
+ return (
+ <A
+ {...(fileId ? { [RENDERER_HANDLED_LINK_ATTR]: 'true' } : {})}
+ className={styles.link}
+ href={linkHref}
+ rel="noopener noreferrer"
+ onClick={handleClick}
+ >
+ <span aria-hidden className={styles.icon}>
+ <FileIcon fileName={label} size={16} variant={'raw'} />
+ </span>
+ <span>{label}</span>
+ </A>
+ );
+});
+
+Render.displayName = 'FileLinkRender';
+
+export default Render;
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/index.ts b/src/features/Conversation/Markdown/plugins/FileLink/index.ts
new file mode 100644
index 00000000000..78c7bf99d24
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/FileLink/index.ts
@@ -0,0 +1,15 @@
+import { type FC } from 'react';
+
+import { type MarkdownElement, type MarkdownElementProps } from '../type';
+import { LOBE_FILE_LINK_TAG } from './parse';
+import { rehypeFileLink } from './rehypePlugin';
+import Render from './Render';
+
+const FileLinkElement: MarkdownElement = {
+ Component: Render as FC<MarkdownElementProps>,
+ rehypePlugin: rehypeFileLink,
+ scope: 'all',
+ tag: LOBE_FILE_LINK_TAG,
+};
+
+export default FileLinkElement;
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts b/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts
new file mode 100644
index 00000000000..142a3e47ec5
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseFileLinkHref } from './parse';
+
+const ORIGIN = 'https://app.lobehub.com';
+
+describe('parseFileLinkHref', () => {
+ it('matches a same-origin absolute file proxy link', () => {
+ expect(parseFileLinkHref(`${ORIGIN}/f/file_abc123`, ORIGIN)).toEqual({
+ fileId: 'file_abc123',
+ });
+ });
+
+ it('matches a root-relative file proxy link regardless of currentOrigin', () => {
+ expect(parseFileLinkHref('/f/file_xyz')).toEqual({ fileId: 'file_xyz' });
+ expect(parseFileLinkHref('/f/file_xyz', ORIGIN)).toEqual({ fileId: 'file_xyz' });
+ });
+
+ it('decodes an encoded file id', () => {
+ expect(parseFileLinkHref('/f/file%20with%20space', ORIGIN)).toEqual({
+ fileId: 'file with space',
+ });
+ });
+
+ it('returns null instead of throwing on a malformed percent-encoded file id', () => {
+ expect(parseFileLinkHref('/f/%', ORIGIN)).toBeNull();
+ });
+
+ it('does not match a cross-origin link sharing the same path shape', () => {
+ expect(parseFileLinkHref('https://example.com/f/not-ours', ORIGIN)).toBeNull();
+ });
+
+ it('does not match an absolute link when no currentOrigin is known', () => {
+ expect(parseFileLinkHref(`${ORIGIN}/f/file_abc123`)).toBeNull();
+ });
+
+ it('does not match a normal external link', () => {
+ expect(parseFileLinkHref('https://example.com/docs', ORIGIN)).toBeNull();
+ });
+
+ it('does not match other app routes', () => {
+ expect(parseFileLinkHref('/api/agent/stream', ORIGIN)).toBeNull();
+ expect(parseFileLinkHref('/features/foo', ORIGIN)).toBeNull();
+ });
+
+ it('returns null for an empty href', () => {
+ expect(parseFileLinkHref(undefined, ORIGIN)).toBeNull();
+ expect(parseFileLinkHref('', ORIGIN)).toBeNull();
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/parse.ts b/src/features/Conversation/Markdown/plugins/FileLink/parse.ts
new file mode 100644
index 00000000000..132a9bfe758
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/FileLink/parse.ts
@@ -0,0 +1,51 @@
+export const LOBE_FILE_LINK_TAG = 'lobeFileLink';
+
+// Matches this app's own file proxy path, e.g. `${APP_URL}/f/:fileId`
+// (see server/routers/lambda/file.ts -> getFileProxyUrl). This is deliberately
+// narrower than Link/internalLink.ts's NON_SPA_ROUTE_ROOTS exclusion of `/f`:
+// that keeps the generic link classifier out of the file proxy entirely, so
+// this plugin claims the anchor first and gives it its own preview affordance.
+const FILE_PROXY_PATH_REGEX = /^\/f\/([^/?#]+)\/?$/;
+
+export interface ParsedFileLink {
+ fileId: string;
+}
+
+export const parseFileLinkHref = (
+ href: string | undefined,
+ currentOrigin?: string,
+): ParsedFileLink | null => {
+ if (!href) return null;
+
+ const isRootRelative = href.startsWith('/') && !href.startsWith('//');
+ let url: URL;
+
+ try {
+ url = new URL(href, currentOrigin || 'https://lobehub.com');
+ } catch {
+ return null;
+ }
+
+ // Only intercept links that point back at this app's own file proxy, never
+ // an externally hosted link that happens to share the path shape. A
+ // root-relative href is inherently same-origin; an absolute one needs an
+ // explicit origin to compare against, so without one it's left alone.
+ if (!isRootRelative) {
+ if (!currentOrigin) return null;
+
+ try {
+ if (url.origin !== new URL(currentOrigin).origin) return null;
+ } catch {
+ return null;
+ }
+ }
+
+ const match = url.pathname.match(FILE_PROXY_PATH_REGEX);
+ if (!match) return null;
+
+ try {
+ return { fileId: decodeURIComponent(match[1]) };
+ } catch {
+ return null;
+ }
+};
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.test.ts b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.test.ts
new file mode 100644
index 00000000000..de5f7140efc
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.test.ts
@@ -0,0 +1,212 @@
+import type * as LobechatConstModule from '@lobechat/const';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useElectronStore } from '@/store/electron';
+
+import { LOBE_FILE_LINK_TAG } from './parse';
+import { rehypeFileLink } from './rehypePlugin';
+
+const mockConstEnv = vi.hoisted(() => ({ isDesktop: false }));
+
+vi.mock('@lobechat/const', async (importOriginal) => {
+ const actual = await importOriginal<typeof LobechatConstModule>();
+ return {
+ ...actual,
+ get isDesktop() {
+ return mockConstEnv.isDesktop;
+ },
+ };
+});
+
+const run = (tree: any) => rehypeFileLink()(tree);
+
+const ORIGIN = () => window.location.origin;
+
+beforeEach(() => {
+ mockConstEnv.isDesktop = false;
+ useElectronStore.setState({ dataSyncConfig: { storageMode: 'cloud' } });
+});
+
+describe('rehypeFileLink', () => {
+ it('retags an absolute, same-origin file proxy link', () => {
+ const href = `${ORIGIN()}/f/file_abc123`;
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'a',
+ properties: { href },
+ children: [{ type: 'text', value: 'bubble_sort.py' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const node = (tree as any).children[0];
+ expect(node.tagName).toBe(LOBE_FILE_LINK_TAG);
+ expect(node.properties).toEqual({
+ fileId: 'file_abc123',
+ linkHref: href,
+ linkLabel: 'bubble_sort.py',
+ });
+ expect(node.children).toEqual([]);
+ });
+
+ it('retags a relative file proxy link', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'a',
+ properties: { href: '/f/file_xyz' },
+ children: [{ type: 'text', value: 'report.xlsx' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ const node = (tree as any).children[0];
+ expect(node.tagName).toBe(LOBE_FILE_LINK_TAG);
+ expect(node.properties.fileId).toBe('file_xyz');
+ });
+
+ it('falls back to the file id as label when the link has no text', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ { type: 'element', tagName: 'a', properties: { href: '/f/file_xyz' }, children: [] },
+ ],
+ };
+
+ run(tree);
+
+ expect((tree as any).children[0].properties.linkLabel).toBe('file_xyz');
+ });
+
+ it('does not intercept a cross-origin link sharing the same path shape', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'a',
+ properties: { href: 'https://example.com/f/not-ours' },
+ children: [{ type: 'text', value: 'not-ours' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ expect((tree as any).children[0].tagName).toBe('a');
+ });
+
+ it('leaves a normal external link untouched', () => {
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'a',
+ properties: { href: 'https://example.com/docs' },
+ children: [{ type: 'text', value: 'docs' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ expect((tree as any).children[0].tagName).toBe('a');
+ });
+
+ it('leaves non-anchor elements untouched', () => {
+ const tree = {
+ type: 'root',
+ children: [{ type: 'element', tagName: 'p', properties: {}, children: [] }],
+ };
+
+ run(tree);
+
+ expect((tree as any).children[0].tagName).toBe('p');
+ });
+
+ describe('desktop', () => {
+ beforeEach(() => {
+ mockConstEnv.isDesktop = true;
+ });
+
+ it('classifies against the official cloud origin, not the renderer origin', () => {
+ useElectronStore.setState({ dataSyncConfig: { storageMode: 'cloud' } });
+
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'a',
+ properties: { href: 'https://app.lobehub.com/f/file_abc123' },
+ children: [{ type: 'text', value: 'bubble_sort.py' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ expect((tree as any).children[0].tagName).toBe(LOBE_FILE_LINK_TAG);
+ });
+
+ it('classifies against the configured self-hosted remote server origin', () => {
+ useElectronStore.setState({
+ dataSyncConfig: {
+ remoteServerUrl: 'https://my-server.example.com',
+ storageMode: 'selfHost',
+ },
+ });
+
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'a',
+ properties: { href: 'https://my-server.example.com/f/file_abc123' },
+ children: [{ type: 'text', value: 'bubble_sort.py' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ expect((tree as any).children[0].tagName).toBe(LOBE_FILE_LINK_TAG);
+ });
+
+ it('still rejects a link to a different origin than the configured remote server', () => {
+ useElectronStore.setState({
+ dataSyncConfig: {
+ remoteServerUrl: 'https://my-server.example.com',
+ storageMode: 'selfHost',
+ },
+ });
+
+ const tree = {
+ type: 'root',
+ children: [
+ {
+ type: 'element',
+ tagName: 'a',
+ properties: { href: 'https://example.com/f/not-ours' },
+ children: [{ type: 'text', value: 'not-ours' }],
+ },
+ ],
+ };
+
+ run(tree);
+
+ expect((tree as any).children[0].tagName).toBe('a');
+ });
+ });
+});
diff --git a/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.ts b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.ts
new file mode 100644
index 00000000000..df3efde3113
--- /dev/null
+++ b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.ts
@@ -0,0 +1,58 @@
+import { isDesktop } from '@lobechat/const';
+import { SKIP, visit } from 'unist-util-visit';
+
+import { useElectronStore } from '@/store/electron';
+import { electronSyncSelectors } from '@/store/electron/selectors';
+
+import { LOBE_FILE_LINK_TAG, parseFileLinkHref } from './parse';
+
+const getNodeText = (node: any): string => {
+ if (!node) return '';
+ if (node.type === 'text') return String(node.value ?? '');
+ if (Array.isArray(node.children)) return node.children.map(getNodeText).join('');
+ return '';
+};
+
+/**
+ * The origin file links should be classified against. On desktop the
+ * renderer's own origin isn't the app's — exported files are absolute URLs
+ * pointing at the remote server, so that's what has to match (see useAppOrigin,
+ * this plugin's non-hook equivalent).
+ */
+const getCurrentOrigin = (): string | undefined => {
+ if (typeof window === 'undefined') return undefined;
+ if (!isDesktop) return window.location.origin;
+
+ const remoteServerUrl = electronSyncSelectors.remoteServerUrl(useElectronStore.getState());
+ return remoteServerUrl || undefined;
+};
+
+/**
+ * Rehype plugin that rewrites `<a href="{APP_URL}/f/:fileId">` anchors —
+ * produced by assistant tool output such as code execution file export —
+ * into a custom `<lobeFileLink>` element, so they open the in-app file
+ * preview panel instead of navigating away. Must run before Link's generic
+ * `rehypeLobeLink`, which would otherwise consume the same anchor first.
+ */
+export const rehypeFileLink = () => (tree: any) => {
+ visit(tree, 'element', (node: any) => {
+ if (node.tagName !== 'a') return;
+
+ const href = node.properties?.href as string | undefined;
+ const parsed = parseFileLinkHref(href, getCurrentOrigin());
+ if (!parsed) return;
+
+ const text = getNodeText(node).trim();
+ const label = text || parsed.fileId;
+
+ node.tagName = LOBE_FILE_LINK_TAG;
+ node.children = [];
+ node.properties = {
+ fileId: parsed.fileId,
+ linkHref: href,
+ linkLabel: label,
+ };
+
+ return SKIP;
+ });
+};
diff --git a/src/features/Conversation/Markdown/plugins/index.ts b/src/features/Conversation/Markdown/plugins/index.ts
index 4adb577ee8b..ee206e70c76 100644
--- a/src/features/Conversation/Markdown/plugins/index.ts
+++ b/src/features/Conversation/Markdown/plugins/index.ts
@@ -1,3 +1,4 @@
+import FileLink from './FileLink';
import ImageSearchRef from './ImageSearchRef';
import Link from './Link';
import LobeAgents from './LobeAgents';
@@ -28,5 +29,6 @@ export const markdownElements: MarkdownElement[] = [
ImageSearchRef,
LobeAgents,
LocalFileLink,
+ FileLink,
Link,
];
diff --git a/src/features/Portal/FilePreview/Title.tsx b/src/features/Portal/FilePreview/Title.tsx
index 13d174bf515..ea1bc64a065 100644
--- a/src/features/Portal/FilePreview/Title.tsx
+++ b/src/features/Portal/FilePreview/Title.tsx
@@ -1,13 +1,17 @@
-import { Flexbox } from '@lobehub/ui';
+import { DropdownMenu, Flexbox, Icon } from '@lobehub/ui';
import { ActionIcon, Skeleton, Text } from '@lobehub/ui/base-ui';
-import { ArrowLeft } from 'lucide-react';
+import { ArrowLeft, DownloadIcon, MoreHorizontalIcon } from 'lucide-react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
import { useFileStore } from '@/store/file';
import { oneLineEllipsis } from '@/styles';
+import { downloadFile } from '@/utils/client/downloadFile';
const Title = () => {
+ const { t } = useTranslation('portal');
const [closeFilePreview, previewFileId] = useChatStore((s) => [
s.closeFilePreview,
chatPortalSelectors.previewFileId(s),
@@ -17,16 +21,39 @@ const Title = () => {
const { data, isLoading } = useFetchFileItem(previewFileId);
+ const dropdownItems = useMemo(
+ () =>
+ data?.url
+ ? [
+ {
+ icon: <Icon icon={DownloadIcon} />,
+ key: 'download',
+ label: t('FilePreview.actions.download'),
+ onClick: () => downloadFile(data.url, data.name),
+ },
+ ]
+ : [],
+ [data?.url, data?.name, t],
+ );
+
return (
- <Flexbox horizontal align={'center'} gap={4}>
- <ActionIcon icon={ArrowLeft} size={'small'} onClick={() => closeFilePreview()} />
-
- {isLoading ? (
- <Skeleton height={28} />
- ) : (
- <Text className={oneLineEllipsis} style={{ fontSize: 16 }} type={'secondary'}>
- {data?.name}
- </Text>
+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={4} style={{ overflow: 'hidden' }}>
+ <ActionIcon icon={ArrowLeft} size={'small'} onClick={() => closeFilePreview()} />
+
+ {isLoading ? (
+ <Skeleton height={28} />
+ ) : (
+ <Text className={oneLineEllipsis} style={{ fontSize: 16 }} type={'secondary'}>
+ {data?.name}
+ </Text>
+ )}
+ </Flexbox>
+
+ {dropdownItems.length > 0 && (
+ <DropdownMenu items={dropdownItems}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} />
+ </DropdownMenu>
)}
</Flexbox>
);