diff --git a/AGENTS.md b/AGENTS.md
index e9c5c0f9..1744e9c6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -139,4 +139,4 @@
- **测试不得依赖非普适二进制**:CI 跑 ubuntu + windows 两个 runner,`rg` / `fd` / `jq` 这类「开发机上有」的工具在 runner 上没有,代价是整个 spec 在**收集阶段**失败(`spawnSync rg ENOENT`)而本地永远绿——上一版的 `tests/primitives-exports.spec.ts` 就这么让分支红了两轮。取文件清单用 `readdirSync` 自己走,或只用 `git` / `tar` / `pnpm` / node 内置能力;确需外部工具时先探测存在性并跳过。
- **测试 fixture 的文件名必须两个平台都合法**:Windows 上 `*` `?` `:` `"` `<` `>` `|` 不能出现在文件名里,`writeFileSync(join(tmp, 'a*b.ts'))` 会直接 `ENOENT`(本次 `tests/search-engines.spec.ts` 的真实引擎用例就这么红在 Windows lane 上,macOS 永远绿)。要验证「元字符按字面处理」就换一个**两平台都合法**的良构元字符(win32 用 `a[b]`,POSIX 用 `a*b`),**不要**用未闭合的 `a[b`——rg 对未转义的 `[` 报 `unclosed character class` 并退出,引擎被判 broken 后回退普通遍历,断言会被兜底路径**意外满足**,判别力归零。
- **按「入参平台」推导路径的函数必须用同方言的 `node:path`**:`bundledRgCandidates(platform, …)` 这类函数若用宿主的 `sep` / `dirname` / `join`,在不同 OS 上就是不同的函数——Windows runner 上 `endsWith('\\node_modules')` 永不命中 POSIX 起始路径,整条走查产不出候选,而本地(macOS)永远绿。按 `platform` 选 `posix` / `win32`,让输出只依赖入参,测试也才能跨方言断言(`posix.join` / `win32.join`)。
-- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**6 tab + 3 viewer**——右列终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / code;第 6 个 tab 是 `terminal-bottom`(#774,`bottomOnly`,只投插件自己的底部工作台))/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位、`bottomOnly` 描述符**不产生任何原生注册**(tab 类型 / slot / guide 条目,#774——此前只有挂载 lane 抓得住);断言写在注册表的事件日志上)/ `file-open-claim.spec.ts`(文件打开的认领判定:插件一切文件入口先问 `sidebarRightTabs.candidates`,被第三方认领的文件改走 `openResource`,无人认领/无注册表/探测抛错逐字保持 editor 原路径——#695,PR #696 移植;`editor-host.spec.tsx` 另钉合并模式原地切换同样让位)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索,含 `explorerExclude` 排除探针:匹配条目不出现也不下钻)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `exclude-patterns.spec.ts` / `fs-tree-exclude.spec.ts` / `fs-tree-compact.spec.ts` / `file-tree-compact.spec.ts` / `file-tree-compact-fold.spec.tsx`(资源管理器排除模式与面包屑折叠:glob 子集编译器及其**缓存身份**——host 目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键;`compact` 单目录链的 host 标记、client 折叠/整链开关与折叠链预加载)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控)。
+- **关键测试守护**:`tests/service.spec.ts` / `builtins.spec.ts`(注册表与内置清单:**6 tab + 4 viewer**——右列终端与浏览器已交还宿主,只读预览也按 §3.2 第 5 条让出,只剩 markdown / html / jsonl(v0.26.0 新增,逐行 JSON 记录预览 + 可保存编辑)/ code;第 6 个 tab 是 `terminal-bottom`(#774,`bottomOnly`,只投插件自己的底部工作台))/ `market-manifest.spec.ts`(市场约束,含 `pnpm pack` 后的产物面)/ `manifest-consistency.spec.ts`(registry 通道形状)/ `e2e-host-protocol.spec.ts`(RPC 双协议)/ `native-surface.spec.ts`(原生右侧栏承载面:guide 条目 id 唯一性、以及 `canOpen` 的「拒绝清单不得宽于宿主渲染器」双向边界)/ `native-registration.spec.ts`(原生 tab 注册生命周期:`files` 接管不得被通知拆建、注册失败必须回滚已占用的 id 与已建槽位、`bottomOnly` 描述符**不产生任何原生注册**(tab 类型 / slot / guide 条目,#774——此前只有挂载 lane 抓得住);断言写在注册表的事件日志上)/ `file-open-claim.spec.ts`(文件打开的认领判定:插件一切文件入口先问 `sidebarRightTabs.candidates`,被第三方认领的文件改走 `openResource`,无人认领/无注册表/探测抛错逐字保持 editor 原路径——#695,PR #696 移植;`editor-host.spec.tsx` 另钉合并模式原地切换同样让位)/ `theme.spec.ts`(皮肤契约,含空白面板胶囊几何)/ `plugin-list.spec.ts`(推荐插件目录)/ `fs-search.spec.ts`(host 文件名搜索,含 `explorerExclude` 排除探针:匹配条目不出现也不下钻)/ `fs-watch.spec.ts`(文件树目录 watch 的去抖、句柄上限与错误路径)/ `exclude-patterns.spec.ts` / `fs-tree-exclude.spec.ts` / `fs-tree-compact.spec.ts` / `file-tree-compact.spec.ts` / `file-tree-compact-fold.spec.tsx`(资源管理器排除模式与面包屑折叠:glob 子集编译器及其**缓存身份**——host 目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键;`compact` 单目录链的 host 标记、client 折叠/整链开关与折叠链预加载)/ `smoke.spec.ts` 的 settings 段(按 entry id 读写表单、**一次性 legacy 迁移**、open 工具门控——其 GET 走真 `node:http`,因为字节路由现在要真 Writable,且必须 `closeAllConnections` 否则 undici 的 keep-alive 会把用例拖过超时)/ `file-stream-route.spec.ts`(字节路由流式化:`open` 成功后才 `writeHead`,所以不可读文件仍是 4xx JSON 信封;流中途失败走 `writeJson` 的 `headersSent` 守卫而不是 `ERR_HTTP_HEADERS_SENT`)/ `fs-read-page.spec.ts`(分页读取:按行对齐、超长单行不裁空、EOF 精确,以及**只锁宽字符编码**这一条:长 ASCII 前缀 + GBK 正文要逐页各自嗅探,纯 CJK 的 UTF-16 页不能推翻首页的宽编码判定)/ `jsonl.spec.ts` / `jsonl-language.spec.ts`(逐行 JSON 词法分析:400 条记录零错误节点(`json()` 是 402 个)、坏行不溢出到后一行、不为缺失结构编造错误)/ `archive.spec.ts` / `archive-tools.spec.ts`(打包改原生命令:argv 含 `-y`(防符号链接环)、公共祖先定位、注入式 spawn 的探测与 `unavailable`、临时文件在流结束后删除、`dispose()` 杀子进程;唯一一条真二进制用例自探测缺席即跳过)/ `editor-large-file.spec.tsx`(超限进入只读分页预览 + 下载出口 + 无 CodeMirror + 无保存按钮,并带可编辑反证)。
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e481c43..66f11c93 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,32 @@
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
+### 未发布
+
+> 📦 **上传、下载、HTML 预览与打包全部改为流式传输,不再有大小限制。** 三个部署限额键 `readLimit` / `mediaLimit` / `uploadLimit` 随之删除(旧 profile 里残留的值会被当作未知键静默忽略,无需迁移);`listLimit` 保留。
+
+- ⚡ **下载不再有 20 MB 上限,宿主内存不再随文件增长**:`/sidebar/file` 与 `/sidebar/html` 从「整份 `readFile` → `res.end(buffer)`」改为 `createReadStream` + `pipeline`。关键在**写响应头的时机**——先等流的 `open` 事件再 `writeHead`,所以文件读不到(ENOENT/EACCES/目录)仍然回插件的 JSON 错误信封,而不是一个 200 加空体;提交之后再失败(文件被换掉、客户端断开)就 `destroy()` 掉连接,并给 `writeJson` 加了 `headersSent` 早退守卫,避免路由的 catch 块在已提交的响应上抛 `ERR_HTTP_HEADERS_SENT` 把「下载被截断」升级成「请求崩溃」。判别性用例见 `tests/file-stream-route.spec.ts`(21 MiB 真 `node:http` 下发、中途断开存活、不可读路径仍是 4xx 信封)。
+
+- ⚡ **上传的两道 128 MB 闸门删除**:上传本就已经端到端流式(`for await (chunk of req)` → 临时文件 → 原子 rename),挡路的只是客户端的 `MAX_UPLOAD_BYTES` 预检与宿主的逐块 `limit` 检查,两者一并去掉;流式核心、失败清理、不留残file的保证一字未改。
+
+- ⚡ **打包改由系统命令完成,不再自己写 ZIP**:删除手写的 300 行 ZIP writer(`src/zip.ts`,连同 `ZIP_MAX_BYTES` / `ZIP_MAX_ENTRIES` 两道上限),改为探测并调用系统的 `zip`(恒带 `-y`,否则会**跟随**符号链接、一个 `a -> .` 的自指环会一直递归)或 `tar`(Windows 10 1803+ 自带 `bsdtar` 而没有 `zip`)。压缩包的 stdout 直接写进 OS 临时目录,**从不整包进内存**,下载时流式下发、流结束后删除。`archive.status` 的 `done/total` 逐条目进度随之消失(子进程不报),状态收缩为 `{ state, bytes }`;工具都不存在时 `archive.build` 立刻回新的 wire 错误码 **`unavailable`**,界面显示一句可操作的提示。客户端的下载也从 `fetch → blob` 改回普通 `` 直链——Blob 会把整包放进标签页内存,正好抵消宿主侧的改造。
+
+- ⚡ **编辑器保存拆掉 1 MiB 的墙**:`fs.write` 原走 JSON,而 `/sidebar/api` 的请求体上限是 1 MiB,所以「能打开的文件存不回去」。保存改为 `POST /sidebar/write` 的 raw 路由(**文档即请求体**),编码与行尾还原逻辑(#523 / #871 的两条保证)原样保留并由 `tests/fs-write-route.spec.ts` 继续钉住,另加一条「远超旧上限的一次保存」。
+
+- 🧾 **超大文件从「截断成只读」改为「只读分页预览」**:`fs.read` 从「全读或截断」变成三态(`text` / `binary` / **`too-large`**)。超过编辑上限(5 MiB)的文本文件不再回半份文档,而是只带 4 KiB 嗅探头的 `too-large`,客户端据此渲染**分页只读预览**(等宽行列表,日志查看器形态)并提供下载出口;超过该大小的**二进制**走原来的 media 路径,行为完全不变。`FileViewerProps.truncated` 与 `truncation` 文案键一并删除——「拿到半份文档但看起来能编辑」这个状态本身就是 #732 的成因。新 `fs.readPage` 按字节窗口分页,窗口回退到最后一个换行,所以一页是整数行;超长单行原样返回而不是空页(否则「下一页」会停在一个永不前进的偏移上)。
+
+- 🆕 **`.jsonl` / `.ndjson` 有原生支持了**:此前它们既没有语法高亮(`lang.ts` 无映射 → 纯白文本),也不能简单地映射到 `json()`——`@lezer/json` 的文法只接受一个顶层值,实测 400 条记录的文件会解析出 **402 个错误节点**。现在有一个手写的逐行 JSON 词法分析器(一行一次、不携带跨行状态、未闭合字符串直接标错),新增第 4 个内置 viewer `jsonl`:**预览**是每条记录一张可折叠卡片(默认折叠成一行摘要,点开用宿主的 `JsonTree`),**编辑**是原样可保存的 CodeMirror,由预览/编辑开关切换。行引用(`a.jsonl#L131`)仍会先切到编辑档再落行。
+
+- 🎨 **修掉「错误标记看不见」**:`tags.invalid` 在深浅两种配色下都是 `#ffffff` —— 在浅色主题里就是白底白字。它是 JSON/JSONL 语法错误落到的 token,读者本该能看出哪段没解析;现改为红色波浪下划线。
+
+- 🔧 **`stat` 失败从 500 变 400**:两条字节路由原先让 `stat` 的原始 rejection 逃成「internal」500,读起来像插件故障;不可读的用户路径是 400。
+
+- 🔧 **分页读取的编码一致性(一处只有真机才会发现的回归)**:第一版锁死了第一页嗅探到的编码,于是「长 ASCII 前缀 + GBK 正文」的文件第一页判成 UTF-8 后,后半段 GBK 字节被按 UTF-8 解成乱码——而一次性全读是能正确解出来的。现在**只锁宽字符编码**(UTF-16/UTF-32 是文件属性,一页恰好没有 NUL 不能重新裁决),字节序编码逐页各自嗅探(纯 ASCII 页在两种编码下解出来是同一个字符串)。这在分页按行对齐的前提下是安全的:`0x0A` 既不能是 UTF-8 的续字节,也不能是 GBK 的尾字节。双向用例见 `tests/fs-read-page.spec.ts`。
+
+- 🧪 新守护:`tests/file-stream-route.spec.ts`、`tests/fs-read-page.spec.ts`、`tests/jsonl.spec.ts`、`tests/jsonl-language.spec.ts`、`tests/archive-tools.spec.ts`、`tests/archive.spec.ts`、`tests/editor-large-file.spec.tsx`(超限只读预览 + 可编辑反证)。`tests/zip.spec.ts` 随 writer 一起重写为 `tests/archive.spec.ts`;唯一一条真二进制用例自探测、缺席即跳过(CI 上没有 `zip` 的 Windows runner 不会红)。
+
+- 📖 设计过程、与 VS Code Web 的对照(含「VS Code 并不分页,它的模型是阈值 + 确认 + 关闭 tokenization」这一条纠错)以及实施偏差记录见 [docs/plans/2026-10-11-streaming-transfer-jsonl-preview.md](docs/plans/2026-10-11-streaming-transfer-jsonl-preview.md)。
+
### v0.25.0
> 📦 **支持线前移:仅适配 DSH `0.2.0-rc.2+`**(peer 下限 `^0.2.0-rc.2`,CI 与挂载 lane 钉 `@deepseek-ai/dsh@0.2.0-rc.2`)。DSH 的 npm `latest` 现在正是 **0.2.0-rc.2**(不再停在 0.1.7-rc.2),本版就钉在它上面。**0.2.0-rc.1 及更早(含 0.1.7 线)请固定 v0.24.1**——`^0.2.0-rc.2` 对 rc.1 判定为 false,会被宿主的启动兼容性预检整行静默禁用;0.1.7 线的最后支持版是 v0.22.1。本次前移是一次纯声明与钉版变更:0.2.0-rc.2 对本插件消费的宿主面仍是纯增量,运行时零改动。
diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md
index 2653568c..5f136848 100644
--- a/CHANGELOG_EN.md
+++ b/CHANGELOG_EN.md
@@ -2,6 +2,32 @@
> Full release history of dsh-better-sidebar (see the [README](README_EN.md) for the latest release; also mirrored on [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases)).
+### Unreleased
+
+> Upload, download, the HTML preview and archive packing all stream now, and there is no size limit left anywhere. The three deployment limit keys `readLimit` / `mediaLimit` / `uploadLimit` are gone with them (a retired key left in an old profile is silently ignored as an unknown field — no migration needed); `listLimit` stays.
+
+- **Downloads have no 20 MB cap and the host's memory no longer grows with the file**: `/sidebar/file` and `/sidebar/html` went from "`readFile` the whole thing → `res.end(buffer)`" to `createReadStream` + `pipeline`. The load-bearing detail is WHEN the header is written — the stream's `open` event is awaited first, so an unreadable file (ENOENT/EACCES/directory) still produces the plugin's JSON error envelope instead of a 200 with an empty body; a failure after that point (the file changed under us, the peer went away) destroys the socket. `writeJson` gained a `headersSent` guard so a route's catch block cannot throw `ERR_HTTP_HEADERS_SENT` on a committed response and turn a truncated download into a crashed request. See `tests/file-stream-route.spec.ts` (a real 21 MiB `node:http` transfer, a mid-stream abort, an unreadable path).
+
+- **Upload's two 128 MB gates are gone**: upload was already streamed end to end (`for await (chunk of req)` → temp file → atomic rename); what stood in the way was the client's `MAX_UPLOAD_BYTES` pre-check and the host's per-chunk `limit` check. The streaming core, the failure cleanup and the "never leaves a partial target or temp file" guarantee are untouched.
+
+- **Packing is the system's job now, not a ZIP writer of ours**: the hand-written 300-line encoder (`src/zip.ts`, with its `ZIP_MAX_BYTES` / `ZIP_MAX_ENTRIES`) is deleted in favour of probing and running the system `zip` (always with `-y` — without it Info-ZIP FOLLOWS symlinks and an `a -> .` loop recurses forever) or `tar` (Windows 10 1803+ ships `bsdtar` and no `zip`). The tool's stdout goes straight into an OS temp file, never into memory, and the download streams it out before the file is deleted. `archive.status` lost its per-entry `done/total` (a child process reports none) and shrank to `{ state, bytes }`; with neither tool installed `archive.build` answers the new wire code `unavailable` and the UI shows an actionable sentence. The client download went back to a plain `` link — a Blob would hold the whole archive in the tab's memory and undo the host-side change.
+
+- **Saving no longer has a 1 MiB wall**: `fs.write` rode the JSON API, whose request body is capped at 1 MiB, so a file the editor could open could not be written back. Saving moved to the raw `POST /sidebar/write` route (the document IS the request body); the encoding and line-ending restore (#523 / #871) is carried over unchanged and still pinned by `tests/fs-write-route.spec.ts`, now with a case far past the old ceiling.
+
+- **Oversized files get a read-only PAGED preview instead of a truncated editor**: `fs.read` went from "whole file or a truncated prefix" to three outcomes (`text` / `binary` / **`too-large`**). Above the editable threshold (5 MiB) a text file is no longer handed over as half a document — it answers `too-large` with a 4 KiB sniff head, and the client renders a paged read-only preview (a monospace line list, the log-viewer shape) with a download escape hatch. Oversized BINARIES are unaffected (the media path is the same as before). `FileViewerProps.truncated` and the `truncation` copy key are both deleted — "half a document that looks editable" is itself the defect #732 was about. The new `fs.readPage` pages by byte window, trimmed back to the last line break so a page is a whole number of lines; a single over-long line is returned as-is rather than as an empty page (otherwise "next" would sit on an offset that never advances).
+
+- **`.jsonl` / `.ndjson` are supported**: they had no highlighting at all (`lang.ts` had no mapping), and mapping them to `json()` is not free — `@lezer/json` accepts ONE top-level value, so a 400-record file parses into **402 error nodes** (measured). There is now a hand-written per-line JSON tokenizer (one line at a time, no cross-line state, an unterminated string marked outright) behind a fourth built-in viewer, `jsonl`: the PREVIEW is one collapsible card per record (collapsed to a one-line summary, expanding into the host's `JsonTree`) and the EDITOR is the same saveable CodeMirror, behind the preview/edit toggle. Line references (`a.jsonl#L131`) still flip to the editor and land on the line.
+
+- **Fixed an invisible error marker**: `tags.invalid` was `#ffffff` in BOTH schemes — white on white in the light theme. It is the token a JSON/JSONL syntax error lands on, and the reader is supposed to be able to see what did not parse; it is now a red wavy underline.
+
+- **A `stat` failure is a 400 now, not a 500**: the two byte routes let the raw rejection escape as an "internal" 500, which reads as a plugin fault. An unreadable user path is a 400.
+
+- **Paged-read encoding consistency (a regression only a real file would surface)**: the first implementation locked the encoding page 1 sniffed, so a "long ASCII prefix + GBK body" file decided UTF-8 from its first page and decoded the GBK tail into mojibake — while a whole-file read had always decoded it correctly. Only WIDE encodings are locked now (UTF-16/UTF-32 is a property of the file; a page that happens to hold no NUL bytes cannot re-litigate it) while byte-oriented encodings are sniffed per page (a pure-ASCII page decodes identically either way). That is safe because pages are line-aligned: `0x0A` can be neither a UTF-8 continuation byte nor a GBK trail byte. Both directions are pinned in `tests/fs-read-page.spec.ts`.
+
+- New guards: `tests/file-stream-route.spec.ts`, `tests/fs-read-page.spec.ts`, `tests/jsonl.spec.ts`, `tests/jsonl-language.spec.ts`, `tests/archive-tools.spec.ts`, `tests/archive.spec.ts`, `tests/editor-large-file.spec.tsx`. `tests/zip.spec.ts` was rewritten as `tests/archive.spec.ts` alongside the writer it tested; the single real-binary case self-probes and skips when neither tool is installed (so the Windows CI runner without `zip` does not go red).
+
+- Design notes, the comparison against VS Code Web (including the correction that **VS Code does not paginate** — its model is threshold + confirmation + turning tokenization off) and the record of implementation deviations live in [docs/plans/2026-10-11-streaming-transfer-jsonl-preview.md](docs/plans/2026-10-11-streaming-transfer-jsonl-preview.md).
+
### v0.24.1
> 🎁 **This release carries everything since v0.22.1** (the Files/Changes UI-UX rebuild and performance work of v0.23.0, the DSH 0.2.0-rc.1 support-line move of v0.24.0, and the fixes below).
diff --git a/README.md b/README.md
index baa613f5..2999cc46 100644
--- a/README.md
+++ b/README.md
@@ -135,12 +135,12 @@ dsh plugin --profile web add dsh-better-sidebar@latest
1. git clone https://github.com/omdsh-dev/DSH-better-sidebar.git ~/Code/DSH-better-sidebar
cd ~/Code/DSH-better-sidebar && pnpm install && pnpm build
2. ~/.dsh/profiles/web/package.json 的 dependencies 写 "dsh-better-sidebar": "link:<克隆目录绝对路径>"
-3. ~/.dsh/profiles/web/cordis.patch.yml 追加挂载行(这一行的 `config` 就是本插件的设置表单:部署限额 `readLimit` / `mediaLimit` / `uploadLimit` / `listLimit` 加用户偏好字段,设置页写的就是它;不写则全部用 schema 默认值):
+3. ~/.dsh/profiles/web/cordis.patch.yml 追加挂载行(这一行的 `config` 就是本插件的设置表单:部署限额 `listLimit` 加用户偏好字段,设置页写的就是它;不写则全部用 schema 默认值。**`readLimit` / `mediaLimit` / `uploadLimit` 三个键已在 v0.26.0 删除**——上传、下载、HTML 预览与打包全部改为流式,不再有大小限制;旧 profile 里残留的这三个键会被当作未知键静默忽略,不会报错):
- insert:
- id: better-sidebar
name: 'dsh-better-sidebar'
config:
- readLimit: 524288
+ listLimit: 1000
4. 在 ~/.dsh/profiles/web 执行 pnpm install
5. 硬刷新浏览器(Cmd/Ctrl+Shift+R)即可看到效果(client 改动无需重启 DSH;host 半改动才需重启)
```
diff --git a/README_EN.md b/README_EN.md
index 30851200..42c3cc87 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -135,12 +135,12 @@ To debug local changes or track the dev branch, point the dependency at a local
1. git clone https://github.com/omdsh-dev/DSH-better-sidebar.git ~/Code/DSH-better-sidebar
cd ~/Code/DSH-better-sidebar && pnpm install && pnpm build
2. In ~/.dsh/profiles/web/package.json dependencies write "dsh-better-sidebar": "link:"
-3. Append this mount line to ~/.dsh/profiles/web/cordis.patch.yml (this row's `config` IS this plugin's settings form: the deployment limits `readLimit` / `mediaLimit` / `uploadLimit` / `listLimit` plus the user-preference fields — that is what the settings page writes; omit it and every field falls back to its schema default):
+3. Append this mount line to ~/.dsh/profiles/web/cordis.patch.yml (this row's `config` IS this plugin's settings form: the deployment limit `listLimit` plus the user-preference fields — that is what the settings page writes; omit it and every field falls back to its schema default. **`readLimit` / `mediaLimit` / `uploadLimit` were removed in v0.26.0**: upload, download, the HTML preview and archive packing all stream now, so there is no size limit left to configure. A retired key left in an old profile is silently ignored as an unknown field rather than rejected):
- insert:
- id: better-sidebar
name: 'dsh-better-sidebar'
config:
- readLimit: 524288
+ listLimit: 1000
4. Run pnpm install in ~/.dsh/profiles/web
5. Restart DSH and hard-refresh
```
diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md
index 1d367b54..46e9a74f 100644
--- a/docs/external-plugin-guide.md
+++ b/docs/external-plugin-guide.md
@@ -514,19 +514,25 @@ interface FileViewerProps {
path: string
title: string
viewerId: string // 命中 viewer 的 id(如 'code' / 'my-plugin:csv')
- content?: string // fetchStrategy='fsRead' 时
- truncated?: boolean // fetchStrategy='fsRead' 时
+ content?: string // fetchStrategy='fsRead' 时;超过编辑上限的文件不带它
+ size?: number // 本次读取量到的文件字节数
+ largeFile?: { size: number } // 见下方「超大文件」
mtimeMs?: number // fetchStrategy='fsRead' 时:本次读取的磁盘 mtime(保存冲突基线)
mediaUrl?: string // fetchStrategy='mediaUrl' 时
customData?: unknown // fetchStrategy='custom' 时(load() 的返回值)
// 以下为内置文本编辑器与 EditorHost 内部协作字段,外部 viewer 忽略:
toolbar?: 'self' | 'host'
+ visible?: boolean // 本 tab 是否在屏(原生 tab 停驻时仍挂载)
onToolbarState?: (state: EditorToolbarState) => void
onToolbarControls?: (controls: EditorToolbarControls | null) => void
onReload?: () => void // 从磁盘重新加载(保存冲突横幅的按钮回调)
}
```
+> **超大文件(v0.26.0 起,`truncated` 已被取代)**:文件超过编辑上限(5 MiB,见 `src/editor-limits.ts` 的 `MAX_EDITABLE_BYTES`)时,`fs.read` 不再回一份被截断的文档,而是 `{ kind: 'too-large', size, mtimeMs, head }` —— **不带 `content`**。宿主把这个结果交给命中的 viewer 时,`content` 缺席、`largeFile: { size }` 到位(见 `planFsReadOutcome`)。内置的文本 viewer 据此渲染只读分页预览(`LargeFileView`),并提供下载出口;**你的 viewer 必须容忍 `content === undefined`**:要么自己处理 `largeFile`(分页预览 / 提示),要么把状态回给 `onToolbarState` 让宿主收起保存按钮。旧的 `truncated` 布尔字段与 `EditorToolbarState.truncated` 都已删除——「拿到半份文档但看起来能编辑」这个状态本身没有了,这正是它被删掉的原因(#732:保存半份文档会毁掉文件尾部)。
+>
+> **分页读取**:`fs.readPage({ sessionId, cwd?, path, offset })` 按字节窗口返回一页文本(宿主按行对齐,并在同一个文件内锁定宽字符编码),返回 `{ kind:'text', text, offset, nextOffset, eof, size, mtimeMs, encoding }`。字节偏移只能向前推进,因此客户端能回看**已访问**的页、并向后取下一页,但不能直接跳到末尾——随机访问需要打开时先扫全文件建索引,而那正是分页要避免的开销。
+
> **模型改完文件后的自动刷新(#855)**:`EditorHost` 订阅插件自有的会话事件增量流(`changes.ops`,**每会话一个共享轮询器**,2.5s 增量、无事件不落盘读),当**当前会话**的某次 `write` / `edit` 工具调用**结算成功**且路径命中本页文件时,自动重跑一次加载——即把页头的刷新按钮变成自动的(走同一条 `fetchStrategy` / `load()` 路径,`mtimeMs` 基线语义不变;命中判定用 `resolveSidebarPath` 把模型写的相对路径按会话 cwd 归一)。对第三方 viewer 有两条含义:① 你**什么都不用做**就会拿到新内容;② 若你的 viewer 持有**未保存的草稿**,必须在 `onToolbarState` 里如实上报 `dirty: true`——dirty 时自动刷新会跳过(脏态优先,绝不覆盖用户输入);未上报 dirty 的 viewer 会被重挂(页面内 state 丢失、`content` 换成新字节)。处于编辑态的 viewer 同理应上报 `mode: 'edit'`(那条也会跳过,免得光标跳走)。**跳过不等于死路**:**未 dirty** 时既有的「编辑 → 预览」边沿照旧重载并拿到新内容(实测 `fsRead` 1→2);**dirty 时这条边沿自身也被守卫抑制**(它的实现同样要求 `dirty !== true`,`EditorHost` 的边沿判定),此时用户的两条显式出口是**页头刷新按钮**(`window.confirm` 后重载)与**「保存 → `fs-conflict` 横幅里的 reload」**(保存带 `mtimeMs` 基线,模型写过就被拒成 `fs-conflict` 而不是静默覆盖模型字节)。一句话:**dirty 期间保持旧内容直到用户显式动作,不存在看不到新内容的死路**。
### 5.3 `fetchStrategy` 对照
@@ -534,7 +540,7 @@ interface FileViewerProps {
| 策略 | 字节来源 | 传给 component 的字段 | 适用 |
|---|---|---|---|
| `none` | 不需要字节 | (无) | 自渲染(如纯 UI) |
-| `fsRead` | `/sidebar/api` 的 `fs.read` | `content`, `truncated` | 文本类(CSV/JSON/XML) |
+| `fsRead` | `/sidebar/api` 的 `fs.read`(超大文件转 `fs.readPage` 分页) | `content`, `size`, `largeFile` | 文本类(CSV/JSON/XML) |
| `mediaUrl` | `/sidebar/file` 媒体路由 URL | `mediaUrl` | 图片/PDF(viewer 自己 fetch 字节) |
| `custom` | viewer 的 `load()` 函数 | `customData` | 自定义协议(如远程拉取) |
| `binary-download` | 不预览,显示下载按钮 | (无) | 无客户端渲染器的二进制格式。**本插件现在没有任何内置 viewer 用这条策略**(`binary-download` viewer 已让给宿主);策略本身仍在契约里,你的 viewer 可以照用 |
@@ -640,8 +646,9 @@ const { value } = await res.json() // 错误时 { ok: false, error: { code, me
| `session.cwd` | 会话权威 cwd(`{ cwd, root, parent }`) |
| `fs.tree` / `fs.trees` | 目录列表(`{ path, entries: FsEntry[], truncated }`;FsEntry 含 `isSymlink`/`broken`,目录软链接的 `isDir` 按目标类型;请求可带 `exclude` 模式串,行上可带 `compact` 标记——单目录链由 client 折叠为面包屑行,匹配条目从列表与折叠探测中彻底移除)。`fs.trees` 是批量版(文件树的真实入口,同样吃 `exclude`) |
| `fs.trees` | **批量**目录列表(v0.23.0+):入参 `{ sessionId, cwd?, paths: string[] }`(最多 64 条,绝对或会话相对),一次请求返回 `{ levels: [{ path, entries, truncated, error? }] }`。每层与 `fs.tree` 同解析、同缓存;**某一层失败只在该层带 `error`**(`entries: []`),整个批次仍是成功响应——树的一次挂载/刷新因此是 1 个请求而不是 N 个 |
-| `fs.read` | 读文件:文本返回 `{ kind: 'text', content, truncated, mtimeMs }`;二进制返回 `{ kind: 'binary', size, truncated, mtimeMs, head }`(head = base64 前 4KB;`mtimeMs` = 本次读取的磁盘 mtime,保存冲突基线) |
-| `fs.write` | 原子写文件:`{ path, content, expectedMtimeMs? }`。带 `expectedMtimeMs` 时是乐观并发门——磁盘 mtime 与基线不符则拒绝(409,wire 错误码 `fs-conflict`),不覆盖对方字节;省略则不做门禁。成功返回 `{ ok: true, mtimeMs }`(新基线) |
+| `fs.read` | 读文件(v0.26.0 起三态):文本 `{ kind: 'text', content, size, mtimeMs }`;二进制 `{ kind: 'binary', size, mtimeMs, head }`;**超过编辑上限**(5 MiB)`{ kind: 'too-large', size, mtimeMs, head }`(head = base64 前 4KB,用于 `detect` 重匹配;`mtimeMs` = 本次读取的磁盘 mtime,保存冲突基线)。**不再有 `truncated` 文本读**——截断文档既不可信也不能保存(#732),超大文件改走 `fs.readPage` 分页预览 |
+| `fs.readPage` | 大文本文件的分页读取(v0.26.0+):`{ sessionId, cwd?, path, offset }` → `{ kind:'text', text, offset, nextOffset, eof, size, mtimeMs, encoding }`。窗口按行对齐(调用方可以直接当作整行/整条记录处理),单个超长行原样返回而不是空页;`nextOffset` 必然前进,`eof` 精确 |
+| `fs.write`(**已移至 raw 路由**) | v0.26.0 起保存走 `POST /sidebar/write?sessionId=&cwd=&path=&expectedMtimeMs=`,**请求体就是 LF 文档**(不再走 JSON,因此不再受 `/sidebar/api` 的 1 MiB body 上限约束);响应仍是 `{ ok: true, value: { ok: true, mtimeMs? } }` 信封。语义不变:`expectedMtimeMs` 是乐观并发门,磁盘 mtime 与基线不符则拒绝(409,wire 错误码 `fs-conflict`),省略则不做门禁;宿主在写盘前按磁盘现状还原文件的行尾与字节编码(`restoreEol` + `encodeText`) |
| `git.status` / `git.diff` / `git.log` 等 | 全套 Git 只读 + 写操作 |
| `pty.close` / `agent-pty.close` | **已删除**(插件自带的 PTY 栈随终端一起移除;宿主 `ui-sidebar-terminal` 不通过本插件的路由暴露控制面) |
| `settings.get` / `settings.update` | 侧边栏偏好读写(revision 守卫,冲突回 wire 错误码 `settings-conflict`);后端在 0.1.7 上就是宿主的 `SettingsForms`,见 §8.2 |
@@ -659,11 +666,14 @@ const route = (path: string): string => ctx.betterSidebar.hostRouteUrl(path)
// 1) 启动:paths 是会话命名空间里的绝对路径(与 fs.tree 的行 path 同形)
const build = await fetch(route('sidebar/api/archive.build'), {
method: 'POST', headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ sessionId, cwd, paths: ['/w/src', '/w/notes.md'], name: '报告.zip' }),
+ body: JSON.stringify({ sessionId, cwd, paths: ['/w/src', '/w/notes.md'], name: '报告' }),
}).then(r => r.json())
-// → { ok: true, value: { id: 'ar-…', entries: 5 } }
+// → { ok: true, value: { id: 'ar-…', name: '报告.zip', entries: 2 } }
+// name 是**最终**下载名:调用方只给词干,扩展名由宿主实际可用的工具决定
+// (只有 tar 的机器产出 .tar.gz)
-// 2) 轮询:state 为 building | ready | error;done/total 是条目进度,bytes 是已读未压缩字节
+// 2) 轮询:state 为 building | ready | error;bytes 是临时文件已写入的字节数
+// (v0.26.0 起没有 done/total:打包交给系统的 zip/tar 子进程,它不报逐条目进度)
const status = await fetch(route('sidebar/api/archive.status'), {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ id: build.value.id, sessionId }),
@@ -673,7 +683,14 @@ const status = await fetch(route('sidebar/api/archive.status'), {
const url = route(`sidebar/archive?${new URLSearchParams({ sessionId, id: build.value.id })}`)
```
-约束与状态码:任务表最多 **4 个并发构建**(超出时 `archive.build` 回 `bad-request`,HTTP 409),完成/失败后保留 **5 分钟**(过期即消失);`id` 只对**创建它的 session** 可用(其他 session 读是 `forbidden` 403);`/sidebar/archive` 在构建中回 **409**、构建失败回 **410**(消息即失败原因)、未知/过期/已下载回 **404**。响应头为 `content-type: application/zip` + `content-disposition: attachment; filename=""; filename*=UTF-8''<百分号编码>`(非 latin1 文件名走 RFC 5987,ASCII 档位对旧客户端生效)。上限沿用 `src/zip.ts` 的 `ZIP_MAX_ENTRIES = 10_000` 与 `ZIP_MAX_BYTES = 256 MiB`(未压缩总量)。
+约束与状态码:任务表最多 **4 个并发构建**(超出时 `archive.build` 回 `bad-request`,HTTP 409),完成/失败后保留 **5 分钟**(过期即消失);`id` 只对**创建它的 session** 可用(其他 session 读是 `forbidden` 403);`/sidebar/archive` 在构建中回 **409**、构建失败回 **410**(消息即打包工具的 stderr 尾部)、未知/过期/已下载回 **404**。响应头为 `content-type: application/zip`(只有 tar 时为 `application/gzip`)+ `content-disposition: attachment; filename=""; filename*=UTF-8''<百分号编码>`(非 latin1 文件名走 RFC 5987,ASCII 档位对旧客户端生效)。
+
+**v0.26.0 起打包交给系统命令,不再由本插件自己写 ZIP**(`src/zip.ts` 已删除,随之消失的是 `ZIP_MAX_ENTRIES` / `ZIP_MAX_BYTES` 两道上限——因此打包不再有大小限制):
+
+- 工具按 `zip` → `tar` 顺序探测(`src/archive-tools.ts`,结果按进程缓存)。`zip` 恒带 `-y`:不加它会**跟随**符号链接,一个 `a -> .` 的自指环会一直递归;`-y` 把链接本身存进包,既不会成环也更忠实。Windows 10 1803+ 自带 `tar.exe` 而没有 `zip`。
+- 入参是绝对路径,宿主取它们的**最深公共祖先**作为工作目录、把相对名交给工具——同一目录下的选择按 basename 入包,不同目录的同名文件自然落在各自父目录下(旧版「逐段长出父目录直到不重名」的算法因此不再需要)。选择本身等于公共祖先时祖先上移一级;选中文件系统根会被 `bad-request` 拒绝。
+- 命令的 stdout 直接写进 OS 临时目录里的临时文件,**从不整包进内存**;下载时 `createReadStream` 流式下发,流结束后才删除临时文件。插件的 teardown 会杀掉仍在跑的构建并清掉临时文件。
+- **两种工具都没有时**:`archive.build` 立刻回 wire 错误码 **`unavailable`**(HTTP 501),客户端把它显示成一句可操作的中文/英文提示,而不是把英文 wire 文本原样抛出。
媒体/下载字节走 `/sidebar/file` 路由(`?sessionId=&path=&cwd=&download=1`):
diff --git a/docs/plans/2026-10-11-streaming-transfer-jsonl-preview.md b/docs/plans/2026-10-11-streaming-transfer-jsonl-preview.md
new file mode 100644
index 00000000..98aafc23
--- /dev/null
+++ b/docs/plans/2026-10-11-streaming-transfer-jsonl-preview.md
@@ -0,0 +1,126 @@
+# 流式传输、原生打包、JSONL 预览与大文件分页预览
+
+日期:2026-10-11
+状态:已实施
+分支:`feat/streaming-transfer-jsonl`(从 `dev` 切出)
+
+---
+
+## 1. 起因
+
+三件看似无关、实则同一个根因的事:
+
+1. **上传/下载有大小限制。** 上传其实早就端到端流式(`for await (chunk of req)` → 临时文件 → rename,见 `src/fs-operations.ts`),真正挡路的是两处 128 MB 常量;下载则整条路径都是 `readFile` → `res.end(buffer)`,配一道 20 MB 的 `mediaLimit` —— 大到足以让一个第三方插件(`dsh-video-preview`)把自己的存在理由写成「不受 20MB mediaLimit 限制」。
+2. **`.jsonl` 完全没有支持。** `src/client/lang.ts` 没有映射,所以 JSONL 是纯白文本;而宿主 `dsh-util-code-language` 早就把 `jsonl`/`ndjson` 归到 JSON 了。更要命的是,直接映射到 `json()` 也不对——`@lezer/json` 的文法只接受**一个**顶层值,实测一个 400 条记录的文件会解析出 402 个错误节点。
+3. **编辑器只有「全读」和「截断」两档。** 超过 `readLimit`(512 KiB)的文件被截成半份、标成只读、禁用保存。那个状态本身就是 #732 的成因:保存半份文档会毁掉文件尾部,所以只能禁止保存 —— 于是「能打开的文件存不回去」。
+
+## 2. 设计
+
+### 2.1 传输:不再有大小限制
+
+**上传**只删掉了两道闸(客户端的 `MAX_UPLOAD_BYTES` 预检与宿主的逐块 `limit` 检查),流式核心、临时文件、失败清理一字未动。
+
+**下载**新增 `src/file-stream.ts` 的 `streamFileToResponse`,`/sidebar/file` 与 `/sidebar/html` 改用它。关键不在 `createReadStream` + `pipeline`(那是常规做法),而在**写响应头的时机**:
+
+```
+open(stream) → await 'open' → writeHead(200) → pipeline(stream, res)
+```
+
+`writeHead` 会提交响应。先等 `'open'`,ENOENT / EACCES / EISDIR 就都发生在提交之前,仍然能变成插件自己的 JSON 错误信封;提交之后再失败(文件被换掉、客户端断开)就只能 `destroy()` —— 半条连接是唯一诚实的信号。配套给 `wire.ts` 的 `writeJson` 加了 `headersSent` 早退守卫:流中途失败时,路由的 catch 块会调 `writeError`,而后者会 `writeHead`,在已提交的响应上抛 `ERR_HTTP_HEADERS_SENT`,把一次「下载被截断」升级成「请求崩溃」。
+
+`content-length` 取同一次 `stat` 的 `size`:浏览器的下载进度条需要它。
+
+### 2.2 打包:交给系统命令
+
+`src/zip.ts`(手写 ZIP:本地文件头、中央目录、CRC-32、原始 DEFLATE,约 300 行)被删除,换成 `src/archive-tools.ts`:
+
+- 工具按 `zip` → `tar` 探测,结果按进程缓存。`zip` **恒带 `-y`**:不加它会**跟随**符号链接,一个 `a -> .` 的自指环会一直递归下去(实测过);`-y` 把链接本身存进包。`tar` 是 Windows 的退路(10 1803+ 自带 `bsdtar`,而没有 `zip`)。
+- `cwd` 取所有选择的**最深公共祖先**,参数是相对该目录的 `/` 分隔名。这替掉了旧版「按 basename 命名、冲突就逐段长出父目录」的算法:相对公共祖先的路径天然唯一,冲突消歧从一道算法变成了布局的性质。
+- stdout 直接重定向到 OS 临时目录里的临时文件(`stdio: ['ignore', fd, 'pipe']`),**从不整包进内存**。
+
+**为什么坚持「后台构建 → 轮询 → 一次性下载」而不是直接把 stdout 管到响应里**(后者代码更少):直接管道意味着命令写到一半失败时,状态行早已提交,浏览器拿到的是一个 200 + 半份 zip,用户只会发现解压失败。写临时文件让「工具不存在 / 路径非法 / 退出码非 0」全部在下载开始前落地,正好保住现有那六个错误分支的语义。
+
+代价说清楚:**`archive.status` 不再有 `done/total`**。子进程不报逐条目进度,而临时文件的大小是唯一的现成信号,所以状态收缩成 `{ state, bytes }`,界面退化为一句「打包中…」。凭空造一个条目计数意味着为了显示而多走一遍目录树。
+
+### 2.3 保存:拆掉 1 MiB 的墙
+
+`fs.write` 走 JSON,而 `/sidebar/api` 的 `MAX_BODY_BYTES = 1 MiB` 是硬顶 —— 所以 >1 MiB 的文件根本存不回去,512 KiB 的 `readLimit` 正是压在它下面。保存改为 `POST /sidebar/write` 的 **raw 路由**(文档即请求体),编码与行尾还原逻辑整体搬进 `src/fs-operations.ts` 的 `writeWorkspaceText`,一字未改。
+
+宿主侧仍然把这 ≤5 MiB 的文档整份读进内存:`encodeText` 是整串编码(GBK 用一张表、UTF-16 需整串),而文档本身被编辑上限封住。这里要消除的是 1 MiB 的墙,不是 5 MiB 的缓冲;真正无界的只有上传。
+
+### 2.4 读取:三态取代「截断」
+
+`fs.read` 从 `{content, truncated, binary, head?}` 变成判别联合:
+
+```
+| { kind: 'text'; content, size, mtimeMs }
+| { kind: 'binary'; size, mtimeMs, head }
+| { kind: 'too-large'; size, mtimeMs, head }
+```
+
+超过 `MAX_EDITABLE_BYTES`(5 MiB,`src/editor-limits.ts`)时只读前 4 KiB:判不出文本就是 `binary`(图片/office/PDF 的 media 路径**完全不变**),是文本就是 `too-large`,并带上 head 让 `detect` 类外部 viewer 仍有机会认领。
+
+**「截断」这个状态被彻底删掉**,包括 `FileViewerProps.truncated`、`EditorToolbarState.truncated` 与 `truncation` 文案键。理由:#732 的教训是「拿到半份文档但看起来能编辑」本身就是缺陷状态 —— 既不可信又不能保存。要么给全,要么明确说不给。
+
+`fs.readPage` 按字节窗口分页:窗口**回退到最后一个换行**,所以一页是整数行(对 JSONL 就是整数条记录);整页没有一个换行(超长单行)时原样返回,否则「下一个」会停在一个永不前进的偏移上。
+
+### 2.5 分页的编码一致性(一处只有实测才会发现的坑)
+
+第一版实现**锁死第一页嗅探到的编码**,理由是「避免同一个文档前后用两种编码解码」。这在真机上错得很具体:
+
+- 「长 ASCII 前缀 + GBK 正文」的文件,第一页纯 ASCII → 嗅探成 UTF-8 并锁死 → 后半段 GBK 字节按 UTF-8 解 → 乱码。而一次性全读(旧行为)是能正确解出来的,所以这是一个**新引入的回归**。
+- 修正后的规则:**只锁宽字符编码**。宽编码(UTF-16/UTF-32)是文件的属性,一页恰好没有 NUL 字节不能重新裁决它(BOM-less UTF-16 的探测是看 NUL 的分布,而一段纯 CJK 的 UTF-16LE 几乎没有 NUL);字节序编码(UTF-8 / GBK / GB18030)则逐页各自嗅探 —— 纯 ASCII 的页在两种编码下解出来是同一个字符串,有非 ASCII 的页则会被正确识别。
+
+逐页嗅探在这里是安全的,因为**分页按行对齐**:`0x0A` 既不能是 UTF-8 的续字节,也不能是 GBK 的尾字节,所以窗口边界永远不会切断一个字符。(`lastLineBreakEnd` 还要再处理宽编码:UTF-16LE 下 `U+0A41` 的低字节就是 `0x0A`,朴素的 `lastIndexOf(0x0A)` 会把字符切两半。)
+
+### 2.6 JSONL:自己的语言 + 记录预览
+
+- **语言**:`src/client/lang-jsonl.ts` 是一个手写的 `StreamLanguage`,一行一次 JSON 词法分析。不携带跨行状态(JSONL 的记录按定义互相独立),未闭合的字符串直接标 `invalid`(一行一条记录,所以这是**可证**的)。没有复用语法的代价:不检查重复键、不做结构校验 —— 词法分析器不是语法分析器,越界只会产出假错误。
+- **描述符**:新增第 4 个内置 viewer `jsonl`(`exts: ['jsonl','ndjson']`、priority 0),而不是塞进 `code` 兜底 —— 这样外部插件可以按格式精确遮蔽,设置页也能单独开关。
+- **预览**:`src/client/LargeFileView.tsx` 一条记录一行,默认折叠成一行摘要(`summarizeRecord` 把第一层内联、更深的用 `{…}`/`[…n]` 省略),点击才展开宿主的 `JsonTree`。一页最多几百行、只对展开项建树,所以渲染成本有界。
+- **编辑**:`mode` 切到 `edit` 就是原来的可保存 CodeMirror(带 jsonl 语言与未提交变更 gutter),仅在 ≤5 MiB 时提供。
+
+### 2.7 大文件:只读分页预览
+
+超过编辑上限的文件不再拒绝打开,而是进入 `LargeFileView` 的只读模式:通用文件是等宽行列表(不换行、横向滚动,日志查看器的形态),JSONL 是记录卡片列表。两者共用 `src/client/text-pages.ts` 的分页游标,内存与文件大小无关。
+
+**游标模型的诚实限制**:字节偏移只能向前累积,所以能回看**已访问**的页、能取下一页,但**不能跳到末尾**,也在读到结尾前不知道总页数。随机访问需要在打开时扫全文件建索引,而那正是分页要避免的开销。读到 EOF 后总页数自然确定。
+
+### 2.8 打包下载:改回直链
+
+客户端的 `saveArchive` 从 `fetch → blob → objectURL` 改成普通 `` 指向路由 URL。Blob 会把整包放进**标签页**的内存 —— 宿主侧刚刚为超过这个而改成流式,客户端再缓冲一次就把收益抵消了。
+
+代价也记在这里:无法再检查路由的 JSON 错误信封,所以这一步失败会把一个 JSON 体存成存档名。但所有现实中的失败(工具缺失、选择不可读、工具退出码非 0)都在 `archive.status` 轮询阶段被拦下,剩下的只有「轮询到点击之间任务被消费或过期」。
+
+## 3. 与 VS Code Web 的对照
+
+用户要求参考 VS Code Web 的做法。研究结论(源码 + 已安装 1.141.0 产物双向核对):
+
+- **VS Code 不分页。** `TextModel` 用 piece tree 装整份文档,没有行窗口或 limit 参数。
+- 真正的模型是**阈值 + 确认 + 降级**:`getLargeFileConfirmationLimit()`(`isWeb` → **50 MB**)→ 超阈值在编辑器区显示占位符「The file is not displayed in the text editor because it is very large.」+ **Open Anyway**(`limits: {size: MAX_VALUE}`)+ **Configure Limit**(设置项 `workbench.editorLargeFileConfirmation`)。
+- 阈值以下但 >20 MB 或 >300k 行 → `editor.largeFileOptimizations` 在**模型构造时永久**关掉 tokenization 以及一切 token 派生的特性。
+- 唯一接近流式的是 Output/日志面板:`readFile(resource, { position: endOffset })` 增量尾读追加到模型里。
+- 顺带纠错:常被引用的 `files.maxMemoryForLargeFilesMB` **不存在**(1.141.0 产物零命中,`files.contribution.ts` 里也没有)。
+
+**采纳**:阈值 + 超限降级为只读;大文件不装作能高亮(分页预览天然没有高亮,与 VS Code 一致);上限取用户给的 5 MiB(VS Code 的 web 阈值是 50 MB,但那是**确认**阈值而非编辑阈值,两者不是一回事)。
+**有意偏离**:VS Code 直接拒绝打开超限文件,我们按用户要求做分页,让大日志**能看**。这与 VS Code Output 面板的 offset 增量读是同一路数。
+
+## 4. 实施偏差与代价(如实记录)
+
+1. **`data-` 前缀之外的一处未预期发现**:`archive.status` 的进度语义无法保留(见 §2.2),这是「交给系统命令」的必然代价,不是实现偷懒。
+2. **分页的编码锁第一版是错的**(见 §2.5),真机测试才发现;已修正并补上双向用例(长 ASCII 前缀 + GBK 正文,以及纯 CJK 的 UTF-16 页)。
+3. **JSONL 词法分析器第一版有死循环**:`StringStream.next()` 在行尾返回 `undefined` 而不是 `null`,未闭合字符串的分支因此无限追加直到 `RangeError: Invalid string length`。测试用例直接抓到了它。
+4. **`stat` 失败从 500 变 400**:两条字节路由原先让 `stat` 的原始 rejection 逃成 500「internal」,读起来像插件故障;不可读的用户路径是 400。smoke 里一条把 500 写进断言的用例随之更新。
+5. **`tags.invalid` 从纯白改成红色波浪线**:`invalid` 是 JSON/JSONL 语法错误落到的 token,而它在深浅两种配色下都是 `#ffffff` —— 浅色主题下就是白底白字,读者看不见哪里没解析。
+6. **保留 `uploadTooLarge` 文案**:`too-large` 这个 wire 码在契约里还在(`SidebarErrorCode`),展示映射留着比删掉 21 份词典的一行更有价值。
+7. **`readLimit` / `mediaLimit` / `uploadLimit` 三个配置键删除**,旧 profile 里残留的值由 schemastery 当未知键容忍(与 `workspaceFence` 同一条先例)。`listLimit` 保留 —— 它是浏览器行数上限,与传输无关。
+
+## 5. 测试守护
+
+- `tests/file-stream-route.spec.ts`:真 `node:http` 下发 21 MiB(旧 `mediaLimit` 之上)、`content-length`、`?download=1` 的 RFC 5987、SVG 的 CSP、**不可读文件仍是 4xx JSON 信封**(证明头是在 open 之后才写的)、客户端中途断开的存活、`writeJson` 的 `headersSent` 守卫。
+- `tests/fs-read-page.spec.ts`:单页/多页重组逐字节相同、页按行对齐、超长单行不被裁空、EOF 精确、偏移缺省与越界、**两种编码场景**(长 ASCII 前缀 + GBK 正文;纯 CJK 的 UTF-16 页)。
+- `tests/jsonl-language.spec.ts`:400 条记录零错误节点(`json()` 是 402 个)、坏行不溢出到后一行、词法分析器**不**为「缺失的结构」编造错误、属性名与字符串值的区分(含负例)、未闭合字符串、超长单行。
+- `tests/jsonl.spec.ts`:`.jsonl`/`.ndjson` 的扩展判定(`.json` 不claim)、逐行解析、空行是「跳过」而不是「损坏」、摘要的第一层内联与省略、单行长度上限。
+- `tests/fs-write-route.spec.ts`:并发保存、mtime 冲突、CRLF/LF/GBK+CRLF 还原,以及**远超旧 1 MiB JSON 上限的一次保存**。
+- `tests/archive-tools.spec.ts` / `tests/archive.spec.ts`:argv 规划(含 `-y`)、公共祖先与上移、根拒绝、扩展名归一、注入式 spawn 的探测顺序与缓存、stderr 尾部、六个错误分支、并发上限、TTL、下载消费任务并删除临时文件、`dispose()` 杀子进程、以及**唯一一条真二进制用例**(自探测、缺席即跳过)。
+- `tests/editor-large-file.spec.tsx`:超限进入只读分页预览 + 下载出口 + 无 CodeMirror + 无保存按钮,并有「可编辑时确实有保存按钮」的反证。
diff --git a/src/client/jsonl.ts b/src/client/jsonl.ts
index 248cdaa4..9916a597 100644
--- a/src/client/jsonl.ts
+++ b/src/client/jsonl.ts
@@ -98,8 +98,3 @@ function preview(value: unknown): string {
if (typeof value === 'object') return '{…}'
return JSON.stringify(value) ?? String(value)
}
-
-/** Clamp a summary to one scannable line. */
-function truncate(text: string): string {
- return text.length <= SUMMARY_MAX ? text : `${text.slice(0, SUMMARY_MAX - 1)}…`
-}
diff --git a/src/index.ts b/src/index.ts
index 7be6d05d..1e601930 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -90,9 +90,8 @@ export type {
FileViewerProps,
FileFetchStrategy,
} from './client/service.ts'
-// The archive naming helper is exercised directly by the archive specs:
-// their bounds live inside the collector, so the suite needs them observable
-// without creating 10 000 rows first.
+// The archive disposition helper is exercised directly by the archive specs:
+// the RFC 5987 header shape is its own contract, testable without a mount.
export { contentDispositionOf } from './archive-route.ts'
/** Plugin identity for cordis.yml rows. */
export const name = 'dsh-better-sidebar'
diff --git a/tests/archive-client.spec.ts b/tests/archive-client.spec.ts
index c48f4829..64dec00f 100644
--- a/tests/archive-client.spec.ts
+++ b/tests/archive-client.spec.ts
@@ -5,10 +5,16 @@
* `archiveStatus` posted a bare `{ id }` while the host requires
* `requireString(payload, 'id')` AND `requireString(payload, 'sessionId')` —
* a 400 on every poll, so the download never happened. The unit specs for the
- * tree mock this module wholesale, and `tests/zip.spec.ts` drives the HOST side
- * with hand-built payloads, so nothing covered what the client actually sends.
- * These cases run the real module against a stubbed `fetch` and assert the
- * request bodies, including the session scope on every archive call.
+ * tree mock this module wholesale, and `tests/archive.spec.ts` drives the HOST
+ * side with hand-built payloads, so nothing covered what the client actually
+ * sends. These cases run the real module against a stubbed `fetch` and assert
+ * the request bodies, including the session scope on every archive call.
+ *
+ * The shapes come from the host: `archive.build` answers `{id, name, entries}`
+ * — `name` is the FINAL name, because the host appends the extension of the
+ * tool it actually has — and the client therefore posts a STEM. `archive.status`
+ * answers `{state, bytes}` only: the system `zip`/`tar` reports no per-entry
+ * progress, so there is no `done`/`total` left to carry.
*/
import './browser-globals.ts'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -41,17 +47,22 @@ afterEach(() => {
describe('archive client payloads', () => {
it('posts the session scope on archive.status (the host requires BOTH keys)', async () => {
- const posted = stubFetch({ state: 'ready', done: 1, total: 1, bytes: 8 })
- await expect(archiveStatus(scope, 'job-1')).resolves.toEqual({ state: 'ready', done: 1, total: 1, bytes: 8 })
+ // The exact new shape: a module still answering `done`/`total` fails here.
+ const posted = stubFetch({ state: 'ready', bytes: 8 })
+ await expect(archiveStatus(scope, 'job-1')).resolves.toEqual({ state: 'ready', bytes: 8 })
expect(posted).toEqual([{ url: 'http://localhost/sidebar/api/archive.status', body: { sessionId: 's1', cwd: '/w', id: 'job-1' } }])
})
- it('carries the scope on archive.build, plus the selection and the name', async () => {
- const posted = stubFetch({ id: 'job-2', entries: 2 })
- await expect(archiveBuild(scope, ['/w/a.ts', '/w/b.ts'], 'archive.zip')).resolves.toEqual({ id: 'job-2', entries: 2 })
+ it('carries the scope on archive.build, plus the selection and the STEM', async () => {
+ // The caller names a STEM and the host answers with the final name (it has
+ // only `tar`, so the extension is `.tar.gz`). The client posts the stem
+ // VERBATIM — appending a guessed suffix here would be a lie.
+ const posted = stubFetch({ id: 'job-2', name: 'selection.tar.gz', entries: 2 })
+ await expect(archiveBuild(scope, ['/w/a.ts', '/w/b.ts'], 'selection'))
+ .resolves.toEqual({ id: 'job-2', name: 'selection.tar.gz', entries: 2 })
expect(posted).toEqual([{
url: 'http://localhost/sidebar/api/archive.build',
- body: { sessionId: 's1', cwd: '/w', paths: ['/w/a.ts', '/w/b.ts'], name: 'archive.zip' },
+ body: { sessionId: 's1', cwd: '/w', paths: ['/w/a.ts', '/w/b.ts'], name: 'selection' },
}])
})
@@ -61,7 +72,7 @@ describe('archive client payloads', () => {
})
it('omits an empty cwd but never the sessionId', async () => {
- const posted = stubFetch({ state: 'building', done: 0, total: 1, bytes: 0 })
+ const posted = stubFetch({ state: 'building', bytes: 0 })
await archiveStatus({ sessionId: 's2', cwd: '' }, 'job-3')
expect(posted[0]?.body).toEqual({ sessionId: 's2', id: 'job-3' })
})
diff --git a/tests/archive-tools.spec.ts b/tests/archive-tools.spec.ts
new file mode 100644
index 00000000..73106b28
--- /dev/null
+++ b/tests/archive-tools.spec.ts
@@ -0,0 +1,497 @@
+/**
+ * archive-tools: the system's own zip/tar behind the file tree's archive action.
+ *
+ * This module replaced the hand-written ZIP encoder, so the old byte-level
+ * reader is gone with it — there is nothing of OURS left to inflate. What is
+ * worth pinning is the PLAN (where the tool runs and what argv it gets), the
+ * NAME the client ends up with, the tool PROBE (which binary answers), and how
+ * ONE run reports success, failure and stderr.
+ *
+ * Every case here injects the spawn face: `zip` does not exist on Windows
+ * (bsdtar does), the ubuntu runner is not guaranteed either, and a spec that
+ * spawned for real would fail at collection time on one platform while staying
+ * green locally forever (AGENTS §6). Exactly ONE case drives a real binary —
+ * it self-probes and returns early when neither tool is installed.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { EventEmitter } from 'node:events'
+import {
+ closeSync,
+ mkdirSync,
+ mkdtempSync,
+ openSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+ writeSync,
+} from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, parse } from 'node:path'
+import { PassThrough } from 'node:stream'
+import {
+ ARCHIVE_STDERR_LIMIT,
+ ARCHIVE_STEM_MAX,
+ archiveFileName,
+ archiveTempName,
+ planArchive,
+ resetArchiveToolCache,
+ resolveArchiveTool,
+ runArchiveTool,
+ tryTools,
+ type ArchiveSpawn,
+ type ArchiveToolSpec,
+} from '../src/archive-tools.ts'
+import { SidebarError } from '../src/wire.ts'
+
+/** What one scripted child answers, per phase. */
+interface Script {
+ /** `--version` probe: the exit code, a spawn error, or no answer at all. */
+ probe?: (bin: string) => number | 'error' | 'hang'
+ /** The real invocation (the one handed the output descriptor). */
+ run?: () => RunAnswer
+}
+
+/** One scripted invocation's outcome. */
+interface RunAnswer {
+ /** Bytes the tool wrote into the caller's descriptor (the archive). */
+ bytes?: Buffer
+ /** Exit code; 'error' = the child could not start, null = killed by a signal. */
+ code?: number | 'error' | null
+ /** What the tool printed on stderr. */
+ stderr?: string
+ /** Keep running until `kill()` — the teardown case. */
+ hang?: boolean
+}
+
+/** The minimum of a ChildProcess the two consumers here touch. */
+type FakeChild = EventEmitter & { stderr: PassThrough; kill: ReturnType }
+
+/** One recorded spawn, for argv/cwd/descriptor assertions. */
+interface SpawnCall {
+ bin: string
+ args: string[]
+ stdio: unknown
+ fd?: number
+}
+
+/**
+ * A scripted `spawn`, never a real binary.
+ *
+ * The probe is told apart from the run the way the module does it: a probe is
+ * spawned with `stdio: 'ignore'`, a run with the caller's descriptor.
+ */
+function scriptedSpawn(script: Script): { spawner: ArchiveSpawn; calls: SpawnCall[]; children: FakeChild[] } {
+ const calls: SpawnCall[] = []
+ const children: FakeChild[] = []
+ const spawner = ((bin: string, args: readonly string[], options: { stdio?: unknown }): FakeChild => {
+ const child = new EventEmitter() as FakeChild
+ child.stderr = new PassThrough()
+ const fd = Array.isArray(options.stdio) ? options.stdio[1] : undefined
+ calls.push({ bin, args: [...args], stdio: options.stdio, ...(typeof fd === 'number' ? { fd } : {}) })
+ children.push(child)
+ // A killed child is one that exits BY SIGNAL: 'close' with no exit code,
+ // which is exactly what a real SIGTERM/SIGKILL looks like from here.
+ let hangs = false
+ child.kill = vi.fn(() => {
+ if (hangs) child.emit('close', null)
+ return true
+ })
+ if (options.stdio === 'ignore') {
+ const answer = script.probe?.(bin) ?? 0
+ process.nextTick(() => {
+ if (answer === 'hang') return
+ if (answer === 'error') {
+ child.emit('error', new Error(`spawn ${bin} ENOENT`))
+ return
+ }
+ child.emit('exit', answer)
+ })
+ return child
+ }
+ const run = script.run?.() ?? {}
+ hangs = run.hang === true
+ process.nextTick(() => {
+ if (hangs) return
+ if (run.stderr !== undefined) child.stderr.write(run.stderr)
+ if (run.bytes !== undefined && typeof fd === 'number') writeSync(fd, run.bytes)
+ const code = run.code === undefined ? 0 : run.code
+ if (code === 'error') {
+ child.emit('error', new Error(`spawn ${bin} ENOENT`))
+ return
+ }
+ child.emit('close', code)
+ })
+ return child
+ }) as unknown as ArchiveSpawn
+ return { spawner, calls, children }
+}
+
+/** Run `fn` and hand back what it threw (SidebarError assertions read better this way). */
+function capture(fn: () => unknown): unknown {
+ try {
+ fn()
+ return undefined
+ } catch (error: unknown) {
+ return error
+ }
+}
+
+/** A platform-native absolute root that does not have to exist: planning is pure path math. */
+const PLAN_ROOT = join(parse(tmpdir()).root, 'dsh-archive-plan')
+
+/**
+ * The tool spec the MODULE defines, resolved through a fake probe — so the
+ * argv assertions below pin the real flags instead of a copy of them.
+ */
+async function specOf(tool: 'zip' | 'tar'): Promise {
+ const spec = await tryTools([tool], scriptedSpawn({ probe: () => 0 }).spawner)
+ if (spec === undefined) throw new Error(`test setup: no ${tool} spec`)
+ return spec
+}
+
+/** Temp trees, removed after each test. */
+const roots: string[] = []
+function tempRoot(): string {
+ const root = mkdtempSync(join(tmpdir(), 'dsh-archive-tools-'))
+ roots.push(root)
+ return root
+}
+
+beforeEach(() => {
+ resetArchiveToolCache()
+})
+afterEach(() => {
+ resetArchiveToolCache()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ while (roots.length > 0) rmSync(roots.pop()!, { recursive: true, force: true })
+})
+
+describe('planArchive', () => {
+ it('plans one selection from its PARENT, named by its basename', async () => {
+ const spec = await specOf('zip')
+ const src = join(PLAN_ROOT, 'ws', 'src')
+ const plan = planArchive([src], spec)
+ // From the parent, so the archive carries a `src/` top-level entry rather
+ // than unpacking its contents into the download directory.
+ expect(plan.cwd).toBe(join(PLAN_ROOT, 'ws'))
+ // `-y` is not decoration: without it Info-ZIP FOLLOWS symlinks, and a
+ // `loop -> .` in the tree then recurses until the process is killed.
+ expect(plan.args).toEqual(['-r', '-q', '-X', '-y', '-', 'src'])
+ expect(plan.spec).toBe(spec)
+ })
+
+ it('plans several selections from their deepest common ancestor, "/"-separated', async () => {
+ const spec = await specOf('zip')
+ const ws = join(PLAN_ROOT, 'ws')
+ const plan = planArchive([join(ws, 'src', 'index.ts'), join(ws, 'lib', 'util.ts')], spec)
+ expect(plan.cwd).toBe(ws)
+ expect(plan.args.slice(spec.flags.length)).toEqual(['src/index.ts', 'lib/util.ts'])
+ // The separator is normalized whatever the platform produced: the tool
+ // gets in-archive names, not host paths.
+ expect(plan.args.every(arg => !arg.includes('\\'))).toBe(true)
+ })
+
+ it('steps the base up one level when a selection IS the common ancestor', async () => {
+ const spec = await specOf('zip')
+ const ws = join(PLAN_ROOT, 'ws')
+ // Selecting a folder AND something inside it would name the folder '' from
+ // its own directory, so the base moves up and both keep a component.
+ const plan = planArchive([join(ws, 'src'), join(ws, 'src', 'index.ts')], spec)
+ expect(plan.cwd).toBe(ws)
+ const names = plan.args.slice(spec.flags.length)
+ expect(names).toEqual(['src', 'src/index.ts'])
+ expect(names.every(name => name !== '')).toBe(true)
+ })
+
+ it('uses the tar invocation for a tar-only host', async () => {
+ const spec = await specOf('tar')
+ const plan = planArchive([join(PLAN_ROOT, 'ws', 'notes.md')], spec)
+ expect(plan.args).toEqual(['-czf', '-', 'notes.md'])
+ expect(plan.spec.ext).toBe('.tar.gz')
+ })
+
+ it('refuses the filesystem root, whose parent does not exist', async () => {
+ const spec = await specOf('zip')
+ const root = parse(tmpdir()).root
+ const thrown = capture(() => planArchive([root], spec))
+ expect(thrown).toBeInstanceOf(SidebarError)
+ expect(thrown).toMatchObject({ code: 'bad-request' })
+ expect((thrown as Error).message).toMatch(/filesystem root/)
+ })
+
+ it('refuses an empty selection', async () => {
+ const spec = await specOf('zip')
+ const thrown = capture(() => planArchive([], spec))
+ expect(thrown).toBeInstanceOf(SidebarError)
+ expect(thrown).toMatchObject({ code: 'bad-request' })
+ expect((thrown as Error).message).toMatch(/no paths/)
+ })
+})
+
+describe('archiveFileName', () => {
+ it('strips whatever archive suffix the caller guessed, then applies the real one', () => {
+ expect(archiveFileName('docs', '.zip')).toBe('docs.zip')
+ expect(archiveFileName('docs.zip', '.zip')).toBe('docs.zip')
+ expect(archiveFileName('docs.tar', '.zip')).toBe('docs.zip')
+ expect(archiveFileName('docs.tar.gz', '.zip')).toBe('docs.zip')
+ expect(archiveFileName('docs.tgz', '.zip')).toBe('docs.zip')
+ // The stem keeps its case, the extension is the tool's literal — a guessed
+ // `DOCS.ZIP` comes back as the real `DOCS.zip`.
+ expect(archiveFileName('DOCS.ZIP', '.zip')).toBe('DOCS.zip')
+ // The TOOL decides, not the client: the same stem on a tar-only host.
+ expect(archiveFileName('docs', '.tar.gz')).toBe('docs.tar.gz')
+ expect(archiveFileName('docs.zip', '.tar.gz')).toBe('docs.tar.gz')
+ })
+
+ it('strips separators, quotes and control characters — a name is never a path', () => {
+ expect(archiveFileName('../../etc/passwd', '.zip')).toBe('etcpasswd.zip')
+ expect(archiveFileName('a\\b".zip', '.zip')).toBe('ab.zip')
+ expect(archiveFileName("it's.zip", '.zip')).toBe('its.zip')
+ expect(archiveFileName('bad\u0000name\u001F.zip', '.zip')).toBe('badname.zip')
+ expect(archiveFileName('del\u007Fete', '.zip')).toBe('delete.zip')
+ // Kept: non-latin1 is the header encoder's problem (see contentDispositionOf).
+ expect(archiveFileName('报告', '.zip')).toBe('报告.zip')
+ })
+
+ it('falls back to `archive`, drops leading dots, and truncates the stem', () => {
+ expect(archiveFileName('', '.zip')).toBe('archive.zip')
+ expect(archiveFileName(' ', '.zip')).toBe('archive.zip')
+ expect(archiveFileName('.zip', '.zip')).toBe('archive.zip')
+ expect(archiveFileName('..zip', '.zip')).toBe('archive.zip')
+ expect(archiveFileName('...hidden', '.zip')).toBe('hidden.zip')
+ const long = archiveFileName(`${'x'.repeat(300)}.zip`, '.zip')
+ expect(long).toBe(`${'x'.repeat(ARCHIVE_STEM_MAX)}.zip`)
+ expect(long.length).toBe(ARCHIVE_STEM_MAX + 4)
+ // `.tar.gz` is one extension, applied whole.
+ expect(archiveFileName('x'.repeat(300), '.tar.gz')).toBe(`${'x'.repeat(ARCHIVE_STEM_MAX)}.tar.gz`)
+ })
+
+ it('names the temp file after the task id and the tool extension', () => {
+ expect(archiveTempName('ar-1', '.zip')).toBe('dsh-better-sidebar-ar-1.zip')
+ expect(archiveTempName('ar-2', '.tar.gz')).toBe('dsh-better-sidebar-ar-2.tar.gz')
+ })
+})
+
+describe('tool probing (injected spawn)', () => {
+ it('takes zip when zip answers exit 0 — tar is never spawned', async () => {
+ const { spawner, calls } = scriptedSpawn({ probe: () => 0 })
+ const spec = await tryTools(['zip', 'tar'], spawner)
+ expect(spec?.tool).toBe('zip')
+ expect(spec?.bin).toBe('zip')
+ expect(spec?.ext).toBe('.zip')
+ expect(spec?.flags).toEqual(['-r', '-q', '-X', '-y', '-'])
+ // `--version`, not `--help`: bsdtar's help exits non-zero on some builds.
+ expect(calls).toHaveLength(1)
+ expect(calls[0]).toMatchObject({ bin: 'zip', args: ['--version'], stdio: 'ignore' })
+ })
+
+ it('falls through to tar when zip cannot be started at all', async () => {
+ const { spawner, calls } = scriptedSpawn({ probe: bin => (bin === 'zip' ? 'error' : 0) })
+ const spec = await tryTools(['zip', 'tar'], spawner)
+ expect(spec?.tool).toBe('tar')
+ expect(spec?.flags).toEqual(['-czf', '-'])
+ expect(spec?.ext).toBe('.tar.gz')
+ expect(calls.map(call => call.bin)).toEqual(['zip', 'tar'])
+ })
+
+ it('falls through to tar when zip answers with a non-zero exit', async () => {
+ const { spawner, calls } = scriptedSpawn({ probe: bin => (bin === 'zip' ? 127 : 0) })
+ const spec = await tryTools(['zip', 'tar'], spawner)
+ expect(spec?.tool).toBe('tar')
+ expect(calls.map(call => call.bin)).toEqual(['zip', 'tar'])
+ })
+
+ it('returns undefined when neither tool answers', async () => {
+ const broken = scriptedSpawn({ probe: () => 'error' })
+ expect(await tryTools(['zip', 'tar'], broken.spawner)).toBeUndefined()
+ expect(broken.calls.map(call => call.bin)).toEqual(['zip', 'tar'])
+ resetArchiveToolCache()
+ const nonZero = scriptedSpawn({ probe: () => 1 })
+ expect(await tryTools(['zip', 'tar'], nonZero.spawner)).toBeUndefined()
+ expect(nonZero.calls.map(call => call.bin)).toEqual(['zip', 'tar'])
+ })
+
+ it('memoizes the probe for the process, and resetArchiveToolCache re-probes', async () => {
+ const first = scriptedSpawn({ probe: () => 0 })
+ expect((await tryTools(['zip'], first.spawner))?.tool).toBe('zip')
+ expect(first.calls).toHaveLength(1)
+ // The second ask is answered from the memo: no second process.
+ const second = scriptedSpawn({ probe: () => 0 })
+ expect((await tryTools(['zip'], second.spawner))?.tool).toBe('zip')
+ expect(second.calls).toHaveLength(0)
+ resetArchiveToolCache()
+ expect((await tryTools(['zip'], second.spawner))?.tool).toBe('zip')
+ expect(second.calls).toHaveLength(1)
+ })
+
+ it('gives up on a probe that never answers, and kills it', async () => {
+ vi.useFakeTimers()
+ const { spawner, children } = scriptedSpawn({ probe: () => 'hang' })
+ const pending = tryTools(['zip'], spawner)
+ // Well past any sane probe budget: the timer, not the child, ends this.
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(await pending).toBeUndefined()
+ expect(children[0]!.kill).toHaveBeenCalled()
+ })
+})
+
+describe('runArchiveTool (injected spawn)', () => {
+ it('resolves with the exit code and the stderr tail for a tool that RAN and failed', async () => {
+ const root = tempRoot()
+ const spec = await specOf('zip')
+ const plan = planArchive([join(root, 'src')], spec)
+ const out = join(root, 'out.zip')
+ const { spawner } = scriptedSpawn({ run: () => ({ code: 2, stderr: 'zip error: nothing to do\n' }) })
+ const fd = openSync(out, 'w')
+ try {
+ // A non-zero exit is a RESULT: the route turns it into an `error` task
+ // with the tool's own message, which is the point of running in the
+ // background at all.
+ await expect(runArchiveTool(plan, fd, spawner)).resolves.toEqual({
+ code: 2,
+ stderr: 'zip error: nothing to do',
+ })
+ } finally {
+ closeSync(fd)
+ }
+ })
+
+ it('rejects with a SidebarError when the child cannot be started', async () => {
+ const root = tempRoot()
+ const spec = await specOf('zip')
+ const plan = planArchive([join(root, 'src')], spec)
+ const out = join(root, 'out.zip')
+ const { spawner } = scriptedSpawn({ run: () => ({ code: 'error' }) })
+ const fd = openSync(out, 'w')
+ try {
+ const thrown = await runArchiveTool(plan, fd, spawner).catch((error: unknown) => error)
+ expect(thrown).toBeInstanceOf(SidebarError)
+ expect(thrown).toMatchObject({ code: 'fs-error' })
+ expect((thrown as Error).message).toMatch(/cannot run zip/)
+ } finally {
+ closeSync(fd)
+ }
+ })
+
+ it('reports code 1 for a child killed by a signal (no exit code at all)', async () => {
+ const root = tempRoot()
+ const spec = await specOf('zip')
+ const plan = planArchive([join(root, 'src')], spec)
+ const out = join(root, 'out.zip')
+ const { spawner } = scriptedSpawn({ run: () => ({ code: null }) })
+ const fd = openSync(out, 'w')
+ try {
+ await expect(runArchiveTool(plan, fd, spawner)).resolves.toEqual({ code: 1, stderr: '' })
+ } finally {
+ closeSync(fd)
+ }
+ })
+
+ it('keeps a bounded TAIL of stderr, not the whole log', async () => {
+ const root = tempRoot()
+ const spec = await specOf('zip')
+ const plan = planArchive([join(root, 'src')], spec)
+ const out = join(root, 'out.zip')
+ // Three budgets of noise with a distinct head and tail: the last lines are
+ // the ones that name the actual problem.
+ const head = 'H'.repeat(64)
+ const tail = 'T'.repeat(64)
+ const { spawner } = scriptedSpawn({
+ run: () => ({ code: 1, stderr: `${head}${'M'.repeat(ARCHIVE_STDERR_LIMIT * 3)}${tail}` }),
+ })
+ const fd = openSync(out, 'w')
+ try {
+ const result = await runArchiveTool(plan, fd, spawner)
+ expect(result.code).toBe(1)
+ expect(result.stderr.length).toBeLessThanOrEqual(ARCHIVE_STDERR_LIMIT)
+ expect(result.stderr.endsWith(tail)).toBe(true)
+ expect(result.stderr.includes(head)).toBe(false)
+ } finally {
+ closeSync(fd)
+ }
+ })
+
+ it('hands the spawn the plan, the caller\'s descriptor and the child', async () => {
+ const root = tempRoot()
+ const spec = await specOf('zip')
+ const plan = planArchive([join(root, 'src')], spec)
+ const out = join(root, 'out.zip')
+ const payload = Buffer.from('PK\u0003\u0004 not really a zip\n')
+ const { spawner, calls, children } = scriptedSpawn({ run: () => ({ bytes: payload }) })
+ const fd = openSync(out, 'w')
+ const spawned: unknown[] = []
+ try {
+ await expect(runArchiveTool(plan, fd, spawner, child => spawned.push(child)))
+ .resolves.toEqual({ code: 0, stderr: '' })
+ } finally {
+ closeSync(fd)
+ }
+ // The TOOL wrote the file, through the descriptor we opened: the route
+ // never holds the bytes.
+ expect(readFileSync(out).equals(payload)).toBe(true)
+ expect(calls[0]).toMatchObject({ bin: 'zip', args: plan.args, fd })
+ // onSpawn hands the child over BEFORE it exits — that is what lets the
+ // task table kill a build at teardown.
+ expect(spawned).toEqual([children[0]])
+ })
+})
+
+describe('real tool (only when one is installed)', () => {
+ // The one case that drives a real binary. `zip` is absent on Windows (where
+ // `tar` is bsdtar) and neither is guaranteed on a bare runner, so the probe
+ // is repeated HERE — with the real spawn face — and a host without either
+ // tool skips instead of failing.
+ it('packs a tree that contains a symlink loop, and the loop does not recurse', async () => {
+ resetArchiveToolCache()
+ const spec = await resolveArchiveTool()
+ if (spec === undefined) return // no zip and no tar: nothing to verify here
+ const root = mkdtempSync(join(tmpdir(), 'dsh-archive-real-'))
+ try {
+ const ws = join(root, 'ws')
+ mkdirSync(join(ws, 'dir'), { recursive: true })
+ writeFileSync(join(ws, 'a.txt'), 'a\n')
+ writeFileSync(join(ws, 'dir', 'b.txt'), 'b\n')
+ // `loop -> .` is the shape that made `-y` mandatory. Creating a symlink
+ // needs a privilege Windows may not grant, so a failure only drops the
+ // loop, not the case.
+ let looped = false
+ try {
+ symlinkSync('.', join(ws, 'loop'), 'dir')
+ looped = true
+ } catch {
+ looped = false
+ }
+ const plan = planArchive([ws], spec)
+ const out = join(root, `out${spec.ext}`)
+ const fd = openSync(out, 'w')
+ let child: ReturnType | undefined
+ let result: Awaited>
+ // A followed loop never finishes. Kill it well inside vitest's own
+ // budget, so a regression fails on the exit code with the tool's stderr
+ // instead of timing the case out.
+ const deadline = setTimeout(() => { child?.kill('SIGKILL') }, 8_000)
+ try {
+ result = await runArchiveTool(plan, fd, undefined, spawned => { child = spawned })
+ } finally {
+ clearTimeout(deadline)
+ closeSync(fd)
+ }
+ expect(result.code, result.stderr).toBe(0)
+ const size = statSync(out).size
+ expect(size).toBeGreaterThan(0)
+ // A followed `loop -> .` grows without bound; `-y` stores the link
+ // itself, so the archive stays a couple of hundred bytes.
+ expect(size).toBeLessThan(1 << 20)
+ if (looped && spec.tool === 'zip') {
+ // Info-ZIP stores entry names uncompressed: a recursion would be
+ // visible as `loop/loop/…` in the bytes.
+ expect(readFileSync(out).includes('loop/loop')).toBe(false)
+ }
+ } finally {
+ rmSync(root, { recursive: true, force: true })
+ }
+ }, 30_000)
+})
diff --git a/tests/archive.spec.ts b/tests/archive.spec.ts
new file mode 100644
index 00000000..063bad4c
--- /dev/null
+++ b/tests/archive.spec.ts
@@ -0,0 +1,864 @@
+/**
+ * The archive flow: `archive.build` → `archive.status` → GET /sidebar/archive.
+ *
+ * The hand-written writer is gone (see archive-tools.ts), so nothing here
+ * inflates bytes any more. What this file pins is the ROUTE contract: the
+ * `{id, name, entries}` a build answers with, the `{state, bytes}` a poll
+ * reads (no entry counters — a child process reports none), the six download
+ * branches, the concurrency cap and the TTL, that a download CONSUMES the task
+ * and deletes its temp file, and that teardown kills a running build.
+ *
+ * Two injection seams, both on purpose (AGENTS §6 — a spec may not depend on
+ * `zip` being installed):
+ * - `createArchiveTasks({spawn, tempDir, resolveTool})` for everything that is
+ * really about the task table and the download mapping;
+ * - the module-level `spawn` for the cases that must go through a MOUNTED
+ * host, whose table is built inside `apply` and is not injectable. That fake
+ * intercepts `zip` / `tar` only and hands every other binary to the real
+ * spawn — resolving the session cwd runs a real `git rev-parse` on the way.
+ * No case here runs a real zip/tar; the one real-binary case lives in
+ * archive-tools.spec.ts and self-probes.
+ *
+ * Temp files: an injected table gets a real `mkdtemp` directory, and the
+ * mounted host gets `TMPDIR`/`TEMP`/`TMP` pointed at one too (`os.tmpdir()`
+ * reads the environment per call), so no case ever writes into — or asserts
+ * about — the user's real temp directory.
+ */
+import './browser-globals.ts'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { EventEmitter } from 'node:events'
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+ writeSync,
+} from 'node:fs'
+import { validateHeaderValue } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { PassThrough, Writable } from 'node:stream'
+import { apply } from '../src/index.ts'
+import { archiveDownloadUrl } from '../src/client/api.ts'
+import {
+ ARCHIVE_MAX_BUILDING,
+ ARCHIVE_TTL_MS,
+ contentDispositionOf,
+ createArchiveTasks,
+ respondArchiveDownload,
+ type ArchiveStatus,
+ type ArchiveTasks,
+} from '../src/archive-route.ts'
+import {
+ archiveTempName,
+ resetArchiveToolCache,
+ type ArchiveSpawn,
+ type ArchiveToolSpec,
+} from '../src/archive-tools.ts'
+import { writeError } from '../src/wire.ts'
+import type { SidebarHttpResponse, SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
+
+/** The OS temp directory as it was BEFORE this file points TMPDIR at a scratch dir. */
+const realTmp = tmpdir()
+
+/**
+ * What the faked `spawn` answers. Shared with the `vi.mock` factory below,
+ * which is hoisted above this module's imports (hence `vi.hoisted`).
+ */
+const tool = vi.hoisted(() => ({
+ /** `ok` writes `payload` and exits 0; `fail` exits 2 with stderr; `hang`
+ * never settles; `missing` makes the probe answer non-zero (no tool at all). */
+ mode: 'ok' as 'ok' | 'fail' | 'hang' | 'missing',
+ /** The bytes a successful build leaves in the temp file. */
+ payload: 'PK\u0003\u0004 fake archive bytes\n',
+ /** Non-probe invocations, in order. */
+ runs: 0,
+ /** Children handed out for a run, so teardown assertions can read `kill`. */
+ children: [] as Array<{ kill: (signal?: string) => boolean }>,
+}))
+
+vi.mock('node:child_process', async () => {
+ const actual = await vi.importActual('node:child_process')
+ const { EventEmitter } = await import('node:events')
+ const { PassThrough } = await import('node:stream')
+ const { writeSync } = await import('node:fs')
+ const spawn = ((bin: string, args: readonly string[], options: { stdio?: unknown }) => {
+ // Only the archive tools are faked: cwd resolution runs a real `git`.
+ if (bin !== 'zip' && bin !== 'tar') {
+ return actual.spawn(bin as never, args as never, options as never)
+ }
+ const child = new EventEmitter() as EventEmitter & {
+ stderr: InstanceType
+ kill: (signal?: string) => boolean
+ }
+ child.stderr = new PassThrough()
+ child.kill = () => true
+ if (options.stdio === 'ignore') {
+ const code = tool.mode === 'missing' ? 1 : 0
+ process.nextTick(() => { child.emit('exit', code) })
+ return child
+ }
+ tool.runs += 1
+ tool.children.push(child)
+ const fd = Array.isArray(options.stdio) ? options.stdio[1] : undefined
+ process.nextTick(() => {
+ if (tool.mode === 'hang') return
+ if (tool.mode === 'fail') {
+ child.stderr.write('zip error: nothing to do\n')
+ child.emit('close', 2)
+ return
+ }
+ if (typeof fd === 'number') writeSync(fd, Buffer.from(tool.payload))
+ child.emit('close', 0)
+ })
+ return child
+ }) as unknown as typeof actual.spawn
+ return { ...actual, spawn }
+})
+
+/** The wire shape of one API answer. */
+interface Envelope {
+ ok: boolean
+ value?: T
+ error?: { code?: string; message?: string }
+}
+
+/** One recorded response: status, headers, raw bytes and the parsed envelope. */
+interface Wire {
+ status: number
+ headers: Record
+ chunks: Buffer[]
+ /** The JSON body as an envelope, read lazily (`{ok: false}` for byte responses). */
+ readonly envelope: Envelope
+}
+
+/**
+ * A response face that records what a route wrote — and is a real Writable, so
+ * the streaming download path (`pipeline`) works against it exactly as it does
+ * against a `node:http` response.
+ *
+ * The returned `wire` is one mutable object the route writes THROUGH (a fresh
+ * one per read would hand the test an empty snapshot taken before the call).
+ */
+function responseRecorder(): { res: SidebarHttpResponse; wire: Wire } {
+ const wire = {
+ status: 200,
+ headers: {} as Record,
+ chunks: [] as Buffer[],
+ get envelope(): Envelope {
+ const body = Buffer.concat(wire.chunks).toString('utf8')
+ if (body === '') return { ok: false }
+ try {
+ return JSON.parse(body) as Envelope
+ } catch {
+ return { ok: false }
+ }
+ },
+ }
+ const stream = new Writable({
+ write(chunk: Buffer | string, _encoding, done) {
+ wire.chunks.push(Buffer.from(chunk))
+ done()
+ },
+ })
+ const res = Object.assign(stream, {
+ writeHead: (status: number, headers: Record = {}) => {
+ wire.status = status
+ wire.headers = headers
+ },
+ })
+ return { res: res as unknown as SidebarHttpResponse, wire }
+}
+
+/** The host mounted against a fake context: both archive routes + the API. */
+function mountHost(): { api: SidebarWebRoute; download: SidebarWebRoute } {
+ const routes: SidebarWebRoute[] = []
+ const ctx = {
+ webRuntime: { trustedHosts: [] },
+ webServer: {
+ register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
+ registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
+ },
+ sessions: { get: () => undefined },
+ tools: { register: () => () => {} },
+ effect: (fn: () => void | (() => void)) => { fn() },
+ inject: () => () => {},
+ on: () => () => {},
+ get: () => undefined,
+ }
+ apply(ctx as never)
+ const api = routes.find(candidate => candidate.path === '/sidebar/api')
+ const download = routes.find(candidate => candidate.path === '/sidebar/archive')
+ if (api === undefined) throw new Error('test setup: /sidebar/api route not registered')
+ if (download === undefined) throw new Error('test setup: /sidebar/archive route not registered')
+ return { api, download }
+}
+
+/** One POST /sidebar/api/ against the mounted API route. */
+async function post(api: SidebarWebRoute, method: string, payload: unknown): Promise {
+ const body = Buffer.from(JSON.stringify(payload))
+ const req = {
+ method: 'POST',
+ url: `/sidebar/api/${method}`,
+ headers: { host: '127.0.0.1:3080' },
+ [Symbol.asyncIterator]: async function* () { yield body },
+ } as never
+ const { res, wire } = responseRecorder()
+ await api.handler(req, res)
+ return wire
+}
+
+/** One request against a mounted raw route. */
+async function request(route: SidebarWebRoute, method: string, url: string): Promise {
+ const req = { method, url, headers: { host: '127.0.0.1:3080' } } as never
+ const { res, wire } = responseRecorder()
+ await route.handler(req, res)
+ return wire
+}
+
+/** Poll `archive.status` until the detached build settles (or throw). */
+async function waitForSettled(api: SidebarWebRoute, id: string, sessionId: string): Promise {
+ let last: ArchiveStatus | undefined
+ for (let attempt = 0; attempt < 400; attempt += 1) {
+ const status = await post(api, 'archive.status', { id, sessionId })
+ if (status.envelope.ok === true) {
+ last = status.envelope.value as ArchiveStatus
+ if (last.state !== 'building') return last
+ }
+ await new Promise(resolve => setTimeout(resolve, 5))
+ }
+ throw new Error(`test setup: archive ${id} never settled (${JSON.stringify(last)})`)
+}
+
+/**
+ * One GET /sidebar/archive through the task table's own mapping: what the
+ * route does, including the JSON envelope its catch block writes.
+ */
+async function download(tasks: ArchiveTasks, sessionId: string | null, id: string | null): Promise {
+ const { res, wire } = responseRecorder()
+ try {
+ await respondArchiveDownload(tasks, { sessionId, id }, res)
+ } catch (error: unknown) {
+ writeError(res, error)
+ }
+ return wire
+}
+
+/** Every temp directory and fixture tree the current case owns. */
+let scratch = ''
+/** The temp directory the plugin's own default would use (TMPDIR points here). */
+let tempDir = ''
+/** Every table this case built: disposed after it (a hanging build holds a descriptor). */
+const tables: ArchiveTasks[] = []
+const savedTmp = { TMPDIR: process.env.TMPDIR, TEMP: process.env.TEMP, TMP: process.env.TMP }
+
+beforeEach(() => {
+ scratch = mkdtempSync(join(realTmp, 'dsh-archive-spec-'))
+ tempDir = mkdtempSync(join(realTmp, 'dsh-archive-tmp-'))
+ process.env.TMPDIR = tempDir
+ process.env.TEMP = tempDir
+ process.env.TMP = tempDir
+ tool.mode = 'ok'
+ tool.runs = 0
+ tool.children.length = 0
+ resetArchiveToolCache()
+})
+
+afterEach(async () => {
+ // Before the mocks go: `dispose()` kills through a fake whose `kill` is a
+ // `vi.fn`, and those implementations do not survive a restore.
+ for (const tasks of tables.splice(0)) tasks.dispose()
+ // A killed child closes asynchronously; let the close land (and the packer
+ // close its descriptor) before the directories underneath it disappear.
+ await new Promise(resolve => setTimeout(resolve, 0))
+ for (const [key, value] of Object.entries(savedTmp)) {
+ if (value === undefined) delete process.env[key]
+ else process.env[key] = value
+ }
+ resetArchiveToolCache()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ rmSync(scratch, { recursive: true, force: true })
+ rmSync(tempDir, { recursive: true, force: true })
+})
+
+/** A directory inside the per-test fixture tree (removed with it). */
+function workspace(name: string): string {
+ const dir = join(scratch, name)
+ mkdirSync(dir, { recursive: true })
+ return dir
+}
+
+/** Two real files to select (the faked tool never looks at them). */
+function sampleSelection(): string[] {
+ const dir = join(scratch, 'selection')
+ mkdirSync(dir, { recursive: true })
+ return ['a.txt', 'b.txt'].map((name) => {
+ writeFileSync(join(dir, name), name)
+ return join(dir, name)
+ })
+}
+
+/** What one injected table's faked tool does. */
+interface ToolBehavior {
+ /** `missing` makes the probe fail (only useful with an injected resolveTool). */
+ probe?: 'ok' | 'missing'
+ run?: {
+ bytes?: Buffer
+ code?: number
+ stderr?: string
+ /** Keep running until `kill()` (a build teardown has to end). */
+ hang?: boolean
+ }
+}
+
+/** The minimum of a ChildProcess these specs touch. */
+type ToolChild = EventEmitter & { stderr: PassThrough; kill: ReturnType }
+
+/** A scripted `spawn`: a probe answers `--version`, a run writes the payload. */
+function toolSpawn(behavior: ToolBehavior = {}): { spawner: ArchiveSpawn; children: ToolChild[] } {
+ const children: ToolChild[] = []
+ const spawner = ((_bin: string, _args: readonly string[], options: { stdio?: unknown }): ToolChild => {
+ const child = new EventEmitter() as ToolChild
+ child.stderr = new PassThrough()
+ const run = behavior.run ?? {}
+ let hangs = run.hang === true
+ // A killed child exits BY SIGNAL — 'close' with no exit code, which is
+ // exactly what a real SIGTERM looks like from here.
+ child.kill = vi.fn(() => {
+ if (hangs) {
+ hangs = false
+ child.emit('close', null)
+ }
+ return true
+ })
+ children.push(child)
+ if (options.stdio === 'ignore') {
+ const ok = (behavior.probe ?? 'ok') === 'ok'
+ process.nextTick(() => { child.emit('exit', ok ? 0 : 1) })
+ return child
+ }
+ const fd = Array.isArray(options.stdio) ? options.stdio[1] : undefined
+ process.nextTick(() => {
+ if (run.hang === true) return
+ if (run.stderr !== undefined) child.stderr.write(run.stderr)
+ if (run.bytes !== undefined && typeof fd === 'number') writeSync(fd, run.bytes)
+ child.emit('close', run.code ?? 0)
+ })
+ return child
+ }) as unknown as ArchiveSpawn
+ return { spawner, children }
+}
+
+/** The zip spec as the route's own extension handling sees it. */
+const ZIP_SPEC: ArchiveToolSpec = { tool: 'zip', bin: 'zip', flags: ['-r', '-q', '-X', '-y', '-'], ext: '.zip' }
+/** A tar-only host's spec (Windows without Info-ZIP). */
+const TAR_SPEC: ArchiveToolSpec = { tool: 'tar', bin: 'tar', flags: ['-czf', '-'], ext: '.tar.gz' }
+
+/** One task table with all three injectable faces faked. */
+function makeTable(input: { spec?: ArchiveToolSpec; behavior?: ToolBehavior } = {}): {
+ tasks: ArchiveTasks
+ tempDir: string
+ children: ToolChild[]
+} {
+ const spec = 'spec' in input ? input.spec : ZIP_SPEC
+ const dir = mkdtempSync(join(scratch, 'archives-'))
+ const { spawner, children } = toolSpawn(input.behavior)
+ const tasks = createArchiveTasks({ spawn: spawner, tempDir: dir, resolveTool: async () => spec })
+ tables.push(tasks)
+ return { tasks, tempDir: dir, children }
+}
+
+/** Poll one table until its task settles (never `building` on return). */
+async function settledStatus(tasks: ArchiveTasks, id: string, sessionId: string): Promise {
+ await vi.waitFor(() => { expect(tasks.status(id, sessionId).state).not.toBe('building') })
+ return tasks.status(id, sessionId)
+}
+
+describe('contentDispositionOf', () => {
+ it('never puts a non-latin1 character in the header value', () => {
+ const header = contentDispositionOf('报告.zip')
+ // Node's writeHead rejects any header value above U+00FF — the whole
+ // reason the raw name cannot be used (it 500s the route). Control: the
+ // exact shape this fix replaced must FAIL the same check.
+ expect(() => validateHeaderValue('content-disposition', 'attachment; filename="报告.zip"'))
+ .toThrow(/Invalid character in header content/)
+ expect([...header].every(char => char.codePointAt(0)! <= 0xFF)).toBe(true)
+ expect(validateHeaderValue('content-disposition', header)).toBeUndefined()
+ expect(header).toBe(`attachment; filename="download.zip"; filename*=UTF-8''${encodeURIComponent('报告.zip')}`)
+ })
+
+ it('keeps a plain ASCII name in both halves (suffix stripped for the fallback stem only)', () => {
+ const header = contentDispositionOf('docs.zip')
+ expect(header).toBe(`attachment; filename="docs.zip"; filename*=UTF-8''docs.zip`)
+ expect(validateHeaderValue('content-disposition', header)).toBeUndefined()
+ // A mixed name keeps whatever ASCII survives in the fallback.
+ expect(contentDispositionOf('報告 Q3.zip')).toContain('filename=" Q3.zip"')
+ })
+})
+
+describe('archive task table (injected spawn)', () => {
+ it('applies the tool\'s extension to the name the client asked for', async () => {
+ const zip = makeTable()
+ const paths = sampleSelection()
+ const started = await zip.tasks.start({ sessionId: 's-1', name: 'docs.zip', paths })
+ expect(started.id).toMatch(/^ar-/)
+ expect(started.name).toBe('docs.zip')
+ expect(started.entries).toBe(paths.length)
+
+ // The same stem on a tar-only host: the client's guessed `.zip` is
+ // replaced by what the tool actually produced.
+ const tar = makeTable({ spec: TAR_SPEC })
+ const guessed = await tar.tasks.start({ sessionId: 's-1', name: 'docs.zip', paths })
+ expect(guessed.name).toBe('docs.tar.gz')
+ })
+
+ it('sanitizes the client\'s name into a flat, traversal-free download name', async () => {
+ const { tasks } = makeTable()
+ const paths = sampleSelection()
+ const traversal = await tasks.start({ sessionId: 's-1', name: '../evil")b.zip', paths })
+ expect(traversal.name).toBe('evil)b.zip')
+ // The served header is the sanitized name, never the raw input.
+ await settledStatus(tasks, traversal.id, 's-1')
+ const served = await download(tasks, 's-1', traversal.id)
+ expect(served.headers['content-disposition']).toContain('filename="evil)b.zip"')
+ expect((await tasks.start({ sessionId: 's-1', name: 'docs', paths })).name).toBe('docs.zip')
+ expect((await tasks.start({ sessionId: 's-1', name: '', paths })).name).toBe('archive.zip')
+ })
+
+ it('reports {state, bytes} — the entry counters are gone — and settles ready', async () => {
+ const payload = Buffer.from('PK\u0003\u0004 payload')
+ const { tasks } = makeTable({ behavior: { run: { bytes: payload } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+ const first = tasks.status(id, 's-1')
+ expect(['building', 'ready']).toContain(first.state)
+ expect(first).not.toHaveProperty('done')
+ expect(first).not.toHaveProperty('total')
+ expect(first).not.toHaveProperty('error')
+ expect(Object.keys(first).sort()).toEqual(['bytes', 'state'])
+
+ const settled = await settledStatus(tasks, id, 's-1')
+ expect(settled.state).toBe('ready')
+ // Bytes are the temp file's size: the archive really is on disk, which is
+ // what the download streams from.
+ expect(settled.bytes).toBe(payload.byteLength)
+ expect(Object.keys(settled).sort()).toEqual(['bytes', 'state'])
+ })
+
+ it('keeps a task building while the child runs', async () => {
+ const { tasks } = makeTable({ behavior: { run: { hang: true } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+ expect(tasks.status(id, 's-1')).toMatchObject({ state: 'building', bytes: 0 })
+ expect(tasks.lookup(id, 's-1')).toMatchObject({ ok: false, reason: 'building' })
+ })
+
+ it('settles a failed build as error and carries the tool\'s stderr', async () => {
+ const { tasks, tempDir: archives } = makeTable({
+ behavior: { run: { code: 2, stderr: 'zip error: nothing to do\n' } },
+ })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+ const settled = await settledStatus(tasks, id, 's-1')
+ expect(settled.state).toBe('error')
+ expect(settled.error).toMatch(/nothing to do/)
+ expect(settled.bytes).toBe(0)
+ expect(tasks.lookup(id, 's-1')).toMatchObject({ ok: false, reason: 'error' })
+ // A failed build leaves nothing behind for a download to serve.
+ await vi.waitFor(() => { expect(readdirSync(archives)).toEqual([]) })
+ })
+
+ it('rejects start with `unavailable` (501) when no tool exists', async () => {
+ const { tasks, tempDir: archives, children } = makeTable({ spec: undefined })
+ await expect(tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() }))
+ .rejects.toMatchObject({ code: 'unavailable', status: 501 })
+ // Nothing was planned, spawned or written.
+ expect(tasks.size()).toBe(0)
+ expect(children).toHaveLength(0)
+ expect(readdirSync(archives)).toEqual([])
+ })
+
+ it('caps concurrent builds at ARCHIVE_MAX_BUILDING (409)', async () => {
+ expect(ARCHIVE_MAX_BUILDING).toBe(4)
+ const { tasks } = makeTable({ behavior: { run: { hang: true } } })
+ const paths = sampleSelection()
+ for (let index = 0; index < ARCHIVE_MAX_BUILDING; index += 1) {
+ await tasks.start({ sessionId: 's-1', name: `a${index}`, paths })
+ }
+ await expect(tasks.start({ sessionId: 's-1', name: 'one-too-many', paths }))
+ .rejects.toMatchObject({ code: 'bad-request', status: 409 })
+ expect(tasks.size()).toBe(ARCHIVE_MAX_BUILDING)
+ })
+
+ it('expires a settled task after ARCHIVE_TTL_MS and deletes its file', async () => {
+ const { tasks, tempDir: archives } = makeTable({ behavior: { run: { bytes: Buffer.from('x') } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+ await settledStatus(tasks, id, 's-1')
+ expect(tasks.size()).toBe(1)
+ const file = join(archives, archiveTempName(id, '.zip'))
+ expect(existsSync(file)).toBe(true)
+ // A clock jump is the same code path as waiting five minutes for it.
+ vi.setSystemTime(Date.now() + ARCHIVE_TTL_MS + 1)
+ try {
+ expect(() => tasks.status(id, 's-1')).toThrow(/unknown or expired/)
+ expect(tasks.lookup(id, 's-1')).toMatchObject({ ok: false, reason: 'missing' })
+ expect(tasks.size()).toBe(0)
+ // An expired task reads as missing on the download route too: 404.
+ expect((await download(tasks, 's-1', id)).status).toBe(404)
+ await vi.waitFor(() => { expect(existsSync(file)).toBe(false) })
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('consumes the task on download, deleting the temp file after the stream', async () => {
+ const payload = Buffer.from('PK\u0003\u0004 archive')
+ const { tasks, tempDir: archives } = makeTable({ behavior: { run: { bytes: payload } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'docs', paths: sampleSelection() })
+ await settledStatus(tasks, id, 's-1')
+ const file = join(archives, archiveTempName(id, '.zip'))
+ expect(existsSync(file)).toBe(true)
+
+ const first = await download(tasks, 's-1', id)
+ expect(first.status).toBe(200)
+ expect(first.headers['content-type']).toBe('application/zip')
+ expect(first.headers['content-disposition']).toBe(`attachment; filename="docs.zip"; filename*=UTF-8''docs.zip`)
+ expect(first.headers['content-length']).toBe(String(payload.byteLength))
+ expect(Buffer.concat(first.chunks).equals(payload)).toBe(true)
+ // The bytes are gone from disk once served — the task table is a queue,
+ // not a store (the unlink is async, hence the wait).
+ await vi.waitFor(() => { expect(existsSync(file)).toBe(false) })
+ expect(readdirSync(archives)).toEqual([])
+
+ const second = await download(tasks, 's-1', id)
+ expect(second.status).toBe(404)
+ expect(second.envelope.error?.code).toBe('not-found')
+ expect(() => tasks.status(id, 's-1')).toThrow(/unknown or expired/)
+ })
+
+ it('releases the task only after the stream settles', async () => {
+ const payload = Buffer.from('PK\u0003\u0004 slow reader')
+ const { tasks, tempDir: archives } = makeTable({ behavior: { run: { bytes: payload } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'slow', paths: sampleSelection() })
+ await settledStatus(tasks, id, 's-1')
+ const file = join(archives, archiveTempName(id, '.zip'))
+
+ // A response that accepts the first chunk and then stalls: releasing the
+ // task before the stream settles would unlink the file underneath it.
+ let resume = (): void => {}
+ const gate = new Promise((resolve) => { resume = resolve })
+ const chunks: Buffer[] = []
+ const stalled = Object.assign(new Writable({
+ write(chunk: Buffer | string, _encoding, done) {
+ chunks.push(Buffer.from(chunk))
+ void gate.then(() => { done() })
+ },
+ }), { writeHead: () => {} })
+ const pending = respondArchiveDownload(tasks, { sessionId: 's-1', id }, stalled as unknown as SidebarHttpResponse)
+ await vi.waitFor(() => { expect(chunks.length).toBeGreaterThan(0) })
+ expect(existsSync(file)).toBe(true)
+ expect(tasks.lookup(id, 's-1')).toMatchObject({ ok: true })
+
+ resume()
+ await pending
+ await vi.waitFor(() => { expect(existsSync(file)).toBe(false) })
+ expect(tasks.lookup(id, 's-1')).toMatchObject({ ok: false, reason: 'missing' })
+ })
+
+ it('dispose() kills a running build and deletes every temp file', async () => {
+ const ready = makeTable({ behavior: { run: { bytes: Buffer.from('PK\u0003\u0004 done') } } })
+ const running = makeTable({ behavior: { run: { hang: true } } })
+ const paths = sampleSelection()
+ const finished = await ready.tasks.start({ sessionId: 's-1', name: 'done', paths })
+ await settledStatus(ready.tasks, finished.id, 's-1')
+ const started = await running.tasks.start({ sessionId: 's-1', name: 'running', paths })
+ const finishedFile = join(ready.tempDir, archiveTempName(finished.id, '.zip'))
+ const runningFile = join(running.tempDir, archiveTempName(started.id, '.zip'))
+ expect(existsSync(finishedFile)).toBe(true)
+ // With resolveTool injected there is no probe: the only child is the build
+ // (the temp file appears when it is OPENED, so the spawn is awaited).
+ await vi.waitFor(() => { expect(running.children).toHaveLength(1) })
+ await vi.waitFor(() => { expect(existsSync(runningFile)).toBe(true) })
+
+ running.tasks.dispose()
+ ready.tasks.dispose()
+ expect(running.children[0]!.kill).toHaveBeenCalled()
+ await vi.waitFor(() => {
+ expect(existsSync(runningFile)).toBe(false)
+ expect(existsSync(finishedFile)).toBe(false)
+ })
+ expect(running.tasks.size()).toBe(0)
+ expect(ready.tasks.size()).toBe(0)
+ })
+})
+
+describe('respondArchiveDownload branches', () => {
+ it('answers 400 when either parameter is missing', async () => {
+ const { tasks } = makeTable()
+ expect((await download(tasks, null, 'ar-1')).status).toBe(400)
+ expect((await download(tasks, 's-1', null)).status).toBe(400)
+ const empty = await download(tasks, 's-1', '')
+ expect(empty.status).toBe(400)
+ expect(empty.envelope.error?.code).toBe('bad-request')
+ })
+
+ it('answers 403 for another session\'s task (and does not consume it)', async () => {
+ const { tasks } = makeTable({ behavior: { run: { bytes: Buffer.from('x') } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+ await settledStatus(tasks, id, 's-1')
+ const foreign = await download(tasks, 's-other', id)
+ expect(foreign.status).toBe(403)
+ expect(foreign.envelope.error?.code).toBe('forbidden')
+ // The failed read left the task alone: its owner can still fetch it.
+ expect((await download(tasks, 's-1', id)).status).toBe(200)
+ })
+
+ it('answers 409 while the build is still running', async () => {
+ const { tasks } = makeTable({ behavior: { run: { hang: true } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+ const answer = await download(tasks, 's-1', id)
+ expect(answer.status).toBe(409)
+ expect(answer.envelope.error?.message).toMatch(/still being built/)
+ })
+
+ it('answers 410 with the tool\'s message for a failed build', async () => {
+ const { tasks } = makeTable({ behavior: { run: { code: 2, stderr: 'zip error: nothing to do\n' } } })
+ const { id } = await tasks.start({ sessionId: 's-1', name: 'a', paths: sampleSelection() })
+ await settledStatus(tasks, id, 's-1')
+ const answer = await download(tasks, 's-1', id)
+ expect(answer.status).toBe(410)
+ expect(answer.envelope.error?.code).toBe('fs-error')
+ expect(answer.envelope.error?.message).toMatch(/nothing to do/)
+ })
+
+ it('answers 404 for an unknown id', async () => {
+ const { tasks } = makeTable()
+ const answer = await download(tasks, 's-1', 'ar-nope')
+ expect(answer.status).toBe(404)
+ expect(answer.envelope.error?.code).toBe('not-found')
+ expect(answer.envelope.error?.message).toMatch(/unknown or expired/)
+ })
+
+ it('serves a tar host as a real .tar.gz with application/gzip', async () => {
+ const payload = Buffer.from('\u001F\u008B gzip bytes')
+ const { tasks } = makeTable({ spec: TAR_SPEC, behavior: { run: { bytes: payload } } })
+ const { id, name } = await tasks.start({ sessionId: 's-1', name: 'docs.zip', paths: sampleSelection() })
+ expect(name).toBe('docs.tar.gz')
+ await settledStatus(tasks, id, 's-1')
+ const answer = await download(tasks, 's-1', id)
+ expect(answer.status).toBe(200)
+ // The extension follows the TOOL: never a `.zip` header over gzip bytes.
+ expect(answer.headers['content-type']).toBe('application/gzip')
+ expect(answer.headers['content-disposition'])
+ .toBe(`attachment; filename="docs.tar.gz"; filename*=UTF-8''docs.tar.gz`)
+ expect(Buffer.concat(answer.chunks).equals(payload)).toBe(true)
+ })
+})
+
+describe('archive.build / archive.status through the mounted host', () => {
+ it('builds, polls and downloads through the real routes (faked tool)', async () => {
+ const { api, download: route } = mountHost()
+ const ws = workspace('flow')
+ writeFileSync(join(ws, 'a.txt'), 'a\n')
+ writeFileSync(join(ws, 'b.txt'), 'b\n')
+
+ const build = await post(api, 'archive.build', {
+ sessionId: 's-flow',
+ cwd: ws,
+ name: 'bundle',
+ paths: [join(ws, 'a.txt'), join(ws, 'b.txt')],
+ })
+ expect(build.status).toBe(200)
+ expect(build.envelope.ok).toBe(true)
+ const value = build.envelope.value as { id: string; name: string; entries: number }
+ expect(value.id).toMatch(/^ar-/)
+ // The tool's extension, applied by the host — the client sends a stem.
+ expect(value.name).toBe('bundle.zip')
+ // `entries` counts SELECTIONS: the walk is the tool's now.
+ expect(value.entries).toBe(2)
+
+ const polled = await post(api, 'archive.status', { id: value.id, sessionId: 's-flow' })
+ expect(polled.envelope.ok).toBe(true)
+ const status = polled.envelope.value as Record
+ expect(['building', 'ready']).toContain(status.state)
+ expect(status).not.toHaveProperty('done')
+ expect(status).not.toHaveProperty('total')
+ expect(status.bytes).toBeGreaterThanOrEqual(0)
+
+ const settled = await waitForSettled(api, value.id, 's-flow')
+ expect(settled.state).toBe('ready')
+ expect(settled.bytes).toBe(Buffer.byteLength(tool.payload))
+
+ const url = `/sidebar/archive?sessionId=s-flow&id=${encodeURIComponent(value.id)}`
+ const served = await request(route, 'GET', url)
+ expect(served.status).toBe(200)
+ expect(Buffer.concat(served.chunks).toString('utf8')).toBe(tool.payload)
+ expect(served.headers['content-length']).toBe(String(Buffer.byteLength(tool.payload)))
+ // The download consumed the task and its temp file (see the TMPDIR stub).
+ await vi.waitFor(() => { expect(readdirSync(tempDir)).toEqual([]) })
+ expect((await request(route, 'GET', url)).status).toBe(404)
+ })
+
+ it('refuses an empty path list before ever touching the tool (400)', async () => {
+ const { api } = mountHost()
+ const ws = workspace('empty')
+ const build = await post(api, 'archive.build', { sessionId: 's-empty', cwd: ws, paths: [] })
+ expect(build.status).toBe(400)
+ expect(build.envelope.error?.code).toBe('bad-request')
+ expect(tool.runs).toBe(0)
+ })
+
+ it('surfaces a missing tool as `unavailable` with status 501', async () => {
+ const { api } = mountHost()
+ const ws = workspace('missing')
+ writeFileSync(join(ws, 'a.txt'), 'a')
+ tool.mode = 'missing'
+ const build = await post(api, 'archive.build', { sessionId: 's-missing', cwd: ws, paths: [join(ws, 'a.txt')] })
+ expect(build.status).toBe(501)
+ expect(build.envelope.error?.code).toBe('unavailable')
+ expect(tool.runs).toBe(0)
+ })
+
+ it('surfaces a non-zero tool exit as an error status, before any download', async () => {
+ const { api, download: route } = mountHost()
+ const ws = workspace('failed')
+ writeFileSync(join(ws, 'a.txt'), 'a')
+ tool.mode = 'fail'
+ const build = await post(api, 'archive.build', {
+ sessionId: 's-fail',
+ cwd: ws,
+ name: 'bad',
+ paths: [join(ws, 'a.txt')],
+ })
+ // The id is handed out immediately — the tool's failure arrives later.
+ expect(build.status).toBe(200)
+ const id = (build.envelope.value as { id: string }).id
+ const settled = await waitForSettled(api, id, 's-fail')
+ expect(settled.state).toBe('error')
+ expect(settled.error).toMatch(/nothing to do/)
+ // That ordering is the whole reason the bytes go to a temp file first: a
+ // failed build is a 410 envelope, never a 200 carrying half an archive.
+ const refused = await request(route, 'GET', `/sidebar/archive?sessionId=s-fail&id=${id}`)
+ expect(refused.status).toBe(410)
+ expect(refused.envelope.error?.message).toMatch(/nothing to do/)
+ await vi.waitFor(() => { expect(readdirSync(tempDir)).toEqual([]) })
+ })
+
+ it('requires both status keys and fences the task by session', async () => {
+ const { api } = mountHost()
+ const ws = workspace('fence')
+ writeFileSync(join(ws, 'a.txt'), 'a')
+ const noKey = await post(api, 'archive.status', { id: 'ar-1' })
+ expect(noKey.status).toBe(400)
+ expect(noKey.envelope.error?.code).toBe('bad-request')
+
+ const build = await post(api, 'archive.build', {
+ sessionId: 's-own',
+ cwd: ws,
+ paths: [join(ws, 'a.txt')],
+ })
+ const id = (build.envelope.value as { id: string }).id
+ const foreign = await post(api, 'archive.status', { id, sessionId: 's-other' })
+ expect(foreign.status).toBe(403)
+ expect(foreign.envelope.error?.code).toBe('forbidden')
+ // The foreign read did not destroy the build: its owner still gets it.
+ const own = await waitForSettled(api, id, 's-own')
+ expect(own.state).toBe('ready')
+ })
+
+ it('caps concurrent builds through the API with 409', async () => {
+ const { api } = mountHost()
+ const ws = workspace('cap')
+ writeFileSync(join(ws, 'a.txt'), 'a')
+ tool.mode = 'hang'
+ for (let index = 0; index < ARCHIVE_MAX_BUILDING; index += 1) {
+ const accepted = await post(api, 'archive.build', {
+ sessionId: 's-cap',
+ cwd: ws,
+ name: `a${index}`,
+ paths: [join(ws, 'a.txt')],
+ })
+ expect(accepted.status).toBe(200)
+ }
+ const refused = await post(api, 'archive.build', {
+ sessionId: 's-cap',
+ cwd: ws,
+ name: 'one-too-many',
+ paths: [join(ws, 'a.txt')],
+ })
+ expect(refused.status).toBe(409)
+ expect(refused.envelope.error?.message).toMatch(/too many archives/)
+ })
+
+ it('accepts a selection outside the session cwd (no fence)', async () => {
+ const { api } = mountHost()
+ const ws = workspace('ws')
+ const outside = join(scratch, 'outside')
+ mkdirSync(outside, { recursive: true })
+ writeFileSync(join(outside, 'secret.txt'), 'secret')
+ // ⚠️ PERMISSION CHANGE: an absolute path outside the workspace is a normal
+ // selection — the old 403 branch is gone, and the tool runs from the
+ // selection's own parent.
+ const build = await post(api, 'archive.build', {
+ sessionId: 's-outside',
+ cwd: ws,
+ name: 'secret',
+ paths: [join(outside, 'secret.txt')],
+ })
+ expect(build.status).toBe(200)
+ expect(build.envelope.value).toMatchObject({ name: 'secret.zip', entries: 1 })
+ })
+
+ it('refuses a non-GET download and a download without parameters', async () => {
+ const { download: route } = mountHost()
+ expect((await request(route, 'POST', '/sidebar/archive?id=x')).status).toBe(405)
+ const noParams = await request(route, 'GET', '/sidebar/archive')
+ expect(noParams.status).toBe(400)
+ expect(noParams.envelope.error?.code).toBe('bad-request')
+ })
+
+ it('serves a non-latin1 download name through REAL node:http (no 500, RFC 5987)', async () => {
+ const { api, download: route } = mountHost()
+ const ws = workspace('http')
+ writeFileSync(join(ws, '数据.txt'), 'x\n')
+ const { createServer } = await import('node:http')
+ const server = createServer((req, res) => { void route.handler(req as never, res as never) })
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
+ try {
+ const address = server.address()
+ if (address === null || typeof address === 'string') throw new Error('test setup: no server port')
+ const build = await post(api, 'archive.build', {
+ sessionId: 's-http',
+ cwd: ws,
+ name: '报告',
+ paths: [join(ws, '数据.txt')],
+ })
+ const id = (build.envelope.value as { id: string }).id
+ await waitForSettled(api, id, 's-http')
+ // The route handler answers a REAL ServerResponse here and the bytes go
+ // through the file streaming path. node:http's writeHead validates
+ // header values, which the plain-object stubs cannot do — exactly how
+ // the Chinese-name 500 hid.
+ const url = `http://127.0.0.1:${address.port}/sidebar/archive?sessionId=s-http&id=${encodeURIComponent(id)}`
+ const response = await fetch(url)
+ expect(response.status).toBe(200)
+ const disposition = response.headers.get('content-disposition') ?? ''
+ // The ASCII half is what old clients read; the RFC 5987 half carries the
+ // real name and is what every current browser picks.
+ expect(disposition).toContain(`filename*=UTF-8''${encodeURIComponent('报告.zip')}`)
+ expect(disposition).toContain('filename="download.zip"')
+ expect([...disposition].every(char => char.codePointAt(0)! <= 0xFF)).toBe(true)
+ expect(Buffer.from(await response.arrayBuffer()).toString('utf8')).toBe(tool.payload)
+ // Released only once the stream settled: the file is gone, the task too.
+ await vi.waitFor(() => { expect(readdirSync(tempDir)).toEqual([]) })
+ expect((await fetch(url)).status).toBe(404)
+ } finally {
+ await new Promise(resolve => server.close(() => resolve()))
+ }
+ })
+
+ it('builds the download URL the client anchors on', () => {
+ expect(archiveDownloadUrl({ sessionId: 's-1' }, 'ar-9'))
+ .toBe('http://localhost/sidebar/archive?sessionId=s-1&id=ar-9')
+ })
+})
diff --git a/tests/editor-host.spec.tsx b/tests/editor-host.spec.tsx
index a6c8c57d..32fb66e1 100644
--- a/tests/editor-host.spec.tsx
+++ b/tests/editor-host.spec.tsx
@@ -37,7 +37,7 @@ vi.mock('../src/client/api.ts', () => ({
// The shared git-status store polls this; a non-repo answer keeps rows plain.
gitStatus: async () => ({ isRepo: false, entries: [] }),
archiveBuild: async () => ({ id: 'ar-1', entries: 1 }),
- archiveStatus: async () => ({ state: 'ready', done: 1, total: 1, bytes: 1 }),
+ archiveStatus: async () => ({ state: 'ready', bytes: 1 }),
// The host's fs.read route (a viewer with `fetchStrategy: 'fsRead'`). No
// built-in viewer is registered in these scenarios — `setup()` registers
// the editor tab type only — so only the case that drives it below reads.
diff --git a/tests/file-tree-archive.spec.tsx b/tests/file-tree-archive.spec.tsx
index dbbbade0..2ff375c4 100644
--- a/tests/file-tree-archive.spec.tsx
+++ b/tests/file-tree-archive.spec.tsx
@@ -1,14 +1,25 @@
/**
* FileTree "zip and download" over the host's ASYNC archive route.
*
- * The menu row starts a job (`api.archiveBuild`), the tree polls
- * `api.archiveStatus` while it builds and shows the `zipProgress` line
- * (`done/total` + percentage), then a `ready` status downloads
- * `api.archiveDownloadUrl(id)` as a blob and saves it through a hidden
- * ``. Every failure path — build rejection, a status
- * `error` state, a status rejection, the download's HTTP envelope — lands in
- * the error strip with `zipFailed`, and a repeated pick while one job runs
- * never starts a second job.
+ * The menu row starts a job (`api.archiveBuild(scope, paths, stem)` →
+ * `{id, name, entries}`), the tree polls `api.archiveStatus` every 250ms while
+ * the host's system `zip`/`tar` packs the selection into a temp file, and a
+ * `ready` status clicks a plain `` on the
+ * route URL, which the browser streams straight to disk. The client names a
+ * STEM and uses the FINAL name the host returned — the host appends the
+ * extension of the tool it actually has (a tar-only host really does produce a
+ * `.tar.gz`), so building the name locally would lie. Deliberately NOT
+ * `fetch → blob → objectURL` any more: a Blob holds the whole archive in the
+ * tab's memory, which is exactly what the host change removed. There is no
+ * per-entry progress either (a child process reports none), so the strip shows
+ * the plain `loading` line and nothing else.
+ *
+ * Every failure path lands in the error strip with `zipFailed`: a build
+ * rejection, a status `error` state, a status rejection. The ONE exception is a
+ * build refused with the wire code `unavailable` — neither `zip` nor `tar` is
+ * installed — which renders `archiveToolMissing`, the sentence the user can act
+ * on, instead of the host's English wire message. A repeated pick while one job
+ * runs never starts a second job.
*
* Appearance gates stay as they were: ≥2 selected rows archive together, a
* LONE directory archives its own subtree, a lone FILE shows no archive row
@@ -20,6 +31,7 @@ import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { FileTree } from '../src/client/FileTree.tsx'
+import { t } from '../src/client/locales.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
@@ -29,11 +41,15 @@ beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
-const { archiveBuild, archiveStatus, fetchMock } = vi.hoisted(() => ({
- archiveBuild: vi.fn(),
- archiveStatus: vi.fn(),
- fetchMock: vi.fn(),
-}))
+const { archiveBuild, archiveStatus, SidebarApiError } = vi.hoisted(() => {
+ /** The wire error FileTree narrows on (`code === 'unavailable'`). */
+ class SidebarApiError extends Error {
+ constructor(readonly code: string, message: string) {
+ super(message)
+ }
+ }
+ return { archiveBuild: vi.fn(), archiveStatus: vi.fn(), SidebarApiError }
+})
vi.mock('../src/client/api.ts', () => ({
api: {
@@ -54,28 +70,10 @@ vi.mock('../src/client/api.ts', () => ({
archiveBuild,
archiveStatus,
archiveDownloadUrl: (_scope: unknown, id: string) => `/sidebar/archive/${id}`,
+ SidebarApiError,
isOutsideWorkspaceMessage: () => false,
}))
-/** jsdom implements neither object-URL helper; these ARE the download probe. */
-const createdUrls: Blob[] = []
-const revokedUrls: string[] = []
-beforeAll(() => {
- Object.defineProperty(URL, 'createObjectURL', {
- configurable: true,
- writable: true,
- value: (blob: Blob) => {
- createdUrls.push(blob)
- return `blob:mock-${createdUrls.length}`
- },
- })
- Object.defineProperty(URL, 'revokeObjectURL', {
- configurable: true,
- writable: true,
- value: (url: string) => { revokedUrls.push(url) },
- })
-})
-
/** The poll cadence the tree uses; advancing less than this must not poll. */
const POLL_MS = 250
@@ -143,12 +141,13 @@ function clickMenuitem(label: string): void {
act(() => { item.click() })
}
-/** The progress line (a `Notice kind="loading"` live region). */
+/** The packing line (a `Notice kind="loading"` live region) — the whole
+ * progress UI now: the host's zip/tar reports no per-entry counts. */
function progressLine(container: HTMLElement): HTMLElement | null {
return container.querySelector('[data-kind="loading"]')
}
-/** Flush the pending promise chain (build / status / download). */
+/** Flush the pending promise chain (build / status / hand-off). */
async function flush(): Promise {
await act(async () => {
await Promise.resolve()
@@ -167,11 +166,9 @@ async function poll(): Promise {
})
}
-/** A `ready` status row. */
-function readyStatus(done: number, total: number): {
- state: 'ready'; done: number; total: number; bytes: number
-} {
- return { state: 'ready', done, total, bytes: 128 }
+/** A `ready` status row (`bytes` only — no `done`/`total` any more). */
+function readyStatus(bytes = 128): { state: 'ready'; bytes: number } {
+ return { state: 'ready', bytes }
}
let harness: Harness
@@ -183,20 +180,11 @@ const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementati
beforeEach(() => {
vi.useFakeTimers()
- vi.stubGlobal('fetch', fetchMock)
- fetchMock.mockReset()
- fetchMock.mockResolvedValue({
- ok: true,
- status: 200,
- blob: async () => new Blob(['zip-bytes'], { type: 'application/zip' }),
- } as unknown as Response)
archiveBuild.mockReset()
- archiveBuild.mockResolvedValue({ id: 'job-1', entries: 2 })
+ archiveBuild.mockResolvedValue({ id: 'job-1', name: 'archive.zip', entries: 2 })
archiveStatus.mockReset()
- archiveStatus.mockResolvedValue(readyStatus(2, 2))
+ archiveStatus.mockResolvedValue(readyStatus())
downloads.length = 0
- createdUrls.length = 0
- revokedUrls.length = 0
clickSpy.mockClear()
})
@@ -204,17 +192,16 @@ afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
vi.useRealTimers()
- vi.unstubAllGlobals()
})
describe('FileTree zip and download', () => {
- it('starts a job, shows done/total progress, then downloads the ready archive', async () => {
- // The first status is held open so the "build phase" (total known, no
- // progress yet) is observable: the poller runs its first tick immediately.
- let releaseStatus: (status: { state: 'building'; done: number; total: number; bytes: number }) => void = () => {}
+ it('starts a job with a stem, shows the packing line, then downloads the ready archive', async () => {
+ // The first status is held open so the packing phase is observable: the
+ // poller runs its first tick immediately.
+ let releaseStatus: (status: { state: 'building'; bytes: number }) => void = () => {}
archiveStatus
- .mockImplementationOnce(async () => await new Promise<{ state: 'building'; done: number; total: number; bytes: number }>(resolve => { releaseStatus = resolve }))
- .mockResolvedValueOnce(readyStatus(2, 2))
+ .mockImplementationOnce(async () => await new Promise<{ state: 'building'; bytes: number }>(resolve => { releaseStatus = resolve }))
+ .mockResolvedValueOnce(readyStatus())
harness = await mountTree()
click(rowByName(harness.container, 'a.ts'), { ctrlKey: true })
click(rowByName(harness.container, 'b.ts'), { ctrlKey: true })
@@ -223,34 +210,34 @@ describe('FileTree zip and download', () => {
clickMenuitem('Zip and download (2 items)')
await flush()
- // The job was started for the whole selection…
- expect(archiveBuild).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp/a.ts', '/tmp/b.ts'], 'archive.zip')
- // …the build phase shows the total it already knows…
- expect(progressLine(harness.container)?.textContent).toBe('Archiving 0/2 · 0%')
- // …the first poll advances the line…
+ // The job was started for the whole selection, named by a STEM: the host
+ // picks the extension of the tool it has and answers with the final name.
+ expect(archiveBuild).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp/a.ts', '/tmp/b.ts'], 'archive')
+ // …the packing line is up while the job runs…
+ expect(progressLine(harness.container)?.textContent).toBe(t('loading'))
+ // …a first poll that is still `building` keeps it, with no counts to show…
await act(async () => {
- releaseStatus({ state: 'building', done: 1, total: 2, bytes: 0 })
+ releaseStatus({ state: 'building', bytes: 0 })
await Promise.resolve()
await Promise.resolve()
})
- expect(progressLine(harness.container)?.textContent).toBe('Archiving 1/2 · 50%')
+ expect(progressLine(harness.container)?.textContent).toBe(t('loading'))
- // …and the next poll reports ready: the download runs and the line clears.
+ // …and the next poll reports ready: the anchor hands the route URL to the
+ // browser (which streams it to disk) and the line clears.
await poll()
await flush()
- expect(fetchMock).toHaveBeenCalledWith('/sidebar/archive/job-1')
- expect(downloads).toEqual(['blob:mock-1|archive.zip'])
+ expect(downloads).toEqual(['/sidebar/archive/job-1|archive.zip'])
expect(progressLine(harness.container)).toBeNull()
// The poll carries the session scope: the host requires BOTH keys on
// `archive.status`, so a bare `{ id }` is refused with a 400.
expect(archiveStatus).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, 'job-1')
- // The object URL is released on the next task.
- await act(async () => { await vi.advanceTimersByTimeAsync(1) })
- expect(revokedUrls).toEqual(['blob:mock-1'])
})
- it('archives a lone directory under its own name', async () => {
- archiveBuild.mockResolvedValue({ id: 'job-dir', entries: 3 })
+ it('archives a lone directory under its own stem, saved under the host name', async () => {
+ // A tar-only host: it appends ITS extension, so the anchor's `download`
+ // must be the returned name — a client-built `sub.zip` would be a lie.
+ archiveBuild.mockResolvedValue({ id: 'job-dir', name: 'sub.tar.gz', entries: 3 })
harness = await mountTree()
rightClick(rowByName(harness.container, 'sub'))
expect(menuLabels()).toContain('Zip and download')
@@ -258,18 +245,20 @@ describe('FileTree zip and download', () => {
await flush()
await poll()
await flush()
- expect(archiveBuild).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp/sub'], 'sub.zip')
- expect(downloads).toEqual(['blob:mock-1|sub.zip'])
+ expect(archiveBuild).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp/sub'], 'sub')
+ expect(downloads).toEqual(['/sidebar/archive/job-dir|sub.tar.gz'])
})
it('archives the workspace root row (a lone directory too)', async () => {
+ archiveBuild.mockResolvedValue({ id: 'job-root', name: 'tmp.zip', entries: 5 })
harness = await mountTree()
rightClick(rowByName(harness.container, 'tmp'))
clickMenuitem('Zip and download')
await flush()
await poll()
await flush()
- expect(archiveBuild).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp'], 'tmp.zip')
+ expect(archiveBuild).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, ['/tmp'], 'tmp')
+ expect(downloads).toEqual(['/sidebar/archive/job-root|tmp.zip'])
})
it('offers nothing for a lone FILE (the download row already covers it)', async () => {
@@ -293,8 +282,36 @@ describe('FileTree zip and download', () => {
expect(downloads).toEqual([])
})
+ it('explains a host with neither zip nor tar instead of echoing the wire message', async () => {
+ // `unavailable` is the ONE code with its own sentence: "no archive command
+ // is installed" is something the user can act on.
+ archiveBuild.mockRejectedValue(new SidebarApiError('unavailable', 'spawn zip ENOENT'))
+ harness = await mountTree()
+ rightClick(rowByName(harness.container, 'sub'))
+ clickMenuitem('Zip and download')
+ await flush()
+ const alert = harness.container.querySelector('[role="alert"]')?.textContent ?? ''
+ expect(alert).toContain(t('archiveToolMissing'))
+ expect(alert).not.toContain('spawn zip ENOENT')
+ expect(progressLine(harness.container)).toBeNull()
+ expect(archiveStatus).not.toHaveBeenCalled()
+ expect(downloads).toEqual([])
+ })
+
+ it('keeps the wire message for a build failure that is not `unavailable`', async () => {
+ archiveBuild.mockRejectedValue(new SidebarApiError('bad-request', 'selection contains a socket'))
+ harness = await mountTree()
+ rightClick(rowByName(harness.container, 'sub'))
+ clickMenuitem('Zip and download')
+ await flush()
+ expect(harness.container.querySelector('[role="alert"]')?.textContent)
+ .toContain('Archive failed: selection contains a socket')
+ expect(progressLine(harness.container)).toBeNull()
+ expect(downloads).toEqual([])
+ })
+
it('reports a status error state with the route message', async () => {
- archiveStatus.mockResolvedValue({ state: 'error', done: 1, total: 2, bytes: 0, error: 'archive too large' })
+ archiveStatus.mockResolvedValue({ state: 'error', bytes: 0, error: 'archive too large' })
harness = await mountTree()
rightClick(rowByName(harness.container, 'sub'))
clickMenuitem('Zip and download')
@@ -318,48 +335,12 @@ describe('FileTree zip and download', () => {
expect(downloads).toEqual([])
})
- it('reports a download refused by the route envelope', async () => {
- fetchMock.mockResolvedValue({
- ok: false,
- status: 413,
- json: async () => ({ ok: false, error: { code: 'bad-request', message: 'archive would exceed 64 MB' } }),
- } as unknown as Response)
- harness = await mountTree()
- rightClick(rowByName(harness.container, 'sub'))
- clickMenuitem('Zip and download')
- await flush()
- await poll()
- await flush()
- expect(harness.container.querySelector('[role="alert"]')?.textContent)
- .toContain('Archive failed: archive would exceed 64 MB')
- expect(downloads).toEqual([])
- expect(createdUrls).toEqual([])
- })
-
- it('falls back to the status when the download carries no JSON body', async () => {
- fetchMock.mockResolvedValue({
- ok: false,
- status: 500,
- json: async () => { throw new Error('not json') },
- } as unknown as Response)
- harness = await mountTree()
- rightClick(rowByName(harness.container, 'sub'))
- clickMenuitem('Zip and download')
- await flush()
- await poll()
- await flush()
- expect(harness.container.querySelector('[role="alert"]')?.textContent)
- .toContain('Archive failed: HTTP 500')
- expect(downloads).toEqual([])
- })
-
it('hands a ready job to the download exactly once, and stops polling first', async () => {
- // The download is held open, so the 250ms poller would tick again while the
- // GET is still in flight; `archiveStatus` keeps answering `ready`. The GET
- // CONSUMES the task, so a second hand-off either double-downloads or reads a
- // 404 and paints `zipFailed` beside a file that actually landed.
- let releaseDownload: (response: Response) => void = () => {}
- fetchMock.mockImplementation(async () => await new Promise(resolve => { releaseDownload = resolve }))
+ // The download route CONSUMES the task, so a second hand-off would either
+ // click the anchor twice or read a 404 and paint `zipFailed` beside a file
+ // that actually landed. The poller must therefore stop BEFORE the anchor
+ // runs — the three extra intervals below are the proof that it has.
+ archiveBuild.mockResolvedValue({ id: 'job-1', name: 'sub.zip', entries: 3 })
harness = await mountTree()
rightClick(rowByName(harness.container, 'sub'))
clickMenuitem('Zip and download')
@@ -367,31 +348,23 @@ describe('FileTree zip and download', () => {
await poll()
await flush()
expect(archiveStatus).toHaveBeenCalledTimes(1)
- expect(fetchMock).toHaveBeenCalledTimes(1)
- expect(downloads).toEqual([])
+ expect(downloads).toEqual(['/sidebar/archive/job-1|sub.zip'])
- // Three more poll intervals: no second download, no bogus failure strip.
+ // Three more poll intervals: no second poll, no second download, and no
+ // bogus failure strip.
await poll()
await poll()
await poll()
expect(archiveStatus).toHaveBeenCalledTimes(1)
- expect(fetchMock).toHaveBeenCalledTimes(1)
- expect(harness.container.querySelector('[role="alert"]')).toBeNull()
-
- await act(async () => {
- releaseDownload({ ok: true, status: 200, blob: async () => new Blob(['zip-bytes']) } as unknown as Response)
- await Promise.resolve()
- await Promise.resolve()
- })
- expect(downloads).toEqual(['blob:mock-1|sub.zip'])
+ expect(downloads).toEqual(['/sidebar/archive/job-1|sub.zip'])
expect(harness.container.querySelector('[role="alert"]')).toBeNull()
})
it('builds once while a job is in flight (double click guard)', async () => {
- let release: (job: { id: string; entries: number }) => void = () => {}
- archiveBuild.mockImplementation(async () => await new Promise<{ id: string; entries: number }>(resolve => { release = resolve }))
+ let release: (job: { id: string; name: string; entries: number }) => void = () => {}
+ archiveBuild.mockImplementation(async () => await new Promise<{ id: string; name: string; entries: number }>(resolve => { release = resolve }))
// Stay in the building state until the test says otherwise.
- archiveStatus.mockResolvedValue({ state: 'building', done: 0, total: 1, bytes: 0 })
+ archiveStatus.mockResolvedValue({ state: 'building', bytes: 0 })
harness = await mountTree()
const pick = (): void => {
rightClick(rowByName(harness.container, 'sub'))
@@ -406,9 +379,9 @@ describe('FileTree zip and download', () => {
expect(archiveBuild).toHaveBeenCalledTimes(1)
expect(archiveStatus).not.toHaveBeenCalled()
- await act(async () => { release({ id: 'job-2', entries: 1 }) })
+ await act(async () => { release({ id: 'job-2', name: 'sub.zip', entries: 1 }) })
await flush()
- expect(progressLine(harness.container)?.textContent).toBe('Archiving 0/1 · 0%')
+ expect(progressLine(harness.container)?.textContent).toBe(t('loading'))
await poll()
// Still building: the line stays and the guard still holds.
expect(progressLine(harness.container)).not.toBeNull()
@@ -417,23 +390,24 @@ describe('FileTree zip and download', () => {
expect(archiveBuild).toHaveBeenCalledTimes(1)
// Finish the job: the download runs, the line clears, the guard releases.
- archiveStatus.mockResolvedValue(readyStatus(1, 1))
+ archiveStatus.mockResolvedValue(readyStatus())
await poll()
await flush()
- expect(downloads).toEqual(['blob:mock-1|sub.zip'])
- archiveBuild.mockResolvedValue({ id: 'job-3', entries: 1 })
+ expect(downloads).toEqual(['/sidebar/archive/job-2|sub.zip'])
+ archiveBuild.mockResolvedValue({ id: 'job-3', name: 'sub.zip', entries: 1 })
pick()
await flush()
expect(archiveBuild).toHaveBeenCalledTimes(2)
await poll()
await flush()
+ expect(downloads).toEqual(['/sidebar/archive/job-2|sub.zip', '/sidebar/archive/job-3|sub.zip'])
})
it('does not resurrect a build that was still starting when the scope changed', async () => {
// The swap settles the archive. A build answering only afterwards used to
// pump its job id back in, restarting the poller in a project that never
// asked for a zip — and reporting the failure there.
- let resolveBuild!: (value: { id: string; entries: number }) => void
+ let resolveBuild!: (value: { id: string; name: string; entries: number }) => void
archiveBuild.mockImplementationOnce(() => new Promise((resolve) => { resolveBuild = resolve }))
harness = await mountTree()
@@ -448,7 +422,7 @@ describe('FileTree zip and download', () => {
await flush()
// The build answers only now.
- await act(async () => { resolveBuild({ id: 'job-stale', entries: 2 }) })
+ await act(async () => { resolveBuild({ id: 'job-stale', name: 'archive.zip', entries: 2 }) })
await flush()
await poll()
diff --git a/tests/file-types.spec.ts b/tests/file-types.spec.ts
index 32573bf9..ecebd3a1 100644
--- a/tests/file-types.spec.ts
+++ b/tests/file-types.spec.ts
@@ -79,6 +79,9 @@ describe('editor language mapping', () => {
['js', 'js'], ['mjs', 'js'], ['cjs', 'js'], ['jsx', 'jsx'],
['ts', 'ts'], ['mts', 'ts'], ['cts', 'ts'], ['tsx', 'tsx'],
['json', 'json'], ['jsonc', 'json'], ['md', 'md'], ['markdown', 'md'],
+ // Newline-delimited JSON has its own per-line language (a `json()` mapping
+ // would report every record after the first as a parse error).
+ ['jsonl', 'jsonl'], ['ndjson', 'jsonl'],
['py', 'python'], ['pyw', 'python'], ['html', 'html'], ['htm', 'html'],
['css', 'css'], ['xml', 'xml'], ['xsl', 'xml'], ['yaml', 'yaml'],
['yml', 'yaml'], ['sql', 'sql'], ['java', 'java'], ['cs', 'csharp'],
diff --git a/tests/trusted-hosts.spec.ts b/tests/trusted-hosts.spec.ts
index 7f258bd8..e5280f7d 100644
--- a/tests/trusted-hosts.spec.ts
+++ b/tests/trusted-hosts.spec.ts
@@ -16,6 +16,7 @@
*/
import { describe, expect, it } from 'vitest'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { Writable } from 'node:stream'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -30,19 +31,44 @@ interface FakeRes {
end(body?: string | Buffer): void
}
+/**
+ * The response face these fence assertions read, backed by a REAL Writable.
+ *
+ * `/sidebar/file` STREAMS now (`createReadStream` → `pipeline` into the
+ * response), and `pipeline` needs an actual writable destination rather than a
+ * plain object with an `end`. The status/header/body facade the assertions use
+ * is layered on the same object, so the media cases keep reading exactly what
+ * they read before.
+ */
function fakeRes(): FakeRes {
- return {
- status: 0,
- headers: {},
- body: '',
- writeHead(status, headers = {}) {
- this.status = status
- this.headers = headers
+ const chunks: Buffer[] = []
+ const stream = new Writable({
+ write(chunk: Buffer, _encoding, callback) {
+ chunks.push(Buffer.from(chunk))
+ callback()
},
- end(body) {
- if (body !== undefined) this.body = body.toString()
- },
- } as FakeRes
+ })
+ // Captured BEFORE the facade shadows the method: `facade === stream`, so
+ // calling `stream.end()` from the replacement would recurse into itself.
+ const finishStream = Writable.prototype.end.bind(stream)
+ const facade = stream as unknown as FakeRes
+ facade.status = 0
+ facade.headers = {}
+ facade.body = ''
+ const collect = (): void => { facade.body = Buffer.concat(chunks).toString('utf8') }
+ facade.writeHead = (status, headers = {}) => {
+ facade.status = status
+ facade.headers = headers
+ }
+ facade.end = (body) => {
+ if (body !== undefined) chunks.push(Buffer.from(body))
+ collect()
+ finishStream()
+ }
+ // `stream.end()` from the pipeline path never goes through `facade.end`, so
+ // the body is also harvested once the writable finishes.
+ stream.on('finish', collect)
+ return facade
}
function req(
diff --git a/tests/zip.spec.ts b/tests/zip.spec.ts
deleted file mode 100644
index 303e3c05..00000000
--- a/tests/zip.spec.ts
+++ /dev/null
@@ -1,948 +0,0 @@
-/**
- * ZIP builder + /sidebar/archive route.
- *
- * Two layers, no third-party ZIP dependency in either direction:
- * - `buildZip` is checked by a minimal reader written HERE (EOCD → central
- * directory → local header → inflate), so the test proves the bytes on the
- * wire, not the writer's own bookkeeping. `unzip -t` is an extra check when
- * the binary happens to exist (CI runners do not ship it).
- * - the route is mounted against a fake cordis context (the same shape
- * smoke.spec.ts uses) and answers a real request over a real temp
- * workspace, covering the fence, the parameter guards and a full
- * directory walk.
- */
-import './browser-globals.ts'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { spawnSync } from 'node:child_process'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
-import { validateHeaderValue } from 'node:http'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { inflateRawSync } from 'node:zlib'
-
-/** Windows has no POSIX file names and no POSIX mode bits (see the two guards below). */
-const isWin32 = process.platform === 'win32'
-import { apply } from '../src/index.ts'
-import { archiveDownloadUrl } from '../src/client/api.ts'
-import {
- ARCHIVE_MAX_BUILDING,
- ARCHIVE_TTL_MS,
- archiveNameOf,
- collectZipEntries,
- contentDispositionOf,
- createArchiveTasks,
- disambiguateArchiveNames,
- respondArchiveDownload,
- type ArchiveTasks,
-} from '../src/archive-route.ts'
-import { crc32, buildZip, type ZipEntry, type ZipProgress } from '../src/zip.ts'
-import { SidebarError } from '../src/wire.ts'
-import type { SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts'
-
-/** One parsed central-directory row + its local payload. */
-interface ParsedEntry {
- name: string
- method: number
- crc: number
- compressedSize: number
- size: number
- flags: number
- externalAttributes: number
- isDirectory: boolean
- data: Buffer
-}
-
-/**
- * Minimal ZIP reader: locate the EOCD from the tail, walk the central
- * directory, then read each local header's payload. Enough to verify names
- * (UTF-8), methods, CRCs, sizes and both compression branches.
- */
-function readZip(archive: Buffer): ParsedEntry[] {
- const eocdAt = archive.lastIndexOf(Buffer.from([0x50, 0x4B, 0x05, 0x06]))
- if (eocdAt < 0) throw new Error('no EOCD')
- if (eocdAt + 22 !== archive.length) throw new Error('EOCD is not the last record')
- const count = archive.readUInt16LE(eocdAt + 10)
- const directorySize = archive.readUInt32LE(eocdAt + 12)
- const directoryAt = archive.readUInt32LE(eocdAt + 16)
- if (count > 0 && archive.readUInt32LE(directoryAt) !== 0x02014B50) throw new Error('bad central directory signature')
- if (directoryAt + directorySize > eocdAt) throw new Error('central directory overruns the EOCD')
-
- const entries: ParsedEntry[] = []
- let cursor = directoryAt
- for (let index = 0; index < count; index += 1) {
- if (archive.readUInt32LE(cursor) !== 0x02014B50) throw new Error(`bad central header ${index}`)
- const flags = archive.readUInt16LE(cursor + 8)
- const method = archive.readUInt16LE(cursor + 10)
- const crc = archive.readUInt32LE(cursor + 16)
- const compressedSize = archive.readUInt32LE(cursor + 20)
- const size = archive.readUInt32LE(cursor + 24)
- const nameLength = archive.readUInt16LE(cursor + 28)
- const extraLength = archive.readUInt16LE(cursor + 30)
- const commentLength = archive.readUInt16LE(cursor + 32)
- const externalAttributes = archive.readUInt32LE(cursor + 38)
- const localAt = archive.readUInt32LE(cursor + 42)
- const name = archive.subarray(cursor + 46, cursor + 46 + nameLength).toString('utf8')
-
- if (archive.readUInt32LE(localAt) !== 0x04034B50) throw new Error(`bad local header for ${name}`)
- const localNameLength = archive.readUInt16LE(localAt + 26)
- const localExtraLength = archive.readUInt16LE(localAt + 28)
- if (archive.readUInt32LE(localAt + 14) !== crc) throw new Error(`local CRC mismatch for ${name}`)
- if (archive.readUInt32LE(localAt + 18) !== compressedSize) throw new Error(`local compressed size mismatch for ${name}`)
- if (archive.readUInt32LE(localAt + 22) !== size) throw new Error(`local size mismatch for ${name}`)
- const payloadAt = localAt + 30 + localNameLength + localExtraLength
- const payload = archive.subarray(payloadAt, payloadAt + compressedSize)
- entries.push({
- name,
- method,
- crc,
- compressedSize,
- size,
- flags,
- externalAttributes,
- isDirectory: name.endsWith('/'),
- data: method === 8 ? inflateRawSync(payload) : Buffer.from(payload),
- })
- cursor += 46 + nameLength + extraLength + commentLength
- }
- return entries
-}
-
-/** The host mounted against a fake context: both archive routes + the API. */
-function mountHost(): { api: SidebarWebRoute; download: SidebarWebRoute } {
- const routes: SidebarWebRoute[] = []
- const ctx = {
- webRuntime: { trustedHosts: [] },
- webServer: {
- register: (route: SidebarWebRoute) => { routes.push(route); return () => {} },
- registerUpgrade: (route: SidebarWebUpgradeRoute) => { void route; return () => {} },
- },
- sessions: { get: () => undefined },
- tools: { register: () => () => {} },
- effect: (fn: () => void | (() => void)) => { fn() },
- inject: () => () => {},
- on: () => () => {},
- get: () => undefined,
- }
- apply(ctx as never)
- const api = routes.find(candidate => candidate.path === '/sidebar/api')
- const download = routes.find(candidate => candidate.path === '/sidebar/archive')
- if (api === undefined) throw new Error('test setup: /sidebar/api route not registered')
- if (download === undefined) throw new Error('test setup: /sidebar/archive route not registered')
- return { api, download }
-}
-
-/** One POST /sidebar/api/ against the mounted API route. */
-async function post(
- api: SidebarWebRoute,
- method: string,
- payload: unknown,
-): Promise<{ status: number; ok: boolean; value?: unknown; error?: { code?: string; message?: string } }> {
- const body = Buffer.from(JSON.stringify(payload))
- const req = {
- method: 'POST',
- url: `/sidebar/api/${method}`,
- headers: { host: '127.0.0.1:3080' },
- [Symbol.asyncIterator]: async function* () { yield body },
- } as never
- const out: { status: number; body: string } = { status: 200, body: '' }
- const res = {
- writeHead: (status: number) => { out.status = status },
- end: (chunk: unknown) => { out.body += String(chunk ?? '') },
- } as never
- await api.handler(req, res)
- return { status: out.status, ...(JSON.parse(out.body) as { ok: boolean; value?: unknown; error?: { code?: string; message?: string } }) }
-}
-
-/** One GET against a mounted route, collecting raw bytes. */
-async function get(route: SidebarWebRoute, url: string): Promise<{ status: number; headers: Record; body: Buffer }> {
- const out: { status: number; headers: Record; chunks: Buffer[] } = { status: 200, headers: {}, chunks: [] }
- const req = { method: 'GET', url, headers: { host: '127.0.0.1:3080' } } as never
- const res = {
- writeHead: (status: number, headers: Record = {}) => { out.status = status; out.headers = headers },
- end: (chunk?: Buffer | string) => { if (chunk !== undefined) out.chunks.push(Buffer.from(chunk)) },
- } as never
- await route.handler(req, res)
- return { status: out.status, headers: out.headers, body: Buffer.concat(out.chunks) }
-}
-
-/** Poll `archive.status` until the detached build settles (or throw). */
-async function waitForReady(
- api: SidebarWebRoute,
- id: string,
- sessionId: string,
-): Promise<{ state: string; done: number; total: number; bytes: number; error?: string }> {
- let last: { state: string; done: number; total: number; bytes: number; error?: string } | undefined
- for (let attempt = 0; attempt < 400; attempt += 1) {
- const status = await post(api, 'archive.status', { id, sessionId })
- if (status.ok === true) {
- last = status.value as { state: string; done: number; total: number; bytes: number; error?: string }
- if (last.state !== 'building') return last
- }
- await new Promise(resolve => setTimeout(resolve, 5))
- }
- throw new Error(`test setup: archive ${id} never settled (${JSON.stringify(last)})`)
-}
-
-/**
- * The whole host flow for one selection: POST archive.build, poll until the
- * detached build settles, then GET the bytes. The caller's session id is both
- * the scope and the download's fence.
- */
-async function archiveFlow(input: {
- sessionId: string
- cwd: string
- name?: string
- paths: readonly string[]
-}): Promise<{ build: Awaited>; status: Awaited>; download: Awaited> }> {
- const { api, download } = mountHost()
- const build = await post(api, 'archive.build', {
- sessionId: input.sessionId,
- cwd: input.cwd,
- paths: [...input.paths],
- ...(input.name === undefined ? {} : { name: input.name }),
- })
- if (build.ok !== true || build.status !== 200) {
- return { build, status: await waitForReady(api, '', input.sessionId), download: await get(download, '/sidebar/archive') }
- }
- const id = (build.value as { id: string }).id
- const status = await waitForReady(api, id, input.sessionId)
- return {
- build,
- status,
- download: await get(download, `/sidebar/archive?sessionId=${encodeURIComponent(input.sessionId)}&id=${encodeURIComponent(id)}`),
- }
-}
-
-/** A temp workspace (plus an outside sibling) removed after each test. */
-const roots: string[] = []
-function tempRoot(): string {
- const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-zip-'))
- roots.push(root)
- return root
-}
-afterEach(() => {
- while (roots.length > 0) rmSync(roots.pop()!, { recursive: true, force: true })
-})
-
-describe('buildZip', () => {
- it('round-trips a deflated file: name, content and CRC-32', async () => {
- const root = tempRoot()
- const path = join(root, 'hello.txt')
- const content = 'hello zip\n'.repeat(200)
- writeFileSync(path, content)
- const archive = await buildZip([{ path, name: 'hello.txt' }])
- const entries = readZip(archive)
- expect(entries).toHaveLength(1)
- const entry = entries[0]!
- expect(entry.name).toBe('hello.txt')
- expect(entry.method).toBe(8)
- expect(entry.data.toString('utf8')).toBe(content)
- expect(entry.crc).toBe(crc32(Buffer.from(content)))
- expect(entry.size).toBe(Buffer.byteLength(content))
- expect(entry.isDirectory).toBe(false)
- })
-
- it('stores incompressible data (method 0) and marks UTF-8 names (bit 11)', async () => {
- const root = tempRoot()
- const path = join(root, 'random.bin')
- // High-entropy bytes: deflateRaw expands them (4096 → ~4100), so the
- // writer must fall back to `store`. Generated from a fixed seed so the
- // case stays deterministic.
- const random = Buffer.alloc(4096)
- let state = 0x9E3779B9
- for (let i = 0; i < random.length; i += 1) {
- state = (Math.imul(state, 1664525) + 1013904223) >>> 0
- random[i] = (state >>> 16) & 0xFF
- }
- writeFileSync(path, random)
- const archive = await buildZip([{ path, name: '数据/随机.bin' }])
- const entries = readZip(archive)
- expect(entries).toHaveLength(1)
- const entry = entries[0]!
- expect(entry.method).toBe(0)
- expect(entry.name).toBe('数据/随机.bin')
- expect((entry.flags & 0x0800) !== 0).toBe(true)
- expect(entry.data.equals(random)).toBe(true)
- expect(entry.crc).toBe(crc32(random))
- })
-
- it('writes directory rows with a trailing slash, zero payload and the dir attribute', async () => {
- const root = tempRoot()
- mkdirSync(join(root, 'nested'))
- writeFileSync(join(root, 'nested', 'a.txt'), 'a')
- const archive = await buildZip([
- { path: join(root, 'nested'), name: 'nested', isDir: true },
- { path: join(root, 'nested', 'a.txt'), name: 'nested/a.txt' },
- ])
- const entries = readZip(archive)
- expect(entries.map(entry => entry.name)).toEqual(['nested/', 'nested/a.txt'])
- const dir = entries[0]!
- expect(dir.isDirectory).toBe(true)
- expect(dir.size).toBe(0)
- expect(dir.crc).toBe(0)
- // The external-attributes word carries the Unix mode in the high half and
- // the MS-DOS directory bit in the low half: without the mode Info-ZIP
- // extracts every member as mode 000.
- expect(dir.externalAttributes & 0x10).toBe(0x10)
- expect(dir.externalAttributes >>> 16).toBe(0o40755)
- expect(entries[1]!.externalAttributes & 0x10).toBe(0)
- expect(entries[1]!.externalAttributes >>> 16).toBe(0o100644)
- })
-
- it('accepts an empty directory set and produces a valid empty archive', async () => {
- const archive = await buildZip([])
- expect(readZip(archive)).toEqual([])
- expect(archive.readUInt32LE(archive.length - 22)).toBe(0x06054B50)
- })
-
- it('reports progress per entry, monotonically, ending at the entry count', async () => {
- const root = tempRoot()
- mkdirSync(join(root, 'dir'))
- writeFileSync(join(root, 'a.txt'), 'a'.repeat(10))
- writeFileSync(join(root, 'dir', 'b.txt'), 'b'.repeat(30))
- const seen: ZipProgress[] = []
- await buildZip([
- { path: join(root, 'dir'), name: 'dir', isDir: true },
- { path: join(root, 'dir', 'b.txt'), name: 'dir/b.txt' },
- { path: join(root, 'a.txt'), name: 'a.txt' },
- ], { onProgress: (progress) => seen.push({ ...progress }) })
- expect(seen).toHaveLength(3)
- expect(seen.map(step => step.done)).toEqual([1, 2, 3])
- expect(seen.every(step => step.total === 3)).toBe(true)
- // `bytes` counts uncompressed payload and never shrinks. The directory row
- // adds nothing; b.txt (30) then a.txt (10) bring it to 40.
- expect(seen.map(step => step.bytes)).toEqual([0, 30, 40])
- // A failed entry reports nothing for itself (the throw ends the build).
- const failed: ZipProgress[] = []
- await expect(buildZip([
- { path: join(root, 'a.txt'), name: 'a.txt' },
- { path: join(root, 'missing.txt'), name: 'missing.txt' },
- ], { onProgress: (progress) => failed.push({ ...progress }) }))
- .rejects.toMatchObject({ code: 'fs-error' })
- expect(failed.map(step => step.done)).toEqual([1])
- })
-
- it('rejects an over-limit entry count before reading anything', async () => {
- const root = tempRoot()
- const path = join(root, 'a.txt')
- writeFileSync(path, 'a')
- await expect(buildZip([{ path, name: 'a.txt' }], { maxEntries: 0 })).rejects.toThrow(SidebarError)
- await expect(buildZip([{ path, name: 'a.txt' }], { maxEntries: 0 })).rejects.toMatchObject({ code: 'fs-error' })
- })
-
- it('rejects an over-limit payload with fs-error', async () => {
- const root = tempRoot()
- const path = join(root, 'big.txt')
- writeFileSync(path, 'x'.repeat(4096))
- await expect(buildZip([{ path, name: 'big.txt' }], { maxBytes: 1024 }))
- .rejects.toMatchObject({ code: 'fs-error' })
- })
-
- it('enforces the byte bound BEFORE reading the payload (stat first)', async () => {
- const root = tempRoot()
- const huge = join(root, 'huge.bin')
- writeFileSync(huge, Buffer.alloc(4 * 1024 * 1024, 7))
- // A source far past the budget is refused on its stat, with the archive's
- // own ceiling in the message (never an internal budget number)…
- await expect(buildZip([{ path: huge, name: 'huge.bin' }], { maxBytes: 1024 }))
- .rejects.toThrow(/exceeds the 1024 byte limit/)
- await expect(buildZip([{ path: huge, name: 'huge.bin' }], { maxBytes: 1024 }))
- .rejects.toMatchObject({ code: 'fs-error' })
- // maxBytes: 0 refuses even a one-byte source.
- const one = join(root, 'one.txt')
- writeFileSync(one, 'x')
- await expect(buildZip([{ path: one, name: 'one.txt' }], { maxBytes: 0 }))
- .rejects.toThrow(/exceeds the 0 byte limit/)
- // …and a source that exactly fills the budget is accepted.
- const two = join(root, 'two.txt')
- writeFileSync(two, 'xy')
- expect(readZip(await buildZip([{ path: two, name: 't.txt' }], { maxBytes: 2 }))[0]!.size).toBe(2)
- // The budget is the REMAINING allowance: the second entry no longer fits
- // (an exhausted budget refuses even a zero-byte source, so a FIFO can
- // never be opened — see the probe below).
- const empty = join(root, 'empty.txt')
- writeFileSync(empty, '')
- await expect(buildZip([{ path: two, name: 'a.txt' }, { path: empty, name: 'b.txt' }], { maxBytes: 2 }))
- .rejects.toMatchObject({ code: 'fs-error' })
- })
-
- it('never opens a source the size probe already refused (FIFO)', async () => {
- if (process.platform === 'win32') return // no FIFOs there
- const root = tempRoot()
- const fifo = join(root, 'pipe')
- const made = spawnSync('mkfifo', [fifo], { encoding: 'utf8' })
- if (made.error !== undefined || made.status !== 0) return // binary absent: skip
- // A 2-byte file consumes the whole 2-byte budget, so the FIFO's remaining
- // allowance is 0. Reading an unwritten FIFO BLOCKS FOREVER, so this test
- // can only complete when the size probe refuses it before open() — with the
- // read-then-check order it hangs and vitest fails it on timeout instead.
- // (This is the discriminating guard for F3: a "rejects quickly" timing
- // probe does NOT discriminate, because the reverted code also rejects.)
- const two = join(root, 'two.txt')
- writeFileSync(two, 'xy')
- await expect(buildZip([{ path: two, name: 'a.txt' }, { path: fifo, name: 'p' }], { maxBytes: 2 }))
- .rejects.toThrow(/exceeds the 2 byte limit/)
- }, 5_000)
-
- it('reports an unreadable source as fs-error and refuses traversal names', async () => {
- const root = tempRoot()
- await expect(buildZip([{ path: join(root, 'missing.txt'), name: 'missing.txt' }]))
- .rejects.toMatchObject({ code: 'fs-error' })
- await expect(buildZip([{ path: join(root, 'x'), name: '../escape.txt' }]))
- .rejects.toMatchObject({ code: 'bad-request' })
- })
-
- // POSIX-only: on Windows a backslash IS the separator, so `a\b.txt` can only
- // ever mean the file `b.txt` inside the directory `a` (the write below fails
- // with ENOENT). The literal-name semantics under test do not exist there.
- it.skipIf(isWin32)('keeps a backslash as part of the file name (POSIX names are literal)', async () => {
- const root = tempRoot()
- // `a\b.txt` is ONE legal POSIX file name; splitting it into a directory
- // would silently rename the member (F8).
- const path = join(root, 'a\\b.txt')
- writeFileSync(path, 'literal\n')
- const archive = await buildZip([{ path, name: 'a\\b.txt' }])
- const entries = readZip(archive)
- expect(entries).toHaveLength(1)
- expect(entries[0]!.name).toBe('a\\b.txt')
- expect(entries[0]!.data.toString('utf8')).toBe('literal\n')
- // A traversal name is still refused, and so is a bare '..'.
- await expect(buildZip([{ path, name: 'dir/../../x' }])).rejects.toMatchObject({ code: 'bad-request' })
- await expect(buildZip([{ path, name: '..' }])).rejects.toMatchObject({ code: 'bad-request' })
- })
-
- it('passes `unzip -t` when the binary exists (skipped otherwise)', async () => {
- const probe = spawnSync('unzip', ['-v'], { encoding: 'utf8' })
- if (probe.error !== undefined || probe.status !== 0) return
- const root = tempRoot()
- const content = 'unzip parity\n'.repeat(100)
- writeFileSync(join(root, 'a.txt'), content)
- mkdirSync(join(root, 'dir'))
- writeFileSync(join(root, 'dir', 'b.txt'), content)
- const archive = await buildZip([
- { path: join(root, 'a.txt'), name: 'a.txt' },
- { path: join(root, 'dir'), name: 'dir', isDir: true },
- { path: join(root, 'dir', 'b.txt'), name: 'dir/b.txt' },
- ])
- const file = join(root, 'out.zip')
- writeFileSync(file, archive)
- const result = spawnSync('unzip', ['-t', file], { encoding: 'utf8' })
- expect(result.status, result.stderr).toBe(0)
- expect(result.stdout).toContain('No errors detected')
- // `-t` only checks CRCs; extract too, so a broken external-attributes word
- // (Info-ZIP writes mode 000 files) cannot pass unnoticed.
- const extracted = join(root, 'out')
- const unpack = spawnSync('unzip', ['-o', file, '-d', extracted], { encoding: 'utf8' })
- expect(unpack.status, unpack.stderr).toBe(0)
- if (!isWin32) {
- // POSIX-only: Windows maps every file to 0o666 on both sides, so the
- // exact-mode parity below can only be asserted where mode bits exist.
- const inMode = statSync(join(root, 'a.txt')).mode & 0o777
- const outMode = statSync(join(extracted, 'a.txt')).mode & 0o777
- expect(outMode).toBe(inMode & 0o644)
- }
- expect(readFileSync(join(extracted, 'a.txt'), 'utf8')).toBe(content)
- expect(readFileSync(join(extracted, 'dir', 'b.txt'), 'utf8')).toBe(content)
- })
-})
-
-describe('collectZipEntries', () => {
- it('walks directories depth-first in name order and bounds the row count', async () => {
- const root = tempRoot()
- mkdirSync(join(root, 'd'))
- writeFileSync(join(root, 'a.txt'), 'a')
- writeFileSync(join(root, 'd', 'b.txt'), 'b')
- const entries: ZipEntry[] = []
- await collectZipEntries(root, 'root', entries)
- expect(entries.map(entry => entry.name)).toEqual(['root', 'root/a.txt', 'root/d', 'root/d/b.txt'])
- expect(entries[0]!.isDir).toBe(true)
-
- const bounded: ZipEntry[] = []
- await expect(collectZipEntries(root, 'root', bounded, 2))
- .rejects.toMatchObject({ code: 'fs-error' })
- // The bound stops the walk early instead of filling the list first.
- expect(bounded.length).toBeLessThanOrEqual(2)
- })
-
- it('treats an unreadable row as fs-error', async () => {
- const root = tempRoot()
- const entries: ZipEntry[] = []
- await expect(collectZipEntries(join(root, 'missing'), 'missing', entries))
- .rejects.toMatchObject({ code: 'fs-error' })
- })
-})
-
-describe('archiveNameOf', () => {
- it('strips separators / quotes / control chars and applies the .zip suffix once', () => {
- expect(archiveNameOf(null)).toBe('archive.zip')
- expect(archiveNameOf('')).toBe('archive.zip')
- expect(archiveNameOf(' ')).toBe('archive.zip')
- expect(archiveNameOf('docs')).toBe('docs.zip')
- expect(archiveNameOf('docs.zip')).toBe('docs.zip')
- expect(archiveNameOf('DOCS.ZIP')).toBe('DOCS.ZIP')
- // Path separators, traversal dots and quotes never survive.
- expect(archiveNameOf('../../etc/passwd')).toBe('etcpasswd.zip')
- expect(archiveNameOf('a\\b".zip')).toBe('ab.zip')
- expect(archiveNameOf('bad\u0000name\u001F.zip')).toBe('badname.zip')
- // Length is capped, and a bare ".zip" input falls back to the default.
- expect(archiveNameOf(`${'x'.repeat(300)}.zip`).length).toBe(124)
- expect(archiveNameOf('.zip')).toBe('archive.zip')
- })
-})
-
-describe('contentDispositionOf', () => {
- it('never puts a non-latin1 character in the header value', () => {
- const header = contentDispositionOf('报告.zip')
- // Node's writeHead rejects any header value above U+00FF — the whole
- // reason the raw name cannot be used (it 500s the route). Control: the
- // exact shape this fix replaced must FAIL the same check.
- expect(() => validateHeaderValue('content-disposition', 'attachment; filename="报告.zip"'))
- .toThrow(/Invalid character in header content/)
- expect([...header].every(char => char.codePointAt(0)! <= 0xFF)).toBe(true)
- expect(validateHeaderValue('content-disposition', header)).toBeUndefined()
- expect(header).toBe(`attachment; filename="download.zip"; filename*=UTF-8''${encodeURIComponent('报告.zip')}`)
- })
-
- it('keeps a plain ASCII name in both halves (suffix stripped for the fallback stem only)', () => {
- const header = contentDispositionOf('docs.zip')
- expect(header).toBe(`attachment; filename="docs.zip"; filename*=UTF-8''docs.zip`)
- expect(validateHeaderValue('content-disposition', header)).toBeUndefined()
- // A mixed name keeps whatever ASCII survives in the fallback.
- expect(contentDispositionOf('報告 Q3.zip')).toContain('filename=" Q3.zip"')
- })
-})
-
-describe('disambiguateArchiveNames', () => {
- it('keeps the basename when nothing collides', () => {
- expect(disambiguateArchiveNames(['/ws/src', '/ws/notes.md'])).toEqual(['src', 'notes.md'])
- })
-
- it('prepends parent directories only for the colliding selections', () => {
- expect(disambiguateArchiveNames(['/ws/a/index.ts', '/ws/b/index.ts']))
- .toEqual(['a/index.ts', 'b/index.ts'])
- // The unaffected selection keeps its short name.
- expect(disambiguateArchiveNames(['/ws/a/index.ts', '/ws/notes.md']))
- .toEqual(['index.ts', 'notes.md'])
- })
-
- it('walks further up while ancestors still collide', () => {
- // Both are `src/index.ts` relative to their own parent: one more level.
- expect(disambiguateArchiveNames(['/ws/a/src/index.ts', '/ws/b/src/index.ts']))
- .toEqual(['a/src/index.ts', 'b/src/index.ts'])
- })
-
- it('falls back to the full path when no ancestor can separate the names', () => {
- expect(disambiguateArchiveNames(['/ws/a.txt', '/ws/a.txt'])).toEqual(['ws/a.txt', 'ws/a.txt'])
- })
-})
-
-describe('archive task flow (build → status → download)', () => {
- it('archive client helpers build the frozen request/URL shapes', () => {
- expect(archiveDownloadUrl({ sessionId: 's-1' }, 'ar-9'))
- .toBe('http://localhost/sidebar/archive?sessionId=s-1&id=ar-9')
- })
-
- it('zips a selected file and a selected directory, walking it recursively', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(join(workspace, 'src', 'deep'), { recursive: true })
- writeFileSync(join(workspace, 'src', 'index.ts'), 'export {}\n')
- writeFileSync(join(workspace, 'src', 'deep', 'nested.ts'), 'nested\n')
- writeFileSync(join(workspace, 'notes.md'), '# notes\n')
- const { build, download } = await archiveFlow({
- sessionId: 's-zip',
- cwd: workspace,
- name: '我的打包.zip',
- paths: [join(workspace, 'src'), join(workspace, 'notes.md')],
- })
- expect(build.ok).toBe(true)
- expect(build.status).toBe(200)
- expect(build.value).toMatchObject({ entries: 5 })
- expect(download.status).toBe(200)
- expect(download.headers['content-type']).toBe('application/zip')
- // F1: the name is never header-raw. See the real-HTTP case below for the
- // node:http proof that a non-latin1 name no longer 500s.
- expect(download.headers['content-disposition'])
- .toBe(`attachment; filename="download.zip"; filename*=UTF-8''${encodeURIComponent('我的打包.zip')}`)
- expect(Number(download.headers['content-length'])).toBe(download.body.byteLength)
- const entries = readZip(download.body)
- expect(entries.map(entry => entry.name)).toEqual([
- 'src/',
- 'src/deep/',
- 'src/deep/nested.ts',
- 'src/index.ts',
- 'notes.md',
- ])
- const byName = new Map(entries.map(entry => [entry.name, entry]))
- expect(byName.get('src/index.ts')!.data.toString('utf8')).toBe('export {}\n')
- expect(byName.get('notes.md')!.data.toString('utf8')).toBe('# notes\n')
- })
-
- it('reports progress through archive.status and releases after the download', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(workspace, { recursive: true })
- writeFileSync(join(workspace, 'a.txt'), 'a\n')
- writeFileSync(join(workspace, 'b.txt'), 'b\n')
- const { api, download } = mountHost()
- const build = await post(api, 'archive.build', { sessionId: 's-zip', cwd: workspace, paths: [join(workspace, 'a.txt'), join(workspace, 'b.txt')] })
- expect(build.ok).toBe(true)
- const id = (build.value as { id: string }).id
- const status = await post(api, 'archive.status', { id, sessionId: 's-zip' })
- expect(status.ok).toBe(true)
- const first = status.value as { state: string; done: number; total: number; bytes: number }
- expect(first.total).toBe(2)
- expect(['building', 'ready']).toContain(first.state)
- expect(first.done).toBeGreaterThanOrEqual(0)
- expect(first.bytes).toBeGreaterThanOrEqual(0)
- const settled = await waitForReady(api, id, 's-zip')
- expect(settled.state).toBe('ready')
- expect(settled.done).toBe(2)
- // The download serves the bytes…
- const served = await get(download, `/sidebar/archive?sessionId=s-zip&id=${encodeURIComponent(id)}`)
- expect(served.status).toBe(200)
- // …and consumes the task: a second fetch is a 404.
- const second = await get(download, `/sidebar/archive?sessionId=s-zip&id=${encodeURIComponent(id)}`)
- expect(second.status).toBe(404)
- const gone = await post(api, 'archive.status', { id, sessionId: 's-zip' })
- expect(gone.ok).toBe(false)
- expect(gone.error?.code).toBe('not-found')
- })
-
- it('settles to ready with done === total (progress is monotonic and complete)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(workspace, { recursive: true })
- for (const name of ['a.txt', 'b.txt', 'c.txt']) writeFileSync(join(workspace, name), name)
- const { api } = mountHost()
- const build = await post(api, 'archive.build', {
- sessionId: 's-zip',
- cwd: workspace,
- paths: [join(workspace, 'a.txt'), join(workspace, 'b.txt'), join(workspace, 'c.txt')],
- })
- const id = (build.value as { id: string }).id
- // The build is detached; poll until it settles. Every poll must be
- // monotonic (done never goes backwards, bytes never shrink).
- let previousDone = -1
- let previousBytes = -1
- let settled: { state: string; done: number; total: number; bytes: number } | undefined
- for (let attempt = 0; attempt < 200; attempt += 1) {
- const status = await post(api, 'archive.status', { id, sessionId: 's-zip' })
- const value = status.value as { state: string; done: number; total: number; bytes: number }
- expect(value.done).toBeGreaterThanOrEqual(previousDone)
- expect(value.bytes).toBeGreaterThanOrEqual(previousBytes)
- previousDone = value.done
- previousBytes = value.bytes
- if (value.state !== 'building') { settled = value; break }
- await new Promise(resolve => setTimeout(resolve, 5))
- }
- expect(settled?.state).toBe('ready')
- expect(settled?.total).toBe(3)
- expect(settled?.done).toBe(3)
- })
-
- it('refuses another session\'s task (403) and an unknown id (404)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(workspace, { recursive: true })
- writeFileSync(join(workspace, 'a.txt'), 'a')
- const { api, download } = mountHost()
- const build = await post(api, 'archive.build', { sessionId: 's-zip', cwd: workspace, paths: [join(workspace, 'a.txt')] })
- const id = (build.value as { id: string }).id
- const foreign = await post(api, 'archive.status', { id, sessionId: 's-other' })
- expect(foreign.ok).toBe(false)
- expect(foreign.error?.code).toBe('forbidden')
- const foreignDownload = await get(download, `/sidebar/archive?sessionId=s-other&id=${encodeURIComponent(id)}`)
- expect(foreignDownload.status).toBe(403)
- const unknown = await post(api, 'archive.status', { id: 'ar-nope', sessionId: 's-zip' })
- expect(unknown.error?.code).toBe('not-found')
- // The failed foreign reads did not consume the task.
- await waitForReady(api, id, 's-zip')
- const own = await get(download, `/sidebar/archive?sessionId=s-zip&id=${encodeURIComponent(id)}`)
- expect(own.status).toBe(200)
- })
-
- it('caps concurrent builds (the 5th start is refused)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(workspace, { recursive: true })
- writeFileSync(join(workspace, 'a.txt'), 'a')
- const { api } = mountHost()
- const tasks = createArchiveTasks()
- expect(ARCHIVE_MAX_BUILDING).toBe(4)
- // A large entry set keeps each detached build running across the next
- // start (a 1-entry build can finish between two awaits).
- const big = join(workspace, 'big.bin')
- writeFileSync(big, Buffer.alloc(2 * 1024 * 1024, 3))
- for (let index = 0; index < ARCHIVE_MAX_BUILDING; index += 1) {
- tasks.start({ sessionId: 's', name: 'x.zip', entries: [{ path: big, name: 'big.bin' }] })
- }
- expect(() => tasks.start({ sessionId: 's', name: 'x.zip', entries: [{ path: big, name: 'big.bin' }] }))
- .toThrow(/too many archives are being built/)
- // The API route surfaces the same refusal as a bad-request envelope.
- for (let index = 0; index < ARCHIVE_MAX_BUILDING; index += 1) {
- const accepted = await post(api, 'archive.build', { sessionId: 's-zip', cwd: workspace, paths: [big] })
- expect(accepted.ok).toBe(true)
- }
- const refused = await post(api, 'archive.build', { sessionId: 's-zip', cwd: workspace, paths: [big] })
- expect(refused.ok).toBe(false)
- expect(refused.error?.message).toMatch(/too many archives/)
- })
-
- it('surfaces a build failure as an error task with its message', async () => {
- const root = tempRoot()
- const missing = join(root, 'missing.txt')
- // The route's collector lstat's every selection, so a missing path never
- // becomes a task at all (the POST refuses it). The DETACHED failure is the
- // race the task state exists for — a source that vanishes after the walk —
- // so it is exercised on the table directly, then through the route by
- // making an errored task's TTL expire.
- const tasks = createArchiveTasks()
- const started = tasks.start({ sessionId: 's', name: 'x.zip', entries: [{ path: missing, name: 'missing.txt' }] })
- await vi.waitFor(() => { expect(tasks.status(started.id, 's').state).toBe('error') })
- const errored = tasks.status(started.id, 's')
- expect(errored.state).toBe('error')
- expect(errored.error).toMatch(/missing\.txt/)
- expect(tasks.lookup(started.id, 's')).toMatchObject({ ok: false, reason: 'error' })
- // An errored task answers its download with 410 Gone, not a silent 404.
- const { api, download } = mountHost()
- const refused = await post(api, 'archive.build', { sessionId: 's-zip', cwd: root, paths: [missing] })
- expect(refused.ok).toBe(false)
- expect(refused.error?.code).toBe('fs-error')
- const gone = await get(download, `/sidebar/archive?sessionId=s-zip&id=ar-nope`)
- expect(gone.status).toBe(404)
- })
-
- it('answers a failed build with 410 Gone and another session with 403', async () => {
- const root = tempRoot()
- const missing = join(root, 'missing.txt')
- const tasks = createArchiveTasks()
- const started = tasks.start({ sessionId: 's', name: 'x.zip', entries: [{ path: missing, name: 'missing.txt' }] })
- await vi.waitFor(() => { expect(tasks.status(started.id, 's').state).toBe('error') })
- // Every non-200 branch of the download route, through its own mapping.
- const answer = (sessionId: string | null, id: string | null): { status: number; error?: string } => {
- const out: { status: number; error?: string } = { status: 0 }
- try {
- respondArchiveDownload(tasks, { sessionId, id }, {
- writeHead: (status) => { out.status = status },
- end: () => {},
- })
- } catch (error) {
- out.error = error instanceof Error ? error.message : String(error)
- out.status = error instanceof SidebarError ? error.status : 500
- }
- return out
- }
- expect(answer('s', started.id)).toMatchObject({ status: 410, error: expect.stringMatching(/missing\.txt/) })
- expect(answer('other', started.id)).toMatchObject({ status: 403 })
- expect(answer(null, started.id)).toMatchObject({ status: 400 })
- expect(answer('s', null)).toMatchObject({ status: 400 })
- expect(answer('s', 'ar-nope')).toMatchObject({ status: 404 })
- // The 409 and 200 branches get a STUB table: a real build of a one-file
- // archive can already be ready by the next line, which would test timing
- // rather than the mapping.
- const stubFile = join(root, 'stub.txt')
- writeFileSync(stubFile, 'stub')
- const bytes = await buildZip([{ path: stubFile, name: 'stub.txt' }])
- let released = 0
- const fake = (lookup: ArchiveTasks['lookup']): ArchiveTasks => ({
- start: () => { throw new Error('not used') },
- status: () => { throw new Error('not used') },
- lookup,
- release: () => { released += 1 },
- size: () => 0,
- })
- const building = fake(() => ({ ok: false, reason: 'building', message: 'archive is still being built' }))
- const buildAnswer = (tasks: ArchiveTasks): { status: number; error?: string } => {
- const out: { status: number; error?: string } = { status: 0 }
- try {
- respondArchiveDownload(tasks, { sessionId: 's', id: 'ar-1' }, { writeHead: (status) => { out.status = status }, end: () => {} })
- } catch (error) {
- out.error = error instanceof Error ? error.message : String(error)
- out.status = error instanceof SidebarError ? error.status : 500
- }
- return out
- }
- expect(buildAnswer(building)).toMatchObject({ status: 409, error: expect.stringMatching(/still being built/) })
- const ready = fake(() => ({
- ok: true,
- task: { id: 'ar-1', sessionId: 's', name: '报告.zip', state: 'ready', done: 1, total: 1, bytes: 1, zip: bytes, expiresAt: 0 },
- }))
- const wire: { status: number; headers?: Record; body?: Buffer } = { status: 0 }
- respondArchiveDownload(ready, { sessionId: 's', id: 'ar-1' }, {
- writeHead: (status, headers) => { wire.status = status; wire.headers = headers },
- end: (chunk) => { wire.body = Buffer.from(chunk ?? '') },
- })
- expect(wire.status).toBe(200)
- expect(wire.headers?.['content-disposition']).toContain(`filename*=UTF-8''${encodeURIComponent('报告.zip')}`)
- expect(wire.headers?.['content-length']).toBe(String(bytes.byteLength))
- expect(wire.body!.equals(bytes)).toBe(true)
- expect(released).toBe(1)
- })
-
- it('serves a non-latin1 download name through REAL node:http (no 500, RFC 5987)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(join(workspace, '报告'), { recursive: true })
- writeFileSync(join(workspace, '报告', '数据.txt'), 'x\n')
- const { api, download } = mountHost()
- const name = '报告.zip'
- const { createServer } = await import('node:http')
- const server = createServer((req, res) => { void download.handler(req as never, res as never) })
- await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
- try {
- const address = server.address()
- if (address === null || typeof address === 'string') throw new Error('test setup: no server port')
- const build = await post(api, 'archive.build', { sessionId: 's-zip', cwd: workspace, name, paths: [join(workspace, '报告')] })
- const id = (build.value as { id: string }).id
- await waitForReady(api, id, 's-zip')
- // The route handler answers a REAL ServerResponse here: node:http's
- // writeHead validates header values, which the plain-object stub in the
- // other cases cannot do — that is exactly how the Chinese-name 500 hid.
- const response = await fetch(`http://127.0.0.1:${address.port}/sidebar/archive?sessionId=s-zip&id=${encodeURIComponent(id)}`)
- expect(response.status).toBe(200)
- const disposition = response.headers.get('content-disposition') ?? ''
- // The ASCII half is what old clients read; the RFC 5987 half carries the
- // real name and is what every current browser picks.
- expect(disposition).toContain(`filename*=UTF-8''${encodeURIComponent(name)}`)
- expect(disposition).toContain('filename="download.zip"')
- // The header VALUE must be latin1-clean (Node's own rule).
- expect([...disposition].every(char => char.codePointAt(0)! <= 0xFF)).toBe(true)
- const entries = readZip(Buffer.from(await response.arrayBuffer()))
- expect(entries.map(entry => entry.name)).toEqual(['报告/', '报告/数据.txt'])
- } finally {
- await new Promise(resolve => server.close(() => resolve()))
- }
- })
-
- it('disambiguates same-name selections with their parent directories', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(join(workspace, 'a'), { recursive: true })
- mkdirSync(join(workspace, 'b'), { recursive: true })
- writeFileSync(join(workspace, 'a', 'index.ts'), 'from a\n')
- writeFileSync(join(workspace, 'b', 'index.ts'), 'from b\n')
- const { download } = await archiveFlow({
- sessionId: 's-zip',
- cwd: workspace,
- paths: [join(workspace, 'a', 'index.ts'), join(workspace, 'b', 'index.ts')],
- })
- expect(download.status).toBe(200)
- const entries = readZip(download.body)
- const names = entries.map(entry => entry.name)
- expect(new Set(names).size).toBe(names.length)
- expect(names).toEqual(['a/index.ts', 'b/index.ts'])
- const byName = new Map(entries.map(entry => [entry.name, entry]))
- expect(byName.get('a/index.ts')!.data.toString('utf8')).toBe('from a\n')
- expect(byName.get('b/index.ts')!.data.toString('utf8')).toBe('from b\n')
- })
-
- it('zips a path outside the session workspace (fence removed)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- const outside = join(root, 'outside')
- mkdirSync(workspace)
- mkdirSync(outside)
- writeFileSync(join(outside, 'secret.txt'), 'secret')
- const { download } = await archiveFlow({
- sessionId: 's-zip',
- cwd: workspace,
- paths: [join(outside, 'secret.txt')],
- })
- // ⚠️ PERMISSION CHANGE: an absolute path outside the workspace is now a
- // normal selection (no 403 branch exists any more).
- expect(download.status).toBe(200)
- const entries = readZip(download.body)
- expect(entries.map(entry => entry.name)).toEqual(['secret.txt'])
- expect(entries[0]!.data.toString('utf8')).toBe('secret')
- })
-
- it('skips a symlink row while walking a directory (no escape by following)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- const outside = join(root, 'outside')
- mkdirSync(workspace)
- mkdirSync(outside)
- writeFileSync(join(outside, 'secret.txt'), 'secret')
- try {
- symlinkSync(outside, join(workspace, 'link'))
- writeFileSync(join(workspace, 'keep.txt'), 'keep')
- } catch {
- return // symlink creation needs privileges on Windows
- }
- // A DIRECTORY walk still never descends through a link (that rule is about
- // cycles, not containment): the link row is reported as an entry-less row,
- // so the archive holds no bytes from its target.
- const { download } = await archiveFlow({ sessionId: 's-zip', cwd: workspace, paths: [workspace] })
- expect(download.status).toBe(200)
- const entries = readZip(download.body)
- expect(entries.map(entry => entry.name)).toEqual(['workspace/', 'workspace/keep.txt'])
- expect(entries.some(entry => entry.data.toString('utf8').includes('secret'))).toBe(false)
- })
-
- it('rejects an empty path list and a download without sessionId/id (400)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(workspace)
- const { api, download } = mountHost()
- const noPath = await post(api, 'archive.build', { sessionId: 's-zip', cwd: workspace, paths: [] })
- expect(noPath.status).toBe(400)
- expect(noPath.error?.code).toBe('bad-request')
- const noId = await get(download, `/sidebar/archive?sessionId=s-zip`)
- expect(noId.status).toBe(400)
- expect(JSON.parse(noId.body.toString('utf8'))).toMatchObject({ ok: false, error: { code: 'bad-request' } })
- const noSession = await get(download, `/sidebar/archive?id=ar-1`)
- expect(noSession.status).toBe(400)
- })
-
- it('sanitizes the download name (separators stripped, default and suffix applied)', async () => {
- const root = tempRoot()
- const workspace = join(root, 'workspace')
- mkdirSync(workspace)
- writeFileSync(join(workspace, 'a.txt'), 'a')
- const paths = [join(workspace, 'a.txt')]
- const traversal = await archiveFlow({ sessionId: 's-zip', cwd: workspace, name: '../evil")b.zip', paths })
- expect(traversal.download.headers['content-disposition']).toContain('filename="evil)b.zip"')
- const bare = await archiveFlow({ sessionId: 's-zip', cwd: workspace, name: 'docs', paths })
- expect(bare.download.headers['content-disposition']).toContain('filename="docs.zip"')
- const fallback = await archiveFlow({ sessionId: 's-zip', cwd: workspace, paths })
- expect(fallback.download.headers['content-disposition']).toContain('filename="archive.zip"')
- })
-
- it('rejects a non-GET method on the download route', async () => {
- const { download } = mountHost()
- const out: { status: number; body: string } = { status: 200, body: '' }
- const req = { method: 'POST', url: '/sidebar/archive?id=x', headers: { host: '127.0.0.1:3080' } } as never
- const res = {
- writeHead: (status: number) => { out.status = status },
- end: (chunk?: string) => { out.body += String(chunk ?? '') },
- } as never
- await download.handler(req, res)
- expect(out.status).toBe(405)
- })
-})
-
-describe('createArchiveTasks', () => {
- it('expires a settled task after its TTL', async () => {
- const root = tempRoot()
- const file = join(root, 'a.txt')
- writeFileSync(file, 'a')
- const tasks = createArchiveTasks()
- const { id } = tasks.start({ sessionId: 's', name: 'x.zip', entries: [{ path: file, name: 'a.txt' }] })
- await vi.waitFor(() => { expect(tasks.status(id, 's').state).toBe('ready') })
- expect(tasks.size()).toBe(1)
- expect(tasks.status(id, 's')).toMatchObject({ state: 'ready', done: 1, total: 1 })
- // A TTL of zero makes the sweep drop it on the next access (the real TTL
- // is 5 minutes; this is the same code path without the wait).
- const aged = createArchiveTasks()
- const started = aged.start({ sessionId: 's', name: 'x.zip', entries: [{ path: file, name: 'a.txt' }] })
- await vi.waitFor(() => { expect(aged.status(started.id, 's').state).toBe('ready') })
- vi.setSystemTime(Date.now() + ARCHIVE_TTL_MS + 1)
- try {
- expect(() => aged.status(started.id, 's')).toThrow(/unknown or expired/)
- expect(aged.size()).toBe(0)
- } finally {
- vi.useRealTimers()
- }
- })
-})