From 673707cef75b355a4eb9bb93d00926e48e0f63d0 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Sun, 27 Sep 2026 12:21:41 +0800 Subject: [PATCH 1/7] fix(native): stop rebuilding the files takeover on every state pulse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `sync()`'s cleanup loop compared the live registrations against the DESCRIPTOR list, which never contains the `files` takeover (its key is `FILES_KIND`, not a descriptor id). Every store/service notification — a Session switch is one — therefore disposed and immediately rebuilt it: [native] DISPOSE type dsh-better-sidebar:files [native] register type dsh-better-sidebar:files Disposal unmounts that kind's body, so the explorer's own component state (its scroll offset) was rebuilt on every pulse even when the plugin-side record survived. Its lifetime really belongs to the editor type's switch, which the loop below already handles; skip it in the cleanup pass. Pinned by "keeps the files takeover registered across a Session switch pulse": reverting the guard turns it red (`expected 2 to be 1` — 2 is the rebuilt registration count). Rebased onto #777 (`4099700`): the guard itself now lives on `main` — its cleanup pass already skips `FILES_KIND` and releases through `disposeSafely` — so what remains in this commit is the comment above that guard, recording the second reason it is load-bearing (a re-registration on an already inactive context orphaned the id), plus the regression spec below. --- src/client/native/index.ts | 9 ++++--- tests/native-surface.spec.ts | 51 ++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/src/client/native/index.ts b/src/client/native/index.ts index 44b23edc..b4224045 100644 --- a/src/client/native/index.ts +++ b/src/client/native/index.ts @@ -379,10 +379,11 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void { wanted.set(descriptor.id, () => registerDescriptor(descriptor)) } for (const [descriptorId, registration] of live) { - // `files` is this module's OWN takeover, never a descriptor: it is - // owned by the editor-type switch below. Re-creating it here on every - // notification used to put its host-side type through a - // tear-down/re-register window on each store commit — and a + // `files` is this module's OWN takeover, never a descriptor (`wanted` + // only ever holds descriptor ids): its lifetime belongs to the + // editor-type switch below. Disposing it here on EVERY notification + // (any prefs/state pulse, a Session switch included) re-mounted the + // explorer body and lost the tree's own component state — and a // re-registration attempted on an already-inactive context (a plugin // reload) left the type registered with nobody holding its disposer, // so the same id could never be registered again for the rest of the diff --git a/tests/native-surface.spec.ts b/tests/native-surface.spec.ts index 88ca574c..4ab7b427 100644 --- a/tests/native-surface.spec.ts +++ b/tests/native-surface.spec.ts @@ -213,6 +213,57 @@ describe('service routing into the native surface', () => { }) describe('registerNativeSurface lifecycle (service-driven registration)', () => { + it('keeps the files takeover registered across a Session switch pulse', () => { + // Regression: `sync()`'s cleanup loop compared the live registrations with + // the DESCRIPTOR list, which never contains the `files` takeover — so every + // store/service pulse (a Session switch is one) disposed and rebuilt it. + // That remounts the explorer body, and a body remount loses the tree's own + // component state (its scroll offset) even though the record survives. + const store = createSidebarStore() + store.setSession('s1') + const service = createBetterSidebarService(store) + service.registerTab({ id: 'editor', title: 'Files', component: () => null, icon: () => null }) + const records = createNativeTabRecords() + + const registered: string[] = [] + const disposed: string[] = [] + const registry = { + current: { + register: (definition: { id: string; kind: string }) => { + registered.push(definition.kind) + return () => { disposed.push(definition.kind) } + }, + }, + } + let runInjected: (() => void) | undefined + const ctx = { + inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => void) => { + runInjected = () => { callback({ get: () => registry.current }) } + return { dispose: () => { runInjected = undefined } } + }, + get: () => registry.current, + slots: { + inject: (_key: string, callback: () => () => void) => callback(), + register: () => () => {}, + }, + } + const dispose = registerNativeSurface({ ctx: ctx as never, store, service, records }) + runInjected?.() + const filesCount = (): number => registered.filter(kind => kind === 'files').length + expect(filesCount(), 'the takeover registers once').toBe(1) + + // A Session switch is a store pulse: it must not tear the takeover down. + store.setSession('s2') + expect(filesCount(), 'a Session switch must not rebuild the takeover').toBe(1) + expect(disposed, 'and nothing was disposed on the way').toEqual([]) + + // Disabling the editor type DOES retire it — the lifetime it really owns. + store.setPrefs({ ...store.getPrefs(), tabsEnabled: { editor: false } }) + expect(disposed, 'the editor switch retired the takeover (with the editor type)').toContain('files') + expect(filesCount(), 'and it was not rebuilt while disabled').toBe(1) + dispose() + }) + it('registers the native tab types when the tab-type registry ARRIVES after the slot declaration', () => { // Regression: the native seat declares `sidebar.right.pane.tab` before it // provides `sidebarRightTabs`, so a registration driven by the slot From 7cf962652ee8c58ad1c69fc24f3010eeaeb64949 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Sun, 27 Sep 2026 12:23:25 +0800 Subject: [PATCH 2/7] fix(native): key a tab record by (session, tab id), not the bare id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Native tab ids restart in every session (`tab1`, `tab2`, …), and DSH 0.1.7 keeps a visited tab body mounted across hiding, tab selection and Session switches, so several sessions' same-named tabs are alive at once. The plugin's registry was a single-keyed map, which made the entering session's body adopt the leaving one's record — and the leaving body's unmount cleanup then delete it. The visible result was #636: after a conversation switch the explorer stopped responding entirely (no request sent), in both directions. Records are now filed under `sessionId::tabId`, and the seat session is carried explicitly instead of inferred: - `createNativeTabRecords` takes the seat session on `ensure`, and `get/has/update/drop/toggleExpanded/versionOf` all take it too; `retain(sessions)` reclaims the records of sessions that are gone; - the title slot gets its own seat `sessionId` — the chip is drawn BEFORE the body, so it used to read whichever record the live slot happened to hold (another conversation's title on the switch frame); - `SidebarSurface.update/has/activate` take an optional `sessionId`: with one, it names the session; without, the mounted seat answers, a unique match still resolves, and an id that names a tab in several sessions resolves to none rather than guessing (writing into another conversation is worse than refusing); - `BetterSidebarService.updateTab` forwards it, and the six call sites that know their own scope (EditorHost, SideChatView, ChangesTab, tree-mutations) pass theirs. Tests (native-surface.spec.ts, +8): per-seat-session identity (same-named tabs stay apart, a patch/drop hits exactly one session, `retain` reclaims), and surface resolution (explicit session wins, mounted seat is the fallback, an ambiguous bare id is refused, close plus dead-session reclaim). Each is red without this change. --- src/client/EditorHost.tsx | 18 +- src/client/SideChatView.tsx | 7 +- src/client/changes/ChangesTab.tsx | 2 +- src/client/native/index.ts | 5 +- src/client/native/surface.ts | 71 ++++++- src/client/native/tab-adapter.tsx | 155 +++++++++++----- src/client/service.ts | 38 ++-- src/client/tree-mutations.ts | 6 +- tests/native-surface.spec.ts | 299 +++++++++++++++++++++++++++--- 9 files changed, 502 insertions(+), 99 deletions(-) diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index 3c2359e4..c14f0f17 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -83,9 +83,15 @@ function treeWidthOf(tab: SidebarTab): number { : TREE_WIDTH_DEFAULT } -/** Merge a patch into the tab's persisted meta (rides the layout). */ -function patchMeta(ctx: Context, tab: SidebarTab, patch: Record): void { - ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { ...metaOf(tab), ...patch } }) +/** + * Merge a patch into the tab's persisted meta (rides the layout). + * + * `sessionId` is the seat session: native ids restart per session and every + * visited tab's body stays mounted (0.1.7 `keepMounted`), so the tab this call + * means must be named, not inferred from whichever seat is on screen. + */ +function patchMeta(ctx: Context, tab: SidebarTab, sessionId: string, patch: Record): void { + ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { ...metaOf(tab), ...patch } }, sessionId) } /** Clamp one dock width into the contract range. */ @@ -160,7 +166,7 @@ export function EditorHost(props: { */ const openFile = (absolute: string): void => { if (inPlace) { - ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }) + ctx.get('betterSidebar')?.updateTab(tab.id, { path: absolute, title: baseName(absolute) }, scope.sessionId) } else { openSidebarFile(ctx, scope.sessionId, absolute) } @@ -286,7 +292,7 @@ export function EditorHost(props: { dragRef.current = null setDragWidth(null) const finalWidth = clampTreeWidth(drag.startWidth + (drag.startX - event.clientX)) - if (finalWidth !== treeWidthOf(tab)) patchMeta(ctx, tab, { treeWidth: finalWidth }) + if (finalWidth !== treeWidthOf(tab)) patchMeta(ctx, tab, scope.sessionId, { treeWidth: finalWidth }) } useEffect(() => { @@ -368,7 +374,7 @@ export function EditorHost(props: { const treeOpen = treeOpenOf(tab) /** Persist the panel flag on the tab (survives reloads with the layout). */ - const toggleTree = (): void => { patchMeta(ctx, tab, { treeOpen: !treeOpen }) } + const toggleTree = (): void => { patchMeta(ctx, tab, scope.sessionId, { treeOpen: !treeOpen }) } const saveLabel = toolbar === null ? '' : toolbar.saveState === 'saving' ? t('loading') : toolbar.saveState === 'saved' ? t('saved') diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index 91464b7c..1dad1f52 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -436,7 +436,8 @@ export function SideChatView(props: { setError(null) try { const { childId } = await api.sidechatStart(scope.sessionId) - ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { threadId: childId } }) + // Name the seat session: the same native id names a tab in every session. + ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { threadId: childId } }, scope.sessionId) } catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)) } finally { @@ -460,12 +461,12 @@ export function SideChatView(props: { const title = threadDisplayTitle(display) if (title !== '' && title !== tab.title) { try { - ctx.get('betterSidebar')?.updateTab(tab.id, { title }) + ctx.get('betterSidebar')?.updateTab(tab.id, { title }, scope.sessionId) } catch { // A stale title is cosmetic; the thread keeps working. } } - }, [summary, tab.id, tab.title, ctx]) + }, [summary, tab.id, tab.title, ctx, scope.sessionId]) /** One transcript pull: the thread's own events beyond the cached tail * (first attach = the whole seed-cut slice; polls = afterSeq deltas), diff --git a/src/client/changes/ChangesTab.tsx b/src/client/changes/ChangesTab.tsx index a18cacbc..4e3471b8 100644 --- a/src/client/changes/ChangesTab.tsx +++ b/src/client/changes/ChangesTab.tsx @@ -118,7 +118,7 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen const patchMeta = (patch: ChangesMeta): void => { ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { ...(tab.meta as ChangesMeta | undefined ?? {}), ...patch }, - }) + }, scope.sessionId) } const chooseLens = (next: Lens): void => { diff --git a/src/client/native/index.ts b/src/client/native/index.ts index b4224045..5f5f4b50 100644 --- a/src/client/native/index.ts +++ b/src/client/native/index.ts @@ -260,7 +260,10 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void { disposers.push(ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: id, - inject: () => ({ records, service, descriptorId: injected.descriptorId }), + // The chip is drawn per session and BEFORE the body, so it needs its + // own session id: every session's tabs live in one registry, and a + // chip that guessed the session would show another one's title. + inject: (sessionId: string) => ({ records, service, descriptorId: injected.descriptorId, sessionId }), }, NativeTabTitle))) } catch (error) { for (const dispose of disposers) disposeSafely(dispose, `native tab slot "${id}"`) diff --git a/src/client/native/surface.ts b/src/client/native/surface.ts index 4886f205..0cb19db8 100644 --- a/src/client/native/surface.ts +++ b/src/client/native/surface.ts @@ -172,9 +172,57 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na if (!place(entry)) pending.push(entry) } + /** + * The seat session a bare tab id belongs to. + * + * The public write face speaks ids without sessions (its consumer contract), + * while records are per seat session — the same native id names a tab in + * EVERY session. The mounted seat answers for a caller acting on what is on + * screen; with no seat mounted (a global panel) a unique match across the + * live sessions still resolves, and an id that names a tab in more than one + * session resolves to none — guessing would write into another conversation. + * @param tabId - the native tab id. + * @param sessionId - the explicit session, when the caller has one. + * @returns the owning session, or undefined. + */ + const sessionOf = (tabId: string, sessionId?: string): string | undefined => { + if (sessionId !== undefined) return records.has(sessionId, tabId) ? sessionId : undefined + const mounted = mountedSessionId(ctx) + if (mounted !== undefined && records.has(mounted, tabId)) return mounted + const byId = ctx.sessions.list.getSnapshot().byId ?? {} + let found: string | undefined + for (const candidate of Object.keys(byId)) { + if (!records.has(candidate, tabId)) continue + if (found !== undefined && found !== candidate) return undefined + found = candidate + } + return found + } + + /** + * Forget the records of sessions that no longer exist. + * + * A `keepMounted` body survives until its tab or its session ends, and a + * session the user DELETED never unmounts anything the plugin can hook, so + * its records (and their tree/edit state) would live for the life of the + * page. The mounted session is always kept: it can be missing from `byId` + * for a moment while the list reloads. + */ + const evictGoneSessions = (): void => { + try { + const live = new Set(Object.keys(ctx.sessions.list.getSnapshot().byId ?? {})) + const mounted = mountedSessionId(ctx) + if (mounted !== undefined) live.add(mounted) + records.retain(live) + } catch { + // A read failure is not evidence that sessions are gone; keep everything. + } + } + // Two feeds flush the queue: the mounted seat (a session coming on screen) // and the session list, which also stays the pulse that picks the native - // service up when it is provided after this surface was created. + // service up when it is provided after this surface was created. The list + // pulse additionally reclaims the records of sessions that are gone. let mountedUnsubscribe: (() => void) | undefined const onListChange = (): void => { if (mountedUnsubscribe === undefined) { @@ -182,8 +230,10 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na if (typeof mounted?.subscribe === 'function') mountedUnsubscribe = mounted.subscribe(flushPending) } flushPending() + evictGoneSessions() } const unsubscribeList = ctx.sessions.list.subscribe(onListChange) + evictGoneSessions() return { openTab({ sessionId, kind, params, revealIfOpened }) { enqueue({ kind: 'tab', sessionId, tabKind: kind, params, revealIfOpened }) @@ -195,9 +245,11 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na return fileAddressFor(sessionId, cwd, path) }, close(sessionId, tabId) { - const record = records.get(tabId) + // Read through the SESSION: the same native id names a tab in every + // session, so a bare read can hand back another session's record. + const record = records.get(sessionId, tabId) if (record === undefined) return undefined - records.drop(tabId) + records.drop(sessionId, tabId) const api = controller() if (api !== undefined) { if (sessionId === mountedSessionId(ctx)) api.close(tabId) @@ -205,18 +257,19 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na } return { type: record.tab.type, title: record.tab.title } }, - update(tabId, patch) { - if (!records.has(tabId)) return false - records.update(tabId, patch) + update(tabId, patch, sessionId) { + const owner = sessionOf(tabId, sessionId) + if (owner === undefined) return false + records.update(owner, tabId, patch) return true }, - activate(tabId) { + activate(tabId, sessionId) { // The native surface has no cross-pane activation face the plugin needs: // a tab is focused by opening its (kind, address) again, which the // native open already de-duplicates. - return records.has(tabId) + return sessionOf(tabId, sessionId) !== undefined }, - has: tabId => records.has(tabId), + has: (tabId, sessionId) => sessionOf(tabId, sessionId) !== undefined, flushPending, dispose: () => { unsubscribeList() diff --git a/src/client/native/tab-adapter.tsx b/src/client/native/tab-adapter.tsx index 89bfa218..c9dd34dc 100644 --- a/src/client/native/tab-adapter.tsx +++ b/src/client/native/tab-adapter.tsx @@ -20,7 +20,7 @@ * Nothing here is a singleton: the registry is created once per client * activation and handed to every registration. */ -import { createElement, useEffect, useMemo, useSyncExternalStore } from 'react' +import { createElement, useMemo, useSyncExternalStore } from 'react' import type { ComponentType, ReactNode } from 'react' import type { Context } from '../../context-types.ts' import type { SessionScope } from '../api.ts' @@ -83,16 +83,35 @@ interface View { version: number } +/** + * The record key: one native tab id names a tab in EVERY session (the host's + * per-session counter restarts at `tab1`), and DSH 0.1.7 keeps visited bodies + * mounted through hiding, tab selection and Session switches + * (`SidebarRightTabDefinition.keepMounted`). Two sessions' `tab1` are therefore + * ALIVE AT THE SAME TIME — a registry keyed by the bare id would hand one + * session's tree/scroll/draft state to the other. The seat's session is part + * of the record's identity. + */ +function viewKey(sessionId: string, id: string): string { + return `${sessionId}::${id}` +} + /** The plugin-side record registry for native tabs. */ export interface NativeTabRecords { /** - * The synthetic record for a native tab, minted on first sight and kept - * across navigations (a navigation refreshes the seed fields, never the + * The synthetic record for one seat's native tab, minted on first sight and + * kept across navigations (a navigation refreshes the seed fields, never the * identity or a plugin-side title/meta mutation). - * @param input - the native record and the session it lives in. + * @param input - the native record, its seat session, and the content scope. * @returns the current view state. */ ensure(input: { + /** + * The SEAT session this tab is drawn in — the record's identity. Not to be + * confused with `scope.sessionId`: a file address carries its own session, + * which is the namespace its content is read/written in. + */ + sessionId: string id: string kind: string title: string @@ -106,20 +125,30 @@ export interface NativeTabRecords { */ mint?: () => { title?: string; meta?: unknown } | undefined }): View - /** One record by native tab id. */ - get(id: string): View | undefined - /** Whether this id belongs to a native tab (vs the plugin's own layout). */ - has(id: string): boolean + /** One record by its seat session and native tab id. */ + get(sessionId: string, id: string): View | undefined + /** Whether this seat session has a record for the id. */ + has(sessionId: string, id: string): boolean /** Merge a patch into the synthetic record (the `updateTab` path). */ - update(id: string, patch: { title?: string; path?: string; meta?: unknown }): void - /** Forget a record (the native tab closed). */ - drop(id: string): void + update(sessionId: string, id: string, patch: { title?: string; path?: string; meta?: unknown }): void + /** + * Forget one record. Called when the NATIVE TAB really closes — never from a + * body unmount, because a Session switch remounts bodies while the reader's + * state must survive. + */ + drop(sessionId: string, id: string): void /** Toggle one directory in a record's expansion set. */ - toggleExpanded(id: string, path: string): void + toggleExpanded(sessionId: string, id: string, path: string): void + /** + * Keep only records of these sessions; the rest are forgotten. A session the + * user deleted never unmounts anything the plugin can hook, so its records + * (and a retained body) would otherwise live for the life of the page. + */ + retain(sessions: ReadonlySet): void /** Mint the next instance number of a kind (titles like "Terminal 2"). */ nextInstance(kind: string): number /** A per-record version for `useSyncExternalStore`. */ - versionOf(id: string): number + versionOf(sessionId: string, id: string): number /** Subscribe to record changes (title/path/meta/expanded). */ subscribe(listener: () => void): () => void } @@ -130,13 +159,14 @@ export function createNativeTabRecords(): NativeTabRecords { const instances = new Map() const listeners = new Set<() => void>() const notify = (): void => { for (const listener of listeners) listener() } - const put = (id: string, view: View): void => { - views.set(id, { ...view, version: view.version + 1 }) + const put = (key: string, view: View): void => { + views.set(key, { ...view, version: view.version + 1 }) notify() } return { - ensure({ id, kind, title, params, scope, mint }) { - const existing = views.get(id) + ensure({ sessionId, id, kind, title, params, scope, mint }) { + const key = viewKey(sessionId, id) + const existing = views.get(key) if (existing === undefined) { const seeded = params?.title === undefined && params?.meta === undefined ? mint?.() : undefined const meta = params?.meta ?? seeded?.meta @@ -154,7 +184,7 @@ export function createNativeTabRecords(): NativeTabRecords { revealed: [], version: 0, } - views.set(id, minted) + views.set(key, minted) return minted } // A navigation may carry new seed fields (the editor's in-place switch, @@ -170,38 +200,54 @@ export function createNativeTabRecords(): NativeTabRecords { patch.meta = { ...meta, url: params.url } } if (existing.scope.cwd !== scope.cwd) { - views.set(id, { ...existing, scope, tab: { ...existing.tab, ...patch } }) - return views.get(id)! + views.set(key, { ...existing, scope, tab: { ...existing.tab, ...patch } }) + return views.get(key)! } if (Object.keys(patch).length === 0) return existing const next: View = { ...existing, tab: { ...existing.tab, ...patch } } - views.set(id, next) + views.set(key, next) return next }, - get: id => views.get(id), - has: id => views.has(id), - update(id, patch) { - const entry = views.get(id) + get: (sessionId, id) => views.get(viewKey(sessionId, id)), + has: (sessionId, id) => views.has(viewKey(sessionId, id)), + update(sessionId, id, patch) { + const key = viewKey(sessionId, id) + const entry = views.get(key) if (entry === undefined) return - put(id, { ...entry, tab: { ...entry.tab, ...patch } }) + put(key, { ...entry, tab: { ...entry.tab, ...patch } }) }, - drop(id) { - if (views.delete(id)) notify() + drop(sessionId, id) { + if (views.delete(viewKey(sessionId, id))) notify() }, - toggleExpanded(id, path) { - const entry = views.get(id) + toggleExpanded(sessionId, id, path) { + const key = viewKey(sessionId, id) + const entry = views.get(key) if (entry === undefined) return const expanded = entry.expanded.includes(path) ? entry.expanded.filter(candidate => candidate !== path) : [...entry.expanded, path] - put(id, { ...entry, expanded }) + put(key, { ...entry, expanded }) + }, + retain(sessions) { + let dropped = false + for (const key of [...views.keys()]) { + // The key's prefix is the seat session; a session id may itself carry + // the separator only if the host allowed one, so split on the first. + const separator = key.indexOf('::') + const owner = separator === -1 ? key : key.slice(0, separator) + if (!sessions.has(owner)) { + views.delete(key) + dropped = true + } + } + if (dropped) notify() }, nextInstance(kind) { const next = (instances.get(kind) ?? 0) + 1 instances.set(kind, next) return next }, - versionOf: id => views.get(id)?.version ?? 0, + versionOf: (sessionId, id) => views.get(viewKey(sessionId, id))?.version ?? 0, subscribe(listener) { listeners.add(listener) return () => { listeners.delete(listener) } @@ -237,10 +283,10 @@ export interface NativeBodyFrameworkProps { } /** Subscribe a component to its own record's mutations. */ -function useRecordVersion(records: NativeTabRecords, id: string): number { +function useRecordVersion(records: NativeTabRecords, sessionId: string, id: string): number { return useSyncExternalStore( listener => records.subscribe(listener), - () => records.versionOf(id), + () => records.versionOf(sessionId, id), ) } @@ -255,16 +301,28 @@ function useSessionCwd(ctx: Context, sessionId: string): string | undefined { /** * One plugin tab rendered inside the native right Sidebar: the descriptor's * own component with the plugin's props, over a synthetic record minted from - * the native tab and dropped when the record ends. + * the native tab. + * + * The record OUTLIVES this component on purpose. `keepMounted` holds a body + * mounted through hiding and tab switches, but a Session switch still remounts + * it on the host side (measured: `drop`+`mint` for the SAME key inside one + * switch), and the reader's exploration state only lives in the record. The + * registry therefore keeps it until the tab is closed (`surface.close`) or its + * session disappears (`retain`) — see the record registry's own notes. */ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkProps): ReactNode { const { ctx, store, service, records, descriptorId, useTabInfo } = props const info = useTabInfo() const nativeTab = info.tab - const version = useRecordVersion(records, nativeTab.id) - const sessionId = props.sessionIdOf?.(info) ?? props.sessionId - const cwd = useSessionCwd(ctx, sessionId) - const scope = useMemo((): SessionScope => ({ sessionId, cwd }), [sessionId, cwd]) + // TWO sessions meet here and they are not interchangeable: the SEAT session + // (the native column this body is drawn in) keys the record, while the SCOPE + // session is the namespace the content is read/written in — a file address + // carries its own session, which is the one that resolves its path. + const seatSessionId = props.sessionId + const scopeSessionId = props.sessionIdOf?.(info) ?? seatSessionId + const version = useRecordVersion(records, seatSessionId, nativeTab.id) + const cwd = useSessionCwd(ctx, scopeSessionId) + const scope = useMemo((): SessionScope => ({ sessionId: scopeSessionId, cwd }), [scopeSessionId, cwd]) // `version` is not read: it only forces this render when the record changed. void version const derived = props.paramsOf?.(info) @@ -273,6 +331,7 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro : { ...derived, ...nativeTab.navigation.params } const descriptor = service.getTab(descriptorId) const view = records.ensure({ + sessionId: seatSessionId, id: nativeTab.id, kind: nativeTab.kind, title: nativeTab.title, @@ -285,7 +344,6 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro return minted === null ? undefined : { title: minted.tab.title, meta: minted.tab.meta } }, }) - useEffect(() => () => { records.drop(nativeTab.id) }, [records, nativeTab.id]) if (descriptor === undefined) { // The orphaned fallback sits in the SAME native host as a live body, so // it gets the same full-height box (its own root also relies on the @@ -315,8 +373,8 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro visible: nativeTab.visible, expanded: view.expanded, revealed: view.revealed, - onToggleDir: (path: string) => { records.toggleExpanded(nativeTab.id, path) }, - onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, sessionId, cwd, path, isDir) }, + onToggleDir: (path: string) => { records.toggleExpanded(seatSessionId, nativeTab.id, path) }, + onReferenceFile: (path: string, isDir: boolean) => { referenceInChat(ctx, scopeSessionId, cwd, path, isDir) }, onOpenDiff: (tab: SidebarTab) => { service.openTab({ type: 'diff', @@ -339,6 +397,13 @@ export interface NativeTitleInjected { readonly service: BetterSidebarService /** The descriptor id this title belongs to (one registration per descriptor). */ readonly descriptorId: string + /** + * The seat session this chip is drawn in. The strip renders BEFORE the pane + * body, and every session's retitled tabs live in the same registry, so the + * chip must name its session instead of reading whichever record the id + * happens to hit. + */ + readonly sessionId: string } /** @@ -356,13 +421,13 @@ export interface NativeTitleInjected { * cannot drift apart. */ export function NativeTabTitle(props: NativeTitleInjected & NativeBodyFrameworkProps): ReactNode { - const { records, service, descriptorId, useTabInfo } = props + const { records, service, descriptorId, sessionId, useTabInfo } = props const nativeTab = useTabInfo().tab const version = useSyncExternalStore( listener => records.subscribe(listener), - () => records.versionOf(nativeTab.id), + () => records.versionOf(sessionId, nativeTab.id), ) - const record = records.get(nativeTab.id) + const record = records.get(sessionId, nativeTab.id) const title = record?.tab.title ?? nativeTab.title // `version` is read so a title/path/meta mutation re-renders the chip; the // icon itself is derived from the record, never stored. diff --git a/src/client/service.ts b/src/client/service.ts index 9ceef334..1a5570ee 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -456,12 +456,18 @@ export interface SidebarSurface { fileAddress(sessionId: string, cwd: string | undefined, path: string): string /** Close one native tab; the closed record's type/title, or undefined when the id is not native. */ close(sessionId: string, tabId: string): { type: string; title: string } | undefined - /** Patch a native tab's plugin-side record; false when it is not native. */ - update(tabId: string, patch: { title?: string; path?: string; meta?: unknown }): boolean - /** Focus a native tab; false when it is not native. */ - activate(tabId: string): boolean - /** Whether a tab id belongs to the native surface. */ - has(tabId: string): boolean + /** + * Patch a native tab's plugin-side record; false when it is not native. + * `sessionId` (optional) names the seat session the tab lives in: native tab + * ids restart per session and several sessions' tabs are alive at once + * (`keepMounted`), so a caller that knows its session should pass it. + * Omitted, the id resolves against the mounted seat. + */ + update(tabId: string, patch: { title?: string; path?: string; meta?: unknown }, sessionId?: string): boolean + /** Focus a native tab; false when it is not native (same `sessionId` rule as `update`). */ + activate(tabId: string, sessionId?: string): boolean + /** Whether a tab id belongs to the native surface (same `sessionId` rule as `update`). */ + has(tabId: string, sessionId?: string): boolean } /** @@ -579,8 +585,14 @@ export interface BetterSidebarService { getSnapshot(): SidebarSnapshot /** Subscribe to snapshot changes (session switch, state changes, prefs changes). Returns the disposer. */ subscribeState(listener: () => void): () => void - /** Update an open tab's display fields (title / path / meta); a missing tab id is a no-op. */ - updateTab(tabId: string, patch: { title?: string; path?: string; meta?: unknown }): void + /** + * Update an open tab's display fields (title / path / meta); a missing tab id + * is a no-op. `sessionId` names the seat session the tab lives in — native + * ids restart per session and several sessions' tabs stay mounted at once, + * so a component that knows its scope should pass it; omitted, a native id + * resolves against the mounted seat. + */ + updateTab(tabId: string, patch: { title?: string; path?: string; meta?: unknown }, sessionId?: string): void /** * Activate an open tab (the tab-bar activation path; fires * descriptor.onActivate). An unknown tab id is a strict no-op. `scope` @@ -1091,8 +1103,12 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe const subscribeState = (listener: () => void): (() => void) => store.subscribe(listener) /** Patch an open tab's display fields (a missing tab id is a no-op). */ - const updateTab = (tabId: string, patch: { title?: string; path?: string; meta?: unknown }): void => { - if (surface?.update(tabId, patch) === true) return + const updateTab = ( + tabId: string, + patch: { title?: string; path?: string; meta?: unknown }, + sessionId?: string, + ): void => { + if (surface?.update(tabId, patch, sessionId) === true) return store.reduce((state) => patchTab(state, tabId, { ...(patch.title !== undefined ? { title: patch.title } : {}), ...(patch.path !== undefined ? { path: patch.path } : {}), @@ -1102,7 +1118,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe /** Activate an open tab (the tab-bar activation path; fires onActivate). */ const activateTab = (tabId: string, scope?: SessionScope): void => { - if (surface?.activate(tabId) === true) return + if (surface?.activate(tabId, scope?.sessionId) === true) return let activated: SidebarTab | undefined store.reduce((state) => { // Unknown tab ids are a strict no-op (no state churn / notify). diff --git a/src/client/tree-mutations.ts b/src/client/tree-mutations.ts index 6fa16413..793e6c0b 100644 --- a/src/client/tree-mutations.ts +++ b/src/client/tree-mutations.ts @@ -30,8 +30,10 @@ function pathTabsOf(snapshot: SidebarSnapshot): SidebarTab[] { export function retargetPathTabs(ctx: Context, store: SidebarStore, oldPath: string, newPath: string): void { const service = ctx.get('betterSidebar') if (service === undefined) return - for (const tab of pathTabsOf(store.getSnapshot())) { - if (tab.path === oldPath) service.updateTab(tab.id, { path: newPath, title: baseName(newPath) }) + // The tabs live in the snapshot's session: native ids restart per session. + const snapshot = store.getSnapshot() + for (const tab of pathTabsOf(snapshot)) { + if (tab.path === oldPath) service.updateTab(tab.id, { path: newPath, title: baseName(newPath) }, snapshot.sessionId) } } diff --git a/tests/native-surface.spec.ts b/tests/native-surface.spec.ts index 4ab7b427..ad201cbb 100644 --- a/tests/native-surface.spec.ts +++ b/tests/native-surface.spec.ts @@ -10,6 +10,7 @@ import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' import { createNativeTabRecords, NativeTabBody, NativeTabTitle } from '../src/client/native/tab-adapter.tsx' import { registerNativeSurface } from '../src/client/native/index.ts' +import { createNativeSurface } from '../src/client/native/surface.ts' import { createBetterSidebarService, type SidebarSurface } from '../src/client/service.ts' import { createSidebarStore, type SidebarTab } from '../src/client/state.ts' @@ -19,6 +20,7 @@ describe('createNativeTabRecords', () => { it('mints a synthetic tab from the native record + params', () => { const records = createNativeTabRecords() const view = records.ensure({ + sessionId: 's1', id: 'tab-1', kind: 'browser', title: 'Browser', params: { url: 'https://a.test', meta: { k: 1 } }, scope, }) expect(view.tab).toMatchObject({ id: 'tab-1', type: 'browser', title: 'Browser', meta: { k: 1 } }) @@ -29,46 +31,46 @@ describe('createNativeTabRecords', () => { it('calls the descriptor factory once for a record that arrives without seed fields', () => { const records = createNativeTabRecords() const mint = vi.fn(() => ({ title: 'Side chat', meta: { autoCreate: true } })) - const view = records.ensure({ id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint }) + const view = records.ensure({ sessionId: 's1', id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint }) expect(mint).toHaveBeenCalledTimes(1) expect(view.tab).toMatchObject({ title: 'Side chat', meta: { autoCreate: true } }) // A second render of the same record does not re-mint. - records.ensure({ id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint }) + records.ensure({ sessionId: 's1', id: 'tab-2', kind: 'sidechat', title: 'Side Chat', params: undefined, scope, mint }) expect(mint).toHaveBeenCalledTimes(1) }) it('refreshes the seed fields on navigation but keeps the record identity', () => { const records = createNativeTabRecords() - records.ensure({ id: 'tab-3', kind: 'editor', title: 'a.ts', params: { path: '/work/a.ts' }, scope }) - records.update('tab-3', { title: 'renamed.ts' }) - const view = records.ensure({ id: 'tab-3', kind: 'editor', title: 'b.ts', params: { path: '/work/b.ts' }, scope }) + records.ensure({ sessionId: 's1', id: 'tab-3', kind: 'editor', title: 'a.ts', params: { path: '/work/a.ts' }, scope }) + records.update('s1', 'tab-3', { title: 'renamed.ts' }) + const view = records.ensure({ sessionId: 's1', id: 'tab-3', kind: 'editor', title: 'b.ts', params: { path: '/work/b.ts' }, scope }) expect(view.tab).toMatchObject({ id: 'tab-3', path: '/work/b.ts', title: 'renamed.ts' }) }) it('tracks expansion per record and bumps its version', () => { const records = createNativeTabRecords() - records.ensure({ id: 'tab-4', kind: 'editor', title: 'Files', params: undefined, scope }) - const before = records.versionOf('tab-4') - records.toggleExpanded('tab-4', '/work/src') - expect(records.get('tab-4')?.expanded).toEqual(['/work/src']) - expect(records.versionOf('tab-4')).toBeGreaterThan(before) - records.toggleExpanded('tab-4', '/work/src') - expect(records.get('tab-4')?.expanded).toEqual([]) + records.ensure({ sessionId: 's1', id: 'tab-4', kind: 'editor', title: 'Files', params: undefined, scope }) + const before = records.versionOf('s1', 'tab-4') + records.toggleExpanded('s1', 'tab-4', '/work/src') + expect(records.get('s1', 'tab-4')?.expanded).toEqual(['/work/src']) + expect(records.versionOf('s1', 'tab-4')).toBeGreaterThan(before) + records.toggleExpanded('s1', 'tab-4', '/work/src') + expect(records.get('s1', 'tab-4')?.expanded).toEqual([]) }) it('notifies subscribers and forgets a dropped record', () => { const records = createNativeTabRecords() - records.ensure({ id: 'tab-5', kind: 'terminal', title: 'Terminal', params: undefined, scope }) + records.ensure({ sessionId: 's1', id: 'tab-5', kind: 'terminal', title: 'Terminal', params: undefined, scope }) const listener = vi.fn() const off = records.subscribe(listener) - records.update('tab-5', { title: 'zsh' }) + records.update('s1', 'tab-5', { title: 'zsh' }) expect(listener).toHaveBeenCalledTimes(1) - expect(records.get('tab-5')?.tab.title).toBe('zsh') - records.drop('tab-5') - expect(records.has('tab-5')).toBe(false) + expect(records.get('s1', 'tab-5')?.tab.title).toBe('zsh') + records.drop('s1', 'tab-5') + expect(records.has('s1', 'tab-5')).toBe(false) off() - records.ensure({ id: 'tab-6', kind: 'terminal', title: 'Terminal', params: undefined, scope }) - records.update('tab-6', { title: 'x' }) + records.ensure({ sessionId: 's1', id: 'tab-6', kind: 'terminal', title: 'Terminal', params: undefined, scope }) + records.update('s1', 'tab-6', { title: 'x' }) expect(listener).toHaveBeenCalledTimes(2) }) }) @@ -514,6 +516,7 @@ describe('NativeTabTitle (the chip glyph)', () => { service: ReturnType, info: unknown, descriptorId: string, + sessionId = 's1', ): { host: HTMLDivElement; unmount: () => void } => { const host = document.createElement('div') document.body.appendChild(host) @@ -524,6 +527,7 @@ describe('NativeTabTitle (the chip glyph)', () => { records, service, descriptorId, + sessionId, useTabInfo: () => info as never, })) }) @@ -557,7 +561,7 @@ describe('NativeTabTitle (the chip glyph)', () => { icon: (size: number) => createElement('i', { 'data-stub-icon': size }), component: () => createElement('div'), }) - records.ensure({ id: 'chip-1', kind: 'stub-tab', title: 'Stub', params: undefined, scope }) + records.ensure({ sessionId: 's1', id: 'chip-1', kind: 'stub-tab', title: 'Stub', params: undefined, scope }) const { host, unmount } = renderTitle(records, service, nativeInfo('chip-1', 'stub-tab', 'Stub'), 'stub-tab') const chip = host.querySelector('[aria-hidden="true"]') @@ -578,6 +582,7 @@ describe('NativeTabTitle (the chip glyph)', () => { component: () => createElement('div'), }) records.ensure({ + sessionId: 's1', id: 'chip-2', kind: 'editor', title: 'notes.md', @@ -598,7 +603,7 @@ describe('NativeTabTitle (the chip glyph)', () => { it('falls back to the title alone when the type is gone (unregistered descriptor)', () => { const records = createNativeTabRecords() const service = createBetterSidebarService(createSidebarStore()) - records.ensure({ id: 'chip-3', kind: 'ghost', title: 'Ghost', params: undefined, scope }) + records.ensure({ sessionId: 's1', id: 'chip-3', kind: 'ghost', title: 'Ghost', params: undefined, scope }) const { host, unmount } = renderTitle(records, service, nativeInfo('chip-3', 'ghost', 'Ghost'), 'ghost') expect(host.querySelector('[aria-hidden="true"]')).toBeNull() @@ -606,3 +611,255 @@ describe('NativeTabTitle (the chip glyph)', () => { unmount() }) }) + +/** + * ONE NATIVE ID, ONE RECORD PER SESSION. + * + * The host's tab counter restarts in every session (`tab1`, `tab2`, …) and + * 0.1.7 keeps visited bodies MOUNTED through hiding, tab selection and Session + * switches (`SidebarTabDefinition.keepMounted`). Two sessions' `tab1` are + * therefore alive at the same time, and a registry keyed by the bare id hands + * one session's tree/edit state to the other — the chain #636/#661 reported. + * These cases pin the per-session identity and the reclaim of dead sessions. + */ +describe('createNativeTabRecords — per-seat-session identity', () => { + it('keeps two sessions\' same-named tab apart', () => { + const records = createNativeTabRecords() + const first = records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope }) + records.toggleExpanded('s1', 'tab1', '/work/src') + const second = records.ensure({ + sessionId: 's2', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, + scope: { sessionId: 's2', cwd: '/other' }, + }) + expect(second).not.toBe(first) + expect(records.get('s1', 'tab1')?.expanded).toEqual(['/work/src']) + expect(records.get('s2', 'tab1')?.expanded, 'the entering session must not inherit').toEqual([]) + expect(records.get('s2', 'tab1')?.scope.sessionId).toBe('s2') + }) + + it('patches and drops exactly one session\'s record', () => { + const records = createNativeTabRecords() + records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope }) + records.ensure({ sessionId: 's2', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope }) + records.update('s2', 'tab1', { title: 'renamed in B' }) + expect(records.get('s1', 'tab1')?.tab.title).toBe('Files') + expect(records.get('s2', 'tab1')?.tab.title).toBe('renamed in B') + records.drop('s1', 'tab1') + expect(records.has('s1', 'tab1')).toBe(false) + expect(records.has('s2', 'tab1')).toBe(true) + }) + + it('retain() reclaims the records of sessions that are gone', () => { + const records = createNativeTabRecords() + records.ensure({ sessionId: 's1', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope }) + records.ensure({ sessionId: 's2', id: 'tab1', kind: 'editor', title: 'Files', params: undefined, scope }) + const versions = new Map() + records.subscribe(() => { versions.set('seen', (versions.get('seen') ?? 0) + 1) }) + records.retain(new Set(['s1'])) + expect(records.has('s2', 'tab1')).toBe(false) + expect(records.has('s1', 'tab1'), 'a live session keeps its state').toBe(true) + expect(versions.get('seen'), 'a reclaim notifies the mounted bodies').toBe(1) + // An unchanged live set is not a change: no notify, no work. + records.retain(new Set(['s1'])) + expect(versions.get('seen')).toBe(1) + }) +}) + +/** + * The surface resolves a BARE tab id (the consumer contract) against a seat + * session: the mounted one when there is one, a unique match otherwise, and + * NOTHING when the id names a tab in several sessions — guessing would write + * into another conversation. A session that disappears takes its records with + * it, because a `keepMounted` body of a deleted session never unmounts. + */ +describe('createNativeSurface — session-scoped ids and reclaim', () => { + const fixture = (sessionIds: string[], mounted?: string) => { + const listListeners = new Set<() => void>() + const byId: Record = {} + for (const id of sessionIds) byId[id] = { cwd: `/work/${id}` } + const calls: unknown[] = [] + let mountedId = mounted + const controller = { + openTab: (kind: string, options?: unknown) => { calls.push({ op: 'openTab', kind, options }) }, + openResource: (address: string, options?: unknown) => { calls.push({ op: 'openResource', address, options }) }, + close: (tabId: string) => { calls.push({ op: 'close', tabId }) }, + closeIn: (sessionId: string, tabId: string) => { calls.push({ op: 'closeIn', sessionId, tabId }) }, + mounted: { getSnapshot: () => mountedId, subscribe: () => () => {} }, + } + const ctx = { + sessions: { + list: { + subscribe: (listener: () => void) => { listListeners.add(listener); return () => { listListeners.delete(listener) } }, + getSnapshot: () => ({ byId }), + }, + }, + get: (name: string) => (name === 'sidebarRight' ? controller : undefined), + } as never + return { + ctx, + calls, + setMounted: (id: string | undefined) => { mountedId = id }, + removeSession: (id: string) => { delete byId[id]; for (const listener of [...listListeners]) listener() }, + } + } + + const seed = (records: ReturnType, sessionId: string, id: string) => + records.ensure({ sessionId, id, kind: 'editor', title: 'Files', params: undefined, scope: { sessionId, cwd: '/work' } }) + + it('targets the session the caller names, never the same id in another one', () => { + const { ctx } = fixture(['s1', 's2'], 's1') + const records = createNativeTabRecords() + seed(records, 's1', 'tab1') + seed(records, 's2', 'tab1') + const surface = createNativeSurface(ctx, records) + expect(surface.update('tab1', { title: 'renamed in B' }, 's2')).toBe(true) + expect(records.get('s2', 'tab1')?.tab.title).toBe('renamed in B') + expect(records.get('s1', 'tab1')?.tab.title, 'the mounted seat is untouched').toBe('Files') + }) + + it('falls back to the mounted seat when no session is named', () => { + const { ctx } = fixture(['s1', 's2'], 's2') + const records = createNativeTabRecords() + seed(records, 's1', 'tab1') + seed(records, 's2', 'tab1') + const surface = createNativeSurface(ctx, records) + expect(surface.update('tab1', { title: 'on screen' })).toBe(true) + expect(records.get('s2', 'tab1')?.tab.title).toBe('on screen') + expect(records.get('s1', 'tab1')?.tab.title).toBe('Files') + }) + + it('refuses an ambiguous bare id instead of guessing a conversation', () => { + const { ctx } = fixture(['s1', 's2'], undefined) + const records = createNativeTabRecords() + seed(records, 's1', 'tab1') + seed(records, 's2', 'tab1') + const surface = createNativeSurface(ctx, records) + expect(surface.update('tab1', { title: 'nope' })).toBe(false) + expect(surface.has('tab1')).toBe(false) + // A unique match still resolves without a mounted seat. + seed(records, 's2', 'tab9') + expect(surface.has('tab9')).toBe(true) + }) + + it('closes one session\'s tab and reclaims a deleted session\'s records', () => { + // `s3` is the mounted seat; `s2` is a background session that will be + // deleted — the case no React unmount ever reports. + const { ctx, calls, removeSession } = fixture(['s1', 's2', 's3'], 's3') + const records = createNativeTabRecords() + seed(records, 's1', 'tab1') + seed(records, 's2', 'tab1') + const surface = createNativeSurface(ctx, records) + expect(surface.close('s1', 'tab1')).toEqual({ type: 'editor', title: 'Files' }) + expect(calls, 'a background session closes through the per-session face').toEqual([{ op: 'closeIn', sessionId: 's1', tabId: 'tab1' }]) + expect(records.has('s1', 'tab1')).toBe(false) + expect(records.has('s2', 'tab1')).toBe(true) + removeSession('s2') + expect(records.has('s2', 'tab1'), 'a gone session leaves no record behind').toBe(false) + }) +}) + +/** + * CO-RESIDENT SEATS. With `keepMounted` the host keeps every visited body + * mounted, so two sessions draw the SAME native id at the same time and one + * unmounting no longer means its record is dead. These cases mount both seats + * together: neither inherits the other's exploration state, and one going away + * does not delete the other's record (the #636 chain). + */ +describe('NativeTabBody — co-resident seats', () => { + const mountSeat = ( + records: ReturnType, + service: ReturnType, + sessionId: string, + id: string, + ) => { + const store = createSidebarStore() + store.setSession(sessionId) + const sessions = { + list: { + subscribe: () => () => {}, + getSnapshot: () => ({ byId: { [sessionId]: { cwd: `/work/${sessionId}` } } }), + }, + } + const ctx = { sessions } as never + const host = document.createElement('div') + document.body.appendChild(host) + const info = { + tab: { + id, + kind: 'explorer', + title: 'Files', + contentId: `sidebar://${id}`, + visible: true, + navigation: { address: `sidebar://${id}`, params: undefined, revision: 0 }, + signal: new AbortController().signal, + }, + } + let root: Root | undefined + act(() => { + root = createRoot(host) + root.render(createElement(NativeTabBody, { + sessionId, + ctx, + store, + service, + records, + descriptorId: 'explorer', + useTabInfo: () => info, + })) + }) + return { + host, + unmount: () => { act(() => { root?.unmount() }); host.remove() }, + } + } + + it('keeps each seat\'s exploration, and an unmount only drops its own', async () => { + const records = createNativeTabRecords() + const service = createBetterSidebarService(createSidebarStore()) + service.registerTab({ + id: 'explorer', + title: 'Files', + component: props => createElement('div', { 'data-seat': props.scope.sessionId }, + createElement('span', { 'data-expanded': (props.expanded ?? []).join(',') }), + createElement('button', { 'data-toggle': props.scope.sessionId, onClick: () => props.onToggleDir?.('/work/src') })), + }) + // BOTH seats name `tab1` — the host's counter restarts per session. + const first = mountSeat(records, service, 's1', 'tab1') + const second = mountSeat(records, service, 's2', 'tab1') + + act(() => { first.host.querySelector('[data-toggle="s1"]')!.click() }) + expect(first.host.querySelector('[data-expanded]')?.getAttribute('data-expanded')).toBe('/work/src') + expect(second.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'), 'the second seat must not inherit').toBe('') + + act(() => { second.host.querySelector('[data-toggle="s2"]')!.click() }) + expect(first.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'), 'and it must not overwrite the first').toBe('/work/src') + expect(second.host.querySelector('[data-expanded]')?.getAttribute('data-expanded')).toBe('/work/src') + + // A Session switch remounts the body on a REAL host (measured), so an + // unmount is NOT a close: the record has to wait for the remount that + // brings the reader's exploration back. + second.unmount() + expect(records.has('s1', 'tab1'), 'the other seat keeps its record').toBe(true) + expect(records.get('s1', 'tab1')?.expanded).toEqual(['/work/src']) + expect(records.has('s2', 'tab1'), 'an unmount must not forget the state').toBe(true) + + const again = mountSeat(records, service, 's2', 'tab1') + expect( + again.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'), + 'the remounted seat finds its own exploration again', + ).toBe('/work/src') + expect( + first.host.querySelector('[data-expanded]')?.getAttribute('data-expanded'), + 'and the other seat is still untouched', + ).toBe('/work/src') + + // Only a real close forgets a record. + records.drop('s2', 'tab1') + expect(records.has('s2', 'tab1')).toBe(false) + first.unmount() + expect(records.has('s1', 'tab1'), 'an unmount is not a close either').toBe(true) + records.drop('s1', 'tab1') + expect(records.has('s1', 'tab1')).toBe(false) + again.unmount() + }) +}) From aec7101374e9a172e157cb429c728385528698b2 Mon Sep 17 00:00:00 2001 From: ymac <707337118@qq.com> Date: Sun, 27 Sep 2026 12:25:08 +0800 Subject: [PATCH 3/7] feat(native): keep visited tab bodies mounted, and pin state retention end to end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DSH 0.1.7 gives a tab TYPE the `keepMounted` switch: a marked body stays mounted through hiding, tab selection and Session switches. That is exactly what the plugin tried to fake with module-level memory, so declare it on every plugin type (the descriptor types and the `files` takeover) and let the host hold the component state — tree scroll, unsaved drafts, chip renames — with no plugin-side memory at all. With the bodies staying up, the per-session record registry from the previous commit is what keeps co-resident sessions apart; both halves are required, because a body may still be remounted by the host (type disposal, session teardown) and the records must outlive that. Verification on a real host (`scripts/e2e-mount.sh`: npm pack -> fresh scratch profile -> real `dsh web` pinned to 0.1.7-rc.1 -> headless Chromium), new lane `tests/e2e/tree-scroll.e2e.ts`: build state in conversation A, switch to B, come back, and compare the whole observable vector (tree expansion, scroll offset, chip title) — plus the negative half, that B does not inherit A's state. That lane also exposed a defect in the old one: it picked its "second conversation" by row index, but the session tree's first row is a WORKSPACE row and a seeded session with no messages takes no row at all, so the "A -> B -> A" round trip was re-selecting the same session and every assertion held vacuously. It now identifies sessions by `data-row-key="session:"` and creates a real second session through the rail. `tests/e2e/mount.e2e.ts` reaches the side-chat tab through its guide entry now: with the record retained, the chip shows the thread's own title, so the old `/Side Chat/` chip match no longer names it. Docs: AGENTS.md records the two facts that must hold together, and docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md replaces the park/archive design (PR #712) with this one. --- AGENTS.md | 2 + ...-native-tab-state-retention-keepmounted.md | 124 ++++++++ src/client/native/index.ts | 7 + tests/e2e/mount.e2e.ts | 8 +- tests/e2e/tree-scroll.e2e.ts | 296 ++++++++++++++++++ 5 files changed, 435 insertions(+), 2 deletions(-) create mode 100644 docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md create mode 100644 tests/e2e/tree-scroll.e2e.ts diff --git a/AGENTS.md b/AGENTS.md index 39da9676..9ed22400 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,6 +70,8 @@ 7. **e2e scratch profile 的 `minimumReleaseAgeExclude` 含 `'@deepseek-ai/*'`**(`scripts/e2e-mount.sh` / `e2e-aggregate-mount.sh`,与仓库根 `pnpm-workspace.yaml` 同策):alpha 版本常在发布后 24h 内跑 lane,pnpm 11 的 `minimumReleaseAge` 默认会拒装新鲜包。 8. **插件开发树的 dsh-* 传递 peer 需提升为 devDependencies**(alpha.3 首见):`dsh-subagent` 等 npm 包把 `dsh-attachment` 等 dsh-* 姊妹包声明为 peerDependencies(由宿主 bundle 树统一提供,宿主侧无此问题),插件仓库若只直接依赖其中一部分,其余 peer 在 pnpm 下会解析到树上残留的旧版——如 `dsh-attachment@0.1.1-rc.1` 缺 `admitPromptContent` 导出、`dsh-subagent` 产物 import 它时测试加载即崩。因此 devDependencies 需涵盖 dev 树实际触达的全部 peer(attachment / scope / session-projection / system-prompt / user-approval / util-time 等,与直接依赖同款精确钉版);**`@deepseek-ai/cordis` peer 自 alpha.3 起要求 `^4.0.2`,0.1.7-alpha.1 要求 `^4.0.3`,rc.1 起要求 `~4.0.4`**(rc.1 顺手把 vendor 一起抬了:cordis 4.0.4 / schemastery 3.18.4 / cordis-plugin-group 1.0.4 / cordis-plugin-include 1.0.9;loader 保持 1.0.5)。**rc.1 实测的教训**:只改 `dependencies` 里的 schemastery 和 peer 里的 cordis **不够**——`cordis-plugin-group` / `-include` 是 `dsh-app-boot` / `dsh-config-editor` 的**传递 peer**,pnpm 会继续沿用 lockfile 里的旧副本,`pnpm peers check` 一次报出四类 unmet peer;按本条把四个 vendor 包**显式钉进 devDependencies** 才收敛(这也是 rc.1 那条「DSH 内部引用一律精确版本」的 workspace-release-ranges 政策的直接后果)。适配新版本时先跑 `pnpm peers check`,把新失配的传递 peer 一并提升进 devDependencies。**0.1.7 新增的同类问题**见 §3.3 第 12 条(`ui-primitives` 的第二层裸 import)。例外:**`dsh-client-locale` 的 peer/devDep 允许落后于基线**的历史已消除,rc.1 起上游恢复发版,0.1.7 起与 DSH 同 tuple。 9. **右侧栏是 DSH 原生栏,插件只提供 tab 类型**:聊天里一切文件打开(工具行 / 产物行 / 正文提及 / 行内代码路径)统一走 `ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path))`。插件的每个 `TabDescriptor` 注册成原生 tab 类型(`kind = descriptor.id`,`extension` 带)+ 原生 tab 体(`sidebar.right.pane.tab` keyed 槽,key = `dsh-better-sidebar:`);`editor` 类型同时认领 `dsh-resource://file/**`(**但按 §3.2 第 5 条的清单让出一部分**),并接管内置 `files` 页面 kind(`openTab('files')` 打开插件文件树,注销即复位)。`ctx.sidebarRight.openTab/openResource/close` 只对**在屏会话**写入;跨会话用具体类上的 `openTabIn/openResourceIn/closeIn`。原生 tab 的插件侧状态在 `src/client/native/tab-adapter.tsx`。**注册必须等服务、不能等槽声明**:原生栏先声明 `sidebar.right.pane.tab` 再 `provide('sidebarRightTabs')`,真机 profile 上槽声明回调里 `ctx.get('sidebarRightTabs')` 仍是 undefined(实测 3 秒后才出现),按槽触发注册会静默什么都不注册且永不重试——用 `ctx.inject(['sidebarRightTabs'], cb)` 驱动类型注册(`tests/native-surface.spec.ts` 以「槽先触发、服务后到达」的顺序守护)。**0.1.6-alpha.2 起**:`SidebarRightGuideEntry.id` 必填且同 provider 内唯一(缺它会静默清空整个承载面);同 provider 的 guide 条目是**追加**关系,`chain` 那种「替换宿主条目」的语义只存在于 `conversation.chat.turnTail` 且已被上游改成 `list`。**0.1.7 起**:`sidebar-right` 本体的契约**零破坏**——槽名无改名、`SidebarRightTabDefinition` 没有新的必填字段、只有新增的可选 `keepMounted` 与 `ISidebarRight.mounted`,`openTabIn/openResourceIn/closeIn` 在具体 class 上字节不变;`tab.visible` 语义收紧为 `active && (...)`(全局面板/后台会话时 body 不挂载);持久化校验收紧(非根 / 列轴 / 嵌套 / 3+ docked pane 的 split 一律判非法**整份丢弃**,0.1.6 的 sidebar 自己产不出这种布局);`RightbarRoot` 现在为每个保留会话渲染一个隐藏 seat(`SidebarSessionViews`,未导出、插件拿不到)。原生 tab 体宿主 `.paneBody` 是**有确定高度的块级滚动容器**(非 flex 容器),native 适配层因此给每个 tab 体包一层 `height:100%` 的列 flex 宿主(`sidebar.module.css` 的 `.nativeTabHost`),tab 组件根继续用 `flex:1`/`height:100%`。全局面板(根级 `main` keyed 槽 + `sidebar.panellist` + `ctx.layout.selectPanel/beginNavigation`、`rightbar` 改根级并新增 `rightbar.session`)插件**不接入**,只做兼容。底部工作台的中心列锚点认 `[data-slot="main.conversation"]`(并跳过 `display: contents` 祖先,同时保留 alpha.1 的 `[data-slot="conversation"]`);文件地址语法跟随 alpha.2(`fileAddressFor` 一律 session 作用域、绝对路径保留前导 `/`、`parseFileAddress` 前缀解析并去 `?`/`#`)。**原生指南说明的 4 条上限(归属更正:这是 0.1.7-alpha.1 起就存在的既成事实,不是 rc.1 的变更)**:`ui-sidebar-right/src/client/tabs/guide/GuideBody.tsx` 的 `MAX_DESCRIBED_ENTRIES = 4` 及其判定行在 alpha.1 / alpha.2 / rc.1 三个 tag 上**逐字相同**,宿主终端的 guide 条目(`ui-sidebar-terminal/src/client/TerminalGuide.tsx`)也是 alpha.1 就有了,`ui-sidebar-terminal/src` 在 rc.1 **零改动**。含义不变:条目 ≤ 4 条才渲染说明,更长的列表是整列丢弃而不是截断——插件默认贡献 4 个 guide 条目(文件 / 文件变动 / 任务管理 / 侧边对话),与宿主的终端条目合计后可能超过 4 条,此时说明不渲染;插件**不恢复**旧的 `nativeGuideDesc` 通用兜底句。**原生注册账本的两条不变量(v0.22.1 起,由 `tests/native-registration.spec.ts` 守护)**:① `live` 里同时装着描述符类型(键 = descriptor id)与 `files` 接管(键 = `FILES_KIND`,**永远不在 `wanted` 里**),清理循环必须**跳过 `FILES_KIND`**——它只由编辑器类型的 `wantsFiles/hasFiles` 开关分支与 seat disposer 管理;否则每次通知都会把它拆掉再重建,而 teardown 期间的那次重建会把 id 孤儿化:`tabs.register` 建在**宿主** ctx 上(宿主 ctx 此时仍活着)所以照样成功,紧随的 `ctx.slots.inject` 建在**插件** ctx 上却抛 `cannot create effect on inactive context`,`live.set` 永不执行 → 该 id 在整页生命周期内不可再注册(真实表现:`native register files error: … already registered` 刷屏 + 文件树落到宿主空态,只有刷新页面才恢复;官方桌面壳日志实证见 [docs/plans/2026-09-28-native-files-takeover-reload-leak.md](docs/plans/2026-09-28-native-files-takeover-reload-leak.md))。② 因此「注册成功一半」是**可达状态**:任何在宿主取走 id **之后**失败的注册(槽位注册抛错等)必须**回滚释放该 type**、并释放已经建好的槽位——插件侧只留一个下次通知可以重试的失败,绝不留下无处释放的 id。相关断言必须写在注册表的**事件日志**上而不是「活着的 id 集合」上:孤儿 id 会让键集合看起来完全正常,键集合断言在未修复代码上同样通过。 + **原生 tab 的状态保留(0.1.7 起,本插件已采纳)**:插件的 tab 类型一律声明 `keepMounted: true`(描述符类型 + `files` 接管)——宿主因此把访问过的 body 挂住,同会话切 tab 不再卸载,组件态(树滚动、未保存草稿、chip 重命名)随之免费保留,**不需要**任何 module-level 记忆。两条必须同时成立的配套事实:(a)**记录不能随卸载删除**(只由 `surface.close` 与「会话消失」回收):跳过 `FILES_KIND` 之后 body 在切 tab 与切会话时都只隐藏不卸载(真机日志里那对 `DISPOSE type …:files` → `register`、同键 `drop`+`mint` 正是「切回会话清零」的那一路,真机 e2e 现断言跨会话 `scrollTop` 复原),而记录按会话记账仍是抗宿主重挂的底线;(b)原生 tab id **每会话各自计数**(`tab1`…)且多会话同号并存,记录与写面一律按 `sessionId::tabId` 记账,`Surface.update/has/activate` 新增可选 `sessionId`(缺省按 `sidebarRight.mounted` 解析,多会话同名时拒绝而不是猜)。设计过程与实测见 [docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md](docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md)。 + 10. **自定义种子必须带 fork 标记对(`meta.isSeeded: true` + `inheritedEventCount`)**:dsh-session 契约「只给 seed 不标 isSeeded,种子算重放历史而非继承前缀」——缺标记时 `Session.ownEvents()` 含整个种子,子会话的 inbox 折重放种子里的 `agent/inbox/spliced`,**继承父会话切割时刻未领取的 inbox 输入**。宿主 `session.fork`(api-session-controller)的调用即规范形态;回归由 `tests/sidechat-seed-validation.spec.ts`(真实 `Session.create` + 对 `ownEvents()` 跑 inbox 折)守护。**0.1.7 复查:`Session.create` 的五个参数与函数体逐字相同**;上游新增了 `buildForkSeed(events, boundary)` 导出,与本插件手工的 `buildSidechatInheritance` 职责重叠但**收益不明确**(插件还有 dangling-tool-call 退回结构化快照的自有需求),暂不替换。 11. **`dsh.plugin.json` 从来不是 DSH 契约**:0.1.7 全树 grep 仍 **0 命中**。DSH 真正读的是 `package.json` 的 `dsh.bundle.patch` + `dsh.client`(`platform`/`inject`/`immediately`/`external`)+ `exports["./client"]`。`dsh.plugin.json` 只服务第三方 registry(社区市场)通道,`lib/client-registry.js` 同理;`tests/manifest-consistency.spec.ts` 守护的是这条通道的形状,不是 DSH 契约。**`dsh.manifestVersion` 也仍是「只声明、零读」**(0.1.7 的 `package-manifest` README 自己写明「Current installers and loaders do not enforce `dsh.manifestVersion` or `engines.dsh`」)。0.1.7 的官方管控面新增:`plugin-manager` 的**多 registry 回退**(`registryPlan()`:配置源 → `fallbackRegistries`(默认含 `registry.npmmirror.com`),`network`/`timeout`/`not-found`/`no-matching-version` 会自动问下一个源;`registry` 入参只存在于 Web 对话框与 `plugin_manager` 工具,**CLI 没有 registry flag**)、`waitForInstall`、以及**插件展示元数据**:`package.json#icon`(36×36、纯填充无描边、**双色渐变**——与 DSH 自带的 `PluginArtwork*` 同风格:它们「carry their own brand colors instead of riding currentColor」,且每个都是多色,单色版在 30px 行内尺寸下会读成一块纯色板)+ `locale/.json` 的 `meta.title`/`description`。本插件**已采纳**(v0.21.1):`icon.svg` + `locale/en.json` + `locale/zh.json`,并由 `tests/plugin-meta.spec.ts` 守护「声明了就必须发布出去」。**rc.1 复查:`packages/boot/app-boot/src/package-meta.ts` 与 `scripts/verify-package-meta.ts` 在两个 tag 上逐字相同**(`ui-plugin-manager/src/client/presentation.ts` 只多了一段 `incompatible-version` 文案),所以上面三条硬规则与「**没有任何尺寸/渐变校验**」都仍然成立。三条硬规则:icon 必须是**包内相对路径**且写进 `files`;`locale/en.json` 是发现基线(缺它整个目录都不读);`exports` 必须暴露 `./locale/*.json` 与 `./package.json`。**所有失败都是静默的**——元数据有问题只会退化成一行纯文字,没有任何报错。`dsh.bundle.patch` 现在多了形状校验(非法值会 `throw`,引导期跳过该 bundle),本插件是合法的单字符串。 12. **peer 声明是启动期硬约束(rc.1 起;本版最容易静默失效的一处)**:`packages/boot/app-boot/src/plugin-compatibility.ts`(rc.1 **新文件**)只做一件事——遍历 profile 行的 `peerDependencies`,对**名字为 `@deepseek-ai/dsh` 或以 `@deepseek-ai/dsh-` 开头**的条目跑 `semver.satisfies(宿主版本, range, { includePrerelease: true })`,不满足就把整行 `row.disabled = true`(group 行连 `group` 一起关掉),只在 stderr 留一行 `disabling profile plugin