diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e220ad2..c2c4c976 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ ### 未发布 - **右栏展开时仍可开关底部工作台**:会话头的底部工作台开关此前在宿主右侧面板展开时整枚隐藏,导致「先开右栏就再也打不开工作台」,必须先收起右栏。现在照常显示(它在会话头 utilities,与右栏那簇控件分属两列,不会重叠)。空白会话的 fixed 兜底入口保持原行为:那个入口锚在右栏控件左侧,展开时锚点落在面板内部。`tests/bottom-toggle.spec.tsx` 守护。 +- ⚡ **卡顿扫描与一轮低风险收敛**(前端页面 + 宿主 `/sidebar/*` 请求;逐条取证与误报核实见[扫描记录](docs/plans/2026-10-24-perf-scan.md)): + - **文件树在隐藏页签里不再干活**:宿主把访问过的页签 body 常驻挂载,此前每个隐藏的文件树仍会在窗口获得焦点、刷新 tick 或另一个树展开目录时发 `fs.trees` 并重渲染整棵树;现在停靠树在隐藏时不加载(含折叠链预加载:隐藏后才返回的在飞层不会再拉下一节)、不监听焦点刷新,重新可见时由目录 watcher 对整套被 watch 的目录发一次批量 `fs.trees`(此前是每目录一次 POST;隐藏期间恰好没有缓存且展开集身份同时变化时最多两批,超过宿主 64 条路径上限仍按上限拆批)。 + - **任务图滚轮缩放改为每帧一次提交**:高回报率滚轮/触控板此前每个 wheel 事件都重绘整张图,且每帧只保住一步缩放;现在与平移共用 `frame batcher`,同一帧的缩放量按步夹紧后完整复合、只提交一次(与逐帧应用等价);背景拖拽期间滚轮让位给拖拽,避免两种手势互相覆盖。 + - **侧聊打字与流式输出不再重扫整段转录**:用户/助手行的本地图片与链接改写按**行对象**缓存(未变化的行在既有 `sidechat-transcript` 里本就是同一对象),输入框每键与每次流式 push 只重算变化的行。 + - **Git diff 只解析一次 + 默认展开有预算**:变动页此前对同一份 patch 在 header 统计与文件行里各解析一遍(≤8MB 在 UI 线程跑两次),现在共用一份解析;默认展开按「变更行预算 2000」封顶,大 commit 不再一次挂载数千行(首屏仍有内容,其余文件一键展开)。 + - **提交图历史行只挂载视口窗口**:`data-graph-count` 仍报整页条数,DOM 只保留视口 ± 8 行,上下留白维持真实滚动条与「加载更多」哨兵位置;深历史滚动/追加不再线性增长。 + - **宿主侧两处常驻成本**:`/sidebar/bundle/*.js` 的 `HEAD` 不再为响应体 `readFile`(ETag 冷路径仍读一次算内容 hash,memo 命中后不读;客户端每次 HEAD 都在 GET 之后,因此实际是热命中);`active-worktree` 在 15s TTL 到期、会话事件游标(`session.seq`)未动**且已解析到 git 顶层**时直接续期,不再重复快照/扫描最多 4000 条事件(实测 miss 9.6–44.7ms,空闲的 5s 轮询每到第三个就踩中);非仓库/探测失败仍按 15s 重探,父目录后来 `git init` 或探测暂时失败都能恢复。 + - 🧪 测试:`tests/tasks-page.spec.tsx`(同帧 5 次滚轮只提交一次且缩放量等于合计;同帧复合与逐帧应用等价;拖拽期间滚轮被忽略)、`tests/file-tree-dir-watch.spec.tsx`(re-arm 单次批量回调)、`tests/file-tree-batch-load.spec.tsx`(隐藏零请求、回屏恰一次批量、折叠链在隐藏后才返回时不继续预加载且回屏后接续)、`tests/editor-host.spec.tsx`(隐藏树对窗口焦点零提交、回屏一次批量)、`tests/sidechat-markdown-labels.spec.tsx`(输入框连敲两键:未变化行改写 0 次)、`tests/diff-files-collapse.spec.tsx`(默认展开按行预算 + 复用调用方解析)、`tests/git-graph-windowing.spec.ts` + `tests/git-graph-ui.spec.tsx`(窗口/留白/滚动跟随/页替换夹紧;隐藏时不留视口观察者)、`tests/bundle-route.spec.ts`(HEAD 无 body)、`tests/active-worktree.spec.ts`(游标未动不重扫、游标推进重扫、非仓库/失败仍按 TTL 重探、无游标宿主回退旧语义)。每条都在旧代码上先复现失败(见扫描记录 §3 与 §7)。 - **任务图展开修复**:平移画布后,聚合卡和 Agent 卡的下一次点击不再被误判为拖动;展开聚合与查看详情恢复正常。 - **任务图性能**:卡片内容使用独立 memo 边界,平移与布局补间不再重复渲染内容;布局用索引和显式栈替代逐边查找与深递归,同次宽度适配复用相同列数的布局。2000 个非根 Agent 的纯布局对照及 200/500 Agent 真浏览器证据见[验证记录](docs/plans/2026-10-23-tasks-folding-performance-validation.md),布局加速不外推为整页加速。 - **任务页拖拽改为每帧一次更新**:图模式背景平移、后台任务浮窗标题拖动、锚定弹层拖动不再按鼠标事件频率重绘(高回报率鼠标下此前每个 pointermove 都提交整块画布);松手同步落位,点击判定与最终位置不变。实测同一帧内 100 次移动的画布提交由 98 次降到 1 次。 diff --git a/docs/plans/2026-10-24-perf-scan.md b/docs/plans/2026-10-24-perf-scan.md new file mode 100644 index 00000000..880f76d9 --- /dev/null +++ b/docs/plans/2026-10-24-perf-scan.md @@ -0,0 +1,143 @@ +# 侧栏卡顿扫描与低风险优化(前端页面 + 宿主请求) + +**日期**:2026-10-24 +**分支**:`fix/perf-scan`(从 `dev` 切出,未 push、未合并 `dev`) +**状态**:已实施,门禁见 §6 +**范围**:用户要求扫描 BSB 前端页面与后端 `/sidebar/*` 请求里可能造成卡顿的位置并优化,允许在「工作量不太大」处引入虚拟化。沿用既有 KISS / 稳态约束:不改 DSH 源码、不碰用户 profile、不关闭 `keepMounted`、不给 perf lane 加耗时阈值。 + +--- + +## 1. 扫描方法与结论 + +只读扫描三条线:客户端渲染/轮询与事件路径、宿主路由/子进程/IO、既有 perf 计划与仓库契约(`AGENTS.md` §5、`docs/plans/2026-10-15-perf-steady-state.md`、`2026-10-13-*`)。每条发现都落到代码行并对触发条件取证;**误报单独核实后剔除**(见 §1.2)。 + +### 1.1 确认并修复 + +| # | 位置(改动前) | 现象 | 修复 | +|---|---|---|---| +| A1 | `src/client/TasksGraph.tsx:365-386` | 每个 `wheel` 事件直接 `setTf` 重绘整张图;同文件的平移已走 frame batcher,滚轮没有。且每个事件都从渲染前的 `tfRef` 起算,同帧多事件只保住一步缩放。 | 滚轮与平移共用 `createFrameBatcher`;缩放量在 `pendingWheelRef` 里**逐步夹紧后链式复合**,每帧提交一次;背景拖拽期间滚轮让位。 | +| A2 | `FileTree.tsx:1001-1010`、`:978-986`、`:1012-1043`;`use-dir-watch.ts:180-186`;`TreePanel.tsx:121-129` | keepMounted 下隐藏的文件树照样响应 refresh tick / 窗口焦点 / 共享 expanded 变化发 `fs.trees`;可见时发出的折叠链预加载在 park 后返回仍会继续拉下一层;重新可见时 watcher 对**每个**被 watch 目录各发一次 `fs.trees`(最多 64 个 POST + 64 次全树重渲染)。 | 隐藏树不加载(`loadLevels` 单一入口 + 两个 effect 门控,覆盖折叠链预加载与丢弃应答的自愈重试)、不吃刷新 tick;停靠面板隐藏时不注册窗口焦点监听;watcher 的 re-arm 改为**一次回调带全套目录**,树侧一次批量 `loadLevels`。 | +| A3 | `SideChatView.tsx:502,512,1364`、`:704` | 每次 render 对每行跑 `surface.rewrite`(图片 + 本地链接两趟正则);输入框 state 就在同一组件,每键 / 每 80–250ms 流式 push 都扫整段转录。 | 行级改写按**行对象**缓存(未变化行在 `sidechat-transcript` 里本就复用对象),输入/cwd/transport base 变化即换缓存。 | +| A4 | `DiffPane.tsx:433-444` + `DiffFiles.tsx:65-66,93-99` | 同一份 patch 被解析两次(header 统计 + 文件行),≤8MB 在 UI 线程跑两遍;`defaultExpandedFiles` 默认展开**所有** source 文件,大 commit 一次挂载数千行。 | 变动页只解析一次并把结果传给 `DiffFiles`;默认展开按 2000 变更行预算封顶(首个 source 文件始终展开,其余一键展开)。 | +| A5 | `GitGraphSection.tsx:281-304` | 无限滚动把所有历史页 append 进 `page.entries` 并全量渲染(每行一个 SVG);上限 10000 行。 | 固定 28px 行高窗口化:只挂载视口 ± 8 行,上下留白维持真实滚动条与 sentinel;纯函数 `windowedRange` 负责夹紧(页替换后 stale scrollTop 不会映射到越界窗口);视口观察者只在可见时持有。 | +| B1 | `bundle-route.ts:92-113` + `chunk-loader.ts:221-233,327-335` | 客户端在每次懒加载后、以及侧栏每次重激活时对已加载 chunk 各发一次 HEAD,只为读 ETag;路由 HEAD 会 `readFile` 整个 chunk(最多约 11MB)。 | HEAD 不再为响应体 `readFile`(响应只回头部;ETag 冷路径仍读一次算内容 hash,之后按 mtime/size memo);GET/304/白名单/fence 不变。 | +| B2 | `active-worktree.ts:380-385`、`:121-137` | 15s TTL 到期即 `snapshotEvents()` + 扫最多 4000 事件(注释实测 miss 9.6–44.7ms),即使 `session.seq` 一条事件都没动;客户端 5s 轮询每到第三个就踩中。 | 缓存项记录解析时的 `eventSeq` 与「是否解析到 git 顶层」;到期、游标未动**且是正向解析** → 只续 TTL 返回。负向/失败答案、游标推进或宿主不暴露 `seq` 时保持原重扫语义(15s 跟随上界不变)。 | + +### 1.2 核实为误报 / 已修(未改) + +- `SessionLens` 的 `new Blob().size`:已在 `ops` 身份上 `useMemo`(`SessionLens.tsx:50-58`),不是每行每 render。 +- `sidechat.events` 的 `live`:已按 `afterSeq/tailSeq` 增量(`sidechat-routes.ts:866-883`),不是每次推送重发整段 attempt。 +- `useGitStatus`:单 store、30s 阶梯、空闲不 notify 已到位;文件树与 GitLens 主 checkout 共享同一 key。 +- 拖拽/缩放/平移、终端、归档/上传/下载、`fs.watch`、推送 socket 均已核过(与 2026-10-15 记录一致)。 + +--- + +## 2. 改动与边界 + +### A1 任务图滚轮合帧(`src/client/TasksGraph.tsx`) +- 新增 `wheelBatcher` 与 `pendingWheelRef`;事件里以 `pending ?? tfRef` 为基准,先算出新的 `{x,y,k}` 再 `schedule(flush)`;**每一步都先 `clampTf` 再写回 pending**(只夹最终值会在中间步触界时改变落点),flush 后 `setTf(pending)`。 +- 背景拖拽期间(pointerdown→release)滚轮直接早退:两种手势都提交整份 transform,互不复合,由拖拽独占。 +- `preventDefault` / `stopGlide` / `touchedRef` 仍逐事件;与 pan 共用一个 dispose effect。 +- 边界:同帧多次缩放与逐帧应用等价(有专门用例);达到 `ZOOM_MAX` 后的事件按原逻辑早退。 + +### A2 停靠文件树零工作 + 单批回屏(`FileTree.tsx`、`use-dir-watch.ts`、`TreePanel.tsx`) +- `use-dir-watch.onStale` 签名改为 `(dirs: readonly string[]) => void`:socket 通知传 `[dir]`,re-arm 传整套目录(内部 hook 契约,非 `service.ts` 公共 API)。 +- `FileTree` 用 `visibleRef` 门控加载 effect 与 refresh tick(**不把 `visible` 放进依赖**:回屏刷新统一由 watcher 的 re-arm 负责,避免两条路径各发一批);`retryDirs` 一次 `loadLevels([...dirs], {force:true})`。 +- `TreePanel` 的 `window.focus` / `dsh-sidebar:refresh-files` 监听只在可见时注册。 +- `loadLevels` 入口再加一道 `visibleRef` 守卫:可见时发出的折叠链预加载在 park 后才返回、或丢弃应答的自愈重试,都不能在隐藏时继续发请求;回屏的 re-arm 在 `visible` 已为 true 的同一提交里运行,不受影响。折叠链预加载 effect 自身也跳过隐藏态(省掉走树)。 +- 边界/已知限制:隐藏树**没有缓存**、且同一个 commit 里 expanded 数组身份也变了时,加载 effect 与 re-arm 会各发一次(2 次,不再是最多 64 次);正常回屏(数组身份稳定)是恰好 1 次。 + +### A3 侧聊逐行 rewrite 缓存(`src/client/SideChatView.tsx`) +- `RowSurface.rewrite` 改为接收散文行(`Extract`);`WeakMap` 缓存,输入变化为 `sessionId` / `cwd` / transport base(`hostTransportBase()`);行内 `text` 兜底比对防原地变更。 +- 流式行每次是新对象 → 只重算该行;pending/echo 仍走原路径。 + +### A4 diff 单次解析 + 展开预算(`src/client/diff/DiffFiles.tsx`、`src/client/changes/DiffPane.tsx`) +- `DiffFilesProps.parsed?: ParsedDiff`(untracked 合成文件时忽略);`DiffPane` 的 header stats 与文件行共用同一解析结果。 +- `DEFAULT_EXPANDED_LINE_BUDGET = 2_000`:按 hunk 行数累计,超预算的文件默认折叠(header 的 +/− 仍在);第一个 source 文件无上限;`DiffRows` 的每文件 600 行上限不变。 + +### A5 提交图历史窗口化(新 `src/client/changes/git-graph-windowing.ts` + `GitGraphSection.tsx`) +- 纯函数 `windowedRange`:`rowsInView = ceil(viewport/28)`、`visible = rowsInView + overscan*2`、`start` 夹到 `[0,count-1]`、`end = min(count, start+visible)`;上下留白 = 两侧未挂载行 × 28。 +- 组件:`scroll` 事件经 frame batcher 合帧读取 `scrollTop/clientHeight`(每帧最多一次 layout 读),`ResizeObserver` 跟随面板高度变化(**只在 `visible` 时持有**,隐藏即断开并取消待帧,回屏重新测量),`useLayoutEffect` 在页长度变化后重读(浏览器夹紧 stale scrollTop 发生在 DOM 提交之后)。 +- `data-graph-count` 报整页条数(e2e 用它替代数 DOM 行);`data-graph-scroll` / `data-graph-spacer` 是测试与 e2e 的稳定选择器;滚动时关闭 hover 卡(锚点行可能被卸载)。 +- 已知代价(标准虚拟化):窗口外的行不挂载 → 浏览器 Ctrl+F / Tab 顺序只覆盖窗口 ± overscan;每行仍有稳定 key(`hashFull`)。 + +### B1 bundle HEAD(`src/bundle-route.ts`) +- `etagOf` 返回 `{etag,size}`(复用同一 stat);HEAD 在 403/405/404/304 判定后写 200 + 四个头并 `end()`,**不再为响应体 `readFile`**。 +- 口径订正:ETag 是内容 hash,**冷路径(首次/文件变化)仍会读一次文件算 hash**,之后按 mtime/size memo 命中不读。客户端的 HEAD 都发生在其 GET 之后,所以实际路径是热命中;`Spec`/`CHANGELOG` 的措辞已按此收窄。 +- GET 行为逐字不变(含 ETag 304);HEAD 也遵循 If-None-Match → 304。 + +### B2 active-worktree 事件尾守卫(`src/active-worktree.ts`) +- 缓存项新增 `eventSeq`(解析开始前读取,解析中若有新事件则存的是旧游标 → 下次到期保守重扫)与 `gitResolved`(本次 base 探测是否真的解析到 git 顶层)。 +- 到期且 `cached.gitResolved && liveSeq !== undefined && cached.eventSeq === liveSeq` → 续 `expires` 后直接返回;否则走原解析。 +- 语义:15s 跟随上界不变(新事件只会在到期后的下一次询问被看到);无 `seq` 的宿主/分离会话保持旧行为。**非仓库/探测失败不续期**:父目录后来 `git init`、网络盘/权限导致的暂时失败都在下一次 TTL 到期时重探(缓存 `gitResolved=false`)。 + +--- + +## 3. 判别性证据(先红后绿) + +每条新用例都先在未改源码上跑过一次并确认失败: + +| 变更 | 用例 | 旧代码的失败 | +|---|---|---| +| A1 | `tests/tasks-page.spec.tsx` 同帧 5 次 wheel | 帧前已提交(`scale(1.0141)`),断言 "no commit before the frame" 失败 | +| A2 | `tests/file-tree-batch-load.spec.tsx` parked tree | 隐藏挂载仍发 1 次 `fs.trees`;回屏后断言恰 1 次失败 | +| A2 | `tests/file-tree-dir-watch.spec.tsx` re-arm | 逐目录 3 次回调(期望 1 次数组) | +| A2 | `tests/editor-host.spec.tsx` parked focus | 撤掉 TreePanel 门控后焦点事件提交 2 次(期望 0;请求断言被 FileTree 门控遮住,故用 Profiler 计提交数) | +| A3 | `tests/sidechat-markdown-labels.spec.tsx` 连敲两键 | 未变化行改写 6 次(期望 0) | +| A4 | `tests/diff-files-collapse.spec.tsx` | 6 个 source 全展开(headers 全 true);`parsed` seam 渲染 0 个文件头 | +| A5 | `tests/git-graph-ui.spec.tsx` 200 行 | 挂载 200 行(期望 17);`windowedRange` 单测 7 例 | +| B1 | `tests/bundle-route.spec.ts` HEAD | 无 `content-length`(undefined),body 被读入 | +| B2 | `tests/active-worktree.spec.ts` 空闲 TTL | 游标未动仍 `scans()===2`(期望 1) | +| A1 | `tests/tasks-page.spec.tsx` 同帧复合 vs 逐帧 | 只夹最终值:同帧 `x=72`,逐帧 `x≈7.9` | +| A1 | `tests/tasks-page.spec.tsx` 拖拽期间滚轮 | 不加守卫时滚轮提交改变了 transform | +| A2 | `tests/file-tree-batch-load.spec.tsx` 折叠链在 park 后返回 | 隐藏树继续请求下一节 `/tmp/b` | +| A5 | `tests/git-graph-ui.spec.tsx` 隐藏时的视口观察者 | `visible=false` 仍创建 1 个 ResizeObserver | +| B2 | `tests/active-worktree.spec.ts` 非仓库 base 过 TTL | 无限续期,`probed` 为空(期望重探 1 次) | + +--- + +## 4. 明确不做(与理由) + +- **文件树虚拟化**:`renderLevel` 递归渲染,行模型还带 fold chain、内联重命名、per-level error/truncated、拖放目标与 reveal 滚动;改成扁平 row model 是对 2462 行组件的重写,超出「工作量不太大」,需单独立项(本轮只做「隐藏不干活 + 回屏单批」,这是当前最频繁的浪费)。 +- **侧聊 transcript 虚拟化**:行高可变(markdown/工具卡)、贴底流式与锚点跳转耦合,需要测量缓存 + 滚动锚定,属高风险大改。 +- `usePolling` / 两个 socket hook 接 `document.visibilityState`:后台标签由浏览器节流,收益在 CPU/电池而非可感知卡顿,且会改全局轮询语义。 +- `fs.trees` 请求级总行预算、`fs.read` 5MB 单次 JSON、`media/html` 缺 ETag/Range、`git status` 第 4 个进程、`git.graph` 8 个进程(可并行化但低于感知阈值)。 +- 关闭 `keepMounted`、CSS `:has`、perf lane 耗时阈值、第二个 git 轮询器。 + +--- + +## 5. 影响面 / 部署说明 + +- 新增测试选择器:`data-graph-scroll`、`data-graph-spacer`、`data-graph-count`;`tests/e2e/git-graph.e2e.ts` 的「50 行」断言改为 `data-graph-count="50"`(行窗口随视口,DOM 行数不再是页大小),并补「滚到底 → 自动翻页到 52 → 再滚到底后最老的 `Graph base` 可达」的真实滚动断言,避免只保留页大小而失去可达性证据。 +- 行为变化:隐藏/停靠文件树不再响应窗口焦点刷新(回屏补刷);大 commit 默认展开集合变小;`onStale` 内部签名变数组。 +- 当前 GUI 跑的是 profile 里的已发布插件:看效果需要 `pnpm build && pnpm pack` 后安装,本批不碰用户 profile。 +- e2e 断言已同步但**未在本机执行**(需要 build+pack+scratch profile 的 mount lane)。 + +--- + +## 6. 门禁记录(2026-10-24 本机) + +- `pnpm typecheck`:通过(0 error)。 +- `pnpm lint`:通过(0 error / 0 warning)。 +- 定向 spec(2026-10-24 首轮 19 文件 / 296 用例):**296 passed**;CR 修复后重跑其中受影响的 8 文件:**153 passed**,再跑同一 19 文件:**301 passed**。 +- `pnpm test`(全量):首轮共跑 4 次,**3 次 225 files / 2776 passed / 17 skipped(exit 0)**;1 次命中仓库已记录的既有 flake `tests/fs-watch.spec.ts > drops the level cache …`(单次写入 15s 内未收到 notice,`2026-10-23-tasks-folding-performance-validation.md:85-89` 记载基线与本批无关;该 spec 单独复跑 2/2 通过,本批未改 `src/fs-watch.ts`)。CR 修复后全量重跑:**225 files / 2781 passed / 17 skipped,exit 0**。 +- `pnpm build`:通过(tsc build + tsdown;新模块进 `lib/client.js`,mermaid chunk 7.05MB 与改前一致)。 +- **未执行**:`pnpm test:mount` / `pnpm test:windows` / perf lane / `tests/e2e/git-graph.e2e.ts`。该 e2e 的行数断言已同步为 `data-graph-count`,但需要 build+pack+scratch profile 的挂载 lane,本机未跑,因此不声称部署级证据。 +- 判别性(每条新用例在旧代码上先红):见 §3。 + +--- + +## 7. CR 后续修复(2026-10-24,gpt-6.1-sol high 审查) + +独立 CR(`git diff dev...HEAD`,含 A1–A5/B1–B2 全部 8 个提交)报 4 条 should-fix + 1 条 nit,逐条核实后修复并各自补了先红后绿用例: + +| 审查发现 | 结论 | 修复 | +|---|---|---| +| A1 只夹最终值,不等价逐帧;pan/wheel 各提交整份 transform 会互相覆盖 | 成立 | 每步 `clampTf` 后写 pending;背景拖拽期间滚轮早退;补「同帧复合 == 逐帧」与「拖拽拥有手势」两例 | +| A2 折叠链预加载 effect 无 `visible` 门控(在飞层返回后继续拉下一节) | 成立 | `loadLevels` 单一入口加守卫 + preload effect 跳过隐藏;补「park 后返回不拉下一节、回屏接续」用例 | +| A5 `ResizeObserver` 不随 `visible` 释放(违反 AGENTS 稳态规则) | 成立 | 依赖 `visible`,隐藏断开并取消待帧,回屏补测;补隐藏零观察者用例 | +| B2 无限续期也覆盖失败/非仓库答案,首次暂败后 seq 不动无法恢复 | 成立 | 缓存增加 `gitResolved`:仅正向解析续期,负向/失败保留 15s 重探;补非仓库过 TTL 重探用例 | +| B1「HEAD 只按 stat、不读 body」过强;测试只验响应为空 | 成立(措辞) | 收窄 Spec/CHANGELOG 为「响应不读 body;ETag 冷路径仍读一次算 hash,memo 命中后不读」;测试名/注释改为「不写 body」。「计数验证读盘」未做:需要给宿主路由加测试专用 read 注入 seam,收益不抵改动,留作后续 | +| CHANGELOG 回屏「只发一次」未限定 | 成立(nit) | 限定正常回屏;注明空缓存 + 展开集身份同步变化最多两批、超 64 条按上限拆批 | + +审查同时确认 A4(parsed 同源、预算/600 cap/stats 等价)、A3(行对象复用、失效键、WeakMap)与 B2 的 seq 读取时机/epoch/LRU 无回归;`data-graph-count` 替换 DOM 行数被判定为「部分弱化」,已用 §5 的 e2e 滚动断言补回可达性证据。 diff --git a/src/active-worktree.ts b/src/active-worktree.ts index 3a6ecdb2..d8b3670c 100644 --- a/src/active-worktree.ts +++ b/src/active-worktree.ts @@ -68,13 +68,24 @@ const ACTIVE_ROOT_PATH_PATTERN = /[A-Za-z]:(?:\\|\/)[^\\/\s"'\x60,;|)<>*?]+(?:[\ * route call, the client's 5 s poll are exactly what the TTL exists to keep * free. * + * `eventSeq` is the live session cursor observed when the entry was computed, + * and `gitResolved` says whether the base probe actually found a repository. + * A TTL expiry alone means only that wall time passed; when the log has not + * moved since, nothing the EVENT SCAN reads can have changed, so a resolved + * entry is re-armed instead of snapshotting the log and scanning up to 4000 + * events again (measured 9.6–44.7 ms per miss — the idle 5 s poll landed on + * one every third ask). A negative/failed base probe is NOT re-armed: `git + * init` in a parent, a transient spawn failure, or a mount coming back are + * invisible to the event log, so those keep the wall-clock re-probe. A moved + * cursor (or a host with no `seq`) also keeps the old meaning. + * * All three maps are BOUNDED: a long-lived host (and a `keepMounted` right * sidebar that keeps asking about every session it has ever shown) would * otherwise grow them forever. `pathTopCache` caches negative answers too * (`undefined` = "no git top level here"), which is what keeps a non-repo * session cheap; those entries are evictable like any other. */ -const activeWorktreeRootCache = new Map() +const activeWorktreeRootCache = new Map() const pathTopCache = new Map() const linkedWorktreeCache = new Map() @@ -378,10 +389,26 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base // (a committed working_directory change) never reuses the other // one's root. const directoryEpoch = directoryEpochOf(ctx, sessionId) + // The live cursor is O(1) (a number on the session face); it is what makes a + // TTL expiry free when nothing was appended. + const liveSeq = ctx.sessions.get(sessionId)?.seq const cached = activeWorktreeRootCache.get(sessionId) - if (cached !== undefined && cached.expires > Date.now() && cached.base === base && cached.directoryEpoch === directoryEpoch) { - cachePut(activeWorktreeRootCache, sessionId, cached, ACTIVE_ROOT_CACHE_MAX) - return cached.root + if (cached !== undefined && cached.base === base && cached.directoryEpoch === directoryEpoch) { + if (cached.expires > Date.now()) { + cachePut(activeWorktreeRootCache, sessionId, cached, ACTIVE_ROOT_CACHE_MAX) + return cached.root + } + // Expired, but the event log has not moved AND the base probe found a + // repository: nothing this resolver reads can have changed, so re-arm the + // entry. Negative/failed answers keep the wall-clock re-probe (see the + // entry doc), and so does a host with no cursor. + if (cached.gitResolved && liveSeq !== undefined && cached.eventSeq === liveSeq) { + cachePut(activeWorktreeRootCache, sessionId, { + ...cached, + expires: Date.now() + ACTIVE_ROOT_TTL_MS, + }, ACTIVE_ROOT_CACHE_MAX) + return cached.root + } } const flightKey = `${sessionId}\0${base}\0${directoryEpoch ?? ''}` const pending = activeRootInFlight.get(flightKey) @@ -402,17 +429,21 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base /** One uncached resolution (see {@link activeWorktreeRootOf}). */ async function resolveActiveWorktreeRoot(ctx: Context, sessionId: string, base: string, directoryEpoch: number | undefined): Promise { + // Read the cursor BEFORE the scan: if an event lands mid-resolution the + // stored seq is the older one, so the next expiry still sees a moved cursor + // and re-scans (conservative — never caches a cursor the scan did not see). + const eventSeq = ctx.sessions.get(sessionId)?.seq const top = await topLevelOf(base) if (top === undefined) { // "Not inside a repository" is an answer too (the base itself), and caching // it is what keeps a non-repo session from re-probing on every ask. - cachePut(activeWorktreeRootCache, sessionId, { root: base, base, directoryEpoch, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX) + cachePut(activeWorktreeRootCache, sessionId, { root: base, base, directoryEpoch, eventSeq, gitResolved: false, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX) return base } const canonicalTop = requireAbsolute(top) const effectiveBase = pathUnderOf(base, canonicalTop) ? base : canonicalTop const active = await activeRootFromEvents(await sessionEventsOf(ctx, sessionId), effectiveBase) const root = active ?? effectiveBase - cachePut(activeWorktreeRootCache, sessionId, { root, base, directoryEpoch, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX) + cachePut(activeWorktreeRootCache, sessionId, { root, base, directoryEpoch, eventSeq, gitResolved: true, expires: Date.now() + ACTIVE_ROOT_TTL_MS }, ACTIVE_ROOT_CACHE_MAX) return root } diff --git a/src/bundle-route.ts b/src/bundle-route.ts index 72631b56..e155599b 100644 --- a/src/bundle-route.ts +++ b/src/bundle-route.ts @@ -9,8 +9,11 @@ * ETag (content hash, memoized per file by mtime/size) and honors * If-None-Match — the browser revalidates each fetch, but a 304 avoids * re-downloading multi-MB chunks that did not change (page refresh, HMR - * re-activation). Same browser-trust fence as every other /sidebar route; - * only allowlisted chunk names are servable (no path traversal). + * re-activation). A HEAD answers from the stat alone (headers + content-length, + * no body): the client re-checks every loaded chunk with HEAD when the sidebar + * re-activates, and Node discards the body of a HEAD response anyway. Same + * browser-trust fence as every other /sidebar route; only allowlisted chunk + * names are servable (no path traversal). */ import { createHash } from 'node:crypto' import { stat, readFile } from 'node:fs/promises' @@ -40,22 +43,23 @@ interface ChunkEtag { const etags = new Map() /** - * The chunk file's ETag (quoted hash), or undefined when the file is - * missing. Hash is recomputed only when mtime/size changed (hashing a - * multi-MB chunk per request is wasteful). + * The chunk file's ETag (quoted hash) and byte size, or undefined when the + * file is missing. Hash is recomputed only when mtime/size changed (hashing a + * multi-MB chunk per request is wasteful); the size comes from the same stat, + * so a HEAD never has to read the body. */ -async function etagOf(name: ChunkName, chunkDir: string): Promise { +async function etagOf(name: ChunkName, chunkDir: string): Promise<{ etag: string; size: number } | undefined> { const path = join(chunkDir, `client-${name}.js`) const key = `${chunkDir}:${name}` try { const info = await stat(path) const memo = etags.get(key) if (memo !== undefined && memo.mtimeMs === info.mtimeMs && memo.size === info.size) { - return memo.etag + return { etag: memo.etag, size: info.size } } const etag = `"${shortHash(await readFile(path))}"` etags.set(key, { mtimeMs: info.mtimeMs, size: info.size, etag }) - return etag + return { etag, size: info.size } } catch { return undefined } @@ -89,17 +93,29 @@ export function createBundleRouteHandler( res.end('not found') return } - const etag = await etagOf(name, chunkDir) - if (etag === undefined) { + const info = await etagOf(name, chunkDir) + if (info === undefined) { // Registered name but unreadable (bundle not built yet): loud 404. res.writeHead(404) res.end('not found') return } - if (req.headers['if-none-match'] === etag) { + if (req.headers['if-none-match'] === info.etag) { // Revalidation hit: unchanged chunk, no body — avoids re-downloading // multi-MB scripts on page refresh / HMR re-activation. - res.writeHead(304, { 'cache-control': 'no-cache', etag }) + res.writeHead(304, { 'cache-control': 'no-cache', etag: info.etag }) + res.end() + return + } + if (req.method === 'HEAD') { + // Header-only answer straight from the stat: the client only wants the + // ETag, and the body of a HEAD response is discarded by Node anyway. + res.writeHead(200, { + 'content-type': 'text/javascript; charset=utf-8', + 'cache-control': 'no-cache', + etag: info.etag, + 'content-length': String(info.size), + }) res.end() return } @@ -108,7 +124,7 @@ export function createBundleRouteHandler( res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-cache', - etag, + etag: info.etag, }) res.end(body) } catch { diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 6eb65b57..704a092f 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -587,6 +587,9 @@ export function FileTree(props: { /** The live props for the stable callbacks below (identity churns per render). */ const propsRef = useRef(props) propsRef.current = props + /** Live visibility for the load effects: a parked tree fetches nothing. */ + const visibleRef = useRef(visible !== false) + visibleRef.current = visible !== false const [data, setData] = useState>({}) /** * Registry revision for the file-icon feature: bumps on ANY registry @@ -822,6 +825,12 @@ export function FileTree(props: { * path — while leaving their current rows untouched until the answer lands. */ const loadLevels = useCallback((paths: readonly string[], options?: { force?: boolean }) => { + // A PARKED tree must not fetch, whoever asked: the visible-set effect and + // the fold-chain preload are gated at their call sites, but an answer that + // lands after the tab was hidden can still re-enter here (the preload's + // next link, or the dropped-answer self-heal below). The un-park re-arm + // runs with `visible` already true, so it is unaffected. + if (visibleRef.current === false) return const force = options?.force === true const wanted = force ? [...new Set(paths)] @@ -927,6 +936,11 @@ export function FileTree(props: { loadLevels([dir], { force: true }) }, [loadLevels]) + /** Re-list a SET of directories in ONE batch (the parked→visible re-arm). */ + const retryDirs = useCallback((dirs: readonly string[]) => { + if (dirs.length > 0) loadLevels([...dirs], { force: true }) + }, [loadLevels]) + /** * Settle the tree after one rename/delete landed at `prefix`: drop every * cached level at or under the old path, collapse the now-stale expanded @@ -980,6 +994,10 @@ export function FileTree(props: { useEffect(() => { if (lastTick.current === refreshTick) return lastTick.current = refreshTick + // A parked tree drops the tick outright: the watcher's re-arm re-lists the + // whole watched set when the tab comes back, so forcing a load here would + // only duplicate that batch (and do it off screen). + if (visibleRef.current === false) return generationRef.current += 1 forceNextLoad.current = true }, [refreshTick]) @@ -1002,8 +1020,13 @@ export function FileTree(props: { // Load the visible set in ONE batch request; already-loaded levels (kept // in the cache) are not refetched, so this asks only for what is new — a // refresh tick re-lists root + every expanded directory in one POST. + // + // A PARKED tree issues nothing: nobody can see the rows, and the watcher's + // re-arm re-lists the whole watched set once on the way back. Visibility is + // read through a ref, NOT a dependency — making it one would fire a second + // batch alongside that re-arm. const root = cwd - if (root === undefined) return + if (root === undefined || visibleRef.current === false) return const force = forceNextLoad.current forceNextLoad.current = false loadLevels([root, ...expanded], { force }) @@ -1021,7 +1044,12 @@ export function FileTree(props: { // 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 + // + // A PARKED tree skips the walk too: an in-flight level can land after the + // tab was hidden, and without this guard the preload would keep pulling + // the next link off screen. Un-parking re-lists the root (watcher re-arm), + // and that data change resumes the chain from the frontier. + if (cwd === undefined || visibleRef.current === false) return loadLevels(compactLoadTargets(dataRef.current, [cwd, ...propsRef.current.expanded])) }, [cwd, data, loadLevels]) @@ -1035,13 +1063,13 @@ export function FileTree(props: { // it was opened stayed stale for the rest of the session. A PARKED tree // (the host keeps every visited tab body mounted) closes the socket — and // with it the host's `fs.watch` handles — and re-lists the watched levels - // once when it comes back. + // once (ONE batch) when it comes back. useDirectoryWatch({ sessionId, root: cwd, dirs: expanded, visible: visible !== false, - onStale: retryDir, + onStale: retryDirs, }) // Bring a "Show in folder" reveal into view: the ancestors expand above diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index 767cc761..feb219de 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -479,8 +479,11 @@ function toolLeading(name: string, failed: boolean): React.ReactNode { * object so a row body never rebuilds them per render. */ interface RowSurface { /** The row's prose pass: local image destinations become session media URLs - * first, then the surface's local-link pass runs (see the view's wiring). */ - rewrite: (text: string) => string + * first, then the surface's local-link pass runs (see the view's wiring). + * Takes the ROW (not its text) so the view can reuse an unchanged row's + * rewrite result by object identity. Only prose rows (user / assistant) + * carry `text`; the other kinds never run this pass. */ + rewrite: (row: Extract) => string /** Open one delivered file through the plugin's own open path. */ openFile: (path: string) => void /** The session-scoped media URL of one image deliverable. */ @@ -499,7 +502,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu case 'user': return (
- +
) case 'assistant': @@ -509,7 +512,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu instead of restarting it; only the durable (settled) message is the final parse. It rides the row's own flag so a superseded live row never claims to be settled. */} - + ) case 'reasoning': @@ -746,6 +749,34 @@ export function SideChatView(props: { ), [rewriteChatLinks, scope], ) + /** The media URL base the rewrite bakes into image destinations. */ + const transportBase = hostTransportBase() + /** + * The row-level prose pass, memoized by ROW OBJECT: the transcript reuses an + * unchanged row's object across updates (`sidechat-transcript.ts`), so a + * composer keystroke or a streaming push must not re-run two regex passes + * over every unchanged row's text. The cache is rebuilt when the inputs the + * pass resolves against change (session, cwd, transport base); the row's own + * text is compared too, so a row mutated in place never serves a stale + * rewrite. + */ + const rewriteCache = useMemo(() => { + // The cache is keyed by rows, but its RESULTS were resolved against the + // session cwd and the transport base, so it must not outlive either. The + // reads below make the dependency real to the hook linter (the repo's + // `void wantedKey` idiom). + void scope.sessionId + void scope.cwd + void transportBase + return new WeakMap() + }, [scope.sessionId, scope.cwd, transportBase]) + const rewriteRow = useCallback((row: Extract): string => { + const cached = rewriteCache.get(row) + if (cached !== undefined && cached.text === row.text) return cached.out + const out = rewriteChatText(row.text) + rewriteCache.set(row, { text: row.text, out }) + return out + }, [rewriteCache, rewriteChatText]) /** Open one delivered file: the plugin's own editor path, session-scoped * like every other open in this view (a relative path resolves against the * session cwd). */ @@ -765,12 +796,12 @@ export function SideChatView(props: { const deliverableTitlePath = useCallback((path: string): string => resolveSidebarPath(scope.cwd, path), [scope.cwd]) const rowSurface = useMemo( () => ({ - rewrite: rewriteChatText, + rewrite: rewriteRow, openFile: openDeliveredFile, media: deliverableMediaUrl, resolvePath: deliverableTitlePath, }), - [rewriteChatText, openDeliveredFile, deliverableMediaUrl, deliverableTitlePath], + [rewriteRow, openDeliveredFile, deliverableMediaUrl, deliverableTitlePath], ) const transcriptRef = useCallback((element: HTMLDivElement | null) => { scrollRef.current = element diff --git a/src/client/TasksGraph.tsx b/src/client/TasksGraph.tsx index 794a283a..979b608d 100644 --- a/src/client/TasksGraph.tsx +++ b/src/client/TasksGraph.tsx @@ -358,33 +358,63 @@ export function TasksGraph(props: TasksGraphProps): ReactNode { return () => { observer.disconnect() } }, [fit]) + /** + * Wheel zoom is applied at most once per animation frame, for the same + * reason the pan is: a trackpad (and a high-report-rate mouse) delivers + * several wheel events per display frame, and every one of them + * used to commit a full canvas re-render. Each event chains off the PENDING + * transform rather than the last drawn one, so coalescing never loses a zoom + * step — the old code re-read `tfRef` for every event and only one step + * survived the frame. + */ + const wheelBatcher = useRef(createFrameBatcher()).current + const pendingWheelRef = useRef<{ x: number; y: number; k: number } | null>(null) + /** + * A background pan gesture owns the transform from pointerdown to release. + * Wheel zoom and the pan both commit a WHOLE transform, so a wheel mid-drag + * would be overwritten by the pan's next frame (or vice versa); the wheel is + * ignored while the gesture is live instead. + */ + const panActiveRef = useRef(false) + // Wheel-zoom to cursor (non-passive: the page must not scroll). useEffect(() => { const container = containerRef.current if (container === null) return const onWheel = (event: WheelEvent): void => { event.preventDefault() + if (panActiveRef.current) return const rect = container.getBoundingClientRect() const mx = event.clientX - rect.left const my = event.clientY - rect.top - const { x, y, k } = tfRef.current + const base = pendingWheelRef.current ?? tfRef.current // Wheel deltas arrive in pixels, lines or pages depending on the device; // normalise first, or a line-scrolling mouse zooms 30× slower than a // trackpad (and a trackpad pinch, which reports ctrlKey, feels stuck). const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 100 : 1 - const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, k * Math.exp(-event.deltaY * unit * 0.0014))) - if (next === k) return + const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, base.k * Math.exp(-event.deltaY * unit * 0.0014))) + if (next === base.k) return touchedRef.current = true stopGlide() - setTf(clampTf({ - x: mx - (mx - x) * (next / k), - y: my - (my - y) * (next / k), + // Clamp EACH composed step, not just the frame's final value: the old + // one-event-per-frame code clamped every step, and a later step's anchor + // math must start from the in-bounds transform the earlier one would + // have shown (otherwise coalescing changes where the zoom lands). + pendingWheelRef.current = clampTf({ + x: mx - (mx - base.x) * (next / base.k), + y: my - (my - base.y) * (next / base.k), k: next, - })) + }) + wheelBatcher.schedule(() => { + const pending = pendingWheelRef.current + if (pending === null) return + pendingWheelRef.current = null + setTf(clampTf(pending)) + }) } container.addEventListener('wheel', onWheel, { passive: false }) return () => { container.removeEventListener('wheel', onWheel) } - }, [clampTf, stopGlide]) + }, [clampTf, stopGlide, wheelBatcher]) const zoomBy = useCallback((factor: number): void => { const container = containerRef.current @@ -428,7 +458,10 @@ export function TasksGraph(props: TasksGraphProps): ReactNode { const panBatcher = useRef(createFrameBatcher()).current const pendingPanRef = useRef<{ x: number; y: number; k: number } | null>(null) const draggingRef = useRef(false) - useEffect(() => () => { panBatcher.dispose() }, [panBatcher]) + useEffect(() => () => { + panBatcher.dispose() + wheelBatcher.dispose() + }, [panBatcher, wheelBatcher]) const onPointerDown = useCallback((event: ReactPointerEvent): void => { if (event.button !== 0) return @@ -441,6 +474,7 @@ export function TasksGraph(props: TasksGraphProps): ReactNode { if (target.closest('[data-graph-controls]') !== null) return const startX = event.clientX const startY = event.clientY + panActiveRef.current = true const { x, y } = tfRef.current const onMove = (move: globalThis.PointerEvent): void => { const dx = move.clientX - startX @@ -465,6 +499,7 @@ export function TasksGraph(props: TasksGraphProps): ReactNode { window.removeEventListener('pointerup', onUp) window.removeEventListener('pointercancel', onUp) panBatcher.flushNow() + panActiveRef.current = false draggingRef.current = false setDragging(false) } diff --git a/src/client/TreePanel.tsx b/src/client/TreePanel.tsx index 97be92b0..51f9b1c1 100644 --- a/src/client/TreePanel.tsx +++ b/src/client/TreePanel.tsx @@ -118,7 +118,13 @@ export function TreePanel(props: { // refresh click. Re-focusing the window bumps the tick automatically, and // integrations can force a refresh by dispatching a bubbling // `dsh-sidebar:refresh-files` event on `window`. + // + // A PARKED panel (the host keeps every visited tab body mounted) listens to + // neither: a focus bump would force a full re-list of a tree nobody can see. + // It catches up through the directory watcher's one batched refresh when it + // becomes visible again (see FileTree's `visibleRef`). useEffect(() => { + if (visible === false) return const bump = (): void => { setRefreshTick(tick => tick + 1) } window.addEventListener('focus', bump) window.addEventListener('dsh-sidebar:refresh-files', bump) @@ -126,7 +132,7 @@ export function TreePanel(props: { window.removeEventListener('focus', bump) window.removeEventListener('dsh-sidebar:refresh-files', bump) } - }, []) + }, [visible]) /** One-line upload status under the search row ('' hides the hint). */ const [uploadStatus, setUploadStatus] = useState('') /** Whether the status line is a failure/cancel (error color, stays visible). */ diff --git a/src/client/changes/DiffPane.tsx b/src/client/changes/DiffPane.tsx index 976b7f2d..e2929a3c 100644 --- a/src/client/changes/DiffPane.tsx +++ b/src/client/changes/DiffPane.tsx @@ -430,18 +430,27 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, [htmlOp, scope, contentAbs], ) - // Header stats for git targets come off the parsed patch text. - const gitStats = useMemo(() => { + /** + * ONE parse of the patch per target: the header stats and the file rows both + * read it. Parsing an ≤8MB patch twice on the UI thread (once here for the + * stats, once inside DiffFiles) was visible when a large commit was opened. + */ + const gitParsed = useMemo(() => { if (target.kind !== 'git' || diffText === null || diffText === '') return null + return parseUnifiedDiff(diffText) + }, [target.kind, diffText]) + // Header stats for git targets come off that shared parse. + const gitStats = useMemo(() => { + if (gitParsed === null) return null let added = 0 let deleted = 0 - for (const file of parseUnifiedDiff(diffText).files) { + for (const file of gitParsed.files) { const stats = diffStats(unifiedSegments(file)) added += stats.added deleted += stats.deleted } return { added, deleted } - }, [target, diffText]) + }, [gitParsed]) // ── Resize: drag the top handle; commit on release (persisted by the // shell). Arrow keys resize by a step for keyboard users. ──────────── @@ -662,6 +671,7 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, {((diffText !== null && diffText !== '') || untracked !== undefined) && ( > @@ -138,6 +140,47 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP const appending = useRef(false) const scrollRef = useRef(null) const sentinelRef = useRef(null) + /** + * The scroll container's measured viewport, and the per-frame coalescer that + * keeps it in step with a scroll stream (a trackpad fires several scroll + * events per display frame; one commit per frame is enough to move the + * window, and each commit reads layout once). + */ + const [view, setView] = useState({ scrollTop: 0, height: 0 }) + const scrollBatcher = useRef(createFrameBatcher()).current + const syncWindow = useCallback((): void => { + const node = scrollRef.current + if (node === null) return + const scrollTop = node.scrollTop + const height = node.clientHeight + setView(current => (current.scrollTop === scrollTop && current.height === height + ? current + : { scrollTop, height })) + }, []) + // A page append/shrink changes the content under the scroll position; the + // browser clamps a stale scrollTop only after the DOM commit, so re-read it + // in the layout phase. The pure range function clamps anyway. + useLayoutEffect(() => { syncWindow() }, [syncWindow, page?.entries.length]) + // A panel resize (the details pane opening, a window resize, the sidebar + // width drag) changes how many rows fit: re-measure so the mounted window + // still covers the viewport instead of leaving a blank band. A HIDDEN + // section holds no observer (AGENTS steady-state rule) — the effect depends + // on `visible`, re-measures on the way back, and drops any frame it had + // queued. + useEffect(() => { + if (!visible) return + const node = scrollRef.current + if (node === null) return + syncWindow() + if (typeof ResizeObserver === 'undefined') return () => { scrollBatcher.dispose() } + const observer = new ResizeObserver(() => { syncWindow() }) + observer.observe(node) + return () => { + scrollBatcher.dispose() + observer.disconnect() + } + }, [scrollBatcher, syncWindow, visible]) + useEffect(() => () => { scrollBatcher.dispose() }, [scrollBatcher]) /** Row hover preview: the middle information rung between the one-line row * (pills + subject) and the details card (everything). It opens only after * a short dwell so scrolling past rows never flashes cards; the pointer @@ -227,6 +270,12 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP const rows = useMemo(() => layoutGraph(page?.entries ?? []), [page?.entries]) const width = Math.max(28, ...rows.map(row => laneX(row.laneCount) + 2)) + const range = windowedRange({ + count: page?.entries.length ?? 0, + rowHeight: ROW_HEIGHT, + scrollTop: view.scrollTop, + viewportHeight: view.height, + }) const remotes = useMemo(() => remoteRefNames(branches), [branches]) const selectedIndex = selectedRef?.kind === 'commit' && selectedRef.worktree === worktree @@ -262,7 +311,8 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP setPage(null) } - return
+ return
-
+
{ + // The window may unmount the row the hover card is anchored to. + if (hover !== null || hoverTimer.current !== null) cancelHover() + scrollBatcher.schedule(syncWindow) + }}> {error !== null &&
{stale ? t('graphStale') : t('graphLoadError')}{!stale && `: ${error}`}
} {loading &&
{t('loading')}
} {!loading && !error && page !== null && page.entries.length === 0 &&
{t(page.isRepo ? 'graphEmpty' : 'notRepo')}
} - {page?.entries.map((entry, index) => { + {range.top > 0 &&