The platform for continuously improving AI agents.
import { useEffect, useRef } from "react";
import { fetchWithAuth } from "@/client";
import { whilePageVisible } from "@/lib/visible-stream";
export interface StreamEvent {
type: string;
/** On "connected": true when it replaces a dropped connection. */
again?: boolean;
}
/** A record's live channel, fetch-based (EventSource cannot send an Authorization header).
* An event names what changed; the page reads it again. A hidden tab holds no connection,
* and the next one says it replaces a dropped one. */
export function useEventStream<T extends StreamEvent>(
path: string | undefined | false,
onEvent: (event: T) => void
) {
const onEventRef = useRef(onEvent);
useEffect(() => {
onEventRef.current = onEvent;
});
const connections = useRef(0);
useEffect(() => {
if (!path) return;
return whilePageVisible(() => {
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let controller: AbortController | null = null;
const consume = (line: string) => {
if (!line.startsWith("data: ")) return;
try {
const event = JSON.parse(line.slice(6)) as T;
if (event.type === "connected") {
connections.current += 1;
onEventRef.current({ ...event, again: connections.current > 1 });
} else onEventRef.current(event);
} catch {
// A malformed frame carries nothing worth surfacing.
}
};
const connect = async () => {
if (cancelled) return;
controller = new AbortController();
let buffer = "";
try {
const res = await fetchWithAuth(path, { signal: controller.signal });
if (!res.ok || !res.body) throw new Error(`events ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) consume(line.trimEnd());
}
} catch {
// Aborted or dropped — reconnect below.
}
if (!cancelled) timer = setTimeout(connect, 3_000);
};
void connect();
return () => {
cancelled = true;
controller?.abort();
if (timer) clearTimeout(timer);
};
});
}, [path]);
}