A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): 文件面板能直接看 Word 和 PDF,不再只给一句「不支持」
lmlihenge5f9aec6c186
diff --git a/changelog/unreleased/2026-10-28-word-pdf-preview.md b/changelog/unreleased/2026-10-28-word-pdf-preview.mdnew file mode 100644index 00000000..7f0ae7d7--- /dev/null+++ b/changelog/unreleased/2026-10-28-word-pdf-preview.md@@ -0,0 +1,68 @@+# Word and PDF files preview in the Files panel++- **Date:** 2026-10-28+- **Type:** feat+- **Scope:** `web`, `server`, `docs`+- **Breaking:** no++[中文](2026-10-28-word-pdf-preview.zh.md)++Selecting a `.docx` in the Files panel used to answer "Preview not supported for this type; download+instead" — a Word file is the one kind of document people hand an Agent most often, and the panel had+nothing to say about it. It now opens: the document's headings, paragraphs, bold and italic runs, lists+and tables, laid out as read-only text in the pane. The extraction runs on the server (a .docx is a zip+of XML, and reading it needs no office suite installed) and comes back as Markdown, so the panel renders+it through the Markdown pipeline it already trusts. A Word preview is a preview: no editor, no source+view, because what is on screen is not the file. A legacy `.doc` says to save it as `.docx`; a `.docx`+that cannot be read says so instead of rendering as garbage.++PDFs stop depending on the client. The pane used to hand the file to the browser's own PDF viewer in an+iframe, which worked on a desktop Chrome and left a blank rectangle wherever that viewer is missing or+set to download instead — a blank pane that reads exactly like a broken file. The panel now paints the+pages itself, one canvas per page as it scrolls into view, so a PDF looks the same in the desktop app, in+any browser, and on a machine with no PDF plugin at all.++## Details++- `packages/server/src/services/docx-preview.ts` (new): `docxToMarkdown` — inflates only+ `word/document.xml` (its declared size capped before inflation), then walks the body's tags into+ Markdown: headings from `w:pStyle` / `w:outlineLvl` (the outline level wins, as Word's own navigation+ pane has it), list items indented by `w:ilvl`, `**bold**` / `*italic*` runs, GFM tables whose first row+ is the header, `w:tab` / `w:br` as spaces, and the XML entities decoded. Every character Markdown would+ read as syntax is escaped, and only the tail of a block is trimmed so a nested item keeps its indent.+ The output is capped at 200,000 characters with `truncated`; a zip without the document part, or bytes+ that are not a zip at all, is a `DocxPreviewError`.+- `packages/server/src/http/routes/workspace-files.ts`: `GET <base>/preview-text?path=…` serves that+ Markdown with the read's version as `ETag`, `no-store`, `nosniff` and `X-Content-Truncated` when the+ extraction was cut. A `.doc` is 415 `doc_legacy`, any other type 415 `preview_unavailable` — this route+ serves a derived document, never the file's own bytes. Registered in both scopes, so the new-chat draft+ and a sidebar Workspace group get it too.+- `packages/server/src/app.ts`: `.mjs` joins the static content types. The web build now emits one ES+ module worker (pdf.js's), and a browser refuses a module script served as `application/octet-stream`.+- `packages/web/src/features/chat/pdf-preview.tsx` (new): `PdfPreview` fetches the bytes with the+ session's credentials, loads pdf.js lazily (its worker as its own asset, so parsing is off the main+ thread), and paints each page at the pane's width — redrawn on resize rather than stretched, at most 2×+ device pixel ratio and a 16MP canvas ceiling, with a placeholder holding each page's height until it+ renders. The loading task is what gets destroyed on unmount, not the document proxy (which has no+ `destroy` in this version).+- `packages/web/src/lib/workspace-tree.ts`: `previewKindFor` gains `doc` for `.docx` / `.doc`;+ `previewKindOf` (the read-only UI `FileBrowser`, which does no extraction fetch) names it unsupported.+- `packages/web/src/features/chat/workspace-browser.tsx`: the `doc` branch fetches `preview-text` and+ presents a read-only Markdown view, with its own message for a legacy `.doc` and for a `.docx` the+ server could not read; the `pdf` branch draws `PdfPreview` instead of an iframe. `fetchTextPreview`+ also honours the server's `X-Content-Truncated`.+- `packages/web/src/api/{endpoints,workspace-files}.ts`: `workspaceFileTextUrl` /+ `workspaceDirFileTextUrl`, and `textUrl` on `FilesApi` for both scopes (with the machine routing the+ other file URLs already carry).+- Strings: `previewDocLegacy`, `previewDocxFailed`, `pdfLoading`, `pdfFailed`.+- Docs: `packages/docs/content/files.{zh,en}.md` — the preview table gains the two types, plus what each+ keeps and drops, the read-only rule, and the legacy `.doc` answer. The context-menu note no longer+ claims PDFs, which are ordinary DOM now.+- `packages/web/package.json`: `pdfjs-dist@^6.4.299` (Apache-2.0, code-split into its own chunk; per+ `THIRD-PARTY-NOTICES.md` a bundled npm package needs no entry there).++## Compatibility++- `preview-text` is a new route; nothing existing changed shape.+- A `.docx` can no longer be mistaken for a text file: it has its own preview kind now.+- PDF previews no longer need the browser's PDF viewer, so no configuration on the client side.diff --git a/changelog/unreleased/2026-10-28-word-pdf-preview.zh.md b/changelog/unreleased/2026-10-28-word-pdf-preview.zh.mdnew file mode 100644index 00000000..389527f3--- /dev/null+++ b/changelog/unreleased/2026-10-28-word-pdf-preview.zh.md@@ -0,0 +1,57 @@+# 文件面板能直接看 Word 和 PDF 了++- **Date:** 2026-10-28+- **Type:** feat+- **Scope:** `web`, `server`, `docs`+- **Breaking:** no++[English](2026-10-28-word-pdf-preview.md)++在文件面板里点开一个 `.docx`,以前只会得到一句「该类型不支持预览,请下载查看」—— Word 恰恰是最常交给+Agent 的那类文档,面板对它却无话可说。现在能看了:文档的标题、段落、粗体斜体、列表和表格,按只读的排版+文本显示在预览里。解析在服务端做(`.docx` 就是一个装 XML 的 zip,不需要机器上装 Office),结果是一份+Markdown,交给面板本来就在用的 Markdown 渲染管线。Word 的预览只是预览:没有编辑器,也没有源码视图,+因为屏幕上显示的不是那个文件本身。旧版 `.doc` 会提示另存为 `.docx`;读不出来的 `.docx` 直接说读不出来,+而不是画成一堆乱码。++PDF 也不再依赖客户端。以前是把文件塞进 iframe 交给浏览器自带的 PDF 阅读器:桌面 Chrome 上能看,可一旦+那个阅读器不存在、或被设成「下载 PDF」,面板里就是一块空白 —— 而空白看起来和文件坏了没有区别。现在面板+自己画:每页滚到眼前时才画一张画布,长文档不会一次画完。桌面应用、任何浏览器、没装 PDF 插件的机器,+看到的都一样。++## 细节++- `packages/server/src/services/docx-preview.ts`(新增):`docxToMarkdown` —— 只解+ `word/document.xml`(解压前先按声明的长度封顶),然后把正文标签走一遍写成 Markdown:标题取自+ `w:pStyle` / `w:outlineLvl`(大纲级别优先,和 Word 自己的导航窗格一致),列表项按 `w:ilvl` 缩进,+ 粗体斜体分别写成 `**` / `*`,表格写成首行即表头的 GFM 表格,`w:tab` / `w:br` 当空格,XML 实体会解码。+ Markdown 会当成语法的字符一律转义;块只裁掉尾部空白,嵌套项的缩进才留得住。输出上限 20 万字符并置+ `truncated`;没有正文部件的 zip、或者根本不是 zip 的字节,都抛 `DocxPreviewError`。+- `packages/server/src/http/routes/workspace-files.ts`:`GET <base>/preview-text?path=…` 返回这份+ Markdown,带读到的版本作 `ETag`、`no-store`、`nosniff`,被截断时带 `X-Content-Truncated`。`.doc` 回+ 415 `doc_legacy`,其他类型回 415 `preview_unavailable` —— 这条路由给的是「派生出来的文档」,不是文件+ 本身的字节。会话与目录两种寻址都注册了,所以新建对话页选的文件夹、侧栏的工作区组也能用。+- `packages/server/src/app.ts`:静态资源表补上 `.mjs`。前端产物里多了一个 ES module worker(pdf.js 的),+ 而以 `application/octet-stream` 提供的模块脚本浏览器会拒绝执行。+- `packages/web/src/features/chat/pdf-preview.tsx`(新增):`PdfPreview` 带着会话凭据取字节,按需加载+ pdf.js(worker 单独成资源,解析不占主线程),按面板宽度逐页画到画布上 —— 宽度变了重画而不是拉伸,最多+ 2 倍像素密度、单页画布上限 16MP,未画的页先用占位撑住高度。卸载时销毁的是 loading task,不是文档对象+ (这个版本的文档对象没有 `destroy`,之前那一下在切文件时抛了 TypeError)。+- `packages/web/src/lib/workspace-tree.ts`:`previewKindFor` 给 `.docx` / `.doc` 加了 `doc` 类;+ `previewKindOf`(只读的 UI `FileBrowser`,不做解析请求)把它当「不支持」。+- `packages/web/src/features/chat/workspace-browser.tsx`:`doc` 分支去取 `preview-text` 并以只读+ Markdown 显示,旧版 `.doc` 和解析失败的 `.docx` 各有自己的提示;`pdf` 分支改成画 `PdfPreview`,不再是+ iframe。`fetchTextPreview` 也会认服务端的 `X-Content-Truncated`。+- `packages/web/src/api/{endpoints,workspace-files}.ts`:新增 `workspaceFileTextUrl` /+ `workspaceDirFileTextUrl`,`FilesApi` 两种 scope 都多一个 `textUrl`(沿用其他文件 URL 已有的机器路由)。+- 文案:`previewDocLegacy`、`previewDocxFailed`、`pdfLoading`、`pdfFailed`。+- 文档:`packages/docs/content/files.{zh,en}.md` —— 预览表格补上这两类,说明各自保留什么、丢掉什么、+ 为什么只读,以及旧版 `.doc` 的答复;右键菜单那条不再把 PDF 算进「弹不出来」的范围(它现在就是普通 DOM)。+- `packages/web/package.json`:新增 `pdfjs-dist@^6.4.299`(Apache-2.0,单独分包;按+ `THIRD-PARTY-NOTICES.md` 的规矩,打进包里的 npm 依赖不必在那里另立条目)。++## 兼容++- `preview-text` 是新路由,原有接口的形状都没有变。+- `.docx` 不会再被当成文本文件去看:它有了自己的预览类型。+- PDF 预览不再需要浏览器自带的阅读器,客户端不需要任何设置。diff --git a/packages/docs/content/files.en.md b/packages/docs/content/files.en.mdindex 519c3c22..5bb1c438 100644--- a/packages/docs/content/files.en.md+++ b/packages/docs/content/files.en.md@@ -70,7 +70,8 @@ Select a file in the tree to open it in the preview. How a file is shown depends| Markdown and HTML | Rendered, with a **Preview / Source** toggle || Text | With syntax highlighting and line numbers || Images | Inline. Select the image to zoom. |-| PDF | Embedded |+| PDF | Painted page by page in the panel; scroll to move through it |+| Word (`.docx`) | The document's headings, paragraphs, lists and tables, laid out as read-only text || Anything else | Offered as a download. See [Download a file](#download-a-file). |A file whose extension says nothing about its type, such as a `Makefile` or a `LICENSE`, is read as text when its bytes look like text.@@ -84,6 +85,10 @@ An HTML file can also be opened in a new browser tab: in the preview, select **OA text preview reads up to 1MB. A larger file is shown truncated, with the message "File too large; preview truncated, download for the full file", and cannot be edited here. **Download** is in the preview header.+PDFs are drawn by the app itself — each page painted onto a canvas as you scroll — so the preview does not depend on the client's own PDF viewer and looks the same everywhere. Long documents paint lazily as pages come into view.++A Word preview shows the document's body: headings, paragraphs, bold and italic runs, lists and tables are kept, while images and comments are not. It is read-only: there is no editor and no source view, because what is on screen is not the file. The body is capped at 200,000 characters — download for more. A legacy `.doc` is a binary format and is answered with a note to save it as `.docx`; a `.docx` the server cannot read says so and offers the download.+Three buttons float over the top right of the file view: **Copy code**, **Wrap** and **Edit**. **Wrap** soft-wraps long lines and is on by default. The source view and the editor share the one remembered choice.## Edit a text file@@ -120,7 +125,7 @@ A save that would land on a changed file is refused before anything is written.Right-click a tree row, the blank space under the rows, or the file view to open the context menu. On a touch screen, long-press. On a keyboard, press Shift+F10 or the menu key.> [!NOTE]-> The context menu does not open inside an HTML or PDF preview, or inside the editor, where the browser's own menu is how text is pasted.+> The context menu does not open inside an HTML preview or inside the editor, where the browser's own menu is how text is pasted.| Menu item | What it does | Available for || --- | --- | --- |diff --git a/packages/docs/content/files.zh.md b/packages/docs/content/files.zh.mdindex 3ef9203a..666604e6 100644--- a/packages/docs/content/files.zh.md+++ b/packages/docs/content/files.zh.md@@ -70,7 +70,8 @@ description: 浏览、预览、编辑和管理对话 Workspace 里的文件。| Markdown 和 HTML | 渲染后显示,可用**预览 / 源码**切换 || 文本 | 语法高亮,带行号 || 图片 | 直接显示,点击可放大 |-| PDF | 内嵌显示 |+| PDF | 在面板里逐页画出,可滚动翻页 |+| Word(`.docx`) | 按文档的标题、段落、列表和表格显示成只读的排版文本 || 其他类型 | 提供下载,见[下载文件](#下载文件) |扩展名看不出类型的文件(例如 `Makefile`、`LICENSE`),如果内容看起来是文本,就按文本处理。@@ -84,6 +85,10 @@ HTML 文件还可以在浏览器新标签页中打开:在预览中选择**新文本预览最多读取 1MB。更大的文件会截断显示,提示「内容过大,预览已截断,请下载查看完整文件」,并且不能在这里编辑。**下载**按钮在预览顶栏。+PDF 由应用自己绘制(逐页画到画布上),不依赖浏览器自带的 PDF 阅读器:在哪台设备、哪个浏览器上看都一样能看。页面随滚动逐页出现,长文档不会一次全部画完。++Word 预览读的是文档正文:标题、段落、粗体斜体、列表和表格都会保留,图片和批注不显示;正文最多取 20 万字符,更长的部分需要下载。它只读,不能在这里编辑,也不提供源码视图。旧版 `.doc` 是二进制格式,面板会提示另存为 `.docx`;修不好的 `.docx` 会提示下载查看。+文件视图右上角浮着三个按钮:**复制代码**、**自动换行**和**编辑**。**自动换行**让过长的行折行显示,默认开启;源码视图和编辑器共用这一个设置,并会记住你的选择。## 编辑文本文件@@ -120,7 +125,7 @@ Agent 也在写同一个 Workspace,所以你编辑的文件可能在此期间在目录树的某一行、行下方的空白处或文件视图上点击右键,即可打开右键菜单。触屏设备上长按,键盘上按 Shift+F10 或菜单键。> [!NOTE]-> HTML 或 PDF 预览内部以及编辑器里不会弹出这个菜单,在编辑器里要靠浏览器自带的右键菜单粘贴文本。+> HTML 预览内部以及编辑器里不会弹出这个菜单,在编辑器里要靠浏览器自带的右键菜单粘贴文本。| 菜单项 | 作用 | 适用于 || --- | --- | --- |diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 67fe79ed..db3dbe12 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -515,6 +515,10 @@ export function createApp(boot: ServerBoot): Hono<AppEnv> {const CONTENT_TYPES: Record<string, string> = {".html": "text/html; charset=utf-8",".js": "text/javascript; charset=utf-8",+ // The build emits one ES module worker besides the .js bundles (pdf.js's), and a browser+ // refuses a module script served as anything but a JavaScript type — the fallback below+ // would answer application/octet-stream and the worker would never start.+ ".mjs": "text/javascript; charset=utf-8",".css": "text/css; charset=utf-8",".json": "application/json",".svg": "image/svg+xml",diff --git a/packages/server/src/http/routes/workspace-files.ts b/packages/server/src/http/routes/workspace-files.tsindex d1594261..619a8efd 100644--- a/packages/server/src/http/routes/workspace-files.ts+++ b/packages/server/src/http/routes/workspace-files.ts@@ -25,6 +25,7 @@ import type { AppEnv } from "../../auth/middleware.js";import type { Access } from "../../mechanisms/projects.js";import type { FileReveal, WorkspaceFiles } from "../../mechanisms/workspace.js";import { MAX_UPLOAD_BYTES } from "../../services/workspace-files-service.js";+import { DocxPreviewError, docxToMarkdown } from "../../services/docx-preview.js";import { assertWorkspaceAllowed } from "../../services/workspace-guard.js";import { HttpError } from "../errors.js";import {@@ -117,6 +118,54 @@ export function registerWorkspaceFileRoutes(});});+ /**+ * A file's text, extracted server-side, for the types a browser cannot show by itself. Today+ * that is Word: a .docx is a zip of XML, and returning its body as Markdown lets the Files+ * panel render it with the same safe Markdown pipeline it already uses for .md — one preview+ * that works in every client, instead of one that needs an office suite installed.+ *+ * Deliberately NOT `/content`: that route serves the file's own bytes with its own type, and+ * this one serves a derived document. Only a .docx has an extraction; anything else is a 415,+ * and legacy .doc gets its own code so the panel can say "save it as .docx" rather than+ * "preview not supported".+ */+ app.get(at("/preview-text"), async (c) => {+ const workspace = await resolve(c);+ const rel = c.req.query("path") ?? "";+ const { data, fileName, version } = await deps.workspaceFiles.read(workspace, rel);+ const ext = path.extname(fileName).toLowerCase();+ if (ext === ".doc") {+ throw new HttpError(+ 415,+ "doc_legacy",+ "Legacy .doc files cannot be previewed; save the file as .docx or download it.",+ );+ }+ if (ext !== ".docx") {+ throw new HttpError(415, "preview_unavailable", "No text preview for this file type.");+ }+ let preview;+ try {+ preview = docxToMarkdown(data);+ } catch (error) {+ if (error instanceof DocxPreviewError)+ throw new HttpError(415, "docx_unreadable", error.message);+ throw error;+ }+ return new Response(preview.markdown, {+ status: 200,+ headers: {+ "Content-Type": "text/markdown; charset=utf-8",+ "X-Content-Type-Options": "nosniff",+ "Cache-Control": "no-store",+ // Same version marker `/content` returns: the panel treats a re-read as a new painting+ // of the same file, never as an editable one (a .docx is read-only here).+ ETag: version,+ ...(preview.truncated ? { "X-Content-Truncated": "1" } : {}),+ },+ });+ });+/*** Writes one file whole. The editor's write precondition rides in `ifVersion` (see* FilesWriteRequest); an upload reads no version and so writes unconditionally. The versiondiff --git a/packages/server/src/services/docx-preview.ts b/packages/server/src/services/docx-preview.tsnew file mode 100644index 00000000..ad6f1ed5--- /dev/null+++ b/packages/server/src/services/docx-preview.ts@@ -0,0 +1,319 @@+/**+ * Word (.docx) → Markdown, for the Files panel's read-only preview.+ *+ * A .docx is a zip of XML parts, and the one this reads is `word/document.xml`: the body text,+ * in run order, with the paragraph and table structure the pane should show. No renderer is+ * involved and nothing is written anywhere — a preview that needs LibreOffice installed, or a+ * headless converter, would be a preview that is missing on most machines.+ *+ * What comes back is **Markdown**, not plain text, because the pane already renders Markdown with+ * its own safe pipeline: headings, list items, bold/italic runs and tables then show as the+ * document shows them, while the document's own markup stays inert text. Every literal character+ * that Markdown would otherwise read as syntax is escaped, so a line beginning with "#" in the+ * document is a line beginning with "#", not a heading.+ *+ * Limits are part of the contract, since the input is an Agent-written file: only the one part is+ * inflated, its declared size is capped before it is (a zip entry states its size, and fflate+ * allocates exactly that), the output is capped by characters, and a document that is not a .docx+ * is refused rather than guessed at.+ */+import { strFromU8, unzipSync } from "fflate";++/** The only part read: the document body. Styles, numbering, media and footnotes are ignored. */+const DOCUMENT_PART = "word/document.xml";++/** Declared uncompressed size of that part; a document body larger than this is not previewed. */+const MAX_DOCUMENT_XML_BYTES = 16 * 1024 * 1024;++/** Characters of Markdown a preview returns before it is cut short. */+export const DOCX_PREVIEW_MAX_CHARS = 200_000;++/** Thrown for anything that is not a previewable .docx: the route turns it into a 415. */+export class DocxPreviewError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "DocxPreviewError";+ }+}++export interface DocxPreview {+ markdown: string;+ truncated: boolean;+}++/** The document body as Markdown, or a {@link DocxPreviewError} naming what was wrong. */+export function docxToMarkdown(+ archive: Uint8Array,+ maxChars = DOCX_PREVIEW_MAX_CHARS,+): DocxPreview {+ let xml: Uint8Array | undefined;+ try {+ const parts = unzipSync(archive, {+ filter: ({ name, originalSize }) => {+ if (name !== DOCUMENT_PART) return false;+ if (originalSize > MAX_DOCUMENT_XML_BYTES) {+ throw new DocxPreviewError("The document body is too large to preview.");+ }+ return true;+ },+ });+ xml = parts[DOCUMENT_PART];+ } catch (error) {+ if (error instanceof DocxPreviewError) throw error;+ // Anything fflate throws here means the bytes are not a zip at all (a renamed .doc, a+ // truncated download), which is exactly the "cannot preview this" answer.+ throw new DocxPreviewError("Not a readable .docx archive.");+ }+ if (xml === undefined) throw new DocxPreviewError("Not a Word document.");+ return { ...markdownFromDocumentXml(strFromU8(xml), maxChars) };+}++/** Escape the characters Markdown would read as syntax, so document text stays text. */+function escapeInline(text: string): string {+ return text.replace(/[\\`*_[\]<>|]/g, (char) => `\\${char}`);+}++/** A line that would open a block construct (heading, bullet, quote, numbered item) is defused. */+function escapeBlockStart(text: string): string {+ if (/^[#\-+>]/.test(text) || /^\d+[.)]/.test(text)) return `\\${text}`;+ return text;+}++/** Heading level a paragraph's own properties declare, or 0 for a normal paragraph. */+function headingLevel(style: string | null, outline: number | null): number {+ // `w:outlineLvl` is the document's own structure and wins over the style name: a heading+ // restyled in Word keeps the level the navigation pane shows.+ if (outline !== null) return Math.min(outline + 1, 6);+ if (style === null) return 0;+ if (/^title$/i.test(style)) return 1;+ const match = /^(?:heading|标题)\s*([1-9])$/i.exec(style) ?? /^([1-9])$/.exec(style);+ return match === null ? 0 : Math.min(Number(match[1]), 6);+}++/** A table as a GFM table: the first row becomes the header, as Word's own tables read. */+function tableBlock(rows: string[][]): string {+ const cells = rows.map((row) => row.map((cell) => cell.replace(/\s+/g, " ").trim()));+ const columns = Math.max(...cells.map((row) => row.length));+ const padded = cells.map((row) => [...row, ...Array<string>(columns - row.length).fill("")]);+ const line = (row: string[]): string => `| ${row.join(" | ")} |`;+ if (padded.length === 0) return "";+ if (padded.length === 1) return line(padded[0]!);+ const [head, ...rest] = padded;+ return [line(head!), `| ${head!.map(() => "---").join(" | ")} |`, ...rest.map(line)].join("\n");+}++interface Paragraph {+ parts: string[];+ style: string | null;+ outline: number | null;+ /** `w:ilvl` of a list item: 0 for the first level, higher for a nested one. */+ listLevel: number | null;+}++interface Run {+ bold: boolean;+ italic: boolean;+ text: string;+}++const TAG = /<(\/?)([A-Za-z_][\w.:-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>/g;++/** XML text as Word wrote it: the five predefined entities and numeric references. */+function decodeXml(text: string): string {+ return text.replace(/&(#x[0-9a-f]+|#\d+|lt|gt|amp|quot|apos);/gi, (whole, entity: string) => {+ switch (entity.toLowerCase()) {+ case "lt":+ return "<";+ case "gt":+ return ">";+ case "amp":+ return "&";+ case "quot":+ return '"';+ case "apos":+ return "'";+ default: {+ if (entity[0] !== "#") return whole;+ const hex = entity[1] === "x" || entity[1] === "X";+ const code = Number.parseInt(entity.slice(hex ? 2 : 1), hex ? 16 : 10);+ if (!Number.isFinite(code) || code < 0 || code > 0x10ffff) return whole;+ try {+ return String.fromCodePoint(code);+ } catch {+ return whole;+ }+ }+ }+ });+}++/** Attribute value of a tag's raw attribute text, e.g. `w:val` out of ` w:val="Heading1"`. */+function attr(raw: string, name: string): string | null {+ const match = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`).exec(raw);+ return match === null ? null : (match[1] ?? match[2] ?? null);+}++/** Walks `word/document.xml` and lays its paragraphs and tables out as Markdown blocks. */+function markdownFromDocumentXml(+ xml: string,+ maxChars: number,+): { markdown: string; truncated: boolean } {+ const blocks: string[] = [];+ let used = 0;+ let truncated = false;++ const push = (block: string): boolean => {+ if (block.trim() === "") return true;+ // Only the tail is trimmed: a nested list item's leading indent is its level.+ const text = block.replace(/\s+$/, "");+ if (used + text.length > maxChars) {+ blocks.push(text.slice(0, Math.max(maxChars - used, 0)));+ used = maxChars;+ truncated = true;+ return false;+ }+ blocks.push(text);+ used += text.length + 2;+ return true;+ };++ let paragraph: Paragraph | null = null;+ let run: Run | null = null;+ let inText = false;+ let table: string[][] | null = null;+ let row: string[] | null = null;+ let cell: string[] | null = null;++ /** Emits the finished paragraph: a heading, a list item, a table cell, or plain text. */+ const endParagraph = (): void => {+ if (paragraph === null) return;+ const text = paragraph.parts.join("").trim();+ const current = paragraph;+ paragraph = null;+ if (text === "") return;+ if (cell !== null) {+ cell.push(text);+ return;+ }+ // Each run already arrived escaped (see `endRun`); only a leading marker that would open a+ // block construct is defused here. Escaping again would put backslashes inside the+ // `**bold**` markers this same function wrote.+ const level = headingLevel(current.style, current.outline);+ if (level > 0) {+ push(`${"#".repeat(level)} ${text}`);+ return;+ }+ if (current.listLevel !== null) {+ push(`${" ".repeat(Math.min(current.listLevel, 4))}- ${text}`);+ return;+ }+ push(escapeBlockStart(text));+ };++ const endRun = (): void => {+ if (run === null) return;+ const text = decodeXml(run.text);+ const { bold, italic } = run;+ run = null;+ if (text === "" || paragraph === null) return;+ const escaped = escapeInline(text);+ if (bold && italic) paragraph.parts.push(`***${escaped}***`);+ else if (bold) paragraph.parts.push(`**${escaped}**`);+ else if (italic) paragraph.parts.push(`*${escaped}*`);+ else paragraph.parts.push(escaped);+ };++ TAG.lastIndex = 0;+ let cursor = 0;+ for (;;) {+ const match = TAG.exec(xml);+ if (match === null) break;+ if (inText && paragraph !== null && run !== null) {+ run.text += xml.slice(cursor, match.index);+ }+ cursor = TAG.lastIndex;+ const names = match as unknown as [string, string, string, string, string];+ const name = names[2];+ const attributes = names[3];+ const closing = names[1] === "/";+ const empty = names[4] === "/";+ switch (name) {+ case "w:p":+ if (closing) endParagraph();+ else if (!empty) paragraph = { parts: [], style: null, outline: null, listLevel: null };+ break;+ case "w:pStyle":+ if (paragraph !== null) paragraph.style = attr(attributes, "w:val");+ break;+ case "w:outlineLvl": {+ const value = attr(attributes, "w:val");+ if (paragraph !== null && value !== null) paragraph.outline = Number(value);+ break;+ }+ case "w:numPr":+ // Opening only: `</w:numPr>` follows the `w:ilvl` inside it and would reset the level.+ if (!closing && paragraph !== null) paragraph.listLevel = 0;+ break;+ case "w:ilvl": {+ const value = attr(attributes, "w:val");+ if (paragraph !== null && paragraph.listLevel !== null && value !== null) {+ const level = Number(value);+ if (Number.isFinite(level)) paragraph.listLevel = Math.max(level, 0);+ }+ break;+ }+ case "w:r":+ if (closing) endRun();+ else if (!empty) run = { bold: false, italic: false, text: "" };+ break;+ case "w:b":+ case "w:i": {+ if (run === null) break;+ const value = attr(attributes, "w:val");+ const on = value === null || value === "1" || value === "true";+ if (name === "w:b") run.bold = on;+ else run.italic = on;+ break;+ }+ case "w:t":+ if (closing) inText = false;+ else inText = !empty;+ break;+ case "w:tab":+ case "w:br":+ case "w:cr":+ if (run !== null) run.text += " ";+ break;+ case "w:tbl":+ if (closing) {+ if (table !== null) push(tableBlock(table));+ table = null;+ } else if (!empty) {+ endParagraph();+ table = [];+ }+ break;+ case "w:tr":+ if (closing) {+ if (table !== null && row !== null) table.push(row);+ row = null;+ } else if (!empty) row = [];+ break;+ case "w:tc":+ if (closing) {+ if (row !== null && cell !== null) row.push(cell.join(" "));+ cell = null;+ } else if (!empty) cell = [];+ break;+ default:+ break;+ }+ if (truncated) break;+ }+ // A document ending inside a paragraph (or a table) still has that last block to show.+ if (!truncated) {+ endParagraph();+ if (table !== null) push(tableBlock(table));+ }+ return { markdown: blocks.join("\n\n"), truncated };+}diff --git a/packages/server/test/docx-preview.test.ts b/packages/server/test/docx-preview.test.tsnew file mode 100644index 00000000..d8029434--- /dev/null+++ b/packages/server/test/docx-preview.test.ts@@ -0,0 +1,194 @@+/**+ * Word previews: the .docx → Markdown extraction and the route that serves it.+ *+ * The extraction:+ * - reads `word/document.xml` out of the zip and lays its paragraphs out as Markdown: headings+ * from the paragraph's own style or outline level, list items indented by their level,+ * bold/italic runs, tables as GFM tables, and the XML entities and line breaks Word writes;+ * - escapes what Markdown would otherwise read as syntax, so document text stays text, while the+ * markers it writes itself are not escaped twice;+ * - refuses anything that is not a .docx (a zip without the document part, or not a zip at+ * all), and cuts the output at its character cap with `truncated`.+ *+ * The route (`files/preview-text`, in both scopes):+ * - answers a .docx with Markdown, an ETag of the read version, `no-store`, and+ * `X-Content-Truncated` when the extraction was cut;+ * - answers a legacy .doc with 415 `doc_legacy` and any other type with 415+ * `preview_unavailable` — this route serves an extraction, never the file;+ * - answers an outsider with 404, and never touches a Workspace it was not given.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { strToU8, zipSync } from "fflate";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import {+ DOCX_PREVIEW_MAX_CHARS,+ DocxPreviewError,+ docxToMarkdown,+} from "../src/services/docx-preview.js";+import type { ProjectCreateResponse, SessionCreateResponse } from "../src/api/types.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++/** A .docx as Word writes one: a zip whose `word/document.xml` is the body. */+function docx(body: string, extra: Record<string, Uint8Array> = {}): Uint8Array {+ return zipSync({+ "[Content_Types].xml": strToU8("<Types/>"),+ "word/document.xml": strToU8(+ `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${body}</w:body></w:document>`,+ ),+ ...extra,+ });+}++/** A run of plain text. */+const run = (text: string): string => `<w:r><w:t xml:space="preserve">${text}</w:t></w:r>`;+/** A paragraph with the given inner XML. */+const para = (inner: string, props = ""): string =>+ `<w:p>${props === "" ? "" : `<w:pPr>${props}</w:pPr>`}${inner}</w:p>`;++describe("docxToMarkdown", () => {+ it("lays paragraphs out as Markdown: headings by style and outline level, bold and italic runs", () => {+ const body = [+ para(run("标题一"), '<w:pStyle w:val="Heading1"/>'),+ para(+ "<w:r><w:rPr><w:b/></w:rPr><w:t>粗体</w:t></w:r><w:r><w:t>与</w:t></w:r><w:r><w:rPr><w:i/></w:rPr><w:t>斜体</w:t></w:r>",+ ),+ para(run("二级标题"), '<w:outlineLvl w:val="1"/>'),+ para(run("普通段落")),+ ].join("");++ expect(docxToMarkdown(docx(body)).markdown).toBe(+ ["# 标题一", "**粗体**与*斜体*", "## 二级标题", "普通段落"].join("\n\n"),+ );+ });++ it("indents list items by their own level and keeps tables as GFM tables", () => {+ const body = [+ para(run("第一项"), '<w:numPr><w:ilvl w:val="0"/></w:numPr>'),+ para(run("第二层"), '<w:numPr><w:ilvl w:val="1"/></w:numPr>'),+ `<w:tbl>${[+ "<w:tr><w:tc><w:p><w:r><w:t>指标</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>数据</w:t></w:r></w:p></w:tc></w:tr>",+ "<w:tr><w:tc><w:p><w:r><w:t>出货量</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>1477 万台</w:t></w:r></w:p></w:tc></w:tr>",+ ].join("")}</w:tbl>`,+ ].join("");++ expect(docxToMarkdown(docx(body)).markdown).toBe(+ ["- 第一项", " - 第二层", "| 指标 | 数据 |\n| --- | --- |\n| 出货量 | 1477 万台 |"].join(+ "\n\n",+ ),+ );+ });++ it("decodes entities and line breaks, and escapes text that would read as Markdown", () => {+ const body = [+ para(run("A & B <tag> 中")),+ para(run("# 不是标题")),+ para("<w:r><w:t>第一行</w:t><w:br/><w:t>第二行</w:t></w:r>"),+ para(run("a*b_c[d]")),+ ].join("");+ const markdown = docxToMarkdown(docx(body)).markdown;+ expect(markdown).toContain("A & B \\<tag\\> 中");+ // The leading "#" would have made a heading; it is defused, not promoted.+ expect(markdown).toContain("\\# 不是标题");+ expect(markdown).toContain("第一行 第二行");+ expect(markdown).toContain("a\\*b\\_c\\[d\\]");+ });++ it("reads only the document part — a large sibling entry is never inflated", () => {+ const body = para(run("正文"));+ const archive = docx(body, { "word/media/image1.png": new Uint8Array(4 * 1024 * 1024) });+ expect(docxToMarkdown(archive).markdown).toBe("正文");+ });++ it("cuts the output at its character cap and says so", () => {+ const body = para(run("长".repeat(500)));+ const out = docxToMarkdown(docx(body), 100);+ expect(out.truncated).toBe(true);+ expect(out.markdown.length).toBe(100);+ expect(docxToMarkdown(docx(body)).truncated).toBe(false);+ expect(DOCX_PREVIEW_MAX_CHARS).toBe(200_000);+ });++ it("refuses what it cannot read: a zip without the document part, and bytes that are not a zip", () => {+ const empty = zipSync({ "word/styles.xml": strToU8("<styles/>") });+ expect(() => docxToMarkdown(empty)).toThrow(DocxPreviewError);+ expect(() => docxToMarkdown(strToU8("not a zip at all"))).toThrow(DocxPreviewError);+ });+});++/** The route: one owner, one outsider, one Session (and so one Workspace) per case. */+let t: TestApp;+let owner: ReturnType<typeof apiClient>;+let outsider: ReturnType<typeof apiClient>;+let projectId: string;++beforeAll(async () => {+ t = await createTestApp();+ owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);+ outsider = apiClient(t.app, (await provisionUser(t.app, "outsider")).cookie);+ const created = (await (+ await owner.post("/api/projects", { projectId: "owner-docx", name: "project" })+ ).json()) as ProjectCreateResponse;+ projectId = created.project.projectId;+ await owner.put(`/api/projects/${projectId}/models`, {+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],+ });+});+afterAll(async () => {+ await t.cleanup();+});++async function sessionWithWords(): Promise<{ sessionId: string; workspace: string }> {+ const sess = (await (+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})+ ).json()) as SessionCreateResponse;+ const workspace = sess.session.workspace;+ await fs.writeFile(path.join(workspace, "doc.docx"), Buffer.from(docx(para(run("你好,Word")))));+ await fs.writeFile(path.join(workspace, "old.doc"), Buffer.from("%D0CF11E0 binary", "latin1"));+ await fs.writeFile(path.join(workspace, "notes.md"), "# md");+ return { sessionId: sess.session.sessionId, workspace };+}++describe("files/preview-text route", () => {+ it("answers a .docx with Markdown and the read's version; no cache, no sniffing", async () => {+ const { sessionId } = await sessionWithWords();+ const res = await owner.get(`/api/sessions/${sessionId}/files/preview-text?path=doc.docx`);+ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toContain("text/markdown");+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");+ expect(res.headers.get("cache-control")).toBe("no-store");+ expect(res.headers.get("etag")).toMatch(/^W\/"\d+-\d+"$/);+ expect(res.headers.get("x-content-truncated")).toBeNull();+ expect(await res.text()).toBe("你好,Word");+ });++ it("names the two refusals apart: a legacy .doc says so, anything else is not extracted", async () => {+ const { sessionId } = await sessionWithWords();+ const legacy = await owner.get(`/api/sessions/${sessionId}/files/preview-text?path=old.doc`);+ expect(legacy.status).toBe(415);+ expect(await legacy.json()).toEqual({+ error: { code: "doc_legacy", message: expect.any(String) },+ });++ const other = await owner.get(`/api/sessions/${sessionId}/files/preview-text?path=notes.md`);+ expect(other.status).toBe(415);+ expect(await other.json()).toEqual({+ error: { code: "preview_unavailable", message: expect.any(String) },+ });+ });++ it("serves the directory scope too, and answers an outsider with 404", async () => {+ const { sessionId, workspace } = await sessionWithWords();+ const byDir = await owner.get(+ `/api/projects/${projectId}/workspace-files/preview-text?workspace=${encodeURIComponent(workspace)}&path=doc.docx`,+ );+ expect(byDir.status).toBe(200);+ expect(await byDir.text()).toBe("你好,Word");++ const nope = await outsider.get(`/api/sessions/${sessionId}/files/preview-text?path=doc.docx`);+ expect(nope.status).toBe(404);+ });+});diff --git a/packages/web/package.json b/packages/web/package.jsonindex 75624232..bade256f 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -21,6 +21,7 @@"@xterm/addon-web-links": "^0.11.0","@xterm/xterm": "^5.5.0","copy-to-clipboard": "^4.0.2",+ "pdfjs-dist": "^6.4.299","react": "^19.1.0","react-dom": "^19.1.0","react-markdown": "^10.1.0",@@ -29,8 +30,8 @@"zustand": "^5.0.15"},"devDependencies": {- "@playwright/test": "^1.61.1","@adelie/server": "workspace:*",+ "@playwright/test": "^1.61.1","@tailwindcss/vite": "^4.1.0","@types/node": "^24.0.0","@types/react": "^19.1.0",diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 0b5f3a91..2003624d 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -1595,6 +1595,17 @@ export const workspaceFileUrl = (sessionId: string, path: string, download = falmachineForSession(sessionId),);+/**+ * A .docx's text as Markdown, extracted by the server (see the route's own comment): the Files+ * panel renders it through its Markdown pipeline, so a Word document previews in any client —+ * no office suite, no download.+ */+export const workspaceFileTextUrl = (sessionId: string, path: string): string =>+ apiUrl(+ `/api/sessions/${sessionId}/files/preview-text?path=${encodeURIComponent(path)}`,+ machineForSession(sessionId),+ );+/*** "Open in a new tab" for a Workspace html file: an App-origin link that mints a signed* token and 302s to the separate preview origin, where the page gets a real origin with@@ -1719,6 +1730,13 @@ export const workspaceDirPreviewUrl = (dir: WorkspaceDir, path: string): stringdir.machineId,);+/** A .docx's text as Markdown for a directory's Workspace, as {@link workspaceFileTextUrl}. */+export const workspaceDirFileTextUrl = (dir: WorkspaceDir, path: string): string =>+ apiUrl(+ `${workspaceDirBase(dir)}/preview-text?workspace=${encodeURIComponent(dir.workspace)}&path=${encodeURIComponent(path)}`,+ dir.machineId,+ );+/** As {@link uploadWorkspaceFile}: resolves to the version written, or null when the server does not say. */export const writeWorkspaceDirFile = (dir: WorkspaceDir,diff --git a/packages/web/src/api/workspace-files.ts b/packages/web/src/api/workspace-files.tsindex fb82eb09..745755cf 100644--- a/packages/web/src/api/workspace-files.ts+++ b/packages/web/src/api/workspace-files.ts@@ -40,6 +40,8 @@ export interface FilesApi {list(path: string): Promise<WorkspaceFilesResponse>;/** A URL an <img>, an <a> or a fetch can use: inline, or as a download. */fileUrl(path: string, download?: boolean): string;+ /** The server's text extraction of a file (Word): Markdown for a .docx, nothing to fetch otherwise. */+ textUrl(path: string): string;/** "Open in a new tab" for an HTML file. */previewUrl(path: string): string;/** Whether the separate preview origin can serve this scope at all (a Session only). */@@ -60,6 +62,7 @@ export function filesApi(scope: FilesScope): FilesApi {return {list: (path) => api.listWorkspaceFiles(id, path),fileUrl: (path, download) => api.workspaceFileUrl(id, path, download),+ textUrl: (path) => api.workspaceFileTextUrl(id, path),previewUrl: (path) => api.workspaceFilePreviewUrl(id, path),isolatablePreviews: true,write: (path, data, ifVersion) => api.uploadWorkspaceFile(id, path, data, ifVersion),@@ -78,6 +81,7 @@ export function filesApi(scope: FilesScope): FilesApi {return {list: (path) => api.listWorkspaceDirFiles(dir, path),fileUrl: (path, download) => api.workspaceDirFileUrl(dir, path, download),+ textUrl: (path) => api.workspaceDirFileTextUrl(dir, path),previewUrl: (path) => api.workspaceDirPreviewUrl(dir, path),isolatablePreviews: false,write: (path, data, ifVersion) => api.writeWorkspaceDirFile(dir, path, data, ifVersion),diff --git a/packages/web/src/features/chat/pdf-preview.tsx b/packages/web/src/features/chat/pdf-preview.tsxnew file mode 100644index 00000000..d102077c--- /dev/null+++ b/packages/web/src/features/chat/pdf-preview.tsx@@ -0,0 +1,244 @@+/**+ * A PDF preview the app draws itself, instead of handing the file to the browser's own viewer.+ *+ * The iframe the pane used to mount was only ever as good as the client: Chromium renders a PDF+ * frame, but a browser with its viewer disabled (or a download-on-navigate policy), and any+ * engine that treats `application/pdf` as an attachment, leave a blank rectangle with no way to+ * tell a broken preview from a slow one. The Files panel answers "what is in this file" for+ * every other type; a PDF should not depend on where the app is being viewed.+ *+ * So the bytes are fetched with the session's credentials like any other preview, pdf.js paints+ * each page onto a canvas at the pane's width, and the pane scrolls through them. Canvas output+ * carries no script surface: an Agent-written PDF cannot reach the app's DOM. The viewer keeps+ * the browser out of the picture entirely — nothing here navigates to the file URL.+ *+ * Pages render when they scroll into view (a 200-page manual is not 200 canvases on open), and+ * a placeholder holds each page's height in the meantime so the scrollbar doesn't jump.+ */+import { useEffect, useRef, useState } from "react";+import type { PDFDocumentLoadingTask, PDFDocumentProxy } from "pdfjs-dist";++/** A page taller than this many pane-widths still renders: the cap is on the canvas, not the page. */+const MAX_CANVAS_PIXELS = 16 * 1024 * 1024;+/** Lazy rendering: a page starts painting this close to the viewport (in px). */+const PRELOAD_MARGIN = 600;++/** The pane's inner width, kept current while the dock is resized. */+function useWidth(ref: React.RefObject<HTMLDivElement | null>): number {+ const [width, setWidth] = useState(0);+ useEffect(() => {+ const el = ref.current;+ if (el === null) return;+ setWidth(el.clientWidth);+ const observer = new ResizeObserver((entries) => {+ const next = entries[0]?.contentRect.width ?? 0;+ setWidth(Math.round(next));+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, [ref]);+ return width;+}++/** One page: a placeholder of the right height until it is near the viewport, then a canvas. */+function PdfPage({+ doc,+ pageNumber,+ width,+}: {+ doc: PDFDocumentProxy;+ pageNumber: number;+ width: number;+}) {+ const hostRef = useRef<HTMLDivElement | null>(null);+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const [visible, setVisible] = useState(false);+ const [aspect, setAspect] = useState<number | null>(null);+ const [failed, setFailed] = useState(false);++ // Page geometry (width/height ratio) so the placeholder reserves the page's height before it+ // is painted — without it, every page would be zero-height until it rendered and the list+ // would grow under the reader's scrollbar.+ useEffect(() => {+ let cancelled = false;+ void doc+ .getPage(pageNumber)+ .then((page) => {+ if (cancelled) return;+ const view = page.getViewport({ scale: 1 });+ setAspect(view.height / view.width);+ page.cleanup();+ })+ .catch(() => {+ if (!cancelled) setFailed(true);+ });+ return () => {+ cancelled = true;+ };+ }, [doc, pageNumber]);++ useEffect(() => {+ const el = hostRef.current;+ if (el === null) return;+ const observer = new IntersectionObserver(+ (entries) => {+ if (entries.some((e) => e.isIntersecting)) setVisible(true);+ },+ { rootMargin: `${PRELOAD_MARGIN}px 0px` },+ );+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ // Paint. Re-runs when the pane is resized: the canvas is redrawn at the new width rather than+ // stretched, which keeps text crisp.+ useEffect(() => {+ if (!visible || width <= 0 || aspect === null) return;+ let cancelled = false;+ let task: { cancel: () => void } | null = null;+ void (async () => {+ try {+ const page = await doc.getPage(pageNumber);+ if (cancelled) return;+ const base = page.getViewport({ scale: 1 });+ const ratio = Math.min(window.devicePixelRatio || 1, 2);+ let scale = (width * ratio) / base.width;+ const pixels = (base.width * scale * (base.height * scale)) | 0;+ if (pixels > MAX_CANVAS_PIXELS)+ scale = Math.sqrt(MAX_CANVAS_PIXELS / (base.width * base.height));+ const viewport = page.getViewport({ scale });+ const canvas = canvasRef.current;+ if (canvas === null) {+ page.cleanup();+ return;+ }+ canvas.width = Math.floor(viewport.width);+ canvas.height = Math.floor(viewport.height);+ canvas.style.width = `${Math.floor(viewport.width / ratio)}px`;+ canvas.style.height = `${Math.floor(viewport.height / ratio)}px`;+ const render = page.render({ canvas, viewport });+ task = render;+ await render.promise;+ page.cleanup();+ } catch (error) {+ // A cancelled render (resize, unmount) is not a failure; anything else leaves the page+ // blank rather than taking the whole preview down.+ const name = (error as { name?: string })?.name;+ if (!cancelled && name !== "RenderingCancelledException") setFailed(true);+ }+ })();+ return () => {+ cancelled = true;+ task?.cancel();+ };+ }, [doc, pageNumber, width, visible, aspect]);++ return (+ <div+ ref={hostRef}+ data-page={pageNumber}+ className="flex flex-col items-center gap-1"+ style={aspect === null ? { minHeight: 240 } : undefined}+ >+ <div+ className="overflow-hidden rounded-sm bg-white shadow-sm ring-1 ring-black/5"+ style={+ aspect === null+ ? { width: width > 0 ? width : undefined, height: 240 }+ : { width: width > 0 ? width : undefined, aspectRatio: `1 / ${aspect}` }+ }+ >+ {failed ? (+ <p className="p-3 text-xs text-fg-subtle">{`p.${pageNumber}`}</p>+ ) : (+ <canvas ref={canvasRef} aria-label={`p.${pageNumber}`} className="block h-full w-full" />+ )}+ </div>+ <span className="text-xs tabular-nums text-fg-subtle">{pageNumber}</span>+ </div>+ );+}++export function PdfPreview({+ src,+ title,+ reloadKey,+ loadingLabel,+ errorLabel,+}: {+ src: string;+ title: string;+ /** Remount-and-refetch key: the same URL is unchanged when the Agent rewrites the file. */+ reloadKey?: number;+ loadingLabel: string;+ errorLabel: string;+}) {+ const scrollRef = useRef<HTMLDivElement | null>(null);+ const width = useWidth(scrollRef);+ const [doc, setDoc] = useState<PDFDocumentProxy | null>(null);+ const [failed, setFailed] = useState(false);++ useEffect(() => {+ let cancelled = false;+ let task: PDFDocumentLoadingTask | null = null;+ setDoc(null);+ setFailed(false);+ void (async () => {+ try {+ // The worker is its own asset: pdf.js parses on a thread of its own, so a long document+ // cannot freeze the conversation behind it.+ const pdfjs = await import("pdfjs-dist");+ pdfjs.GlobalWorkerOptions.workerSrc = new URL(+ "pdfjs-dist/build/pdf.worker.min.mjs",+ import.meta.url,+ ).href;+ const response = await fetch(src, { credentials: "same-origin" });+ if (!response.ok) throw new Error(String(response.status));+ const data = new Uint8Array(await response.arrayBuffer());+ if (cancelled) return;+ task = pdfjs.getDocument({ data });+ const document = await task.promise;+ if (cancelled) {+ void task.destroy();+ task = null;+ return;+ }+ setDoc(document);+ } catch {+ if (!cancelled) setFailed(true);+ }+ })();+ // The loading task owns the worker and is what tears both down — a document proxy has no+ // `destroy` of its own in this pdf.js version, and calling one was a TypeError on unmount.+ return () => {+ cancelled = true;+ void task?.destroy();+ };+ }, [src, reloadKey]);++ // The scroll box is always mounted, even while the document is loading: it is what the width+ // is measured from, and an element that only appears after the fetch would report 0 to the+ // measurement effect that already ran (and never re-run it).+ return (+ <div+ ref={scrollRef}+ aria-label={title}+ tabIndex={0}+ className="h-full w-full overflow-auto rounded-md border border-line bg-gray-100 p-2 dark:bg-gray-900"+ >+ {failed ? (+ <p className="p-1 text-sm text-tone-danger-fg">{errorLabel}</p>+ ) : doc === null ? (+ <p className="p-1 text-sm text-fg-subtle" role="status">+ {loadingLabel}+ </p>+ ) : (+ <div className="flex flex-col items-center gap-3">+ {Array.from({ length: doc.numPages }, (_, i) => (+ <PdfPage key={i + 1} doc={doc} pageNumber={i + 1} width={Math.max(width - 16, 0)} />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex 2f23a8a6..4d1501d1 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -120,6 +120,7 @@ import {defaultTreeWidth,dropTargetDir,expandTo,+ extOf,searchRows,flattenTree,isDirty,@@ -154,6 +155,7 @@ import { toneInk } from "../../lib/tone";import { setCloseGuard } from "../dock/close-guard";import { tabKey } from "../dock/dock-state";import { PAPERCLIP_ICON } from "./attached-files-banner";+import { PdfPreview } from "./pdf-preview";import { WorkspaceTreeView } from "./workspace-tree-view";/**@@ -211,7 +213,7 @@ function withStorageShim(html: string): string {interface Preview {path: string;name: string;- kind: "text" | "md" | "image" | "html" | "pdf" | "unsupported";+ kind: "text" | "md" | "image" | "html" | "pdf" | "doc" | "unsupported";/** Content for kind=text/md/html (may be truncated). */content?: string;truncated?: boolean;@@ -220,6 +222,9 @@ interface Preview {/** Bumped on every previewPath call; keys the isolated HTML iframe so re-opening the* same path remounts it and refetches fresh content (its src alone would not change). */nonce: number;+ /** Why this file has no preview, when the generic sentence would be wrong (a legacy .doc+ * says to save it as .docx; a .docx the server could not read says so). */+ message?: string;}/** Monotonic counter behind Preview.nonce. Doubles as the staleness guard: previewPath@@ -260,6 +265,9 @@ async function fetchTextPreview(if (res.body === null) throw new Error("no response body");const version = res.headers.get("etag");if (version === null) throw new Error("no version header");+ // A text extraction can be cut at the source (the .docx route caps what it converts), which+ // is the same "you are looking at part of the file" answer as the byte cap below.+ const cutAtSource = res.headers.get("x-content-truncated") === "1";const reader = res.body.getReader();const chunks: Uint8Array[] = [];let total = 0;@@ -283,7 +291,7 @@ async function fetchTextPreview(bytes.set(chunk, offset);offset += chunk.length;}- const truncated = total > TEXT_PREVIEW_LIMIT;+ const truncated = cutAtSource || total > TEXT_PREVIEW_LIMIT;const shown = truncated ? utf8Complete(bytes.subarray(0, TEXT_PREVIEW_LIMIT)) : bytes;return { content: new TextDecoder().decode(shown), truncated, version };}@@ -826,11 +834,55 @@ export function WorkspaceBrowser({present({ path: filePath, name, kind: "image", nonce });return;}- // PDF: the server returns it inline as application/pdf, embedded directly in an iframe and rendered by the browser.+ // PDF: the panel paints it itself (see features/chat/pdf-preview.tsx). Handing the file to+ // the browser's own viewer instead only worked where that viewer exists — a client that+ // downloads `application/pdf` on navigation left a blank pane that looked like a broken+ // file. Nothing here navigates to the URL.if (kind === "pdf") {present({ path: filePath, name, kind: "pdf", nonce });return;}+ // Word: a .docx is read through the server's text extraction and shown as Markdown — the+ // preview of a document, never an editor for it. A legacy .doc is a binary Word file+ // nothing here can read, and says so instead of failing like a corrupt .docx would.+ if (kind === "doc") {+ if (extOf(name) === "doc") {+ if (!refresh) {+ present({+ path: filePath,+ name,+ kind: "unsupported",+ message: S.files.previewDocLegacy,+ nonce,+ });+ }+ return;+ }+ try {+ const result = await fetchTextPreview(files.textUrl(filePath), false);+ if (result === null) throw new Error("no extraction");+ present({+ path: filePath,+ name,+ kind: "doc",+ content: result.content,+ truncated: result.truncated,+ version: result.version,+ nonce,+ });+ } catch {+ if (!refresh) {+ present({+ path: filePath,+ name,+ kind: "unsupported",+ message: S.files.previewDocxFailed,+ nonce,+ });+ }+ }+ return;+ }// Isolated HTML: the rendered view is an iframe onto the preview origin and needs no// text here, so the iframe mounts with no upfront fetch — a large file isn't// downloaded twice, and a transient fetch failure can't downgrade a page the iframe@@ -2225,13 +2277,27 @@ export function WorkspaceBrowser({};}if (p.kind === "pdf") {+ // Painted here rather than embedded: the pane must not depend on the client's own PDF+ // viewer (see pdf-preview.tsx). The URL is fetched with the session's credentials.return {- kind: "pdf",- src: files.fileUrl(p.path),- title: p.name,- reloadKey: p.nonce,+ kind: "embed",+ node: (+ <PdfPreview+ src={files.fileUrl(p.path)}+ title={p.name}+ reloadKey={p.nonce}+ loadingLabel={S.files.pdfLoading}+ errorLabel={S.files.pdfFailed}+ />+ ),};}+ if (p.kind === "doc") {+ if (p.content === undefined) return pendingSource();+ // A Word document, read as the Markdown the server extracted from it. Rendered only: there+ // is no source view and no editor, because what is on screen is not the file.+ return { kind: "markdown", text: p.content, truncatedNote };+ }if (p.kind === "html" && richView === "rendered") {if (previewIsolated) {return {@@ -2354,7 +2420,7 @@ export function WorkspaceBrowser({truncatedNote,};}- return { kind: "unsupported", message: S.files.previewUnsupported };+ return { kind: "unsupported", message: p.message ?? S.files.previewUnsupported };};/**diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex d246a975..e77b8144 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -4141,6 +4141,13 @@ export const en: Strings = {root: ".",empty: "Empty directory",previewUnsupported: "Preview not supported for this type; download instead",+ /** A legacy .doc is a binary format nothing here can read; the way out is a resave. */+ previewDocLegacy: "Legacy .doc files cannot be previewed; save the file as .docx to preview it",+ /** The server could not read this .docx (damaged, or not really a Word file). */+ previewDocxFailed: "This Word file could not be read; download it instead",+ /** The pane paints PDFs itself (features/chat/pdf-preview.tsx); these are its two states. */+ pdfLoading: "Opening the PDF…",+ pdfFailed: "The PDF could not be read; download it to open in a reader",uploadedCount: (n: number): string => (n === 1 ? "1 file uploaded" : `${n} files uploaded`),uploading: (done: number, total: number): string => `Uploading ${done}/${total}…`,/** Oversize picks are named and skipped before anything is read. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 954a9ea5..3dc5ddeb 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -4184,6 +4184,13 @@ export const zh = {root: ".",empty: "空目录",previewUnsupported: "该类型不支持预览,请下载查看",+ /** A legacy .doc is a binary format nothing here can read; the way out is a resave. */+ previewDocLegacy: "旧版 .doc 无法预览,用 Word 另存为 .docx 后即可预览",+ /** The server could not read this .docx (damaged, or not really a Word file). */+ previewDocxFailed: "这个 Word 文件无法解析,请下载查看",+ /** The pane paints PDFs itself (features/chat/pdf-preview.tsx); these are its two states. */+ pdfLoading: "正在打开 PDF…",+ pdfFailed: "PDF 读取失败,可下载后用阅读器查看",uploadedCount: (n: number): string => `已上传 ${n} 个文件`,uploading: (done: number, total: number): string => `正在上传 ${done}/${total}…`,/** Oversize picks are named and skipped before anything is read. */diff --git a/packages/web/src/lib/workspace-tree.ts b/packages/web/src/lib/workspace-tree.tsindex cb9a93df..753085e7 100644--- a/packages/web/src/lib/workspace-tree.ts+++ b/packages/web/src/lib/workspace-tree.ts@@ -319,7 +319,7 @@ const HTML_EXTS = new Set(["html", "htm"]);* browser reads such a file's first bytes and treats it as text when they look like text* (a Makefile, a LICENSE, a dotfile with no extension).*/-export type PreviewKind = "text" | "md" | "image" | "html" | "pdf" | "unknown";+export type PreviewKind = "text" | "md" | "image" | "html" | "pdf" | "doc" | "unknown";/** The lowercased extension, or the whole lowercased name when it has none ("Makefile" → "makefile", ".env" → "env"). */export function extOf(name: string): string {@@ -331,6 +331,9 @@ export function previewKindFor(name: string): PreviewKind {const ext = extOf(name);if (IMAGE_EXTS.has(ext)) return "image";if (ext === "pdf") return "pdf";+ // Word previews through the server's own text extraction (a .docx is a zip of XML, see+ // services/docx-preview.ts), read-only: a preview of a document is not its source.+ if (ext === "docx" || ext === "doc") return "doc";if (HTML_EXTS.has(ext)) return "html";if (ext === "md") return "md";if (TEXT_EXTS.has(ext)) return "text";@@ -347,6 +350,9 @@ export function previewKindFor(name: string): PreviewKind {export function previewKindOf(name: string): FileBrowserPreviewKind {const kind = previewKindFor(name);if (kind === "html") return "text";+ // A Word document needs the server's extraction fetch, which this read-only browser does not+ // do; it names the type instead of drawing an empty pane.+ if (kind === "doc") return "unsupported";return kind === "unknown" ? "unsupported" : kind;}diff --git a/packages/web/test/workspace-tree.test.ts b/packages/web/test/workspace-tree.test.tsindex 00029771..ef6b3ad9 100644--- a/packages/web/test/workspace-tree.test.ts+++ b/packages/web/test/workspace-tree.test.ts@@ -236,6 +236,10 @@ describe("file kinds", () => {expect(previewKindFor(".gitignore")).toBe("text");expect(previewKindFor("photo.PNG")).toBe("image");expect(previewKindFor("paper.pdf")).toBe("pdf");+ // Word previews through the server's text extraction, in both the modern and the legacy+ // extension: the panel tells them apart when it loads one (a .doc gets its own message).+ expect(previewKindFor("设计稿.docx")).toBe("doc");+ expect(previewKindFor("old.DOC")).toBe("doc");expect(previewKindFor("Makefile")).toBe("unknown");expect(previewKindFor("archive.tar.gz")).toBe("unknown");});@@ -244,6 +248,8 @@ describe("file kinds", () => {expect(previewKindOf("index.html")).toBe("text");expect(previewKindOf("Makefile")).toBe("unsupported");expect(previewKindOf("README.md")).toBe("md");+ // No extraction fetch in the read-only browser: a Word file reads as unsupported there.+ expect(previewKindOf("设计稿.docx")).toBe("unsupported");});it("takes UTF-8 text for text, including a chunk cut inside a multi-byte character", () => {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9907be5e..fd6145af 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -677,6 +677,9 @@ importers:copy-to-clipboard:specifier: ^4.0.2version: 4.0.2+ pdfjs-dist:+ specifier: ^6.4.299+ version: 6.4.299react:specifier: ^19.1.0version: 19.2.7@@ -1648,6 +1651,81 @@ packages:resolution: {integrity: sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==}engines: {node: '>=20'}+ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [android]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [linux]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}+ engines: {node: '>= 10'}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}+ engines: {node: '>= 10'}+'@noble/[email protected]':resolution: {integrity: sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==}engines: {node: '>= 16'}@@ -3954,6 +4032,10 @@ packages:resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}engines: {node: '>= 14.16'}+ resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}+ engines: {node: '>=22.13.0 || >=24'}+resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==}engines: {node: '>=12', npm: '>=6'}@@ -5943,6 +6025,54 @@ snapshots:'@modelcontextprotocol/core': 2.0.0zod: 4.4.3+ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optional: true++ '@napi-rs/[email protected]':+ optionalDependencies:+ '@napi-rs/canvas-android-arm64': 1.0.13+ '@napi-rs/canvas-darwin-arm64': 1.0.13+ '@napi-rs/canvas-darwin-x64': 1.0.13+ '@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13+ '@napi-rs/canvas-linux-arm64-gnu': 1.0.13+ '@napi-rs/canvas-linux-arm64-musl': 1.0.13+ '@napi-rs/canvas-linux-riscv64-gnu': 1.0.13+ '@napi-rs/canvas-linux-x64-gnu': 1.0.13+ '@napi-rs/canvas-linux-x64-musl': 1.0.13+ '@napi-rs/canvas-win32-arm64-msvc': 1.0.13+ '@napi-rs/canvas-win32-x64-msvc': 1.0.13+ optional: true+'@noble/[email protected]': {}'@noble/[email protected]': {}@@ -8626,6 +8756,10 @@ snapshots:+ optionalDependencies:+ '@napi-rs/canvas': 1.0.13+