import { useEffect, useRef, useState } from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { getJson } from '../api/client'; export interface RunEvent { seq: number; ts: string; node: string | null; kind: string; summary: Record } export type StreamMode = 'sse' | 'polling' | 'idle'; /** Live run events: Server-Sent Events (/api/runs/{id}/stream) with automatic fallback to polling /events?after=. */ export function useRunStream(runId: string, opts: { forcePolling?: boolean; pollMs?: number } = {}) { const [events, setEvents] = useState([]); const [mode, setMode] = useState('idle'); const last = useRef(0); const qc = useQueryClient(); useEffect(() => { let stopped = false; let es: EventSource | null = null; let timer: ReturnType | null = null; let refresh: ReturnType | null = null; last.current = 0; setEvents([]); // A status change makes the run's views stale. The stream replays a run's whole history when the page opens (one // message per event), so refreshes are coalesced: at most one per second, after the burst. Agent steps finishing // are not status changes: the run's own refresh shows them. const refreshSoon = () => { if (refresh) return; refresh = setTimeout(() => { refresh = null; if (stopped) return; void qc.invalidateQueries({ queryKey: ['run', runId] }); void qc.invalidateQueries({ queryKey: ['runs'] }); }, 1000); }; const push = (evs: RunEvent[]) => { const fresh = evs.filter((e) => e.seq > last.current); if (!fresh.length) return; last.current = fresh[fresh.length - 1].seq; setEvents((prev) => [...prev, ...fresh]); if (fresh.some((e) => e.kind === 'status' || e.kind === 'interrupted')) refreshSoon(); }; const poll = async () => { if (stopped) return; try { push(await getJson(`/api/runs/${encodeURIComponent(runId)}/events?after=${last.current}`)); } catch { /* transient; keep polling */ } timer = setTimeout(poll, opts.pollMs ?? 2000); }; const startPolling = () => { if (stopped) return; setMode('polling'); void poll(); }; if (!opts.forcePolling && typeof EventSource !== 'undefined') { let failures = 0; es = new EventSource(`/api/runs/${encodeURIComponent(runId)}/stream?after=0`); setMode('sse'); es.addEventListener('run_event', (m) => { failures = 0; push([JSON.parse((m as MessageEvent).data) as RunEvent]); }); es.addEventListener('end', () => { es?.close(); refreshSoon(); setTimeout(() => !stopped && poll(), 3000); // a resumed run starts emitting again: keep a slow poll }); es.onerror = () => { failures += 1; if (failures >= 2) { es?.close(); startPolling(); } }; } else { startPolling(); } return () => { stopped = true; es?.close(); if (timer) clearTimeout(timer); if (refresh) clearTimeout(refresh); }; }, [runId, opts.forcePolling, opts.pollMs, qc]); return { events, mode }; } export type NodeState = 'pending' | 'running' | 'done' | 'error' | 'waiting' | 'skipped'; /** Fold the event log into a per-node state (and the per-module research workers). */ export function nodeStates(events: RunEvent[], nodes: string[], finished: boolean): Record { const out: Record = {}; for (const n of nodes) out[n] = { state: 'pending', count: 0, modules: [] }; for (const e of events) { if (!e.node || !out[e.node]) continue; const s = out[e.node]; if (e.kind === 'started') { s.state = 'running'; s.count += 1; const m = e.summary?.module; if (typeof m === 'string') s.modules.push(m); } else if (e.kind === 'finished') s.state = 'done'; else if (e.kind === 'interrupted') s.state = 'waiting'; else if (e.kind === 'error' || e.kind === 'killed') s.state = 'error'; } if (finished) for (const n of nodes) if (out[n].state === 'pending') out[n].state = 'skipped'; return out; }