diff --git a/README.md b/README.md index b4321c87b..9a0cc7cac 100644 --- a/README.md +++ b/README.md @@ -244,7 +244,7 @@ Windows / Linux / macOS supported (macOS verified daily, the rest covered by uni QQ group: 577011007
- WeChat group QR + WeChat group QR QQ group QR
diff --git a/README_ZH.md b/README_ZH.md index 8dfa06579..43d819982 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -244,7 +244,7 @@ Windows / Linux / macOS 三平台适配(macOS 日常验证,其余经单元 推荐添加 QQ 群(577011007)
- 微信群二维码 + 微信群二维码 QQ群二维码
diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index dbdbf2d84..5b03e5754 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -995,6 +995,40 @@ ctx.effect(() => --- +### 7.1 侧边对话渲染适配器(新增提案,尚未发布) + +这是配合 [dsh-genui #354](https://github.com/omdsh-dev/dsh-genui/issues/354) 的**新增、窄范围接入提案**,不是 v0.28.0 或既有发布版本承诺过的契约。消费方必须先探测方法存在;未安装、旧版本或未注册适配器时,侧边对话继续使用原有 `MarkdownText` 和 `markdownTextProps()`,不改变普通 Markdown 与代码围栏。 + +```ts +interface SidechatSurface { + readonly root: HTMLElement + readonly source: 'dsh-better-sidebar/sidechat' + readonly threadId: string + readonly eventSeq: number + readonly contentBlockIndex: number + readonly text: string + readonly sendPrompt: (text: string) => Promise +} +interface SidechatSurfaceAdapter { + readonly id: string + readonly mount: (surface: SidechatSurface) => (() => void) +} +// BetterSidebarService 的新增消费入口: +registerSidechatSurfaceAdapter(adapter: SidechatSurfaceAdapter): () => void +``` + +两个类型可从 `dsh-better-sidebar` 或 `dsh-better-sidebar/client/service` 做 type-only 导入。注册必须包在消费插件的 `ctx.effect()` 中;同一个 id 重复注册会抛错,返回的 disposer 可重复调用。 + +- 只提供当前可见、已结算、身份有效的 assistant 文本块。用户消息、推理、工具、流式增量、隐藏页签及身份缺失的行不接入。`eventSeq` 与 `contentBlockIndex` 必须是非负安全整数;块序号保留原始 `message.content` 数组位置,包括非文本和空块留下的空位,不按过滤后的行号重新编号。 +- `root` 是该行真实的 Markdown 容器;`text` 是链接改写前的原始文本。侧边对话容器始终带 `data-genui-surface="dsh-better-sidebar/sidechat"`,包括流式与没有消费插件时,供主对话扫描器明确排除;**不伪造宿主的 `data-chat-*` 标记**。 +- 消费插件自行决定是否增强 `dsh-ui` 围栏,复用它自己的解析器、渲染器和状态,不把渲染实现放到 BetterSidebar,也不扫描该 root 之外的内容。挂载返回的 cleanup 必须释放监听器、观察者、计时器和渲染实例,并还原原始 Markdown;挂载中途失败须先回滚自身改动再抛错。单个适配器的挂载或释放异常会记录,但不会中断其余适配器和侧边对话。 +- 晚注册会接到当时仍可见的行。隐藏、行变更、线程切换或卸载会释放;再次可见时重新挂载。适配器卸载会释放它自己的所有行;BetterSidebar 卸载会释放所有行和注册。内部只保留当前活跃的 root,不积累隐藏页签的引用,也不新增轮询。 +- `sendPrompt(text)` 只调用当前行捕获的子线程 `sidechat.prompt` 路由。它不读取主会话、`scope.sessionId` 或任何兜底目标。行、适配器、线程绑定或插件失效之后,旧回调拒绝执行;请求失败同时通过现有侧边对话错误区显示并 reject 给消费方。调用方应处理 rejection,销毁时取消延迟动作。 + +该提案仍需以真实 DSH `0.2.1-rc.2` profile 同时安装两个候选插件验收,不能把单元测试或模拟 DOM 结果写成已完成双插件验收。 + +--- + ## 8. 声明式设置(v0.4.1+) 每个注册的 tab / viewer **自动**出现在 DSH 设置页「侧边卡片」分区(`SideCardSection` 按注册表驱动渲染,无硬编码): diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index feb219ded..15e274974 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -31,7 +31,7 @@ * session, archive) lives in the COMPOSER BAR, not a top header — the reader's * attention is on the input, and a header's actions went unnoticed. */ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useSyncExternalStore } from 'react' import clsx from 'clsx' import { @@ -64,6 +64,7 @@ import { type TerminalBlockLabels, } from '@deepseek-ai/dsh-client-ui-primitives' import { markdownTextProps } from './markdown-labels.tsx' +import { SidechatAssistantRow, type SidechatRowSurfaceBinding } from './SidechatAssistantRow.tsx' import { rewriteProseLocalImageUrls } from './markdown-images.ts' import { hostTransportBase } from './desktop-env.ts' import { baseName, resolveSidebarPath } from './paths.ts' @@ -89,6 +90,7 @@ import { formatTokens, toolArgsSummary, transcriptRows, + sidechatRowKey, type SidechatToolCard, type SidechatTranscriptRow, } from './sidechat-transcript.ts' @@ -232,6 +234,8 @@ function rememberSidechatThread(sessionId: string, threadId: string): void { /** 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 { + /** Rows must never be rebound to a different child while a reset is pending. */ + threadId?: string entries: SidebarHistoryEntry[] /** The CURRENT attempt's live deltas (replaced every pull, never merged). */ live: SidechatLiveEvent[] @@ -496,29 +500,27 @@ interface RowSurface { /** One row renderer (React keys ride the source event seq). `surface` is the * markdown prose pass the rows run before rendering — the rows are model * prose, so a relative destination resolves against the session cwd (see - * use-markdown-surface) — plus the delivered-file open and media helpers. */ -function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSurface): React.ReactNode { + * use-markdown-surface) — plus the delivered-file open and media helpers. + * `genui` binds the rows to the owning child thread: the key remounts every + * row when the tab switches threads, and a registered GenUI consumer may + * claim a visible, settled assistant row (see SidechatAssistantRow). */ +function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSurface, genui: SidechatRowSurfaceBinding): React.ReactNode { + const key = `${genui.threadId ?? 'unbound'}:${sidechatRowKey(row)}` switch (row.kind) { case 'user': return ( -
+
) case 'assistant': return ( -
- {/* `streaming` keeps the host's incremental parse across chunks - instead of restarting it; only the durable (settled) message is - the final parse. It rides the row's own flag so a superseded - live row never claims to be settled. */} - -
+ ) case 'reasoning': return ( @@ -527,7 +529,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu ) case 'injection': return ( - +
{row.text}
) @@ -535,7 +537,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu // A provider/agent failure: rendered plainly (never markdown) so a raw // provider message with odd punctuation survives verbatim. return ( -
+
{t('sideChatRunError', { message: row.text })}
) @@ -549,7 +551,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu if (row.durationMs !== undefined) parts.push(formatDurationMs(row.durationMs)) if (parts.length === 0) return null return ( -
+
{parts.join(' · ')}
) @@ -607,7 +609,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu ) return ( => { + const cache = cacheRef.current + if (cache.threadId !== childId) return controllerRef.current?.abort() const controller = new AbortController() controllerRef.current = controller try { - const cache = cacheRef.current const afterSeq = cache.entries.at(-1)?.event.seq const { events, live, pending } = await api.sidechatEvents(childId, afterSeq, controller.signal) + if (controller.signal.aborted || cacheRef.current !== cache) return // The live set is the CURRENT attempt, so it replaces whatever the // previous pull held; a settled step drops out of the host buffer and // its durable assistant/message takes over in the mapping. The pending @@ -937,7 +941,7 @@ export function SideChatView(props: { // Reset the transcript cache whenever the binding changes, then focus // the composer — it owns the first message of a fresh thread. useEffect(() => { - cacheRef.current = { entries: [], live: [], pending: [] } + cacheRef.current = { threadId, entries: [], live: [], pending: [] } prevRowsRef.current = [] controllerRef.current?.abort() if (invalidateRef.current !== undefined) { @@ -1040,7 +1044,8 @@ export function SideChatView(props: { const live = cache.live .filter(event => !settled.has(`${String(event.data.turn)}:${String(event.data.step)}`)) .map(event => ({ event: event as SidebarSessionEvent })) - const next = threadId === undefined ? [] : transcriptRows([...cache.entries, ...live], prevRowsRef.current) + const next = threadId === undefined || cache.threadId !== threadId + ? [] : transcriptRows([...cache.entries, ...live], prevRowsRef.current) prevRowsRef.current = next return next }, @@ -1236,6 +1241,34 @@ export function SideChatView(props: { field.style.height = `${Math.min(field.scrollHeight, COMPOSER_MAX_HEIGHT)}px` } + // Capture a binding generation, not a mutable "current session" fallback. + // A deferred slider action from an old row must fail even after A → B → A. + const surfaceBinding = useMemo(() => ({ childId: threadId, active: visible }), [threadId, visible]) + useLayoutEffect(() => { + surfaceBinding.active = visible + return () => { surfaceBinding.active = false } + }, [surfaceBinding, visible]) + const sendSurfacePrompt = useCallback(async (text: string): Promise => { + try { + const childId = surfaceBinding.childId + if (!surfaceBinding.active || childId === undefined || childId.trim() === '' || text.trim() === '') { + throw new Error('Sidechat surface is no longer active or the prompt is empty') + } + setError(null) + await api.sidechatPrompt(childId, text) + if (surfaceBinding.active) { + void fetchThread(childId) + void fetchInfo(childId) + } + } catch (cause) { + if (surfaceBinding.active) setError(cause instanceof Error ? cause.message : String(cause)) + throw cause + } + }, [surfaceBinding, fetchThread, fetchInfo]) + const genuiRowSurface: SidechatRowSurfaceBinding = { + service: ctx.get('betterSidebar'), threadId, visible, sendPrompt: sendSurfacePrompt, + } + const handleSend = async (): Promise => { const text = composer.trim() if (text === '' || threadId === undefined || busy !== null) return @@ -1387,12 +1420,12 @@ export function SideChatView(props: { onReconnect={() => { ctx.connection?.reconnect() }} /> )} -
+
{/* The host delegate is what makes a local markdown link in a row clickable at all (see use-markdown-surface), scoped to this transcript so nothing outside it is claimed. */} - {rows.map(row => renderRow(row, rowLabels, rowSurface))} + {rows.map(row => renderRow(row, rowLabels, rowSurface, genuiRowSurface))} {/* The unclaimed inbox: accepted messages whose claim has not logged them yet. The same bubble surface (and markdown pass) as a durable user row, plus the state word and the dequeue button. */} diff --git a/src/client/SidechatAssistantRow.tsx b/src/client/SidechatAssistantRow.tsx new file mode 100644 index 000000000..a1ecdd109 --- /dev/null +++ b/src/client/SidechatAssistantRow.tsx @@ -0,0 +1,53 @@ +/** Keep the host Markdown renderer as the default; a registered consumer may + * enhance only this real row root while it is visible and durably identified. */ +import { useLayoutEffect, useRef } from 'react' +import { MarkdownText } from '@deepseek-ai/dsh-client-ui-primitives' +import { markdownTextProps, type MarkdownCopyLabels } from './markdown-labels.tsx' +import { attachSidechatSurface, isSidechatSurfaceIdentity } from './sidechat-surface.ts' +import type { SidechatTranscriptRow } from './sidechat-transcript.ts' +import css from './SideChatView.module.css' + +export interface SidechatRowSurfaceBinding { + service: object | undefined + threadId: string | undefined + visible: boolean + sendPrompt: (text: string) => Promise +} + +export function SidechatAssistantRow(props: { + row: Extract + labels: MarkdownCopyLabels + /** The view's row-level prose pass (image destinations first, then local + * links) — takes the ROW so an unchanged row reuses its cached rewrite. */ + rewrite: (row: Extract) => string + surface: SidechatRowSurfaceBinding +}): React.ReactNode { + const rootRef = useRef(null) + const { row, labels, rewrite, surface } = props + const { service, threadId, visible, sendPrompt } = surface + const renderedText = rewrite(row) + useLayoutEffect(() => { + const root = rootRef.current + if (!visible || !row.settled || root === null || threadId === undefined + || row.contentBlockIndex === undefined + || !isSidechatSurfaceIdentity(threadId, row.seq, row.contentBlockIndex)) return + return attachSidechatSurface(service, { + root, + source: 'dsh-better-sidebar/sidechat', + threadId, + eventSeq: row.seq, + contentBlockIndex: row.contentBlockIndex, + text: row.text, + sendPrompt, + }) + }, [service, threadId, visible, sendPrompt, row.settled, row.seq, row.contentBlockIndex, row.text, renderedText]) + return ( +
+ {/* `streaming` keeps the host's incremental parse across chunks + instead of restarting it; only the durable (settled) message is + the final parse. It rides the row's own flag so a superseded + live row never claims to be settled. */} + +
+ ) +} diff --git a/src/client/index.tsx b/src/client/index.tsx index ce6d3d325..0cf931271 100644 --- a/src/client/index.tsx +++ b/src/client/index.tsx @@ -13,6 +13,7 @@ import { createRoot, type Root } from 'react-dom/client' import type { Context } from '../context-types.ts' import { createSidebarStore } from './state.ts' import { createBetterSidebarService, matchUrlTarget } from './service.ts' +import { disposeSidechatSurfaces } from './sidechat-surface.ts' import { revalidateChunksOnReactivate, setChunkModuleSystem } from './chunk-loader.ts' import { registerBuiltins } from './builtins/index.ts' import { Sidebar } from './Sidebar.tsx' @@ -170,6 +171,7 @@ export function apply(ctx: Context): void { // are ready by the time the sidebar renders. const service = createBetterSidebarService(sidebarStore) ctx.provide('betterSidebar', service) + ctx.effect(() => () => { disposeSidechatSurfaces(service) }, 'dsh-better-sidebar: sidechat surface adapters') // The native right-Sidebar surface: the plugin's content is registered as // DSH tab types (one per descriptor) and every open routes there, so the // right column belongs to the host and only the bottom workbench stays diff --git a/src/client/service.ts b/src/client/service.ts index 8072a32be..54d9f73ee 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -31,6 +31,8 @@ import { hostRouteUrl as resolveHostRoute } from './host-route-url.ts' import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx' import type { SessionScope } from './api.ts' import type { SidebarPrefs } from '../prefs-shared.ts' +import { bindSidechatSurfaces, type SidechatSurfaceAdapter } from './sidechat-surface.ts' +export type { SidechatSurface, SidechatSurfaceAdapter } from './sidechat-surface.ts' /** * Public state vocabulary re-exported for consumers (type-only; the values @@ -619,6 +621,8 @@ export interface SidebarSurface { * The registry service published as `ctx.betterSidebar`. */ export interface BetterSidebarService { + /** Proposed opt-in bridge for settled assistant Markdown in sidechat only. */ + registerSidechatSurfaceAdapter(adapter: SidechatSurfaceAdapter): () => void registerTab(descriptor: TabDescriptor): () => void registerFileViewer(descriptor: FileViewerDescriptor): () => void registerFileIcon(descriptor: FileIconDescriptor): () => void @@ -1444,7 +1448,8 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe openTab({ type: 'editor', title: title ?? baseNameOf(path), path, id: `editor:${path}` }, scope) } - return { + const service: BetterSidebarService = { + registerSidechatSurfaceAdapter: adapter => registerSidechatSurfaceAdapter(adapter), registerTab, registerFileViewer, registerFileIcon, @@ -1474,6 +1479,8 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe nativePathTabs: () => surface?.pathTabs?.() ?? [], clearUnread: clearUnreadFor, } + const registerSidechatSurfaceAdapter = bindSidechatSurfaces(service) + return service } /** diff --git a/src/client/sidechat-surface.ts b/src/client/sidechat-surface.ts new file mode 100644 index 000000000..2b602dc3f --- /dev/null +++ b/src/client/sidechat-surface.ts @@ -0,0 +1,146 @@ +/** A deliberately narrow, opt-in bridge for settled sidechat Markdown. + * The renderer lives in the consumer; this module never searches or forges + * main-conversation DOM and holds only currently attached row roots. */ +export interface SidechatSurface { + readonly root: HTMLElement + readonly source: 'dsh-better-sidebar/sidechat' + readonly threadId: string + readonly eventSeq: number + readonly contentBlockIndex: number + /** Original assistant text, before Markdown link rewriting. */ + readonly text: string + readonly sendPrompt: (text: string) => Promise +} + +export interface SidechatSurfaceAdapter { + readonly id: string + /** Own only this root; return an idempotent cleanup that restores Markdown. + * A throwing mount must roll back its own partial changes before throwing. */ + readonly mount: (surface: SidechatSurface) => (() => void) +} + +interface Registration { + adapter: SidechatSurfaceAdapter + active: boolean +} + +interface AttachedSurface { + surface: SidechatSurface + active: boolean + mounts: Map void> +} + +const noop = (): void => {} + +function safely(action: () => void): void { + try { + action() + } catch (error) { + console.error('[dsh-better-sidebar] sidechat surface adapter error:', error) + } +} + +/** Identity is log-owned, never guessed from a DOM position or parent session. */ +export function isSidechatSurfaceIdentity(threadId: unknown, eventSeq: unknown, contentBlockIndex: unknown): boolean { + return typeof threadId === 'string' && threadId.trim() !== '' + && typeof eventSeq === 'number' && Number.isSafeInteger(eventSeq) && eventSeq >= 0 + && typeof contentBlockIndex === 'number' && Number.isSafeInteger(contentBlockIndex) && contentBlockIndex >= 0 +} + +function createRegistry() { + const adapters = new Map() + const roots = new Map() + let disposed = false + + const mount = (registration: Registration, attached: AttachedSurface): void => { + if (!registration.active || !attached.active || attached.mounts.has(registration)) return + safely(() => { + const cleanup = registration.adapter.mount({ + ...attached.surface, + sendPrompt: async (text: string): Promise => { + if (!registration.active || !attached.active) throw new Error('Sidechat surface is no longer active') + await attached.surface.sendPrompt(text) + }, + }) + if (typeof cleanup !== 'function') throw new Error('Sidechat surface adapter must return a cleanup function') + // A callback can synchronously unregister itself or detach the row. + if (!registration.active || !attached.active) safely(cleanup) + else attached.mounts.set(registration, cleanup) + }) + } + + const detach = (attached: AttachedSurface): void => { + if (!attached.active) return + attached.active = false + if (roots.get(attached.surface.root) === attached) roots.delete(attached.surface.root) + const cleanups = [...attached.mounts.values()] + attached.mounts.clear() + for (const cleanup of cleanups) safely(cleanup) + } + + return { + register(adapter: SidechatSurfaceAdapter): () => void { + if (disposed) throw new Error('[dsh-better-sidebar] sidechat surface registry is disposed') + if (typeof adapter.id !== 'string' || adapter.id.trim() === '' || typeof adapter.mount !== 'function') { + throw new Error('[dsh-better-sidebar] invalid sidechat surface adapter') + } + if (adapters.has(adapter.id)) { + throw new Error(`[dsh-better-sidebar] sidechat surface adapter "${adapter.id}" already registered`) + } + const registration: Registration = { adapter, active: true } + adapters.set(adapter.id, registration) + for (const attached of [...roots.values()]) mount(registration, attached) + return () => { + if (!registration.active) return + registration.active = false + if (adapters.get(adapter.id) === registration) adapters.delete(adapter.id) + for (const attached of [...roots.values()]) { + const cleanup = attached.mounts.get(registration) + attached.mounts.delete(registration) + if (cleanup !== undefined) safely(cleanup) + } + } + }, + attach(surface: SidechatSurface): () => void { + if (disposed || surface.source !== 'dsh-better-sidebar/sidechat' + || !isSidechatSurfaceIdentity(surface.threadId, surface.eventSeq, surface.contentBlockIndex) + || typeof surface.text !== 'string' || typeof surface.sendPrompt !== 'function') return noop + const Element = surface.root?.ownerDocument?.defaultView?.HTMLElement + if (Element === undefined || !(surface.root instanceof Element)) return noop + const previous = roots.get(surface.root) + if (previous !== undefined) detach(previous) + const attached: AttachedSurface = { surface, active: true, mounts: new Map() } + roots.set(surface.root, attached) + for (const registration of [...adapters.values()]) mount(registration, attached) + return () => { detach(attached) } + }, + dispose(): void { + if (disposed) return + disposed = true + for (const registration of adapters.values()) registration.active = false + adapters.clear() + for (const attached of [...roots.values()]) detach(attached) + }, + } +} + +/** Weak service ownership avoids adding attach/dispose to the public service. */ +const registries = new WeakMap>() + +/** @internal Bind once while the BetterSidebar service is being constructed. */ +export function bindSidechatSurfaces(service: object): (adapter: SidechatSurfaceAdapter) => (() => void) { + const registry = createRegistry() + registries.set(service, registry) + return adapter => registry.register(adapter) +} + +/** @internal Only SideChatView attaches real, visible settled Markdown roots. */ +export function attachSidechatSurface(service: object | undefined, surface: SidechatSurface): () => void { + return service === undefined ? noop : registries.get(service)?.attach(surface) ?? noop +} + +/** @internal Plugin teardown, even if a React row has not unmounted yet. */ +export function disposeSidechatSurfaces(service: object): void { + registries.get(service)?.dispose() + registries.delete(service) +} diff --git a/src/client/sidechat-transcript.ts b/src/client/sidechat-transcript.ts index 525ba3dab..c5f32423c 100644 --- a/src/client/sidechat-transcript.ts +++ b/src/client/sidechat-transcript.ts @@ -5,8 +5,9 @@ * display rows. * * A thread child's log starts with the ENTIRE inherited parent log as its - * fork seed. The route already cuts everything up to the LAST - * `session/end-seed` marker; the mapping re-applies the same cut so any + * fork seed. The route already cuts everything up to the last tagged + * `session/end-seed { inherited: true }` marker; the mapping re-applies the + * same cut (never a restore/replay lifecycle marker) so any * seed event that somehow crosses the wire still never renders, and maps * context injections (the "Side conversation boundary" prompt, * plugin-sourced context) onto a collapsible injection row, so the view @@ -32,7 +33,7 @@ */ import type { DiffHunk, ReadBlockLine } from '@deepseek-ai/dsh-client-ui-primitives' import type { SidebarHistoryEntry } from '../context-types.ts' -import { isContextInjectionMessage, SIDE_BOUNDARY_PROMPT } from '../sidechat-core.ts' +import { isContextInjectionMessage, SIDE_BOUNDARY_PROMPT, threadOwnLogEvents } from '../sidechat-core.ts' /** * Structured render payload for a tool row that maps onto one of the host's @@ -62,9 +63,9 @@ export interface SidechatDeliverable { } /** One compact transcript row rendered in the thread view. `seq` is the - * source event's log sequence — stable row identity for React keys across - * polls (streaming caches ride the key, so window slides must not re-key - * rows). */ + * source event's log sequence. Text/reasoning also retain the original + * content-block index: one event can yield several rows, so seq alone is + * not a unique React key across polls. */ export type SidechatTranscriptRow = /** `messageId` is the durable message identity the log records on the event * (`data.id`); the view uses it to dedupe a still-pending inbox row against @@ -81,9 +82,10 @@ export type SidechatTranscriptRow = * failure. */ | { kind: 'error'; seq: number; text: string } /** `settled` distinguishes an assembled message from a still-streaming - * chunk accumulation (streaming rows are superseded by the settle). */ - | { kind: 'assistant'; seq: number; text: string; settled: boolean } - | { kind: 'reasoning'; seq: number; text: string; settled: boolean } + * chunk accumulation. Original content-block indexes are never compacted; + * a live chunk that lacks a valid index keeps it undefined. */ + | { kind: 'assistant'; seq: number; text: string; settled: boolean; contentBlockIndex?: number } + | { kind: 'reasoning'; seq: number; text: string; settled: boolean; contentBlockIndex?: number } | { kind: 'tool' seq: number @@ -212,14 +214,6 @@ function resultTextOf(data: Record): string { return parts.join('\n') } -/** Index of the last `session/end-seed` event (fork seed marker), or -1. */ -function lastSeedEnd(events: readonly { type: string }[]): number { - for (let index = events.length - 1; index >= 0; index--) { - if (events[index]?.type === 'session/end-seed') return index - } - return -1 -} - /** Parse the tool's raw arguments JSON to an object, or undefined. */ function parseArgsObject(args: string | undefined): Record | undefined { if (args === undefined) return undefined @@ -438,8 +432,7 @@ function attemptFailure(stream: unknown): string | undefined { * @returns display rows in log order. */ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: readonly SidechatTranscriptRow[]): SidechatTranscriptRow[] { - const events = entries.map(entry => entry.event) - const seedEnd = lastSeedEnd(events) + const events = threadOwnLogEvents(entries.map(entry => entry.event)) const rows: SidechatTranscriptRow[] = [] /** (turn, step, index, kind) key → index of its accumulating stream row. */ const streamRows = new Map() @@ -460,7 +453,6 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r * context re-sent, so summing would double-count). */ const turnUsage = new Map() for (let index = 0; index < events.length; index++) { - if (index <= seedEnd) continue const event = events[index] if (event === undefined) continue const data = event.data as Record @@ -549,7 +541,10 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r } } else { streamRows.set(key, rows.length) - rows.push({ kind, seq: event.seq, text: chunk.text, settled: false }) + rows.push({ kind, seq: event.seq, text: chunk.text, settled: false, + ...(typeof blockIndex === 'number' && Number.isSafeInteger(blockIndex) && blockIndex >= 0 + ? { contentBlockIndex: blockIndex } : {}), + }) } break } @@ -577,14 +572,14 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r const content = Array.isArray((data.message as { content?: unknown } | undefined)?.content) ? (data.message as { content: readonly unknown[] }).content : [] - const settled: SidechatTranscriptRow[] = content.flatMap((block): SidechatTranscriptRow[] => { + const settled: SidechatTranscriptRow[] = content.flatMap((block, contentBlockIndex): SidechatTranscriptRow[] => { if (block === null || typeof block !== 'object') return [] const candidate = block as { type?: unknown; text?: unknown } if (candidate.type === 'reasoning' && typeof candidate.text === 'string' && candidate.text !== '') { - return [{ kind: 'reasoning', seq: event.seq, text: candidate.text, settled: true }] + return [{ kind: 'reasoning', seq: event.seq, text: candidate.text, settled: true, contentBlockIndex }] } if (candidate.type === 'text' && typeof candidate.text === 'string' && candidate.text !== '') { - return [{ kind: 'assistant', seq: event.seq, text: candidate.text, settled: true }] + return [{ kind: 'assistant', seq: event.seq, text: candidate.text, settled: true, contentBlockIndex }] } return [] }) @@ -711,6 +706,14 @@ export function transcriptRows(entries: readonly SidebarHistoryEntry[], prev?: r return reuseRows(rows, prev) } +/** A single assistant event can have multiple text/reasoning blocks. Keep the + * original block index (including skipped blocks), not a filtered row index. */ +export function sidechatRowKey(row: SidechatTranscriptRow): string { + return row.kind === 'assistant' || row.kind === 'reasoning' + ? `${row.kind}:${row.seq}:${row.contentBlockIndex ?? 'unknown'}` + : `${row.kind}:${row.seq}` +} + /** Whether two rows carry identical display content (identity fields plus * every rendered field of their kind). */ function rowsEqual(a: SidechatTranscriptRow, b: SidechatTranscriptRow): boolean { @@ -729,6 +732,7 @@ function rowsEqual(a: SidechatTranscriptRow, b: SidechatTranscriptRow): boolean case 'reasoning': { const other = b as typeof a return a.text === other.text && a.settled === other.settled + && a.contentBlockIndex === other.contentBlockIndex } case 'tool': { // The card is NOT compared by value: its content is a pure function of diff --git a/src/index.ts b/src/index.ts index feb309574..1cc24269c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -83,6 +83,8 @@ export type { SidebarConfig, ResolvedSidebarConfig } export type { Context } from './context-types.ts' export type { BetterSidebarService, + SidechatSurface, + SidechatSurfaceAdapter, TabDescriptor, TabComponentProps, FileViewerDescriptor, diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index c5b8416ca..62fa70853 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -1459,12 +1459,15 @@ export function effectiveModelSelection( return parentModelSelection(events) } -/** The events a thread produced itself: everything after the LAST - * `session/end-seed` marker (the fork-seed boundary). A log with no marker - * (a thread created before seeding existed) is returned whole. */ +/** The events a thread produced itself: everything after its last + * `session/end-seed { inherited: true }` fork boundary. Untagged markers + * delimit restore/replay lifecycles, not inherited history. A log with no + * inherited marker (including an already-cut route payload) is returned whole. */ export function threadOwnLogEvents(events: readonly SidechatLogEvent[]): SidechatLogEvent[] { for (let index = events.length - 1; index >= 0; index--) { - if (events[index]?.type === 'session/end-seed') return events.slice(index + 1) + const event = events[index] + if (event?.type === 'session/end-seed' && typeof event.data === 'object' && event.data !== null + && 'inherited' in event.data && event.data.inherited === true) return events.slice(index + 1) } return [...events] } diff --git a/tests/consumer-types.ts b/tests/consumer-types.ts index 95ad7f690..5574a1252 100644 --- a/tests/consumer-types.ts +++ b/tests/consumer-types.ts @@ -19,6 +19,8 @@ import { } from '../src/client/service.ts' import type { BetterSidebarService, + SidechatSurface, + SidechatSurfaceAdapter, FileFetchStrategy, FileIconDescriptor, FileViewerDescriptor, @@ -165,3 +167,18 @@ const features: readonly string[] = SIDEBAR_FEATURES void version; void features const strategy: FileFetchStrategy = 'mediaUrl' void diff; void prefs; void store; void declaration; void typeName; void strategy + + +/** Proposed sidechat adapter: browser-only types, no host implementation import. */ +const sidechatAdapter: SidechatSurfaceAdapter = { + id: 'my-plugin:sidechat', + mount: (surface: SidechatSurface) => { + const source: 'dsh-better-sidebar/sidechat' = surface.source + const root: HTMLElement = surface.root + const identity: [string, number, number] = [surface.threadId, surface.eventSeq, surface.contentBlockIndex] + const send: (text: string) => Promise = surface.sendPrompt + void source; void root; void identity; void send + return () => {} + }, +} +service.registerSidechatSurfaceAdapter(sidechatAdapter)() diff --git a/tests/service.spec.ts b/tests/service.spec.ts index c2e05d8d3..be664e03d 100644 --- a/tests/service.spec.ts +++ b/tests/service.spec.ts @@ -24,6 +24,17 @@ import { createBetterSidebarService, matchUrlTarget, SIDEBAR_FEATURES, SIDEBAR_S import { createSidebarStore, allLeaves, makeDefaultState, openDiffTab, openTabInBottomPane, sanitizeState } from '../src/client/state.ts' describe('BetterSidebar service', () => { + it('provides the opt-in sidechat adapter registration without exposing internal attach/dispose', () => { + const service = createBetterSidebarService(createSidebarStore()) + const adapter = { id: 'synthetic:genui', mount: () => () => {} } + const unregister = service.registerSidechatSurfaceAdapter(adapter) + expect(() => service.registerSidechatSurfaceAdapter(adapter)).toThrow('already registered') + unregister() + expect(() => service.registerSidechatSurfaceAdapter(adapter)).not.toThrow() + expect(service).not.toHaveProperty('attachSidechatSurface') + expect(service).not.toHaveProperty('disposeSidechatSurfaces') + }) + it('registerTab adds to the registry and dispose removes it', () => { const store = createSidebarStore() const service = createBetterSidebarService(store) diff --git a/tests/sidechat-assistant-row.spec.tsx b/tests/sidechat-assistant-row.spec.tsx new file mode 100644 index 000000000..4e92f1a48 --- /dev/null +++ b/tests/sidechat-assistant-row.spec.tsx @@ -0,0 +1,66 @@ +/** Host Markdown remains the default; only identified, settled, visible + * assistant rows expose their real root to the optional surface consumer. */ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { SidechatAssistantRow } from '../src/client/SidechatAssistantRow.tsx' +import { bindSidechatSurfaces, disposeSidechatSurfaces } from '../src/client/sidechat-surface.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' + +setupReactAct() +const labels = { copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code', wrapLabel: 'Wrap', unwrapLabel: 'Unwrap' } +const row = { kind: 'assistant' as const, seq: 5, text: '**original**\n\n```dsh-ui\n{"type":"button"}\n```', settled: true, contentBlockIndex: 2 } +const rewrite = (row: { text: string }): string => row.text.replace('original', 'rewritten') + +afterEach(() => { vi.restoreAllMocks() }) + +describe('SidechatAssistantRow', () => { + it('keeps real Markdown without a consumer and exposes original text on late registration', () => { + const service = {} + const register = bindSidechatSurfaces(service) + const surface = { service, threadId: 'child', visible: true, sendPrompt: vi.fn(async () => {}) } + const rendered = renderRoot(createElement(SidechatAssistantRow, { row, labels, rewrite, surface })) + expect(rendered.container.querySelector('strong')?.textContent).toBe('rewritten') + expect(rendered.container.querySelector('pre code')?.textContent).toContain('"type":"button"') + const cleanup = vi.fn() + const mount = vi.fn(() => cleanup) + const unregister = register({ id: 'genui', mount }) + expect(mount).toHaveBeenCalledWith(expect.objectContaining({ + root: rendered.container.firstElementChild, threadId: 'child', eventSeq: 5, contentBlockIndex: 2, text: row.text, + })) + rendered.rerender(createElement(SidechatAssistantRow, { row: { ...row }, labels, rewrite, surface: { ...surface } })) + expect(mount).toHaveBeenCalledTimes(1) + rendered.rerender(createElement(SidechatAssistantRow, { row, labels, rewrite, surface: { ...surface, visible: false } })) + expect(cleanup).toHaveBeenCalledTimes(1) + rendered.rerender(createElement(SidechatAssistantRow, { row, labels, rewrite, surface })) + expect(mount).toHaveBeenCalledTimes(2) + unregister() + expect(cleanup).toHaveBeenCalledTimes(2) + expect(rendered.container.querySelector('pre code')?.textContent).toContain('"type":"button"') + rendered.unmount() + disposeSidechatSurfaces(service) + }) + + it.each([ + { name: 'streaming', row: { ...row, settled: false }, threadId: 'child', visible: true }, + { name: 'hidden', row, threadId: 'child', visible: false }, + { name: 'missing thread', row, threadId: undefined, visible: true }, + { name: 'blank thread', row, threadId: ' ', visible: true }, + { name: 'invalid event', row: { ...row, seq: -1 }, threadId: 'child', visible: true }, + { name: 'missing index', row: { ...row, contentBlockIndex: undefined }, threadId: 'child', visible: true }, + ])('does not opt in $name, but always keeps the scanner exclusion marker', ({ row: current, threadId, visible }) => { + const service = {} + const register = bindSidechatSurfaces(service) + const mount = vi.fn(() => () => {}) + register({ id: 'genui', mount }) + const rendered = renderRoot(createElement(SidechatAssistantRow, { + row: current, labels, rewrite, surface: { service, threadId, visible, sendPrompt: vi.fn(async () => {}) }, + })) + expect(mount).not.toHaveBeenCalled() + expect(rendered.container.firstElementChild?.getAttribute('data-genui-surface')).toBe('dsh-better-sidebar/sidechat') + expect(rendered.container.querySelector('[data-chat-role], [data-chat-seq]')).toBeNull() + expect(rendered.container.querySelector('strong')?.textContent).toBe('rewritten') + rendered.unmount() + disposeSidechatSurfaces(service) + }) +}) diff --git a/tests/sidechat-present-card.spec.tsx b/tests/sidechat-present-card.spec.tsx index 7f1208d80..d50aeb0a6 100644 --- a/tests/sidechat-present-card.spec.tsx +++ b/tests/sidechat-present-card.spec.tsx @@ -182,7 +182,7 @@ describe('SideChatView present deliverables card (C2)', () => { time: 0, data: { turn: 1, callId: 'c-seed', files: [{ path: `${SESSION_CWD}/seed-only.pdf`, description: 'seed 交付' }] }, }, - { type: 'session/end-seed', seq: 1, time: 1_000, data: {} }, + { type: 'session/end-seed', seq: 1, time: 1_000, data: { inherited: true } }, { type: 'user/message', seq: 2, time: 2_000, data: { content: [{ type: 'text', text: 'and now?' }], source: { kind: 'user' } } }, { type: 'turn/start', seq: 3, time: 3_000, data: { turn: 2 } }, { diff --git a/tests/sidechat-resume-boundary.spec.ts b/tests/sidechat-resume-boundary.spec.ts new file mode 100644 index 000000000..5ccf8e84a --- /dev/null +++ b/tests/sidechat-resume-boundary.spec.ts @@ -0,0 +1,105 @@ +/** Real Session restore semantics, synthetic in-memory events only. No host/browser/provider. */ +import { describe, expect, it } from 'vitest' +import { Session, SessionLogOffset, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import type { SessionId, SessionSeedEventState } from '@deepseek-ai/dsh-session' +import type { SidebarHistoryEntry } from '../src/context-types.ts' +import { threadOwnLogEvents, threadHasCompletedTurn, threadTrailingPending, type SidechatLogEvent } from '../src/sidechat-core.ts' +import { transcriptRows } from '../src/client/sidechat-transcript.ts' + +const childContent = [ + { type: 'text', text: 'Synthetic child block zero.' }, + { type: 'reasoning', text: 'Synthetic non-text-block gap.' }, + { type: 'text', text: 'Synthetic child block two.' }, +] +function turn(session: Session, number: number, label: string, content = childContent): void { + session.append('turn/start', { turn: number }) + session.append('step/start', { turn: number, step: 1 }) + session.append('user/message', { id: `${label}-user`, role: 'user', source: { kind: 'user' }, + content: [{ type: 'text', text: label }] } as never, { surfaceOp: 'append' }) + session.append('assistant/message', { turn: number, step: 1, + message: { id: `${label}-assistant`, role: 'assistant', source: { kind: 'model', provider: 'synthetic', model: 'fixture' }, content }, + stream: [] } as never, { surfaceOp: 'append' }) + session.append('step/end', { turn: number, step: 1 }) + session.append('turn/end', { turn: number, reason: { kind: 'completed' } }) +} +function fork(parent: Session, id: string): Session { + return Session.create(id as SessionId, parent.snapshotEvents(), { + version: SESSION_FORMAT_VERSION, id: id as SessionId, createdAt: 1, isSeeded: true, + }, SessionLogOffset(parent.snapshotEvents().length)) +} +function seed(): Session { + const parent = Session.create('session-synthetic-parent' as SessionId) + turn(parent, 1, 'synthetic inherited parent', [{ type: 'text', text: 'Inherited parent output must stay excluded.' }]) + const child = fork(parent, 'session-synthetic-child') + turn(child, 2, 'synthetic child turn') + return child +} +function restore(session: Session, mode: SessionSeedEventState): Session { + return Session.fromRestore(session.id, + mode === 'detached' ? structuredClone(session.snapshotEvents()) : session.snapshotEvents(), + mode === 'detached' ? structuredClone(session.header) : session.header, session.inheritedEventCount, mode) +} +const log = (session: Session): readonly SidechatLogEvent[] => session.snapshotEvents() +const entries = (events: readonly SidechatLogEvent[]): SidebarHistoryEntry[] => events.map(event => ({ event } as SidebarHistoryEntry)) +const assistants = (events: readonly SidechatLogEvent[]) => transcriptRows(entries(events)).filter(row => row.kind === 'assistant') +const marker = (seq: number, data: unknown): SidechatLogEvent => ({ type: 'session/end-seed', seq, time: seq, data }) +const message = (seq: number): SidechatLogEvent => ({ type: 'user/message', seq, time: seq, data: { role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: `synthetic-${seq}` }] } }) + +describe('inherited boundary is not a restore boundary', () => { + it('cuts only the last tagged inherited prefix, including nested forks', () => { + const events = [message(0), marker(1, { inherited: true }), message(2), marker(3, {}), + marker(4, { inherited: true }), message(5), marker(6, {})] + expect(threadOwnLogEvents(events).map(event => event.seq)).toEqual([5, 6]) + }) + it('is idempotent on the already-cut route payload containing restore markers', () => { + const events = [message(0), marker(1, { inherited: true }), message(2), marker(3, {})] + const own = threadOwnLogEvents(events) + expect(own.map(event => event.seq)).toEqual([2, 3]) + expect(threadOwnLogEvents(own)).toEqual(own) + expect(transcriptRows(entries(own))).toEqual([{ kind: 'user', seq: 2, text: 'synthetic-2' }]) + }) + it('does not invent a fork cut from replay, false, malformed or absent markers', () => { + const events = [message(0), marker(1, {}), marker(2, { inherited: false }), marker(3, { inherited: 'true' }), + marker(4, null), message(5)] + expect(threadOwnLogEvents(events)).toEqual(events) + expect(transcriptRows(entries(events)).filter(row => row.kind === 'user').map(row => row.seq)).toEqual([0, 5]) + }) + for (const mode of ['detached', 'shared-frozen'] as const) { + it(`preserves both original text-block indexes across actual ${mode} restore and route→client composition`, () => { + const child = seed(), before = assistants(log(child)) + expect(before.map(row => row.contentBlockIndex)).toEqual([0, 2]) + const resumed = restore(child, mode), events = log(resumed) + expect(events.at(-1)).toMatchObject({ type: 'session/end-seed', data: {} }) + expect(resumed.inheritedEventCount).toBe(child.inheritedEventCount) + expect(assistants(events)).toEqual(before) + expect(assistants(threadOwnLogEvents(events))).toEqual(before) + expect(JSON.stringify(transcriptRows(entries(threadOwnLogEvents(events))))).not.toContain('Inherited parent output') + expect(threadHasCompletedTurn(entries(events))).toBe(true) + expect(threadTrailingPending(entries(events))).toBe(false) + }) + it(`retains earlier child turns across multiple actual ${mode} restore markers`, () => { + const first = restore(seed(), mode) + turn(first, 3, 'synthetic second child turn') + const second = restore(first, mode), events = log(second) + expect(events.filter(event => event.type === 'session/end-seed').map(event => event.data)).toEqual([ + { inherited: true }, {}, {}, + ]) + expect(assistants(threadOwnLogEvents(events)).map(row => row.contentBlockIndex)).toEqual([0, 2, 0, 2]) + expect(assistants(events)).toEqual(assistants(threadOwnLogEvents(events))) + second.append('user/message', { id: 'synthetic pending', role: 'user', source: { kind: 'user' }, + content: [{ type: 'text', text: 'synthetic follow-up' }] } as never, { surfaceOp: 'append' }) + expect(threadTrailingPending(entries(log(second)))).toBe(true) + }) + it(`keeps nested parent history excluded after actual ${mode} restore`, () => { + const parent = restore(seed(), mode) + const empty = fork(parent, 'session-synthetic-empty-child') + expect(assistants(log(restore(empty, mode)))).toEqual([]) + const grandchild = fork(parent, 'session-synthetic-grandchild') + turn(grandchild, 4, 'synthetic grandchild') + const resumed = restore(grandchild, mode) + const output = assistants(threadOwnLogEvents(log(resumed))) + expect(output.map(row => row.contentBlockIndex)).toEqual([0, 2]) + expect(output.every(row => row.seq > Number(grandchild.inheritedEventCount))).toBe(true) + }) + } +}) diff --git a/tests/sidechat-routes.spec.ts b/tests/sidechat-routes.spec.ts index acaf54960..4ee74cc91 100644 --- a/tests/sidechat-routes.spec.ts +++ b/tests/sidechat-routes.spec.ts @@ -645,7 +645,7 @@ function threadLog(): Array> { return [ ev('user/message', 0, { content: [{ type: 'text', text: 'inherited parent question' }], source: { kind: 'user' } }), ev('turn/end', 1, { turn: 0, reason: { kind: 'completed' } }), - ev('session/end-seed', 2), + ev('session/end-seed', 2, { inherited: true }), ev('subagent/descriptor', 3, { mode: 'continuable' }), ev('user/message', 4, { content: [{ type: 'text', text: 'Side conversation boundary.' }], source: { kind: SIDE_INJECTION_SOURCE_KIND } }), ev('user/message', 5, { content: [{ type: 'text', text: 'the side question' }], source: { kind: 'user' } }), @@ -665,6 +665,17 @@ describe('sidechat.events', () => { expect(services.open).not.toHaveBeenCalled() }) + it('keeps pre-resume child history when a live restored log ends in an untagged lifecycle marker', async () => { + const child = agent('child', { events: [...threadLog(), ev('session/end-seed', 8, {})] }) + const services = happyServices(undefined, child) + const api = buildSidechatApi(ctxWith(services)) + const result = await api['sidechat.events']({ childId: 'child' }) + expect(result.events.map(event => event.seq)).toEqual([3, 4, 5, 6, 7, 8]) + const delta = await api['sidechat.events']({ childId: 'child', afterSeq: 6 }) + expect(delta.events.map(event => event.seq)).toEqual([7, 8]) + expect(services.open).not.toHaveBeenCalled() + }) + it('narrows to the afterSeq delta on polls (and never resurrects the seed)', async () => { const child = agent('child', { events: threadLog() }) const services = happyServices(undefined, child) diff --git a/tests/sidechat-surface.spec.ts b/tests/sidechat-surface.spec.ts new file mode 100644 index 000000000..d89a760bc --- /dev/null +++ b/tests/sidechat-surface.spec.ts @@ -0,0 +1,144 @@ +/** Opt-in sidechat bridge: scoped roots, late registration, exact identity, + * failure isolation and disposal. No timer, global DOM scan or host session. */ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + attachSidechatSurface, bindSidechatSurfaces, disposeSidechatSurfaces, + type SidechatSurface, type SidechatSurfaceAdapter, +} from '../src/client/sidechat-surface.ts' + +function fixture() { + const service = {} + const register = bindSidechatSurfaces(service) + const root = document.createElement('div') + root.innerHTML = '
synthetic dsh-ui source
' + document.body.append(root) + const prompt = vi.fn(async () => {}) + const surface: SidechatSurface = { + root, source: 'dsh-better-sidebar/sidechat', threadId: 'child-a', + eventSeq: 5, contentBlockIndex: 2, text: 'synthetic dsh-ui source', sendPrompt: prompt, + } + return { service, register, root, surface, prompt } +} + +afterEach(() => { document.body.replaceChildren(); vi.restoreAllMocks() }) + +describe('sidechat surface registration', () => { + it('mounts an existing visible surface on late registration and restores it on unregister', () => { + const { service, register, root, surface } = fixture() + const detach = attachSidechatSurface(service, surface) + const code = root.querySelector('pre')! + const cleanup = vi.fn(() => { code.hidden = false }) + const mount = vi.fn((received: SidechatSurface) => { + expect(received).toMatchObject({ root, source: surface.source, threadId: 'child-a', eventSeq: 5, contentBlockIndex: 2, text: surface.text }) + code.hidden = true + return cleanup + }) + const unregister = register({ id: 'genui', mount }) + expect(mount).toHaveBeenCalledTimes(1) + expect(code.hidden).toBe(true) + unregister(); unregister() + expect(cleanup).toHaveBeenCalledTimes(1) + expect(code.hidden).toBe(false) + detach(); detach() + expect(cleanup).toHaveBeenCalledTimes(1) + disposeSidechatSurfaces(service) + }) + + it('does not retain detached rows for later adapters', () => { + const { service, register, surface } = fixture() + const detach = attachSidechatSurface(service, surface) + detach() + const mount = vi.fn(() => () => {}) + register({ id: 'late', mount }) + expect(mount).not.toHaveBeenCalled() + disposeSidechatSurfaces(service) + }) + + it('rejects duplicate adapter ids without mounting twice, then permits the released id', () => { + const { service, register, surface } = fixture() + attachSidechatSurface(service, surface) + const mount = vi.fn(() => () => {}) + const unregister = register({ id: 'genui', mount }) + expect(() => register({ id: 'genui', mount })).toThrow('already registered') + expect(mount).toHaveBeenCalledTimes(1) + unregister() + register({ id: 'genui', mount }) + expect(mount).toHaveBeenCalledTimes(2) + disposeSidechatSurfaces(service) + }) + + it('isolates mount and cleanup failures so another adapter still mounts and cleans up', () => { + const { service, register, surface } = fixture() + const logged = vi.spyOn(console, 'error').mockImplementation(() => {}) + register({ id: 'throws-on-mount', mount: () => { throw new Error('synthetic mount failure') } }) + register({ id: 'throws-on-cleanup', mount: () => () => { throw new Error('synthetic cleanup failure') } }) + const cleanup = vi.fn() + const mount = vi.fn(() => cleanup) + register({ id: 'healthy', mount }) + const detach = attachSidechatSurface(service, surface) + expect(mount).toHaveBeenCalledTimes(1) + detach() + expect(cleanup).toHaveBeenCalledTimes(1) + expect(logged).toHaveBeenCalledTimes(2) + disposeSidechatSurfaces(service) + }) + + it.each(['row', 'adapter', 'plugin'] as const)('revokes old send callbacks on %s disposal', async (target) => { + const { service, register, surface, prompt } = fixture() + let received: SidechatSurface | undefined + const unregister = register({ id: 'genui', mount: value => { received = value; return () => {} } }) + const detach = attachSidechatSurface(service, surface) + await received!.sendPrompt('synthetic child prompt') + expect(prompt).toHaveBeenCalledWith('synthetic child prompt') + if (target === 'row') detach() + else if (target === 'adapter') unregister() + else disposeSidechatSurfaces(service) + await expect(received!.sendPrompt('must not send')).rejects.toThrow('no longer active') + expect(prompt).toHaveBeenCalledTimes(1) + disposeSidechatSurfaces(service) + }) + + it('cleans all roots once on plugin unload and rejects stale registration', () => { + const { service, register, surface } = fixture() + const cleanup = vi.fn() + register({ id: 'genui', mount: () => cleanup }) + const detach = attachSidechatSurface(service, surface) + const secondRoot = document.createElement('div') + document.body.append(secondRoot) + attachSidechatSurface(service, { ...surface, root: secondRoot, contentBlockIndex: 4 }) + disposeSidechatSurfaces(service); disposeSidechatSurfaces(service); detach() + expect(cleanup).toHaveBeenCalledTimes(2) + expect(() => register({ id: 'late', mount: () => () => {} })).toThrow('disposed') + }) + + it.each([ + { threadId: '' }, { threadId: ' ' }, { eventSeq: -1 }, { eventSeq: 0.5 }, + { eventSeq: Number.NaN }, { contentBlockIndex: -1 }, { contentBlockIndex: undefined }, + { source: 'main-conversation' }, + ])('fails closed for invalid identity %j', (invalid) => { + const { service, register, surface } = fixture() + const mount = vi.fn(() => () => {}) + register({ id: 'genui', mount }) + attachSidechatSurface(service, { ...surface, ...invalid } as SidechatSurface) + expect(mount).not.toHaveBeenCalled() + disposeSidechatSurfaces(service) + }) + + it('releases the previous lease when the same root is reattached', () => { + const { service, register, surface } = fixture() + const cleanups: ReturnType[] = [] + const adapter: SidechatSurfaceAdapter = { id: 'genui', mount: () => { + const cleanup = vi.fn(); cleanups.push(cleanup); return cleanup + } } + register(adapter) + const oldDetach = attachSidechatSurface(service, surface) + const newDetach = attachSidechatSurface(service, { ...surface, eventSeq: 6 }) + expect(cleanups[0]).toHaveBeenCalledTimes(1) + oldDetach() + expect(cleanups[1]).not.toHaveBeenCalled() + newDetach() + expect(cleanups[1]).toHaveBeenCalledTimes(1) + disposeSidechatSurfaces(service) + }) +}) diff --git a/tests/sidechat-transcript.spec.ts b/tests/sidechat-transcript.spec.ts index f8142551e..b344c6008 100644 --- a/tests/sidechat-transcript.spec.ts +++ b/tests/sidechat-transcript.spec.ts @@ -14,6 +14,7 @@ import { formatTokens, toolArgsSummary, transcriptRows, + sidechatRowKey, type SidechatTranscriptRow, } from '../src/client/sidechat-transcript.ts' @@ -57,10 +58,10 @@ function toolRoleResultMessage(callId: string, text: string, isError = false): R } describe('transcriptRows', () => { - it('cuts the inherited seed at the last end-seed and renders the boundary as an injection row', () => { + it('cuts the inherited seed at the last tagged end-seed and renders the boundary as an injection row', () => { const entries = [ entry(ev('user/message', 0, { content: textBlocks('inherited'), source: { kind: 'user' } })), - entry(ev('session/end-seed', 1)), + entry(ev('session/end-seed', 1, { inherited: true })), entry(ev('user/message', 2, { content: textBlocks(`${SIDE_BOUNDARY_PREFIX}\n\nmode`), source: { kind: SIDE_INJECTION_SOURCE_KIND } })), entry(ev('user/message', 3, { content: textBlocks('the side question'), source: { kind: 'user' } })), ] @@ -593,7 +594,7 @@ describe('present deliverables rows', () => { const rows = transcriptRows([ presentCall(0, 'c-seed'), presentedEvent(1, 'c-seed', [{ path: '/p/inherited.pdf' }]), - entry(ev('session/end-seed', 2)), + entry(ev('session/end-seed', 2, { inherited: true })), presentedEvent(3, 'c-own', [{ path: '/p/own.pdf' }]), ]) expect(rows).toEqual([{ kind: 'deliverables', seq: 3, callId: 'c-own', files: [{ path: '/p/own.pdf' }] }]) @@ -730,3 +731,44 @@ describe('transcriptRows row reuse (newer row kinds)', () => { expect(after[0]).toMatchObject({ kind: 'tool', executing: false }) }) }) + + +describe('sidechat content-block identity', () => { + it('keeps original indexes through text, skipped, empty and reasoning blocks', () => { + const rows = transcriptRows([entry(ev('assistant/message', 17, { message: { content: [ + { type: 'text', text: 'first' }, + { type: 'image', url: 'synthetic' }, + { type: 'text', text: '' }, + null, + { type: 'text', text: 'second' }, + { type: 'reasoning', text: 'reason one' }, + { type: 'reasoning', text: 'reason two' }, + ] } }))]) + expect(rows.map(row => 'contentBlockIndex' in row ? row.contentBlockIndex : undefined)).toEqual([0, 4, 5, 6]) + expect(rows.map(sidechatRowKey)).toEqual(['assistant:17:0', 'assistant:17:4', 'reasoning:17:5', 'reasoning:17:6']) + expect(new Set(rows.map(sidechatRowKey)).size).toBe(rows.length) + }) + + it('does not reuse a prior row when its block index changed', () => { + const first = transcriptRows([entry(ev('assistant/message', 17, { message: { content: textBlocks('same text') } }))]) + const changed = transcriptRows([entry(ev('assistant/message', 17, { message: { content: [null, ...textBlocks('same text')] } }))], first) + expect(changed[0]).not.toBe(first[0]) + expect(changed[0]).toMatchObject({ contentBlockIndex: 1 }) + const unchanged = transcriptRows([entry(ev('assistant/message', 17, { message: { content: [null, ...textBlocks('same text')] } }))], changed) + expect(unchanged[0]).toBe(changed[0]) + }) + + it('keeps missing and invalid streaming block indexes unavailable rather than guessing zero', () => { + for (const index of [undefined, -1, 0.5, '0']) { + const rows = transcriptRows([entry(ev('assistant/live-chunk', 20, { turn: 1, step: 1, + chunk: { type: 'text-delta', text: 'incomplete', ...(index === undefined ? {} : { index }) }, + }))]) + expect(rows[0]).toMatchObject({ kind: 'assistant', settled: false }) + expect(rows[0]).not.toHaveProperty('contentBlockIndex') + } + const rows = transcriptRows([entry(ev('assistant/live-chunk', 20, { turn: 1, step: 1, + chunk: { type: 'text-delta', text: 'incomplete', index: 3 }, + }))]) + expect(rows[0]).toMatchObject({ contentBlockIndex: 3, settled: false }) + }) +}) diff --git a/tests/sidechat-view.spec.tsx b/tests/sidechat-view.spec.tsx index 7cde4f821..f9284b40f 100644 --- a/tests/sidechat-view.spec.tsx +++ b/tests/sidechat-view.spec.tsx @@ -19,6 +19,7 @@ import { createElement } from 'react' 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 { attachLocale } from '../src/client/locales.ts' import type { Context, SidebarSessionList } from '../src/context-types.ts' import type { SidebarTab } from '../src/client/state.ts' @@ -196,6 +197,8 @@ const EARLY_EVENTS = EVENTS.slice(0, 5) let eventsPulls = 0 /** The wire values the fetch stub serves; each test overrides what it reads. */ let eventsValue: unknown[] = EVENTS +let liveValue: unknown[] = [] +let promptCalls: Record[] = [] let pendingValue: unknown[] = [] let infoValue: Record = { live: false, provider: 'deepseek', preset: 'side' } let catalogValue: Record = { available: false, groups: [], failures: [] } @@ -238,6 +241,8 @@ beforeEach(() => { vi.stubGlobal('WebSocket', FakeSocket) eventsPulls = 0 eventsValue = EVENTS + liveValue = [] + promptCalls = [] pendingValue = [] infoValue = { live: false, provider: 'deepseek', preset: 'side' } catalogValue = { available: false, groups: [], failures: [] } @@ -253,7 +258,7 @@ beforeEach(() => { : JSON.parse(String(init.body)) as Record if (method === 'sidechat.events') { eventsPulls += 1 - return jsonResponse({ ok: true, value: { events: eventsValue, live: [], pending: pendingValue } }) + return jsonResponse({ ok: true, value: { events: eventsValue, live: liveValue, pending: pendingValue } }) } if (method === 'sidechat.info') return jsonResponse({ ok: true, value: infoValue }) if (method === 'sidechat.models') return jsonResponse({ ok: true, value: catalogValue }) @@ -272,6 +277,7 @@ beforeEach(() => { return jsonResponse({ ok: true, value: { accepted: true, removed: 1 } }) } if (method === 'sidechat.prompt') { + promptCalls.push(payload) if (promptError !== null) { return { ok: false, @@ -701,3 +707,78 @@ describe('SideChatView queue, echo and model picker', () => { unmount() }) }) + + +/** Actual bridge ownership, with only the unrelated sidebar controls faked. */ +function surfaceContext() { + const service = { updateTab: vi.fn(), openTab: vi.fn() } + const register = bindSidechatSurfaces(service) + const ctx = { sessions: { list: threadStore() }, get: (key: string) => key === 'betterSidebar' ? service : undefined } as unknown as Context + return { service, register, ctx } +} + +describe('SideChatView opt-in assistant surfaces', () => { + it('exposes only settled assistant blocks, preserving indexes and excluding the entire transcript from main scanners', async () => { + eventsValue = EVENTS.map(event => event.type === 'assistant/message' ? { ...event, data: { turn: 1, step: 2, message: { content: [ + { type: 'text', text: 'first block' }, { type: 'image', url: 'synthetic' }, + { type: 'reasoning', text: 'private reasoning fixture' }, { type: 'text', text: '' }, + { type: 'text', text: 'second block' }, + ] } } } : event) + liveValue = [{ type: 'assistant/live-chunk', seq: 100, time: 7_000, data: { turn: 2, step: 1, chunk: { type: 'text-delta', index: 0, text: 'streaming fixture' } } }] + const { service, register, ctx } = surfaceContext() + const surfaces: SidechatSurface[] = [] + register({ id: 'genui', mount: surface => { surfaces.push(surface); return () => {} } }) + const rendered = renderRoot(createElement(SideChatView, viewProps(ctx))) + await act(async () => {}) + expect(surfaces.map(surface => [surface.threadId, surface.eventSeq, surface.contentBlockIndex, surface.text])).toEqual([ + ['t1', 5, 0, 'first block'], ['t1', 5, 4, 'second block'], + ]) + expect(surfaces.every(surface => rendered.container.contains(surface.root))).toBe(true) + const transcript = rendered.container.querySelector('[data-dsh-md-surface]') + expect(transcript?.getAttribute('data-genui-surface')).toBe('dsh-better-sidebar/sidechat') + expect(transcript?.textContent).toContain('streaming fixture') + expect(transcript?.querySelector('[data-chat-role], [data-chat-seq]')).toBeNull() + rendered.unmount(); disposeSidechatSurfaces(service) + }) + + it('sends to the captured child only and shows route failures through the existing error UI', async () => { + const { service, register, ctx } = surfaceContext() + let surface: SidechatSurface | undefined + register({ id: 'genui', mount: value => { surface = value; return () => {} } }) + const rendered = renderRoot(createElement(SideChatView, viewProps(ctx))) + await act(async () => {}) + await act(async () => { await surface!.sendPrompt('synthetic action') }) + expect(promptCalls).toEqual([{ childId: 't1', text: 'synthetic action' }]) + promptError = 'synthetic sidechat prompt failed' + await act(async () => { await expect(surface!.sendPrompt('failed action')).rejects.toThrow('synthetic sidechat prompt failed') }) + expect(rendered.container.textContent).toContain('synthetic sidechat prompt failed') + expect(promptCalls.every(payload => payload.childId === 't1' && !('sessionId' in payload))).toBe(true) + rendered.unmount(); disposeSidechatSurfaces(service) + }) + + it('never labels old cached rows as a new child and revokes callbacks on thread switch and hide', async () => { + const { service, register, ctx } = surfaceContext() + const surfaces: SidechatSurface[] = [] + const cleanup = vi.fn() + register({ id: 'genui', mount: surface => { surfaces.push(surface); return cleanup } }) + const props = viewProps(ctx) + const rendered = renderRoot(createElement(SideChatView, props)) + await act(async () => {}) + const old = surfaces[0]! + eventsValue = [{ type: 'assistant/message', seq: 5, time: 5_000, data: { message: { content: [{ type: 'text', text: 'new child only' }] } } }] + const next = { ...props, tab: { ...props.tab, meta: { threadId: 't2' } } } + rendered.rerender(createElement(SideChatView, next)) + expect(surfaces.some(surface => surface.threadId === 't2' && surface.text === 'done')).toBe(false) + await expect(old.sendPrompt('late slider')).rejects.toThrow('no longer active') + await act(async () => {}) + expect(surfaces.at(-1)).toMatchObject({ threadId: 't2', text: 'new child only' }) + const current = surfaces.at(-1)! + await act(async () => { await current.sendPrompt('new child action') }) + expect(promptCalls).toEqual([{ childId: 't2', text: 'new child action' }]) + rendered.rerender(createElement(SideChatView, { ...next, visible: false })) + await expect(current.sendPrompt('hidden slider')).rejects.toThrow('no longer active') + expect(promptCalls).toHaveLength(1) + expect(cleanup).toHaveBeenCalledTimes(2) + rendered.unmount(); disposeSidechatSurfaces(service) + }) +})