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
-
+
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)
-
+
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