Spaces:
Running
Running
File size: 4,096 Bytes
03608f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | "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<RunTimeline>(`/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;
}
|