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
10 changed files with 793 additions and 88 deletions

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) } };
}
}