Watch
0
0
Fork
You've already forked hyperhive
0

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.
This commit is contained in:
iris 2026-11-26 00:57:53 +01:00
commit bbdd32c2e0
3 changed files with 294 additions and 138 deletions

View file

@ -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<ArrivedMessage[]>([]);
const [connection, setConnection] = useState<ConnectionState>("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 };
}

View file

@ -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<Response>) {
// 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<Response>,
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 (

View file

@ -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