// Live SSE consumer for the swarm-relayed agent terminal // (`GET /api/agents/{name}/term/stream`, swarm-controller's // `term_stream.rs`). The relay forwards one bare `TermMsg` per SSE event, its // replayed rows first and in order on the same stream, so there is nothing to // buffer, dedupe or backfill against. The browser's own `Last-Event-ID` // resumes a reconnect, so rows are kept across one. Rows that arrive within // 50 ms are folded in together, and `term-rows.ts` holds the rules for that: // coalesce by key, and keep the newest `MAX_ROWS`. import { useRef, useState } from "preact/hooks"; import type { TermMsg, TermRow } from "@hive/shared/term-msg.js"; import { useEventStream, type ConnectionState, } from "../../ui/stream/useEventStream.js"; import { appendRows } from "./term-rows.js"; export type { ConnectionState }; // Rows that arrive close together are folded in at once: a busy turn sends many a // second, and each fold copies the list. const BATCH_MS = 50; export interface UseSwarmTermStreamResult { rows: TermRow[]; connection: ConnectionState; /** Opens the stream again, for one the browser gave up on. */ reconnect: () => void; } export function useSwarmTermStream( streamUrl: string, ): UseSwarmTermStreamResult { const [rows, setRows] = useState([]); const keySeqRef = useRef(0); const { connection, reconnect } = useEventStream(streamUrl, () => { setRows([]); keySeqRef.current = 0; let batch: TermRow[] = []; let timer: ReturnType | null = null; function flush() { timer = null; const next = batch; batch = []; setRows((prev) => appendRows(prev, next)); } function push(row: TermRow) { batch.push(row); if (timer === null) timer = setTimeout(flush, BATCH_MS); } return { onMessage: (data) => { keySeqRef.current += 1; const key = "r" + keySeqRef.current; let msg: TermMsg; try { msg = JSON.parse(data); } catch { push({ key, level: "warn", fromHistory: false, summary: "[parse err] " + data, }); return; } push({ ...msg, key, fromHistory: false }); }, dispose: () => { if (timer !== null) clearTimeout(timer); }, }; }, []); return { rows, connection, reconnect }; }