From bbdd32c2e052c7d07981c47e74f5172dea5d3dc2 Mon Sep 17 00:00:00 2001 From: iris Date: Thu, 26 Nov 2026 00:57:53 +0100 Subject: [PATCH] swarm-ui: one stream hook, and one rule for confirming a change Part of the unification order in the UI sweep issue (steps e and f). The terminal, turn-state and message feeds each opened an EventSource, tracked connecting/open/reconnecting/closed, probed the session when the browser gave up, and reconnected through an attempt counter. openStream (no Preact, source injected, tested with a fake) and useEventStream now own that; each feed keeps only what it does with a message. A change confirmed itself three ways: a toast, inline, or nothing. The design guide now says forms confirm inline, actions on a card in a refreshing list confirm with a toast, and a change the page already shows says nothing. Fire now, saving a schedule and removing an egress entry gain the toast they lacked. --- docs/4-implementation/web-ui/swarm-ui.md | 6 +- docs/5-project/web-ui/design-guide.md | 9 ++ .../src/agent/detail/AllowedDomains.tsx | 3 +- .../src/agent/detail/useAllowedDomains.ts | 9 +- .../terminal/useSwarmAgentStateStream.ts | 49 ++++------ .../src/agent/terminal/useSwarmTermStream.ts | 66 ++++++------- .../src/pages/messages/useMessageStream.ts | 95 ++++++++----------- .../src/pages/schedules/SchedulesPage.tsx | 27 ++++-- .../swarm-ui/src/pages/swarm/EgressCard.tsx | 3 +- .../swarm-ui/src/ui/stream/connection.ts | 38 ++++++++ .../swarm-ui/src/ui/stream/useEventStream.ts | 61 ++++++++++++ .../swarm-ui/test/stream-connection.test.mjs | 68 ++++++++++++- 12 files changed, 295 insertions(+), 139 deletions(-) create mode 100644 frontend/packages/swarm-ui/src/ui/stream/useEventStream.ts diff --git a/docs/4-implementation/web-ui/swarm-ui.md b/docs/4-implementation/web-ui/swarm-ui.md index 2937dcf5b..c52662a70 100644 --- a/docs/4-implementation/web-ui/swarm-ui.md +++ b/docs/4-implementation/web-ui/swarm-ui.md @@ -499,6 +499,8 @@ to its agents as a broadcast (`POST /api/agents/broadcast`) after a confirmation and leaves the schedule paused with its start unchanged; a toast says who got it, and the error banner names any agent that didn't. **pause** and **resume** stop and restart it; **remove** deletes it after a confirmation. +A toast says `sent now` after **fire now** and `schedule saved` after a +save; pause, resume and remove say nothing, since the card flips or goes. **+ schedule** opens an empty form above the list, and the filters narrow the list by name, agent or state (`active`, `paused`, or `past` for a one-shot whose time has passed). `past` is the controller's clock against the start time, @@ -1056,7 +1058,7 @@ list every agent has: one badge per source with its count, **swarm-wide** (the entries for every agent), **this agent** (the ones for it alone) and **automatic**. Selecting a badge opens the names behind it. An entry matters to a restricted agent. One with the unrestricted internet flag reaches any name the -proxy's private-range rules leave. **remove**, beside a name, drops one entry; +proxy's private-range rules leave. **remove**, beside a name, drops one entry and shows a toast (`removed `); **add** opens a dialog with a domain box and a tick for every agent in the swarm. The tick is off by default, so an entry is for this agent alone. @@ -1067,7 +1069,7 @@ rows. **allowed** is the list above. **denied** is the swarm's deny list: every egress mode refuses a denied name, even when an allowed entry, a hive's own `allowedDomains` or the unrestricted internet flag would let it through. The card says which hives haven't applied the current deny list yet; until they do, their proxies may still let -those names through. The two lists use the same requests as the agent card, against +those names through. Removing an entry shows a toast (`removed `). The two lists use the same requests as the agent card, against `/api/egress/allowed-domains` and `/api/egress/denied-domains`. The deny list has no per-agent editor on the agent card yet, and no automatic entries. diff --git a/docs/5-project/web-ui/design-guide.md b/docs/5-project/web-ui/design-guide.md index b911425d1..faf30bb43 100644 --- a/docs/5-project/web-ui/design-guide.md +++ b/docs/5-project/web-ui/design-guide.md @@ -126,6 +126,15 @@ for confirmation before a destructive/dangerous action, and offer helpful hints — it just shouldn't get in the way of someone who already knows what they're doing. +## Confirming a change + +A change confirms itself in one of three ways, by where you make it. A form +confirms inline with `FormResult`, under its own button, unless the form closes +on save, which leaves no button to put it under: that confirms with a toast. An action on a card in +a list that refreshes confirms with a toast. A change the page already shows +(a card that flips or goes, a row that appears) says nothing. A new action picks +the way by this rule and doesn't add a fourth. + ## Empty states Graceful fallbacks, always — a table with zero rows should show diff --git a/frontend/packages/swarm-ui/src/agent/detail/AllowedDomains.tsx b/frontend/packages/swarm-ui/src/agent/detail/AllowedDomains.tsx index 24d9f42db..aa189f8ec 100644 --- a/frontend/packages/swarm-ui/src/agent/detail/AllowedDomains.tsx +++ b/frontend/packages/swarm-ui/src/agent/detail/AllowedDomains.tsx @@ -27,6 +27,7 @@ import { Badge } from "@hive/shared/badge.js"; import { ActionRow } from "../../ui/action-row/ActionRow.js"; import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js"; import { Button } from "../../ui/button/Button.js"; +import { showToast } from "../../ui/toast/toasts.js"; import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js"; import { FormStack } from "../../ui/form-stack/FormStack.js"; import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js"; @@ -89,7 +90,7 @@ export function AllowedDomains({ agent }: { agent: string }) { ) { return; } - void remove(e); + if (await remove(e)) showToast(`removed ${e.domain}`, "ok"); } // A list already loaded stays under a failed refetch, so a change that diff --git a/frontend/packages/swarm-ui/src/agent/detail/useAllowedDomains.ts b/frontend/packages/swarm-ui/src/agent/detail/useAllowedDomains.ts index 8b9e62639..09ec79164 100644 --- a/frontend/packages/swarm-ui/src/agent/detail/useAllowedDomains.ts +++ b/frontend/packages/swarm-ui/src/agent/detail/useAllowedDomains.ts @@ -34,8 +34,9 @@ function useDomainList(url: string) { reload, } = useResource((signal) => fetchJson(url, signal), [url]); - async function remove(entry: AllowedDomain) { - if (busy) return; + /** True when the entry was removed. */ + async function remove(entry: AllowedDomain): Promise { + if (busy) return false; setBusy(true); try { const r = await fetch(url, { @@ -45,12 +46,14 @@ function useDomainList(url: string) { }); if (!r.ok) { setRemoveError(await readApiError(r)); - return; + return false; } setRemoveError(null); reload(); + return true; } catch (e: unknown) { setRemoveError({ detail: String(e) }); + return false; } finally { setBusy(false); } diff --git a/frontend/packages/swarm-ui/src/agent/terminal/useSwarmAgentStateStream.ts b/frontend/packages/swarm-ui/src/agent/terminal/useSwarmAgentStateStream.ts index 48e12b900..e59135680 100644 --- a/frontend/packages/swarm-ui/src/agent/terminal/useSwarmAgentStateStream.ts +++ b/frontend/packages/swarm-ui/src/agent/terminal/useSwarmAgentStateStream.ts @@ -15,13 +15,12 @@ // endpoint today that can seed turn_state/model/ctx/cost synchronously — // `GET /api/agents/status`'s snapshot carries only // `status_text`/`running`). -import { useEffect, useState } from "preact/hooks"; +import { useState } from "preact/hooks"; import { - connectionAfterError, + useEventStream, type ConnectionState, -} from "../../ui/stream/connection.js"; -import { probeSession } from "../../ui/session/session.js"; +} from "../../ui/stream/useEventStream.js"; export type { ConnectionState }; @@ -68,35 +67,23 @@ export function useSwarmAgentStateStream( streamUrl: string | null, ): UseSwarmAgentStateStreamResult { const [header, setHeader] = useState(null); - const [connection, setConnection] = useState("connecting"); - // Bumped by `reconnect`, which reruns the effect below. - const [attempt, setAttempt] = useState(0); - useEffect(() => { + // `null`: a terminal with no header to follow (a subagent's). + const { connection, reconnect } = useEventStream(streamUrl, () => { setHeader(null); - setConnection("connecting"); - // `null`: a terminal with no header to follow (a subagent's). - if (streamUrl === null) return; - const es = new EventSource(streamUrl); - es.onopen = () => setConnection("open"); - es.onmessage = (e) => { - try { - setHeader(JSON.parse(e.data) as AgentStateHeader); - } catch { - // Malformed payload: drop it silently. Unlike the terminal - // preview there is no row list to append a "[parse err]" line - // to here, and one bad header isn't worth degrading the whole - // badge cluster over — the next valid header replaces it. - } + return { + onMessage: (data) => { + try { + setHeader(JSON.parse(data) as AgentStateHeader); + } catch { + // Malformed payload: drop it silently. Unlike the terminal + // preview there is no row list to append a "[parse err]" line + // to here, and one bad header isn't worth degrading the whole + // badge cluster over — the next valid header replaces it. + } + }, }; - es.onerror = () => { - const state = connectionAfterError(es.readyState); - setConnection(state); - // The browser gave up: say whether the session ended, which `EventSource` does not tell. - if (state === "closed") probeSession(); - }; - return () => es.close(); - }, [streamUrl, attempt]); + }, []); - return { header, connection, reconnect: () => setAttempt((n) => n + 1) }; + return { header, connection, reconnect }; } diff --git a/frontend/packages/swarm-ui/src/agent/terminal/useSwarmTermStream.ts b/frontend/packages/swarm-ui/src/agent/terminal/useSwarmTermStream.ts index 3dd33700d..1838920e5 100644 --- a/frontend/packages/swarm-ui/src/agent/terminal/useSwarmTermStream.ts +++ b/frontend/packages/swarm-ui/src/agent/terminal/useSwarmTermStream.ts @@ -6,14 +6,13 @@ // 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 { useEffect, useRef, useState } from "preact/hooks"; +import { useRef, useState } from "preact/hooks"; import type { TermMsg, TermRow } from "@hive/shared/term-msg.js"; import { - connectionAfterError, + useEventStream, type ConnectionState, -} from "../../ui/stream/connection.js"; -import { probeSession } from "../../ui/session/session.js"; +} from "../../ui/stream/useEventStream.js"; import { appendRows } from "./term-rows.js"; export type { ConnectionState }; @@ -33,14 +32,10 @@ export function useSwarmTermStream( streamUrl: string, ): UseSwarmTermStreamResult { const [rows, setRows] = useState([]); - const [connection, setConnection] = useState("connecting"); const keySeqRef = useRef(0); - // Bumped by `reconnect`, which reruns the effect below. - const [attempt, setAttempt] = useState(0); - useEffect(() => { + const { connection, reconnect } = useEventStream(streamUrl, () => { setRows([]); - setConnection("connecting"); keySeqRef.current = 0; let batch: TermRow[] = []; let timer: ReturnType | null = null; @@ -54,36 +49,29 @@ export function useSwarmTermStream( batch.push(row); if (timer === null) timer = setTimeout(flush, BATCH_MS); } - const es = new EventSource(streamUrl); - es.onopen = () => setConnection("open"); - es.onmessage = (e) => { - keySeqRef.current += 1; - const key = "r" + keySeqRef.current; - let msg: TermMsg; - try { - msg = JSON.parse(e.data); - } catch { - push({ - key, - level: "warn", - fromHistory: false, - summary: "[parse err] " + e.data, - }); - return; - } - push({ ...msg, key, fromHistory: false }); + 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); + }, }; - es.onerror = () => { - const state = connectionAfterError(es.readyState); - setConnection(state); - // The browser gave up: say whether the session ended, which `EventSource` does not tell. - if (state === "closed") probeSession(); - }; - return () => { - es.close(); - if (timer !== null) clearTimeout(timer); - }; - }, [streamUrl, attempt]); + }, []); - return { rows, connection, reconnect: () => setAttempt((n) => n + 1) }; + return { rows, connection, reconnect }; } diff --git a/frontend/packages/swarm-ui/src/pages/messages/useMessageStream.ts b/frontend/packages/swarm-ui/src/pages/messages/useMessageStream.ts index dcbfb49b8..129a8a2c5 100644 --- a/frontend/packages/swarm-ui/src/pages/messages/useMessageStream.ts +++ b/frontend/packages/swarm-ui/src/pages/messages/useMessageStream.ts @@ -7,15 +7,14 @@ // Each message gets an id as it arrives, and the events that arrive within one // frame join the list in a single update, so a long replay is one render per // frame instead of one per message. -import { useEffect, useRef, useState } from "preact/hooks"; +import { useRef, useState } from "preact/hooks"; import type { ArrivedMessage, SwarmMessage } from "./messages.js"; import { messagesUrl, newest, numbered } from "./messages.js"; import { - connectionAfterError, + useEventStream, type ConnectionState, -} from "../../ui/stream/connection.js"; -import { probeSession } from "../../ui/session/session.js"; +} from "../../ui/stream/useEventStream.js"; export type { ConnectionState }; @@ -29,59 +28,49 @@ export function useMessageStream(sinceMinutes: number): { reconnect: () => void; } { const [messages, setMessages] = useState([]); - const [connection, setConnection] = useState("connecting"); // The next id to hand out; it never goes back, so an id is not reused after // a reconnect either. const nextId = useRef(0); - // Bumped by `reconnect`, which reruns the effect below. - const [attempt, setAttempt] = useState(0); - useEffect(() => { - setMessages([]); - setConnection("connecting"); - const es = new EventSource(messagesUrl(sinceMinutes)); - let pending: SwarmMessage[] = []; - let frame: number | null = null; - - function drop() { - pending = []; - if (frame !== null) cancelAnimationFrame(frame); - frame = null; - } - function flush() { - frame = null; - const batch = numbered(pending, nextId.current); - pending = []; - nextId.current += batch.length; - setMessages((prev) => newest([...prev, ...batch], MAX_MESSAGES)); - } - - es.onopen = () => { - drop(); + const { connection, reconnect } = useEventStream( + messagesUrl(sinceMinutes), + () => { setMessages([]); - setConnection("open"); - }; - es.onmessage = (e) => { - let m: SwarmMessage; - try { - m = JSON.parse(e.data) as SwarmMessage; - } catch { - return; - } - pending.push(m); - if (frame === null) frame = requestAnimationFrame(flush); - }; - es.onerror = () => { - const state = connectionAfterError(es.readyState); - setConnection(state); - // The browser gave up: say whether the session ended, which `EventSource` does not tell. - if (state === "closed") probeSession(); - }; - return () => { - drop(); - es.close(); - }; - }, [sinceMinutes, attempt]); + let pending: SwarmMessage[] = []; + let frame: number | null = null; - return { messages, connection, reconnect: () => setAttempt((n) => n + 1) }; + function drop() { + pending = []; + if (frame !== null) cancelAnimationFrame(frame); + frame = null; + } + function flush() { + frame = null; + const batch = numbered(pending, nextId.current); + pending = []; + nextId.current += batch.length; + setMessages((prev) => newest([...prev, ...batch], MAX_MESSAGES)); + } + return { + onOpen: () => { + drop(); + setMessages([]); + }, + onMessage: (data) => { + let m: SwarmMessage; + try { + m = JSON.parse(data) as SwarmMessage; + } catch { + return; + } + pending.push(m); + if (frame === null) frame = requestAnimationFrame(flush); + }, + dispose: drop, + }; + }, + [], + ); + + return { messages, connection, reconnect }; } diff --git a/frontend/packages/swarm-ui/src/pages/schedules/SchedulesPage.tsx b/frontend/packages/swarm-ui/src/pages/schedules/SchedulesPage.tsx index 2fc7215dd..684498a04 100644 --- a/frontend/packages/swarm-ui/src/pages/schedules/SchedulesPage.tsx +++ b/frontend/packages/swarm-ui/src/pages/schedules/SchedulesPage.tsx @@ -117,8 +117,14 @@ function SchedulesBody() { // One mutation on one schedule: pending while in flight, the error kept // for the banner, a refetch on success so the card shows the controller's - // own answer rather than a guessed one. - async function act(id: string, request: () => Promise) { + // own answer rather than a guessed one. `done` is a toast for a change the + // page does not show by itself (pause, resume and remove flip or drop the + // card, so they say nothing). + async function act( + id: string, + request: () => Promise, + done?: string, + ) { markPending(id, true); setActionError(null); setErrorContext(SCHEDULE_UNCHANGED); @@ -129,6 +135,7 @@ function SchedulesBody() { return; } refresh(); + if (done) showToast(done, "ok"); } catch (err) { setActionError({ detail: String(err) }); } finally { @@ -180,12 +187,15 @@ function SchedulesBody() { ), }); if (!yes) return; - return act(s.id, () => - fetch(`/api/schedules/${encodeURIComponent(s.id)}`, { - method: "PATCH", - headers: { "content-type": "application/json" }, - body: JSON.stringify(fireNowBody(Date.now())), - }), + return act( + s.id, + () => + fetch(`/api/schedules/${encodeURIComponent(s.id)}`, { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify(fireNowBody(Date.now())), + }), + `sent ${s.name} now`, ); } @@ -219,6 +229,7 @@ function SchedulesBody() { setCreating(false); setEditingId(null); refresh(); + showToast("schedule saved", "ok"); } return ( diff --git a/frontend/packages/swarm-ui/src/pages/swarm/EgressCard.tsx b/frontend/packages/swarm-ui/src/pages/swarm/EgressCard.tsx index b96d253f1..40b52f7fd 100644 --- a/frontend/packages/swarm-ui/src/pages/swarm/EgressCard.tsx +++ b/frontend/packages/swarm-ui/src/pages/swarm/EgressCard.tsx @@ -22,6 +22,7 @@ import { useDeniedDomains, } from "../../agent/detail/useAllowedDomains.js"; import { Button } from "../../ui/button/Button.js"; +import { showToast } from "../../ui/toast/toasts.js"; import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js"; import { LazyDisclosure } from "../../ui/disclosure/LazyDisclosure.js"; import { Dialog } from "../../ui/dialog/Dialog.js"; @@ -66,7 +67,7 @@ function DomainSection({ ) { return; } - void remove(e); + if (await remove(e)) showToast(`removed ${e.domain}`, "ok"); } // A list already loaded stays under a failed refetch, so a change that diff --git a/frontend/packages/swarm-ui/src/ui/stream/connection.ts b/frontend/packages/swarm-ui/src/ui/stream/connection.ts index 8a439b15b..3b54d214d 100644 --- a/frontend/packages/swarm-ui/src/ui/stream/connection.ts +++ b/frontend/packages/swarm-ui/src/ui/stream/connection.ts @@ -12,3 +12,41 @@ const CONNECTING = 0; export function connectionAfterError(readyState: number): ConnectionState { return readyState === CONNECTING ? "reconnecting" : "closed"; } + +/** What `openStream` uses of an `EventSource`; a test passes a fake. */ +export interface StreamSource { + onopen: ((e: Event) => void) | null; + onmessage: ((e: MessageEvent) => void) | null; + onerror: ((e: Event) => void) | null; + readonly readyState: number; + close(): void; +} + +/** + * Opens one stream and reports it the same way for every page. `onState` hears + * "open" when the stream opens, and "reconnecting" or "closed" after an error + * (see `connectionAfterError`); `onGaveUp` runs when the browser gave up, so a + * page can ask whether the session ended, which an `EventSource` does not + * tell. Returns the function that closes it. + */ +export function openStream(opts: { + url: string; + makeSource: (url: string) => StreamSource; + onState: (state: ConnectionState) => void; + onOpen?: () => void; + onMessage: (data: string) => void; + onGaveUp?: () => void; +}): () => void { + const source = opts.makeSource(opts.url); + source.onopen = () => { + opts.onState("open"); + opts.onOpen?.(); + }; + source.onmessage = (e) => opts.onMessage(String(e.data)); + source.onerror = () => { + const state = connectionAfterError(source.readyState); + opts.onState(state); + if (state === "closed") opts.onGaveUp?.(); + }; + return () => source.close(); +} diff --git a/frontend/packages/swarm-ui/src/ui/stream/useEventStream.ts b/frontend/packages/swarm-ui/src/ui/stream/useEventStream.ts new file mode 100644 index 000000000..2155fec24 --- /dev/null +++ b/frontend/packages/swarm-ui/src/ui/stream/useEventStream.ts @@ -0,0 +1,61 @@ +// 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) }; +} diff --git a/frontend/packages/swarm-ui/test/stream-connection.test.mjs b/frontend/packages/swarm-ui/test/stream-connection.test.mjs index c8f34fd65..a66f3af94 100644 --- a/frontend/packages/swarm-ui/test/stream-connection.test.mjs +++ b/frontend/packages/swarm-ui/test/stream-connection.test.mjs @@ -1,6 +1,9 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { connectionAfterError } from "../src/ui/stream/connection.ts"; +import { + connectionAfterError, + openStream, +} from "../src/ui/stream/connection.ts"; test("connectionAfterError: the browser still retrying is reconnecting", () => { assert.equal(connectionAfterError(0), "reconnecting"); @@ -13,3 +16,66 @@ test("connectionAfterError: a given-up stream is closed", () => { test("connectionAfterError: an open readyState on error is also closed", () => { assert.equal(connectionAfterError(1), "closed"); }); + +// A fake event source the test drives by hand. +function fakeStream() { + const source = { + onopen: null, + onmessage: null, + onerror: null, + readyState: 0, + closed: false, + close() { + this.closed = true; + }, + }; + const seen = { states: [], opened: 0, messages: [], gaveUp: 0, urls: [] }; + const close = openStream({ + url: "/s", + makeSource: (url) => { + seen.urls.push(url); + return source; + }, + onState: (s) => seen.states.push(s), + onOpen: () => seen.opened++, + onMessage: (d) => seen.messages.push(d), + onGaveUp: () => seen.gaveUp++, + }); + return { source, seen, close }; +} + +test("openStream: opens the url, and open reports the state and runs onOpen", () => { + const { source, seen } = fakeStream(); + assert.deepEqual(seen.urls, ["/s"]); + source.onopen(); + assert.deepEqual(seen.states, ["open"]); + assert.equal(seen.opened, 1); +}); + +test("openStream: a message reaches onMessage as its text", () => { + const { source, seen } = fakeStream(); + source.onmessage({ data: '{"a":1}' }); + assert.deepEqual(seen.messages, ['{"a":1}']); +}); + +test("openStream: an error while the browser retries is reconnecting and not given up", () => { + const { source, seen } = fakeStream(); + source.readyState = 0; + source.onerror(); + assert.deepEqual(seen.states, ["reconnecting"]); + assert.equal(seen.gaveUp, 0); +}); + +test("openStream: an error after the browser gave up is closed and runs onGaveUp", () => { + const { source, seen } = fakeStream(); + source.readyState = 2; + source.onerror(); + assert.deepEqual(seen.states, ["closed"]); + assert.equal(seen.gaveUp, 1); +}); + +test("openStream: the returned function closes the source", () => { + const { source, close } = fakeStream(); + close(); + assert.equal(source.closed, true); +});