diff --git a/AGENTS.md b/AGENTS.md index 3afe1310..e5cec8e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,6 +127,7 @@ - **接入 API 即文档**:`src/client/service.ts` 与 `src/client/builtins/` 的任何行为变更,必须同步 [docs/external-plugin-guide.md](docs/external-plugin-guide.md)(唯一权威接入文档,不再双份维护)。 - **文件/文件夹图标**:回退链是「具体 `names`/`exts` 注册 → catch-all(`exts: []`)→ 宿主 `FileTypeIcon`」。插件**不持有**扩展名表、图标数据或图标 chunk(#429 的 563 条数据与 `fileIconTheme` 开关在 rc.2 适配时删除,因为宿主已导出官方图形)。**语义雷区**:宿主分类器覆盖任意路径,所以注册 `exts: []` 会接管所有未具体命中的行——只想补几个类型的插件必须用 `exts`/`names`。 - **内置 tab 图标**:内置类型(文件 / 文件变动 / 任务管理 / 侧边对话 / diff / 终端)的 glyph 集中在 `src/client/builtins/tab-icons.tsx`(颜色在 `tab-icons.module.css`,全部 `--dsw-alias-*`),三处消费面自动同步:底部工作台 tab 条、原生指南胶囊、原生 tab 芯片。**原生芯片的图标是插件自己画的**——宿主的 `SidebarRightTabDefinition` 没有 icon 字段,但 `sidebar.right.pane.tab.title` 槽就是芯片内容(`NativeTabTitle` 渲染 `[glyph][title]`,glyph `aria-hidden` 以免改可访问名)。 +- **git 状态轮询只有一条,且它很贵**([docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md](docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md)):全插件只有 `src/client/ui/git-status.ts` 一个 store,一次抓取 = `git status --untracked-files=all` + 两条全仓库 `--numstat`(4 个进程)。因此:**基线 30 s**(`POLL_BASE_MS`),往返超 750 ms / 2 s / 5 s 依次退到 2×/6×/停止自动轮询(快响应自动回落,事件驱动刷新永远可用);**空闲轮询不 `notify`**(`notify()` 自增的 `slot.version` 就是 `useSyncExternalStore` 的 snapshot,无条件自增会让文件树的每一行每 tick 重渲染一次);消费者分两类——`poll: true`(文件树、变动页)持有定时器,`poll: false`(编辑器 gutter)只读答案、**永不持有定时器**。新写读 git 的组件前先读这个 store 的头注释:**不要把功能开关当作 `visible` 传进去**(#212 就是这么让编辑器整页生命周期持有轮询的),也**不要自建第二个轮询器**。 --- @@ -139,4 +140,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 + 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 + 无保存按钮,并带可编辑反证)。 +- **关键测试守护**:`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` / `fs-tree-probe-gate.spec.ts`(请求级探测预算:`createProbeGate` 的在飞上界 / 排队任务抛错后释放且保持 FIFO / `limit<1` 夹紧,以及 `listDirectory` 每个目录探测恰花一个槽位、缓存命中不花——`fs.trees` 整批共享一个 gate,见 [docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md](docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md))/ `file-tree-compact.spec.ts` / `file-tree-compact-fold.spec.tsx`(资源管理器排除模式与面包屑折叠:glob 子集编译器及其**缓存身份**——host 目录缓存按「路径 + 行额 + 模式集身份」分键,改排除列表即换键;`compact` 单目录链的 host 标记、client 折叠/整链开关与折叠链预加载——预加载与渲染共用同一个 32 链上限,超出即停)/ `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 + 无保存按钮,并带可编辑反证)/ `git-status-poll.spec.tsx`(共享 git 状态 store 的节奏契约,见 §5 那条:`poll:false` 不得启动定时器、非轮询消费者先到不阻塞后来的轮询者而轮询者离开即停表、**空闲同结果不通知**(snapshot 恒等)、30 s 基线、慢往返退到 60 s 且快响应回落、极慢往返停止自动轮询且 `refresh()` 可恢复、不可见不订阅)/ `editor-git-gutter.spec.tsx`(行映射与 blame memo 之外,另钉「在屏编辑器不持有轮询:推进 120 s 仍只读一次」「页签不可见时完全不订阅」「换文件与保存各只重读一次、纯重渲染不重读」——回退 `poll: false` 这三条当场红)/ `git-worktree.spec.ts`(未跟踪目录在 linked-checkout 清单里计 1(单命令计数),而完整 `status()` 仍逐文件展开)。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 83648097..6f2031ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,30 @@ > 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。 -### Unreleased +### v0.26.0 + +- ⚡ **git 状态轮询不再拖慢界面**([#212](https://github.com/omdsh-dev/DSH-better-sidebar/issues/212) 后续;设计与实测见 [docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md](docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md)):一次抓取是 `git status --untracked-files=all` 加两条全仓库 `--numstat`(4 个进程),在**未忽略的大目录**(嵌套 `node_modules`、pnpm store,就是「根锚定 `/node_modules` 盖不住子目录」那种仓库)上实测 **59,631 条 / 9.24 MB / 0.131 s**,而截断上限是在整份输出产出并解析成五万多个对象**之后**才生效的。三处一起收: + - **编辑器 gutter 不再持有轮询**——它此前把**功能开关**当成了页签可见性传进共享 store,而那个参数正是启动定时器的开关;加上原生页签 `keepMounted`(切走不卸载),**只要打开过任何一个文件,整页生命周期就每 2.5 s 跑一次那个扫描**,哪怕你正在打字。现在它只读共享答案、只在**换文件或保存**时各重读一次;页签不可见时连订阅都不建立。 + - **节奏降到 30 s 起,并按实测自动退档**——往返超 750 ms / 2 s / 5 s 依次退到 60 s / 180 s / **停止自动轮询**(快响应自动回落;暂存、提交、丢弃、保存、手动刷新这类事件驱动的刷新永远即时,也是恢复通道)。文件列表与染色条目的语义零变化,只是后台不再常驻 git 进程。 + - **空闲轮询不再触发重渲染**——store 的 `notify()` 原先每 tick 无条件自增 `version`,而它就是 `useSyncExternalStore` 的 snapshot,于是**每个消费者每 2.5 s 整体重渲染一次**(文件树那一列逐行重算 git 状态也在其中),即便数据一字未变;现在只有真的变了才通知。 + - **linked-checkout 清单的计数改单命令**——变动页的 worktree 选择器每 30 s 为**每个** checkout 跑一次完整 `status()` 只为读条目数,现改为一条轻量 `status --untracked-files=normal`。**一处刻意的语义变化**:未跟踪**目录**计 1(此前展开计入每个文件,而且数字还被 2000 上限悄悄截断)。文件树与变动页的逐文件行不受影响。 + - 🧪 测试:新增 `tests/git-status-poll.spec.tsx`(7 例:非轮询消费者不得启动定时器、非轮询先到不阻塞后来的轮询者而轮询者离开即停表、空闲同结果不通知、30 s 基线、慢往返退档与快响应回落、极慢往返停止自动轮询且事件刷新可恢复、不可见不订阅);`tests/editor-git-gutter.spec.tsx` +3(在屏编辑器推进 120 s 仍只读一次、不可见完全不订阅、换文件与保存各只重读一次而纯重渲染不重读);`tests/git-worktree.spec.ts` +1(未跟踪目录计 1,完整 `status()` 仍展开)。判别性:分别回退空闲守卫、`poll` 归属与 gutter 的 `poll: false`,对应用例当场红(已逐条实测)。同批还把 `.delta/` 加进 `vitest.config.ts` 的 `exclude` 与 `eslint.config.js` 的 `ignores`——那是 DSH worktree 通道留下的陈旧检出,`.git/info/exclude` 忽略它,但这两个工具只读各自的配置,不排除时本地 `pnpm test` 会报 6 文件 / 7 用例**假红**、`pnpm lint` 报 1115 errors(`eslint` 的「点开头目录默认也不进」那句注释同时订正)。 + +- ⚡ **文件树两处性能放大收敛:折叠链预加载 + 宿主逐子目录探测**(逐条核查结论与「按用户决定不做」的清单见 [docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md](docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md)):① **折叠链的预加载与渲染现在共用同一个 32 链上限**——`compactLoadTargets` 此前扫描**所有已加载层**,而渲染侧 `compactChain` 在 `MAX_COMPACT_DEPTH` 就停手,于是渲染收在 32 节、预加载仍继续请求第 33、34… 节(每节一次串行 `fs.trees` POST 加一次全树 render,标签却不会再变长);现改为从渲染根(`cwd` + 展开集)沿**同一条** `compactChain` 下行,上限自然继承。顺带订正了「安全上限,健康缓存下永不触及」这处不准确注释:合法的深单子目录链(`src/main/java/com/...` 这类)真会触及,循环守卫是 `compactChain` 的 `visited` 而不是这个常量。② **`fs.trees` 整批共享一个探测预算**——新增 `PROBE_BUDGET` / `ProbeGate` / `createProbeGate`,`listDirectory` 增加可选 `gate` 参数(只在真实文件系统探测外层取槽,**缓存命中的层一次都不花**),路由每请求建一个 gate 并传给它的所有层:此前一个批次最多 64 条路径 × 每层 32 路探测可**同开约 2048 个 `opendir`**,冷挂载一棵宽目录树就是一次 syscall 风暴。单层与 `fs.tree` 单路径行为逐字不变(gate 缺省即原并发)。**明确未做**:文件树**不引入虚拟化**(memo 边界 + 每层 1000 行上限 + `truncated` 提示已够,用户判断当前性能无问题)、**watch 上限不加用户提示也不加全局句柄**(无法 watch 的机器本就存在,VS Code 同样不提示)、不改 `DirRow` 的 chain identity。 + - 🧪 测试:新增 `tests/fs-tree-probe-gate.spec.ts`(gate 在飞上界、排队任务抛错后释放且保持 FIFO、`limit<1` 夹紧;`listDirectory` 每个目录探测恰花一个槽位、缓存命中零开销;三层共享一个 gate 合计 9 次);`tests/file-tree-compact.spec.ts` 与 `tests/file-tree-compact-fold.spec.tsx` 新增「到渲染上限即停」(把实现回退到旧扫描,两条当场红:预加载会一路问到链尾);`tests/smoke.spec.ts` 新增路由级断言「一次 `fs.trees` 只建一个 gate」(`vi.mock` 包一层计数,其余导出保持真实)。 + +- 🐞 **文件树的「加载中」占位不再把子树永久卡死**:`loadLevels` 对非强制加载会先写一个空 `{}` 占位(渲染即 Loading 行),而应答被世代守卫**丢弃**时(刷新 tick / 排除列表变化 / 卸载都会 bump 世代)那个占位没人回收——之后任何加载都把「缓存里有条目」当成已加载(空占位也算命中,注释里写明是为了避免重复请求),于是这一层再也不会被重新请求,**子树停在 Loading 行直到下一次强制刷新或重挂**。现在占位的**所有权跟着请求走**(`pendingRef`:path → 写下它的世代):应答被丢弃时只回收**本次调用仍持有、且仍是空占位**的层(已有列表或错误的一律不动——丢弃的应答不得清空屏上的行),并**补发一次**该批请求,让丢弃自愈而不是等下一个 tick。 + - 🧪 测试:`tests/editor-host.spec.tsx` 新增「a listing dropped by a refresh tick does not strand the level on Loading…」(首答延迟 300 ms、tick 在飞行中使其失效、tick 触发的强制重列人为挂死);去掉本修复该用例当场红并打印现场。 - 🖥️ **底部工作台可以同时开多个终端 Tab([#927](https://github.com/omdsh-dev/DSH-better-sidebar/issues/927),PR [#926](https://github.com/omdsh-dev/DSH-better-sidebar/pull/926))**:`terminal-bottom` 去掉 `single: true` 改为提供 `createTab`——每开一个 mint 一个 `terminal-bottom:` 的 id,并在 `meta.terminalInstance` 里记下自己的实例;宿主侧的出现键与内容身份都带上它(`dsh-better-sidebar:terminal-bottom:[#run]`),于是两个 tab **各自一个 shell**、刷新后各回各的进程,关掉一个只结束它自己那条。**旧 tab(`meta` 里没有 `terminalInstance`)读出来仍是 `undefined`,身份与改造前逐字节相同**,恢复绑定不丢。**维护者收尾**:`nextTerminalMeta()` 必须把实例一起带过去——`patchTab` 是**整份替换 `meta`**,只回 `terminalRun` 会让「新建终端」之后的 tab 掉回旧命名空间,于是两个都换过进程的 tab 撞在同一个 `…terminal-bottom#1` 上、被宿主(按 `(sessionId, key)` 记忆一个 model)发成**同一个 shell**。设计文档 `docs/plans/2026-10-05-bottom-terminal-tab.md` 的「一个终端」限制随之标注放开。 - - 🧪 测试:`tests/terminal-tab.spec.tsx` +3(实例随「新建终端」保留、旧 tab 不长出实例;两个实例各自 `#1` 不撞、且都不等于旧的裸 `#1`;两个实例渲染出两个宿主终端与两条不同的 `(session,key,contentId)`),描述符关闭钩子补一条「带实例的 tab 只结束自己的终端」。判别性:把 `nextTerminalMeta` 退回只回 `terminalRun`,前两条当场红。 + - 🧪 测试:`tests/terminal-tab.spec.tsx` +3(实例随「新建终端」保留、旧 tab 不长出实例;两个实例各自 `#1` 不撞、且都不等于旧的裸 `#1`;两个实例渲染出两个宿主终端与两条不同的 `(session,key,contentId)`),描述符关闭钩子补一条「带实例的 tab 只结束自己的终端」。判别性:把 `nextTerminalMeta` 退回只回 `terminalRun`,前两条当场红。(贡献者 PR [#926](https://github.com/omdsh-dev/DSH-better-sidebar/pull/926) @eleven-lings) + +- 💬 **侧边对话补齐到接近原生:实时推送 + 排队可见 + per-thread 模型选择 + 底栏重构**(PR [#925](https://github.com/omdsh-dev/DSH-better-sidebar/pull/925);设计、真机证据与「哪些做不到」的清单见 [docs/plans/2026-10-12-sidechat-native-surface.md](docs/plans/2026-10-12-sidechat-native-surface.md)): + - **实时推送**:新增 `/sidebar/ws/sidechat`(`src/sidechat-push.ts`,客户端 `src/client/use-sidechat-push.ts`)。宿主把 `session/event`(60 ms 去抖)与 `agent/assistant-stream`(250 ms 去抖)压成**纯失效帧** `{threadId}`——不带事件体、客户端收到才带 `afterSeq` 增量重拉,协议面最小、单一事实源、断线自愈;每 socket 最多观察 64 个线程,空闲时**零帧**,重连指数退避 1→15 s,轮询降级为 15 s 兜底。 + - **排队可见**:`sidechat.events` 增返 `pending`(`agent.inbox.nextStep/nextTurn` 投影,按 claim 顺序),队列在底栏可见;`sidechat.dequeue` 可按 id 撤一条、不带 id 清空整队。注入门控同时看 `boundaryDelivered` 与 `boundaryPending`——否则「首问还没被 claim 就连发第二条」会注入第二对 boundary + question。 + - **per-thread 模型选择**:宿主对 `origin:'subagent'` 会话**显式禁用**自带选择器(`modelDirectories.assertAvailable`),`sessionController.selectModel` 也被 subagent fence 挡住,所以插件自建两条路由——`sidechat.models`(直通 `sessionController.modelCatalog()`,缺服务即 `available:false`,此时 UI 只提供「继承主对话」)与 `sidechat.model`(`ctx.get('llm').resolveCallConfig` 归一化后**同时**落 `session.append('model/selection')` 与 `installModelSelection(agent.ctx, ref)`,否则控制器缓存的 per-agent selection 永不回读投影;resume 后按日志里的有效选择重装)。 + - **幽灵输入改为精确清扫**:冷恢复(`sidechat.prompt` → `agents.resume`)此前没有 create 路径那道 `inbox.clear()` 围栏。现在改为 `dropInheritedGhosts`——只折**继承前缀**得到幽灵 id 集合,再逐个 `agent.inbox.remove(id)`,精确且幂等,不会误杀「用户在线程里排队、宿主重启后尚未领取」的合法输入。同时确认幽灵的来源比原先记录的更宽:父会话 mid-turn 且工具有未返回调用时,种子被截断在 `turn/start` **之前**,而 inbox 的领取 splice 发生在 `turn/start` **之后**,所以父会话本轮开头已领取的输入在种子折叠里仍是 pending。 + - 🧪 测试:新增 `tests/sidechat-push.spec.ts`、`tests/use-sidechat-push.spec.ts`、`tests/sidechat-transcript.spec.ts`;`tests/sidechat-core.spec.ts` / `tests/sidechat-routes.spec.ts` / `tests/sidechat-view.spec.tsx` 大幅增补(含真实 `Session.create` + 真实 `SessionProjectionRegistry` 的种子验证);挂载 lane 的 sidechat 宿主路由烟测同步。 - 🛡 **三处静默数据问题**([#898](https://github.com/omdsh-dev/DSH-better-sidebar/issues/898) / [#899](https://github.com/omdsh-dev/DSH-better-sidebar/issues/899) / [#900](https://github.com/omdsh-dev/DSH-better-sidebar/issues/900)):① 编辑器草稿守卫的记账键从**裸 tab id** 改成 **`会话::tab id`**——原生右栏每个会话的 id 都从 `tab1` 重新计数、底部工作台对同一路径在各会话复用 `editor:`,两套身份原先挤在同一个键上,**另一个会话打开编辑器就会把本会话的草稿记录一并删掉**(刷新时静默丢失);② 面包屑折叠行(`a/b/c` 压成一行)的重命名此前提交的是**链头**目录、与预填名不一致——不改字直接回车等于把父目录改名,现在落到链尾;③ 无 BOM 的 16 位小端数据(低幅采样表 / 未压缩音频数据段这类)不再被判成 UTF-16 文本打开、保存后整份改写(奇数长度还会丢尾字节):新的文本闸门要求 ≥90% 的单元是合法文本单元。同批还带了 dev 新增代码的一轮去重(内部导出 `runGitRaw` / `bottomTerminalKey` / `formatModelRoute` / `dirtyCountForSession` 收敛,仓内调用点同批改完)。(贡献者 PR [#901](https://github.com/omdsh-dev/DSH-better-sidebar/pull/901) @UNscientific-9) - 🧪 测试:`tests/editor-unsaved-guard.spec.tsx`(跨会话草稿:第二个会话挂同一个原生 id,既不能清掉、也不能确认掉第一个会话的草稿)、`tests/file-tree-compact-fold.spec.tsx`(折叠行重命名断言落到链尾:`/tmp/a/b/c` → `renamed`)、`tests/text-encoding.spec.ts`(uint16LE 采样表 / WAV `data` 段 / 奇数长度判二进制,真 UTF-16LE/BE 仍是文本)。 @@ -20,10 +40,10 @@ - **落地没有光标,还会被预览的阅读位置覆盖**:落地只 `dispatch({ selection })`,而 CodeMirror **只在获焦的编辑器里画光标**、零长度选择本身什么都不画——文件短时一页装得下又没有光标,读者无从判断落在哪。且「进入编辑态按预览滚动位置恢复」那条副作用**声明在落地之后**,同一次提交里会把选择与滚动重新写回读者刚才预览的位置:先在预览里滚动、再点带行号的引用,跳转被静默抹掉。现在行号引用这条路上 `view.focus()`(普通打开不动读者焦点,他可能正从聊天输入框点链接),并在落地前清空 `previewSyncRef`。 - 🧪 测试:新增 `tests/editor-line-nav-mode.spec.tsx`(4 例,**真 `TextEditor` 过真 `EditorHost`**:落地后能切回预览 / 页头刷新不回弹 / 同文件新行号仍落地 / 换文件不继承行号),`tests/text-editor-line-jump.spec.tsx` +6(落地获焦 / 普通打开不抢焦点 / markdown 翻转后仍获焦 / 消费契约两例 / 预览位置覆盖),`tests/markdown-surface.spec.tsx` +2(真实宿主 `MarkdownText` 下点 `#L42` 与 `#L20-L25` 进记录、标题锚点仍只走 parked 片段),`tests/native-tab-line.spec.ts` +2(换 path 清行号 / 只改 title 保留),`tests/markdown-navigation.spec.ts` +1(`lineOfHostFragment`),`tests/file-open-claim.spec.ts` +1(种子透传与「不传就不带这个键」)。判别性:去掉 `previewSyncRef` 清空 → 预览覆盖用例红(期望第 3 行的 offset 8、实得按比例算出的 14);去掉两个记录层的清行号 → 对应两条红。(回归报告 [#914](https://github.com/omdsh-dev/DSH-better-sidebar/issues/914);贡献者 PR [#916](https://github.com/omdsh-dev/DSH-better-sidebar/pull/916) @yanzhaohui1999) -- 💾 **带基线保存时目标已不存在判冲突([#911](https://github.com/omdsh-dev/DSH-better-sidebar/pull/911))**:文件读进来之后被删掉或改名走,此前会当成「没有基线可比」直接写回,`mkdir -p` 于是把用户刚删掉的文件(连同父目录)**无提示重建出来**,界面还报「已保存」。数字基线只可能来自一次成功的读取,所以「读不到」是冲突而不是新建意图——现在同样回 409 `fs-conflict`,文案分成「已不存在」与「已在磁盘上被改过」两种;新建走 `fs.createFile`、上传走上传路径,都不受影响。 +- 💾 **带基线保存时目标已不存在判冲突([#911](https://github.com/omdsh-dev/DSH-better-sidebar/pull/911))**:文件读进来之后被删掉或改名走,此前会当成「没有基线可比」直接写回,`mkdir -p` 于是把用户刚删掉的文件(连同父目录)**无提示重建出来**,界面还报「已保存」。数字基线只可能来自一次成功的读取,所以「读不到」是冲突而不是新建意图——现在同样回 409 `fs-conflict`,文案分成「已不存在」与「已在磁盘上被改过」两种;新建走 `fs.createFile`、上传走上传路径,都不受影响。(贡献者 PR [#911](https://github.com/omdsh-dev/DSH-better-sidebar/pull/911) @UNscientific-9) - 🧪 测试:`tests/fs-write-route.spec.ts` +2(删文件后保存 → 409 且文件不复活、无临时残留;父目录被删 → 409 且目录不重建)。 -- 🧭 **改动块内以 `---` / `+++` 开头的正文不再被当成文件头([#910](https://github.com/omdsh-dev/DSH-better-sidebar/pull/910))**:删掉一行以 `-- ` 开头的源码(SQL / Lua / Haskell 注释、文档里的命令行参数行)在 git diff 里就是 `--- …`,与文件头分隔行**逐字节同形**——解析器据此把该文件**从这一行往后的改动整段丢掉**,而且不报错。现在两条头部分支只在**尚未进入 hunk** 时生效,并补了「真文件头跟在 hunk 之后仍能解析」的反证用例。 +- 🧭 **改动块内以 `---` / `+++` 开头的正文不再被当成文件头([#910](https://github.com/omdsh-dev/DSH-better-sidebar/pull/910))**:删掉一行以 `-- ` 开头的源码(SQL / Lua / Haskell 注释、文档里的命令行参数行)在 git diff 里就是 `--- …`,与文件头分隔行**逐字节同形**——解析器据此把该文件**从这一行往后的改动整段丢掉**,而且不报错。现在两条头部分支只在**尚未进入 hunk** 时生效,并补了「真文件头跟在 hunk 之后仍能解析」的反证用例。(贡献者 PR [#910](https://github.com/omdsh-dev/DSH-better-sidebar/pull/910) @UNscientific-9) - 🧪 测试:`tests/diff-rows.spec.ts` 3 例(删除的 `-- foo` 留在 hunk 内、新增的 `++ i;` 不改文件名、真文件头仍能开场)。 - 📜 **超大文件的预览改成 VS Code 那种追加式滚动**:第一版做的是「上一页/下一页」的显式翻页(新页替换当前页),现在改为**滚到底自动取下一页并拼接**——读者读过的内容不会被抽走,行号跨页连续,「加载全部」就是一路追加到 EOF(必须串行:每一页的 `offset` 就是上一页响应的 `nextOffset`)。超限提示条最右侧新增「加载全部」按钮,加载中显示已读字节进度,到 EOF 后自动置灰。 @@ -43,6 +63,8 @@ - 🧾 **超大文件从「截断成只读」改为「只读分页预览」**:`fs.read` 从「全读或截断」变成三态(`text` / `binary` / **`too-large`**)。超过编辑上限(5 MiB)的文本文件不再回半份文档,而是只带 4 KiB 嗅探头的 `too-large`,客户端据此渲染**分页只读预览**(等宽行列表,日志查看器形态)并提供下载出口;超过该大小的**二进制**走原来的 media 路径,行为完全不变。`FileViewerProps.truncated` 与 `truncation` 文案键一并删除——「拿到半份文档但看起来能编辑」这个状态本身就是 #732 的成因。新 `fs.readPage` 按字节窗口分页,窗口回退到最后一个换行,所以一页是整数行;超长单行原样返回而不是空页(否则「下一页」会停在一个永不前进的偏移上)。 +- 🔧 **`.jsonl` 预览不再谎报「文件过大」**:预览态的 JSONL(小于编辑上限)走的是同一套分页记录视图,但顶部那段「文件过大,仅提供分页预览」对它是一句谎话——**阈值决定提示,不是组件决定**。`LargeFileView` 现在自己按 `MAX_EDITABLE_BYTES` 判断,一个 2 KB 的记录文件不再顶着超限提示条。 + - 🆕 **`.jsonl` / `.ndjson` 有原生支持了**:此前它们既没有语法高亮(`lang.ts` 无映射 → 纯白文本),也不能简单地映射到 `json()`——`@lezer/json` 的文法只接受一个顶层值,实测 400 条记录的文件会解析出 **402 个错误节点**。现在有一个手写的逐行 JSON 词法分析器(一行一次、不携带跨行状态、未闭合字符串直接标错),新增第 4 个内置 viewer `jsonl`:**预览**是每条记录一张可折叠卡片(默认折叠成一行摘要,点开用宿主的 `JsonTree`),**编辑**是原样可保存的 CodeMirror,由预览/编辑开关切换。行引用(`a.jsonl#L131`)仍会先切到编辑档再落行。 - 🎨 **修掉「错误标记看不见」**:`tags.invalid` 在深浅两种配色下都是 `#ffffff` —— 在浅色主题里就是白底白字。它是 JSON/JSONL 语法错误落到的 token,读者本该能看出哪段没解析;现改为红色波浪下划线。 @@ -55,22 +77,6 @@ - 📖 设计过程、与 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)。 -- 🃏 **任务卡小条只说原生状态**(首轮):运行中不再是「● 运行中 正在读取文件」这样把状态念两遍,而是**活动行取代状态词**——`正在分析请求` / `正在读取文件 · main.ts` / `正在准备读取文件` / `正在运行命令 · npm run build` 等措辞来自宿主 `chat` 命名空间,与主对话逐字一致;已结算小条同理(只留 `已读取文件、执行了命令`)。**`空闲` 与 `出错` 保留状态词**(不被任何活动措辞蕴含),完全没有活动数据时回退状态词,小条永不空着。状态点、执行扫光与折叠 chevron、22px 高度都不变。 -- 🧩 **主代理卡片接上自己的实时数据**:`subagents.live` 路由一直把拓扑根的 fold 结果放在 `live[rootSessionId]`,而模型从未把它挂到根节点上——于是主代理卡片的状态文本**恒为 thinking 兜底**,与主会话在做什么无关。现在根卡显示真实状态,树模式根行的实时行也从恒定的「思考中…」变成真实活动。 -- 🔎 **节点详情浮窗的活动行移到标题下方**:原来在键值格里(`最近活动 | 值`),右对齐的值列在 280px 被省略、标签又占掉三分之一宽;现在是标题下的一行 10px 小字(宿主措辞)+ 夹两行的实时文本尾行,**没有活动数据就不渲染**(此前每个浮窗都会显示「最近活动:正在分析请求」,已结算节点也一样)。词条 `tasksNodeActivity` 随这一行从 20 份词典删除。 -- 🗂 **聚合卡改为「按组展开」**:点一个聚合卡只展开**该组**(`fold:` / `fold::idle`),兄弟组、页级折叠与手工折叠都不受影响;控制条按钮仍是页级展开/折叠,且**收起时清掉按组展开**。树里的聚合行同一语义。**展开后卡片自己的 chevron 仍然有效**(手动折叠是该节点的最新意图,优先级高于组展开),聚合卡随之重新出现并能再次展开——否则「展开后点不回去了」。 -- 🔢 **聚合卡计数只说一次、小条变动作行**:待命组徽标此前印的是**字面量字母 N**(`tasksFoldIdleGroup` 在 20 份词典里都没有 `{count}` 插值),现在插值出真实计数;小条不再是重复计数的空条,而是「组图标 + 展开 + 出错尾注 + 展开箭头」,完整 tally 仍是卡片的 `aria-label` 与 tooltip。 -- 🏷 **模式词搬进徽标行**:子代理卡片此前每个都有一行 mono 元信息写着「一次性」——同一句话在每张卡上重复一次、还占一行高。现在模式(一次性 / 可持续)是**徽标旁的 chip**,智能体卡因此不再有元信息行、卡片高度预算同步收窄(只有工作流 run 卡还保留那行状态 / 成员元信息,行距按模型里有没有 run 取)。 -- 📊 **节点详情多两项事实**:新增 **Token 用量**(宿主 `tokenUsage` projection 的四个互斥桶求和,悬停给出未缓存输入 / 缓存读取 / 缓存写入 / 输出明细)与 **耗时**(宿主 `subagentTiming`:已结算回合 + 正在跑的那一轮,按页面轮询刷新)。两项都按宿主投影的**存在性**渲染——没有测量就不显示这一行,绝不打印一个说不清的 0;`SidebarProjectionSnapshot.values` 的镜像类型同步补上这两个键。 -- 🪟 **「查看转录」改为在原生右侧栏打开**(这是宿主自带能力):`dsh-resource://subagentchat/session/?parent=&mode=` + `ctx.sidebarRight.openResource(..., { kind: 'subagentchat', preferNewPane: true })`——与宿主自己的子代理列表(点行 = 主窗、点 chevron = 侧栏)同一套 tab 类型,主列保持不动;右侧新增小下拉按钮,菜单里可**在主窗中打开**(走原有的 `uiWorkspace.openSession` + 页签重挂)。宿主没有该 tab 类型 / 没有右栏 / 没有挂载会话时逐项降级回主窗并保持单按钮。 -- ✨ **动效:画布在自己的坐标系里补间**(`tasks-layout-tween.ts`)。卡片层带着 fit 的 `transform: scale(k)`,所以任何「量 rect、播 transform」的 FLIP 库在这里都是错的——`@formkit/auto-animate` 更会把离场卡片钉上由 rect 换算的绝对 `left/top`(缩放层里根本表达不出来 → 跳位)。改为**直接补间布局坐标**(每张卡的 `x`/`y`/高度):`left`/`top` 就是画布自己的单位,缩放对它和对终点位置一样生效;而连线路径与相位框都是「盒子的纯函数」,于是**跟着卡片逐帧走**,不再在卡片还在飞的时候先瞬移到终点。入场另有 CSS 关键帧(300ms:上浮 + 0.88→1 缩放 + 淡入,带轻微过冲),并按节点顺序**错峰 26ms**(一次展开多张时是瀑布而不是一下全冒),`backwards` 填充让等待中的卡片先隐形而不是先冒再动。 -- 🧭 **自动适配改成「滑过去」而不是「跳过去」**:布局一变,视图变换(平移 + 缩放)与卡片一起补间 220ms,于是**展开后画面仍然是自适应的居中位置**(不会让节点溢出面板/偏到一角),同时也没有原来那种瞬跳。规则不变:读者拖过或缩放过就不再自动重框(那一刻视图归他),⌂ 按钮随时交还自动适配;切会话重置并重新适配(新的树 = 新的画布),顺带修掉「拖过一次之后换会话就不再适配」的旧账。 -- 🪶 **FLIP 库只留给流式布局**:树模式行与后台任务行的离场是「原地淡出 + 兄弟滑位」,那正是 FLIP 的语义且不受缩放影响;画布则明确排除(`tests/tasks-motion.spec.ts` 钉死:画布不得 import 它、树与抽屉必须有)。 -- 💬 **卡片标题下也写最新文本**:图模式卡片在名称下新增一行 10px 的**最新助手文本尾行**(此前只有详情弹窗里才看得到),小条继续写合并活动——两行各答一个问题。**行数按布局预算夹紧**:`textTailLines()` 按字符宽度估算折行、上限 3 行,并把估算值写进卡片的 `-webkit-line-clamp`,所以渲染永远不会超出布局给这个节点算好的盒子(也就不会把行距撑爆);行距 `rowStrideFor()` 改为**按模型里最高的一张卡**计算(工作流 run 的元信息行、成员的任务行、以及最多三行文本尾行都算进去)。详情弹窗的文本块同步从夹两行改为夹三行。 -- 🌲 **树模式对齐画布并补齐动效**:模式词从行内 mono 行搬成**标题旁的 chip**(与卡片徽标行同一处、同一个词),mono 行只留状态;**每个嵌套层级都有自己的 FLIP host**(`TreeLevel` 组件——库只看容器的直接子节点,单个 host 会让嵌套折叠硬闪);连线改成**每个子节点自己画的肘线**——竖线落在父行的标记列上、且最后一个兄弟的竖线**停在它自己的标记处**(不再拖出组外)。 -- 🌲 **树模式补上「收起 / 展开」整套**:此前树只有页级「已完成节点聚合」,**没有任何按节点的展开收起**。现在:每行右侧有一个**单个收起/展开**(有子节点的行才有,位置与画布卡片小条的 chevron 一致,16px 同一处);控制条新增 **全部收起 / 全部展开**(用文字而不是更多 chevron——旁边的已结算折叠开关已经占了那套图形语汇);键盘补上标准树行为:**→ 展开(已展开则进入子级)、← 收起(已收起则退回父级)**;行上带 `aria-expanded`,折叠状态跨图/树切换保留。它与「已结算聚合」是两条互不干扰的轴:一个收子树,一个收已完成的叶子。 -- 🧪 测试:新增 `tests/session-metrics.spec.ts`(5 条:四桶求和、空投影、运行中耗时按渲染时钟、0 不算工作、时钟回拨不显示负数)与 `tests/activity-icons.spec.ts`(3 条:13 个类别全覆盖、读 / 命令 / 搜索 / 网页互不同型、`undefined` 走思考图标);`tests/tasks-page.spec.tsx` 补 6 条(原生状态取代状态词、无数据回退、根卡真实状态、浮窗活动块位置、一次只开一组 + 判据极性的判别性用例、展开后成员仍可手工折回、Token / 耗时两行、侧栏打开地址 + 下拉在主窗打开 + 无宿主能力时单按钮、模式 chip 在徽标行);`tests/tasks-graph-layout.spec.ts` 的高度 / 行距断言跟随新的卡片预算。[设计文档](docs/plans/2026-10-11-tasks-status-and-group-fold.md)。 - - 🃏 **任务卡小条只说原生状态**:运行中小条不再是「● 运行中 正在读取文件」这样把状态念两遍,而是**活动行取代状态词**——`正在分析请求` / `正在读取文件 · main.ts` / `正在准备读取文件` / `正在运行命令 · npm run build` 等措辞全部来自宿主 `chat` 命名空间,与主对话逐字一致;已结算小条同理(只留 `已读取文件、执行了命令`,不重复「已完成」)。**`空闲` 与 `出错` 保留状态词**(「待命」「失败」不被任何活动措辞蕴含),**完全没有活动数据时回退状态词**,小条永不空着。状态点、执行扫光与折叠 chevron 不变,小条仍是 22px——画布几何与卡片高度预算零改动。 - 🧩 **主代理卡片接上自己的实时数据**:`subagents.live` 路由一直把拓扑根的 fold 结果放在 `live[rootSessionId]`,而模型从未把它挂到根节点上——于是**主代理卡片的状态文本恒为 thinking 兜底**(「正在分析请求」),与主会话在做什么无关。现在根卡显示真实状态,树模式根行的实时行也从恒定的「思考中…」变成真实活动。 - 🔎 **节点详情浮窗的活动行移到标题下方**:那行原来在键值格里(`最近活动 | 值`),右对齐的值列在 280px 里被省略,标签又占掉三分之一宽;现在它是标题下的一行 10px 小字(宿主措辞),实时文本尾行紧接其下并夹到两行。**没有活动数据就不渲染这一块**——此前每个节点浮窗都会显示「最近活动:正在分析请求」,已结算节点也不例外。词条 `tasksNodeActivity` 随这一行从 20 份词典删除。 @@ -79,6 +85,7 @@ - 🎨 **树模式实时行的图标按活动类别取**:`tool-icons.tsx`(工具名映射,只有一处写死的调用)换成 `activity-icons.tsx` 的 `activityGlyph(kind)`——读文件 / 搜索 / 编辑 / 命令 / 网页 / 子代理 / 计划 / 提问 / 通用工具各用自己的宿主图标,尚未派发时是思考图标;`Record` 让上游新增类别编译失败而不是静默兜底。 - 🧪 测试:`tests/tasks-page.spec.tsx` 新增一个 `FakeChatLocale`(挂宿主 `chat` 命名空间,否则只能断言到 fallback 的 detail)并补 5 条(原生状态取代状态词、无数据回退、根卡真实状态、浮窗活动块位置与「无数据不渲染」、一次只开一组+全局收起折回、徽标真实计数);`tests/tasks-model.spec.ts` 补 4 条(按组展开的双向隔离、组 id、`expandedGroups` 盖过残留手工折叠、根节点带 live);新增 `tests/activity-icons.spec.ts`(类别全覆盖 + 读/命令/搜索/网页互不同型 + `undefined` 走思考图标)。[设计文档](docs/plans/2026-10-11-tasks-status-and-group-fold.md)。 +- 🔌 **预览插件目录收录音频预览插件**:[`@huanlin/dsh-plugin-better-sidebar-plugin-audio`](https://github.com/HuanLinOTO/dsh-plugin-better-sidebar-plugin-audio)——设置页「添加插件」弹窗的预览插件目录里可一键复制安装命令(20 份词典同步 `pluginAudioName` / `pluginAudioDesc`,条目写进 `tests/plugin-list.spec.ts` 的目录断言,README 的预览插件表格 3 → 4)。(贡献者 PR [#881](https://github.com/omdsh-dev/DSH-better-sidebar/pull/881) @HuanLinOTO) ### v0.25.0 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 1bef5de4..47a2277d 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -1,8 +1,17 @@ # Changelog > 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)). +> +> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current. -### Unreleased +### v0.26.0 + +- ⚡ **git status polling no longer drags the UI down** (follow-up to [#212](https://github.com/omdsh-dev/DSH-better-sidebar/issues/212)): one fetch is `git status --untracked-files=all` plus two whole-repo `--numstat` diffs — four processes — and on a repository with a large UNIGNORED tree (a nested `node_modules`, a package-manager store) that measured **59,631 entries / 9.24 MB / 0.131 s**, with the 2,000-entry cap only applied AFTER the whole output had been produced and parsed. Three changes together: + - **the editor's gutter no longer owns the poll** — it passed the feature switch where the tab's visibility belongs, and that parameter is what starts the timer; with native tabs kept mounted, opening any file kept the scan running every 2.5 s for the rest of the page's life. It now reads the shared answer and refreshes only on a file switch or a save, and holds no subscription at all while its tab is parked. + - **the baseline is 30 s, with automatic back-off** — a round trip over 750 ms / 2 s / 5 s drops the slot to 60 s / 180 s / no automatic timer, a fast answer climbs straight back, and event-driven refreshes (stage, commit, discard, save, manual refresh) stay immediate. + - **idle polls notify nobody** — the store's version counter is the `useSyncExternalStore` snapshot, so bumping it on every tick re-rendered every consumer once per cadence even when nothing had changed. + - Linked-checkout inventory counts now use a single cheap command instead of a full `status()` per checkout; an untracked DIRECTORY counts as one entry there (it used to expand to every file, and the number was silently capped anyway). +- 🚀 Plus everything else in v0.26.0: fully streamed transfers with the three deployment caps removed, a read-only paged preview for very large files, a fourth built-in viewer for `.jsonl` / `.ndjson`, Side Chat live push + visible queue + per-thread model selection, multiple bottom-workbench terminal tabs, the rebuilt Tasks panel, native-right-sidebar rename/delete reconciliation, and several silent data fixes. See the [Chinese CHANGELOG](./CHANGELOG.md#v0260) for the full list. - **Oversized-file preview is now append-on-scroll, the way VS Code's log view works**: the first cut used explicit previous/next paging (each new page REPLACED the current one). Now reaching the bottom pulls the next window and keeps everything already read — line numbers continue across page boundaries, and "load all" is simply append-until-EOF. The walk has to be sequential: each page's `offset` IS the previous response's `nextOffset`. The too-large notice grew a "load all" button (showing byte progress while it works, disabled once EOF is reached). @@ -33,6 +42,12 @@ - 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.25.0 + +> 📦 **Support line moved: DSH `0.2.0-rc.2+` only** (peer floor `^0.2.0-rc.2`). npm's `latest` for DSH is exactly 0.2.0-rc.2 now, and this release pins it. **Hosts on 0.2.0-rc.1 or older (including the 0.1.7 line) should pin v0.24.1** — `^0.2.0-rc.2` evaluates false against rc.1, so the host's startup compatibility preflight disables the whole row silently. Declaration and pin change only: zero runtime changes. +> +> 🙏 Carries work from several contributors (listed in merge order in the [Chinese CHANGELOG](./CHANGELOG.md#v0250)). This English file was not updated for v0.25.0 at the time. + ### 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 e98ef901..853cd62c 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ > [!IMPORTANT] > **v0.19.0 起接入 DSH 原生侧边栏**:右列就是 DSH 自己的右侧栏,插件把每个 tab 类型注册为原生 tab(不再自绘右侧面板),只保留自绘的底部工作台与开放给所有插件的 `ctx.betterSidebar` 服务。 > -> **v0.24.1 起要求 DSH `0.2.0-rc.2+`**(peer 下限 `^0.2.0-rc.2`)。0.2.0 对本插件所用的全部宿主 API 是**纯增量**(零导出删除、会话格式仍 v4、CLI 与客户端运行时未变),所以这一版没有运行时兼容分支,只把支持线整体前移。**DSH 0.1.7 线的用户请固定 `dsh-better-sidebar@0.22.1`——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 在 0.2.0 宿主上会被启动预检静默禁用**;按 DSH 版本选插件版本的对照表见[安装](#-安装)。 +> **v0.25.0 起要求 DSH `0.2.0-rc.2+`**(peer 下限 `^0.2.0-rc.2`,v0.26.0 不变)。0.2.0 对本插件所用的全部宿主 API 是**纯增量**(零导出删除、会话格式仍 v4、CLI 与客户端运行时未变),所以这条支持线上没有运行时兼容分支,只把基线整体前移。**DSH 0.1.7 线的用户请固定 `dsh-better-sidebar@0.22.1`——caret 范围跨 minor 不成立,`^0.1.7-rc.1` 在 0.2.0 宿主上会被启动预检静默禁用**;按 DSH 版本选插件版本的对照表见[安装](#-安装)。
@@ -14,7 +14,7 @@ GitHub stars License: MIT dshfind

- 支持的 DSH 版本(v0.24.1):0.2.0-rc.2+ + 支持的 DSH 版本(v0.26.0):0.2.0-rc.2+ 插件生态:GitHub topic dsh-better-sidebar

文件管理 编辑预览 底部工作台 文件变动 后台任务 侧边对话 插件接入

右侧栏 + 底部面板双工作台,并把 ctx.betterSidebar 服务开放给所有插件——
@@ -62,16 +62,16 @@ **前置**:已装好 DSH(`dsh web` 能正常运行),Node.js ≥ 20、pnpm ≥ 10。 **支持的 DSH 版本**: -支持的 DSH 版本(v0.24.0):0.2.0-rc.2+ +支持的 DSH 版本(v0.26.0):0.2.0-rc.2+ -> 📌 **通道与支持线**:`v0.24.1` 适配 DSH **0.2.0-rc.2+**(0.2.0 首个候选版走 npm `next` 通道,`latest` 仍是 0.1.7-rc.2)。**装 DSH 请写精确版本号**:`npm i -g @deepseek-ai/dsh@0.2.0-rc.2`。**0.1.7 线的用户请固定 `dsh-better-sidebar@0.22.1`**:0.2.0 是宿主 minor 变更,`^0.1.7-rc.1` 这类 caret 范围在 0.2.0 上会被宿主的启动兼容性预检判定失败、整行静默禁用。 +> 📌 **通道与支持线**:`v0.26.0` 适配 DSH **0.2.0-rc.2+**(npm 的 `latest` / `next` 都是 `0.2.0-rc.2`)。**装 DSH 请写精确版本号**:`npm i -g @deepseek-ai/dsh@0.2.0-rc.2`(`alpha` 通道的 `0.2.1-alpha.x` 不在本版支持线内)。**0.1.7 线的用户请固定 `dsh-better-sidebar@0.22.1`**:0.2.0 是宿主 minor 变更,`^0.1.7-rc.1` 这类 caret 范围在 0.2.0 上会被宿主的启动兼容性预检判定失败、整行静默禁用。 > 🧭 **按你的 DSH 版本选插件版本**: > > | 你的 DSH 版本 | 安装命令 | 版本 / peer 声明 | > | --- | --- | --- | -> | **0.2.0-rc.2+**(含之后的 0.2.0 正式版) | `dsh plugin --profile web add dsh-better-sidebar@latest` | **0.24.1**,`^0.2.0-rc.2` | -> | **0.1.7-rc.1 ~ 0.1.7-rc.2**(含 0.1.7 正式版;npm `latest` 目前仍是 0.1.7-rc.2) | `dsh plugin --profile web add dsh-better-sidebar@0.22.1` | **0.22.1**,`^0.1.7-rc.1` | +> | **0.2.0-rc.2+**(含之后的 0.2.0 正式版) | `dsh plugin --profile web add dsh-better-sidebar@latest` | **0.26.0**,`^0.2.0-rc.2` | +> | **0.1.7-rc.1 ~ 0.1.7-rc.2**(含 0.1.7 正式版) | `dsh plugin --profile web add dsh-better-sidebar@0.22.1` | **0.22.1**,`^0.1.7-rc.1` | > | 0.1.7-alpha.1 / 0.1.7-alpha.2 | **没有可装版本**——先把 DSH 升到 rc.1,再跑上一行:
`npm i -g @deepseek-ai/dsh@0.1.7-rc.1` | — | > | 0.1.6-alpha.2 及更早、`0.1.5-rc.*`(含 npm `latest` 的 0.1.5-rc.3) | `dsh plugin --profile web add dsh-better-sidebar@0.19.1` | **0.19.1**,`^0.1.5-rc.1` | > | `0.1.5-alpha.2` | `dsh plugin --profile web add dsh-better-sidebar@0.19.0-alpha.1` | `^0.1.5-alpha.2` | @@ -191,7 +191,19 @@ dsh registry enable dsh-external/dsh-better-sidebar ## 🆕 最近更新 -**支持的 DSH 版本**:支持的 DSH 版本(v0.24.0):0.2.0-rc.2+ · 完整发布历史见 [Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases) +**支持的 DSH 版本**:支持的 DSH 版本(v0.26.0):0.2.0-rc.2+ · 完整发布历史见 [Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases) + +### v0.26.0 + +> 🚀 **四件大事**:① **传输全面流式化**——上传 / 下载 / HTML 预览 / 打包都不再有大小上限(三个部署限额键 `readLimit` / `mediaLimit` / `uploadLimit` 随之删除),编辑器保存也拆掉了 1 MiB 的请求体墙;② **超大文件从「截断成半份文档」改为只读分页预览**(滚到底自动续读 + 「加载全部」,到 5 万行提示改用下载),并新增第 4 个内置 viewer **`.jsonl` / `.ndjson`**(逐条可折叠卡片 + 可保存编辑);③ **侧边对话补齐到接近原生**——实时推送(纯失效帧 + 增量重拉)、排队可见与按 id 撤回、per-thread 模型选择;④ **任务管理面板整批重构**(按组展开、Token 用量与耗时、画布动效与错峰入场)。另有底部工作台**多终端 Tab**、编辑器**引用行号**的四处收尾、文件改名 / 删除**同时作用于原生右栏页签**(修掉「改名后保存把旧文件重建」「删掉的文件被保存复活」这类数据面问题)、三处静默数据问题等,逐条见 [CHANGELOG](./CHANGELOG.md#v0260)。 + +> ⚡ **性能**:修掉一个会让界面发卡的 git 状态轮询——编辑器打开文件后**不再长期持有轮询**(此前每 2.5 s 跑一次 `git status --untracked-files=all` 加两条全仓库 `--numstat`,在未忽略的大目录上实测 59,631 条 / 9.24 MB / 0.13 s 一次),基线改为 **30 s** 并按实测自动退档(60 s / 180 s / 停止自动轮询),**空闲轮询也不再触发重渲染**;文件树的折叠链预加载与逐子目录探测两处放大一并收敛。 + +### 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.2.0-rc.1 及更早(含 0.1.7 线)请固定 v0.24.1**——`^0.2.0-rc.2` 对 rc.1 判定为 false,会被宿主的启动兼容性预检整行静默禁用。本次前移是一次**纯声明与钉版变更**:0.2.0-rc.2 对本插件消费的宿主面仍是纯增量,运行时零改动。 +> +> 🙏 本版包含多位贡献者的工作(按合并先后列在 [CHANGELOG](./CHANGELOG.md#v0250) 里)。 ### v0.24.1 diff --git a/README_EN.md b/README_EN.md index 88650370..4df8bb12 100644 --- a/README_EN.md +++ b/README_EN.md @@ -3,7 +3,7 @@ > [!IMPORTANT] > **Built on DSH's native sidebar API** (since v0.19.0): the right column *is* DSH's own sidebar — the plugin registers every tab type as a native tab (no right panel of its own anymore) and keeps only its self-drawn bottom workbench and the `ctx.betterSidebar` service open to every plugin. > -> **Since v0.24.1 the host support floor is DSH `0.2.0-rc.2+`** (peer floor `^0.2.0-rc.2`). Everything this plugin consumes from 0.2.0 is **purely additive** (zero removed exports, session format still v4, CLI and client runtime byte-identical), so this version carries no runtime compatibility branch — it only moves the support line. **Hosts on the 0.1.7 line should pin `dsh-better-sidebar@0.22.1` — a caret never spans a minor bump, and `^0.1.7-rc.1` is silently disabled by the 0.2.0 startup preflight**; the DSH-to-plugin version table is in [Installation](#-installation). +> **Since v0.25.0 the host support floor is DSH `0.2.0-rc.2+`** (peer floor `^0.2.0-rc.2`; unchanged in v0.26.0). Everything this plugin consumes from 0.2.0 is **purely additive** (zero removed exports, session format still v4, CLI and client runtime byte-identical), so this support line carries no runtime compatibility branch — it only moves the baseline. **Hosts on the 0.1.7 line should pin `dsh-better-sidebar@0.22.1` — a caret never spans a minor bump, and `^0.1.7-rc.1` is silently disabled by the 0.2.0 startup preflight**; the DSH-to-plugin version table is in [Installation](#-installation).
@@ -14,7 +14,7 @@ GitHub stars License: MIT dshfind

- Supported DSH versions (v0.24.1): 0.2.0-rc.2+ + Supported DSH versions (v0.26.0): 0.2.0-rc.2+ Plugin ecosystem: GitHub topic dsh-better-sidebar

File management Edit & preview Bottom workbench Changes Background tasks Side Chat Plugin integration

A dual workbench (right sidebar + bottom panel) that opens its ctx.betterSidebar service to every plugin —
@@ -62,16 +62,16 @@ What this plugin adds on top of DSH's stock sidebar: **Prerequisites**: DSH installed (`dsh web` boots), Node.js ≥ 20, pnpm ≥ 10. **Supported DSH versions**: -Supported DSH versions (v0.24.0): 0.2.0-rc.2+ +Supported DSH versions (v0.26.0): 0.2.0-rc.2+ -> 📌 **Channel and support line**: `v0.24.1` targets DSH **0.2.0-rc.2+** (0.2.0's first candidate rides npm's `next` dist-tag; `latest` is still 0.1.7-rc.2). **Pin the DSH version exactly**: `npm i -g @deepseek-ai/dsh@0.2.0-rc.2`. **Hosts on the 0.1.7 line should pin `dsh-better-sidebar@0.22.1`**: 0.2.0 is a host minor bump, and caret ranges such as `^0.1.7-rc.1` fail the host's startup compatibility preflight on 0.2.0, which disables the whole profile row silently. +> 📌 **Channel and support line**: `v0.26.0` targets DSH **0.2.0-rc.2+** (both `latest` and `next` on npm are `0.2.0-rc.2`). **Pin the DSH version exactly**: `npm i -g @deepseek-ai/dsh@0.2.0-rc.2` (the `alpha` channel's `0.2.1-alpha.x` is outside this release's support line). **Hosts on the 0.1.7 line should pin `dsh-better-sidebar@0.22.1`**: 0.2.0 is a host minor bump, and caret ranges such as `^0.1.7-rc.1` fail the host's startup compatibility preflight on 0.2.0, which disables the whole profile row silently. > 🧭 **Pick the plugin version that matches your DSH**: > > | Your DSH | Install command | Version / peer declared | > | --- | --- | --- | -> | **0.2.0-rc.2+** (including a later 0.2.0 stable) | `dsh plugin --profile web add dsh-better-sidebar@latest` | **0.24.1**, `^0.2.0-rc.2` | -> | **0.1.7-rc.1 – 0.1.7-rc.2** (and a later 0.1.7 stable; npm `latest` is still 0.1.7-rc.2) | `dsh plugin --profile web add dsh-better-sidebar@0.22.1` | **0.22.1**, `^0.1.7-rc.1` | +> | **0.2.0-rc.2+** (including a later 0.2.0 stable) | `dsh plugin --profile web add dsh-better-sidebar@latest` | **0.26.0**, `^0.2.0-rc.2` | +> | **0.1.7-rc.1 – 0.1.7-rc.2** (and a later 0.1.7 stable) | `dsh plugin --profile web add dsh-better-sidebar@0.22.1` | **0.22.1**, `^0.1.7-rc.1` | > | 0.1.7-alpha.1 / 0.1.7-alpha.2 | **nothing to install** — move DSH to rc.1 first, then run the row above:
`npm i -g @deepseek-ai/dsh@0.1.7-rc.1` | — | > | 0.1.6-alpha.2 and earlier, `0.1.5-rc.*` (including the 0.1.5-rc.3 that is npm's `latest`) | `dsh plugin --profile web add dsh-better-sidebar@0.19.1` | **0.19.1**, `^0.1.5-rc.1` | > | `0.1.5-alpha.2` | `dsh plugin --profile web add dsh-better-sidebar@0.19.0-alpha.1` | `^0.1.5-alpha.2` | @@ -200,7 +200,19 @@ WeChat / QQ group QR codes will live here. After uploading the QR images (drag t Service API base screenshot
-**Supported DSH versions**: Supported DSH versions (v0.24.0): 0.2.0-rc.2+ · full release history on the [Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases) page +**Supported DSH versions**: Supported DSH versions (v0.26.0): 0.2.0-rc.2+ · full release history on the [Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases) page + +### v0.26.0 + +> 🚀 **Four headline changes**: ① **transfers are fully streamed** — upload, download, the HTML preview and archiving have no size ceiling left (the three deployment caps `readLimit` / `mediaLimit` / `uploadLimit` are gone with them), and saving from the editor dropped its 1 MiB request-body wall; ② **very large files** no longer open as a truncated half-document — they get a read-only paged preview (scroll to the end to append the next page, "load all", and a download hint at 50k rows) — plus a **fourth built-in viewer for `.jsonl` / `.ndjson`** (collapsible record cards + saveable edit); ③ **Side Chat reaches near-parity with a native session** — live push (invalidation frames + incremental refetch), a visible queue with per-item retraction, and per-thread model selection; ④ **the Tasks panel was rebuilt** (expand by group, token usage and duration, canvas motion with staggered entrances). Also: **multiple terminal tabs** in the bottom workbench, four follow-ups to **reference line numbers**, rename/delete now reaching the **native right-sidebar tabs** (fixing data-level bugs such as "saving recreated a renamed file" and "saving resurrected a deleted one"), and three silent data problems. Item by item in [CHANGELOG](./CHANGELOG.md#v0260). + +> ⚡ **Performance**: a git-status poll that made the whole UI stutter is gone — the editor no longer *owns* the poll after you open a file (it used to run `git status --untracked-files=all` plus two whole-repo `--numstat` diffs every 2.5 s; measured on a repository with a large unignored tree: 59,631 entries / 9.24 MB / 0.13 s per call), the baseline is **30 s** now with automatic back-off (60 s / 180 s / no automatic polling), and idle polls no longer re-render anything; two file-tree amplifiers (fold-chain preload, per-directory probing) were converged in the same batch. + +### v0.25.0 + +> 📦 **Support line moved: DSH `0.2.0-rc.2+` only** (peer floor `^0.2.0-rc.2`, CI and the mount lane pin `@deepseek-ai/dsh@0.2.0-rc.2`). npm's `latest` for DSH is exactly **0.2.0-rc.2** now, and this release pins it. **Hosts on 0.2.0-rc.1 or older (including the 0.1.7 line) should pin v0.24.1** — `^0.2.0-rc.2` evaluates false against rc.1, so the host's startup compatibility preflight disables the whole row silently. The move itself is a **declaration-and-pin change only**: 0.2.0-rc.2 stays purely additive against everything this plugin consumes, with zero runtime changes. +> +> 🙏 This release carries work from several contributors (listed in merge order in [CHANGELOG](./CHANGELOG.md#v0250)). ### v0.24.1 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 38f68590..f6d27e84 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -34,7 +34,7 @@ | 文件打开的认领判定 | 插件自己的一切文件入口(文件树点击 / 路径输入 / 文件变动页 / 「新标签页打开」,合并与分屏两种模式)都先问宿主原生 tab 注册表:`ctx.sidebarRightTabs.candidates(address)` 的头名若不是本插件的 `editor`,地址改走 `ctx.sidebarRight.openResource`,由**认领类型**渲染自己的 tab——第三方直接在宿主注册表按更具体 glob 注册的原生类型(如 `.drawio` 画板)从此在文件树里点得开(#695);无人认领、宿主无注册表或探测失败时行为逐字保持原样(落到 `editor` / code 兜底) | | 终端(宿主一条 + 插件底部一条,彼此独立) | 插件**不在原生右侧栏提供终端**:宿主 0.1.6 起自带 `ui-sidebar-terminal`(kind `terminal`),插件侧 PTY 栈与 `terminal_*` 工具整体删除。**但插件自己的底部工作台有一条终端**(`terminal-bottom`,#774):它不注册原生类型、不占 guide 条目(`bottomOnly`),页面是插件自绘的 xterm,进程由**宿主的会话级终端服务** `ctx.webTerminals` 供给——插件不持有 PTY,也不与右列那条共享进程(两条终端各自独立是有意的,右列仍是宿主的地盘)。宿主没挂终端控制器时该类型 `available` 为 false(菜单置灰),页面显示「宿主未提供终端能力」而不是崩 | | `bottomOnly`(#774) | 只投底部、永不注册原生承载面的类型(字段说明见 §4)。它同时意味着:`openTab` 落点强制 `'bottom'`(连 `target: 'side'` 也被改道——原生栏里的 tab 不在底部工作台的分栏树里,两者归属矛盾)、原生 tab 类型与 guide 条目都不注册。`hidden: true` **不是**它的替代品:那会连 `+` 菜单一起摘掉(`buildNewTabOptions` 过滤 `!hidden`),而它要的正是「留在 `+` 菜单、只离开原生栏」 | -| 底部终端的恢复语义(#774) | 刷新后重新上屏同一页签时,页面用**同一份 `(sessionId, key, contentId)`** 再次调用宿主的 `webTerminals.view()`:宿主持久化在 localStorage 的 `(sessionId, contentId) → 终端 id` 绑定因此把**同一个** PTY 认回来(`contentId` 恒为 `dsh-better-sidebar:terminal-bottom`)。插件**不把 terminalId 写进 `tab.meta`**:`view()` 显式传 terminalId 会关掉宿主的「缺了就建」分支,一个过期的 id 会把页签永久卡在 `missingTerminal` 上。DSH 重启后 PTY 全没了而 localStorage 绑定还在,所以「新建终端」按钮把 `tab.meta.terminalRun` +1 换一代 `contentId`,让宿主另铸一个进程,而不是反复认领死绑定 | +| 底部终端的恢复语义(#774) | 刷新后重新上屏同一页签时,页面用**同一份 `(sessionId, key, contentId)`** 再次调用宿主的 `webTerminals.view()`:宿主持久化在 localStorage 的 `(sessionId, contentId) → 终端 id` 绑定因此把**同一个** PTY 认回来(`contentId` 是 `dsh-better-sidebar:terminal-bottom:`——**每个页签一个实例,不再是恒定值**,#926)。插件**不把 terminalId 写进 `tab.meta`**:`view()` 显式传 terminalId 会关掉宿主的「缺了就建」分支,一个过期的 id 会把页签永久卡在 `missingTerminal` 上。DSH 重启后 PTY 全没了而 localStorage 绑定还在,所以「新建终端」按钮把 `tab.meta.terminalRun` +1 换一代 `contentId`,让宿主另铸一个进程,而不是反复认领死绑定 | | 底部工作台的开合 | 落到底部工作台的打开一律展开它(新建与聚焦都算),因此 `openTab` 的落点永远可见;开合按钮注册在 DSH 会话头的 utilities 槽(`conversation.session.header.utilities`),不在插件自己的宿主里 | | 在侧边打开(`target: 'side'`,v0.22.0+) | 原生栏里的 tab **不在插件底部工作台的分栏树里**,所以「在侧边打开」不能写 `bottomSplits`(那样会落到用户没展开的底部工作台 = 点了没反应)。服务改为把这一步交给宿主:带 path 的 `editor` seed 走 `openResource(address, { preferNewPane: true, revealIfOpened: false })`——宿主先按自己的两格上限与空间规则尝试分栏,分不了才回退到当前格;`revealIfOpened: false` 允许与已打开的同名资源并存,因此对同一个文件再点一次也会新开一格。其余类型若传 `target: 'side'`,同样以 `preferNewPane` 落原生栏(组件型 tab 的 path 仍是组件种子)——**唯一的例外是 `bottomOnly` 类型**(#774):它没有原生承载面可落,`target: 'side'` 被改道回 `'bottom'`。path-less 的 `editor`(文件页)与 `'bottom'` 行为不变 | | 新建标签页列表 | 每个 tab 类型在原生 guide 里占一行:标题取 `title` + 图标取 `icon`(缺图标时宿主补一个方块占位),说明取可选的 `description`——**宿主只在 guide 列出的条目 ≤ 4 条时渲染说明**(上游 `MAX_DESCRIBED_ENTRIES = 4`),更长的列表整列丢掉所有说明;未声明 `description` 的条目渲染成单行「图标 + 标题」(rc.1 起 `description` 回到宿主契约,但**宿主与插件都没有兜底句**,所以插件恢复字段而不恢复旧的通用句);`hidden: true` 的类型不占行,**`bottomOnly: true` 的类型同样不占行**(#774:它只活在插件自己的底部 `+` 菜单里)。插件的 `editor` 类型不再单独占行(它认领的文件资源由 `files` 接管页承载同一视图)。**本插件默认贡献 4 个 guide 条目**(文件 / 文件变动 / 任务管理 / 侧边对话,恰好在上限内),**但宿主的终端条目也占一行**——装了宿主终端即是 5 条,说明整列不渲染;要让说明回来,需在插件设置页关掉足够多的 tab 类型把总数压到 ≤ 4 条 | @@ -51,7 +51,7 @@ better-sidebar 从 v0.4.0 起把自己改造成一个**注册表服务**: - **新页面(tab)**:注册一种新的侧边栏 tab 类型,出现在侧边栏 `+` 菜单里,用户点击后在自己的分栏里打开你的 React 页面; - **文件预览器(file viewer)**:注册一种文件类型预览器,让用户在侧边栏打开文件时走你的渲染组件(覆盖或补充内置的 markdown/html/code)。**宿主自己也有文档预览**——DSH 0.1.7 的 `ui-sidebar-documentpreview` 拿走了表格 / PDF / 图片 / Office 等只读格式,本插件因此**拒绝**认领那些扩展名,你的 viewer 也接不到它们(清单与原因见 §5.4)。 -内置的 6 个 tab(editor / git——「文件变动」统一 tab(Git 视角 + 本轮文件视角)/ subagent / sidechat / terminal-bottom / diff)和 3 个 viewer(markdown / html / code)**自己也是通过同一套 API 注册的**(吃自己的狗粮),所以外部插件的能力与内置功能完全对等。**不再内置 terminal / browser 两个 tab 类型**:DSH 0.1.6 自带右列终端(`ui-sidebar-terminal`、kind `terminal`),浏览器是 0.1.6 的 `ui-sidebar-browser`(kind `browser`,**0.1.7 起只在 desktop profile 挂载**,Web profile 没有这个 kind);插件的同名类型会让读者看到两份实现。同理,0.1.7 的 `ui-sidebar-documentpreview` 让插件的 image / pdf / Office / 表格预览失去意义,那三个 viewer 描述符(image / pdf / binary-download)已删除。 +内置的 6 个 tab(editor / git——「文件变动」统一 tab(Git 视角 + 本轮文件视角)/ subagent / sidechat / terminal-bottom / diff)和 4 个 viewer(markdown / html / jsonl / code)**自己也是通过同一套 API 注册的**(吃自己的狗粮),所以外部插件的能力与内置功能完全对等。**不再内置 terminal / browser 两个 tab 类型**:DSH 0.1.6 自带右列终端(`ui-sidebar-terminal`、kind `terminal`),浏览器是 0.1.6 的 `ui-sidebar-browser`(kind `browser`,**0.1.7 起只在 desktop profile 挂载**,Web profile 没有这个 kind);插件的同名类型会让读者看到两份实现。同理,0.1.7 的 `ui-sidebar-documentpreview` 让插件的 image / pdf / Office / 表格预览失去意义,那三个 viewer 描述符(image / pdf / binary-download)已删除。 关键机制一句话:better-sidebar 的 client half 在 `apply()` 开头执行 `ctx.provide('betterSidebar', service)`(`src/client/index.tsx`),消费插件在 `inject` 里声明 `'betterSidebar'`,Cordis 保证服务就绪后才激活你的插件,然后你调用 `ctx.betterSidebar.registerTab(...)` / `registerFileViewer(...)` 完成注册,返回的 disposer 由 Cordis fiber 在卸载(HMR / 禁用)时自动调用。 @@ -458,7 +458,7 @@ ctx.effect(() => { | `subagent` | 30 | 是 | 否 | 任务管理(工作流图/树、团队任务板、后台任务抽屉) | | `sidechat` | 35 | 否(`sidechat:`,按 `meta.threadId` 去重) | 否 | 侧边对话(每对话一 Tab):打开即建空线程(首条消息赢得标签并同步标题);线程 = 插件自建子会话(种子继承父会话上下文,进行中回合以 `interrupted` 闭合;种子带合法 `subagent/descriptor`,SubagentView 按 `Side: ` 前缀过滤),`origin:'subagent'` 隐藏于主列表;走 `/sidebar/api/sidechat.*` 路由;头部菜单切换/重开(`parkSidechatReopen` + 确定性 id),关 Tab 释放 live agent;重开经 `collectOwnEvents` 回源到种子边界;「保存为新会话」= `session.fork`(`this` 敏感)。[设计文档](plans/2026-08-20-sidechat-tab-design.md) | | `diff` | -1 | 否(按 id 去重) | 是 | 差异查看(changes tab 的预览面板「展开为独立页签」触发,同一渲染栈) | -| `terminal-bottom` | 40 | 是 | 否 | 底部工作台的终端(#774)。**`bottomOnly`**(见 §4 与「原生承载面」表的说明):没有原生 tab 类型、不占 guide 条目,只在底部 `+` 菜单里。页面是插件自绘的 xterm(`lib/client-terminal.js` chunk),**进程由宿主的会话级终端服务 `ctx.webTerminals` 供给**(结构化探测,不写进 `dsh.client.inject`——缺服务只会让这一行置灰,不会把整行拖成 `pending`)。恢复靠宿主持久化的 `(sessionId, contentId) → 终端 id` 绑定(`contentId` 恒定),关页签走 `onClose` → `webTerminals.close()` 结束进程(卸载**不**关:宿主的契约是「视图跨 DOM 卸载存活」,刷新要能认回同一个 shell),`tab.meta.terminalRun`(默认 0)是「新建终端」换代号用的代号位。[设计文档](plans/2026-10-05-bottom-terminal-tab.md) | +| `terminal-bottom` | 40 | 否(`createTab` 每次铸新 id) | 否 | 底部工作台的终端(#774)。**`bottomOnly`**(见 §4 与「原生承载面」表的说明):没有原生 tab 类型、不占 guide 条目,只在底部 `+` 菜单里。页面是插件自绘的 xterm(`lib/client-terminal.js` chunk),**进程由宿主的会话级终端服务 `ctx.webTerminals` 供给**(结构化探测,不写进 `dsh.client.inject`——缺服务只会让这一行置灰,不会把整行拖成 `pending`)。恢复靠宿主持久化的 `(sessionId, contentId) → 终端 id` 绑定(`contentId` 形如 `dsh-better-sidebar:terminal-bottom:`,**每个页签一个实例**,#926),关页签走 `onClose` → `webTerminals.close()` 结束进程(卸载**不**关:宿主的契约是「视图跨 DOM 卸载存活」,刷新要能认回同一个 shell),`tab.meta.terminalRun`(默认 0)是「新建终端」换代号用的代号位。[设计文档](plans/2026-10-05-bottom-terminal-tab.md) | 你的 `id` 不可与上述重复,否则 `registerTab` 抛 `"tab type \"X\" already registered"`。 diff --git a/docs/plans/2026-10-05-editor-git-gutter.md b/docs/plans/2026-10-05-editor-git-gutter.md index fa3703c1..c3bd9dd4 100644 --- a/docs/plans/2026-10-05-editor-git-gutter.md +++ b/docs/plans/2026-10-05-editor-git-gutter.md @@ -58,6 +58,17 @@ 问题,不是产品回归。 - **`tests/prefs.spec.ts` 三个「整份 prefs 深比较」补上 `editorGitGutter: true`**: 新增 schema 字段的既有约定动作。 +- **收尾(2026-10-13):gutter 不再持有共享轮询。** 上面「行映射只有一个来源」 + 那条只做对了一半——它确实没起第二个轮询器,但**把功能开关当成了可见性** + (`useGitStatus(scope, { visible: enabled })`),而 `visible` 正是启动 2.5 s + 定时器的那把开关,且原生页签 `keepMounted` 让编辑器切走也不卸载。于是从打开 + 第一个 `code` / `jsonl` 文件起,整页生命周期里每 2.5 s 跑一次 + `git status --untracked-files=all`(外加两条全仓库 `--numstat`)——在未忽略的 + 嵌套 `node_modules` / 包管理器 store 上是 9.24 MB、0.131 s 一次(真机实测), + 用户侧的观感就是后台 CPU 与风扇。现在改为 `{ visible: active, poll: false }`: + 编辑器只读共享答案、只在**换文件或保存**时各重读一次,**永不拥有定时器**;页签 + 不可见时连订阅都不建立。共享轮询的节奏与降频阶梯见 + [2026-10-13-git-poll-ladder-and-idle-notify.md](2026-10-13-git-poll-ladder-and-idle-notify.md)。 ## 验收 diff --git a/docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md b/docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md new file mode 100644 index 00000000..7d552c54 --- /dev/null +++ b/docs/plans/2026-10-13-file-tree-perf-fold-preload-and-probe-budget.md @@ -0,0 +1,69 @@ +# 文件树性能核查与两处收敛:折叠链预加载上限 + 请求级探测预算 + +日期:2026-10-13 分支:`fix/file-tree-perf`(从 `dev` 切出) + +## 1. 背景与核查结论 + +用户带着六条断言要求核查「文件 Tab」与「深层级文件」的性能问题。逐条落到代码后的结论(每条都有实测/直读证据,未采纳的项见 §4): + +| 断言 | 结论 | 证据 | +|---|---|---| +| 文件 Tab「无 memo 边界」 | **不成立** | `FileRow`/`DirRow`/`RootRow` 三个 `memo` 组件(`src/client/FileTree.tsx:249/331/413`),`actions` 经 `useMemo` 稳定(`:1252`),props 刻意只传原始值/稳定引用(git 状态以 `gitTone`/`gitLetter` 原始值传入,`:237-247`) | +| 文件 Tab「无虚拟化」 | 成立(本轮不处理) | 递归直出(`:2025-2127`),全客户端无 windowing/`contain`/`content-visibility`;每层受 `listLimit`(默认 1000)与 `truncated` 提示约束 | +| 宿主每列一层、每个子目录一次探测 | **成立** | `fs-tree.ts` 的 `readDirectory` → `probeCompactRows` → `hasSingletonChild`(`src/fs-tree.ts:263-291`):每个目录行一次 `opendir` + ≤2 次 dirent 读;缓解是 1.5s TTL 层缓存 + 单层并发 32 | +| ↳ 并发放大(核查中新增) | **成立** | `fs.trees` 对 ≤64 路径 `Promise.all`(`src/index.ts:712-727`)× 每层 32 路 → 冷挂载宽目录树时单请求理论上同开约 2048 个 `opendir` | +| 折叠链「一节一次往返」 | **成立且严格串行** | 下一节名字只能从上一节 listing 得到(`src/client/file-tree-compact.ts:48-53`),预加载 effect 依赖 `data`(`src/client/FileTree.tsx:1004-1012`)→ N 节 = N 个串行 POST(每波跨链合批上限 64)。`tests/file-tree-compact-fold.spec.tsx` 钉的是**被请求路径集合**,不锁 POST 次数 | +| 「超 32 节静默截断」 | **成立**(折叠链维度,非路径截断) | `MAX_COMPACT_DEPTH = 32` 只在渲染侧生效(`file-tree-compact.ts:27/40`),而 `compactLoadTargets` 旧实现**无深度上限**——渲染在 32 停手、预加载继续往下;注释里「健康缓存永不触及」也不准确,合法的深单子目录链真会触及 | +| watch 64 上限「静默击穿」 | 单连接**未**击穿;「静默」与进程级无全局上限成立 | 上限 64、超限 `add()` 返回 false(`src/fs-watch.ts:31/104`),测试钉住前 64 接受且不驱逐(`tests/fs-watch.spec.ts:119-132`);拒绝只回 `{dir, ok:false}` 而客户端不处理该分支(`src/client/use-dir-watch.ts:116-125`);cap 是 per-WebSocket,`keepMounted` 下多会话同时挂载时进程总句柄可达 64×N | + +核查中另行记录(未入选本轮):`DirRow` 的 `chain` 数组来自 `useMemo(…, [data])`(`FileTree.tsx:1842-1851`),层级缓存一变整份重建 → 每次 watch 通知/展开/改名都让**所有目录行**重渲染(`FileRow` 仍能 bail);git 状态每 2.5s 在请求开始与结束各 `notify` 一次(`src/client/ui/git-status.ts:211/236`),导致整树每 2.5s 重建一次 element 树(快照 identity 保留机制见 `:216-224`)。 + +## 2. 改动一:折叠链预加载与渲染共用同一深度口径(client) + +`compactLoadTargets` 从「扫描所有已加载层」改为「从**渲染根**沿折叠链下行」,上限由同一个 `compactChain` 天然继承(它本就按 `MAX_COMPACT_DEPTH` 截断): + +```ts +compactLoadTargets(levels, roots) // roots = [cwd, ...expanded] + work list(非递归,深树不压栈)+ visited 去重 + 对每个已加载层的每个目录行: + chain = compactChain(entry, levelOf) // ≤ 32 链接,停在首个未加载链接 + tail = chain.at(-1) + tail 仍 compact 且该层未加载 → 收集为 frontier(唯一需要加载的一节) + 否则链尾已加载:chain.length < 32 才下行扫下一节(收敛点) +``` + +- **为什么这样就能封顶**:链长到 32 时 `compactChain` 不再延伸,于是永远拿不出第 33 节作为目标——不需要额外的深度计数。 +- **语义等价性**:非 compact 目录的 `compactChain` 立即返回单元素链,只在下行时探查其(已展开才存在的)已加载层,与旧全局扫描覆盖相同;折叠行未展开也继续长齐标签的行为保留(逐波补链)。 +- **调用点**:`FileTree.tsx:1015` 传 `[cwd, ...propsRef.current.expanded]`,effect 依赖保持 `[cwd, data, loadLevels]`(`data` 是真到达信号,展开总会伴随可见集 effect 的加载,故不需要把 `expanded` 放进依赖)。 +- **注释订正**:`MAX_COMPACT_DEPTH` 上方原先「健康缓存下永不触及」的表述改为准确口径(合法深链会触及;循环守卫是 `compactChain` 的 `visited`,不是这个常量)。 + +旧实现下 `tests/file-tree-compact.spec.ts` 与 `tests/file-tree-compact-fold.spec.tsx` 的新用例实测变红(`expected 40 to be 32`、`['/elsewhere/x']`、第 33 节被请求),证明用例有判别力。 + +## 3. 改动二:请求级探测预算(host) + +- `src/fs-tree.ts` 新增 `PROBE_BUDGET = 32`、`ProbeGate`、`createProbeGate(limit)`(FIFO 信号量,`limit < 1` 夹到 1;`run` 用 `try/finally` 释放;释放时把槽位直接交给队首)。 +- `listDirectory(path, maxEntries, exclude?, gate?)` → `listDirectoryCached` → `readDirectory`(**仅缓存未命中**路径),两个 probe(symlink stat / compact opendir)都经 `runProbe(gate, …)`。缓存命中不占额度。 +- `src/index.ts` 的 `fs.trees`(`:711`)在 `Promise.all` 之前建**一个** gate 并传给每个 `listDirectory`;`fs.tree` 单路径路由传 `undefined`,行为逐字不变。 +- 值取 32 = 现有单层常量:单层/单路径行为与改前完全一致,只是「层数 × 32」变成了「每请求 ≤32」。 +- 实现偏差记录:第一版把 gate 取槽放在 `forEachRow` 的**行访问**上,于是 symlink probe 对非链接行、compact probe 对文件行也各取一次空转槽位——计数单测立刻暴露(期望 9 实际 18)。改为只在真实 fs 调用外层取槽(`runProbe`)。 +- `forEachRow` 因此保持原三参签名不变,per-level 的 `SYMLINK_PROBE_CONCURRENCY` / `COMPACT_PROBE_CONCURRENCY = 32` 继续作为单层 worker 池。 + +## 4. 明确不做(用户已定,记录以免重复争论) + +1. **不引入虚拟化**,也不为此加压力测试/文档:memo 边界 + 每层 1000 行上限 + `truncated` 提示已够用(用户判断「目前性能看起来都没问题」)。 +2. **watch 上限不加任何用户提示、不加全局(跨连接)句柄上限**:有的机器本来就无法 watch,VS Code 自动刷新失败同样不提示(保留 per-连接语义与既有日志行为)。 +3. **不改 `DirRow` 的 chain identity**(每层级变动全目录行重渲染)。 +4. **不处理 git 每 2.5s 导致的整树 element 重建**。 + +## 5. 测试与验证 + +- `tests/file-tree-compact.spec.ts`:`compactLoadTargets` 两条既有用例改新签名 + roots;新增「只从渲染根走」(不可达层不再贡献目标)与「到渲染上限即停」(fixture 是 MAX_COMPACT_DEPTH+1 条已加载链接、第 33 节存在但未加载,旧实现会收它)。 +- `tests/file-tree-compact-fold.spec.tsx`:既有「折叠成一行 + 预加载整条链」断言保持;新增一条 40 节链的用例——预加载最深恰为 `MAX_COMPACT_DEPTH`、绝不请求第 33 节。 +- `tests/fs-tree-probe-gate.spec.ts`(新,真实临时目录,不 mock `node:fs`):`createProbeGate` 的在飞上界 / 排队任务抛错后槽位释放且保持 FIFO / `limit<1` 夹紧;`listDirectory` 每个目录探测恰好花一个槽位、缓存命中花零个;三个层共享一个 gate 时合计 9 次(3 层 × 3 个目录行)。 +- `tests/smoke.spec.ts`:新增路由级断言——一次 `fs.trees` 请求只调一次 `createProbeGate`(用 `vi.mock(…, importOriginal)` 包一层计数,其余导出保持真实),即「批次共享一个预算」;`fs.tree` 单路径与其余路由行为回归由既有用例覆盖。 +- 既有 `tests/fs-tree*.spec.ts` / `tests/fs-watch.spec.ts` 全绿(`gate` 是可选参数,既有调用逐字不变)。 +- **与本轮无关的既有 flaky**:`tests/fs-watch.spec.ts` 的「treats a repeat add as already-watched」是 `fs.watch` + 真实写入的 15s 等待,在多副本并行跑时会在任意副本上偶发红;把全部改动 stash 掉后同样复现,故不是本轮引入。 + +## 6. 交付说明 + +门禁:`pnpm typecheck`、`pnpm lint`、`pnpm test`(本轮不涉及 e2e/挂载 lane)。改动仅 4 个源文件 + 3 个测试文件 + 本文件;`fs.tree` 单路径路由与 `fs-watch` 行为未触碰,未新增 UI 文案或 locale key。 diff --git a/docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md b/docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md new file mode 100644 index 00000000..d74f020f --- /dev/null +++ b/docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md @@ -0,0 +1,121 @@ +# git 状态轮询收敛:30 s 基线 + 空闲不通知 + 降频阶梯(v0.26.0) + +> 分支 `fix/git-poll-ladder`(基于 `dev`,DSH 0.2.0-rc.2 线)。 +> 触发:维护者反馈「有嵌套 node_modules 的仓库里整个界面发卡、风扇转,编辑文件时尤其明显」。 + +## 问题与实测 + +一次性成本远大于预期。本机 `~/Code/deepseek-harness-desktop`(未忽略的 `.pnpm-store` +与「嵌套 node_modules 未被 `/node_modules` 锚定规则覆盖」是同一形态)实测: + +| 命令 | 条目 | stdout | 耗时 | +|---|---|---|---| +| `status --porcelain=v1 -z --untracked-files=all` | **59,631** | **9.24 MB** | 0.131 s | +| 同上 `-unormal` | 1 | 0.00 MB | 0.032 s | + +`GIT_STATUS_LIMIT = 2000` 是在整份 9.24 MB 已经产出、拼进 Node 字符串、`split('\0')` +成 59,631 个对象**之后**才截断的。而它每 2.5 s 跑一次(外加两条无 pathspec 的 +`diff --numstat` 与一条建仓查询,共 4 个进程)。 + +两个放大器让这件事从「后台开销」变成「看得见的卡」: + +1. **编辑器 gutter 持有轮询**([2026-10-05-editor-git-gutter.md](2026-10-05-editor-git-gutter.md) + 的「实施偏差」收尾条):`useGitStatus(scope, { visible: enabled })` 把功能开关当 + 可见性,而 `visible` 就是启动定时器的开关;原生页签 `keepMounted` 让编辑器切走 + 也不卸载。于是打开过任何一个 `code` / `jsonl` 文件之后,**整页生命周期**都在跑。 +2. **空闲轮询触发全量重渲染**:`fetchSlot` 的 `.finally()` 无条件 `notify()` 自增 + `slot.version`,而它就是 `useSyncExternalStore` 的 snapshot。`sameStatus` 已经保住 + 了 snapshot 身份(注释写明是为了让下游 memo 跨 tick 保持),版本号却在订阅层把 + 这份努力作废——文件树在**父层**逐行算 `dirHasChanges`/`statusOf`,每 tick 照付。 + +## 落地内容 + +### 1. 空闲不通知(`src/client/ui/git-status.ts`) + +只有可观测状态真的变了才 `notify`:起手仅当 `loading` false→true;`.then` 仅在快照 +被替换或 `error` 解除时;`.catch` 仅在 `error` 置位时;`.finally` 仅当「变了」或 +「loading 落回 false」。`release()` 丢弃快照仍通知。数据未变时消费者**一次都不重渲染**。 + +### 2. 降频阶梯 + +```ts +const POLL_BASE_MS = 30_000 +const SLOW_TIERS_MS = [750, 2_000, 5_000] +const TIER_FACTORS = [1, 2, 6, null] // 30s / 60s / 180s / 停止自动轮询 +``` + +tier 是**最近一次往返耗时的纯函数**(`tier = SLOW_TIERS_MS.filter(t => d >= t).length`), +所以快响应立刻回到基线,没有连续计数、不会卡在某一档。tier 变化即重建定时器 +(间隔烘在 handle 里)。停在最高档后,挂载 / 保存 / 暂存 / 提交 / 丢弃 / 手动刷新 +这些**事件驱动**的刷新照常工作,而且它们就是恢复通道。 + +选客户端往返耗时而不是服务端上报:它同时覆盖 git 的工作量与传输,且不需要新协议。 + +**阈值取位的说明**:上面实测的那个仓库(0.131 s)**不会**触发降档——它落在 tier 0, +靠的是基线本身从 2.5 s 抬到 30 s(同一份扫描的工作量降到 1/12,占空比从约 5% 降到 +约 0.4%)。750 ms 那一档是给真正慢的形态兜底:更大的 monorepo、冷缓存、网络盘 / +WSL 挂载、Windows 上的进程 spawn 开销。把第一个阈值压到能命中 0.131 s 没有必要, +那会让正常的仓库也频繁退档。 + +### 3. 两种消费者(`poll`) + +`useGitStatus` 新增 `poll?: boolean`(默认 `true`)。`Slot` 把「要数据」(`visible`) +与「要定时器」(`pollers`)分开计数: + +- `visible 0→1` 时抓一次(**与 poll 无关**,非轮询消费者也要一次读数); +- `pollers 0→1` 起表、`1→0` 停表; +- 只有 `poll: true` 的消费者会写 `slot.pollMs`,不会覆盖别人正在跑的节奏; +- `visible → 0` 时停表 + 清快照。 + +文件树(`FileTree.tsx`)与文件变动页(`changes/GitLens.tsx`)走默认值,**行为逐字不变**, +只是节奏从 2.5 s 变 30 s 起。 + +### 4. gutter 只读不轮询 + +`useEditorGitGutter` 新增 `visible`,订阅改为 `{ visible: active, poll: false }` +(`active = enabled && visible`),并只在**换文件或保存**时各 `refresh()` 一次; +`TextEditor` 把 `props.visible !== false` 传下去(`FileViewerProps.visible` 早已由 +`EditorHost` 下发,无需新增管道)。挂载时**不**额外请求——没有别的承载面时 +`retain` 已经抓了一次,同一提交里再要一次只是重复扫描。 + +### 5. `worktrees()` 的计数不再跑完整 status + +`worktrees()` 对**每个 linked checkout** 调完整 `status()`(4 个进程,含 `-uall` 与两条 +全仓库 numstat)只为读 `.entries.length`,而变动页每 30 s 轮询它一次。改为单命令 +`git status --porcelain=v1 -z --untracked-files=normal` 并数条目:N×4 → N×1 轻量进程。 + +**语义有一处刻意的变化**:未跟踪**目录**计 1 而不是展开计入每个文件——「这个 checkout +有没有改动」本来就该这么读,而且旧数字还被 `GIT_STATUS_LIMIT` 悄悄截断过。文件树与 +变动页的逐文件行不受影响(它们读的是完整 `status()`)。 + +## 验收 + +- `tests/git-status-poll.spec.tsx`(7 例):`poll:false` 不起表 / `poll:true` 走 30 s 基线 / + 非轮询先到不阻塞后来的轮询者、轮询者离开即停表 / **空闲同结果不通知**(snapshot 恒等)/ + 慢往返退到 60 s 且快响应回到基线 / 极慢往返停止自动轮询且事件刷新可恢复 / 不可见不订阅。 +- `tests/editor-git-gutter.spec.tsx` +3:在屏编辑器不持有轮询(推进 120 s 仍 1 次)/ + 不可见时完全不订阅 / 换文件与保存各只重读一次、纯重渲染不重读。 +- `tests/git-worktree.spec.ts` +1:未跟踪目录在清单里计 1,而完整 `status()` 仍展开 50 条。 +- 判别性:分别回退「空闲守卫」「poll 归属」「gutter 的 `poll:false`」,对应用例当场红 + (已逐条实测)。 + +## 后续项(本次普查发现,未纳入本批) + +三条只读普查线(客户端周期任务 / 宿主命令成本 / 长驻流式资源)共 30+ 项,按 +「收益 ÷ 改动量」排序,本批只收 git 这一族: + +| # | 位置 | 问题 | 量级 | +|---|---|---|---| +| 1 | `src/git.ts` 的 `status()` | 两条**无 pathspec** 的 `diff --numstat`,每轮成本 = 全部已改文件字节 | 21 MB 已改文件 = 0.17 s/轮 | +| 2 | `src/git.ts` 的 `runGit` | stdout 全量拼成 JS 字符串,**无字节上限** | 9.24 MB → ≥18 MB 串 + rope | +| 3 | `src/fs-tree.ts` compact 探测 / `src/index.ts` 单层 `fs.tree` 路由 | 每个目录行一次 `opendir`(1000 行 = 21.1 ms);`ProbeGate` 只在飞并发 32、不限总量;单层路由**不传 gate** | 单批最坏 6.4 万次 `opendir` | +| 4 | `src/client/sidebar/right-panel-open.ts` + `dock-fallback.tsx` | 两个常驻 500 ms 定时器做强制同步布局;`dock-fallback` 最坏每 tick 400 步 `elementsFromPoint`;都无视 `document.hidden` | 4 次/秒强制布局(估低 git 那条 1–2 个数量级) | +| 5 | `src/sidechat-routes.ts` | cold 线程每次轮询**全量重读**持久化日志后 `slice(8000)` | O(线程历史) | +| 6 | `src/client/JobsDrawer.tsx`、`SubagentView.tsx` | 每秒 / 每 3 s **无条件**写新对象 → 整表重渲染 | 行数决定 | +| 7 | `git-status.ts:slots`、`git.ts:repoRootsCache`、`active-worktree.ts`、`ops-stream.ts` | 模块级 Map **无容量上限** | 内存增长(非本次症状) | + +已核实有界、不需要动的:三条推送 socket(纯失效帧 + 去抖 + 指数退避 + 空闲零帧)、 +终端(插件不持 PTY,宿主逐帧 ack = 天然背压)、归档/流式(并发 4 + TTL + 全错误路径删 +临时文件 + `pipeline` 常量内存)、`ops-stream` 的 leader 选举与空闲裁剪、`frame-batcher`、 +有界 rAF 动效、`use-polling` 的 self-scheduling,以及除 `git-status.ts` 之外所有 +`useSyncExternalStore` 快照的稳定性(逐个查过,那条计数器是孤例)。 diff --git a/dsh.plugin.json b/dsh.plugin.json index 8be510d4..d7e2e1de 100644 --- a/dsh.plugin.json +++ b/dsh.plugin.json @@ -1,6 +1,6 @@ { "id": "dsh-external/dsh-better-sidebar", - "version": "0.25.0", + "version": "0.26.0", "main": "./lib/index.js", "description": "更好用的右侧边栏——文件树、编辑器、文件变动、任务和侧边对话都收在这一栏里,每个会话互不干扰。暴露服务供其他插件注册侧边栏页面与文件预览器", "engines": { diff --git a/eslint.config.js b/eslint.config.js index 85e274c9..c5c9492d 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -10,7 +10,9 @@ import reactHooks from 'eslint-plugin-react-hooks' import tseslint from 'typescript-eslint' export default tseslint.config( - // 构建产物 / 工具目录不参与 lint(node_modules 与点开头目录默认也不进)。 + // 构建产物 / 工具目录不参与 lint(node_modules 默认不进,但**点开头目录 + // 并不自动排除**——`.worktrees/` 与 `.delta/` 都必须显式列出,否则 ESLint + // 会走进那些陈旧检出,把别的分支的错误报成我们的:实测一次 1115 errors)。 { ignores: [ 'lib/', @@ -22,6 +24,7 @@ export default tseslint.config( 'node_modules/', '.worktrees/', 'soruce/vscode/', // Pinned upstream reference checkout, not plugin source. + '.delta/', ], }, diff --git a/package.json b/package.json index fd564001..4fd90c42 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-better-sidebar", - "version": "0.25.0", + "version": "0.26.0", "description": "Better Sidebar for DSH — file tree, editor, changes, tasks and side chat in one column, separate for every conversation. Also exposes a service other plugins use to register sidebar tabs and file viewers.", "type": "module", "repository": { diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 65a31998..b3991b3f 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -1006,9 +1006,15 @@ export function FileTree(props: { // levels are loaded ahead of any expansion (without them the breadcrumb // label would grow one segment at a time as the user clicks). Each arrival // can reveal the next link, hence the rescan on every cache update; - // loadLevels skips what is already loaded, so this settles. + // loadLevels skips what is already loaded, so this settles. The roots are + // read LIVE through `propsRef`, keeping this effect's dependencies at + // [cwd, data, loadLevels]: the level cache is the real trigger (an arrival + // reveals the next link), and an expansion is always accompanied by the + // visible-set effect above loading (or having loaded) that level. The walk + // itself stops at the render cap, so a chain the row stopped folding at + // MAX_COMPACT_DEPTH never keeps pulling deeper levels. if (cwd === undefined) return - loadLevels(compactLoadTargets(dataRef.current)) + loadLevels(compactLoadTargets(dataRef.current, [cwd, ...propsRef.current.expanded])) }, [cwd, data, loadLevels]) // A torn-down tree must not write the answer of an in-flight batch into a diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index facc434b..bed2573e 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -153,7 +153,17 @@ export function TextEditor(props: FileViewerProps) { () => ({ scope: { sessionId: scope.sessionId, cwd: scope.cwd, repoRoot: scope.repoRoot }, path }), [scope.sessionId, scope.cwd, scope.repoRoot, path], ) - const gitKinds = useEditorGitGutter({ enabled: gitGutterEnabled, scope, path, content, revision: gitRevision }) + const gitKinds = useEditorGitGutter({ + enabled: gitGutterEnabled, + // A parked native tab stays MOUNTED (`keepMounted`), so the tab's own + // visibility is what decides whether the gutter does git work at all: a + // hidden editor holds no status subscription and no timer. + visible: props.visible !== false, + scope, + path, + content, + revision: gitRevision, + }) /** Preview scroll position across the preview<->edit toggle. The preview * container re-mounts on every mode switch and its scrollTop lives on that * element, so capture it on scroll and restore after each remount. Seeded diff --git a/src/client/editor-git-gutter.ts b/src/client/editor-git-gutter.ts index 404414ca..e1f03b0c 100644 --- a/src/client/editor-git-gutter.ts +++ b/src/client/editor-git-gutter.ts @@ -7,10 +7,12 @@ * end-of-line author widget, no badges, no animation, no gradient. * * Three rules shape the wiring: - * - ONE git status source. `useGitStatus` (the plugin's shared store, also - * behind the file tree's ink) decides WHICH files changed and whether a - * file is untracked; this module never starts a second poller. The line - * map itself comes from `git diff --no-color` through the existing + * - ONE git status source, and it is READ-ONLY here: `useGitStatus` (the + * plugin's shared store, also behind the file tree's ink) decides WHICH + * files changed and whether a file is untracked; this module never starts a + * second poller AND never owns the shared one — it subscribes with + * `poll: false` and refreshes on its own events (a file open, a save). The + * line map itself comes from `git diff --no-color` through the existing * unified-diff parser (`diff/rows.ts`), so a line's class is git's own * answer — context rows are never marked. * - Only the `code` viewer carries the extensions (the caller passes null @@ -24,7 +26,7 @@ * and a vanished diff (the file was committed or discarded) must not leave * the pre-commit line answering the next hover. */ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { RangeSet, Compartment, StateEffect, StateField, type EditorState, type Extension } from '@codemirror/state' import { EditorView, GutterMarker, gutter, gutterLineClass, hoverTooltip, type Tooltip } from '@codemirror/view' import { api, type GitBlameLine, type SessionScope } from './api.ts' @@ -293,8 +295,14 @@ function blameTooltipDom(entry: GitBlameLine): HTMLElement { /** Everything the gutter needs from the editor component. */ export interface EditorGitGutterOptions { - /** False for every viewer but `code`, and when the setting is off. */ + /** False for every viewer but `code` / `jsonl`, and when the setting is off. */ enabled: boolean + /** + * Whether the editor's tab is actually on screen. Native tabs are kept + * MOUNTED while parked, which is not the same as staying subscribed: a + * hidden editor must not hold any git work. + */ + visible: boolean scope: SessionScope path: string /** The loaded text; a reload re-reads the change set. */ @@ -310,7 +318,7 @@ export interface EditorGitGutterOptions { * the disabled state all resolve to an empty map — no decoration. */ export function useEditorGitGutter(options: EditorGitGutterOptions): ReadonlyMap { - const { enabled, path, content, revision } = options + const { enabled, visible, path, content, revision } = options const sessionId = options.scope.sessionId const cwd = options.scope.cwd const repoRoot = options.scope.repoRoot @@ -318,9 +326,34 @@ export function useEditorGitGutter(options: EditorGitGutterOptions): ReadonlyMap () => ({ sessionId, cwd, ...(repoRoot !== undefined ? { repoRoot } : {}) }), [sessionId, cwd, repoRoot], ) - const status = useGitStatus(scope, { visible: enabled }) - const entry = enabled ? status.statusOf(path) : undefined + const active = enabled && visible + // `poll: false` — the gutter reads the shared answer but NEVER owns the + // timer. Passing the feature switch as `visible` (what this did before) meant + // that opening any file kept a `git status --untracked-files=all` running for + // the rest of the page's life, cadence after cadence, while the user was + // simply typing — megabytes of output per scan on a repository with an + // unignored nested `node_modules` or package-manager store. The gutter is + // allowed to lag; the file listing and the rest of the page are not. + const status = useGitStatus(scope, { visible: active, poll: false }) + const entry = active ? status.statusOf(path) : undefined const [kinds, setKinds] = useState>(EMPTY_KINDS) + const refresh = status.refresh + + /** + * One event-driven re-read when the gutter's question changes: a DIFFERENT + * file, or the SAME file after a save. Deliberately not on mount — when no + * other surface holds the status, `retain` has already fetched one answer, + * and a second request in the same commit would only duplicate that scan. + */ + const lastAsk = useRef(null) + useEffect(() => { + if (!active) return + const ask = `${path}\u0000${String(revision)}` + const previous = lastAsk.current + lastAsk.current = ask + if (previous === null || previous === ask) return + refresh() + }, [active, path, revision, refresh]) useEffect(() => { // A fresh change set invalidates the file's blame memo (the lines that @@ -330,7 +363,7 @@ export function useEditorGitGutter(options: EditorGitGutterOptions): ReadonlyMap // the enabled branch would never run and the next hover would be answered // with the pre-commit line (the '[Not Committed Yet]' placeholder too). forgetBlame(scope.sessionId, path) - if (!enabled || entry === undefined) { + if (!active || entry === undefined) { setKinds(EMPTY_KINDS) return undefined } @@ -344,7 +377,7 @@ export function useEditorGitGutter(options: EditorGitGutterOptions): ReadonlyMap () => { if (!cancelled) setKinds(EMPTY_KINDS) }, ) return () => { cancelled = true } - }, [enabled, scope, path, content, revision, entry]) + }, [active, scope, path, content, revision, entry]) return kinds } diff --git a/src/client/file-tree-compact.ts b/src/client/file-tree-compact.ts index 5c5e6494..1ef29e35 100644 --- a/src/client/file-tree-compact.ts +++ b/src/client/file-tree-compact.ts @@ -20,9 +20,13 @@ export interface CompactLevel { } /** - * Safety cap on one fold chain. Real directories cannot cycle, so this is - * never reached on a healthy cache — it bounds the chain when a stale cache - * lies about a level's contents. + * Cap on one fold chain, shared by what the row RENDERS and what the preload + * loads ahead of it ({@link compactLoadTargets}) so a chain never pays for + * links the breadcrumb would not show. A legitimate deep singleton chain + * (a Java package path, a chain of single-child project folders) does reach + * this; past it the breadcrumb stops folding and the next link appears as its + * own row on expansion. The stale-cache cycle guard is {@link compactChain}'s + * `visited` set, not this. */ export const MAX_COMPACT_DEPTH = 32 @@ -58,19 +62,47 @@ export function compactChain(entry: FsEntry, levelOf: (path: string) => CompactL /** * The collapsed singleton directories whose levels still need loading, so - * fold chains can extend past what the user has expanded. Scans every - * LOADED level once; each arrival may reveal the next link, so the caller - * re-runs this after every cache update. Chains cannot cycle (host never - * marks symlink children), so the walk terminates at the chain's real end. + * fold chains can extend past what the user has expanded. Walks down from the + * RENDERED levels (`roots` — the workspace root plus every expanded + * directory) along the very same {@link compactChain} the row renderer builds + * its label with, so the walk inherits that chain's + * {@link MAX_COMPACT_DEPTH} cap: past the cap the breadcrumb stops folding and + * the preload stops asking for links the renderer would never draw. (The + * previous every-loaded-level scan kept pulling link 33, 34, … for a chain + * the row had already stopped folding at 32 — one serial POST plus one + * whole-tree render per wasted link.) + * + * Each arrival may reveal the next link, so the caller re-runs this after + * every cache update. `visited` dedupes that walk and keeps it terminating: + * chains cannot cycle (the host never marks symlink children). + * @param levels - the tree's level cache, keyed by absolute path. + * @param roots - the levels the tree actually renders, in any order. + * @returns the absolute paths of the frontier links still to load. */ -export function compactLoadTargets(levels: Record): string[] { +export function compactLoadTargets(levels: Record, roots: readonly string[]): string[] { const targets = new Set() - for (const level of Object.values(levels)) { - if (level.entries === undefined) continue + const visited = new Set() + // A work list, not recursion: a deep expanded tree must not grow the stack. + const pending = [...roots] + while (pending.length > 0) { + const dir = pending.pop()! + if (visited.has(dir)) continue + visited.add(dir) + const level = levels[dir] + // Unloaded, in-flight (`{}`) or failed level: nothing to scan here. + if (level?.entries === undefined) continue for (const entry of level.entries) { - if (entry.isDir && entry.compact === true && levels[entry.path] === undefined) { - targets.add(entry.path) + if (!entry.isDir) continue + const chain = compactChain(entry, path => levels[path]) + const tail = chain[chain.length - 1]! + // The chain's frontier: its tail still folds but that level is unloaded. + if (tail.compact === true && levels[tail.path] === undefined) { + targets.add(tail.path) + continue } + // Tail already loaded: descend for the next frontier link — but stop at + // the render cap, which is exactly where the label stops extending. + if (chain.length < MAX_COMPACT_DEPTH) pending.push(tail.path) } } return [...targets] diff --git a/src/client/service.ts b/src/client/service.ts index 9fb9d2d5..e32a31bb 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -819,7 +819,7 @@ export function matchUrlTarget(tabs: readonly TabDescriptor[], url: URL): TabDes * The plugin version this service instance reports. Keep in lockstep with * `package.json`'s version — `tests/service.spec.ts` asserts the pair. */ -export const SIDEBAR_SERVICE_VERSION = '0.25.0' +export const SIDEBAR_SERVICE_VERSION = '0.26.0' /** * Monotonic capability list consumers use to gate new API usage (features diff --git a/src/client/ui/git-status.ts b/src/client/ui/git-status.ts index d8b36bd1..3b62a328 100644 --- a/src/client/ui/git-status.ts +++ b/src/client/ui/git-status.ts @@ -19,6 +19,28 @@ * Coalescing: a `refresh()` that lands while a fetch is in flight is queued * once and re-run when it settles — never dropped (the old `GitLens.refresh` * returned early, so a click during the poll silently did nothing). + * + * Cadence: the fetch behind this store is `git status --untracked-files=all` + * plus two `--numstat` diffs, and on a repository holding a large UNIGNORED + * tree (a nested `node_modules`, a pnpm store) that is megabytes of output and + * a fifth of a second of CPU. It therefore runs on a SLOW baseline (30 s) and + * drops a tier whenever the last round trip came back slow — 2x, then 6x (the + * user's "60 s / 180 s"), and finally no automatic timer at all — so a + * pathological repository cannot keep a git process running forever. Every + * consumer keeps the event-driven refreshes (`refresh()`, + * `invalidateGitStatus`) at full speed, and any fast answer climbs back to the + * baseline, so the ladder is self-correcting rather than sticky. + * + * Two kinds of consumer exist, and the store separates them: one that WANTS + * the timer (`poll`, the default — the file tree's ink and the changes page) + * and one that only wants the answer (`poll: false` — the editor's gutter, + * which refreshes on mount and after a save). A non-polling consumer can never + * be the reason a timer runs, and it can never delay one either. + * + * Idle polls are silent: a fetch that returns the same status notifies nobody. + * Bumping the version on every tick re-rendered every consumer — the file + * tree's rows included — once per cadence for no reason, which is what the + * snapshot identity check above exists to prevent. */ import { useCallback, useEffect, useSyncExternalStore } from 'react' import { api, type GitLineCounts, type GitStatusResult, type SessionScope } from '../api.ts' @@ -169,8 +191,14 @@ interface Slot { generation: number running: boolean pending: boolean + /** Consumers that want the ANSWER (any `poll` value). */ visible: number + /** Consumers that want the automatic TIMER (`poll: true`). */ + pollers: number + /** The base cadence a polling consumer asked for (30 s by default). */ pollMs: number + /** Which slow tier the last round trip landed in (0 = the baseline). */ + tier: number timer: number | undefined listeners: Set<() => void> index: Index | null @@ -178,8 +206,32 @@ interface Slot { indexSource: GitStatusResult | null } +/** + * The baseline cadence of an automatic poll. Deliberately slow: one fetch is a + * full `git status --untracked-files=all` (plus two `--numstat` diffs), and the + * ink it drives is decoration — the file tree's own listing comes from + * `fs.trees` and never waits for git. Every user-visible git action + * (stage / commit / discard, a manual refresh, a save in the editor) refreshes + * through `invalidateGitStatus` / `refresh()` immediately, so the cadence only + * governs how fast an EXTERNAL change shows up. + */ +const POLL_BASE_MS = 30_000 + +/** Round trips slower than these drop the slot one tier (measured client-side, + * so it covers both git's work and the transport). */ +const SLOW_TIERS_MS = [750, 2_000, 5_000] + +/** The interval factor of each tier: 30 s, 60 s, 180 s, then no timer at all. */ +const TIER_FACTORS: readonly (number | null)[] = [1, 2, 6, null] + const slots = new Map() +/** The automatic cadence of one slot; `null` = no timer (tier 3). */ +function intervalOf(slot: Slot): number | null { + const factor = TIER_FACTORS[slot.tier] ?? null + return factor === null ? null : slot.pollMs * factor +} + function slotOf(scope: SessionScope, worktree: string | undefined): Slot { const { sessionId, cwd, repoRoot } = scope const key = `${sessionId}\u0000${cwd ?? ''}\u0000${repoRoot ?? ''}\u0000${worktree ?? ''}` @@ -188,7 +240,8 @@ function slotOf(scope: SessionScope, worktree: string | undefined): Slot { const slot: Slot = { key, sessionId, cwd, repoRoot, worktree, snapshot: null, loading: false, error: false, version: 0, generation: 0, - running: false, pending: false, visible: 0, pollMs: 2_500, timer: undefined, + running: false, pending: false, visible: 0, pollers: 0, + pollMs: POLL_BASE_MS, tier: 0, timer: undefined, listeners: new Set(), index: null, indexSource: null, } @@ -201,6 +254,19 @@ function notify(slot: Slot): void { for (const listener of slot.listeners) listener() } +/** + * Move the slot to the tier the last round trip belongs in and re-arm the + * timer when that changed. The tier is a pure function of the most recent + * measurement, so a repository that recovers climbs straight back to the + * baseline — no streak counters, no stuck ladder. + */ +function noteFetchDuration(slot: Slot, durationMs: number): void { + const tier = SLOW_TIERS_MS.filter(threshold => durationMs >= threshold).length + if (tier === slot.tier) return + slot.tier = tier + reschedule(slot) +} + /** Fetch one snapshot; a concurrent call just marks the slot dirty. */ function fetchSlot(slot: Slot): void { if (slot.running) { @@ -209,33 +275,44 @@ function fetchSlot(slot: Slot): void { } slot.running = true const generation = ++slot.generation + const wasLoading = slot.loading slot.loading = slot.snapshot === null - notify(slot) + if (slot.loading !== wasLoading) notify(slot) + // Whether this fetch changed anything a consumer can SEE. An idle poll that + // returns the same status must stay silent: the version counter is the + // `useSyncExternalStore` snapshot, so notifying re-renders every consumer — + // the changes list and every rendered file-tree row with it — once per + // cadence for nothing. The snapshot identity below is preserved for exactly + // this reason; the notification has to honour it too. + let changed = false + const startedAt = Date.now() const scope: SessionScope = { sessionId: slot.sessionId, cwd: slot.cwd, repoRoot: slot.repoRoot } api.gitStatus(scope, slot.worktree) .then((snapshot) => { if (generation !== slot.generation) return - // Idle polls return the same answer as a NEW object every 2.5s. Keeping - // the previous identity when nothing changed is what lets every - // downstream memo (the changes tree, the file tree's row model, the - // icon index) hold across ticks — without it the whole list re-rendered - // and re-resolved icons on every poll. + // Idle polls return the same answer as a NEW object. Keeping the + // previous identity when nothing changed is what lets every downstream + // memo (the changes tree, the file tree's row model, the icon index) + // hold across ticks. if (slot.snapshot !== null && sameStatus(slot.snapshot, snapshot)) { - slot.error = false + if (slot.error) { slot.error = false; changed = true } return } slot.snapshot = snapshot slot.error = false + changed = true }) .catch(() => { if (generation !== slot.generation) return - slot.error = true + if (!slot.error) { slot.error = true; changed = true } }) .finally(() => { if (generation !== slot.generation) return slot.running = false + const stillLoading = slot.loading slot.loading = false - notify(slot) + if (changed || stillLoading) notify(slot) + noteFetchDuration(slot, Date.now() - startedAt) if (slot.pending) { slot.pending = false fetchSlot(slot) @@ -245,7 +322,9 @@ function fetchSlot(slot: Slot): void { function startTimer(slot: Slot): void { if (slot.timer !== undefined) return - slot.timer = window.setInterval(() => { fetchSlot(slot) }, slot.pollMs) + const interval = intervalOf(slot) + if (interval === null) return + slot.timer = window.setInterval(() => { fetchSlot(slot) }, interval) } function stopTimer(slot: Slot): void { @@ -254,18 +333,35 @@ function stopTimer(slot: Slot): void { slot.timer = undefined } -function retain(slot: Slot): void { - slot.visible += 1 - if (slot.visible === 1) { - if (slot.snapshot === null) fetchSlot(slot) - startTimer(slot) - } +/** + * Re-arm the timer after the tier moved. A cadence change means a new handle + * (the interval is baked into the old one); a slot whose tier 3 stopped the + * timer stays stopped, and one with no polling consumer is left alone. + */ +function reschedule(slot: Slot): void { + if (slot.pollers === 0) return + stopTimer(slot) + startTimer(slot) } -function release(slot: Slot): void { +function retain(slot: Slot, poll: boolean): void { + slot.visible += 1 + if (poll) slot.pollers += 1 + // The answer is fetched for the FIRST consumer whatever kind it is — a + // non-polling consumer still needs one reading, it just must not own a timer. + if (slot.visible === 1 && slot.snapshot === null) fetchSlot(slot) + if (poll && slot.pollers === 1) startTimer(slot) +} + +function release(slot: Slot, poll: boolean): void { slot.visible = Math.max(0, slot.visible - 1) + if (poll) { + slot.pollers = Math.max(0, slot.pollers - 1) + if (slot.pollers === 0) stopTimer(slot) + } if (slot.visible === 0) { stopTimer(slot) + slot.pollers = 0 // No consumer left: drop the snapshot so a later mount re-reads the truth // instead of coloring rows from a stale answer. slot.snapshot = null @@ -311,14 +407,18 @@ export interface GitStatusView { } /** - * Subscribe to the shared git status of one session (optionally of one - * linked worktree). The poll runs while `visible` is true, at `pollMs`. + * Subscribe to the shared git status of one session (optionally of one linked + * worktree). While `visible` is true the consumer holds the answer; while + * `poll` is also true it holds the automatic timer (at `pollMs`, escalated by + * the slow tiers). `poll: false` is for a consumer that wants one reading and + * event-driven refreshes — the editor's gutter — so it can never keep a git + * process running in the background. */ export function useGitStatus( scope: SessionScope, - options: { worktree?: string; visible?: boolean; pollMs?: number } = {}, + options: { worktree?: string; visible?: boolean; pollMs?: number; poll?: boolean } = {}, ): GitStatusView { - const { worktree, visible = true, pollMs = 2_500 } = options + const { worktree, visible = true, pollMs = POLL_BASE_MS, poll = true } = options const slot = slotOf(scope, worktree) const subscribe = useCallback((listener: () => void) => { slot.listeners.add(listener) @@ -330,11 +430,13 @@ export function useGitStatus( useSyncExternalStore(subscribe, () => slot.version, () => slot.version) useEffect(() => { - slot.pollMs = pollMs + // Only a polling consumer states the cadence; a non-polling one must not + // overwrite the rhythm the timer is actually running at. + if (poll) slot.pollMs = pollMs if (!visible) return undefined - retain(slot) - return () => { release(slot) } - }, [slot, visible, pollMs]) + retain(slot, poll) + return () => { release(slot, poll) } + }, [slot, visible, pollMs, poll]) const refresh = useCallback(() => { fetchSlot(slot) }, [slot]) const statusOf = useCallback( diff --git a/src/fs-tree.ts b/src/fs-tree.ts index 3d238c5f..2c6d721d 100644 --- a/src/fs-tree.ts +++ b/src/fs-tree.ts @@ -124,12 +124,13 @@ export function invalidateDirectoryCache(path?: string): void { const DIRECTORY_CACHE_MAX = 512 /** Read one level through the cache when it is fresh. */ -async function listDirectoryCached(path: string, maxEntries: number, exclude?: ExcludeMatcher): Promise { +async function listDirectoryCached(path: string, maxEntries: number, exclude?: ExcludeMatcher, gate?: ProbeGate): Promise { const key = cacheKey(path, maxEntries, exclude) const now = Date.now() const hit = directoryCache.get(key) + // A cached level runs no filesystem probe at all, so it never spends budget. if (hit !== undefined && now - hit.at < DIRECTORY_CACHE_TTL_MS) return hit.listing - const listing = await readDirectory(path, maxEntries, exclude) + const listing = await readDirectory(path, maxEntries, exclude, gate) // Bounded: a deep walk of many directories must not grow this map without // limit (entries are tiny, but an unbounded map in a long-lived host is a // leak). Map iteration order is insertion order, so the first key is oldest. @@ -148,15 +149,18 @@ async function listDirectoryCached(path: string, maxEntries: number, exclude?: E * @param exclude - compiled exclude-pattern probe (the explorerExclude pref): * matched entries are dropped from the listing AND the singleton fold probe, * so they never render nor block a breadcrumb fold. + * @param gate - optional shared probe budget; a batch listing many levels + * passes ONE gate ({@link createProbeGate}) so the per-level probe bounds do + * not multiply. Cache hits never touch it. * @returns the sorted listing. * @throws {SidebarError} fs-error when the level is unreadable or not a directory. */ -export async function listDirectory(path: string, maxEntries = 1000, exclude?: ExcludeMatcher): Promise { - return await listDirectoryCached(path, maxEntries, exclude) +export async function listDirectory(path: string, maxEntries = 1000, exclude?: ExcludeMatcher, gate?: ProbeGate): Promise { + return await listDirectoryCached(path, maxEntries, exclude, gate) } /** Read one level straight from the filesystem (the cache's slow path). */ -async function readDirectory(path: string, maxEntries: number, exclude?: ExcludeMatcher): Promise { +async function readDirectory(path: string, maxEntries: number, exclude?: ExcludeMatcher, gate?: ProbeGate): Promise { let dirents try { // One syscall batch instead of an `opendir` stream: `readdir` with types is @@ -197,15 +201,70 @@ async function readDirectory(path: string, maxEntries: number, exclude?: Exclude // symlink-heavy level (UNC/network targets) would otherwise serialize up to // maxEntries stat calls and stall the explorer. Non-symlink rows are skipped, // so levels without links stay as cheap as before. - await probeSymlinkTargets(rows) + await probeSymlinkTargets(rows, gate) // Mark singleton-directory rows AFTER the symlink probe (it finalizes // isDir/broken), so the client can fold compact chains without an extra // round trip per collapsed level. - await probeCompactRows(rows, exclude) + await probeCompactRows(rows, exclude, gate) rows.sort(compareEntries) return { path, entries: rows, truncated } } +/** + * In-flight filesystem probes ONE listing request may run across ALL of its + * levels. The per-level bounds below are exactly that — per level — while a + * batch request lists up to `FS_TREES_MAX_PATHS` levels concurrently + * (`fs.trees`), so without a shared budget a cold mount of a wide tree could + * hold levels × per-level probes open at once (64 × 32). Equal to the + * per-level constant on purpose: a single-level listing behaves as before. + */ +export const PROBE_BUDGET = 32 + +/** A FIFO gate bounding how many probe operations run at the same time. */ +export interface ProbeGate { + /** + * Run one probe operation under the gate. + * @param task - the probe; it must not acquire the gate itself. + * @returns the task's own result. + */ + run(task: () => Promise): Promise +} + +/** + * Create the probe gate one listing request shares across its levels. + * @param limit - maximum probes in flight; below 1 is clamped to 1. + * @returns the gate. + */ +export function createProbeGate(limit = PROBE_BUDGET): ProbeGate { + const max = Math.max(1, Math.floor(limit)) + let active = 0 + const waiting: (() => void)[] = [] + const acquire = (): Promise => new Promise((resolve) => { + if (active < max) { + active += 1 + resolve() + return + } + waiting.push(() => { active += 1; resolve() }) + }) + const release = (): void => { + active -= 1 + // Hand the freed slot straight to the next waiter (it re-increments), so + // `active` never reports fewer probes than are actually running. + waiting.shift()?.() + } + return { + async run(task: () => Promise): Promise { + await acquire() + try { + return await task() + } finally { + release() + } + }, + } +} + /** * Visit every row with at most `concurrency` visitors in flight, in row order. * Both probes below spend one await per row (a network stat, an opendir) on a @@ -225,13 +284,26 @@ async function forEachRow(rows: readonly SidebarFsEntry[], concurrency: number, await Promise.all(workers) } +/** + * Run one FILESYSTEM probe under the request's budget. + * + * The slot is taken here, around the syscall, not around the row visit: a row + * the visitor skips without touching the filesystem must not spend budget. + * @param gate - the request's gate, or absent for an unbounded probe. + * @param task - the probe operation. + * @returns the probe's own result. + */ +function runProbe(gate: ProbeGate | undefined, task: () => Promise): Promise { + return gate === undefined ? task() : gate.run(task) +} + /** Probe each symlink row's target once (bounded concurrency, order-preserving). */ -async function probeSymlinkTargets(rows: SidebarFsEntry[], concurrency = SYMLINK_PROBE_CONCURRENCY): Promise { +async function probeSymlinkTargets(rows: SidebarFsEntry[], gate?: ProbeGate, concurrency = SYMLINK_PROBE_CONCURRENCY): Promise { await forEachRow(rows, concurrency, async (row) => { if (!row.isSymlink) return // stat follows the chain; any failure (missing target, ELOOP, permission) // leaves the row as a broken file-shaped link the editor refuses to read. - const info = await stat(row.path).catch(() => undefined) + const info = await runProbe(gate, () => stat(row.path)).catch(() => undefined) row.isDir = info !== undefined ? info.isDirectory() : row.isDir row.broken = info === undefined }) @@ -246,14 +318,15 @@ const COMPACT_PROBE_CONCURRENCY = 32 * row. The terminal link (sole FILE child) is marked too: the client * preloads marked levels to stabilize the fold label before expansion. * Bounded concurrency like the symlink probe: each probe is one opendir + up - * to two dirent reads, so a directory-heavy level stays responsive. Probe - * failures (unreadable child level) leave the row unmarked — it simply does - * not fold. + * to two dirent reads, so a directory-heavy level stays responsive. A shared + * {@link ProbeGate} also keeps a whole batch's levels within one probe budget. + * Probe failures (unreadable child level) leave the row unmarked — it simply + * does not fold. */ -async function probeCompactRows(rows: SidebarFsEntry[], exclude?: ExcludeMatcher, concurrency = COMPACT_PROBE_CONCURRENCY): Promise { +async function probeCompactRows(rows: SidebarFsEntry[], exclude?: ExcludeMatcher, gate?: ProbeGate, concurrency = COMPACT_PROBE_CONCURRENCY): Promise { await forEachRow(rows, concurrency, async (row) => { if (!row.isDir || row.broken) return - if (await hasSingletonChild(row.path, exclude)) row.compact = true + if (await runProbe(gate, () => hasSingletonChild(row.path, exclude))) row.compact = true }) } diff --git a/src/git.ts b/src/git.ts index 9eace8ed..83bfb00c 100644 --- a/src/git.ts +++ b/src/git.ts @@ -640,6 +640,23 @@ async function listedWorktrees(cwd: string): Promise { return parseWorktreeList(raw).filter(entry => !entry.prunable) } +/** + * How many entries `git status` reports for one checkout, as ONE cheap command. + * + * The inventory below used to call the full `status()`, which spawns four + * processes — including the `--untracked-files=all` walk and two whole-repo + * `--numstat` diffs — just to read `.entries.length`, per linked checkout, on a + * 30 s poll. This asks the same question with a single process and without the + * untracked walk. The number differs in exactly one way, deliberately: an + * untracked DIRECTORY counts as one entry instead of as every file inside it, + * which is what "this checkout has changes" should read as anyway (and the old + * number was silently capped at `GIT_STATUS_LIMIT` regardless). + */ +async function countChanges(cwd: string): Promise { + const raw = await runGit(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=normal']) + return parsePorcelainZ(raw).length +} + /** All linked checkouts of the repository containing `cwd`, enriched with a * live change count. The current checkout is first so a single-worktree repo * preserves the old UI ordering. */ @@ -653,7 +670,7 @@ export async function worktrees(cwd: string): Promise { current: pathIdentity(entry.path) === pathIdentity(currentRoot), // One stale/permission-raced linked checkout must not hide the valid // current repository from the panel. Targeted operations still fail loud. - changes: await status(entry.path).then(result => result.entries.length, () => 0), + changes: await countChanges(entry.path).catch(() => 0), }))) return rows.sort((left, right) => Number(right.current) - Number(left.current)) } diff --git a/src/index.ts b/src/index.ts index 917f084f..a0288990 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,7 +26,7 @@ import { type SidebarConfig, type SidebarPrefs, } from './config.ts' -import { listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts' +import { createProbeGate, listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts' import { resolveSessionPath } from './session-path.ts' import { createWorkspaceFile, mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceText, writeWorkspaceUpload } from './fs-operations.ts' import { ensureWorkspacePath } from './path-security.ts' @@ -705,6 +705,11 @@ function buildApi( // explorerExclude pref has to be compiled here too, or the exclude list // would simply not reach the only surface the explorer reads. const exclude = compileExcludePatterns(record?.exclude, cwd) + // ONE probe budget for the whole request: every level keeps its own + // per-level probe bound, but a batch of up to FS_TREES_MAX_PATHS levels + // shares one gate, so the bounds do not multiply (64 × 32 opendirs on a + // cold mount of a wide tree). Cache hits never touch the gate. + const gate = createProbeGate() const levels = await Promise.all(paths.map(async (raw): Promise => { // A session-relative path is accepted here (the tree already carries // cwd-relative paths); `fs.tree` itself keeps requiring absolute @@ -714,7 +719,7 @@ function buildApi( const homeRelative = raw === '~' || raw.startsWith('~/') || raw.startsWith('~\\') const requested = isAbsolute(raw) || homeRelative ? raw : `${cwd}${sep}${raw}` try { - return await listDirectory(await ensureWorkspacePath(cwd, requested), resolved.listLimit, exclude) + return await listDirectory(await ensureWorkspacePath(cwd, requested), resolved.listLimit, exclude, gate) } catch (error) { // Per-level failure: the batch itself stays a success (one unreadable // directory must not blank the whole tree). diff --git a/tests/editor-git-gutter.spec.tsx b/tests/editor-git-gutter.spec.tsx index 1c6517cb..7716174b 100644 --- a/tests/editor-git-gutter.spec.tsx +++ b/tests/editor-git-gutter.spec.tsx @@ -18,11 +18,11 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createElement } from 'react' +import { createElement, type ReactNode } from 'react' import { act } from 'react-dom/test-utils' import { EditorState } from '@codemirror/state' import { EditorView } from '@codemirror/view' -import type { GitStatusResult } from '../src/client/api.ts' +import type { GitStatusResult, SessionScope } from '../src/client/api.ts' const { gitStatus, gitDiffHead, gitBlame } = vi.hoisted(() => ({ gitStatus: vi.fn(), @@ -53,6 +53,7 @@ import { gitGutterExtensions, gitLineKinds, loadBlameLine, + useEditorGitGutter, type GitLineKind, } from '../src/client/editor-git-gutter.ts' import { TextEditor } from '../src/client/TextEditor.tsx' @@ -424,3 +425,119 @@ describe('TextEditor wiring (code viewer only, one switch)', () => { } }) }) + +/** + * The gutter must not OWN the shared git status poll (#212 follow-up). + * + * Opening a `code` / `jsonl` file used to subscribe the editor as a POLLING + * consumer — the feature switch was passed where the visibility flag belongs — + * so from the first opened file onward the plugin ran a full + * `git status --untracked-files=all` (plus two whole-repo `--numstat` diffs) + * every cadence for the rest of the page's life, megabytes of output at a time + * on a repository with an unignored nested `node_modules`. These cases pin the + * fix: no timer, no subscription at all while the tab is parked, and exactly + * one re-read per new question (a different file, or the same file after a + * save). + */ +describe('gutter poll ownership and visibility', () => { + /** A fresh sessionId mints a fresh status slot, so cases never share one. */ + const pollScope = (id: string): SessionScope => ({ sessionId: id, cwd: '/p' }) + + const GUTTER_PATCH = patch('a.ts', '@@ -1,2 +1,3 @@\n one\n+inserted\n two\n') + /** `a.ts` modified: enough for the gutter to engage. */ + const MODIFIED: GitStatusResult = { isRepo: true, root: '/p', entries: [{ path: 'a.ts', xy: ' M' }] } + + function viewerProps(id: string, overrides: Partial = {}): FileViewerProps { + return { + ctx: {} as FileViewerProps['ctx'], + store: createSidebarStore(), + scope: pollScope(id), + path: '/p/a.ts', + title: 'a.ts', + viewerId: 'code', + content: 'one\ntwo\nthree\n', + ...overrides, + } + } + + /** A minimal host for the hook alone, to drive `path` / `revision`. */ + function GutterProbe(props: { scope: SessionScope; path: string; revision: number }): ReactNode { + useEditorGitGutter({ + enabled: true, + visible: true, + scope: props.scope, + path: props.path, + content: 'one\ntwo\nthree\n', + revision: props.revision, + }) + return createElement('span') + } + + /** Flush the store's fetch chain inside act(). */ + async function settle(): Promise { + await act(async () => { + for (let round = 0; round < 5; round += 1) await Promise.resolve() + }) + } + + it('keeps no git status poll running for an open editor', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(MODIFIED) + gitDiffHead.mockResolvedValue({ diff: GUTTER_PATCH }) + const mounted = renderRoot(createElement(TextEditor, viewerProps('gutter-open'))) + try { + await settle() + // The one reading a `poll: false` consumer is entitled to. + expect(gitStatus).toHaveBeenCalledTimes(1) + // Two old cadences' worth of idling: nothing may ask git again. + await act(async () => { await vi.advanceTimersByTimeAsync(120_000) }) + expect(gitStatus).toHaveBeenCalledTimes(1) + } finally { + mounted.unmount() + vi.useRealTimers() + } + }) + + it('subscribes to nothing at all while the editor tab is hidden', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(MODIFIED) + gitDiffHead.mockResolvedValue({ diff: GUTTER_PATCH }) + const mounted = renderRoot(createElement(TextEditor, viewerProps('gutter-hidden', { visible: false }))) + try { + await act(async () => { await vi.advanceTimersByTimeAsync(120_000) }) + expect(gitStatus).not.toHaveBeenCalled() + expect(gitDiffHead).not.toHaveBeenCalled() + } finally { + mounted.unmount() + vi.useRealTimers() + } + }) + + it('re-reads the status once per new question, not once per render', async () => { + gitStatus.mockResolvedValue(MODIFIED) + gitDiffHead.mockResolvedValue({ diff: GUTTER_PATCH }) + const scope = pollScope('gutter-ask') + const view = (path: string, revision: number): ReactNode => + createElement(GutterProbe, { scope, path, revision }) + const mounted = renderRoot(view('/p/a.ts', 0)) + try { + await settle() + expect(gitStatus).toHaveBeenCalledTimes(1) + + // Same question (a re-render): no extra scan. + mounted.rerender(view('/p/a.ts', 0)) + await settle() + expect(gitStatus).toHaveBeenCalledTimes(1) + + // A save, then a different file: one scan each. + mounted.rerender(view('/p/a.ts', 1)) + await settle() + expect(gitStatus).toHaveBeenCalledTimes(2) + mounted.rerender(view('/p/b.ts', 1)) + await settle() + expect(gitStatus).toHaveBeenCalledTimes(3) + } finally { + mounted.unmount() + } + }) +}) diff --git a/tests/file-tree-compact-fold.spec.tsx b/tests/file-tree-compact-fold.spec.tsx index 1eadfd6b..a828a28c 100644 --- a/tests/file-tree-compact-fold.spec.tsx +++ b/tests/file-tree-compact-fold.spec.tsx @@ -19,6 +19,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 { MAX_COMPACT_DEPTH } from '../src/client/file-tree-compact.ts' import { setupReactAct } from './test-utils.ts' setupReactAct() @@ -236,6 +237,39 @@ describe('FileTree breadcrumb folding', () => { expect(harness.container.textContent).toContain('readme.md') }) + it('stops the preload at the render cap instead of requesting deeper links', async () => { + // A chain longer than a row can fold: every level is a singleton dir for + // MAX_COMPACT_DEPTH + 8 links. The breadcrumb stops folding at the cap, so + // the preload must stop asking there too — the every-loaded-level scan it + // replaced kept requesting link 33, 34, … (one serial POST plus one + // whole-tree render each) for a chain the renderer never drew. + const DEPTH = MAX_COMPACT_DEPTH + 8 + const linkAt = (index: number): string => index === 0 + ? '/tmp' + : `/tmp/${Array.from({ length: index }, (_, step) => `l${step + 1}`).join('/')}` + const depthOf = (path: string): number => path === '/tmp' ? 0 : path.split('/').length - 2 + fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({ + levels: paths.map((path) => { + const depth = depthOf(path) + return { + path, + entries: depth < DEPTH ? [dir(linkAt(depth + 1), true)] : [file(`${path}/leaf.txt`)], + truncated: false, + } + }), + })) + harness = mountTree() + // One wave per link (each arrival reveals the next frontier link); a + // generous fixed bound keeps a regression that loops on the cap from + // hanging the run — it fails on the assertion below instead. + for (let wave = 0; wave < DEPTH * 4; wave += 1) await flush() + + // The preload followed the chain all the way to the cap… + expect(Math.max(...requestedPaths().map(depthOf))).toBe(MAX_COMPACT_DEPTH) + // …and never asked for the link past it. + expect(new Set(requestedPaths()).has(linkAt(MAX_COMPACT_DEPTH + 1))).toBe(false) + }) + it('toggles the WHOLE chain on a plain click, so the row closes as one', async () => { // The head was expanded by an earlier interaction (before the fold formed): // closing the row must collapse every link, not just the head. diff --git a/tests/file-tree-compact.spec.ts b/tests/file-tree-compact.spec.ts index 30e378f4..7f6f0f34 100644 --- a/tests/file-tree-compact.spec.ts +++ b/tests/file-tree-compact.spec.ts @@ -128,7 +128,7 @@ describe('compactLoadTargets', () => { '/root/a/b': {}, } // Only marked, not-yet-loaded dirs qualify: files and plain dirs never do. - expect(compactLoadTargets(levels)).toEqual(['/root/a/c']) + expect(compactLoadTargets(levels, ['/root'])).toEqual(['/root/a/c']) }) it('skips already-loaded paths and dedupes repeat appearances', () => { @@ -138,6 +138,32 @@ describe('compactLoadTargets', () => { '/alt': { entries: [row] }, '/root/a': { entries: [] }, } - expect(compactLoadTargets(levels)).toEqual([]) + expect(compactLoadTargets(levels, ['/root'])).toEqual([]) + }) + + it('only walks from the rendered roots', () => { + // `/elsewhere` is loaded but no chain reaches it from what the tree + // renders, so its singleton child needs no preload. + const levels: Record = { + '/root': { entries: [dir('/root/plain')] }, + '/elsewhere': { entries: [dir('/elsewhere/x', true)] }, + } + expect(compactLoadTargets(levels, ['/root'])).toEqual([]) + }) + + it('stops at the render cap instead of pulling deeper links', () => { + // MAX_COMPACT_DEPTH + 1 loaded links, each one a singleton: the row's + // breadcrumb already stops folding at the cap, so the link PAST it — the + // one the deepest loaded level names — must not be preloaded. The + // every-loaded-level scan this replaced collected exactly that link, and + // with it link 34, 35, … (one serial POST and one whole-tree render each). + const levels: Record = {} + for (let index = 1; index <= MAX_COMPACT_DEPTH + 1; index += 1) { + levels[`/${'x'.repeat(index)}`] = { entries: [dir(`/${'x'.repeat(index + 1)}`, true)] } + } + // The fixture is cap-limited, not data-limited: the head's chain IS full… + expect(compactChain(dir('/x', true), path => levels[path])).toHaveLength(MAX_COMPACT_DEPTH) + // …so nothing past the cap is requested. + expect(compactLoadTargets(levels, ['/x'])).toEqual([]) }) }) diff --git a/tests/fs-tree-probe-gate.spec.ts b/tests/fs-tree-probe-gate.spec.ts new file mode 100644 index 00000000..a83932f4 --- /dev/null +++ b/tests/fs-tree-probe-gate.spec.ts @@ -0,0 +1,138 @@ +/** + * The request-wide probe budget behind `fs.trees`. + * + * One batch lists up to `FS_TREES_MAX_PATHS` levels concurrently, and each + * level runs its own bounded probe pool (a `stat` per symlink row, an + * `opendir` per directory row for the singleton fold mark). Without a shared + * budget those bounds multiply — a cold mount of a wide tree could hold + * levels × pool probes open at once. The bound itself is proved on the gate; + * these tests prove the WIRING: every probe of every level spends the one + * gate the request was given (and a cache hit spends nothing at all). The + * route's per-request gate SHARING is asserted in tests/smoke.spec.ts. + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { createProbeGate, listDirectory, type ProbeGate } from '../src/fs-tree.ts' + +/** A gate that only COUNTS acquisitions: it bounds nothing of its own, so the + * count it reports is exactly the probes the caller routed through it. */ +function countingGate(): { gate: ProbeGate; calls: () => number } { + const state = { calls: 0 } + return { + gate: { + async run(task: () => Promise): Promise { + state.calls += 1 + return await task() + }, + }, + calls: () => state.calls, + } +} + +describe('createProbeGate', () => { + it('keeps at most `limit` tasks in flight', async () => { + const gate = createProbeGate(2) + let live = 0 + let peak = 0 + await Promise.all(Array.from({ length: 8 }, () => gate.run(async () => { + live += 1 + peak = Math.max(peak, live) + await new Promise(resolve => setTimeout(resolve, 1)) + live -= 1 + }))) + expect(peak).toBe(2) + expect(live).toBe(0) + }) + + it('releases the slot when a queued task throws, in FIFO order', async () => { + const gate = createProbeGate(1) + const order: string[] = [] + const first = gate.run(async () => { + await new Promise(resolve => setTimeout(resolve, 1)) + order.push('first') + }) + const failing = gate.run(async () => { + order.push('failing') + throw new Error('probe failed') + }) + const last = gate.run(async () => { + order.push('last') + return 'ok' + }) + await first + await expect(failing).rejects.toThrow('probe failed') + // A thrown probe must not strand the waiter behind it. + await expect(last).resolves.toBe('ok') + expect(order).toEqual(['first', 'failing', 'last']) + }) + + it('clamps a limit below one so the gate still runs', async () => { + const gate = createProbeGate(0) + const settled = await Promise.race([ + gate.run(async () => 'ok'), + new Promise(resolve => { setTimeout(() => { resolve('timed out') }, 100) }), + ]) + expect(settled).toBe('ok') + }) +}) + +describe('listDirectory probe budget', () => { + it('spends one gate slot per directory probe, and none on a cache hit', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-probe-gate-')) + try { + // Four singleton dirs (one child each) plus one ordinary dir: every + // directory row costs exactly one compact probe. + for (let index = 0; index < 4; index += 1) { + mkdirSync(join(dir, `only-${index}`)) + writeFileSync(join(dir, `only-${index}`, 'child.txt'), 'x') + } + mkdirSync(join(dir, 'plain')) + writeFileSync(join(dir, 'plain', 'a.txt'), 'x') + writeFileSync(join(dir, 'plain', 'b.txt'), 'x') + + const counted = countingGate() + const listing = await listDirectory(dir, 1000, undefined, counted.gate) + expect(counted.calls()).toBe(5) + expect(listing.entries.filter(entry => entry.compact === true).map(entry => entry.name).sort()) + .toEqual(['only-0', 'only-1', 'only-2', 'only-3']) + + // A fresh call is answered from the level cache, which runs no probe at + // all — so it must not spend budget either. + const spent = counted.calls() + const cached = await listDirectory(dir, 1000, undefined, counted.gate) + expect(counted.calls()).toBe(spent) + expect(cached).toBe(listing) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('routes a whole batch of levels through ONE shared gate', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-probe-batch-')) + try { + const levels: string[] = [] + for (let index = 0; index < 3; index += 1) { + const level = join(root, `l${index}`) + mkdirSync(level) + for (let child = 0; child < 3; child += 1) { + mkdirSync(join(level, `s${child}`)) + writeFileSync(join(level, `s${child}`, 'child.txt'), 'x') + } + levels.push(level) + } + + const counted = countingGate() + // Exactly the shape the `fs.trees` route builds: one gate, many levels. + const listings = await Promise.all(levels.map(level => listDirectory(level, 1000, undefined, counted.gate))) + // 3 levels × 3 directory rows: every probe went through the shared gate. + expect(counted.calls()).toBe(9) + for (const listing of listings) { + expect(listing.entries.filter(entry => entry.compact === true)).toHaveLength(3) + } + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/git-status-poll.spec.tsx b/tests/git-status-poll.spec.tsx new file mode 100644 index 00000000..6ad8f2fa --- /dev/null +++ b/tests/git-status-poll.spec.tsx @@ -0,0 +1,248 @@ +/** + * The shared git-status store's CADENCE contract. + * + * One fetch here is `git status --untracked-files=all` plus two `--numstat` + * diffs, so an automatic poll is real work — and it used to run every 2.5 s for + * as long as any consumer was on screen, notified on every tick whether or not + * anything had changed. Four behaviours are pinned: + * + * - OWNERSHIP: only a `poll: true` consumer starts the timer. A `poll: false` + * consumer (the editor's gutter) reads the shared answer and refreshes on + * its own events, so it can never keep git running in the background. + * - ORDER: a non-polling consumer that arrives FIRST must not stop a polling + * consumer that arrives later from starting the timer. + * - SILENCE: an idle poll that returns an equal status notifies nobody — the + * version counter is the `useSyncExternalStore` snapshot, and bumping it + * re-rendered every consumer (the file tree's rows included) once per + * cadence for nothing. + * - THE LADDER: the baseline is 30 s, a slow round trip drops the slot to + * 60 s then 180 s, and a really slow one stops the automatic timer + * altogether; a fast answer climbs straight back to the baseline. + */ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createElement, useEffect, type ReactNode } from 'react' +import { act } from 'react-dom/test-utils' +import type { GitStatusResult, SessionScope } from '../src/client/api.ts' + +const { gitStatus } = vi.hoisted(() => ({ gitStatus: vi.fn() })) + +vi.mock('../src/client/api.ts', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, api: { ...actual.api, gitStatus } } +}) + +import { renderRoot, setupReactAct } from './test-utils.ts' +import { useGitStatus, type GitStatusView } from '../src/client/ui/git-status.ts' + +setupReactAct() + +const REPO: GitStatusResult = { + isRepo: true, + root: '/tmp', + entries: [{ path: 'a.ts', xy: ' M' }], +} + +/** The scope of one test; a fresh sessionId mints a fresh slot. */ +const scopeFor = (id: string): SessionScope => ({ sessionId: id, cwd: '/tmp' }) + +/** Commits observed for the probe component (not renders — see Probe). */ +interface Counter { value: number } + +/** The view the probe most recently received, for the event-driven cases. */ +let latest: GitStatusView | null = null + +function Probe(props: { scope: SessionScope; poll?: boolean; visible?: boolean; commits: Counter }): ReactNode { + const view = useGitStatus(props.scope, { poll: props.poll, visible: props.visible }) + // One per COMMIT: the store's only observable is the version counter behind + // `useSyncExternalStore`, so a commit is exactly "the store notified". + useEffect(() => { props.commits.value += 1 }) + latest = view + return createElement('span') +} + +/** Let the store's in-flight fetch settle (inside act — it notifies React). */ +async function flush(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + }) +} + +/** Advance the fake clock, letting the store's promises settle inside act. */ +async function tick(ms: number): Promise { + await act(async () => { await vi.advanceTimersByTimeAsync(ms) }) +} + +let mounted: ReturnType | null = null +afterEach(() => { + mounted?.unmount() + mounted = null + latest = null + gitStatus.mockReset() + vi.useRealTimers() +}) + +describe('the shared git status store cadence', () => { + it('never starts a timer for a poll:false consumer', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + const commits: Counter = { value: 0 } + mounted = renderRoot(createElement(Probe, { scope: scopeFor('poll-off'), poll: false, commits })) + await tick(0) + await flush() + // The one reading a non-polling consumer is entitled to. + expect(gitStatus).toHaveBeenCalledTimes(1) + await tick(120_000) + expect(gitStatus).toHaveBeenCalledTimes(1) + }) + + it('polls a poll:true consumer on the 30 s baseline', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + const commits: Counter = { value: 0 } + mounted = renderRoot(createElement(Probe, { scope: scopeFor('poll-on'), commits })) + await tick(0) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(1) + // Still inside the first interval: the old 2.5 s cadence would already + // have fired ten times here. + await tick(29_000) + expect(gitStatus).toHaveBeenCalledTimes(1) + await tick(2_000) + expect(gitStatus).toHaveBeenCalledTimes(2) + }) + + it('starts the timer even when the non-polling consumer arrived first', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + const commits: Counter = { value: 0 } + const scope = scopeFor('mixed-order') + // Both mount in one commit; effects run in tree order, so the non-polling + // consumer retains the slot first. + const tree = (withPolling: boolean): ReactNode => createElement('div', null, + createElement(Probe, { scope, poll: false, commits }), + withPolling ? createElement(Probe, { scope, poll: true, commits }) : null, + ) + mounted = renderRoot(tree(true)) + await tick(0) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(1) + + // The polling consumer owns the timer... + await tick(31_000) + expect(gitStatus).toHaveBeenCalledTimes(2) + + // ...and when it leaves, the timer goes with it while the non-polling one + // keeps its answer. + mounted.rerender(tree(false)) + await flush() + const afterLeave = gitStatus.mock.calls.length + await tick(120_000) + expect(gitStatus).toHaveBeenCalledTimes(afterLeave) + expect(latest?.snapshot).not.toBeNull() + }) + + it('stays silent when an idle poll returns the same status', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + const commits: Counter = { value: 0 } + mounted = renderRoot(createElement(Probe, { scope: scopeFor('idle-silent'), commits })) + await tick(0) + await flush() + const settled = commits.value + expect(settled).toBeGreaterThan(0) + + // One full cadence: the poll runs (a NEW object every time), the status is + // equal, so no consumer may be told anything. Without the guard this bumps + // the version and the probe commits again. + await tick(30_000) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(2) + expect(commits.value).toBe(settled) + + // A real change still lands. + gitStatus.mockResolvedValue({ ...REPO, entries: [{ path: 'a.ts', xy: ' M' }, { path: 'b.ts', xy: '??' }] }) + await tick(30_000) + await flush() + expect(commits.value).toBeGreaterThan(settled) + }) + + it('drops to 60 s when a round trip is slow, and climbs back when it is fast', async () => { + vi.useFakeTimers() + gitStatus.mockImplementation(() => new Promise((resolve) => { + setTimeout(() => { resolve(REPO) }, 1_000) + })) + const commits: Counter = { value: 0 } + mounted = renderRoot(createElement(Probe, { scope: scopeFor('ladder-down'), commits })) + // The first answer takes 1 s of (fake) wall clock: tier 1, i.e. 2x. + await tick(1_000) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(1) + + // Past the OLD cadence and past the baseline, but inside 60 s: no tick. + await tick(30_000) + expect(gitStatus).toHaveBeenCalledTimes(1) + // Past 60 s from the moment the slow answer landed: one tick. + await tick(31_000) + expect(gitStatus).toHaveBeenCalledTimes(2) + + // A fast answer now resets the ladder to the baseline. + gitStatus.mockResolvedValue(REPO) + // t=122s: the deferred 60 s tick lands and comes back instantly. + await tick(60_000) + await flush() + const recovered = gitStatus.mock.calls.length + expect(recovered).toBeGreaterThan(2) + // Inside a 30 s window: nothing yet... + await tick(20_000) + expect(gitStatus).toHaveBeenCalledTimes(recovered) + // ...but 40 s on, the baseline cadence must have fired (a 60 s one would + // still be waiting, which is what makes this the ladder-down check). + await tick(20_000) + expect(gitStatus).toHaveBeenCalledTimes(recovered + 1) + }) + + it('stops the automatic timer after a very slow round trip, until an event refreshes', async () => { + vi.useFakeTimers() + gitStatus.mockImplementation(() => new Promise((resolve) => { + setTimeout(() => { resolve(REPO) }, 6_000) + })) + const commits: Counter = { value: 0 } + mounted = renderRoot(createElement(Probe, { scope: scopeFor('ladder-stop'), commits })) + await tick(6_000) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(1) + + // Tier 3: no timer at all, so ten minutes of idling cost nothing. + await tick(600_000) + expect(gitStatus).toHaveBeenCalledTimes(1) + + // An event-driven refresh still runs — and a fast answer restores polling. + gitStatus.mockResolvedValue(REPO) + await tick(1_000) + await act(async () => { latest?.refresh() }) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(2) + await tick(30_000) + expect(gitStatus).toHaveBeenCalledTimes(3) + }) + + it('does not fetch at all for a hidden consumer, and starts when it shows', async () => { + vi.useFakeTimers() + gitStatus.mockResolvedValue(REPO) + const commits: Counter = { value: 0 } + const scope = scopeFor('visibility') + mounted = renderRoot(createElement(Probe, { scope, visible: false, commits })) + await tick(0) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(0) + await tick(120_000) + expect(gitStatus).toHaveBeenCalledTimes(0) + + mounted.rerender(createElement(Probe, { scope, visible: true, commits })) + await tick(0) + await flush() + expect(gitStatus).toHaveBeenCalledTimes(1) + }) +}) diff --git a/tests/git-view-worktree.spec.tsx b/tests/git-view-worktree.spec.tsx index ee5bd593..5b633a6d 100644 --- a/tests/git-view-worktree.spec.tsx +++ b/tests/git-view-worktree.spec.tsx @@ -814,7 +814,10 @@ describe('GitLens (changes tab, git lens) change tree', () => { await flushEffects() expect(counted(container, '[data-path="src/a.ts"] [data-lines="count"]').added).toBe('1') - await act(async () => { await vi.advanceTimersByTimeAsync(2_600) }) + // Past the store's automatic cadence (a 30 s baseline; see + // docs/plans/2026-10-13-git-poll-ladder-and-idle-notify.md) — that + // tick is what makes the second answer arrive at all. + await act(async () => { await vi.advanceTimersByTimeAsync(31_000) }) await flushEffects() // Both caches had to notice: the store's field-by-field snapshot // compare AND the lens's content key. Either one ignoring the counts diff --git a/tests/git-worktree.spec.ts b/tests/git-worktree.spec.ts index 7a5e91f6..d51e3505 100644 --- a/tests/git-worktree.spec.ts +++ b/tests/git-worktree.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { spawnSync } from 'node:child_process' -import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' import { parseWorktreeList, resolveWorktree, status, worktrees } from '../src/git.ts' @@ -100,4 +100,36 @@ describe('linked Git worktrees', () => { rmSync(root, { recursive: true, force: true }) } }) + + it('counts an untracked directory as ONE entry in the inventory', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-worktree-count-')) + const main = join(root, 'main') + try { + git(root, ['init', '-q', main]) + git(main, ['checkout', '-q', '-b', 'main']) + writeFileSync(join(main, 'tracked.txt'), 'base\n') + git(main, ['add', '-A']) + git(main, ['commit', '-q', '-m', 'base']) + // A large untracked tree. The inventory used to answer this by calling + // the full `status()` — FOUR processes per linked checkout, including the + // `--untracked-files=all` walk — on a 30 s poll, only to read + // `.entries.length`. "Does this checkout have changes" is the question, + // and one directory row is its answer: cheaper, and not silently capped + // at GIT_STATUS_LIMIT the way the expanded count was. + mkdirSync(join(main, 'vendor/nested'), { recursive: true }) + for (let index = 0; index < 50; index += 1) { + writeFileSync(join(main, `vendor/nested/f${index}.txt`), 'x\n') + } + + const listed = await worktrees(main) + expect(listed).toHaveLength(1) + expect(listed[0]!.changes).toBe(1) + + // The per-file answer is untouched: the tree's ink and the changes page + // still expand the same tree file by file. + expect((await status(main)).entries).toHaveLength(50) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) }) diff --git a/tests/smoke.spec.ts b/tests/smoke.spec.ts index a1014557..74655e10 100644 --- a/tests/smoke.spec.ts +++ b/tests/smoke.spec.ts @@ -3,7 +3,7 @@ * exercises the real integrations — route registration, git against the * actual repository, and a real directory listing. Runs with `pnpm test`. */ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { spawnSync } from 'node:child_process' import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir, homedir } from 'node:os' @@ -18,6 +18,25 @@ import * as git from '../src/git.ts' import { listDirectory } from '../src/fs-tree.ts' import type { SidebarLoaderEntry, SidebarWebRoute, SidebarWebUpgradeRoute } from '../src/context-types.ts' +/** + * The probe-budget factory is spied on so a batch's gate SHARING is asserted + * rather than assumed: `fs.trees` lists many levels at once and must build ONE + * gate per request, or the per-level probe bounds multiply. Everything else + * about the module stays real, so this file's own `listDirectory` calls (and + * every other route) behave exactly as before. + */ +const probeGateCalls = vi.hoisted(() => [] as unknown[][]) +vi.mock('../src/fs-tree.ts', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + createProbeGate: (...args: Parameters) => { + probeGateCalls.push(args) + return actual.createProbeGate(...args) + }, + } +}) + /** Symlink creation may require elevated privileges on Windows. */ const canCreateSymlink = (() => { const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-security-probe-')) @@ -1159,6 +1178,34 @@ describe('session cwd resolution over the API route', () => { } }) + it('fs.trees shares ONE probe gate across the batch levels', async () => { + const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-trees-gate-')) + const workspace = join(root, 'workspace') + const level = join(workspace, 'level') + mkdirSync(level, { recursive: true }) + for (let index = 0; index < 3; index += 1) { + mkdirSync(join(level, `only-${index}`)) + writeFileSync(join(level, `only-${index}`, 'child.txt'), 'x') + } + try { + const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } }) + const before = probeGateCalls.length + const answer = await invoke(route, 'fs.trees', { sessionId: 's-tree-gate', paths: [workspace, level] }) + expect(answer.ok).toBe(true) + // ONE gate for the whole request: a per-level gate would let each level's + // probe pool run at full width, which is the runaway this bounds. + expect(probeGateCalls.length - before).toBe(1) + // The shared budget changed nothing about what the levels report. (The + // local `invoke` types `value` as its cwd probe, hence the double cast.) + const levels = (answer.value as unknown as { + levels: { path: string; entries: { compact?: boolean }[] }[] + }).levels + expect(levels.find(entry => entry.path === level)?.entries.filter(row => row.compact === true)).toHaveLength(3) + } finally { + rmSync(root, { recursive: true, force: true }) + } + }) + it.skipIf(!canCreateSymlink)('lists a workspace symlink that resolves outside the workspace', async () => { const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-symlink-security-')) const workspace = join(root, 'workspace') diff --git a/vitest.config.ts b/vitest.config.ts index f0fa18da..7a80ecc0 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -50,6 +50,11 @@ export default defineConfig({ // Local dev worktrees (pnpm/DSH-style task branches) may carry stale // code against this checkout's node_modules — never collect them. '**/.worktrees/**', + // Same hazard, different directory: the DSH worktree lanes keep their + // checkouts under `.delta/`, which `.git/info/exclude` ignores but this + // list is the only thing vitest reads. Left out, `pnpm test` collects + // those stale copies and reports THEIR failures as ours. + '**/.delta/**', '**/node_modules/**', '**/dist/**', '**/cypress/**',