🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(file): open Docs file links beside the chat and share files by link (#21913)
Lobehub Coderfb1349ebae26
diff --git a/apps/cli/src/commands/file.test.ts b/apps/cli/src/commands/file.test.tsindex d990ae756f5..c634823ecd4 100644--- a/apps/cli/src/commands/file.test.ts+++ b/apps/cli/src/commands/file.test.ts@@ -93,7 +93,7 @@ describe('file command', () => {expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(- [{ ...items[0], appUrl: 'https://app.lobehub.com/resource?file=f1' }],+ [{ ...items[0], appUrl: 'https://app.lobehub.com/resource/file/f1' }],null,2,),diff --git a/apps/cli/src/commands/resourceUrl.test.ts b/apps/cli/src/commands/resourceUrl.test.tsindex e091843d0f0..6bcaf9202ca 100644--- a/apps/cli/src/commands/resourceUrl.test.ts+++ b/apps/cli/src/commands/resourceUrl.test.ts@@ -35,7 +35,7 @@ describe('resourcePath', () => {resourcePath.document({ id: 'docs_1', knowledgeBaseId: 'kb_1' }),'/resource/library/kb_1?file=docs_1',],- [resourcePath.file({ id: 'file_1' }), '/resource?file=file_1'],+ [resourcePath.file({ id: 'file_1' }), '/resource/file/file_1'],[resourcePath.dashboard({ id: 'dsh_1', projectId: 'prj_1' }), '/project/prj_1/dashboard/dsh_1'],[resourcePath.task({ id: 'task_1', identifier: 'T-1', name: 'Ship it' }), '/task/T-1/ship-it'],[resourcePath.acceptance('acc_1'), '/acceptance/acc_1'],@@ -65,7 +65,7 @@ describe('withUrl', () => {expect(withUrl(file, toUrl, resourcePath.file(file))).toEqual({...file,- appUrl: 'https://app.example.com/acme/resource?file=file_1',+ appUrl: 'https://app.example.com/acme/resource/file/file_1',});});diff --git a/apps/cli/src/commands/resourceUrl.ts b/apps/cli/src/commands/resourceUrl.tsindex e93c5a801a9..3c1a3536736 100644--- a/apps/cli/src/commands/resourceUrl.ts+++ b/apps/cli/src/commands/resourceUrl.ts@@ -30,11 +30,12 @@ export const resourcePath = {? libraryItemPath(doc.id, doc.knowledgeBaseId): `/page/${seg(doc.id)}`;},+ /** A library file opens inside its library, else in Docs at `/resource/file/<id>`. */file: (file: { id?: Id; knowledgeBaseId?: Id }) => {if (!file.id) return undefined;return file.knowledgeBaseId? libraryItemPath(file.id, file.knowledgeBaseId)- : `/resource?file=${seg(file.id)}`;+ : `/resource/file/${seg(file.id)}`;},goal: (id: Id) => (id ? `/goal/${seg(id)}` : undefined),group: (id: Id) => (id ? `/group/${seg(id)}` : undefined),diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 212805dc355..a1204623bd0 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -3,6 +3,7 @@*/import { accountDeletionRouter } from '@/business/server/lambda-routers/accountDeletion';import { artifactShareRouter } from '@/business/server/lambda-routers/artifactShare';+import { fileShareRouter } from '@/business/server/lambda-routers/fileShare';import { pageShareRouter } from '@/business/server/lambda-routers/pageShare';import { referralRouter } from '@/business/server/lambda-routers/referral';import { spendRouter } from '@/business/server/lambda-routers/spend';@@ -231,6 +232,7 @@ export const lambdaRouter = router({workspaceUserSettings: workspaceUserSettingsRouter,accountDeletion: accountDeletionRouter,artifactShare: artifactShareRouter,+ fileShare: fileShareRouter,pageShare: pageShareRouter,referral: referralRouter,spend: spendRouter,diff --git a/apps/share/app/lib/seo.ts b/apps/share/app/lib/seo.tsindex ea413e8bbe6..9f9b9473023 100644--- a/apps/share/app/lib/seo.ts+++ b/apps/share/app/lib/seo.ts@@ -8,10 +8,12 @@ import type { MetaDescriptor } from 'react-router';const OG_IMAGE_URL = 'https://lobehub.com/assets/cao-og.webp';const TWITTER_SITE = '@lobehub';-type DescriptionKey = 'artifactDescription' | 'pageDescription' | 'topicDescription';+type DescriptionKey =+ 'artifactDescription' | 'fileDescription' | 'pageDescription' | 'topicDescription';const FALLBACK_DESCRIPTION: Record<DescriptionKey, string> = {artifactDescription: `An artifact shared from ${BRANDING_NAME}.`,+ fileDescription: `A file shared from ${BRANDING_NAME}.`,pageDescription: `A page shared from ${BRANDING_NAME}.`,topicDescription: `A conversation shared from ${BRANDING_NAME}.`,};diff --git a/apps/share/app/routes.ts b/apps/share/app/routes.tsindex 94fd5a0758b..29931818ca3 100644--- a/apps/share/app/routes.ts+++ b/apps/share/app/routes.ts@@ -6,5 +6,6 @@ export default [route('share/t/:id/llm.txt', 'routes/shareTopicText.ts'),route('share/page/:id', 'routes/sharePage.tsx'),route('share/artifact/:id', 'routes/shareArtifact.tsx'),+ route('share/file/:id', 'routes/shareFile.tsx'),route('*', 'routes/catchall.tsx'),] satisfies RouteConfig;diff --git a/apps/share/app/routes/shareFile.tsx b/apps/share/app/routes/shareFile.tsxnew file mode 100644index 00000000000..474b377e7bf--- /dev/null+++ b/apps/share/app/routes/shareFile.tsx@@ -0,0 +1,58 @@+import { BRANDING_NAME } from '@lobechat/business-const';+import type { LoaderFunctionArgs, MetaFunction } from 'react-router';+import { useLoaderData } from 'react-router';+import { SWRConfig, unstable_serialize } from 'swr';++import { shareKeys } from '@/libs/swr/keys';+import { resolveRequestLocale } from '@/locales/requestLocale';++import SharedFileView from '../../src/features/file/SharedFileView';+import { loadShareT } from '../../src/shell/createShareI18n';+import { cloudflareContext } from '../lib/cloudflareContext';+import { buildPageMeta, shareMetaDescription } from '../lib/seo';+import { createServerLambdaClient } from '../lib/serverTrpc';++export const loader = async ({ context, params, request }: LoaderFunctionArgs) => {+ const shareId = params.id!;+ const locale = resolveRequestLocale(request);+ const apiBase = context.get(cloudflareContext).env.SHARE_API_BASE as string | undefined;++ const sharedFile = await createServerLambdaClient(request, apiBase)+ .fileShare.getSharedFile.query({ shareId })+ .catch((error) => {+ console.error('[share] shared file SSR fetch failed:', error);+ return null;+ });++ return {+ description: shareMetaDescription(await loadShareT(locale), 'fileDescription'),+ locale,+ shareId,+ sharedFile,+ };+};++export const meta: MetaFunction<typeof loader> = ({ loaderData }) => {+ const name = loaderData?.sharedFile?.file.name;++ return buildPageMeta({+ description: loaderData?.description ?? '',+ locale: loaderData?.locale,+ title: name ? `${name} · ${BRANDING_NAME}` : BRANDING_NAME,+ type: 'website',+ });+};++export default function ShareFileRoute() {+ const { shareId, sharedFile } = useLoaderData<typeof loader>();++ return (+ <SWRConfig+ value={{+ fallback: sharedFile ? { [unstable_serialize(shareKeys.file(shareId))]: sharedFile } : {},+ }}+ >+ <SharedFileView />+ </SWRConfig>+ );+}diff --git a/apps/share/src/features/file/SharedFileStage.client.tsx b/apps/share/src/features/file/SharedFileStage.client.tsxnew file mode 100644index 00000000000..246edf3d432--- /dev/null+++ b/apps/share/src/features/file/SharedFileStage.client.tsx@@ -0,0 +1,151 @@+'use client';++import type { SharedFileData } from '@lobechat/types';+import { Center, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import FileIcon from '@/components/FileIcon';+import FileViewer from '@/features/FileViewer';+import { type FileListItem } from '@/types/files';++import type { SharedFileKind } from './fileKind';++const styles = stylex.create({+ audio: {+ backgroundColor: cssVar.colorFillQuaternary,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'solid',+ borderWidth: 1,+ padding: 24,+ },+ audioPlayer: {+ width: '100%',+ },+ download: {+ borderColor: cssVar.colorBorder,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'dashed',+ borderWidth: 1,+ paddingBlock: 56,+ paddingInline: 24,+ },+ media: {+ borderRadius: cssVar.borderRadius,+ display: 'block',+ maxHeight: '72vh',+ maxWidth: '100%',+ },+ reader: {+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'solid',+ borderWidth: 1,+ height: '78vh',+ overflow: 'hidden',+ },+ stage: {+ // A neutral dark stage reads as "media" in both themes and keeps the+ // frame's own colors honest.+ backgroundColor: '#111',+ borderRadius: cssVar.borderRadiusLG,+ minHeight: 240,+ overflow: 'hidden',+ padding: 16,+ },+});++type SharedFile = SharedFileData['file'];++/**+ * Archives (and anything a browser cannot open) are delivered, not shown; the+ * hero's Download is the one action, so the card only explains.+ */+const DownloadCard = ({ file }: { file: SharedFile }) => {+ const { t } = useTranslation('chat');++ return (+ <Center {...stylex.props(styles.download)} gap={16}>+ <FileIcon fileName={file.name} size={64} variant={'raw'} />+ <Flexbox align={'center'} gap={4}>+ <Text weight={600}>{t('sharePage.file.noPreview.title')}</Text>+ <Text type={'secondary'}>{t('sharePage.file.noPreview.desc')}</Text>+ </Flexbox>+ </Center>+ );+};++/** Documents and text go through the reader the app itself uses. */+const Reader = ({ file, shareId }: { file: SharedFile; shareId: string }) => {+ // FileViewer renders a library item; a share carries only what a visitor may+ // read, so the rest of the item is inert.+ const item = useMemo<FileListItem>(() => {+ const createdAt = new Date(0);+ return {+ chunkCount: null,+ chunkingError: null,+ createdAt,+ embeddingError: null,+ fileType: file.fileType,+ finishEmbedding: false,+ // The share stands in for the file: a visitor never learns the file id.+ id: shareId,+ name: file.name,+ size: file.size,+ sourceType: 'file',+ updatedAt: createdAt,+ url: file.previewUrl,+ };+ }, [file, shareId]);++ return (+ <Flexbox {...stylex.props(styles.reader)}>+ <FileViewer {...item} showChunkHighlights={false} />+ </Flexbox>+ );+};++interface SharedFileStageProps {+ file: SharedFile;+ kind: SharedFileKind;+ shareId: string;+}++const SharedFileStage = memo<SharedFileStageProps>(({ file, kind, shareId }) => {+ switch (kind) {+ case 'video': {+ return (+ <Center {...stylex.props(styles.stage)}>+ <video controls playsInline src={file.previewUrl} {...stylex.props(styles.media)} />+ </Center>+ );+ }+ case 'image': {+ return (+ <Center {...stylex.props(styles.stage)}>+ <img alt={file.name} src={file.previewUrl} {...stylex.props(styles.media)} />+ </Center>+ );+ }+ case 'audio': {+ return (+ <div {...stylex.props(styles.audio)}>+ <audio controls src={file.previewUrl} {...stylex.props(styles.audioPlayer)} />+ </div>+ );+ }+ case 'archive': {+ return <DownloadCard file={file} />;+ }+ default: {+ return <Reader file={file} shareId={shareId} />;+ }+ }+});++SharedFileStage.displayName = 'SharedFileStage';++export default SharedFileStage;diff --git a/apps/share/src/features/file/SharedFileView.tsx b/apps/share/src/features/file/SharedFileView.tsxnew file mode 100644index 00000000000..8b0e4771203--- /dev/null+++ b/apps/share/src/features/file/SharedFileView.tsx@@ -0,0 +1,126 @@+'use client';++import type { SharedFileData } from '@lobechat/types';+import { Button, Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { DownloadIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { useParams } from 'react-router';+import useSWR from 'swr';++import { ShareHero } from '@/business/client/features/ShareShell';+import FileIcon from '@/components/FileIcon';+import { shareKeys } from '@/libs/swr/keys';+import { lambdaClient } from '@/libs/trpc/client';+import { formatSize } from '@/utils/format';++import { clientOnly } from '../../shell/clientOnly';+import ShareLayout from '../../shell/ShareLayout';+import { getSharedFileKind } from './fileKind';++const FILE_PAGE_WIDTH = 960;++// The stage plays or reads the file's bytes (PDF, Office, code highlighting…);+// none of it belongs in the worker, and there is nothing to show before the+// browser fetches them anyway. The hero above it is server-rendered.+const SharedFileStage = clientOnly(() => import('./SharedFileStage.client'));++const styles = stylex.create({+ column: {+ marginInline: 'auto',+ maxWidth: FILE_PAGE_WIDTH,+ paddingBlockEnd: 64,+ paddingInline: 24,+ width: '100%',+ },+ scroll: {+ flex: '1',+ overflowY: 'auto',+ },+ stagePlaceholder: {+ minHeight: 360,+ },+});++const FileHero = ({ data }: { data: SharedFileData }) => {+ const { t } = useTranslation(['chat', 'pageShare']);+ const { file, ownerMeta } = data;+ const extension = file.name.includes('.') ? file.name.split('.').pop()?.toUpperCase() : '';++ return (+ <Flexbox horizontal align={'flex-end'} gap={16} justify={'space-between'} wrap={'wrap'}>+ <ShareHero+ avatar={<FileIcon fileName={file.name} size={48} variant={'raw'} />}+ title={file.name}+ byline={[+ extension,+ formatSize(file.size),+ ownerMeta.displayName &&+ t('shell.sharedBy', { name: ownerMeta.displayName, ns: 'pageShare' }),+ ]+ .filter(Boolean)+ .join(' · ')}+ />+ <Flexbox paddingBlock={'0 16px'}>+ <Button+ href={file.downloadUrl}+ icon={DownloadIcon}+ type={'primary'}+ // The address answers with `Content-Disposition: attachment`, so+ // following it downloads without leaving the page.+ >+ {t('sharePage.file.download')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+};++const SharedFileView = memo(() => {+ const { t } = useTranslation('chat');+ const { id: shareId } = useParams<{ id: string }>();++ const { data, error, isLoading } = useSWR(+ shareId ? shareKeys.file(shareId) : null,+ () => lambdaClient.fileShare.getSharedFile.query({ shareId: shareId! }),+ // Every read counts a view, so the copy on screen is never read again: not+ // on mount over the SSR document, nor on refocus or reconnect. Its file+ // addresses re-check the share per request (`SharedFileData`), so they do+ // not expire under a page left open and stop working once it is private.+ { revalidateIfStale: false, revalidateOnFocus: false, revalidateOnReconnect: false },+ );++ const loading = isLoading && !data;++ return (+ <ShareLayout+ contentWidth={FILE_PAGE_WIDTH}+ error={error || (!loading && !data)}+ loading={loading}+ title={data?.file.name}+ notFound={{+ desc: t('sharePage.error.fileNotFound.subtitle'),+ title: t('sharePage.error.fileNotFound.title'),+ }}+ >+ {data && (+ <div {...stylex.props(styles.scroll)}>+ <div {...stylex.props(styles.column)}>+ <FileHero data={data} />+ <SharedFileStage+ fallback={<div {...stylex.props(styles.stagePlaceholder)} />}+ file={data.file}+ kind={getSharedFileKind(data.file)}+ shareId={data.shareId}+ />+ </div>+ </div>+ )}+ </ShareLayout>+ );+});++SharedFileView.displayName = 'SharedFileView';++export default SharedFileView;diff --git a/apps/share/src/features/file/fileKind.test.ts b/apps/share/src/features/file/fileKind.test.tsnew file mode 100644index 00000000000..661e37a743c--- /dev/null+++ b/apps/share/src/features/file/fileKind.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { getSharedFileKind } from './fileKind';++describe('getSharedFileKind', () => {+ it('classifies by MIME type first', () => {+ expect(getSharedFileKind({ fileType: 'video/mp4', name: 'intro' })).toBe('video');+ expect(getSharedFileKind({ fileType: 'audio/mpeg', name: 'a.bin' })).toBe('audio');+ expect(getSharedFileKind({ fileType: 'image/png', name: 'x' })).toBe('image');+ expect(getSharedFileKind({ fileType: 'application/zip', name: 'x' })).toBe('archive');+ });++ it('falls back to the extension when the type is generic', () => {+ expect(getSharedFileKind({ fileType: 'application/octet-stream', name: 'Clip.MOV' })).toBe(+ 'video',+ );+ expect(getSharedFileKind({ fileType: '', name: 'song.flac' })).toBe('audio');+ expect(getSharedFileKind({ name: 'bundle.tar.gz' })).toBe('archive');+ });++ it('sends everything else to the reader', () => {+ expect(getSharedFileKind({ fileType: 'application/pdf', name: 'r.pdf' })).toBe('document');+ expect(getSharedFileKind({ fileType: 'text/markdown', name: 'notes.md' })).toBe('document');+ expect(getSharedFileKind({ name: 'main.py' })).toBe('document');+ });+});diff --git a/apps/share/src/features/file/fileKind.ts b/apps/share/src/features/file/fileKind.tsnew file mode 100644index 00000000000..3de95286f96--- /dev/null+++ b/apps/share/src/features/file/fileKind.ts@@ -0,0 +1,47 @@+/**+ * How the share page presents a file. Media gets a stage of its own, archives+ * a download card; everything else goes through the reader (`FileViewer`),+ * which picks a renderer for PDFs, Office files, Markdown, HTML and text.+ */+export type SharedFileKind = 'archive' | 'audio' | 'document' | 'image' | 'video';++const EXTENSIONS: Record<Exclude<SharedFileKind, 'document'>, string[]> = {+ archive: ['7z', 'bz2', 'gz', 'rar', 'tar', 'tgz', 'xz', 'zip'],+ audio: ['aac', 'flac', 'm4a', 'mp3', 'oga', 'ogg', 'opus', 'wav'],+ image: ['avif', 'bmp', 'gif', 'jpeg', 'jpg', 'png', 'svg', 'webp'],+ video: ['m4v', 'mov', 'mp4', 'webm'],+};++const ARCHIVE_MIME_TYPES = new Set([+ 'application/gzip',+ 'application/vnd.rar',+ 'application/x-7z-compressed',+ 'application/x-bzip2',+ 'application/x-gzip',+ 'application/x-rar-compressed',+ 'application/x-tar',+ 'application/x-xz',+ 'application/x-zip-compressed',+ 'application/zip',+]);++export const getSharedFileKind = ({+ fileType,+ name,+}: {+ fileType?: string | null;+ name: string;+}): SharedFileKind => {+ const mime = fileType?.toLowerCase() ?? '';+ if (mime.startsWith('video/')) return 'video';+ if (mime.startsWith('audio/')) return 'audio';+ if (mime.startsWith('image/')) return 'image';+ if (ARCHIVE_MIME_TYPES.has(mime)) return 'archive';++ const ext = name.toLowerCase().split('.').pop() ?? '';+ for (const kind of ['video', 'audio', 'image', 'archive'] as const) {+ if (EXTENSIONS[kind].includes(ext)) return kind;+ }++ return 'document';+};diff --git a/apps/share/src/router.tsx b/apps/share/src/router.tsxindex c6611638186..ef406463948 100644--- a/apps/share/src/router.tsx+++ b/apps/share/src/router.tsx@@ -84,6 +84,10 @@ export const shareRoutes: RouteObject[] = [element: lazyElement(() => import('./features/artifact/SharedArtifactView')),path: 'share/artifact/:id',},+ {+ element: lazyElement(() => import('./features/file/SharedFileView')),+ path: 'share/file/:id',+ },{element: <ExitShare />,path: '*',diff --git a/apps/share/src/shell/ShareLayout.tsx b/apps/share/src/shell/ShareLayout.tsxindex d65f7f4122c..b0a22cda276 100644--- a/apps/share/src/shell/ShareLayout.tsx+++ b/apps/share/src/shell/ShareLayout.tsx@@ -9,7 +9,7 @@ import * as ShareChrome from '@/business/client/features/ShareChrome';import { ProductLogo } from '@/components/Branding';import Loading from '@/components/Loading/BrandTextLoading';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';-import ShareErrorView from '@/features/Share/ErrorView';+import ShareErrorView, { type ShareNotFoundCopy } from '@/features/Share/ErrorView';type HeaderActionsProps = {actions?: ReactNode;@@ -131,6 +131,8 @@ export interface ShareLayoutProps {contentWidth?: number;error?: unknown;loading?: boolean;+ /** Copy for a missing share; the error view defaults to the topic wording. */+ notFound?: ShareNotFoundCopy;title?: string | null;}@@ -161,10 +163,11 @@ const ShareLayout = ({contentWidth,error,loading,+ notFound,title,}: ShareLayoutProps) => {let body = children;- if (error) body = <ShareErrorView error={error} />;+ if (error) body = <ShareErrorView error={error} notFound={notFound} />;else if (loading) body = <Loading debugId="share layout" />;const laneStyle = contentWidthdiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 3031eb806e9..e6cc267c5ff 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2262,6 +2262,8 @@"sharePage.app.help": "Trouble opening the app?","sharePage.app.helpDescription": "If this browser prevents opening the app, use its menu to open this page in your system browser. You can also keep reading here.","sharePage.app.open": "Open app",+ "sharePage.error.fileNotFound.subtitle": "This file does not exist, has been removed, or is no longer shared.",+ "sharePage.error.fileNotFound.title": "File Not Found","sharePage.error.forbidden.subtitle": "This share is private and not accessible.","sharePage.error.forbidden.title": "Access Denied","sharePage.error.notFound.subtitle": "This topic does not exist or has been removed.",@@ -2273,11 +2275,15 @@"sharePage.explain.copied": "Prompt copied. Paste it into any AI chat.","sharePage.explain.failed": "Could not copy the prompt. Please try again.","sharePage.explain.prompt": "Take a look at this conversation. Briefly tell me what it is about and what is worth noticing:\n{{url}}",+ "sharePage.file.download": "Download",+ "sharePage.file.noPreview.desc": "Download it to open it on your device.",+ "sharePage.file.noPreview.title": "This file can't be previewed here","sharePage.menu.copyLink": "Copy Link","sharePage.menu.goToLobeHub": "Go to LobeHub","sharePage.menu.more": "More","sharePage.menu.report": "Report","sharePage.meta.artifactDescription": "An artifact shared from {{appName}}.",+ "sharePage.meta.fileDescription": "A file shared from {{appName}}.","sharePage.meta.pageDescription": "A page shared from {{appName}}.","sharePage.meta.topicDescription": "A topic shared from {{appName}}.","sharePage.pill.edit": "Edit",diff --git a/locales/en-US/fileShare.json b/locales/en-US/fileShare.jsonnew file mode 100644index 00000000000..c1abbd0148d--- /dev/null+++ b/locales/en-US/fileShare.json@@ -0,0 +1,15 @@+{+ "popover.copyLink": "Copy Link",+ "popover.copyLinkSuccess": "Link copied",+ "popover.linkHint": "Anyone with the link can view and download this file",+ "popover.permissionLink": "Anyone with the link",+ "popover.permissionPrivate": "Private",+ "popover.privateHint": "Only you can open this file",+ "popover.sectionViews_one": "{{count}} view",+ "popover.sectionViews_other": "{{count}} views",+ "popover.title": "Share File",+ "popover.updateError": "Failed to update sharing settings",+ "popover.visibility": "Visibility",+ "popover.visibilityUpdated": "Visibility updated",+ "shareButton.label": "Share"+}diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3d08b59e361..01d5e84a01e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2262,6 +2262,8 @@"sharePage.app.help": "打开 App 遇到问题?","sharePage.app.helpDescription": "如果当前浏览器阻止打开 App,可以通过浏览器菜单在系统浏览器中打开此页面。你也可以继续在这里阅读。","sharePage.app.open": "打开 App",+ "sharePage.error.fileNotFound.subtitle": "该文件不存在、已被删除或已取消分享。",+ "sharePage.error.fileNotFound.title": "文件不存在","sharePage.error.forbidden.subtitle": "此分享为私密状态,无法访问。","sharePage.error.forbidden.title": "无权访问","sharePage.error.notFound.subtitle": "该话题不存在或已被删除。",@@ -2273,11 +2275,15 @@"sharePage.explain.copied": "已复制,粘贴给任意 AI 即可","sharePage.explain.failed": "复制失败,请重试","sharePage.explain.prompt": "帮我看看这段对话,简单说说它在聊什么,有哪些值得注意的内容:\n{{url}}",+ "sharePage.file.download": "下载",+ "sharePage.file.noPreview.desc": "下载后在你的设备上打开。",+ "sharePage.file.noPreview.title": "此文件无法在线预览","sharePage.menu.copyLink": "复制链接","sharePage.menu.goToLobeHub": "前往 LobeHub","sharePage.menu.more": "更多","sharePage.menu.report": "举报","sharePage.meta.artifactDescription": "分享自 {{appName}} 的 Artifact。",+ "sharePage.meta.fileDescription": "分享自 {{appName}} 的文件。","sharePage.meta.pageDescription": "分享自 {{appName}} 的页面。","sharePage.meta.topicDescription": "分享自 {{appName}} 的话题。","sharePage.pill.edit": "编辑",diff --git a/locales/zh-CN/fileShare.json b/locales/zh-CN/fileShare.jsonnew file mode 100644index 00000000000..fdf0772e7c6--- /dev/null+++ b/locales/zh-CN/fileShare.json@@ -0,0 +1,15 @@+{+ "popover.copyLink": "复制链接",+ "popover.copyLinkSuccess": "链接已复制",+ "popover.linkHint": "拥有链接的任何人都可查看和下载此文件",+ "popover.permissionLink": "拥有链接者",+ "popover.permissionPrivate": "私密",+ "popover.privateHint": "仅你可打开此文件",+ "popover.sectionViews_one": "{{count}} 次浏览",+ "popover.sectionViews_other": "{{count}} 次浏览",+ "popover.title": "分享文件",+ "popover.updateError": "更新分享设置失败",+ "popover.visibility": "可见性",+ "popover.visibilityUpdated": "可见性已更新",+ "shareButton.label": "分享"+}diff --git a/packages/business-server/src/lambda-routers/fileShare.ts b/packages/business-server/src/lambda-routers/fileShare.tsnew file mode 100644index 00000000000..9ecf2ddcb3c--- /dev/null+++ b/packages/business-server/src/lambda-routers/fileShare.ts@@ -0,0 +1,21 @@+import type { FileShareSettings, SharedFileData } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';++export const fileShareRouter = router({+ getShareSettings: authedProcedure+ .input(z.object({ fileId: z.string() }))+ .query(async (): Promise<FileShareSettings | null> => null),++ updateShareSettings: authedProcedure+ .input(z.object({ fileId: z.string(), visibility: z.enum(['private', 'link']) }))+ .mutation(async (): Promise<FileShareSettings | null> => null),++ getSharedFile: publicProcedure+ .input(z.object({ shareId: z.string() }))+ .query(async (): Promise<SharedFileData> => {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'File sharing is not available' });+ }),+});diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 4ef42ea1c75..9f90245694e 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -235,6 +235,9 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule// Personal sidebar shortcuts, like other per-user preferences.favorite: rw('user:read', 'user:write'),file: rw('file:read', 'file:write'),+ // a link share opens one file to anyone holding the link — the same authority+ // as the file itself+ fileShare: rw('file:read', 'file:write'),followUpAction: rw('chat:read', 'chat:write'),generation: { any: 'model:invoke' },generationBatch: { any: 'model:invoke' },diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c4e642037f4..7c25e951a3e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1873,6 +1873,9 @@ export default {'sharePage.explain.prompt':'Take a look at this conversation. Briefly tell me what it is about and what is worth noticing:\n{{url}}','sharePage.actions.tryItYourself': 'Try it yourself',+ 'sharePage.error.fileNotFound.subtitle':+ 'This file does not exist, has been removed, or is no longer shared.',+ 'sharePage.error.fileNotFound.title': 'File Not Found','sharePage.error.forbidden.subtitle': 'This share is private and not accessible.','sharePage.error.forbidden.title': 'Access Denied','sharePage.error.notFound.subtitle': 'This topic does not exist or has been removed.',@@ -1880,11 +1883,15 @@ export default {'sharePage.error.unauthorized.action': 'Sign In','sharePage.error.unauthorized.subtitle': 'Please sign in to view this shared topic.','sharePage.error.unauthorized.title': 'Sign In Required',+ 'sharePage.file.download': 'Download',+ 'sharePage.file.noPreview.desc': 'Download it to open it on your device.',+ 'sharePage.file.noPreview.title': "This file can't be previewed here",'sharePage.menu.copyLink': 'Copy Link','sharePage.menu.goToLobeHub': 'Go to LobeHub','sharePage.menu.more': 'More','sharePage.menu.report': 'Report','sharePage.meta.artifactDescription': 'An artifact shared from {{appName}}.',+ 'sharePage.meta.fileDescription': 'A file shared from {{appName}}.','sharePage.meta.pageDescription': 'A page shared from {{appName}}.','sharePage.meta.topicDescription': 'A topic shared from {{appName}}.','sharePage.pill.edit': 'Edit',diff --git a/packages/locales/src/default/fileShare.ts b/packages/locales/src/default/fileShare.tsnew file mode 100644index 00000000000..7467fa774de--- /dev/null+++ b/packages/locales/src/default/fileShare.ts@@ -0,0 +1,16 @@+// Cloud-only feature; namespace kept here so locale dictionary stays centralized.+export default {+ 'popover.copyLink': 'Copy Link',+ 'popover.copyLinkSuccess': 'Link copied',+ 'popover.linkHint': 'Anyone with the link can view and download this file',+ 'popover.permissionLink': 'Anyone with the link',+ 'popover.permissionPrivate': 'Private',+ 'popover.privateHint': 'Only you can open this file',+ 'popover.sectionViews_one': '{{count}} view',+ 'popover.sectionViews_other': '{{count}} views',+ 'popover.title': 'Share File',+ 'popover.updateError': 'Failed to update sharing settings',+ 'popover.visibility': 'Visibility',+ 'popover.visibilityUpdated': 'Visibility updated',+ 'shareButton.label': 'Share',+};diff --git a/packages/locales/src/default/index.ts b/packages/locales/src/default/index.tsindex 36bb872a7e7..4212f73f4aa 100644--- a/packages/locales/src/default/index.ts+++ b/packages/locales/src/default/index.ts@@ -17,6 +17,7 @@ import electron from './electron';import error from './error';import eval_ from './eval';import file from './file';+import fileShare from './fileShare';import home from './home';import hotkey from './hotkey';import image from './image';@@ -75,6 +76,7 @@ const resources = {error,'eval': eval_,file,+ fileShare,home,hotkey,image,diff --git a/packages/types/src/fileShare.ts b/packages/types/src/fileShare.tsindex a7426860ca9..9a12ea85cef 100644--- a/packages/types/src/fileShare.ts+++ b/packages/types/src/fileShare.ts@@ -3,3 +3,41 @@* Stored as jsonb, so adding a control needs no migration; unset keys fall back to defaults.*/export type FileShareConfig = Record<string, unknown>;++/** `'private'` = owner only, `'link'` = anyone with the link (see `ShareVisibility`). */+export type FileShareVisibility = 'private' | 'link';++/** The owner's view of a file's share link. */+export interface FileShareSettings {+ fileId: string;+ pageViewCount: number;+ /** The share link id: `/share/file/<shareId>`. */+ shareId: string;+ visibility: FileShareVisibility;+}++/**+ * What a share link visitor reads: the file and addresses to its bytes.+ *+ * The addresses are scoped to the SHARE and re-check it on every request, so+ * making the share private cuts off a page already open. They must also outlive+ * the page — it reads the share once (each read counts a view), so a signed URL+ * that expires would break a later download or a resumed video. The file's own+ * id is deliberately absent: the `/f/:fileId` proxy is public by id and would+ * outlive the share.+ */+export interface SharedFileData {+ file: {+ /** Address that downloads the bytes under the file's own name. */+ downloadUrl: string;+ fileType: string;+ name: string;+ /** Address the viewer renders from. */+ previewUrl: string;+ size: number;+ };+ isOwner: boolean;+ ownerMeta: { avatar: string | null; displayName: string | null };+ pageViewCount: number;+ shareId: string;+}diff --git a/packages/utils/src/fileShare.test.ts b/packages/utils/src/fileShare.test.tsnew file mode 100644index 00000000000..b434da570aa--- /dev/null+++ b/packages/utils/src/fileShare.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';++import { fileSharePath, fileShareUrl } from './fileShare';++describe('fileShareUrl', () => {+ it('builds the share page address on the given origin', () => {+ expect(fileShareUrl('https://lobehub.com/', 'Ab3_x')).toBe(+ 'https://lobehub.com/share/file/Ab3_x',+ );+ });++ it('encodes the share id', () => {+ expect(fileSharePath('a/b')).toBe('/share/file/a%2Fb');+ });+});diff --git a/packages/utils/src/fileShare.ts b/packages/utils/src/fileShare.tsnew file mode 100644index 00000000000..ce405171834--- /dev/null+++ b/packages/utils/src/fileShare.ts@@ -0,0 +1,4 @@+export const fileSharePath = (shareId: string) => `/share/file/${encodeURIComponent(shareId)}`;++export const fileShareUrl = (origin: string, shareId: string) =>+ `${origin.replace(/\/+$/, '')}${fileSharePath(shareId)}`;diff --git a/src/app/robots.tsx b/src/app/robots.tsxindex dfc9ae017a2..6989632af27 100644--- a/src/app/robots.tsx+++ b/src/app/robots.tsx@@ -28,7 +28,7 @@ const robots = (): MetadataRoute.Robots => {// fetch the URL, so the three real share routes are allowed on top of the `/share/*`// block. Everything else under `/share/` keeps the block: the SPA fallback answers those// paths with the indexable app shell.- allow: ['/', '/share/t/', '/share/page/', '/share/artifact/'],+ allow: ['/', '/share/t/', '/share/page/', '/share/artifact/', '/share/file/'],// `/a/*` is the Agent Share visitor page: link-visible, creator-owned// content that must never be indexed. `/agent/*` is the creator's own// agent pages (and still forwards legacy share links).diff --git a/src/business/client/features/FileShare/ShareButton.tsx b/src/business/client/features/FileShare/ShareButton.tsxnew file mode 100644index 00000000000..eb346625f68--- /dev/null+++ b/src/business/client/features/FileShare/ShareButton.tsx@@ -0,0 +1,3 @@+export default function ShareButton(_: { fileId: string }) {+ return null;+}diff --git a/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsxindex c84347240c2..23dfa0ba773 100644--- a/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx+++ b/src/features/Conversation/Markdown/plugins/FileLink/Render.tsx@@ -1,29 +1,100 @@'use client';+import { isDesktop } from '@lobechat/const';import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';-import { A, createStaticStyles } from '@lobehub/ui';+import { A, copyToClipboard, createStaticStyles, Icon, toast } from '@lobehub/ui';+import { CopyIcon } from 'lucide-react';import type { MouseEvent } from 'react';import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';import FileIcon from '@/components/FileIcon';+import { EntityLinkRender, parseLobeLink } from '@/features/EntityLink';import { useChatStore } from '@/store/chat';+import { useElectronStore } from '@/store/electron';+import { electronSyncSelectors } from '@/store/electron/selectors';+import { useFileStore } from '@/store/file';import { useConversationStore } from '../../../store';import type { MarkdownElementProps } from '../type';-import { getFileLinkOpenAction } from './parse';+import {+ getFileLinkCopyHref,+ getFileLinkOpenAction,+ getFileLinkTargetHref,+ isShareVisitorContext,+ resolveAppOrigin,+} from './parse';interface FileLinkProperties {fileId?: string;linkHref?: string;linkLabel?: string;+ linkScope?: 'active' | 'foreign';+ proxyHref?: string;}+/**+ * The app server's origin, read at click time: on desktop the renderer's own+ * origin (`app://renderer`) is not the server a copied link must point at.+ * Kept out of render so the share page's SSR never touches the window or the+ * (stubbed) desktop store.+ */+const getAppOrigin = () =>+ resolveAppOrigin({+ isDesktop,+ remoteServerUrl: () => electronSyncSelectors.remoteServerUrl(useElectronStore.getState()),+ windowOrigin: () => window.location.origin,+ });+const styles = createStaticStyles(({ css, cssVar }) => ({+ copy: css`+ cursor: pointer;++ display: inline-flex;+ align-items: center;+ justify-content: center;++ width: 18px;+ height: 18px;+ margin-inline-start: 2px;+ padding: 0;+ border: none;+ border-radius: ${cssVar.borderRadiusSM};++ color: ${cssVar.colorTextQuaternary};+ vertical-align: -0.2em;++ background: transparent;++ transition:+ color 0.15s,+ background 0.15s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimaryBorder};+ outline-offset: 1px;+ }+ `,icon: css`display: inline-flex;flex-shrink: 0;align-items: center;`,+ label: css`+ /* The same treatment as an internal entity link: body text with an+ underline, not link blue — the file icon already says what it is. */+ text-decoration-color: ${cssVar.colorTextTertiary};+ text-decoration-line: underline;+ text-decoration-thickness: 1px;+ text-underline-offset: 3px;++ transition: text-decoration-color 0.15s;+ `,link: css`cursor: pointer;@@ -31,44 +102,70 @@ const styles = createStaticStyles(({ css, cssVar }) => ({gap: 4px;align-items: center;- margin-inline: -2px;- padding-inline: 2px;- border-radius: ${cssVar.borderRadiusSM};-+ color: ${cssVar.colorText} !important;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};+ color: ${cssVar.colorText} !important;}- &:active {- color: ${cssVar.colorLinkActive};- background: ${cssVar.colorFill};+ &:hover > span:last-child {+ text-decoration-color: ${cssVar.colorTextSecondary};}&:focus-visible {+ border-radius: 2px;outline: 2px solid ${cssVar.colorPrimaryBorder};outline-offset: 2px;}`,}));+const FileLabel = ({ label }: { label: string }) => (+ <>+ <span aria-hidden className={styles.icon}>+ <FileIcon fileName={label} size={16} variant={'raw'} />+ </span>+ <span className={styles.label}>{label}</span>+ </>+);++/**+ * A pasted address (`https://…/resource/file/file_x`) says nothing about the+ * file, so the owner sees its name instead — the same item the preview panel+ * reads, so the click opens instantly.+ */+const OwnedFileLabel = memo<{ fallback: string; fileId: string }>(({ fallback, fileId }) => {+ const useFetchKnowledgeItem = useFileStore((s) => s.useFetchKnowledgeItem);+ const { data: file } = useFetchKnowledgeItem(fileId);++ return <FileLabel label={file?.name || fallback} />;+});++OwnedFileLabel.displayName = 'FileLinkOwnedFileLabel';+const Render = memo<MarkdownElementProps<FileLinkProperties>>(({ node }) => {- const { fileId, linkHref, linkLabel } = node?.properties || {};+ const { fileId, linkHref, linkLabel, linkScope, proxyHref } = node?.properties || {};const openFilePreview = useChatStore((s) => s.openFilePreview);- const isAgentShareVisitor = useConversationStore((s) => !!s.context.agentShareId);+ // A share reader previews and copies the public proxy, not the owner's page.+ const isShareVisitor = useConversationStore((s) => isShareVisitorContext(s.context));+ const { t } = useTranslation('common');const label = linkLabel || linkHref || '';+ const isBareLink = !linkLabel || linkLabel === linkHref || linkLabel === fileId;+ const targetHref = getFileLinkTargetHref({ isShareVisitor, linkHref, proxyHref });++ const handleCopy = useCallback(async () => {+ const href = getFileLinkCopyHref({+ isShareVisitor,+ linkHref,+ origin: getAppOrigin(),+ proxyHref,+ });+ if (!href) return;+ await copyToClipboard(href);+ toast.success(t('copySuccess'));+ }, [isShareVisitor, linkHref, proxyHref, t]);const handleClick = useCallback((event: MouseEvent<HTMLAnchorElement>) => {@@ -79,29 +176,60 @@ const Render = memo<MarkdownElementProps<FileLinkProperties>>(({ node }) => {if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;event.preventDefault();- const action = getFileLinkOpenAction({ fileId, isAgentShareVisitor, label, linkHref });+ const action = getFileLinkOpenAction({ fileId, isShareVisitor, label, proxyHref });if (action.kind === 'newTab') {window.open(action.url, '_blank', 'noopener,noreferrer');return;}openFilePreview(action.params);},- [fileId, isAgentShareVisitor, label, linkHref, openFilePreview],+ [fileId, isShareVisitor, label, openFilePreview, proxyHref],);+ // The owner's link into another scope (a personal file inside a workspace,+ // another workspace's file) cannot preview in this one: it stays an ordinary+ // internal link that navigates there.+ if (linkScope === 'foreign' && !isShareVisitor) {+ return (+ <EntityLinkRender+ node={{+ properties: {+ linkHref,+ linkKind: parseLobeLink(linkHref)?.kind ?? 'generic',+ linkLabel: label,+ },+ }}+ />+ );+ }+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>+ <>+ <A+ {...(fileId ? { [RENDERER_HANDLED_LINK_ATTR]: 'true' } : {})}+ className={styles.link}+ href={targetHref}+ rel="noopener noreferrer"+ onClick={handleClick}+ >+ {fileId && isBareLink && !isShareVisitor ? (+ <OwnedFileLabel fallback={label} fileId={fileId} />+ ) : (+ <FileLabel label={label} />+ )}+ </A>+ {targetHref && (+ <button+ aria-label={t('copy')}+ className={styles.copy}+ title={t('copy')}+ type={'button'}+ onClick={handleCopy}+ >+ <Icon icon={CopyIcon} size={12} />+ </button>+ )}+ </>);});diff --git a/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts b/src/features/Conversation/Markdown/plugins/FileLink/parse.test.tsindex 1adc21e7342..21c49c699c3 100644--- a/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts+++ b/src/features/Conversation/Markdown/plugins/FileLink/parse.test.ts@@ -1,6 +1,13 @@import { describe, expect, it } from 'vitest';-import { getFileLinkOpenAction, parseFileLinkHref } from './parse';+import {+ getFileLinkCopyHref,+ getFileLinkOpenAction,+ getFileLinkTargetHref,+ isShareVisitorContext,+ parseFileLinkHref,+ resolveAppOrigin,+} from './parse';const ORIGIN = 'https://app.lobehub.com';@@ -8,18 +15,18 @@ describe('parseFileLinkHref', () => {it('matches a same-origin absolute file proxy link', () => {expect(parseFileLinkHref(`${ORIGIN}/f/file_abc123`, ORIGIN)).toEqual({fileId: 'file_abc123',+ proxyHref: '/f/file_abc123',+ scope: 'active',});});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' });+ expect(parseFileLinkHref('/f/file_xyz')?.fileId).toBe('file_xyz');+ expect(parseFileLinkHref('/f/file_xyz', ORIGIN)?.fileId).toBe('file_xyz');});it('decodes an encoded file id', () => {- expect(parseFileLinkHref('/f/file%20with%20space', ORIGIN)).toEqual({- fileId: 'file with space',- });+ expect(parseFileLinkHref('/f/file%20with%20space', ORIGIN)?.fileId).toBe('file with space');});it('returns null instead of throwing on a malformed percent-encoded file id', () => {@@ -34,11 +41,11 @@ describe('parseFileLinkHref', () => {// Desktop cloud mode classifies against the gateway apex, while links// written earlier still point at app.lobehub.com.expect(- parseFileLinkHref('https://app.lobehub.com/f/file_abc123', 'https://lobehub.com'),- ).toEqual({ fileId: 'file_abc123' });+ parseFileLinkHref('https://app.lobehub.com/f/file_abc123', 'https://lobehub.com')?.fileId,+ ).toBe('file_abc123');expect(- parseFileLinkHref('https://lobehub.com/f/file_abc123', 'https://app.lobehub.com'),- ).toEqual({ fileId: 'file_abc123' });+ parseFileLinkHref('https://lobehub.com/f/file_abc123', 'https://app.lobehub.com')?.fileId,+ ).toBe('file_abc123');});it('does not treat other official subdomains as the app', () => {@@ -78,11 +85,104 @@ describe('parseFileLinkHref', () => {});});+describe('parseFileLinkHref Docs file links', () => {+ // Regression: `lh file upload` prints `/resource/file/<id>` (and printed+ // `/resource?file=<id>` before), which left the chat for the Docs page+ // instead of previewing beside the conversation.+ it('matches the Docs file path the CLI prints', () => {+ expect(parseFileLinkHref('https://lobehub.com/resource/file/file_ynz', ORIGIN)).toEqual({+ fileId: 'file_ynz',+ proxyHref: '/f/file_ynz',+ scope: 'active',+ });+ });++ // Regression: an absolute `https://app.lobehub.com/f/x` previewed from a page+ // on another origin redirects cross-origin with a tainted Origin, so the+ // bucket refuses the preview's `fetch` of a text file.+ it('keeps the proxy root-relative so it resolves on the reading page', () => {+ expect(+ parseFileLinkHref('https://app.lobehub.com/f/file_ynz', 'https://lobehub.com')?.proxyHref,+ ).toBe('/f/file_ynz');+ });++ it('matches the legacy ?file= Docs link and a library item', () => {+ expect(parseFileLinkHref('https://lobehub.com/resource?file=file_ynz', ORIGIN)?.fileId).toBe(+ 'file_ynz',+ );+ expect(parseFileLinkHref('/resource/library/kb_1?file=file_ynz', ORIGIN)).toEqual({+ fileId: 'file_ynz',+ proxyHref: '/f/file_ynz',+ scope: 'active',+ });+ });++ it('leaves a page opened through ?file= to the entity link', () => {+ expect(parseFileLinkHref('/resource?file=docs_abc', ORIGIN)).toBeNull();+ expect(parseFileLinkHref('/resource/page/abc', ORIGIN)).toBeNull();+ });++ // The legacy `?file=docs_x` redirects to `/resource/file/docs_x`, which+ // Docs opens as a page, so that address must not open the file panel.+ it('leaves a page addressed through the file path to Docs', () => {+ expect(parseFileLinkHref('/resource/file/docs_abc', ORIGIN)).toBeNull();+ });++ it('matches an older upload whose id is a bare UUID', () => {+ const id = '14639096-839f-43f3-92c6-ed4f839c0796';+ expect(parseFileLinkHref(`/resource/file/${id}`, ORIGIN)?.fileId).toBe(id);+ expect(parseFileLinkHref(`/resource?file=${id}`, ORIGIN)?.fileId).toBe(id);+ });++ it('scopes a workspace-prefixed link to the active workspace only', () => {+ const href = `${ORIGIN}/acme/resource/file/file_ynz`;++ expect(parseFileLinkHref(href, ORIGIN, { activeWorkspaceSlug: 'acme' })).toEqual({+ fileId: 'file_ynz',+ proxyHref: '/f/file_ynz',+ scope: 'active',+ });+ expect(parseFileLinkHref(href, ORIGIN, { activeWorkspaceSlug: 'other' })?.scope).toBe(+ 'foreign',+ );+ });++ // Regression: a shared workspace topic is read with no active workspace, so a+ // `/{slug}/resource/file/:id` link was not recognized and the visitor followed+ // the owner's Docs page instead of the public proxy.+ it('recognizes a workspace-prefixed link with no active workspace', () => {+ expect(parseFileLinkHref(`${ORIGIN}/acme/resource/file/file_ynz`, ORIGIN)).toEqual({+ fileId: 'file_ynz',+ proxyHref: '/f/file_ynz',+ scope: 'foreign',+ });+ });++ // Regression: inside a workspace an unprefixed Docs link names a personal+ // file; previewing it by id in the workspace scope showed it as unavailable.+ it('marks an unprefixed Docs link foreign inside a workspace', () => {+ const options = { activeWorkspaceSlug: 'acme' };++ expect(parseFileLinkHref('/resource/file/file_ynz', ORIGIN, options)?.scope).toBe('foreign');+ expect(parseFileLinkHref('/resource?file=file_ynz', ORIGIN, options)?.scope).toBe('foreign');+ // The file proxy is addressed by id alone, in every scope.+ expect(parseFileLinkHref('/f/file_ynz', ORIGIN, options)?.scope).toBe('active');+ });++ it('does not take an unrelated two-segment path for a workspace link', () => {+ expect(parseFileLinkHref('/acme/settings', ORIGIN)).toBeNull();+ });++ it('does not match a Docs path on a foreign host', () => {+ expect(parseFileLinkHref('https://example.com/resource/file/file_ynz', ORIGIN)).toBeNull();+ });+});+describe('getFileLinkOpenAction', () => {- const link = { fileId: 'file_1', label: 'report.md', linkHref: `${ORIGIN}/f/file_1` };+ const link = { fileId: 'file_1', label: 'report.md', proxyHref: `${ORIGIN}/f/file_1` };it('opens the owner-scoped preview by id for the file owner', () => {- expect(getFileLinkOpenAction({ ...link, isAgentShareVisitor: false })).toEqual({+ expect(getFileLinkOpenAction({ ...link, isShareVisitor: false })).toEqual({kind: 'preview',params: { fileId: 'file_1' },});@@ -91,7 +191,7 @@ describe('getFileLinkOpenAction', () => {// Regression: the visitor does not own the creator's file, so the// id-only preview fetched nothing and showed "file unavailable".it('previews from the public /f/:id link on the agent-share visitor page', () => {- expect(getFileLinkOpenAction({ ...link, isAgentShareVisitor: true })).toEqual({+ expect(getFileLinkOpenAction({ ...link, isShareVisitor: true })).toEqual({kind: 'preview',params: { fileId: 'file_1', source: { name: 'report.md', url: `${ORIGIN}/f/file_1` } },});@@ -99,7 +199,75 @@ describe('getFileLinkOpenAction', () => {it('opens the public link in a new tab when the visitor label names no file type', () => {expect(- getFileLinkOpenAction({ ...link, isAgentShareVisitor: true, label: 'Download the deck' }),+ getFileLinkOpenAction({ ...link, isShareVisitor: true, label: 'Download the deck' }),).toEqual({ kind: 'newTab', url: `${ORIGIN}/f/file_1` });});});++describe('isShareVisitorContext', () => {+ it('treats the owner conversation as the owner', () => {+ expect(isShareVisitorContext({})).toBe(false);+ });++ // Regression: a topic-share reader got the owner-scoped preview, which reads+ // the visitor's empty file store and showed the file as unavailable.+ it('treats agent-share and topic-share readers as visitors', () => {+ expect(isShareVisitorContext({ agentShareId: 'share_1' })).toBe(true);+ expect(isShareVisitorContext({ topicShareId: 'share_1' })).toBe(true);+ });+});++describe('getFileLinkCopyHref', () => {+ const link = {+ linkHref: '/resource/file/file_1',+ origin: ORIGIN,+ proxyHref: '/f/file_1',+ };++ it('copies the link as written for the owner, made absolute', () => {+ expect(getFileLinkCopyHref({ ...link, isShareVisitor: false })).toBe(+ `${ORIGIN}/resource/file/file_1`,+ );+ });++ it('copies the public proxy for a share visitor', () => {+ expect(getFileLinkCopyHref({ ...link, isShareVisitor: true })).toBe(`${ORIGIN}/f/file_1`);+ });++ it('copies nothing without an address', () => {+ expect(getFileLinkCopyHref({ isShareVisitor: false, origin: ORIGIN })).toBeUndefined();+ });+});++describe('getFileLinkTargetHref', () => {+ const link = { linkHref: '/resource/file/file_1', proxyHref: '/f/file_1' };++ it('points at the address as written for the owner', () => {+ expect(getFileLinkTargetHref({ ...link, isShareVisitor: false })).toBe('/resource/file/file_1');+ });++ // Regression: on a share page a modifier or middle click followed the anchor's+ // own href, the owner's Docs page, instead of the public proxy.+ it('points a share visitor at the public proxy', () => {+ expect(getFileLinkTargetHref({ ...link, isShareVisitor: true })).toBe('/f/file_1');+ });+});++describe('resolveAppOrigin', () => {+ const sources = {+ remoteServerUrl: () => 'https://hub.example.com/',+ windowOrigin: () => 'app://renderer',+ };++ // Regression: on desktop a copied root-relative link came out as+ // `app://renderer/f/...`, which opens nothing outside the desktop shell.+ it('uses the remote server on desktop, not the renderer origin', () => {+ expect(resolveAppOrigin({ ...sources, isDesktop: true })).toBe('https://hub.example.com');+ });++ it('uses the page origin on the web', () => {+ expect(resolveAppOrigin({ isDesktop: false, ...sources, windowOrigin: () => ORIGIN })).toBe(+ ORIGIN,+ );+ });+});diff --git a/src/features/Conversation/Markdown/plugins/FileLink/parse.ts b/src/features/Conversation/Markdown/plugins/FileLink/parse.tsindex ddf00b8448b..49b55a5a03e 100644--- a/src/features/Conversation/Markdown/plugins/FileLink/parse.ts+++ b/src/features/Conversation/Markdown/plugins/FileLink/parse.ts@@ -20,13 +20,97 @@ const OFFICIAL_APP_ORIGINS = new Set([// this plugin claims the anchor first and gives it its own preview affordance.const FILE_PROXY_PATH_REGEX = /^\/f\/([^/?#]+)\/?$/;+// Where Docs opens an uploaded file: `/resource/file/:fileId` (what `lh` prints),+// the pre-Docs `/resource?file=:fileId`, and a library item+// `/resource/library/:libraryId?file=:fileId`.+const DOCS_FILE_PATH_REGEX = /^\/resource\/file\/([^/?#]+)\/?$/;+const DOCS_FILE_QUERY_PATH_REGEX = /^\/resource(?:\/library\/[^/?#]+)?\/?$/;++// Docs addresses also open pages (`docs_*`), which are not files: the legacy+// `?file=docs_x` redirects to `/resource/file/docs_x`. Only an uploaded file+// previews in the file panel; older uploads carry bare UUID ids, so pages are+// excluded by prefix rather than files matched by one.+const PAGE_ID_PREFIX = 'docs_';++const asUploadedFileId = (id: string | null | undefined): string | null =>+ id && !id.startsWith(PAGE_ID_PREFIX) ? id : null;+export interface ParsedFileLink {fileId: string;+ /**+ * The public `/f/:id` address of the same file, root-relative. A Docs link is+ * a page of the app, readable only in the owner's scope; the proxy is what a+ * share visitor can open. Root-relative keeps the first hop on the page's own+ * origin, so the redirect to storage keeps the Origin the bucket allows and+ * the preview can `fetch` text files (an absolute app address from another+ * origin taints it).+ */+ proxyHref: string;+ /**+ * `active` when the link addresses the scope this client reads (or names no+ * scope: the `/f/:id` proxy is addressed by id alone); `foreign` for a+ * personal-space link inside a workspace or another workspace's link. The+ * owner opens a foreign link by navigating; a share visitor reads every one+ * through the proxy, since a share page has no workspace of its own.+ */+ scope: 'active' | 'foreign';}+export interface ParseFileLinkOptions {+ /**+ * The active workspace's slug. A Docs link written in a workspace is prefixed+ * with its slug; only the active one resolves through this client's file store.+ */+ activeWorkspaceSlug?: string | null;+}++const safeDecode = (value: string): string | null => {+ try {+ return decodeURIComponent(value);+ } catch {+ return null;+ }+};++/** The file id a Docs path names, or null. `pathname` has no workspace prefix. */+const matchDocsFile = (pathname: string, searchParams: URLSearchParams): string | null => {+ const pathMatch = pathname.match(DOCS_FILE_PATH_REGEX);+ if (pathMatch) return asUploadedFileId(safeDecode(pathMatch[1]));++ if (DOCS_FILE_QUERY_PATH_REGEX.test(pathname)) return asUploadedFileId(searchParams.get('file'));++ return null;+};++const isDocsPath = (pathname: string) =>+ pathname === '/resource' || pathname.startsWith('/resource/');++/**+ * Split a Docs link into its scope and its unprefixed Docs path, or null when+ * it is not a Docs path. Workspace routes always carry `/{slug}`, so an+ * unprefixed path is the personal space: active only outside a workspace.+ */+const resolveDocsScope = (+ pathname: string,+ activeWorkspaceSlug?: string | null,+): { docsPathname: string; scope: ParsedFileLink['scope'] } | null => {+ if (isDocsPath(pathname)) {+ return { docsPathname: pathname, scope: activeWorkspaceSlug ? 'foreign' : 'active' };+ }++ const match = pathname.match(/^\/([^/]+)(\/.*)$/);+ if (!match || !isDocsPath(match[2])) return null;++ return {+ docsPathname: match[2],+ scope: safeDecode(match[1]) === activeWorkspaceSlug ? 'active' : 'foreign',+ };+};+export const parseFileLinkHref = (href: string | undefined,currentOrigin?: string,+ { activeWorkspaceSlug }: ParseFileLinkOptions = {},): ParsedFileLink | null => {if (!href) return null;@@ -57,14 +141,21 @@ export const parseFileLinkHref = (}}- const match = url.pathname.match(FILE_PROXY_PATH_REGEX);- if (!match) return null;+ // Root-relative on purpose; see `ParsedFileLink.proxyHref`.+ const toProxyHref = (fileId: string) => `/f/${encodeURIComponent(fileId)}`;- try {- return { fileId: decodeURIComponent(match[1]) };- } catch {- return null;+ const proxyMatch = url.pathname.match(FILE_PROXY_PATH_REGEX);+ if (proxyMatch) {+ const fileId = safeDecode(proxyMatch[1]);+ return fileId ? { fileId, proxyHref: toProxyHref(fileId), scope: 'active' } : null;}++ const docs = resolveDocsScope(url.pathname, activeWorkspaceSlug);+ if (!docs) return null;+ const { docsPathname, scope } = docs;++ const fileId = matchDocsFile(docsPathname, url.searchParams);+ return fileId ? { fileId, proxyHref: toProxyHref(fileId), scope } : null;};// A link label that names a file, e.g. `report.md` or `action-items.csv`.@@ -77,7 +168,7 @@ export type FileLinkOpenAction =/*** What a file link click opens.*- * The agent-share visitor does not own the creator's files, so the portal's+ * A share visitor (agent or topic share) does not own the creator's files, so the portal's* owner-scoped fetch by id finds nothing and shows "file unavailable"; the* `/f/:id` link itself is public by id, so the visitor previews straight from* it. That preview only knows the file through the link label (the FileViewer@@ -87,18 +178,82 @@ export type FileLinkOpenAction =*/export const getFileLinkOpenAction = ({fileId,- isAgentShareVisitor,+ isShareVisitor,label,- linkHref,+ proxyHref,}: {fileId: string;- isAgentShareVisitor: boolean;+ isShareVisitor: boolean;label: string;- linkHref?: string;+ /** The public `/f/:id` address; see {@link ParsedFileLink.proxyHref}. */+ proxyHref?: string;}): FileLinkOpenAction => {- if (!isAgentShareVisitor || !linkHref) return { kind: 'preview', params: { fileId } };+ if (!isShareVisitor || !proxyHref) return { kind: 'preview', params: { fileId } };++ if (!FILE_NAME_WITH_EXTENSION_REGEX.test(label.trim())) {+ return { kind: 'newTab', url: proxyHref };+ }++ return { kind: 'preview', params: { fileId, source: { name: label.trim(), url: proxyHref } } };+};++/**+ * Whether the conversation is read through a share page (agent or topic+ * share). Its reader does not own the creator's files: the owner-scoped file+ * store holds none of them (and is an empty stub during share SSR).+ */+export const isShareVisitorContext = (context: {+ agentShareId?: string | null;+ topicShareId?: string | null;+}): boolean => !!context.agentShareId || !!context.topicShareId;++/**+ * Where the link points for this reader: the address as written for the+ * owner, the public proxy for a share visitor (the Docs page is the owner's+ * scope). The anchor's own `href` uses it too, so a modifier or middle click+ * opens the same target an ordinary click previews.+ */+export const getFileLinkTargetHref = ({+ isShareVisitor,+ linkHref,+ proxyHref,+}: {+ isShareVisitor: boolean;+ linkHref?: string;+ proxyHref?: string;+}): string | undefined => (isShareVisitor ? (proxyHref ?? linkHref) : linkHref);- if (!FILE_NAME_WITH_EXTENSION_REGEX.test(label.trim())) return { kind: 'newTab', url: linkHref };+/** The copy button's address: the link target, made absolute against `origin`. */+export const getFileLinkCopyHref = ({+ origin,+ ...link+}: {+ isShareVisitor: boolean;+ linkHref?: string;+ origin: string;+ proxyHref?: string;+}): string | undefined => {+ const href = getFileLinkTargetHref(link);+ if (!href) return undefined;- return { kind: 'preview', params: { fileId, source: { name: label.trim(), url: linkHref } } };+ try {+ return new URL(href, origin).toString();+ } catch {+ return undefined;+ }};++/**+ * The app server's origin a copied link resolves against. On desktop the+ * renderer's own origin (`app://renderer`) is not that server; the remote+ * server URL is (trailing slashes trimmed, as a self-hosted URL may carry one).+ */+export const resolveAppOrigin = ({+ isDesktop,+ remoteServerUrl,+ windowOrigin,+}: {+ isDesktop: boolean;+ remoteServerUrl: () => string;+ windowOrigin: () => string;+}): string => (isDesktop ? remoteServerUrl().replace(/\/+$/, '') : windowOrigin());diff --git a/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.test.ts b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.test.tsindex 0223a359c99..7a94fa243ca 100644--- a/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.test.ts+++ b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.test.ts@@ -50,6 +50,8 @@ describe('rehypeFileLink', () => {fileId: 'file_abc123',linkHref: href,linkLabel: 'bubble_sort.py',+ linkScope: 'active',+ proxyHref: '/f/file_abc123',});expect(node.children).toEqual([]);});diff --git a/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.ts b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.tsindex 8e732340d64..6f8d6dcb804 100644--- a/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.ts+++ b/src/features/Conversation/Markdown/plugins/FileLink/rehypePlugin.ts@@ -1,6 +1,7 @@import { isDesktop, OFFICIAL_URL } from '@lobechat/const';import { SKIP, visit } from 'unist-util-visit';+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';import { useElectronStore } from '@/store/electron';import { electronSyncSelectors } from '@/store/electron/selectors';@@ -37,10 +38,11 @@ const getCurrentOrigins = (): string[] => {};const parseAgainstOrigins = (href: string | undefined, origins: string[]) => {- if (origins.length === 0) return parseFileLinkHref(href);+ const options = { activeWorkspaceSlug: getActiveWorkspaceSlug() };+ if (origins.length === 0) return parseFileLinkHref(href, undefined, options);for (const origin of origins) {- const parsed = parseFileLinkHref(href, origin);+ const parsed = parseFileLinkHref(href, origin, options);if (parsed) return parsed;}@@ -49,7 +51,8 @@ const parseAgainstOrigins = (href: string | undefined, origins: string[]) => {/*** Rehype plugin that rewrites `<a href="{APP_URL}/f/:fileId">` anchors —- * produced by assistant tool output such as code execution file export —+ * produced by assistant tool output such as code execution file export — and+ * Docs file links (`/resource/file/:fileId`, which `lh file upload` prints)* 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.@@ -71,6 +74,8 @@ export const rehypeFileLink = () => (tree: any) => {fileId: parsed.fileId,linkHref: href,linkLabel: label,+ linkScope: parsed.scope,+ proxyHref: parsed.proxyHref,};return SKIP;diff --git a/src/features/Portal/FilePreview/Header.tsx b/src/features/Portal/FilePreview/Header.tsxnew file mode 100644index 00000000000..60f7234a5bc--- /dev/null+++ b/src/features/Portal/FilePreview/Header.tsx@@ -0,0 +1,25 @@+import { memo } from 'react';++import ShareButton from '@/business/client/features/FileShare/ShareButton';++import PortalHeader from '../components/Header';+import Title from './Title';+import { usePreviewFileItem } from './usePreviewFileItem';++const Header = memo<{ onClose?: () => void }>(({ onClose }) => {+ const { data, fromSource } = usePreviewFileItem();++ return (+ <PortalHeader+ // A preview opened from a share source is someone else's file; a+ // document-coalesced item carries a `docs_*` id over the file it wraps.+ rightExtra={data && !fromSource ? <ShareButton fileId={data.fileId ?? data.id} /> : undefined}+ title={<Title />}+ onClose={onClose}+ />+ );+});++Header.displayName = 'FilePreviewHeader';++export default Header;diff --git a/src/features/Portal/FilePreview/index.ts b/src/features/Portal/FilePreview/index.tsindex 33b69453c37..06faf1a70a7 100644--- a/src/features/Portal/FilePreview/index.ts+++ b/src/features/Portal/FilePreview/index.ts@@ -1,10 +1,12 @@import { type PortalImpl } from '../type';import Body from './Body';+import Header from './Header';import Title from './Title';import { useFilePreviewMoreMenu } from './useMoreMenu';export const FilePreview: PortalImpl = {Body,+ Header,Title,useMoreMenu: useFilePreviewMoreMenu,};diff --git a/src/features/ResourceManager/components/Editor/index.tsx b/src/features/ResourceManager/components/Editor/index.tsxindex f5a47c8932d..f2daf9d96b6 100644--- a/src/features/ResourceManager/components/Editor/index.tsx+++ b/src/features/ResourceManager/components/Editor/index.tsx@@ -6,6 +6,7 @@ import { ArrowLeftIcon, DownloadIcon, InfoIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import ShareButton from '@/business/client/features/FileShare/ShareButton';import NavHeader from '@/features/NavHeader';import { PageAgentProvider } from '@/features/PageEditor/PageAgentProvider';import FileDetailComponent from '@/features/ResourceManager/FileDetail';@@ -98,6 +99,7 @@ const FileEditorCanvas = memo<FileEditorProps>(({ onBack }) => {}right={<Flexbox horizontal gap={8}>+ {fileDetail && <ShareButton fileId={fileDetail.fileId ?? fileDetail.id} />}{fileDetail?.url && (<ActionIconicon={DownloadIcon}diff --git a/src/features/Share/ErrorView.tsx b/src/features/Share/ErrorView.tsxindex 45ae17c4caf..6b604577f1a 100644--- a/src/features/Share/ErrorView.tsx+++ b/src/features/Share/ErrorView.tsx@@ -8,11 +8,17 @@ import { useTranslation } from 'react-i18next';import NotFound from '@/components/404';import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';+import { resolveShareNotFoundCopy, type ShareNotFoundCopy } from './notFoundCopy';++export type { ShareNotFoundCopy } from './notFoundCopy';+interface ShareErrorViewProps {error: unknown;+ /** What a missing share is called on this page; defaults to the topic copy. */+ notFound?: ShareNotFoundCopy;}-const ShareErrorView = memo<ShareErrorViewProps>(({ error }) => {+const ShareErrorView = memo<ShareErrorViewProps>(({ error, notFound }) => {const { t } = useTranslation('chat');const trpcError = error instanceof TRPCClientError ? error : null;@@ -60,12 +66,14 @@ const ShareErrorView = memo<ShareErrorViewProps>(({ error }) => {);}+ const copy = resolveShareNotFoundCopy(notFound, {+ desc: t('sharePage.error.notFound.subtitle'),+ title: t('sharePage.error.notFound.title'),+ });+return (<Center height={'100%'} padding={48}>- <NotFound- desc={t('sharePage.error.notFound.subtitle')}- title={t('sharePage.error.notFound.title')}- />+ <NotFound desc={copy.desc} title={copy.title} /></Center>);});diff --git a/src/features/Share/notFoundCopy.test.ts b/src/features/Share/notFoundCopy.test.tsnew file mode 100644index 00000000000..cd51530023c--- /dev/null+++ b/src/features/Share/notFoundCopy.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { resolveShareNotFoundCopy } from './notFoundCopy';++const topicCopy = { desc: 'This topic does not exist.', title: 'Topic Not Found' };++describe('resolveShareNotFoundCopy', () => {+ it('keeps the topic wording by default', () => {+ expect(resolveShareNotFoundCopy(undefined, topicCopy)).toBe(topicCopy);+ });++ // Regression: a broken file share link reported "Topic Not Found".+ it("uses the page's own wording when it names one", () => {+ const fileCopy = { desc: 'This file does not exist.', title: 'File Not Found' };+ expect(resolveShareNotFoundCopy(fileCopy, topicCopy)).toBe(fileCopy);+ });+});diff --git a/src/features/Share/notFoundCopy.ts b/src/features/Share/notFoundCopy.tsnew file mode 100644index 00000000000..5322f412056--- /dev/null+++ b/src/features/Share/notFoundCopy.ts@@ -0,0 +1,13 @@+export interface ShareNotFoundCopy {+ desc: string;+ title: string;+}++/**+ * What a missing share is called. The topic wording is the default; a share+ * page of another kind (a file) names its own subject.+ */+export const resolveShareNotFoundCopy = (+ pageCopy: ShareNotFoundCopy | undefined,+ topicCopy: ShareNotFoundCopy,+): ShareNotFoundCopy => pageCopy ?? topicCopy;diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 3eb15054438..3023de7e686 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -779,6 +779,7 @@ export const shareKeys = {agentId,]),artifact: def('share:artifact', (id: string) => ['share:artifact', id]),+ file: def('share:file', (shareId: string) => ['share:file', shareId]),pageDocument: def('share:pageDocument', (documentId: string) => ['share:pageDocument',documentId,