Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): render PDF preview from bytes via scoped IPC (no CSP change)

Shao-Wu Hu5a7c1618cc2a
diff --git a/apps/desktop/src/main/__tests__/fileReadBytes.test.ts b/apps/desktop/src/main/__tests__/fileReadBytes.test.ts
new file mode 100644
index 0000000000..4a437d5af5
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/fileReadBytes.test.ts
@@ -0,0 +1,232 @@
+/** fileReadBytes.test — core of the privileged read-file-bytes IPC.
+ * The trusted-sender gate lives in the handler and is covered by
+ * trustedAppRenderer.test; here we exercise every validation / policy /
+ * symlink / size-cap / sanitized-error path of the injectable core. */
+
+import type { Stats } from 'node:fs';
+
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ readFileBytesForPreview,
+ READ_FILE_BYTES_CAP,
+ type FileHandleLike,
+ type ReadFileBytesDeps,
+} from '../fileReadBytes';
+
+function statStub(size: number, isFile = true, ino = 1, dev = 1): Stats {
+ return { size, isFile: () => isFile, ino, dev } as unknown as Stats;
+}
+
+/** Fake FileHandle whose fstat size can differ from the readable bytes, so we
+ * can prove the read is bounded to the fstat'd size (regular-file TOCTOU).
+ * ino/dev model the opened descriptor's identity for the swap-revalidation. */
+function fakeHandle(opts: {
+ statSize: number;
+ isFile?: boolean;
+ data?: Buffer;
+ ino?: number;
+ dev?: number;
+ readSpy?: (buf: Buffer, offset: number, length: number, position: number) => void;
+}): FileHandleLike {
+ const data = opts.data ?? Buffer.alloc(opts.statSize);
+ return {
+ stat: async () => statStub(opts.statSize, opts.isFile ?? true, opts.ino ?? 1, opts.dev ?? 1),
+ read: async (buffer, offset, length, position) => {
+ opts.readSpy?.(buffer, offset, length, position);
+ const bytesRead = data.copy(buffer, offset, position, position + length);
+ return { bytesRead };
+ },
+ close: async () => undefined,
+ };
+}
+
+function deps(over: Partial<ReadFileBytesDeps> = {}): ReadFileBytesDeps {
+ return {
+ isPathAllowed: () => true,
+ realpath: async (p) => p,
+ // expected identity ino/dev=1 matches fakeHandle's default fstat identity
+ stat: async () => statStub(4, true, 1, 1),
+ open: async () => fakeHandle({ statSize: 4, data: Buffer.from([1, 2, 3, 4]) }),
+ ...over,
+ };
+}
+
+async function codeOf(promise: Promise<unknown>): Promise<string> {
+ try {
+ await promise;
+ } catch (err) {
+ return (err as { code?: string }).code ?? `NO_CODE:${String(err)}`;
+ }
+ throw new Error('expected the call to reject, but it resolved');
+}
+
+const ABS = '/Users/x/project/paper.pdf';
+
+describe('readFileBytesForPreview', () => {
+ it('returns an exact-copy Uint8Array + real size on success', async () => {
+ const res = await readFileBytesForPreview({ filePath: ABS }, deps());
+ expect(Array.from(res.bytes)).toEqual([1, 2, 3, 4]);
+ expect(res.size).toBe(4);
+ expect(res.bytes.byteOffset).toBe(0);
+ expect(res.bytes.buffer.byteLength).toBe(4);
+ });
+
+ it('rejects a null / non-object params with INVALID_PARAMS (no raw TypeError)', async () => {
+ expect(await codeOf(readFileBytesForPreview(null, deps()))).toBe('INVALID_PARAMS');
+ expect(await codeOf(readFileBytesForPreview(42, deps()))).toBe('INVALID_PARAMS');
+ });
+
+ it('rejects a non-string / relative filePath with INVALID_PARAMS', async () => {
+ expect(await codeOf(readFileBytesForPreview({ filePath: 123 }, deps()))).toBe('INVALID_PARAMS');
+ expect(await codeOf(readFileBytesForPreview({ filePath: 'rel/paper.pdf' }, deps()))).toBe(
+ 'INVALID_PARAMS',
+ );
+ });
+
+ it('rejects a blocked lexical path with PERMISSION_DENIED (before any fs access)', async () => {
+ const realpath = vi.fn(async (p: string) => p);
+ expect(
+ await codeOf(
+ readFileBytesForPreview({ filePath: ABS }, deps({ isPathAllowed: () => false, realpath })),
+ ),
+ ).toBe('PERMISSION_DENIED');
+ expect(realpath).not.toHaveBeenCalled();
+ });
+
+ it('rejects a symlink whose realpath escapes into a blocked dir (PERMISSION_DENIED, no open)', async () => {
+ const open = vi.fn(async () => fakeHandle({ statSize: 4 }));
+ // lexical /tmp/leak.pdf passes, but it resolves into /etc → must be denied.
+ const code = await codeOf(
+ readFileBytesForPreview(
+ { filePath: '/tmp/leak.pdf' },
+ deps({
+ isPathAllowed: (p) => !p.startsWith('/etc'),
+ realpath: async () => '/etc/shadow',
+ open,
+ }),
+ ),
+ );
+ expect(code).toBe('PERMISSION_DENIED');
+ expect(open).not.toHaveBeenCalled();
+ });
+
+ it('rejects when the opened descriptor identity differs from the realpath (ancestor symlink swap)', async () => {
+ // expected realpath identity ino=1; the opened fd resolves to ino=999 → an
+ // ancestor component was swapped to point elsewhere between realpath & open.
+ expect(
+ await codeOf(
+ readFileBytesForPreview(
+ { filePath: ABS },
+ deps({
+ stat: async () => statStub(4, true, 1, 1),
+ open: async () => fakeHandle({ statSize: 4, data: Buffer.from([1, 2, 3, 4]), ino: 999 }),
+ }),
+ ),
+ ),
+ ).toBe('PRECONDITION_FAILED');
+ });
+
+ it('rejects a non-regular file (FIFO/socket/device) with INVALID_PARAMS', async () => {
+ expect(
+ await codeOf(
+ readFileBytesForPreview(
+ { filePath: ABS },
+ deps({ open: async () => fakeHandle({ statSize: 0, isFile: false }) }),
+ ),
+ ),
+ ).toBe('INVALID_PARAMS');
+ });
+
+ it('rejects when the fstat size already exceeds the cap (PRECONDITION_FAILED)', async () => {
+ expect(
+ await codeOf(
+ readFileBytesForPreview(
+ { filePath: ABS },
+ deps({ open: async () => fakeHandle({ statSize: READ_FILE_BYTES_CAP + 1 }) }),
+ ),
+ ),
+ ).toBe('PRECONDITION_FAILED');
+ });
+
+ it('bounds the read to the fstat size even if the file is larger (regular-file TOCTOU)', async () => {
+ // fstat reports 4 bytes; the underlying data is 100. The read must be
+ // bounded to 4 (never buffer the extra bytes into main-process memory).
+ let maxLengthRequested = 0;
+ const handle = fakeHandle({
+ statSize: 4,
+ data: Buffer.alloc(100, 7),
+ readSpy: (_b, _o, length) => {
+ maxLengthRequested = Math.max(maxLengthRequested, length);
+ },
+ });
+ const res = await readFileBytesForPreview({ filePath: ABS, maxSize: 8 }, deps({ open: async () => handle }));
+ expect(res.size).toBe(4);
+ expect(res.bytes.byteLength).toBe(4);
+ expect(maxLengthRequested).toBeLessThanOrEqual(4);
+ });
+
+ it('handles a shrunk file (EOF before fstat size) by returning what was read', async () => {
+ // fstat says 10 but only 3 bytes are readable → return those 3.
+ const res = await readFileBytesForPreview(
+ { filePath: ABS },
+ deps({ open: async () => fakeHandle({ statSize: 10, data: Buffer.from([9, 8, 7]) }) }),
+ );
+ expect(Array.from(res.bytes)).toEqual([9, 8, 7]);
+ expect(res.size).toBe(3);
+ });
+
+ it('a NaN / non-positive maxSize falls back to the hard cap (does not drop it)', async () => {
+ expect(
+ await codeOf(
+ readFileBytesForPreview(
+ { filePath: ABS, maxSize: Number.NaN },
+ deps({ open: async () => fakeHandle({ statSize: READ_FILE_BYTES_CAP + 1 }) }),
+ ),
+ ),
+ ).toBe('PRECONDITION_FAILED');
+ const ok = await readFileBytesForPreview({ filePath: ABS, maxSize: -5 }, deps());
+ expect(ok.size).toBe(4);
+ });
+
+ it('maps realpath / open failures to a sanitized NOT_FOUND', async () => {
+ expect(
+ await codeOf(
+ readFileBytesForPreview(
+ { filePath: ABS },
+ deps({ realpath: async () => { throw new Error('ENOENT: /secret/abs/path'); } }),
+ ),
+ ),
+ ).toBe('NOT_FOUND');
+ expect(
+ await codeOf(
+ readFileBytesForPreview(
+ { filePath: ABS },
+ deps({ open: async () => { throw new Error('EACCES: /secret/abs/path'); } }),
+ ),
+ ),
+ ).toBe('NOT_FOUND');
+ });
+
+ it('maps an fstat() failure to a sanitized INTERNAL', async () => {
+ const handle: FileHandleLike = {
+ stat: async () => { throw new Error('EIO: /secret/abs/path'); },
+ read: async () => ({ bytesRead: 0 }),
+ close: async () => undefined,
+ };
+ expect(
+ await codeOf(readFileBytesForPreview({ filePath: ABS }, deps({ open: async () => handle }))),
+ ).toBe('INTERNAL');
+ });
+
+ it('maps a read() failure to a sanitized INTERNAL', async () => {
+ const handle: FileHandleLike = {
+ stat: async () => statStub(4),
+ read: async () => { throw new Error('EIO: /secret/abs/path'); },
+ close: async () => undefined,
+ };
+ expect(
+ await codeOf(readFileBytesForPreview({ filePath: ABS }, deps({ open: async () => handle }))),
+ ).toBe('INTERNAL');
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 240c0569a0..43b28d676c 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -262,6 +262,7 @@ import {
markAppContentWindow,
} from './windowFocusClassifier.js';
import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';
+import { readFileBytesForPreview } from './fileReadBytes.js';
import { initHeartbeatService } from './heartbeatService';
import { initAnalyticsSettingsService, noteAuthColdStartState } from './analyticsSettingsService';
import { WindowManualDragController } from './windowManualDrag';
@@ -4238,6 +4239,43 @@ const registerIpcHandlers = () => {
},
);
+ // Read a local file's raw bytes for in-app rendering (currently PDF preview).
+ // Same path policy + size cap as read-file-for-attachment, but returns a
+ // Uint8Array over structured clone instead of base64: pdf.js getDocument({
+ // data }) wants bytes, and skipping base64 avoids a large transient string
+ // plus a main-thread atob/charCodeAt decode loop in the renderer. No new
+ // access surface — read-file-for-attachment already exposes these same bytes
+ // (as base64) under the identical isPathAllowed policy.
+ ipcMain.handle(
+ 'read-file-bytes',
+ async (
+ event: Electron.IpcMainInvokeEvent,
+ params: { filePath: string; maxSize?: number },
+ ): Promise<{ bytes: Uint8Array; size: number }> => {
+ // Reject any caller that is not the trusted main app renderer — an
+ // auxiliary window / child frame / webview bearing the shared preload
+ // must not be able to pull raw file bytes. Mirrors the shell:open-path
+ // policy (assertTrusted + isPathAllowed) for a path-taking privileged IPC.
+ assertTrustedAppRendererEvent(event);
+ // Validation + policy + regular-file + size-cap + exact-copy live in the
+ // injectable core (fileReadBytes.ts) so they are unit-tested without
+ // Electron; failures throw a sanitized IpcError that rejects the invoke().
+ // O_NOFOLLOW on the final component: the core opens the realpath'd target,
+ // whose last segment is a real file — so a legit open succeeds, but if the
+ // final component was swapped to a symlink in the realpath→open race it
+ // fails (ELOOP) instead of following into a denied file. Falls back to 0
+ // where the platform lacks the flag (Windows), matching saveChatAttachment.
+ const noFollow =
+ typeof fs.constants.O_NOFOLLOW === 'number' ? fs.constants.O_NOFOLLOW : 0;
+ return readFileBytesForPreview(params, {
+ isPathAllowed,
+ realpath: (p) => fs.promises.realpath(p),
+ stat: (p) => fs.promises.stat(p),
+ open: (p) => fs.promises.open(p, fs.constants.O_RDONLY | noFollow),
+ });
+ },
+ );
+
// ── File header peek IPC (F-FI-8 fallback inference) ──
// Read at most `bytes` (default 8192, hard-cap 64KB) from the head of a file
// for the renderer to run magic-bytes + UTF-8 sniffing on. Independent from
diff --git a/apps/desktop/src/main/fileReadBytes.ts b/apps/desktop/src/main/fileReadBytes.ts
new file mode 100644
index 0000000000..6a3a47f566
--- /dev/null
+++ b/apps/desktop/src/main/fileReadBytes.ts
@@ -0,0 +1,149 @@
+/**
+ * fileReadBytes — sender-agnostic core of the `read-file-bytes` IPC.
+ *
+ * The IPC handler (bootstrap-electron.ts) adds the trusted-sender gate
+ * (`assertTrustedAppRendererEvent`) and injects the real fs/policy deps; this
+ * module holds the validation + bounded-read logic so it is unit-testable
+ * without Electron. Every failure throws a sanitized `IpcError` (no raw fs
+ * message or absolute-path leak) — the renderer's invoke() rejects and
+ * PdfPreview falls back to its placeholder.
+ *
+ * Hardening (each exercised by fileReadBytes.test.ts):
+ * - params must be an object (null/non-object → INVALID_PARAMS, not a raw
+ * TypeError from destructuring);
+ * - filePath must be an absolute string (INVALID_PARAMS);
+ * - the lexical path AND its realpath must both pass the injected policy — a
+ * symlink whose name passes but resolves into a blocked dir (e.g.
+ * /tmp/leak.pdf → /etc/…) is denied (PERMISSION_DENIED); we then open the
+ * resolved path so a check→open swap can't smuggle a different file;
+ * - a single descriptor is fstat'd and read (no path re-resolution between
+ * the size check and the read): non-regular files (FIFO/socket/device) are
+ * rejected (INVALID_PARAMS), and the read buffer is bounded to the fstat'd
+ * size (≤ maxSize) so a regular file that grows/gets replaced after the
+ * check can never make the read exceed the ceiling in main-process memory
+ * (PRECONDITION_FAILED when already over cap at fstat time);
+ * - realpath / open / read errors map to sanitized NOT_FOUND / INTERNAL;
+ * - success returns an exact-copy Uint8Array (no pooled-slab spillover).
+ */
+
+import type { Stats } from 'node:fs';
+import * as nodePath from 'node:path';
+
+import { throwIpcError } from './utils/ipcValidate.js';
+
+/** Hard ceiling regardless of the caller-requested maxSize. */
+export const READ_FILE_BYTES_CAP = 30 * 1024 * 1024;
+
+/** The subset of fs.promises.FileHandle this module uses (injectable for tests). */
+export interface FileHandleLike {
+ stat: () => Promise<Stats>;
+ read: (
+ buffer: Buffer,
+ offset: number,
+ length: number,
+ position: number,
+ ) => Promise<{ bytesRead: number }>;
+ close: () => Promise<void>;
+}
+
+export interface ReadFileBytesDeps {
+ isPathAllowed: (filePath: string) => boolean;
+ realpath: (filePath: string) => Promise<string>;
+ /** stat of the (symlink-free) realpath, for the expected dev/ino identity. */
+ stat: (filePath: string) => Promise<Stats>;
+ open: (filePath: string) => Promise<FileHandleLike>;
+}
+
+export async function readFileBytesForPreview(
+ params: unknown,
+ deps: ReadFileBytesDeps,
+): Promise<{ bytes: Uint8Array; size: number }> {
+ // Validate the payload shape BEFORE destructuring: a null / non-object
+ // params from a buggy or hostile renderer must land on INVALID_PARAMS, not
+ // throw a raw TypeError that leaks a stack to the renderer.
+ if (typeof params !== 'object' || params === null) {
+ throwIpcError('INVALID_PARAMS', 'params must be an object');
+ }
+ const { filePath, maxSize: rawMaxSize } = params as { filePath?: unknown; maxSize?: unknown };
+
+ // Coerce defensively: a NaN / non-finite / non-positive maxSize must fall
+ // back to the hard cap, never make Math.min return NaN (which would make the
+ // size comparisons below vacuously false and drop the cap entirely).
+ const requested = Number(rawMaxSize);
+ const maxSize =
+ Number.isFinite(requested) && requested > 0
+ ? Math.min(requested, READ_FILE_BYTES_CAP)
+ : READ_FILE_BYTES_CAP;
+
+ if (typeof filePath !== 'string' || !nodePath.isAbsolute(filePath)) {
+ throwIpcError('INVALID_PARAMS', 'filePath must be an absolute path');
+ }
+ if (!deps.isPathAllowed(filePath)) {
+ throwIpcError('PERMISSION_DENIED', 'path is not allowed');
+ }
+
+ // Resolve symlinks and re-check the policy on the REAL target: isPathAllowed
+ // is a lexical deny-list, and stat/read follow symlinks, so a symlink whose
+ // name passes but resolves into a blocked dir must be denied here. We then
+ // open the resolved path; the injected `open` is expected to use O_NOFOLLOW
+ // on the final component so a realpath→open swap of that component fails
+ // (ELOOP) instead of following into a denied file.
+ const realPath = await deps
+ .realpath(filePath)
+ .catch(() => throwIpcError('NOT_FOUND', 'file not found'));
+ if (!deps.isPathAllowed(realPath)) {
+ throwIpcError('PERMISSION_DENIED', 'path is not allowed');
+ }
+
+ // Expected identity of the resolved target, captured right after the policy
+ // check. O_NOFOLLOW (in the injected open) only guards the FINAL component; an
+ // ancestor dir swapped to a symlink between realpath and open would still be
+ // followed. Comparing the opened descriptor's dev/ino against this expected
+ // identity rejects that swap (a mismatch means open landed on a different
+ // inode than the path we policy-checked). Node has no portable openat2 /
+ // RESOLVE_NO_SYMLINKS, so this fd-identity revalidation is the mitigation;
+ // the shipped xdt-file:// protocol (localFileProtocol.ts) carries the same
+ // residual realpath→stat micro-race.
+ const expected = await deps
+ .stat(realPath)
+ .catch(() => throwIpcError('NOT_FOUND', 'file not found'));
+
+ const handle = await deps
+ .open(realPath)
+ .catch(() => throwIpcError('NOT_FOUND', 'file not found'));
+ try {
+ const st = await handle.stat().catch(() => throwIpcError('INTERNAL', 'failed to stat file'));
+ // Regular files only: a FIFO / socket / device stats as size 0 and would
+ // otherwise be read as an unbounded stream.
+ if (!st.isFile()) {
+ throwIpcError('INVALID_PARAMS', 'not a regular file');
+ }
+ // Descriptor-identity revalidation: the opened fd must be the very inode the
+ // policy-checked realpath resolved to (guards the ancestor-symlink swap).
+ if (st.dev !== expected.dev || st.ino !== expected.ino) {
+ throwIpcError('PRECONDITION_FAILED', 'file changed during read');
+ }
+ if (st.size > maxSize) {
+ throwIpcError('PRECONDITION_FAILED', 'file exceeds the preview size limit');
+ }
+ // Bound the buffer to the fstat'd size of THIS descriptor (≤ maxSize): even
+ // if the file grows or is replaced after the check, we never read more than
+ // this into main-process memory. Loop over short reads; stop early on EOF
+ // (file shrank) and return exactly what was read.
+ const buffer = Buffer.alloc(st.size);
+ let offset = 0;
+ while (offset < st.size) {
+ const { bytesRead } = await handle
+ .read(buffer, offset, st.size - offset, offset)
+ .catch(() => throwIpcError('INTERNAL', 'failed to read file'));
+ if (bytesRead === 0) break;
+ offset += bytesRead;
+ }
+ // buffer.buffer is exact-size (Buffer.alloc is unpooled); slice to the bytes
+ // actually read so a shrunk file doesn't ship trailing zero padding.
+ const bytes = new Uint8Array(buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + offset));
+ return { bytes, size: offset };
+ } finally {
+ await handle.close().catch(() => undefined);
+ }
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7f9fe487da..11e29e580d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2562,6 +2562,19 @@ contextBridge.exposeInMainWorld('electronAPI', {
truncated?: boolean;
}> => ipcRenderer.invoke('read-file-for-attachment', params),
+ /**
+ * Read a local file's raw bytes (Uint8Array) under the same path policy /
+ * size cap as readFileForAttachment, gated to the trusted app renderer. For
+ * in-app renderers that want bytes directly (PDF preview → pdf.js
+ * getDocument({ data })) without a base64 round-trip. Rejects with an
+ * IpcError (PERMISSION_DENIED / INVALID_PARAMS / NOT_FOUND /
+ * PRECONDITION_FAILED / INTERNAL) on failure — no partial/fallback payload.
+ */
+ readFileBytes: (params: {
+ filePath: string;
+ maxSize?: number;
+ }): Promise<{ bytes: Uint8Array; size: number }> => ipcRenderer.invoke('read-file-bytes', params),
+
// File header peek IPC (F-FI-8 fallback inference)
peekFileHeader: (params: {
filePath: string;
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx
index 7ac608f012..dad6eaa1c9 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx
@@ -4,7 +4,16 @@
* 资源:
* - worker 通过 ?url import,Vite 在 dev / build 都会发出可访问 URL。
* - cmaps / standard_fonts 在 vite.renderer.config.ts 的 pdfjsAssetsPlugin
- * 里挂在 /pdfjs/ 下。CJK PDF 没 cmaps 会显示成方块。
+ * 里挂在 /pdfjs/ 下(同源 `self`,CSP connect-src 已覆盖)。CJK PDF 没
+ * cmaps 会显示成方块。
+ * - PDF 字节:经 `readFileBytes` IPC 以 Uint8Array 读入(可结构化克隆,
+ * 无 base64 中转),喂给 pdf.js `getDocument({ data })`。**不走**
+ * `getDocument({ url })` 直接 fetch xdt-file://——那会要求把 xdt-file:
+ * 放进 CSP connect-src。xdt-file:// 本身受扩展名白名单 + 敏感目录黑名单
+ * 约束(见 localFileProtocol.ts),并非任意文件;但放进 connect-src 会让
+ * 整个渲染进程脚本可 fetch 这些白名单媒体的字节(超出 PDF 预览所需)。
+ * 改走 IPC 后:不进 renderer 的 fetch 面、按发送方可信校验 + 与用户附件
+ * 同一套 main 侧路径策略、硬上限 30MB;失败以 IpcError 抛出 → 占位卡。
*
* 视觉:
* - 容器灰底跟仓库其它预览容器对齐 (#f5f5f5 / #2c2c2a)。
@@ -19,7 +28,6 @@ import * as pdfjs from 'pdfjs-dist';
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
import { createLogger } from '@/lib/logger';
-import { toLocalFileUrl } from '@/lib/localPathResolver';
import { UnrenderablePlaceholder } from './UnrenderablePlaceholder';
import { joinPath } from './lib/fileMeta';
@@ -49,24 +57,32 @@ export function PdfPreview({ workdir, relPath, size, mtimeMs }: PdfPreviewProps)
useEffect(() => {
let cancelled = false;
+ let loadingTask: ReturnType<typeof pdfjs.getDocument> | null = null;
+ let pdfDoc: pdfjs.PDFDocumentProxy | null = null;
const container = containerRef.current;
if (!container) return;
container.replaceChildren();
setState({ kind: 'loading' });
const absPath = joinPath(workdir, relPath);
- const url = toLocalFileUrl(absPath);
-
- const loadingTask = pdfjs.getDocument({
- url,
- cMapUrl: '/pdfjs/cmaps/',
- cMapPacked: true,
- standardFontDataUrl: '/pdfjs/standard_fonts/',
- });
(async () => {
try {
+ // 读字节走 main 侧受策略约束的 IPC(可信发送方校验、拒敏感路径、
+ // 硬上限 30MB),以 Uint8Array 直接交给 pdf.js —— 不用 getDocument({
+ // url }) 让渲染进程 fetch xdt-file://(那需要放开 CSP connect-src)。
+ // 越权 / 超上限 / 读失败时 IPC 以 IpcError reject,由下方 catch 落
+ // 占位卡。详见文件头注释。
+ const { bytes } = await window.electronAPI.readFileBytes({ filePath: absPath });
+ if (cancelled) return;
+ loadingTask = pdfjs.getDocument({
+ data: bytes,
+ cMapUrl: '/pdfjs/cmaps/',
+ cMapPacked: true,
+ standardFontDataUrl: '/pdfjs/standard_fonts/',
+ });
const pdf = await loadingTask.promise;
+ pdfDoc = pdf;
if (cancelled) {
await pdf.destroy();
return;
@@ -103,9 +119,16 @@ export function PdfPreview({ workdir, relPath, size, mtimeMs }: PdfPreviewProps)
return () => {
cancelled = true;
- void loadingTask.destroy();
+ // destroy 两者:loadingTask 中止未完成的加载;pdfDoc 释放已解析文档的
+ // worker / 渲染资源(promise resolve 后仅 destroy loadingTask 不够,
+ // 中途导航离开会泄漏文档)。destroy 幂等,两者都调是安全的。
+ void loadingTask?.destroy();
+ void pdfDoc?.destroy();
};
- }, [workdir, relPath]);
+ // size/mtimeMs 进依赖:同一路径的文件被就地改写(agent 重生成 PDF 等)时
+ // relPath 不变但 mtimeMs/size 变,需要重新读字节 + 重渲染,否则预览会停在
+ // 旧内容直到用户切走再切回。FileBodyView 正是为此把 size/mtimeMs 传进来。
+ }, [workdir, relPath, size, mtimeMs]);
if (state.kind === 'error') {
return (
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 01e0ac7581..0ac9ea0a75 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2146,6 +2146,13 @@ interface ElectronAPI {
truncated?: boolean;
}>;
+ /** Raw-bytes sibling of readFileForAttachment (PDF preview → pdf.js data).
+ * Rejects with an IpcError on failure (no partial payload). */
+ readFileBytes: (params: {
+ filePath: string;
+ maxSize?: number;
+ }) => Promise<{ bytes: Uint8Array; size: number }>;
+
// ── File header peek IPC (F-FI-8 fallback inference) ──
/**
* Read at most `bytes` (default 8192, hard-cap 64KB) from the head of a