// One `EventSource` for a page: `{ connection, reconnect }`. The three live // feeds (the agent terminal, an agent's turn-state header and the message // list) differ only in what they do with a message, so the state machine, the // close on cleanup, the session probe and `reconnect` live here once. // // `setup` runs each time the stream is opened (a new `url`, a new `deps`, or // `reconnect`) and returns what to do with the stream: reset the page's data // there, and return `onMessage` (and `onOpen`, and `dispose` for a timer or a // frame the page keeps). A `null` url opens nothing. import { useEffect, useState } from "preact/hooks"; import { probeSession } from "../session/session.js"; import { openStream, type ConnectionState } from "./connection.js"; export type { ConnectionState }; export interface StreamHandlers { onMessage: (data: string) => void; /** Runs when the stream opens, a reconnect included. */ onOpen?: () => void; /** Runs when the stream closes, for a timer or a frame the page keeps. */ dispose?: () => void; } export function useEventStream( url: string | null, setup: () => StreamHandlers, deps: readonly unknown[], ): { connection: ConnectionState; /** Opens the stream again, for one the browser gave up on. */ reconnect: () => void; } { const [connection, setConnection] = useState("connecting"); // Bumped by `reconnect`, which runs the effect below again. const [attempt, setAttempt] = useState(0); useEffect(() => { setConnection("connecting"); const handlers = setup(); if (url === null) { handlers.dispose?.(); return; } const close = openStream({ url, makeSource: (u) => new EventSource(u), onState: setConnection, onOpen: handlers.onOpen, onMessage: handlers.onMessage, onGaveUp: probeSession, }); return () => { close(); handlers.dispose?.(); }; // `setup` is a fresh closure each render; `deps` names what it depends on. // eslint-disable-next-line react-hooks/exhaustive-deps }, [url, attempt, ...deps]); return { connection, reconnect: () => setAttempt((n) => n + 1) }; }