File size: 4,441 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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<string, unknown> }
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<RunEvent[]>([]);
  const [mode, setMode] = useState<StreamMode>('idle');
  const last = useRef(0);
  const qc = useQueryClient();

  useEffect(() => {
    let stopped = false;
    let es: EventSource | null = null;
    let timer: ReturnType<typeof setTimeout> | null = null;
    let refresh: ReturnType<typeof setTimeout> | 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<RunEvent[]>(`/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<string, { state: NodeState; count: number; modules: string[] }> {
  const out: Record<string, { state: NodeState; count: number; modules: string[] }> = {};
  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;
}