Files
apes-sidebar/tests/subagent-live-polling.spec.tsx
T
Menghuan1918 a454cfc9fe refactor(tasks): 移植主 Agent 同款合并活动折叠(数据层)
把上一轮验证过的数据层搬到工作图基座上,图/树两种模式共用:

- 新增 src/process-activity.ts:宿主 ui-chat 的 process group 算法移植
  (activity() 分类表逐条照抄、liveToolDetail 键优先级与 160 字截断、
  counts 计数排序与并列规则、preparing 语义、按 user/reply 边界切范围)。
  按本轮设计裁剪掉逐阶段列表(阶段改由徽标 + 颜色表达)。新增一条
  偏差:最新范围为空(子代理刚回复完)时回退到上一个「做过事」的范围,
  否则已结算卡片的小条只会显示「已完成分析」。
- chatT:从宿主 chat 命名空间读 message.stepProcess.* 措辞(方法调用 +
  try/catch 兜底,key 未命中即回退),4 个回归用例钉住「不许解绑 bind」。
- subagents.live 载荷换新:SidebarChildLiveView { running?, text?, summary?,
  lastEventTime? },报告树内每个子节点(含已结算)与拓扑根;删除
  expand/stages 机制;childActivity → childLive(「不在 map 里 = 未运行」
  的读法随旧协议一起作废)。
- tasks-model 消费新形状;LiveLine 与节点详情浮窗改显示合并活动措辞。
- 删除 src/subagent-activity.ts 与 tests/subagent-activity.spec.ts。

验证:typecheck / lint 通过;pnpm test 1252 passed / 9 skipped。

(cherry picked from commit 5e5284f214846b0c366048acbee459f3a7a79456)
2026-09-27 22:18:35 +08:00

262 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 } from 'react'
import { act } from 'react-dom/test-utils'
import { renderRoot } from './test-utils.ts'
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,
openSubagent: () => {},
open: () => {},
},
connection: {
api: {
sessions: { history: historySpy },
subagents: { history: historySpy },
},
},
} as unknown as Context
}
function jsonResponse(value: unknown): Response {
return { ok: true, status: 200, json: async () => value } as unknown as Response
}
/** One `subagentCatalog` projection row (DSH 0.1.7 shape). */
function entry(
id: string,
mode: 'one-shot' | 'continuable' | 'unknown',
label?: string,
): { id: string; createdAt: number; mode: 'one-shot' | 'continuable' | 'unknown'; label?: string } {
return { id, createdAt: 1_000, mode, ...(label === undefined ? {} : { label }) }
}
/** One session's loaded projection snapshot. */
function ready(entries: ReturnType<typeof entry>[]) {
return { values: { subagentCatalog: entries }, state: 'ready' as const, error: null }
}
/**
* A topology snapshot with two direct subagents and their catalogs. The rows
* carry no activity of their own any more: the live channel below is what
* marks a child running.
*/
function runningSnapshot(): SidebarSessionList {
return {
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 },
},
projectionsBySession: {
root: ready([entry('a', 'one-shot', 'A'), entry('b', 'one-shot', 'B')]),
a: ready([]),
b: ready([]),
},
}
}
/** The same tree re-rooted under a new ancestor ('grand' becomes the root). */
function reRootedSnapshot(): SidebarSessionList {
return {
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 },
},
projectionsBySession: {
grand: ready([entry('root', 'continuable', 'R')]),
root: ready([entry('a', 'one-shot', 'A'), entry('b', 'one-shot', 'B')]),
a: ready([]),
b: ready([]),
},
}
}
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: { a: { running: true }, b: { running: true } } } })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { container, unmount } = renderRoot(
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 })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { unmount } = renderRoot(
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: { a: { running: true }, b: { running: true } } } }))
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 })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { rerender, unmount } = renderRoot(
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: { running: true, 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: { running: true, text: 'hello' } } : {}
return jsonResponse({ ok: true, value: { live } })
}
if (method === 'jobs.list') return jsonResponse({ ok: true, value: { jobs: [] } })
throw new Error(`unexpected fetch ${String(url)}`)
})
const store = makeStore(runningSnapshot())
const { container, unmount } = renderRoot(
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()
})
})