From 1748c7b0d47bf0c124f3b94196aef12caec101e3 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Tue, 6 Oct 2026 00:34:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(editor):=20LLM=20=E6=94=B9=E5=AE=8C?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=90=8E=E8=87=AA=E5=8A=A8=E5=88=B7=E6=96=B0?= =?UTF-8?q?=E6=AD=A3=E5=9C=A8=E7=9C=8B=E7=9A=84=E9=A2=84=E8=A7=88=EF=BC=88?= =?UTF-8?q?#855=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 模型在会话里 write/edit 一个正开着的文件后,侧栏里仍是旧内容,只能手点刷新或 关掉重开——加载 effect 的依赖里没有任何一项会因写盘而变化,keepMounted 又让 切走再切回不重挂。 信号源用插件自有的 `changes.ops` 增量流(宿主按 seq > afterSeq 下发 tool/call + tool/result,客户端折成文件操作),不新增第二个轮询机制:没有 fs.watch,也没有 任何周期性的 fsRead 指纹轮询。 - 新增 src/client/ops-stream.ts:每会话一条流 + 成员选举一个 leader,只有 leader 跑 usePolling(self-scheduling,2.5s,与文件变动页会话透镜同一路由同一节奏)。 一个会话开 N 个编辑器 tab 每 tick 仍只有 1 个 changes.ops 请求;成员全部离开即 停轮询但保留游标与已发布状态,页签回来时补折离开期间错过的增量。 - 只发布结算成功的 write/edit(running === false && !isError);第一帧是基线, 打开前已结算的写入一律不触发。 - 命中判定 fileOpKey(cwd, path):resolveSidebarPath 归一相对路径 + `.`/`..` 词法 折叠 + 分隔符统一 + Windows 盘符/UNC 大小写折叠。 - EditorHost:命中且非 dirty、非编辑态时 setReloadSeq(+1)——复用页头刷新按钮那条 完全相同的加载路径,手动入口原样保留。脏态优先:dirty 时绝不覆盖用户输入。 测试 tests/editor-auto-refresh.spec.tsx(12 例,jsdom + 假计时器),逐条做了 「还原源码即红」的变异验证;#167 的既有 4 条未改动。 docs:接入指南 §5.2 与行为差异表、CHANGELOG、设计文档。 --- CHANGELOG.md | 6 + docs/external-plugin-guide.md | 3 + docs/plans/2026-10-06-editor-auto-refresh.md | 80 +++ src/client/EditorHost.tsx | 40 ++ src/client/ops-stream.ts | 292 ++++++++++ tests/editor-auto-refresh.spec.tsx | 527 +++++++++++++++++++ 6 files changed, 948 insertions(+) create mode 100644 docs/plans/2026-10-06-editor-auto-refresh.md create mode 100644 src/client/ops-stream.ts create mode 100644 tests/editor-auto-refresh.spec.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 4af2fd0f..2ccde8c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ ### Unreleased +- 🔄 **模型改完文件后,正在看的预览自己刷新**([#855](https://github.com/omdsh-dev/DSH-better-sidebar/issues/855)):此前模型在会话里 `write` / `edit` 一个你正开着的文件,侧栏里仍是旧内容,只能手点刷新(或切走再切回、关掉重开)。现在**命中即静默重载**:走页头刷新按钮那条完全相同的加载路径(同样的 `fsRead` / `load()`),因此手动刷新入口原样保留。信号来自**插件自有的会话事件增量流** `changes.ops`(不是新的文件系统观察者):宿主按 `seq > afterSeq` 增量下发 `tool/call` + `tool/result`,客户端折成文件操作后只认**结算成功**的 `write` / `edit`(`running === false && !isError`)——半写内容与失败的调用都不触发重载。**每会话一个共享轮询器**(`src/client/ops-stream.ts` 的成员选举,2.5s、self-scheduling,与文件变动页的会话透镜同一节奏、同一路由):一个会话开 N 个编辑器 tab 每 tick 仍只有 **1 个** `changes.ops` 请求,页签全部离开即停;**没有 fs.watch,也没有任何周期性的 `fsRead` 指纹轮询**。 + - **只刷新命中的那一个**:命中判定用 `resolveSidebarPath` 把模型写的相对路径按会话 cwd 归一(含 `.` / `..` 词法折叠、Windows 盘符与 UNC 大小写折叠),未命中的文件**零重读**、不重挂、不动滚动位置。 + - **脏态优先**:编辑器上报 `dirty` 时自动刷新**直接跳过**——草稿只活在编辑器实例里,重载会重挂它,用户没保存的输入永远不会被磁盘内容覆盖;处于**编辑态**(`mode === 'edit'`)同样跳过,免得光标跳走(既有的「编辑 → 预览」边沿与页头刷新按钮仍是那两条出口)。 + - **不误报历史**:流的第一帧是**基线**——打开文件之前会话里已经结算的写入一条都不会触发(该文件刚刚才被读过),只有**打开之后**才结算的动作会刷新。会话作用域按会话 id 分账,别的会话写同一个路径不会串台。 + - 🧪 测试:`tests/editor-auto-refresh.spec.tsx`(11 例,jsdom + 假计时器),每条都做了**还原源码即红**的证伪:拿掉重载调用 → 「命中即重读重渲染」与「相对路径命中」红;拿掉路径命中判定 → 「未命中零重读」红;拿掉 dirty 判定 → 「脏草稿不被覆盖」红;把每会话一条流改成全局共享 → 「另一会话写本文件不刷新」红(并带正向对照,证明两个编辑器确实都在轮询);拿掉成员选举 → 「N 个 tab 每 tick 恰 1 个请求」红(3 个 tab 变 3 个请求);拿掉编辑态判定 → 编辑态用例红;拿掉基线 → 「打开前写过的文件不被重读」红;放行 running / err 的调用 → 「结算成功才刷新」红;**塞进一个周期性 `fsRead`** → 「无事件不轮询 fsRead」红。`tests/editor-refresh.spec.tsx` 的既有 4 条(#167)未改动、仍绿。 + - ⚠️ **滚动位置与「真实浏览器」边界(如实记录)**:重载走的是既有那条加载路径(与 #167 的保存后刷新、页头刷新按钮逐字相同),所以 markdown / html **预览态**的滚动位置由 `TextEditor` 既有的模块级 per-file 滚动记忆恢复(`previewScrollMemory` + 布局 effect;jsdom 量不出 `scrollHeight`,这一层是**读源码得出、未在真机浏览器验证**);`code` 这类「编辑器就是唯一视图」的文件(`toolbar.mode` 恒为 `preview`)**无法保留光标/滚动**——重挂会回到文档开头,但**内容不会丢**(dirty 时根本不刷新)。真实浏览器里「预览是否真的刷到了新内容」这一层本轮**只在 jsdom 验证**,没有做真机点击验证。[设计文档](docs/plans/2026-10-06-editor-auto-refresh.md) - 🔗 **Markdown 里的本地 `.md` 链接改在侧栏打开,标题锚点可跳转**([#363](https://github.com/omdsh-dev/DSH-better-sidebar/issues/363)):插件自绘的四处 markdown(编辑器预览 / 侧边对话转录 / 文件变动阅读视图 / 任务笔记)原先把 `[x](./other.md)` 渲染成**不可点的纯文本**——宿主渲染器只有在 `MarkdownDelegateProvider` 提供 `openFile` 时才把本地目标变成可点元素,且它自己的 `parseFileLink` **只认行号 fragment**(`#L24`),带标题 fragment 会让整个目标判为非法,于是「点了没反应」。现在链接被判为「同文档 fragment」或「要打开的文件」:同文档的就地滚动预览**自己的滚动容器**(不用 `window.scrollTo`,也不用 `scrollIntoView`——后者会连整条侧栏一起滚),跨文件的把 fragment 以 `%23` 编码带过宿主解析器、按「会话 + 绝对路径」暂存,目标文件渲染出来后落到对应标题。 - **标题 id 现在与 GitHub 逐字一致**:`githubHeadingSlug` 改成 GitHub `github-slugger` 的真实规则——**不 trim、不折叠连续空白**(每个空格各转一个 `-`)、删 emoji 与 `\uFE0F` 等 variation selector、删标点与符号、保留任意文字系统的字母/数字/组合标记、重复标题 `-1`/`-2`,文档里已存在的显式 id 先占用。**这是本批最有用户价值的一处**:仓库自己的两份 README 目录锚点因此从 **0/15 全部失效**(点击被认领成按钮但 `scrollTop` 纹丝不动,静默 no-op)变为 **15/15 全部可用**(真实 `TextEditor` + 真实宿主 `MarkdownText` 渲染后逐个锚点点击实测)。旧实现错在两处:先 `trim` 再把空白折叠成一个 `-`(GitHub 两者都不做,`## 🛠️ Development & Build` 的真实 id 是 `-development--build`),以及保留 `\p{M}` 而把 VS16 留在 id 里(`🖼️ 特性巡礼` 曾得到含不可见字符的 `"\uFE0F-特性巡礼"`)。 - 🧹 `` 这类空显式锚点(GitHub README 常用)被标为 `hidden`——不再占版面,id 仍在,`#x` 深链照旧。 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 051a2522..ac3fee43 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -27,6 +27,7 @@ | 跨会话打开 | 目标会话的右侧栏 store 未挂载时,打开会排队到该会话上屏后重放 | | 内置类型接管 | 插件的 `editor` 类型以 `extension` 优先级认领 `dsh-resource://file/**`(压过内置 `ui-sidebar-documentpreview` 的 `text` 预览——即 `fallback` 带),并接管内置 `files` 页面 kind(`openTab('files')` 打开插件的文件树);插件卸载/禁用时内置实现自动复位。**但认领是有选择的**:宿主自己的文档预览已经覆盖的格式(表格 / PDF / 图片 / Office,清单见 §5.4)由 `editor.canOpen` 主动**拒绝**,地址交回内置 `text` 档 | | 文件树实时刷新(v0.21.1+) | 插件接管了内置 `files` 页,所以宿主自己的按目录 watch 覆盖不到这棵树——插件自带一条 `/sidebar/ws/fs-watch` socket:客户端上报**已展开**的目录集,宿主侧按目录 `fs.watch`(150ms 去抖、每连接上限 64 个句柄),变动后只让那一层缓存失效并重列;目录折叠即退订。路径仍走 `fs.tree` 同一套词法解析 | +| 编辑器预览自动刷新(#855) | 模型在会话里改完文件后,**正在看的那个预览**自己刷新,不必再手点刷新或重开文件。信号是插件自有的会话事件增量流 `changes.ops`(宿主 `src/index.ts` 路由),**每会话一个共享轮询器**(N 个编辑器 tab 每 tick 仍只有 1 个请求,全部隐藏即停),**不新增 fs.watch / fsRead 指纹轮询**。只有 `write` / `edit` **结算成功**且路径命中本页文件的那些调用会触发重载(走既有的 `fsRead`/`load` 路径),未命中的文件零重读;**dirty 草稿与编辑态一律跳过**(脏态优先)。第三方 viewer 要保住自己的草稿就必须如实上报 `onToolbarState.dirty` / `mode`,见 §5.2 | | 地址里的行号(#826) | 宿主的 markdown 链接语法只认 GitHub 的 `#L131` 片段,`path:131` 形式(编译器诊断 / `grep` 的写法,模型输出很常见)会被当成**文件名的一部分**送进地址。插件的 `editor` 类型在把地址转成合成记录时把尾部行号规格(`:行` / `:起-止` / `:行:列`)切掉,tab 标题同样按切完的文件名给——否则点开就是一个报「文件不存在」的 `x.c:131`。切分只在这一步发生(`src/client/path-line.ts`),文件树 / 搜索 / 插件自有流程的路径不经过它;代价是**从聊天链接**打开一个真名以 `:数字` 结尾的文件会丢掉后缀(Windows 上 `:` 本就不是合法文件名字符) | | 链接接管(v0.21.1+) | DOM 层只接管**有类型通过 `urlTarget` 声明认领**的外链(Ctrl/Cmd/Shift/Alt 点击一律放行);一个都没认领到时**不阻止默认行为**,交回宿主。见 §4.1 的 `urlTarget` | | path 种子的去向(v0.19.2+) | `path` seed 的含义**跟随类型**:只有 `editor`(唯一认领 `dsh-resource://file/**` 的类型)把 path 转成资源地址打开(文件落在编辑器);**其余类型保留页面型打开**,path 随导航 params 落到合成记录的 `tab.path` 供组件消费——组件型 tab 的 path seed 不会被改道到文件编辑器(v0.19.0/0.19.1 上一切 path seed 都被改道,组件从未挂载,#632) | @@ -526,6 +527,8 @@ interface FileViewerProps { } ``` +> **模型改完文件后的自动刷新(#855)**:`EditorHost` 订阅插件自有的会话事件增量流(`changes.ops`,**每会话一个共享轮询器**,2.5s 增量、无事件不落盘读),当**当前会话**的某次 `write` / `edit` 工具调用**结算成功**且路径命中本页文件时,自动重跑一次加载——即把页头的刷新按钮变成自动的(走同一条 `fetchStrategy` / `load()` 路径,`mtimeMs` 基线语义不变;命中判定用 `resolveSidebarPath` 把模型写的相对路径按会话 cwd 归一)。对第三方 viewer 有两条含义:① 你**什么都不用做**就会拿到新内容;② 若你的 viewer 持有**未保存的草稿**,必须在 `onToolbarState` 里如实上报 `dirty: true`——dirty 时自动刷新会跳过(脏态优先,绝不覆盖用户输入);未上报 dirty 的 viewer 会被重挂(页面内 state 丢失、`content` 换成新字节)。处于编辑态的 viewer 同理应上报 `mode: 'edit'`(那条也会跳过,由既有的「编辑 → 预览」边沿补刷)。 + ### 5.3 `fetchStrategy` 对照 | 策略 | 字节来源 | 传给 component 的字段 | 适用 | diff --git a/docs/plans/2026-10-06-editor-auto-refresh.md b/docs/plans/2026-10-06-editor-auto-refresh.md new file mode 100644 index 00000000..8ba0f947 --- /dev/null +++ b/docs/plans/2026-10-06-editor-auto-refresh.md @@ -0,0 +1,80 @@ +# 编辑器预览自动刷新(#855) + +> 状态:已实现(`feat/855-editor-auto-refresh`)。来源:已关闭的 PR [#216](https://github.com/omdsh-dev/DSH-better-sidebar/pull/216) +> 拆出的需求(原 PR 的信号源 `intercept.tsx` + `produced-files.ts` 已被 `58ba17d` 整体删除,剩下的只有消费端)。 +> 本实现从 `dev` 重做,信号源改用**插件自有的 `changes.ops` 增量流**。 + +## 1. 问题 + +模型在会话里 `write` / `edit` 一个你正开着的文件后,侧栏里显示的仍是旧内容:加载 effect 的依赖是 +`[scope.sessionId, scope.cwd, path, ctx, showEmpty, isDir, reloadSeq]`,写盘本身不改变其中任何一项, +`keepMounted` 又让切走再切回**不重挂**。用户的唯一出路是手点页头刷新按钮或把文件关掉重开。 + +## 2. 已核实的信号源(不自建轮询机制) + +`src/index.ts` 的 **`changes.ops`** 路由:按 `seq > afterSeq` 增量下发该会话事件日志里的 `tool/call` +与 `tool/result` 两类行(`changes/ops.ts` 的 `extractFileOps` 把它们折成带 `path` / `kind` / `running` / +`isError` 的文件操作)。这是文件变动页会话透镜已经在用的流,**插件自有、无需新宿主 API、无自写回环** +(插件自己的保存走 `/sidebar/file`,不产生会话事件)。 + +被否掉的备选: + +| 备选 | 否掉的原因 | +|---|---| +| `src/fs-watch.ts`(既有的按目录 watch) | 自述只报**目录条目表**变化,「文件夹内文件内容改写观测不到」(`fs-watch.ts:59-61`) | +| 定时 `fsRead` 指纹轮询 | `docs/plans/2026-08-19-editor-preview-refresh.md:21` 明确记为范围外;且每个编辑器 tab 都要读整文件 | +| 宿主 `ui-deliverables` / 轮尾产物行 | 不在本插件 peer 与客户端共享白名单里,会破构建纯度门;且 list 槽契约已淘汰该接管 | + +## 3. 设计(`src/client/ops-stream.ts` + `EditorHost.tsx`) + +**每会话一条流、成员选举一个 leader。** 编辑器 tab(成员)加入会话的流,只有 leader 跑 +`usePolling`(`mode: 'self-scheduling'`,2.5s,与文件变动页同一节奏;`use-polling.ts` 是侧栏唯一的轮询循环)。 +所以「一个会话开 N 个编辑器 tab」每 tick 仍只有 **1 个** `changes.ops` 请求;成员全部离开即停。 +**没有 `fs.watch`,没有任何周期性 `fsRead`。** + +**只认结算成功的写入。** `kind ∈ {write, edit}` 且 `running === false && !isError` 才发布 —— +半写内容不会进预览,失败的调用不会白发一次重载。 + +**第一帧是基线。** 新流的第一帧把所有**已经结算**的操作标记为已见、不发布任何东西:打开文件时那次 +`fsRead` 就是它的新鲜读数,历史写入不该再触发一次重读。只有**开始看之后**才结算的操作会刷新。 + +**会话作用域。** 流按 `sessionId` 分账,命中判定用 `fileOpKey(cwd, path)`(`resolveSidebarPath` 归一相对 +路径 + `.`/`..` 词法折叠 + 反斜杠统一 + Windows 盘符/UNC 大小写折叠)。别的会话写同一个路径不会串台。 + +**消费端(`EditorHost.tsx`)**:命中本页文件且**非 dirty、非编辑态**时 `setReloadSeq(+1)` —— +即复用页头刷新按钮那条完全相同的加载路径(`AbortController` 中止旧加载、重挂 viewer)。 + +## 4. 实施偏差(与 PR #216 计划的差异,均有意) + +1. **不做「每 tick 至多 1 次请求」的跨页合并**:文件变动页的会话透镜保留**自己的**轮询器(它的启停条件是 + 「tab 可见 **且** 会话透镜在屏」,与编辑器的「页签在屏」是两条不同的可见性)。因此一个会话同时开着 + 文件变动页(会话透镜)与编辑器时,该会话每 tick 最多有 2 个 `changes.ops` 请求(原来就有 1 个)。 + 把两者合并到同一条流会改动一个已被 591 行 spec 钉住的既有特性(含「只在会话透镜在屏时轮询」这条断言), + 超出本 issue 的范围。**已如实记录为后续可选项。** +2. **不给 dirty 态加「有新版本」提示**:改为静默跳过。理由是加提示需要新词典 key(20 份),而 + dirty 时用户正在编辑器里,页头既有 dirty 点、刷新按钮与保存时的 `fs-conflict` 提示三条现成出口; + 「可见且不打扰」的提示方式没有不引入新 UI 与词条的现成载体。 +3. **不做「每 op 一次精读 diff」**:只做重载,不把模型写的正文直接注入预览(PR #216 也没有)。 +4. **流的记录**在最后一个成员离开后**保留**(只停轮询,并把事件窗口从 400 收窄到 32):回来时从持久化的 + `seq` 游标续拉,把离开期间错过的增量补折并发布——否则「页面停在被写过的文件上、切走再切回」会看到旧内容。 + 实测由 `tests/editor-auto-refresh.spec.tsx` 的 park/resume 用例钉住。 + +## 5. 已知边界(如实记录) + +- **`code` 文件(编辑器就是唯一视图)保留不了光标/滚动**:这类文件 `toolbar.mode` 恒为 `preview` + (模式开关不渲染),重挂会回到文档开头——**内容不会丢**(dirty 时根本不刷新)。markdown / html + **预览态**的滚动位置由 `TextEditor` 既有的模块级 per-file 滚动记忆恢复(`previewScrollMemory` + + 布局 effect),但 **jsdom 量不出 `scrollHeight`,这层是读源码得出、未在真机浏览器验证**。 +- **真实浏览器未验证**:本批只在 jsdom 里验证了行为(12 条用例 + 逐条变异证伪)。挂载 lane 证明的是 + 「打包产物在真机挂载后不 crash」,它没有模型回合,无法在 lane 里造出真实的 `tool/call`。 +- 相对路径命中需要会话 `cwd` 已知:`scope.cwd` 缺失时(极少数降级路径)模型写的相对路径无法归一, + 那一类改动不会触发刷新(绝对路径不受影响)。 + +## 6. 验证 + +- `pnpm typecheck` / `pnpm lint` / `pnpm exec vitest run --maxWorkers=3`:184 文件 2150 通过 / 13 跳过 / 0 失败。 +- `tests/editor-auto-refresh.spec.tsx`(12 例,jsdom + 假计时器),逐条做了「还原源码即红」的变异验证: + 重载调用、路径命中、dirty 判定、编辑态判定、结算判定、基线、会话分账、成员选举、park/resume 记录、 + 「无事件不轮询 fsRead」(变异方式:塞进一个周期性 `fsRead`)。 +- `tests/editor-refresh.spec.tsx`(#167 的既有 4 条)未改动、仍绿。 +- 真实挂载 lane:`DSH_CMD='npx -y --package @deepseek-ai/dsh@0.2.0-rc.1 dsh' pnpm test:mount`。 diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index b7ddb652..b44b6fad 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -35,6 +35,7 @@ import { baseName } from './FileTree.tsx' import { createFrameBatcher } from './frame-batcher.ts' import { openClaimedNativeFile, openSidebarFile } from './sidebar-file.ts' import { openWithSshActive, openWithUrl, parseOpenWithConfig, resolveOpenWithTargets } from './open-with.ts' +import { fileOpKey, useFileOpStream } from './ops-stream.ts' import { updatePluginSettings } from './plugin-settings.ts' import { createOpenInApp } from './open-in-app.ts' import { TreePanel } from './TreePanel.tsx' @@ -452,6 +453,45 @@ export function EditorHost(props: { prevSaveState.current = current }, [toolbar?.saveState, toolbar?.mode]) + // Model-write auto-refresh (issue #855): a `write` / `edit` tool call of THIS + // session that settled without an error and named THIS file reloads the + // preview — silently, through the very same load path the header's refresh + // button uses (so that manual entry keeps working untouched). + // + // The signal is the plugin's own `changes.ops` delta stream, consumed by ONE + // shared poller per session (see ops-stream.ts): this tab joins it only while + // it is on screen with a real file, so a parked tab costs no requests, and a + // tab of another session never sees these touches at all. + const ops = useFileOpStream(scope, visible && !showEmpty && !isDir) + /** The stream revision this tab's current path is known fresh at. */ + const opBaseline = useRef<{ key: string; revision: number } | null>(null) + useEffect(() => { + const key = `${scope.sessionId}\u0000${path}` + const seen = opBaseline.current + if (seen === null || seen.key !== key) { + // A (re)targeted tab has just loaded the file: only a touch published + // AFTER this moment may reload it. Without this, every already-settled + // write of the session would fire on open. + opBaseline.current = { key, revision: ops.revision } + return + } + const touch = ops.touched.get(fileOpKey(scope.cwd, path)) + if (touch === undefined || touch.revision <= seen.revision) return + // Consume the touch whatever we decide: the file on disk moved past this + // tab, and neither branch may fire twice for the same revision. + opBaseline.current = { key, revision: ops.revision } + // Dirty priority (#228, #855): a draft lives only in the editor instance, + // and reloading remounts it — the user's unsaved input must never be + // overwritten by what the model wrote. An open edit session is skipped for + // the same reason (it would drop the caret); the pre-existing + // edit→preview edge reloads on the way back, and the header's refresh + // button stays the explicit escape hatch in both cases. + if (toolbar?.dirty === true || toolbar?.mode === 'edit') return + setReloadSeq(sequence => sequence + 1) + // Granular deps: the scope object's identity churns, so only its + // sessionId / cwd fields gate this decision. + }, [ops, path, scope.sessionId, scope.cwd, toolbar?.dirty, toolbar?.mode]) + const treeOpen = treeOpenOf(tab) /** Persist the panel flag on the tab (survives reloads with the layout). */ const toggleTree = (): void => { patchMeta(ctx, tab, scope.sessionId, { treeOpen: !treeOpen }) } diff --git a/src/client/ops-stream.ts b/src/client/ops-stream.ts new file mode 100644 index 00000000..5be9401b --- /dev/null +++ b/src/client/ops-stream.ts @@ -0,0 +1,292 @@ +/** + * The session's live FILE-OPERATION stream — the signal the editor's + * auto-refresh rides (#855). + * + * The model's file tools leave their calls in the session event log, and the + * plugin's own `changes.ops` route ships that log's `tool/call` + + * `tool/result` rows as a `seq > afterSeq` delta (see `src/index.ts`). This + * module folds those deltas into "which file did the model just write or + * edit", which is the whole question an open preview has to answer. + * + * Design constraints it exists to honour: + * + * - **One poller per session, not one per tab.** The native right sidebar + * keeps every visited tab body mounted (`keepMounted`), so an N-editor + * session would otherwise run N identical `changes.ops` polls. Members + * (editor tabs) elect ONE leader per session; that leader owns the single + * `usePolling` loop and every member reads the same published state. Any + * member leaving re-elects, and the loop stops when the last one goes. + * - **The plugin's own `changes.ops` delta stream, on ONE poller per session.** + * No `fs.watch`, no `fsRead` fingerprint polling, and no per-tab interval — + * a per-tab poll would multiply the same request by the number of mounted + * editors. Requests ride `use-polling.ts` (the sidebar's one polling loop) + * on the changes tab's own 2.5s cadence, and stop entirely while no editor + * of the session is on screen. The plugin's OWN saves go through + * `/sidebar/file` and leave no session event, so a reload can never + * re-trigger itself. + * - **Settled successes only.** A `write`/`edit` call fires once its result + * landed without an error, so a half-written file never reaches a preview + * and a failed call never triggers a pointless reload. + * - **Nothing historical fires.** The first pull of a fresh stream is the + * BASELINE: every op the session already settled is recorded as seen and + * published to nobody. Only an op that settles while someone is watching + * can refresh anything. + * - **Session-scoped.** Streams are keyed by session id; a touch published + * for one session is invisible to every other session's editors. + * + * The stream record outlives its members (only the poller stops): a tab that + * becomes visible again re-joins, the leader resumes from the persisted `seq` + * cursor, and the missed delta is folded then — so a file the model rewrote + * while the tab was parked is still seen as touched. + */ +import { useCallback, useEffect, useState, useSyncExternalStore } from 'react' +import type { SidebarSessionEvent } from '../context-types.ts' +import { api, type SessionScope } from './api.ts' +import { extractFileOps, type FileOp } from './changes/ops.ts' +import { resolveSidebarPath } from './paths.ts' +import { usePolling } from './use-polling.ts' + +/** The delta cadence: the changes tab's session-lens poll of the same route. */ +export const FILE_OPS_INTERVAL_MS = 2_500 + +/** + * Events kept for cross-tick `tool/call` → `tool/result` pairing: a call may + * be delivered in one delta and settle in the next. Only the tail matters + * (a call that old has long since settled), and the bound is what keeps a + * long session's fold cheap. + */ +const EVENT_WINDOW = 400 + +/** + * Events kept once the last member goes away. The cursor, the baseline and + * the published touches all survive, so a returning tab resumes the delta it + * missed — but a session's tool traffic (write payloads, read results) must + * not be pinned for the page's lifetime just because a tab was visited. + */ +const IDLE_EVENT_WINDOW = 32 + +/** Touched paths remembered per session (oldest insertion evicted past this). */ +const TOUCH_WINDOW = 256 + +/** The op kinds that changed a file's bytes. */ +export type FileOpTouchKind = 'write' | 'edit' + +/** The newest settled write/edit of one path. */ +export interface FileOpTouch { + readonly kind: FileOpTouchKind + /** The published revision this touch belongs to (compare with a baseline). */ + readonly revision: number + /** The originating tool call's event time (epoch ms). */ + readonly time: number +} + +/** What a member reads: the published state of its session's stream. */ +export interface FileOpStreamState { + /** Monotonic per-session counter, bumped once per published delta. */ + readonly revision: number + /** Comparison key ({@link fileOpKey}) → that path's newest settled touch. */ + readonly touched: ReadonlyMap +} + +/** The state every session starts from (a stable identity: the store contract). */ +const EMPTY_STATE: FileOpStreamState = { revision: 0, touched: new Map() } + +/** + * The comparison key of one path, so a model-spelled path and an editor tab's + * absolute path meet: relative paths are resolved against the session cwd + * ({@link resolveSidebarPath}), `.`/`..` segments are folded lexically, both + * separators unify to '/', and Windows-style paths (drive letters, UNC + * shares) fold case — the same file may be spelled either way there. + * @param cwd - the session working directory (undefined = nothing to join onto). + * @param path - an absolute or session-relative path. + * @returns the comparison key (never a path to hand back to the host). + */ +export function fileOpKey(cwd: string | undefined, path: string): string { + const unified = resolveSidebarPath(cwd, path).replace(/\\/g, '/') + const windows = /^[A-Za-z]:\//.test(unified) || unified.startsWith('//') + const segments: string[] = [] + for (const segment of unified.split('/')) { + if (segment === '' || segment === '.') continue + if (segment === '..') { + segments.pop() + continue + } + segments.push(segment) + } + const key = `${unified.startsWith('/') ? '/' : ''}${segments.join('/')}` + return windows ? key.toLowerCase() : key +} + +/** One polling member: an editor tab, and the way to tell it it leads now. */ +interface Member { + /** Become (true) or stop being (false) this session's poller. */ + lead(leading: boolean): void +} + +/** One session's stream: the shared cursor, the published state, the members. */ +interface Stream { + state: FileOpStreamState + listeners: Set<() => void> + members: Set + leader: Member | undefined + /** The delivered cursor (`0` = no cursor yet, so the next pull is the baseline). */ + seq: number + /** Whether the baseline pull completed (only then may a delta publish). */ + primed: boolean + events: SidebarSessionEvent[] + /** callIds already accounted for: a settle must fire exactly once. */ + published: Set + /** The leader's cwd, used to resolve the model's own relative spellings. */ + cwd: string | undefined +} + +/** Every session's stream, alive for the page (only its poller stops). */ +const streams = new Map() + +/** The stream record of one session, created on first use. */ +function streamOf(sessionId: string): Stream { + let stream = streams.get(sessionId) + if (stream === undefined) { + stream = { + state: EMPTY_STATE, + listeners: new Set(), + members: new Set(), + leader: undefined, + seq: 0, + primed: false, + events: [], + published: new Set(), + cwd: undefined, + } + streams.set(sessionId, stream) + } + return stream +} + +/** Publish one delta's settled write/edit ops to every member of the stream. */ +function publish(stream: Stream, ops: readonly FileOp[]): void { + const revision = stream.state.revision + 1 + const touched = new Map(stream.state.touched) + // `extractFileOps` orders newest first; walking it backwards leaves the + // NEWEST op of this delta as the one recorded for a path touched twice. + for (const op of [...ops].reverse()) { + stream.published.add(op.callId) + touched.set(fileOpKey(stream.cwd, op.path), { kind: op.kind as FileOpTouchKind, revision, time: op.time }) + } + // Bound the memory of a long session. Map iteration is insertion order, and + // re-touching a path keeps its original slot, so the evicted entry is not + // strictly the oldest revision — a miss here only costs a stale preview + // until the next write of that path, never wrong content. + for (const key of touched.keys()) { + if (touched.size <= TOUCH_WINDOW) break + touched.delete(key) + } + stream.state = { revision, touched } + for (const listener of stream.listeners) listener() +} + +/** + * Fold one delta (plus the retained window) into the stream. + * @param baseline - true for a fresh stream's FIRST fold: everything already + * settled predates the editors that are joining, so it marks state without + * publishing anything. + */ +function fold(stream: Stream, events: readonly SidebarSessionEvent[], baseline: boolean): void { + const merged = [...stream.events, ...events] + stream.events = merged.length > EVENT_WINDOW ? merged.slice(merged.length - EVENT_WINDOW) : merged + const ops = extractFileOps(stream.events) + if (baseline) { + for (const op of ops) stream.published.add(op.callId) + } else { + const settled = ops.filter(op => (op.kind === 'write' || op.kind === 'edit') + && !op.running && !op.isError && !stream.published.has(op.callId)) + if (settled.length > 0) publish(stream, settled) + } + // Ops that scrolled out of the window cannot settle any more: drop their + // marks so the set can never grow past what the window can hold. + const present = new Set(ops.map(op => op.callId)) + for (const callId of stream.published) { + if (!present.has(callId)) stream.published.delete(callId) + } +} + +/** One leader's delta pull: advance the cursor, then fold (or baseline) it. */ +async function pullStream(stream: Stream, scope: SessionScope, signal: AbortSignal): Promise { + const { events, lastSeq } = await api.changesOps(scope, stream.seq, signal) + // A torn-down run's answer must never publish state: the transport may + // deliver an aborted response anyway. + if (signal.aborted === true) return + if (scope.cwd !== undefined && scope.cwd !== '') stream.cwd = scope.cwd + if (lastSeq > stream.seq) stream.seq = lastSeq + const baseline = !stream.primed + stream.primed = true + if (events.length > 0) fold(stream, events, baseline) +} + +/** + * Join one session's file-operation stream while `enabled`, and read its + * published state. Every mounted editor of a session calls this; exactly one + * of them (the elected leader) runs the poll. + * @param scope - the session whose log is watched (sessionId + cwd). + * @param enabled - whether this tab is on screen and holds a real file (a + * parked tab must not keep polling, and a folder/path-less window has no file + * to watch). + * @returns the session's published touches, stable between deltas. + */ +export function useFileOpStream(scope: SessionScope, enabled: boolean): FileOpStreamState { + const { sessionId } = scope + const [leading, setLeading] = useState(false) + + useEffect(() => { + if (!enabled || sessionId === '') { + setLeading(false) + return + } + const stream = streamOf(sessionId) + const member: Member = { lead: (value: boolean) => { setLeading(value) } } + stream.members.add(member) + if (stream.leader === undefined) { + stream.leader = member + setLeading(true) + } + return () => { + stream.members.delete(member) + if (stream.members.size === 0 && stream.events.length > IDLE_EVENT_WINDOW) { + // Nobody is watching: keep only what a settle landing right now would + // still need to pair with. The cursor and the published touches stay, + // so the missed delta is folded (and published) when a tab returns. + stream.events = stream.events.slice(stream.events.length - IDLE_EVENT_WINDOW) + } + if (stream.leader !== member) return + stream.leader = undefined + setLeading(false) + // Hand the loop to whoever is left: only a member's own hook can run it. + const next = stream.members.values().next().value as Member | undefined + if (next !== undefined) { + stream.leader = next + next.lead(true) + } + } + }, [enabled, sessionId]) + + // Granular scope fields: the scope object's identity churns every render, + // only its sessionId / cwd gate the request target. + const cwd = scope.cwd + const pull = useCallback(async (signal: AbortSignal): Promise => { + await pullStream(streamOf(sessionId), { sessionId, cwd }, signal) + }, [sessionId, cwd]) + + // Self-scheduling: at most ONE delta request in flight per session, and the + // first one runs immediately so the baseline is established before any + // delta can be mistaken for a fresh write. + usePolling(leading, pull, { intervalMs: FILE_OPS_INTERVAL_MS, mode: 'self-scheduling', immediate: true }) + + return useSyncExternalStore( + useCallback((listener: () => void) => { + const stream = streamOf(sessionId) + stream.listeners.add(listener) + return () => { stream.listeners.delete(listener) } + }, [sessionId]), + useCallback(() => streams.get(sessionId)?.state ?? EMPTY_STATE, [sessionId]), + ) +} diff --git a/tests/editor-auto-refresh.spec.tsx b/tests/editor-auto-refresh.spec.tsx new file mode 100644 index 00000000..4cec2f33 --- /dev/null +++ b/tests/editor-auto-refresh.spec.tsx @@ -0,0 +1,527 @@ +/** + * Editor preview auto-refresh (#855): a settled `write` / `edit` tool call of + * the SAME session that names THIS file reloads the preview; nothing else does. + * + * The signal is the plugin's own `changes.ops` delta stream, so every test + * drives `api.changesOps` (the host route is not part of this layer) and + * counts `api.fsRead` — the number IS the "did the preview re-read" evidence. + * Fake timers drive the shared 2.5s cadence: the tests can therefore also prove + * the absence of an fsRead poller and that N editor tabs of one session share + * ONE delta request. + */ +// @vitest-environment jsdom +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement, useEffect, useState } from 'react' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct } from './test-utils.ts' +import type { Context } from '../src/context-types.ts' +import type { SidebarSessionEvent } from '../src/context-types.ts' +import { EditorHost } from '../src/client/EditorHost.tsx' +import { createBetterSidebarService, type EditorToolbarControls, type EditorToolbarState, type FileViewerProps } from '../src/client/service.ts' +import { allLeaves, createSidebarStore, type SidebarTab } from '../src/client/state.ts' + +setupReactAct() + +const fsRead = vi.fn() +const changesOps = vi.fn() +vi.mock('../src/client/api.ts', () => ({ + api: { + fsRead: (...args: unknown[]) => fsRead(...args), + changesOps: (...args: unknown[]) => changesOps(...args), + mediaUrl: () => '', + }, +})) + +/** fsRead call count: the "did anything re-read the file" evidence. */ +function reads(): number { + return fsRead.mock.calls.length +} + +/** How many reads ONE path saw (`api.fsRead(scope, path)`). */ +function readsOf(path: string): number { + return fsRead.mock.calls.filter(call => call[1] === path).length +} + +/** One settled, successful `write` call pair (the op that must refresh). */ +function writePair(seq: number, path: string, callId = `w${seq}`): SidebarSessionEvent[] { + return [ + { + type: 'tool/call', + seq, + time: seq, + data: { name: 'write', callId, arguments: JSON.stringify({ file_path: path, content: 'model body' }) }, + }, + { + type: 'tool/result', + seq: seq + 1, + time: seq + 1, + data: { message: { role: 'tool', source: { kind: 'tool', callId }, content: [{ type: 'text', text: 'ok' }] } }, + }, + ] +} + +/** One settled, successful `edit` call pair. */ +function editPair(seq: number, path: string, callId = `e${seq}`): SidebarSessionEvent[] { + return [ + { + type: 'tool/call', + seq, + time: seq, + data: { name: 'edit', callId, arguments: JSON.stringify({ file_path: path, old_string: 'a', new_string: 'b' }) }, + }, + { + type: 'tool/result', + seq: seq + 1, + time: seq + 1, + data: { message: { role: 'tool', source: { kind: 'tool', callId }, content: [{ type: 'text', text: 'ok' }] } }, + }, + ] +} + +/** The delta one poll answers with, and the cursor it reports. */ +function delta(events: SidebarSessionEvent[], lastSeq: number): { events: SidebarSessionEvent[]; lastSeq: number } { + return { events, lastSeq } +} + +/** + * The mock viewer: a viewer-owned draft (the input) plus a hoisted toolbar, so + * a reload is observable as a REMOUNT (the draft resets to the new content) and + * a dirty state is observable exactly like the real text editor reports it. + */ +function MockViewer(props: { + content?: string + initialMode: 'preview' | 'edit' + onToolbarState?: (state: EditorToolbarState) => void + onToolbarControls?: (controls: EditorToolbarControls | null) => void +}) { + const { content, initialMode, onToolbarState, onToolbarControls } = props + const [mode, setMode] = useState<'preview' | 'edit'>(initialMode) + const [draft, setDraft] = useState(null) + const [dirty, setDirty] = useState(false) + useEffect(() => { + onToolbarState?.({ modes: true, mode, dirty, editable: true, saveState: 'idle' }) + }, [mode, dirty, onToolbarState]) + useEffect(() => { + onToolbarControls?.({ + setMode: (next) => { setMode(next) }, + save: () => { setDraft(null); setDirty(false) }, + }) + return () => { onToolbarControls?.(null) } + }, [onToolbarControls]) + return createElement('div', null, [ + createElement('span', { key: 'mode', 'data-testid': 'mode' }, `mode-${mode}`), + createElement('input', { + key: 'draft', + 'data-testid': 'draft', + value: draft ?? content ?? '', + onChange: (event: { target: { value: string } }) => { + setDraft(event.target.value) + setDirty(true) + }, + }), + ]) +} + +interface Harness { + ctx: Context + store: ReturnType + tabOf: (path: string) => SidebarTab +} + +/** One sidebar service + store; tabs are opened per file path. */ +function harness(sessionId: string): Harness { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null }) + service.registerFileViewer({ + id: 'mock-text', + exts: ['ts'], + priority: 0, + fetchStrategy: 'fsRead', + component: (props: FileViewerProps) => createElement(MockViewer, { + content: props.content, + initialMode: 'preview', + onToolbarState: props.onToolbarState, + onToolbarControls: props.onToolbarControls, + }), + }) + store.setSession(sessionId) + const ctx = { + betterSidebar: service, + sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { [sessionId]: { cwd: '/tmp' } } }) } }, + get: (name: string) => name === 'betterSidebar' ? service : undefined, + } as unknown as Context + return { + ctx, + store, + tabOf: (path: string): SidebarTab => { + ctx.betterSidebar.openTab({ type: 'editor', title: path.split('/').pop()!, path, id: `editor:${path}` }) + return allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs) + .find(tab => tab.path === path)! + }, + } +} + +/** The EditorHost element for one file of one session. */ +function editorElement(ctx: Context, sessionId: string, tab: SidebarTab, visible: boolean): ReturnType { + return createElement(EditorHost, { + ctx, + store: ctx.betterSidebar as never, + scope: { sessionId, cwd: '/tmp' }, + tab, + visible, + expanded: [], + revealed: [], + onToggleDir: () => {}, + onReferenceFile: () => {}, + }) +} + +/** Mount one EditorHost for one file of one session. */ +function mount(ctx: Context, sessionId: string, tab: SidebarTab, visible = true): ReturnType { + return renderRoot(editorElement(ctx, sessionId, tab, visible)) +} + +/** Let the mount's initial fsRead and the stream's first (baseline) pull settle. */ +async function settle(): Promise { + await act(async () => { await Promise.resolve() }) + await act(async () => { await Promise.resolve() }) +} + +/** The mounted viewer's draft input (a remount resets it to the fresh content). */ +function draftOf(container: HTMLElement): string { + return container.querySelector('[data-testid="draft"]')!.value +} + +/** Type into the viewer's draft (the user's unsaved edit). */ +function type(container: HTMLElement, text: string): void { + const input = container.querySelector('[data-testid="draft"]')! + act(() => { + const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set! + setter.call(input, text) + input.dispatchEvent(new Event('input', { bubbles: true })) + }) +} + +/** Advance the shared 2.5s cadence by `ticks` deltas and settle the answers. */ +async function tick(ticks = 1): Promise { + for (let index = 0; index < ticks; index += 1) { + await act(async () => { await vi.advanceTimersByTimeAsync(2_500) }) + } + await settle() +} + +let contentVersion = 0 + +beforeEach(() => { + vi.useFakeTimers() + contentVersion = 0 + fsRead.mockReset() + // Every read answers a NEW body: a re-read is visible in the DOM, and a + // non-re-read keeps the previous one. + fsRead.mockImplementation(async () => ({ kind: 'text', content: `body-${++contentVersion}`, truncated: false })) + changesOps.mockReset() + changesOps.mockResolvedValue(delta([], 0)) +}) + +describe('editor preview auto-refresh (#855)', () => { + it('A: a settled write of the open file re-reads and re-renders it', async () => { + const { ctx, tabOf } = harness('session-a') + const view = mount(ctx, 'session-a', tabOf('/tmp/a.ts')) + try { + await settle() + expect(reads()).toBe(1) + expect(draftOf(view.container)).toBe('body-1') + + changesOps.mockResolvedValue(delta(writePair(11, '/tmp/a.ts'), 12)) + await tick() + + expect(reads()).toBe(2) + expect(draftOf(view.container)).toBe('body-2') + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('A: a settled edit spelled relative to the session cwd hits the same file', async () => { + const { ctx, tabOf } = harness('session-a-rel') + const view = mount(ctx, 'session-a-rel', tabOf('/tmp/a.ts')) + try { + await settle() + expect(reads()).toBe(1) + + changesOps.mockResolvedValue(delta(editPair(11, 'a.ts'), 12)) + await tick() + + expect(reads()).toBe(2) + expect(draftOf(view.container)).toBe('body-2') + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('A: a file the model wrote BEFORE the tab opened is not re-read on open', async () => { + const { ctx, tabOf } = harness('session-a-baseline') + // The session's whole history already contains a write of the file the + // user is about to open: the tab's own load is that content's fresh read. + changesOps.mockResolvedValue(delta(writePair(1, '/tmp/a.ts'), 2)) + const view = mount(ctx, 'session-a-baseline', tabOf('/tmp/a.ts')) + try { + await settle() + await tick(3) + + expect(reads()).toBe(1) + expect(draftOf(view.container)).toBe('body-1') + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('A: a running or failed write refreshes nothing; its successful finish does', async () => { + const { ctx, tabOf } = harness('session-a-settle') + const view = mount(ctx, 'session-a-settle', tabOf('/tmp/a.ts')) + try { + await settle() + expect(reads()).toBe(1) + + // A call with no result yet (the file is still being written) ... + changesOps.mockResolvedValue(delta([writePair(11, '/tmp/a.ts', 'w11')[0]!], 11)) + await tick(1) + expect(reads()).toBe(1) + + // ... and one whose result reported an error (nothing was written). + changesOps.mockResolvedValue(delta([ + writePair(21, '/tmp/a.ts', 'w21')[0]!, + { + type: 'tool/result', + seq: 22, + time: 22, + data: { message: { role: 'tool', source: { kind: 'tool', callId: 'w21' }, isError: true, content: [{ type: 'text', text: 'permission denied' }] } }, + }, + ], 22)) + await tick(1) + expect(reads()).toBe(1) + + // The same call settling cleanly is the write that must refresh. + changesOps.mockResolvedValue(delta([{ + type: 'tool/result', + seq: 23, + time: 23, + data: { message: { role: 'tool', source: { kind: 'tool', callId: 'w21' }, content: [{ type: 'text', text: 'ok' }] } }, + }], 23)) + await tick(1) + expect(reads()).toBe(2) + expect(draftOf(view.container)).toBe('body-2') + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('B: a settled write of ANOTHER file re-reads nothing', async () => { + const { ctx, tabOf } = harness('session-b') + const view = mount(ctx, 'session-b', tabOf('/tmp/a.ts')) + try { + await settle() + expect(reads()).toBe(1) + + changesOps.mockResolvedValue(delta(writePair(11, '/tmp/b.ts'), 12)) + await tick(3) + + expect(reads()).toBe(1) + expect(draftOf(view.container)).toBe('body-1') + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('C: a dirty draft is never overwritten by the model writing the file', async () => { + const { ctx, tabOf } = harness('session-c') + const view = mount(ctx, 'session-c', tabOf('/tmp/a.ts')) + try { + await settle() + expect(reads()).toBe(1) + type(view.container, 'my unsaved draft') + expect(draftOf(view.container)).toBe('my unsaved draft') + + changesOps.mockResolvedValue(delta(writePair(11, '/tmp/a.ts'), 12)) + await tick(2) + + // The user's input survives: no reload, no remount, no fsRead. + expect(draftOf(view.container)).toBe('my unsaved draft') + expect(reads()).toBe(1) + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('D: another session writing this file does not refresh this session', async () => { + const a = harness('session-d-a') + const b = harness('session-d-b') + const viewA = mount(a.ctx, 'session-d-a', a.tabOf('/tmp/a.ts')) + const viewB = mount(b.ctx, 'session-d-b', b.tabOf('/tmp/b.ts')) + try { + await settle() + expect(readsOf('/tmp/a.ts')).toBe(1) + expect(readsOf('/tmp/b.ts')).toBe(1) + const bodyOfA = draftOf(viewA.container) + const bodyOfB = draftOf(viewB.container) + + // Each session's log names the OTHER session's open file: a stream that + // were shared (or subscribed with the wrong session id) would refresh + // both tabs here. + changesOps.mockImplementation(async (scope: { sessionId: string }) => scope.sessionId === 'session-d-a' + ? delta(writePair(11, '/tmp/b.ts'), 12) + : delta(writePair(21, '/tmp/a.ts'), 22)) + await tick(2) + + expect(readsOf('/tmp/a.ts')).toBe(1) + expect(readsOf('/tmp/b.ts')).toBe(1) + expect(draftOf(viewA.container)).toBe(bodyOfA) + expect(draftOf(viewB.container)).toBe(bodyOfB) + + // Positive control: the two editors ARE live and polling — session A's + // own log now touching A's file refreshes exactly that tab. + changesOps.mockImplementation(async (scope: { sessionId: string }) => scope.sessionId === 'session-d-a' + ? delta(writePair(31, '/tmp/a.ts', 'w31'), 32) + : delta([], 0)) + await tick(1) + + expect(readsOf('/tmp/a.ts')).toBe(2) + expect(readsOf('/tmp/b.ts')).toBe(1) + } finally { + viewA.unmount() + viewB.unmount() + vi.useRealTimers() + } + }) + + it('E: no delta ever polls fsRead (the refresh rides the event stream)', async () => { + const { ctx, tabOf } = harness('session-e') + const view = mount(ctx, 'session-e', tabOf('/tmp/a.ts')) + try { + await settle() + expect(reads()).toBe(1) + const pullsAfterMount = changesOps.mock.calls.length + + await tick(4) + + // The stream really did tick (so the timer is not simply dead)... + expect(changesOps.mock.calls.length).toBeGreaterThan(pullsAfterMount) + // ...and nothing on disk was probed for it. + expect(reads()).toBe(1) + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('F: N editor tabs of one session share exactly ONE delta request per tick', async () => { + const { ctx, tabOf } = harness('session-f') + const views = [ + mount(ctx, 'session-f', tabOf('/tmp/a.ts')), + mount(ctx, 'session-f', tabOf('/tmp/b.ts')), + mount(ctx, 'session-f', tabOf('/tmp/c.ts')), + ] + try { + await settle() + expect(changesOps.mock.calls.length).toBe(1) + + await tick(2) + + expect(changesOps.mock.calls.length).toBe(3) + } finally { + for (const view of views) view.unmount() + vi.useRealTimers() + } + }) + + it('F: the delta poll stops when the last editor tab goes away', async () => { + const { ctx, tabOf } = harness('session-f-stop') + const view = mount(ctx, 'session-f-stop', tabOf('/tmp/a.ts')) + await settle() + const pulls = changesOps.mock.calls.length + view.unmount() + await tick(3) + expect(changesOps.mock.calls.length).toBe(pulls) + vi.useRealTimers() + }) + + it('H: a touch that lands while the tab is parked still refreshes it on return', async () => { + const { ctx, tabOf } = harness('session-h') + const tab = tabOf('/tmp/a.ts') + const view = mount(ctx, 'session-h', tab) + try { + await settle() + expect(reads()).toBe(1) + const pullsWhileVisible = changesOps.mock.calls.length + + // The tab goes away (another tab of the same session, or its panel + // closed): the shared poller stops... + view.rerender(editorElement(ctx, 'session-h', tab, false)) + changesOps.mockResolvedValue(delta(writePair(11, '/tmp/a.ts'), 12)) + await tick(2) + expect(changesOps.mock.calls.length).toBe(pullsWhileVisible) + expect(reads()).toBe(1) + + // ...and coming back resumes the cursor: the missed write is folded then + // (the stream record outlives its members), so the tab is not stale. + view.rerender(editorElement(ctx, 'session-h', tab, true)) + await tick(1) + expect(reads()).toBe(2) + expect(draftOf(view.container)).toBe('body-2') + } finally { + view.unmount() + vi.useRealTimers() + } + }) + + it('G: an open edit session is left alone (its caret must not jump)', async () => { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab) => tab.path, component: () => null }) + service.registerFileViewer({ + id: 'mock-text', + exts: ['ts'], + priority: 0, + fetchStrategy: 'fsRead', + component: (props: FileViewerProps) => createElement(MockViewer, { + content: props.content, + initialMode: 'edit', + onToolbarState: props.onToolbarState, + onToolbarControls: props.onToolbarControls, + }), + }) + const sessionId = 'session-g' + store.setSession(sessionId) + const ctx = { + betterSidebar: service, + sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { [sessionId]: { cwd: '/tmp' } } }) } }, + get: (name: string) => name === 'betterSidebar' ? service : undefined, + } as unknown as Context + const view = mount(ctx, sessionId, (() => { + ctx.betterSidebar.openTab({ type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts' }) + return allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)[0]! + })()) + try { + await settle() + expect(reads()).toBe(1) + expect(view.container.querySelector('[data-testid="mode"]')!.textContent).toBe('mode-edit') + + changesOps.mockResolvedValue(delta(writePair(11, '/tmp/a.ts'), 12)) + await tick(2) + + // No reload while the mode toggle says "edit"; the existing edit→preview + // edge and the header's refresh button remain the entry points. + expect(reads()).toBe(1) + } finally { + view.unmount() + vi.useRealTimers() + } + }) +})