fix(sidechat): bind the native side chat tab to its thread across re-navigation

The native right sidebar keeps at most ONE page tab per kind, so a side chat
tab is never a copy: every open re-delivers the same tab with fresh navigation
params and an incremented `navigation.revision` (verified in the pinned host's
client bundle: `TabDomain.navigate` replaces the whole target and bumps the
revision, and `openContent` settles an already-held page tab through it). Two
opposite mistakes followed from that: `records.ensure` only read the seed
`meta` when it MINTED a record (so the header thread menu closed and nothing
changed — #762), while adopting it on every pass would clobber the thread id
the view writes back through `updateTab` (the orphan `Side: New thread` half of
#684).

Adopt a navigation's `params.meta` exactly once per revision, and reattach an
unbound auto-creating tab to the thread its session was last in instead of
minting another empty one.

Rewritten against the current dev tree rather than merged from the PR:

- #776 (7cf9626) made a record key `(seat session, native tab id)`; the
  revision ledger is keyed the same way and is dropped together with the
  record — in `drop` AND in `retain(sessions)`, which also forgets records.
- dev's existing branch never wrote `meta` and folds a url seed into
  `nextPath`, so the PR's url/meta merge has no counterpart here and is
  deliberately not ported: "revision unchanged" simply leaves `meta` alone,
  which is what keeps #684's other half fixed.
- `updateTab` takes the seat session as its third argument (same commit), so
  the reattach names it like the rest of the view does.
- The "newest real thread, placeholders last" heuristic already exists on dev
  (477f627, the archive fallback); it is extracted into `newestThreadId` and
  reused instead of being copied a second time.
- The remembered thread uses the client store's key space
  (`dsh-sidebar:v1:sidechat-thread`), not the PR's `dsh-better-sidebar:*`.
- `openNewThread` starts the thread first and parks it for `createTab`, and an
  auto-creating tab no longer offers a manual create button while it binds.

Tests (the PR reported none): the revision gate, its no-revision guard (both
fail on the unported adapter), the call-site wiring through `NativeTabBody`,
plus the two dev-side records cases around them.

Refs #839

Co-authored-by: waser0434 <178004182+Waser750@users.noreply.github.com>
This commit is contained in:
Menghuan1918andwaser0434 committed 2026-10-05 02:19:58 +08:00
1 parent 3bd5e1947b
commit 900b1592e1
3 files changed
+306 -24

No files matched your search

+127 -19
View File
@@ -61,6 +61,7 @@ import {
threadTrailingPending,
type SidechatLiveEvent,
type SidechatThreadInfo,
type SideThreadRow,
} from '../sidechat-core.ts'
import {
formatDurationMs,
@@ -110,6 +111,60 @@ export function consumeSidechatSeed(): string | undefined {
* StrictMode / HMR must not mint two threads for one tab). */
const inFlightStarts = new Set<string>()
/** Where the last side-chat thread of each main session is remembered (the
* client store's own key space, like the diff pane's redaction flag). */
const LAST_THREAD_KEY = 'dsh-sidebar:v1:sidechat-thread'
/** The in-memory mirror of {@link LAST_THREAD_KEY}. */
const lastThreadBySession = new Map<string, string>()
/** Whether the localStorage mirror has been read into the map yet. */
let lastThreadsLoaded = false
/**
* A native tab's record and its navigation params live in the host's memory
* only, so collapsing the sidebar (or restarting DSH) remounts the tab with
* NO thread bound — the autoCreate path — and the reader would land in a
* brand-new empty thread instead of the one they were in. Remembering the
* last thread per session is what makes the reattach below possible; the
* storage is best-effort (a denied or unparseable entry just means the
* reattach falls back to the newest thread).
*/
function loadLastThreads(): void {
if (lastThreadsLoaded) return
lastThreadsLoaded = true
try {
const raw = localStorage.getItem(LAST_THREAD_KEY)
if (raw === null) return
const parsed: unknown = JSON.parse(raw)
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return
for (const [sessionId, threadId] of Object.entries(parsed as Record<string, unknown>)) {
if (typeof threadId === 'string') lastThreadBySession.set(sessionId, threadId)
}
} catch {
// No storage (or unreadable JSON): nothing was remembered.
}
}
/** The thread a session's side-chat tab was last bound to, if any. */
function lastSidechatThread(sessionId: string): string | undefined {
loadLastThreads()
return lastThreadBySession.get(sessionId)
}
/** Remember the side-chat thread a session is bound to (also across reloads). */
function rememberSidechatThread(sessionId: string, threadId: string): void {
loadLastThreads()
if (lastThreadBySession.get(sessionId) === threadId) return
lastThreadBySession.set(sessionId, threadId)
try {
localStorage.setItem(LAST_THREAD_KEY, JSON.stringify(Object.fromEntries(lastThreadBySession)))
} catch {
// A full or denied storage keeps the in-memory binding: reattaching
// within this page still works, only a reload loses it.
}
}
/** Per-thread transcript cache: thread-own events merged by seq (polls ride
* the afterSeq delta and never re-download what they already hold). */
interface ThreadCache {
@@ -446,6 +501,19 @@ export function SideChatView(props: {
return sideThreadRows(list.byId, scope.sessionId).filter(row => !archived.has(row.id))
}, [list, scope.sessionId, archivedIds])
/** The newest thread of `candidates`: the session list carries the thread
* rows but not their age, so the creation order comes from the host's
* subagent catalog. An untouched "new thread" placeholder only wins when
* nothing else is left. */
const newestThreadId = useCallback((candidates: readonly SideThreadRow[]): string | undefined => {
const catalog = list.projectionsBySession?.[scope.sessionId]?.values.subagentCatalog
const rank = (id: string): number => catalog?.find(entry => entry.id === id)?.createdAt ?? 0
const real = candidates.filter(row => row.title !== SIDE_NEW_THREAD_TITLE)
const pool = real.length > 0 ? real : candidates
if (pool.length === 0) return undefined
return pool.reduce((newest, row) => (rank(row.id) > rank(newest.id) ? row : newest)).id
}, [list, scope.sessionId])
// The thread this tab is bound to rides tab.meta (refresh-restored).
const threadId = sidechatThreadIdOf(tab)
const autoCreate = (tab.meta as { autoCreate?: unknown } | undefined)?.autoCreate === true
@@ -501,12 +569,41 @@ export function SideChatView(props: {
}
}, [ctx, scope.sessionId, tab.id])
// Codex-style immediate create: an autoCreate tab spawns its thread as
// soon as it first renders.
/**
* The existing thread an unbound side chat should reattach to: the binding
* this session was last in (kept only while the thread is still listed — a
* deleted or archived thread must not be revived), then the newest thread
* that already carries a real first prompt.
*/
const reattachTarget = useCallback((): string | undefined => {
const remembered = lastSidechatThread(scope.sessionId)
if (remembered !== undefined && (threads.length === 0 || threads.some(row => row.id === remembered))) {
return remembered
}
return newestThreadId(threads)
}, [newestThreadId, scope.sessionId, threads])
// Codex-style immediate create: an autoCreate tab spawns its thread as soon
// as it first renders. A tab that LOST its binding (a panel collapse or a
// restart — the host holds navigation params in memory only, see
// loadLastThreads) reattaches to the thread the session was last in instead
// of leaving yet another orphan "Side: New thread" session behind.
useEffect(() => {
if (threadId !== undefined || !autoCreate || !visible) return
const reattach = reattachTarget()
if (reattach !== undefined) {
// Name the seat session: the same native id names a tab in every session.
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: { threadId: reattach } }, scope.sessionId)
return
}
void startThread()
}, [threadId, autoCreate, visible, startThread])
}, [threadId, autoCreate, visible, startThread, reattachTarget, ctx, tab.id, scope.sessionId])
// Remember the thread this tab holds, so reopening the panel (or a restart)
// reattaches it instead of minting another one.
useEffect(() => {
if (threadId !== undefined) rememberSidechatThread(scope.sessionId, threadId)
}, [threadId, scope.sessionId])
// The tab title follows the thread's durable label (the first prompt
// renames the thread; the strip picks it up here).
@@ -648,11 +745,27 @@ export function SideChatView(props: {
scroller.scrollTop = scroller.scrollHeight
}, [rows.length, threadId])
/** Open a NEW thread tab (createTab mints the autoCreate tab; its view
* creates the thread on mount). */
const openNewThread = (): void => {
/** Open a NEW thread tab: the thread is created FIRST and parked for the
* descriptor's createTab, so the tab that opens is already bound to it —
* the pane never sits on the empty hero while a thread is being created,
* and the native page kind (which re-delivers its one tab instead of
* copying it) switches to the new thread through the same navigation the
* thread menu uses. */
const openNewThread = async (): Promise<void> => {
setMenuOpen(false)
ctx.get('betterSidebar')?.openTab({ type: 'sidechat' }, scope)
if (busy !== null) return
setBusy('starting')
setError(null)
try {
const { childId } = await api.sidechatStart(scope.sessionId)
rememberSidechatThread(scope.sessionId, childId)
parkSidechatReopen(childId)
ctx.get('betterSidebar')?.openTab({ type: 'sidechat' }, scope)
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause))
} finally {
setBusy(null)
}
}
/** Switch to an existing thread: parked for createTab, deduped to the
@@ -721,15 +834,10 @@ export function SideChatView(props: {
* order), the newest placeholder only when nothing else is left, and
* `undefined` when the thread menu is empty — the tab then unbinds to the
* empty state instead of staying bound to an archived session. */
const fallbackThreadId = useCallback((excludeId: string): string | undefined => {
const candidates = threads.filter(row => row.id !== excludeId)
const catalog = list.projectionsBySession?.[scope.sessionId]?.values.subagentCatalog
const rank = (id: string): number => catalog?.find(entry => entry.id === id)?.createdAt ?? 0
const real = candidates.filter(row => row.title !== SIDE_NEW_THREAD_TITLE)
const pool = real.length > 0 ? real : candidates
if (pool.length === 0) return undefined
return pool.reduce((newest, row) => (rank(row.id) > rank(newest.id) ? row : newest)).id
}, [list, scope.sessionId, threads])
const fallbackThreadId = useCallback(
(excludeId: string): string | undefined => newestThreadId(threads.filter(row => row.id !== excludeId)),
[newestThreadId, threads],
)
const handleSave = async (): Promise<void> => {
if (threadId === undefined || !canSave || busy !== null) return
@@ -792,11 +900,11 @@ export function SideChatView(props: {
busy === 'starting' && css.sidechatShimmerText,
)}
>
{busy === 'starting' ? t('sideChatCreating') : t('sideChatEmpty')}
{busy === 'starting' || (autoCreate && error === null) ? t('sideChatCreating') : t('sideChatEmpty')}
</div>
<div className={css.sidechatHeroDesc}>{t('sideChatEmptyDesc')}</div>
{error !== null && <div className={css.sidechatError}>{t('sideChatError', { message: error })}</div>}
{busy !== 'starting' && (
{busy !== 'starting' && (!autoCreate || error !== null) && (
<button
type="button"
className={css.sidechatPrimaryBtn}
@@ -830,7 +938,7 @@ export function SideChatView(props: {
)}
items={menuItems}
selectedId={threadId}
onSelect={(id) => { if (id === '$new') openNewThread(); else openExistingThread(id) }}
onSelect={(id) => { if (id === '$new') void openNewThread(); else openExistingThread(id) }}
onClose={() => { setMenuOpen(false) }}
align="end"
portal
+44 -4
View File
@@ -130,6 +130,14 @@ export interface NativeTabRecords {
title: string
params: NativeTabParams | undefined
scope: SessionScope
/**
* The native navigation revision this call carries. The native surface
* re-delivers the LAST navigation on every render (its `useTabInfo`
* snapshot is stable until the host really navigates), so the seed `meta`
* is adopted once per revision — see {@link createNativeTabRecords}.
* Absent (the plugin's own layout, an older caller) never re-adopts.
*/
revision?: number
/**
* The descriptor's own factory, called ONCE for a record that arrives
* without seed fields (a native guide open, which knows nothing about the
@@ -185,6 +193,19 @@ function samePaths(left: readonly string[], right: readonly string[]): boolean {
export function createNativeTabRecords(): NativeTabRecords {
const views = new Map<string, View>()
const instances = new Map<string, number>()
/**
* Record key -> the navigation revision whose seed meta was last adopted.
*
* `meta` has two writers: an opener's navigation (a page kind is
* re-delivered with fresh `params` on every open — the side chat switches
* threads that way) and the view itself through `updateTab` (a tab that
* minted a thread binds its id there). The native surface re-delivers the
* SAME navigation on every render, so adopting the seed unconditionally
* would let the plugin's own write be overwritten on the next pass: the tab
* would fall back to "unbound" and mint thread after thread. Only a
* revision this record has not adopted yet may seed.
*/
const navigationRevisions = new Map<string, number>()
const listeners = new Set<() => void>()
const notify = (): void => { for (const listener of listeners) listener() }
const put = (key: string, view: View): void => {
@@ -224,7 +245,7 @@ export function createNativeTabRecords(): NativeTabRecords {
next.subscribe(syncExpanded)
syncExpanded()
},
ensure({ sessionId, id, kind, title, params, scope, mint }) {
ensure({ sessionId, id, kind, title, params, scope, revision, mint }) {
const key = viewKey(sessionId, id)
const existing = views.get(key)
if (existing === undefined) {
@@ -249,15 +270,26 @@ export function createNativeTabRecords(): NativeTabRecords {
version: 0,
}
views.set(key, minted)
// The seed meta of THIS navigation is what the mint just adopted: a
// re-delivery of the same navigation must not re-adopt it (it would
// clobber the thread the view writes back through `updateTab`).
if (revision !== undefined) navigationRevisions.set(key, revision)
return minted
}
// A navigation may carry new seed fields (the editor's in-place switch,
// a browser tab pointed at another URL); the record's identity and any
// plugin-side mutation (title/meta from updateTab) stay.
// a browser tab pointed at another URL, a side chat switching threads);
// the record's identity and any plugin-side mutation (title from
// `updateTab`) stay. `meta` is the exception — it also has a plugin-side
// writer, so only a navigation this record has not adopted yet may seed
// it (see {@link navigationRevisions}).
const patch: Partial<SidebarTab> = {}
const nextPath = params?.path ?? params?.url
if (nextPath !== undefined && nextPath !== existing.tab.path) patch.path = nextPath
if (params?.diff !== undefined) patch.diff = params.diff
if (revision !== undefined && navigationRevisions.get(key) !== revision) {
navigationRevisions.set(key, revision)
if (params?.meta !== undefined) patch.meta = params.meta
}
// The expansion set always mirrors the CURRENT session state (a record
// reused for another session must not keep the previous one's set).
const expanded = expandedOf(scope.sessionId)
@@ -283,7 +315,11 @@ export function createNativeTabRecords(): NativeTabRecords {
put(key, { ...entry, tab: { ...entry.tab, ...patch } })
},
drop(sessionId, id) {
if (views.delete(viewKey(sessionId, id))) notify()
const key = viewKey(sessionId, id)
// The revision ledger dies with the record: an id reused later arrives
// with its own navigation, and a stale entry would swallow its seed.
navigationRevisions.delete(key)
if (views.delete(key)) notify()
},
toggleExpanded(sessionId, id, path) {
const entry = views.get(viewKey(sessionId, id))
@@ -308,6 +344,9 @@ export function createNativeTabRecords(): NativeTabRecords {
const owner = separator === -1 ? key : key.slice(0, separator)
if (!sessions.has(owner)) {
views.delete(key)
// The ledger is part of the record (see `drop`): a session the user
// deleted must not leave its revisions behind.
navigationRevisions.delete(key)
dropped = true
}
}
@@ -400,6 +439,7 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
title: nativeTab.title,
params,
scope,
revision: nativeTab.navigation.revision,
mint: () => {
const state = store.getSnapshot().state
if (descriptor?.createTab === undefined || state === undefined) return undefined
+135 -1
View File
@@ -11,7 +11,7 @@ import { act } from 'react-dom/test-utils'
import { createNativeTabRecords, NativeTabBody, NativeTabTitle } from '../src/client/native/tab-adapter.tsx'
import { createNativeSurface } from '../src/client/native/surface.ts'
import { fileParamsOf, registerNativeSurface } from '../src/client/native/index.ts'
import { createBetterSidebarService, type SidebarSurface } from '../src/client/service.ts'
import { createBetterSidebarService, type SidebarSurface, type TabComponentProps } from '../src/client/service.ts'
import { createSidebarStore, toggleExpanded, type SidebarTab } from '../src/client/state.ts'
const scope = { sessionId: 's1', cwd: '/work' }
@@ -47,6 +47,51 @@ describe('createNativeTabRecords', () => {
expect(view.tab).toMatchObject({ id: 'tab-3', path: '/work/b.ts', title: 'renamed.ts' })
})
it('adopts a navigation seed meta once per revision (#762 / #684)', () => {
// The native surface re-delivers the LAST navigation on every render and
// bumps `revision` only for a real one: the seed meta must win for a new
// revision (the thread menu switching threads, #762) and leave the meta
// the VIEW wrote alone otherwise (#684: a re-adopted seed unbound the tab
// and made it mint thread after thread).
const records = createNativeTabRecords()
const sidechat = (revision: number, threadId: string) => records.ensure({
sessionId: 's1',
id: 'tab-11',
kind: 'sidechat',
title: 'Side Chat',
params: { meta: { threadId } },
scope,
revision,
})
sidechat(1, 't-1')
// The view binds the thread it minted — the plugin's own meta writer.
records.update('s1', 'tab-11', { meta: { threadId: 't-2' } })
sidechat(1, 't-1')
expect(records.get('s1', 'tab-11')?.tab.meta).toEqual({ threadId: 't-2' })
sidechat(2, 't-3')
expect(records.get('s1', 'tab-11')?.tab.meta).toEqual({ threadId: 't-3' })
// …and the re-delivery of THAT navigation does not undo the next binding.
records.update('s1', 'tab-11', { meta: { threadId: 't-4' } })
sidechat(2, 't-3')
expect(records.get('s1', 'tab-11')?.tab.meta).toEqual({ threadId: 't-4' })
})
it('never re-adopts the seed meta of a caller that carries no revision', () => {
// Absent revision = a caller that is not the native surface. It still mints
// the record from its seed, but it must NEVER overwrite a plugin-side
// binding afterwards — not even when the last navigation this record
// adopted carried a revision (an unguarded comparison would read that
// stored number as "a different navigation").
const records = createNativeTabRecords()
records.ensure({ sessionId: 's1', id: 'tab-12', kind: 'sidechat', title: 'Side Chat', params: { meta: { threadId: 't-1' } }, scope, revision: 5 })
records.update('s1', 'tab-12', { meta: { threadId: 't-2' } })
records.ensure({ sessionId: 's1', id: 'tab-12', kind: 'sidechat', title: 'Side Chat', params: { meta: { threadId: 't-9' } }, scope })
expect(records.get('s1', 'tab-12')?.tab.meta).toEqual({ threadId: 't-2' })
})
it('tracks expansion in the SESSION state and bumps the record version', () => {
const store = createSidebarStore()
store.setSession('s1')
@@ -774,6 +819,95 @@ describe('NativeTabBody full-height host wrapper', () => {
})
})
/**
* The revision the adapter READS off the native record is what gates the seed
* meta (the `createNativeTabRecords` cases above pin the gate itself): this
* pins the wiring at the real call site, where a missing `revision` would
* leave the gate permanently closed (the #762 fix silently absent) or
* permanently open (#684 back).
*/
describe('NativeTabBody — the navigation revision reaches the record', () => {
it('adopts a new navigation meta and keeps the plugin-written one across re-renders', () => {
const metaSeen: unknown[] = []
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
service.registerTab({
id: 'sidechat',
title: 'Side chat',
component: (props: TabComponentProps) => {
metaSeen.push((props.tab.meta as { threadId?: string } | undefined)?.threadId)
return null
},
})
const records = createNativeTabRecords()
const ctx = { sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: {} }) } } } as never
const navigation: { address: string; params: { meta?: unknown } | undefined; revision: number } = {
address: 'sidebar://sidechat',
params: { meta: { threadId: 't-1' } },
revision: 1,
}
const info = {
tab: {
id: 'native-7',
kind: 'sidechat',
title: 'Side chat',
contentId: 'sidebar://sidechat',
visible: true,
navigation,
signal: new AbortController().signal,
},
}
const host = document.createElement('div')
document.body.appendChild(host)
let root: Root | undefined
const draw = (): void => {
act(() => {
root!.render(createElement(NativeTabBody, {
sessionId: 's1',
ctx,
store,
service,
records,
descriptorId: 'sidechat',
useTabInfo: () => info,
}))
})
}
act(() => {
root = createRoot(host)
root.render(createElement(NativeTabBody, {
sessionId: 's1',
ctx,
store,
service,
records,
descriptorId: 'sidechat',
useTabInfo: () => info,
}))
})
expect(metaSeen.at(-1)).toBe('t-1')
// The view binds the thread it minted — the `updateTab` path.
act(() => { records.update('s1', 'native-7', { meta: { threadId: 't-2' } }) })
expect(metaSeen.at(-1)).toBe('t-2')
// A re-render re-delivers the SAME navigation (same revision).
draw()
expect(metaSeen.at(-1)).toBe('t-2')
// The thread menu navigates: the host replaces the params and bumps the
// revision, so the new thread must win.
navigation.params = { meta: { threadId: 't-3' } }
navigation.revision = 2
draw()
expect(metaSeen.at(-1)).toBe('t-3')
act(() => { root?.unmount() })
host.remove()
})
})
/**
* The native tab CHIP: the host's tab definition carries no icon field, so
* the plugin draws the glyph itself inside the `sidebar.right.pane.tab.title`