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(agent-documents): upload and preview original files (#19760)

Inneif0db7ae5b7ab
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index da5a1dc745e..13bb54e2ec4 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -447,6 +447,9 @@ importers:
../../packages/file-loaders:
dependencies:
+ '@lobechat/utils':
+ specifier: workspace:*
+ version: link:../utils
'@xmldom/xmldom':
specifier: ^0.9.10
version: 0.9.10
diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.ts
index 5e0be619c99..66a0695efd1 100644
--- a/apps/server/src/routers/lambda/agentDocument.ts
+++ b/apps/server/src/routers/lambda/agentDocument.ts
@@ -971,6 +971,18 @@ export const agentDocumentRouter = router({
return ctx.agentDocumentService.associateDocument(input.agentId, input.documentId);
}),
+ importFile: agentDocumentProcedureWrite
+ .input(
+ z.object({
+ agentId: z.string(),
+ fileId: z.string(),
+ parentId: z.string().nullish(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ return ctx.agentDocumentService.importFile(input.agentId, input.fileId, input.parentId);
+ }),
+
/**
* Tool-oriented: create document
*/
diff --git a/apps/server/src/services/agentDocuments/index.test.ts b/apps/server/src/services/agentDocuments/index.test.ts
index e6f37654296..90b28df9fc4 100644
--- a/apps/server/src/services/agentDocuments/index.test.ts
+++ b/apps/server/src/services/agentDocuments/index.test.ts
@@ -11,10 +11,12 @@ import {
extractMarkdownH1Title,
} from '@/database/models/agentDocuments';
import { AgentSkillModel } from '@/database/models/agentSkill';
+import { FileModel } from '@/database/models/file';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import type { LobeChatDatabase } from '@/database/type';
import { DocumentService } from '../document';
+import { FileService } from '../file';
import { SkillResourceService } from '../skill/resource';
import { AgentDocumentsService } from './index';
@@ -45,10 +47,18 @@ vi.mock('@/database/models/topicDocument', () => ({
TopicDocumentModel: vi.fn(),
}));
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn(),
+}));
+
vi.mock('../document', () => ({
DocumentService: vi.fn(),
}));
+vi.mock('../file', () => ({
+ FileService: vi.fn(),
+}));
+
vi.mock('../skill/resource', () => ({
SkillResourceService: vi.fn(),
}));
@@ -114,6 +124,12 @@ describe('AgentDocumentsService', () => {
trySaveCurrentDocumentHistory: vi.fn(),
updateDocument: vi.fn(),
};
+ const mockFileModel = {
+ findById: vi.fn(),
+ };
+ const mockFileService = {
+ getFileContent: vi.fn(),
+ };
const mockAgentModel = {
getAgentConfigById: vi.fn(),
};
@@ -144,6 +160,12 @@ describe('AgentDocumentsService', () => {
(DocumentService as any).mockImplementation(function () {
return mockDocumentService;
});
+ (FileModel as any).mockImplementation(function () {
+ return mockFileModel;
+ });
+ (FileService as any).mockImplementation(function () {
+ return mockFileService;
+ });
(SkillResourceService as any).mockImplementation(function () {
return mockSkillResourceService;
});
@@ -1122,6 +1144,179 @@ lossless tool result
});
});
+ describe('importFile', () => {
+ it('creates a file-backed agent document from an uploaded file', async () => {
+ mockFileModel.findById.mockResolvedValue({
+ fileType: 'application/pdf',
+ id: 'file-1',
+ name: 'brief.pdf',
+ url: 's3://brief.pdf',
+ });
+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);
+ mockModel.create.mockResolvedValue({ id: 'ad-1', documentId: 'doc-1' });
+
+ const service = new AgentDocumentsService(db, userId);
+ const result = await service.importFile('agent-1', 'file-1');
+
+ expect(mockFileService.getFileContent).not.toHaveBeenCalled();
+ expect(mockModel.create).toHaveBeenCalledWith('agent-1', 'brief.pdf', '', {
+ fileId: 'file-1',
+ fileType: 'application/pdf',
+ source: 's3://brief.pdf',
+ sourceType: 'file',
+ title: 'brief.pdf',
+ });
+ expect(result).toEqual({ id: 'ad-1', documentId: 'doc-1' });
+ });
+
+ it('creates under the given parent folder', async () => {
+ mockFileModel.findById.mockResolvedValue({
+ fileType: 'application/pdf',
+ id: 'file-1b',
+ name: 'brief.pdf',
+ url: 's3://brief.pdf',
+ });
+ mockModel.findByDocumentId.mockResolvedValue({
+ documentId: 'folder-doc',
+ fileType: DOCUMENT_FOLDER_TYPE,
+ });
+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);
+ mockModel.create.mockResolvedValue({ id: 'ad-1b' });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.importFile('agent-1', 'file-1b', 'folder-doc');
+
+ expect(mockModel.findByParentAndFilename).toHaveBeenCalledWith(
+ 'agent-1',
+ 'folder-doc',
+ 'brief.pdf',
+ );
+ expect(mockModel.create).toHaveBeenCalledWith(
+ 'agent-1',
+ 'brief.pdf',
+ '',
+ expect.objectContaining({ fileId: 'file-1b', parentId: 'folder-doc' }),
+ );
+ });
+
+ it('keeps text uploads file-backed without converting their contents', async () => {
+ mockFileModel.findById.mockResolvedValue({
+ fileType: 'text/markdown',
+ id: 'file-2',
+ name: 'notes.md',
+ url: 's3://notes.md',
+ });
+ mockFileService.getFileContent.mockResolvedValue('# Hello');
+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);
+ mockModel.create.mockResolvedValue({ id: 'ad-2' });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.importFile('agent-1', 'file-2');
+
+ // ROOT CAUSE:
+ // Import converted selected text formats into a second editable Markdown copy.
+ // The file preview must read the original bytes, regardless of filename or MIME.
+ /** @example Importing text keeps its file association without a Markdown snapshot. */
+ expect(mockFileService.getFileContent).not.toHaveBeenCalled();
+ expect(mockModel.create).toHaveBeenCalledWith(
+ 'agent-1',
+ 'notes.md',
+ '',
+ expect.objectContaining({
+ fileId: 'file-2',
+ sourceType: 'file',
+ }),
+ );
+ });
+
+ it('uniques a colliding filename with a spaced suffix', async () => {
+ mockFileModel.findById.mockResolvedValue({
+ fileType: 'text/plain',
+ id: 'file-3',
+ name: 'notes.md',
+ url: 's3://notes.md',
+ });
+ mockFileService.getFileContent.mockResolvedValue('body');
+ mockModel.findByParentAndFilename
+ .mockResolvedValueOnce({ id: 'existing' })
+ .mockResolvedValueOnce(undefined);
+ mockModel.create.mockResolvedValue({ id: 'ad-3' });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.importFile('agent-1', 'file-3');
+
+ expect(mockModel.findByParentAndFilename).toHaveBeenNthCalledWith(
+ 1,
+ 'agent-1',
+ null,
+ 'notes.md',
+ );
+ expect(mockModel.findByParentAndFilename).toHaveBeenNthCalledWith(
+ 2,
+ 'agent-1',
+ null,
+ 'notes 2.md',
+ );
+ expect(mockModel.create).toHaveBeenCalledWith(
+ 'agent-1',
+ 'notes 2.md',
+ '',
+ expect.objectContaining({ fileId: 'file-3' }),
+ );
+ });
+
+ it('rejects a parent that is not a folder', async () => {
+ mockFileModel.findById.mockResolvedValue({
+ fileType: 'application/pdf',
+ id: 'file-4b',
+ name: 'brief.pdf',
+ url: 's3://brief.pdf',
+ });
+ mockModel.findByDocumentId.mockResolvedValue({ fileType: 'agent/document', id: 'doc-row' });
+
+ const service = new AgentDocumentsService(db, userId);
+
+ await expect(service.importFile('agent-1', 'file-4b', 'doc-row')).rejects.toThrow(
+ 'Parent document is not a folder: doc-row',
+ );
+ expect(mockModel.create).not.toHaveBeenCalled();
+ });
+
+ it('rejects a missing parent folder', async () => {
+ mockFileModel.findById.mockResolvedValue({
+ fileType: 'application/pdf',
+ id: 'file-4',
+ name: 'brief.pdf',
+ url: 's3://brief.pdf',
+ });
+ mockModel.findByDocumentId.mockResolvedValue(undefined);
+
+ const service = new AgentDocumentsService(db, userId);
+
+ await expect(service.importFile('agent-1', 'file-4', 'missing-folder')).rejects.toThrow(
+ 'Parent folder not found: missing-folder',
+ );
+ expect(mockModel.create).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse an existing document for the same file', async () => {
+ mockFileModel.findById.mockResolvedValue({
+ fileType: 'application/pdf',
+ id: 'file-5',
+ name: 'brief.pdf',
+ url: 's3://brief.pdf',
+ });
+ mockModel.findByParentAndFilename.mockResolvedValue(undefined);
+ mockModel.create.mockResolvedValue({ id: 'ad-5' });
+
+ const service = new AgentDocumentsService(db, userId);
+ await service.importFile('agent-1', 'file-5');
+
+ expect(mockModel.create).toHaveBeenCalled();
+ expect(mockModel.associate).not.toHaveBeenCalled();
+ });
+ });
+
describe('getAgentSkills', () => {
// Inject docs with the derive flags already set so we test the
// bundle → index-child → identifier mapping in isolation, not the
diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.ts
index 8a41a4ebc72..b0c02a836ed 100644
--- a/apps/server/src/services/agentDocuments/index.ts
+++ b/apps/server/src/services/agentDocuments/index.ts
@@ -26,6 +26,7 @@ import {
deriveAgentDocumentFields,
extractMarkdownH1Title,
} from '@/database/models/agentDocuments';
+import { FileModel } from '@/database/models/file';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import { isUuid } from '@/database/utils/uuid';
@@ -42,7 +43,6 @@ import {
} from './headlessEditor';
const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;
-
const appendFilenameSuffix = (filename: string, suffix: number): string => {
const dotIndex = filename.lastIndexOf('.');
@@ -51,6 +51,14 @@ const appendFilenameSuffix = (filename: string, suffix: number): string => {
return `${filename.slice(0, dotIndex)}-${suffix}${filename.slice(dotIndex)}`;
};
+const appendSpacedFilenameSuffix = (filename: string, suffix: number): string => {
+ const dotIndex = filename.lastIndexOf('.');
+
+ if (dotIndex <= 0) return `${filename} ${suffix}`;
+
+ return `${filename.slice(0, dotIndex)} ${suffix}${filename.slice(dotIndex)}`;
+};
+
interface UpsertDocumentParams {
agentId: string;
content: string;
@@ -147,6 +155,7 @@ const toAgentDocumentContextPayload = (
export class AgentDocumentsService {
private agentDocumentModel: AgentDocumentModel;
private documentService: DocumentService;
+ private fileModel: FileModel;
private topicDocumentModel: TopicDocumentModel;
constructor(
@@ -167,6 +176,7 @@ export class AgentDocumentsService {
callerAgentVisibility,
documentAccessScope,
);
+ this.fileModel = new FileModel(db, userId, workspaceId);
this.topicDocumentModel = new TopicDocumentModel(db, userId, workspaceId, documentAccessScope);
}
@@ -527,6 +537,61 @@ export class AgentDocumentsService {
return this.agentDocumentModel.associate({ agentId, documentId });
}
+ /**
+ * Attach an uploaded file to the agent's document tree without converting its bytes.
+ *
+ * Use when:
+ * - An upload has completed and needs an entry in the agent's space.
+ *
+ * Expects:
+ * - An accessible file and, when supplied, a folder belonging to this agent.
+ *
+ * Returns:
+ * - A new file-backed document binding with a unique filename in its parent.
+ */
+ async importFile(agentId: string, fileId: string, parentId?: string | null) {
+ const file = await this.fileModel.findById(fileId);
+ if (!file) throw new Error(`File not found: ${fileId}`);
+
+ if (parentId) {
+ const parent = await this.agentDocumentModel.findByDocumentId(agentId, parentId);
+ if (!parent) throw new Error(`Parent folder not found: ${parentId}`);
+ if (parent.fileType !== DOCUMENT_FOLDER_TYPE) {
+ throw new Error(`Parent document is not a folder: ${parentId}`);
+ }
+ }
+
+ const resolvedParentId = parentId ?? null;
+ const baseFilename = buildDocumentFilename(file.name);
+ let filename = baseFilename;
+ let suffix = 2;
+
+ while (
+ await this.agentDocumentModel.findByParentAndFilename(agentId, resolvedParentId, filename)
+ ) {
+ if (suffix > MAX_UNIQUE_FILENAME_ATTEMPTS) {
+ throw new Error(
+ `Unable to generate a unique filename for "${file.name}" after ${MAX_UNIQUE_FILENAME_ATTEMPTS} attempts.`,
+ );
+ }
+
+ filename = appendSpacedFilenameSuffix(baseFilename, suffix);
+ suffix += 1;
+ }
+
+ const createParams = {
+ fileId: file.id,
+ fileType: file.fileType || 'application/octet-stream',
+ ...(resolvedParentId ? { parentId: resolvedParentId } : {}),
+ source: file.url,
+ sourceType: 'file' as const,
+ title: file.name,
+ };
+
+ // Imported bytes stay in files; preview reads the original rather than an editable copy.
+ return this.agentDocumentModel.create(agentId, filename, '', createParams);
+ }
+
async createDocument(
agentId: string,
title: string,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index b8bb39c8666..e299e33fc26 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2682,6 +2682,8 @@
"workingPanel.resources.tree.rename": "Rename",
"workingPanel.resources.tree.untitledDocument": "Untitled document",
"workingPanel.resources.tree.untitledFolder": "Untitled folder",
+ "workingPanel.resources.tree.uploadError": "Failed to upload",
+ "workingPanel.resources.tree.uploadFile": "Upload file",
"workingPanel.resources.updatedAt": "Updated {{time}}",
"workingPanel.resources.viewMode.list": "List view",
"workingPanel.resources.viewMode.tree": "Tree view",
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index c4f050b92cd..c2c93a16914 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -243,6 +243,7 @@
"preview.downloadFile": "Download File",
"preview.raw": "Raw",
"preview.render": "Preview",
+ "preview.tooLarge": "This file is too large to preview. Download it to view its contents.",
"preview.unsupportedFileAndContact": "This file format is not currently supported for online preview. If you have a request for previewing, feel free to <1>contact us</1>.",
"resource": "Resource",
"resourceList.batchCopyDescription": "You can copy to personal or workspaces that have permission to create resources.",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 81f50a7ea63..c5743c7feda 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2682,6 +2682,8 @@
"workingPanel.resources.tree.rename": "重命名",
"workingPanel.resources.tree.untitledDocument": "未命名文档",
"workingPanel.resources.tree.untitledFolder": "未命名文件夹",
+ "workingPanel.resources.tree.uploadError": "上传失败",
+ "workingPanel.resources.tree.uploadFile": "上传文件",
"workingPanel.resources.updatedAt": "更新于 {{time}}",
"workingPanel.resources.viewMode.list": "列表视图",
"workingPanel.resources.viewMode.tree": "树状视图",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 75a0f9fec16..4858d2e0b6e 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -243,6 +243,7 @@
"preview.downloadFile": "下载文件",
"preview.raw": "原文",
"preview.render": "预览",
+ "preview.tooLarge": "文件过大,无法在线预览。请下载后查看。",
"preview.unsupportedFileAndContact": "此文件格式暂不支持在线预览,如有预览诉求,欢迎<1>反馈给我们</1>",
"resource": "资源",
"resourceList.batchCopyDescription": "您可以拷贝到有权限创建资源的个人账户或工作区。",
diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
index 9730110b02b..9ef162746a2 100644
--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
@@ -9,7 +9,7 @@ import { and, eq } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import { agentDocuments, agents, documents, users } from '../../../schemas';
+import { agentDocuments, agents, documents, files, users } from '../../../schemas';
import {
AGENT_SKILL_TEMPLATE_ID,
DOCUMENT_FOLDER_TYPE,
@@ -202,6 +202,39 @@ describe('AgentDocumentModel', () => {
expect(created.source).toBe(`agent-document://${agentId}/brief`);
});
+ it('persists fileId on a file-backed document', async () => {
+ const [file] = await serverDB
+ .insert(files)
+ .values({
+ fileType: 'application/pdf',
+ name: 'brief.pdf',
+ size: 12,
+ url: 's3://brief.pdf',
+ userId,
+ })
+ .returning();
+
+ const created = await agentDocumentModel.create(agentId, 'brief.pdf', '', {
+ fileId: file!.id,
+ fileType: 'application/pdf',
+ sourceType: 'file',
+ });
+
+ const [doc] = await serverDB
+ .select()
+ .from(documents)
+ .where(eq(documents.id, created.documentId));
+
+ expect(doc?.fileId).toBe(file!.id);
+ /** @example Both tree and topic-scoped lists retain the original-file preview target. */
+ expect((await agentDocumentModel.listByAgent(agentId))[0].fileId).toBe(file!.id);
+ expect(
+ (await agentDocumentModel.listByDocumentIds(agentId, [created.documentId]))[0].fileId,
+ ).toBe(file!.id);
+ expect(doc?.sourceType).toBe('file');
+ expect(doc?.filename).toBe('brief.pdf');
+ });
+
it('allows trusted callers to set document source attribution', async () => {
const created = await agentDocumentModel.create(agentId, 'skill-a', 'content', {
source: 'agent-signal:skill-management',
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index 6d1c3ce9510..71dd2a365d1 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -62,6 +62,7 @@ interface AgentDocumentQueryOptions {
interface AgentDocumentCreateParams {
createdAt?: Date;
editorData?: Record<string, any>;
+ fileId?: string;
fileType?: string;
loadPosition?: DocumentLoadPosition;
loadRules?: DocumentLoadRules;
@@ -91,6 +92,7 @@ interface ConvertAgentDocumentToSkillIndexParams {
interface AgentDocumentListQueryRow {
description: string | null;
documentId: string;
+ fileId: string | null;
filename: string | null;
fileType: string;
id: string;
@@ -236,6 +238,7 @@ export class AgentDocumentModel {
const item = {
description: row.description ?? null,
documentId: row.documentId,
+ fileId: row.fileId,
fileType: row.fileType,
filename,
id: row.id,
@@ -418,6 +421,7 @@ export class AgentDocumentModel {
const {
createdAt,
editorData,
+ fileId,
fileType = AGENT_DOCUMENT_FILE_TYPE,
loadPosition,
loadRules,
@@ -453,6 +457,7 @@ export class AgentDocumentModel {
filename,
parentId,
metadata: scopedMetadata,
+ ...(fileId ? { fileId } : {}),
source: source ?? `agent-document://${agentId}/${encodeURIComponent(filename)}`,
sourceType,
title,
@@ -1041,6 +1046,7 @@ export class AgentDocumentModel {
.select({
description: documents.description,
documentId: agentDocuments.documentId,
+ fileId: documents.fileId,
fileType: documents.fileType,
filename: documents.filename,
id: agentDocuments.id,
@@ -1223,6 +1229,7 @@ export class AgentDocumentModel {
.select({
description: documents.description,
documentId: agentDocuments.documentId,
+ fileId: documents.fileId,
fileType: documents.fileType,
filename: documents.filename,
id: agentDocuments.id,
diff --git a/packages/database/src/models/agentDocuments/types.ts b/packages/database/src/models/agentDocuments/types.ts
index 8a10314bd72..b7c8f1ea45d 100644
--- a/packages/database/src/models/agentDocuments/types.ts
+++ b/packages/database/src/models/agentDocuments/types.ts
@@ -83,9 +83,12 @@ export interface AgentDocumentWithRules extends AgentDocument, AgentDocumentDeri
loadRules: DocumentLoadRules;
}
+/** A document-tree entry with its optional original uploaded file. */
export interface AgentDocumentListItem extends AgentDocumentDerivedFields {
description: string | null;
documentId: string;
+ /** Original file to preview; absent for editable agent documents. */
+ fileId?: string | null;
filename: string;
fileType: string;
id: string;
diff --git a/packages/file-loaders/package.json b/packages/file-loaders/package.json
index c6c4d181270..c12bd36b9ec 100644
--- a/packages/file-loaders/package.json
+++ b/packages/file-loaders/package.json
@@ -25,6 +25,7 @@
"test:coverage": "vitest --coverage --silent='passed-only'"
},
"dependencies": {
+ "@lobechat/utils": "workspace:*",
"@xmldom/xmldom": "^0.9.10",
"concat-stream": "^2.0.0",
"debug": "^4.4.3",
diff --git a/packages/file-loaders/src/utils/detectUtf16.ts b/packages/file-loaders/src/utils/detectUtf16.ts
index 96da44901dd..cb5f88b586c 100644
--- a/packages/file-loaders/src/utils/detectUtf16.ts
+++ b/packages/file-loaders/src/utils/detectUtf16.ts
@@ -1,37 +1,2 @@
-const HEURISTIC_SAMPLE_BYTES = 512;
-const HEURISTIC_THRESHOLD = 0.3;
-
-export type Utf16Variant = 'utf-16le' | 'utf-16be';
-
-/**
- * Detect UTF-16 without BOM by sampling and counting ASCII-shaped code-unit
- * pairs. ASCII chars in UTF-16 produce a 0x00 byte at the high half: at
- * odd index for LE, at even index for BE.
- *
- * Used both by `TextLoader` (to pick the right decoder) and by the binary
- * sniffer (so a UTF-16 text file without BOM isn't mistaken for binary
- * because of its alternating null bytes).
- */
-export const detectUtf16NoBom = (buffer: Buffer): Utf16Variant | null => {
- const sample = buffer.subarray(0, Math.min(HEURISTIC_SAMPLE_BYTES, buffer.length));
- if (sample.length < 4 || sample.length % 2 !== 0) return null;
-
- let leAsciiPairs = 0;
- let beAsciiPairs = 0;
- const totalPairs = sample.length / 2;
-
- for (let i = 0; i < sample.length; i += 2) {
- const lo = sample[i];
- const hi = sample[i + 1];
- if (hi === 0x00 && lo !== 0x00) leAsciiPairs++;
- else if (lo === 0x00 && hi !== 0x00) beAsciiPairs++;
- }
-
- if (leAsciiPairs > beAsciiPairs && leAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
- return 'utf-16le';
- }
- if (beAsciiPairs > leAsciiPairs && beAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
- return 'utf-16be';
- }
- return null;
-};
+// Shared with browser file previews so encoding detection stays consistent.
+export { detectUtf16NoBom, type Utf16Variant } from '@lobechat/utils/detectUtf16';
diff --git a/packages/file-loaders/src/utils/isBinaryContent.ts b/packages/file-loaders/src/utils/isBinaryContent.ts
index 11d1c7e5385..f3481d83e9e 100644
--- a/packages/file-loaders/src/utils/isBinaryContent.ts
+++ b/packages/file-loaders/src/utils/isBinaryContent.ts
@@ -1,80 +1,11 @@
import { open } from 'node:fs/promises';
-import { detectUtf16NoBom } from './detectUtf16';
+import type { BinarySniffResult } from '@lobechat/utils/isBinaryContent';
+import { sniffBinaryBuffer } from '@lobechat/utils/isBinaryContent';
-const SNIFF_BYTES = 8192;
-const NON_PRINTABLE_THRESHOLD = 0.3;
-
-export interface BinarySniffResult {
- isBinary: boolean;
- reason?: string;
-}
-
-const hasUtf8Bom = (buf: Buffer): boolean =>
- buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf;
-
-const hasUtf16Bom = (buf: Buffer): boolean =>
- buf.length >= 2 && ((buf[0] === 0xff && buf[1] === 0xfe) || (buf[0] === 0xfe && buf[1] === 0xff));
-
-/**
- * Heuristically determine if a buffer looks like binary data.
- *
- * - UTF-8 / UTF-16 BOM → text
- * - UTF-16 detected without BOM (Windows-style exports) → text, decoded for
- * the printable-ratio check
- * - Any null byte (and not UTF-16) → binary
- * - More than 30% of decoded chars are control or U+FFFD replacement → binary
- *
- * Note: this only catches truly binary content. Text-encoded blobs (e.g., a
- * single 27KB line of base64) will pass this check — the extension whitelist
- * and the post-load char cap are what stop those.
- */
-export const sniffBinaryBuffer = (buffer: Buffer): BinarySniffResult => {
- if (buffer.length === 0) return { isBinary: false };
-
- if (hasUtf8Bom(buffer) || hasUtf16Bom(buffer)) return { isBinary: false };
-
- const utf16Variant = detectUtf16NoBom(buffer);
- if (utf16Variant) {
- const text = new TextDecoder(utf16Variant, { fatal: false }).decode(buffer);
- return checkPrintableRatio(text, buffer.length);
- }
-
- if (buffer.includes(0)) {
- return { isBinary: true, reason: 'contains null byte' };
- }
-
- const text = new TextDecoder('utf-8', { fatal: false }).decode(buffer);
- return checkPrintableRatio(text, buffer.length);
-};
+export { type BinarySniffResult, sniffBinaryBuffer } from '@lobechat/utils/isBinaryContent';
-const REPLACEMENT_CHAR = '�';
-
-const checkPrintableRatio = (text: string, sampledBytes: number): BinarySniffResult => {
- if (text.length === 0) return { isBinary: false };
-
- let suspect = 0;
- for (const ch of text) {
- if (ch === REPLACEMENT_CHAR) {
- suspect++;
- continue;
- }
- const code = ch.codePointAt(0)!;
- if (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
- suspect++;
- }
- }
-
- const ratio = suspect / text.length;
- if (ratio > NON_PRINTABLE_THRESHOLD) {
- return {
- isBinary: true,
- reason: `${(ratio * 100).toFixed(1)}% non-printable chars in first ${sampledBytes} bytes`,
- };
- }
-
- return { isBinary: false };
-};
+const SNIFF_BYTES = 8192;
/**
* Read up to the leading 8KB of a file and run the binary heuristic on it.
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 5cbee5b4429..d57b2f5519d 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2732,6 +2732,8 @@ export default {
'workingPanel.resources.tree.rename': 'Rename',
'workingPanel.resources.tree.untitledDocument': 'Untitled document',
'workingPanel.resources.tree.untitledFolder': 'Untitled folder',
+ 'workingPanel.resources.tree.uploadError': 'Failed to upload',
+ 'workingPanel.resources.tree.uploadFile': 'Upload file',
'workingPanel.resources.updatedAt': 'Updated {{time}}',
'workingPanel.resources.viewMode.list': 'List view',
'workingPanel.resources.viewMode.tree': 'Tree view',
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index d0331e85aff..712ef41d159 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -298,6 +298,7 @@ export default {
'resourceList.transferTo': 'Move to…',
'resourceList.viewTransferred': 'View',
'portal.openInPageEditor': 'Edit in Page',
+ 'preview.tooLarge': 'This file is too large to preview. Download it to view its contents.',
'preview.downloadFile': 'Download File',
'preview.raw': 'Raw',
'preview.render': 'Preview',
diff --git a/packages/utils/src/detectUtf16.ts b/packages/utils/src/detectUtf16.ts
new file mode 100644
index 00000000000..7b92996c443
--- /dev/null
+++ b/packages/utils/src/detectUtf16.ts
@@ -0,0 +1,47 @@
+const HEURISTIC_SAMPLE_BYTES = 512;
+const HEURISTIC_THRESHOLD = 0.3;
+
+/** UTF-16 byte ordering supported by the shared text detector. */
+export type Utf16Variant = 'utf-16le' | 'utf-16be';
+
+/**
+ * Detect UTF-16 without BOM by sampling and counting ASCII-shaped code-unit
+ * pairs. ASCII chars in UTF-16 produce a 0x00 byte at the high half: at
+ * odd index for LE, at even index for BE.
+ *
+ * Used both by `TextLoader` (to pick the right decoder) and by the binary
+ * sniffer (so a UTF-16 text file without BOM isn't mistaken for binary
+ * because of its alternating null bytes).
+ *
+ * Use when:
+ * - Selecting a decoder for bytes without an encoding marker.
+ *
+ * Expects:
+ * - Raw file bytes; only the first 512 bytes are sampled.
+ *
+ * Returns:
+ * - A likely UTF-16 byte order, or null when the sample is inconclusive.
+ */
+export const detectUtf16NoBom = (buffer: Uint8Array): Utf16Variant | null => {
+ const sample = buffer.subarray(0, Math.min(HEURISTIC_SAMPLE_BYTES, buffer.length));
+ if (sample.length < 4 || sample.length % 2 !== 0) return null;
+
+ let leAsciiPairs = 0;
+ let beAsciiPairs = 0;
+ const totalPairs = sample.length / 2;
+
+ for (let i = 0; i < sample.length; i += 2) {
+ const lo = sample[i];
+ const hi = sample[i + 1];
+ if (hi === 0x00 && lo !== 0x00) leAsciiPairs++;
+ else if (lo === 0x00 && hi !== 0x00) beAsciiPairs++;
+ }
+
+ if (leAsciiPairs > beAsciiPairs && leAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
+ return 'utf-16le';
+ }
+ if (beAsciiPairs > leAsciiPairs && beAsciiPairs / totalPairs >= HEURISTIC_THRESHOLD) {
+ return 'utf-16be';
+ }
+ return null;
+};
diff --git a/packages/utils/src/imageToBase64.ts b/packages/utils/src/imageToBase64.ts
index 083b603001e..bd2868c0765 100644
--- a/packages/utils/src/imageToBase64.ts
+++ b/packages/utils/src/imageToBase64.ts
@@ -1,6 +1,9 @@
import { Buffer } from 'buffer.js';
import { resolveMimeTypeFromBytes } from './imageMimeType';
+import { readBlobWithLimit } from './readBlobWithLimit';
+
+export { readBlobWithLimit } from './readBlobWithLimit';
export const imageToBase64 = ({
size,
@@ -45,48 +48,6 @@ export interface ImageUrlToBase64Options {
maxBytes?: number;
}
-const sizeLimitError = (maxBytes: number) =>
- new RangeError(`Remote binary exceeds the ${maxBytes}-byte download limit`);
-
-export const readBlobWithLimit = async (response: Response, maxBytes: number): Promise<Blob> => {
- const declaredLength = Number(response.headers.get('content-length'));
- if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
- await response.body?.cancel().catch(() => {});
- throw sizeLimitError(maxBytes);
- }
-
- if (!response.body) {
- const blob = await response.blob();
- if (blob.size > maxBytes) throw sizeLimitError(maxBytes);
- return blob;
- }
-
- const reader = response.body.getReader();
- const chunks: Uint8Array[] = [];
- let receivedBytes = 0;
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
-
- receivedBytes += value.byteLength;
- if (receivedBytes > maxBytes) {
- await reader.cancel();
- throw sizeLimitError(maxBytes);
- }
- chunks.push(value);
- }
-
- const bytes = new Uint8Array(receivedBytes);
- let offset = 0;
- for (const chunk of chunks) {
- bytes.set(chunk, offset);
- offset += chunk.byteLength;
- }
-
- return new Blob([bytes], { type: response.headers.get('content-type') || '' });
-};
-
/**
* Convert image URL to base64
* Uses SSRF-safe fetch on server-side to prevent SSRF attacks
diff --git a/packages/utils/src/isBinaryContent.ts b/packages/utils/src/isBinaryContent.ts
new file mode 100644
index 00000000000..bae349d0c77
--- /dev/null
+++ b/packages/utils/src/isBinaryContent.ts
@@ -0,0 +1,115 @@
+import { detectUtf16NoBom } from './detectUtf16';
+
+const NON_PRINTABLE_THRESHOLD = 0.3;
+
+/** Result of heuristic byte inspection, independent of filename and MIME. */
+export interface BinarySniffResult {
+ /** Whether sampled bytes look binary rather than readable text. */
+ isBinary: boolean;
+ /** Human-readable explanation when the bytes look binary. */
+ reason?: string;
+}
+
+const hasUtf8Bom = (buf: Uint8Array): boolean =>
+ buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf;
+
+const hasUtf16Bom = (buf: Uint8Array): boolean =>
+ buf.length >= 2 && ((buf[0] === 0xff && buf[1] === 0xfe) || (buf[0] === 0xfe && buf[1] === 0xff));
+
+/**
+ * Heuristically determine if a buffer looks like binary data.
+ *
+ * - UTF-8 / UTF-16 BOM → text
+ * - UTF-16 detected without BOM (Windows-style exports) → text, decoded for
+ * the printable-ratio check
+ * - Any null byte (and not UTF-16) → binary
+ * - More than 30% of decoded chars are control or U+FFFD replacement → binary
+ *
+ * Note: this only catches truly binary content. Text-encoded blobs (e.g., a
+ * single 27KB line of base64) will pass this check. The former loader-specific
+ * comment described an extension whitelist and post-load cap; callers now
+ * own their format policy and size limits.
+ *
+ * Use when:
+ * - Checking raw bytes before attempting text decoding.
+ *
+ * Expects:
+ * - A byte buffer bounded or sampled by the caller.
+ *
+ * Returns:
+ * - A heuristic binary verdict and an optional reason.
+ */
+export const sniffBinaryBuffer = (buffer: Uint8Array): BinarySniffResult => {
+ if (buffer.length === 0) return { isBinary: false };
+
+ if (hasUtf8Bom(buffer) || hasUtf16Bom(buffer)) return { isBinary: false };
+
+ const utf16Variant = detectUtf16NoBom(buffer);
+ if (utf16Variant) {
+ const text = new TextDecoder(utf16Variant, { fatal: false }).decode(buffer);
+ return checkPrintableRatio(text, buffer.length);
+ }
+
+ if (buffer.includes(0)) {
+ return { isBinary: true, reason: 'contains null byte' };
+ }
+
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(buffer);
+ return checkPrintableRatio(text, buffer.length);
+};
+
+const REPLACEMENT_CHAR = '�';
+
+const checkPrintableRatio = (text: string, sampledBytes: number): BinarySniffResult => {
+ if (text.length === 0) return { isBinary: false };
+
+ let suspect = 0;
+ for (const ch of text) {
+ if (ch === REPLACEMENT_CHAR) {
+ suspect++;
+ continue;
+ }
+ const code = ch.codePointAt(0)!;
+ if (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
+ suspect++;
+ }
+ }
+
+ const ratio = suspect / text.length;
+ if (ratio > NON_PRINTABLE_THRESHOLD) {
+ return {
+ isBinary: true,
+ reason: `${(ratio * 100).toFixed(1)}% non-printable chars in first ${sampledBytes} bytes`,
+ };
+ }
+
+ return { isBinary: false };
+};
+
+/**
+ * Decode a previewable UTF-8 or UTF-16 text buffer without relying on its filename.
+ *
+ * Use when:
+ * - Showing original uploaded bytes as read-only text.
+ *
+ * Expects:
+ * - A buffer already bounded by the caller's preview size limit.
+ *
+ * Returns:
+ * - Decoded text (including empty text), or null for binary/unsupported encoding.
+ */
+export const decodeTextBuffer = (buffer: Uint8Array): string | null => {
+ if (sniffBinaryBuffer(buffer).isBinary) return null;
+
+ const encoding = hasUtf16Bom(buffer)
+ ? buffer[0] === 0xff
+ ? 'utf-16le'
+ : 'utf-16be'
+ : (detectUtf16NoBom(buffer) ?? 'utf8');
+ try {
+ // Reject invalid encoding rather than replacing original bytes with replacement characters.
+ return new TextDecoder(encoding, { fatal: true }).decode(buffer);
+ } catch {
+ return null;
+ }
+};
diff --git a/packages/utils/src/readBlobWithLimit.ts b/packages/utils/src/readBlobWithLimit.ts
new file mode 100644
index 00000000000..1553b2614bf
--- /dev/null
+++ b/packages/utils/src/readBlobWithLimit.ts
@@ -0,0 +1,53 @@
+const sizeLimitError = (maxBytes: number) =>
+ new RangeError(`Remote binary exceeds the ${maxBytes}-byte download limit`);
+
+/**
+ * Read a response body while enforcing a byte limit, including chunked responses.
+ *
+ * Use when:
+ * - Downloading a remote file into memory for a bounded preview or conversion.
+ *
+ * Expects:
+ * - An unread response and a positive maximum byte count.
+ *
+ * Returns:
+ * - A blob, or throws RangeError after cancelling an oversized response.
+ */
+export const readBlobWithLimit = async (response: Response, maxBytes: number): Promise<Blob> => {
+ const declaredLength = Number(response.headers.get('content-length'));
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
+ await response.body?.cancel().catch(() => {});
+ throw sizeLimitError(maxBytes);
+ }
+
+ if (!response.body) {
+ const blob = await response.blob();
+ if (blob.size > maxBytes) throw sizeLimitError(maxBytes);
+ return blob;
+ }
+
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let receivedBytes = 0;
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ receivedBytes += value.byteLength;
+ if (receivedBytes > maxBytes) {
+ await reader.cancel();
+ throw sizeLimitError(maxBytes);
+ }
+ chunks.push(value);
+ }
+
+ const bytes = new Uint8Array(receivedBytes);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+
+ return new Blob([bytes], { type: response.headers.get('content-type') || '' });
+};
diff --git a/src/features/AgentDocumentPage/Header/index.tsx b/src/features/AgentDocumentPage/Header/index.tsx
index eb20347cd2f..f1a1b5463e8 100644
--- a/src/features/AgentDocumentPage/Header/index.tsx
+++ b/src/features/AgentDocumentPage/Header/index.tsx
@@ -23,6 +23,8 @@ interface HeaderProps {
agentDocumentId?: string;
agentId: string;
documentId: string;
+ /** Hide editor-only actions for original uploaded files. */
+ fileBacked?: boolean;
itemError?: unknown;
onBack: () => void;
onDeleted: () => void;
@@ -31,7 +33,17 @@ interface HeaderProps {
}
const Header = memo<HeaderProps>(
- ({ agentId, agentDocumentId, documentId, itemError, onBack, onDeleted, title, updatedAt }) => {
+ ({
+ agentId,
+ agentDocumentId,
+ documentId,
+ fileBacked,
+ itemError,
+ onBack,
+ onDeleted,
+ title,
+ updatedAt,
+ }) => {
const { t } = useTranslation(['file', 'chat']);
const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId));
const showTitleError = !!itemError && !title;
@@ -43,6 +55,7 @@ const Header = memo<HeaderProps>(
agentId,
documentId,
onDeleted,
+ fileBacked,
title,
updatedAt,
});
@@ -82,8 +95,8 @@ const Header = memo<HeaderProps>(
}
right={
<Flexbox horizontal align={'center'} gap={4}>
- {documentId && <AutoSaveHint documentId={documentId} />}
- {documentId && <ShareButton documentId={documentId} />}
+ {documentId && !fileBacked && <AutoSaveHint documentId={documentId} />}
+ {documentId && !fileBacked && <ShareButton documentId={documentId} />}
<ToggleRightPanelButton hideWhenExpanded />
</Flexbox>
}
diff --git a/src/features/AgentDocumentPage/Header/useMenu.tsx b/src/features/AgentDocumentPage/Header/useMenu.tsx
index dbb114c158b..bf61cc360de 100644
--- a/src/features/AgentDocumentPage/Header/useMenu.tsx
+++ b/src/features/AgentDocumentPage/Header/useMenu.tsx
@@ -20,6 +20,7 @@ interface UseMenuParams {
agentDocumentId?: string;
agentId: string;
documentId: string;
+ fileBacked?: boolean;
onDeleted: () => void;
title?: string;
updatedAt?: Date | string | null;
@@ -34,6 +35,7 @@ export const useMenu = ({
agentDocumentId,
agentId,
documentId,
+ fileBacked,
onDeleted,
title,
updatedAt,
@@ -169,7 +171,9 @@ export const useMenu = ({
);
}
- return items;
+ return fileBacked
+ ? items.filter((item) => item?.key !== 'export' && item?.key !== 'full-width')
+ : items;
}, [
activeWorkspaceSlug,
agentDocumentId,
@@ -177,6 +181,7 @@ export const useMenu = ({
appOrigin,
documentId,
editor,
+ fileBacked,
lg,
dateLocale,
onDeleted,
diff --git a/src/features/AgentDocumentPage/index.test.tsx b/src/features/AgentDocumentPage/index.test.tsx
index 3f7e81dbc6b..f99f1d8ca6a 100644
--- a/src/features/AgentDocumentPage/index.test.tsx
+++ b/src/features/AgentDocumentPage/index.test.tsx
@@ -9,6 +9,12 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import AgentDocumentPage from './index';
+vi.mock('@/features/FileViewer/FileDocumentPreview', () => ({
+ FileDocumentPreview: ({ fileId }: { fileId?: string | null }) => (
+ <div data-file-id={fileId} data-testid="original-file-preview" />
+ ),
+}));
+
vi.mock('react-router', () => ({
useParams: () => ({ aid: 'agent-from-url' }),
}));
@@ -97,6 +103,23 @@ vi.mock('@/features/FloatingChatPanel', () => ({
}));
describe('AgentDocumentPage', () => {
+ /** @example Opening an imported file as a page preserves its original-file preview. */
+ it('previews uploads instead of mounting the page editor', () => {
+ // ROOT CAUSE:
+ // The standalone route always mounted PageEditor, even for file-backed records.
+ // It now uses the same file preview as the chat portal and keeps the document chat panel.
+ agentDocumentItemState.current.item = {
+ fileId: 'file-original',
+ filename: 'source.unknown',
+ id: 'agent-document-1',
+ };
+ render(<AgentDocumentPage documentId="docs_uploaded" />);
+ /** @example The uploaded file renders without an editable copy. */
+ expect(screen.getByTestId('original-file-preview').dataset.fileId).toBe('file-original');
+ expect(screen.queryByTestId('page-editor')).toBeNull();
+ expect(screen.getByTestId('floating-chat-panel')).toBeTruthy();
+ });
+
beforeEach(() => {
agentDocumentItemState.current = {
error: undefined,
diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsx
index 9aaea02b2e8..4d46388fe67 100644
--- a/src/features/AgentDocumentPage/index.tsx
+++ b/src/features/AgentDocumentPage/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import { EditorProvider } from '@lobehub/editor/react';
import { Flexbox } from '@lobehub/ui';
import { memo, useCallback, useEffect, useMemo } from 'react';
import { useParams } from 'react-router';
@@ -7,12 +8,14 @@ import { useParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import { type ComposerTarget, createComposerTarget } from '@/features/Conversation/types';
+import { FileDocumentPreview } from '@/features/FileViewer/FileDocumentPreview';
import FloatingChatPanel from '@/features/FloatingChatPanel';
import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';
import { PageEditor } from '@/features/PageEditor';
import RightPanel from '@/features/RightPanel';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { getDocumentRenderMode } from '@/utils/documentRenderMode';
import Header from './Header';
import { buildAgentDocumentsPath } from './navigation';
@@ -99,12 +102,15 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
? skillBundle.title || skillBundle.filename || item?.title || item?.filename
: item?.title || item?.filename;
+ const isFile = !!item && getDocumentRenderMode(item).mode === 'file';
+
const header = useMemo(
() => (
<Header
agentDocumentId={item?.id}
agentId={agentId}
documentId={documentId}
+ fileBacked={isFile}
itemError={itemError}
title={title}
updatedAt={item?.updatedAt}
@@ -112,7 +118,17 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
onDeleted={backToDocs}
/>
),
- [agentId, backToChat, backToDocs, documentId, item?.id, item?.updatedAt, itemError, title],
+ [
+ agentId,
+ backToChat,
+ backToDocs,
+ documentId,
+ item?.id,
+ item?.updatedAt,
+ itemError,
+ isFile,
+ title,
+ ],
);
// Genuinely-absent doc (deleted or bad deep link): render nothing while the
@@ -133,24 +149,31 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
width={'100%'}
>
<Flexbox flex={1} style={{ minHeight: 0 }} width={'100%'}>
- <PageEditor
- fullWidthHeader
- askCopilotTarget={askCopilotTarget}
- header={header}
- key={documentId}
- // A skill index's visible name is the bundle title; renaming must go
- // through the skill APIs, so lock the page title/emoji here. A plain
- // title save would overwrite the `SKILL.md` filename and desync the
- // bundle (and the bundle rename API rejects managed skill docs anyway).
- metaReadOnly={isSkillIndex}
- pageId={documentId}
- rightPanel={false}
- syncPageAgentActiveState={false}
- title={title}
- // Refresh the list so the breadcrumb and working-sidebar entry pick up
- // the new title after the shared page save persists it.
- onTitleChange={() => mutate()}
- />
+ {isFile ? (
+ <EditorProvider>
+ {header}
+ <FileDocumentPreview fileId={item?.fileId} />
+ </EditorProvider>
+ ) : (
+ <PageEditor
+ fullWidthHeader
+ askCopilotTarget={askCopilotTarget}
+ header={header}
+ key={documentId}
+ // A skill index's visible name is the bundle title; renaming must go
+ // through the skill APIs, so lock the page title/emoji here. A plain
+ // title save would overwrite the `SKILL.md` filename and desync the
+ // bundle (and the bundle rename API rejects managed skill docs anyway).
+ metaReadOnly={isSkillIndex}
+ pageId={documentId}
+ rightPanel={false}
+ syncPageAgentActiveState={false}
+ title={title}
+ // Refresh the list so the breadcrumb and working-sidebar entry pick up
+ // the new title after the shared page save persists it.
+ onTitleChange={() => mutate()}
+ />
+ )}
</Flexbox>
{chatAgentId && docChatTopicId && (
<RightPanel expand defaultWidth={400} maxWidth={720} minWidth={320}>
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx
index 19b32011e07..53305f61adb 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx
@@ -1,17 +1,13 @@
import { Flexbox, Icon } from '@lobehub/ui';
import { ActionIcon, type DropdownItem, DropdownMenu, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import { FilePlusIcon, FolderPlusIcon, PlusIcon } from 'lucide-react';
-import { memo, useMemo } from 'react';
+import { FilePlusIcon, FileUp, FolderPlusIcon, PlusIcon } from 'lucide-react';
+import { memo, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
const styles = createStaticStyles(({ css, cssVar }) => ({
toolbar: css`
- /* padding-inline start matches a tree row's content edge:
- --trees-padding-inline (4) - --trees-item-margin-x (4), clamped at 0,
- plus the row's own margin (4) and padding (8). */
- padding-block: 8px 4px;
- padding-inline: 12px 8px;
+ margin-inline: 6px;
color: ${cssVar.colorTextSecondary};
`,
title: css`
@@ -25,43 +21,71 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface Props {
onCreateDocument: () => void;
onCreateFolder: () => void;
+ onUploadFiles: (files: File[]) => void;
}
-const DocumentExplorerToolbar = memo<Props>(({ onCreateDocument, onCreateFolder }) => {
- const { t } = useTranslation('chat');
- const createMenuItems = useMemo<DropdownItem[]>(
- () => [
- {
- icon: <Icon icon={FilePlusIcon} />,
- key: 'new-document',
- label: t('workingPanel.resources.tree.newDocument'),
- onClick: onCreateDocument,
- },
- {
- icon: <Icon icon={FolderPlusIcon} />,
- key: 'new-folder',
- label: t('workingPanel.resources.tree.newFolder'),
- onClick: onCreateFolder,
- },
- ],
- [onCreateDocument, onCreateFolder, t],
- );
+const DocumentExplorerToolbar = memo<Props>(
+ ({ onCreateDocument, onCreateFolder, onUploadFiles }) => {
+ const { t } = useTranslation('chat');
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const createMenuItems = useMemo<DropdownItem[]>(
+ () => [
+ {
+ icon: <Icon icon={FilePlusIcon} />,
+ key: 'new-document',
+ label: t('workingPanel.resources.tree.newDocument'),
+ onClick: onCreateDocument,
+ },
+ {
+ icon: <Icon icon={FolderPlusIcon} />,
+ key: 'new-folder',
+ label: t('workingPanel.resources.tree.newFolder'),
+ onClick: onCreateFolder,
+ },
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={FileUp} />,
+ key: 'upload-file',
+ label: t('workingPanel.resources.tree.uploadFile'),
+ onClick: () => fileInputRef.current?.click(),
+ },
+ ],
+ [onCreateDocument, onCreateFolder, t],
+ );
- return (
- <Flexbox horizontal align={'center'} className={styles.toolbar} distribution={'space-between'}>
- <Text className={styles.title} type={'secondary'}>
- {t('workingPanel.resources.filter.documents')}
- </Text>
- <DropdownMenu items={createMenuItems} placement={'bottomRight'}>
- <ActionIcon
- icon={PlusIcon}
- size={'small'}
- title={t('workingPanel.resources.tree.create')}
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.toolbar}
+ distribution={'space-between'}
+ >
+ <Text className={styles.title} type={'secondary'}>
+ {t('workingPanel.resources.filter.documents')}
+ </Text>
+ <DropdownMenu items={createMenuItems} placement={'bottomRight'}>
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={t('workingPanel.resources.tree.create')}
+ />
+ </DropdownMenu>
+ <input
+ hidden
+ multiple
+ ref={fileInputRef}
+ type={'file'}
+ onChange={(event) => {
+ const files = Array.from(event.target.files ?? []);
+ event.target.value = '';
+ if (files.length === 0) return;
+ onUploadFiles(files);
+ }}
/>
- </DropdownMenu>
- </Flexbox>
- );
-});
+ </Flexbox>
+ );
+ },
+);
DocumentExplorerToolbar.displayName = 'DocumentExplorerToolbar';
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
index 48bf53e0967..1efbabbb47b 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
@@ -43,15 +43,17 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
items,
}: {
children: ReactNode;
- items: { key: string; label: string; onClick: () => void }[];
+ items: { key?: string; label?: string; onClick?: () => void; type?: string }[];
}) => (
<div>
{children}
- {items.map((item) => (
- <button data-testid={`create-menu-${item.key}`} key={item.key} onClick={item.onClick}>
- {item.label}
- </button>
- ))}
+ {items
+ .filter((item) => item.type !== 'divider' && item.key)
+ .map((item) => (
+ <button data-testid={`create-menu-${item.key}`} key={item.key} onClick={item.onClick}>
+ {item.label}
+ </button>
+ ))}
</div>
),
}));
@@ -233,6 +235,28 @@ describe('DocumentExplorerTree', () => {
expect(screen.getByTestId('create-menu-new-folder')).toHaveTextContent(
'workingPanel.resources.tree.newFolder',
);
+ expect(screen.getByTestId('create-menu-upload-file')).toHaveTextContent(
+ 'workingPanel.resources.tree.uploadFile',
+ );
+ });
+
+ it('offers upload on a folder context menu', () => {
+ const data = [
+ createDocument({
+ documentId: 'folder-doc',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ filename: 'Notes',
+ id: 'folder-row',
+ isFolder: true,
+ title: 'Notes',
+ }),
+ ];
+
+ render(<DocumentExplorerTree agentId="agent-1" data={data} mutate={vi.fn()} />, {
+ wrapper: MemoryRouter,
+ });
+
+ expect(screen.getByTestId('tree-menu-folder-row-upload-file')).toBeInTheDocument();
});
it('renders managed skill bundle as a folder with SKILL.md underneath', () => {
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
index c86c3537e14..f11986a0b0a 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx
@@ -3,7 +3,7 @@ import { Center, Empty, Flexbox, Icon } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import { createStaticStyles } from 'antd-style';
import { FileTextIcon, Maximize2Icon, PenLineIcon, Trash2Icon } from 'lucide-react';
-import type { CSSProperties } from 'react';
+import type { ChangeEvent, CSSProperties } from 'react';
import { memo, useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { KeyedMutator } from 'swr';
@@ -107,6 +107,8 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
const navigate = useWorkspaceAwareNavigate();
const treeRef = useRef<ExplorerTreeHandle | null>(null);
const containerRef = useRef<HTMLDivElement | null>(null);
+ const folderUploadInputRef = useRef<HTMLInputElement | null>(null);
+ const folderUploadParentIdRef = useRef<string | null>(null);
const startInlineRename = useCallback((id: string) => {
treeRef.current?.startRenaming(id);
@@ -211,6 +213,20 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
ops.createDocument(parentId, { onPendingInserted: focusNewRowForRename }),
[focusNewRowForRename, ops],
);
+ const openFolderFilePicker = useCallback((parentId: string | null) => {
+ folderUploadParentIdRef.current = parentId;
+ folderUploadInputRef.current?.click();
+ }, []);
+ const handleFolderUploadChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(event.target.files ?? []);
+ const parentId = folderUploadParentIdRef.current;
+ event.target.value = '';
+ if (files.length === 0) return;
+ void ops.uploadFiles(parentId, files);
+ },
+ [ops],
+ );
const handleConvertToSkill = useCallback(
(doc: AgentDocumentItem) => {
@@ -346,6 +362,12 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
onClick: () => handleCreateDocument(targetParentId),
sfSymbol: 'doc.badge.plus',
},
+ {
+ key: 'upload-file',
+ label: t('workingPanel.resources.tree.uploadFile'),
+ onClick: () => openFolderFilePicker(targetParentId),
+ sfSymbol: 'square.and.arrow.up',
+ },
{ key: 'div-1', type: 'divider' },
);
}
@@ -375,7 +397,11 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
// Only plain agent documents (not folders, web sources, or existing
// skills) can be migrated into a managed skill.
const isConvertibleToSkill =
- !isFolder && !isSkill && node.data?.category === AGENT_DOCUMENT_CATEGORY;
+ !isFolder &&
+ !isSkill &&
+ !node.data?.fileId &&
+ node.data?.sourceType !== 'file' &&
+ node.data?.category === AGENT_DOCUMENT_CATEGORY;
if (isConvertibleToSkill && !isMulti) {
items.push({
icon: <Icon icon={SkillsIcon} size={14} />,
@@ -405,6 +431,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
handleCreateDocument,
handleCreateFolder,
isRecoverableSkillBundle,
+ openFolderFilePicker,
navigate,
ops,
startInlineRename,
@@ -416,11 +443,19 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, onOpenDocumen
<DocumentExplorerToolbar
onCreateDocument={() => handleCreateDocument(null)}
onCreateFolder={() => handleCreateFolder(null)}
+ onUploadFiles={(files) => void ops.uploadFiles(null, files)}
/>
);
return (
<div className={styles.tree} ref={containerRef} style={treeStyle}>
+ <input
+ hidden
+ multiple
+ ref={folderUploadInputRef}
+ type={'file'}
+ onChange={handleFolderUploadChange}
+ />
{nodes.length === 0 ? (
// Keep the toolbar reachable (new folder / new doc) above the placeholder.
<Flexbox height={'100%'}>
diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts
new file mode 100644
index 00000000000..63582ada901
--- /dev/null
+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.test.ts
@@ -0,0 +1,156 @@
+import { CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentDocumentItem } from '../types';
+import { useDocumentTreeOps } from './useDocumentTreeOps';
+
+const toastError = vi.hoisted(() => vi.fn());
+const importFileMock = vi.hoisted(() => vi.fn());
+const uploadWithProgressMock = vi.hoisted(() => vi.fn());
+const dispatchDockFileListMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ confirmModal: vi.fn(),
+ toast: { error: toastError, success: vi.fn() },
+}));
+
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: {
+ importFile: importFileMock,
+ },
+}));
+
+vi.mock('@/store/file', () => ({
+ useFileStore: {
+ getState: () => ({
+ dispatchDockFileList: dispatchDockFileListMock,
+ uploadWithProgress: uploadWithProgressMock,
+ }),
+ },
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+const createDoc = (overrides: Partial<AgentDocumentItem> = {}): AgentDocumentItem =>
+ ({
+ category: 'document',
+ description: null,
+ documentId: 'folder-doc',
+ filename: 'Notes',
+ fileType: CUSTOM_FOLDER_FILE_TYPE,
+ id: 'folder-row',
+ isFolder: true,
+ isSkillBundle: false,
+ isSkillIndex: false,
+ parentId: null,
+ sourceType: 'agent',
+ templateId: null,
+ title: 'Notes',
+ updatedAt: new Date(),
+ ...overrides,
+ }) as AgentDocumentItem;
+
+describe('useDocumentTreeOps.uploadFiles', () => {
+ const mutate = vi.fn();
+
+ beforeEach(() => {
+ toastError.mockReset();
+ importFileMock.mockReset();
+ uploadWithProgressMock.mockReset();
+ dispatchDockFileListMock.mockReset();
+ mutate.mockReset();
+ importFileMock.mockResolvedValue({ id: 'ad-1' });
+ uploadWithProgressMock.mockResolvedValue({ id: 'file-1' });
+ });
+
+ it('uploads then imports at the tree root', async () => {
+ const { result } = renderHook(() =>
+ useDocumentTreeOps({ agentId: 'agent-1', data: [], mutate }),
+ );
+
+ await result.current.uploadFiles(null, [
+ new File(['hi'], 'notes.md', { type: 'text/markdown' }),
+ ]);
+
+ expect(dispatchDockFileListMock).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'addFiles' }),
+ );
+ expect(uploadWithProgressMock).toHaveBeenCalledWith(
+ expect.objectContaining({ skipCheckFileType: true }),
+ );
+ expect(importFileMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ fileId: 'file-1',
+ parentId: null,
+ });
+ expect(mutate).toHaveBeenCalled();
+ });
+
+ it('imports into the selected folder', async () => {
+ const { result } = renderHook(() =>
+ useDocumentTreeOps({ agentId: 'agent-1', data: [createDoc()], mutate }),
+ );
+
+ await result.current.uploadFiles('folder-row', [
+ new File(['hi'], 'notes.md', { type: 'text/markdown' }),
+ ]);
+
+ expect(importFileMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ fileId: 'file-1',
+ parentId: 'folder-doc',
+ });
+ });
+
+ it('skips import when upload is cancelled', async () => {
+ uploadWithProgressMock.mockResolvedValue(undefined);
+
+ const { result } = renderHook(() =>
+ useDocumentTreeOps({ agentId: 'agent-1', data: [], mutate }),
+ );
+
+ await result.current.uploadFiles(null, [
+ new File(['hi'], 'notes.md', { type: 'text/markdown' }),
+ ]);
+
+ expect(importFileMock).not.toHaveBeenCalled();
+ expect(mutate).not.toHaveBeenCalled();
+ });
+
+ it('toasts a per-file import failure and continues', async () => {
+ uploadWithProgressMock
+ .mockResolvedValueOnce({ id: 'file-1' })
+ .mockResolvedValueOnce({ id: 'file-2' });
+ importFileMock.mockRejectedValueOnce(new Error('boom')).mockResolvedValueOnce({ id: 'ad-2' });
+
+ const { result } = renderHook(() =>
+ useDocumentTreeOps({ agentId: 'agent-1', data: [], mutate }),
+ );
+
+ await result.current.uploadFiles(null, [
+ new File(['a'], 'a.md', { type: 'text/markdown' }),
+ new File(['b'], 'b.md', { type: 'text/markdown' }),
+ ]);
+
+ expect(toastError).toHaveBeenCalled();
+ expect(importFileMock).toHaveBeenCalledTimes(2);
+ expect(mutate).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores blacklisted system files', async () => {
+ const { result } = renderHook(() =>
+ useDocumentTreeOps({ agentId: 'agent-1', data: [], mutate }),
+ );
+
+ await result.current.uploadFiles(null, [new File([''], '.DS_Store')]);
+
+ expect(uploadWithProgressMock).not.toHaveBeenCalled();
+ expect(importFileMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
index bab91c0db1f..8d2fb1ec7ab 100644
--- a/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
+++ b/src/features/AgentDocumentsExplorer/hooks/useDocumentTreeOps.ts
@@ -1,10 +1,13 @@
import { confirmModal, toast } from '@lobehub/ui/base-ui';
+import { nanoid } from 'nanoid';
import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import type { KeyedMutator } from 'swr';
+import { FILE_UPLOAD_BLACKLIST } from '@/const/file';
import { useSingleton } from '@/hooks/useSingleton';
import { agentDocumentService } from '@/services/agentDocument';
+import { useFileStore } from '@/store/file';
import type { AgentDocumentItem } from '../types';
import { isPendingId, isProtectedManagedSkillItem } from '../types';
@@ -52,6 +55,7 @@ export interface DocumentTreeOps {
targetId: string | null;
}) => Promise<void>;
renameDocument: (id: string, newName: string) => Promise<void>;
+ uploadFiles: (parentId: string | null, files: File[]) => Promise<void>;
}
export const useDocumentTreeOps = ({
@@ -237,6 +241,59 @@ export const useDocumentTreeOps = ({
[agentId, buildParentPathFromRowId, byRowId, mutate, pendingCreates, pickUniqueFilename, t],
);
+ const uploadFiles = useCallback(
+ async (parentId: string | null, files: File[]) => {
+ const parentPath = buildParentPathFromRowId(parentId);
+ if (parentPath === null) {
+ toast.error(t('workingPanel.resources.tree.parentMissing'));
+ return;
+ }
+
+ const accepted = files.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));
+ if (accepted.length === 0) return;
+
+ const parentDocumentId = parentId ? (byRowId.get(parentId)?.documentId ?? null) : null;
+ const { dispatchDockFileList, uploadWithProgress } = useFileStore.getState();
+
+ for (const file of accepted) {
+ const abortController = new AbortController();
+ const uploadId = `upload_${nanoid(12)}`;
+
+ dispatchDockFileList({
+ atStart: true,
+ files: [{ abortController, file, id: uploadId, status: 'pending' }],
+ type: 'addFiles',
+ });
+
+ try {
+ const result = await uploadWithProgress({
+ abortController,
+ file,
+ onStatusUpdate: dispatchDockFileList,
+ skipCheckFileType: true,
+ uploadId,
+ });
+
+ if (!result?.id) continue;
+
+ await agentDocumentService.importFile({
+ agentId,
+ fileId: result.id,
+ parentId: parentDocumentId,
+ });
+ await mutate();
+ } catch (error) {
+ toast.error(
+ error instanceof Error
+ ? `${t('workingPanel.resources.tree.uploadError')}: ${error.message}`
+ : t('workingPanel.resources.tree.uploadError'),
+ );
+ }
+ }
+ },
+ [agentId, buildParentPathFromRowId, byRowId, mutate, t],
+ );
+
const renameDocument = useCallback(
async (id: string, newName: string) => {
const target = dataRef.current.find((doc) => doc.id === id);
@@ -486,7 +543,8 @@ export const useDocumentTreeOps = ({
deleteDocuments,
moveDocument,
renameDocument,
+ uploadFiles,
}),
- [createDocument, createFolder, deleteDocuments, moveDocument, renameDocument],
+ [createDocument, createFolder, deleteDocuments, moveDocument, renameDocument, uploadFiles],
);
};
diff --git a/src/features/ExplorerTree/view/__snapshots__/ExplorerTree.test.tsx.snap b/src/features/ExplorerTree/view/__snapshots__/ExplorerTree.test.tsx.snap
index ad64e0d09ee..182a9a9994f 100644
--- a/src/features/ExplorerTree/view/__snapshots__/ExplorerTree.test.tsx.snap
+++ b/src/features/ExplorerTree/view/__snapshots__/ExplorerTree.test.tsx.snap
@@ -21,17 +21,23 @@ exports[`DocumentExplorerTree menu ownership > goes native for the folder row co
"sfSymbol": "doc.badge.plus",
"type": "normal",
},
+ {
+ "id": "2",
+ "label": "workingPanel.resources.tree.uploadFile",
+ "sfSymbol": "square.and.arrow.up",
+ "type": "normal",
+ },
{
"type": "separator",
},
{
- "id": "3",
+ "id": "4",
"label": "workingPanel.resources.tree.rename",
"sfSymbol": "pencil",
"type": "normal",
},
{
- "id": "4",
+ "id": "5",
"label": "delete",
"sfSymbol": "trash",
"type": "normal",
diff --git a/src/features/FileViewer/FileDocumentPreview.tsx b/src/features/FileViewer/FileDocumentPreview.tsx
new file mode 100644
index 00000000000..ae3ab69d923
--- /dev/null
+++ b/src/features/FileViewer/FileDocumentPreview.tsx
@@ -0,0 +1,61 @@
+import { Flexbox } from '@lobehub/ui';
+import { Button, Text } from '@lobehub/ui/base-ui';
+import { DownloadIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import Loading from '@/components/Loading/CircleLoading';
+import FileNotFound from '@/features/FileNotFound';
+import { normalizeAsyncError } from '@/libs/swr/normalizeError';
+import { useFileStore } from '@/store/file';
+import { downloadFile } from '@/utils/client/downloadFile';
+import { formatSize } from '@/utils/format';
+
+import FileViewer from './index';
+
+/** Reference to the original upload; null means the backing file has been deleted. */
+interface FileDocumentPreviewProps {
+ /** Original files-table id, not the document-tree id. */
+ fileId?: string | null;
+}
+
+/**
+ * Show an agent document's original upload with file metadata and download access.
+ *
+ * Use when:
+ * - A chat portal or document page displays a file-backed document.
+ *
+ * Expects:
+ * - A files-table id; a missing or revoked file renders the not-found state.
+ *
+ * Returns:
+ * - A read-only file preview, never an editable copy of document content.
+ */
+export const FileDocumentPreview = ({ fileId }: FileDocumentPreviewProps) => {
+ const { t } = useTranslation('file');
+ const useFetchKnowledgeItem = useFileStore((s) => s.useFetchKnowledgeItem);
+ const { data, error, isLoading, mutate } = useFetchKnowledgeItem(fileId ?? undefined);
+
+ if (isLoading) return <Loading />;
+ if (error && normalizeAsyncError(error).status !== 404)
+ return <AsyncError error={error} variant={'block'} onRetry={() => void mutate()} />;
+ if (error || !data) return <FileNotFound />;
+
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0 }}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'} padding={12}>
+ <Text ellipsis type={'secondary'}>
+ {data.name} · {formatSize(data.size)}
+ </Text>
+ {data.url && (
+ <Button icon={DownloadIcon} onClick={() => downloadFile(data.url!, data.name)}>
+ {t('preview.downloadFile')}
+ </Button>
+ )}
+ </Flexbox>
+ <Flexbox flex={1} style={{ minHeight: 0, overflow: 'auto' }}>
+ <FileViewer {...data} key={fileId} />
+ </Flexbox>
+ </Flexbox>
+ );
+};
diff --git a/src/features/FileViewer/NotSupport/index.tsx b/src/features/FileViewer/NotSupport/index.tsx
index bb24393668e..2997f55a68b 100644
--- a/src/features/FileViewer/NotSupport/index.tsx
+++ b/src/features/FileViewer/NotSupport/index.tsx
@@ -23,10 +23,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface NotSupportProps {
fileName?: string;
style?: CSSProperties;
+ /** Explain a bounded-preview limit instead of claiming the format is unsupported. */
+ tooLarge?: boolean;
url?: string | null;
}
-const NotSupport: ComponentType<NotSupportProps> = ({ fileName, url, style }) => {
+const NotSupport: ComponentType<NotSupportProps> = ({ fileName, url, style, tooLarge }) => {
const { t } = useTranslation('file');
const [loading, setLoading] = useState(false);
@@ -36,20 +38,24 @@ const NotSupport: ComponentType<NotSupportProps> = ({ fileName, url, style }) =>
<Flexbox align={'center'} gap={12}>
<FluentEmoji emoji={'👀'} size={64} />
<Flexbox style={{ textAlign: 'center' }}>
- <Trans
- i18nKey="preview.unsupportedFileAndContact"
- ns={'file'}
- components={[
- <span key="0" />,
- <a
- aria-label={'todo'}
- href={MORE_FILE_PREVIEW_REQUEST_URL}
- key="1"
- rel="noreferrer"
- target="_blank"
- />,
- ]}
- />
+ {tooLarge ? (
+ t('preview.tooLarge')
+ ) : (
+ <Trans
+ i18nKey="preview.unsupportedFileAndContact"
+ ns={'file'}
+ components={[
+ <span key="0" />,
+ <a
+ aria-label={'todo'}
+ href={MORE_FILE_PREVIEW_REQUEST_URL}
+ key="1"
+ rel="noreferrer"
+ target="_blank"
+ />,
+ ]}
+ />
+ )}
</Flexbox>
{url && (
<Button
diff --git a/src/features/FileViewer/Renderer/Code/index.tsx b/src/features/FileViewer/Renderer/Code/index.tsx
index 0d6b200fd80..d502a9d6fcd 100644
--- a/src/features/FileViewer/Renderer/Code/index.tsx
+++ b/src/features/FileViewer/Renderer/Code/index.tsx
@@ -4,10 +4,12 @@ import { Center, Flexbox, Highlighter } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
+import AsyncError from '@/components/AsyncError';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { getLanguageFromFilename } from '@/utils/fileLanguage';
import { useTextFileLoader } from '../../hooks/useTextFileLoader';
+import NotSupport from '../../NotSupport';
const styles = createStaticStyles(({ css }) => ({
page: css`
@@ -24,12 +26,20 @@ interface CodeViewerProps {
}
const CodeViewer = memo<CodeViewerProps>(({ url, fileName }) => {
- const { fileData, loading } = useTextFileLoader(url);
+ const { error, fileData, loading, tooLarge } = useTextFileLoader(url);
const language = getLanguageFromFilename(fileName);
+ if (!loading && fileData === null)
+ return (
+ <Flexbox>
+ {error && <AsyncError error={error} variant={'block'} />}
+ <NotSupport fileName={fileName} tooLarge={tooLarge} url={url} />
+ </Flexbox>
+ );
+
return (
<Flexbox className={styles.page}>
- {!loading && fileData ? (
+ {!loading && fileData !== null ? (
<Highlighter language={language} showLanguage={false} variant={'borderless'}>
{fileData}
</Highlighter>
diff --git a/src/features/FileViewer/Renderer/HTML/index.tsx b/src/features/FileViewer/Renderer/HTML/index.tsx
index 69474c637d8..f77854320b0 100644
--- a/src/features/FileViewer/Renderer/HTML/index.tsx
+++ b/src/features/FileViewer/Renderer/HTML/index.tsx
@@ -4,10 +4,12 @@ import { Center, Flexbox } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { memo } from 'react';
+import AsyncError from '@/components/AsyncError';
import { InlineHtmlPreview } from '@/components/HtmlPreview';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useTextFileLoader } from '../../hooks/useTextFileLoader';
+import NotSupport from '../../NotSupport';
const styles = createStaticStyles(({ css }) => ({
page: css`
@@ -23,7 +25,15 @@ interface HTMLViewerProps {
}
const HTMLViewer = memo<HTMLViewerProps>(({ url }) => {
- const { fileData, loading } = useTextFileLoader(url);
+ const { error, fileData, loading, tooLarge } = useTextFileLoader(url);
+
+ if (!loading && fileData === null)
+ return (
+ <Flexbox>
+ {error && <AsyncError error={error} variant={'block'} />}
+ <NotSupport tooLarge={tooLarge} url={url} />
+ </Flexbox>
+ );
return (
<Flexbox className={styles.page}>
diff --git a/src/features/FileViewer/Renderer/Markdown/index.tsx b/src/features/FileViewer/Renderer/Markdown/index.tsx
index ddda4a516f6..6c510a5478c 100644
--- a/src/features/FileViewer/Renderer/Markdown/index.tsx
+++ b/src/features/FileViewer/Renderer/Markdown/index.tsx
@@ -7,9 +7,11 @@ import { CodeIcon, EyeIcon } from 'lucide-react';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { useTextFileLoader } from '../../hooks/useTextFileLoader';
+import NotSupport from '../../NotSupport';
const styles = createStaticStyles(({ css }) => ({
// Same floating-controls treatment as the LocalFile portal's text preview, so
@@ -57,9 +59,17 @@ interface MarkdownViewerProps {
*/
const MarkdownViewer = memo<MarkdownViewerProps>(({ url }) => {
const { t } = useTranslation('file');
- const { fileData, loading } = useTextFileLoader(url);
+ const { error, fileData, loading, tooLarge } = useTextFileLoader(url);
const [mode, setMode] = useState<PreviewMode>('render');
+ if (!loading && fileData === null)
+ return (
+ <Flexbox>
+ {error && <AsyncError error={error} variant={'block'} />}
+ <NotSupport tooLarge={tooLarge} url={url} />
+ </Flexbox>
+ );
+
if (loading || fileData === null)
return (
<Center height={'100%'} width={'100%'}>
diff --git a/src/features/FileViewer/hooks/useTextFileLoader.test.ts b/src/features/FileViewer/hooks/useTextFileLoader.test.ts
new file mode 100644
index 00000000000..11164229a3a
--- /dev/null
+++ b/src/features/FileViewer/hooks/useTextFileLoader.test.ts
@@ -0,0 +1,118 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useTextFileLoader } from './useTextFileLoader';
+
+// ROOT CAUSE:
+// Text preview used response.text() without byte validation, size limits, or request cancellation.
+// Unknown extensions never reached this path, and binary/failed/empty loads could show blank editors
+// or permanent spinners. Byte-based loading provides a format-independent fallback.
+/** @example Original text, unsupported bytes, and failures resolve into distinct preview states. */
+describe('useTextFileLoader', () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ /** @example An unknown suffix does not prevent Unicode source from being previewed. */
+ it('loads original text without a recognized extension or MIME', async () => {
+ const content = '<tag>日本語</tag>\n source { value: 1 }';
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(content)));
+ const { result } = renderHook(() => useTextFileLoader('/source.unrecognized'));
+ await waitFor(() => {
+ /** @example Whitespace and markup are preserved verbatim. */
+ expect(result.current.fileData).toBe(content);
+ });
+ });
+
+ /** @example Empty uploads are successful previews, not perpetual loading. */
+ it('finishes loading an empty file', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('')));
+ const { result } = renderHook(() => useTextFileLoader('/empty'));
+ await waitFor(() => {
+ /** @example Empty content is distinguishable from unsupported content. */
+ expect(result.current).toMatchObject({ error: null, fileData: '', loading: false });
+ });
+ });
+
+ /** @example Binary data falls back to file download. */
+ it('does not decode binary bytes as source', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(new Response(new Uint8Array([0, 0, 1, 2, 3]))),
+ );
+ const { result } = renderHook(() => useTextFileLoader('/binary'));
+ await waitFor(() => {
+ /** @example Unsupported bytes complete loading without text. */
+ expect(result.current).toMatchObject({ error: null, fileData: null, loading: false });
+ });
+ });
+
+ /** @example UTF-16 bytes are text despite containing null bytes. */
+ it('decodes a supported non-UTF-8 encoding', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(new Response(new Uint8Array([255, 254, 65, 0, 66, 0]))),
+ );
+ const { result } = renderHook(() => useTextFileLoader('/encoded'));
+ await waitFor(() => {
+ /** @example UTF-16LE BOM selects the appropriate decoder. */
+ expect(result.current.fileData).toBe('AB');
+ });
+ });
+
+ /** @example A server cannot bypass preview limits by omitting Content-Length. */
+ it('stops oversized streamed downloads', async () => {
+ const cancel = vi.fn();
+ const stream = new ReadableStream<Uint8Array>({
+ cancel,
+ start(controller) {
+ controller.enqueue(new Uint8Array(2 * 1024 * 1024 + 1));
+ },
+ });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(stream)));
+ const { result } = renderHook(() => useTextFileLoader('/large'));
+ await waitFor(() => {
+ /** @example Oversized files settle into the download fallback and stop the stream. */
+ expect(result.current).toMatchObject({ error: null, fileData: null, loading: false });
+ expect(cancel).toHaveBeenCalled();
+ });
+ });
+
+ /** @example Failed reads remain visible as errors alongside the download fallback. */
+ it('reports HTTP errors and ends loading', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('', { status: 403 })));
+ const { result } = renderHook(() => useTextFileLoader('/denied'));
+ await waitFor(() => {
+ /** @example Failed requests do not leave a permanent spinner. */
+ expect(result.current.loading).toBe(false);
+ expect(result.current.error?.message).toContain('403');
+ });
+ });
+
+ /** @example Navigation prevents an older request from replacing the newly opened file. */
+ it('ignores stale responses after switching files', async () => {
+ let resolveFirst!: (response: Response) => void;
+ const fetchMock = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<Response>((resolve) => {
+ resolveFirst = resolve;
+ }),
+ )
+ .mockResolvedValueOnce(new Response('new content'));
+ vi.stubGlobal('fetch', fetchMock);
+ const { result, rerender } = renderHook(({ url }) => useTextFileLoader(url), {
+ initialProps: { url: '/old' },
+ });
+ rerender({ url: '/new' });
+ await waitFor(() => {
+ /** @example The latest file wins. */
+ expect(result.current.fileData).toBe('new content');
+ });
+ await act(async () => {
+ resolveFirst(new Response('old content'));
+ });
+ /** @example A late response cannot overwrite the active file. */
+ expect(result.current.fileData).toBe('new content');
+ expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(true);
+ });
+});
diff --git a/src/features/FileViewer/hooks/useTextFileLoader.ts b/src/features/FileViewer/hooks/useTextFileLoader.ts
index 866ce3085de..74fdcad5d34 100644
--- a/src/features/FileViewer/hooks/useTextFileLoader.ts
+++ b/src/features/FileViewer/hooks/useTextFileLoader.ts
@@ -1,36 +1,72 @@
+import { decodeTextBuffer } from '@lobechat/utils/isBinaryContent';
+import { readBlobWithLimit } from '@lobechat/utils/readBlobWithLimit';
import { useEffect, useState } from 'react';
-export const useTextFileLoader = (url: string | null) => {
- const [fileData, setFileData] = useState<string | null>(null);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<Error | null>(null);
+/** Bound text downloads and decoding to 2 MiB to keep preview rendering responsive. */
+const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
+
+interface TextFileState {
+ error: Error | null;
+ fileData: string | null;
+ loading: boolean;
+ tooLarge?: boolean;
+ url: string | null;
+}
+
+/**
+ * Load original file bytes for a bounded, read-only text preview.
+ *
+ * Use when:
+ * - Rendering text or attempting a text fallback for an unknown file format.
+ *
+ * Expects:
+ * - An accessible file URL; null disables the request.
+ *
+ * Returns:
+ * - Text, loading/error state, or null content for binary and oversized files.
+ */
+export const useTextFileLoader = (url: string | null): TextFileState => {
+ const [state, setState] = useState<TextFileState>({
+ error: null,
+ fileData: null,
+ loading: !!url,
+ url,
+ });
useEffect(() => {
- if (!url) {
- setLoading(false);
- return;
- }
+ const controller = new AbortController();
+ setState({ error: null, fileData: null, loading: !!url, url });
+ if (!url) return;
const loadFile = async () => {
try {
- setLoading(true);
- const response = await fetch(url);
- if (!response.ok) {
- throw new Error(`Failed to load file: ${response.statusText}`);
- }
- const text = await response.text();
- setFileData(text);
- setError(null);
- } catch (err) {
- setError(err instanceof Error ? err : new Error('Unknown error'));
- setFileData(null);
- } finally {
- setLoading(false);
+ // Abort on navigation; enforce the limit even when Content-Length is missing or wrong.
+ const response = await fetch(url, { signal: controller.signal });
+ if (!response.ok) throw new Error(`Failed to load file: ${response.status}`);
+ const blob = await readBlobWithLimit(response, MAX_TEXT_PREVIEW_BYTES);
+ const fileData = decodeTextBuffer(new Uint8Array(await blob.arrayBuffer()));
+ if (!controller.signal.aborted) setState({ error: null, fileData, loading: false, url });
+ } catch (cause) {
+ if (controller.signal.aborted) return;
+ setState({
+ error:
+ cause instanceof RangeError
+ ? null
+ : cause instanceof Error
+ ? cause
+ : new Error('Failed to load file'),
+ fileData: null,
+ loading: false,
+ tooLarge: cause instanceof RangeError,
+ url,
+ });
}
};
- loadFile();
+ void loadFile();
+ return () => controller.abort();
}, [url]);
- return { error, fileData, loading };
+ // Never flash a previous file's content while the new URL's effect is starting.
+ return state.url === url ? state : { error: null, fileData: null, loading: !!url, url };
};
diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsx
index dbad9cc5e51..044a633b793 100644
--- a/src/features/FileViewer/index.tsx
+++ b/src/features/FileViewer/index.tsx
@@ -20,7 +20,6 @@ import MSDocViewer from './Renderer/MSDoc';
import type { PDFViewerProps } from './Renderer/PDF';
import { preloadPDFRenderer } from './Renderer/PDF/loader';
import VideoViewer from './Renderer/Video';
-import { VERILOG_FILE_EXTENSIONS, VERILOG_FILE_MIME_TYPES } from './verilogSupport';
// File type definitions
const IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.bmp'];
@@ -36,157 +35,6 @@ const IMAGE_MIME_TYPES = new Set([
const VIDEO_EXTENSIONS = ['.mp4', '.webm', '.ogg'];
const VIDEO_MIME_TYPES = new Set(['video/mp4', 'video/webm', 'video/ogg', 'mp4', 'webm', 'ogg']);
-const CODE_EXTENSIONS = [
- // JavaScript/TypeScript
- '.js',
- '.jsx',
- '.ts',
- '.tsx',
- '.mjs',
- '.cjs',
- // Python
- '.py',
- '.pyw',
- // Java/JVM
- '.java',
- '.kt',
- '.kts',
- '.scala',
- '.groovy',
- // C/C++
- '.c',
- '.h',
- '.cpp',
- '.cxx',
- '.cc',
- '.hpp',
- '.hxx',
- // Hardware description languages (canonical entries in ./verilogSupport)
- ...VERILOG_FILE_EXTENSIONS,
- // Other compiled languages
- '.cs',
- '.go',
- '.rs',
- '.rb',
- '.php',
- '.swift',
- '.lua',
- '.r',
- '.dart',
- // Shell
- '.sh',
- '.bash',
- '.zsh',
- // Web
- '.html',
- '.htm',
- '.css',
- '.scss',
- '.sass',
- '.less',
- // Data formats
- '.json',
- '.xml',
- '.yaml',
- '.yml',
- '.toml',
- '.sql',
- '.csv',
- '.tsv',
- // Functional languages
- '.ex',
- '.exs',
- '.erl',
- '.hrl',
- '.clj',
- '.cljs',
- '.cljc',
- // Markdown
- '.md',
- '.mdx',
- // Other
- '.vim',
- '.graphql',
- '.gql',
- '.txt',
-];
-
-const CODE_MIME_TYPES = new Set([
- // JavaScript/TypeScript
- 'js',
- 'jsx',
- 'ts',
- 'tsx',
- 'application/javascript',
- 'application/x-javascript',
- 'text/javascript',
- 'application/typescript',
- 'text/typescript',
- // Python
- 'python',
- 'text/x-python',
- 'application/x-python-code',
- // Java/JVM
- 'java',
- 'text/x-java-source',
- 'kotlin',
- 'scala',
- // C/C++
- 'c',
- 'text/x-c',
- 'cpp',
- 'text/x-c++',
- // Other languages
- 'csharp',
- 'go',
- 'rust',
- // Hardware description languages (canonical entries in ./verilogSupport)
- ...VERILOG_FILE_MIME_TYPES,
- 'ruby',
- 'php',
- 'text/x-php',
- 'swift',
- 'lua',
- 'r',
- 'dart',
- // Shell
- 'bash',
- 'shell',
- 'text/x-shellscript',
- // Web
- 'html',
- 'text/html',
- 'css',
- 'text/css',
- 'scss',
- 'sass',
- 'less',
- // Data
- 'json',
- 'application/json',
- 'xml',
- 'text/xml',
- 'application/xml',
- 'yaml',
- 'text/yaml',
- 'application/x-yaml',
- 'toml',
- 'sql',
- 'text/x-sql',
- 'csv',
- 'text/csv',
- 'tsv',
- 'text/tab-separated-values',
- // Markdown
- 'md',
- 'mdx',
- ...MARKDOWN_MIME_TYPES,
- // Other
- 'graphql',
- 'txt',
- 'text/plain',
-]);
-
// Markdown renders as rich text (with a raw toggle) instead of the highlighted
// source view — must be checked before the code fallback, whose lists also
// contain the md/mdx extensions and MIME types.
@@ -352,13 +200,9 @@ const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) =>
return <MarkdownViewer fileId={id} url={url} />;
}
- // Code files (JavaScript, TypeScript, Python, Java, C++, Go, Rust, etc.)
- if (matchesFileType(fileType, name, CODE_EXTENSIONS, CODE_MIME_TYPES)) {
- return <CodeViewer fileId={id} fileName={name} url={url} />;
- }
-
- // Unsupported file type
- return <NotSupport fileName={name} style={style} url={url} />;
+ // The former code-extension/MIME list is replaced by byte detection: unknown extensions can still contain text. The loader checks bytes and caps downloads;
+ // binary, oversized, or unreadable content falls back to the download view.
+ return <CodeViewer fileId={id} fileName={name} key={url} url={url} />;
});
export default FileViewer;
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index c644aaa0e07..ca3b6e90988 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -3,6 +3,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import DocumentBody from './Body';
+vi.mock('@/features/FileViewer/FileDocumentPreview', () => ({
+ FileDocumentPreview: ({ fileId }: { fileId?: string | null }) => (
+ <div data-file-id={fileId} data-testid="original-file-preview" />
+ ),
+}));
+
vi.mock('antd-style', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
@@ -47,6 +53,8 @@ vi.mock('@/components/CodeEditorPane', () => ({
const mockDocumentMeta = vi.hoisted(() => ({
current: { content: '', filename: 'doc.md' } as {
content?: string;
+ fileId?: string | null;
+ sourceType?: string;
fileType?: string | null;
filename?: string | null;
title?: string | null;
@@ -141,6 +149,21 @@ vi.mock('@/store/document', () => ({
}));
describe('DocumentBody', () => {
+ /** @example A file-backed document previews its upload and retains document chat. */
+ it('shows the original upload without mounting either editor', () => {
+ // ROOT CAUSE:
+ // File-backed documents used the empty content field as an editable document.
+ // Selecting a file preview must not mount an editor that could save this empty copy.
+ mockDocumentMeta.current = { content: '', fileId: 'file-original', filename: 'source.unknown' };
+ render(<DocumentBody />);
+ /** @example The original file id reaches the read-only preview. */
+ expect(screen.getByTestId('original-file-preview').dataset.fileId).toBe('file-original');
+ /** @example Neither editor mounts, while document chat stays available. */
+ expect(screen.queryByTestId('highlight-editor')).toBeNull();
+ expect(screen.queryByTestId('editor-canvas')).toBeNull();
+ expect(screen.getByTestId('floating-chat-panel')).toBeTruthy();
+ });
+
beforeEach(() => {
mockAgentState.current.activeAgentId = 'agent-1';
mockChatState.current.portalStack[0].agentDocumentId = 'agent-document-1';
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index caa285f74ab..daa44ed2770 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -10,7 +10,11 @@ import type { ChangeEvent } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import AsyncError from '@/components/AsyncError';
import CodeEditorPane from '@/components/CodeEditorPane';
+import Loading from '@/components/Loading/CircleLoading';
+import FileNotFound from '@/features/FileNotFound';
+import { FileDocumentPreview } from '@/features/FileViewer/FileDocumentPreview';
import FloatingChatPanel from '@/features/FloatingChatPanel';
import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';
import WideScreenContainer from '@/features/WideScreenContainer';
@@ -339,9 +343,13 @@ const DocumentBody = memo(() => {
);
const isSkillMarkdown = contentFormat === 'skillMarkdown';
- const { data: documentMeta, mutate: mutateDocumentMeta } = useClientDataSWR(
- documentId ? portalKeys.documentHeader(documentId) : null,
- () => documentService.getDocumentById(documentId!),
+ const {
+ data: documentMeta,
+ error: documentError,
+ isLoading: documentLoading,
+ mutate: mutateDocumentMeta,
+ } = useClientDataSWR(documentId ? portalKeys.documentHeader(documentId) : null, () =>
+ documentService.getDocumentById(documentId!),
);
const renderMode = documentMeta
? getDocumentRenderMode(documentMeta)
@@ -358,10 +366,12 @@ const DocumentBody = memo(() => {
const editorContent = (
<>
- {documentId && isSkillMarkdown && (
+ {renderMode.mode !== 'file' && documentId && isSkillMarkdown && (
<SkillFrontmatterBlock documentId={documentId} frontmatter={skillFrontmatter} />
)}
- {renderMode.mode === 'highlight' && documentId ? (
+ {renderMode.mode === 'file' ? (
+ <FileDocumentPreview fileId={documentMeta?.fileId} />
+ ) : renderMode.mode === 'highlight' && documentId ? (
<HighlightEditor
content={documentMeta?.content ?? ''}
documentId={documentId}
@@ -375,12 +385,27 @@ const DocumentBody = memo(() => {
</>
);
+ if (documentLoading) return <Loading />;
+ if (documentError)
+ return (
+ <AsyncError
+ error={documentError}
+ variant={'block'}
+ onRetry={() => void mutateDocumentMeta()}
+ />
+ );
+ if (!documentMeta) return <FileNotFound />;
+
return (
<Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
<div className={fullPage ? styles.contentFull : styles.content}>
- {fullPage ? <WideScreenContainer>{editorContent}</WideScreenContainer> : editorContent}
+ {fullPage && renderMode.mode !== 'file' ? (
+ <WideScreenContainer>{editorContent}</WideScreenContainer>
+ ) : (
+ editorContent
+ )}
</div>
- <TodoList />
+ {renderMode.mode !== 'file' && <TodoList />}
{/* The full-page route hosts its own panel through `AgentDocumentPage`, so
the in-portal panel only renders for the compact view. Both call sites
drive a doc-anchored chat topic via `useDocumentChatTopic`, so the panel
diff --git a/src/features/Portal/Document/Header.tsx b/src/features/Portal/Document/Header.tsx
index 9242a5b6c9d..9a4bd778897 100644
--- a/src/features/Portal/Document/Header.tsx
+++ b/src/features/Portal/Document/Header.tsx
@@ -22,7 +22,7 @@ const Header = () => {
);
const title = document?.filename || document?.title;
- const isReadonly = !!document && getDocumentRenderMode(document).mode === 'highlight';
+ const isReadonly = !!document && getDocumentRenderMode(document).mode !== 'editor';
if (!documentId) return null;
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index 7851ae69bf8..d91d2d1d6dc 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -91,6 +91,18 @@ class AgentDocumentService {
return result;
};
+ importFile = async (params: { agentId: string; fileId: string; parentId?: string | null }) => {
+ const result = await lambdaClient.agentDocument.importFile.mutate(params);
+ await invalidateDocumentMutation({
+ agentDocumentId: getAgentDocumentId(result),
+ agentId: params.agentId,
+ cause: 'agent-document',
+ documentId: getDocumentId(result),
+ });
+
+ return result;
+ };
+
createDocument = async (
params: {
agentId: string;
diff --git a/src/utils/__tests__/documentRenderMode.test.ts b/src/utils/__tests__/documentRenderMode.test.ts
index d848e86d8e0..c788e2292c4 100644
--- a/src/utils/__tests__/documentRenderMode.test.ts
+++ b/src/utils/__tests__/documentRenderMode.test.ts
@@ -8,6 +8,16 @@ import { describe, expect, it } from 'vitest';
import { getDocumentRenderMode } from '../documentRenderMode';
describe('getDocumentRenderMode', () => {
+ /** @example File associations take precedence over filename-based editor selection. */
+ it('keeps uploads in the file view, including after the backing file is removed', () => {
+ /** @example A Markdown upload is still a file, not an editable page. */
+ expect(getDocumentRenderMode({ fileId: 'file-1', filename: 'note.md' })).toEqual({
+ mode: 'file',
+ });
+ /** @example A removed file displays a missing-file state instead of a blank editor. */
+ expect(getDocumentRenderMode({ fileId: null, sourceType: 'file' })).toEqual({ mode: 'file' });
+ });
+
it('returns editor for SKILL.md skill index', () => {
expect(getDocumentRenderMode({ fileType: 'skills/index', title: 'SKILL.md' })).toEqual({
mode: 'editor',
diff --git a/src/utils/documentRenderMode.ts b/src/utils/documentRenderMode.ts
index 80101817453..76a72d42bfd 100644
--- a/src/utils/documentRenderMode.ts
+++ b/src/utils/documentRenderMode.ts
@@ -13,13 +13,16 @@ import { isSkillMarkdownDocument } from './skillMarkdown';
interface DocumentRenderModeFields {
category?: string | null;
+ fileId?: string | null;
filename?: string | null;
fileType?: string | null;
sourceType?: string | null;
title?: string | null;
}
-export type DocumentRenderMode = { mode: 'editor' } | { language: string; mode: 'highlight' };
+/** Content surface selected for an uploaded file or an editable document. */
+export type DocumentRenderMode =
+ { mode: 'editor' } | { language: string; mode: 'highlight' } | { mode: 'file' };
const EDITOR_DOCUMENT_FILE_TYPES = new Set([
AGENT_DOCUMENT_FILE_TYPE,
@@ -34,7 +37,22 @@ const isEditorDocument = (document: DocumentRenderModeFields): boolean => {
return !!document.sourceType && EDITOR_DOCUMENT_SOURCE_TYPES.includes(document.sourceType);
};
+/**
+ * Select a content surface, giving original uploads priority over editor formats.
+ *
+ * Use when:
+ * - Opening document metadata from a chat portal or standalone page.
+ *
+ * Expects:
+ * - Document metadata; file source attribution survives deletion of the original file.
+ *
+ * Returns:
+ * - File preview, rich-text editor, or source editor mode.
+ */
export const getDocumentRenderMode = (document: DocumentRenderModeFields): DocumentRenderMode => {
+ // Keep deleted uploads in the file view even after their fileId FK is cleared.
+ if (document.fileId || document.sourceType === 'file') return { mode: 'file' };
+
if (isSkillMarkdownDocument(document)) return { mode: 'editor' };
if (!document.filename) return { mode: 'editor' };