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:
parent
7f8d6abc58
commit
bbdd32c2e0
12 changed files with 294 additions and 138 deletions
|
|
@ -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
|
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
|
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.
|
**resume** stop and restart it; **remove** deletes it after a confirmation.
|
||||||
|
A toast says `sent <name> 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
|
**+ 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
|
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,
|
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
|
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
|
**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
|
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 <domain>`);
|
||||||
**add** opens a dialog with a domain box and a tick for every agent in the
|
**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.
|
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
|
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
|
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
|
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 <domain>`). 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
|
`/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.
|
per-agent editor on the agent card yet, and no automatic entries.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
helpful hints — it just shouldn't get in the way of someone who already
|
||||||
knows what they're doing.
|
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
|
## Empty states
|
||||||
|
|
||||||
Graceful fallbacks, always — a table with zero rows should show
|
Graceful fallbacks, always — a table with zero rows should show
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,7 @@ import { Badge } from "@hive/shared/badge.js";
|
||||||
import { ActionRow } from "../../ui/action-row/ActionRow.js";
|
import { ActionRow } from "../../ui/action-row/ActionRow.js";
|
||||||
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
|
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
|
||||||
import { Button } from "../../ui/button/Button.js";
|
import { Button } from "../../ui/button/Button.js";
|
||||||
|
import { showToast } from "../../ui/toast/toasts.js";
|
||||||
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
|
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
|
||||||
import { FormStack } from "../../ui/form-stack/FormStack.js";
|
import { FormStack } from "../../ui/form-stack/FormStack.js";
|
||||||
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
|
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
|
||||||
|
|
@ -89,7 +90,7 @@ export function AllowedDomains({ agent }: { agent: string }) {
|
||||||
) {
|
) {
|
||||||
return;
|
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
|
// A list already loaded stays under a failed refetch, so a change that
|
||||||
|
|
|
||||||
|
|
@ -34,8 +34,9 @@ function useDomainList(url: string) {
|
||||||
reload,
|
reload,
|
||||||
} = useResource((signal) => fetchJson<Listing>(url, signal), [url]);
|
} = useResource((signal) => fetchJson<Listing>(url, signal), [url]);
|
||||||
|
|
||||||
async function remove(entry: AllowedDomain) {
|
/** True when the entry was removed. */
|
||||||
if (busy) return;
|
async function remove(entry: AllowedDomain): Promise<boolean> {
|
||||||
|
if (busy) return false;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
const r = await fetch(url, {
|
const r = await fetch(url, {
|
||||||
|
|
@ -45,12 +46,14 @@ function useDomainList(url: string) {
|
||||||
});
|
});
|
||||||
if (!r.ok) {
|
if (!r.ok) {
|
||||||
setRemoveError(await readApiError(r));
|
setRemoveError(await readApiError(r));
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
setRemoveError(null);
|
setRemoveError(null);
|
||||||
reload();
|
reload();
|
||||||
|
return true;
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
setRemoveError({ detail: String(e) });
|
setRemoveError({ detail: String(e) });
|
||||||
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,13 +15,12 @@
|
||||||
// endpoint today that can seed turn_state/model/ctx/cost synchronously —
|
// endpoint today that can seed turn_state/model/ctx/cost synchronously —
|
||||||
// `GET /api/agents/status`'s snapshot carries only
|
// `GET /api/agents/status`'s snapshot carries only
|
||||||
// `status_text`/`running`).
|
// `status_text`/`running`).
|
||||||
import { useEffect, useState } from "preact/hooks";
|
import { useState } from "preact/hooks";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
connectionAfterError,
|
useEventStream,
|
||||||
type ConnectionState,
|
type ConnectionState,
|
||||||
} from "../../ui/stream/connection.js";
|
} from "../../ui/stream/useEventStream.js";
|
||||||
import { probeSession } from "../../ui/session/session.js";
|
|
||||||
|
|
||||||
export type { ConnectionState };
|
export type { ConnectionState };
|
||||||
|
|
||||||
|
|
@ -68,35 +67,23 @@ export function useSwarmAgentStateStream(
|
||||||
streamUrl: string | null,
|
streamUrl: string | null,
|
||||||
): UseSwarmAgentStateStreamResult {
|
): UseSwarmAgentStateStreamResult {
|
||||||
const [header, setHeader] = useState<AgentStateHeader | null>(null);
|
const [header, setHeader] = useState<AgentStateHeader | null>(null);
|
||||||
const [connection, setConnection] = useState<ConnectionState>("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);
|
setHeader(null);
|
||||||
setConnection("connecting");
|
return {
|
||||||
// `null`: a terminal with no header to follow (a subagent's).
|
onMessage: (data) => {
|
||||||
if (streamUrl === null) return;
|
try {
|
||||||
const es = new EventSource(streamUrl);
|
setHeader(JSON.parse(data) as AgentStateHeader);
|
||||||
es.onopen = () => setConnection("open");
|
} catch {
|
||||||
es.onmessage = (e) => {
|
// Malformed payload: drop it silently. Unlike the terminal
|
||||||
try {
|
// preview there is no row list to append a "[parse err]" line
|
||||||
setHeader(JSON.parse(e.data) as AgentStateHeader);
|
// to here, and one bad header isn't worth degrading the whole
|
||||||
} catch {
|
// badge cluster over — the next valid header replaces it.
|
||||||
// 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 };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,14 +6,13 @@
|
||||||
// resumes a reconnect, so rows are kept across one. Rows that arrive within
|
// 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:
|
// 50 ms are folded in together, and `term-rows.ts` holds the rules for that:
|
||||||
// coalesce by key, and keep the newest `MAX_ROWS`.
|
// 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 type { TermMsg, TermRow } from "@hive/shared/term-msg.js";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
connectionAfterError,
|
useEventStream,
|
||||||
type ConnectionState,
|
type ConnectionState,
|
||||||
} from "../../ui/stream/connection.js";
|
} from "../../ui/stream/useEventStream.js";
|
||||||
import { probeSession } from "../../ui/session/session.js";
|
|
||||||
import { appendRows } from "./term-rows.js";
|
import { appendRows } from "./term-rows.js";
|
||||||
|
|
||||||
export type { ConnectionState };
|
export type { ConnectionState };
|
||||||
|
|
@ -33,14 +32,10 @@ export function useSwarmTermStream(
|
||||||
streamUrl: string,
|
streamUrl: string,
|
||||||
): UseSwarmTermStreamResult {
|
): UseSwarmTermStreamResult {
|
||||||
const [rows, setRows] = useState<TermRow[]>([]);
|
const [rows, setRows] = useState<TermRow[]>([]);
|
||||||
const [connection, setConnection] = useState<ConnectionState>("connecting");
|
|
||||||
const keySeqRef = useRef(0);
|
const keySeqRef = useRef(0);
|
||||||
// Bumped by `reconnect`, which reruns the effect below.
|
|
||||||
const [attempt, setAttempt] = useState(0);
|
|
||||||
|
|
||||||
useEffect(() => {
|
const { connection, reconnect } = useEventStream(streamUrl, () => {
|
||||||
setRows([]);
|
setRows([]);
|
||||||
setConnection("connecting");
|
|
||||||
keySeqRef.current = 0;
|
keySeqRef.current = 0;
|
||||||
let batch: TermRow[] = [];
|
let batch: TermRow[] = [];
|
||||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
@ -54,36 +49,29 @@ export function useSwarmTermStream(
|
||||||
batch.push(row);
|
batch.push(row);
|
||||||
if (timer === null) timer = setTimeout(flush, BATCH_MS);
|
if (timer === null) timer = setTimeout(flush, BATCH_MS);
|
||||||
}
|
}
|
||||||
const es = new EventSource(streamUrl);
|
return {
|
||||||
es.onopen = () => setConnection("open");
|
onMessage: (data) => {
|
||||||
es.onmessage = (e) => {
|
keySeqRef.current += 1;
|
||||||
keySeqRef.current += 1;
|
const key = "r" + keySeqRef.current;
|
||||||
const key = "r" + keySeqRef.current;
|
let msg: TermMsg;
|
||||||
let msg: TermMsg;
|
try {
|
||||||
try {
|
msg = JSON.parse(data);
|
||||||
msg = JSON.parse(e.data);
|
} catch {
|
||||||
} catch {
|
push({
|
||||||
push({
|
key,
|
||||||
key,
|
level: "warn",
|
||||||
level: "warn",
|
fromHistory: false,
|
||||||
fromHistory: false,
|
summary: "[parse err] " + data,
|
||||||
summary: "[parse err] " + e.data,
|
});
|
||||||
});
|
return;
|
||||||
return;
|
}
|
||||||
}
|
push({ ...msg, key, fromHistory: false });
|
||||||
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 };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,15 +7,14 @@
|
||||||
// Each message gets an id as it arrives, and the events that arrive within one
|
// 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 join the list in a single update, so a long replay is one render per
|
||||||
// frame instead of one per message.
|
// 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 type { ArrivedMessage, SwarmMessage } from "./messages.js";
|
||||||
import { messagesUrl, newest, numbered } from "./messages.js";
|
import { messagesUrl, newest, numbered } from "./messages.js";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
connectionAfterError,
|
useEventStream,
|
||||||
type ConnectionState,
|
type ConnectionState,
|
||||||
} from "../../ui/stream/connection.js";
|
} from "../../ui/stream/useEventStream.js";
|
||||||
import { probeSession } from "../../ui/session/session.js";
|
|
||||||
|
|
||||||
export type { ConnectionState };
|
export type { ConnectionState };
|
||||||
|
|
||||||
|
|
@ -29,59 +28,49 @@ export function useMessageStream(sinceMinutes: number): {
|
||||||
reconnect: () => void;
|
reconnect: () => void;
|
||||||
} {
|
} {
|
||||||
const [messages, setMessages] = useState<ArrivedMessage[]>([]);
|
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
|
// The next id to hand out; it never goes back, so an id is not reused after
|
||||||
// a reconnect either.
|
// a reconnect either.
|
||||||
const nextId = useRef(0);
|
const nextId = useRef(0);
|
||||||
// Bumped by `reconnect`, which reruns the effect below.
|
|
||||||
const [attempt, setAttempt] = useState(0);
|
|
||||||
|
|
||||||
useEffect(() => {
|
const { connection, reconnect } = useEventStream(
|
||||||
setMessages([]);
|
messagesUrl(sinceMinutes),
|
||||||
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();
|
|
||||||
setMessages([]);
|
setMessages([]);
|
||||||
setConnection("open");
|
let pending: SwarmMessage[] = [];
|
||||||
};
|
let frame: number | null = null;
|
||||||
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]);
|
|
||||||
|
|
||||||
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 };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -117,8 +117,14 @@ function SchedulesBody() {
|
||||||
|
|
||||||
// One mutation on one schedule: pending while in flight, the error kept
|
// 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
|
// for the banner, a refetch on success so the card shows the controller's
|
||||||
// own answer rather than a guessed one.
|
// own answer rather than a guessed one. `done` is a toast for a change the
|
||||||
async function act(id: string, request: () => Promise<Response>) {
|
// 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);
|
markPending(id, true);
|
||||||
setActionError(null);
|
setActionError(null);
|
||||||
setErrorContext(SCHEDULE_UNCHANGED);
|
setErrorContext(SCHEDULE_UNCHANGED);
|
||||||
|
|
@ -129,6 +135,7 @@ function SchedulesBody() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
refresh();
|
refresh();
|
||||||
|
if (done) showToast(done, "ok");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setActionError({ detail: String(err) });
|
setActionError({ detail: String(err) });
|
||||||
} finally {
|
} finally {
|
||||||
|
|
@ -180,12 +187,15 @@ function SchedulesBody() {
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
if (!yes) return;
|
if (!yes) return;
|
||||||
return act(s.id, () =>
|
return act(
|
||||||
fetch(`/api/schedules/${encodeURIComponent(s.id)}`, {
|
s.id,
|
||||||
method: "PATCH",
|
() =>
|
||||||
headers: { "content-type": "application/json" },
|
fetch(`/api/schedules/${encodeURIComponent(s.id)}`, {
|
||||||
body: JSON.stringify(fireNowBody(Date.now())),
|
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);
|
setCreating(false);
|
||||||
setEditingId(null);
|
setEditingId(null);
|
||||||
refresh();
|
refresh();
|
||||||
|
showToast("schedule saved", "ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
|
||||||
|
|
@ -22,6 +22,7 @@ import {
|
||||||
useDeniedDomains,
|
useDeniedDomains,
|
||||||
} from "../../agent/detail/useAllowedDomains.js";
|
} from "../../agent/detail/useAllowedDomains.js";
|
||||||
import { Button } from "../../ui/button/Button.js";
|
import { Button } from "../../ui/button/Button.js";
|
||||||
|
import { showToast } from "../../ui/toast/toasts.js";
|
||||||
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
|
import { useConfirm } from "../../ui/confirm-dialog/useConfirm.js";
|
||||||
import { LazyDisclosure } from "../../ui/disclosure/LazyDisclosure.js";
|
import { LazyDisclosure } from "../../ui/disclosure/LazyDisclosure.js";
|
||||||
import { Dialog } from "../../ui/dialog/Dialog.js";
|
import { Dialog } from "../../ui/dialog/Dialog.js";
|
||||||
|
|
@ -66,7 +67,7 @@ function DomainSection({
|
||||||
) {
|
) {
|
||||||
return;
|
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
|
// A list already loaded stays under a failed refetch, so a change that
|
||||||
|
|
|
||||||
|
|
@ -12,3 +12,41 @@ const CONNECTING = 0;
|
||||||
export function connectionAfterError(readyState: number): ConnectionState {
|
export function connectionAfterError(readyState: number): ConnectionState {
|
||||||
return readyState === CONNECTING ? "reconnecting" : "closed";
|
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();
|
||||||
|
}
|
||||||
|
|
|
||||||
61
frontend/packages/swarm-ui/src/ui/stream/useEventStream.ts
Normal file
61
frontend/packages/swarm-ui/src/ui/stream/useEventStream.ts
Normal file
|
|
@ -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<ConnectionState>("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) };
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,9 @@
|
||||||
import { test } from "node:test";
|
import { test } from "node:test";
|
||||||
import assert from "node:assert/strict";
|
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", () => {
|
test("connectionAfterError: the browser still retrying is reconnecting", () => {
|
||||||
assert.equal(connectionAfterError(0), "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", () => {
|
test("connectionAfterError: an open readyState on error is also closed", () => {
|
||||||
assert.equal(connectionAfterError(1), "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);
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue