侧边对话的四处用户痛点,加上「实时 fork」与「隐藏会话」两条路线的可行性结论。
全部结论都有真机复现取证(在运行中的宿主上建线程 + 读真实 session 日志)。
- 排队信息漏入:create 的 `inbox.clear()` 围栏确实生效(真机复现:子会话
request 只有 [boundary, 问题]);但幽灵来源比文档更宽——父会话 mid-turn 且
工具未返回时,种子被截断在 `turn/start` 之前,而 inbox 的「领取」splice 发生
在其后,于是**父会话本轮已领取的输入**在种子折叠里仍是 pending;而冷恢复
路径完全没有围栏。修法:create 保留硬围栏(本线程自己不可能有排队输入),
resume 改为 `inheritedPendingIds` 只折继承前缀得到幽灵 id → `inbox.remove(id)`
精确清扫,绝不误杀用户自己排的队。
- 消息不及时:新增 `/sidebar/ws/sidechat` 推送(`session/event` 60ms、
`agent/assistant-stream` 250ms 去抖,**纯失效帧**,客户端带 afterSeq 重拉),
2s 轮询降级为 15s 兜底,断线自愈。
- 模型选不了:宿主对 `origin:'subagent'` 会话**显式禁用**自带选择器,
`sessionController.selectModel` 又被 subagent fence 挡;插件因此自建
`sidechat.models`(直通宿主模型目录)与 `sidechat.model`(append
`model/selection` + `installModelSelection`),并让 `sidechat.info` 报**有效**
选择而不是冻结的创建期 options。
- 排队可见 / 回显 / spinner / 错误行:`sidechat.events` 增返 `pending`(claim
顺序)、`sidechat.dequeue` 按 id 撤销或清空、发送即本地回显、立即 thinking
行、`turn/end{error}` 与失败 attempt 渲染成可见错误行;另修掉「首问未 claim
时连发第二条会注入第二对 boundary+question」(新增 `boundaryPending`)。
- 底栏重构(用户反馈「注意力全在底栏,看不到上栏的保存为新会话」):顶栏整条
删除,`[+新建][线程][保存][归档] … [模型选择器][发送/停止]` 与主会话底栏对齐
(图标靠左、选择器靠右完整显示,agent 徽标不再显示);推理强度改为**平铺行**
——宿主 `Menu` 的 submenu 只能开在父项右侧(无翻转开关)且会让整个面板失去
滚动,钉在侧栏右缘必然被裁;每个控件加宿主 `Tooltip` 悬停气泡(锚在启用的
span 上,禁用态才解释得了「为什么不能点」),替代原生 title。
设计文档:docs/plans/2026-10-12-sidechat-native-surface.md(含取证、判定、
实施偏差与未验证项);AGENTS §3.4 第 4/10 条同步。
门禁:`tsc --noEmit` / `eslint .` / `vitest run`(2268 passed / 17 skipped)全绿;
宿主半 build + pack 后真实挂载进 sidechat-test profile 并验证新路由与 WS 通道。
168 lines
6.2 KiB
TypeScript
168 lines
6.2 KiB
TypeScript
/**
|
|
* Side-chat live push behind `/sidebar/ws/sidechat`.
|
|
*
|
|
* The side-chat transcript used to learn about new rows only by polling
|
|
* `sidechat.events` every 2s while the thread ran, so a streaming answer, the
|
|
* claim of a just-sent message, or a finished tool call could sit invisible for
|
|
* up to two seconds. The host already knows the moment either happens: the
|
|
* session append feed (`session/event`) carries every durable row, and the
|
|
* process-local `agent/assistant-stream` frames carry in-flight model deltas
|
|
* (they are deliberately NOT logged — see assistant-live.ts).
|
|
*
|
|
* This hub turns both feeds into per-thread INVALIDATION notices. A notice
|
|
* never carries event bodies: the client re-pulls `sidechat.events` with its
|
|
* `afterSeq`, so the transcript transport, its tail cap and its delta logic are
|
|
* unchanged, a dropped socket self-heals, and there is exactly one source of
|
|
* truth for what a thread contains.
|
|
*
|
|
* Two coalescing windows, shortest first: a durable append is worth telling the
|
|
* reader about almost immediately (60ms), while stream deltas arrive tens of
|
|
* times a second and are folded into one notice per 250ms — each notice costs
|
|
* the client a pull that re-sends the CURRENT attempt's chunks, so faster would
|
|
* only burn bandwidth.
|
|
* @module dsh-better-sidebar/sidechat-push
|
|
*/
|
|
import type { WebSocket } from 'ws'
|
|
import type { Context } from './context-types.ts'
|
|
|
|
/** Coalescing window for durable session appends. */
|
|
const DURABLE_DEBOUNCE_MS = 60
|
|
/** Coalescing window for in-flight model deltas. */
|
|
const STREAM_DEBOUNCE_MS = 250
|
|
/** Thread ids one socket may watch (a resource guard, not a policy). */
|
|
const MAX_WATCHED = 64
|
|
|
|
/** One frame the host pushes: the thread whose transcript is stale. */
|
|
export interface SidechatPushFrame {
|
|
threadId: string
|
|
}
|
|
|
|
/** The frame the client sends to replace its watch set. */
|
|
interface WatchFrame {
|
|
op?: unknown
|
|
threadIds?: unknown
|
|
}
|
|
|
|
/** The host-side push hub: one set of feeds, any number of sockets. */
|
|
export interface SidechatPushHub {
|
|
/** Attach one accepted socket (reads its watch frames, pushes notices). */
|
|
attach(ws: WebSocket): void
|
|
/** Release the session feeds (socket teardown stays with the server). */
|
|
dispose(): void
|
|
}
|
|
|
|
/**
|
|
* Register the side-chat push feeds.
|
|
* @param ctx - host plugin context (its `on` subscribes the append feed).
|
|
* @returns the hub plus a disposer unbinding both listeners.
|
|
*/
|
|
export function createSidechatPushHub(ctx: Context): SidechatPushHub {
|
|
const sockets = new Set<SidechatSocket>()
|
|
if (typeof ctx.on !== 'function') {
|
|
// Test doubles without the event API still accept sockets, which then
|
|
// simply never hear anything.
|
|
return { attach: () => {}, dispose: () => {} }
|
|
}
|
|
const offEvent = ctx.on('session/event', (session) => {
|
|
const sessionId = (session as { id?: unknown } | null)?.id
|
|
if (typeof sessionId !== 'string') return
|
|
for (const socket of sockets) socket.notify(sessionId, DURABLE_DEBOUNCE_MS)
|
|
})
|
|
const offStream = ctx.on('agent/assistant-stream', (payload) => {
|
|
const record = payload as { agent?: unknown } | null
|
|
const session = (record?.agent as { session?: { id?: unknown } } | undefined)?.session
|
|
const sessionId = typeof session?.id === 'string' ? session.id : undefined
|
|
if (sessionId === undefined) return
|
|
for (const socket of sockets) socket.notify(sessionId, STREAM_DEBOUNCE_MS)
|
|
})
|
|
return {
|
|
attach: (ws) => {
|
|
const socket = new SidechatSocket(ws, () => { sockets.delete(socket) })
|
|
sockets.add(socket)
|
|
},
|
|
dispose: () => {
|
|
offEvent()
|
|
offStream()
|
|
for (const socket of sockets) socket.close()
|
|
sockets.clear()
|
|
},
|
|
}
|
|
}
|
|
|
|
/** One attached socket's watch set and per-thread coalescing timers. */
|
|
class SidechatSocket {
|
|
private readonly socket: WebSocket
|
|
private readonly onClosed: () => void
|
|
private readonly watched = new Set<string>()
|
|
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>()
|
|
private closed = false
|
|
|
|
/**
|
|
* @param socket - the accepted WebSocket.
|
|
* @param onClosed - hub-side cleanup (idempotent).
|
|
*/
|
|
constructor(socket: WebSocket, onClosed: () => void) {
|
|
this.socket = socket
|
|
this.onClosed = onClosed
|
|
socket.on('message', (data: unknown) => { this.onMessage(data) })
|
|
socket.on('close', () => { this.close() })
|
|
socket.on('error', () => { this.close() })
|
|
}
|
|
|
|
/** Apply one client frame (an unparseable frame is ignored, never fatal). */
|
|
private onMessage(data: unknown): void {
|
|
let frame: WatchFrame
|
|
try {
|
|
frame = JSON.parse(typeof data === 'string' ? data : String(data)) as WatchFrame
|
|
} catch {
|
|
return
|
|
}
|
|
if (frame === null || typeof frame !== 'object' || frame.op !== 'watch') return
|
|
const ids = Array.isArray(frame.threadIds)
|
|
? frame.threadIds.filter((id): id is string => typeof id === 'string' && id !== '')
|
|
: []
|
|
this.watched.clear()
|
|
for (const id of ids.slice(0, MAX_WATCHED)) this.watched.add(id)
|
|
// Threads no longer watched drop their pending notice with their timer.
|
|
for (const [id, timer] of this.timers) {
|
|
if (this.watched.has(id)) continue
|
|
clearTimeout(timer)
|
|
this.timers.delete(id)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Coalesce one notice for a thread. The FIRST trigger's window wins, so a
|
|
* burst of deltas never postpones the notice it already scheduled.
|
|
* @param threadId - the session whose transcript is stale.
|
|
* @param delayMs - coalescing window for this trigger.
|
|
*/
|
|
notify(threadId: string, delayMs: number): void {
|
|
if (this.closed || !this.watched.has(threadId) || this.timers.has(threadId)) return
|
|
this.timers.set(threadId, setTimeout(() => {
|
|
this.timers.delete(threadId)
|
|
this.send({ threadId })
|
|
}, delayMs))
|
|
}
|
|
|
|
/** Push one notice (silently dropped once the socket is gone). */
|
|
private send(frame: SidechatPushFrame): void {
|
|
if (this.closed) return
|
|
try {
|
|
this.socket.send(JSON.stringify(frame))
|
|
} catch {
|
|
// A send on a dying socket is expected; the close handler cleans up.
|
|
}
|
|
}
|
|
|
|
/** Release every timer and de-register (idempotent). */
|
|
close(): void {
|
|
if (this.closed) return
|
|
this.closed = true
|
|
for (const timer of this.timers.values()) clearTimeout(timer)
|
|
this.timers.clear()
|
|
this.watched.clear()
|
|
this.onClosed()
|
|
}
|
|
}
|