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(work): open document works and edited files in the in-app preview portal (#17739)

YuTengjing4a17652d7d30
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index 43a5d59808d..f1b049d5221 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -137,15 +137,44 @@ const normalizeContentType = (contentType: string): string =>
const isTextPreviewMimeType = (mimeType: string): boolean =>
mimeType.startsWith('text/') || TEXT_PREVIEW_MIME_TYPES.has(mimeType);
+/** Binary documents the in-app portal can preview (or offer to download). */
+const DOCUMENT_PREVIEW_MIME_TYPES = new Set([
+ 'application/msword',
+ 'application/pdf',
+ 'application/vnd.ms-excel',
+ 'application/vnd.ms-powerpoint',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+]);
+
+/**
+ * Documents above this raw size fall back to the content-less `binary` / `pdf`
+ * variants: base64 inflates the payload ~4/3 and it must fit in a single
+ * IPC / Gateway RPC response.
+ */
+const MAX_DOCUMENT_PREVIEW_BYTES = 20 * 1024 * 1024;
+
const serializePreviewFile = ({
buffer,
contentType,
+ oversized,
}: {
buffer: Buffer;
contentType: string;
+ oversized?: boolean;
}): NonNullable<LocalFilePreviewResult['preview']> => {
const normalizedContentType = normalizeContentType(contentType);
+ // The protocol manager short-circuited the read (oversized document):
+ // `buffer` is empty by construction, so go straight to the content-less
+ // fallback instead of serializing the empty buffer as a real document.
+ if (oversized) {
+ return normalizedContentType === 'application/pdf'
+ ? { contentType: normalizedContentType, type: 'pdf' }
+ : { contentType: normalizedContentType, type: 'binary' };
+ }
+
if (normalizedContentType.startsWith('image/')) {
return {
base64: buffer.toString('base64'),
@@ -162,6 +191,17 @@ const serializePreviewFile = ({
};
}
+ if (
+ DOCUMENT_PREVIEW_MIME_TYPES.has(normalizedContentType) &&
+ buffer.byteLength <= MAX_DOCUMENT_PREVIEW_BYTES
+ ) {
+ return {
+ base64: buffer.toString('base64'),
+ contentType: normalizedContentType,
+ type: 'document',
+ };
+ }
+
if (normalizedContentType === 'application/pdf') {
return { contentType: normalizedContentType, type: 'pdf' };
}
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 6f66d9479a7..842daebd01a 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -393,6 +393,70 @@ describe('LocalFileCtr', () => {
});
});
+ it('should return binary document previews as base64', async () => {
+ mockLocalFileProtocolManager.readPreviewFile.mockResolvedValue({
+ buffer: Buffer.from('docx-bytes'),
+ contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ realPath: '/workspace/report.docx',
+ });
+
+ const result = await localFileCtr.getLocalFilePreview({
+ path: '/workspace/report.docx',
+ workingDirectory: '/workspace',
+ });
+
+ expect(result).toEqual({
+ preview: {
+ base64: Buffer.from('docx-bytes').toString('base64'),
+ contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ type: 'document',
+ },
+ success: true,
+ });
+ });
+
+ it('should fall back to the content-less pdf variant for oversized documents', async () => {
+ mockLocalFileProtocolManager.readPreviewFile.mockResolvedValue({
+ buffer: Buffer.alloc(20 * 1024 * 1024 + 1),
+ contentType: 'application/pdf',
+ realPath: '/workspace/huge.pdf',
+ });
+
+ const result = await localFileCtr.getLocalFilePreview({
+ path: '/workspace/huge.pdf',
+ workingDirectory: '/workspace',
+ });
+
+ expect(result).toEqual({
+ preview: { contentType: 'application/pdf', type: 'pdf' },
+ success: true,
+ });
+ });
+
+ it('should serialize short-circuited oversized reads as content-less fallbacks', async () => {
+ // The protocol manager returns an empty buffer with `oversized` when it
+ // skipped the read; the serializer must NOT treat it as a real document.
+ mockLocalFileProtocolManager.readPreviewFile.mockResolvedValue({
+ buffer: Buffer.alloc(0),
+ contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ oversized: true,
+ realPath: '/workspace/huge.docx',
+ });
+
+ const result = await localFileCtr.getLocalFilePreview({
+ path: '/workspace/huge.docx',
+ workingDirectory: '/workspace',
+ });
+
+ expect(result).toEqual({
+ preview: {
+ contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ type: 'binary',
+ },
+ success: true,
+ });
+ });
+
it('should forward user-approved external preview reads', async () => {
mockLocalFileProtocolManager.readPreviewFile.mockResolvedValue({
buffer: Buffer.from('<h1>Demo</h1>'),
diff --git a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
index 66e172752a5..94186c48a52 100644
--- a/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/LocalFileProtocolManager.ts
@@ -1,8 +1,9 @@
import { randomUUID } from 'node:crypto';
import { readFile, realpath, stat } from 'node:fs/promises';
+import { homedir } from 'node:os';
import path from 'node:path';
-import { resolveMimeType } from '@lobechat/utils/mimeType';
+import { getMimeType, resolveMimeType } from '@lobechat/utils/mimeType';
import { app, protocol } from 'electron';
import { LOCAL_FILE_PROTOCOL_HOST, LOCAL_FILE_PROTOCOL_SCHEME } from '@/const/protocol';
@@ -23,8 +24,40 @@ const PREVIEW_TOKEN_TTL_MS = 5 * 60 * 1000;
const EXTERNAL_PREVIEW_APPROVAL_TTL_MS = 10 * 60 * 1000;
const PREVIEW_SESSION_HOST_PREFIX = 'preview-';
+/**
+ * Mirrors the renderer/device document cap (`MAX_DOCUMENT_PREVIEW_BYTES`): an
+ * oversized document can only ever produce the content-less fallback, so the
+ * protocol handler must not read it into main-process memory at all. The real
+ * size travels in `X-Preview-Content-Size` (an empty body computes its own
+ * `Content-Length`), which the renderer's oversize gate reads first.
+ */
+const DOCUMENT_PREVIEW_MIME_TYPES = new Set([
+ 'application/msword',
+ 'application/pdf',
+ 'application/vnd.ms-excel',
+ 'application/vnd.ms-powerpoint',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+]);
+const MAX_DOCUMENT_PREVIEW_BYTES = 20 * 1024 * 1024;
+export const PREVIEW_CONTENT_SIZE_HEADER = 'X-Preview-Content-Size';
+
+// Edited-file records can carry `~`-prefixed paths (the file tools expand the
+// home directory at write time) — expand them here so previews resolve the
+// file that was actually written instead of rejecting a non-absolute path.
+const expandHomePath = (filePath: string): string => {
+ if (filePath === '~') return homedir();
+ // Slice off the full `~/` / `~\` prefix (mirroring local-file-shell's
+ // `expandTilde`) so the separator never survives as a literal character.
+ if (filePath.startsWith('~/') || filePath.startsWith('~\\')) {
+ return path.join(homedir(), filePath.slice(2));
+ }
+ return filePath;
+};
+
const normalizeAbsolutePath = (filePath: string): string | null => {
- const normalized = path.normalize(filePath);
+ const normalized = path.normalize(expandHomePath(filePath));
return path.isAbsolute(normalized) ? normalized : null;
};
@@ -73,6 +106,12 @@ interface PreviewRootTokenRecord {
export interface PreviewFileReadResult {
buffer: Buffer;
contentType: string;
+ /**
+ * Set when the file is a document above `MAX_DOCUMENT_PREVIEW_BYTES`: the
+ * read was short-circuited and `buffer` is empty. Consumers must serialize
+ * the content-less fallback instead of treating `buffer` as the file body.
+ */
+ oversized?: boolean;
realPath: string;
}
@@ -162,6 +201,18 @@ export class LocalFileProtocolManager {
return new Response('Not a file', { status: 404 });
}
+ if (fileStat.size > MAX_DOCUMENT_PREVIEW_BYTES) {
+ const extensionType = getMimeType(realResolvedPath).split(';')[0].trim();
+ if (DOCUMENT_PREVIEW_MIME_TYPES.has(extensionType)) {
+ const headers = new Headers();
+ headers.set('Content-Type', extensionType);
+ headers.set(PREVIEW_CONTENT_SIZE_HEADER, String(fileStat.size));
+ headers.set('Cross-Origin-Resource-Policy', 'cross-origin');
+ headers.set('X-Content-Type-Options', 'nosniff');
+ return new Response(new Uint8Array(0), { headers, status: 200 });
+ }
+ }
+
const buffer = await readFile(realResolvedPath);
const headers = new Headers();
const contentType = await resolveMimeType(realResolvedPath, buffer);
@@ -342,6 +393,28 @@ export class LocalFileProtocolManager {
const fileStat = await stat(realFilePath);
if (!fileStat.isFile()) return null;
+ // Oversized documents can only ever produce the content-less fallback —
+ // detect them by extension so the main process never reads a 100 MB report
+ // into memory just to discard it. Mirrors the protocol handler above and
+ // the device daemon's `defaultGetLocalFilePreview` (@lobechat/device-control).
+ if (fileStat.size > MAX_DOCUMENT_PREVIEW_BYTES) {
+ const extensionType = getMimeType(realFilePath).split(';')[0].trim();
+ if (DOCUMENT_PREVIEW_MIME_TYPES.has(extensionType)) {
+ if (!isAcceptedPreviewContentType(extensionType, accept)) return null;
+
+ if (allowExternalFile) {
+ this.grantExternalPreviewApproval(realFilePath);
+ }
+
+ return {
+ buffer: Buffer.alloc(0),
+ contentType: extensionType,
+ oversized: true,
+ realPath: realFilePath,
+ };
+ }
+ }
+
const buffer = await readFile(realFilePath);
const contentType = await resolveMimeType(realFilePath, buffer);
if (!isAcceptedPreviewContentType(contentType, accept)) return null;
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
index 60d6aa4ffbc..3e5542325aa 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/LocalFileProtocolManager.test.ts
@@ -34,6 +34,11 @@ vi.mock('node:fs/promises', () => ({
stat: mockStat,
}));
+vi.mock('node:os', async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ return { ...actual, default: actual, homedir: () => '/Users/alice' };
+});
+
vi.mock('@/utils/logger', () => ({
createLogger: () => ({
debug: vi.fn(),
@@ -106,6 +111,46 @@ describe('LocalFileProtocolManager', () => {
expect(response.headers.get('Content-Length')).toBe(String(pngBytes.byteLength));
});
+ it('short-circuits oversized documents without reading them', async () => {
+ const oversized = 20 * 1024 * 1024 + 1;
+ mockStat.mockImplementation(async () => ({ isFile: () => true, size: oversized }));
+
+ const manager = new LocalFileProtocolManager();
+ manager.registerHandler();
+ await manager.approveWorkspaceRoot('/Users/alice/project');
+ const url = await manager.createPreviewUrl({
+ filePath: '/Users/alice/project/big.pdf',
+ workspaceRoot: '/Users/alice/project',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
+
+ const handler = protocolHandlerRef.current;
+ const response = await handler({ headers: new Headers(), method: 'GET', url });
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get('Content-Type')).toBe('application/pdf');
+ expect(response.headers.get('X-Preview-Content-Size')).toBe(String(oversized));
+ expect(mockReadFile).not.toHaveBeenCalled();
+ });
+
+ it('expands ~ paths against the home directory', async () => {
+ const manager = new LocalFileProtocolManager();
+ manager.registerHandler();
+ await manager.approveWorkspaceRoot('/Users/alice');
+ const url = await manager.createPreviewUrl({
+ filePath: '~/report.md',
+ workspaceRoot: '/Users/alice',
+ });
+ if (!url) throw new Error('Expected local file preview URL');
+
+ const handler = protocolHandlerRef.current;
+ const response = await handler({ headers: new Headers(), method: 'GET', url });
+
+ expect(response.status).toBe(200);
+ expect(mockStat).toHaveBeenCalledWith('/Users/alice/report.md');
+ expect(mockReadFile).toHaveBeenCalledWith('/Users/alice/report.md');
+ });
+
it('serves source files as text through the localfile protocol', async () => {
const manager = new LocalFileProtocolManager();
manager.registerHandler();
@@ -459,6 +504,63 @@ describe('LocalFileProtocolManager', () => {
expect(mockReadFile).toHaveBeenCalledWith('/Users/alice/project/App.tsx');
});
+ it('short-circuits oversized document preview reads without reading them', async () => {
+ const oversized = 20 * 1024 * 1024 + 1;
+ mockStat.mockImplementation(async () => ({ isFile: () => true, size: oversized }));
+
+ const manager = new LocalFileProtocolManager();
+ await manager.approveIndexedProjectRoot('/Users/alice/project');
+
+ const result = await manager.readPreviewFile({
+ filePath: '/Users/alice/project/report.pdf',
+ workspaceRoot: '/Users/alice/project',
+ });
+
+ expect(result).toEqual({
+ buffer: Buffer.alloc(0),
+ contentType: 'application/pdf',
+ oversized: true,
+ realPath: '/Users/alice/project/report.pdf',
+ });
+ expect(mockReadFile).not.toHaveBeenCalled();
+ });
+
+ it('rejects oversized documents on image-only preview reads without reading them', async () => {
+ const oversized = 20 * 1024 * 1024 + 1;
+ mockStat.mockImplementation(async () => ({ isFile: () => true, size: oversized }));
+
+ const manager = new LocalFileProtocolManager();
+ await manager.approveIndexedProjectRoot('/Users/alice/project');
+
+ const result = await manager.readPreviewFile({
+ accept: 'image',
+ filePath: '/Users/alice/project/report.docx',
+ workspaceRoot: '/Users/alice/project',
+ });
+
+ expect(result).toBeNull();
+ expect(mockReadFile).not.toHaveBeenCalled();
+ });
+
+ it('still reads oversized non-document files in full', async () => {
+ // Only document formats have a content-less fallback; an oversized image
+ // must keep the full read so the preview still renders.
+ const oversized = 20 * 1024 * 1024 + 1;
+ mockStat.mockImplementation(async () => ({ isFile: () => true, size: oversized }));
+ mockReadFile.mockResolvedValue(Buffer.from('big-image-bytes'));
+
+ const manager = new LocalFileProtocolManager();
+ await manager.approveIndexedProjectRoot('/Users/alice/project');
+
+ const result = await manager.readPreviewFile({
+ filePath: '/Users/alice/project/photo.png',
+ workspaceRoot: '/Users/alice/project',
+ });
+
+ expect(result?.oversized).toBeUndefined();
+ expect(mockReadFile).toHaveBeenCalledWith('/Users/alice/project/photo.png');
+ });
+
it('does not return text payloads for image-only preview reads', async () => {
const manager = new LocalFileProtocolManager();
await manager.approveIndexedProjectRoot('/Users/alice/project');
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index bfc13bc2050..edeba85dd46 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1647,11 +1647,16 @@
"workingPanel.localFile.closeLeft": "Close to the Left",
"workingPanel.localFile.closeOther": "Close Others",
"workingPanel.localFile.closeRight": "Close to the Right",
+ "workingPanel.localFile.document.download": "Download",
+ "workingPanel.localFile.document.openWithDefaultApp": "Open with default app",
+ "workingPanel.localFile.document.truncatedRows": "Showing the first {{count}} rows",
+ "workingPanel.localFile.document.unsupported": "This document type can't be previewed in-app yet",
"workingPanel.localFile.error": "Couldn't load this file",
"workingPanel.localFile.preview.raw": "Raw",
"workingPanel.localFile.preview.reload": "Reload preview",
"workingPanel.localFile.preview.render": "Preview",
"workingPanel.localFile.preview.source": "Source",
+ "workingPanel.localFile.sandboxUnavailable": "This file is no longer available — its sandbox environment has been recycled",
"workingPanel.localFile.truncated": "File preview truncated to {{limit}} characters",
"workingPanel.openMenu.configuration": "Configuration",
"workingPanel.openMenu.terminal": "Terminal",
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index 312c3663968..f8fa9eecd83 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -197,6 +197,8 @@
"pageList.workspaceTitle": "Workspace",
"portal.openInPageEditor": "Edit in Page",
"preview.downloadFile": "Download File",
+ "preview.raw": "Raw",
+ "preview.render": "Preview",
"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 d0cb1846f61..5841df758ff 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1647,11 +1647,16 @@
"workingPanel.localFile.closeLeft": "关闭左侧",
"workingPanel.localFile.closeOther": "关闭其他",
"workingPanel.localFile.closeRight": "关闭右侧",
+ "workingPanel.localFile.document.download": "下载",
+ "workingPanel.localFile.document.openWithDefaultApp": "用默认应用打开",
+ "workingPanel.localFile.document.truncatedRows": "仅显示前 {{count}} 行",
+ "workingPanel.localFile.document.unsupported": "此文档类型暂不支持应用内预览",
"workingPanel.localFile.error": "无法加载此文件",
"workingPanel.localFile.preview.raw": "原文",
"workingPanel.localFile.preview.reload": "刷新预览",
"workingPanel.localFile.preview.render": "预览",
"workingPanel.localFile.preview.source": "源码",
+ "workingPanel.localFile.sandboxUnavailable": "此文件已不可用——所在的沙盒环境已被回收",
"workingPanel.localFile.truncated": "文件预览被截断至 {{limit}} 个字符",
"workingPanel.openMenu.configuration": "配置",
"workingPanel.openMenu.terminal": "终端",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 5dc04a06dac..8ce92755be0 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -197,6 +197,8 @@
"pageList.workspaceTitle": "工作区",
"portal.openInPageEditor": "在文稿中编辑",
"preview.downloadFile": "下载文件",
+ "preview.raw": "原文",
+ "preview.render": "预览",
"preview.unsupportedFileAndContact": "此文件格式暂不支持在线预览,如有预览诉求,欢迎<1>反馈给我们</1>",
"resource": "资源",
"resourceList.batchCopyDescription": "您可以拷贝到有权限创建资源的个人账户或工作区。",
diff --git a/package.json b/package.json
index e3bd0aa3723..c339acff82a 100644
--- a/package.json
+++ b/package.json
@@ -178,6 +178,7 @@
"stylelint-config-clean-order": "7.0.0"
},
"dependencies": {
+ "@aiden0z/pptx-renderer": "^1.2.4",
"@ant-design/icons": "^6.3.2",
"@anthropic-ai/sdk": "^0.73.0",
"@atlaskit/pragmatic-drag-and-drop": "^1.8.1",
@@ -354,10 +355,12 @@
"debug": "^4.4.3",
"diff": "^8.0.4",
"discord-api-types": "^0.38.49",
+ "docx-preview": "^0.4.0",
"drizzle-orm": "^0.45.2",
"drizzle-zod": "^0.8.3",
"epub2": "^3.0.2",
"es-toolkit": "^1.49.0",
+ "exceljs": "^4.4.0",
"expo-server-sdk": "^6.1.0",
"fast-deep-equal": "^3.1.3",
"fflate": "^0.8.3",
diff --git a/packages/device-control/src/__tests__/filePreview.test.ts b/packages/device-control/src/__tests__/filePreview.test.ts
index 8ae312ed715..2cd5479a0bd 100644
--- a/packages/device-control/src/__tests__/filePreview.test.ts
+++ b/packages/device-control/src/__tests__/filePreview.test.ts
@@ -2,17 +2,26 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
-import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { defaultGetLocalFilePreview } from '../filePreview';
+const mockedHome = vi.hoisted(() => ({ dir: '' }));
+
+vi.mock('node:os', async (importOriginal) => {
+ const actual = (await importOriginal()) as Record<string, unknown>;
+ return { ...actual, default: actual, homedir: () => mockedHome.dir };
+});
+
let root: string;
let outside: string;
beforeAll(async () => {
root = await mkdtemp(path.join(tmpdir(), 'dc-preview-'));
outside = await mkdtemp(path.join(tmpdir(), 'dc-outside-'));
+ mockedHome.dir = root;
await writeFile(path.join(root, 'note.txt'), 'hello preview\n');
+ await writeFile(path.join(root, 'win.txt'), 'hello windows\n');
// Full PNG signature + IHDR chunk header so file-type recognises the format.
await writeFile(
path.join(root, 'pic.png'),
@@ -22,6 +31,14 @@ beforeAll(async () => {
]),
);
await writeFile(path.join(outside, 'secret.txt'), 'do not read\n');
+ // `%PDF` magic bytes so file-type recognises the format.
+ await writeFile(path.join(root, 'doc.pdf'), Buffer.from('%PDF-1.4\n%fake'));
+ // No magic bytes on purpose: a binary buffer + `.docx` extension resolves the
+ // OOXML mime through the extension fallback.
+ await writeFile(
+ path.join(root, 'report.docx'),
+ Buffer.concat([Buffer.from([0x05, 0x00, 0x03]), Buffer.from('fake-docx')]),
+ );
});
afterAll(async () => {
@@ -38,6 +55,37 @@ describe('defaultGetLocalFilePreview', () => {
expect(result.preview).toMatchObject({ content: 'hello preview\n', type: 'text' });
});
+ it('expands ~ paths against the home directory', async () => {
+ const result = await defaultGetLocalFilePreview({
+ path: '~/note.txt',
+ workingDirectory: root,
+ });
+ expect(result.success).toBe(true);
+ expect(result.preview).toMatchObject({ content: 'hello preview\n', type: 'text' });
+ });
+
+ it('falls back to a content-less document preview without reading oversized files', async () => {
+ const bigPdf = path.join(root, 'big.pdf');
+ // 20 MB + 1 byte of zeros: over the document cap, extension-detectable.
+ await writeFile(bigPdf, Buffer.alloc(20 * 1024 * 1024 + 1));
+
+ const result = await defaultGetLocalFilePreview({
+ path: bigPdf,
+ workingDirectory: root,
+ });
+ expect(result.success).toBe(true);
+ expect(result.preview).toEqual({ contentType: 'application/pdf', type: 'pdf' });
+ });
+
+ it('expands backslash home paths without leaving a literal separator', async () => {
+ const result = await defaultGetLocalFilePreview({
+ path: '~\\win.txt',
+ workingDirectory: root,
+ });
+ expect(result.success).toBe(true);
+ expect(result.preview).toMatchObject({ content: 'hello windows\n', type: 'text' });
+ });
+
it('reads an image file as base64', async () => {
const result = await defaultGetLocalFilePreview({
path: path.join(root, 'pic.png'),
@@ -49,6 +97,29 @@ describe('defaultGetLocalFilePreview', () => {
expect((result.preview as { contentType: string }).contentType).toBe('image/png');
});
+ it('reads a pdf as a base64 document preview', async () => {
+ const result = await defaultGetLocalFilePreview({
+ path: path.join(root, 'doc.pdf'),
+ workingDirectory: root,
+ });
+ expect(result.success).toBe(true);
+ expect(result.preview).toMatchObject({ contentType: 'application/pdf', type: 'document' });
+ expect((result.preview as { base64: string }).base64).toBeTruthy();
+ });
+
+ it('reads an office file as a base64 document preview', async () => {
+ const result = await defaultGetLocalFilePreview({
+ path: path.join(root, 'report.docx'),
+ workingDirectory: root,
+ });
+ expect(result.success).toBe(true);
+ expect(result.preview).toMatchObject({
+ contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ type: 'document',
+ });
+ expect((result.preview as { base64: string }).base64).toBeTruthy();
+ });
+
it('rejects a non-image when accept is "image"', async () => {
const result = await defaultGetLocalFilePreview({
accept: 'image',
diff --git a/packages/device-control/src/filePreview.ts b/packages/device-control/src/filePreview.ts
index fcfa655e886..ee9f4f85ab8 100644
--- a/packages/device-control/src/filePreview.ts
+++ b/packages/device-control/src/filePreview.ts
@@ -1,7 +1,8 @@
import { readFile, realpath, stat } from 'node:fs/promises';
+import { homedir } from 'node:os';
import path from 'node:path';
-import { resolveMimeType } from '@lobechat/utils/mimeType';
+import { getMimeType, resolveMimeType } from '@lobechat/utils/mimeType';
import type { LocalFilePreview, LocalFilePreviewResult, LocalFilePreviewUrlParams } from './types';
@@ -25,6 +26,24 @@ const isTextPreviewMimeType = (contentType: string): boolean => {
return bare.startsWith('text/') || TEXT_PREVIEW_MIME_TYPES.has(bare);
};
+/** Binary documents the in-app portal can preview (or offer to download). */
+const DOCUMENT_PREVIEW_MIME_TYPES = new Set([
+ 'application/msword',
+ 'application/pdf',
+ 'application/vnd.ms-excel',
+ 'application/vnd.ms-powerpoint',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+]);
+
+/**
+ * Documents above this raw size fall back to the content-less `binary` / `pdf`
+ * variants: base64 inflates the payload ~4/3 and it must fit in a single
+ * Gateway RPC response.
+ */
+const MAX_DOCUMENT_PREVIEW_BYTES = 20 * 1024 * 1024;
+
const serializePreviewFile = (buffer: Buffer, contentType: string): LocalFilePreview => {
if (contentType.startsWith('image/')) {
return { base64: buffer.toString('base64'), contentType, type: 'image' };
@@ -32,6 +51,12 @@ const serializePreviewFile = (buffer: Buffer, contentType: string): LocalFilePre
if (isTextPreviewMimeType(contentType)) {
return { content: buffer.toString('utf8'), contentType, type: 'text' };
}
+ if (
+ DOCUMENT_PREVIEW_MIME_TYPES.has(normalizeContentType(contentType)) &&
+ buffer.byteLength <= MAX_DOCUMENT_PREVIEW_BYTES
+ ) {
+ return { base64: buffer.toString('base64'), contentType, type: 'document' };
+ }
if (normalizeContentType(contentType) === 'application/pdf') {
return { contentType, type: 'pdf' };
}
@@ -41,6 +66,20 @@ const serializePreviewFile = (buffer: Buffer, contentType: string): LocalFilePre
return { contentType, type: 'binary' };
};
+// Edited-file records can carry `~`-prefixed paths (the file tools expand the
+// home directory at write time) — expand them before resolving so the preview
+// targets the file that was actually written, not `<cwd>/~/...`.
+// Mirrors local-file-shell's `expandTilde`: slice off the full `~/` / `~\`
+// prefix so the separator never survives as a literal filename character on
+// POSIX.
+const expandHomePath = (target: string): string => {
+ if (target === '~') return homedir();
+ if (target.startsWith('~/') || target.startsWith('~\\')) {
+ return path.join(homedir(), target.slice(2));
+ }
+ return target;
+};
+
/** Resolve the real path, tolerating non-existent targets. */
const safeRealpath = async (target: string): Promise<string> => {
try {
@@ -68,8 +107,8 @@ export const defaultGetLocalFilePreview = async (
return { error: 'Missing working directory', success: false };
}
- const realRoot = await safeRealpath(workingDirectory);
- const realFile = await safeRealpath(filePath);
+ const realRoot = await safeRealpath(expandHomePath(workingDirectory));
+ const realFile = await safeRealpath(expandHomePath(filePath));
const withinRoot = realFile === realRoot || realFile.startsWith(`${realRoot}${path.sep}`);
if (!withinRoot) {
return { error: 'File is outside the approved workspace', success: false };
@@ -80,6 +119,25 @@ export const defaultGetLocalFilePreview = async (
return { error: 'Path is not a file', success: false };
}
+ // Oversized documents can only ever produce the content-less fallback —
+ // detect them by extension so the daemon never reads a 100 MB report into
+ // memory just to discard it.
+ if (stats.size > MAX_DOCUMENT_PREVIEW_BYTES) {
+ const extensionType = normalizeContentType(getMimeType(realFile));
+ if (DOCUMENT_PREVIEW_MIME_TYPES.has(extensionType)) {
+ if (accept === 'image') {
+ return { error: 'File is not an image', success: false };
+ }
+ return {
+ preview:
+ extensionType === 'application/pdf'
+ ? { contentType: extensionType, type: 'pdf' }
+ : { contentType: extensionType, type: 'binary' },
+ success: true,
+ };
+ }
+ }
+
const buffer = await readFile(realFile);
const contentType = await resolveMimeType(realFile, buffer);
if (accept === 'image' && !contentType.startsWith('image/')) {
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index 45ce2513f07..c26a1a5a90f 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -86,13 +86,27 @@ export interface LocalFilePreviewImage {
type: 'image';
}
+/**
+ * Binary document (pdf / office) small enough to preview in-app, carried as
+ * base64 so it survives RPC serialization. Oversized documents stay on the
+ * `binary` / `pdf` unsupported variants.
+ */
+export interface LocalFilePreviewDocument {
+ base64: string;
+ contentType: string;
+ type: 'document';
+}
+
export interface LocalFilePreviewUnsupported {
contentType: string;
type: 'binary' | 'pdf' | 'video';
}
export type LocalFilePreview =
- LocalFilePreviewImage | LocalFilePreviewText | LocalFilePreviewUnsupported;
+ | LocalFilePreviewDocument
+ | LocalFilePreviewImage
+ | LocalFilePreviewText
+ | LocalFilePreviewUnsupported;
export interface LocalFilePreviewResult {
error?: string;
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index f8fe9d6e3a9..f74d365ad6e 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -163,13 +163,27 @@ export interface LocalFilePreviewImage {
type: 'image';
}
+/**
+ * Binary document (pdf / office) small enough to preview in-app, carried as
+ * base64 so it survives IPC / RPC serialization. Oversized documents stay on
+ * the `binary` / `pdf` unsupported variants.
+ */
+export interface LocalFilePreviewDocument {
+ base64: string;
+ contentType: string;
+ type: 'document';
+}
+
export interface LocalFilePreviewUnsupported {
contentType: string;
type: 'binary' | 'pdf' | 'video';
}
export type LocalFilePreview =
- LocalFilePreviewImage | LocalFilePreviewText | LocalFilePreviewUnsupported;
+ | LocalFilePreviewDocument
+ | LocalFilePreviewImage
+ | LocalFilePreviewText
+ | LocalFilePreviewUnsupported;
export interface LocalFilePreviewResult {
error?: string;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index bc7a63ee44c..376cd9a0054 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1805,8 +1805,14 @@ export default {
'workingPanel.localFile.closeLeft': 'Close to the Left',
'workingPanel.localFile.closeOther': 'Close Others',
'workingPanel.localFile.closeRight': 'Close to the Right',
+ 'workingPanel.localFile.document.download': 'Download',
+ 'workingPanel.localFile.document.openWithDefaultApp': 'Open with default app',
+ 'workingPanel.localFile.document.truncatedRows': 'Showing the first {{count}} rows',
+ 'workingPanel.localFile.document.unsupported': "This document type can't be previewed in-app yet",
'workingPanel.localFile.error': "Couldn't load this file",
'workingPanel.localFile.preview.raw': 'Raw',
+ 'workingPanel.localFile.sandboxUnavailable':
+ 'This file is no longer available — its sandbox environment has been recycled',
'workingPanel.localFile.preview.reload': 'Reload preview',
'workingPanel.localFile.preview.render': 'Preview',
'workingPanel.localFile.preview.source': 'Source',
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index 3617b3f279f..ef641d48c36 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -254,6 +254,8 @@ export default {
'resourceList.viewTransferred': 'View',
'portal.openInPageEditor': 'Edit in Page',
'preview.downloadFile': 'Download File',
+ 'preview.raw': 'Raw',
+ 'preview.render': 'Preview',
'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',
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index e5e1fa188c6..205c0ee1a65 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -645,13 +645,27 @@ export interface DeviceLocalFilePreviewImage {
type: 'image';
}
+/**
+ * Binary document (pdf / office) small enough to preview in-app. Carries the
+ * raw bytes as base64 so they can cross the Gateway/RPC boundary; oversized
+ * documents stay on the `binary` / `pdf` unsupported variants.
+ */
+export interface DeviceLocalFilePreviewDocument {
+ base64: string;
+ contentType: string;
+ type: 'document';
+}
+
export interface DeviceLocalFilePreviewUnsupported {
contentType: string;
type: 'binary' | 'pdf' | 'video';
}
export type DeviceLocalFilePreview =
- DeviceLocalFilePreviewImage | DeviceLocalFilePreviewText | DeviceLocalFilePreviewUnsupported;
+ | DeviceLocalFilePreviewDocument
+ | DeviceLocalFilePreviewImage
+ | DeviceLocalFilePreviewText
+ | DeviceLocalFilePreviewUnsupported;
/**
* File preview payload for a file on a remote device. Mirrors the desktop local
diff --git a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
index b840544a26c..3f28e03a615 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.test.ts
@@ -158,6 +158,27 @@ describe('deriveOperationEditedFiles', () => {
expect(entries.map((e) => e.path)).toEqual(['/repo/data.csv']);
});
+ it('keeps a deleted entity file in the card even when the round has a work surface', () => {
+ // The file Work registrar skips `kind === 'deleted'` entries (nothing left
+ // to export), so the card is the only surface where the deletion shows.
+ const codexDelete = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'delete', linesAdded: 0, linesDeleted: 12, path: '/repo/report.pdf' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles([block([codexDelete])], true);
+
+ expect(entries.map((e) => [e.path, e.kind])).toEqual([['/repo/report.pdf', 'deleted']]);
+ });
+
it('drops an entity file only when its LAST edit is sandbox-backed', () => {
// Sandbox writes it, codex re-edits it → the Work provenance rule keys off
// the last edit, so no Work registers and the card must keep the file.
@@ -182,6 +203,32 @@ describe('deriveOperationEditedFiles', () => {
expect(entries.map((e) => e.path)).toEqual(['/work/deck.pptx']);
});
+ it('annotates entries with sandboxBacked from the LAST edit provenance', () => {
+ // The card routes clicks by origin: sandbox-backed files live-read via the
+ // sandbox tool, everything else goes through the local/device filesystem.
+ const codexCsv = tool({
+ apiName: 'file_change',
+ id: 't2',
+ identifier: 'codex',
+ result: {
+ content: '',
+ id: 't2-r',
+ state: {
+ changes: [{ kind: 'update', linesAdded: 2, linesDeleted: 1, path: '/repo/data.csv' }],
+ },
+ },
+ });
+
+ const entries = deriveOperationEditedFiles([
+ block([sandboxWrite('t1', '/work/notes.md'), codexCsv]),
+ ]);
+
+ expect(entries.map((e) => [e.path, e.sandboxBacked])).toEqual([
+ ['/work/notes.md', true],
+ ['/repo/data.csv', false],
+ ]);
+ });
+
it('drops a tool call whose result carries an error', () => {
const entries = deriveOperationEditedFiles([
block([
diff --git a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
index 2f4551df5b5..f4d93cb5518 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/deriveEditedFiles.ts
@@ -59,30 +59,53 @@ export const collectFileEditToolCallRecords = (
* persisted. Callers must memoize on the blocks reference (see
* {@link useOperationEditedFiles}) so the scan runs once per snapshot.
*/
+/**
+ * An edited-file entry annotated with its content origin, so the card can route
+ * a click to the right preview transport (sandbox live-read vs local/device
+ * filesystem).
+ */
+export interface OperationEditedFile extends EditedFileEntry {
+ /**
+ * Whether the file's LAST edit came from the cloud sandbox — mirroring the
+ * server's provenance rule, the terminal edit owns the file's content.
+ */
+ sandboxBacked: boolean;
+}
+
export const deriveOperationEditedFiles = (
blocks: AssistantContentBlock[] = [],
hasWorkSurface = false,
-): EditedFileEntry[] => {
+): OperationEditedFile[] => {
const records = collectFileEditToolCallRecords(blocks);
if (records.length === 0) return [];
- const entries = scanOperationFileEdits(records);
- if (!hasWorkSurface) return entries;
-
const sandboxToolCallIds = new Set(
records
.filter((record) => record.identifier === CLOUD_SANDBOX_IDENTIFIER)
.map((record) => record.toolCallId),
);
- return entries.filter((entry) => {
- if (classifyEditedFile(entry.path).category !== 'entity') return true;
- // Mirrors the server's provenance rule: a Work version's provenance is the
- // file's LAST edit, so the card drops the entry only when that edit came
- // from the sandbox (→ a Work card covers it).
+ const entries = scanOperationFileEdits(records).map((entry): OperationEditedFile => {
const lastSourceToolCallId = entry.sourceToolCallIds.at(-1);
- return !(lastSourceToolCallId && sandboxToolCallIds.has(lastSourceToolCallId));
+ return {
+ ...entry,
+ sandboxBacked: !!lastSourceToolCallId && sandboxToolCallIds.has(lastSourceToolCallId),
+ };
});
+ if (!hasWorkSurface) return entries;
+
+ // Drop sandbox-backed entity files: their `file` Work card covers them.
+ // Deleted entries stay — the file Work registrar skips `kind === 'deleted'`
+ // (there is nothing left in the sandbox to export), so the card is the only
+ // surface where a deleted entity file remains visible.
+ return entries.filter(
+ (entry) =>
+ !(
+ entry.kind !== 'deleted' &&
+ classifyEditedFile(entry.path).category === 'entity' &&
+ entry.sandboxBacked
+ ),
+ );
};
export interface EditedFilesTotals {
diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.test.ts b/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
index beea24a902b..7549ebb20c6 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/index.test.ts
@@ -24,6 +24,7 @@ const singleEntry = {
linesAdded: 7,
linesDeleted: 2,
path: '/workspace/Acceptance/index.tsx',
+ sandboxBacked: false,
sourceToolCallIds: ['tool-1'],
};
diff --git a/src/features/Conversation/Messages/EditedFilesCard/index.tsx b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
index 2fb3383bf70..343f53c1187 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/index.tsx
+++ b/src/features/Conversation/Messages/EditedFilesCard/index.tsx
@@ -18,7 +18,8 @@ import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
-import { summarizeEditedFilesTotals } from './deriveEditedFiles';
+import { type OperationEditedFile, summarizeEditedFilesTotals } from './deriveEditedFiles';
+import { useOpenEditedFile } from './useOpenEditedFile';
export const SINGLE_EDITED_FILE_ICON_SIZE = 40;
@@ -64,6 +65,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
opacity: 1;
}
`,
+ singleHeaderClickable: css`
+ cursor: pointer;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
singleIcon: css`
flex-shrink: 0;
@@ -125,6 +133,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
row: css`
padding-block: 6px;
padding-inline: 12px;
+
+ &:hover [data-view-changes],
+ &:focus-within [data-view-changes] {
+ pointer-events: auto;
+ transform: translateX(0);
+ opacity: 1;
+ }
`,
rowMain: css`
min-height: 24px;
@@ -152,24 +167,30 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
`,
}));
-const EditedFileRow = memo<{ entry: EditedFileEntry }>(({ entry }) => {
+const EditedFileRow = memo<{ entry: EditedFileEntry; onOpen?: () => void }>(({ entry, onOpen }) => {
+ const { t } = useTranslation('chat');
const [expanded, setExpanded] = useState(false);
const hasDiff = entry.diffTexts.length > 0;
const fileName = getFileName(entry.path);
const language = getFileLanguage(entry.path);
+ // Preview when the file's content is reachable; otherwise the row keeps its
+ // legacy diff-toggle click so it never turns into a dead affordance.
+ const handleRowClick = onOpen ?? (hasDiff ? () => setExpanded((prev) => !prev) : undefined);
+ const clickable = !!handleRowClick;
+
return (
- <Flexbox className={cx(styles.row, hasDiff && styles.rowClickable)}>
+ <Flexbox className={cx(styles.row, clickable && styles.rowClickable)}>
<Flexbox
horizontal
align={'center'}
- aria-expanded={hasDiff ? expanded : undefined}
+ aria-expanded={onOpen ? undefined : hasDiff ? expanded : undefined}
className={styles.rowMain}
gap={10}
- role={hasDiff ? 'button' : undefined}
- tabIndex={hasDiff ? 0 : undefined}
- onClick={hasDiff ? () => setExpanded((prev) => !prev) : undefined}
- onKeyDown={hasDiff ? toggleOnKey(() => setExpanded((prev) => !prev)) : undefined}
+ role={clickable ? 'button' : undefined}
+ tabIndex={clickable ? 0 : undefined}
+ onClick={handleRowClick}
+ onKeyDown={handleRowClick ? toggleOnKey(handleRowClick) : undefined}
>
<KindDot kind={entry.kind} />
<div className={styles.path}>
@@ -181,7 +202,26 @@ const EditedFileRow = memo<{ entry: EditedFileEntry }>(({ entry }) => {
linesAdded={entry.linesAdded}
linesDeleted={entry.linesDeleted}
/>
- {hasDiff &&
+ {onOpen && hasDiff && (
+ <Button
+ data-view-changes
+ aria-expanded={expanded}
+ className={cx(styles.viewChanges, expanded && styles.viewChangesVisible)}
+ size={'small'}
+ type={'text'}
+ onClick={(event) => {
+ event.stopPropagation();
+ setExpanded((prev) => !prev);
+ }}
+ // Enter/Space on the button must not bubble into the row's own
+ // key handler, which would also open the file preview.
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ {t(expanded ? 'editedFiles.hideChanges' : 'editedFiles.viewChanges')}
+ </Button>
+ )}
+ {!onOpen &&
+ hasDiff &&
(expanded ? (
<ChevronDownIcon className={styles.chevron} size={14} />
) : (
@@ -209,7 +249,7 @@ const EditedFileRow = memo<{ entry: EditedFileEntry }>(({ entry }) => {
EditedFileRow.displayName = 'EditedFileRow';
interface EditedFilesCardProps {
- entries: EditedFileEntry[];
+ entries: OperationEditedFile[];
}
export const getEditedFilesCardMode = (fileCount: number) => {
@@ -220,64 +260,81 @@ export const getEditedFilesCardMode = (fileCount: number) => {
export const getEditedFileIconName = (filePath: string) => getFileName(filePath);
-const SingleEditedFileCard = memo<{ entry: EditedFileEntry }>(({ entry }) => {
- const { t } = useTranslation('chat');
- const [showDiff, setShowDiff] = useState(false);
- const hasDiff = entry.diffTexts.length > 0;
- const fileName = getFileName(entry.path);
- const { displayPath } = getFilePathDisplayInfo(entry.path);
- const language = getFileLanguage(entry.path);
-
- return (
- <Flexbox className={styles.card}>
- <Flexbox horizontal align={'center'} className={styles.singleHeader} gap={10}>
- <Center className={styles.singleIcon}>
- <FileIcon fileName={getEditedFileIconName(entry.path)} size={24} />
- </Center>
- <Flexbox flex={1} gap={2}>
- <Text ellipsis className={styles.singleTitle}>
- {t('editedFiles.singleTitle', { path: displayPath })}
- </Text>
- <LineStats
- hideZeroDeltas
- className={styles.stats}
- linesAdded={entry.linesAdded}
- linesDeleted={entry.linesDeleted}
- />
+const SingleEditedFileCard = memo<{ entry: EditedFileEntry; onOpen?: () => void }>(
+ ({ entry, onOpen }) => {
+ const { t } = useTranslation('chat');
+ const [showDiff, setShowDiff] = useState(false);
+ const hasDiff = entry.diffTexts.length > 0;
+ const fileName = getFileName(entry.path);
+ const { displayPath } = getFilePathDisplayInfo(entry.path);
+ const language = getFileLanguage(entry.path);
+
+ return (
+ <Flexbox className={styles.card}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.singleHeader, onOpen && styles.singleHeaderClickable)}
+ gap={10}
+ role={onOpen ? 'button' : undefined}
+ tabIndex={onOpen ? 0 : undefined}
+ onClick={onOpen}
+ onKeyDown={onOpen ? toggleOnKey(onOpen) : undefined}
+ >
+ <Center className={styles.singleIcon}>
+ <FileIcon fileName={getEditedFileIconName(entry.path)} size={24} />
+ </Center>
+ <Flexbox flex={1} gap={2}>
+ <Text ellipsis className={styles.singleTitle}>
+ {t('editedFiles.singleTitle', { path: displayPath })}
+ </Text>
+ <LineStats
+ hideZeroDeltas
+ className={styles.stats}
+ linesAdded={entry.linesAdded}
+ linesDeleted={entry.linesDeleted}
+ />
+ </Flexbox>
+ {hasDiff && (
+ <Button
+ data-view-changes
+ aria-expanded={showDiff}
+ className={cx(styles.viewChanges, showDiff && styles.viewChangesVisible)}
+ icon={<ArrowUpRightIcon size={14} />}
+ iconPosition={'end'}
+ size={'small'}
+ type={'text'}
+ onKeyDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ // The header itself may open the file preview — keep the diff
+ // toggle from also triggering it.
+ event.stopPropagation();
+ setShowDiff((prev) => !prev);
+ }}
+ >
+ {t(showDiff ? 'editedFiles.hideChanges' : 'editedFiles.viewChanges')}
+ </Button>
+ )}
</Flexbox>
- {hasDiff && (
- <Button
- data-view-changes
- aria-expanded={showDiff}
- className={cx(styles.viewChanges, showDiff && styles.viewChangesVisible)}
- icon={<ArrowUpRightIcon size={14} />}
- iconPosition={'end'}
- size={'small'}
- type={'text'}
- onClick={() => setShowDiff((prev) => !prev)}
- >
- {t(showDiff ? 'editedFiles.hideChanges' : 'editedFiles.viewChanges')}
- </Button>
+ {hasDiff && showDiff && (
+ <div className={styles.patch}>
+ {entry.diffTexts.map((patch, index) => (
+ <PatchDiff
+ fileName={fileName}
+ key={index}
+ language={language}
+ patch={patch}
+ showHeader={false}
+ variant={'borderless'}
+ viewMode={'unified'}
+ />
+ ))}
+ </div>
)}
</Flexbox>
- {hasDiff && showDiff && (
- <div className={styles.patch}>
- {entry.diffTexts.map((patch, index) => (
- <PatchDiff
- fileName={fileName}
- key={index}
- language={language}
- patch={patch}
- showHeader={false}
- variant={'borderless'}
- viewMode={'unified'}
- />
- ))}
- </div>
- )}
- </Flexbox>
- );
-});
+ );
+ },
+);
SingleEditedFileCard.displayName = 'SingleEditedFileCard';
/**
@@ -289,9 +346,11 @@ SingleEditedFileCard.displayName = 'SingleEditedFileCard';
const EditedFilesCard = memo<EditedFilesCardProps>(({ entries }) => {
const { t } = useTranslation('chat');
const [expanded, setExpanded] = useState(false);
+ const getOpenAction = useOpenEditedFile();
if (entries.length === 0) return null;
- if (entries.length === 1) return <SingleEditedFileCard entry={entries[0]} />;
+ if (entries.length === 1)
+ return <SingleEditedFileCard entry={entries[0]} onOpen={getOpenAction(entries[0])} />;
const totals = summarizeEditedFilesTotals(entries);
@@ -328,7 +387,7 @@ const EditedFilesCard = memo<EditedFilesCardProps>(({ entries }) => {
{expanded && (
<Flexbox className={styles.list}>
{entries.map((entry) => (
- <EditedFileRow entry={entry} key={entry.path} />
+ <EditedFileRow entry={entry} key={entry.path} onOpen={getOpenAction(entry)} />
))}
</Flexbox>
)}
diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.test.ts b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.test.ts
new file mode 100644
index 00000000000..a2d6e30cc7b
--- /dev/null
+++ b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.test.ts
@@ -0,0 +1,191 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ canPreviewEditedFile,
+ isUncPath,
+ isWithinWorkingDirectory,
+ planFilesystemOpen,
+ resolveEntryPath,
+} from './useOpenEditedFile';
+
+describe('resolveEntryPath', () => {
+ it('anchors relative paths to the working directory', () => {
+ expect(resolveEntryPath('deck.pptx', '/repo')).toBe('/repo/deck.pptx');
+ expect(resolveEntryPath('out/report.md', '/repo/')).toBe('/repo/out/report.md');
+ });
+
+ it('keeps POSIX and drive-letter absolute paths untouched', () => {
+ expect(resolveEntryPath('/tmp/report.md', '/repo')).toBe('/tmp/report.md');
+ expect(resolveEntryPath('C:\\work\\report.md', '/repo')).toBe('C:\\work\\report.md');
+ expect(resolveEntryPath('c:/work/report.md', '/repo')).toBe('c:/work/report.md');
+ });
+
+ // Regression: Windows drive-rooted paths (single leading backslash) are
+ // absolute per Node's win32 `path.isAbsolute` — anchoring one would produce
+ // `C:\repo/\Users\alice\report.md`.
+ it('keeps Windows drive-rooted single-backslash paths untouched', () => {
+ expect(resolveEntryPath('\\Users\\alice\\report.md', 'C:\\repo')).toBe(
+ '\\Users\\alice\\report.md',
+ );
+ expect(isUncPath('\\Users\\alice\\report.md')).toBe(false);
+ });
+
+ it('flags UNC paths so the local desktop leg keeps them diff-only', () => {
+ expect(isUncPath('\\\\server\\share\\report.md')).toBe(true);
+ expect(isUncPath('C:\\work\\report.md')).toBe(false);
+ expect(isUncPath('/tmp/report.md')).toBe(false);
+ });
+
+ it('flags relative entries resolved inside a UNC workspace as UNC', () => {
+ expect(isUncPath(resolveEntryPath('deck.pptx', '\\\\server\\share\\repo'))).toBe(true);
+ });
+
+ it('does not re-anchor home or UNC paths', () => {
+ expect(resolveEntryPath('~/report.md', '/repo')).toBe('~/report.md');
+ expect(resolveEntryPath('~', '/repo')).toBe('~');
+ expect(resolveEntryPath('~\\report.md', '/repo')).toBe('~\\report.md');
+ expect(resolveEntryPath('\\\\server\\share\\report.md', '/repo')).toBe(
+ '\\\\server\\share\\report.md',
+ );
+ });
+
+ // Regression: the file tools expand exactly `~`, `~/`, and `~\` — a first
+ // segment merely starting with `~` is a valid cwd-relative path and skipping
+ // the anchor would resolve it under the preview host's own cwd instead.
+ it('anchors paths whose first segment merely starts with ~', () => {
+ expect(resolveEntryPath('~backup/report.md', '/repo')).toBe('/repo/~backup/report.md');
+ });
+
+ // Regression: Windows accepts forward-slash UNC roots too, and they hit the
+ // same localfile:// codec that collapses the leading double separator.
+ it('flags forward-slash UNC paths so the local desktop leg keeps them diff-only', () => {
+ expect(isUncPath('//server/share/report.md')).toBe(true);
+ expect(isUncPath(resolveEntryPath('deck.pptx', '//server/share/repo'))).toBe(true);
+ expect(isUncPath('/tmp/report.md')).toBe(false);
+ });
+});
+
+describe('isWithinWorkingDirectory', () => {
+ it('contains the root itself and nested paths', () => {
+ expect(isWithinWorkingDirectory('/repo', '/repo')).toBe(true);
+ expect(isWithinWorkingDirectory('/repo/out/report.md', '/repo')).toBe(true);
+ expect(isWithinWorkingDirectory('/repo/out/report.md', '/repo/')).toBe(true);
+ });
+
+ // Regression: an outside-cwd absolute path (e.g. an approved /tmp write) has
+ // no implicit preview permission — it needs the external allowance on the
+ // desktop leg and stays diff-only on the device leg.
+ it('rejects outside-cwd paths without prefix-collision false positives', () => {
+ expect(isWithinWorkingDirectory('/tmp/report.md', '/repo')).toBe(false);
+ expect(isWithinWorkingDirectory('/repo-archive/report.md', '/repo')).toBe(false);
+ });
+
+ it('normalizes separators across Windows and POSIX forms', () => {
+ expect(isWithinWorkingDirectory('C:\\work\\report.md', 'C:/work')).toBe(true);
+ expect(isWithinWorkingDirectory('C:/other/report.md', 'C:\\work')).toBe(false);
+ });
+
+ // Regression: Windows filesystems (drive-letter and UNC) are
+ // case-insensitive — `c:\repo\out.md` lives inside `C:\Repo`. POSIX paths
+ // must keep case sensitivity: /Repo and /repo are different directories.
+ it('compares Windows-style paths case-insensitively but POSIX case-sensitively', () => {
+ expect(isWithinWorkingDirectory('c:\\repo\\out.md', 'C:\\Repo')).toBe(true);
+ expect(isWithinWorkingDirectory('//SERVER/Share/x.md', '//server/share')).toBe(true);
+ expect(isWithinWorkingDirectory('/Repo/out.md', '/repo')).toBe(false);
+ });
+
+ // Regression: `..` segments must resolve before containment — a shell write
+ // of `../report.md` from /repo/sub lexically prefix-matches /repo/sub but
+ // actually lands outside it, and both preview hosts would reject the open.
+ it('resolves dot segments before comparing', () => {
+ expect(isWithinWorkingDirectory('/repo/sub/../report.md', '/repo/sub')).toBe(false);
+ expect(isWithinWorkingDirectory('/repo/sub/../report.md', '/repo')).toBe(true);
+ expect(isWithinWorkingDirectory('/repo/./out/report.md', '/repo')).toBe(true);
+ expect(isWithinWorkingDirectory('/repo/../../etc/passwd', '/repo')).toBe(false);
+ expect(isWithinWorkingDirectory('//server/share/sub/../x.md', '//server/share')).toBe(true);
+ });
+});
+
+describe('canPreviewEditedFile', () => {
+ // Regression: a deleted file no longer exists on any transport — opening the
+ // portal would render a load error, so the deletion diff stays primary.
+ it('keeps deleted entries diff-only but previews every other kind', () => {
+ expect(canPreviewEditedFile({ kind: 'deleted' })).toBe(false);
+ expect(canPreviewEditedFile({ kind: 'added' })).toBe(true);
+ expect(canPreviewEditedFile({ kind: 'modified' })).toBe(true);
+ expect(canPreviewEditedFile({ kind: 'renamed' })).toBe(true);
+ });
+});
+
+describe('planFilesystemOpen', () => {
+ it('opens within-cwd paths plainly on both legs', () => {
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: false,
+ resolvedPath: '/repo/report.md',
+ workingDirectory: '/repo',
+ }),
+ ).toEqual({});
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: true,
+ resolvedPath: '/repo/report.md',
+ workingDirectory: '/repo',
+ }),
+ ).toEqual({});
+ });
+
+ it('handles outside-cwd paths per leg: desktop allowance, device diff-only', () => {
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: false,
+ resolvedPath: '/tmp/report.md',
+ workingDirectory: '/repo',
+ }),
+ ).toEqual({ allowExternalFilePreview: true });
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: true,
+ resolvedPath: '/tmp/report.md',
+ workingDirectory: '/repo',
+ }),
+ ).toBeUndefined();
+ });
+
+ // Regression: the literal `~` never containment-matches an absolute cwd, but
+ // the preview hosts expand it themselves — the device daemon must get the
+ // open (it enforces its own boundary) instead of an inert row.
+ it('defers home-anchored paths to the preview hosts', () => {
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: true,
+ resolvedPath: '~/project/report.md',
+ workingDirectory: '/home/alice/project',
+ }),
+ ).toEqual({});
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: false,
+ resolvedPath: '~/project/report.md',
+ workingDirectory: '/Users/alice/project',
+ }),
+ ).toEqual({ allowExternalFilePreview: true });
+ });
+
+ it('keeps UNC paths diff-only on the local desktop but serves them via a device', () => {
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: false,
+ resolvedPath: '\\\\server\\share\\report.md',
+ workingDirectory: '\\\\server\\share',
+ }),
+ ).toBeUndefined();
+ expect(
+ planFilesystemOpen({
+ isDeviceMode: true,
+ resolvedPath: '\\\\server\\share\\report.md',
+ workingDirectory: '\\\\server\\share',
+ }),
+ ).toEqual({});
+ });
+});
diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
new file mode 100644
index 00000000000..a5e6c418c6f
--- /dev/null
+++ b/src/features/Conversation/Messages/EditedFilesCard/useOpenEditedFile.ts
@@ -0,0 +1,208 @@
+import { useCallback } from 'react';
+
+import { isDesktop } from '@/const/version';
+import { resolveExecutionTarget } from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { useEffectiveWorkingDirectory } from '@/hooks/useEffectiveWorkingDirectory';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+
+import type { OperationEditedFile } from './deriveEditedFiles';
+
+// Home-relative paths are already anchored: the file tools expand exactly `~`,
+// `~/…`, and `~\…` at write time (see local-file-shell's `expandTilde`). A
+// first segment that merely STARTS with `~` (e.g. `~backup/report.md`) is NOT
+// expanded there, so it is a valid cwd-relative path and must be anchored.
+const isHomeAnchoredPath = (filePath: string) =>
+ filePath === '~' || filePath.startsWith('~/') || filePath.startsWith('~\\');
+
+// `~` and UNC (`\\server\share`) paths are already anchored — the file tools
+// expand `~` at write time and UNC paths are absolute on Windows — so they
+// must not be re-anchored to the working directory.
+const isAbsolutePath = (filePath: string) =>
+ // A single leading separator is rooted on both platforms: POSIX absolute, or
+ // a Windows drive-rooted path (`\Users\alice\report.md`) — Node's win32
+ // `path.isAbsolute` treats the latter as absolute too, so never re-anchor it.
+ // (`startsWith('\\')` also matches UNC's `\\` prefix, which is fine here.)
+ filePath.startsWith('/') ||
+ filePath.startsWith('\\') ||
+ isHomeAnchoredPath(filePath) ||
+ /^[A-Z]:[/\\]/i.test(filePath);
+
+/**
+ * The desktop `localfile://` codec collapses a UNC path's leading double
+ * backslash (`\\server\share` → `\server\share`), so UNC entries would open a
+ * broken preview on the local desktop — keep them diff-only there until the
+ * protocol round trip preserves UNC roots. Windows accepts the forward-slash
+ * form (`//server/share`) too, and it hits the same collapsing codec.
+ */
+export const isUncPath = (filePath: string) =>
+ filePath.startsWith('\\\\') || filePath.startsWith('//');
+
+/**
+ * Shell-scan entries can carry workspace-relative paths (e.g. `deck.pptx` from
+ * `marp -o deck.pptx`); both the desktop preview manager and the device-control
+ * preview require absolute paths, so anchor relative ones to the working
+ * directory before opening.
+ */
+export const resolveEntryPath = (entryPath: string, workingDirectory: string) =>
+ isAbsolutePath(entryPath) ? entryPath : `${workingDirectory.replace(/[/\\]+$/, '')}/${entryPath}`;
+
+/**
+ * Collapse a path to slash-separated segments with `.` / `..` resolved
+ * lexically, so `/repo/sub/../report.md` compares as `/repo/report.md` instead
+ * of prefix-matching `/repo/sub`. A `..` that would climb past the root is kept
+ * (the resulting path can never match a real root, so containment fails —
+ * the safe outcome). UNC roots keep their leading double slash.
+ */
+const normalizePathForContainment = (value: string): string => {
+ const slashed = value.replaceAll('\\', '/');
+ const segments: string[] = [];
+ for (const segment of slashed.split('/')) {
+ if (segment === '' || segment === '.') continue;
+ if (segment === '..' && segments.length > 0 && segments.at(-1) !== '..') {
+ segments.pop();
+ continue;
+ }
+ segments.push(segment);
+ }
+ const prefix = slashed.startsWith('//') ? '//' : slashed.startsWith('/') ? '/' : '';
+ return prefix + segments.join('/');
+};
+
+/**
+ * Windows-style (drive-letter or UNC) after slash normalization. Those
+ * filesystems compare case-insensitively; POSIX paths must stay
+ * case-sensitive (`/Repo` and `/repo` are different directories).
+ */
+const isWindowsStylePath = (normalized: string) =>
+ /^[A-Z]:/i.test(normalized) || normalized.startsWith('//');
+
+/**
+ * Whether a resolved absolute path sits inside the working directory. Paths
+ * outside it (e.g. an approved `/tmp/report.md` write) have no implicit preview
+ * permission: the desktop preview manager rejects them unless the open carries
+ * the explicit external-file allowance, and the device daemon enforces the cwd
+ * boundary with no external mechanism at all. Purely lexical (separators and
+ * dot segments normalized, no realpath), which matches how the daemon compares
+ * roots.
+ */
+export const isWithinWorkingDirectory = (resolvedPath: string, workingDirectory: string) => {
+ let file = normalizePathForContainment(resolvedPath);
+ let root = normalizePathForContainment(workingDirectory);
+ if (!root) return false;
+ if (isWindowsStylePath(file) && isWindowsStylePath(root)) {
+ file = file.toLowerCase();
+ root = root.toLowerCase();
+ }
+ return file === root || file.startsWith(`${root}/`);
+};
+
+/**
+ * A deleted file has nothing to preview on ANY transport (the sandbox read and
+ * both filesystem hosts would all error) — the deletion diff stays the row's
+ * primary action.
+ */
+export const canPreviewEditedFile = (entry: Pick<OperationEditedFile, 'kind'>) =>
+ entry.kind !== 'deleted';
+
+/**
+ * Filesystem-leg open decision for a resolved entry path. Returns `undefined`
+ * when the row must stay diff-only, otherwise the extra `openLocalFile` params:
+ *
+ * - UNC paths stay diff-only on the LOCAL desktop (the `localfile://` codec
+ * collapses UNC roots); a bound device serves them over RPC instead.
+ * - Outside-cwd paths carry the explicit external allowance on desktop (same
+ * trust level as LocalFileLink clicks) and stay diff-only on a device — the
+ * portable daemon enforces the cwd boundary with no external mechanism.
+ * - Home-anchored (`~`) paths can't be containment-checked lexically against
+ * an absolute cwd; the preview hosts expand `~` themselves, so defer to
+ * them: plain open on a device, external allowance on desktop in case the
+ * expansion lands outside the workspace.
+ */
+export const planFilesystemOpen = ({
+ isDeviceMode,
+ resolvedPath,
+ workingDirectory,
+}: {
+ isDeviceMode: boolean;
+ resolvedPath: string;
+ workingDirectory: string;
+}): { allowExternalFilePreview?: true } | undefined => {
+ if (!isDeviceMode && isUncPath(resolvedPath)) return undefined;
+ if (isWithinWorkingDirectory(resolvedPath, workingDirectory)) return {};
+ if (isHomeAnchoredPath(resolvedPath)) {
+ return isDeviceMode ? {} : { allowExternalFilePreview: true };
+ }
+ if (isDeviceMode) return undefined;
+ return { allowExternalFilePreview: true };
+};
+
+/**
+ * Resolve a per-entry "open in portal" action for the edited-files card.
+ *
+ * Returns `undefined` when the entry has no reachable content — sandbox files
+ * without an active topic, or filesystem files when neither the local desktop
+ * nor a bound device can serve reads (mirrors the WorkingSidebar Files gate) —
+ * so the row degrades to its diff-only affordance instead of a dead click.
+ *
+ * Context is resolved from the CURRENT agent config, not the round that ran:
+ * best effort, matching how the files sidebar targets "where the agent works
+ * now".
+ */
+export const useOpenEditedFile = () => {
+ const [openLocalFile, activeTopicId] = useChatStore((s) => [s.openLocalFile, s.activeTopicId]);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
+ const workingDirectory = useEffectiveWorkingDirectory(activeAgentId);
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(activeAgentId);
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(activeAgentId);
+
+ const effectiveTarget = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero,
+ workspaceScoped,
+ });
+ const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
+ const remoteDeviceId = isDeviceMode ? agencyConfig?.boundDeviceId : undefined;
+ const filesystemAvailable = (effectiveTarget === 'local' && isDesktop) || isDeviceMode;
+
+ return useCallback(
+ (entry: OperationEditedFile): (() => void) | undefined => {
+ if (!canPreviewEditedFile(entry)) return undefined;
+ if (entry.sandboxBacked) {
+ if (!activeTopicId) return undefined;
+ return () =>
+ openLocalFile({
+ filePath: entry.path,
+ sandboxTopicId: activeTopicId,
+ // Sandbox reads resolve paths inside the sandbox itself — there is
+ // no client-side working directory to scope by.
+ workingDirectory: '',
+ });
+ }
+
+ if (!filesystemAvailable || !workingDirectory) return undefined;
+ // Gate on the RESOLVED path: a relative entry inside a UNC workspace
+ // resolves to a UNC path too.
+ const resolvedPath = resolveEntryPath(entry.path, workingDirectory);
+ const plan = planFilesystemOpen({
+ isDeviceMode: !!remoteDeviceId,
+ resolvedPath,
+ workingDirectory,
+ });
+ if (!plan) return undefined;
+ return () =>
+ openLocalFile({
+ ...plan,
+ deviceId: remoteDeviceId,
+ filePath: resolvedPath,
+ workingDirectory,
+ });
+ },
+ [activeTopicId, filesystemAvailable, openLocalFile, remoteDeviceId, workingDirectory],
+ );
+};
diff --git a/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts b/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
index ebd7cc9d638..a690dafb9e9 100644
--- a/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
+++ b/src/features/Conversation/Messages/EditedFilesCard/useOperationEditedFiles.ts
@@ -1,8 +1,7 @@
-import type { EditedFileEntry } from '@lobechat/builtin-tools/fileEditScan';
import type { AssistantContentBlock } from '@lobechat/types';
import { useMemo } from 'react';
-import { deriveOperationEditedFiles } from './deriveEditedFiles';
+import { deriveOperationEditedFiles, type OperationEditedFile } from './deriveEditedFiles';
/**
* Derived, non-persisted list of files edited across one assistant round.
@@ -23,5 +22,5 @@ import { deriveOperationEditedFiles } from './deriveEditedFiles';
export const useOperationEditedFiles = (
blocks?: AssistantContentBlock[],
hasWorkSurface?: boolean,
-): EditedFileEntry[] =>
+): OperationEditedFile[] =>
useMemo(() => deriveOperationEditedFiles(blocks ?? [], hasWorkSurface), [blocks, hasWorkSurface]);
diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
index bc4d8c78365..4c07f703a74 100644
--- a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
+++ b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
@@ -59,7 +59,11 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
const { t } = useTranslation('chat');
const [expanded, setExpanded] = useState(false);
- const [openDocument, openTaskDetail] = useChatStore((s) => [s.openDocument, s.openTaskDetail]);
+ const [openDocument, openFilePreview, openTaskDetail] = useChatStore((s) => [
+ s.openDocument,
+ s.openFilePreview,
+ s.openTaskDetail,
+ ]);
const ToggleIcon = expanded ? ChevronDownIcon : ChevronRightIcon;
// The underlying task was deleted outside the tool path — the Work survives as
// an orphan rendered from its snapshot, and opening the (gone) task detail 404s.
@@ -86,6 +90,9 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
? () => window.open(openTarget.url, '_blank', 'noopener,noreferrer')
: undefined;
}
+ case 'filePreview': {
+ return () => openFilePreview({ fileId: openTarget.fileId });
+ }
case 'task': {
return taskDeleted ? undefined : () => openTaskDetail(openTarget.identifier);
}
diff --git a/src/features/FileViewer/Renderer/Markdown/index.tsx b/src/features/FileViewer/Renderer/Markdown/index.tsx
new file mode 100644
index 00000000000..ddda4a516f6
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Markdown/index.tsx
@@ -0,0 +1,94 @@
+'use client';
+
+import { Center, Flexbox, Highlighter, Icon, Markdown } from '@lobehub/ui';
+import { Tabs } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CodeIcon, EyeIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+
+import { useTextFileLoader } from '../../hooks/useTextFileLoader';
+
+const styles = createStaticStyles(({ css }) => ({
+ // Same floating-controls treatment as the LocalFile portal's text preview, so
+ // the render/raw toggle reads identically across both file-preview surfaces.
+ controls: css`
+ position: absolute;
+ z-index: 2;
+ inset-block-start: 8px;
+ inset-inline-end: 12px;
+
+ padding: 4px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ opacity: 0.55;
+ background: ${cssVar.colorBgElevated};
+ backdrop-filter: blur(8px);
+ box-shadow: ${cssVar.boxShadowTertiary};
+
+ transition: opacity 150ms ease;
+
+ &:hover {
+ opacity: 1;
+ }
+ `,
+ page: css`
+ position: relative;
+ overflow: hidden auto;
+ width: 100%;
+ height: 100%;
+ `,
+}));
+
+type PreviewMode = 'render' | 'raw';
+
+interface MarkdownViewerProps {
+ fileId: string;
+ url: string | null;
+}
+
+/**
+ * Rendered markdown preview for cloud files (with a raw-source toggle) — the
+ * FilePreview counterpart of the LocalFile portal's markdown pane. Plain code
+ * files keep going through `Renderer/Code`.
+ */
+const MarkdownViewer = memo<MarkdownViewerProps>(({ url }) => {
+ const { t } = useTranslation('file');
+ const { fileData, loading } = useTextFileLoader(url);
+ const [mode, setMode] = useState<PreviewMode>('render');
+
+ if (loading || fileData === null)
+ return (
+ <Center height={'100%'} width={'100%'}>
+ <NeuralNetworkLoading size={36} />
+ </Center>
+ );
+
+ return (
+ <Flexbox className={styles.page}>
+ <Flexbox horizontal align={'center'} className={styles.controls} gap={4}>
+ <Tabs
+ activeKey={mode}
+ size={'small'}
+ items={[
+ { icon: <Icon icon={EyeIcon} />, key: 'render', label: t('preview.render') },
+ { icon: <Icon icon={CodeIcon} />, key: 'raw', label: t('preview.raw') },
+ ]}
+ onChange={(key) => setMode(key as PreviewMode)}
+ />
+ </Flexbox>
+ {mode === 'render' ? (
+ <Markdown style={{ paddingBlock: 16, paddingInline: 24 }}>{fileData}</Markdown>
+ ) : (
+ <Highlighter language={'markdown'} showLanguage={false} variant={'borderless'}>
+ {fileData}
+ </Highlighter>
+ )}
+ </Flexbox>
+ );
+});
+
+export default MarkdownViewer;
diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsx
index 9d22cee48e2..3cb091251f9 100644
--- a/src/features/FileViewer/index.tsx
+++ b/src/features/FileViewer/index.tsx
@@ -15,6 +15,7 @@ import NotSupport from './NotSupport';
import CodeViewer from './Renderer/Code';
import HTMLViewer from './Renderer/HTML';
import ImageViewer from './Renderer/Image';
+import MarkdownViewer from './Renderer/Markdown';
import MSDocViewer from './Renderer/MSDoc';
import type { PDFViewerProps } from './Renderer/PDF';
import { preloadPDFRenderer } from './Renderer/PDF/loader';
@@ -87,6 +88,8 @@ const CODE_EXTENSIONS = [
'.yml',
'.toml',
'.sql',
+ '.csv',
+ '.tsv',
// Functional languages
'.ex',
'.exs',
@@ -165,6 +168,10 @@ const CODE_MIME_TYPES = new Set([
'toml',
'sql',
'text/x-sql',
+ 'csv',
+ 'text/csv',
+ 'tsv',
+ 'text/tab-separated-values',
// Markdown
'md',
'mdx',
@@ -175,6 +182,12 @@ const CODE_MIME_TYPES = new Set([
'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.
+const MARKDOWN_EXTENSIONS = ['.md', '.mdx', '.markdown'];
+const MARKDOWN_FILE_MIME_TYPES = new Set(['md', 'mdx', 'markdown', ...MARKDOWN_MIME_TYPES]);
+
const MSDOC_EXTENSIONS = ['.doc', '.docx', '.odt', '.ppt', '.pptx', '.xls', '.xlsx'];
const MSDOC_MIME_TYPES = new Set([
'doc',
@@ -329,7 +342,12 @@ const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) =>
return <HTMLViewer fileId={id} url={url} />;
}
- // Code files (JavaScript, TypeScript, Python, Java, C++, Go, Rust, Markdown, etc.)
+ // Markdown files render as rich text with a raw toggle.
+ if (matchesFileType(fileType, name, MARKDOWN_EXTENSIONS, MARKDOWN_FILE_MIME_TYPES)) {
+ 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} />;
}
diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsx
index ae5083e0f7a..ed8dc24aacd 100644
--- a/src/features/Portal/LocalFile/Body.tsx
+++ b/src/features/Portal/LocalFile/Body.tsx
@@ -4,7 +4,7 @@ import { ActionIcon, Center, Empty, Flexbox, Icon, Image, Markdown, Text } from
import { Tabs } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { CodeIcon, EyeIcon, RefreshCwIcon } from 'lucide-react';
-import { memo, useCallback, useEffect, useMemo, useState } from 'react';
+import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import CodeEditorPane from '@/components/CodeEditorPane';
@@ -12,6 +12,7 @@ import { InlineHtmlPreview, isHtmlFile } from '@/components/HtmlPreview';
import Loading from '@/components/Loading/CircleLoading';
import { useClientDataSWR } from '@/libs/swr';
import { localFileKeys } from '@/libs/swr/keys';
+import { cloudSandboxService } from '@/services/cloudSandbox';
import { type LocalFilePreview, projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -25,6 +26,9 @@ import {
import { extensionToLanguage, getFileExtension } from './Body.helpers';
import MarkdownImage from './MarkdownImage';
+// Deferred: pulls in react-pdf, only needed once a binary document is opened.
+const DocumentPreview = lazy(() => import('./DocumentPreview'));
+
interface ImagePreviewProps {
blob: Blob;
filename: string;
@@ -355,16 +359,52 @@ interface ActiveFileViewProps {
allowExternalFilePreview?: boolean;
deviceId?: string;
filePath: string;
+ /** Read the file live from the topic's cloud sandbox instead of a filesystem. */
+ sandboxTopicId?: string;
workingDirectory: string;
}
+/**
+ * Live-read a text file from the topic's cloud sandbox via the `readLocalFile`
+ * sandbox tool. There is no durable copy anywhere — a recycled sandbox (or any
+ * tool failure) rejects, surfacing the sandbox-unavailable empty state.
+ */
+const fetchSandboxFilePreview = async (
+ path: string,
+ topicId: string,
+): Promise<LocalFilePreview> => {
+ // `readLocalFile` defaults an omitted range to the first 200 lines — always
+ // request the whole file for previews so long files don't render truncated.
+ const result = await cloudSandboxService.callTool(
+ 'readLocalFile',
+ { fullContent: true, path },
+ { topicId },
+ );
+ if (!result.success || typeof result.result?.content !== 'string')
+ throw new Error(result.error?.message || 'Failed to read sandbox file');
+
+ return {
+ content: result.result.content,
+ contentType: result.result.mimeType || 'text/plain',
+ type: 'text',
+ };
+};
+
const ActiveFileView = memo<ActiveFileViewProps>(
- ({ activeTopicId, allowExternalFilePreview, deviceId, filePath, workingDirectory }) => {
+ ({
+ activeTopicId,
+ allowExternalFilePreview,
+ deviceId,
+ filePath,
+ sandboxTopicId,
+ workingDirectory,
+ }) => {
const { t } = useTranslation('chat');
const filename = filePath.split('/').at(-1) ?? '';
- const enabled = Boolean(workingDirectory) && (!!deviceId || isDesktop);
- const resourceScope = !deviceId && isHtmlFile({ path: filePath }) ? 'workspace' : undefined;
+ const enabled = sandboxTopicId ? true : Boolean(workingDirectory) && (!!deviceId || isDesktop);
+ const resourceScope =
+ !sandboxTopicId && !deviceId && isHtmlFile({ path: filePath }) ? 'workspace' : undefined;
const {
data: preview,
error,
@@ -378,17 +418,20 @@ const ActiveFileView = memo<ActiveFileViewProps>(
deviceId,
filePath,
...(resourceScope && { resourceScope }),
+ ...(sandboxTopicId && { sandboxTopicId }),
workingDirectory,
})
: null,
() =>
- projectFileService.getLocalFilePreview({
- allowExternalFile: allowExternalFilePreview,
- deviceId,
- path: filePath,
- ...(resourceScope && { resourceScope }),
- workingDirectory,
- }),
+ sandboxTopicId
+ ? fetchSandboxFilePreview(filePath, sandboxTopicId)
+ : projectFileService.getLocalFilePreview({
+ allowExternalFile: allowExternalFilePreview,
+ deviceId,
+ path: filePath,
+ ...(resourceScope && { resourceScope }),
+ workingDirectory,
+ }),
{ revalidateOnFocus: false },
);
@@ -408,7 +451,13 @@ const ActiveFileView = memo<ActiveFileViewProps>(
if (error || !preview) {
return (
<Center height={'100%'} width={'100%'}>
- <Empty description={t('workingPanel.localFile.error')} />
+ <Empty
+ description={t(
+ sandboxTopicId
+ ? 'workingPanel.localFile.sandboxUnavailable'
+ : 'workingPanel.localFile.error',
+ )}
+ />
</Center>
);
}
@@ -417,6 +466,19 @@ const ActiveFileView = memo<ActiveFileViewProps>(
return <ImagePreview blob={preview.blob} filename={filename} />;
}
+ if (preview.type === 'document') {
+ return (
+ <Suspense fallback={<Loading />}>
+ <DocumentPreview
+ blob={preview.blob}
+ contentType={preview.contentType}
+ filePath={filePath}
+ isLocalFile={!sandboxTopicId && !deviceId && isDesktop}
+ />
+ </Suspense>
+ );
+ }
+
if (preview.type !== 'text') {
return (
<Center height={'100%'} width={'100%'}>
@@ -437,7 +499,8 @@ const ActiveFileView = memo<ActiveFileViewProps>(
filePath={filePath}
// Remote files are now editable: saveLocalFile routes the write to the
// device over RPC (writeProjectFile) just as local files go through IPC.
- readOnly={false}
+ // Sandbox files stay read-only — there is no write-back transport.
+ readOnly={!!sandboxTopicId}
reloading={isValidating}
resourceBaseUrl={preview.resourceBaseUrl}
workingDirectory={workingDirectory}
@@ -474,6 +537,7 @@ const Body = memo(() => {
allowExternalFilePreview={activeFile.allowExternalFilePreview}
deviceId={activeFile.deviceId}
filePath={activeFile.filePath}
+ sandboxTopicId={activeFile.sandboxTopicId}
workingDirectory={activeFile.workingDirectory}
/>
</Flexbox>
diff --git a/src/features/Portal/LocalFile/DocumentPreview.tsx b/src/features/Portal/LocalFile/DocumentPreview.tsx
new file mode 100644
index 00000000000..a2019ac3551
--- /dev/null
+++ b/src/features/Portal/LocalFile/DocumentPreview.tsx
@@ -0,0 +1,483 @@
+'use client';
+
+import 'react-pdf/dist/Page/AnnotationLayer.css';
+import 'react-pdf/dist/Page/TextLayer.css';
+
+import { Center, Flexbox, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import FileIcon from '@/components/FileIcon';
+import Loading from '@/components/Loading/CircleLoading';
+import { Document, Page, pdfjs } from '@/libs/pdfjs';
+import { localFileService } from '@/services/electron/localFileService';
+
+// Same CDN assets as the FileViewer PDF renderer — cmaps / fonts are required
+// for non-latin PDFs.
+const pdfOptions = {
+ cMapUrl: `https://registry.npmmirror.com/pdfjs-dist/${pdfjs.version}/files/cmaps/`,
+ standardFontDataUrl: `https://registry.npmmirror.com/pdfjs-dist/${pdfjs.version}/files/standard_fonts/`,
+};
+
+const maxPageWidth = 1200;
+
+const styles = createStaticStyles(({ css }) => ({
+ docxContainer: css`
+ overflow: auto;
+ height: 100%;
+ background: ${cssVar.colorBgLayout};
+
+ /* docx-preview renders fixed-size "pages"; keep them centered with a gap.
+ "safe center" falls back to flex-start when the page is wider than the
+ pane, so the left edge stays reachable by horizontal scroll. */
+ .docx-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ align-items: safe center;
+
+ padding: 10px;
+
+ background: transparent;
+ }
+
+ .docx-wrapper > section.docx {
+ margin-block-end: 0;
+ border-radius: 4px;
+ box-shadow: ${cssVar.boxShadowTertiary};
+ }
+ `,
+ fallbackIcon: css`
+ width: 64px;
+ height: 64px;
+ border-radius: 14px;
+ background: ${cssVar.colorFillTertiary};
+ `,
+ officeContainer: css`
+ overflow: auto;
+ height: 100%;
+ background: ${cssVar.colorBgLayout};
+ `,
+ page: css`
+ overflow: hidden;
+ margin-block-end: 12px;
+ border-radius: 4px;
+ box-shadow: ${cssVar.boxShadowTertiary};
+ `,
+ sheetTab: css`
+ cursor: pointer;
+
+ padding-block: 4px;
+ padding-inline: 12px;
+ border: none;
+ border-radius: 6px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ background: transparent;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ &[data-active='true'] {
+ font-weight: 500;
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ sheetTabs: css`
+ overflow-x: auto;
+ display: flex;
+ flex: none;
+ gap: 4px;
+
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ truncatedNote: css`
+ padding-block: 8px;
+ padding-inline: 12px;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ xlsxContainer: css`
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ background: ${cssVar.colorBgContainer};
+ `,
+ xlsxTable: css`
+ overflow: auto;
+ flex: 1;
+
+ table {
+ border-collapse: collapse;
+ font-size: 12px;
+ }
+
+ td {
+ overflow: hidden;
+
+ max-width: 320px;
+ padding-block: 4px;
+ padding-inline: 8px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ `,
+ pdfContainer: css`
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+
+ height: 100%;
+ padding-block: 10px;
+
+ background: ${cssVar.colorBgLayout};
+ `,
+}));
+
+const PdfPane = memo<{ blob: Blob }>(({ blob }) => {
+ const [numPages, setNumPages] = useState(0);
+ const [container, setContainer] = useState<HTMLElement | null>(null);
+ const [containerWidth, setContainerWidth] = useState<number>();
+
+ useEffect(() => {
+ if (!container) return;
+
+ const observer = new ResizeObserver(([entry]) => {
+ if (entry) setContainerWidth(entry.contentRect.width);
+ });
+ observer.observe(container);
+ return () => observer.disconnect();
+ }, [container]);
+
+ const width = containerWidth ? Math.min(containerWidth - 32, maxPageWidth) : undefined;
+
+ return (
+ <div className={styles.pdfContainer} ref={setContainer}>
+ <Document
+ file={blob}
+ loading={<Loading />}
+ options={pdfOptions}
+ onLoadSuccess={(document) => setNumPages(document.numPages)}
+ >
+ {Array.from({ length: numPages }, (_, index) => (
+ <Page
+ className={styles.page}
+ key={`page_${index + 1}`}
+ pageNumber={index + 1}
+ width={width}
+ />
+ ))}
+ </Document>
+ </div>
+ );
+});
+
+PdfPane.displayName = 'PdfPane';
+
+interface OfficePaneProps {
+ blob: Blob;
+ /** Renderer failed — parent swaps in the download / open-externally state. */
+ onError: (error: unknown) => void;
+}
+
+const PptxPane = memo<OfficePaneProps>(({ blob, onError }) => {
+ const [loading, setLoading] = useState(true);
+ const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);
+ const [container, setContainer] = useState<HTMLElement | null>(null);
+
+ useEffect(() => {
+ if (!container || !scrollEl) return;
+
+ const controller = new AbortController();
+ let viewer: { destroy: () => void } | undefined;
+
+ (async () => {
+ try {
+ const { PptxViewer, RECOMMENDED_ZIP_LIMITS } = await import('@aiden0z/pptx-renderer');
+ if (controller.signal.aborted) return;
+ viewer = await PptxViewer.open(blob, container, {
+ listOptions: { windowed: true },
+ scrollContainer: scrollEl,
+ signal: controller.signal,
+ // Local files are still untrusted input (agent/tool generated) — cap
+ // the ZIP expansion to keep a hostile pptx from exhausting memory.
+ zipLimits: RECOMMENDED_ZIP_LIMITS,
+ });
+ setLoading(false);
+ } catch (error) {
+ if (controller.signal.aborted) return;
+ onError(error);
+ }
+ })();
+
+ return () => {
+ controller.abort();
+ viewer?.destroy();
+ };
+ }, [blob, container, scrollEl, onError]);
+
+ return (
+ <div className={styles.officeContainer} ref={setScrollEl}>
+ {loading && <Loading />}
+ {/* The viewer owns this node's children — React must never render into it,
+ or its bookkeeping breaks when the library replaces the content. */}
+ <div ref={setContainer} />
+ </div>
+ );
+});
+
+PptxPane.displayName = 'PptxPane';
+
+const DocxPane = memo<OfficePaneProps>(({ blob, onError }) => {
+ const [loading, setLoading] = useState(true);
+ const [container, setContainer] = useState<HTMLElement | null>(null);
+
+ useEffect(() => {
+ if (!container) return;
+
+ let disposed = false;
+
+ (async () => {
+ try {
+ const { renderAsync } = await import('docx-preview');
+ if (disposed) return;
+ await renderAsync(blob, container);
+ if (!disposed) setLoading(false);
+ } catch (error) {
+ if (!disposed) onError(error);
+ }
+ })();
+
+ return () => {
+ disposed = true;
+ // renderAsync has no dispose handle — it owns the container's children
+ // (including injected <style>), so clearing it is the documented cleanup.
+ container.replaceChildren();
+ };
+ }, [blob, container, onError]);
+
+ return (
+ <div className={styles.docxContainer}>
+ {loading && <Loading />}
+ <div ref={setContainer} />
+ </div>
+ );
+});
+
+DocxPane.displayName = 'DocxPane';
+
+/**
+ * DOM tables choke on huge sheets; a preview only needs the head of the data.
+ * Users open the real file (default app / download) for the full sheet.
+ */
+const MAX_PREVIEW_ROWS = 500;
+
+interface SheetGrid {
+ name: string;
+ rows: string[][];
+ truncated: boolean;
+}
+
+/** Flatten an exceljs cell value (rich text / formula / hyperlink / date …) to display text. */
+const formatCellValue = (value: unknown): string => {
+ if (value === null || value === undefined) return '';
+ if (value instanceof Date) return value.toISOString().slice(0, 10);
+ if (typeof value === 'object') {
+ const cell = value as {
+ error?: string;
+ formula?: string;
+ hyperlink?: string;
+ result?: unknown;
+ richText?: { text: string }[];
+ text?: unknown;
+ };
+ if (cell.richText) return cell.richText.map((run) => run.text).join('');
+ if (cell.formula !== undefined) return formatCellValue(cell.result);
+ if (cell.text !== undefined) return formatCellValue(cell.text);
+ if (cell.error) return cell.error;
+ return '';
+ }
+ return String(value);
+};
+
+const XlsxPane = memo<OfficePaneProps>(({ blob, onError }) => {
+ const { t } = useTranslation('chat');
+ const [sheets, setSheets] = useState<SheetGrid[]>();
+ const [activeSheet, setActiveSheet] = useState(0);
+
+ useEffect(() => {
+ let disposed = false;
+
+ (async () => {
+ try {
+ const { Workbook } = await import('exceljs');
+ const workbook = new Workbook();
+ await workbook.xlsx.load(await blob.arrayBuffer());
+ if (disposed) return;
+
+ const grids: SheetGrid[] = workbook.worksheets.map((sheet) => {
+ const columnCount = sheet.actualColumnCount;
+ const rows: string[][] = [];
+ // eachRow skips empty rows, keeping the preview dense; row order is preserved.
+ sheet.eachRow((row) => {
+ if (rows.length >= MAX_PREVIEW_ROWS) return;
+ const cells: string[] = [];
+ for (let index = 1; index <= columnCount; index++) {
+ cells.push(formatCellValue(row.getCell(index).value));
+ }
+ rows.push(cells);
+ });
+ return { name: sheet.name, rows, truncated: sheet.actualRowCount > MAX_PREVIEW_ROWS };
+ });
+ setSheets(grids);
+ setActiveSheet(0);
+ } catch (error) {
+ if (!disposed) onError(error);
+ }
+ })();
+
+ return () => {
+ disposed = true;
+ };
+ }, [blob, onError]);
+
+ if (!sheets) return <Loading />;
+
+ const sheet = sheets[activeSheet] ?? sheets[0];
+
+ return (
+ <div className={styles.xlsxContainer}>
+ {sheets.length > 1 && (
+ <div className={styles.sheetTabs}>
+ {sheets.map((item, index) => (
+ <button
+ className={styles.sheetTab}
+ data-active={index === activeSheet}
+ key={`${index}-${item.name}`}
+ type={'button'}
+ onClick={() => setActiveSheet(index)}
+ >
+ {item.name}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className={styles.xlsxTable}>
+ <table>
+ <tbody>
+ {sheet?.rows.map((row, rowIndex) => (
+ <tr key={rowIndex}>
+ {row.map((cell, cellIndex) => (
+ <td key={cellIndex}>{cell}</td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {sheet?.truncated && (
+ <div className={styles.truncatedNote}>
+ {t('workingPanel.localFile.document.truncatedRows', { count: MAX_PREVIEW_ROWS })}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+});
+
+XlsxPane.displayName = 'XlsxPane';
+
+/**
+ * Modern OOXML formats with an in-app renderer. Legacy binary formats (.doc /
+ * .ppt / .xls) have none and keep the download / open-externally fallback.
+ */
+const OFFICE_PANES: Record<string, typeof PptxPane> = {
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': PptxPane,
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': XlsxPane,
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': DocxPane,
+};
+
+export interface DocumentPreviewProps {
+ blob: Blob;
+ contentType: string;
+ filePath: string;
+ /** File lives on this desktop's filesystem — offer "open with default app". */
+ isLocalFile: boolean;
+}
+
+/**
+ * In-portal preview for binary documents transported as blobs. PDFs render
+ * inline via react-pdf (the Electron iframe PDF plugin is disabled, so a blob
+ * URL in an iframe would not render on desktop); pptx / docx / xlsx render
+ * inline via dynamically-imported client renderers, falling back to a
+ * download / open-externally state when parsing fails. Legacy binary office
+ * formats (.doc / .ppt / .xls) have no local renderer and always degrade.
+ */
+const DocumentPreview = memo<DocumentPreviewProps>(
+ ({ blob, contentType, filePath, isLocalFile }) => {
+ const { t } = useTranslation('chat');
+ const filename = filePath.split('/').at(-1) ?? '';
+ const [renderError, setRenderError] = useState(false);
+
+ useEffect(() => {
+ setRenderError(false);
+ }, [blob, contentType]);
+
+ const handleRenderError = useCallback((error: unknown) => {
+ console.error('[DocumentPreview] office render failed:', error);
+ setRenderError(true);
+ }, []);
+
+ const handleDownload = useCallback(() => {
+ const url = URL.createObjectURL(blob);
+ const anchor = globalThis.document.createElement('a');
+ anchor.href = url;
+ anchor.download = filename;
+ anchor.click();
+ // Chromium resolves the blob URL synchronously on click, but defer the
+ // revoke so slower engines can still start the download.
+ setTimeout(() => URL.revokeObjectURL(url), 10_000);
+ }, [blob, filename]);
+
+ if (contentType === 'application/pdf') return <PdfPane blob={blob} />;
+
+ const OfficePane = OFFICE_PANES[contentType];
+ if (OfficePane && !renderError) {
+ return <OfficePane blob={blob} onError={handleRenderError} />;
+ }
+
+ return (
+ <Center gap={16} height={'100%'} width={'100%'}>
+ <Center className={styles.fallbackIcon}>
+ <FileIcon fileName={filename} size={40} />
+ </Center>
+ <Flexbox align={'center'} gap={4}>
+ <Text style={{ fontWeight: 500 }}>{filename}</Text>
+ <Text type={'secondary'}>{t('workingPanel.localFile.document.unsupported')}</Text>
+ </Flexbox>
+ {isLocalFile ? (
+ <Button onClick={() => localFileService.openLocalFile({ path: filePath })}>
+ {t('workingPanel.localFile.document.openWithDefaultApp')}
+ </Button>
+ ) : (
+ <Button onClick={handleDownload}>{t('workingPanel.localFile.document.download')}</Button>
+ )}
+ </Center>
+ );
+ },
+);
+
+DocumentPreview.displayName = 'DocumentPreview';
+
+export default DocumentPreview;
diff --git a/src/features/Portal/LocalFile/Header.tsx b/src/features/Portal/LocalFile/Header.tsx
index 95dfb12fd5c..a0ce0bbc051 100644
--- a/src/features/Portal/LocalFile/Header.tsx
+++ b/src/features/Portal/LocalFile/Header.tsx
@@ -26,6 +26,11 @@ const Header = memo(() => {
const navigate = useWorkspaceAwareNavigate();
const params = useParams<{ aid?: string; topicId?: string }>();
const activeLocalFilePath = useChatStore(chatPortalSelectors.activeLocalFilePath);
+ // Sandbox-backed tabs point at paths inside the cloud sandbox, not the local
+ // filesystem — "show in system" would open an unrelated folder or fail.
+ const isSandboxFile = useChatStore(
+ (s) => !!chatPortalSelectors.currentLocalFile(s)?.sandboxTopicId,
+ );
const [canGoBack, goBack, clearPortalStack] = useChatStore((s) => [
chatPortalSelectors.canGoBack(s),
s.goBack,
@@ -55,7 +60,7 @@ const Header = memo(() => {
}
right={
<Fragment>
- {isDesktop && activeLocalFilePath && (
+ {isDesktop && activeLocalFilePath && !isSandboxFile && (
<ActionIcon
icon={FolderOpen}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
diff --git a/src/features/Portal/LocalFile/TabStrip.tsx b/src/features/Portal/LocalFile/TabStrip.tsx
index 82a4eb0177a..cd4abddf210 100644
--- a/src/features/Portal/LocalFile/TabStrip.tsx
+++ b/src/features/Portal/LocalFile/TabStrip.tsx
@@ -207,7 +207,10 @@ const TabStrip = memo(() => {
label: t('workingPanel.localFile.closeOther'),
onClick: () => closeOtherLocalFileTabs(id),
},
- ...(isDesktop
+ // Sandbox-backed tabs point at paths inside the cloud sandbox — a local
+ // "show in system" would open an unrelated folder or fail.
+ ...(isDesktop &&
+ !openLocalFiles.find((file) => getLocalFileTabId(file) === id)?.sandboxTopicId
? [
{
key: 'showInSystem',
diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsx
index 29a8e7ba86e..70c2adc6dea 100644
--- a/src/features/Work/WorkSummaryCard.tsx
+++ b/src/features/Work/WorkSummaryCard.tsx
@@ -118,6 +118,7 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
({ className, item, onOpen, variant = 'card' }) => {
const { t } = useTranslation('chat');
const openDocument = useChatStore((s) => s.openDocument);
+ const openFilePreview = useChatStore((s) => s.openFilePreview);
const openTaskDetail = useChatStore((s) => s.openTaskDetail);
const cost = formatWorkVersionCost(item.totalCost);
@@ -154,6 +155,10 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
window.open(openTarget.url, '_blank', 'noopener,noreferrer');
return;
}
+ case 'filePreview': {
+ openFilePreview({ fileId: openTarget.fileId });
+ return;
+ }
case 'task': {
openTaskDetail(openTarget.identifier);
}
diff --git a/src/features/Work/descriptors.test.ts b/src/features/Work/descriptors.test.ts
index a06735b5e1a..da847dbb828 100644
--- a/src/features/Work/descriptors.test.ts
+++ b/src/features/Work/descriptors.test.ts
@@ -27,6 +27,60 @@ describe('getWorkTypeDescriptor', () => {
expect(descriptor.getOpenTarget(item)).toBeNull();
});
+ describe('file open target', () => {
+ const baseFileItem = {
+ description: '/tmp/deck/slides.pptx',
+ id: 'work-file-1',
+ identifier: 'slides.pptx',
+ resourceId: 'user:topic:/tmp/deck/slides.pptx',
+ title: 'slides.pptx',
+ type: 'file',
+ };
+
+ it('prefers the in-app file preview when the summary metadata carries a fileId', () => {
+ const item = {
+ ...baseFileItem,
+ event: { metadata: { fileId: 'file-1', fileUrl: 'https://cdn.example.com/f/1' } },
+ url: 'https://cdn.example.com/f/1',
+ } as any;
+
+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({
+ fileId: 'file-1',
+ kind: 'filePreview',
+ url: 'https://cdn.example.com/f/1',
+ });
+ });
+
+ it('omits the url fallback when the persisted url is not http(s)', () => {
+ const item = {
+ ...baseFileItem,
+ event: { metadata: { fileId: 'file-1', fileUrl: 'javascript:alert(1)' } },
+ url: null,
+ } as any;
+
+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({
+ fileId: 'file-1',
+ kind: 'filePreview',
+ url: undefined,
+ });
+ });
+
+ it('falls back to the external url for list rows without version metadata', () => {
+ const item = { ...baseFileItem, url: 'https://cdn.example.com/f/1' } as any;
+
+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({
+ kind: 'external',
+ url: 'https://cdn.example.com/f/1',
+ });
+ });
+
+ it('yields no target when neither fileId nor a safe url exists', () => {
+ const item = { ...baseFileItem, url: null } as any;
+
+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toBeNull();
+ });
+ });
+
it('still resolves a known type to its concrete descriptor', () => {
const item = {
description: 'Doc body',
diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsx
index a750d6cb252..e6b8762c235 100644
--- a/src/features/Work/descriptors.tsx
+++ b/src/features/Work/descriptors.tsx
@@ -8,6 +8,7 @@ import {
type WorkVersionMetadata,
} from '@lobechat/types';
import { Github } from '@lobehub/icons';
+import { FileTypeIcon as FileTypeBadge } from '@lobehub/ui';
import {
ClipboardListIcon,
FileBoxIcon,
@@ -19,6 +20,8 @@ import {
} from 'lucide-react';
import type { ComponentType } from 'react';
+import { mimeTypeMap } from '@/components/FileIcon/config';
+
import LinearIcon from './icons/LinearIcon';
type WorkIcon = ComponentType<{ className?: string; size?: number }>;
@@ -41,7 +44,13 @@ const PROVIDER_ICONS: Record<WorkSkillProvider, WorkIcon> = {
export type WorkOpenTarget =
| { agentDocumentId?: string; documentId: string; kind: 'document' }
| { identifier: string; kind: 'task' }
- | { kind: 'external'; url: string };
+ | { kind: 'external'; url: string }
+ /**
+ * In-app preview of a cloud-persisted file (the FilePreview chat portal).
+ * `url` is the already-allowlisted download fallback for surfaces without a
+ * chat portal (WorkGallery), so they don't recompute the file-metadata lookup.
+ */
+ | { fileId: string; kind: 'filePreview'; url?: string };
/**
* Client-side allowlist for external Work URLs (defense in depth over the
@@ -96,8 +105,8 @@ interface WorkTypeDescriptor<Item extends WorkListItem | WorkSummaryItem> {
}
/**
- * Entity-format icon per {@link classifyEditedFile} kind. `pdf` gets its own
- * glyph; everything unclassifiable falls back to the generic file-text icon.
+ * Fallback entity-format glyph per {@link classifyEditedFile} kind, for a future
+ * entity extension without a `mimeTypeMap` brand color.
*/
const FILE_WORK_ICONS: Record<'slides' | 'sheet' | 'doc' | 'pdf', WorkIcon> = {
doc: FileTextIcon,
@@ -106,6 +115,34 @@ const FILE_WORK_ICONS: Record<'slides' | 'sheet' | 'doc' | 'pdf', WorkIcon> = {
slides: PresentationIcon,
};
+/**
+ * Branded file-type badge (the colored PPTX/DOCX/XLSX/PDF glyph used by the file
+ * preview surfaces) for entity file Works. Cached per extension so `getIcon`
+ * keeps a stable component identity across renders — an inline closure would
+ * remount the icon subtree every time the card re-renders.
+ */
+const FILE_BADGE_ICONS = new Map<string, WorkIcon>();
+
+const getFileBadgeIcon = (extension: string): WorkIcon | undefined => {
+ const color = mimeTypeMap[extension];
+ if (!color) return undefined;
+
+ let Icon = FILE_BADGE_ICONS.get(extension);
+ if (!Icon) {
+ Icon = ({ className, size }) => (
+ <FileTypeBadge
+ className={className}
+ color={color}
+ filetype={extension.toUpperCase()}
+ size={size}
+ type={'file'}
+ />
+ );
+ FILE_BADGE_ICONS.set(extension, Icon);
+ }
+ return Icon;
+};
+
/**
* The per-version file identity (path / url / line deltas) lives in the version
* metadata, which only summary rows carry (`event.metadata`); plain list rows
@@ -147,22 +184,27 @@ export const WORK_TYPE_DESCRIPTORS: {
// Subtitle is the file path (metadata), falling back to the denormalized
// description column for list rows without version metadata.
getDescription: (item) => getFileWorkPath(item),
- // Pick the icon from the file's entity kind; unclassifiable paths (or a
- // path-less list row) fall back to the generic file-text glyph.
+ // Pick the branded file-type badge from the file's extension; unclassifiable
+ // paths (or a path-less list row) fall back to the generic file-text glyph.
getIcon: (item) => {
const path = getFileWorkPath(item);
const classified = path ? classifyEditedFile(path) : undefined;
- return classified?.category === 'entity'
- ? FILE_WORK_ICONS[classified.entityKind]
- : FileTextIcon;
+ if (classified?.category !== 'entity') return FileTextIcon;
+ const extension = path!.split('.').pop()!.toLowerCase();
+ return getFileBadgeIcon(extension) ?? FILE_WORK_ICONS[classified.entityKind];
},
getIdentifier: (item) => item.identifier,
- // Open/download the persisted file when a durable URL exists — prefer the
- // version metadata's fileUrl, else the denormalized `url` column. Gated on
- // http(s) so Electron only ever hands safe URLs to shell.openExternal.
+ // Prefer the in-app FilePreview portal via the file-store id (summary rows
+ // only — list rows carry no version metadata). Fall back to opening the
+ // persisted URL when no fileId exists: prefer the version metadata's
+ // fileUrl, else the denormalized `url` column. Gated on http(s) so Electron
+ // only ever hands safe URLs to shell.openExternal.
getOpenTarget: (item) => {
- const fileUrl = getFileWorkMetadata(item)?.fileUrl ?? item.url;
- return isSafeExternalUrl(fileUrl) ? { kind: 'external', url: fileUrl } : null;
+ const metadata = getFileWorkMetadata(item);
+ const fileUrl = metadata?.fileUrl ?? item.url;
+ const safeUrl = isSafeExternalUrl(fileUrl) ? fileUrl : undefined;
+ if (metadata?.fileId) return { fileId: metadata.fileId, kind: 'filePreview', url: safeUrl };
+ return safeUrl ? { kind: 'external', url: safeUrl } : null;
},
// Title is the file name (basename of the path), falling back to the
// denormalized title column.
diff --git a/src/features/WorkGallery/WorkPreviewCard.tsx b/src/features/WorkGallery/WorkPreviewCard.tsx
index 9643e678c64..f140135f1be 100644
--- a/src/features/WorkGallery/WorkPreviewCard.tsx
+++ b/src/features/WorkGallery/WorkPreviewCard.tsx
@@ -92,9 +92,13 @@ const WorkPreviewCard = memo<WorkPreviewCardProps>(({ item, onOpen }) => {
item.id;
const description = descriptor.getDescription(item);
// Same clickability gating as WorkSummaryCard: no open target or an orphaned
- // (deleted-task) Work renders inert.
+ // (deleted-task) Work renders inert. The gallery has no chat portal, so a
+ // filePreview target is only actionable here through its persisted URL
+ // fallback — without one the card must not offer a dead click.
const taskDeleted = item.resourceType === 'task' && item.taskDeleted;
- const clickable = !!descriptor.getOpenTarget(item) && !taskDeleted;
+ const openTarget = descriptor.getOpenTarget(item);
+ const actionable = !!openTarget && (openTarget.kind !== 'filePreview' || !!openTarget.url);
+ const clickable = actionable && !taskDeleted;
return (
<Flexbox
diff --git a/src/features/WorkGallery/index.tsx b/src/features/WorkGallery/index.tsx
index 8d38711d64a..30badc6c823 100644
--- a/src/features/WorkGallery/index.tsx
+++ b/src/features/WorkGallery/index.tsx
@@ -244,6 +244,14 @@ const WorkGallery = memo<WorkGalleryProps>(({ galleryKey }) => {
window.open(openTarget.url, '_blank', 'noopener,noreferrer');
return;
}
+ // file works: the gallery lives outside the conversation UI, so the
+ // FilePreview chat portal isn't available — fall back to opening the
+ // persisted file URL like the pre-portal behavior.
+ case 'filePreview': {
+ if (isSafeExternalUrl(openTarget.url))
+ window.open(openTarget.url, '_blank', 'noopener,noreferrer');
+ return;
+ }
// task: no external URL — the standalone detail route resolves the same
// identifier-or-id the chat portal uses.
case 'task': {
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 48a0eb221bc..79c3a4f5c20 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -40,6 +40,8 @@ interface LocalFilePreviewKeyParams {
deviceId?: string;
filePath: string;
resourceScope?: 'workspace';
+ /** Topic scope when the previewed file lives in the topic's cloud sandbox. */
+ sandboxTopicId?: string;
workingDirectory: string;
}
@@ -927,10 +929,11 @@ export const localFileKeys = {
deviceId,
filePath,
resourceScope,
+ sandboxTopicId,
workingDirectory,
}: LocalFilePreviewKeyParams) => [
'localFile:preview',
- deviceId ?? 'local',
+ sandboxTopicId ? `sandbox:${sandboxTopicId}` : (deviceId ?? 'local'),
filePath,
workingDirectory,
accept ?? 'any',
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index e387bbb44b5..b5c017f0b14 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -60,6 +60,16 @@ export interface BinaryLocalFilePreview {
type: 'binary' | 'pdf' | 'video';
}
+/**
+ * Binary document (pdf / office) small enough to preview in-app. Oversized
+ * documents stay on the content-less `binary` / `pdf` variants.
+ */
+export interface DocumentLocalFilePreview {
+ blob: Blob;
+ contentType: string;
+ type: 'document';
+}
+
export interface ImageLocalFilePreview {
blob: Blob;
contentType: string;
@@ -74,7 +84,25 @@ export interface TextLocalFilePreview {
}
export type LocalFilePreview =
- BinaryLocalFilePreview | ImageLocalFilePreview | TextLocalFilePreview;
+ BinaryLocalFilePreview | DocumentLocalFilePreview | ImageLocalFilePreview | TextLocalFilePreview;
+
+/** Binary documents the in-app portal can preview (or offer to download). */
+const DOCUMENT_PREVIEW_MIME_TYPES = new Set([
+ 'application/msword',
+ 'application/pdf',
+ 'application/vnd.ms-excel',
+ 'application/vnd.ms-powerpoint',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+]);
+
+/**
+ * Mirrors the device-RPC document cap (`MAX_DOCUMENT_PREVIEW_BYTES` in the
+ * desktop / device-control serializers) so the same file previews — or falls
+ * back — identically on every transport.
+ */
+const MAX_DOCUMENT_PREVIEW_BYTES = 20 * 1024 * 1024;
const normalizeContentType = (contentType: string | null): string =>
contentType?.split(';')[0].trim().toLowerCase() ?? '';
@@ -112,6 +140,28 @@ const fetchLocalFilePreview = async (
};
}
+ if (DOCUMENT_PREVIEW_MIME_TYPES.has(contentType)) {
+ // Gate on the size headers first so an oversized document is never
+ // materialized in renderer memory just to be discarded. The desktop
+ // protocol short-circuits oversized documents with an empty body and the
+ // real size in `X-Preview-Content-Size`; Content-Length covers hosts that
+ // still serve the body. Fall back to the blob-size check otherwise.
+ const contentLength = Number(
+ response.headers.get('x-preview-content-size') ?? response.headers.get('content-length'),
+ );
+ const oversizedByHeader =
+ Number.isFinite(contentLength) &&
+ contentLength > 0 &&
+ contentLength > MAX_DOCUMENT_PREVIEW_BYTES;
+
+ if (!oversizedByHeader) {
+ const blob = await response.blob();
+ if (blob.size <= MAX_DOCUMENT_PREVIEW_BYTES) {
+ return { blob, contentType, type: 'document' };
+ }
+ }
+ }
+
if (contentType === 'application/pdf') {
return { contentType, type: 'pdf' };
}
diff --git a/src/services/projectFile.ts b/src/services/projectFile.ts
index 2d39545d4dc..fdaad502338 100644
--- a/src/services/projectFile.ts
+++ b/src/services/projectFile.ts
@@ -24,6 +24,14 @@ const base64ToBlob = (base64: string, contentType: string): Blob => {
const deserializeLocalFilePreview = (preview: DeviceLocalFilePreview): LocalFilePreview => {
switch (preview.type) {
+ case 'document': {
+ return {
+ blob: base64ToBlob(preview.base64, preview.contentType),
+ contentType: preview.contentType,
+ type: 'document',
+ };
+ }
+
case 'image': {
return {
blob: base64ToBlob(preview.base64, preview.contentType),
diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.ts
index 5ba1260847d..e298283c0bd 100644
--- a/src/store/chat/slices/portal/action.test.ts
+++ b/src/store/chat/slices/portal/action.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it, vi } from 'vitest';
import { projectFileService } from '@/services/projectFile';
import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { createLocalFileScopeKey, createLocalFileTabId } from './helpers';
import { PortalViewType } from './initialState';
@@ -483,6 +485,97 @@ describe('chatDockSlice', () => {
expect(result.current.activeLocalFilePath).toBe('/tmp/worktree-switcher-demo.html');
});
+ // Regression: sandbox tabs are visible in the current topic's cwd scope
+ // (the selector exempts them from the cwd match), so their activation must
+ // land in that scope — previously it landed in the empty-cwd scope and the
+ // portal kept showing the topic's previously active local file.
+ it('activates a sandbox tab within the current topic cwd scope', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-a',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'agent-1' })]: {
+ currentPage: 1,
+ hasMore: false,
+ items: [{ id: 'topic-a', metadata: { workingDirectory: '/project-a' } }],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ } as never);
+ });
+
+ act(() => {
+ result.current.openLocalFile({
+ filePath: '/project-a/a.ts',
+ workingDirectory: '/project-a',
+ });
+ });
+
+ act(() => {
+ result.current.openLocalFile({
+ filePath: '/work/notes.md',
+ sandboxTopicId: 'topic-a',
+ workingDirectory: '',
+ });
+ });
+
+ expect(
+ result.current.activeLocalFileIdsByScope?.[createLocalFileScopeKey('/project-a')],
+ ).toBe(
+ createLocalFileTabId({
+ filePath: '/work/notes.md',
+ sandboxTopicId: 'topic-a',
+ workingDirectory: '',
+ }),
+ );
+ });
+
+ it('keeps per-topic sandbox activation when topics have no cwd', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({ activeAgentId: 'agent-1', activeTopicId: 'topic-a' } as never);
+ });
+
+ act(() => {
+ result.current.openLocalFile({
+ filePath: '/work/a.md',
+ sandboxTopicId: 'topic-a',
+ workingDirectory: '',
+ });
+ });
+
+ act(() => {
+ useChatStore.setState({ activeTopicId: 'topic-b' } as never);
+ });
+
+ act(() => {
+ result.current.openLocalFile({
+ filePath: '/work/b.md',
+ sandboxTopicId: 'topic-b',
+ workingDirectory: '',
+ });
+ });
+
+ // Back in topic-a, its own sandbox tab must stay active even though the
+ // legacy global active id now points at topic-b's tab.
+ act(() => {
+ useChatStore.setState({ activeTopicId: 'topic-a' } as never);
+ });
+
+ expect(chatPortalSelectors.activeLocalFileId(useChatStore.getState())).toBe(
+ createLocalFileTabId({
+ filePath: '/work/a.md',
+ sandboxTopicId: 'topic-a',
+ workingDirectory: '',
+ }),
+ );
+ });
+
it('should keep same file path from different device context as separate tabs', () => {
const { result } = renderHook(() => useChatStore());
@@ -972,6 +1065,57 @@ describe('chatDockSlice', () => {
'/project-a/b.ts',
]);
});
+
+ it('groups sandbox tabs by serving topic when closing others in a cwd scope', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-a',
+ topicDataMap: {
+ [topicMapKey({ agentId: 'agent-1' })]: {
+ currentPage: 1,
+ hasMore: false,
+ items: [{ id: 'topic-a', metadata: { workingDirectory: '/project-a' } }],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ } as never);
+ });
+
+ act(() => {
+ result.current.openLocalFile({
+ filePath: '/project-a/a.ts',
+ workingDirectory: '/project-a',
+ });
+ result.current.openLocalFile({
+ filePath: '/work/notes.md',
+ sandboxTopicId: 'topic-a',
+ workingDirectory: '',
+ });
+ // Hidden in topic-a: served by another topic's sandbox.
+ result.current.openLocalFile({
+ filePath: '/work/other.md',
+ sandboxTopicId: 'topic-b',
+ workingDirectory: '',
+ });
+ });
+
+ act(() => {
+ result.current.closeOtherLocalFileTabs(
+ localFileTabId({ filePath: '/project-a/a.ts', workingDirectory: '/project-a' }),
+ );
+ });
+
+ // The visible sandbox tab (topic-a) closes with the scope; the hidden
+ // topic-b sandbox tab survives.
+ expect(result.current.openLocalFiles.map((f) => f.filePath)).toEqual([
+ '/project-a/a.ts',
+ '/work/other.md',
+ ]);
+ });
});
describe('setActiveLocalFile', () => {
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index e4562332e6e..852f37be9ae 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -7,7 +7,12 @@ import { type StoreSetter } from '@/store/types';
import { type PortalArtifact } from '@/types/artifact';
import { topicSelectors } from '../topic/selectors';
-import { createLocalFileScopeKey, createLocalFileTabId, getLocalFileTabId } from './helpers';
+import {
+ createLocalFileScopeKey,
+ createLocalFileTabId,
+ createSandboxLocalFileScopeKey,
+ getLocalFileTabId,
+} from './helpers';
import { type OpenLocalFileParams, type PortalFile, type PortalViewData } from './initialState';
import { PortalViewType } from './initialState';
@@ -34,8 +39,14 @@ const findLocalFileById = <T extends OpenLocalFileParams & { id?: string }>(
openLocalFiles.find((file) => file.filePath === id))
: undefined;
+// Sandbox tabs carry no client-side working directory, so their fallback scope
+// (used when the active topic has no cwd) is keyed by the serving topic —
+// otherwise every unscoped topic shares one global scope and overwrites the
+// others' activation.
const getLocalFileEntryScopeKey = (file: OpenLocalFileParams): string =>
- createLocalFileScopeKey(file.workingDirectory);
+ file.sandboxTopicId
+ ? createSandboxLocalFileScopeKey(file.sandboxTopicId)
+ : createLocalFileScopeKey(file.workingDirectory);
const getLocalFilesInEntryScope = <T extends OpenLocalFileParams & { id?: string }>(
openLocalFiles: T[],
@@ -48,6 +59,20 @@ const getCurrentLocalFileScopeKey = (state: ChatStore): string | undefined => {
return workingDirectory ? createLocalFileScopeKey(workingDirectory) : undefined;
};
+// Mirrors the selector's `isLocalFileInCurrentScope`: sandbox tabs carry no
+// client-side working directory, so they are scoped by their serving topic
+// rather than the cwd match — bulk-close actions must group them the same way
+// the tab strip renders them.
+const isLocalFileVisibleInScope = <T extends OpenLocalFileParams>(
+ state: ChatStore,
+ currentScopeKey: string,
+ file: T,
+): boolean => {
+ if (file.allowExternalFilePreview) return true;
+ if (file.sandboxTopicId) return file.sandboxTopicId === state.activeTopicId;
+ return getLocalFileEntryScopeKey(file) === currentScopeKey;
+};
+
const getLocalFileCloseScope = <T extends OpenLocalFileParams & { id?: string }>({
openLocalFiles,
state,
@@ -60,8 +85,7 @@ const getLocalFileCloseScope = <T extends OpenLocalFileParams & { id?: string }>
const currentScopeKey = getCurrentLocalFileScopeKey(state);
const targetEntryScopeKey = getLocalFileEntryScopeKey(target);
const targetIsVisibleInCurrentScope =
- !!currentScopeKey &&
- (target.allowExternalFilePreview || targetEntryScopeKey === currentScopeKey);
+ !!currentScopeKey && isLocalFileVisibleInScope(state, currentScopeKey, target);
if (!currentScopeKey || !targetIsVisibleInCurrentScope) {
return {
@@ -71,10 +95,7 @@ const getLocalFileCloseScope = <T extends OpenLocalFileParams & { id?: string }>
}
return {
- files: openLocalFiles.filter(
- (file) =>
- file.allowExternalFilePreview || getLocalFileEntryScopeKey(file) === currentScopeKey,
- ),
+ files: openLocalFiles.filter((file) => isLocalFileVisibleInScope(state, currentScopeKey, file)),
scopeKey: currentScopeKey,
};
};
@@ -83,7 +104,12 @@ const getLocalFileActivationScopeKey = (state: ChatStore, file: OpenLocalFilePar
const entryScopeKey = getLocalFileEntryScopeKey(file);
const currentScopeKey = getCurrentLocalFileScopeKey(state);
- return file.allowExternalFilePreview && currentScopeKey ? currentScopeKey : entryScopeKey;
+ // External and sandbox tabs render inside the current topic's scope (the
+ // visibility filter exempts them from the cwd match), so their activation
+ // must land in that scope too — otherwise a cwd topic keeps showing its
+ // previously active tab after the open.
+ const rendersInCurrentScope = file.allowExternalFilePreview || !!file.sandboxTopicId;
+ return rendersInCurrentScope && currentScopeKey ? currentScopeKey : entryScopeKey;
};
const resolveActiveLocalFile = <T extends OpenLocalFileParams & { id?: string }>(
@@ -485,14 +511,16 @@ export class ChatPortalActionImpl {
allowExternalFilePreview,
deviceId,
filePath,
+ sandboxTopicId,
workingDirectory,
}: OpenLocalFileParams): void => {
const { activeLocalFileIdsByScope, openLocalFiles } = this.#get();
- const id = createLocalFileTabId({ deviceId, filePath, workingDirectory });
+ const id = createLocalFileTabId({ deviceId, filePath, sandboxTopicId, workingDirectory });
const exists = openLocalFiles.some((f) => getLocalFileTabId(f) === id);
const nextFile = {
...(allowExternalFilePreview === undefined ? {} : { allowExternalFilePreview }),
...(deviceId ? { deviceId } : {}),
+ ...(sandboxTopicId ? { sandboxTopicId } : {}),
filePath,
id,
workingDirectory,
diff --git a/src/store/chat/slices/portal/helpers.ts b/src/store/chat/slices/portal/helpers.ts
index c0629a2253d..b3ff3d4a76b 100644
--- a/src/store/chat/slices/portal/helpers.ts
+++ b/src/store/chat/slices/portal/helpers.ts
@@ -6,12 +6,31 @@ const LOCAL_FILE_GLOBAL_SCOPE = '__global__';
export const createLocalFileScopeKey = (workingDirectory?: string): string =>
workingDirectory || LOCAL_FILE_GLOBAL_SCOPE;
+/**
+ * Activation scope for sandbox tabs in topics without a working directory.
+ * Sandbox tabs are visible per serving topic, so their active-tab bookkeeping
+ * must be per topic too — the global scope would let unscoped topics overwrite
+ * each other's activation.
+ */
+export const createSandboxLocalFileScopeKey = (topicId: string): string => `sandbox:${topicId}`;
+
export const createLocalFileTabId = ({
deviceId,
filePath,
+ sandboxTopicId,
workingDirectory,
}: OpenLocalFileParams): string =>
- [deviceId ? `device:${deviceId}` : LOCAL_FILE_TAB_LOCAL_DEVICE, workingDirectory, filePath]
+ [
+ // Sandbox files are scoped by topic, not device — keep their tab ids from
+ // colliding with a same-path file on the local machine.
+ sandboxTopicId
+ ? createSandboxLocalFileScopeKey(sandboxTopicId)
+ : deviceId
+ ? `device:${deviceId}`
+ : LOCAL_FILE_TAB_LOCAL_DEVICE,
+ workingDirectory,
+ filePath,
+ ]
.map(encodeURIComponent)
.join('|');
diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.ts
index 31f38c58d1e..4b1c0300595 100644
--- a/src/store/chat/slices/portal/initialState.ts
+++ b/src/store/chat/slices/portal/initialState.ts
@@ -40,6 +40,13 @@ export interface OpenLocalFileParams {
allowExternalFilePreview?: boolean;
deviceId?: string;
filePath: string;
+ /**
+ * Present when the file lives in the topic's cloud sandbox instead of a local
+ * or device filesystem: content is fetched live via the sandbox
+ * `readLocalFile` tool scoped to this topic, read-only, and unavailable once
+ * the sandbox is recycled.
+ */
+ sandboxTopicId?: string;
workingDirectory: string;
}
diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.ts
index 906bc734756..03eceffe5ec 100644
--- a/src/store/chat/slices/portal/selectors.test.ts
+++ b/src/store/chat/slices/portal/selectors.test.ts
@@ -324,6 +324,27 @@ describe('chatDockSelectors', () => {
});
});
+ describe('openLocalFiles scope filter', () => {
+ // Regression: sandbox tabs open with `workingDirectory: ''`, so the cwd
+ // filter of a project-scoped topic dropped them and the portal cleared
+ // right after opening. They are scoped by their sandbox topic instead.
+ it('keeps sandbox tabs of the active topic visible in a cwd-scoped topic', () => {
+ const state = createState({
+ ...createTopicState('topic-a', { 'topic-a': '/project-a' }),
+ openLocalFiles: [
+ { filePath: '/project-a/a.ts', workingDirectory: '/project-a' },
+ { filePath: '/work/notes.md', sandboxTopicId: 'topic-a', workingDirectory: '' },
+ { filePath: '/work/other.md', sandboxTopicId: 'topic-b', workingDirectory: '' },
+ ],
+ } as Partial<ChatStoreState>);
+
+ expect(chatPortalSelectors.openLocalFiles(state).map((file) => file.filePath)).toEqual([
+ '/project-a/a.ts',
+ '/work/notes.md',
+ ]);
+ });
+ });
+
describe('currentLocalFile', () => {
it('should return undefined when activeLocalFilePath is undefined', () => {
expect(chatPortalSelectors.currentLocalFile(createState())).toBeUndefined();
diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.ts
index ab7b3143844..5088b1a962f 100644
--- a/src/store/chat/slices/portal/selectors.ts
+++ b/src/store/chat/slices/portal/selectors.ts
@@ -4,7 +4,11 @@ import { type PortalArtifact } from '@/types/artifact';
import { dbMessageSelectors } from '../message/selectors';
import { topicSelectors } from '../topic/selectors';
-import { createLocalFileScopeKey, getLocalFileTabId } from './helpers';
+import {
+ createLocalFileScopeKey,
+ createSandboxLocalFileScopeKey,
+ getLocalFileTabId,
+} from './helpers';
import { type OpenLocalFileEntry, type PortalFile, type PortalViewData } from './initialState';
import { PortalViewType } from './initialState';
@@ -159,6 +163,11 @@ const currentLocalFileScopeKey = (s: ChatStoreState): string | undefined => {
const isLocalFileInCurrentScope = (s: ChatStoreState, file: OpenLocalFileEntry): boolean => {
if (file.allowExternalFilePreview) return true;
+ // Sandbox tabs carry no client-side working directory — scope them by the
+ // topic whose sandbox serves the read; the cwd filter would drop them in
+ // project-scoped topics.
+ if (file.sandboxTopicId) return file.sandboxTopicId === s.activeTopicId;
+
const workingDirectory = currentLocalFileScopeWorkingDirectory(s);
return workingDirectory ? file.workingDirectory === workingDirectory : true;
};
@@ -169,10 +178,22 @@ const openLocalFiles = (s: ChatStoreState): OpenLocalFileEntry[] =>
const activeLocalFileId = (s: ChatStoreState): string | undefined => {
const files = openLocalFiles(s);
const scopeKey = currentLocalFileScopeKey(s);
- const scopedActiveId = scopeKey ? s.activeLocalFileIdsByScope?.[scopeKey] : s.activeLocalFileId;
-
- if (scopedActiveId && files.some((file) => getLocalFileTabId(file) === scopedActiveId)) {
- return scopedActiveId;
+ // Without a cwd scope, the legacy global id may have been overwritten by a
+ // sandbox tab activated in another unscoped topic — fall back to this
+ // topic's own sandbox-scope entry before giving up.
+ const scopedActiveIds = scopeKey
+ ? [s.activeLocalFileIdsByScope?.[scopeKey]]
+ : [
+ s.activeLocalFileId,
+ s.activeTopicId
+ ? s.activeLocalFileIdsByScope?.[createSandboxLocalFileScopeKey(s.activeTopicId)]
+ : undefined,
+ ];
+
+ for (const scopedActiveId of scopedActiveIds) {
+ if (scopedActiveId && files.some((file) => getLocalFileTabId(file) === scopedActiveId)) {
+ return scopedActiveId;
+ }
}
const active = s.activeLocalFilePath;