Watch
0
0
Fork
You've already forked hyperhive
0

swarm ui: select several agents on the agents page and broadcast to them

Select mode picks agents from the list: the select button in the filter
card, a press on an agent's icon, or a long press on a card starts it. In
it a card toggles a tick instead of opening its details, and the card's own
controls stop answering. A bar at the foot of the list has select all shown,
clear, broadcast and done; Escape leaves the mode.

Broadcast opens a dialog with the picked agents and a message box, sending
through the existing broadcast endpoint; the composer's send and result
parts are now shared with the swarm page's broadcast card. A full send shows
a toast and ends select mode; a partial one keeps the result with a retry
for the agents that failed.
This commit is contained in:
iris 2026-11-22 18:47:53 +01:00
commit 56ed2e07da
16 changed files with 793 additions and 88 deletions

View file

@ -62,3 +62,68 @@
outline: 2px solid var(--purple);
outline-offset: 2px;
}
/* The icon is where a press starts select mode, so it shows the pointer; the tick
sits over its corner while picking. */
.ui-agent-card-icon {
position: relative;
flex: none;
display: block;
cursor: pointer;
}
.ui-agent-card-row[role="checkbox"] {
cursor: pointer;
}
.ui-agent-card-row[role="checkbox"] .ui-agent-card-icon {
cursor: inherit;
}
.ui-agent-card-tick {
position: absolute;
top: 0.3em;
right: 0.3em;
width: 1.4em;
height: 1.4em;
box-sizing: border-box;
border: 2px solid var(--muted);
border-radius: 50%;
background: color-mix(in srgb, var(--bg) 70%, transparent);
transition:
background-color 0.15s ease,
border-color 0.15s ease,
transform 0.15s ease;
}
.ui-agent-card-tick-on {
border-color: var(--purple);
background: var(--purple);
transform: scale(1.1);
}
/* The check mark inside, drawn with two borders, in the card's own background. */
.ui-agent-card-tick-on::after {
content: "";
position: absolute;
left: 0.38em;
top: 0.14em;
width: 0.28em;
height: 0.58em;
border: solid var(--bg);
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
/* Not a control while picking: the card takes the click. */
.ui-agent-card-row[role="checkbox"] [inert] {
opacity: 0.55;
}
@media (prefers-reduced-motion: reduce) {
.ui-agent-card-tick {
transition: none;
}
}
:root[data-motion="reduce"] .ui-agent-card-tick {
transition: none;
}
/* A press and hold starts select mode, so it must not also select the text. */
.ui-agent-card-row {
-webkit-user-select: none;
user-select: none;
-webkit-touch-callout: none;
}

View file

@ -5,6 +5,12 @@
// which the page turns into `/agents/<name>`); the card of the open agent is
// marked `selected`.
//
// In select mode (`select` is set) a choice toggles the card's tick instead, to
// pick several agents for something to do to all of them. A tick on the icon
// shows which are picked; the card's own controls (terminal, wanted menu, login)
// stop answering so a stray tap can't start or stop an agent. Outside select
// mode, a press on the icon, or a long press on the card, starts it (`onStartSelect`).
//
// The terminal badge beside the wanted menu opens the agent's terminal tab, the
// most common action, without opening the card.
//
@ -17,6 +23,7 @@ import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { Badge } from "@hive/shared/badge.js";
import { TerminalIcon } from "@hive/shared/icons.js";
import { Card } from "../../ui/card/Card.js";
import { useLongPress } from "./useLongPress.js";
import { useDynamicTabs } from "../../shell/useDynamicTabs.js";
import { AgentIcon } from "../AgentIcon.js";
import { ClaudeLoginDialog } from "../claude-login/ClaudeLoginDialog.js";
@ -41,6 +48,8 @@ export function AgentCard({
actions,
selected = false,
onOpen,
select,
onStartSelect,
}: {
row: AgentRow;
actions: AgentActions;
@ -48,29 +57,63 @@ export function AgentCard({
selected?: boolean;
/** Called when the card is chosen, to open the agent's details. */
onOpen: () => void;
/** Set in select mode: whether this agent is picked, and the way to flip it. */
select?: { picked: boolean; onToggle: () => void };
/** Called to enter select mode with this agent picked. */
onStartSelect: () => void;
}) {
const [loggingIn, setLoggingIn] = useState(false);
const error = actions.actionErrors.get(row.name);
const { open: openTab } = useDynamicTabs();
const term = termPaths(row.name);
const selecting = select !== undefined;
const choose = selecting ? select.onToggle : onOpen;
const press = useLongPress(onStartSelect, !selecting);
// The controls inside the card do nothing while picking.
const inert = selecting ? { inert: true } : {};
return (
<Card selected={selected}>
<Card selected={selecting ? select.picked : selected}>
<AgentCardLayout
rowProps={{
role: "button",
role: selecting ? "checkbox" : "button",
tabIndex: 0,
"data-agent": row.name,
"aria-current": selected ? "true" : undefined,
onClick: onOpen,
"aria-checked": selecting ? select.picked : undefined,
"aria-current": !selecting && selected ? "true" : undefined,
onClick: () => {
if (!press.shouldIgnoreClick()) choose();
},
onKeyDown: (e) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onOpen();
choose();
}
},
...press.handlers,
}}
icon={<AgentIcon name={row.name} />}
icon={
<span
class="ui-agent-card-icon"
title={selecting ? undefined : `select ${row.name}`}
onClick={(e) => {
if (selecting) return;
e.stopPropagation();
onStartSelect();
}}
>
<AgentIcon name={row.name} />
{selecting ? (
<span
class={
"ui-agent-card-tick" +
(select.picked ? " ui-agent-card-tick-on" : "")
}
aria-hidden="true"
/>
) : null}
</span>
}
name={<span class="ui-agent-card-name">{row.name}</span>}
status={
<>
@ -116,6 +159,7 @@ export function AgentCard({
<span
class="ui-agent-card-login"
onClick={(e) => e.stopPropagation()}
{...inert}
>
<Badge
tone="warning"
@ -142,6 +186,7 @@ export function AgentCard({
<span
class="ui-agent-card-wanted"
onClick={(e) => e.stopPropagation()}
{...inert}
>
<Badge
variant="quiet"

View file

@ -0,0 +1,44 @@
// A long press: the pointer held down on one spot for `LONG_PRESS_MS`. Plain
// functions so `npm test` runs them; `useLongPress` wires them to a component.
/** How long a press must last to count as a long one. */
export const LONG_PRESS_MS = 500;
/** How far (px) the pointer may stray before the press is a drag or a scroll. */
export const LONG_PRESS_SLOP = 8;
/** Whether the pointer has left the spot where the press began. */
export function strayed(
from: { x: number; y: number },
to: { x: number; y: number },
): boolean {
return Math.hypot(to.x - from.x, to.y - from.y) > LONG_PRESS_SLOP;
}
/**
* Whether a long press has just started select mode and its closing click is
* still to come. Every press starts by clearing it (`pressed`), so a long press
* that ends with no click (the browser's own menu on a touch screen, a release
* off the card) cannot swallow the next real tap.
*/
export function createLongPressFlag() {
let fired = false;
return {
/** A new press begins. */
pressed: () => {
fired = false;
},
/** The press ran long enough. */
fire: () => {
fired = true;
},
/** The click after a press: true once if that press was a long one. */
consumeClick: () => {
const was = fired;
fired = false;
return was;
},
/** Whether the context menu that a long press opens should be blocked. */
blocksContextMenu: () => fired,
};
}

View file

@ -0,0 +1,57 @@
// useLongPress — handlers to spread on an element so that holding a pointer
// (finger or mouse) on it for `LONG_PRESS_MS` calls `onLongPress`. A press that
// moves, lifts early or is cancelled (a scroll starting) does nothing. The click
// that follows a long press is the same gesture ending, so `shouldIgnoreClick`
// tells the click handler to skip it, once (`createLongPressFlag`).
import { useRef } from "preact/hooks";
import { LONG_PRESS_MS, createLongPressFlag, strayed } from "./long-press.js";
type PointerHandler = (e: PointerEvent) => void;
export function useLongPress(onLongPress: () => void, enabled = true) {
const timer = useRef<number | undefined>(undefined);
const origin = useRef({ x: 0, y: 0 });
const flag = useRef(createLongPressFlag());
const cancel = () => {
window.clearTimeout(timer.current);
timer.current = undefined;
};
// Always attached, even while `enabled` is off: every press has to clear the
// flag, or a long press that began select mode would leave it set.
const onPointerDown: PointerHandler = (e) => {
flag.current.pressed();
cancel();
// A press on a control inside (the terminal button, a menu) is that
// control's own.
if (!enabled) return;
if ((e.target as HTMLElement).closest("button, a, input") !== null) return;
origin.current = { x: e.clientX, y: e.clientY };
timer.current = window.setTimeout(() => {
timer.current = undefined;
flag.current.fire();
onLongPress();
}, LONG_PRESS_MS);
};
const onPointerMove: PointerHandler = (e) => {
if (timer.current === undefined) return;
if (strayed(origin.current, { x: e.clientX, y: e.clientY })) cancel();
};
return {
handlers: {
onPointerDown,
onPointerMove,
onPointerUp: cancel,
onPointerCancel: cancel,
onPointerLeave: cancel,
// A long press on a touch screen also opens the browser's own menu.
onContextMenu: (e: Event) => {
if (flag.current.blocksContextMenu()) e.preventDefault();
},
},
/** True once after a long press, so its closing click is not a plain one. */
shouldIgnoreClick: () => flag.current.consumeClick(),
};
}

View file

@ -20,11 +20,12 @@
// the list narrows to a column and the agent's details slide in beside it, and
// on a narrow screen they replace the list (mara: "it only becomes a
// main-detail page only when an agent is tapped"). `AgentsLayout` owns the
// columns and `AgentDetailPane` the details; this file owns the page's own
// state and the filter fields only. `AgentRow` and friends live in
// `AgentTypes.ts`, the wanted-state control in `WantedMenu.tsx`, the actions
// on an agent in `AgentActions.tsx`, the card in `AgentCard.tsx`. The filter
// bar is `FilterableView` (`ui/filterable-view/`, see its own comment).
// columns and `AgentDetailPane` the details. Select mode (the icon, a long press
// or the **select** button) picks several agents to broadcast to: see
// `useAgentSelection`, `SelectionBar` and `BroadcastDialog`. This file owns the
// page's own state and the filter fields; `AgentRow` and friends live in
// `AgentTypes.ts`, the actions on an agent in `AgentActions.tsx`, the card in
// `AgentCard.tsx`. The filter bar is `FilterableView`.
import { useEffect, useRef, useState } from "preact/hooks";
import { useLocation } from "wouter-preact";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
@ -37,6 +38,9 @@ import { Dialog } from "../../ui/dialog/Dialog.js";
import { SkeletonRegion } from "../../ui/skeleton/Skeleton.js";
import { AgentDetailPane } from "./AgentDetailPane.js";
import { AgentsLayout } from "./AgentsLayout.js";
import { BroadcastDialog } from "./BroadcastDialog.js";
import { SelectionBar } from "./SelectionBar.js";
import { useAgentSelection } from "./useAgentSelection.js";
import { usePageTitle } from "../../shell/page-title.js";
import { agentPath, selectedAgent } from "../../shell/routes.js";
import { FilterableView } from "../../ui/filterable-view/FilterableView.js";
@ -110,6 +114,8 @@ export function AgentsPage() {
{ cacheKey: "agents" },
);
const [createOpen, setCreateOpen] = useState(false);
const [broadcasting, setBroadcasting] = useState(false);
const picks = useAgentSelection((rows ?? []).map((a) => a.name));
const [path, navigate] = useLocation();
const selected = selectedAgent(path);
// The details stay drawn, fading out, while the column closes.
@ -154,6 +160,9 @@ export function AgentsPage() {
<Button variant="primary" onClick={() => setCreateOpen(true)}>
+ agent
</Button>
<Button onClick={() => (picks.selecting ? picks.stop() : picks.start())}>
{picks.selecting ? "done" : "select"}
</Button>
<RefreshIntervalPicker
id="agents-refresh"
value={intervalMs}
@ -211,8 +220,29 @@ export function AgentsPage() {
actions={actions}
selected={a.name === selected}
onOpen={() => navigate(agentPath(a.name))}
select={
picks.selecting
? {
picked: picks.picked.includes(a.name),
onToggle: () => picks.toggle(a.name),
}
: undefined
}
onStartSelect={() => picks.start(a.name)}
/>
)}
footer={(shown) =>
picks.selecting ? (
<SelectionBar
count={picks.picked.length}
shown={shown.length}
onSelectAll={() => picks.pickAll(shown.map((a) => a.name))}
onClear={picks.clear}
onBroadcast={() => setBroadcasting(true)}
onDone={picks.stop}
/>
) : null
}
/>
}
/>
@ -225,6 +255,17 @@ export function AgentsPage() {
>
<CreateAgentForm onClose={() => setCreateOpen(false)} />
</Dialog>
{broadcasting ? (
<BroadcastDialog
agents={picks.picked}
onClose={() => setBroadcasting(false)}
onSent={() => {
setBroadcasting(false);
picks.stop();
}}
onRetry={picks.set}
/>
) : null}
{actions.dialogs}
</>
);

View file

@ -0,0 +1,29 @@
/* <BroadcastDialog>: the recipients, the message, the result. */
.agents-broadcast {
display: flex;
flex-direction: column;
gap: 1em;
min-width: min(32em, 80vw);
}
.agents-broadcast-targets {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 0.4em;
}
.agents-broadcast-targets li {
display: inline-flex;
align-items: center;
gap: 0.4em;
padding: 0.2em 0.6em;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--bg);
font-size: 0.9em;
}
.agents-broadcast-send {
display: flex;
justify-content: flex-end;
}

View file

@ -0,0 +1,115 @@
// <BroadcastDialog> — one message to the agents picked on the agents page. The
// picked agents are listed, the message goes in a box, and the send posts it to
// `POST /api/agents/broadcast` (see `broadcast-send.ts`). When every agent got
// it, a toast says so and the dialog closes; when some did not, the dialog stays
// with the per-agent result, and "select the N that failed" hands those agents
// back to the page's pick so the same words go to just them.
//
// The dialog mounts while it is open, so a new one starts with an empty box.
import { useState } from "preact/hooks";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { AgentIcon } from "../../agent/AgentIcon.js";
import { Button } from "../../ui/button/Button.js";
import { Dialog } from "../../ui/dialog/Dialog.js";
import { Panel } from "../../ui/panel/Panel.js";
import { TextAreaField } from "../../ui/text-area-field/TextAreaField.js";
import { showToast } from "../../ui/toast/toasts.js";
import { failedAgents, sendLabel } from "../broadcast/broadcast-types.js";
import { postBroadcast, type SendState } from "../broadcast/broadcast-send.js";
import { SendResults } from "../broadcast/SendResults.js";
import "./BroadcastDialog.css";
export function BroadcastDialog({
agents,
onClose,
onSent,
onRetry,
}: {
/** The agents to send to, in the order they were picked. */
agents: string[];
onClose: () => void;
/** Every agent got the message. */
onSent: () => void;
/** Some did not: the page picks just those. */
onRetry: (failed: string[]) => void;
}) {
const [body, setBody] = useState("");
const [send, setSend] = useState<SendState>({ status: "idle" });
const sending = send.status === "sending";
async function submit(e: Event) {
e.preventDefault();
if (sending || body.trim() === "" || agents.length === 0) return;
setSend({ status: "sending" });
const answer = await postBroadcast(agents, body);
if (answer.status === "done" && failedAgents(answer.results).length === 0) {
showToast(
agents.length === 1
? `sent to ${agents[0]}`
: `sent to ${agents.length} agents`,
"ok",
);
onSent();
return;
}
setSend(answer);
}
return (
<Dialog
open
onClose={onClose}
label="broadcast to the selected agents"
plain
>
<Panel
title={`broadcast to ${agents.length === 1 ? agents[0] : `${agents.length} agents`}`}
icon="📣"
onClose={onClose}
>
<form class="agents-broadcast" onSubmit={submit}>
<ul class="agents-broadcast-targets" aria-label="recipients">
{agents.map((name) => (
<li key={name}>
<AgentIcon name={name} small />
{name}
</li>
))}
</ul>
<TextAreaField
id="agents-broadcast-body"
label="message"
value={body}
rows={5}
placeholder="sent exactly as typed, from you, to each selected agent"
onInput={setBody}
/>
<div class="agents-broadcast-send">
<Button
variant="primary"
type="submit"
busy={sending}
disabled={body.trim() === "" || agents.length === 0}
>
{sendLabel(agents.length)}
</Button>
</div>
<div aria-live="polite">
{send.status === "error" ? (
<ApiErrorPanel context="failed to send" problem={send.problem} />
) : null}
{send.status === "done" ? (
<SendResults
results={send.results}
onRetry={(results) => {
setSend({ status: "idle" });
onRetry(failedAgents(results));
}}
/>
) : null}
</div>
</form>
</Panel>
</Dialog>
);
}

View file

@ -0,0 +1,60 @@
/* <SelectionBar>: sticks to the foot of the viewport under the list. */
.agents-selection-bar {
position: sticky;
bottom: 0.75em;
z-index: 5;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5em 1em;
margin-top: 0.75em;
padding: 0.6em 1em;
border: 1px solid var(--purple);
border-radius: 0.5em;
background: color-mix(in srgb, var(--bg-elev) 92%, var(--purple));
box-shadow: 0 0.4em 1.2em color-mix(in srgb, var(--crust) 60%, transparent);
animation: agents-selection-bar-in 180ms ease;
}
.agents-selection-count {
font-weight: 600;
}
.agents-selection-link {
border: none;
background: none;
padding: 0.25em 0;
color: var(--blue);
font: inherit;
cursor: pointer;
}
.agents-selection-link:disabled {
color: var(--muted);
cursor: default;
}
.agents-selection-actions {
display: flex;
align-items: center;
gap: 0.5em;
margin-left: auto;
}
.agents-selection-cap {
color: var(--red);
font-size: 0.9em;
}
@keyframes agents-selection-bar-in {
from {
opacity: 0;
transform: translateY(0.75em);
}
to {
opacity: 1;
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
.agents-selection-bar {
animation: none;
}
}
:root[data-motion="reduce"] .agents-selection-bar {
animation: none;
}

View file

@ -0,0 +1,66 @@
// <SelectionBar> — the bar at the foot of the agents list in select mode: how
// many agents are picked, the ways to change the pick (all shown, none), the
// action to take on them (broadcast, the only one so far) and done, which leaves
// select mode. It sticks to the bottom of the viewport while the list scrolls
// under it, so the action is in reach however far down the picks are.
import { Button } from "../../ui/button/Button.js";
import { MAX_BROADCAST } from "../broadcast/broadcast-types.js";
import "./SelectionBar.css";
export function SelectionBar({
count,
shown,
onSelectAll,
onClear,
onBroadcast,
onDone,
}: {
/** Agents picked. */
count: number;
/** Agents the filter shows, so "select all" has something to pick. */
shown: number;
onSelectAll: () => void;
onClear: () => void;
onBroadcast: () => void;
onDone: () => void;
}) {
const overCap = count > MAX_BROADCAST;
return (
<div class="agents-selection-bar" role="toolbar" aria-label="selection">
<span class="agents-selection-count" role="status">
{count === 0 ? "none selected" : `${count} selected`}
</span>
<button
type="button"
class="agents-selection-link"
disabled={shown === 0}
onClick={onSelectAll}
>
select all shown
</button>
<button
type="button"
class="agents-selection-link"
disabled={count === 0}
onClick={onClear}
>
clear
</button>
<span class="agents-selection-actions">
{overCap ? (
<span class="agents-selection-cap" role="status">
at most {MAX_BROADCAST} at once
</span>
) : null}
<Button
variant="primary"
disabled={count === 0 || overCap}
onClick={onBroadcast}
>
broadcast…
</Button>
<Button onClick={onDone}>done</Button>
</span>
</div>
);
}

View file

@ -0,0 +1,30 @@
// The agents page's picks for select mode. Plain functions with no imports, so
// `npm test` runs them; `useAgentSelection` holds the state.
/** `picked` without the agents the roster no longer has (one destroyed meanwhile). */
export function stillThere(picked: string[], roster: string[]): string[] {
const known = new Set(roster);
return picked.filter((name) => known.has(name));
}
/** Starting select mode on `name`: it is picked, and any earlier picks stay. */
export function startedOn(picked: string[], name: string | null): string[] {
if (name === null || picked.includes(name)) return picked;
return [...picked, name];
}
/** `picked` with `name` flipped. */
export function toggled(picked: string[], name: string): string[] {
return picked.includes(name)
? picked.filter((n) => n !== name)
: [...picked, name];
}
/** `picked` plus every shown agent, without repeating a name. */
export function pickedAll(picked: string[], shown: string[]): string[] {
const out = [...picked];
for (const name of shown) {
if (!out.includes(name)) out.push(name);
}
return out;
}

View file

@ -0,0 +1,41 @@
// useAgentSelection — the agents page's select mode: whether it is on, and which
// agents are picked. Escape leaves it, unless a dialog is open (the dialog takes
// the Escape). A pick whose agent leaves the roster drops out of the count.
import { useEffect, useState } from "preact/hooks";
import { pickedAll, startedOn, stillThere, toggled } from "./selection.js";
export function useAgentSelection(roster: string[]) {
const [selecting, setSelecting] = useState(false);
const [raw, setPicked] = useState<string[]>([]);
const picked = stillThere(raw, roster);
useEffect(() => {
if (!selecting) return;
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Escape" || document.querySelector("dialog[open]")) return;
setSelecting(false);
setPicked([]);
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [selecting]);
return {
selecting,
picked,
/** Enter select mode, with `name` picked when given. */
start: (name: string | null = null) => {
setSelecting(true);
setPicked((prev) => startedOn(prev, name));
},
/** Leave select mode and forget the picks. */
stop: () => {
setSelecting(false);
setPicked([]);
},
toggle: (name: string) => setPicked((prev) => toggled(prev, name)),
pickAll: (shown: string[]) => setPicked((prev) => pickedAll(prev, shown)),
clear: () => setPicked([]),
set: setPicked,
};
}

View file

@ -14,8 +14,6 @@
// controller takes the sender from the gateway, as for the single-agent box).
import { useState } from "preact/hooks";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { AgentIcon } from "../../agent/AgentIcon.js";
import { AgentPicker } from "../../agent/picker/AgentPicker.js";
import { Button } from "../../ui/button/Button.js";
import {
@ -31,7 +29,6 @@ import {
failedAgents,
filterShowing,
isRunning,
parseResults,
selectedVisible,
MAX_BROADCAST,
sendLabel,
@ -42,17 +39,13 @@ import {
type BroadcastAgent,
type BroadcastResult,
} from "./broadcast-types.js";
import { postBroadcast, type SendState } from "./broadcast-send.js";
import { SendResults } from "./SendResults.js";
import "./BroadcastComposer.css";
const DEFAULT_INTERVAL_MS: RefreshIntervalMs = 30_000;
const FILTER_KEY = "swarm-ui:broadcast:filter";
type SendState =
| { status: "idle" }
| { status: "sending" }
| { status: "done"; results: BroadcastResult[] }
| { status: "error"; problem: ProblemDetails };
function storedFilter(): AgentFilter {
try {
return localStorage.getItem(FILTER_KEY) === "all" ? "all" : "running";
@ -122,30 +115,12 @@ export function BroadcastComposer() {
e.preventDefault();
if (!canSend) return;
setSend({ status: "sending" });
try {
const res = await fetch("/api/agents/broadcast", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ agents: targets, body }),
});
if (!res.ok) {
setSend({ status: "error", problem: await readApiError(res) });
return;
}
const results = parseResults(await res.json());
if (results === null) {
setSend({
status: "error",
problem: { detail: "the controller's answer was not understood" },
});
return;
}
setSend({ status: "done", results });
// Everyone got it: the text has served its purpose. A partial send keeps
// it so the retry to the rest sends the same words.
if (failedAgents(results).length === 0) setBody("");
} catch (err) {
setSend({ status: "error", problem: { detail: String(err) } });
const answer = await postBroadcast(targets, body);
setSend(answer);
// Everyone got it: the text has served its purpose. A partial send keeps
// it so the retry to the rest sends the same words.
if (answer.status === "done" && failedAgents(answer.results).length === 0) {
setBody("");
}
}
@ -261,46 +236,3 @@ export function BroadcastComposer() {
</>
);
}
function SendResults({
results,
onRetry,
}: {
results: BroadcastResult[];
onRetry: (results: BroadcastResult[]) => void;
}) {
const failed = failedAgents(results);
const sent = results.length - failed.length;
return (
<section class="ui-broadcast-results" aria-label="send result">
<p class="ui-broadcast-summary">
sent to {sent} of {results.length}
{failed.length > 0 && (
<button
type="button"
class="ui-broadcast-link"
onClick={() => onRetry(results)}
>
select the {failed.length} that failed
</button>
)}
</p>
<ul class="ui-broadcast-outcomes">
{results.map((r) => (
<li
key={r.agent}
class={r.sent ? "ui-broadcast-ok" : "ui-broadcast-fail"}
>
<AgentIcon name={r.agent} small />
<span class="ui-broadcast-outcome-name">{r.agent}</span>
<span>
{r.sent
? "✓ sent"
: `✗ not sent${r.reason ? `: ${r.reason}` : ""}`}
</span>
</li>
))}
</ul>
</section>
);
}

View file

@ -0,0 +1,48 @@
// <SendResults> — what a broadcast came back with: how many agents got it, one
// line per agent, and a way to select just the ones that failed for a retry.
import { AgentIcon } from "../../agent/AgentIcon.js";
import { failedAgents, type BroadcastResult } from "./broadcast-types.js";
import "./BroadcastComposer.css";
export function SendResults({
results,
onRetry,
}: {
results: BroadcastResult[];
onRetry: (results: BroadcastResult[]) => void;
}) {
const failed = failedAgents(results);
const sent = results.length - failed.length;
return (
<section class="ui-broadcast-results" aria-label="send result">
<p class="ui-broadcast-summary">
sent to {sent} of {results.length}
{failed.length > 0 && (
<button
type="button"
class="ui-broadcast-link"
onClick={() => onRetry(results)}
>
select the {failed.length} that failed
</button>
)}
</p>
<ul class="ui-broadcast-outcomes">
{results.map((r) => (
<li
key={r.agent}
class={r.sent ? "ui-broadcast-ok" : "ui-broadcast-fail"}
>
<AgentIcon name={r.agent} small />
<span class="ui-broadcast-outcome-name">{r.agent}</span>
<span>
{r.sent
? "✓ sent"
: `✗ not sent${r.reason ? `: ${r.reason}` : ""}`}
</span>
</li>
))}
</ul>
</section>
);
}

View file

@ -0,0 +1,37 @@
// Sending one message to several agents: `POST /api/agents/broadcast` answers
// one outcome per agent, so one that is down does not stop the rest. The
// composer on the swarm page and the agents page's broadcast dialog both send
// through this, and show the answer with `SendResults`.
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { parseResults, type BroadcastResult } from "./broadcast-types.js";
export type SendState =
| { status: "idle" }
| { status: "sending" }
| { status: "done"; results: BroadcastResult[] }
| { status: "error"; problem: ProblemDetails };
/** Sends `body` to `agents`, as typed; settles on `done` or `error`. */
export async function postBroadcast(
agents: string[],
body: string,
): Promise<SendState> {
try {
const res = await fetch("/api/agents/broadcast", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ agents, body }),
});
if (!res.ok) return { status: "error", problem: await readApiError(res) };
const results = parseResults(await res.json());
if (results === null) {
return {
status: "error",
problem: { detail: "the controller's answer was not understood" },
};
}
return { status: "done", results };
} catch (err) {
return { status: "error", problem: { detail: String(err) } };
}
}

View file

@ -146,10 +146,13 @@ export function FilterableView<T>(
// `barActions` (buttons, a refresh picker) sit at its trailing edge.
standalone?: boolean;
barActions?: ComponentChildren;
// Cards view only. Drawn after the cards with the rows the filter leaves, so
// a bar that acts on what is shown (select all) needs no copy of the filter.
footer?: (visibleRows: T[]) => ComponentChildren;
},
) {
const { columns, rows, rowKey, storageKey, renderCard, emptyMessage } = props;
const { standalone, barActions } = props;
const { standalone, barActions, footer } = props;
const {
visibleRows,
activeFilters,
@ -198,6 +201,7 @@ export function FilterableView<T>(
))}
</div>
) : null}
{footer ? footer(visibleRows) : null}
</>
);
}

View file

@ -0,0 +1,76 @@
// The agents page's select mode: the picks and the long press. Run by `npm test`.
import assert from "node:assert/strict";
import { test } from "node:test";
import {
pickedAll,
startedOn,
stillThere,
toggled,
} from "../src/pages/agents/selection.ts";
import {
LONG_PRESS_SLOP,
createLongPressFlag,
strayed,
} from "../src/agent/roster/long-press.ts";
test("starting on an agent picks it and keeps the earlier picks", () => {
assert.deepEqual(startedOn([], "iris"), ["iris"]);
assert.deepEqual(startedOn(["argus"], "iris"), ["argus", "iris"]);
});
test("starting on an agent already picked changes nothing", () => {
const picked = ["iris"];
assert.equal(startedOn(picked, "iris"), picked);
});
test("starting with no agent (the select button) picks nothing", () => {
assert.deepEqual(startedOn([], null), []);
});
test("a click flips the agent's pick", () => {
assert.deepEqual(toggled(["a"], "b"), ["a", "b"]);
assert.deepEqual(toggled(["a", "b"], "a"), ["b"]);
});
test("select all adds every shown agent once, after the earlier picks", () => {
assert.deepEqual(pickedAll(["b"], ["a", "b", "c"]), ["b", "a", "c"]);
assert.deepEqual(pickedAll([], []), []);
});
test("a pick whose agent left the roster drops out", () => {
assert.deepEqual(stillThere(["a", "gone", "b"], ["a", "b", "c"]), ["a", "b"]);
});
test("a press that moves past the slop is not a long press", () => {
const from = { x: 10, y: 10 };
assert.equal(strayed(from, { x: 10, y: 10 }), false);
assert.equal(strayed(from, { x: 10 + LONG_PRESS_SLOP, y: 10 }), false);
assert.equal(strayed(from, { x: 10 + LONG_PRESS_SLOP + 1, y: 10 }), true);
assert.equal(strayed(from, { x: 16, y: 16 }), true);
});
test("the click that closes a long press is ignored once", () => {
const flag = createLongPressFlag();
flag.pressed();
flag.fire();
assert.equal(flag.blocksContextMenu(), true);
assert.equal(flag.consumeClick(), true);
assert.equal(flag.consumeClick(), false);
});
test("a long press that ends with no click does not swallow the next tap", () => {
const flag = createLongPressFlag();
flag.pressed();
flag.fire();
// No click follows (the context menu opened instead). The next tap starts
// with a press, which clears the flag.
flag.pressed();
assert.equal(flag.consumeClick(), false);
});
test("a plain press and click is not a long one", () => {
const flag = createLongPressFlag();
flag.pressed();
assert.equal(flag.blocksContextMenu(), false);
assert.equal(flag.consumeClick(), false);
});