refactor(tabs): 精简改名/删除页签调解的原生枚举与用例装配(行为不变)

上一个提交(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 条。
This commit is contained in:
unsc9 committed 2026-10-11 16:49:24 +08:00
1 parent e876aa9667
commit e4a2d530ea
6 files changed
+97 -134

No files matched your search

+3 -3
View File
@@ -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)
+6 -30
View File
@@ -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
}
+8 -25
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'
@@ -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<SidebarTab> = {}
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
+37
View File
@@ -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,
}
}
+13 -11
View File
@@ -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)
+30 -65
View File
@@ -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<typeof createSidebarStore>
service: BetterSidebarService
records: ReturnType<typeof createNativeTabRecords>
close: ReturnType<typeof vi.fn>
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<typeof createNativeTabRecords>,
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')