import { describe, test, expect, beforeEach, afterEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' import { setLocale } from '../../web/src/lib/i18n' import { createElement } from 'react' import { renderToString } from 'react-dom/server' /** * 跨包链路拼接测试 — 后台任务事件的完整闭环: * * REPL worker(enqueueSdkEvent 旁路 / writeSdkMessages) * → 服务端 ingestBridgeMessage(真实实现) * → publishSessionEvent → EventBus(真实事件,normalizePayload 形状) * → web RCSChatAdapter.handleEvent(实时 SSE 路径) * → web RCSChatAdapter.loadHistory(刷新回放路径) * → BackgroundTasksSection 渲染(Session Ops 侧边栏) * * 背景:交互式 REPL 的 enqueueSdkEvent 不入队(只有 headless print.ts 循环 * drain),事件靠 useReplBridge 注册的 listener 旁路上 wire。此测试固定 * 「REPL 发出的原始 SDK 消息形状 → web 面板渲染」每一环真实可用,任何 * 一环(服务端字段丢失、web fold 不识别、渲染退化)都会在这里失败。 */ // Mock config before RCS server imports mock.module('../config', () => mockConfigModule()) import { storeReset } from '../store' import { getAllEventBuses, removeEventBus } from '../transport/event-bus' import { ingestBridgeMessage } from '../transport/ws-handler' import type { SessionEvent } from '../../web/src/types' const { RCSChatAdapter } = await import('../../web/src/lib/rcs-chat-adapter') const { BackgroundTasksSection } = await import( '../../web/src/components/TaskPanel' ) const { getVisibleSubagents } = await import('../../web/src/lib/subagentState') // bun 的 navigator.language 不稳定 — 固定 locale 保证文案断言 setLocale('en') /** REPL worker 经 writeSdkMessages 发出的原始 SDK 消息(与 * enqueueSdkEvent / emitTaskTerminatedSdk 构造的事件逐字段一致)。 */ const REPL_TASK_STARTED = { type: 'system', subtype: 'task_started', task_id: 'a1234567', description: 'explore the repo', task_type: 'local_agent', } const REPL_TASK_PROGRESS = { type: 'system', subtype: 'task_progress', task_id: 'a1234567', description: 'explore the repo', usage: { total_tokens: 1200, tool_uses: 3, duration_ms: 45000 }, last_tool_name: 'Grep', } const REPL_TASK_NOTIFICATION = { type: 'system', subtype: 'task_notification', task_id: 'a1234567', status: 'completed', output_file: '/tmp/out/a1234567', summary: 'found the root cause', usage: { total_tokens: 2000, tool_uses: 5, duration_ms: 60000 }, } /** 服务端 EventBus 发布的会话内事件(含 bus.publish 附上的 seqNum/id)。 */ interface BusEvent { id: string sessionId: string type: string payload: unknown direction: string seqNum: number } let busEvents: BusEvent[] = [] beforeEach(() => { storeReset() for (const [key] of getAllEventBuses()) { removeEventBus(key) } busEvents = [] // 服务端把所有事件发布到 EventBus — web 端 SSE /history 都从这里来。 // 订阅即模拟「web 客户端连上后收到的事件流」。 const { getEventBus } = require('../transport/event-bus') getEventBus('pipeline-s1').subscribe((e: BusEvent) => busEvents.push(e)) }) afterEach(() => { storeReset() for (const [key] of getAllEventBuses()) { removeEventBus(key) } }) /** 把服务端 EventBus 事件转成 web SessionEvent 形状(SSE 投递形状)。 */ function busEventsAsWebEvents(): SessionEvent[] { return busEvents.map(e => ({ type: e.type, payload: e.payload as never, direction: e.direction as 'inbound' | 'outbound', seqNum: e.seqNum, id: e.id, })) } describe('background task pipeline: REPL worker → RCS server → web panel', () => { test('task lifecycle events survive every hop and render in the sidebar', async () => { // ---- 1. REPL worker 旁路上 wire(原始 SDK 消息形状)---- ingestBridgeMessage('pipeline-s1', { ...REPL_TASK_STARTED, uuid: 'e1' }) ingestBridgeMessage('pipeline-s1', { ...REPL_TASK_PROGRESS, uuid: 'e2' }) // 服务端:事件已入 EventBus,类型 system,payload 保留 task 字段 const webEvents = busEventsAsWebEvents() expect(webEvents).toHaveLength(2) expect(webEvents.every(e => e.type === 'system')).toBe(true) // ---- 2. web 实时路径(SSE handleEvent)---- const adapterUpdates: Array<{ tasks: Record }> = [] const setEntries = () => {} const adapter = new RCSChatAdapter('pipeline-s1', setEntries, { onSubagentUpdate: state => adapterUpdates.push(state as never), }) for (const event of webEvents) { adapter.handleEvent(event) } expect(adapterUpdates).toHaveLength(2) const liveState = adapterUpdates[adapterUpdates.length - 1] expect( liveState.tasks['a1234567'] as Record, ).toMatchObject({ status: 'running', name: 'explore the', taskType: 'local_agent', tokenCount: 1200, toolUseCount: 3, lastToolName: 'Grep', }) // ---- 3. 刷新路径(loadHistory 从服务端事件日志回放)---- const realFetch = globalThis.fetch globalThis.fetch = (async (input: RequestInfo | URL) => { if (String(input).includes('/history')) { return new Response( JSON.stringify({ events: busEventsAsWebEvents() }), { status: 200, }, ) } return new Response('{}', { status: 200 }) }) as typeof fetch try { const replayUpdates: Array<{ tasks: Record }> = [] const freshAdapter = new RCSChatAdapter('pipeline-s1', setEntries, { onSubagentUpdate: state => replayUpdates.push(state as never), }) await freshAdapter.loadHistory() expect(replayUpdates).toHaveLength(1) const replayed = replayUpdates[0].tasks['a1234567'] as Record< string, unknown > expect(replayed).toMatchObject({ status: 'running', taskType: 'local_agent', tokenCount: 1200, }) // ---- 4. 渲染闭环(Session Ops 侧边栏分区)---- const html = renderToString( createElement(BackgroundTasksSection, { state: replayUpdates[0] as never, onStopTask: () => {}, }), ) expect(html).toContain('Local agents') expect(html).toContain('explore the repo') expect(html).toContain('Grep') expect(html).toContain('running') } finally { globalThis.fetch = realFetch } }) test('terminal notification closes the row and renders the final summary', () => { ingestBridgeMessage('pipeline-s1', { ...REPL_TASK_STARTED, uuid: 'e1' }) ingestBridgeMessage('pipeline-s1', { ...REPL_TASK_NOTIFICATION, uuid: 'e3', }) const updates: Array<{ tasks: Record }> = [] const adapter = new RCSChatAdapter('pipeline-s1', () => {}, { onSubagentUpdate: state => updates.push(state as never), }) for (const event of busEventsAsWebEvents()) { adapter.handleEvent(event) } const state = updates[updates.length - 1] const task = state.tasks['a1234567'] as Record expect(task.status).toBe('completed') expect(task.finalSummary).toBe('found the root cause') // 宽限期内仍可见(getVisibleSubagents 时间感知过滤) expect(getVisibleSubagents(state as never)).toHaveLength(1) const html = renderToString( createElement(BackgroundTasksSection, { state: state as never }), ) expect(html).toContain('found the root cause') expect(html).toContain('1 recent') }) })