Merge PR #776: fix(native): 按会话记账 + 宿主 keepMounted,原生 tab 状态不再跨切换丢失(#636 #661)
# Conflicts: # src/client/native/index.ts # src/client/native/tab-adapter.tsx
This commit is contained in:
commit
92ab1f83b8
13 files changed
+1234
-130
No files matched your search
@@ -87,6 +87,8 @@
|
||||
7. **e2e scratch profile 的 `minimumReleaseAgeExclude` 含 `'@deepseek-ai/*'`**(`scripts/e2e-mount.sh` / `e2e-aggregate-mount.sh`,与仓库根 `pnpm-workspace.yaml` 同策):alpha 版本常在发布后 24h 内跑 lane,pnpm 11 的 `minimumReleaseAge` 默认会拒装新鲜包。
|
||||
8. **插件开发树的 dsh-* 传递 peer 需提升为 devDependencies**(alpha.3 首见):`dsh-subagent` 等 npm 包把 `dsh-attachment` 等 dsh-* 姊妹包声明为 peerDependencies(由宿主 bundle 树统一提供,宿主侧无此问题),插件仓库若只直接依赖其中一部分,其余 peer 在 pnpm 下会解析到树上残留的旧版——如 `dsh-attachment@0.1.1-rc.1` 缺 `admitPromptContent` 导出、`dsh-subagent` 产物 import 它时测试加载即崩。因此 devDependencies 需涵盖 dev 树实际触达的全部 peer(attachment / scope / session-projection / system-prompt / user-approval / util-time 等,与直接依赖同款精确钉版);**`@deepseek-ai/cordis` peer 自 alpha.3 起要求 `^4.0.2`,0.1.7-alpha.1 要求 `^4.0.3`,rc.1 起要求 `~4.0.4`**(rc.1 顺手把 vendor 一起抬了:cordis 4.0.4 / schemastery 3.18.4 / cordis-plugin-group 1.0.4 / cordis-plugin-include 1.0.9;loader 保持 1.0.5)。**rc.1 实测的教训**:只改 `dependencies` 里的 schemastery 和 peer 里的 cordis **不够**——`cordis-plugin-group` / `-include` 是 `dsh-app-boot` / `dsh-config-editor` 的**传递 peer**,pnpm 会继续沿用 lockfile 里的旧副本,`pnpm peers check` 一次报出四类 unmet peer;按本条把四个 vendor 包**显式钉进 devDependencies** 才收敛(这也是 rc.1 那条「DSH 内部引用一律精确版本」的 workspace-release-ranges 政策的直接后果)。适配新版本时先跑 `pnpm peers check`,把新失配的传递 peer 一并提升进 devDependencies。**0.1.7 新增的同类问题**见 §3.3 第 12 条(`ui-primitives` 的第二层裸 import)。例外:**`dsh-client-locale` 的 peer/devDep 允许落后于基线**的历史已消除,rc.1 起上游恢复发版,0.1.7 起与 DSH 同 tuple。
|
||||
9. **右侧栏是 DSH 原生栏,插件只提供 tab 类型**:聊天里一切文件打开(工具行 / 产物行 / 正文提及 / 行内代码路径)统一走 `ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path))`。插件的每个 `TabDescriptor` 注册成原生 tab 类型(`kind = descriptor.id`,`extension` 带)+ 原生 tab 体(`sidebar.right.pane.tab` keyed 槽,key = `dsh-better-sidebar:<id>`);`editor` 类型同时认领 `dsh-resource://file/**`(**但按 §3.2 第 5 条的清单让出一部分**),并接管内置 `files` 页面 kind(`openTab('files')` 打开插件文件树,注销即复位)。`ctx.sidebarRight.openTab/openResource/close` 只对**在屏会话**写入;跨会话用具体类上的 `openTabIn/openResourceIn/closeIn`。原生 tab 的插件侧状态在 `src/client/native/tab-adapter.tsx`。**注册必须等服务、不能等槽声明**:原生栏先声明 `sidebar.right.pane.tab` 再 `provide('sidebarRightTabs')`,真机 profile 上槽声明回调里 `ctx.get('sidebarRightTabs')` 仍是 undefined(实测 3 秒后才出现),按槽触发注册会静默什么都不注册且永不重试——用 `ctx.inject(['sidebarRightTabs'], cb)` 驱动类型注册(`tests/native-surface.spec.ts` 以「槽先触发、服务后到达」的顺序守护)。**0.1.6-alpha.2 起**:`SidebarRightGuideEntry.id` 必填且同 provider 内唯一(缺它会静默清空整个承载面);同 provider 的 guide 条目是**追加**关系,`chain` 那种「替换宿主条目」的语义只存在于 `conversation.chat.turnTail` 且已被上游改成 `list`。**0.1.7 起**:`sidebar-right` 本体的契约**零破坏**——槽名无改名、`SidebarRightTabDefinition` 没有新的必填字段、只有新增的可选 `keepMounted` 与 `ISidebarRight.mounted`,`openTabIn/openResourceIn/closeIn` 在具体 class 上字节不变;`tab.visible` 语义收紧为 `active && (...)`(全局面板/后台会话时 body 不挂载);持久化校验收紧(非根 / 列轴 / 嵌套 / 3+ docked pane 的 split 一律判非法**整份丢弃**,0.1.6 的 sidebar 自己产不出这种布局);`RightbarRoot` 现在为每个保留会话渲染一个隐藏 seat(`SidebarSessionViews`,未导出、插件拿不到)。原生 tab 体宿主 `.paneBody` 是**有确定高度的块级滚动容器**(非 flex 容器),native 适配层因此给每个 tab 体包一层 `height:100%` 的列 flex 宿主(`sidebar.module.css` 的 `.nativeTabHost`),tab 组件根继续用 `flex:1`/`height:100%`。全局面板(根级 `main` keyed 槽 + `sidebar.panellist` + `ctx.layout.selectPanel/beginNavigation`、`rightbar` 改根级并新增 `rightbar.session`)插件**不接入**,只做兼容。底部工作台的中心列锚点认 `[data-slot="main.conversation"]`(并跳过 `display: contents` 祖先,同时保留 alpha.1 的 `[data-slot="conversation"]`);文件地址语法跟随 alpha.2(`fileAddressFor` 一律 session 作用域、绝对路径保留前导 `/`、`parseFileAddress` 前缀解析并去 `?`/`#`)。**原生指南说明的 4 条上限(归属更正:这是 0.1.7-alpha.1 起就存在的既成事实,不是 rc.1 的变更)**:`ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx` 的 `MAX_DESCRIBED_ENTRIES = 4` 及其判定行在 alpha.1 / alpha.2 / rc.1 三个 tag 上**逐字相同**,宿主终端的 guide 条目(`ui-sidebar-terminal/src/client/TerminalGuide.tsx`)也是 alpha.1 就有了,`ui-sidebar-terminal/src` 在 rc.1 **零改动**。含义不变:条目 ≤ 4 条才渲染说明,更长的列表是整列丢弃而不是截断——插件默认贡献 4 个 guide 条目(文件 / 文件变动 / 任务管理 / 侧边对话),与宿主的终端条目合计后可能超过 4 条,此时说明不渲染;插件**不恢复**旧的 `nativeGuideDesc` 通用兜底句。**原生注册账本的两条不变量(v0.22.1 起,由 `tests/native-registration.spec.ts` 守护)**:① `live` 里同时装着描述符类型(键 = descriptor id)与 `files` 接管(键 = `FILES_KIND`,**永远不在 `wanted` 里**),清理循环必须**跳过 `FILES_KIND`**——它只由编辑器类型的 `wantsFiles/hasFiles` 开关分支与 seat disposer 管理;否则每次通知都会把它拆掉再重建,而 teardown 期间的那次重建会把 id 孤儿化:`tabs.register` 建在**宿主** ctx 上(宿主 ctx 此时仍活着)所以照样成功,紧随的 `ctx.slots.inject` 建在**插件** ctx 上却抛 `cannot create effect on inactive context`,`live.set` 永不执行 → 该 id 在整页生命周期内不可再注册(真实表现:`native register files error: … already registered` 刷屏 + 文件树落到宿主空态,只有刷新页面才恢复;官方桌面壳日志实证见 [docs/plans/2026-09-28-native-files-takeover-reload-leak.md](docs/plans/2026-09-28-native-files-takeover-reload-leak.md))。② 因此「注册成功一半」是**可达状态*Line truncated
|
||||
**原生 tab 的状态保留(0.1.7 起,本插件已采纳)**:插件的 tab 类型一律声明 `keepMounted: true`(描述符类型 + `files` 接管)——宿主因此把访问过的 body 挂住,同会话切 tab 不再卸载,组件态(树滚动、未保存草稿、chip 重命名)随之免费保留,**不需要**任何 module-level 记忆。三条必须同时成立的配套事实:(a)**记录不能随卸载删除**(只由 `surface.close` 与「会话消失」回收):清理循环跳过 `FILES_KIND`(该守卫由 v0.22.1 落地,见上一条不变量 ①)之后,body 在切 tab 与切会话时都只隐藏不卸载(真机日志里那对 `DISPOSE type …:files` → `register`、同键 `drop`+`mint` 正是「切回会话清零」的那一路,真机 e2e 现断言跨会话 `scrollTop` 复原),而记录按会话记账仍是抗宿主重挂的底线;(b)原生 tab id **每会话各自计数**(`tab1`…)且多会话同号并存,记录与写面一律按 `sessionId::tabId` 记账,`Surface.update/has/activate` 新增可选 `sessionId`(缺省按 `sidebarRight.mounted` 解析,多会话同名时拒绝而不是猜);(c)**展开集的权威在插件 store 的会话状态里**(v0.23.x 的 `5c95002` 落地:`attachStore` + `syncExpanded` + `getSessionStates().expanded`,由 `native/index.ts` 绑定),记录只负责**身份**与投影——两套持久化会互相打架,插件不自持「每记录的展开集」。设计过程与实测见 [docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md](docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md)。
|
||||
|
||||
10. **自定义种子必须带 fork 标记对(`meta.isSeeded: true` + `inheritedEventCount`)**:dsh-session 契约「只给 seed 不标 isSeeded,种子算重放历史而非继承前缀」——缺标记时 `Session.ownEvents()` 含整个种子,子会话的 inbox 折重放种子里的 `agent/inbox/spliced`,**继承父会话切割时刻未领取的 inbox 输入**。宿主 `session.fork`(api-session-controller)的调用即规范形态;回归由 `tests/sidechat-seed-validation.spec.ts`(真实 `Session.create` + 对 `ownEvents()` 跑 inbox 折)守护。**0.1.7 复查:`Session.create` 的五个参数与函数体逐字相同**;上游新增了 `buildForkSeed(events, boundary)` 导出,与本插件手工的 `buildSidechatInheritance` 职责重叠但**收益不明确**(插件还有 dangling-tool-call 退回结构化快照的自有需求),暂不替换。
|
||||
11. **`dsh.plugin.json` 从来不是 DSH 契约**:0.1.7 全树 grep 仍 **0 命中**。DSH 真正读的是 `package.json` 的 `dsh.bundle.patch` + `dsh.client`(`platform`/`inject`/`immediately`/`external`)+ `exports["./client"]`。`dsh.plugin.json` 只服务第三方 registry(社区市场)通道,`lib/client-registry.js` 同理;`tests/manifest-consistency.spec.ts` 守护的是这条通道的形状,不是 DSH 契约。**`dsh.manifestVersion` 也仍是「只声明、零读」**(0.1.7 的 `package-manifest` README 自己写明「Current installers and loaders do not enforce `dsh.manifestVersion` or `engines.dsh`」)。0.1.7 的官方管控面新增:`plugin-manager` 的**多 registry 回退**(`registryPlan()`:配置源 → `fallbackRegistries`(默认含 `registry.npmmirror.com`),`network`/`timeout`/`not-found`/`no-matching-version` 会自动问下一个源;`registry` 入参只存在于 Web 对话框与 `plugin_manager` 工具,**CLI 没有 registry flag**)、`waitForInstall`、以及**插件展示元数据**:`package.json#icon`(36×36、纯填充无描边、**双色渐变**——与 DSH 自带的 `PluginArtwork*` 同风格:它们「carry their own brand colors instead of riding currentColor」,且每个都是多色,单色版在 30px 行内尺寸下会读成一块纯色板)+ `locale/<lang>.json` 的 `meta.title`/`description`。本插件**已采纳**(v0.21.1):`icon.svg` + `locale/en.json` + `locale/zh.json`,并由 `tests/plugin-meta.spec.ts` 守护「声明了就必须发布出去」。**rc.1 复查:`packages/boot/app-boot/src/package-meta.ts` 与 `scripts/verify-package-meta.ts` 在两个 tag 上逐字相同**(`ui-plugin-manager/src/client/presentation.ts` 只多了一段 `incompatible-version` 文案),所以上面三条硬规则与「**没有任何尺寸/渐变校验**」都仍然成立。三条硬规则:icon 必须是**包内相对路径**且写进 `files`;`locale/en.json` 是发现基线(缺它整个目录都不读);`exports` 必须暴露 `./locale/*.json` 与 `./package.json`。**所有失败都是静默的**——元数据有问题只会退化成一行纯文字,没有任何报错。`dsh.bundle.patch` 现在多了形状校验(非法值会 `throw`,引导期跳过该 bundle),本插件是合法的单字符串。
|
||||
12. **peer 声明是启动期硬约束(rc.1 起;本版最容易静默失效的一处)**:`packages/boot/app-boot/src/plugin-compatibility.ts`(rc.1 **新文件**)只做一件事——遍历 profile 行的 `peerDependencies`,对**名字为 `@deepseek-ai/dsh` 或以 `@deepseek-ai/dsh-` 开头**的条目跑 `semver.satisfies(宿主版本, range, { includePrerelease: true })`,不满足就把整行 `row.disabled = true`(group 行连 `group` 一起关掉),只在 stderr 留一行 `disabling profile plugin <label>: <reason>`。调用点:`compatibility-preflight.ts` 的 `prepareProfileEntries`(`dsh web --profile <p>` 的必经路径)、`profile.ts`(bundle 行,异常被吞成 skip,该 bundle 不再贡献 patch 层)、`agent-preset-registry/src/mount.ts`(预置行),以及 plugin-manager 的安装前/安装后校验。**四个要点**:(a)它**只读 peer,不读 `engines.dsh` / `dsh.manifestVersion`**(那两个字段仍然零读者,见第 11 条);(b)`peerDependenciesMeta.optional` **没有任何豁免**——我们那条 optional 的 `@deepseek-ai/dsh-client-ui-sidebar-right` 照样参与判定;(c)`includePrerelease` 被强制打开,判定比 npm 宽松(`^0.1.6-alpha.2` 也能满足 `0.1.7-rc.1`),但**精确版本号、或没有预发布子句的范围(如 `^0.1.7`)一定不过**;(d)豁免只能写 profile 自己的 `compatibility.json`(`dsh plugin allow-version <pkg@ver> --dsh-version <exact> --accept-risk`),没有全局开关也没有环境变量。因此本仓库的 DSH peer **一律写 `^<基线>` 浮动范围、绝不钉精确版本**(devDependencies 才用精确钉版);`tests/market-manifest.spec.ts` 新增一条守护把这条规则钉住。**`pnpm peers check` 看不到这个失败模式**:它校验的是解析出来的 dev 树,不是宿主会读的范围形状。
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
# 原生 tab 的状态保留:宿主 `keepMounted` + 按会话记账(PR #712 的重做)
|
||||
|
||||
日期:2026-09-25 分支:`fix/712-keepmounted-native-state`
|
||||
|
||||
> 本文取代 `2026-09-17-native-tab-state-retention.md`(PR #712 的 park/归档方案)。
|
||||
> 目标不变(#636 跨会话失灵 / #661 切 tab 丢状态 / 切回会话清零),
|
||||
> 但 DSH 0.1.7 的 `SidebarRightTabDefinition.keepMounted` 让宿主承担了「保活」,
|
||||
> 插件只剩两件事:**按会话区分身份**、**记录活过 body 的卸载**。
|
||||
|
||||
## 背景
|
||||
|
||||
#712 收录的三组症状:**#636** 切会话后文件浏览器点不动;**#661** 同会话切 tab
|
||||
丢状态(树展开集、就地打开的文件、chip 标题);**切回会话清零**。
|
||||
|
||||
## 事实(DSH 0.1.7-rc.1;源码 + 真机实测)
|
||||
|
||||
| 事实 | 出处 / 证据 |
|
||||
|---|---|
|
||||
| `keepMounted` 是 tab **类型**上的可选字段:被标记的 body 首次显示后**跨隐藏、切 tab 保持挂载** | `ui-sidebar-right/src/client/tab-registry.ts`;真机日志:同会话切 tab 全程无 `drop`/`mint` |
|
||||
| 切 tab 后展开集、滚动位置、chip 标题全在 → **组件态也不需要插件自保** | `tests/e2e/tree-scroll.e2e.ts` 的 tab-switch 三条断言(真机通过) |
|
||||
| 切换会话时 body 曾被重挂(`drop A::tab3` 紧跟 `mint A::tab3`)——**根因是插件自己**(见下),修掉后同一会话/跨会话都只隐藏不卸载 | 插件侧 `console.debug` 痕迹 + 页面阶段标记交错(见 §验证) |
|
||||
| 原生 tab id **每会话各自计数**(`tab1`…)→ 保留的多会话同号并存 | `dsh-client-ui-sidebar-right` 的 `createSurface()` 计数器;`keepMounted` 之后常驻 |
|
||||
| 非活动体用 `display: none` 隐藏;Chromium 恢复显示后 `scrollTop` 回原值 | `ui-dockkit` 的 `.tabCell[hidden]`;本地探针 320 → 0 → 320 |
|
||||
| `ISidebarRight.mounted` 是「哪个会话在屏」的唯一诚实来源 | 0.1.7 新增;main 已在 `surface.ts` 接线(§3.3 第 9 条) |
|
||||
|
||||
**根因二:插件自己的接管类型抖动**(本次一并修掉,也是「状态为什么过不去会话」的真答案)
|
||||
|
||||
`src/client/native/index.ts` 的 `sync()` 用「描述符清单」比对 live 注册表,而 `files`
|
||||
接管不是描述符(键是 `FILES_KIND`)——于是**每一次 store/service 通知**(会话切换、
|
||||
改设置、任何 state 变更)都会把它注销再重建:
|
||||
|
||||
```
|
||||
[mark] switching-to-B 48675
|
||||
[native] DISPOSE type dsh-better-sidebar:files 48736 ← 插件自己注销
|
||||
[native] register type dsh-better-sidebar:files 48736 ← 立刻重建
|
||||
```
|
||||
|
||||
注销即意味着该 kind 的 body 被卸载,于是**只有记录活下来、组件态(树滚动、草稿所在的
|
||||
视图)必然重建**。修法:清理循环跳过 `FILES_KIND`,它的寿命只由「编辑器类型被关闭」
|
||||
决定。修掉之后,同一次真机 lane 里跨会话的 `scrollTop` 从 0 变回 320(e2e 已固化为断言)。
|
||||
|
||||
> **归属更正(rebase 到 #777 之后)**:清理循环里那句
|
||||
> `if (descriptorId === FILES_KIND || wanted.has(descriptorId)) continue` 是 **#777**
|
||||
> (`4099700`)落进 `main` 的行——它同时修掉同一个循环的另一个后果(teardown 期间重建
|
||||
> 把该 id 孤儿化,见 `2026-09-28-native-files-takeover-reload-leak.md`),所以本 PR
|
||||
> rebase 后不再带那行代码,只保留上面这条设计与锁住它的回归 spec
|
||||
> (`tests/native-surface.spec.ts` 的「keeps the files takeover registered across a
|
||||
> Session switch pulse」:撤掉该守卫即红)。
|
||||
|
||||
> **合并最新 main 之后的分工(v0.24.1 / DSH 0.2.0-rc.1,2026-10-01)**:展开集这条线
|
||||
> `main` 已经用**另一条路**实现了——`5c95002` 把展开集搬进插件 store 的会话状态
|
||||
> (`attachStore` / `syncExpanded` / `getSessionStates().expanded`,由 `native/index.ts`
|
||||
> 绑定),于是本 PR 与它重叠的那半(「记录自己持有展开集」)**整体让给 store**;本 PR 只留
|
||||
> **身份**:`views` 键为 `sessionId::tabId`,`get/has/update/drop/versionOf/retain` 收 seat
|
||||
> 会话,`toggleExpanded(sessionId, id, path)` 用 seat 定位记录、写入 **scope 会话**的状态
|
||||
> (沿用 main 的 active-`reduce` / background-`reduceFor` 分流)。body 卸载不再
|
||||
> `records.drop`、两个 `tabs.register` 带 `keepMounted: true`,仍由本 PR 负责。两套持久化
|
||||
> 并存会互相打架,所以只留一条权威。
|
||||
|
||||
**两条推论**(都经真机验证):
|
||||
1. `keepMounted` 一旦打开,插件原先的前提「宿主同一时刻只挂载在屏会话的 body」
|
||||
不成立——A 与 B 的同号 tab 同时活着,所以键必须是 `sessionId::tabId`。
|
||||
2. 记录的寿命**不能绑在 body 上**:body 仍可能被宿主重挂(类型注销、会话销毁路径);
|
||||
记录只由「原生 tab 关闭」与「会话消失」回收。
|
||||
|
||||
## 决策
|
||||
|
||||
| 维度 | #712(park/归档,被取代) | 本方案 |
|
||||
|---|---|---|
|
||||
| 同会话切 tab 的保活 | 插件自建 `parked` 归档 + 停/取回 | **宿主 `keepMounted`**:body 不卸载 |
|
||||
| 身份 | 裸 `tabId` 单键(前提:同时只有一个会话在挂载) | **`sessionId::tabId` 复合键** |
|
||||
| 记录寿命 | 活到宿主关 tab(卸载不删)——方向正确 | 同:活到 `surface.close` / 会话消失;**卸载不删** |
|
||||
| 跨会话取回 | 归档 + 显式取回(`ensure` 里判会话) | 不需要:复合键的 `ensure` 天然命中自己的记录 |
|
||||
| 组件态(滚动/草稿/commit/worktree) | module-level 记忆(4 处 + 3 个 spec) | **不需要**:body 一直挂着(切 tab 与切会话都是,真机已验证滚动) |
|
||||
| 会话消失 | `retain(liveSessions)` 驱逐归档 | 同:驱逐复合键记录 |
|
||||
| 公开写面 | 不动签名 | `update/has/activate` **新增可选 `sessionId`**;缺省按在屏会话解析,歧义时拒绝而不是猜 |
|
||||
|
||||
**被推翻的 #712 教条**:它的 §不做第 3 条写「不做 keep-alive 式的隐藏而不卸载——
|
||||
宿主『一 pane 一 body』的挂载模型在宿主侧,插件无法单方面改变」。0.1.7 把这个开关
|
||||
(`keepMounted`)交到了 tab 类型手里,于是这一半由宿主实现,插件只留身份与寿命。
|
||||
|
||||
## 改动清单
|
||||
|
||||
| 文件 | 变更 |
|
||||
|---|---|
|
||||
| `src/client/native/index.ts` | 两个 `tabs.register` 加 `keepMounted: true`;title 槽 `inject` 带 seat `sessionId`(chip 渲染早于 body,且各会话同号并存);**`sync()` 清理循环跳过 `FILES_KIND`**(否则每次会话切换/通知都重建接管,body 被重挂) |
|
||||
| `src/client/native/tab-adapter.tsx` | `viewKey(sessionId, id)`;`ensure` 收 `sessionId`(seat)并与 `scope.sessionId`(内容命名空间)分开;`get/has/update/drop/toggleExpanded/versionOf` 收会话;新增 `retain(sessions)`;**删除 body 卸载清理** |
|
||||
| `src/client/native/surface.ts` | `close` 按会话读写;`update/has/activate` 支持显式会话(缺省按在屏/唯一命中,歧义 → false);会话列表变化与会话绑定时驱逐消失会话的记录 |
|
||||
| `src/client/service.ts` | `updateTab(tabId, patch, sessionId?)`;`activateTab` 传 `scope.sessionId`;`SidebarSurface` 三个方法新增可选 `sessionId` |
|
||||
| `src/client/{EditorHost,SideChatView,tree-mutations}.tsx/ts`、`changes/ChangesTab.tsx` | 6 个 `updateTab` 调用点带上自己的会话 |
|
||||
| **不采用** | #712 的 `parked` 归档、`FileTree` 滚动记忆、`TextEditor` 草稿归档、`GitLens` commit/worktree 记忆(约 200 行 + 3 个 spec) |
|
||||
|
||||
## 验证
|
||||
|
||||
**单测**(`tests/native-surface.spec.ts`,+9):会话隔离 3(同号会话互不继承 / 按会话
|
||||
patch 与 drop / `retain` 驱逐并通知)、表面解析 4(显式会话 / 缺省按在屏 / 歧义拒绝 /
|
||||
close 只清一个会话 + 死会话驱逐)、同屏双 seat 组件级 1(互不继承、互不覆盖、
|
||||
**卸载不忘状态**、重挂载取回自己的展开集、只有 `drop` 才忘)、接管寿命 1 条
|
||||
(**会话切换的脉冲不得重建 `files` 接管**;回退该修复该用例即红:`expected 2 to be 1`
|
||||
——`2` 就是被重建的注册次数)。
|
||||
|
||||
**真机**(`tests/e2e/tree-scroll.e2e.ts` → `scripts/e2e-mount.sh`:npm 打包 → 全新
|
||||
scratch profile → 真实 `dsh web` 钉 0.1.7-rc.1 → headless Chromium):同会话切 tab
|
||||
保住展开集/滚动/chip;**新建一个会话**后 B 不继承 A 的展开集与滚动;回到 A 时
|
||||
展开集、**滚动位置**与 chip 复原。**1 passed (1.1m)**。
|
||||
|
||||
**同一根因下的 mount lane 适配**:`tests/e2e/mount.e2e.ts` 原先用
|
||||
`getByRole('tab', { name: /Side Chat/ })` 重新激活侧边对话 tab——那条断言只在
|
||||
「切 tab 丢记录 → chip 回退到打开时的标题」时才成立。记录不再丢之后 chip 显示
|
||||
线程名,改经指南条目(`[data-sidebar-right-guide-entry="sidechat"]`)打开。
|
||||
(#712 已记录过同一处改动。)
|
||||
|
||||
**顺带修掉的 e2e 缺陷**(#712 的 lane 一直没真的切过会话):原写法按行号点「第二个
|
||||
会话」,而会话树的 treeitem 里**第一行是 workspace 行**,且**没有消息的种子会话根本
|
||||
不占行**——那次「A → B → A」实际是重选同一个会话,三条断言天然为真。现在按
|
||||
`data-row-key="session:<id>"` 认会话、用 rail 自己的 New session 建出真正的第二个
|
||||
会话,并断言「确实离开了 A」。
|
||||
|
||||
## 未覆盖(诚实记录)
|
||||
|
||||
- **编辑器未保存草稿跨会话**:接管抖动已修,但 lane 里只驱动了 `files` 接管,
|
||||
`editor` 资源 tab(草稿所在)没有被跨会话实测;若宿主在该 kind 上仍重挂 body,
|
||||
草稿仍会丢。要钉死得在 lane 里加「打开文件 → 键入 → 切会话 → 回来看内容」。
|
||||
#712 的 `editorDrafts` module 记忆是等价兜底(本轮未采用)。
|
||||
- 编辑器撤销历史/光标、浏览器前进后退历史:本来就不做(#712 §未覆盖)。
|
||||
- **内存上界**:`keepMounted` 的 body 与其记录活到 tab 关闭/会话消失,宿主没有
|
||||
LRU 上限;访问过的会话越多、`keepMounted` 类型越多,常驻越高。属宿主策略,
|
||||
插件无法单方面设界——记为已知代价。
|
||||
|
||||
## 不做
|
||||
|
||||
- 不改 DSH 源码(仓库硬约束 §1)。
|
||||
- 不删既有签名:`update/has/activate` 只**新增**可选 `sessionId`(在屏会话下与旧行为
|
||||
完全一致,外部插件不传照旧)。
|
||||
@@ -83,9 +83,15 @@ function treeWidthOf(tab: SidebarTab): number {
|
||||
: TREE_WIDTH_DEFAULT
|
||||
}
|
||||
|
||||
/** Merge a patch into the tab's persisted meta (rides the layout). */
|
||||
function patchMeta(ctx: Context, tab: SidebarTab, patch: Record<string, unknown>): void {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { ...metaOf(tab), ...patch } })
|
||||
/**
|
||||
* Merge a patch into the tab's persisted meta (rides the layout).
|
||||
*
|
||||
* `sessionId` is the seat session: native ids restart per session and every
|
||||
* visited tab's body stays mounted (0.1.7 `keepMounted`), so the tab this call
|
||||
* means must be named, not inferred from whichever seat is on screen.
|
||||
*/
|
||||
function patchMeta(ctx: Context, tab: SidebarTab, sessionId: string, patch: Record<string, unknown>): void {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { ...metaOf(tab), ...patch } }, sessionId)
|
||||
}
|
||||
|
||||
/** Clamp one dock width into the contract range. */
|
||||
@@ -177,7 +183,7 @@ export function EditorHost(props: {
|
||||
*/
|
||||
const openFile = (absolute: string): void => {
|
||||
if (inPlace) {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) })
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId)
|
||||
} else {
|
||||
openSidebarFile(ctx, scope.sessionId, absolute)
|
||||
}
|
||||
@@ -317,7 +323,7 @@ export function EditorHost(props: {
|
||||
dragRef.current = null
|
||||
setDragWidth(null)
|
||||
const finalWidth = clampTreeWidth(drag.startWidth + (drag.startX - event.clientX))
|
||||
if (finalWidth !== treeWidthOf(tab)) patchMeta(ctx, tab, { treeWidth: finalWidth })
|
||||
if (finalWidth !== treeWidthOf(tab)) patchMeta(ctx, tab, scope.sessionId, { treeWidth: finalWidth })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -399,7 +405,7 @@ export function EditorHost(props: {
|
||||
|
||||
const treeOpen = treeOpenOf(tab)
|
||||
/** Persist the panel flag on the tab (survives reloads with the layout). */
|
||||
const toggleTree = (): void => { patchMeta(ctx, tab, { treeOpen: !treeOpen }) }
|
||||
const toggleTree = (): void => { patchMeta(ctx, tab, scope.sessionId, { treeOpen: !treeOpen }) }
|
||||
const saveLabel = toolbar === null ? ''
|
||||
: toolbar.saveState === 'saving' ? t('loading')
|
||||
: toolbar.saveState === 'saved' ? t('saved')
|
||||
|
||||
@@ -436,7 +436,8 @@ export function SideChatView(props: {
|
||||
setError(null)
|
||||
try {
|
||||
const { childId } = await api.sidechatStart(scope.sessionId)
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { threadId: childId } })
|
||||
// Name the seat session: the same native id names a tab in every session.
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { threadId: childId } }, scope.sessionId)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause))
|
||||
} finally {
|
||||
@@ -460,12 +461,12 @@ export function SideChatView(props: {
|
||||
const title = threadDisplayTitle(display)
|
||||
if (title !== '' && title !== tab.title) {
|
||||
try {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { title })
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { title }, scope.sessionId)
|
||||
} catch {
|
||||
// A stale title is cosmetic; the thread keeps working.
|
||||
}
|
||||
}
|
||||
}, [summary, tab.id, tab.title, ctx])
|
||||
}, [summary, tab.id, tab.title, ctx, scope.sessionId])
|
||||
|
||||
/** One transcript pull: the thread's own events beyond the cached tail
|
||||
* (first attach = the whole seed-cut slice; polls = afterSeq deltas),
|
||||
|
||||
@@ -162,7 +162,7 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen
|
||||
const patchMeta = (patch: ChangesMeta): void => {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, {
|
||||
meta: { ...(tab.meta as ChangesMeta | undefined ?? {}), ...patch },
|
||||
})
|
||||
}, scope.sessionId)
|
||||
}
|
||||
|
||||
const chooseLens = (next: Lens): void => {
|
||||
|
||||
@@ -87,6 +87,7 @@ interface NativeTabRegistry {
|
||||
id: string
|
||||
kind: string
|
||||
multiple?: boolean
|
||||
keepMounted?: boolean
|
||||
patterns?: readonly string[]
|
||||
priority?: 'extension' | 'builtin' | 'fallback'
|
||||
canOpen?: (address: string) => boolean
|
||||
@@ -274,10 +275,14 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
|
||||
// file it shows, and the chip must be able to draw it BEFORE — and
|
||||
// without — the plugin-side record, which exists only after the body
|
||||
// has rendered (and is gone again once the body unmounts).
|
||||
inject: () => ({
|
||||
// The chip is also drawn per session and BEFORE the body, so it needs
|
||||
// its own session id: every session's tabs live in one registry, and
|
||||
// a chip that guessed the session would show another one's title.
|
||||
inject: (sessionId: string) => ({
|
||||
records,
|
||||
service,
|
||||
descriptorId: injected.descriptorId,
|
||||
sessionId,
|
||||
...(params.paramsOf === undefined ? {} : { paramsOf: params.paramsOf }),
|
||||
}),
|
||||
}, NativeTabTitle)))
|
||||
@@ -296,6 +301,11 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
|
||||
const disposeType = tabs.register({
|
||||
id,
|
||||
kind: descriptor.id,
|
||||
// 0.1.7: the host keeps a visited body MOUNTED through hiding,
|
||||
// tab selection and Session switches, so the plugin's own React state
|
||||
// (records, tree expansion, scroll, unsaved drafts) survives without
|
||||
// the adapter faking it.
|
||||
keepMounted: true,
|
||||
...(isEditor
|
||||
? {
|
||||
patterns: ['dsh-resource://file/**'],
|
||||
@@ -361,6 +371,7 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
|
||||
const disposeType = tabs.register({
|
||||
id,
|
||||
kind: FILES_KIND,
|
||||
keepMounted: true,
|
||||
priority: 'extension',
|
||||
title: () => t('files'),
|
||||
guide: [{
|
||||
@@ -398,10 +409,11 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
|
||||
wanted.set(descriptor.id, () => registerDescriptor(descriptor))
|
||||
}
|
||||
for (const [descriptorId, registration] of live) {
|
||||
// `files` is this module's OWN takeover, never a descriptor: it is
|
||||
// owned by the editor-type switch below. Re-creating it here on every
|
||||
// notification used to put its host-side type through a
|
||||
// tear-down/re-register window on each store commit — and a
|
||||
// `files` is this module's OWN takeover, never a descriptor (`wanted`
|
||||
// only ever holds descriptor ids): its lifetime belongs to the
|
||||
// editor-type switch below. Disposing it here on EVERY notification
|
||||
// (any prefs/state pulse, a Session switch included) re-mounted the
|
||||
// explorer body and lost the tree's own component state — and a
|
||||
// re-registration attempted on an already-inactive context (a plugin
|
||||
// reload) left the type registered with nobody holding its disposer,
|
||||
// so the same id could never be registered again for the rest of the
|
||||
|
||||
@@ -177,9 +177,57 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
if (!place(entry)) pending.push(entry)
|
||||
}
|
||||
|
||||
/**
|
||||
* The seat session a bare tab id belongs to.
|
||||
*
|
||||
* The public write face speaks ids without sessions (its consumer contract),
|
||||
* while records are per seat session — the same native id names a tab in
|
||||
* EVERY session. The mounted seat answers for a caller acting on what is on
|
||||
* screen; with no seat mounted (a global panel) a unique match across the
|
||||
* live sessions still resolves, and an id that names a tab in more than one
|
||||
* session resolves to none — guessing would write into another conversation.
|
||||
* @param tabId - the native tab id.
|
||||
* @param sessionId - the explicit session, when the caller has one.
|
||||
* @returns the owning session, or undefined.
|
||||
*/
|
||||
const sessionOf = (tabId: string, sessionId?: string): string | undefined => {
|
||||
if (sessionId !== undefined) return records.has(sessionId, tabId) ? sessionId : undefined
|
||||
const mounted = mountedSessionId(ctx)
|
||||
if (mounted !== undefined && records.has(mounted, tabId)) return mounted
|
||||
const byId = ctx.sessions.list.getSnapshot().byId ?? {}
|
||||
let found: string | undefined
|
||||
for (const candidate of Object.keys(byId)) {
|
||||
if (!records.has(candidate, tabId)) continue
|
||||
if (found !== undefined && found !== candidate) return undefined
|
||||
found = candidate
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget the records of sessions that no longer exist.
|
||||
*
|
||||
* A `keepMounted` body survives until its tab or its session ends, and a
|
||||
* session the user DELETED never unmounts anything the plugin can hook, so
|
||||
* its records (and their tree/edit state) would live for the life of the
|
||||
* page. The mounted session is always kept: it can be missing from `byId`
|
||||
* for a moment while the list reloads.
|
||||
*/
|
||||
const evictGoneSessions = (): void => {
|
||||
try {
|
||||
const live = new Set(Object.keys(ctx.sessions.list.getSnapshot().byId ?? {}))
|
||||
const mounted = mountedSessionId(ctx)
|
||||
if (mounted !== undefined) live.add(mounted)
|
||||
records.retain(live)
|
||||
} catch {
|
||||
// A read failure is not evidence that sessions are gone; keep everything.
|
||||
}
|
||||
}
|
||||
|
||||
// Two feeds flush the queue: the mounted seat (a session coming on screen)
|
||||
// and the session list, which also stays the pulse that picks the native
|
||||
// service up when it is provided after this surface was created.
|
||||
// service up when it is provided after this surface was created. The list
|
||||
// pulse additionally reclaims the records of sessions that are gone.
|
||||
let mountedUnsubscribe: (() => void) | undefined
|
||||
const onListChange = (): void => {
|
||||
if (mountedUnsubscribe === undefined) {
|
||||
@@ -187,8 +235,10 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
if (typeof mounted?.subscribe === 'function') mountedUnsubscribe = mounted.subscribe(flushPending)
|
||||
}
|
||||
flushPending()
|
||||
evictGoneSessions()
|
||||
}
|
||||
const unsubscribeList = ctx.sessions.list.subscribe(onListChange)
|
||||
evictGoneSessions()
|
||||
return {
|
||||
openTab({ sessionId, kind, params, revealIfOpened, preferNewPane }) {
|
||||
enqueue({ kind: 'tab', sessionId, tabKind: kind, params, revealIfOpened, preferNewPane: preferNewPane === true })
|
||||
@@ -200,9 +250,11 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
return fileAddressFor(sessionId, cwd, path)
|
||||
},
|
||||
close(sessionId, tabId) {
|
||||
const record = records.get(tabId)
|
||||
// Read through the SESSION: the same native id names a tab in every
|
||||
// session, so a bare read can hand back another session's record.
|
||||
const record = records.get(sessionId, tabId)
|
||||
if (record === undefined) return undefined
|
||||
records.drop(tabId)
|
||||
records.drop(sessionId, tabId)
|
||||
const api = controller()
|
||||
if (api !== undefined) {
|
||||
if (sessionId === mountedSessionId(ctx)) api.close(tabId)
|
||||
@@ -210,18 +262,19 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
}
|
||||
return { type: record.tab.type, title: record.tab.title }
|
||||
},
|
||||
update(tabId, patch) {
|
||||
if (!records.has(tabId)) return false
|
||||
records.update(tabId, patch)
|
||||
update(tabId, patch, sessionId) {
|
||||
const owner = sessionOf(tabId, sessionId)
|
||||
if (owner === undefined) return false
|
||||
records.update(owner, tabId, patch)
|
||||
return true
|
||||
},
|
||||
activate(tabId) {
|
||||
activate(tabId, sessionId) {
|
||||
// The native surface has no cross-pane activation face the plugin needs:
|
||||
// a tab is focused by opening its (kind, address) again, which the
|
||||
// native open already de-duplicates.
|
||||
return records.has(tabId)
|
||||
return sessionOf(tabId, sessionId) !== undefined
|
||||
},
|
||||
has: tabId => records.has(tabId),
|
||||
has: (tabId, sessionId) => sessionOf(tabId, sessionId) !== undefined,
|
||||
flushPending,
|
||||
dispose: () => {
|
||||
unsubscribeList()
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
* Nothing here is a singleton: the registry is created once per client
|
||||
* activation and handed to every registration.
|
||||
*/
|
||||
import { createElement, useEffect, useMemo, useSyncExternalStore } from 'react'
|
||||
import { createElement, useMemo, useSyncExternalStore } from 'react'
|
||||
import type { ComponentType, ReactNode } from 'react'
|
||||
import type { Context } from '../../context-types.ts'
|
||||
import type { SessionScope } from '../api.ts'
|
||||
@@ -95,16 +95,35 @@ interface View {
|
||||
version: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The record key: one native tab id names a tab in EVERY session (the host's
|
||||
* per-session counter restarts at `tab1`), and DSH 0.1.7 keeps visited bodies
|
||||
* mounted through hiding, tab selection and Session switches
|
||||
* (`SidebarRightTabDefinition.keepMounted`). Two sessions' `tab1` are therefore
|
||||
* ALIVE AT THE SAME TIME — a registry keyed by the bare id would hand one
|
||||
* session's tree/scroll/draft state to the other. The seat's session is part
|
||||
* of the record's identity.
|
||||
*/
|
||||
function viewKey(sessionId: string, id: string): string {
|
||||
return `${sessionId}::${id}`
|
||||
}
|
||||
|
||||
/** The plugin-side record registry for native tabs. */
|
||||
export interface NativeTabRecords {
|
||||
/**
|
||||
* The synthetic record for a native tab, minted on first sight and kept
|
||||
* across navigations (a navigation refreshes the seed fields, never the
|
||||
* The synthetic record for one seat's native tab, minted on first sight and
|
||||
* kept across navigations (a navigation refreshes the seed fields, never the
|
||||
* identity or a plugin-side title/meta mutation).
|
||||
* @param input - the native record and the session it lives in.
|
||||
* @param input - the native record, its seat session, and the content scope.
|
||||
* @returns the current view state.
|
||||
*/
|
||||
ensure(input: {
|
||||
/**
|
||||
* The SEAT session this tab is drawn in — the record's identity. Not to be
|
||||
* confused with `scope.sessionId`: a file address carries its own session,
|
||||
* which is the namespace its content is read/written in.
|
||||
*/
|
||||
sessionId: string
|
||||
id: string
|
||||
kind: string
|
||||
title: string
|
||||
@@ -118,14 +137,18 @@ export interface NativeTabRecords {
|
||||
*/
|
||||
mint?: () => { title?: string; meta?: unknown } | undefined
|
||||
}): View
|
||||
/** One record by native tab id. */
|
||||
get(id: string): View | undefined
|
||||
/** Whether this id belongs to a native tab (vs the plugin's own layout). */
|
||||
has(id: string): boolean
|
||||
/** One record by its seat session and native tab id. */
|
||||
get(sessionId: string, id: string): View | undefined
|
||||
/** Whether this seat session has a record for the id. */
|
||||
has(sessionId: string, id: string): boolean
|
||||
/** Merge a patch into the synthetic record (the `updateTab` path). */
|
||||
update(id: string, patch: { title?: string; path?: string; meta?: unknown }): void
|
||||
/** Forget a record (the native tab closed). */
|
||||
drop(id: string): void
|
||||
update(sessionId: string, id: string, patch: { title?: string; path?: string; meta?: unknown }): void
|
||||
/**
|
||||
* Forget one record. Called when the NATIVE TAB really closes — never from a
|
||||
* body unmount, because a Session switch remounts bodies while the reader's
|
||||
* state must survive.
|
||||
*/
|
||||
drop(sessionId: string, id: string): void
|
||||
/**
|
||||
* Bind the plugin store — the per-session state is the AUTHORITY for every
|
||||
* view's expansion set. Idempotent; the first call also subscribes to store
|
||||
@@ -133,12 +156,21 @@ export interface NativeTabRecords {
|
||||
* persisted restore) refreshes every native view.
|
||||
*/
|
||||
attachStore(store: SidebarStore): void
|
||||
/** Toggle one directory in a record's SESSION expansion set. */
|
||||
toggleExpanded(id: string, path: string): void
|
||||
/**
|
||||
* Toggle one directory in the SCOPE session's expansion set (the set every
|
||||
* view of that session mirrors); `sessionId` names the record's SEAT.
|
||||
*/
|
||||
toggleExpanded(sessionId: string, id: string, path: string): void
|
||||
/**
|
||||
* Keep only records of these sessions; the rest are forgotten. A session the
|
||||
* user deleted never unmounts anything the plugin can hook, so its records
|
||||
* (and a retained body) would otherwise live for the life of the page.
|
||||
*/
|
||||
retain(sessions: ReadonlySet<string>): void
|
||||
/** Mint the next instance number of a kind (titles like "Terminal 2"). */
|
||||
nextInstance(kind: string): number
|
||||
/** A per-record version for `useSyncExternalStore`. */
|
||||
versionOf(id: string): number
|
||||
versionOf(sessionId: string, id: string): number
|
||||
/** Subscribe to record changes (title/path/meta/expanded). */
|
||||
subscribe(listener: () => void): () => void
|
||||
}
|
||||
@@ -154,8 +186,8 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
const instances = new Map<string, number>()
|
||||
const listeners = new Set<() => void>()
|
||||
const notify = (): void => { for (const listener of listeners) listener() }
|
||||
const put = (id: string, view: View): void => {
|
||||
views.set(id, { ...view, version: view.version + 1 })
|
||||
const put = (key: string, view: View): void => {
|
||||
views.set(key, { ...view, version: view.version + 1 })
|
||||
notify()
|
||||
}
|
||||
/** The session-state authority (bound through {@link NativeTabRecords.attachStore}). */
|
||||
@@ -191,8 +223,9 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
next.subscribe(syncExpanded)
|
||||
syncExpanded()
|
||||
},
|
||||
ensure({ id, kind, title, params, scope, mint }) {
|
||||
const existing = views.get(id)
|
||||
ensure({ sessionId, id, kind, title, params, scope, mint }) {
|
||||
const key = viewKey(sessionId, id)
|
||||
const existing = views.get(key)
|
||||
if (existing === undefined) {
|
||||
const seeded = params?.title === undefined && params?.meta === undefined ? mint?.() : undefined
|
||||
const meta = params?.meta ?? seeded?.meta
|
||||
@@ -214,7 +247,7 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
revealed: [],
|
||||
version: 0,
|
||||
}
|
||||
views.set(id, minted)
|
||||
views.set(key, minted)
|
||||
return minted
|
||||
}
|
||||
// A navigation may carry new seed fields (the editor's in-place switch,
|
||||
@@ -228,48 +261,63 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
// reused for another session must not keep the previous one's set).
|
||||
const expanded = expandedOf(scope.sessionId)
|
||||
if (existing.scope.sessionId !== scope.sessionId || !samePaths(existing.expanded, expanded)) {
|
||||
views.set(id, { ...existing, scope, expanded, tab: { ...existing.tab, ...patch } })
|
||||
return views.get(id)!
|
||||
views.set(key, { ...existing, scope, expanded, tab: { ...existing.tab, ...patch } })
|
||||
return views.get(key)!
|
||||
}
|
||||
if (existing.scope.cwd !== scope.cwd) {
|
||||
views.set(id, { ...existing, scope, tab: { ...existing.tab, ...patch } })
|
||||
return views.get(id)!
|
||||
views.set(key, { ...existing, scope, tab: { ...existing.tab, ...patch } })
|
||||
return views.get(key)!
|
||||
}
|
||||
if (Object.keys(patch).length === 0) return existing
|
||||
const next: View = { ...existing, tab: { ...existing.tab, ...patch } }
|
||||
views.set(id, next)
|
||||
views.set(key, next)
|
||||
return next
|
||||
},
|
||||
get: id => views.get(id),
|
||||
has: id => views.has(id),
|
||||
update(id, patch) {
|
||||
const entry = views.get(id)
|
||||
get: (sessionId, id) => views.get(viewKey(sessionId, id)),
|
||||
has: (sessionId, id) => views.has(viewKey(sessionId, id)),
|
||||
update(sessionId, id, patch) {
|
||||
const key = viewKey(sessionId, id)
|
||||
const entry = views.get(key)
|
||||
if (entry === undefined) return
|
||||
put(id, { ...entry, tab: { ...entry.tab, ...patch } })
|
||||
put(key, { ...entry, tab: { ...entry.tab, ...patch } })
|
||||
},
|
||||
drop(id) {
|
||||
if (views.delete(id)) notify()
|
||||
drop(sessionId, id) {
|
||||
if (views.delete(viewKey(sessionId, id))) notify()
|
||||
},
|
||||
toggleExpanded(id, path) {
|
||||
const entry = views.get(id)
|
||||
toggleExpanded(sessionId, id, path) {
|
||||
const entry = views.get(viewKey(sessionId, id))
|
||||
if (entry === undefined || store === undefined) return
|
||||
const sessionId = entry.scope.sessionId
|
||||
const scopeSessionId = entry.scope.sessionId
|
||||
// The ACTIVE session goes through `reduce` (it notifies, so the native
|
||||
// views refresh through the subscription); a background session goes
|
||||
// through `reduceFor`, which deliberately stays silent — refresh here.
|
||||
if (store.getSnapshot().sessionId === sessionId) {
|
||||
if (store.getSnapshot().sessionId === scopeSessionId) {
|
||||
store.reduce(state => toggleExpanded(state, path))
|
||||
return
|
||||
}
|
||||
store.reduceFor(sessionId, state => toggleExpanded(state, path))
|
||||
store.reduceFor(scopeSessionId, state => toggleExpanded(state, path))
|
||||
syncExpanded()
|
||||
},
|
||||
retain(sessions) {
|
||||
let dropped = false
|
||||
for (const key of [...views.keys()]) {
|
||||
// The key's prefix is the seat session; a session id may itself carry
|
||||
// the separator only if the host allowed one, so split on the first.
|
||||
const separator = key.indexOf('::')
|
||||
const owner = separator === -1 ? key : key.slice(0, separator)
|
||||
if (!sessions.has(owner)) {
|
||||
views.delete(key)
|
||||
dropped = true
|
||||
}
|
||||
}
|
||||
if (dropped) notify()
|
||||
},
|
||||
nextInstance(kind) {
|
||||
const next = (instances.get(kind) ?? 0) + 1
|
||||
instances.set(kind, next)
|
||||
return next
|
||||
},
|
||||
versionOf: id => views.get(id)?.version ?? 0,
|
||||
versionOf: (sessionId, id) => views.get(viewKey(sessionId, id))?.version ?? 0,
|
||||
subscribe(listener) {
|
||||
listeners.add(listener)
|
||||
return () => { listeners.delete(listener) }
|
||||
@@ -305,10 +353,10 @@ export interface NativeBodyFrameworkProps {
|
||||
}
|
||||
|
||||
/** Subscribe a component to its own record's mutations. */
|
||||
function useRecordVersion(records: NativeTabRecords, id: string): number {
|
||||
function useRecordVersion(records: NativeTabRecords, sessionId: string, id: string): number {
|
||||
return useSyncExternalStore(
|
||||
listener => records.subscribe(listener),
|
||||
() => records.versionOf(id),
|
||||
() => records.versionOf(sessionId, id),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -323,16 +371,28 @@ function useSessionCwd(ctx: Context, sessionId: string): string | undefined {
|
||||
/**
|
||||
* One plugin tab rendered inside the native right Sidebar: the descriptor's
|
||||
* own component with the plugin's props, over a synthetic record minted from
|
||||
* the native tab and dropped when the record ends.
|
||||
* the native tab.
|
||||
*
|
||||
* The record OUTLIVES this component on purpose. `keepMounted` holds a body
|
||||
* mounted through hiding and tab switches, but a Session switch still remounts
|
||||
* it on the host side (measured: `drop`+`mint` for the SAME key inside one
|
||||
* switch), and the reader's exploration state only lives in the record. The
|
||||
* registry therefore keeps it until the tab is closed (`surface.close`) or its
|
||||
* session disappears (`retain`) — see the record registry's own notes.
|
||||
*/
|
||||
export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkProps): ReactNode {
|
||||
const { ctx, store, service, records, descriptorId, useTabInfo } = props
|
||||
const info = useTabInfo()
|
||||
const nativeTab = info.tab
|
||||
const version = useRecordVersion(records, nativeTab.id)
|
||||
const sessionId = props.sessionIdOf?.(info) ?? props.sessionId
|
||||
const cwd = useSessionCwd(ctx, sessionId)
|
||||
const scope = useMemo((): SessionScope => ({ sessionId, cwd }), [sessionId, cwd])
|
||||
// TWO sessions meet here and they are not interchangeable: the SEAT session
|
||||
// (the native column this body is drawn in) keys the record, while the SCOPE
|
||||
// session is the namespace the content is read/written in — a file address
|
||||
// carries its own session, which is the one that resolves its path.
|
||||
const seatSessionId = props.sessionId
|
||||
const scopeSessionId = props.sessionIdOf?.(info) ?? seatSessionId
|
||||
const version = useRecordVersion(records, seatSessionId, nativeTab.id)
|
||||
const cwd = useSessionCwd(ctx, scopeSessionId)
|
||||
const scope = useMemo((): SessionScope => ({ sessionId: scopeSessionId, cwd }), [scopeSessionId, cwd])
|
||||
// `version` is not read: it only forces this render when the record changed.
|
||||
void version
|
||||
const derived = props.paramsOf?.(info)
|
||||
@@ -341,6 +401,7 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
|
||||
: { ...derived, ...nativeTab.navigation.params }
|
||||
const descriptor = service.getTab(descriptorId)
|
||||
const view = records.ensure({
|
||||
sessionId: seatSessionId,
|
||||
id: nativeTab.id,
|
||||
kind: nativeTab.kind,
|
||||
title: nativeTab.title,
|
||||
@@ -353,7 +414,6 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
|
||||
return minted === null ? undefined : { title: minted.tab.title, meta: minted.tab.meta }
|
||||
},
|
||||
})
|
||||
useEffect(() => () => { records.drop(nativeTab.id) }, [records, nativeTab.id])
|
||||
if (descriptor === undefined) {
|
||||
// The orphaned fallback sits in the SAME native host as a live body, so
|
||||
// it gets the same full-height box (its own root also relies on the
|
||||
@@ -383,8 +443,8 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
|
||||
visible: nativeTab.visible,
|
||||
expanded: view.expanded,
|
||||
revealed: view.revealed,
|
||||
onToggleDir: (path: string) => { records.toggleExpanded(nativeTab.id, path) },
|
||||
onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, sessionId, cwd, path, isDir) },
|
||||
onToggleDir: (path: string) => { records.toggleExpanded(seatSessionId, nativeTab.id, path) },
|
||||
onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, scopeSessionId, cwd, path, isDir) },
|
||||
onOpenDiff: (tab: SidebarTab) => {
|
||||
service.openTab({
|
||||
type: 'diff',
|
||||
@@ -407,6 +467,14 @@ export interface NativeTitleInjected {
|
||||
readonly service: BetterSidebarService
|
||||
/** The descriptor id this title belongs to (one registration per descriptor). */
|
||||
readonly descriptorId: string
|
||||
/**
|
||||
/**
|
||||
* The seat session this chip is drawn in. The strip renders BEFORE the pane
|
||||
* body, and every session's retitled tabs live in the same registry, so the
|
||||
* chip must name its session instead of reading whichever record the id
|
||||
* happens to hit.
|
||||
*/
|
||||
readonly sessionId: string
|
||||
/**
|
||||
* The seed fields the native RECORD itself carries, when the type declares
|
||||
* them (a file address names the file the tab shows).
|
||||
@@ -435,14 +503,14 @@ export interface NativeTitleInjected {
|
||||
* cannot drift apart.
|
||||
*/
|
||||
export function NativeTabTitle(props: NativeTitleInjected & NativeBodyFrameworkProps): ReactNode {
|
||||
const { records, service, descriptorId, paramsOf, useTabInfo } = props
|
||||
const { records, service, descriptorId, sessionId, paramsOf, useTabInfo } = props
|
||||
const info = useTabInfo()
|
||||
const nativeTab = info.tab
|
||||
const version = useSyncExternalStore(
|
||||
listener => records.subscribe(listener),
|
||||
() => records.versionOf(nativeTab.id),
|
||||
() => records.versionOf(sessionId, nativeTab.id),
|
||||
)
|
||||
const record = records.get(nativeTab.id)
|
||||
const record = records.get(sessionId, nativeTab.id)
|
||||
const title = record?.tab.title ?? nativeTab.title
|
||||
// `version` is read so a title/path/meta mutation re-renders the chip; the
|
||||
// icon itself is derived from the record, never stored.
|
||||
|
||||
+27
-11
@@ -462,12 +462,18 @@ export interface SidebarSurface {
|
||||
fileAddress(sessionId: string, cwd: string | undefined, path: string): string
|
||||
/** Close one native tab; the closed record's type/title, or undefined when the id is not native. */
|
||||
close(sessionId: string, tabId: string): { type: string; title: string } | undefined
|
||||
/** Patch a native tab's plugin-side record; false when it is not native. */
|
||||
update(tabId: string, patch: { title?: string; path?: string; meta?: unknown }): boolean
|
||||
/** Focus a native tab; false when it is not native. */
|
||||
activate(tabId: string): boolean
|
||||
/** Whether a tab id belongs to the native surface. */
|
||||
has(tabId: string): boolean
|
||||
/**
|
||||
* Patch a native tab's plugin-side record; false when it is not native.
|
||||
* `sessionId` (optional) names the seat session the tab lives in: native tab
|
||||
* ids restart per session and several sessions' tabs are alive at once
|
||||
* (`keepMounted`), so a caller that knows its session should pass it.
|
||||
* Omitted, the id resolves against the mounted seat.
|
||||
*/
|
||||
update(tabId: string, patch: { title?: string; path?: string; meta?: unknown }, sessionId?: string): boolean
|
||||
/** Focus a native tab; false when it is not native (same `sessionId` rule as `update`). */
|
||||
activate(tabId: string, sessionId?: string): boolean
|
||||
/** Whether a tab id belongs to the native surface (same `sessionId` rule as `update`). */
|
||||
has(tabId: string, sessionId?: string): boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -585,8 +591,14 @@ export interface BetterSidebarService {
|
||||
getSnapshot(): SidebarSnapshot
|
||||
/** Subscribe to snapshot changes (session switch, state changes, prefs changes). Returns the disposer. */
|
||||
subscribeState(listener: () => void): () => void
|
||||
/** Update an open tab's display fields (title / path / meta); a missing tab id is a no-op. */
|
||||
updateTab(tabId: string, patch: { title?: string; path?: string; meta?: unknown }): void
|
||||
/**
|
||||
* Update an open tab's display fields (title / path / meta); a missing tab id
|
||||
* is a no-op. `sessionId` names the seat session the tab lives in — native
|
||||
* ids restart per session and several sessions' tabs stay mounted at once,
|
||||
* so a component that knows its scope should pass it; omitted, a native id
|
||||
* resolves against the mounted seat.
|
||||
*/
|
||||
updateTab(tabId: string, patch: { title?: string; path?: string; meta?: unknown }, sessionId?: string): void
|
||||
/**
|
||||
* Activate an open tab (the tab-bar activation path; fires
|
||||
* descriptor.onActivate). An unknown tab id is a strict no-op. `scope`
|
||||
@@ -1111,8 +1123,12 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
const subscribeState = (listener: () => void): (() => void) => store.subscribe(listener)
|
||||
|
||||
/** Patch an open tab's display fields (a missing tab id is a no-op). */
|
||||
const updateTab = (tabId: string, patch: { title?: string; path?: string; meta?: unknown }): void => {
|
||||
if (surface?.update(tabId, patch) === true) return
|
||||
const updateTab = (
|
||||
tabId: string,
|
||||
patch: { title?: string; path?: string; meta?: unknown },
|
||||
sessionId?: string,
|
||||
): void => {
|
||||
if (surface?.update(tabId, patch, sessionId) === true) return
|
||||
store.reduce((state) => patchTab(state, tabId, {
|
||||
...(patch.title !== undefined ? { title: patch.title } : {}),
|
||||
...(patch.path !== undefined ? { path: patch.path } : {}),
|
||||
@@ -1122,7 +1138,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
|
||||
/** Activate an open tab (the tab-bar activation path; fires onActivate). */
|
||||
const activateTab = (tabId: string, scope?: SessionScope): void => {
|
||||
if (surface?.activate(tabId) === true) return
|
||||
if (surface?.activate(tabId, scope?.sessionId) === true) return
|
||||
let activated: SidebarTab | undefined
|
||||
store.reduce((state) => {
|
||||
// Unknown tab ids are a strict no-op (no state churn / notify).
|
||||
|
||||
@@ -30,8 +30,10 @@ function pathTabsOf(snapshot: SidebarSnapshot): SidebarTab[] {
|
||||
export function retargetPathTabs(ctx: Context, store: SidebarStore, oldPath: string, newPath: string): void {
|
||||
const service = ctx.get('betterSidebar')
|
||||
if (service === undefined) return
|
||||
for (const tab of pathTabsOf(store.getSnapshot())) {
|
||||
if (tab.path === oldPath) service.updateTab(tab.id, { path: newPath, title: baseName(newPath) })
|
||||
// The tabs live in the snapshot's session: native ids restart per session.
|
||||
const snapshot = store.getSnapshot()
|
||||
for (const tab of pathTabsOf(snapshot)) {
|
||||
if (tab.path === oldPath) service.updateTab(tab.id, { path: newPath, title: baseName(newPath) }, snapshot.sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -330,8 +330,12 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async
|
||||
// The sweep opened the Side Chat type, whose view auto-creates a thread and
|
||||
// polls the transcript — that poll MUST ride the plugin's own
|
||||
// sidechat.events route (the host transport this lane locks). The poll runs
|
||||
// only while the tab is visible, so activate its chip first.
|
||||
await pane.getByRole('tab', { name: /Side Chat|侧边对话|侧边聊天/ }).first().click()
|
||||
// only while the tab is visible, so activate it first — THROUGH ITS GUIDE
|
||||
// ENTRY, not by chip text: the chip follows the thread's own display title
|
||||
// once the tab keeps its record (the state-retention fix), so `/Side Chat/`
|
||||
// no longer names it.
|
||||
if (await page.locator('[data-sidebar-right-guide]').count() === 0) await addTab.click()
|
||||
await page.locator('[data-sidebar-right-guide-entry="sidechat"]').click()
|
||||
await expect
|
||||
.poll(
|
||||
() => page.evaluate(() =>
|
||||
|
||||
@@ -0,0 +1,489 @@
|
||||
/**
|
||||
* Cross-conversation state retention, on a REAL host — the comparison the
|
||||
* review asked for: build state in conversation A, switch to conversation B,
|
||||
* switch back to A, and compare the whole observable state vector before vs
|
||||
* after.
|
||||
*
|
||||
* Why a vector and not one scalar: the host mounts ONE tab body per pane and
|
||||
* native tab ids restart in every session (`tab1`, `tab2`, …), so the entering
|
||||
* conversation's tab meets the leaving one's id. A registry keyed by the bare
|
||||
* id hands the leaving session's state to the entering one and destroys it —
|
||||
* tree expansion, the file opened in place, the unsaved commit message. A lone
|
||||
* `scrollTop` assertion cannot see any of that.
|
||||
*
|
||||
* Determinism: the workspace is seeded wide enough that the tree overflows;
|
||||
* every wait is on a DOM/poll marker; the suite is serial.
|
||||
*/
|
||||
import { appendFileSync, existsSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
|
||||
import { PAGE_URL, createHostApi, hostRpc, sendFirstMessage } from './host'
|
||||
|
||||
/** Git must not pick up the developer's identity/config inside the lane. */
|
||||
const GIT_ENV = {
|
||||
...process.env,
|
||||
GIT_CONFIG_GLOBAL: '/dev/null',
|
||||
GIT_CONFIG_SYSTEM: '/dev/null',
|
||||
}
|
||||
|
||||
/** This lane's own workspace (lanes run serially against one server). */
|
||||
const WORKSPACE_PATH = process.env.DSH_E2E_SCROLL_WORKSPACE ?? join(tmpdir(), 'dsh-e2e-scroll-workspace')
|
||||
|
||||
/** Rows seeded into the root, plus real directories to expand. */
|
||||
const ROOT_FILES = 80
|
||||
const DIRS = ['alpha', 'beta', 'gamma']
|
||||
|
||||
/** The offset written before switching away (well inside the scroll range). */
|
||||
const SCROLL_TO = 320
|
||||
|
||||
/** The tree body (its CSS-module class carries a hashed prefix). */
|
||||
/**
|
||||
* The tree body. Scoped to the VISIBLE panel: with `keepMounted` every visited
|
||||
* session keeps its seat in the DOM, so a bare class selector matches one body
|
||||
* per retained conversation.
|
||||
*/
|
||||
const TREE_BODY = '[class*="explorerBody"]:visible'
|
||||
/**
|
||||
* A directory row by its label. Directory rows carry NO `title` attribute
|
||||
* (only file rows do — they show the full path there), so a directory is
|
||||
* addressed by its name span, which is also what the reader clicks.
|
||||
*/
|
||||
function dirRow(dir: string) {
|
||||
return `${TREE_BODY} [role="button"]:has([class*="explorerName"]:text-is("${dir}"))`
|
||||
}
|
||||
/** The file row inside an expanded directory (file rows DO carry `title`). */
|
||||
function innerRow(dir: string) {
|
||||
return `${TREE_BODY} [role="button"][title$="${dir}/inner.txt"]:visible, ${TREE_BODY} [role="button"][title$="${dir}\\\\inner.txt"]:visible`
|
||||
}
|
||||
const GUIDE = '[data-sidebar-right-panel]:visible [data-sidebar-right-guide]'
|
||||
const GUIDE_FILES = '[data-sidebar-right-panel]:visible [data-sidebar-right-guide-entry="files"]'
|
||||
const SESSION_ROWS = '[role="tree"][aria-label="Sessions"] [role="treeitem"][data-row-key^="session:"]'
|
||||
|
||||
let api: APIRequestContext
|
||||
|
||||
async function seedSessions(): Promise<void> {
|
||||
mkdirSync(WORKSPACE_PATH, { recursive: true })
|
||||
for (let index = 0; index < ROOT_FILES; index++) {
|
||||
writeFileSync(join(WORKSPACE_PATH, `seed-${String(index).padStart(3, '0')}.txt`), `row ${index}\n`)
|
||||
}
|
||||
for (const dir of DIRS) {
|
||||
mkdirSync(join(WORKSPACE_PATH, dir), { recursive: true })
|
||||
writeFileSync(join(WORKSPACE_PATH, dir, 'inner.txt'), `${dir} inner\n`)
|
||||
}
|
||||
// A git repo with ONE staged change: the changes tab needs somewhere to put
|
||||
// an unsaved commit message, and staging is what enables its commit button.
|
||||
// Idempotent: the lane's workspace persists between local runs, so an
|
||||
// existing repo is reset rather than re-initialised (and `rm -rf .git` would
|
||||
// be the only way to make a fresh `git init` + first commit work again).
|
||||
const git = (...args: string[]): void => { execFileSync('git', args, { cwd: WORKSPACE_PATH, env: GIT_ENV }) }
|
||||
if (!existsSync(join(WORKSPACE_PATH, '.git'))) git('init', '-q')
|
||||
git('config', 'user.email', 'lane@example.test')
|
||||
git('config', 'user.name', 'retention lane')
|
||||
git('add', '-A')
|
||||
// The first commit may have nothing to record (a re-run of a clean repo).
|
||||
const dirty = execFileSync('git', ['status', '--porcelain'], { cwd: WORKSPACE_PATH, env: GIT_ENV }).toString()
|
||||
if (dirty.trim() !== '') git('commit', '-qm', 'seed', '--no-verify')
|
||||
appendFileSync(join(WORKSPACE_PATH, 'seed-000.txt'), 'staged change\n')
|
||||
git('add', 'seed-000.txt')
|
||||
|
||||
// A LINKED worktree: it gives the changes tab a second checkout to choose
|
||||
// from, which is the state #712 parked in a module-level map. Created last so
|
||||
// the staged change above belongs to the primary checkout only.
|
||||
const linkedPath = join(WORKSPACE_PATH, 'linked-checkout')
|
||||
if (!existsSync(linkedPath)) git('worktree', 'add', '-q', '-b', 'lane-linked', linkedPath)
|
||||
|
||||
const workspace = await hostRpc<{ workspace: { workspaceId: string } }>(api, 'workspace.create', { path: WORKSPACE_PATH })
|
||||
const workspaceId = workspace.value.workspace.workspaceId
|
||||
// ONE conversation is enough: the round trip creates its own second one
|
||||
// through the rail, because a seeded session that never received a message
|
||||
// does not get a rail row (see newConversation).
|
||||
await hostRpc(api, 'session.create', { workspaceId })
|
||||
}
|
||||
|
||||
test.beforeAll(async () => {
|
||||
api = await createHostApi()
|
||||
await seedSessions()
|
||||
})
|
||||
|
||||
test.afterAll(async () => {
|
||||
await api?.dispose()
|
||||
})
|
||||
|
||||
/** Dismiss whatever onboarding takeover is present (the other lanes' dance). */
|
||||
async function dismissOnboarding(page: Page): Promise<void> {
|
||||
try {
|
||||
await expect
|
||||
.poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 })
|
||||
.toBeGreaterThan(0)
|
||||
} catch {
|
||||
console.warn('[e2e-scroll] no onboarding takeover appeared; proceeding')
|
||||
}
|
||||
for (let round = 0; round < 8; round++) {
|
||||
let dismissed = false
|
||||
for (const name of ['Continue', 'Configure later']) {
|
||||
const button = page.getByRole('button', { name, exact: true }).first()
|
||||
if ((await button.count()) === 0) continue
|
||||
try {
|
||||
await button.click({ timeout: 4_000 })
|
||||
dismissed = true
|
||||
await page.waitForTimeout(1_000)
|
||||
} catch {
|
||||
// Masked by the takeover stacked above; retry in the next round.
|
||||
}
|
||||
}
|
||||
if (!dismissed) break
|
||||
}
|
||||
}
|
||||
|
||||
/** Open the native Sidebar, then the plugin's Files page inside it. */
|
||||
async function openFiles(page: Page): Promise<void> {
|
||||
const pane = page.locator('[data-sidebar-right-panel]:visible')
|
||||
const expand = page.locator('[data-sidebar-right-expand]:visible')
|
||||
if (await expand.count() > 0) await expand.first().click()
|
||||
await expect(pane).toBeVisible({ timeout: 30_000 })
|
||||
if (await page.locator(GUIDE).count() > 0) await page.locator(GUIDE_FILES).click()
|
||||
await expect(
|
||||
page.locator(`${TREE_BODY} [role="button"][title$="seed-000.txt"]:visible`),
|
||||
'the plugin explorer must render the seeded rows',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
}
|
||||
|
||||
/**
|
||||
* The observable state vector of the Files window. Every field is something a
|
||||
* reader would notice losing — the comparison the review asked for.
|
||||
*/
|
||||
interface StateVector {
|
||||
/** The tree's scroll offset. */
|
||||
scrollTop: number
|
||||
/** The directory whose children are on screen ('' when none is expanded). */
|
||||
expandedDir: string
|
||||
/** The active tab's chip text (an in-place file open rewrites it). */
|
||||
chip: string
|
||||
}
|
||||
|
||||
async function readState(page: Page): Promise<StateVector> {
|
||||
// Whatever directory is expanded shows its inner.txt; report which one.
|
||||
const expandedDir = await page.locator(`${TREE_BODY} [role="button"][title*="inner.txt"]:visible`)
|
||||
.evaluateAll(nodes => nodes.length === 0
|
||||
? ''
|
||||
: (nodes[0]!.getAttribute('title') ?? '').split(/[\\/]/).slice(-2, -1)[0] ?? '')
|
||||
return {
|
||||
scrollTop: await page.locator(TREE_BODY).first().evaluate(el => el.scrollTop),
|
||||
expandedDir,
|
||||
chip: (await page.locator('[data-sidebar-right-panel]:visible [role="tab"][aria-selected="true"]').first().innerText()).trim(),
|
||||
}
|
||||
}
|
||||
|
||||
/** Expand one directory in the tree and require its child to appear. */
|
||||
async function expandDir(page: Page, dir: string): Promise<void> {
|
||||
await page.locator(dirRow(dir)).first().click()
|
||||
await expect(
|
||||
page.locator(innerRow(dir)).first(),
|
||||
`expanding ${dir} must reveal its child`,
|
||||
).toBeVisible({ timeout: 30_000 })
|
||||
}
|
||||
|
||||
/**
|
||||
* The session id of the seat that is on screen (DSH's own marker on every
|
||||
* retained session container). Reading the IDENTITY rather than counting rows
|
||||
* keeps this lane honest: the rail re-sorts as sessions take turns, so
|
||||
* "the second row" is not a stable name for a conversation.
|
||||
*
|
||||
* 0.2.x marks BOTH every RETAINED seat and each seat's panel with
|
||||
* `data-sidebar-right-session` — one seat per retained Conversation stays in the
|
||||
* DOM — so the attribute alone names several conversations at once. The panel
|
||||
* that is actually laid out is the seat on screen, which is the same `:visible`
|
||||
* convention the rest of this lane already uses.
|
||||
*/
|
||||
async function onScreenSession(page: Page): Promise<string | undefined> {
|
||||
const panel = page.locator('[data-sidebar-right-panel]:visible').first()
|
||||
if ((await panel.count()) > 0) {
|
||||
return (await panel.getAttribute('data-sidebar-right-session')) ?? undefined
|
||||
}
|
||||
const seat = page.locator('[data-sidebar-right-session]:visible').first()
|
||||
if ((await seat.count()) > 0) {
|
||||
return (await seat.getAttribute('data-sidebar-right-session')) ?? undefined
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a NEW conversation from the rail and wait until it owns the right
|
||||
* sidebar seat.
|
||||
*
|
||||
* The lane used to click "the second row" of the rail: the row list also
|
||||
* contains the WORKSPACE row, and a seeded session with no messages never gets
|
||||
* a row of its own — so that click re-selected the SAME conversation and the
|
||||
* "round trip" never left it. Creating one through the rail's own control is
|
||||
* the only switch that certainly changes the session.
|
||||
* @param page - the lane's page.
|
||||
* @param from - the session the lane built its state in.
|
||||
* @returns the new session's id.
|
||||
*/
|
||||
async function newConversation(page: Page, from: string | undefined): Promise<string> {
|
||||
await page.getByRole('button', { name: /^(New session|新建会话)$/ }).first().click()
|
||||
await expect.poll(() => onScreenSession(page), { timeout: 60_000 }).not.toBe(from)
|
||||
const now = await onScreenSession(page)
|
||||
if (now === undefined) throw new Error('the new conversation did not take the right sidebar seat')
|
||||
return now
|
||||
}
|
||||
|
||||
/** Select one conversation by its own rail row key. */
|
||||
async function selectConversation(page: Page, sessionId: string): Promise<void> {
|
||||
const row = page.locator(`${SESSION_ROWS}[data-row-key="session:${sessionId}"]`).first()
|
||||
await expect(row).toBeAttached({ timeout: 30_000 })
|
||||
await row.click()
|
||||
await expect.poll(() => onScreenSession(page), { timeout: 60_000 }).toBe(sessionId)
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin-side reads a reader would notice being repeated, by URL fragment.
|
||||
* `keepMounted` is supposed to make a conversation switch a pure show/hide: the
|
||||
* body stays up, so its already-loaded levels must NOT be fetched again.
|
||||
*
|
||||
* The root level IS re-fetched on every activation on purpose (the tree is the
|
||||
* one view that has to show the disk as it is now), so it is excluded here and
|
||||
* asserted separately; what this counts is the work a kept-alive body should
|
||||
* never repeat.
|
||||
*/
|
||||
const REPEATABLE_READS = ['/sidebar/api/fs.tree', '/sidebar/api/fs.read']
|
||||
|
||||
test('the explorer keeps its state across a tab switch and a conversation round trip', async ({ page }) => {
|
||||
const pageErrors: string[] = []
|
||||
page.on('pageerror', (error) => pageErrors.push(String(error)))
|
||||
page.on('console', (message) => { console.log('[page]', message.text()) })
|
||||
|
||||
// Count the plugin's own reads so "state survived" is not confused with
|
||||
// "everything was silently reloaded". These routes are POSTs — the path
|
||||
// being listed or read travels in the BODY, not the URL — so the body is
|
||||
// what tells one level/file from another.
|
||||
const reads: Array<{ url: string; path: string; at: number }> = []
|
||||
page.on('request', (request) => {
|
||||
const url = request.url()
|
||||
if (!REPEATABLE_READS.some(fragment => url.includes(fragment))) return
|
||||
const body = request.postData() ?? ''
|
||||
const path = /"path"\s*:\s*"([^"]*)"/.exec(body)?.[1] ?? ''
|
||||
reads.push({ url, path: decodeURIComponent(path), at: Date.now() })
|
||||
})
|
||||
const readsSince = (mark: number, match?: string): string[] =>
|
||||
reads
|
||||
.filter(entry => entry.at >= mark && (match === undefined || entry.path.includes(match)))
|
||||
.map(entry => entry.path)
|
||||
|
||||
|
||||
await page.goto(PAGE_URL, { waitUntil: 'domcontentloaded' })
|
||||
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
|
||||
await dismissOnboarding(page)
|
||||
await sendFirstMessage(page)
|
||||
await openFiles(page)
|
||||
|
||||
const body = page.locator(TREE_BODY).first()
|
||||
await expect(body).toBeVisible({ timeout: 30_000 })
|
||||
await expect
|
||||
.poll(() => body.evaluate(el => el.scrollHeight - el.clientHeight), { timeout: 30_000 })
|
||||
.toBeGreaterThan(100)
|
||||
|
||||
// ── Build state up in the FIRST conversation ──────────────────────────────
|
||||
await expandDir(page, 'alpha')
|
||||
await body.evaluate((el, top) => { el.scrollTop = top }, SCROLL_TO)
|
||||
await expect.poll(() => body.evaluate(el => el.scrollTop), { timeout: 10_000 }).toBe(SCROLL_TO)
|
||||
|
||||
const sessionA = await onScreenSession(page)
|
||||
expect(sessionA, 'the right sidebar seat must name its session').toBeDefined()
|
||||
const before = await readState(page)
|
||||
expect(before.expandedDir, 'alpha must be recorded as expanded before switching').toBe('alpha')
|
||||
|
||||
// ── A tab switch inside the same conversation ─────────────────────────────
|
||||
await page.locator('[data-dockkit-add-tab]').first().click()
|
||||
await expect(page.locator(GUIDE)).toBeVisible({ timeout: 30_000 })
|
||||
await page.locator(GUIDE_FILES).click()
|
||||
await expect(
|
||||
page.locator(innerRow('alpha')).first(),
|
||||
'a same-conversation tab switch must keep the expansion',
|
||||
).toBeVisible({ timeout: 30_000 })
|
||||
|
||||
const afterTab = await readState(page)
|
||||
expect(afterTab.expandedDir, 'the expansion survives a tab switch').toBe(before.expandedDir)
|
||||
expect(afterTab.scrollTop, 'the scroll position survives a tab switch').toBe(SCROLL_TO)
|
||||
expect(afterTab.chip, 'the chip keeps its title across a tab switch').toBe(before.chip)
|
||||
|
||||
// ── A FILE open in conversation A: the resource question ──────────────────
|
||||
// Opening a file in merged mode switches THIS tab to the editor, so the tree
|
||||
// component unmounts by design (its scroll does not survive that, and never
|
||||
// did). What must survive a CONVERSATION switch is the file itself: it stays
|
||||
// open, and its bytes are not read again.
|
||||
const fileMark = Date.now()
|
||||
await page.locator(innerRow('alpha')).first().click({ position: { x: 8, y: 8 } })
|
||||
await expect(
|
||||
page.locator('[data-sidebar-right-panel]:visible .cm-editor').first(),
|
||||
'the file must open in the plugin editor',
|
||||
).toBeVisible({ timeout: 30_000 })
|
||||
expect(
|
||||
readsSince(fileMark, 'inner.txt'),
|
||||
'opening the file reads it exactly once',
|
||||
).toHaveLength(1)
|
||||
|
||||
// ── An UNSAVED EDIT in conversation A (the worst loss is data) ────────────
|
||||
// #712 parked drafts in a module-level map; this branch claims `keepMounted`
|
||||
// makes that unnecessary because the body never unmounts. That claim was
|
||||
// never exercised — the draft is the one loss a reader cannot re-derive.
|
||||
const DRAFT = 'edited by the retention lane'
|
||||
const content = page.locator('[data-sidebar-right-panel]:visible .cm-content').first()
|
||||
await content.click()
|
||||
await page.keyboard.press('ControlOrMeta+End')
|
||||
await page.keyboard.type(`\n${DRAFT}`)
|
||||
await expect(content, 'the typing must land in the live document').toContainText(DRAFT)
|
||||
const draftDoc = async (): Promise<string> =>
|
||||
page.locator('[data-sidebar-right-panel]:visible .cm-content').first().innerText()
|
||||
|
||||
// ── An UNSAVED COMMIT MESSAGE (the other typed-state loss) ────────────────
|
||||
const COMMIT_MSG = 'fix: an unsaved message from the lane'
|
||||
await page.locator('[data-dockkit-add-tab]').first().click()
|
||||
await expect(page.locator(GUIDE)).toBeVisible({ timeout: 30_000 })
|
||||
await page.locator('[data-sidebar-right-panel]:visible [data-sidebar-right-guide-entry="git"]').click()
|
||||
const commitBox = page.locator('[data-sidebar-right-panel]:visible')
|
||||
.getByRole('textbox', { name: /Commit message/i }).first()
|
||||
await expect(commitBox, 'the changes tab must render its commit box').toBeVisible({ timeout: 30_000 })
|
||||
await commitBox.fill(COMMIT_MSG)
|
||||
await expect(commitBox).toHaveValue(COMMIT_MSG)
|
||||
|
||||
// ── A CHOSEN WORKTREE (the third painted-state loss #712 covered) ─────────
|
||||
// The lane's linked checkout is the non-auto choice: picking it must survive
|
||||
// the round trip, not be re-derived from the inventory. Paths are compared
|
||||
// through `realpathSync` because macOS /var is a symlink to /private/var and
|
||||
// git reports the resolved form.
|
||||
const linkedPath = realpathSync(join(WORKSPACE_PATH, 'linked-checkout'))
|
||||
const worktreeSelect = page.locator('[data-sidebar-right-panel]:visible select')
|
||||
.filter({ has: page.locator('option') }).first()
|
||||
await expect(worktreeSelect, 'the changes tab must offer its worktree selector').toBeVisible({ timeout: 30_000 })
|
||||
const linkedOption = await worktreeSelect.locator('option').evaluateAll(
|
||||
(options, path) => options.some(option => (option as HTMLOptionElement).value === path),
|
||||
linkedPath,
|
||||
)
|
||||
expect(linkedOption, 'the linked worktree must appear in the selector').toBe(true)
|
||||
await worktreeSelect.selectOption(linkedPath)
|
||||
await expect(worktreeSelect).toHaveValue(linkedPath)
|
||||
|
||||
// Back to the Files window and RE-BUILD the scroll offset: opening the file
|
||||
// swapped this tab's content, so the tree remounted at the top (by design,
|
||||
// unrelated to session retention). The round trip below must then preserve
|
||||
// this second offset.
|
||||
await page.locator('[data-sidebar-right-panel]:visible [role="tab"]').filter({ hasText: /Files|文件/ }).first().click()
|
||||
await expect(page.locator(innerRow('alpha')).first()).toBeVisible({ timeout: 30_000 })
|
||||
const bodyAgain = page.locator(TREE_BODY).first()
|
||||
await bodyAgain.evaluate((el, top) => { el.scrollTop = top }, SCROLL_TO)
|
||||
await expect.poll(() => bodyAgain.evaluate(el => el.scrollTop), { timeout: 10_000 }).toBe(SCROLL_TO)
|
||||
const beforeTrip = await readState(page)
|
||||
expect(beforeTrip.expandedDir, 'alpha is still expanded after the file round trip').toBe('alpha')
|
||||
|
||||
// ── A conversation round trip: A → B → A ──────────────────────────────────
|
||||
const firstConversationChip = beforeTrip.chip
|
||||
await page.evaluate(() => console.log('[mark] switching-to-B', Date.now() % 1000000))
|
||||
const sessionB = await newConversation(page, sessionA)
|
||||
await page.evaluate(() => console.log('[mark] in-B', Date.now() % 1000000))
|
||||
// A brand-new conversation can raise the same takeover the first one did.
|
||||
await dismissOnboarding(page)
|
||||
// ISOLATION (the probe this lane adds for the keepMounted experiment): B is
|
||||
// a DIFFERENT conversation whose native tab ids restart at `tab1`. If the
|
||||
// plugin's registry is keyed by the bare native id, B's Files window shows
|
||||
// A's expansion — the leak the registry must not have.
|
||||
await openFiles(page)
|
||||
const isolation = await readState(page)
|
||||
expect(
|
||||
isolation.expandedDir,
|
||||
'conversation B must not inherit conversation A tree expansion',
|
||||
).toBe('')
|
||||
expect(
|
||||
isolation.scrollTop,
|
||||
'conversation B must not inherit conversation A scroll offset',
|
||||
).toBe(0)
|
||||
expect(sessionB, 'the lane must have left conversation A').not.toBe(sessionA)
|
||||
await page.waitForTimeout(1_500)
|
||||
const backMark = Date.now()
|
||||
await page.evaluate(() => console.log('[mark] switching-back-to-A', Date.now() % 1000000))
|
||||
await selectConversation(page, sessionA!)
|
||||
await dismissOnboarding(page)
|
||||
// A's tab strip comes back with every tab it had (Files / the file / the
|
||||
// changes window) — asserted by the strip below, since the ACTIVE tab is
|
||||
// whichever the lane last showed.
|
||||
// The changes tab is where the unsaved message lives: it is the other claim
|
||||
// `keepMounted` makes on #712's behalf.
|
||||
const changesTab = page.locator('[data-sidebar-right-panel]:visible [role="tab"]').filter({ hasText: /Changes|文件变动/ })
|
||||
await expect(changesTab, 'the changes tab survives the round trip').toHaveCount(1, { timeout: 30_000 })
|
||||
await changesTab.first().click()
|
||||
const backCommitBox = page.locator('[data-sidebar-right-panel]:visible')
|
||||
.getByRole('textbox', { name: /Commit message/i }).first()
|
||||
await expect(backCommitBox, 'the changes tab still renders its commit box').toBeVisible({ timeout: 30_000 })
|
||||
await expect(
|
||||
backCommitBox,
|
||||
'an unsaved commit message survives the conversation round trip',
|
||||
).toHaveValue(COMMIT_MSG)
|
||||
await expect(
|
||||
page.locator('[data-sidebar-right-panel]:visible select').first(),
|
||||
'the chosen worktree survives the conversation round trip',
|
||||
).toHaveValue(linkedPath)
|
||||
// And the tree's own tab is still there too.
|
||||
await expect(
|
||||
page.locator('[data-sidebar-right-panel]:visible [role="tab"]').filter({ hasText: /Files|文件/ }),
|
||||
'the files tab survives the round trip',
|
||||
).toHaveCount(1, { timeout: 30_000 })
|
||||
|
||||
// The FILE opened in A is still open, and its bytes were NOT read again —
|
||||
// the editor body stayed mounted, so it still holds them. (Its tab is not
|
||||
// active on return, so it is asserted by opening it, which must be a plain
|
||||
// show of already-held content.)
|
||||
expect(
|
||||
readsSince(backMark, 'inner.txt'),
|
||||
'the file opened in A must not be re-read when the conversation comes back',
|
||||
).toEqual([])
|
||||
const editorTab = page.locator('[data-sidebar-right-panel]:visible [role="tab"]').filter({ hasText: 'inner.txt' })
|
||||
await expect(editorTab, 'the file opened in A is still open after the round trip').toHaveCount(1, { timeout: 30_000 })
|
||||
await editorTab.first().click()
|
||||
await expect(
|
||||
page.locator('[data-sidebar-right-panel]:visible .cm-editor').first(),
|
||||
'selecting it shows the editor without a new read',
|
||||
).toBeVisible({ timeout: 30_000 })
|
||||
expect(
|
||||
readsSince(backMark, 'inner.txt'),
|
||||
'and showing it again still re-read nothing',
|
||||
).toEqual([])
|
||||
|
||||
// THE DRAFT: the typing from before the switch must still be in the document.
|
||||
// This is the claim `keepMounted` makes on #712's behalf, and the only loss
|
||||
// here that a reader cannot recover by looking again.
|
||||
expect(
|
||||
await draftDoc(),
|
||||
'an unsaved edit survives the conversation round trip',
|
||||
).toContain(DRAFT)
|
||||
|
||||
// Back to the Files window for the remaining vector (its own tab is still
|
||||
// there, and selecting it is a plain show — not a reload).
|
||||
await page.locator('[data-sidebar-right-panel]:visible [role="tab"]').filter({ hasText: /Files|文件/ }).first().click()
|
||||
await expect(page.locator(innerRow('alpha')).first()).toBeVisible({ timeout: 30_000 })
|
||||
await expect
|
||||
.poll(async () => (await readState(page)).expandedDir, { timeout: 30_000 })
|
||||
.toBe('alpha')
|
||||
|
||||
const afterRoundTrip = await readState(page)
|
||||
// The tree's own scroll offset is COMPONENT state, not record state: it
|
||||
// survives this trip only because the explorer body stays mounted — which
|
||||
// holds only while the plugin keeps the `files` takeover registration alive
|
||||
// across the pulse a Session switch emits (see the sync() note).
|
||||
expect(
|
||||
afterRoundTrip.scrollTop,
|
||||
'the tree scroll offset survives a conversation round trip',
|
||||
).toBe(SCROLL_TO)
|
||||
expect(
|
||||
afterRoundTrip.expandedDir,
|
||||
'the tree expansion survives a conversation round trip',
|
||||
).toBe(beforeTrip.expandedDir)
|
||||
expect(
|
||||
afterRoundTrip.chip,
|
||||
'the tab chip survives a conversation round trip',
|
||||
).toBe(firstConversationChip)
|
||||
expect(pageErrors, 'no page errors during the round trip').toEqual([])
|
||||
|
||||
await page.screenshot({ path: 'test-results/tree-state-restored.png' })
|
||||
})
|
||||
+358
-41
@@ -10,6 +10,7 @@ import { createRoot, type Root } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import { createNativeTabRecords, NativeTabBody, NativeTabTitle } from '../src/client/native/tab-adapter.tsx'
|
||||
import { registerNativeSurface } from '../src/client/native/index.ts'
|
||||
import { createNativeSurface } from '../src/client/native/surface.ts'
|
||||
import { createBetterSidebarService, type SidebarSurface } from '../src/client/service.ts'
|
||||
import { createSidebarStore, toggleExpanded, type SidebarTab } from '../src/client/state.ts'
|
||||
|
||||
@@ -19,6 +20,7 @@ describe('createNativeTabRecords', () => {
|
||||
it('mints a synthetic tab from the native record + params', () => {
|
||||
const records = createNativeTabRecords()
|
||||
const view = records.ensure({
|
||||
sessionId: 's1',
|
||||
id: 'tab-1', kind: 'browser', title: 'Browser', params: { url: 'https://a.test', meta: { k: 1 } }, scope,
|
||||
})
|
||||
expect(view.tab).toMatchObject({ id: 'tab-1', type: 'browser', title: 'Browser', meta: { k: 1 } })
|
||||
@@ -29,19 +31,19 @@ describe('createNativeTabRecords', () => {
|
||||
it('calls the descriptor factory once for a record that arrives without seed fields', () => {
|
||||
const records = createNativeTabRecords()
|
||||
const mint = vi.fn(() => ({ title: 'Side chat', meta: { autoCreate: true } }))
|
||||
const view = records.ensure({ id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint })
|
||||
const view = records.ensure({ sessionId: 's1', id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint })
|
||||
expect(mint).toHaveBeenCalledTimes(1)
|
||||
expect(view.tab).toMatchObject({ title: 'Side chat', meta: { autoCreate: true } })
|
||||
// A second render of the same record does not re-mint.
|
||||
records.ensure({ id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint })
|
||||
records.ensure({ sessionId: 's1', id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint })
|
||||
expect(mint).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('refreshes the seed fields on navigation but keeps the record identity', () => {
|
||||
const records = createNativeTabRecords()
|
||||
records.ensure({ id: 'tab-3', kind: 'editor', title: 'a.ts', params: { path: '/work/a.ts' }, scope })
|
||||
records.update('tab-3', { title: 'renamed.ts' })
|
||||
const view = records.ensure({ id: 'tab-3', kind: 'editor', title: 'b.ts', params: { path: '/work/b.ts' }, scope })
|
||||
records.ensure({ sessionId: 's1', id: 'tab-3', kind: 'editor', title: 'a.ts', params: { path: '/work/a.ts' }, scope })
|
||||
records.update('s1', 'tab-3', { title: 'renamed.ts' })
|
||||
const view = records.ensure({ sessionId: 's1', id: 'tab-3', kind: 'editor', title: 'b.ts', params: { path: '/work/b.ts' }, scope })
|
||||
expect(view.tab).toMatchObject({ id: 'tab-3', path: '/work/b.ts', title: 'renamed.ts' })
|
||||
})
|
||||
|
||||
@@ -50,14 +52,14 @@ describe('createNativeTabRecords', () => {
|
||||
store.setSession('s1')
|
||||
const records = createNativeTabRecords()
|
||||
records.attachStore(store)
|
||||
records.ensure({ id: 'tab-4', kind: 'editor', title: 'Files', params: undefined, scope })
|
||||
const before = records.versionOf('tab-4')
|
||||
records.toggleExpanded('tab-4', '/work/src')
|
||||
expect(records.get('tab-4')?.expanded).toEqual(['/work/src'])
|
||||
records.ensure({ sessionId: 's1', id: 'tab-4', kind: 'editor', title: 'Files', params: undefined, scope })
|
||||
const before = records.versionOf('s1', 'tab-4')
|
||||
records.toggleExpanded('s1', 'tab-4', '/work/src')
|
||||
expect(records.get('s1', 'tab-4')?.expanded).toEqual(['/work/src'])
|
||||
expect(store.getSessionStates().get('s1')?.expanded).toEqual(['/work/src'])
|
||||
expect(records.versionOf('tab-4')).toBeGreaterThan(before)
|
||||
records.toggleExpanded('tab-4', '/work/src')
|
||||
expect(records.get('tab-4')?.expanded).toEqual([])
|
||||
expect(records.versionOf('s1', 'tab-4')).toBeGreaterThan(before)
|
||||
records.toggleExpanded('s1', 'tab-4', '/work/src')
|
||||
expect(records.get('s1', 'tab-4')?.expanded).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the expansion after a tab record is DROPPED and rebuilt (the reported bug)', () => {
|
||||
@@ -68,13 +70,13 @@ describe('createNativeTabRecords', () => {
|
||||
store.setSession('s1')
|
||||
const records = createNativeTabRecords()
|
||||
records.attachStore(store)
|
||||
records.ensure({ id: 'files-1', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.toggleExpanded('files-1', '/work/src')
|
||||
records.toggleExpanded('files-1', '/work/src/components')
|
||||
expect(records.get('files-1')?.expanded).toEqual(['/work/src', '/work/src/components'])
|
||||
records.ensure({ sessionId: 's1', id: 'files-1', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.toggleExpanded('s1', 'files-1', '/work/src')
|
||||
records.toggleExpanded('s1', 'files-1', '/work/src/components')
|
||||
expect(records.get('s1', 'files-1')?.expanded).toEqual(['/work/src', '/work/src/components'])
|
||||
|
||||
records.drop('files-1')
|
||||
const rebuilt = records.ensure({ id: 'files-2', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.drop('s1', 'files-1')
|
||||
const rebuilt = records.ensure({ sessionId: 's1', id: 'files-2', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
expect(rebuilt.expanded).toEqual(['/work/src', '/work/src/components'])
|
||||
})
|
||||
|
||||
@@ -83,20 +85,20 @@ describe('createNativeTabRecords', () => {
|
||||
store.setSession('s1')
|
||||
const records = createNativeTabRecords()
|
||||
records.attachStore(store)
|
||||
records.ensure({ id: 'files-a', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.ensure({ id: 'files-b', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's1', id: 'files-a', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's1', id: 'files-b', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
|
||||
records.toggleExpanded('files-a', '/work/src')
|
||||
expect(records.get('files-b')?.expanded).toEqual(['/work/src'])
|
||||
records.toggleExpanded('s1', 'files-a', '/work/src')
|
||||
expect(records.get('s1', 'files-b')?.expanded).toEqual(['/work/src'])
|
||||
|
||||
// The WORKBENCH's own toggle (the per-session reducer) is the same state.
|
||||
store.reduce(state => toggleExpanded(state, '/work/lib'))
|
||||
expect(records.get('files-a')?.expanded).toEqual(['/work/src', '/work/lib'])
|
||||
expect(records.get('files-b')?.expanded).toEqual(['/work/src', '/work/lib'])
|
||||
expect(records.get('s1', 'files-a')?.expanded).toEqual(['/work/src', '/work/lib'])
|
||||
expect(records.get('s1', 'files-b')?.expanded).toEqual(['/work/src', '/work/lib'])
|
||||
|
||||
// …and a toggle from the native side is visible to the workbench reducer's
|
||||
// state (one authority, two surfaces).
|
||||
records.toggleExpanded('files-b', '/work/src')
|
||||
records.toggleExpanded('s1', 'files-b', '/work/src')
|
||||
expect(store.getSessionStates().get('s1')?.expanded).toEqual(['/work/lib'])
|
||||
})
|
||||
|
||||
@@ -105,15 +107,15 @@ describe('createNativeTabRecords', () => {
|
||||
store.setSession('s1')
|
||||
const records = createNativeTabRecords()
|
||||
records.attachStore(store)
|
||||
records.ensure({ id: 's1-files', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.ensure({ id: 's2-files', kind: 'files', title: 'Files', params: undefined, scope: { sessionId: 's2', cwd: '/other' } })
|
||||
records.ensure({ sessionId: 's1', id: 's1-files', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's2', id: 's2-files', kind: 'files', title: 'Files', params: undefined, scope: { sessionId: 's2', cwd: '/other' } })
|
||||
|
||||
// The ACTIVE session goes through `reduce`; the background one through
|
||||
// `reduceFor` — both must land in their own session only.
|
||||
records.toggleExpanded('s1-files', '/work/src')
|
||||
records.toggleExpanded('s2-files', '/other/lib')
|
||||
expect(records.get('s1-files')?.expanded).toEqual(['/work/src'])
|
||||
expect(records.get('s2-files')?.expanded).toEqual(['/other/lib'])
|
||||
records.toggleExpanded('s1', 's1-files', '/work/src')
|
||||
records.toggleExpanded('s2', 's2-files', '/other/lib')
|
||||
expect(records.get('s1', 's1-files')?.expanded).toEqual(['/work/src'])
|
||||
expect(records.get('s2', 's2-files')?.expanded).toEqual(['/other/lib'])
|
||||
expect(store.getSessionStates().get('s1')?.expanded).toEqual(['/work/src'])
|
||||
expect(store.getSessionStates().get('s2')?.expanded).toEqual(['/other/lib'])
|
||||
})
|
||||
@@ -124,23 +126,23 @@ describe('createNativeTabRecords', () => {
|
||||
store.reduce(state => toggleExpanded(state, '/work/src'))
|
||||
const records = createNativeTabRecords()
|
||||
records.attachStore(store)
|
||||
const view = records.ensure({ id: 'late', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
const view = records.ensure({ sessionId: 's1', id: 'late', kind: 'files', title: 'Files', params: undefined, scope })
|
||||
expect(view.expanded).toEqual(['/work/src'])
|
||||
})
|
||||
|
||||
it('notifies subscribers and forgets a dropped record', () => {
|
||||
const records = createNativeTabRecords()
|
||||
records.ensure({ id: 'tab-5', kind: 'terminal', title: 'Terminal', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's1', id: 'tab-5', kind: 'terminal', title: 'Terminal', params: undefined, scope })
|
||||
const listener = vi.fn()
|
||||
const off = records.subscribe(listener)
|
||||
records.update('tab-5', { title: 'zsh' })
|
||||
records.update('s1', 'tab-5', { title: 'zsh' })
|
||||
expect(listener).toHaveBeenCalledTimes(1)
|
||||
expect(records.get('tab-5')?.tab.title).toBe('zsh')
|
||||
records.drop('tab-5')
|
||||
expect(records.has('tab-5')).toBe(false)
|
||||
expect(records.get('s1', 'tab-5')?.tab.title).toBe('zsh')
|
||||
records.drop('s1', 'tab-5')
|
||||
expect(records.has('s1', 'tab-5')).toBe(false)
|
||||
off()
|
||||
records.ensure({ id: 'tab-6', kind: 'terminal', title: 'Terminal', params: undefined, scope })
|
||||
records.update('tab-6', { title: 'x' })
|
||||
records.ensure({ sessionId: 's1', id: 'tab-6', kind: 'terminal', title: 'Terminal', params: undefined, scope })
|
||||
records.update('s1', 'tab-6', { title: 'x' })
|
||||
expect(listener).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -285,6 +287,57 @@ describe('service routing into the native surface', () => {
|
||||
})
|
||||
|
||||
describe('registerNativeSurface lifecycle (service-driven registration)', () => {
|
||||
it('keeps the files takeover registered across a Session switch pulse', () => {
|
||||
// Regression: `sync()`'s cleanup loop compared the live registrations with
|
||||
// the DESCRIPTOR list, which never contains the `files` takeover — so every
|
||||
// store/service pulse (a Session switch is one) disposed and rebuilt it.
|
||||
// That remounts the explorer body, and a body remount loses the tree's own
|
||||
// component state (its scroll offset) even though the record survives.
|
||||
const store = createSidebarStore()
|
||||
store.setSession('s1')
|
||||
const service = createBetterSidebarService(store)
|
||||
service.registerTab({ id: 'editor', title: 'Files', component: () => null, icon: () => null })
|
||||
const records = createNativeTabRecords()
|
||||
|
||||
const registered: string[] = []
|
||||
const disposed: string[] = []
|
||||
const registry = {
|
||||
current: {
|
||||
register: (definition: { id: string; kind: string }) => {
|
||||
registered.push(definition.kind)
|
||||
return () => { disposed.push(definition.kind) }
|
||||
},
|
||||
},
|
||||
}
|
||||
let runInjected: (() => void) | undefined
|
||||
const ctx = {
|
||||
inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => void) => {
|
||||
runInjected = () => { callback({ get: () => registry.current }) }
|
||||
return { dispose: () => { runInjected = undefined } }
|
||||
},
|
||||
get: () => registry.current,
|
||||
slots: {
|
||||
inject: (_key: string, callback: () => () => void) => callback(),
|
||||
register: () => () => {},
|
||||
},
|
||||
}
|
||||
const dispose = registerNativeSurface({ ctx: ctx as never, store, service, records })
|
||||
runInjected?.()
|
||||
const filesCount = (): number => registered.filter(kind => kind === 'files').length
|
||||
expect(filesCount(), 'the takeover registers once').toBe(1)
|
||||
|
||||
// A Session switch is a store pulse: it must not tear the takeover down.
|
||||
store.setSession('s2')
|
||||
expect(filesCount(), 'a Session switch must not rebuild the takeover').toBe(1)
|
||||
expect(disposed, 'and nothing was disposed on the way').toEqual([])
|
||||
|
||||
// Disabling the editor type DOES retire it — the lifetime it really owns.
|
||||
store.setPrefs({ ...store.getPrefs(), tabsEnabled: { editor: false } })
|
||||
expect(disposed, 'the editor switch retired the takeover (with the editor type)').toContain('files')
|
||||
expect(filesCount(), 'and it was not rebuilt while disabled').toBe(1)
|
||||
dispose()
|
||||
})
|
||||
|
||||
it('registers the native tab types when the tab-type registry ARRIVES after the slot declaration', () => {
|
||||
// Regression: the native seat declares `sidebar.right.pane.tab` before it
|
||||
// provides `sidebarRightTabs`, so a registration driven by the slot
|
||||
@@ -602,6 +655,7 @@ describe('NativeTabTitle (the chip glyph)', () => {
|
||||
service: ReturnType<typeof createBetterSidebarService>,
|
||||
info: unknown,
|
||||
descriptorId: string,
|
||||
sessionId = 's1',
|
||||
): { host: HTMLDivElement; unmount: () => void } => {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
@@ -612,6 +666,7 @@ describe('NativeTabTitle (the chip glyph)', () => {
|
||||
records,
|
||||
service,
|
||||
descriptorId,
|
||||
sessionId,
|
||||
useTabInfo: () => info as never,
|
||||
}))
|
||||
})
|
||||
@@ -645,7 +700,7 @@ describe('NativeTabTitle (the chip glyph)', () => {
|
||||
icon: (size: number) => createElement('i', { 'data-stub-icon': size }),
|
||||
component: () => createElement('div'),
|
||||
})
|
||||
records.ensure({ id: 'chip-1', kind: 'stub-tab', title: 'Stub', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's1', id: 'chip-1', kind: 'stub-tab', title: 'Stub', params: undefined, scope })
|
||||
|
||||
const { host, unmount } = renderTitle(records, service, nativeInfo('chip-1', 'stub-tab', 'Stub'), 'stub-tab')
|
||||
const chip = host.querySelector('[aria-hidden="true"]')
|
||||
@@ -666,6 +721,7 @@ describe('NativeTabTitle (the chip glyph)', () => {
|
||||
component: () => createElement('div'),
|
||||
})
|
||||
records.ensure({
|
||||
sessionId: 's1',
|
||||
id: 'chip-2',
|
||||
kind: 'editor',
|
||||
title: 'notes.md',
|
||||
@@ -686,7 +742,7 @@ describe('NativeTabTitle (the chip glyph)', () => {
|
||||
it('falls back to the title alone when the type is gone (unregistered descriptor)', () => {
|
||||
const records = createNativeTabRecords()
|
||||
const service = createBetterSidebarService(createSidebarStore())
|
||||
records.ensure({ id: 'chip-3', kind: 'ghost', title: 'Ghost', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's1', id: 'chip-3', kind: 'ghost', title: 'Ghost', params: undefined, scope })
|
||||
|
||||
const { host, unmount } = renderTitle(records, service, nativeInfo('chip-3', 'ghost', 'Ghost'), 'ghost')
|
||||
expect(host.querySelector('[aria-hidden="true"]')).toBeNull()
|
||||
@@ -694,3 +750,264 @@ describe('NativeTabTitle (the chip glyph)', () => {
|
||||
unmount()
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* ONE NATIVE ID, ONE RECORD PER SESSION.
|
||||
*
|
||||
* The host's tab counter restarts in every session (`tab1`, `tab2`, …) and
|
||||
* 0.1.7 keeps visited bodies MOUNTED through hiding, tab selection and Session
|
||||
* switches (`SidebarTabDefinition.keepMounted`). Two sessions' `tab1` are
|
||||
* therefore alive at the same time, and a registry keyed by the bare id hands
|
||||
* one session's tree/edit state to the other — the chain #636/#661 reported.
|
||||
* These cases pin the per-session identity and the reclaim of dead sessions.
|
||||
*/
|
||||
describe('createNativeTabRecords — per-seat-session identity', () => {
|
||||
it('keeps two sessions\' same-named tab apart', () => {
|
||||
const store = createSidebarStore()
|
||||
store.setSession('s1')
|
||||
const records = createNativeTabRecords()
|
||||
// Expansion lives in the SESSION state (the one authority), so the registry
|
||||
// has to be bound to a store for a toggle to land anywhere.
|
||||
records.attachStore(store)
|
||||
const first = records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope })
|
||||
records.toggleExpanded('s1', 'tab1', '/work/src')
|
||||
const second = records.ensure({
|
||||
sessionId: 's2', id: 'tab1', kind: 'editor', title: 'Files', params: undefined,
|
||||
scope: { sessionId: 's2', cwd: '/other' },
|
||||
})
|
||||
expect(second).not.toBe(first)
|
||||
expect(records.get('s1', 'tab1')?.expanded).toEqual(['/work/src'])
|
||||
expect(records.get('s2', 'tab1')?.expanded, 'the entering session must not inherit').toEqual([])
|
||||
expect(records.get('s2', 'tab1')?.scope.sessionId).toBe('s2')
|
||||
})
|
||||
|
||||
it('patches and drops exactly one session\'s record', () => {
|
||||
const records = createNativeTabRecords()
|
||||
records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's2', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope })
|
||||
records.update('s2', 'tab1', { title: 'renamed in B' })
|
||||
expect(records.get('s1', 'tab1')?.tab.title).toBe('Files')
|
||||
expect(records.get('s2', 'tab1')?.tab.title).toBe('renamed in B')
|
||||
records.drop('s1', 'tab1')
|
||||
expect(records.has('s1', 'tab1')).toBe(false)
|
||||
expect(records.has('s2', 'tab1')).toBe(true)
|
||||
})
|
||||
|
||||
it('retain() reclaims the records of sessions that are gone', () => {
|
||||
const records = createNativeTabRecords()
|
||||
records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope })
|
||||
records.ensure({ sessionId: 's2', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope })
|
||||
const versions = new Map<string, number>()
|
||||
records.subscribe(() => { versions.set('seen', (versions.get('seen') ?? 0) + 1) })
|
||||
records.retain(new Set(['s1']))
|
||||
expect(records.has('s2', 'tab1')).toBe(false)
|
||||
expect(records.has('s1', 'tab1'), 'a live session keeps its state').toBe(true)
|
||||
expect(versions.get('seen'), 'a reclaim notifies the mounted bodies').toBe(1)
|
||||
// An unchanged live set is not a change: no notify, no work.
|
||||
records.retain(new Set(['s1']))
|
||||
expect(versions.get('seen')).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The surface resolves a BARE tab id (the consumer contract) against a seat
|
||||
* session: the mounted one when there is one, a unique match otherwise, and
|
||||
* NOTHING when the id names a tab in several sessions — guessing would write
|
||||
* into another conversation. A session that disappears takes its records with
|
||||
* it, because a `keepMounted` body of a deleted session never unmounts.
|
||||
*/
|
||||
describe('createNativeSurface — session-scoped ids and reclaim', () => {
|
||||
const fixture = (sessionIds: string[], mounted?: string) => {
|
||||
const listListeners = new Set<() => void>()
|
||||
const byId: Record<string, { cwd: string }> = {}
|
||||
for (const id of sessionIds) byId[id] = { cwd: `/work/${id}` }
|
||||
const calls: unknown[] = []
|
||||
let mountedId = mounted
|
||||
const controller = {
|
||||
openTab: (kind: string, options?: unknown) => { calls.push({ op: 'openTab', kind, options }) },
|
||||
openResource: (address: string, options?: unknown) => { calls.push({ op: 'openResource', address, options }) },
|
||||
close: (tabId: string) => { calls.push({ op: 'close', tabId }) },
|
||||
closeIn: (sessionId: string, tabId: string) => { calls.push({ op: 'closeIn', sessionId, tabId }) },
|
||||
mounted: { getSnapshot: () => mountedId, subscribe: () => () => {} },
|
||||
}
|
||||
const ctx = {
|
||||
sessions: {
|
||||
list: {
|
||||
subscribe: (listener: () => void) => { listListeners.add(listener); return () => { listListeners.delete(listener) } },
|
||||
getSnapshot: () => ({ byId }),
|
||||
},
|
||||
},
|
||||
get: (name: string) => (name === 'sidebarRight' ? controller : undefined),
|
||||
} as never
|
||||
return {
|
||||
ctx,
|
||||
calls,
|
||||
setMounted: (id: string | undefined) => { mountedId = id },
|
||||
removeSession: (id: string) => { delete byId[id]; for (const listener of [...listListeners]) listener() },
|
||||
}
|
||||
}
|
||||
|
||||
const seed = (records: ReturnType<typeof createNativeTabRecords>, sessionId: string, id: string) =>
|
||||
records.ensure({ sessionId, id, kind: 'editor', title: 'Files', params: undefined, scope: { sessionId, cwd: '/work' } })
|
||||
|
||||
it('targets the session the caller names, never the same id in another one', () => {
|
||||
const { ctx } = fixture(['s1', 's2'], 's1')
|
||||
const records = createNativeTabRecords()
|
||||
seed(records, 's1', 'tab1')
|
||||
seed(records, 's2', 'tab1')
|
||||
const surface = createNativeSurface(ctx, records)
|
||||
expect(surface.update('tab1', { title: 'renamed in B' }, 's2')).toBe(true)
|
||||
expect(records.get('s2', 'tab1')?.tab.title).toBe('renamed in B')
|
||||
expect(records.get('s1', 'tab1')?.tab.title, 'the mounted seat is untouched').toBe('Files')
|
||||
})
|
||||
|
||||
it('falls back to the mounted seat when no session is named', () => {
|
||||
const { ctx } = fixture(['s1', 's2'], 's2')
|
||||
const records = createNativeTabRecords()
|
||||
seed(records, 's1', 'tab1')
|
||||
seed(records, 's2', 'tab1')
|
||||
const surface = createNativeSurface(ctx, records)
|
||||
expect(surface.update('tab1', { title: 'on screen' })).toBe(true)
|
||||
expect(records.get('s2', 'tab1')?.tab.title).toBe('on screen')
|
||||
expect(records.get('s1', 'tab1')?.tab.title).toBe('Files')
|
||||
})
|
||||
|
||||
it('refuses an ambiguous bare id instead of guessing a conversation', () => {
|
||||
const { ctx } = fixture(['s1', 's2'], undefined)
|
||||
const records = createNativeTabRecords()
|
||||
seed(records, 's1', 'tab1')
|
||||
seed(records, 's2', 'tab1')
|
||||
const surface = createNativeSurface(ctx, records)
|
||||
expect(surface.update('tab1', { title: 'nope' })).toBe(false)
|
||||
expect(surface.has('tab1')).toBe(false)
|
||||
// A unique match still resolves without a mounted seat.
|
||||
seed(records, 's2', 'tab9')
|
||||
expect(surface.has('tab9')).toBe(true)
|
||||
})
|
||||
|
||||
it('closes one session\'s tab and reclaims a deleted session\'s records', () => {
|
||||
// `s3` is the mounted seat; `s2` is a background session that will be
|
||||
// deleted — the case no React unmount ever reports.
|
||||
const { ctx, calls, removeSession } = fixture(['s1', 's2', 's3'], 's3')
|
||||
const records = createNativeTabRecords()
|
||||
seed(records, 's1', 'tab1')
|
||||
seed(records, 's2', 'tab1')
|
||||
const surface = createNativeSurface(ctx, records)
|
||||
expect(surface.close('s1', 'tab1')).toEqual({ type: 'editor', title: 'Files' })
|
||||
expect(calls, 'a background session closes through the per-session face').toEqual([{ op: 'closeIn', sessionId: 's1', tabId: 'tab1' }])
|
||||
expect(records.has('s1', 'tab1')).toBe(false)
|
||||
expect(records.has('s2', 'tab1')).toBe(true)
|
||||
removeSession('s2')
|
||||
expect(records.has('s2', 'tab1'), 'a gone session leaves no record behind').toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* CO-RESIDENT SEATS. With `keepMounted` the host keeps every visited body
|
||||
* mounted, so two sessions draw the SAME native id at the same time and one
|
||||
* unmounting no longer means its record is dead. These cases mount both seats
|
||||
* together: neither inherits the other's exploration state, and one going away
|
||||
* does not delete the other's record (the #636 chain).
|
||||
*/
|
||||
describe('NativeTabBody — co-resident seats', () => {
|
||||
const mountSeat = (
|
||||
records: ReturnType<typeof createNativeTabRecords>,
|
||||
service: ReturnType<typeof createBetterSidebarService>,
|
||||
store: ReturnType<typeof createSidebarStore>,
|
||||
sessionId: string,
|
||||
id: string,
|
||||
) => {
|
||||
store.setSession(sessionId)
|
||||
const sessions = {
|
||||
list: {
|
||||
subscribe: () => () => {},
|
||||
getSnapshot: () => ({ byId: { [sessionId]: { cwd: `/work/${sessionId}` } } }),
|
||||
},
|
||||
}
|
||||
const ctx = { sessions } as never
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const info = {
|
||||
tab: {
|
||||
id,
|
||||
kind: 'explorer',
|
||||
title: 'Files',
|
||||
contentId: `sidebar://${id}`,
|
||||
visible: true,
|
||||
navigation: { address: `sidebar://${id}`, params: undefined, revision: 0 },
|
||||
signal: new AbortController().signal,
|
||||
},
|
||||
}
|
||||
let root: Root | undefined
|
||||
act(() => {
|
||||
root = createRoot(host)
|
||||
root.render(createElement(NativeTabBody, {
|
||||
sessionId,
|
||||
ctx,
|
||||
store,
|
||||
service,
|
||||
records,
|
||||
descriptorId: 'explorer',
|
||||
useTabInfo: () => info,
|
||||
}))
|
||||
})
|
||||
return {
|
||||
host,
|
||||
unmount: () => { act(() => { root?.unmount() }); host.remove() },
|
||||
}
|
||||
}
|
||||
|
||||
it('keeps each seat\'s exploration, and an unmount only drops its own', async () => {
|
||||
// ONE store for the whole page (as in the app): the exploration sets are
|
||||
// per SESSION inside it, which is what lets both seats stay mounted.
|
||||
const store = createSidebarStore()
|
||||
const service = createBetterSidebarService(store)
|
||||
const records = createNativeTabRecords()
|
||||
records.attachStore(store)
|
||||
service.registerTab({
|
||||
id: 'explorer',
|
||||
title: 'Files',
|
||||
component: props => createElement('div', { 'data-seat': props.scope.sessionId },
|
||||
createElement('span', { 'data-expanded': (props.expanded ?? []).join(',') }),
|
||||
createElement('button', { 'data-toggle': props.scope.sessionId, onClick: () => props.onToggleDir?.('/work/src') })),
|
||||
})
|
||||
// BOTH seats name `tab1` — the host's counter restarts per session.
|
||||
const first = mountSeat(records, service, store, 's1', 'tab1')
|
||||
const second = mountSeat(records, service, store, 's2', 'tab1')
|
||||
|
||||
act(() => { first.host.querySelector<HTMLButtonElement>('[data-toggle="s1"]')!.click() })
|
||||
expect(first.host.querySelector('[data-expanded]')?.getAttribute('data-expanded')).toBe('/work/src')
|
||||
expect(second.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'), 'the second seat must not inherit').toBe('')
|
||||
|
||||
act(() => { second.host.querySelector<HTMLButtonElement>('[data-toggle="s2"]')!.click() })
|
||||
expect(first.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'), 'and it must not overwrite the first').toBe('/work/src')
|
||||
expect(second.host.querySelector('[data-expanded]')?.getAttribute('data-expanded')).toBe('/work/src')
|
||||
|
||||
// A Session switch remounts the body on a REAL host (measured), so an
|
||||
// unmount is NOT a close: the record has to wait for the remount that
|
||||
// brings the reader's exploration back.
|
||||
second.unmount()
|
||||
expect(records.has('s1', 'tab1'), 'the other seat keeps its record').toBe(true)
|
||||
expect(records.get('s1', 'tab1')?.expanded).toEqual(['/work/src'])
|
||||
expect(records.has('s2', 'tab1'), 'an unmount must not forget the state').toBe(true)
|
||||
|
||||
const again = mountSeat(records, service, store, 's2', 'tab1')
|
||||
expect(
|
||||
again.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'),
|
||||
'the remounted seat finds its own exploration again',
|
||||
).toBe('/work/src')
|
||||
expect(
|
||||
first.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'),
|
||||
'and the other seat is still untouched',
|
||||
).toBe('/work/src')
|
||||
|
||||
// Only a real close forgets a record.
|
||||
records.drop('s2', 'tab1')
|
||||
expect(records.has('s2', 'tab1')).toBe(false)
|
||||
first.unmount()
|
||||
expect(records.has('s1', 'tab1'), 'an unmount is not a close either').toBe(true)
|
||||
records.drop('s1', 'tab1')
|
||||
expect(records.has('s1', 'tab1')).toBe(false)
|
||||
again.unmount()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user