fix(native): key a tab record by (session, tab id), not the bare id
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.
This commit is contained in:
1 parent
673707cef7
commit
7cf962652e
9 files changed
+502
-99
No files matched your search
@@ -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<string, unknown>): 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<string, unknown>): 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')
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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 => {
|
||||
|
||||
@@ -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}"`)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<string>): 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<string, number>()
|
||||
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.
|
||||
|
||||
+27
-11
@@ -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).
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+278
-21
@@ -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<typeof createBetterSidebarService>,
|
||||
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<string, number>()
|
||||
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<string, { cwd: string }> = {}
|
||||
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<typeof createNativeTabRecords>, 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<typeof createNativeTabRecords>,
|
||||
service: ReturnType<typeof createBetterSidebarService>,
|
||||
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<HTMLButtonElement>('[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<HTMLButtonElement>('[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()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user