fix(tabs): 改名/删除的页签调解覆盖右侧栏原生页签,并让改名不再重载文档

文件树改名/删除后的页签调解只走 `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` 混拼时会把 `新名/.` 写进记录)。
This commit is contained in:
unsc9 committed 2026-10-10 22:19:07 +08:00
1 parent 1184d063c9
commit e876aa9667
7 files changed
+589 -42

No files matched your search

@@ -35,6 +35,14 @@
- tab 枚举覆盖 `state.splits` / `state.bottomSplits` / `state.floats`(浮动窗口的 tab 同样算打开)。走 service 路径(而非直改 state)使注册的生命周期回调照常触发。
- FileTree/TreePanel 透传 `onPathRenamed?` / `onPathDeleted?`(可选,测试可不接线);EditorHost 两处 `<TreePanel>` 接线。
### 实施偏差与修正(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 属性限定作用域,宿主默认不受影响):
+29 -1
View File
@@ -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)
+29 -2
View File
@@ -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
}
+75 -14
View File
@@ -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<SidebarTab> = {}
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.
+161 -24
View File
@@ -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<string, Retarget[]>()
/** 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 })
}
}
+241 -1
View File
@@ -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<typeof createNativeTabRecords>
close: ReturnType<typeof vi.fn>
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<typeof createNativeTabRecords>,
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()
+46
View File
@@ -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')
})
})