🤯 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
🐛 fix(resource): make file-backed documents preview and download correctly (#17432)
Innei8d0e2601f09a
diff --git a/apps/server/src/routers/lambda/document.ts b/apps/server/src/routers/lambda/document.tsindex a4722d21f50..37884ac23fb 100644--- a/apps/server/src/routers/lambda/document.ts+++ b/apps/server/src/routers/lambda/document.ts@@ -14,6 +14,7 @@ import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { DocumentService } from '@/server/services/document';+import { FileService } from '@/server/services/file';import {assertCanEditResource,assertCanPerformResourceAction,@@ -256,7 +257,19 @@ export const documentRouter = router({getDocumentById: documentProcedure.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => {- return ctx.documentService.getDocumentById(input.id);+ const doc = await ctx.documentService.getDocumentById(input.id);+ // `source` is a storage key for file-backed documents; sign it so PDF viewers+ // and downloads receive a usable URL. Absolute URLs (web sources) pass through.+ if (!doc?.source || /^https?:\/\//i.test(doc.source)) return doc;+ const fileService = new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);+ return {+ ...doc,+ source: await fileService.getFileAccessUrl({+ fileId: doc.fileId ?? undefined,+ id: doc.id,+ url: doc.source,+ }),+ };}),listDocumentHistory: documentProcedurediff --git a/src/features/FileViewer/fileType.test.ts b/src/features/FileViewer/fileType.test.tsnew file mode 100644index 00000000000..70492c27f3f--- /dev/null+++ b/src/features/FileViewer/fileType.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';++import { isPdfFile } from './fileType';++describe('isPdfFile', () => {+ it('detects PDF files by MIME type', () => {+ expect(isPdfFile({ fileType: 'pdf' })).toBe(true);+ expect(isPdfFile({ fileType: 'application/pdf' })).toBe(true);+ expect(isPdfFile({ fileType: 'application/pdf; charset=utf-8' })).toBe(true);+ expect(isPdfFile({ fileType: 'APPLICATION/PDF' })).toBe(true);+ expect(isPdfFile({ fileType: 'application/x-pdf' })).toBe(true);+ });++ it('detects PDF files by filename or path extension', () => {+ expect(isPdfFile({ fileName: 'report.PDF' })).toBe(true);+ expect(isPdfFile({ path: '/tmp/demo.pdf' })).toBe(true);+ expect(isPdfFile({ fileName: 'untitled', path: '/tmp/demo.pdf' })).toBe(true);+ expect(isPdfFile({ fileName: '国内大模型蒸馏风波的来龙去脉 (1).pdf' })).toBe(true);+ });++ it('detects PDF documents whose fileType is a MIME string and name has no extension', () => {+ expect(+ isPdfFile({ fileName: '国内大模型蒸馏风波的来龙去脉', fileType: 'application/pdf' }),+ ).toBe(true);+ });++ it('detects PDF documents whose fileType is generic but source path ends with .pdf', () => {+ expect(+ isPdfFile({+ fileName: '国内大模型蒸馏风波的来龙去脉',+ fileType: 'custom/document',+ path: 'assets/495734/a3bedf85-3ccb-43c0-9e94-b526fb435bac.pdf',+ }),+ ).toBe(true);+ });++ it('detects PDF via signed URL path with query string', () => {+ expect(+ isPdfFile({+ fileName: '国内大模型蒸馏风波的来龙去脉',+ fileType: 'custom/document',+ path: 'https://lobechat-cloud.example.r2.cloudflarestorage.com/assets/495734/a3bedf85.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=abc',+ }),+ ).toBe(true);+ });++ it('rejects non-PDF files', () => {+ expect(isPdfFile({ fileName: 'report.docx', fileType: 'application/msword' })).toBe(false);+ expect(isPdfFile({ path: '/tmp/notes.txt' })).toBe(false);+ expect(isPdfFile({ fileType: 'custom/document' })).toBe(false);+ expect(isPdfFile({})).toBe(false);+ });+});diff --git a/src/features/FileViewer/fileType.ts b/src/features/FileViewer/fileType.tsnew file mode 100644index 00000000000..264c1e609f1--- /dev/null+++ b/src/features/FileViewer/fileType.ts@@ -0,0 +1,31 @@+const PDF_FILE_EXTENSIONS = ['.pdf'];+const PDF_FILE_TYPES = new Set(['pdf', 'application/pdf', 'application/x-pdf']);++const normalizeFileType = (fileType?: string | null) =>+ fileType?.split(';')[0].trim().toLowerCase();++// Signed storage URLs carry `?X-Amz-...` query strings; strip query and fragment+// before extension matching so `.pdf?...` still resolves to `.pdf`.+const stripUrlSuffix = (candidate: string) => candidate.split(/[?#]/)[0];++interface PdfFileFields {+ fileName?: string | null;+ fileType?: string | null;+ path?: string | null;+}++export const isPdfFile = ({ fileName, fileType, path }: PdfFileFields): boolean => {+ const normalizedFileType = normalizeFileType(fileType);++ if (normalizedFileType && PDF_FILE_TYPES.has(normalizedFileType)) return true;++ const candidates = [fileName, path].flatMap((candidate) =>+ candidate ? [stripUrlSuffix(candidate).toLowerCase()] : [],+ );++ if (candidates.length === 0) return false;++ return candidates.some((candidate) =>+ PDF_FILE_EXTENSIONS.some((extension) => candidate.endsWith(extension)),+ );+};diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsxindex 7ac5f8817c7..197373e8875 100644--- a/src/features/FileViewer/index.tsx+++ b/src/features/FileViewer/index.tsx@@ -7,6 +7,7 @@ import { memo } from 'react';import { isHtmlFile } from '@/components/HtmlPreview';import { type FileListItem } from '@/types/files';+import { isPdfFile } from './fileType';import NotSupport from './NotSupport';import CodeViewer from './Renderer/Code';import HTMLViewer from './Renderer/HTML';@@ -206,6 +207,8 @@ const ARCHIVE_MIME_TYPES = new Set([]);// Helper function to check file type+// Note: fileType is matched exactly against the MIME set; substring matching would let+// generic values like `custom/document` bleed into MSDoc via the `doc` substring.const matchesFileType = (fileType: string | undefined,fileName: string | undefined,@@ -215,17 +218,10 @@ const matchesFileType = (const lowerFileType = fileType?.toLowerCase();const lowerFileName = fileName?.toLowerCase();- // Check MIME typeif (lowerFileType && mimeTypes.has(lowerFileType)) {return true;}- // Check file extension in fileType- if (lowerFileType && extensions.some((ext) => lowerFileType.includes(ext.slice(1)))) {- return true;- }-- // Check file extension in fileNameif (lowerFileName && extensions.some((ext) => lowerFileName.endsWith(ext))) {return true;}@@ -243,7 +239,7 @@ interface FileViewerProps extends FileListItem {*/const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) => {// PDF files- if (fileType?.toLowerCase() === 'pdf' || name?.toLowerCase().endsWith('.pdf')) {+ if (isPdfFile({ fileName: name, fileType, path: url })) {return <PDFViewer fileId={id} url={url} />;}diff --git a/src/features/ResourceManager/components/Editor/index.tsx b/src/features/ResourceManager/components/Editor/index.tsxindex 485ec9d205f..2023b5eb44a 100644--- a/src/features/ResourceManager/components/Editor/index.tsx+++ b/src/features/ResourceManager/components/Editor/index.tsx@@ -10,7 +10,6 @@ import { useTranslation } from 'react-i18next';import NavHeader from '@/features/NavHeader';import { PageAgentProvider } from '@/features/PageEditor/PageAgentProvider';-import { lambdaQuery } from '@/libs/trpc/client';import FileDetailComponent from '@/routes/(main)/resource/features/FileDetail';import { useResourceManagerStore } from '@/routes/(main)/resource/features/store';import { fileManagerSelectors, useFileStore } from '@/store/file';@@ -36,10 +35,8 @@ const FileDetailSkeleton = () => (const FileDetailModalContent = memo(() => {const currentViewItemId = useResourceManagerStore((s) => s.currentViewItemId);const fromStore = useFileStore(fileManagerSelectors.getFileById(currentViewItemId));- const { data: fromQuery } = lambdaQuery.file.getFileItemById.useQuery(- { id: currentViewItemId ?? '' },- { enabled: !fromStore && !!currentViewItemId },- );+ const useFetchKnowledgeItem = useFileStore((s) => s.useFetchKnowledgeItem);+ const { data: fromQuery } = useFetchKnowledgeItem(!fromStore ? currentViewItemId : undefined);const fileDetail = fromStore ?? fromQuery;return (<Flexbox style={{ minHeight: 260 }}>@@ -69,7 +66,10 @@ const FileEditorCanvas = memo<FileEditorProps>(({ onBack }) => {const currentViewItemId = useResourceManagerStore((s) => s.currentViewItemId);- const fileDetail = useFileStore(fileManagerSelectors.getFileById(currentViewItemId));+ const fromStore = useFileStore(fileManagerSelectors.getFileById(currentViewItemId));+ const useFetchKnowledgeItem = useFileStore((s) => s.useFetchKnowledgeItem);+ const { data: fromFetch } = useFetchKnowledgeItem(!fromStore ? currentViewItemId : undefined);+ const fileDetail = fromStore ?? fromFetch;return (<Flexbox horizontal height={'100%'} width={'100%'}>diff --git a/src/routes/(main)/resource/features/hooks/useInitFileCheck.ts b/src/routes/(main)/resource/features/hooks/useInitFileCheck.tsindex 4366586f6cf..fea8cf93dde 100644--- a/src/routes/(main)/resource/features/hooks/useInitFileCheck.ts+++ b/src/routes/(main)/resource/features/hooks/useInitFileCheck.ts@@ -4,6 +4,7 @@ import { CUSTOM_DOCUMENT_FILE_TYPE, DERIVED_DOCUMENT_SOURCE_TYPE } from '@lobechimport { useEffect } from 'react';import { useSearchParams } from 'react-router';+import { isPdfFile } from '@/features/FileViewer/fileType';import { documentSelectors, useFileStore } from '@/store/file';import { useResourceManagerStore } from '../store';@@ -32,13 +33,16 @@ export const useInitFileCheck = () => {if (fileData || documentData) {const isPDF =- fileData?.fileType?.toLowerCase() === 'pdf' ||- fileData?.fileType?.toLowerCase() === 'application/pdf' ||- fileData?.name?.toLowerCase().endsWith('.pdf') ||- documentData?.fileType?.toLowerCase() === 'pdf' ||- documentData?.fileType?.toLowerCase() === 'application/pdf' ||- documentData?.filename?.toLowerCase().endsWith('.pdf') ||- documentData?.source?.toLowerCase().endsWith('.pdf');+ isPdfFile({+ fileName: fileData?.name,+ fileType: fileData?.fileType,+ path: fileData?.url,+ }) ||+ isPdfFile({+ fileName: documentData?.filename,+ fileType: documentData?.fileType,+ path: documentData?.source,+ });const isPage =!isPDF &&