"use client"; import { useEffect, useReducer } from "react"; import { api, authHeaders, buildUrl } from "@/lib/api"; import { streamSse } from "@/lib/sse"; import type { AuditAction, RunStatusEvent, RunTimeline } from "@/lib/types"; export const TERMINAL = new Set(["completed", "rejected", "failed", "unsupported"]); export interface RunStreamState { timeline: RunTimeline | null; live: boolean; error: string | null; } type Action = | { type: "snapshot"; timeline: RunTimeline } | { type: "action"; action: AuditAction } | { type: "status"; status: RunStatusEvent } | { type: "live"; live: boolean } | { type: "error"; error: string }; export function runStreamReducer(s: RunStreamState, a: Action): RunStreamState { switch (a.type) { case "snapshot": return { ...s, timeline: a.timeline, error: null }; case "action": { if (!s.timeline || s.timeline.actions.some((x) => x.seq === a.action.seq)) return s; return { ...s, timeline: { ...s.timeline, actions: [...s.timeline.actions, a.action] } }; } case "status": if (!s.timeline) return s; return { ...s, timeline: { ...s.timeline, run: a.status.run, state: Object.keys(a.status.state ?? {}).length ? a.status.state : s.timeline.state, approvals: a.status.approvals, }, }; case "live": return { ...s, live: a.live }; case "error": return { ...s, error: a.error, live: false }; } } /** Initial snapshot from /runs/{id}/timeline, then live updates over SSE until the run ends. * Follows through approval waits and reconnects (resuming after the last event id). */ export function useRunStream(runId: string): RunStreamState { const [state, dispatch] = useReducer(runStreamReducer, { timeline: null, live: false, error: null, }); useEffect(() => { const ctrl = new AbortController(); let lastSeq = 0; let status = ""; const loop = async () => { try { const tl = await api(`/runs/${runId}/timeline`, { signal: ctrl.signal }); dispatch({ type: "snapshot", timeline: tl }); lastSeq = tl.actions.reduce((m, x) => Math.max(m, x.seq), 0); status = tl.run.status; } catch (e) { if (!ctrl.signal.aborted) dispatch({ type: "error", error: (e as Error).message }); return; } let backoff = 1000; while (!ctrl.signal.aborted && !TERMINAL.has(status)) { try { dispatch({ type: "live", live: true }); const code = await streamSse( buildUrl(`/runs/${runId}/stream`, { follow: true, after: lastSeq }), { headers: await authHeaders(), signal: ctrl.signal, onEvent: (e) => { const data = JSON.parse(e.data) as unknown; if (e.event === "action") { const a = data as AuditAction; lastSeq = Math.max(lastSeq, a.seq); dispatch({ type: "action", action: a }); } else if (e.event === "status") { const st = data as RunStatusEvent; status = st.run.status; dispatch({ type: "status", status: st }); } else if (e.event === "end") { status = (data as { status: string }).status; } }, }, ); if (code === 401) await api("/me", { signal: ctrl.signal }); // refreshes the token backoff = 1000; } catch { if (ctrl.signal.aborted) break; backoff = Math.min(backoff * 2, 15_000); } if (!TERMINAL.has(status) && !ctrl.signal.aborted) { await new Promise((r) => setTimeout(r, backoff)); } } if (!ctrl.signal.aborted) dispatch({ type: "live", live: false }); }; void loop(); return () => ctrl.abort(); }, [runId]); return state; }