import { useCallback, useEffect, useState } from "react";
import { hosting, type HostingSettings, type StoredImage } from "../lib/agent";
import { banner, crowdedBy, reservedBars, rows, type DeploymentsResponse } from "../lib/deployments";
import { MACHINE, fmtGb as gb, screenError } from "../lib/format";
import { Button, Field, Go, Notice, Pill, ScreenHead, Toggle } from "../components/ui";
import { Bar, Card, CardGrid, CardHead, Facts, Section, Tile, type IconName } from "../components/kit";
// What this machine hosts inside Zakuro's limits: every runner kind (greyed
// out with the reason when it cannot run), how much of the limits they hold,
// and "Free up space": what Zakuro keeps on disk, removable now. The limits
// themselves are set on Resources.
const ago = (secs: number | null) => {
if (secs == null) return "never used";
const d = Math.floor((Date.now() / 1000 - secs) / 86400);
return d <= 0 ? "used today" : `used ${d} d ago`;
};
const message = screenError;
export function Hosting({ onResources }: { onResources: () => void }) {
const [d, setD] = useState<DeploymentsResponse | null>(null);
const [images, setImages] = useState<{ images: StoredImage[]; ttl_days: number } | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [confirm, setConfirm] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const [dep, img] = await Promise.all([hosting.deployments(), hosting.images()]);
setD(dep);
setImages(img);
setError(null);
} catch (e) {
setError(message(e));
}
}, []);
useEffect(() => {
load();
const t = setInterval(load, 15_000);
return () => clearInterval(t);
}, [load]);
const toggle = async (kind: string, on: boolean) => {
setBusy(true);
try {
setD(await hosting.setEnabled(kind, on));
setError(null);
} catch (e) {
setError(message(e));
} finally {
setBusy(false);
}
};
const remove = async (id: string) => {
setBusy(true);
setConfirm(null);
try {
await hosting.removeImage(id);
await load();
} catch (e) {
setError(message(e));
} finally {
setBusy(false);
}
};
// "Remove unused images after N days" lives here, next to what it removes.
const [settings, setSettings] = useState<HostingSettings | null>(null);
const [ttl, setTtl] = useState("");
useEffect(() => {
hosting.settings().then(
(h) => {
setSettings(h);
setTtl(h.cleanup.idle_ttl.replace(/\D/g, ""));
},
() => {},
);
}, []);
const saveTtl = async () => {
if (!settings || !/^[1-9]\d{0,2}$/.test(ttl) || `${ttl}d` === settings.cleanup.idle_ttl) return;
const next = { ...settings, cleanup: { idle_ttl: `${ttl}d` } };
try {
await hosting.saveSettings(next);
setSettings(next);
setError(null);
await load();
} catch (e) {
setError(message(e));
}
};
const b = d && banner(d);
const held = d
? reservedBars(d).map((x) => ({
label: x.resource === "CPU" ? "CPU" : x.resource === "Disk" ? "Disk" : "Memory",
pct: x.limit > 0 ? (x.used / x.limit) * 100 : 0,
text: x.resource === "CPU" ? `${(x.used / 1000).toFixed(1)} of ${(x.limit / 1000).toFixed(1)} cores` : `${gb(x.used)} of ${gb(x.limit)}`,
}))
: null;
const sorted = [...(images?.images ?? [])].sort((x, y) => y.size_bytes - x.size_bytes);
const list = d ? rows(d) : [];
const total = sorted.reduce((a, i) => a + i.size_bytes, 0);
return (
<>
<ScreenHead title="Hosting" sub={`The kinds of work this ${MACHINE} takes for Zakuro, and what it keeps on disk for them`} />
{b && (
<Notice tone="warn" title={b}>
<Go onClick={onResources}>Change the limits on Resources</Go>
</Notice>
)}
{error && <Notice title="The agent refused">{error}</Notice>}
<Section title="What this machine takes" count={d ? list.filter((r) => r.state !== "disabled" && r.state !== "unsupported").length + " on" : undefined} aside={<Go onClick={onResources}>Change limits</Go>}>
{d ? (
<CardGrid min={280}>
{list.map((r) => {
const on = r.state !== "disabled" && r.state !== "unsupported";
const running = r.state === "running";
return (
<Card key={r.kind} accent={running}>
<div className={r.greyed ? "opacity-60" : undefined}>
<CardHead
tile={<Tile icon={KIND_ICON[r.kind] ?? "box"} tone={running ? "live" : on && !r.greyed ? "wine" : "neutral"} />}
eyebrow={running ? "Running" : !on ? "Off" : r.greyed ? "Waiting" : "Ready"}
title={r.label}
corner={<Toggle label={r.label} on={on} disabled={busy || r.state === "unsupported"} onChange={(v) => toggle(r.kind, v)} />}
/>
</div>
<Facts>
<span>{r.reserve}</span>
{r.earnPerGb && <span>{r.earnPerGb}</span>}
</Facts>
{r.why && <span className={"text-[11.5px] " + (on ? "text-warn" : "text-fg-dim")}>{(d && crowdedBy(d, r.kind)) ?? r.why}</span>}
</Card>
);
})}
</CardGrid>
) : (
<WaitCard />
)}
{held && (
<Card>
<div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-x-6 gap-y-2">
{held.map((h) => (
<div key={h.label} className="grid gap-1">
<div className="flex justify-between text-[12px]">
<span>{h.label} reserved</span>
<span className="tnum text-fg-dim">{h.text}</span>
</div>
<Bar parts={[{ pct: h.pct, className: "bg-wine" }]} />
</div>
))}
</div>
<Facts>Each kind you switch on reserves its size inside your limits, whether or not a job is running.</Facts>
</Card>
)}
</Section>
<Section
title="Kept on disk"
count={images ? `${sorted.length} · ${gb(total)}` : undefined}
aside={
settings ? (
<label className="flex items-center gap-1.5">
Remove what's unused for
<Field aria-label="Days before unused images are removed" className="w-12" inputMode="numeric" value={ttl} invalid={!/^[1-9]\d{0,2}$/.test(ttl)} onChange={(e) => setTtl(e.target.value.replace(/\D/g, ""))} onBlur={saveTtl} onKeyDown={(e) => e.key === "Enter" && saveTtl()} />
days
</label>
) : images ? (
`unused for ${images.ttl_days} days is removed automatically`
) : undefined
}
>
{sorted.length === 0 ? (
<Card dashed>
<Facts>{images ? "Nothing stored. Images, runner environments and model caches show up here as jobs need them." : "Waiting for the agent."}</Facts>
</Card>
) : (
<CardGrid min={300}>
{sorted.map((i) => (
<Card key={i.id}>
<CardHead
tile={<Tile icon="disk" tone="neutral" />}
eyebrow={KIND_LABEL[i.kind] ?? i.kind}
title={<span title={i.id}>{shortId(i.id)}</span>}
corner={
i.in_use ? (
<Pill>in use</Pill>
) : confirm === i.id ? (
<Button size="sm" variant="primary" disabled={busy} onClick={() => remove(i.id)}>
Remove {gb(i.size_bytes)}
</Button>
) : (
<Button size="sm" disabled={busy} onClick={() => setConfirm(i.id)}>
Remove
</Button>
)
}
/>
<Facts>
<b className="font-semibold text-fg">{gb(i.size_bytes)}</b>
<span>{ago(i.last_used)}</span>
<span>earned ¥{i.earnings}</span>
</Facts>
</Card>
))}
</CardGrid>
)}
</Section>
</>
);
}
const KIND_ICON: Record<string, IconName> = { "atelier-peft": "bolt", "atelier-ludwig": "grid", spaces: "box", environments: "nodes" };
const KIND_LABEL: Record<string, string> = { container: "Container image", "runner-env": "Runner environment", "model-cache": "Model cache" };
/** `work/b6dca84b-0bbc-…` reads as `work/b6dca84b…`; the full id is the tooltip. */
function shortId(id: string): string {
return id.replace(/([0-9a-f]{8})-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, "$1…").replace(/^hf\/models--/, "").replace(/--/g, "/");
}
function WaitCard() {
return (
<Card dashed>
<Facts>Waiting for the agent.</Facts>
</Card>
);
}