Files
server-26/drb-frontend/components/NodeDiscordRadio.tsx
T
Logan CusanoandClaude Opus 5.5 1ee1560383 Discord picker: per-bot permission status, owner's preferred bot (server-26#225 S4)
Node-page picker and the admin Add form now show, per voice channel, whether
a radio bot can stream there, from S3's voice-check routes:
- Badge per channel: Ready / Needs fix (names the missing permission) /
  Couldn't check / Bots busy / No radio bot / Not a voice channel / Limit N.
- The chosen channel shows "<bot> can't Speak in #dispatch: <what removed it>"
  plus c2-core's fix sentence, and an expandable per-bot list.
- Footer: "Permissions checked 40s ago · Re-check" (refresh=1, rate limited
  server-side; a limited re-check says so). Invite links when no bot fits.
- Start is disabled only on a definite refusal (needs_fix, bad_channel);
  unknown fails open. A channel this system already plays in is judged by
  the bot that carries it, so Update/move is never blocked by the other bots.
- Admin Add form disables bots that are definitely denied in the bot list.
- 409 refusals (missing_permissions, preferred_busy, preferred_other_node,
  bad_channel) are shown verbatim, multi-line.

Org owners (owner decision Q2) get "Radio bot per system" on
Settings > Organization: their own systems, their own BYO bots, set/clear
through S3's PUT /tokens/{id}/prefer/{system}. New GET /tokens/org/preferred
lists only the caller org's systems and bots (no pool bots, no token
strings; a pool bot an admin chose is flagged, not named).

The prefer route now drops the 5-minute doc_get_cached entry for every
system it rewrites, so a new preference applies to the next start.

Stacked on feat/225-s3-perm-check: must merge after S3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:28:36 -04:00

579 lines
26 KiB
TypeScript

"use client";
// Node page "Discord radio" panel + picker (server-26#213 item 3, #109 item 13).
// Replaces the raw Guild ID / Voice Channel ID modal. The picker lists only
// the Discord servers linked to this node's org and the voice channels the
// DRB bot reported in them; a pick becomes a radio channel pinned to this node
// (desired state — the node reconciles and reports back, shown per row).
// A voice channel can carry several radio streams, each its own bot playing
// its own system (server-26#213 follow-up): picking a channel that already
// plays another system ADDS this node's system beside it; only a stream of
// this node's own system there is restarted / moved here.
// Layout follows design-canvas/discord-system-mockup.html "Radio channels".
// Each voice channel shows whether a radio bot can actually stream there
// (server-26#225): Ready / Needs fix (which permission, what removed it, where
// to fix it) / Couldn't check / Limit N. Start is disabled only on a definite
// deny; an unanswered check fails open.
import { useCallback, useEffect, useMemo, useState } from "react";
import { c2api } from "@/lib/c2api";
import {
blocksStart,
channelVerdict,
normalizeVoiceCheck,
parseC2Error,
type DiscordGuildOption,
type DiscordInvite,
type DiscordJoinOptions,
type DiscordStreamView,
type ParsedC2Error,
type StreamState,
type VoiceCheck,
} from "@/lib/discordPicker";
import { BotDetails, CheckFooter, FixText, VerdictBadge } from "@/components/discord/VoiceCheckBits";
const POLL_MS = 10_000;
const STATE: Record<StreamState, { label: string; dot: string }> = {
pending: { label: "on → waiting for node", dot: "bg-sev-moderate" },
connecting: { label: "on → connecting", dot: "bg-sev-moderate" },
connected: { label: "on → connected", dot: "bg-green-500" },
error: { label: "on → error", dot: "bg-sev-major" },
stopping: { label: "off → stopping", dot: "bg-ink-muted" },
stopped: { label: "off", dot: "bg-ink-muted" },
node_offline: { label: "on → node offline", dot: "bg-sev-major" },
paused_locally: { label: "on → paused on node", dot: "bg-sev-moderate" },
};
function StatePill({ s }: { s: DiscordStreamView }) {
const st = STATE[s.actual?.state ?? "pending"] ?? STATE.pending;
return (
<span className="inline-flex items-center gap-1.5 text-xs font-medium whitespace-nowrap text-ink">
<i className={`inline-block w-2 h-2 rounded-full ${st.dot}`} />
{st.label}
</span>
);
}
function InviteLinks({ invite }: { invite: DiscordInvite[] }) {
if (!invite.length) return null;
return (
<span className="flex flex-wrap gap-x-3 gap-y-1 mt-1">
{invite.map((i) => (
<a
key={i.invite_url}
href={i.invite_url}
target="_blank"
rel="noopener noreferrer"
className="text-accent hover:underline"
>
Invite {i.name}
</a>
))}
</span>
);
}
function modeLabel(mode: DiscordStreamView["mode"]) {
return mode === "persistent" ? "persistent" : "ad-hoc";
}
function streamLabel(s: DiscordStreamView) {
const sys = s.system_name ?? "radio";
return s.token_name ? `${sys} (${s.token_name})` : sys;
}
// ---------------------------------------------------------------------------
// Picker
// ---------------------------------------------------------------------------
function DiscordPicker({
nodeId,
options,
onClose,
onStarted,
}: {
nodeId: string;
options: DiscordJoinOptions;
onClose: () => void;
onStarted: () => void;
}) {
const usable = options.guilds;
const [guildId, setGuildId] = useState<string>(usable.length === 1 ? usable[0].guild_id : "");
const [channelId, setChannelId] = useState("");
const [mode, setMode] = useState<"adhoc" | "persistent">("adhoc");
const [sending, setSending] = useState(false);
const [error, setError] = useState<ParsedC2Error | null>(null);
// Permission check per server: the result, whether a load is in flight, and
// why the last load failed (shown under the footer; the badges fail open).
const [checks, setChecks] = useState<
Record<string, { data: VoiceCheck | null; busy: boolean; error: string | null; limited: boolean }>
>({});
const guild: DiscordGuildOption | undefined = usable.find((g) => g.guild_id === guildId);
const channel = guild?.voice_channels.find((c) => c.channel_id === channelId);
const atNodeCap = options.limits.node_used >= options.limits.node_max;
const channelOnHere = channel?.stream?.node_id === nodeId;
const check = guildId ? checks[guildId] : undefined;
const checkOn = check?.data?.enabled !== false;
const verdictOf = (c: DiscordGuildOption["voice_channels"][number]) => {
const row = check?.data && checkOn ? check.data.channels[c.channel_id] : undefined;
const v = channelVerdict(row);
// This system already plays here: c2-core counts its bot as busy (it holds
// the channel), so the channel can read "Needs fix"/"Bots busy" for a NEW
// bot while a restart/move keeps the one that works. Judge by that bot.
const own = c.stream?.token_name ? row?.bots.find((b) => b.name === c.stream?.token_name) : undefined;
if (v && own?.ok === true && v.kind !== "ready") return { kind: "ready" as const, limit: v.limit };
return v;
};
const chosenVerdict = channel ? verdictOf(channel) : null;
const definiteDeny = blocksStart(chosenVerdict);
const showInvite = chosenVerdict?.kind === "fix" || chosenVerdict?.kind === "no_bot" || chosenVerdict?.kind === "busy";
const runCheck = useCallback(
async (gid: string, refresh: boolean) => {
setChecks((m) => ({ ...m, [gid]: { data: m[gid]?.data ?? null, busy: true, error: null, limited: false } }));
try {
const data = normalizeVoiceCheck(await c2api.getNodeVoiceCheck(nodeId, gid, refresh));
setChecks((m) => ({ ...m, [gid]: { data, busy: false, error: null, limited: refresh && data.refreshed === false } }));
} catch (err) {
const e = parseC2Error(err);
// 404 = route not deployed yet or server not visible: no badges (fail-open).
const msg = e.status === 404 ? null : e.message;
setChecks((m) => ({ ...m, [gid]: { data: m[gid]?.data ?? null, busy: false, error: msg, limited: false } }));
}
},
[nodeId],
);
// First look at a server's channels: load its check (cached server-side).
useEffect(() => {
if (guild?.synced && !checks[guild.guild_id]) runCheck(guild.guild_id, false);
}, [guild, checks, runCheck]);
const grouped = useMemo(() => {
const out: { category: string | null; channels: DiscordGuildOption["voice_channels"] }[] = [];
for (const c of guild?.voice_channels ?? []) {
const last = out[out.length - 1];
if (last && last.category === c.category) last.channels.push(c);
else out.push({ category: c.category, channels: [c] });
}
return out;
}, [guild]);
async function start() {
if (!guild || !channel) return;
setSending(true);
setError(null);
try {
await c2api.startNodeDiscordStream(nodeId, { guild_id: guild.guild_id, channel_id: channel.channel_id, mode });
onStarted();
onClose();
} catch (err) {
const e = parseC2Error(err);
setError(e);
// The refusal may be newer than the badges (C2 drops its cache entry on
// a permission refusal) — reload them so the row matches the error.
if (e.code === "missing_permissions") runCheck(guild.guild_id, false);
} finally {
setSending(false);
}
}
return (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4" role="dialog" aria-modal="true" aria-labelledby="discord-picker-title">
<div className="bg-surface border border-line rounded-xl w-full max-w-lg max-h-[90vh] flex flex-col text-sm">
<div className="px-5 pt-5 pb-3 border-b border-line">
<h3 id="discord-picker-title" className="text-ink font-semibold text-base">Add radio channel</h3>
<p className="text-ink-muted text-xs mt-1">
Source: <span className="text-ink-2">{options.system_name ?? "no system"}</span> ·{" "}
<span className="text-ink-2">{options.node_name ?? nodeId}</span>. Audio comes from this node&apos;s
PulseAudio monitor.
</p>
</div>
<div className="px-5 py-4 space-y-4 overflow-y-auto">
{/* 1 — server */}
<fieldset>
<legend className="text-xs text-ink-muted mb-2">Discord server</legend>
{usable.length === 0 ? (
<p className="text-xs text-ink-2 bg-raised border border-line rounded-lg px-3 py-2">
No Discord server is linked to your organization yet. Add the DRB bot to your Discord server and
link it to your organization; it shows up here once the bot reports its channels.
</p>
) : (
<div className="space-y-1.5">
{usable.map((g) => (
<label
key={g.guild_id}
className={`flex items-start gap-3 rounded-lg border px-3 py-2 cursor-pointer ${
g.guild_id === guildId ? "border-accent bg-accent/10" : "border-line bg-raised hover:border-line-strong"
}`}
>
<input
type="radio"
name="guild"
className="mt-1 accent-[var(--accent)]"
checked={g.guild_id === guildId}
onChange={() => {
setGuildId(g.guild_id);
setChannelId("");
setError(null);
}}
/>
<span className="flex-1 min-w-0">
<span className="text-ink font-medium block truncate">{g.name ?? `Server ${g.guild_id}`}</span>
<span className="text-xs text-ink-muted block">
{g.linked ? "Linked" : "Default organization (not linked yet)"} · {g.streams_on} /{" "}
{options.limits.guild_max} radio channels on
</span>
{!g.bot.ok && (
<span className="text-xs text-sev-moderate block mt-1">
{g.bot.message}
<InviteLinks invite={g.bot.invite} />
</span>
)}
</span>
</label>
))}
</div>
)}
</fieldset>
{/* 2 — voice channel */}
{guild && (
<fieldset>
<legend className="text-xs text-ink-muted mb-2">Voice channel</legend>
{!guild.synced ? (
<p className="text-xs text-ink-2 bg-raised border border-line rounded-lg px-3 py-2">
The DRB bot has not reported this server&apos;s channels yet. It does when it starts and every 15
minutes — check back shortly.
</p>
) : guild.voice_channels.length === 0 ? (
<p className="text-xs text-ink-2 bg-raised border border-line rounded-lg px-3 py-2">
This server has no voice channels the DRB bot can see.
</p>
) : (
<div className="space-y-2">
{grouped.map((grp, gi) => (
<div key={`${grp.category ?? ""}-${gi}`}>
{grp.category && (
<div className="text-[11px] uppercase tracking-wider text-ink-muted mb-1">{grp.category}</div>
)}
<div className="space-y-1">
{grp.channels.map((c) => {
const here = c.stream?.node_id === nodeId;
const others = (c.streams ?? []).filter((x) => x.stream_id !== c.stream?.stream_id);
const verdict = verdictOf(c);
return (
<label
key={c.channel_id}
className={`flex items-start gap-3 rounded-lg border px-3 py-1.5 cursor-pointer ${
c.channel_id === channelId ? "border-accent bg-accent/10" : "border-line bg-raised hover:border-line-strong"
}`}
>
<input
type="radio"
name="channel"
className="mt-1 accent-[var(--accent)]"
checked={c.channel_id === channelId}
onChange={() => {
setChannelId(c.channel_id);
setError(null);
}}
/>
<span className="flex-1 min-w-0">
<span className="flex items-center gap-2 min-w-0">
<span className="text-ink truncate">🔊 {c.name}</span>
{checkOn && <VerdictBadge verdict={verdict} loading={check?.busy} />}
</span>
{verdict && c.channel_id === channelId && <FixText verdict={verdict} channelName={c.name} />}
{c.stream && (
<span className="text-xs text-ink-muted block">
{here
? `${options.system_name ?? "This system"} is already on this node here`
: `${options.system_name ?? "This system"} is carried by ${c.stream.node_name ?? "another node"} — picking it moves it to this node`}
</span>
)}
{others.length > 0 && (
<span className="text-xs text-ink-muted block">
Also playing: {others.map(streamLabel).join(", ")}
{!c.stream && ` — this adds ${options.system_name ?? "this node's system"} beside it with another bot`}
</span>
)}
{c.channel_id === channelId && checkOn && (
<BotDetails channel={check?.data?.channels[c.channel_id]} channelName={c.name} />
)}
</span>
</label>
);
})}
</div>
</div>
))}
<CheckFooter
checkedAt={check?.data?.checked_at ?? null}
busy={!!check?.busy}
error={check?.error ?? null}
disabled={!checkOn}
limited={!!check?.limited}
invite={showInvite ? check?.data?.invite : undefined}
onRecheck={() => runCheck(guild.guild_id, true)}
/>
</div>
)}
</fieldset>
)}
{/* 3 — mode */}
{channel && (
<fieldset>
<legend className="text-xs text-ink-muted mb-2">Mode</legend>
<div className="grid grid-cols-2 gap-2">
{(
[
["adhoc", "Ad-hoc", "Stops if this node goes offline or switches system."],
["persistent", "Persistent", `Stays up: if this node drops, DRB moves it to another node on ${options.system_name ?? "this system"}.`],
] as const
).map(([value, label, hint]) => (
<label
key={value}
className={`rounded-lg border px-3 py-2 cursor-pointer ${
mode === value ? "border-accent bg-accent/10" : "border-line bg-raised hover:border-line-strong"
}`}
>
<span className="flex items-center gap-2">
<input
type="radio"
name="mode"
className="accent-[var(--accent)]"
checked={mode === value}
onChange={() => setMode(value)}
/>
<span className="text-ink font-medium">{label}</span>
</span>
<span className="text-xs text-ink-muted block mt-1">{hint}</span>
</label>
))}
</div>
</fieldset>
)}
{!options.system_id && (
<p className="text-xs text-sev-moderate">
This node is not listening to a system yet. Assign it one before adding a radio channel.
</p>
)}
{atNodeCap && !channelOnHere && (
<p className="text-xs text-sev-moderate">
This node already carries {options.limits.node_used} of {options.limits.node_max} radio channels. Stop one
first.
</p>
)}
{error && (
<div role="alert" className="text-xs text-sev-major whitespace-pre-line">
{error.message}
<InviteLinks invite={error.invite} />
</div>
)}
</div>
<div className="flex gap-3 px-5 py-4 border-t border-line">
<button
type="button"
onClick={start}
disabled={sending || !channel || !options.system_id || (atNodeCap && !channelOnHere) || definiteDeny}
title={definiteDeny ? "No radio bot in this server can stream into this channel — fix the permission in Discord, then Re-check." : undefined}
className="flex-1 bg-accent hover:brightness-110 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg py-2 text-sm font-semibold"
>
{sending ? "Starting…" : channelOnHere ? "Update" : "Start radio"}
</button>
<button
type="button"
onClick={onClose}
className="flex-1 bg-raised border border-line hover:brightness-110 text-ink-2 rounded-lg py-2 text-sm"
>
Cancel
</button>
</div>
</div>
</div>
);
}
// ---------------------------------------------------------------------------
// Panel
// ---------------------------------------------------------------------------
export function NodeDiscordRadio({ nodeId }: { nodeId: string }) {
const [options, setOptions] = useState<DiscordJoinOptions | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [picking, setPicking] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const load = useCallback(async () => {
try {
setOptions(await c2api.getNodeDiscordOptions(nodeId));
setLoadError(null);
} catch (err) {
setLoadError(parseC2Error(err).message);
}
}, [nodeId]);
useEffect(() => {
load();
const t = setInterval(() => {
if (document.visibilityState === "visible") load();
}, POLL_MS);
return () => clearInterval(t);
}, [load]);
async function stop(streamId?: string) {
if (!streamId && !confirm("Stop every Discord radio channel this node carries?")) return;
setBusy(streamId ?? "all");
setActionError(null);
try {
await c2api.stopNodeDiscordStreams(nodeId, streamId);
await load();
} catch (err) {
setActionError(parseC2Error(err).message);
} finally {
setBusy(null);
}
}
async function remove(s: DiscordStreamView) {
const name = s.channel_name ?? "this channel";
if (!confirm(`Remove ${streamLabel(s)} from ${name} permanently? It is stopped first (the node logs its radio bot out), then deleted from DRB. Other streams in that voice channel keep playing.`)) return;
setBusy(`rm:${s.stream_id}`);
setActionError(null);
try {
await c2api.removeNodeDiscordStream(nodeId, s.stream_id);
await load();
} catch (err) {
setActionError(parseC2Error(err).message);
} finally {
setBusy(null);
}
}
const streams = options?.streams ?? [];
const canControl = options?.can_control ?? false;
const canRemove = options?.can_remove ?? false;
return (
<section className="bg-surface border border-line rounded-lg overflow-hidden">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-3 border-b border-line">
<h2 className="text-sm font-semibold text-ink">Discord radio</h2>
<span className="text-xs text-ink-muted">
Voice channels this node streams into. They reconnect by themselves; state is reported by the node.
</span>
{canControl && (
<span className="ml-auto flex gap-2">
{streams.length > 1 && (
<button
type="button"
disabled={busy !== null}
onClick={() => stop()}
className="bg-raised border border-line hover:brightness-110 disabled:opacity-50 text-ink-2 rounded-md px-2.5 py-1 text-xs"
>
{busy === "all" ? "Stopping…" : "Stop all"}
</button>
)}
<button
type="button"
disabled={!options}
onClick={() => setPicking(true)}
className="bg-accent hover:brightness-110 disabled:opacity-50 text-white rounded-md px-2.5 py-1 text-xs font-semibold"
>
+ Add radio channel
</button>
</span>
)}
</div>
{loadError ? (
<p role="alert" className="px-4 py-3 text-xs text-sev-major">Couldn&apos;t load Discord radio: {loadError}</p>
) : !options ? (
<p className="px-4 py-3 text-xs text-ink-muted">Loading…</p>
) : streams.length === 0 ? (
<p className="px-4 py-3 text-xs text-ink-muted">
Not streaming into any Discord voice channel.
{!canControl && " The organization owner or this node's operator can add one."}
</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-xs text-ink-muted border-b border-line">
<th className="px-4 py-2 text-left font-medium">Server · channel</th>
<th className="px-4 py-2 text-left font-medium">Mode</th>
<th className="px-4 py-2 text-left font-medium">Desired → actual</th>
{(canControl || canRemove) && <th className="px-4 py-2" />}
</tr>
</thead>
<tbody>
{streams.map((s) => (
<tr key={s.stream_id} className="border-b border-line last:border-0 align-top">
<td className="px-4 py-2.5">
<div className="text-ink font-medium">🔊 {s.channel_name ?? s.channel_id}</div>
<div className="text-xs text-ink-muted">
{s.guild_name ?? s.guild_id} · {streamLabel(s)}
</div>
</td>
<td className="px-4 py-2.5 text-ink-2">{modeLabel(s.mode)}</td>
<td className="px-4 py-2.5">
<StatePill s={s} />
{s.actual?.error && (
<div className="text-xs text-ink-muted mt-1 max-w-xs">
{s.actual.error}
{s.actual.code && <span className="font-mono"> [{s.actual.code}]</span>}
</div>
)}
</td>
{(canControl || canRemove) && (
<td className="px-4 py-2.5 text-right whitespace-nowrap">
{canControl && (
<button
type="button"
disabled={busy !== null}
onClick={() => stop(s.stream_id)}
className="bg-raised border border-line hover:brightness-110 disabled:opacity-50 text-ink-2 rounded-md px-2 py-0.5 text-xs"
>
{busy === s.stream_id ? "Stopping…" : "Stop"}
</button>
)}
{canRemove && (
<button
type="button"
disabled={busy !== null}
onClick={() => remove(s)}
className="ml-1 bg-sev-major hover:brightness-110 disabled:opacity-50 text-white rounded-md px-2 py-0.5 text-xs"
>
{busy === `rm:${s.stream_id}` ? "Removing…" : "Remove"}
</button>
)}
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
)}
{actionError && <p role="alert" className="px-4 py-2 text-xs text-sev-major border-t border-line">{actionError}</p>}
{options && !options.node_online && streams.length > 0 && (
<p className="px-4 py-2 text-xs text-ink-muted bg-raised border-t border-line">
This node is offline — its channels resume if it reconnects shortly. If it stays down, ad-hoc ones stop and persistent ones move to another node on the same system.
</p>
)}
{picking && options && (
<DiscordPicker nodeId={nodeId} options={options} onClose={() => setPicking(false)} onStarted={load} />
)}
</section>
);
}