Merge branch 'dev' into fix/bottom-toggle-with-right-panel

This commit is contained in:
WinterXMQ authored and GitHub committed 2026-10-25 02:25:33 +08:00
commit f2ad4b1af8
24 files changed
+1181 -92

No files matched your search

+8
View File
@@ -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 次。
+143
View File
@@ -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<SidechatTranscriptRow, {text:string}>`);`WeakMap<row, {text,out}>` 缓存,输入变化为 `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 滚动断言补回可达性证据。
+37 -6
View File
@@ -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<string, { root: string; base: string; directoryEpoch: number | undefined; expires: number }>()
const activeWorktreeRootCache = new Map<string, { root: string; base: string; directoryEpoch: number | undefined; eventSeq: number | undefined; gitResolved: boolean; expires: number }>()
const pathTopCache = new Map<string, string | undefined>()
const linkedWorktreeCache = new Map<string, boolean>()
@@ -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<string> {
// 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
}
+29 -13
View File
@@ -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<string, ChunkEtag>()
/**
* 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<string | undefined> {
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 {
+32 -4
View File
@@ -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<Record<string, LevelData>>({})
/**
* 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
+37 -6
View File
@@ -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<SidechatTranscriptRow, { text: string }>) => 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 (
<div key={`${row.kind}:${row.seq}`} className={css.sidechatUser}>
<MarkdownText {...markdownTextProps(surface.rewrite(row.text), labels)} />
<MarkdownText {...markdownTextProps(surface.rewrite(row), labels)} />
</div>
)
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. */}
<MarkdownText {...markdownTextProps(surface.rewrite(row.text), labels)} streaming={!row.settled} />
<MarkdownText {...markdownTextProps(surface.rewrite(row), labels)} streaming={!row.settled} />
</div>
)
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<object, { text: string; out: string }>()
}, [scope.sessionId, scope.cwd, transportBase])
const rewriteRow = useCallback((row: Extract<SidechatTranscriptRow, { text: string }>): 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<RowSurface>(
() => ({
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
+44 -9
View File
@@ -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<HTMLDivElement>): 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)
}
+7 -1
View File
@@ -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). */
+14 -4
View File
@@ -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) && (
<DiffFiles
diff={diffText ?? ''}
parsed={untracked === undefined ? gitParsed ?? undefined : undefined}
resolveFold={resolveFold}
untrackedPath={untracked !== undefined && target.ref.kind === 'worktree' ? target.ref.path : undefined}
untrackedContent={untracked}
+62 -4
View File
@@ -7,7 +7,7 @@
* Mounted by {@link GitLens} on the repo/worktree target the lens has already
* selected; it owns its own bounded page (`git.graph`) and reports the
* selected commit upward for the tab's bottom pane (`details` tab). */
import { useEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import {
Button, IconBranchOutlineRegular, IconCheckOutlineRegular, IconGlobeOutlineRegular,
} from '@deepseek-ai/dsh-client-ui-primitives'
@@ -17,6 +17,8 @@ import { relativeTime, t } from '../locales.ts'
import { Notice } from '../ui/index.ts'
import { AnchoredPopover } from '../AnchoredPopover.tsx'
import { edgePath, layoutGraph } from './graph-layout.ts'
import { createFrameBatcher } from '../frame-batcher.ts'
import { windowedRange } from './git-graph-windowing.ts'
import css from './graph.module.css'
type GraphPage = Awaited<ReturnType<typeof api.gitGraph>>
@@ -138,6 +140,47 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
const appending = useRef(false)
const scrollRef = useRef<HTMLDivElement | null>(null)
const sentinelRef = useRef<HTMLDivElement | null>(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 <section className={css.root} aria-label={t('gitGraph')} data-git-graph>
return <section className={css.root} aria-label={t('gitGraph')} data-git-graph
data-graph-count={page?.entries.length ?? 0}>
<div className={css.toolbar}>
<select className={css.select} aria-label={t('graphBranchFilter')}
value={branch} onChange={event => { chooseBranch(event.target.value) }}>
@@ -271,14 +321,21 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
{branch && !branches.some(item => item.ref === branch) && <option value={branch}>{branch}</option>}
</select>
</div>
<div className={css.scroll} aria-busy={loading} ref={scrollRef}>
<div className={css.scroll} aria-busy={loading} ref={scrollRef} data-graph-scroll
onScroll={() => {
// The window may unmount the row the hover card is anchored to.
if (hover !== null || hoverTimer.current !== null) cancelHover()
scrollBatcher.schedule(syncWindow)
}}>
{error !== null && <div className={css.notice} role="alert">
<Notice kind="warn">{stale ? t('graphStale') : t('graphLoadError')}{!stale && `: ${error}`}</Notice>
<Button onClick={() => { if (stale || !failedAppend.current) setRetry(value => value + 1); else void request(true) }}>{t('retry')}</Button>
</div>}
{loading && <div className={css.notice} role="status">{t('loading')}</div>}
{!loading && !error && page !== null && page.entries.length === 0 && <div className={css.notice}>{t(page.isRepo ? 'graphEmpty' : 'notRepo')}</div>}
{page?.entries.map((entry, index) => {
{range.top > 0 && <div aria-hidden="true" data-graph-spacer="top" style={{ height: range.top }} />}
{page?.entries.slice(range.start, range.end).map((entry, offset) => {
const index = range.start + offset
const row = rows[index]!
const slot = colorSlot(row.colorIndex)
return <button key={entry.hashFull} type="button" className={css.row}
@@ -302,6 +359,7 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP
<span className={css.subject}>{entry.subject}</span>
</button>
})}
{range.bottom > 0 && <div aria-hidden="true" data-graph-spacer="bottom" style={{ height: range.bottom }} />}
{page?.hasMore && !stale && <div className={css.notice} ref={sentinelRef} data-graph-sentinel>
<Button disabled={loading} onClick={() => { void request(true) }}>{t('graphLoadMore')}</Button>
</div>}
+64
View File
@@ -0,0 +1,64 @@
/**
* The visible slice of a fixed-height row list (the commit graph's history).
*
* `page.entries` grows by one infinite-scroll page at a time (50 rows; the
* host caps the walk at 10000) and every row carries an SVG rail, so mounting
* the whole history made each append and each scroll cost O(history). Only
* the viewport window (± overscan) is mounted; the two spacer heights keep the
* real scrollbar, the end sentinel's position and the `data-graph-count` page
* size intact.
*
* The arithmetic is pure and clamped on purpose: the list can shrink under the
* scroll position (a branch switch, a refresh collapses the page), and the
* browser only clamps `scrollTop` afterwards — a stale `scrollTop` must never
* translate into an out-of-range window (that would render the wrong rows
* while the scrollbar sits at the top).
*/
export interface WindowedRange {
/** First mounted row (inclusive). */
start: number
/** One past the last mounted row. */
end: number
/** Pixel height of the rows above the window. */
top: number
/** Pixel height of the rows below the window. */
bottom: number
}
export interface WindowedRangeOptions {
/** Total number of rows in the list. */
count: number
/** Height of one row in pixels (the graph's rows are a fixed 28). */
rowHeight: number
/** The scroll container's current `scrollTop`. */
scrollTop: number
/** The scroll container's client height; 0 before it is measured. */
viewportHeight: number
/** Extra rows kept mounted above and below the viewport (default 8). */
overscan?: number
}
/**
* Compute the mounted row range for one scroll position.
* @param options - row count/height, scroll position, viewport height and overscan.
* @returns The clamped half-open range plus the two spacer heights.
*/
export function windowedRange(options: WindowedRangeOptions): WindowedRange {
const { count, rowHeight, scrollTop, viewportHeight } = options
const overscan = Math.max(0, options.overscan ?? 8)
if (count <= 0 || rowHeight <= 0) return { start: 0, end: 0, top: 0, bottom: 0 }
// A container that is not measured yet still mounts one row plus the
// overscan band, so the first paint is not empty and the height feedback
// loop (measure → render) has content to measure.
const rowsInView = Math.max(1, Math.ceil(Math.max(0, viewportHeight) / rowHeight))
const visible = rowsInView + overscan * 2
const first = Math.floor(Math.max(0, scrollTop) / rowHeight) - overscan
const start = Math.min(Math.max(0, first), count - 1)
const end = Math.min(count, start + visible)
return {
start,
end,
top: start * rowHeight,
bottom: (count - end) * rowHeight,
}
}
+30 -8
View File
@@ -10,7 +10,7 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import clsx from 'clsx'
import { t } from '../locales.ts'
import { diffStats, displayPath, parseUnifiedDiff, unifiedSegments, untrackedFile, type DiffFile, type DiffRow, type FoldSegment } from './rows.ts'
import { diffStats, displayPath, parseUnifiedDiff, unifiedSegments, untrackedFile, type DiffFile, type DiffRow, type FoldSegment, type ParsedDiff } from './rows.ts'
import { langOfPath } from './highlight.ts'
import { DiffRows } from './DiffRows.tsx'
import css from './diff.module.css'
@@ -20,16 +20,32 @@ const DOC_PATH = /(^|\/)(?:docs?|documentation)(?:\/|$)|(^|\/)(?:readme|changelo
const GENERATED_PATH = /(^|\/)(?:dist|build|coverage|generated|vendor|node_modules)(?:\/|$)|(^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|composer\.lock|cargo\.lock|poetry\.lock)$/i
const SOURCE_PATH = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts|py|pyw|rb|php|java|kt|kts|scala|go|rs|swift|c|h|cc|cpp|cxx|hpp|hh|hxx|cs|fs|fsx|vb|dart|lua|r|ex|exs|erl|hrl|clj|cljs|cljc|groovy|sh|bash|zsh|fish|ps1|sql|vue|svelte|astro|html|htm|css|scss|sass|less)$/i
/**
* How many changed lines the default expansion may mount.
*
* Source files open by default, but a commit that rewrites a dozen of them
* used to mount every row at once (each file renders through DiffRows, capped
* at 600 rows). The budget keeps the first screen useful without paying for
* the whole patch: the FIRST source file always opens (an all-folded pane
* reads as empty), and everything past the budget stays folded with its +/−
* stats still on the header, one click away.
*/
const DEFAULT_EXPANDED_LINE_BUDGET = 2_000
/** Source files open by default; tests, docs, generated files and unknown types stay folded. */
function defaultExpandedFiles(files: readonly DiffFile[]): Set<number> {
const expanded = new Set<number>()
let budget = 0
files.forEach((file, index) => {
const path = displayPath(file.newPath === '/dev/null' ? file.oldPath : file.newPath)
if (!file.binary && file.hunks.length > 0
const isSource = !file.binary && file.hunks.length > 0
&& !TEST_PATH.test(path) && !DOC_PATH.test(path) && !GENERATED_PATH.test(path)
&& SOURCE_PATH.test(path)) {
expanded.add(index)
}
&& SOURCE_PATH.test(path)
if (!isSource) return
const changedLines = file.hunks.reduce((total, hunk) => total + hunk.lines.length, 0)
if (expanded.size > 0 && budget + changedLines > DEFAULT_EXPANDED_LINE_BUDGET) return
expanded.add(index)
budget += changedLines
})
return expanded
}
@@ -48,6 +64,12 @@ function fileTag(file: DiffFile): string | null {
export interface DiffFilesProps {
/** Unified diff text (`git.diff` or `git.commit-diff` payloads). */
diff: string
/** A parse the caller ALREADY did for its own header stats: rendering the
* same ≤8MB patch twice on the UI thread was visible on large commits. The
* component trusts it as-is (the changes pane passes the parse it just
* summarized); omit it to parse `diff` here. Ignored for untracked files,
* whose synthetic full-file addition comes from their content. */
parsed?: ParsedDiff
/** Untracked-file content: when present, renders as a full-file addition instead of parsing. */
untrackedPath?: string
untrackedContent?: string
@@ -58,13 +80,13 @@ export interface DiffFilesProps {
resolveFold?: (file: DiffFile, segment: FoldSegment) => Promise<readonly DiffRow[]>
}
export function DiffFiles({ diff, untrackedPath, untrackedContent, resolveFold }: DiffFilesProps) {
export function DiffFiles({ diff, parsed: provided, untrackedPath, untrackedContent, resolveFold }: DiffFilesProps) {
const parsed = useMemo(() => {
if (untrackedPath !== undefined) {
return { files: [untrackedFile(untrackedPath, untrackedContent ?? '')] }
}
return parseUnifiedDiff(diff)
}, [diff, untrackedPath, untrackedContent])
return provided ?? parseUnifiedDiff(diff)
}, [provided, diff, untrackedPath, untrackedContent])
const [expandedFiles, setExpandedFiles] = useState<Set<number>>(() => defaultExpandedFiles(parsed.files))
useEffect(() => { setExpandedFiles(defaultExpandedFiles(parsed.files)) }, [parsed])
+11 -6
View File
@@ -47,10 +47,14 @@ export interface DirectoryWatchOptions {
*/
visible?: boolean
/**
* A directory whose listing is stale.
* @param dir - absolute directory path, exactly the form the tree keys levels by.
* Directories whose listings are stale.
*
* A watch notice names one directory. The parked→visible re-arm names the
* WHOLE watched set at once: the caller re-lists it in one batch request
* instead of firing one request per directory.
* @param dirs - absolute directory paths, exactly the form the tree keys levels by.
*/
onStale: (dir: string) => void
onStale: (dirs: readonly string[]) => void
}
/** How long to wait before re-opening a dropped socket; failures back off to the cap. */
@@ -146,7 +150,7 @@ export function useDirectoryWatch(options: DirectoryWatchOptions): void {
watching.add(frame.dir)
return
}
if (frame.ok === undefined) staleRef.current(frame.dir)
if (frame.ok === undefined) staleRef.current([frame.dir])
}
socket.onclose = () => {
if (closed) return
@@ -175,13 +179,14 @@ export function useDirectoryWatch(options: DirectoryWatchOptions): void {
* Re-armed after being parked: the socket is brand new (the old one's
* notices are gone with it), so nothing the host saw while the tree was
* hidden was delivered. Re-list every watched directory once instead of
* showing a listing that may be minutes old.
* showing a listing that may be minutes old — as ONE batch (the caller
* re-lists the set in a single `fs.trees` request), not one per directory.
*/
const wasArmedRef = useRef(armed)
useEffect(() => {
const previous = wasArmedRef.current
wasArmedRef.current = armed
if (!armed || previous) return
for (const dir of wantedRef.current) staleRef.current(dir)
if (wantedRef.current.length > 0) staleRef.current(wantedRef.current)
}, [armed])
}
+126
View File
@@ -98,6 +98,36 @@ function countingSessionCtx(cwd: string, calls: Array<Record<string, unknown>>):
return { ctx: ctx as Context, scans: () => scans }
}
/**
* A live session face with a MUTABLE event cursor: `seq` moves when an event
* is appended, exactly like the host's. `scans` counts real snapshot reads, so
* a cache hit that only compared the cursor costs zero.
*/
function cursorSessionCtx(
cwd: string,
calls: Array<Record<string, unknown>>,
initialSeq = 5,
): { ctx: Context; scans: () => number; append: () => void } {
let scans = 0
let seq = initialSeq
const ctx = {
sessions: {
get: () => {
return {
header: { cwd },
seq,
snapshotEvents: () => {
scans += 1
return calls.map((data, index) => ({ type: 'tool/call', seq: index, time: index, data }))
},
}
},
},
get: () => undefined,
} as never
return { ctx: ctx as Context, scans: () => scans, append: () => { seq += 1 } }
}
describe('active worktree root', () => {
it('follows a linked worktree of a DIFFERENT repository named by the tool calls', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
@@ -256,6 +286,100 @@ describe('active worktree root', () => {
}
})
/**
* A TTL miss is not automatically a rescan: the entry is only invalid because
* wall time passed, and the resolver reads the event log (up to 4000 events
* + git probes, measured 9.6–44.7 ms). When the session's cursor has not
* moved, nothing it reads can have changed — re-arm the TTL instead of
* snapshotting the log again. This is the idle 5 s poll's hot path.
*/
it('does not re-scan the event log after the TTL when the session cursor is unchanged', async () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
try {
initRepo(repo, 'a.txt')
mkdirSync(join(repo, 'src'))
const { ctx, scans, append } = cursorSessionCtx(repo, [{ cwd: join(repo, 'src') }])
const first = await activeWorktreeRootOf(ctx, 's-cursor', repo)
expect(first).toBe(realpathSync.native(repo))
expect(scans()).toBe(1)
probed.length = 0
const started = Date.now()
const clock = vi.spyOn(Date, 'now').mockReturnValue(started + 60_000)
try {
await expect(activeWorktreeRootOf(ctx, 's-cursor', repo)).resolves.toBe(first)
expect(scans(), 'an idle TTL expiry must not snapshot the log').toBe(1)
expect(probed).toEqual([])
// A new event moves the cursor: the next expiry re-scans (inside the
// re-armed TTL the cached root still wins — the 15 s follow bound).
append()
clock.mockReturnValue(started + 120_000)
await expect(activeWorktreeRootOf(ctx, 's-cursor', repo)).resolves.toBe(first)
expect(scans(), 'a moved cursor re-scans').toBe(2)
} finally {
clock.mockRestore()
}
} finally {
removeTree(root)
}
})
/**
* A cache entry whose base probe found NO repository (or failed) must keep
* the wall-clock re-probe even when the event cursor is idle: `git init` in
* a parent, a transient spawn failure, or a mount that comes back are all
* invisible to the event log. Only a resolved git top may be re-armed.
*/
it('keeps re-probing a non-repository base after the TTL with an idle cursor', async () => {
// A plain directory: `git rev-parse` fails, so the answer is the base.
const base = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
try {
const { ctx, scans } = cursorSessionCtx(base, [])
probed.length = 0
await expect(activeWorktreeRootOf(ctx, 's-norepo', base)).resolves.toBe(base)
expect(probed).toEqual([base])
expect(scans()).toBe(0)
probed.length = 0
const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 60_000)
try {
await expect(activeWorktreeRootOf(ctx, 's-norepo', base)).resolves.toBe(base)
expect(probed, 'a negative repository answer must not be re-armed forever').toEqual([base])
} finally {
clock.mockRestore()
}
} finally {
removeTree(base)
}
})
/**
* The fallback: hosts (and detached sessions) without a live cursor expose no
* `seq`, so the TTL keeps its old meaning — expire means re-scan.
*/
it('re-scans after the TTL when the host exposes no event cursor', async () => {
probed.length = 0
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
const repo = join(root, 'repo')
try {
initRepo(repo, 'a.txt')
const { ctx, scans } = countingSessionCtx(repo, [{ cwd: join(repo, 'src') }])
await activeWorktreeRootOf(ctx, 's-no-cursor', repo)
expect(scans()).toBe(1)
const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 60_000)
try {
await activeWorktreeRootOf(ctx, 's-no-cursor', repo)
expect(scans()).toBe(2)
} finally {
clock.mockRestore()
}
} finally {
removeTree(root)
}
})
/**
* The three process-wide maps are bounded LRUs. The module exposes no test
* seam, so the bound is observed the only way it is observable from outside:
@@ -263,6 +387,8 @@ describe('active worktree root', () => {
* again (it was evicted) while the youngest ones still hit.
*/
it('bounds the root cache: the oldest session is evicted past the cap', async () => {
// Probe calls are module-wide; this case counts them from a clean slate.
probed.length = 0
const root = mkdtempSync(join(tmpdir(), 'dsh-active-root-'))
try {
// The canned answer keeps the 257 probes from being 257 real processes;
+19
View File
@@ -64,6 +64,25 @@ describe('/sidebar/bundle route', () => {
}
})
it('answers HEAD with the headers only, without materializing the chunk', async () => {
// The client HEADs every loaded chunk when the sidebar re-activates (and
// once after each lazy load) to read the ETag. Reading the multi-MB body
// for a request whose body Node discards is pure waste.
const { handler, cleanup } = setup()
try {
const res = fakeRes()
await handler(req('HEAD', '/sidebar/bundle/editor.js'), res as unknown as ServerResponse)
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/javascript; charset=utf-8')
expect(res.headers['cache-control']).toBe('no-cache')
expect(res.headers.etag).toMatch(/^"[0-9a-f]{12}"$/)
expect(res.headers['content-length']).toBe(String('window.__ModuleLoader__ && 0;'.length))
expect(res.body, 'HEAD must not read the chunk body').toBe('')
} finally {
cleanup()
}
})
it('revalidates with a 304 when If-None-Match matches (no re-download)', async () => {
const { handler, cleanup } = setup()
try {
+52
View File
@@ -4,6 +4,7 @@ import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { DiffFiles } from '../src/client/diff/DiffFiles.tsx'
import { parseUnifiedDiff } from '../src/client/diff/rows.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
@@ -57,4 +58,55 @@ describe('DiffFiles file folding', () => {
container.remove()
}
})
it('caps the default expansion by changed lines, not by file count', () => {
// Six source files of 600 changed lines each: the first three fill the
// 2000-line budget, so the other three start folded (their headers still
// carry the +/− stats and can be opened one by one).
const parts: string[] = []
for (let file = 0; file < 6; file += 1) {
parts.push(
`diff --git a/src/f${file}.ts b/src/f${file}.ts`,
`--- a/src/f${file}.ts`,
`+++ b/src/f${file}.ts`,
'@@ -1,300 +1,300 @@',
)
for (let line = 0; line < 300; line += 1) parts.push(`-old-${file}-${line}`, `+new-${file}-${line}`)
}
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
act(() => { root.render(createElement(DiffFiles, { diff: parts.join('\n') })) })
const headers = [...container.querySelectorAll<HTMLButtonElement>('button[aria-expanded]')]
expect(headers).toHaveLength(6)
expect(headers.map(header => header.getAttribute('aria-expanded')))
.toEqual(['true', 'true', 'true', 'false', 'false', 'false'])
// Only the three budgeted files mount their rows (600 each; the pairs
// render as `mod`, so count every change class and not just `add`).
expect(container.querySelectorAll('[data-kind="add"], [data-kind="del"], [data-kind="mod"], [data-kind="context"]'))
.toHaveLength(1800)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
it('renders the caller-supplied parse instead of parsing the patch again', () => {
// The changes pane parses one patch for BOTH its header stats and these
// rows; a second parse of an ≤8MB patch on the UI thread was the cost.
const parsed = parseUnifiedDiff(diff)
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
try {
act(() => { root.render(createElement(DiffFiles, { diff: 'not a unified diff', parsed })) })
const headers = [...container.querySelectorAll<HTMLButtonElement>('button[aria-expanded]')]
expect(headers).toHaveLength(3)
expect(container.textContent).toContain('new-a')
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})
+17 -2
View File
@@ -93,7 +93,9 @@ test('read-only Git Graph renders merge history and filters without checkout', a
expect(await page.locator('[data-scm-section="graph"]').evaluate(el => Math.round(el.getBoundingClientRect().height))).toBe(28)
await graphHeader.click()
await expect(graph).toBeVisible()
await expect(graph.locator('[data-graph-commit]')).toHaveCount(50)
// The row window is viewport-bound now; the PAGE size is what the state
// carries, so assert it on the section rather than counting mounted rows.
await expect(graph).toHaveAttribute('data-graph-count', '50')
await expectGraphFillsHeight()
// Stress the outer scroller only after verifying graph interactions are read-only.
@@ -102,7 +104,20 @@ test('read-only Git Graph renders merge history and filters without checkout', a
await changes.getByRole('button', { name: 'Refresh', exact: true }).click()
await expect(changes.locator('[data-row="change-39.txt"]')).toHaveCount(1)
await expect(graphScroll).toHaveAttribute('aria-busy', 'false')
await expect(graph.locator('[data-graph-commit]')).toHaveCount(50)
// The row window is viewport-bound now; the PAGE size is what the state
// carries, so assert it on the section rather than counting mounted rows.
await expect(graph).toHaveAttribute('data-graph-count', '50')
// …but the mounted window must still reach the history: scrolling to the
// end appends the remaining commits, and the oldest one renders once the
// window follows to the new bottom. (Counting DOM rows alone would lose
// this reachability evidence.)
const topHash = await graph.locator('[data-graph-commit]').first().getAttribute('data-graph-commit')
await graphScroll.evaluate(el => { el.scrollTop = el.scrollHeight })
await expect(graph).toHaveAttribute('data-graph-count', '52', { timeout: 20_000 })
await graphScroll.evaluate(el => { el.scrollTop = el.scrollHeight })
await expect.poll(async () => graph.locator('[data-graph-commit]').first().getAttribute('data-graph-commit'))
.not.toBe(topHash)
await expect(graph.getByText('Graph base', { exact: true })).toBeVisible()
const outer = page.locator('[data-git-scroll]')
expect(await outer.evaluate(el => el.scrollHeight > el.clientHeight)).toBe(true)
expect(await graph.evaluate(el => Math.round(el.getBoundingClientRect().height))).toBe(220)
+69 -16
View File
@@ -10,7 +10,7 @@
*/
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement, useEffect, type ReactNode } from 'react'
import { createElement, Profiler, useEffect, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import type { Context } from '../src/context-types.ts'
@@ -282,29 +282,44 @@ function mountHost(ctx: Context, store: ReturnType<typeof createSidebarStore>, t
* context-menu scenarios need the file row in the DOM). The scope carries the
* session cwd — without a root the docked tree has nothing to list.
*/
async function mountHostWithTreeWithCwd(ctx: Context, store: ReturnType<typeof createSidebarStore>, tab: () => SidebarTab): Promise<{
async function mountHostWithTreeWithCwd(
ctx: Context,
store: ReturnType<typeof createSidebarStore>,
tab: () => SidebarTab,
options: { visible?: boolean; onRender?: () => void } = {},
): Promise<{
container: HTMLDivElement
rerender: (visible: boolean) => Promise<void>
unmount: () => void
}> {
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
await act(async () => {
root.render(createElement(EditorHost, {
ctx,
store,
scope: { sessionId, cwd: '/tmp' },
tab: tab(),
expanded: [],
revealed: [],
onToggleDir: () => {},
onReferenceFile: () => {},
}))
await Promise.resolve()
await Promise.resolve()
})
let visible = options.visible
const render = async (): Promise<void> => {
await act(async () => {
const host = createElement(EditorHost, {
ctx,
store,
scope: { sessionId, cwd: '/tmp' },
tab: tab(),
expanded: [],
revealed: [],
onToggleDir: () => {},
onReferenceFile: () => {},
visible,
})
root.render(options.onRender === undefined
? host
: createElement(Profiler, { id: 'editor-host', onRender: options.onRender }, host))
await Promise.resolve()
await Promise.resolve()
})
}
await render()
return {
container,
rerender: async (next: boolean) => { visible = next; await render() },
unmount: () => {
act(() => { root.unmount() })
container.remove()
@@ -856,6 +871,44 @@ describe('EditorHost native-tab context-menu actions', { timeout: 120_000 }, ()
}
})
it('a parked tree ignores window focus and re-lists the watched set once on return', async () => {
// The host keeps every visited tab body mounted, so a hidden tree used to
// answer every window focus with a forced full re-list (one per mounted
// panel). It must stay silent while parked and catch up in ONE batch.
let commits = 0
const store = createSidebarStore()
const { service } = spyService(store)
service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab: SidebarTab) => tab.path, component: () => null })
store.setSession(sessionId)
store.setPrefs({ ...store.getPrefs(), editorExplorer: false })
service.openTab({
type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts', meta: { treeOpen: true },
})
const fileTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
.find(tab => tab.path === '/tmp/a.ts')!
const { container, rerender, unmount } = await mountHostWithTreeWithCwd(
fakeCtx(service) as unknown as Context, store, fileTab, { onRender: () => { commits += 1 } },
)
try {
await waitForTreeRow(container, 'a.ts')
expect(treeAnswers().calls).toBe(1)
await rerender(false)
commits = 0
await act(async () => { window.dispatchEvent(new Event('focus')) })
expect(treeAnswers().calls, 'a parked tree does not answer window focus').toBe(1)
// The parked panel must not even re-render on a focus bump: one state
// update would reconcile every row of a tree nobody can see.
expect(commits, 'a parked tree does not re-render on window focus').toBe(0)
await rerender(true)
expect(treeAnswers().calls, 'the return re-lists the watched set once').toBe(2)
} finally {
unmount()
}
})
it('keeps the bottom-workbench split for a tab that lives there', async () => {
const store = createSidebarStore()
const { service } = spyService(store)
+75 -7
View File
@@ -84,16 +84,16 @@ class FakeSocket {
interface Harness {
container: HTMLDivElement
/** Re-render with a new expansion set; `refreshTick` only when bumping it. */
rerender: (expanded: string[], refreshTick?: number) => void
/** Re-render with a new expansion set; `refreshTick`/`visible` only when changed. */
rerender: (expanded: string[], refreshTick?: number, visible?: boolean) => void
unmount: () => void
}
function mountTree(expanded: string[] = DIRS, refreshTick = 0): Harness {
function mountTree(expanded: string[] = DIRS, refreshTick = 0, visible = true): Harness {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
const render = (dirs: string[], tick: number): void => {
const render = (dirs: string[], tick: number, shown: boolean): void => {
root.render(createElement(FileTree, {
sessionId: 's1',
cwd: '/tmp',
@@ -105,15 +105,18 @@ function mountTree(expanded: string[] = DIRS, refreshTick = 0): Harness {
refreshTick: tick,
onUploadRequest: () => {},
busy: false,
visible: shown,
}))
}
let tick = refreshTick
act(() => { render(expanded, tick) })
let shown = visible
act(() => { render(expanded, tick, shown) })
return {
container,
rerender: (dirs: string[], nextTick?: number) => {
rerender: (dirs: string[], nextTick?: number, nextVisible?: boolean) => {
if (nextTick !== undefined) tick = nextTick
act(() => { render(dirs, tick) })
if (nextVisible !== undefined) shown = nextVisible
act(() => { render(dirs, tick, shown) })
},
unmount: () => { act(() => { root.unmount() }); container.remove() },
}
@@ -232,6 +235,71 @@ describe('FileTree level loading is batched', () => {
expect(batchPaths(0)).toEqual(['/tmp', ...DIRS].sort())
})
it('does no work while parked, then re-lists the watched set in ONE request when shown', async () => {
// The host keeps every visited tab body mounted. A parked tree must not
// answer refresh ticks or expansion changes (they are other tabs' work),
// and coming back must not fire one request per watched directory.
harness = mountTree(DIRS, 0, false)
await flush()
expect(fsTrees).not.toHaveBeenCalled()
// Another tab of the same session expands a directory while this one is
// parked: the change is dropped, and the same expansion array is handed
// back when the tab returns (the shell keeps the session state's identity).
const parkedExpanded = [...DIRS, '/tmp/d9']
harness.rerender(parkedExpanded, 1, false)
await flush()
expect(fsTrees).not.toHaveBeenCalled()
harness.rerender(parkedExpanded, 1, true)
await flush()
expect(fsTrees).toHaveBeenCalledTimes(1)
expect(batchPaths(0)).toEqual(['/tmp', ...DIRS, '/tmp/d9'].sort())
expect(fsTree).not.toHaveBeenCalled()
})
it('stops the compact fold-chain preload while parked', async () => {
// A fold chain is preloaded link by link: each level that lands reveals the
// next one. When an in-flight level returns AFTER the tab was parked, the
// chain used to keep walking off screen (up to MAX_COMPACT_DEPTH levels).
const dir = (path: string, compact: boolean): Record<string, unknown> => ({
name: path.slice(path.lastIndexOf('/') + 1), path, isDir: true, hidden: false, compact,
})
const compactLevel = (path: string): Record<string, unknown> => {
if (path === '/tmp') return { path, entries: [dir('/tmp/a', true)], truncated: false }
if (path === '/tmp/a') return { path, entries: [dir('/tmp/b', true)], truncated: false }
if (path === '/tmp/b') return { path, entries: [{ name: 'file.ts', path: '/tmp/b/file.ts', isDir: false }], truncated: false }
return { path, entries: [], truncated: false }
}
let release: (() => void) | undefined
fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => {
// Hold the first fold link open so it can land after the park.
if (paths.length === 1 && paths[0] === '/tmp/a') {
await new Promise<void>(resolve => { release = resolve })
}
return { levels: paths.map(path => compactLevel(path)) }
})
harness = mountTree([], 0)
await flush()
// Root + the first fold link (`/tmp/a`, held open).
expect(fsTrees).toHaveBeenCalledTimes(2)
expect(release).toBeDefined()
harness.rerender([], 0, false)
await act(async () => { release!() })
await flush()
const parkedCalls = fsTrees.mock.calls.length
expect(fsTrees.mock.calls.some(call => (call[1] as string[]).includes('/tmp/b')),
'a parked tree must not walk the next fold link').toBe(false)
// Coming back resumes the chain (the root re-list re-reveals the frontier).
harness.rerender([], 0, true)
await flush()
expect(fsTrees.mock.calls.length).toBeGreaterThan(parkedCalls)
expect(fsTrees.mock.calls.some(call => (call[1] as string[]).includes('/tmp/b'))).toBe(true)
})
it('re-lists ONLY the stale level when the directory watcher reports one', async () => {
harness = mountTree(DIRS)
await flush()
+6 -6
View File
@@ -57,7 +57,7 @@ class FakeSocket {
}
}
function Probe(props: { dirs: string[]; root: string | undefined; visible: boolean; onStale: (dir: string) => void }): ReactNode {
function Probe(props: { dirs: string[]; root: string | undefined; visible: boolean; onStale: (dirs: readonly string[]) => void }): ReactNode {
useDirectoryWatch({
sessionId: 's1',
root: props.root,
@@ -76,7 +76,7 @@ interface Harness {
}
function mountProbe(
onStale: (dir: string) => void,
onStale: (dirs: readonly string[]) => void,
options: { visible?: boolean; dirs?: string[]; root?: string | undefined } = {},
): Harness {
const { visible = true, dirs = ['/tmp/a'] } = options
@@ -184,7 +184,7 @@ describe('useDirectoryWatch', () => {
act(() => { socket.frame({ dir: '/tmp/a', ok: false }) })
expect(onStale).not.toHaveBeenCalled()
act(() => { socket.frame({ dir: '/tmp/a' }) })
expect(onStale).toHaveBeenCalledWith('/tmp/a')
expect(onStale).toHaveBeenCalledWith(['/tmp/a'])
// A malformed frame is ignored outright.
act(() => { socket.frame({ nope: 1 }) })
expect(onStale).toHaveBeenCalledTimes(1)
@@ -244,16 +244,16 @@ describe('useDirectoryWatch', () => {
])
// ...and every level is re-listed once: whatever changed while parked was
// seen by nobody, so the parked listing may be minutes old.
expect(onStale.mock.calls.map(([dir]) => dir)).toEqual(['/tmp', '/tmp/a', '/tmp/a/b'])
expect(onStale.mock.calls.map(([dirs]) => dirs)).toEqual([['/tmp', '/tmp/a', '/tmp/a/b']])
// Re-rendering the same inputs refreshes nothing again.
harness.rerender(['/tmp/a', '/tmp/a/b'], true)
expect(onStale).toHaveBeenCalledTimes(3)
expect(onStale).toHaveBeenCalledTimes(1)
// A parked-unparked cycle repeats exactly once more.
harness.rerender(['/tmp/a', '/tmp/a/b'], false)
harness.rerender(['/tmp/a', '/tmp/a/b'], true)
expect(onStale).toHaveBeenCalledTimes(6)
expect(onStale).toHaveBeenCalledTimes(2)
expect(FakeSocket.instances).toHaveLength(2)
harness.unmount()
})
+93
View File
@@ -507,3 +507,96 @@ describe('graph end-sentinel auto-load', () => {
} finally { hidden.unmount(); io.restore() }
})
})
/** One spacer's pixel height (absent spacer = 0). */
function spacerHeight(scroll: HTMLElement, which: 'top' | 'bottom'): number {
const node = scroll.querySelector<HTMLElement>(`[data-graph-spacer="${which}"]`)
return node === null ? 0 : Number.parseFloat(node.style.height)
}
/** jsdom ships no ResizeObserver: install a recording fake for the gate test. */
interface FakeResizeObserver {
targets: Element[]
disconnected: boolean
}
function installResizeObserver(): { observers: FakeResizeObserver[]; restore: () => void } {
const original = (globalThis as Record<string, unknown>).ResizeObserver
const observers: FakeResizeObserver[] = []
class Fake {
targets: Element[] = []
disconnected = false
constructor(public callback: ResizeObserverCallback) { observers.push(this) }
observe(target: Element): void { this.targets.push(target) }
unobserve(): void {}
disconnect(): void { this.disconnected = true }
}
;(globalThis as Record<string, unknown>).ResizeObserver = Fake
return {
observers,
restore: () => {
if (original === undefined) delete (globalThis as Record<string, unknown>).ResizeObserver
else (globalThis as Record<string, unknown>).ResizeObserver = original
},
}
}
describe('graph visibility gate', () => {
it('holds its viewport observer only while visible', async () => {
const ro = installResizeObserver()
vi.spyOn(api, 'gitGraph').mockResolvedValue(graphPage([entry(HASH_A)]))
const hidden = renderRoot(createElement(GitGraphSection, { ...defaults, visible: false }))
try {
await flush()
expect(ro.observers, 'a hidden graph holds no observer').toHaveLength(0)
} finally { hidden.unmount() }
const shown = renderRoot(createElement(GitGraphSection, defaults))
try {
await flush()
expect(ro.observers).toHaveLength(1)
expect(ro.observers[0]!.targets).toHaveLength(1)
} finally { shown.unmount(); ro.restore() }
expect(ro.observers[0]!.disconnected, 'unmount disconnects').toBe(true)
})
})
describe('graph history windowing', () => {
it('mounts only the viewport window and keeps the spacers in step with the scroll position', async () => {
// The host caps the walk at 10000 rows; 200 is already enough that the DOM
// used to grow with the history instead of the viewport.
const many = Array.from({ length: 200 }, (_, index) => entry(`${index.toString(16).padStart(8, '0')}${'f'.repeat(32)}`))
vi.spyOn(api, 'gitGraph').mockResolvedValue(graphPage(many))
const mounted = renderRoot(createElement(GitGraphSection, defaults))
try {
await flush()
const graph = mounted.container.querySelector<HTMLElement>('[data-git-graph]')!
const scroll = mounted.container.querySelector<HTMLElement>('[data-graph-scroll]')!
expect(scroll).not.toBeNull()
expect(graph.getAttribute('data-graph-count')).toBe('200')
// The row height is the component's own constant: read it off the rail
// so the test cannot drift from it.
const rowHeight = Number(scroll.querySelector('svg')!.getAttribute('height'))
expect(rowHeight).toBeGreaterThan(0)
// jsdom has no layout: clientHeight is 0, so one row plus the 8-row
// overscan band on each side mounts, and the spacers keep the height.
expect(mounted.container.querySelectorAll('[data-graph-commit]')).toHaveLength(17)
expect(spacerHeight(scroll, 'top')).toBe(0)
expect(spacerHeight(scroll, 'bottom')).toBe((200 - 17) * rowHeight)
// Scroll five pages down: only the viewport (20 rows) plus overscan mounts.
Object.defineProperty(scroll, 'clientHeight', { configurable: true, value: 20 * rowHeight })
scroll.scrollTop = 50 * rowHeight
await act(async () => {
scroll.dispatchEvent(new Event('scroll'))
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()))
})
const rendered = [...mounted.container.querySelectorAll('[data-graph-commit]')]
expect(rendered).toHaveLength(36)
expect(rendered[0]!.getAttribute('data-graph-commit')).toBe(many[42]!.hashFull)
expect(rendered.at(-1)!.getAttribute('data-graph-commit')).toBe(many[77]!.hashFull)
expect(spacerHeight(scroll, 'top')).toBe(42 * rowHeight)
expect(spacerHeight(scroll, 'bottom')).toBe((200 - 78) * rowHeight)
} finally { mounted.unmount() }
})
})
+56
View File
@@ -0,0 +1,56 @@
/**
* The commit graph mounts only the viewport window of its history rows (the
* list is unbounded: infinite scroll appends 50 at a time up to the host's
* 10000 cap, and every row carries an SVG rail). This is the pure arithmetic
* behind it — the component test in `git-graph-ui.spec.tsx` pins the wiring.
*
* The clamping cases matter: the list SHRINKS under the scroll position when
* the branch selection changes or a refresh drops the page, and the browser
* clamps `scrollTop` a frame later. A stale scrollTop must never point the
* window past the end of the new list.
*/
import { describe, expect, it } from 'vitest'
import { windowedRange } from '../src/client/changes/git-graph-windowing.ts'
const ROW = 28
describe('windowedRange', () => {
it('renders nothing for an empty list', () => {
expect(windowedRange({ count: 0, rowHeight: ROW, scrollTop: 0, viewportHeight: 560 }))
.toEqual({ start: 0, end: 0, top: 0, bottom: 0 })
})
it('mounts the whole list when it is shorter than the viewport', () => {
expect(windowedRange({ count: 10, rowHeight: ROW, scrollTop: 0, viewportHeight: 560 }))
.toEqual({ start: 0, end: 10, top: 0, bottom: 0 })
})
it('mounts the first page plus overscan before the viewport is measured', () => {
// viewportHeight 0 (jsdom, or a hidden panel): one row of view plus the
// 8-row band on each side.
expect(windowedRange({ count: 200, rowHeight: ROW, scrollTop: 0, viewportHeight: 0 }))
.toEqual({ start: 0, end: 17, top: 0, bottom: 183 * ROW })
})
it('follows the scroll position with one overscan band on each side', () => {
// 560px viewport = 20 rows; scrolled to row 50.
expect(windowedRange({ count: 200, rowHeight: ROW, scrollTop: 50 * ROW, viewportHeight: 560 }))
.toEqual({ start: 42, end: 78, top: 42 * ROW, bottom: 122 * ROW })
})
it('stops at the end of the list (no spacer below the last row)', () => {
expect(windowedRange({ count: 200, rowHeight: ROW, scrollTop: 199 * ROW, viewportHeight: 560 }))
.toEqual({ start: 191, end: 200, top: 191 * ROW, bottom: 0 })
})
it('clamps a stale scrollTop that outlived a shrinking list', () => {
// Branch switch: 200 rows -> 5 rows, the browser has not clamped yet.
expect(windowedRange({ count: 5, rowHeight: ROW, scrollTop: 100_000, viewportHeight: 560 }))
.toEqual({ start: 4, end: 5, top: 4 * ROW, bottom: 0 })
})
it('honours an explicit overscan (0 = exactly the viewport)', () => {
expect(windowedRange({ count: 200, rowHeight: ROW, scrollTop: 50 * ROW, viewportHeight: 560, overscan: 0 }))
.toEqual({ start: 50, end: 70, top: 50 * ROW, bottom: 130 * ROW })
})
})
+34
View File
@@ -32,6 +32,20 @@ const markdownRenders = vi.hoisted(() => ({
calls: [] as Array<{ text: string; streaming: boolean | undefined }>,
}))
/** How many times the session-scoped prose pass ran (one call per row rewritten). */
const rewriteCalls = vi.hoisted(() => ({ count: 0 }))
vi.mock('../src/client/markdown-images.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/client/markdown-images.ts')>()
return {
...actual,
rewriteProseLocalImageUrls: (...args: Parameters<typeof actual.rewriteProseLocalImageUrls>) => {
rewriteCalls.count += 1
return actual.rewriteProseLocalImageUrls(...args)
},
}
})
vi.mock('@deepseek-ai/dsh-client-ui-primitives', async (importOriginal) => {
const actual = await importOriginal<typeof import('@deepseek-ai/dsh-client-ui-primitives')>()
const react = await import('react')
@@ -157,6 +171,26 @@ describe('SideChatView markdown re-parse (C3)', () => {
view.unmount()
})
it('does not re-run the prose rewrite for unchanged rows on a composer keystroke', async () => {
harness.wire.events = settledConversation()
const view = harness.mount()
await harness.flush()
// Guard: the rewrite really ran for the mounted rows (a mock that never
// applied would make the zero-delta assertion vacuous).
expect(rewriteCalls.count).toBeGreaterThan(0)
rewriteCalls.count = 0
harness.typeComposer('a')
await harness.flush()
harness.typeComposer('ab')
await harness.flush()
expect(harness.composerValue()).toBe('ab')
expect(rewriteCalls.count, 'a composer keystroke re-ran the prose rewrite for unchanged rows').toBe(0)
view.unmount()
})
it('passes streaming to an unsettled live row and not to the settled message', async () => {
const settled = 'settled-answer'
const live = 'live-token'
+116
View File
@@ -614,6 +614,122 @@ describe('Tasks page graph interactions and team board', () => {
unmount()
})
it('coalesces wheel zooms into one update per animation frame without losing steps', async () => {
const store = makeStore(snapshotWithChildren(2))
const { container, unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
)
const canvas = container.querySelector('[role="group"]') as HTMLElement
const inner = canvas.querySelector('div[style*="transform"]') as HTMLElement
const scaleOf = (style: string | null): number => Number(/scale\(([\d.]+)\)/.exec(style ?? '')?.[1] ?? NaN)
await act(async () => { await new Promise<void>(resolve => requestAnimationFrame(() => resolve())) })
const settled = inner.getAttribute('style')
const baseScale = scaleOf(settled)
// A trackpad reports several wheel events between two frames. None may
// commit on its own, and the frame must apply the SUM of the deltas (the
// old code re-read the drawn transform for every event, so only one step
// survived).
const steps = 5
await act(async () => {
for (let step = 0; step < steps; step += 1) {
canvas.dispatchEvent(new WheelEvent('wheel', {
deltaY: -10, clientX: 100, clientY: 100, bubbles: true, cancelable: true,
}))
}
})
expect(inner.getAttribute('style'), 'no commit before the frame').toBe(settled)
await act(async () => { await new Promise<void>(resolve => requestAnimationFrame(() => resolve())) })
const afterFrame = scaleOf(inner.getAttribute('style'))
expect(afterFrame, 'the frame applies the batch').not.toBe(baseScale)
// One event per frame would give base * e^0.014; the coalesced frame gives
// base * e^(0.014 * steps).
expect(afterFrame).toBeCloseTo(baseScale * Math.exp(0.014 * steps), 3)
unmount()
})
/** The canvas transform as numbers (the style is `translate(x, y) scale(k)`). */
function transformOf(style: string | null): { x: number; y: number; k: number } {
const match = /translate\(([-\d.]+)px, ([-\d.]+)px\) scale\(([\d.]+)\)/.exec(style ?? '')
return { x: Number(match?.[1]), y: Number(match?.[2]), k: Number(match?.[3]) }
}
it('makes a coalesced wheel frame equivalent to rendering each step', async () => {
const store = makeStore(snapshotWithChildren(2))
const settle = async (): Promise<void> => {
await act(async () => { await new Promise<void>(resolve => requestAnimationFrame(() => resolve())) })
}
const wheel = (canvas: HTMLElement, deltaY: number): void => {
canvas.dispatchEvent(new WheelEvent('wheel', {
deltaY, clientX: 200, clientY: 200, bubbles: true, cancelable: true,
}))
}
const mount = (): { canvas: HTMLElement; inner: HTMLElement; unmount: () => void } => {
const rendered = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
)
const canvas = rendered.container.querySelector('[role="group"]') as HTMLElement
const inner = canvas.querySelector('div[style*="transform"]') as HTMLElement
return { canvas, inner, unmount: rendered.unmount }
}
// One event per frame: the reference the coalesced frame must match.
const sequential = mount()
await settle()
// Zoom out far enough that the first step hits the pan bound (PAN_KEEP=72
// with a zero-width jsdom canvas), then zoom back in around the same point.
await act(async () => { wheel(sequential.canvas, 990) })
await settle()
await act(async () => { wheel(sequential.canvas, -290) })
await settle()
const stepwise = transformOf(sequential.inner.getAttribute('style'))
sequential.unmount()
// Both events in one frame must compose to the SAME transform. Clamping
// only the final value (instead of each step) lands elsewhere once the
// intermediate transform hit a pan bound.
const batched = mount()
await settle()
await act(async () => { wheel(batched.canvas, 990); wheel(batched.canvas, -290) })
await settle()
const composed = transformOf(batched.inner.getAttribute('style'))
batched.unmount()
expect(composed.k).toBeCloseTo(stepwise.k, 5)
expect(composed.x).toBeCloseTo(stepwise.x, 5)
expect(composed.y).toBeCloseTo(stepwise.y, 5)
})
it('lets a background pan own the gesture: a wheel mid-drag is ignored', async () => {
const store = makeStore(snapshotWithChildren(2))
const { container, unmount } = renderRoot(
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }),
)
const canvas = container.querySelector('[role="group"]') as HTMLElement
const inner = canvas.querySelector('div[style*="transform"]') as HTMLElement
await act(async () => { await new Promise<void>(resolve => requestAnimationFrame(() => resolve())) })
await act(async () => {
canvas.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, clientX: 5, clientY: 5 }))
window.dispatchEvent(new MouseEvent('pointermove', { bubbles: true, clientX: 205, clientY: 205 }))
})
await act(async () => { await new Promise<void>(resolve => requestAnimationFrame(() => resolve())) })
const dragged = inner.getAttribute('style')
await act(async () => {
canvas.dispatchEvent(new WheelEvent('wheel', {
deltaY: -200, clientX: 100, clientY: 100, bubbles: true, cancelable: true,
}))
})
await act(async () => { await new Promise<void>(resolve => requestAnimationFrame(() => resolve())) })
expect(inner.getAttribute('style'), 'the pan gesture owns the transform').toBe(dragged)
await act(async () => { window.dispatchEvent(new MouseEvent('pointerup', { bubbles: true })) })
expect(inner.getAttribute('style')).toBe(dragged)
unmount()
})
it('activates a graph node after a background pointerdown (no click theft)', async () => {
const navigation: NavigationSpy = { opened: [] }
const store = makeStore(snapshotWithChildren(1))