Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ Windows / Linux / macOS supported (macOS verified daily, the rest covered by uni
QQ group: 577011007

<div align="center">
<img width="220" alt="WeChat group QR" src="https://github.com/user-attachments/assets/e9c77c37-83f5-4c3a-911e-6afeaf815615" />
<img width="220" alt="WeChat group QR" src="https://github.com/user-attachments/assets/777c995b-e140-4414-970f-60d3656dc59e" />
<img width="220" alt="QQ group QR" src="https://github.com/user-attachments/assets/9be34629-26ef-4537-aad4-1393c147f81c" />
</div>

Expand Down
2 changes: 1 addition & 1 deletion README_ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ Windows / Linux / macOS 三平台适配(macOS 日常验证,其余经单元
推荐添加 QQ 群(577011007)

<div align="center">
<img width="220" alt="微信群二维码" src="https://github.com/user-attachments/assets/e9c77c37-83f5-4c3a-911e-6afeaf815615" />
<img width="220" alt="微信群二维码" src="https://github.com/user-attachments/assets/777c995b-e140-4414-970f-60d3656dc59e" />
<img width="220" alt="QQ群二维码" src="https://github.com/user-attachments/assets/9be34629-26ef-4537-aad4-1393c147f81c" />
</div>

Expand Down
34 changes: 34 additions & 0 deletions docs/external-plugin-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>
}
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` 按注册表驱动渲染,无硬编码):
Expand Down
75 changes: 54 additions & 21 deletions src/client/SideChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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'
Expand All @@ -89,6 +90,7 @@ import {
formatTokens,
toolArgsSummary,
transcriptRows,
sidechatRowKey,
type SidechatToolCard,
type SidechatTranscriptRow,
} from './sidechat-transcript.ts'
Expand Down Expand Up @@ -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[]
Expand Down Expand Up @@ -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 (
<div key={`${row.kind}:${row.seq}`} className={css.sidechatUser}>
<div key={key} className={css.sidechatUser}>
<MarkdownText {...markdownTextProps(surface.rewrite(row), labels)} />
</div>
)
case 'assistant':
return (
<div key={`${row.kind}:${row.seq}`} className={css.sidechatAssistant}>
{/* `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. */}
<MarkdownText {...markdownTextProps(surface.rewrite(row), labels)} streaming={!row.settled} />
</div>
<SidechatAssistantRow key={key} row={row} labels={labels} rewrite={surface.rewrite} surface={genui} />
)
case 'reasoning':
return (
<CollapsibleRow
key={`${row.kind}:${row.seq}`}
key={key}
label={labels.thinkLabel}
streaming={!row.settled}
>
Expand All @@ -527,15 +529,15 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu
)
case 'injection':
return (
<CollapsibleRow key={`${row.kind}:${row.seq}`} label={labels.injectionLabel}>
<CollapsibleRow key={key} label={labels.injectionLabel}>
<div className={css.sidechatRowProse}>{row.text}</div>
</CollapsibleRow>
)
case 'error':
// A provider/agent failure: rendered plainly (never markdown) so a raw
// provider message with odd punctuation survives verbatim.
return (
<div key={`${row.kind}:${row.seq}`} className={css.sidechatErrorRow}>
<div key={key} className={css.sidechatErrorRow}>
{t('sideChatRunError', { message: row.text })}
</div>
)
Expand All @@ -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 (
<div key={`${row.kind}:${row.seq}`} className={css.sidechatTurnSummary}>
<div key={key} className={css.sidechatTurnSummary}>
{parts.join(' · ')}
</div>
)
Expand Down Expand Up @@ -607,7 +609,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu
)
return (
<CollapsibleRow
key={`${row.kind}:${row.seq}`}
key={key}
label={row.name}
meta={toolArgsSummary(row.args)}
icon={toolLeading(row.name, row.failed)}
Expand Down Expand Up @@ -900,13 +902,15 @@ export function SideChatView(props: {
* (first attach = the whole seed-cut slice; polls = afterSeq deltas),
* merged by seq. */
const fetchThread = useCallback(async (childId: string): Promise<void> => {
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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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
},
Expand Down Expand Up @@ -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<void> => {
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<void> => {
const text = composer.trim()
if (text === '' || threadId === undefined || busy !== null) return
Expand Down Expand Up @@ -1387,12 +1420,12 @@ export function SideChatView(props: {
onReconnect={() => { ctx.connection?.reconnect() }}
/>
)}
<div ref={transcriptRef} className={css.sidechatScroll}>
<div ref={transcriptRef} className={css.sidechatScroll} data-genui-surface="dsh-better-sidebar/sidechat">
{/* 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. */}
<MarkdownDelegateProvider openFile={openChatFile}>
{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. */}
Expand Down
53 changes: 53 additions & 0 deletions src/client/SidechatAssistantRow.tsx
Original file line number Diff line number Diff line change
@@ -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<void>
}

export function SidechatAssistantRow(props: {
row: Extract<SidechatTranscriptRow, { kind: 'assistant' }>
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<SidechatTranscriptRow, { text: string }>) => string
surface: SidechatRowSurfaceBinding
}): React.ReactNode {
const rootRef = useRef<HTMLDivElement | null>(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 (
<div ref={rootRef} className={css.sidechatAssistant} data-genui-surface="dsh-better-sidebar/sidechat">
{/* `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. */}
<MarkdownText {...markdownTextProps(renderedText, labels)} streaming={!row.settled} />
</div>
)
}
2 changes: 2 additions & 0 deletions src/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down
9 changes: 8 additions & 1 deletion src/client/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -1474,6 +1479,8 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
nativePathTabs: () => surface?.pathTabs?.() ?? [],
clearUnread: clearUnreadFor,
}
const registerSidechatSurfaceAdapter = bindSidechatSurfaces(service)
return service
}

/**
Expand Down
Loading