Merge pull request #912 from UNscientific-9/fix/native-tab-path-reconcile

fix(tabs): 改名/删除的页签调解覆盖右侧栏原生页签,并让改名不再重载文档
This commit is contained in:
Atlas Zeng authored and GitHub committed 2026-10-12 01:40:02 +08:00
commit 963bef89f0
8 files changed
+554 -44

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'
@@ -392,7 +392,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 pathChanged = previousPath !== path
loadedPathRef.current = path
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)
+4 -1
View File
@@ -22,7 +22,7 @@
*/
import type { Context } from '../../context-types.ts'
import { fileAddressFor } from '../resource-address.ts'
import type { NativeTabParams, SidebarSurface } from '../service.ts'
import type { NativePathTab, NativeTabParams, SidebarSurface } from '../service.ts'
import type { NativeTabRecords } from './tab-adapter.tsx'
/** One open the surface could not place yet. */
@@ -67,6 +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 path (see {@link SidebarSurface.pathTabs}). */
pathTabs(): NativePathTab[]
}
/** The native controller, probed at call time (the service can arrive late). */
@@ -295,6 +297,7 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
return true
},
has: (tabId, sessionId) => sessionOf(tabId, sessionId) !== undefined,
pathTabs: () => records.pathTabs(),
flushPending,
dispose: () => {
unsubscribeList()
+59 -15
View File
@@ -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'
@@ -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):
@@ -149,6 +158,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 +284,7 @@ export function createNativeTabRecords(): NativeTabRecords {
...(meta === undefined ? {} : { meta }),
},
scope,
seat: sessionId,
expanded: expandedOf(scope.sessionId),
revealed: [],
version: 0,
@@ -281,12 +299,28 @@ 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> = {}
// 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
// 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 && newNavigation) {
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 +328,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 +345,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)
@@ -352,12 +400,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.
+37
View File
@@ -541,6 +541,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.
*
@@ -565,6 +587,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
/**
@@ -747,6 +776,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). */
@@ -1394,6 +1430,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,
}
}
+165 -26
View File
@@ -1,54 +1,193 @@
/**
* 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 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
* 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 type { NativePathTab } from './service.ts'
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 { 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, native: readonly NativePathTab[]): 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 native) {
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)
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
// 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
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
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 })
}
}
+206 -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,209 @@ describe('tree close-on-delete', () => {
})
})
describe('tree rename/delete reconciliation', () => {
/**
* 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 mountNativeSession(): {
store: ReturnType<typeof createSidebarStore>
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 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 { store, service, 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,
seat: { sessionId?: string; cwd?: string } = {},
): void => {
const sessionId = seat.sessionId ?? 'native-scope'
records.ensure({
sessionId,
id,
kind: 'editor',
title: 'a.ts',
params: { path },
scope: seat.cwd === undefined ? { sessionId } : { sessionId, cwd: seat.cwd },
})
}
// 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']
const resetModuleRegistries = (): void => {
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, records, context } = mountNativeSession()
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, records, context } = mountNativeSession()
openNativeFile(records, 'tab2', 'src/a.ts', { 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, records, context } = mountNativeSession()
openNativeFile(records, 'tab1', '/ws/a.ts')
openNativeFile(records, 'tab1', '/ws/a.ts', { 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, 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
// 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, 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')
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, records, context } = mountNativeSession()
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')
})
})