import { useEffect, useRef, useState } from 'react' import type { ResearchRequest } from '../lib/day3' import type { SearchQuery } from '../lib/day2' import type { QaScope } from '../lib/conversations' import { api, ApiError } from '../lib/api' export interface TaskEvent { id: number type: string payload: { message?: string; text?: string; status?: string; [key: string]: unknown } } export interface AgentTask { id: string status: string operation: string question: string | null answeredAt?: string | null result: unknown usage?: { external_calls: number; zlbx_calls: number; known_cost_units: number; unknown_cost_calls: number; model_web_calls: number; input_tokens: number; output_tokens: number; unknown_token_calls: number } request: { operation: string; workflow: string; input: string; entityConfirmed: boolean; maxCalls: number; maxCostUnits: number; opportunity?: SearchQuery; research?: ResearchRequest; qa?: QaScope; summarizeList?: boolean } children?: { id: string; status: string; operation: string; target?: { research?: ResearchRequest; qa?: QaScope } }[] calls: Record[] evidence: { id: string; url: string | null; locator: string; excerpt: string; title?: string; verified?: boolean }[] } /** 原生 EventSource 用 Cookie 鉴权;游标只重放事件,不重复 POST 收费任务。 */ export function useTaskEvents(taskId: string | null, revision = 0) { const [events, setEvents] = useState([]) const [task, setTask] = useState(null) const [error, setError] = useState('') const cursor = useRef(0) useEffect(() => { if (!taskId) return let active = true let source: EventSource | null = null let timer: ReturnType | undefined let initial = true let refreshVersion = 0 let retries = 0 cursor.current = 0 const refresh = async () => { const version = ++refreshVersion const next = await api(`/agent/tasks/${taskId}`) // 多页进度与终态可能相邻到达,只接受最近一次读取,防止慢响应覆盖最终报告。 if (active && version === refreshVersion) { if (initial) { setEvents([]); initial = false } setTask(next) setError('') if (!['RECEIVED', 'PLANNING', 'RUNNING'].includes(next.status)) clearInterval(poll) } return next } // 后端暂时不可达时持续只读恢复,延迟最多 15 秒;认证失效后停止,交给登录页处理。 const retry = (error?: unknown) => { if (!active || (error instanceof ApiError && [401, 403, 404].includes(error.status))) { if (active && error instanceof Error) setError(error.message) return } setError('连接已中断,正在恢复事件与已有结果;不会重新发起收费请求') if (timer) clearTimeout(timer) timer = setTimeout(() => { void refresh().then(() => { if (active) connect() }).catch(retry) }, Math.min(15000, 1000 * 2 ** Math.min(retries++, 4))) } const connect = () => { if (!active) return source = new EventSource(`/api/agent/tasks/${taskId}/events?after=${cursor.current}`) source.addEventListener('task-event', event => { const entry: TaskEvent = JSON.parse((event as MessageEvent).data) if (!active || entry.id <= cursor.current) return cursor.current = entry.id setEvents(items => [...items, entry]) setError(''); retries = 0 if (['STATE', 'TOOL_START', 'PAGE_COLLECTED', 'MARKET_COLLECTED', 'RESEARCH_STEP', 'SUMMARY_PROGRESS'].includes(entry.type)) void refresh().catch(error => { if (active) setError(error.message) }) }) source.addEventListener('idle', () => { source?.close() void refresh().catch(error => { if (active) setError(error.message) }) }) source.onerror = () => { source?.close() // 无论任务是否刚好完成,都重新订阅并追完游标之后的最终事件,直到收到 idle。 retry() } } // 某些代理会缓冲 SSE,连接可能保持打开却迟迟收不到结束事件。轮询仅回读任务,补齐最终答案。 const poll = setInterval(() => { void refresh().catch(() => { /* SSE 的重连流程负责提示错误 */ }) }, 5000) void refresh().then(() => { if (active) connect() }).catch(retry) return () => { active = false; source?.close(); if (timer) clearTimeout(timer); clearInterval(poll) } }, [taskId, revision]) return { events, task: task?.id === taskId ? task : null, error } }