* fix(subagent): 子代理页实时预览改为批量接口,避免 O(N²) history 请求风暴
## 背景
DSH Web UI 中,当主代理同时运行多个子代理时,`dsh-better-sidebar` 的「任务管理/子代理」页面会出现明显卡顿。经调查,卡顿根因不在页面渲染,而在实时预览的请求模式。
## 根因
旧实现中,每个 running 子代理卡片都独立轮询 `subagents.history`:
- N 个 running 子代理 → 每 3 秒产生 N 次 `subagents.history` 请求;
- 每次 `subagents.history` 都会在 host 侧触发一次完整的 `listChildren` 全量子代理目录枚举;
- 子代理数量越多,服务端重复扫描越严重,近似 O(N²) 放大;
- 请求超过 3 秒时,客户端还会 abort 旧请求并重发,进一步形成请求风暴。
## 改动内容
1. **新增 host 批量接口 `POST /sidebar/api/subagents.live`**
- 请求 `{ rootSessionId }`;
- 通过 `ctx.subagents.listDescendants(rootSessionId)` 一次枚举整棵子代理树;
- 仅对 running 且非 Side Chat 的子代理,从 session events 尾部提取最新 `text/tool` 活动;
- 返回 `{ live: Record<childId, { text?, tool? }> }`;
- 缺 `subagents`/`agents` 服务或枚举失败时返回 503;单个子代理日志异常只跳过该子代理。
2. **客户端改为单轮询 + 单飞行请求**
- 删除每个 running 子代理独立的 `subagents.history` 定时器;
- 在 `SubagentView` 中合并为一个 `useSubagentLive` 轮询 hook;
- 使用递归 `setTimeout` 和单在途请求,慢请求不再被 abort/重发;
- 页面隐藏或 root 变化时停止轮询并中止在途请求。
3. **解析器优化**
- `lastActivity` 改为接收原始 `SidebarSessionEvent[]`;
- 从事件尾部向前扫描,找到最新 text 和 tool 后提前停止,避免复制/遍历完整历史。
4. **UI 保持不变**
- 实时预览的展示逻辑、文案、截断规则均未改变。
## 测试
- 新增 `tests/subagent-live-route.spec.ts`:覆盖批量接口成功聚合、只返回 running、跳过 Side Chat、缺服务 503、枚举失败 503、`ctx.get` 回退、bad-request。
- 新增 `tests/subagent-live-polling.spec.tsx`:覆盖每轮只发 1 次 `subagents.live`、不再调用 `subagents.history`、单在途不并发。
- 更新 `tests/subagent-activity.spec.ts` 与 `tests/subagent-jobs-view.spec.tsx`。
- `pnpm typecheck` ✅
- `pnpm build` ✅
- 相关测试 29 个全部通过 ✅
> 本机完整 `pnpm test` 仍有与本改动无关的环境性失败(node-pty 超时、Windows CRLF 断言、pty-deps 路径断言),不影响本 PR 逻辑。
* fix(subagent): live 预览以 catalog activity 为准,删除 agents 第二事实源 (#298)
- host 路由 running 门改回 entry.activity === 'running'(与客户端卡片渲染门一致),
恢复 PR 承诺的 UI 不变:turn 间 idle 的 continuable 子代理仍显示最后活动
- 删除 ctx.agents 依赖与 SidebarAgent.status 新增(agents 缺失时不再静默 200 空 map;
503 契约收窄为只涉及 subagents,与文档/测试一致)
- service 解析统一为 ctx.get('subagents')(兄弟路由惯例;插件未 inject subagents,
直接属性访问有抛错风险)
- buildSubagentLiveApi 签名改收完整 Context,删除 SidebarSubagentLiveContext 窄接口
- api.ts 复用 LastActivity,删除重复类型 SubagentLiveEntry
- 测试:route spec 删除 agents 相关用例;polling spec 新增页面隐藏停止轮询、
root 变化清空 live 并重启轮询两个用例
* fix(subagent): live 预览恢复最近 12 条消息窗口,排除陈旧活动 (#298)
CR 反馈:新批量接口把完整 session event log 喂给 lastActivity,
- 长时间只输出文本、早期调用过工具的 running 子代理会持续显示陈旧 tool
- 无 tool 的长会话每次轮询反向扫描整个事件数组,重新引入与历史长度
相关的 CPU 成本
修复(与旧 subagents.history({ maxMessages: 12 }) 窗口语义一致):
- lastActivity 增加可选 maxMessages 参数:反向扫描按表面消息
(user/message + assistant/message)计数,窗口满后更老事件一律跳过
- 路由传 LIVE_WINDOW_MESSAGES = 12(导出常量)
- 回归测试:窗口外旧 tool 不返回;窗口内 tool 保留;非消息事件不消耗配额
---------
Co-authored-by: Menghuan1918 <menghuan2003@outlook.com>
283 lines
10 KiB
TypeScript
283 lines
10 KiB
TypeScript
/**
|
|
* Component-level regression for the Subagent page live preview polling:
|
|
* one shared `subagents.live` request per refresh, never a per-child
|
|
* `subagents.history` call, and never a second in-flight request while a
|
|
* slow host is still answering.
|
|
*/
|
|
// @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 { SubagentView } from '../src/client/SubagentView.tsx'
|
|
import type { Context, SidebarSessionList } from '../src/context-types.ts'
|
|
|
|
/** A subscribable sessions-list snapshot (mirror of the runtime list feed). */
|
|
function makeStore(initial: SidebarSessionList) {
|
|
let snapshot = initial
|
|
const listeners = new Set<() => void>()
|
|
return {
|
|
getSnapshot: () => snapshot,
|
|
subscribe: (fn: () => void) => {
|
|
listeners.add(fn)
|
|
return () => { listeners.delete(fn) }
|
|
},
|
|
set(next: SidebarSessionList) {
|
|
snapshot = next
|
|
for (const fn of [...listeners]) fn()
|
|
},
|
|
}
|
|
}
|
|
|
|
type Store = ReturnType<typeof makeStore>
|
|
|
|
/** The client context face SubagentView touches; history is spied for the
|
|
* regression assertion (the new page must never call it). */
|
|
function makeCtx(store: Store, historySpy: ReturnType<typeof vi.fn>): Context {
|
|
return {
|
|
sessions: {
|
|
list: store,
|
|
setSubagentCatalogOpen: () => {},
|
|
openSubagent: () => {},
|
|
open: () => {},
|
|
refreshSubagents: async () => {},
|
|
},
|
|
connection: {
|
|
api: {
|
|
sessions: { history: historySpy },
|
|
subagents: { history: historySpy },
|
|
},
|
|
},
|
|
} as unknown as Context
|
|
}
|
|
|
|
/** Render `node` into a detached body container under React's act(). */
|
|
function mount(node: ReactNode): {
|
|
container: HTMLDivElement
|
|
rerender: (next: ReactNode) => void
|
|
unmount: () => void
|
|
} {
|
|
const container = document.createElement('div')
|
|
document.body.append(container)
|
|
const root: Root = createRoot(container)
|
|
const rerender = (next: ReactNode): void => { act(() => { root.render(next) }) }
|
|
act(() => { root.render(node) })
|
|
const unmount = (): void => {
|
|
act(() => { root.unmount() })
|
|
container.remove()
|
|
}
|
|
return { container, rerender, unmount }
|
|
}
|
|
|
|
function jsonResponse(value: unknown): Response {
|
|
return { ok: true, status: 200, json: async () => value } as unknown as Response
|
|
}
|
|
|
|
/** A topology snapshot with two running direct subagents and a ready catalog. */
|
|
function runningSnapshot(): SidebarSessionList {
|
|
return {
|
|
current: 'root',
|
|
byId: {
|
|
root: { id: 'root', displayTitle: '主会话' },
|
|
a: { id: 'a', displayTitle: 'A', origin: 'subagent', parentId: 'root', running: true },
|
|
b: { id: 'b', displayTitle: 'B', origin: 'subagent', parentId: 'root', running: true },
|
|
},
|
|
subagentsByParent: {
|
|
root: {
|
|
entries: [
|
|
{ kind: 'child', id: 'a', activity: 'running', hasChildren: false, mode: 'one-shot', label: 'A' },
|
|
{ kind: 'child', id: 'b', activity: 'running', hasChildren: false, mode: 'one-shot', label: 'B' },
|
|
],
|
|
parentAvailable: true,
|
|
state: 'ready',
|
|
error: null,
|
|
},
|
|
},
|
|
jobsBySession: {},
|
|
}
|
|
}
|
|
|
|
/** The same tree re-rooted under a new ancestor ('grand' becomes the root). */
|
|
function reRootedSnapshot(): SidebarSessionList {
|
|
return {
|
|
current: 'root',
|
|
byId: {
|
|
grand: { id: 'grand', displayTitle: '主会话' },
|
|
root: { id: 'root', displayTitle: 'R', origin: 'subagent', parentId: 'grand', running: true },
|
|
a: { id: 'a', displayTitle: 'A', origin: 'subagent', parentId: 'root', running: true },
|
|
b: { id: 'b', displayTitle: 'B', origin: 'subagent', parentId: 'root', running: true },
|
|
},
|
|
subagentsByParent: {
|
|
grand: {
|
|
entries: [
|
|
{ kind: 'child', id: 'root', activity: 'running', hasChildren: true, mode: 'continuable', label: 'R' },
|
|
],
|
|
parentAvailable: true,
|
|
state: 'ready',
|
|
error: null,
|
|
},
|
|
root: {
|
|
entries: [
|
|
{ kind: 'child', id: 'a', activity: 'running', hasChildren: false, mode: 'one-shot', label: 'A' },
|
|
{ kind: 'child', id: 'b', activity: 'running', hasChildren: false, mode: 'one-shot', label: 'B' },
|
|
],
|
|
parentAvailable: true,
|
|
state: 'ready',
|
|
error: null,
|
|
},
|
|
},
|
|
jobsBySession: {},
|
|
}
|
|
}
|
|
|
|
beforeEach(() => {
|
|
Object.defineProperty(globalThis.navigator, 'language', { value: 'zh-CN', configurable: true })
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
vi.useRealTimers()
|
|
for (const el of document.querySelectorAll('body > div')) el.remove()
|
|
})
|
|
|
|
describe('SubagentView live polling', () => {
|
|
it('sends one subagents.live per poll and never calls per-child history', async () => {
|
|
vi.useFakeTimers()
|
|
const historySpy = vi.fn()
|
|
const liveCalls: string[] = []
|
|
vi.stubGlobal('fetch', async (url: string | URL | Request, init?: RequestInit) => {
|
|
const method = String(url).split('/').pop()
|
|
if (method === 'subagents.live') {
|
|
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
|
|
liveCalls.push(body.rootSessionId ?? '')
|
|
return jsonResponse({ ok: true, value: { live: {} } })
|
|
}
|
|
throw new Error(`unexpected fetch ${String(url)}`)
|
|
})
|
|
|
|
const store = makeStore(runningSnapshot())
|
|
const { container, unmount } = mount(
|
|
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
|
|
)
|
|
// Initial load plus the first scheduled tick.
|
|
await act(async () => { await Promise.resolve() })
|
|
expect(liveCalls).toEqual(['root'])
|
|
expect(historySpy).not.toHaveBeenCalled()
|
|
expect(container.textContent).toContain('思考中…')
|
|
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(3_000) })
|
|
expect(liveCalls).toEqual(['root', 'root'])
|
|
expect(historySpy).not.toHaveBeenCalled()
|
|
unmount()
|
|
})
|
|
|
|
it('never starts a second request while one is in flight', async () => {
|
|
vi.useFakeTimers()
|
|
const historySpy = vi.fn()
|
|
const liveCalls: string[] = []
|
|
let resolveFirst: ((response: Response) => void) | undefined
|
|
vi.stubGlobal('fetch', (url: string | URL | Request, init?: RequestInit) => {
|
|
const method = String(url).split('/').pop()
|
|
if (method === 'subagents.live') {
|
|
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
|
|
liveCalls.push(body.rootSessionId ?? '')
|
|
return new Promise<Response>((resolve) => { resolveFirst = resolve })
|
|
}
|
|
throw new Error(`unexpected fetch ${String(url)}`)
|
|
})
|
|
|
|
const store = makeStore(runningSnapshot())
|
|
const { unmount } = mount(
|
|
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
|
|
)
|
|
await act(async () => { await Promise.resolve() })
|
|
expect(liveCalls).toEqual(['root'])
|
|
expect(resolveFirst).toBeTypeOf('function')
|
|
|
|
// While the first request is pending, no timer can fire a second one.
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
|
|
expect(liveCalls).toEqual(['root'])
|
|
|
|
// Settle the first request; only then does the next 3s tick fire.
|
|
await act(async () => {
|
|
resolveFirst?.(jsonResponse({ ok: true, value: { live: {} } }))
|
|
await Promise.resolve()
|
|
})
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(3_000) })
|
|
expect(liveCalls).toEqual(['root', 'root'])
|
|
expect(historySpy).not.toHaveBeenCalled()
|
|
unmount()
|
|
})
|
|
|
|
it('stops polling and drops the in-flight request when the page hides', async () => {
|
|
vi.useFakeTimers()
|
|
const historySpy = vi.fn()
|
|
const liveCalls: string[] = []
|
|
let resolveFirst: ((response: Response) => void) | undefined
|
|
vi.stubGlobal('fetch', (url: string | URL | Request, init?: RequestInit) => {
|
|
const method = String(url).split('/').pop()
|
|
if (method === 'subagents.live') {
|
|
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
|
|
liveCalls.push(body.rootSessionId ?? '')
|
|
return new Promise<Response>((resolve) => { resolveFirst = resolve })
|
|
}
|
|
throw new Error(`unexpected fetch ${String(url)}`)
|
|
})
|
|
|
|
const store = makeStore(runningSnapshot())
|
|
const { rerender, unmount } = mount(
|
|
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
|
|
)
|
|
await act(async () => { await Promise.resolve() })
|
|
expect(liveCalls).toEqual(['root'])
|
|
|
|
// Hide the page: the effect cleanup aborts the in-flight request and no
|
|
// timer may fire afterwards.
|
|
rerender(createElement(SubagentView, { sessionId: 'root', active: false, ctx: makeCtx(store, historySpy) }))
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
|
|
expect(liveCalls).toEqual(['root'])
|
|
|
|
// Settling the stale response must neither render nor schedule a poll.
|
|
await act(async () => {
|
|
resolveFirst?.(jsonResponse({ ok: true, value: { live: { a: { text: 'stale' } } } }))
|
|
await Promise.resolve()
|
|
})
|
|
await act(async () => { await vi.advanceTimersByTimeAsync(10_000) })
|
|
expect(liveCalls).toEqual(['root'])
|
|
expect(historySpy).not.toHaveBeenCalled()
|
|
unmount()
|
|
})
|
|
|
|
it('clears the live map and re-polls when the topology root changes', async () => {
|
|
vi.useFakeTimers()
|
|
const historySpy = vi.fn()
|
|
const liveCalls: string[] = []
|
|
vi.stubGlobal('fetch', async (url: string | URL | Request, init?: RequestInit) => {
|
|
const method = String(url).split('/').pop()
|
|
if (method === 'subagents.live') {
|
|
const body = JSON.parse(String(init?.body)) as { rootSessionId?: string }
|
|
liveCalls.push(body.rootSessionId ?? '')
|
|
const live = body.rootSessionId === 'root' ? { a: { text: 'hello' } } : {}
|
|
return jsonResponse({ ok: true, value: { live } })
|
|
}
|
|
throw new Error(`unexpected fetch ${String(url)}`)
|
|
})
|
|
|
|
const store = makeStore(runningSnapshot())
|
|
const { container, unmount } = mount(
|
|
createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store, historySpy) }),
|
|
)
|
|
await act(async () => { await Promise.resolve() })
|
|
expect(liveCalls).toEqual(['root'])
|
|
expect(container.textContent).toContain('hello')
|
|
|
|
// The tree is re-rooted under a new ancestor: old rows must not leak.
|
|
store.set(reRootedSnapshot())
|
|
await act(async () => { await Promise.resolve() })
|
|
expect(liveCalls).toEqual(['root', 'grand'])
|
|
expect(container.textContent).not.toContain('hello')
|
|
expect(historySpy).not.toHaveBeenCalled()
|
|
unmount()
|
|
})
|
|
})
|