zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useCallback, useEffect, useState } from "react";
import { hosting, isAgentError, type StoredImage } from "../lib/agent";
import { banner, bars, rows, type DeploymentsResponse } from "../lib/deployments";
import { Button, Empty, Meter, Notice, Panel, Pill, Row, RowName, ScreenHead, Toggle } from "../components/ui";

// What this machine hosts inside the owner's budget: one bar per budgeted
// resource, every runner kind (greyed out with the reason when it cannot
// run), and "Free up space": what Zakuro keeps on disk, removable now.

const GB = 2 ** 30;
const gb = (b: number) => `${(b / GB).toFixed(1)} GB`;
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 = (e: unknown) => (isAgentError(e) ? e.message : String(e));

export function Hosting() {
  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);
    }
  };

  const b = d && banner(d);
  const sorted = [...(images?.images ?? [])].sort((x, y) => y.size_bytes - x.size_bytes);

  return (
    <>
      <ScreenHead title="Hosting" sub="What this machine runs for Zakuro, inside your budget" />
      {b && <Notice tone="warn" title={b} />}
      {error && <Notice title="The agent refused">{error}</Notice>}
      <div className="grid grid-cols-2 gap-3">
        <Panel title="Budget in use">
          {d ? (
            bars(d).map((x) => (
              <div key={x.resource} className="grid gap-1 py-1.5">
                <div className="flex justify-between text-[12px]">
                  <span>{x.resource}</span>
                  <span className="tnum text-fg-dim">
                    {x.resource === "CPU" ? `${(x.used / 1000).toFixed(1)} of ${(x.limit / 1000).toFixed(1)} cores` : `${gb(x.used)} of ${gb(x.limit)}`}
                  </span>
                </div>
                <Meter parts={[{ pct: x.limit > 0 ? (x.used / x.limit) * 100 : 0 }]} />
              </div>
            ))
          ) : (
            <Empty>Waiting for the agent.</Empty>
          )}
        </Panel>
        <Panel title="Deployments" aside="on by default when this machine can run them">
          {d ? (
            rows(d).map((r) => (
              <Row key={r.kind} cols="1fr auto auto">
                <div className={r.greyed ? "opacity-50" : undefined}>
                  <RowName name={r.label} sub={[r.reserve, r.why].filter(Boolean).join(" · ")} />
                </div>
                <span className="text-[11.5px] text-fg-dim">{r.state === "running" ? <Pill tone="ok">running</Pill> : r.earnPerGb}</span>
                <Toggle
                  label={r.label}
                  on={r.state !== "disabled" && r.state !== "unsupported"}
                  disabled={busy || r.state === "unsupported"}
                  onChange={(v) => toggle(r.kind, v)}
                />
              </Row>
            ))
          ) : (
            <Empty>Waiting for the agent.</Empty>
          )}
        </Panel>
      </div>
      <Panel title="Free up space" aside={images ? `unused for ${images.ttl_days} days is removed automatically` : undefined}>
        {sorted.length === 0 ? (
          <Empty>Nothing stored.</Empty>
        ) : (
          sorted.map((i) => (
            <Row key={i.id} cols="1fr auto auto">
              <RowName name={i.id} sub={`${gb(i.size_bytes)} · ${ago(i.last_used)} · earned ¥${i.earnings}`} />
              {i.in_use ? <Pill>in use</Pill> : <span />}
              {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 || i.in_use} onClick={() => setConfirm(i.id)}>
                  Remove
                </Button>
              )}
            </Row>
          ))
        )}
      </Panel>
    </>
  );
}