Files
apes-sidebar/tests/use-sidechat-push.spec.ts
T
Menghuan1918 5330eab474 feat(sidechat): 实时推送 + 排队可见 + per-thread 模型选择 + 底栏重构
侧边对话的四处用户痛点,加上「实时 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 通道。
2026-10-12 00:56:34 +08:00

166 lines
6.0 KiB
TypeScript

/**
* The client half of the Side Chat staleness push: one socket per mounted
* tab, opened under `/sidebar/ws/sidechat`, whose `watch` frames carry the
* WHOLE subscription set (a replacement, never an incremental add), whose
* notices are routed to `onInvalidate` for WATCHED ids only, and which does
* not exist at all while the id list is empty.
*
* The identity guard mirrors the fs-watch hook's: the wanted set derives from
* the CONTENT of the id list (a NUL-joined key), so a caller re-rendering
* with a fresh array of the same ids neither reopens the socket nor re-sends
* the watch frame.
*/
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement, type ReactNode } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { useSidechatPush } from '../src/client/use-sidechat-push.ts'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
/** The smallest WebSocket the hook talks to: `send` records the frames. */
class FakeSocket {
static instances: FakeSocket[] = []
static readonly OPEN = 1
static readonly CONNECTING = 0
readonly url: string
readyState = FakeSocket.CONNECTING
sent: string[] = []
onopen: (() => void) | null = null
onmessage: ((event: { data: string }) => void) | null = null
onclose: (() => void) | null = null
closed = false
constructor(url: string) {
this.url = url
FakeSocket.instances.push(this)
}
send(frame: string): void { this.sent.push(frame) }
close(): void { this.closed = true; this.readyState = 3 }
/** The host's connection acknowledgement. */
open(): void { this.readyState = FakeSocket.OPEN; this.onopen?.() }
/** One host frame (an invalidation notice, or something malformed). */
frame(payload: unknown): void { this.onmessage?.({ data: JSON.stringify(payload) }) }
/** The frames the hook sent, as parsed objects. */
frames(): { op: string; threadIds: string[] }[] {
return this.sent.map(frame => JSON.parse(frame) as { op: string; threadIds: string[] })
}
}
function Probe(props: { threadIds: string[]; onInvalidate: (id: string) => void }): ReactNode {
useSidechatPush({ threadIds: props.threadIds, onInvalidate: props.onInvalidate })
return null
}
interface Harness {
rerender: (threadIds: string[]) => void
/** The single open socket; throws when the list was empty. */
socket: () => FakeSocket
unmount: () => void
}
function mountProbe(onInvalidate: (id: string) => void, initial: string[] = ['t1']): Harness {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
const render = (threadIds: string[]): void => { root.render(createElement(Probe, { threadIds, onInvalidate })) }
act(() => { render(initial) })
return {
rerender: (threadIds: string[]) => { act(() => { render(threadIds) }) },
socket: () => {
const socket = FakeSocket.instances[0]
if (socket === undefined) throw new Error('no socket opened')
return socket
},
unmount: () => { act(() => { root.unmount() }); container.remove() },
}
}
beforeEach(() => {
FakeSocket.instances = []
vi.stubGlobal('WebSocket', FakeSocket)
})
afterEach(() => {
document.body.innerHTML = ''
vi.unstubAllGlobals()
})
describe('useSidechatPush', () => {
it('opens the sidechat socket and announces the watched ids once it opens', () => {
const harness = mountProbe(() => {})
const socket = harness.socket()
expect(socket.url).toContain('/sidebar/ws/sidechat')
// Nothing is sent before the connection opens.
expect(socket.sent).toEqual([])
act(() => { socket.open() })
expect(socket.frames()).toEqual([{ op: 'watch', threadIds: ['t1'] }])
harness.unmount()
})
it('re-announces the full set on the SAME socket when the ids change', () => {
const harness = mountProbe(() => {})
const socket = harness.socket()
act(() => { socket.open() })
harness.rerender(['t1', 't2'])
expect(FakeSocket.instances).toHaveLength(1)
expect(socket.frames().at(-1)).toEqual({ op: 'watch', threadIds: ['t1', 't2'] })
harness.unmount()
})
it('sends nothing when a re-render repeats the same ids in a fresh array', () => {
const harness = mountProbe(() => {})
const socket = harness.socket()
act(() => { socket.open() })
const before = socket.sent.length
harness.rerender(['t1'])
expect(FakeSocket.instances).toHaveLength(1)
expect(socket.sent.length).toBe(before)
harness.unmount()
})
it('invalidates a watched id and ignores everything else', () => {
const onInvalidate = vi.fn()
const harness = mountProbe(onInvalidate)
const socket = harness.socket()
act(() => { socket.open() })
// A thread this socket does not watch (a late notice after a switch).
act(() => { socket.frame({ threadId: 't9' }) })
expect(onInvalidate).not.toHaveBeenCalled()
// A malformed frame is ignored outright.
act(() => { socket.frame({ nope: 1 }) })
expect(onInvalidate).not.toHaveBeenCalled()
// The notice is an invalidation: `running` rides along but changes nothing.
act(() => { socket.frame({ threadId: 't1', running: true }) })
expect(onInvalidate).toHaveBeenCalledWith('t1')
expect(onInvalidate).toHaveBeenCalledTimes(1)
harness.unmount()
})
it('opens no socket while the list is empty, and closes it when the list empties', () => {
const harness = mountProbe(() => {}, [])
expect(FakeSocket.instances).toHaveLength(0)
harness.rerender(['t1'])
const socket = harness.socket()
act(() => { socket.open() })
expect(socket.frames()).toEqual([{ op: 'watch', threadIds: ['t1'] }])
harness.rerender([])
expect(socket.closed).toBe(true)
expect(FakeSocket.instances).toHaveLength(1)
harness.unmount()
})
it('closes the socket on unmount', () => {
const harness = mountProbe(() => {})
const socket = harness.socket()
act(() => { socket.open() })
harness.unmount()
expect(socket.closed).toBe(true)
})
})