import { useCallback, useEffect, useState } from "react";
import { hosting, host, offers as offersApi, type Offer } from "../lib/agent";
import { MACHINE, ago, fmtCores, fmtGb, perHour, screenError, yen } from "../lib/format";
import { STATE_LABEL, containerLabel, gauges, newNodeBounds, runsLabel, split, stateTone, type LocalNode, type LocalNodesV1 } from "../lib/nodes";
import type { Overview } from "../lib/overview";
import type { AgentHook } from "../lib/useAgent";
import { NodeTerminal } from "../components/NodeTerminal";
import { Button, Go, Notice, Panel, Pill, Row, RowName, ScreenHead, Seg, Stepper } from "../components/ui";
import { Bar, Card, CardGrid, CardHead, Facts, Icon, Key, Section, Tile } from "../components/kit";
// The nodes on this machine (ADR ZC-0027), then every machine on the account.
//
// A machine always runs its main node, which takes the hub's jobs. The owner
// may add more, each one a real mesh node of its own: a fixed share of the
// limit set on Resources, its workers as a compose project, and optionally
// one hub environment it hosts. Per node: what it uses of its share right
// now, its containers, and a terminal inside it.
const GB = 2 ** 30;
const POLL_MS = 5000;
export function Nodes({ hook, ov, onResources, preset, onPresetDone }: { hook: AgentHook; ov: Overview | null; onResources: () => void; preset?: string | null; onPresetDone?: () => void }) {
const [v, setV] = useState<LocalNodesV1 | null>(null);
const [error, setError] = useState<string | null>(null);
const [adding, setAdding] = useState(false);
const [term, setTerm] = useState<{ node: LocalNode; container: string | null } | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
try {
setV(await hosting.localNodes());
setError(null);
} catch (e) {
const status = (e as { status?: number | null }).status;
setError(status === 404 ? "This zc's agent cannot run several nodes yet. Update zc in Settings." : screenError(e));
}
}, []);
useEffect(() => {
load();
const t = window.setInterval(() => document.visibilityState === "visible" && load(), POLL_MS);
return () => window.clearInterval(t);
}, [load]);
// Environments › "Host in its own node" lands here with the template chosen.
useEffect(() => {
if (preset) setAdding(true);
}, [preset]);
const change = async (f: () => Promise<LocalNodesV1>) => {
setBusy(true);
try {
setV(await f());
setError(null);
return true;
} catch (e) {
setError(screenError(e) ?? "The agent isn't answering.");
return false;
} finally {
setBusy(false);
}
};
const bounds = v ? newNodeBounds(v) : null;
const others = (ov?.nodes ?? []).filter((n) => !n.thisNode);
return (
<>
<ScreenHead title="Nodes" sub={`What you lend, split between the nodes on this ${MACHINE}: one for the hub's jobs, and one for each environment you host`}>
<Button variant="primary" disabled={!v || adding} onClick={() => setAdding(true)}>
Add a node
</Button>
</ScreenHead>
{error && (
<Notice tone="warn" title="Couldn't change or read the nodes" onClose={() => setError(null)}>
{error}
</Notice>
)}
{v?.usage_error && (
<Notice tone="warn" title="The nodes' use couldn't be measured">
{v.usage_error}
</Notice>
)}
{v && <Split v={v} onResources={onResources} />}
{adding && v && bounds && (
<AddNode
v={v}
bounds={bounds}
busy={busy}
preset={preset ?? null}
onCancel={() => {
setAdding(false);
onPresetDone?.();
}}
onCreate={async (n) => {
if (await change(() => hosting.addNode(n))) {
setAdding(false);
onPresetDone?.();
}
}}
/>
)}
<Section title={`On this ${MACHINE}`} count={v ? v.nodes.length : undefined}>
<CardGrid min={340}>
{v ? (
v.nodes.map((n, i) => (
<NodeCard
key={n.id}
n={n}
shade={SHADES[Math.min(i, SHADES.length - 1)]!}
busy={busy || hook.busy}
onWorkers={(w) => (n.main ? hook.setWorkers(w).then(load) : change(() => hosting.setNode(n.id, { workers: w })))}
onRemove={() => {
if (term?.node.id === n.id) setTerm(null);
return change(() => hosting.removeNode(n.id));
}}
onTerminal={(container) => setTerm({ node: n, container })}
/>
))
) : (
<Card dashed>
<Facts>Waiting for the agent.</Facts>
</Card>
)}
{v && !adding && bounds?.canAdd && (
<button type="button" onClick={() => setAdding(true)} className="grid min-h-[150px] place-items-center rounded-md border border-dashed border-hairline text-fg-dim transition-colors hover:border-wine/60 hover:text-wine-bright">
<span className="grid justify-items-center gap-1.5 text-[12.5px]">
<Icon name="plus" className="h-5 w-5" />
Add a node
<span className="text-[11px]">for an environment, or more hub jobs</span>
</span>
</button>
)}
</CardGrid>
</Section>
{term && <NodeTerminal key={`${term.node.id}:${term.container ?? ""}`} node={term.node.id} title={term.node.main ? term.node.name : term.node.id} container={term.container} onClose={() => setTerm(null)} />}
<Section title="Other machines on your account" count={others.length || undefined} aside={ov ? `${ov.nodesOnline} of ${ov.nodesTotal} nodes online` : undefined}>
{others.length ? (
<CardGrid min={260}>
{others.map((n) => (
<Card key={n.id}>
<CardHead tile={<Tile letter={n.name} tone="neutral" />} eyebrow={`seen ${ago(n.lastSeenAt)}`} title={n.name} corner={<Pill tone={n.online ? "ok" : "neutral"}>{n.online ? "Online" : n.freshness}</Pill>} />
<Facts>
<span>
{n.workers} worker{n.workers === 1 ? "" : "s"}
</span>
<b className="font-semibold text-fg">{n.priceMin === null ? "—" : n.priceMin === n.priceMax ? perHour(n.priceMin) : `${yen(n.priceMin)}–${perHour(n.priceMax)}`}</b>
{n.link && (
<button type="button" className="ml-auto text-wine-bright hover:underline" onClick={() => n.link && host.openExternal(n.link)}>
Hub ↗
</button>
)}
</Facts>
</Card>
))}
</CardGrid>
) : (
<Card dashed>
<Facts>{ov ? `No other machine on your account yet. Extra nodes on this ${MACHINE} also show up here once the hub has seen them.` : "Waiting for the agent."}</Facts>
</Card>
)}
</Section>
</>
);
}
const SHADES = ["bg-wine", "bg-cyan", "bg-amber", "bg-live", "bg-fg-dim"];
/** The owner's limit as one bar per resource, a colour per node. */
function Split({ v, onResources }: { v: LocalNodesV1; onResources: () => void }) {
if (!v.limit) return null;
const rows: { label: string; key: "cpu_cores" | "memory_bytes"; fmt: (n: number) => string }[] = [
{ label: "CPU", key: "cpu_cores", fmt: fmtCores },
{ label: "Memory", key: "memory_bytes", fmt: fmtGb },
];
return (
<Card>
<div className="flex flex-wrap items-baseline justify-between gap-2">
<b className="text-[13px] font-semibold">
What you lend: {fmtCores(v.limit.cpu_cores)} and {fmtGb(v.limit.memory_bytes)}
</b>
<Go onClick={onResources}>Change the limit</Go>
</div>
<div className="grid grid-cols-[repeat(auto-fit,minmax(240px,1fr))] gap-x-6 gap-y-2">
{rows.map((r) => (
<div key={r.key} className="grid gap-1">
<span className="text-[11.5px] text-fg-dim">{r.label}</span>
<Bar
className="h-2"
label={`${r.label} split: ${v.nodes.map((n) => `${n.main ? n.name : n.id} ${n.share ? r.fmt(n.share[r.key]) : "—"}`).join(", ")}`}
parts={split(v, r.key).map((s, i) => ({ pct: s.pct, className: SHADES[Math.min(i, SHADES.length - 1)]! }))}
/>
</div>
))}
</div>
<Facts>
{v.nodes.map((n, i) => (
<Key key={n.id} className={SHADES[Math.min(i, SHADES.length - 1)]!}>
{n.main ? `${n.name} (main)` : n.id}
{n.share && ` · ${fmtCores(n.share.cpu_cores)}, ${fmtGb(n.share.memory_bytes)}`}
</Key>
))}
</Facts>
</Card>
);
}
function NodeCard({ n, shade, busy, onWorkers, onRemove, onTerminal }: { n: LocalNode; shade: string; busy: boolean; onWorkers: (w: number) => void; onRemove: () => void; onTerminal: (container: string | null) => void }) {
const [confirm, setConfirm] = useState(false);
const [open, setOpen] = useState(false);
const title = n.main ? n.name : n.id;
const tone = n.state === "running" ? "live" : n.state === "error" ? "warn" : "neutral";
return (
<Card accent={n.state === "running"}>
<CardHead
tile={<Tile icon={n.runs === "environment" ? "grid" : "nodes"} tone={tone} />}
eyebrow={
<span className="flex items-center gap-1.5">
<i className={"inline-block h-1.5 w-1.5 rounded-full " + shade} aria-hidden="true" />
{n.main ? "Main node" : "Node"}
</span>
}
title={title}
sub={runsLabel(n)}
corner={<Pill tone={stateTone(n.state)}>{STATE_LABEL[n.state]}</Pill>}
/>
{n.error && <span className="text-[11.5px] text-warn">{n.error}</span>}
<div className="grid gap-2">
{gauges(n).map((g) => (
<div key={g.label} className="grid gap-1">
<div className="flex justify-between text-[11.5px]">
<span className="text-fg-dim">{g.label}</span>
<span className="tnum">{g.text}</span>
</div>
<Bar parts={[{ pct: g.pct, className: "bg-wine" }]} />
</div>
))}
</div>
<div className="flex items-center justify-between gap-2 border-t border-hairline pt-2 text-[12px]">
<span className="grid gap-px">
<b className="font-semibold">Workers</b>
<span className="text-[11px] text-fg-dim">
{n.workers.running} running{n.runs === "environment" ? " · optional here" : ""}
</span>
</span>
<Stepper label="Workers" value={n.workers.desired} min={n.runs === "environment" || n.main ? 0 : 1} max={n.workers.max} disabled={busy} onChange={onWorkers} />
</div>
<div className="flex flex-wrap items-center gap-2">
<Button size="sm" disabled={!n.terminal} title={n.terminal ? undefined : "Nothing is running in this node yet"} onClick={() => onTerminal(null)}>
<Icon name="terminal" className="h-3.5 w-3.5" />
Terminal
</Button>
<Button size="sm" disabled={n.containers.length === 0} aria-expanded={open} onClick={() => setOpen(!open)}>
{n.containers.length} container{n.containers.length === 1 ? "" : "s"} {open ? "▴" : "▾"}
</Button>
{!n.main &&
(confirm ? (
<span className="ml-auto flex items-center gap-2">
<Button size="sm" variant="primary" disabled={busy} onClick={onRemove}>
Remove node
</Button>
<Button size="sm" onClick={() => setConfirm(false)}>
Cancel
</Button>
</span>
) : (
<Button size="sm" className="ml-auto" disabled={busy} onClick={() => setConfirm(true)}>
Remove…
</Button>
))}
</div>
{confirm && <span className="text-[11.5px] text-fg-dim">Its share goes back to the main node, and its identity on the mesh is deleted.</span>}
{open && (
<div className="grid">
{n.containers.map((c) => (
<Row key={c.name} cols="1fr auto auto">
<RowName name={containerLabel(c)} sub={c.name} />
<span className="tnum text-[11.5px] text-fg-dim">{c.running ? `${c.cpu_cores == null ? "—" : fmtCores(c.cpu_cores)} · ${c.memory_bytes == null ? "—" : fmtGb(c.memory_bytes)}` : "stopped"}</span>
<Button size="sm" disabled={!c.running} aria-label={`Terminal in ${c.name}`} onClick={() => onTerminal(c.name)}>
<Icon name="terminal" className="h-3.5 w-3.5" />
</Button>
</Row>
))}
</div>
)}
<span className="truncate font-mono text-[10px] text-fg-dim/80" title={n.address ?? undefined}>
{n.address ?? "no mesh identity yet"}
{n.broker_port ? ` · :${n.broker_port}` : ""}
</span>
</Card>
);
}
function AddNode({
v,
bounds,
busy,
preset,
onCancel,
onCreate,
}: {
v: LocalNodesV1;
bounds: ReturnType<typeof newNodeBounds>;
busy: boolean;
preset: string | null;
onCancel: () => void;
onCreate: (n: { cpu_cores: number; memory_bytes: number; environment?: string; environment_name?: string; workers: number }) => void;
}) {
const [kind, setKind] = useState<"environment" | "hub_jobs">("environment");
const [catalogue, setCatalogue] = useState<Offer[] | null>(null);
const [template, setTemplate] = useState<string>(preset ?? "");
const [cpu, setCpu] = useState(Math.min(1, bounds.maxCpu));
const [mem, setMem] = useState(Math.min(2, bounds.maxMemoryGb));
const [workers, setWorkers] = useState(0);
useEffect(() => {
offersApi.list().then(
(r) => setCatalogue(r.offers),
() => setCatalogue([]),
);
}, []);
useEffect(() => setWorkers(kind === "environment" ? 0 : 1), [kind]);
const taken = new Set(v.nodes.map((n) => n.environment).filter(Boolean));
const choices = (catalogue ?? []).filter((o) => !taken.has(o.template.id));
const chosen = choices.find((o) => o.template.id === template) ?? null;
const blocked = chosen && chosen.fits === false;
const ready = bounds.canAdd && cpu >= 0.5 && mem >= 1 && (kind === "hub_jobs" || (!!chosen && !blocked));
return (
<Panel className="max-w-[640px]" title="Add a node" aside={`up to ${fmtCores(bounds.maxCpu)} and ${bounds.maxMemoryGb} GB free`}>
{!bounds.canAdd && bounds.why && <span className="text-[12.5px] text-warn">{bounds.why}</span>}
<Row cols="1fr auto">
<RowName name="What it runs" sub="An environment gets a node to itself; the main node keeps the hub's jobs" />
<Seg
value={kind}
onChange={setKind}
options={[
{ value: "environment", label: "An environment" },
{ value: "hub_jobs", label: "More hub jobs" },
]}
/>
</Row>
{kind === "environment" && (
<Row cols="1fr auto">
<RowName
name="Environment"
sub={chosen ? (blocked ? `This ${MACHINE} can't host it: ${chosen.fit_reason ?? "it doesn't fit"}` : chosen.template.description || chosen.template.image) : catalogue === null ? "Reading the hub's catalogue…" : choices.length ? "From the hub's catalogue" : "The hub's catalogue is empty or unreachable"}
/>
<select
aria-label="Environment"
value={template}
onChange={(e) => setTemplate(e.target.value)}
className="max-w-[240px] rounded-sm border border-hairline bg-bg px-2 py-1 text-[12.5px] outline-none focus:border-wine"
>
<option value="">Choose…</option>
{choices.map((o) => (
<option key={o.template.id} value={o.template.id}>
{o.template.name}
{o.fits === false ? " (doesn't fit)" : ""}
</option>
))}
</select>
</Row>
)}
<Row cols="1fr auto">
<RowName name="CPU" sub={`Taken from the main node's share · ${fmtCores(cpu)}`} />
<HalfStepper label="Cores" value={cpu} min={0.5} max={bounds.maxCpu} step={0.5} onChange={setCpu} />
</Row>
<Row cols="1fr auto">
<RowName name="Memory" sub={`Taken from the main node's share · ${mem} GB`} />
<HalfStepper label="Memory" value={mem} min={1} max={bounds.maxMemoryGb} step={1} onChange={setMem} />
</Row>
<Row cols="1fr auto">
<RowName name="Workers" sub={kind === "environment" ? "Optional: they share half the node with the environment" : "Each worker runs one job at a time"} />
<Stepper label="Workers" value={workers} min={kind === "environment" ? 0 : 1} max={8} onChange={setWorkers} />
</Row>
<div className="flex items-center justify-end gap-2 pt-1">
<Button size="sm" onClick={onCancel}>
Cancel
</Button>
<Button
size="sm"
variant="primary"
disabled={!ready || busy}
onClick={() =>
onCreate({
cpu_cores: cpu,
memory_bytes: mem * GB,
workers,
...(kind === "environment" && chosen ? { environment: chosen.template.id, environment_name: chosen.template.name } : {}),
})
}
>
{busy ? "Creating…" : "Create node"}
</Button>
</div>
</Panel>
);
}
function HalfStepper({ label, value, min, max, step, onChange }: { label: string; value: number; min: number; max: number; step: number; onChange: (v: number) => void }) {
return (
<div className="flex items-center gap-2" role="group" aria-label={label}>
<Button size="sm" aria-label={`Less ${label.toLowerCase()}`} disabled={value - step < min} onClick={() => onChange(Math.round((value - step) * 10) / 10)}>
−
</Button>
<span className="tnum w-8 text-center font-mono">{value}</span>
<Button size="sm" aria-label={`More ${label.toLowerCase()}`} disabled={value + step > max} onClick={() => onChange(Math.round((value + step) * 10) / 10)}>
+
</Button>
</div>
);
}