fix(sidechat): preserve independent native tabs and exact thread bindings
This commit is contained in:
1 parent
83a25c27bc
commit
ba6f3a3423
14 files changed
+726
-116
No files matched your search
@@ -26,9 +26,9 @@
|
||||
|
||||
| 事项 | 说明 |
|
||||
|---|---|
|
||||
| 生命周期回调 | 原生面的「打开」不区分新建/聚焦,因此 `onOpen` 每次打开都触发(`onActivate` 仅在插件自己的底部工作台里触发)。程序化 `closeTab` 与 `activateTab` 在原生 tab 上正常工作:关闭走宿主 per-session 面,回调拿到完整 `tab`(**含 `meta`**);激活经 `ISidebarRight.focus` 聚焦 tab 与其 pane。**例外**:用户直接点原生 tab 上的 × 关闭不会触发 `onClose`(宿主不广播该事件,插件在 tab 体卸载时丢弃记录) |
|
||||
| 去重 | 原生按 `(kind, 地址)` 去重:有 `createTab` 的类型每次新开一个 tab(sidechat / diff),其余聚焦已有 tab;`dedupeKey` 的自定义语义不参与原生面 |
|
||||
| 布局持久化 | 原生栏的布局**只在内存**(刷新后回到折叠默认),插件自己的底部工作台仍然持久化 |
|
||||
| 生命周期回调 | 原生面的「打开」不区分新建/聚焦,因此 `onOpen` 每次打开都触发(`onActivate` 仅在插件自己的底部工作台里触发)。程序化 `closeTab` 与 `activateTab` 在原生 tab 上正常工作:关闭走宿主 per-session 面,回调拿到完整 `tab`(**含 `meta`**);激活经 `ISidebarRight.focus` 聚焦 tab 与其 pane。**侧聊例外已修复**:sidechat 通过宿主 `registerCloseHandler` 接收原生 ×/菜单关闭,归档并释放该线程一次;组件卸载、折叠、刷新和插件卸载不触发归档。其他类型仍需自行注册宿主关闭处理器 |
|
||||
| 去重 | 原生页面默认每个 pane 同 kind 单实例,`createTab` / `revealIfOpened: false` 不能覆盖这条宿主规则。声明 `multiple: true` 才会创建独立原生 occurrence;内置 sidechat 已声明。多实例类型的 `dedupeKey` 在原生打开时参与查找;显式 `seed.meta` 的线程打开同时检查底部与原生栏,已有线程只聚焦其所属面。底部工厂返回值也会合并显式 `seed.meta` 再去重。 |
|
||||
| 布局持久化 | 原生宿主持久化布局及 contentId,但不持久化 navigation.params。sidechat 单独按 `(sessionId, contentId)` 保存线程绑定和标题(最多 512 项);新建从不恢复 last/newest 线程。缺失/损坏绑定的旧标签显示空态与历史菜单,不自动猜测或创建替代线程。底部工作台继续保存 tab.meta。 |
|
||||
| 跨会话打开 | 目标会话的右侧栏 store 未挂载时,打开会排队到该会话上屏后重放 |
|
||||
| 内置类型接管 | 插件的 `editor` 类型以 `extension` 优先级认领 `dsh-resource://file/**`(压过内置 `ui-sidebar-documentpreview` 的 `text` 预览——即 `fallback` 带),并接管内置 `files` 页面 kind(`openTab('files')` 打开插件的文件树);插件卸载/禁用时内置实现自动复位。**但认领是有选择的**:宿主自己的文档预览已经覆盖的格式(表格 / PDF / 图片 / Office,清单见 §5.4)由 `editor.canOpen` 主动**拒绝**,地址交回内置 `text` 档 |
|
||||
| 文件树实时刷新(v0.21.1+) | 插件接管了内置 `files` 页,所以宿主自己的按目录 watch 覆盖不到这棵树——插件自带一条 `/sidebar/ws/fs-watch` socket:客户端上报**已展开**的目录集,宿主侧按目录 `fs.watch`(150ms 去抖、每连接上限 64 个句柄),变动后只让那一层缓存失效并重列;目录折叠即退订。路径仍走 `fs.tree` 同一套词法解析 |
|
||||
@@ -248,6 +248,8 @@ interface TabDescriptor {
|
||||
* 同类型 tab 而非新开)。显式给出 dedupeKey 时优先于 single。
|
||||
*/
|
||||
single?: boolean
|
||||
/** 原生页面多实例(内置 sidechat 已启用);缺省为宿主单实例页面。 */
|
||||
multiple?: boolean
|
||||
/**
|
||||
* 去重键:openTab 时若已存在 dedupeKey 相同的 tab,则聚焦而非新开。
|
||||
* 返回 undefined 表示不去重(每次都新开,但同 id 会被 id 安全网聚焦)。
|
||||
@@ -815,6 +817,8 @@ interface BetterSidebarService {
|
||||
* ——走定向通道(不发布、不通知),与定向 `openTab(seed, scope)` 同一条路;
|
||||
* 这正是文件树删除调解能覆盖后台会话页面的机制。不传 scope 行为不变。 */
|
||||
closeTab(tabId: string, scope?: SessionScope): void
|
||||
/** 异步创建返回前可检查标签是否仍存在,避免关闭后绑定到不存在的标签。 */
|
||||
hasTab?(tabId: string, sessionId: string): boolean
|
||||
/** 订阅注册表变化(register/dispose 时触发) */
|
||||
subscribe(listener: () => void): () => void
|
||||
// ── v0.12.0+ ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
# Independent native Side Chat tabs
|
||||
|
||||
## Reproduction and cause
|
||||
|
||||
On the native right sidebar, open Side Chat, then use the tab strip's `+` and choose Side Chat again. The host focuses the existing tab. The `+` below the composer creates a new thread but navigates that same tab, so it appears to replace the old conversation.
|
||||
|
||||
There are two independent causes:
|
||||
|
||||
1. The descriptor factory mints a unique plugin tab id, but native registration omits `multiple`. DSH therefore uses the singleton `sidebar://sidechat` page identity; `revealIfOpened: false` does not override singleton-page deduplication.
|
||||
2. An unbound view restores the session's last/newest thread before considering `autoCreate`. Giving the host independent occurrences alone would still bind new tabs to the old thread.
|
||||
|
||||
## Implementation
|
||||
|
||||
- Side Chat opts into `TabDescriptor.multiple`, forwarded to native registration. Other kinds retain their previous multiplicity.
|
||||
- A fresh `autoCreate` view starts its own thread. Composer/history actions pass `meta.threadId` explicitly rather than relying on the global parked seed.
|
||||
- Native layout identity is durable, navigation parameters are not. A bounded versioned localStorage map stores only thread id and title under `(seat session, contentId)`; it never stores transcripts or drafts. Reloads and client-entry replacements restore that exact occurrence. A new occurrence has a new contentId and cannot inherit another tab's binding.
|
||||
- Missing/corrupt bindings use the neutral hero with the existing history menu; no newest-thread guess, automatic replacement thread, or deletion of old history. The legacy last-thread hint remains written for external consumers but is no longer our restore authority.
|
||||
- Existing-thread opens dedupe across both bottom and native carriers. The host inventory also covers unvisited/restored native tabs; explicit seeds are persisted immediately after placement so synchronous repeated opens can dedupe before React mounts. Bottom factory results merge explicit `seed.meta` before dedupe.
|
||||
- Native explicit closes use `registerCloseHandler`, not component unmount or `AbortSignal` (the latter also fires on host teardown). Registration follows the host service lifetime, including late arrival. This applies the already-declared sidechat `onClose` behavior once; programmatic close can also resolve a restored occurrence before its body is visited. Plugin teardown keeps bindings for recovery.
|
||||
- Creation locks include the parent session, preventing two sessions' `tab1` from blocking each other. A late creation result for a closed tab is released instead of rebound.
|
||||
- `reveal:false` and cross-session queueing preserve focus isolation. A history open whose owner is in the collapsed bottom workbench expands that workbench.
|
||||
|
||||
## Compatibility and scope
|
||||
|
||||
The contribution is based on upstream `dev` at `09b83cc`. It preserves the image-draft, GenUI, and model-selection paths. The #949 manual archive guard remains intact. A recoverable non-subagent binding clears only its own tab after archive, rather than stealing another open thread.
|
||||
|
||||
**Close semantics remain archive-on-close** as specified by the existing descriptor and #942/#981. This patch makes the native close button honor that behavior too. A user who needs an independently recoverable ordinary session must use “Save as new session” before closing; this change does not introduce an unarchive interface for hidden subagent sessions.
|
||||
|
||||
No DSH source changes, new dependency, version bump, polling loop, model request, or unrelated terminal behavior change. The storage holds at most 512 recent native bindings. When storage is unavailable or a binding is missing, recovery uses the neutral state rather than guessing a thread.
|
||||
|
||||
## Verification
|
||||
|
||||
Regression coverage:
|
||||
|
||||
- Two native guide opens and two ordinary service opens yield independent occurrences.
|
||||
- Composer `+` opens an explicit new-thread binding without rewriting the current tab.
|
||||
- History dedupe works before body mount and across bottom/native carriers.
|
||||
- Independent reload and client-entry remount restore, cross-session identical ids, malformed storage, explicit-close cleanup, teardown retention, and close-during-create.
|
||||
- Archived-thread handling and the upstream image-composer restore test use exact occurrence identity.
|
||||
- A real-host Chromium test clicks the two top-level opens and composer `+`, asserts three bindings, reloads, and visits all three without another creation request. Its sidechat transport is stubbed, so this proves real host/DOM binding behavior, not concurrent model execution.
|
||||
|
||||
The original v0.28.2 source fails the three discriminating component tests (fresh create with an existing thread, explicit composer new-tab binding, concurrent same-id tabs in two parent sessions). The repaired local implementation passes them; the contribution is revalidated on current dev rather than reusing those old suite totals.
|
||||
|
||||
Validation commands and final results are recorded in the PR body. Relevant commands:
|
||||
|
||||
```sh
|
||||
pnpm install --frozen-lockfile
|
||||
pnpm typecheck
|
||||
pnpm lint
|
||||
pnpm test --maxWorkers=2
|
||||
pnpm build
|
||||
pnpm check:consumer-types
|
||||
pnpm check:engines
|
||||
pnpm pack
|
||||
pnpm exec playwright install chromium
|
||||
bash scripts/e2e-mount.sh --grep 'sidechat multi-instance|plugin mounts into|bottom workbench opens|native tab types survive'
|
||||
```
|
||||
|
||||
Mount tests install a tarball into a new scratch profile through the official CLI. No user profile or production session is used.
|
||||
|
||||
### Receipt — 2026-11-04
|
||||
|
||||
Typecheck, repository-wide ESLint, build, pack and consumer declarations passed. The full unit/component sweep passed 247 files / 3047 tests, with 17 platform-related skips. Engine checks passed for installed ripgrep; fd was absent and its probes skipped. The four selected Chromium cases passed on the pinned DSH 0.2.1-rc.1 host (37.7 s). Windows execution is left to upstream CI. Two extra review regressions (queued-native-to-bottom ownership and closing a restored unvisited tab) were first observed failing, then passed with the fixes.
|
||||
+48
-85
@@ -101,7 +101,6 @@ import {
|
||||
type SidechatModelInfo,
|
||||
type SidechatPendingInput,
|
||||
type SidechatThreadInfo,
|
||||
type SideThreadRow,
|
||||
} from '../sidechat-core.ts'
|
||||
import {
|
||||
formatDurationMs,
|
||||
@@ -234,15 +233,9 @@ function scheduleLastThreadsWrite(): void {
|
||||
}, 200)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
/** Read the legacy last-thread hint for external consumers. It is deliberately
|
||||
* NOT a restore authority: native/sidechat-bindings stores each occurrence's
|
||||
* exact thread, whereas a per-session hint collapses every tab onto one. */
|
||||
function loadLastThreads(): void {
|
||||
if (lastThreadsLoaded) return
|
||||
lastThreadsLoaded = true
|
||||
@@ -259,12 +252,6 @@ function loadLastThreads(): void {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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()
|
||||
@@ -1066,24 +1053,16 @@ 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 createdAt = new Map((catalog ?? []).map(entry => [entry.id, entry.createdAt]))
|
||||
const rank = (id: string): number => createdAt.get(id) ?? 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
|
||||
|
||||
useEffect(() => {
|
||||
if (threadId !== undefined && archivedIds.includes(threadId)) {
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: {}, title: t('sideChatUntitled') }, scope.sessionId)
|
||||
}
|
||||
}, [archivedIds, ctx, scope.sessionId, tab.id, threadId])
|
||||
|
||||
const draft = useSidechatDraft(threadId)
|
||||
const composer = draft.owner.text
|
||||
const setComposer = draft.setText
|
||||
@@ -1244,54 +1223,42 @@ export function SideChatView(props: {
|
||||
|
||||
/** Create this tab's thread (immediate-create tabs and hero retries). */
|
||||
const startThread = useCallback(async (): Promise<void> => {
|
||||
if (inFlightStarts.has(tab.id)) return
|
||||
inFlightStarts.add(tab.id)
|
||||
const startKey = JSON.stringify([scope.sessionId, tab.id])
|
||||
if (inFlightStarts.has(startKey)) return
|
||||
inFlightStarts.add(startKey)
|
||||
setBusy('starting')
|
||||
setError(null)
|
||||
try {
|
||||
const { childId } = await api.sidechatStart(scope.sessionId)
|
||||
const sidebar = ctx.get('betterSidebar')
|
||||
if (sidebar?.hasTab?.(tab.id, scope.sessionId) === false) {
|
||||
// The user closed this unbound tab while creation was in flight.
|
||||
// Release only the new orphan, never update another occurrence.
|
||||
const workspace = ctx.get('uiWorkspace') as unknown as ArchiveSessionFace | undefined
|
||||
try { await workspace?.archiveSession?.(childId, { stopActivity: true }) }
|
||||
finally { await api.sidechatDispose(childId) }
|
||||
return
|
||||
}
|
||||
// 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 {
|
||||
inFlightStarts.delete(tab.id)
|
||||
inFlightStarts.delete(startKey)
|
||||
setBusy(null)
|
||||
}
|
||||
}, [ctx, scope.sessionId, tab.id])
|
||||
|
||||
/**
|
||||
* 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.
|
||||
// autoCreate is an explicit NEW conversation, not a request to resume the
|
||||
// session's last thread. Native restores are resolved by exact contentId in
|
||||
// the adapter; bottom tabs already persist their own meta.
|
||||
useEffect(() => {
|
||||
if (threadId !== undefined || !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
|
||||
}
|
||||
if (autoCreate) void startThread()
|
||||
}, [threadId, autoCreate, visible, startThread, reattachTarget, ctx, tab.id, scope.sessionId])
|
||||
if (threadId !== undefined || !autoCreate || !visible) return
|
||||
void startThread()
|
||||
}, [threadId, autoCreate, visible, startThread])
|
||||
|
||||
// Remember the thread this tab holds, so reopening the panel (or a restart)
|
||||
// reattaches it instead of minting another one.
|
||||
// Compatibility hint for consumers of the old last-thread key. Our own
|
||||
// restoration never reads it: every native occurrence has its own binding.
|
||||
useEffect(() => {
|
||||
if (threadId !== undefined) rememberSidechatThread(scope.sessionId, threadId)
|
||||
}, [threadId, scope.sessionId])
|
||||
@@ -1664,8 +1631,7 @@ export function SideChatView(props: {
|
||||
try {
|
||||
const { childId } = await api.sidechatStart(scope.sessionId)
|
||||
rememberSidechatThread(scope.sessionId, childId)
|
||||
parkSidechatReopen(childId)
|
||||
ctx.get('betterSidebar')?.openTab({ type: 'sidechat' }, scope)
|
||||
ctx.get('betterSidebar')?.openTab({ type: 'sidechat', meta: { threadId: childId } }, scope)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause))
|
||||
} finally {
|
||||
@@ -1678,8 +1644,7 @@ export function SideChatView(props: {
|
||||
const openExistingThread = (id: string): void => {
|
||||
setMenuOpen(false)
|
||||
if (id === threadId) return
|
||||
parkSidechatReopen(id)
|
||||
ctx.get('betterSidebar')?.openTab({ type: 'sidechat' }, scope)
|
||||
ctx.get('betterSidebar')?.openTab({ type: 'sidechat', meta: { threadId: id } }, scope)
|
||||
}
|
||||
|
||||
const menuItems = useMemo<MenuEntry[]>(() => {
|
||||
@@ -1978,16 +1943,6 @@ export function SideChatView(props: {
|
||||
}
|
||||
}
|
||||
|
||||
/** The thread that should replace `excludeId` once it is archived: the newest
|
||||
* real thread first (the host's own subagent catalog carries the creation
|
||||
* 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 => newestThreadId(threads.filter(row => row.id !== excludeId)),
|
||||
[newestThreadId, threads],
|
||||
)
|
||||
|
||||
const handleSave = async (): Promise<void> => {
|
||||
if (threadId === undefined || !canSave || busy !== null) return
|
||||
setBusy('saving')
|
||||
@@ -2015,12 +1970,9 @@ export function SideChatView(props: {
|
||||
|
||||
/** Archive the bound thread on the host (the same capability the session
|
||||
* list's own archive action uses; `stopActivity` settles a running agent
|
||||
* first). Disabled for a side thread: the host session list never lists a
|
||||
* subagent-origin row, so no "unarchive" entry could ever recover it (issue
|
||||
* #949) — the guard below makes that a hard rule, not just a disabled
|
||||
* styling. For a recoverable binding the tab then moves to another live
|
||||
* thread: leaving it bound to an archived session would dead-end the panel,
|
||||
* because the host refuses to open archived sessions. */
|
||||
* first). The upstream #949 guard still disables this for subagent threads.
|
||||
* A recoverable binding unbinds after archive; another live thread may
|
||||
* already own its own tab and must not be substituted here. */
|
||||
const handleArchive = async (): Promise<void> => {
|
||||
if (threadId === undefined || busy !== null || archiveBlocked) return
|
||||
setBusy('archiving')
|
||||
@@ -2030,8 +1982,8 @@ export function SideChatView(props: {
|
||||
const service = ctx.get('uiWorkspace') as unknown as ArchiveSessionFace | undefined
|
||||
if (service?.archiveSession === undefined) throw new Error('the workspace service is unavailable')
|
||||
await service.archiveSession(threadId, { stopActivity: true })
|
||||
const next = fallbackThreadId(threadId)
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: next === undefined ? {} : { threadId: next } })
|
||||
// Never steal another open tab's thread after archiving this one.
|
||||
ctx.get('betterSidebar')?.updateTab(tab.id, { meta: {}, title: t('sideChatUntitled') }, scope.sessionId)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : String(cause))
|
||||
} finally {
|
||||
@@ -2065,6 +2017,17 @@ export function SideChatView(props: {
|
||||
{error === null ? t('sideChatNew') : t('sideChatRetry')}
|
||||
</button>
|
||||
)}
|
||||
{threads.length > 0 && !autoCreate && (
|
||||
<Menu
|
||||
open={menuOpen}
|
||||
anchor={<button type="button" className={css.sidechatIconBtn} aria-label={t('sideChatThreads')} onClick={() => { setMenuOpen(value => !value) }}><IconHistoryOutline16 /></button>}
|
||||
items={menuItems}
|
||||
onSelect={(id) => { if (id === '$new') void openNewThread(); else openExistingThread(id) }}
|
||||
onClose={() => { setMenuOpen(false) }}
|
||||
portal
|
||||
dense
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -275,6 +275,7 @@ export function builtinTabs(ctx: Context): readonly TabDescriptor[] {
|
||||
},
|
||||
{
|
||||
id: 'sidechat',
|
||||
multiple: true,
|
||||
title: () => t('sideChat'),
|
||||
description: () => t('guideDescSidechat'),
|
||||
icon: sidechatTabIcon,
|
||||
|
||||
@@ -187,7 +187,9 @@ export function apply(ctx: Context): void {
|
||||
// released with this activation.
|
||||
const nativeGuide = createNativeGuideCatalog(ctx)
|
||||
ctx.effect(() => () => { nativeGuide.dispose() }, 'dsh-better-sidebar: native guide catalog')
|
||||
const nativeSurface = createNativeSurface(ctx, nativeRecords)
|
||||
const nativeSurface = createNativeSurface(ctx, nativeRecords, (tab, sessionId) => {
|
||||
service.getTab(tab.type)?.onClose?.(tab, { sessionId })
|
||||
})
|
||||
service.setSurface(nativeSurface)
|
||||
// The optional dsh-context diagnostics: ONE controller per activation. It
|
||||
// re-proves the optional runtime faces itself, so the plugin needs no new
|
||||
|
||||
@@ -479,6 +479,7 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void {
|
||||
// (records, tree expansion, scroll, unsaved drafts) survives without
|
||||
// the adapter faking it.
|
||||
keepMounted: true,
|
||||
...(descriptor.multiple === true ? { multiple: true } : {}),
|
||||
...(isEditor
|
||||
? {
|
||||
patterns: ['dsh-resource://file/**'],
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Durable thread identity for native side-chat occurrences. The host persists
|
||||
* contentId, but not navigation.params. Never restore by tab1 or session-last:
|
||||
* both can name a different conversation after a new tab/layout is created. */
|
||||
export const SIDECHAT_BINDINGS_KEY = 'dsh-sidebar:v1:native-sidechat-bindings'
|
||||
const MAX_BINDINGS = 512
|
||||
|
||||
export interface SidechatBinding {
|
||||
sessionId: string
|
||||
contentId: string
|
||||
threadId: string
|
||||
title: string
|
||||
}
|
||||
|
||||
/** Only identity and a display label are persisted; never transcripts/drafts. */
|
||||
export function createSidechatBindings() {
|
||||
const rows = new Map<string, SidechatBinding>()
|
||||
const keyOf = (sessionId: string, contentId: string): string => JSON.stringify([sessionId, contentId])
|
||||
let loaded = false
|
||||
const trim = (): void => {
|
||||
while (rows.size > MAX_BINDINGS) rows.delete(rows.keys().next().value!)
|
||||
}
|
||||
const load = (): void => {
|
||||
if (loaded) return
|
||||
loaded = true
|
||||
try {
|
||||
const value: unknown = JSON.parse(localStorage.getItem(SIDECHAT_BINDINGS_KEY) ?? '[]')
|
||||
if (!Array.isArray(value)) return
|
||||
for (const row of value.slice(-MAX_BINDINGS)) {
|
||||
if (row === null || typeof row !== 'object') continue
|
||||
const { sessionId, contentId, threadId, title } = row as Partial<SidechatBinding>
|
||||
if (typeof sessionId !== 'string' || !sessionId || typeof contentId !== 'string'
|
||||
|| !contentId.startsWith('sidebar://sidechat') || typeof threadId !== 'string'
|
||||
|| !threadId || typeof title !== 'string') continue
|
||||
rows.set(keyOf(sessionId, contentId), { sessionId, contentId, threadId, title })
|
||||
}
|
||||
} catch { /* Denied/corrupt storage must not prevent new conversations. */ }
|
||||
}
|
||||
const save = (): void => {
|
||||
trim()
|
||||
try { localStorage.setItem(SIDECHAT_BINDINGS_KEY, JSON.stringify([...rows.values()])) } catch { /* best effort */ }
|
||||
}
|
||||
return {
|
||||
get(sessionId: string, contentId: string): SidechatBinding | undefined {
|
||||
load()
|
||||
return rows.get(keyOf(sessionId, contentId))
|
||||
},
|
||||
set(sessionId: string, contentId: string, threadId: string, title: string): void {
|
||||
load()
|
||||
const key = keyOf(sessionId, contentId)
|
||||
const previous = rows.get(key)
|
||||
if (previous?.threadId === threadId && previous.title === title) return
|
||||
rows.delete(key)
|
||||
rows.set(key, { sessionId, contentId, threadId, title })
|
||||
save()
|
||||
},
|
||||
delete(sessionId: string, contentId: string): void {
|
||||
load()
|
||||
if (rows.delete(keyOf(sessionId, contentId))) save()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -25,10 +25,11 @@ import { addressBaseOf } from '../address-base.ts'
|
||||
import { fileAddressFor } from '../resource-address.ts'
|
||||
import type { NativePathTab, NativeTabParams, SidebarSurface } from '../service.ts'
|
||||
import type { NativeTabRecords } from './tab-adapter.tsx'
|
||||
import type { SidebarTab } from '../state.ts'
|
||||
|
||||
/** One open the surface could not place yet. */
|
||||
type Pending =
|
||||
| { kind: 'tab'; sessionId: string; tabKind: string; params: NativeTabParams; revealIfOpened: boolean; preferNewPane: boolean }
|
||||
| { kind: 'tab'; sessionId: string; tabKind: string; params: NativeTabParams; revealIfOpened: boolean; preferNewPane: boolean; reveal?: boolean; reuseTab?: () => boolean; matchTab?: (tab: SidebarTab) => boolean }
|
||||
| { kind: 'resource'; sessionId: string; address: string; line: number | undefined; revealIfOpened: boolean; preferNewPane: boolean }
|
||||
|
||||
/**
|
||||
@@ -43,7 +44,11 @@ export interface MountedSessions {
|
||||
}
|
||||
|
||||
/** The controller face this module uses (a structural slice of `ISidebarRight`). */
|
||||
interface OpenTab { sessionId: string; tabId: string; kind: string; contentId: string }
|
||||
|
||||
interface NativeController {
|
||||
openTabs?: { getSnapshot(): readonly OpenTab[]; subscribe(listener: () => void): () => void }
|
||||
registerCloseHandler?(kind: string, handler: (sessionId: string, tab: { id: string; kind: string; contentId: string }) => void): () => void
|
||||
openTab(kind: string, options?: { params?: unknown; revealIfOpened?: boolean; preferNewPane?: boolean }): void
|
||||
openResource(address: string, options?: { params?: unknown; revealIfOpened?: boolean; preferNewPane?: boolean }): void
|
||||
close(tabId: string): void
|
||||
@@ -136,9 +141,41 @@ export function mountedSessionId(ctx: Context): string | undefined {
|
||||
* @param records - the plugin's native tab record registry.
|
||||
* @returns the surface, plus a disposer unbinding its two feed subscriptions.
|
||||
*/
|
||||
export function createNativeSurface(ctx: Context, records: NativeTabRecords): NativeSurface {
|
||||
export function createNativeSurface(ctx: Context, records: NativeTabRecords, onClose?: (tab: SidebarTab, sessionId: string) => void): NativeSurface {
|
||||
const pending: Pending[] = []
|
||||
const controller = (): NativeController | undefined => controllerOf(ctx)
|
||||
let closeController: NativeController | undefined
|
||||
let disposeClose: (() => void) | undefined
|
||||
const bindClose = (): void => {
|
||||
const api = controller()
|
||||
if (api === closeController || api?.registerCloseHandler === undefined) return
|
||||
disposeClose?.()
|
||||
closeController = api
|
||||
disposeClose = api.registerCloseHandler('sidechat', (sessionId, nativeTab) => {
|
||||
const tab = records.tabAt(sessionId, nativeTab.id, nativeTab.kind, nativeTab.contentId)
|
||||
// A service.close already claimed the lifecycle; native x/context-menu
|
||||
// closes arrive here with the binding still present. Never run on unload.
|
||||
records.drop(sessionId, nativeTab.id)
|
||||
records.sidechatBindings.delete(sessionId, nativeTab.contentId)
|
||||
if (tab !== undefined) onClose?.(tab, sessionId)
|
||||
})
|
||||
}
|
||||
const rememberSeed = (entry: Extract<Pending, { kind: 'tab' }>, opened: OpenTab): void => {
|
||||
if (entry.tabKind !== 'sidechat') return
|
||||
const meta = entry.params.meta as { threadId?: unknown } | undefined
|
||||
if (typeof meta?.threadId === 'string') {
|
||||
records.sidechatBindings.set(entry.sessionId, opened.contentId, meta.threadId, entry.params.title ?? '')
|
||||
}
|
||||
}
|
||||
|
||||
const findTab = (sessionId: string, kind: string, match: (tab: SidebarTab) => boolean): string | undefined => {
|
||||
const opened = controller()?.openTabs?.getSnapshot().find(row => {
|
||||
if (row.sessionId !== sessionId || row.kind !== kind) return false
|
||||
const tab = records.tabAt(row.sessionId, row.tabId, row.kind, row.contentId)
|
||||
return tab !== undefined && match(tab)
|
||||
})
|
||||
return opened?.tabId
|
||||
}
|
||||
|
||||
const place = (entry: Pending): boolean => {
|
||||
const api = controller()
|
||||
@@ -151,7 +188,25 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
...(entry.preferNewPane ? { preferNewPane: true } : {}),
|
||||
}
|
||||
if (onScreen) {
|
||||
if (entry.reuseTab?.() === true) return true
|
||||
const before = api.openTabs?.getSnapshot() ?? []
|
||||
if (entry.matchTab !== undefined) {
|
||||
const match = before.find(opened => {
|
||||
if (opened.sessionId !== entry.sessionId || opened.kind !== entry.tabKind) return false
|
||||
const tab = records.tabAt(opened.sessionId, opened.tabId, opened.kind, opened.contentId)
|
||||
return tab !== undefined && entry.matchTab!(tab)
|
||||
})
|
||||
if (match !== undefined && api.focus !== undefined) {
|
||||
if (entry.reveal !== false) api.focus(match.tabId)
|
||||
return true
|
||||
}
|
||||
}
|
||||
api.openTab(entry.tabKind, options)
|
||||
// Seed the durable binding before React mounts: two synchronous opens
|
||||
// of an existing thread must dedupe even with no body record yet.
|
||||
const opened = api.openTabs?.getSnapshot().find(tab => tab.sessionId === entry.sessionId
|
||||
&& tab.kind === entry.tabKind && !before.some(old => old.sessionId === tab.sessionId && old.tabId === tab.tabId))
|
||||
if (opened !== undefined) rememberSeed(entry, opened)
|
||||
return true
|
||||
}
|
||||
// Do not hand a non-current session's open to openTabIn(): for a session
|
||||
@@ -202,7 +257,11 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
* @returns the owning session, or undefined.
|
||||
*/
|
||||
const sessionOf = (tabId: string, sessionId?: string): string | undefined => {
|
||||
if (sessionId !== undefined) return records.has(sessionId, tabId) ? sessionId : undefined
|
||||
if (sessionId !== undefined) {
|
||||
const inventory = controller()?.openTabs?.getSnapshot()
|
||||
if (inventory !== undefined && !inventory.some(tab => tab.sessionId === sessionId && tab.tabId === tabId)) return 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 ?? {}
|
||||
@@ -241,6 +300,7 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
// pulse additionally reclaims the records of sessions that are gone.
|
||||
let mountedUnsubscribe: (() => void) | undefined
|
||||
const onListChange = (): void => {
|
||||
bindClose()
|
||||
if (mountedUnsubscribe === undefined) {
|
||||
const mounted = controller()?.mounted
|
||||
if (typeof mounted?.subscribe === 'function') mountedUnsubscribe = mounted.subscribe(flushPending)
|
||||
@@ -248,11 +308,21 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
flushPending()
|
||||
evictGoneSessions()
|
||||
}
|
||||
const closeSeat = typeof ctx.inject === 'function' ? ctx.inject(['sidebarRight'], () => {
|
||||
bindClose()
|
||||
return () => {
|
||||
disposeClose?.()
|
||||
disposeClose = undefined
|
||||
closeController = undefined
|
||||
}
|
||||
}) : undefined
|
||||
const unsubscribeList = ctx.sessions.list.subscribe(onListChange)
|
||||
evictGoneSessions()
|
||||
bindClose()
|
||||
return {
|
||||
openTab({ sessionId, kind, params, revealIfOpened, preferNewPane }) {
|
||||
enqueue({ kind: 'tab', sessionId, tabKind: kind, params, revealIfOpened, preferNewPane: preferNewPane === true })
|
||||
findTab,
|
||||
openTab({ sessionId, kind, params, revealIfOpened, preferNewPane, matchTab, reveal, reuseTab }) {
|
||||
enqueue({ kind: 'tab', sessionId, tabKind: kind, params, revealIfOpened, preferNewPane: preferNewPane === true, matchTab, reveal, reuseTab })
|
||||
},
|
||||
openResource({ sessionId, address, line, revealIfOpened, preferNewPane }) {
|
||||
enqueue({ kind: 'resource', sessionId, address, line, revealIfOpened, preferNewPane: preferNewPane === true })
|
||||
@@ -277,18 +347,22 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
close(sessionId, 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(sessionId, tabId)
|
||||
const api = controller()
|
||||
const nativeTab = api?.openTabs?.getSnapshot().find(tab => tab.sessionId === sessionId && tab.tabId === tabId)
|
||||
const record = records.get(sessionId, tabId)
|
||||
const tab = record?.tab ?? (nativeTab === undefined ? undefined : records.tabAt(sessionId, tabId, nativeTab.kind, nativeTab.contentId))
|
||||
if (tab === undefined) return undefined
|
||||
const contentId = nativeTab?.contentId ?? record?.contentId
|
||||
records.drop(sessionId, tabId)
|
||||
if (contentId !== undefined) records.sidechatBindings.delete(sessionId, contentId)
|
||||
if (api !== undefined) {
|
||||
if (sessionId === mountedSessionId(ctx)) api.close(tabId)
|
||||
else if (api.closeIn !== undefined) api.closeIn(sessionId, tabId)
|
||||
}
|
||||
return {
|
||||
type: record.tab.type,
|
||||
title: record.tab.title,
|
||||
...(record.tab.meta === undefined ? {} : { meta: record.tab.meta }),
|
||||
type: tab.type,
|
||||
title: tab.title,
|
||||
...(tab.meta === undefined ? {} : { meta: tab.meta }),
|
||||
}
|
||||
},
|
||||
update(tabId, patch, sessionId) {
|
||||
@@ -301,7 +375,8 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
// External plugin tabs (multi-instance kinds like side chats) carry no
|
||||
// (kind, address) identity to re-open against, so "open again to focus"
|
||||
// cannot work for them — focus through the controller's own face.
|
||||
if (sessionOf(tabId, sessionId) === undefined) return false
|
||||
const owner = sessionOf(tabId, sessionId)
|
||||
if (owner === undefined || owner !== mountedSessionId(ctx)) return false
|
||||
controller()?.focus?.(tabId)
|
||||
return true
|
||||
},
|
||||
@@ -309,6 +384,8 @@ export function createNativeSurface(ctx: Context, records: NativeTabRecords): Na
|
||||
pathTabs: () => records.pathTabs(),
|
||||
flushPending,
|
||||
dispose: () => {
|
||||
void closeSeat?.dispose()
|
||||
disposeClose?.()
|
||||
unsubscribeList()
|
||||
mountedUnsubscribe?.()
|
||||
},
|
||||
|
||||
@@ -39,6 +39,7 @@ import { t } from '../locales.ts'
|
||||
import { isUnread, toggleExpanded } from '../state.ts'
|
||||
import type { SidebarStore, SidebarTab, TabType } from '../state.ts'
|
||||
import css from '../sidebar.module.css'
|
||||
import { createSidechatBindings } from './sidechat-bindings.ts'
|
||||
|
||||
/** The chip glyph's size: the tab strip's own icon scale. */
|
||||
const CHIP_ICON_SIZE = 14
|
||||
@@ -94,6 +95,8 @@ interface View {
|
||||
* session id may itself contain the separator.
|
||||
*/
|
||||
seat: string
|
||||
/** Stable host page identity; unlike tab1 it survives reload without reuse. */
|
||||
contentId?: string
|
||||
scope: SessionScope
|
||||
/**
|
||||
* A PROJECTION of the session's expansion set (never an authoritative copy):
|
||||
@@ -124,6 +127,9 @@ function viewKey(sessionId: string, id: string): string {
|
||||
|
||||
/** The plugin-side record registry for native tabs. */
|
||||
export interface NativeTabRecords {
|
||||
readonly sidechatBindings: ReturnType<typeof createSidechatBindings>
|
||||
/** Read a live or durably bound occurrence, including an unmounted tab. */
|
||||
tabAt(sessionId: string, id: string, kind: string, contentId: string): SidebarTab | undefined
|
||||
/**
|
||||
* 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
|
||||
@@ -140,6 +146,7 @@ export interface NativeTabRecords {
|
||||
sessionId: string
|
||||
id: string
|
||||
kind: string
|
||||
contentId?: string
|
||||
title: string
|
||||
params: NativeTabParams | undefined
|
||||
scope: SessionScope
|
||||
@@ -213,6 +220,16 @@ function samePaths(left: readonly string[], right: readonly string[]): boolean {
|
||||
/** Create the record registry for one client activation. */
|
||||
export function createNativeTabRecords(): NativeTabRecords {
|
||||
const views = new Map<string, View>()
|
||||
const sidechatBindings = createSidechatBindings()
|
||||
const persist = (view: View): void => {
|
||||
if (view.tab.type !== 'sidechat' || view.contentId === undefined) return
|
||||
const meta = view.tab.meta as { threadId?: unknown } | undefined
|
||||
if (typeof meta?.threadId === 'string' && meta.threadId !== '') {
|
||||
sidechatBindings.set(view.seat, view.contentId, meta.threadId, view.tab.title)
|
||||
} else {
|
||||
sidechatBindings.delete(view.seat, view.contentId)
|
||||
}
|
||||
}
|
||||
const instances = new Map<string, number>()
|
||||
/**
|
||||
* Record key -> the navigation revision whose seed meta was last adopted.
|
||||
@@ -230,6 +247,7 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
const listeners = new Set<() => void>()
|
||||
const notify = (): void => { for (const listener of listeners) listener() }
|
||||
const put = (key: string, view: View): void => {
|
||||
persist(view)
|
||||
views.set(key, { ...view, version: view.version + 1 })
|
||||
notify()
|
||||
}
|
||||
@@ -259,6 +277,13 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
if (changed) notify()
|
||||
}
|
||||
return {
|
||||
sidechatBindings,
|
||||
tabAt(sessionId, id, kind, contentId) {
|
||||
const live = views.get(viewKey(sessionId, id))
|
||||
if (live !== undefined && (live.contentId === undefined || live.contentId === contentId)) return live.tab
|
||||
const binding = kind === 'sidechat' ? sidechatBindings.get(sessionId, contentId) : undefined
|
||||
return binding === undefined ? undefined : { id, type: kind, title: binding.title, meta: { threadId: binding.threadId } }
|
||||
},
|
||||
attachStore(next) {
|
||||
if (store === next) return
|
||||
store = next
|
||||
@@ -267,12 +292,22 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
next.subscribe(syncExpanded)
|
||||
syncExpanded()
|
||||
},
|
||||
ensure({ sessionId, id, kind, title, params, scope, revision, mint }) {
|
||||
ensure({ sessionId, id, kind, contentId, title, params, scope, revision, mint }) {
|
||||
const key = viewKey(sessionId, id)
|
||||
const existing = views.get(key)
|
||||
const held = views.get(key)
|
||||
const existing = held?.contentId === contentId ? held : undefined
|
||||
if (existing === undefined) {
|
||||
const seeded = params?.title === undefined && params?.meta === undefined ? mint?.() : undefined
|
||||
const meta = params?.meta ?? seeded?.meta
|
||||
// A new open gets a NEW contentId. The same occurrence may remount
|
||||
// with revision zero (reload) or its original autoCreate navigation
|
||||
// (client entry replacement); neither may replace its bound thread.
|
||||
const explicit = params?.meta as { threadId?: unknown } | undefined
|
||||
const binding = kind === 'sidechat' && contentId !== undefined && typeof explicit?.threadId !== 'string'
|
||||
? sidechatBindings.get(sessionId, contentId) : undefined
|
||||
const restoring = kind === 'sidechat' && contentId !== undefined && revision === 0 && params?.meta === undefined
|
||||
const seeded = binding !== undefined || restoring
|
||||
? { title: binding?.title, meta: binding === undefined ? {} : { threadId: binding.threadId } }
|
||||
: params?.title === undefined && params?.meta === undefined ? mint?.() : undefined
|
||||
const meta = binding !== undefined ? seeded?.meta : params?.meta ?? seeded?.meta
|
||||
// A url seed lands on `path`: the browser tab reads its address from
|
||||
// there and persists navigations back to the same field, so a record
|
||||
// that dropped it opened with an empty address bar.
|
||||
@@ -281,7 +316,7 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
tab: {
|
||||
id,
|
||||
type: kind as TabType,
|
||||
title: params?.title ?? seeded?.title ?? title,
|
||||
title: binding?.title ?? params?.title ?? seeded?.title ?? title,
|
||||
...(path === undefined ? {} : { path }),
|
||||
...(params?.line === undefined ? {} : { line: params.line }),
|
||||
...(params?.diff === undefined ? {} : { diff: params.diff }),
|
||||
@@ -289,10 +324,12 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
},
|
||||
scope,
|
||||
seat: sessionId,
|
||||
...(contentId === undefined ? {} : { contentId }),
|
||||
expanded: expandedOf(scope.sessionId),
|
||||
revealed: [],
|
||||
version: 0,
|
||||
}
|
||||
persist(minted)
|
||||
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
|
||||
@@ -345,6 +382,7 @@ export function createNativeTabRecords(): NativeTabRecords {
|
||||
}
|
||||
if (Object.keys(patch).length === 0) return existing
|
||||
const next: View = { ...existing, tab: { ...existing.tab, ...patch } }
|
||||
persist(next)
|
||||
views.set(key, next)
|
||||
return next
|
||||
},
|
||||
@@ -513,6 +551,7 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro
|
||||
sessionId: seatSessionId,
|
||||
id: nativeTab.id,
|
||||
kind: nativeTab.kind,
|
||||
contentId: nativeTab.contentId,
|
||||
title: nativeTab.title,
|
||||
params,
|
||||
scope,
|
||||
|
||||
+48
-3
@@ -229,6 +229,9 @@ export interface TabDescriptor {
|
||||
* are given. Builtins: explorer/git/subagent use `single: true`.
|
||||
*/
|
||||
single?: boolean
|
||||
/** Opt into independent native page occurrences (e.g. one side-chat tab per
|
||||
* thread). Native guide opens otherwise focus the same page in each pane. */
|
||||
multiple?: boolean
|
||||
/**
|
||||
* If provided, opening a tab whose `dedupeKey(tab)` matches an existing
|
||||
* tab's key focuses the existing one instead of creating a new one.
|
||||
@@ -723,7 +726,9 @@ export interface NativePathTab {
|
||||
*/
|
||||
export interface SidebarSurface {
|
||||
/** Open a page type in one session's native surface. */
|
||||
openTab(input: { sessionId: string; kind: string; params: NativeTabParams; revealIfOpened: boolean; preferNewPane?: boolean }): void
|
||||
openTab(input: { sessionId: string; kind: string; params: NativeTabParams; revealIfOpened: boolean; preferNewPane?: boolean; reveal?: boolean; reuseTab?: () => boolean; matchTab?: (tab: SidebarTab) => boolean }): void
|
||||
/** Find a bound occurrence across live and saved native layouts. */
|
||||
findTab?(sessionId: string, kind: string, match: (tab: SidebarTab) => boolean): string | undefined
|
||||
/** Open a resource address in one session's native surface. */
|
||||
openResource(input: { sessionId: string; address: string; line?: number; revealIfOpened: boolean; preferNewPane?: boolean }): void
|
||||
/** The file address of one path (the native surface owns the grammar). */
|
||||
@@ -886,6 +891,8 @@ export interface BetterSidebarService {
|
||||
* background conversation's pages. Without a scope nothing changes.
|
||||
*/
|
||||
closeTab(tabId: string, scope?: SessionScope): void
|
||||
/** Test membership before binding an asynchronous result to a tab. */
|
||||
hasTab?(tabId: string, sessionId: string): boolean
|
||||
/** Subscribe to registry changes (register/dispose). */
|
||||
subscribe(listener: () => void): () => void
|
||||
/** The plugin version this service instance was built from ('0.12.0'). */
|
||||
@@ -1343,6 +1350,36 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
const targetSessionId = scope?.sessionId ?? store.getSnapshot().sessionId
|
||||
if (targetSessionId === undefined) return
|
||||
const callbackScope: SessionScope = scope ?? { sessionId: targetSessionId }
|
||||
// Re-evaluate this at placement too: a queued native open may acquire a
|
||||
// bottom owner while its session is off screen.
|
||||
const reuseBottom = (match: (tab: SidebarTab) => boolean): boolean => {
|
||||
const state = store.getSessionState(targetSessionId)
|
||||
const bottom = state === undefined ? undefined : allLeaves(state.bottomSplits).flatMap(leaf => leaf.tabs).find(match)
|
||||
if (bottom === undefined) return false
|
||||
if (seed.reveal !== false) {
|
||||
reduceInSession(targetSessionId, state => ({
|
||||
...activateTabReducer(state, findPaneIdOf(state, bottom.id), bottom.id), bottomOpen: true,
|
||||
}))
|
||||
clearUnreadFor(bottom.type, targetSessionId)
|
||||
safeCall(() => descriptor.onActivate?.(bottom, callbackScope))
|
||||
}
|
||||
return true
|
||||
}
|
||||
// A thread is one conversation across BOTH carriers. Opening its history
|
||||
// entry must not duplicate it on the other surface (closing either copy
|
||||
// would otherwise archive the thread still displayed by the first).
|
||||
if (descriptor.multiple === true && descriptor.dedupeKey !== undefined && seed.meta !== undefined) {
|
||||
const candidate: SidebarTab = { id: seed.id ?? seed.type, type: seed.type, title: seed.title ?? '', meta: seed.meta }
|
||||
const key = descriptor.dedupeKey(candidate)
|
||||
if (key !== undefined) {
|
||||
const match = (tab: SidebarTab): boolean => tab.type === seed.type && descriptor.dedupeKey?.(tab) === key
|
||||
if (reuseBottom(match)) return
|
||||
if (surface?.findTab?.(targetSessionId, seed.type, match) !== undefined) {
|
||||
surface.openTab({ sessionId: targetSessionId, kind: seed.type, params: { meta: seed.meta }, revealIfOpened: true, reveal: seed.reveal !== false, matchTab: match, reuseTab: () => reuseBottom(match) })
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
// ── Native right Sidebar ──────────────────────────────────────────────
|
||||
// With the native surface installed, every open except an explicit
|
||||
// bottom-panel one — and except a `bottomOnly` type, which has no native
|
||||
@@ -1421,9 +1458,12 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
// A component type's path seed stays on the page open (regression
|
||||
// #632: rerouting every path seed into openResource sent the open to
|
||||
// the editor, so the registered component never mounted).
|
||||
const dedupeKey = descriptor.dedupeKey
|
||||
const key = descriptor.multiple === true ? dedupeKey?.(synthetic) : undefined
|
||||
surface.openTab({
|
||||
sessionId: targetSessionId,
|
||||
kind: seed.type,
|
||||
...(key === undefined ? {} : { matchTab: (tab: SidebarTab) => dedupeKey?.(tab) === key, reuseTab: () => reuseBottom(tab => tab.type === seed.type && dedupeKey?.(tab) === key), reveal: seed.reveal !== false }),
|
||||
params: {
|
||||
title,
|
||||
...(seed.path === undefined ? {} : { path: seed.path }),
|
||||
@@ -1460,8 +1500,8 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
if (descriptor.createTab !== undefined) {
|
||||
const result = descriptor.createTab(state)
|
||||
if (result === null) return state
|
||||
tab = result.tab
|
||||
next = applyDedupe(state, result.tab, descriptor, land)
|
||||
tab = { ...result.tab, ...(seed.meta === undefined ? {} : { meta: seed.meta }) }
|
||||
next = applyDedupe(state, tab, descriptor, land)
|
||||
if (result.patch !== undefined) next = { ...next, ...result.patch }
|
||||
} else {
|
||||
tab = {
|
||||
@@ -1710,6 +1750,11 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
matchFileViewer,
|
||||
openTab,
|
||||
closeTab,
|
||||
hasTab: (tabId, sessionId) => {
|
||||
if (surface?.has(tabId, sessionId) === true) return true
|
||||
const state = store.getSessionState(sessionId)
|
||||
return state !== undefined && tabOpenIn(state, tabId)
|
||||
},
|
||||
subscribe,
|
||||
version: SIDEBAR_SERVICE_VERSION,
|
||||
features: SIDEBAR_FEATURES,
|
||||
|
||||
@@ -175,6 +175,54 @@ test.afterAll(async () => {
|
||||
await api?.dispose()
|
||||
})
|
||||
|
||||
test('sidechat multi-instance: both plus buttons preserve independent tabs across reload', async ({ page }) => {
|
||||
// Real host layout/registration/React, deterministic sidechat transport: no
|
||||
// provider credentials, no model calls, no production sessions touched.
|
||||
let starts = 0
|
||||
const pulls: string[] = []
|
||||
await page.route('**/sidebar/api/sidechat.*', async route => {
|
||||
const method = route.request().url().split('/').pop()
|
||||
const body = route.request().postDataJSON() as { childId?: string }
|
||||
let value: unknown = { accepted: true }
|
||||
if (method === 'sidechat.start') value = { childId: `test-thread-${++starts}` }
|
||||
if (method === 'sidechat.info') value = { live: false, preset: 'test' }
|
||||
if (method === 'sidechat.models') value = { available: false, groups: [], failures: [] }
|
||||
if (method === 'sidechat.events') {
|
||||
pulls.push(body.childId ?? '')
|
||||
value = { events: [], live: [], pending: [] }
|
||||
}
|
||||
await route.fulfill({ json: { ok: true, value } })
|
||||
})
|
||||
await page.goto(PAGE_URL, { waitUntil: 'domcontentloaded' })
|
||||
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
|
||||
await dismissOnboarding(page)
|
||||
await sendFirstMessage(page)
|
||||
await page.locator('[data-sidebar-right-expand]').first().click()
|
||||
await page.locator('[data-sidebar-right-guide-entry="sidechat"]').click()
|
||||
await expect.poll(() => starts).toBe(1)
|
||||
await expect.poll(() => pulls.includes('test-thread-1')).toBe(true)
|
||||
const tabs = page.locator('[data-sidebar-right-panel] [role="tab"]')
|
||||
const initial = await tabs.count()
|
||||
await page.locator('[data-dockkit-add-tab]').first().click()
|
||||
await page.locator('[data-sidebar-right-guide-entry="sidechat"]').click()
|
||||
await expect.poll(() => starts).toBe(2)
|
||||
await expect(tabs).toHaveCount(initial + 1)
|
||||
await expect.poll(() => pulls.includes('test-thread-2')).toBe(true)
|
||||
await page.locator('[data-dsh-native-tab-host]:visible button[aria-label="新建对话"], [data-dsh-native-tab-host]:visible button[aria-label="New thread"]').click()
|
||||
await expect.poll(() => starts).toBe(3)
|
||||
await expect(tabs).toHaveCount(initial + 2)
|
||||
await expect.poll(() => pulls.includes('test-thread-3')).toBe(true)
|
||||
const saved = await page.evaluate(() => JSON.parse(localStorage.getItem('dsh-sidebar:v1:native-sidechat-bindings') ?? '[]') as Array<{ threadId: string }>)
|
||||
expect(saved.map(row => row.threadId).sort()).toEqual(['test-thread-1', 'test-thread-2', 'test-thread-3'])
|
||||
pulls.length = 0
|
||||
await page.reload({ waitUntil: 'domcontentloaded' })
|
||||
await expect(page.locator('[data-dsh-better-sidebar]')).toBeAttached({ timeout: 90_000 })
|
||||
await expect(tabs).toHaveCount(initial + 2, { timeout: 30_000 })
|
||||
for (let index = 0; index < await tabs.count(); index++) await tabs.nth(index).click()
|
||||
await expect.poll(() => new Set(pulls).size).toBe(3)
|
||||
expect(starts, 'reload must not create replacement threads').toBe(3)
|
||||
})
|
||||
|
||||
test('plugin mounts into the DSH shell and survives a built-in tab sweep', async ({ page }) => {
|
||||
const pageErrors: string[] = []
|
||||
const consoleErrors: string[] = []
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createElement } from 'react'
|
||||
import { installSidechatHarness, type SidechatHarness } from './helpers/sidechat-view-harness.tsx'
|
||||
import { SideChatView } from '../src/client/SideChatView.tsx'
|
||||
import { clearSavedSidechatDrafts } from '../src/client/sidechat-draft.ts'
|
||||
import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
import type { RenderedRoot } from './test-utils.ts'
|
||||
|
||||
@@ -149,13 +150,17 @@ describe('sidechat image composer', () => {
|
||||
expect(calls).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('reattaches a restored native tab to the remembered thread without sending again', async () => {
|
||||
it('restores the native occurrence’s exact thread without sending again', async () => {
|
||||
await harness.flush()
|
||||
const snapshot = { byId: { root: { id: 'root', displayTitle: 'root', running: false }, t1: { id: 't1', displayTitle: 'Side: thread', origin: 'subagent', parentId: 'root', running: false } } }
|
||||
const ctx = { get: (key: string) => key === 'betterSidebar' ? harness.host : undefined, sessions: { list: { subscribe: () => () => {}, getSnapshot: () => snapshot } } } as unknown as Context
|
||||
mounted.rerender(createElement(SideChatView, { ctx, scope: { sessionId: 'root', cwd: '/p' }, tab: { id: 'restored', type: 'sidechat', title: 'Side Chat' }, visible: true }))
|
||||
const records = createNativeTabRecords()
|
||||
records.sidechatBindings.set('root', 'sidebar://sidechat/image-thread', 't1', 'Side Chat')
|
||||
const restored = createNativeTabRecords().ensure({ sessionId: 'root', id: 'restored', kind: 'sidechat', contentId: 'sidebar://sidechat/image-thread', title: 'Side Chat', params: undefined, revision: 0, scope: { sessionId: 'root', cwd: '/p' } })
|
||||
mounted.rerender(createElement(SideChatView, { ctx, scope: restored.scope, tab: restored.tab, visible: true }))
|
||||
await harness.flush()
|
||||
expect(harness.host.updateTab).toHaveBeenCalledWith('restored', { meta: { threadId: 't1' } }, 'root')
|
||||
expect(restored.tab.meta).toEqual({ threadId: 't1' })
|
||||
expect(mounted.container.querySelector('textarea')).not.toBeNull()
|
||||
expect(calls).toEqual([])
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
// @vitest-environment jsdom
|
||||
/** Regression: host pages are singleton unless multiple:true. Navigation params
|
||||
* are NOT persisted by DSH; stable contentId is. Model both contracts rather
|
||||
* than trusting the plugin's factory UUID or revealIfOpened:false. */
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSidebarStore } from '../src/client/state.ts'
|
||||
import { createBetterSidebarService } from '../src/client/service.ts'
|
||||
import { builtinTabs } from '../src/client/builtins/tabs.tsx'
|
||||
import { registerNativeSurface } from '../src/client/native/index.ts'
|
||||
import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx'
|
||||
import { createNativeSurface } from '../src/client/native/surface.ts'
|
||||
import { SIDECHAT_BINDINGS_KEY } from '../src/client/native/sidechat-bindings.ts'
|
||||
|
||||
type OpenTab = { sessionId: string; tabId: string; kind: string; contentId: string }
|
||||
function harness() {
|
||||
const store = createSidebarStore()
|
||||
store.setSession('s1')
|
||||
const service = createBetterSidebarService(store)
|
||||
const records = createNativeTabRecords()
|
||||
let mounted = 's1'
|
||||
let rows: OpenTab[] = []
|
||||
const mountedListeners = new Set<() => void>()
|
||||
const definitions = new Map<string, { kind: string; multiple?: boolean }>()
|
||||
let closed: ((sessionId: string, tab: { id: string; kind: string; contentId: string }) => void) | undefined
|
||||
const onClose = vi.fn()
|
||||
const controller = {
|
||||
openTabs: { getSnapshot: () => rows, subscribe: () => () => {} },
|
||||
mounted: { getSnapshot: () => mounted, subscribe: (fn: () => void) => { mountedListeners.add(fn); return () => { mountedListeners.delete(fn) } } },
|
||||
focus: vi.fn(),
|
||||
openTab: vi.fn((kind: string) => {
|
||||
// Mirrors DSH's page identity, including its singleton dedupe.
|
||||
const contentId = definitions.get(kind)?.multiple ? `sidebar://${kind}/${crypto.randomUUID()}` : `sidebar://${kind}`
|
||||
const held = rows.find(row => row.sessionId === mounted && row.contentId === contentId)
|
||||
if (held) { controller.focus(held.tabId); return }
|
||||
rows = [...rows, { sessionId: mounted, tabId: `tab${rows.length + 1}`, kind, contentId }]
|
||||
}),
|
||||
registerCloseHandler: (_kind: string, callback: typeof closed) => { closed = callback; return () => { closed = undefined } },
|
||||
close: (tabId: string) => {
|
||||
const row = rows.find(tab => tab.sessionId === mounted && tab.tabId === tabId)!
|
||||
closed?.(mounted, { id: row.tabId, kind: row.kind, contentId: row.contentId })
|
||||
rows = rows.filter(tab => tab !== row)
|
||||
},
|
||||
}
|
||||
const registry = { register: (definition: { kind: string; multiple?: boolean }) => { definitions.set(definition.kind, definition); return () => { definitions.delete(definition.kind) } } }
|
||||
const ctx = {
|
||||
get: (key: string) => key === 'sidebarRight' ? controller : key === 'sidebarRightTabs' ? registry : undefined,
|
||||
sessions: { list: { getSnapshot: () => ({ byId: { s1: {}, s2: {} } }), subscribe: () => () => {} } },
|
||||
inject: (_deps: readonly string[], callback: (ctx: unknown) => (() => void) | undefined) => {
|
||||
const cleanup = callback(ctx)
|
||||
return { dispose: () => cleanup?.() }
|
||||
},
|
||||
slots: { inject: (_key: string, callback: () => () => void) => callback(), register: () => () => {} },
|
||||
}
|
||||
service.registerTab({ ...builtinTabs(ctx as never).find(tab => tab.id === 'sidechat')!, onClose })
|
||||
const disposeRegistration = registerNativeSurface({ ctx: ctx as never, store, service, records })
|
||||
const surface = createNativeSurface(ctx as never, records, onClose)
|
||||
service.setSurface(surface)
|
||||
const mount = (row: OpenTab, threadId: string) => records.ensure({
|
||||
sessionId: row.sessionId, id: row.tabId, kind: row.kind, contentId: row.contentId,
|
||||
title: threadId, params: { meta: { threadId } }, revision: 1, scope: { sessionId: row.sessionId },
|
||||
})
|
||||
return { ctx, store, service, records, controller, surface, onClose, mount, rows: () => rows,
|
||||
switchSession: (sid: string) => { mounted = sid; mountedListeners.forEach(fn => fn()) },
|
||||
dispose: () => { surface.dispose(); disposeRegistration() },
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => localStorage.clear())
|
||||
|
||||
describe('independent native side chats', () => {
|
||||
it('two guide opens get two host occurrences, not one singleton page', () => {
|
||||
const h = harness()
|
||||
h.controller.openTab('sidechat')
|
||||
h.controller.openTab('sidechat')
|
||||
expect(h.rows()).toHaveLength(2)
|
||||
expect(h.rows()[0]!.contentId).not.toBe(h.rows()[1]!.contentId)
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('new service opens stay separate, while an existing thread focuses even before body mount', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } })
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'b' } })
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } })
|
||||
expect(h.rows()).toHaveLength(2)
|
||||
expect(h.controller.focus).toHaveBeenLastCalledWith(h.rows()[0]!.tabId)
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('a background reveal:false request dedupes without stealing focus', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } })
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' }, reveal: false })
|
||||
expect(h.rows()).toHaveLength(1)
|
||||
expect(h.controller.focus).not.toHaveBeenCalled()
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('plain service opens are always fresh, not deduped to the last thread', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat' })
|
||||
h.service.openTab({ type: 'sidechat' })
|
||||
expect(h.rows()).toHaveLength(2)
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('restores each occurrence from its own binding after registry reload', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } })
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'b' } })
|
||||
const reloaded = createNativeTabRecords()
|
||||
const restored = h.rows().map(row => reloaded.ensure({ sessionId: 's1', id: row.tabId, kind: 'sidechat',
|
||||
contentId: row.contentId, title: '', params: undefined, revision: 0, scope: { sessionId: 's1' },
|
||||
mint: () => { throw new Error('restore must not mint') },
|
||||
}).tab.meta)
|
||||
expect(restored).toEqual([{ threadId: 'a' }, { threadId: 'b' }])
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('a new occurrence ignores old bindings, while remount preserves the exact binding', () => {
|
||||
const records = createNativeTabRecords()
|
||||
records.sidechatBindings.set('s1', 'sidebar://sidechat/old', 'a', 'A')
|
||||
const base = { sessionId: 's1', id: 'tab1', kind: 'sidechat', title: '', params: undefined, scope: { sessionId: 's1' } }
|
||||
const mint = vi.fn(() => ({ meta: { autoCreate: true } }))
|
||||
expect(records.ensure({ ...base, contentId: 'sidebar://sidechat/new', revision: 1, mint }).tab.meta).toEqual({ autoCreate: true })
|
||||
expect(records.ensure({ ...base, contentId: 'sidebar://sidechat/old', revision: 1, params: { meta: { autoCreate: true } }, mint }).tab.meta).toEqual({ threadId: 'a' })
|
||||
expect(records.ensure({ ...base, contentId: 'sidebar://sidechat/reset', revision: 0, mint }).tab.meta).toEqual({})
|
||||
expect(mint).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('separates identical tab ids and content ids belonging to different sessions', () => {
|
||||
const records = createNativeTabRecords()
|
||||
for (const sessionId of ['s1', 's2']) {
|
||||
records.ensure({ sessionId, id: 'tab1', contentId: 'sidebar://sidechat/shared', kind: 'sidechat', title: sessionId,
|
||||
scope: { sessionId }, revision: 1, params: { meta: { threadId: sessionId } } })
|
||||
}
|
||||
const restored = createNativeTabRecords()
|
||||
expect(restored.sidechatBindings.get('s1', 'sidebar://sidechat/shared')?.threadId).toBe('s1')
|
||||
expect(restored.sidechatBindings.get('s2', 'sidebar://sidechat/shared')?.threadId).toBe('s2')
|
||||
})
|
||||
|
||||
it('host close releases just that thread, while teardown keeps durable bindings', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } })
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'b' } })
|
||||
const [a, b] = h.rows()
|
||||
h.mount(a!, 'a')
|
||||
h.mount(b!, 'b')
|
||||
h.controller.close(a!.tabId)
|
||||
expect(h.onClose).toHaveBeenCalledTimes(1)
|
||||
expect(h.onClose.mock.calls[0]?.[0].meta).toEqual({ threadId: 'a' })
|
||||
expect(h.records.sidechatBindings.get('s1', a!.contentId)).toBeUndefined()
|
||||
expect(h.records.get('s1', b!.tabId)?.tab.meta).toEqual({ threadId: 'b' })
|
||||
h.dispose()
|
||||
expect(h.onClose).toHaveBeenCalledTimes(1)
|
||||
expect(createNativeTabRecords().sidechatBindings.get('s1', b!.contentId)?.threadId).toBe('b')
|
||||
})
|
||||
|
||||
it('background dedupe waits for the correct session rather than focusing another seat', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } })
|
||||
h.switchSession('s2')
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } }, { sessionId: 's1' })
|
||||
expect(h.controller.focus).not.toHaveBeenCalled()
|
||||
h.switchSession('s1')
|
||||
h.surface.flushPending()
|
||||
expect(h.rows()).toHaveLength(1)
|
||||
expect(h.controller.focus).toHaveBeenCalledWith(h.rows()[0]!.tabId)
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('history opens dedupe across bottom and native carriers, in either direction', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat', target: 'bottom', meta: { threadId: 'bottom-a' } })
|
||||
h.store.reduce(state => ({ ...state, bottomOpen: false }))
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'bottom-a' } })
|
||||
expect(h.rows()).toHaveLength(0)
|
||||
expect(h.store.getSnapshot().state?.bottomOpen).toBe(true)
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'native-b' } })
|
||||
h.service.openTab({ type: 'sidechat', target: 'bottom', meta: { threadId: 'native-b' } })
|
||||
expect(h.rows()).toHaveLength(1)
|
||||
expect(h.controller.focus).toHaveBeenCalledWith(h.rows()[0]!.tabId)
|
||||
expect(h.onClose).not.toHaveBeenCalled()
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('rechecks bottom ownership when a queued native open is replayed', () => {
|
||||
const h = harness()
|
||||
h.switchSession('s2')
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } }, { sessionId: 's1' })
|
||||
h.service.openTab({ type: 'sidechat', target: 'bottom', meta: { threadId: 'a' } }, { sessionId: 's1' })
|
||||
h.switchSession('s1')
|
||||
h.surface.flushPending()
|
||||
expect(h.rows()).toHaveLength(0)
|
||||
expect(h.onClose).not.toHaveBeenCalled()
|
||||
h.dispose()
|
||||
})
|
||||
|
||||
it('programmatic close handles a restored occurrence before its body is visited', () => {
|
||||
const h = harness()
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'a' } })
|
||||
h.service.openTab({ type: 'sidechat', meta: { threadId: 'b' } })
|
||||
const [a, b] = h.rows()
|
||||
h.surface.dispose()
|
||||
const restored = createNativeTabRecords()
|
||||
const surface = createNativeSurface(h.ctx as never, restored, h.onClose)
|
||||
h.service.setSurface(surface)
|
||||
h.service.closeTab(a!.tabId, { sessionId: 's1' })
|
||||
expect(h.rows()).toEqual([b])
|
||||
expect(h.onClose).toHaveBeenCalledTimes(1)
|
||||
expect(h.onClose.mock.calls[0]?.[0].meta).toEqual({ threadId: 'a' })
|
||||
surface.dispose(); h.dispose()
|
||||
})
|
||||
|
||||
it('binds close cleanup when the host service arrives without a session-list pulse', () => {
|
||||
let available: unknown = undefined
|
||||
let arrive: (() => void) | undefined
|
||||
let cleanup: (() => void) | undefined
|
||||
const unregister = vi.fn()
|
||||
const controller = { registerCloseHandler: vi.fn(() => unregister) }
|
||||
const ctx = {
|
||||
get: () => available,
|
||||
inject: (_deps: readonly string[], callback: () => (() => void)) => {
|
||||
arrive = () => { cleanup = callback() }
|
||||
return { dispose: () => cleanup?.() }
|
||||
},
|
||||
sessions: { list: { getSnapshot: () => ({ byId: {} }), subscribe: () => () => {} } },
|
||||
}
|
||||
const surface = createNativeSurface(ctx as never, createNativeTabRecords())
|
||||
expect(controller.registerCloseHandler).not.toHaveBeenCalled()
|
||||
available = controller
|
||||
arrive!()
|
||||
expect(controller.registerCloseHandler).toHaveBeenCalledWith('sidechat', expect.any(Function))
|
||||
surface.dispose()
|
||||
expect(unregister).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('corrupt storage cannot bind a thread or prevent an explicit new tab', () => {
|
||||
localStorage.setItem(SIDECHAT_BINDINGS_KEY, '{broken')
|
||||
const records = createNativeTabRecords()
|
||||
expect(records.sidechatBindings.get('s1', 'sidebar://sidechat/a')).toBeUndefined()
|
||||
records.sidechatBindings.set('s1', 'sidebar://sidechat/a', 'a', 'A')
|
||||
expect(createNativeTabRecords().sidechatBindings.get('s1', 'sidebar://sidechat/a')?.threadId).toBe('a')
|
||||
})
|
||||
})
|
||||
@@ -20,6 +20,7 @@ import { act } from 'react-dom/test-utils'
|
||||
import { renderRoot, setupReactAct } from './test-utils.ts'
|
||||
import { SideChatView } from '../src/client/SideChatView.tsx'
|
||||
import { bindSidechatSurfaces, disposeSidechatSurfaces, type SidechatSurface } from '../src/client/sidechat-surface.ts'
|
||||
import { api } from '../src/client/api.ts'
|
||||
import { attachLocale } from '../src/client/locales.ts'
|
||||
import type { Context, SidebarSessionList } from '../src/context-types.ts'
|
||||
import type { SidebarTab } from '../src/client/state.ts'
|
||||
@@ -516,7 +517,7 @@ describe('SideChatView archive', () => {
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('archives a recoverable bound session with stopActivity and rebinds to the newest remaining thread', async () => {
|
||||
it('archives a recoverable binding without stealing another tab’s remaining thread', async () => {
|
||||
const host = makeArchiveHost()
|
||||
const store = makeStore({
|
||||
byId: {
|
||||
@@ -546,9 +547,9 @@ describe('SideChatView archive', () => {
|
||||
// The host's own archive capability, once, with a running agent settled.
|
||||
expect(host.archiveSession).toHaveBeenCalledTimes(1)
|
||||
expect(host.archiveSession).toHaveBeenCalledWith('t1', { stopActivity: true })
|
||||
// The tab moves to the newest remaining thread.
|
||||
// t2 may already be open in its own tab; archiving t1 must not bind it here.
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledTimes(1)
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: { threadId: 't2' } })
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: {}, title: '新对话' }, 'root')
|
||||
unmount()
|
||||
})
|
||||
|
||||
@@ -579,11 +580,66 @@ describe('SideChatView archive', () => {
|
||||
// `{}` rather than a dangling threadId: the panel unbinds instead of
|
||||
// staying bound to the session the host just archived.
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledTimes(1)
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: {} })
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: {}, title: '新对话' }, 'root')
|
||||
unmount()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SideChatView independent creation', () => {
|
||||
it('autoCreate starts a new thread even when the session already has one', async () => {
|
||||
const host = makeArchiveHost()
|
||||
const props = viewProps(makeArchiveCtx(threadStore(), host))
|
||||
props.tab = { ...props.tab, meta: { autoCreate: true } }
|
||||
const { unmount } = renderRoot(createElement(SideChatView, props))
|
||||
await act(async () => {})
|
||||
expect(startCalls).toBe(1)
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: { threadId: 'session-new' } }, 'root')
|
||||
expect(host.betterSidebar.updateTab).not.toHaveBeenCalledWith('tab1', { meta: { threadId: 't1' } }, 'root')
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('the input-bar plus opens a new bound tab instead of rebinding its current tab', async () => {
|
||||
const host = makeArchiveHost()
|
||||
const { container, unmount } = renderRoot(createElement(SideChatView, viewProps(makeArchiveCtx(threadStore(), host))))
|
||||
await act(async () => {})
|
||||
const plus = container.querySelector<HTMLButtonElement>('button[aria-label="新建对话"]')!
|
||||
await act(async () => { plus.click() })
|
||||
expect(startCalls).toBe(1)
|
||||
expect(host.betterSidebar.openTab).toHaveBeenCalledWith({ type: 'sidechat', meta: { threadId: 'session-new' } }, expect.objectContaining({ sessionId: 'root' }))
|
||||
expect(host.betterSidebar.updateTab).not.toHaveBeenCalled()
|
||||
unmount()
|
||||
})
|
||||
|
||||
it('two sessions with the same native tab1 can both create while requests are pending', async () => {
|
||||
const resolve: Array<(value: { childId: string }) => void> = []
|
||||
const start = vi.spyOn(api, 'sidechatStart').mockImplementation(() => new Promise(done => { resolve.push(done) }))
|
||||
const host = makeArchiveHost()
|
||||
const props = viewProps(makeArchiveCtx(threadStore(), host))
|
||||
props.tab = { ...props.tab, meta: { autoCreate: true } }
|
||||
const a = renderRoot(createElement(SideChatView, props))
|
||||
const b = renderRoot(createElement(SideChatView, { ...props, scope: { sessionId: 'other' } }))
|
||||
expect(start).toHaveBeenCalledTimes(2)
|
||||
await act(async () => { resolve[0]!({ childId: 'a' }); resolve[1]!({ childId: 'b' }) })
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: { threadId: 'a' } }, 'root')
|
||||
expect(host.betterSidebar.updateTab).toHaveBeenCalledWith('tab1', { meta: { threadId: 'b' } }, 'other')
|
||||
a.unmount(); b.unmount(); start.mockRestore()
|
||||
})
|
||||
|
||||
it('closing a starting tab releases the newly created orphan instead of rebinding', async () => {
|
||||
const host = makeArchiveHost()
|
||||
Object.assign(host.betterSidebar, { hasTab: () => false })
|
||||
const dispose = vi.spyOn(api, 'sidechatDispose').mockResolvedValue({ accepted: true })
|
||||
const props = viewProps(makeArchiveCtx(threadStore(), host))
|
||||
props.tab = { ...props.tab, meta: { autoCreate: true } }
|
||||
const { unmount } = renderRoot(createElement(SideChatView, props))
|
||||
await act(async () => {})
|
||||
expect(host.betterSidebar.updateTab).not.toHaveBeenCalled()
|
||||
expect(host.archiveSession).toHaveBeenCalledWith('session-new', { stopActivity: true })
|
||||
expect(dispose).toHaveBeenCalledWith('session-new')
|
||||
unmount(); dispose.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('SideChatView queue, echo and model picker', () => {
|
||||
/** The catalogue the picker cases serve (the host's own shape). */
|
||||
const CATALOG = {
|
||||
|
||||
Reference in new issue
Block a user