From e876aa9667839ed5cb513b05dcfe1cb0136aafe7 Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sat, 10 Oct 2026 20:49:15 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(tabs):=20=E6=94=B9=E5=90=8D/=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E7=9A=84=E9=A1=B5=E7=AD=BE=E8=B0=83=E8=A7=A3=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E5=8F=B3=E4=BE=A7=E6=A0=8F=E5=8E=9F=E7=94=9F=E9=A1=B5?= =?UTF-8?q?=E7=AD=BE=EF=BC=8C=E5=B9=B6=E8=AE=A9=E6=94=B9=E5=90=8D=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E9=87=8D=E8=BD=BD=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 文件树改名/删除后的页签调解只走 `state.bottomSplits`(插件自己的底部工作台), 而当前架构下文件默认开在 **DSH 原生右侧栏**:有原生承载面时 `service.openTab` 直接走 native,从不写 store。那些页签因此从不参与调解—— - 改名后:页签仍绑旧路径,`EditorHost` 的保存按旧名字写盘;旧名字已被改掉, `fs.write` 的 `mkdir -p` + 写入把旧文件(连同被一并删掉的父目录)重建出来, 界面还报「已保存」。仓库里于是同时留下新旧两份,新名字那份是旧内容。 - 删除后:连「有未保存改动,确定关吗」都不弹(`closePathTabs` 同样只遍历底部 工作台),Ctrl+S 直接复活刚删掉的文件。 改动: - `NativeTabRecords.pathTabs()` 按路径枚举原生记录(带 seat session), `NativeSurface.fileTabs()` 把它交给调解;`installedNativeSurface()` 是插件自身 读原生承载面的句柄(模块级,与 `editor-dirty.ts` 同款「每次激活一份」)。 - `tree-mutations.ts`:两个页签空间一起遍历;改名按**子树**匹配(与删除同口径, 此前只有删除覆盖子树,目录改名时子树里的页签连底部工作台也不改道);原生页签 的关闭带上自己的 seat session。 - 改名**不重载文档**:`path` 变化原本会让编辑器重载,而重载会换掉文档并丢掉只存在 于编辑器实例里的草稿——可改名并没有改字节。现在 `retargetPathTabs` 用 `markRetargetedPath` / `consumeRetargetedPath` 把这次移动交给编辑器认领:文档与 草稿留着,下一次保存落到新名字;没有这个标记的 `path` 变化(真实切换文件)照旧 加载。 - `tab-adapter.tsx` 的 `ensure()`:`path` 与 `meta` 一样,只被「尚未采纳的导航修订」 覆盖。原生承载面每次渲染都重投同一次导航,无条件按地址改 `path` 会把插件侧的 改址当渲染垃圾丢掉——调解刚改完,下一次渲染就改回旧名字。 - 设计文档补实施偏差:`docs/plans/2026-09-04-file-tree-rename-delete-design.md`。 用例:`tests/editor-unsaved-guard.spec.tsx` 新增 `tree rename/delete reconciliation`(原生页签改名改址、目录改名两个空间都改道、改名不重读文件且草稿 仍在、删除时脏页签先问、目录删除连子树关);`tests/native-surface.spec.ts` 新增 `path enumeration and the navigation gate`(枚举只含带路径的记录、插件侧改址扛得住 同修订重投、新修订仍按地址改回)。 复查后收紧(三支独立评审小队 + 自查收敛到同一处): - `retargetedPaths` 的键由「tab id」改成「编辑器看到的那一侧会话 + tab id」 (`pathTabKey`,写方与读方共用同一处定义):原生 tab id 每会话各自计数(`tab1` 每个会话都有),只按 id 记键时两个会话的编辑器共用一个槽——其中一个(哪怕它自己 的路径没动)在清理时会抹掉另一个尚未认领的移动,被抹掉的那个照旧重载、照旧丢草稿。 同一键仍允许一个移动被认领多次(两个席位显示同一会话的文件时)。 - 生命周期补齐:`clear` 现在按细键生效,编辑器卸载时回收,删除关闭页签时也回收 (原先只增不减:每次「改名没被已挂载编辑器认领」都会留一条)。 - `View` 记下 seat session:`pathTabs()` 不必再从视图键里拆 session,`retain()` 也 不再重复同一份拆分(键只是内部编码,不该被别处解析)。 - 子树尾段改用 `paths.ts` 的 `relativeTo`(分隔符与大小写口径与全仓其它相对路径 统一;原先手写的 slice 在旧路径带尾分隔符或大小写不同拼写时会算错);顺手删掉 一条与既有用例重复的回归用例(`native-surface.spec.ts` 既有的「同记录二次 ensure 且无 revision 时 path 跟着走」已经钉住同一事实)。 - **两种路径拼写**:聊天文件链接打开的页签,`path` 来自地址,而 `fileAddressFor` 在工作区内一律写相对拼写(`src/a.ts`);文件树改名给的却是绝对路径。最初按原样 比较,这类页签(正是默认打开方式)会整条判成「无关」,仍绑在刚被改名掉的旧名字 上。现在比较统一在「按会话 cwd 解析后的绝对拼写」上进行,写回记录时用调用方给的 新名;`movedPath` 的相等判断改用 `relativeTo` 的 `.`(字符串相等在 `E:/a` 与 `E:\a` 混拼时会把 `新名/.` 写进记录)。 --- ...26-09-04-file-tree-rename-delete-design.md | 8 + src/client/EditorHost.tsx | 30 ++- src/client/native/surface.ts | 31 ++- src/client/native/tab-adapter.tsx | 89 ++++++- src/client/tree-mutations.ts | 185 +++++++++++-- tests/editor-unsaved-guard.spec.tsx | 242 +++++++++++++++++- tests/native-surface.spec.ts | 46 ++++ 7 files changed, 589 insertions(+), 42 deletions(-) diff --git a/docs/plans/2026-09-04-file-tree-rename-delete-design.md b/docs/plans/2026-09-04-file-tree-rename-delete-design.md index 58c1ac77..d11ef7ef 100644 --- a/docs/plans/2026-09-04-file-tree-rename-delete-design.md +++ b/docs/plans/2026-09-04-file-tree-rename-delete-design.md @@ -35,6 +35,14 @@ - tab 枚举覆盖 `state.splits` / `state.bottomSplits` / `state.floats`(浮动窗口的 tab 同样算打开)。走 service 路径(而非直改 state)使注册的生命周期回调照常触发。 - FileTree/TreePanel 透传 `onPathRenamed?` / `onPathDeleted?`(可选,测试可不接线);EditorHost 两处 `` 接线。 +### 实施偏差与修正(2026-10-09) + +- **枚举面收窄成一处**:`state.splits` / `state.floats` 随自由窗口机制一起消失(指南 §11),`bottomSplits` 成了插件自己唯一的 tab 空间;而文件默认开在 **DSH 原生右侧栏**,那些 tab **不在 store 里**(`service.openTab` 有原生承载面时直接走 native,从不写 store)。于是改名/删除的调解**整体漏掉了右侧栏**:改名后页签仍绑旧路径,下一次保存把旧名字写回来(`mkdir -p` 连同被删的目录一起重建);删除后连「有未保存改动,确定关吗」都不弹,Ctrl+S 直接复活文件。修正:`NativeTabRecords.pathTabs()` 枚举原生记录,`retargetPathTabs` / `closePathTabs` 走两个空间。 +- **改名不再重载文档**:`path` 变化原本会触发编辑器重载,重载会换掉文档并丢掉只存在于编辑器实例里的草稿(改名并没有改字节)。现在改名通过 `consumeRetargetedPath` 认领,编辑器保留文档与草稿,下一次保存落到新名字;没有这个标记的 `path` 变化(真实切换文件)照旧加载。 +- **改名也走子树**:原实现只精确匹配 `tab.path === old`,删除那条却用 `isWithinWorkspace` 覆盖子树——目录改名时子树里的页签(含底部工作台)都不改道。现两条路径统一按子树匹配。 +- **两种路径拼写**:聊天文件链接打开的页签,其 `path` 来自地址,而 `fileAddressFor` 在工作区内一律写**相对**拼写(`src/a.ts`);文件树改名给的却是**绝对**路径。按原样比较时,这类页签(也就是默认打开方式)会整条判成「无关」,仍绑在刚被改名掉的旧名字上。现在比较统一在「按会话 cwd 解析后的绝对拼写」上进行,写回记录时用调用方给的新名;`movedPath` 的相等判断也交给 `relativeTo` 的 `.`(原先的字符串相等在 `E:/a` 与 `E:\a` 混拼时会漏出 `新名/.`)。 +- 客户端用例:`tests/editor-unsaved-guard.spec.tsx` 的 `tree rename/delete reconciliation`(含聊天链接的相对拼写、两个 seat 同号 id 的标记隔离);`tests/native-surface.spec.ts` 的 `path enumeration and the navigation gate`。 + ## 二级菜单视觉关系(layout.css,同批) 针对「二级菜单没有视觉关系」的反馈,两条纯 CSS 规则(仍以 `data-dsh-sidebar-submenu` body 属性限定作用域,宿主默认不受影响): diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index c787f27b..5e0ea330 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -42,7 +42,7 @@ import { TreePanel } from './TreePanel.tsx' import { t } from './locales.ts' import { relativeTo } from './paths.ts' import { resolveSidebarPath } from './paths.ts' -import { closePathTabs, retargetPathTabs } from './tree-mutations.ts' +import { clearRetargetedPath, closePathTabs, consumeRetargetedPath, pathTabKey, retargetPathTabs } from './tree-mutations.ts' import type { EditorToolbarControls, EditorToolbarState, FileViewerDescriptor } from './service.ts' import { firstLeaf, insertLeafAt, leafWithTab, mintTabId, type SidebarStore, type SidebarTab } from './state.ts' import css from './sidebar.module.css' @@ -373,7 +373,35 @@ export function EditorHost(props: { if (finalWidth !== treeWidthOf(tab)) patchMeta(ctx, tab, scope.sessionId, { treeWidth: finalWidth }) } + /** The rename-marker key for this tab (see `pathTabKey`): the session this + * editor reads and writes in, plus the tab id. */ + const retargetKey = pathTabKey(scope.sessionId, tab.id) + /** The path this editor last loaded (or was mounted on) — the rename retarget + * announces itself as a move away from it. */ + const loadedPathRef = useRef(path) + // A mounted editor is the only thing that can claim a retarget: once it is + // gone the announcement can never be applied, so it must not sit in the map + // for the rest of the page's life. A remount loads the record's current path + // either way, which is exactly what the marker would have preserved. + useEffect(() => () => { clearRetargetedPath(retargetKey) }, [retargetKey]) useEffect(() => { + // A rename moved the file, not its bytes: the tab follows the new name + // (tree-mutations' retargetPathTabs) while the loaded document — and an + // unsaved draft, which lives only in the editor instance — stays put. + // Reloading here would swap the content for the very same bytes and drop + // the draft with it, so the retarget is consumed instead; the next save + // simply lands on the new name. A path that moved WITHOUT that marker is a + // real switch to another file, which must load as usual. + // + // This runs BEFORE the toolbar reset below: nothing reloads, so the viewer + // keeps reporting the state it already has — clearing it here dropped the + // dirty mark (and with it the close guard) of a draft that was still + // unsaved. + const previousPath = loadedPathRef.current + const movedPath = previousPath !== path + loadedPathRef.current = path + if (movedPath && consumeRetargetedPath(retargetKey, previousPath, path)) return + if (!movedPath) clearRetargetedPath(retargetKey) // A (re)load or a path-less tab clears any hoisted toolbar state — the // fresh viewer re-registers its own. setToolbar(null) diff --git a/src/client/native/surface.ts b/src/client/native/surface.ts index bb2cc6eb..ceaf1177 100644 --- a/src/client/native/surface.ts +++ b/src/client/native/surface.ts @@ -23,7 +23,7 @@ import type { Context } from '../../context-types.ts' import { fileAddressFor } from '../resource-address.ts' import type { NativeTabParams, SidebarSurface } from '../service.ts' -import type { NativeTabRecords } from './tab-adapter.tsx' +import type { NativePathTab, NativeTabRecords } from './tab-adapter.tsx' /** One open the surface could not place yet. */ type Pending = @@ -67,6 +67,27 @@ export interface NativeSurface extends SidebarSurface { flushPending(): void /** Stop observing the session list and the mounted-seat feed. */ dispose(): void + /** + * Every native tab bound to a file path. The file tree's rename/delete + * reconciliation walks BOTH tab spaces, and this is the only handle on the + * right column's records — the store cannot see them. + */ + fileTabs(): NativePathTab[] +} + +/** + * The live native surface, for the plugin's OWN reconciliation. + * + * Module-level like `editor-dirty.ts`: one instance per client-plugin + * activation, and the surface is the only thing that can enumerate the right + * column's tabs. `undefined` before the surface is installed (and in unit + * tests that never mount one), which the callers read as "no native tabs". + */ +let installed: NativeSurface | undefined + +/** The installed native surface, or undefined when none is live. */ +export function installedNativeSurface(): NativeSurface | undefined { + return installed } /** The native controller, probed at call time (the service can arrive late). */ @@ -247,7 +268,7 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na } const unsubscribeList = ctx.sessions.list.subscribe(onListChange) evictGoneSessions() - return { + const surface: NativeSurface = { openTab({ sessionId, kind, params, revealIfOpened, preferNewPane }) { enqueue({ kind: 'tab', sessionId, tabKind: kind, params, revealIfOpened, preferNewPane: preferNewPane === true }) }, @@ -295,10 +316,16 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na return true }, has: (tabId, sessionId) => sessionOf(tabId, sessionId) !== undefined, + fileTabs: () => records.pathTabs(), flushPending, dispose: () => { unsubscribeList() mountedUnsubscribe?.() + // Only the surface that is still the installed one clears the handle: a + // reload installs its replacement before the old one tears down. + if (installed === surface) installed = undefined }, } + installed = surface + return surface } diff --git a/src/client/native/tab-adapter.tsx b/src/client/native/tab-adapter.tsx index 65383cc6..3e360ef2 100644 --- a/src/client/native/tab-adapter.tsx +++ b/src/client/native/tab-adapter.tsx @@ -82,6 +82,15 @@ export interface NativeTabInfo { /** One native tab's plugin-side view state. */ interface View { tab: SidebarTab + /** + * The SEAT session this record belongs to: the session the tab is drawn in, + * which is NOT `scope.sessionId` (a file address carries its own content + * session, and the two differ whenever a tab shows another session's file). + * Recorded rather than re-derived from the view key: `retain()` and + * `pathTabs()` both need it, the key encoding is an internal detail, and a + * session id may itself contain the separator. + */ + seat: string scope: SessionScope /** * A PROJECTION of the session's expansion set (never an authoritative copy): @@ -110,6 +119,26 @@ function viewKey(sessionId: string, id: string): string { return `${sessionId}::${id}` } +/** One native tab that carries a file path (the file tree's reconciliation + * handle: the right column's tabs live only in these records). */ +export interface NativePathTab { + /** The SEAT session the tab is drawn in (native tab ids restart per session, + * so this is what tells two same-numbered tabs apart). */ + sessionId: string + /** The session the tab's CONTENT belongs to — the `scope.sessionId` its + * editor runs with, and the half of the reconciliation's marker key the + * editor itself can reproduce. */ + scopeSessionId: string + /** That session's workspace root, for resolving `path` when the address + * stored it workspace-relative (a chat link does). */ + cwd: string | undefined + /** The native tab id. */ + id: string + /** The path the tab is bound to — a file path, or a browser tab's address + * (a url seed is stored on the same field). */ + path: string +} + /** The plugin-side record registry for native tabs. */ export interface NativeTabRecords { /** @@ -149,6 +178,14 @@ export interface NativeTabRecords { }): View /** One record by its seat session and native tab id. */ get(sessionId: string, id: string): View | undefined + /** + * Every record that carries a file path, across every live session. The file + * tree's rename/delete reconciliation walks BOTH tab spaces: the bottom + * workbench's splits come from the store, and the right column — where files + * actually open by default — only exists here. Without this the reconciliation + * silently skipped every native editor tab (its next save wrote the OLD name). + */ + pathTabs(): NativePathTab[] /** 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). */ @@ -267,6 +304,7 @@ export function createNativeTabRecords(): NativeTabRecords { ...(meta === undefined ? {} : { meta }), }, scope, + seat: sessionId, expanded: expandedOf(scope.sessionId), revealed: [], version: 0, @@ -281,12 +319,25 @@ export function createNativeTabRecords(): NativeTabRecords { // A navigation may carry new seed fields (the editor's in-place switch, // a browser tab pointed at another URL, a side chat switching threads); // the record's identity and any plugin-side mutation (title from - // `updateTab`) stay. `meta` is the exception — it also has a plugin-side - // writer, so only a navigation this record has not adopted yet may seed - // it (see {@link navigationRevisions}). + // `updateTab`) stay. `meta` and `path` are the exceptions — both also + // have a plugin-side writer, so only a navigation this record has not + // adopted yet may seed them (see {@link navigationRevisions}). const patch: Partial = {} + const adopted = revision !== undefined && navigationRevisions.get(key) !== revision ? revision : undefined + if (adopted !== undefined) { + navigationRevisions.set(key, adopted) + if (params?.meta !== undefined) patch.meta = params.meta + } + // `path` rides the same gate as `meta`: the file tree retargets an open + // editor onto a renamed file through `updateTab`, and while the host's + // address keeps naming the OLD path, honoring it on every render undid + // that retarget — the next save wrote a name the user had just renamed + // away, recreating it. Only a real navigation (a new revision) may move + // the record back onto its address. const nextPath = params?.path ?? params?.url - if (nextPath !== undefined && nextPath !== existing.tab.path) patch.path = nextPath + if (nextPath !== undefined && nextPath !== existing.tab.path && (revision === undefined || adopted !== undefined)) { + patch.path = nextPath + } // The landing line clears as well as sets: an in-place switch from // `a.c:131` to a bare `a.c` must not leave the old line behind and jump // the reader back there. Compared against the current value so the @@ -294,10 +345,6 @@ export function createNativeTabRecords(): NativeTabRecords { // keeps its identity. if (params?.line !== existing.tab.line) patch.line = params?.line if (params?.diff !== undefined) patch.diff = params.diff - if (revision !== undefined && navigationRevisions.get(key) !== revision) { - navigationRevisions.set(key, revision) - if (params?.meta !== undefined) patch.meta = params.meta - } // The expansion set always mirrors the CURRENT session state (a record // reused for another session must not keep the previous one's set). const expanded = expandedOf(scope.sessionId) @@ -315,6 +362,24 @@ export function createNativeTabRecords(): NativeTabRecords { return next }, get: (sessionId, id) => views.get(viewKey(sessionId, id)), + pathTabs() { + const tabs: NativePathTab[] = [] + for (const entry of views.values()) { + const path = entry.tab.path + // A browser tab's address lands on `path` too (a url seed is stored + // there), so this is every tab bound to a path or an address. + if (path !== undefined) { + tabs.push({ + sessionId: entry.seat, + scopeSessionId: entry.scope.sessionId, + cwd: entry.scope.cwd, + id: entry.tab.id, + path, + }) + } + } + return tabs + }, has: (sessionId, id) => views.has(viewKey(sessionId, id)), update(sessionId, id, patch) { const key = viewKey(sessionId, id) @@ -345,12 +410,8 @@ export function createNativeTabRecords(): NativeTabRecords { }, 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)) { + for (const [key, entry] of [...views]) { + if (!sessions.has(entry.seat)) { views.delete(key) // The ledger is part of the record (see `drop`): a session the user // deleted must not leave its revisions behind. diff --git a/src/client/tree-mutations.ts b/src/client/tree-mutations.ts index fd2f05d2..459a2340 100644 --- a/src/client/tree-mutations.ts +++ b/src/client/tree-mutations.ts @@ -1,54 +1,191 @@ /** * Open-tab reconciliation after a file-tree mutation (rename/delete). * - * The tree owns the rows; the TABS live in the sidebar state (the bottom - * workbench's split tree). A rename must retarget every - * tab whose `path` is the renamed file (the editor content survives and - * later saves land on the new path); a delete must close every tab at or - * under the removed path — files and anything inside a removed directory - * (a stale tab's next save would fail against a missing path). Both ride - * the SERVICE paths (`updateTab`/`closeTab`) rather than direct state - * reducers so the registered lifecycle callbacks fire like any other tab - * mutation. + * The tree owns the rows; the TABS live in TWO spaces: the bottom workbench's + * split tree (the sidebar state) and — where files actually open by default — + * DSH's native right Sidebar, whose records only the native surface can + * enumerate ({@link installedNativeSurface}). Both are walked here: skipping + * the native one left every right-column editor bound to the OLD path, so its + * next save wrote a name the user had just renamed away (recreating it) and a + * deleted file came back with no prompt. + * + * A rename must retarget every tab at the renamed path — files, and anything + * under a renamed directory (the same subtree rule the delete path already + * had) — so the editor content survives and later saves land on the new path; + * a delete must close every tab at or under the removed path. Both ride the + * SERVICE paths (`updateTab`/`closeTab`) rather than direct state reducers so + * the registered lifecycle callbacks fire like any other tab mutation. */ import type { Context } from '../context-types.ts' -import { baseName } from './FileTree.tsx' +import { baseName, isWithinWorkspace, relativeTo, resolveSidebarPath } from './paths.ts' import { confirmDiscardDraft } from './editor-dirty.ts' -import { allLeaves, type SidebarSnapshot, type SidebarStore, type SidebarTab } from './state.ts' -import { isWithinWorkspace } from './paths.ts' +import { installedNativeSurface } from './native/surface.ts' +import { allLeaves, type SidebarSnapshot, type SidebarStore } from './state.ts' -/** Every open tab that carries a file path. */ -function pathTabsOf(snapshot: SidebarSnapshot): SidebarTab[] { +/** One open tab that carries a file path, and the space it lives in. */ +interface PathTab { + /** The rename-marker key ({@link pathTabKey}). */ + key: string + id: string + /** The path in the tab's OWN spelling: what its editor holds, compares and + * marks against. */ + path: string + /** The same path resolved against the session cwd. The tree hands this module + * ABSOLUTE paths while a tab opened from a chat link carries the address's + * workspace-relative spelling, so every comparison runs here. */ + absolute: string + /** The native tab's seat session; absent for a bottom-workbench tab, whose + * updates resolve against the store's current session. */ + sessionId?: string +} + +/** + * The rename-marker key for one tab: the session its editor runs in, plus the + * tab id. + * + * Native tab ids restart per session — `tab1` exists in every conversation — + * so the id alone is not an identity. Keyed by the id alone, two seats' editors + * shared one marker, and an editor whose own path did NOT move (its effect + * clears the marker it finds) wiped the other seat's pending move; that other + * editor then reloaded the renamed file and dropped the draft this whole + * mechanism exists to protect. The session half is the one the editor reads in + * its `scope.sessionId`, so the writers here and the reader in `EditorHost` + * build the same key. + */ +export function pathTabKey(sessionId: string, tabId: string): string { + return `${sessionId}\u0000${tabId}` +} + +/** One announced move: the path a tab had, and the one it was re-pointed to. */ +interface Retarget { + from: string + to: string +} + +/** + * Retargets a rename has announced — the editor's side of the move. + * + * A tab is re-pointed by patching its `path`, and the editor host reloads + * whenever that path changes. Reloading a renamed file would swap the loaded + * document for the very same bytes while dropping the draft that lives only in + * the editor instance, so the retarget announces itself here instead: the + * editor keeps its document and the next save simply lands on the new name. + * + * A list per key rather than one slot: two tabs can still share a key (two + * seats showing the same session's file under the same id), and each of them + * has to claim the move on its own. + */ +const retargetedPaths = new Map() + +/** Announce that `key`'s file moved from `from` to `to`. */ +function markRetargetedPath(key: string, from: string, to: string): void { + const pending = retargetedPaths.get(key) + if (pending === undefined) retargetedPaths.set(key, [{ from, to }]) + else pending.push({ from, to }) +} + +/** Whether this exact move is one `key` has not applied yet. Consumes it: a + * tab that never sees the move must not swallow a later, unrelated one. */ +export function consumeRetargetedPath(key: string, from: string, to: string): boolean { + const pending = retargetedPaths.get(key) + if (pending === undefined) return false + const at = pending.findIndex(entry => entry.from === from && entry.to === to) + if (at === -1) return false + pending.splice(at, 1) + if (pending.length === 0) retargetedPaths.delete(key) + return true +} + +/** Forget a key's pending retargets. Called where the announcement can no + * longer be claimed — the editor unmounted (a fresh mount loads the record's + * current path anyway), loaded something else, or its tab is being closed — + * so the map cannot grow for the life of the page. */ +export function clearRetargetedPath(key: string): void { + retargetedPaths.delete(key) +} + +/** Every open tab that carries a file path, from BOTH tab spaces. */ +function pathTabsOf(snapshot: SidebarSnapshot): PathTab[] { + const tabs: PathTab[] = [] const state = snapshot.state - if (state === undefined) return [] - const tabs: SidebarTab[] = [] - for (const leaf of allLeaves(state.bottomSplits)) tabs.push(...leaf.tabs) - return tabs.filter(tab => tab.path !== undefined) + if (state !== undefined) { + const session = snapshot.sessionId ?? '' + for (const leaf of allLeaves(state.bottomSplits)) { + for (const tab of leaf.tabs) { + // A bottom-workbench row carries an absolute path already, and it is the + // same string the tree hands this module — one spelling, both fields. + if (tab.path !== undefined) { + tabs.push({ key: pathTabKey(session, tab.id), id: tab.id, path: tab.path, absolute: tab.path }) + } + } + } + } + for (const tab of installedNativeSurface()?.fileTabs() ?? []) { + tabs.push({ + key: pathTabKey(tab.scopeSessionId, tab.id), + id: tab.id, + path: tab.path, + // A chat link opens its tab with the ADDRESS's path, and `fileAddressFor` + // spells that workspace-relative whenever it knows the cwd. Comparing it + // raw against the tree's absolute paths skipped exactly those tabs, so the + // comparison runs on the resolved form while the tab keeps its spelling. + absolute: resolveSidebarPath(tab.cwd, tab.path), + sessionId: tab.sessionId, + }) + } + return tabs +} + +/** + * Where `path` moves to when `oldPath` (a file OR a directory) became + * `newPath`, or undefined when the tab is unaffected. A renamed directory + * takes its subtree along, so `dir/a.ts` follows `dir` → `renamed` — the same + * containment rule the delete path uses. + */ +function movedPath(path: string, oldPath: string, newPath: string): string | undefined { + if (!isWithinWorkspace(oldPath, path)) return undefined + // `relativeTo` owns the base→tail projection (separator and letter-case + // policy), and its `.` doubles as the equality test: a raw string compare + // missed `E:/a` vs `E:\a` and then spliced a stray `/.` onto the new name. + const tail = relativeTo(oldPath, path) + return tail === '.' ? newPath : `${newPath}/${tail}` } /** Retarget tabs after `oldPath` became `newPath` (title follows the new - * base name, matching how openFile titles editor tabs). */ + * base name, matching how openFile titles editor tabs). + * + * Files and anything under a renamed DIRECTORY are retargeted — the same + * subtree rule the delete path uses. The move is announced through + * {@link markRetargetedPath} so the editor keeps its document (and an unsaved + * draft) instead of reloading the new name. */ export function retargetPathTabs(ctx: Context, store: SidebarStore, oldPath: string, newPath: string): void { const service = ctx.get('betterSidebar') if (service === undefined) return // 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) + const moved = movedPath(tab.absolute, oldPath, newPath) + if (moved === undefined) continue + // The announcement has to match what the editor will see: it compares the + // path it holds (the tab's own spelling) with the one written here. + markRetargetedPath(tab.key, tab.path, moved) + service.updateTab(tab.id, { path: moved, title: baseName(moved) }, tab.sessionId) } } /** Close tabs at or under the removed `target` (a directory takes its whole * subtree of open files with it). A tab holding an unsaved draft asks first * (the same guard + copy as the sidebar's tab close); declining keeps the - * tab — its next save recreates the file, which is the user's call. */ + * tab — which is the user's call for the bottom workbench, and stays a + * conflict-gated save on the native side, never a silent re-create. */ export function closePathTabs(ctx: Context, store: SidebarStore, target: string, unsavedMessage: string): void { const service = ctx.get('betterSidebar') if (service === undefined) return for (const tab of pathTabsOf(store.getSnapshot())) { - const path = tab.path - if (path === undefined || (path !== target && !isWithinWorkspace(target, path))) continue + if (tab.absolute !== target && !isWithinWorkspace(target, tab.absolute)) continue if (!confirmDiscardDraft(tab.id, unsavedMessage)) continue - service.closeTab(tab.id) + // The tab is going away: a move announced for it can never be claimed. + clearRetargetedPath(tab.key) + service.closeTab(tab.id, tab.sessionId === undefined ? undefined : { sessionId: tab.sessionId }) } } diff --git a/tests/editor-unsaved-guard.spec.tsx b/tests/editor-unsaved-guard.spec.tsx index a75ccef3..23d593f7 100644 --- a/tests/editor-unsaved-guard.spec.tsx +++ b/tests/editor-unsaved-guard.spec.tsx @@ -23,7 +23,9 @@ import { clearEditorDirty, confirmDiscardDraft, dirtyCount, dirtyCountForSession, editorDirtyRevision, isEditorDirty, setEditorDirty, subscribeEditorDirty, } from '../src/client/editor-dirty.ts' -import { closePathTabs } from '../src/client/tree-mutations.ts' +import { clearRetargetedPath, closePathTabs, consumeRetargetedPath, pathTabKey, retargetPathTabs } from '../src/client/tree-mutations.ts' +import { createNativeSurface } from '../src/client/native/surface.ts' +import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx' setupReactAct() @@ -238,6 +240,244 @@ describe('tree close-on-delete', () => { }) }) +describe('tree rename/delete reconciliation', () => { + /** + * A real native surface over a real record registry, installed on the + * service like the client half does. Native tabs are the DEFAULT place a file + * opens (with a native surface installed, `openTab` never touches the bottom + * splits), so a reconciliation that only walked `bottomSplits` skipped the + * tabs the user actually has open. + */ + function mountNative(service: BetterSidebarService): { + records: ReturnType + close: ReturnType + context: Context + } { + const close = vi.fn() + const controller = { + openTab: () => {}, openResource: () => {}, close, focus: () => {}, + mounted: { getSnapshot: () => 'native-scope', subscribe: () => () => {} }, + openTabIn: () => {}, openResourceIn: () => {}, closeIn: () => {}, + } + const records = createNativeTabRecords() + const surfaceCtx = { + get: (name: string) => (name === 'sidebarRight' ? controller : undefined), + sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({}) } }, + } + const surface = createNativeSurface(surfaceCtx as never, records) + service.setSurface(surface) + const context = { betterSidebar: service, get: (name: string) => name === 'betterSidebar' ? service : undefined } as unknown as Context + return { records, close, context } + } + + /** One editor record bound to a file, as a native open would mint it. */ + const openNativeFile = ( + records: ReturnType, + id: string, + path: string, + ): void => { + records.ensure({ + sessionId: 'native-scope', + id, + kind: 'editor', + title: 'a.ts', + params: { path }, + scope: { sessionId: 'native-scope' }, + }) + } + + // Both registries are module-level: a leaked draft would break the + // neighbouring suites' counts, and a leftover retarget marker would suppress + // a later test's load. + const TEST_IDS = ['tab1', 'tab2', 'tab3', 'tab4', 'tab5'] + const TEST_SEATS = ['native-scope', 'other-scope'] + beforeEach(() => { + for (const id of TEST_IDS) { + clearEditorDirty(id) + for (const seat of TEST_SEATS) clearRetargetedPath(pathTabKey(seat, id)) + } + }) + afterEach(() => { + for (const id of TEST_IDS) { + clearEditorDirty(id) + for (const seat of TEST_SEATS) clearRetargetedPath(pathTabKey(seat, id)) + } + }) + + it('retargets a native tab when the FILE it shows is renamed', () => { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('native-scope') + const { records, context } = mountNative(service) + openNativeFile(records, 'tab1', '/ws/dir/a.ts') + + retargetPathTabs(context, store, '/ws/dir/a.ts', '/ws/dir/b.ts') + + expect(records.get('native-scope', 'tab1')?.tab).toMatchObject({ path: '/ws/dir/b.ts', title: 'b.ts' }) + // The move is announced for the editor, which keeps its document (and any + // unsaved draft) instead of reloading the new name. Each announcement is + // claimed once — a second claim of the same move reports false, and so does + // a move this tab was never told about. + const key = pathTabKey('native-scope', 'tab1') + expect(consumeRetargetedPath(key, '/ws/dir/a.ts', '/ws/dir/b.ts')).toBe(true) + expect(consumeRetargetedPath(key, '/ws/dir/a.ts', '/ws/dir/b.ts')).toBe(false) + expect(consumeRetargetedPath(key, '/ws/dir/a.ts', '/ws/elsewhere.ts')).toBe(false) + }) + + it('retargets a tab opened from a CHAT LINK (its address stores a workspace-relative path)', () => { + // `fileAddressFor` spells a path inside the workspace relatively, so a tab + // opened from chat holds `src/a.ts` while the tree renames by absolute path. + // Comparing the two raw skipped exactly those tabs — the default way a file + // reaches this column — and left them bound to the name the user had just + // renamed away. + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('native-scope') + const { records, context } = mountNative(service) + records.ensure({ + sessionId: 'native-scope', + id: 'tab2', + kind: 'editor', + title: 'a.ts', + params: { path: 'src/a.ts' }, + scope: { sessionId: 'native-scope', cwd: '/ws' }, + }) + + retargetPathTabs(context, store, '/ws/src/a.ts', '/ws/src/b.ts') + + // The tab follows to the new name, spelled absolutely now: `fs.write` + // resolves either spelling, and the record keeps the host's address until + // the host navigates it again. + expect(records.get('native-scope', 'tab2')?.tab.path).toBe('/ws/src/b.ts') + // The announcement carries the tab's OWN old spelling — what its editor + // compares against. + expect(consumeRetargetedPath(pathTabKey('native-scope', 'tab2'), 'src/a.ts', '/ws/src/b.ts')).toBe(true) + }) + + it('keeps one seat\'s pending move when another seat clears its own (native ids restart per session)', () => { + // `tab1` names a tab in EVERY conversation, so a rename reaches two seats at + // once. Keyed by the id alone they shared one marker: whichever editor ran + // its effect first (even one whose own path did not move — it clears what it + // finds) wiped the other's pending move, and that editor reloaded the + // renamed file with the draft this mechanism exists to protect. + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('native-scope') + const { records, context } = mountNative(service) + openNativeFile(records, 'tab1', '/ws/a.ts') + records.ensure({ + sessionId: 'other-scope', + id: 'tab1', + kind: 'editor', + title: 'a.ts', + params: { path: '/ws/a.ts' }, + scope: { sessionId: 'other-scope' }, + }) + + retargetPathTabs(context, store, '/ws/a.ts', '/ws/b.ts') + + expect(records.get('native-scope', 'tab1')?.tab.path).toBe('/ws/b.ts') + expect(records.get('other-scope', 'tab1')?.tab.path).toBe('/ws/b.ts') + const here = pathTabKey('native-scope', 'tab1') + const there = pathTabKey('other-scope', 'tab1') + clearRetargetedPath(here) + expect(consumeRetargetedPath(there, '/ws/a.ts', '/ws/b.ts')).toBe(true) + expect(consumeRetargetedPath(here, '/ws/a.ts', '/ws/b.ts')).toBe(false) + }) + + it('keeps the loaded document when a rename moves an OPEN tab (the draft survives)', async () => { + const mounted = mountSidebarWithEditor() + try { + await act(async () => { await Promise.resolve() }) + const readsBefore = fsRead.mock.calls.length + const tabOf = (): { id: string; path?: string } => allLeaves(mounted.store.getSnapshot().state!.bottomSplits) + .flatMap(leaf => leaf.tabs).find(candidate => candidate.path !== undefined)! + const id = tabOf().id + expect(isEditorDirty(id)).toBe(true) + + const context = { + get: (name: string) => name === 'betterSidebar' ? mounted.service : undefined, + } as unknown as Context + act(() => { retargetPathTabs(context, mounted.store, '/tmp/a.ts', '/tmp/b.ts') }) + await act(async () => { await Promise.resolve() }) + + // The tab follows the file… + expect(tabOf().path).toBe('/tmp/b.ts') + // …without re-reading it: a reload would replace the document with the + // same bytes and drop the draft, which lives only in the editor. + expect(fsRead.mock.calls.length).toBe(readsBefore) + expect(isEditorDirty(id)).toBe(true) + } finally { + mounted.unmount() + } + }) + + it('retargets the SUBTREE when a directory is renamed (both tab spaces)', () => { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('native-scope') + const { records, context } = mountNative(service) + openNativeFile(records, 'tab2', '/ws/dir/deep/a.ts') + // …and one in the bottom workbench (`target: 'bottom'` is the one open that + // stays in the plugin's own layout), which the old code DID walk but only + // for an exact path match. + service.openTab({ type: 'editor', title: 'c.ts', path: '/ws/dir/c.ts', target: 'bottom' }) + const before = records.get('native-scope', 'tab2')?.tab.path + + retargetPathTabs(context, store, '/ws/dir', '/ws/renamed') + + expect(before).toBe('/ws/dir/deep/a.ts') + expect(records.get('native-scope', 'tab2')?.tab.path).toBe('/ws/renamed/deep/a.ts') + const bottom = allLeaves(store.getSnapshot().state!.bottomSplits) + .flatMap(leaf => leaf.tabs).find(tab => tab.path !== undefined) + expect(bottom?.path).toBe('/ws/renamed/c.ts') + }) + + it('closes a native tab when its FILE is deleted, asking first when dirty', () => { + const confirmSpy = vi.fn().mockReturnValue(false) + vi.stubGlobal('confirm', confirmSpy) + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('native-scope') + const { records, close, context } = mountNative(service) + openNativeFile(records, 'tab3', '/ws/a.ts') + // The editor host registers the draft under the NATIVE tab id. + setEditorDirty('tab3', true, 'native-scope', '/ws/a.ts') + + closePathTabs(context, store, '/ws/a.ts', 'discard?') + expect(confirmSpy).toHaveBeenCalledWith('discard?') + expect(records.has('native-scope', 'tab3')).toBe(true) + expect(close).not.toHaveBeenCalled() + + confirmSpy.mockReturnValue(true) + closePathTabs(context, store, '/ws/a.ts', 'discard?') + expect(records.has('native-scope', 'tab3')).toBe(false) + // The host's own tab really closes too (the record alone would leave an + // empty pane behind). + expect(close).toHaveBeenCalledWith('tab3') + }) + + it('closes native tabs under a deleted DIRECTORY', () => { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + store.setSession('native-scope') + const { records, context } = mountNative(service) + openNativeFile(records, 'tab4', '/ws/dir/deep/a.ts') + openNativeFile(records, 'tab5', '/ws/other.ts') + + closePathTabs(context, store, '/ws/dir', 'discard?') + + expect(records.has('native-scope', 'tab4')).toBe(false) + expect(records.has('native-scope', 'tab5')).toBe(true) + }) +}) + describe('EditorHost dirty registration', () => { it('registers the open tab and clears it when the host unmounts', async () => { const store = createSidebarStore() diff --git a/tests/native-surface.spec.ts b/tests/native-surface.spec.ts index 84491a44..9cb080d2 100644 --- a/tests/native-surface.spec.ts +++ b/tests/native-surface.spec.ts @@ -1290,3 +1290,49 @@ describe('NativeTabBody — co-resident seats', () => { again.unmount() }) }) + +/** + * The file tree's rename/delete reconciliation reads the right column's tabs + * through `pathTabs()` — the store cannot see them — and it retargets a renamed + * file with `updateTab`, i.e. a plugin-side write of `path`. The native surface + * re-delivers the LAST navigation on every render, so an ungated `path` patch + * let the host's (stale) address win on the next pass: the retarget was undone + * and the editor saved onto the old name again. + */ +describe('native records: path enumeration and the navigation gate', () => { + const scope = { sessionId: 's1' } + + it('lists exactly the records that carry a file path, across seats', () => { + const records = createNativeTabRecords() + records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'a.ts', params: { path: '/w/a.ts' }, scope }) + records.ensure({ sessionId: 's1', id: 'tab2', kind: 'sidechat', title: 'chat', params: { meta: { threadId: 't' } }, scope }) + // A chat link's address is session-scoped and its path workspace-relative: + // the record keeps that spelling and carries the cwd that resolves it. + records.ensure({ sessionId: 's2', id: 'tab1', kind: 'editor', title: 'b.ts', params: { path: 'b.ts' }, scope: { sessionId: 's2', cwd: '/w' } }) + records.ensure({ sessionId: 's3', id: 'tab9', kind: 'browser', title: 'site', params: { url: 'https://example.test/x' }, scope: { sessionId: 's3' } }) + + expect(records.pathTabs().sort((left, right) => left.id.localeCompare(right.id))).toEqual([ + { sessionId: 's1', scopeSessionId: 's1', cwd: undefined, id: 'tab1', path: '/w/a.ts' }, + { sessionId: 's2', scopeSessionId: 's2', cwd: '/w', id: 'tab1', path: 'b.ts' }, + // A browser seed lands on `path` too (the address bar reads it there). + { sessionId: 's3', scopeSessionId: 's3', cwd: undefined, id: 'tab9', path: 'https://example.test/x' }, + ]) + }) + + it('keeps a plugin-side retarget across a re-delivery of the same navigation', () => { + const records = createNativeTabRecords() + const navigate = (revision: number): void => { + records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'a.ts', params: { path: '/w/a.ts' }, scope, revision }) + } + navigate(5) + records.update('s1', 'tab1', { path: '/w/b.ts', title: 'b.ts' }) + + // The surface re-renders: same navigation, same revision. + navigate(5) + expect(records.get('s1', 'tab1')?.tab).toMatchObject({ path: '/w/b.ts', title: 'b.ts' }) + + // A REAL navigation still wins: the host is addressing this tab again. + navigate(6) + expect(records.get('s1', 'tab1')?.tab.path).toBe('/w/a.ts') + }) +}) From e4a2d530ead66a0052f9566398fbaa35e38d930b Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sun, 11 Oct 2026 16:49:24 +0800 Subject: [PATCH 2/2] =?UTF-8?q?refactor(tabs):=20=E7=B2=BE=E7=AE=80?= =?UTF-8?q?=E6=94=B9=E5=90=8D/=E5=88=A0=E9=99=A4=E9=A1=B5=E7=AD=BE?= =?UTF-8?q?=E8=B0=83=E8=A7=A3=E7=9A=84=E5=8E=9F=E7=94=9F=E6=9E=9A=E4=B8=BE?= =?UTF-8?q?=E4=B8=8E=E7=94=A8=E4=BE=8B=E8=A3=85=E9=85=8D=EF=BC=88=E8=A1=8C?= =?UTF-8?q?=E4=B8=BA=E4=B8=8D=E5=8F=98=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上一个提交(e876aa9)过了一轮「代码精简」审查(复用 / 简化 / 效率 / 修在哪一层 四个角度,四个只读子代理并发),这里只落地行为完全不变的那批,净减 37 行。 - **原生页签枚举接回仓库既有的那条缝**:`SidebarSurface` 已有 `tabTypeOf?` (存在理由逐字相同:「service 自己看不见原生记录」),新增可选 `pathTabs?()`,service 上加 `@internal nativePathTabs()` 转发。删掉 `src/client/native/surface.ts` 里的模块级单例 `installed`、 `installedNativeSurface()`,以及 dispose 里那条「只有仍是当前实例才清句柄」 的顺序敏感守卫——那是同一个状态被存两份才需要的补丁。`NativePathTab` 从 `native/tab-adapter.tsx` 上移到 `service.ts`(与 `NativeTabParams` 并列, `SidebarSurface` 的方法就引用它),`createNativeSurface` 因此回到直接 `return { … }`,不再需要局部 `surface` 变量。 - `tab-adapter.tsx` 的 `ensure()`:`adopted`(三目求值 + `!== undefined` + `||`)改成具名布尔 `newNavigation`,`meta` 与 `path` 共用一次判断。真值表 逐格等价(revision 缺省 → true;已定义且不同 → true;已定义且相同 → false)。 - `closePathTabs` 的 `tab.absolute !== target &&` 多余:`isWithinWorkspace` 本身对目标自身就返回 true,一条判断同时覆盖「这个文件」与「这个目录下」。 - `EditorHost.tsx` 的布尔 `movedPath` 与 `tree-mutations.ts` 里返回**路径**的 `movedPath` 撞名,改成 `pathChanged`。 - 用例装配:`mountNativeSession()` 一次装好 store / service / editor 描述符 / 原生承载面 / 会话,`resetModuleRegistries()` 供 `beforeEach` 与 `afterEach` 共用,`openNativeFile()` 参数化 seat 与 cwd(收掉两处手写 `records.ensure`)。 六个用例各自少 5 行样板,用例数与断言不变(15 条)。 按「超出本次 diff / 会改变行为」跳过的三条,留档:改名标记改挂 `SidebarTab` 临时字段(要动持久化 schema 与 `updateTab` 公开 patch 类型)、标记在「宿主直接 关页签且编辑器不再挂载」这条极端路径上不回收(每次几百字节)、批量删除逐行重跑 全量枚举(低于可测量门槛)。 验证:`tsc --noEmit` 通过;eslint 对 6 个改动文件无输出;`vitest run --dir tests` 189 个文件 2240 条用例,184 个文件通过,8 条失败均与本次改动无关且为环境原因 (3 条 Windows 建符号链接 EPERM、1 条 `tar` 在 Windows 输出 CRLF 使结尾带 `\r`、 4 条中文语言标签)——覆盖本次改动模块的用例全绿(`editor-unsaved-guard` 15、 `native-surface` 50,另有 `service`、`editor-host`)。旁证:本地 `.tmp-audit/upstream-tree` 那份不含本改动的镜像副本,在 `tasks-model` 上红的是 同样 4 条。 --- src/client/EditorHost.tsx | 6 +- src/client/native/surface.ts | 36 ++--------- src/client/native/tab-adapter.tsx | 33 +++------- src/client/service.ts | 37 +++++++++++ src/client/tree-mutations.ts | 24 ++++---- tests/editor-unsaved-guard.spec.tsx | 95 +++++++++-------------------- 6 files changed, 97 insertions(+), 134 deletions(-) diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index 5e0ea330..df5ac6d2 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -398,10 +398,10 @@ export function EditorHost(props: { // dirty mark (and with it the close guard) of a draft that was still // unsaved. const previousPath = loadedPathRef.current - const movedPath = previousPath !== path + const pathChanged = previousPath !== path loadedPathRef.current = path - if (movedPath && consumeRetargetedPath(retargetKey, previousPath, path)) return - if (!movedPath) clearRetargetedPath(retargetKey) + if (pathChanged && consumeRetargetedPath(retargetKey, previousPath, path)) return + if (!pathChanged) clearRetargetedPath(retargetKey) // A (re)load or a path-less tab clears any hoisted toolbar state — the // fresh viewer re-registers its own. setToolbar(null) diff --git a/src/client/native/surface.ts b/src/client/native/surface.ts index ceaf1177..6d61b8ef 100644 --- a/src/client/native/surface.ts +++ b/src/client/native/surface.ts @@ -22,8 +22,8 @@ */ import type { Context } from '../../context-types.ts' import { fileAddressFor } from '../resource-address.ts' -import type { NativeTabParams, SidebarSurface } from '../service.ts' -import type { NativePathTab, NativeTabRecords } from './tab-adapter.tsx' +import type { NativePathTab, NativeTabParams, SidebarSurface } from '../service.ts' +import type { NativeTabRecords } from './tab-adapter.tsx' /** One open the surface could not place yet. */ type Pending = @@ -67,27 +67,8 @@ export interface NativeSurface extends SidebarSurface { flushPending(): void /** Stop observing the session list and the mounted-seat feed. */ dispose(): void - /** - * Every native tab bound to a file path. The file tree's rename/delete - * reconciliation walks BOTH tab spaces, and this is the only handle on the - * right column's records — the store cannot see them. - */ - fileTabs(): NativePathTab[] -} - -/** - * The live native surface, for the plugin's OWN reconciliation. - * - * Module-level like `editor-dirty.ts`: one instance per client-plugin - * activation, and the surface is the only thing that can enumerate the right - * column's tabs. `undefined` before the surface is installed (and in unit - * tests that never mount one), which the callers read as "no native tabs". - */ -let installed: NativeSurface | undefined - -/** The installed native surface, or undefined when none is live. */ -export function installedNativeSurface(): NativeSurface | undefined { - return installed + /** Every native tab bound to a path (see {@link SidebarSurface.pathTabs}). */ + pathTabs(): NativePathTab[] } /** The native controller, probed at call time (the service can arrive late). */ @@ -268,7 +249,7 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na } const unsubscribeList = ctx.sessions.list.subscribe(onListChange) evictGoneSessions() - const surface: NativeSurface = { + return { openTab({ sessionId, kind, params, revealIfOpened, preferNewPane }) { enqueue({ kind: 'tab', sessionId, tabKind: kind, params, revealIfOpened, preferNewPane: preferNewPane === true }) }, @@ -316,16 +297,11 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na return true }, has: (tabId, sessionId) => sessionOf(tabId, sessionId) !== undefined, - fileTabs: () => records.pathTabs(), + pathTabs: () => records.pathTabs(), flushPending, dispose: () => { unsubscribeList() mountedUnsubscribe?.() - // Only the surface that is still the installed one clears the handle: a - // reload installs its replacement before the old one tears down. - if (installed === surface) installed = undefined }, } - installed = surface - return surface } diff --git a/src/client/native/tab-adapter.tsx b/src/client/native/tab-adapter.tsx index 3e360ef2..1dbc336c 100644 --- a/src/client/native/tab-adapter.tsx +++ b/src/client/native/tab-adapter.tsx @@ -31,7 +31,7 @@ import { RenderBoundary } from '../RenderBoundary.tsx' import { OrphanedTab } from '../OrphanedTab.tsx' import { referenceInChat } from '../reference-in-chat.ts' import { useSessionRoot } from '../use-session-root.ts' -import type { BetterSidebarService } from '../service.ts' +import type { BetterSidebarService, NativePathTab } from '../service.ts' import { t } from '../locales.ts' import { isUnread, toggleExpanded } from '../state.ts' import type { SidebarStore, SidebarTab, TabType } from '../state.ts' @@ -119,26 +119,6 @@ function viewKey(sessionId: string, id: string): string { return `${sessionId}::${id}` } -/** One native tab that carries a file path (the file tree's reconciliation - * handle: the right column's tabs live only in these records). */ -export interface NativePathTab { - /** The SEAT session the tab is drawn in (native tab ids restart per session, - * so this is what tells two same-numbered tabs apart). */ - sessionId: string - /** The session the tab's CONTENT belongs to — the `scope.sessionId` its - * editor runs with, and the half of the reconciliation's marker key the - * editor itself can reproduce. */ - scopeSessionId: string - /** That session's workspace root, for resolving `path` when the address - * stored it workspace-relative (a chat link does). */ - cwd: string | undefined - /** The native tab id. */ - id: string - /** The path the tab is bound to — a file path, or a browser tab's address - * (a url seed is stored on the same field). */ - path: string -} - /** The plugin-side record registry for native tabs. */ export interface NativeTabRecords { /** @@ -323,9 +303,12 @@ export function createNativeTabRecords(): NativeTabRecords { // have a plugin-side writer, so only a navigation this record has not // adopted yet may seed them (see {@link navigationRevisions}). const patch: Partial = {} - const adopted = revision !== undefined && navigationRevisions.get(key) !== revision ? revision : undefined - if (adopted !== undefined) { - navigationRevisions.set(key, adopted) + // Whether the host is addressing this record with a navigation it has not + // delivered yet. A revision-less caller (the plugin's own layout, an + // older caller) counts as new: it has no ledger to be compared against. + const newNavigation = revision === undefined || navigationRevisions.get(key) !== revision + if (revision !== undefined && newNavigation) { + navigationRevisions.set(key, revision) if (params?.meta !== undefined) patch.meta = params.meta } // `path` rides the same gate as `meta`: the file tree retargets an open @@ -335,7 +318,7 @@ export function createNativeTabRecords(): NativeTabRecords { // away, recreating it. Only a real navigation (a new revision) may move // the record back onto its address. const nextPath = params?.path ?? params?.url - if (nextPath !== undefined && nextPath !== existing.tab.path && (revision === undefined || adopted !== undefined)) { + if (nextPath !== undefined && nextPath !== existing.tab.path && newNavigation) { patch.path = nextPath } // The landing line clears as well as sets: an in-place switch from diff --git a/src/client/service.ts b/src/client/service.ts index 853b9934..79497e4b 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -508,6 +508,28 @@ export interface NativeTabParams { meta?: unknown } +/** + * One native tab that carries a file path, as {@link SidebarSurface.pathTabs} + * reports it. The right column's records live in the native adapter and are + * invisible to the store, so this is the only handle on its open files. + */ +export interface NativePathTab { + /** The SEAT session the tab is drawn in (native tab ids restart per session, + * so this is what tells two same-numbered tabs apart). */ + sessionId: string + /** The session the tab's CONTENT belongs to — the `scope.sessionId` its + * editor runs with. */ + scopeSessionId: string + /** That session's workspace root, for resolving `path` when the address + * stored it workspace-relative (a chat link does). */ + cwd: string | undefined + /** The native tab id. */ + id: string + /** The path the tab is bound to — a file path, or a browser tab's address + * (a url seed is stored on the same field). */ + path: string +} + /** * The plugin's write face over DSH's native right Sidebar. * @@ -532,6 +554,13 @@ export interface SidebarSurface { * itself, and a tab id is not a type. */ tabTypeOf?(sessionId: string, tabId: string): string | undefined + /** + * Every native tab bound to a path. The file tree's rename/delete + * reconciliation walks BOTH tab spaces — the bottom workbench's splits come + * from the store, and the right column exists only here. A surface that + * cannot enumerate them omits this. + */ + pathTabs?(): NativePathTab[] /** Close one native tab; the closed record's type/title/meta, or undefined when the id is not native. */ close(sessionId: string, tabId: string): { type: string; title: string; meta?: unknown } | undefined /** @@ -707,6 +736,13 @@ export interface BetterSidebarService { * @internal Called once by the client half; not part of the consumer API. */ setSurface(surface: SidebarSurface | undefined): void + /** + * Every native tab bound to a path (empty when no native surface is + * installed). + * @internal The file tree's rename/delete reconciliation; not part of the + * consumer API. + */ + nativePathTabs(): NativePathTab[] } /** The file name of a path (both separators). */ @@ -1347,6 +1383,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe openFile, hostRouteUrl: (path: string): string => resolveHostRoute(path).href, setSurface: (next: SidebarSurface | undefined) => { surface = next }, + nativePathTabs: () => surface?.pathTabs?.() ?? [], clearUnread: clearUnreadFor, } } diff --git a/src/client/tree-mutations.ts b/src/client/tree-mutations.ts index 459a2340..a356ad02 100644 --- a/src/client/tree-mutations.ts +++ b/src/client/tree-mutations.ts @@ -3,11 +3,11 @@ * * The tree owns the rows; the TABS live in TWO spaces: the bottom workbench's * split tree (the sidebar state) and — where files actually open by default — - * DSH's native right Sidebar, whose records only the native surface can - * enumerate ({@link installedNativeSurface}). Both are walked here: skipping - * the native one left every right-column editor bound to the OLD path, so its - * next save wrote a name the user had just renamed away (recreating it) and a - * deleted file came back with no prompt. + * DSH's native right Sidebar, whose records the store cannot see (they are + * reported by {@link SidebarSurface.pathTabs}, read through the service). Both + * are walked here: skipping the native one left every right-column editor bound + * to the OLD path, so its next save wrote a name the user had just renamed away + * (recreating it) and a deleted file came back with no prompt. * * A rename must retarget every tab at the renamed path — files, and anything * under a renamed directory (the same subtree rule the delete path already @@ -17,9 +17,9 @@ * the registered lifecycle callbacks fire like any other tab mutation. */ import type { Context } from '../context-types.ts' +import type { NativePathTab } from './service.ts' import { baseName, isWithinWorkspace, relativeTo, resolveSidebarPath } from './paths.ts' import { confirmDiscardDraft } from './editor-dirty.ts' -import { installedNativeSurface } from './native/surface.ts' import { allLeaves, type SidebarSnapshot, type SidebarStore } from './state.ts' /** One open tab that carries a file path, and the space it lives in. */ @@ -105,7 +105,7 @@ export function clearRetargetedPath(key: string): void { } /** Every open tab that carries a file path, from BOTH tab spaces. */ -function pathTabsOf(snapshot: SidebarSnapshot): PathTab[] { +function pathTabsOf(snapshot: SidebarSnapshot, native: readonly NativePathTab[]): PathTab[] { const tabs: PathTab[] = [] const state = snapshot.state if (state !== undefined) { @@ -120,7 +120,7 @@ function pathTabsOf(snapshot: SidebarSnapshot): PathTab[] { } } } - for (const tab of installedNativeSurface()?.fileTabs() ?? []) { + for (const tab of native) { tabs.push({ key: pathTabKey(tab.scopeSessionId, tab.id), id: tab.id, @@ -163,7 +163,7 @@ export function retargetPathTabs(ctx: Context, store: SidebarStore, oldPath: str if (service === undefined) return // The tabs live in the snapshot's session: native ids restart per session. const snapshot = store.getSnapshot() - for (const tab of pathTabsOf(snapshot)) { + for (const tab of pathTabsOf(snapshot, service.nativePathTabs())) { const moved = movedPath(tab.absolute, oldPath, newPath) if (moved === undefined) continue // The announcement has to match what the editor will see: it compares the @@ -181,8 +181,10 @@ export function retargetPathTabs(ctx: Context, store: SidebarStore, oldPath: str export function closePathTabs(ctx: Context, store: SidebarStore, target: string, unsavedMessage: string): void { const service = ctx.get('betterSidebar') if (service === undefined) return - for (const tab of pathTabsOf(store.getSnapshot())) { - if (tab.absolute !== target && !isWithinWorkspace(target, tab.absolute)) continue + for (const tab of pathTabsOf(store.getSnapshot(), service.nativePathTabs())) { + // `isWithinWorkspace` is true for the target itself too, so one test covers + // both "this exact file" and "anything under this directory". + if (!isWithinWorkspace(target, tab.absolute)) continue if (!confirmDiscardDraft(tab.id, unsavedMessage)) continue // The tab is going away: a move announced for it can never be claimed. clearRetargetedPath(tab.key) diff --git a/tests/editor-unsaved-guard.spec.tsx b/tests/editor-unsaved-guard.spec.tsx index 23d593f7..9d07995d 100644 --- a/tests/editor-unsaved-guard.spec.tsx +++ b/tests/editor-unsaved-guard.spec.tsx @@ -242,13 +242,15 @@ describe('tree close-on-delete', () => { describe('tree rename/delete reconciliation', () => { /** - * A real native surface over a real record registry, installed on the - * service like the client half does. Native tabs are the DEFAULT place a file - * opens (with a native surface installed, `openTab` never touches the bottom - * splits), so a reconciliation that only walked `bottomSplits` skipped the - * tabs the user actually has open. + * A session with the editor type registered and a real native surface + * installed on the service, exactly like the client half does. Native tabs are + * the DEFAULT place a file opens (with a native surface installed, `openTab` + * never touches the bottom splits), so a reconciliation that only walked + * `bottomSplits` skipped the tabs the user actually has open. */ - function mountNative(service: BetterSidebarService): { + function mountNativeSession(): { + store: ReturnType + service: BetterSidebarService records: ReturnType close: ReturnType context: Context @@ -264,10 +266,13 @@ describe('tree rename/delete reconciliation', () => { get: (name: string) => (name === 'sidebarRight' ? controller : undefined), sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({}) } }, } - const surface = createNativeSurface(surfaceCtx as never, records) - service.setSurface(surface) + const store = createSidebarStore() + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) + service.setSurface(createNativeSurface(surfaceCtx as never, records)) + store.setSession('native-scope') const context = { betterSidebar: service, get: (name: string) => name === 'betterSidebar' ? service : undefined } as unknown as Context - return { records, close, context } + return { store, service, records, close, context } } /** One editor record bound to a file, as a native open would mint it. */ @@ -275,14 +280,16 @@ describe('tree rename/delete reconciliation', () => { records: ReturnType, id: string, path: string, + seat: { sessionId?: string; cwd?: string } = {}, ): void => { + const sessionId = seat.sessionId ?? 'native-scope' records.ensure({ - sessionId: 'native-scope', + sessionId, id, kind: 'editor', title: 'a.ts', params: { path }, - scope: { sessionId: 'native-scope' }, + scope: seat.cwd === undefined ? { sessionId } : { sessionId, cwd: seat.cwd }, }) } @@ -291,25 +298,17 @@ describe('tree rename/delete reconciliation', () => { // a later test's load. const TEST_IDS = ['tab1', 'tab2', 'tab3', 'tab4', 'tab5'] const TEST_SEATS = ['native-scope', 'other-scope'] - beforeEach(() => { + const resetModuleRegistries = (): void => { for (const id of TEST_IDS) { clearEditorDirty(id) for (const seat of TEST_SEATS) clearRetargetedPath(pathTabKey(seat, id)) } - }) - afterEach(() => { - for (const id of TEST_IDS) { - clearEditorDirty(id) - for (const seat of TEST_SEATS) clearRetargetedPath(pathTabKey(seat, id)) - } - }) + } + beforeEach(resetModuleRegistries) + afterEach(resetModuleRegistries) it('retargets a native tab when the FILE it shows is renamed', () => { - const store = createSidebarStore() - const service = createBetterSidebarService(store) - service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) - store.setSession('native-scope') - const { records, context } = mountNative(service) + const { store, records, context } = mountNativeSession() openNativeFile(records, 'tab1', '/ws/dir/a.ts') retargetPathTabs(context, store, '/ws/dir/a.ts', '/ws/dir/b.ts') @@ -331,19 +330,8 @@ describe('tree rename/delete reconciliation', () => { // Comparing the two raw skipped exactly those tabs — the default way a file // reaches this column — and left them bound to the name the user had just // renamed away. - const store = createSidebarStore() - const service = createBetterSidebarService(store) - service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) - store.setSession('native-scope') - const { records, context } = mountNative(service) - records.ensure({ - sessionId: 'native-scope', - id: 'tab2', - kind: 'editor', - title: 'a.ts', - params: { path: 'src/a.ts' }, - scope: { sessionId: 'native-scope', cwd: '/ws' }, - }) + const { store, records, context } = mountNativeSession() + openNativeFile(records, 'tab2', 'src/a.ts', { cwd: '/ws' }) retargetPathTabs(context, store, '/ws/src/a.ts', '/ws/src/b.ts') @@ -362,20 +350,9 @@ describe('tree rename/delete reconciliation', () => { // its effect first (even one whose own path did not move — it clears what it // finds) wiped the other's pending move, and that editor reloaded the // renamed file with the draft this mechanism exists to protect. - const store = createSidebarStore() - const service = createBetterSidebarService(store) - service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) - store.setSession('native-scope') - const { records, context } = mountNative(service) + const { store, records, context } = mountNativeSession() openNativeFile(records, 'tab1', '/ws/a.ts') - records.ensure({ - sessionId: 'other-scope', - id: 'tab1', - kind: 'editor', - title: 'a.ts', - params: { path: '/ws/a.ts' }, - scope: { sessionId: 'other-scope' }, - }) + openNativeFile(records, 'tab1', '/ws/a.ts', { sessionId: 'other-scope' }) retargetPathTabs(context, store, '/ws/a.ts', '/ws/b.ts') @@ -416,11 +393,7 @@ describe('tree rename/delete reconciliation', () => { }) it('retargets the SUBTREE when a directory is renamed (both tab spaces)', () => { - const store = createSidebarStore() - const service = createBetterSidebarService(store) - service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) - store.setSession('native-scope') - const { records, context } = mountNative(service) + const { store, service, records, context } = mountNativeSession() openNativeFile(records, 'tab2', '/ws/dir/deep/a.ts') // …and one in the bottom workbench (`target: 'bottom'` is the one open that // stays in the plugin's own layout), which the old code DID walk but only @@ -440,11 +413,7 @@ describe('tree rename/delete reconciliation', () => { it('closes a native tab when its FILE is deleted, asking first when dirty', () => { const confirmSpy = vi.fn().mockReturnValue(false) vi.stubGlobal('confirm', confirmSpy) - const store = createSidebarStore() - const service = createBetterSidebarService(store) - service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) - store.setSession('native-scope') - const { records, close, context } = mountNative(service) + const { store, records, close, context } = mountNativeSession() openNativeFile(records, 'tab3', '/ws/a.ts') // The editor host registers the draft under the NATIVE tab id. setEditorDirty('tab3', true, 'native-scope', '/ws/a.ts') @@ -463,11 +432,7 @@ describe('tree rename/delete reconciliation', () => { }) it('closes native tabs under a deleted DIRECTORY', () => { - const store = createSidebarStore() - const service = createBetterSidebarService(store) - service.registerTab({ id: 'editor', title: 'Files', dedupeKey: (tab) => tab.path, component: () => null }) - store.setSession('native-scope') - const { records, context } = mountNative(service) + const { store, records, context } = mountNativeSession() openNativeFile(records, 'tab4', '/ws/dir/deep/a.ts') openNativeFile(records, 'tab5', '/ws/other.ts')