zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useCallback, useEffect, useState } from "react";
import { hosting, type HostingSettings } from "../lib/agent";
import { MACHINE, screenError } from "../lib/format";
import type { Overview } from "../lib/overview";
import { limitSetting, resourceBars, snap, vmSummary, type ResourceBar, type ResourcesV1 } from "../lib/resources";
import type { AgentHook } from "../lib/useAgent";
import { Button, Notice, Pill, ScreenHead, Seg, Stepper, Toggle } from "../components/ui";
import { Card, CardGrid, CardHead, Facts, Key, Ring, Section, Tile, type IconName } from "../components/kit";

// What this machine lends, and the one place to change it.
//
// One card per resource: a ring of the whole machine (what Zakuro uses, the
// rest of what is reserved for it, what your apps use, what is free) and a
// slider for the limit, saved to the sharing policy on release. Then the
// rules as cards (workers, GPU, power, when), and the sandbox.
// Price is on the Price screen; on/off is the Sharing switch in the sidebar.
// Readings: the agent's `GET /v2/resources`, every 5 s while visible.

type ResKey = ResourceBar["key"];
const POLL_MS = 5000;

export function Resources({ hook, ov, onNodes }: { hook: AgentHook; ov: Overview | null; onNodes: () => void }) {
  const [r, setR] = useState<ResourcesV1 | null>(null);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      setR(await hosting.resources());
      setError(null);
    } catch (e) {
      const status = (e as { status?: number | null }).status;
      setError(status === 404 ? "This zc's agent has no resources view yet. Update zc in Settings." : screenError(e));
    }
  }, []);
  useEffect(() => {
    load();
    const t = window.setInterval(() => document.visibilityState === "visible" && load(), POLL_MS);
    return () => window.clearInterval(t);
  }, [load]);

  const [settings, setSettings] = useState<HostingSettings | null>(null);
  const agentUp = hook.state.status === "ok";
  useEffect(() => {
    if (agentUp) hosting.settings().then(setSettings, () => {});
  }, [agentUp]);
  // A just-set limit, shown until the agent's reading catches up.
  const [pending, setPending] = useState<Partial<Record<ResKey, number>>>({});
  const [status, setStatus] = useState<string | null>(null);

  const save = useCallback(
    async (change: (h: HostingSettings) => HostingSettings, what: string) => {
      setStatus(`Saving ${what}…`);
      try {
        const next = change(settings ?? (await hosting.settings()));
        const d = await hosting.saveSettings(next);
        setSettings(next);
        setStatus(d.budget_full ? `Saved ${what}. Some deployments no longer fit: see Hosting.` : `Saved ${what}.`);
        setError(null);
        window.setTimeout(load, 300);
        window.setTimeout(load, 4500);
      } catch (e) {
        setStatus(null);
        setError(screenError(e));
      }
    },
    [settings, load],
  );
  const budget = (patch: Partial<HostingSettings["budget"]>, what: string) => save((h) => ({ ...h, budget: { ...h.budget, ...patch } }), what);

  const setLimit = (x: ResourceBar, v: number) => {
    setPending((p) => ({ ...p, [x.key]: v }));
    budget({ [x.key]: limitSetting(x, v) }, `the ${x.label.toLowerCase()} limit (${x.fmt(v)})`);
  };

  // Drop a pending value once the reading agrees (or after 10 s).
  useEffect(() => {
    if (!r) return;
    setPending((p) => {
      const bars = resourceBars(r);
      const left = Object.fromEntries(
        Object.entries(p).filter(([k, v]) => {
          const x = bars.find((b) => b.key === k);
          return x?.limit != null && Math.abs(x.limit - (v as number)) > x.step / 2;
        }),
      );
      return Object.keys(left).length === Object.keys(p).length ? p : left;
    });
  }, [r]);
  useEffect(() => {
    if (!Object.keys(pending).length) return;
    const t = window.setTimeout(() => setPending({}), 10_000);
    return () => window.clearTimeout(t);
  }, [pending]);

  const paused = ov?.thisNode.sharing === false;
  const w = ov?.thisNode.workers;
  const bars = r ? resourceBars(r) : null;
  const sandbox = r ? vmSummary(r, ov?.thisNode.sharing ?? null) : null;

  return (
    <>
      <ScreenHead title="Resources" sub={`How much of this ${MACHINE} Zakuro may use, and what it and your apps use right now`} />

      {error && (
        <Notice tone="warn" title="Couldn't read this machine's resources">
          {error}
        </Notice>
      )}
      {paused && (
        <Notice tone="warn" title="Sharing is paused">
          Zakuro runs nothing here, and your apps have the whole {MACHINE}. The limits below apply again when you turn Sharing back on.
        </Notice>
      )}

      <Section
        title="What you lend"
        aside={
          <span className="flex flex-wrap items-center gap-x-3 gap-y-1">
            <Key className="bg-wine">Zakuro using</Key>
            <Key className="bg-wine/30">Reserved for Zakuro</Key>
            <Key className="bg-fg-dim/50">Your apps</Key>
            <Key className="bg-raised ring-1 ring-hairline">Free</Key>
          </span>
        }
      >
        <CardGrid min={300}>
          {(bars ?? ([null, null, null] as const)).map((x, i) => (
            <Gauge key={x?.key ?? i} x={x} icon={ICONS[i]!} pending={x ? pending[x.key] : undefined} onCommit={(v) => x && setLimit(x, v)} />
          ))}
        </CardGrid>
        <span className="text-[11.5px] text-fg-dim" aria-live="polite">
          {status ?? "Move a slider to change what's reserved for Zakuro. It applies as soon as you let go."}
        </span>
      </Section>

      <Section title="How and when Zakuro uses it">
        <CardGrid min={240}>
          <Card>
            <CardHead tile={<Tile icon="workers" />} eyebrow="Parallel jobs" title="Workers" corner={<Stepper label="Workers" value={w?.desired ?? null} min={0} max={w?.max ?? 0} disabled={!w || hook.busy} onChange={(n) => hook.setWorkers(n)} />} />
            <Facts>{w ? `${w.running} running · ${w.busy} busy · up to ${w.max}` : "One job per worker"}</Facts>
          </Card>
          <Card accent={!!settings?.budget.gpu}>
            <CardHead tile={<Tile icon="bolt" />} eyebrow="Inside the memory limit" title="Share the GPU" corner={<Toggle label="Share the GPU" on={!!settings?.budget.gpu} disabled={!settings} onChange={(v) => budget({ gpu: v }, v ? "GPU sharing" : "no GPU sharing")} />} />
            <Facts>Lets LLM fine-tuning run here</Facts>
          </Card>
          <Card accent={!!settings?.budget.on_ac_only}>
            <CardHead tile={<Tile icon="plug" />} eyebrow="Battery" title="Only when plugged in" corner={<Toggle label="Only when plugged in" on={!!settings?.budget.on_ac_only} disabled={!settings} onChange={(v) => budget({ on_ac_only: v }, "the power setting")} />} />
            <Facts>A running job wraps up when you unplug</Facts>
          </Card>
          <Card>
            <CardHead tile={<Tile icon="moon" />} eyebrow={`While you use this ${MACHINE}`} title={settings?.sharing.when === "always" ? "Always" : "Only when idle"} />
            {settings ? (
              <div className="justify-self-start">
              <Seg
                value={settings.sharing.when === "always" ? "always" : "idle"}
                options={[
                  { value: "idle", label: "Idle only" },
                  { value: "always", label: "Always" },
                ]}
                onChange={(v) => save((h) => ({ ...h, sharing: { ...h.sharing, when: v } }), v === "idle" ? "idle-only sharing" : "always-on sharing")}
              />
              </div>
            ) : (
              <Facts>Waiting for the agent</Facts>
            )}
          </Card>
        </CardGrid>
      </Section>

      <Section title="Where Zakuro's jobs run">
        <CardGrid min={300}>
          <Card>
            <CardHead
              tile={<Tile icon="shield" tone={sandbox?.state === "running" ? "live" : sandbox?.state === "none" || (sandbox?.state === "not_created" && ov?.thisNode.sharing) ? "warn" : "neutral"} />}
              eyebrow="Sandbox"
              title={sandbox?.title ?? "Waiting for the agent"}
              corner={
                sandbox &&
                { running: <Pill tone="ok">Running</Pill>, stopped: <Pill>Stopped</Pill>, not_created: ov?.thisNode.sharing ? <Pill tone="warn">Missing</Pill> : <Pill>Not created yet</Pill>, none: <Pill tone="warn">None</Pill> }[sandbox.state]
              }
            />
            {sandbox && <p className="m-0 text-[12px] leading-snug text-fg-dim">{sandbox.detail}</p>}
          </Card>
          <Card>
            <CardHead tile={<Tile icon="nodes" />} eyebrow="Inside these limits" title="Nodes" corner={<Button size="sm" onClick={onNodes}>Open</Button>} />
            <p className="m-0 text-[12px] leading-snug text-fg-dim">What you lend can be split between several nodes on this {MACHINE}: the main one for the hub's jobs, and one per environment you host.</p>
          </Card>
        </CardGrid>
        {r && (
          <span className="text-[11.5px] text-fg-dim">
            Zakuro's use is measured {r.zakuro.used_scope === "vm+processes" ? `inside its VM, plus its own processes on this ${MACHINE}` : `from its own processes on this ${MACHINE}`}. A running VM can hold more memory than its jobs use, up to its size.
          </span>
        )}
      </Section>
    </>
  );
}

const ICONS: IconName[] = ["cpu", "memory", "disk"];

function Gauge({ x, icon, pending, onCommit }: { x: ResourceBar | null; icon: IconName; pending?: number; onCommit: (v: number) => void }) {
  const [drag, setDrag] = useState<number | null>(null);
  if (!x) {
    return (
      <Card>
        <CardHead tile={<Tile icon={icon} tone="neutral" />} eyebrow="Reading" title="Waiting for the agent" />
        <div className="h-[112px]" />
      </Card>
    );
  }
  const cap = x.capacity;
  const limit = drag ?? pending ?? x.limit;
  const pct = (n: number | null) => (n == null || !cap ? 0 : Math.max(0, Math.min(100, (n / cap) * 100)));
  const disk = x.key === "disk";
  const reserved = pct(limit);
  const zak = Math.min(x.pct.zakuro, reserved);
  const rest = cap != null && limit != null ? cap - limit : null;
  const yours = disk ? pct(x.yours) : rest == null ? x.pct.yours : pct(x.yours == null ? null : Math.min(x.yours, rest));
  const overflow = !disk && x.yours != null && rest != null && x.yours > rest;
  const v = (n: number | null) => (n == null ? "—" : x.fmt(n));
  const editable = cap != null && cap > 0 && limit != null;
  const commit = () => {
    if (drag != null && drag !== x.limit) onCommit(drag);
    setDrag(null);
  };
  const nudge = (d: number) => limit != null && onCommit(snap(limit + d * x.step, x.min, x.max, x.step));
  // Disk: what is on the disk comes first; Zakuro's reservation is carved
  // out of what is free. CPU and memory: Zakuro's share first, then yours.
  const parts = disk
    ? [
        { pct: yours, className: "stroke-fg-dim/50" },
        { pct: Math.min(reserved, 100 - yours), className: "stroke-wine/40" },
      ]
    : [
        { pct: zak, className: "stroke-wine" },
        { pct: reserved - zak, className: "stroke-wine/30" },
        { pct: yours, className: "stroke-fg-dim/50" },
      ];
  const [big, unit] = (limit == null ? "—" : x.fmt(limit)).split(" ");

  return (
    <Card>
      <CardHead tile={<Tile icon={icon} />} eyebrow={cap == null ? x.label : `${x.label} · ${x.fmt(cap)}`} title={`${v(limit)} for Zakuro`} />
      <div className="flex items-center gap-4">
        <Ring parts={parts} label={`${x.label}: ${v(limit)} reserved for Zakuro${cap == null ? "" : ` of ${x.fmt(cap)}`}`}>
          <span className="grid leading-none">
            <b className="tnum text-[22px] font-semibold tracking-tight">{big}</b>
            <span className="mt-1 text-[10.5px] text-fg-dim">{unit ?? ""} lent</span>
          </span>
        </Ring>
        <div className="tnum grid min-w-0 flex-1 gap-1.5 text-[12px]">
          {disk ? (
            <>
              <Line k={<Key className="bg-fg-dim/50">In use</Key>} v={v(x.yours)} />
              <Line k={<Key className="bg-raised ring-1 ring-hairline">Free</Key>} v={cap != null && x.yours != null ? x.fmt(Math.max(0, cap - x.yours)) : "—"} />
              <Line k={<Key className="bg-wine/40">Zakuro may keep</Key>} v={v(limit)} strong />
            </>
          ) : (
            <>
              <Line k={<Key className="bg-wine">Zakuro using</Key>} v={x.zakuro == null ? "—" : x.fmt(Math.min(x.zakuro, limit ?? x.zakuro))} strong />
              <Line k={<Key className="bg-fg-dim/50">Your apps</Key>} v={v(x.yours)} />
              <Line k={<Key className="bg-raised ring-1 ring-hairline">Kept for you</Key>} v={v(rest)} />
            </>
          )}
        </div>
      </div>
      {editable && (
        <div className="flex items-center gap-2">
          <Button size="sm" aria-label={`Less ${x.label.toLowerCase()} for Zakuro`} disabled={limit <= x.min} onClick={() => nudge(-1)}>
            −
          </Button>
          <input
            type="range"
            aria-label={`${x.label} reserved for Zakuro`}
            aria-valuetext={x.fmt(limit)}
            min={x.min}
            max={x.max}
            step={x.step}
            value={limit}
            onChange={(e) => setDrag(Number(e.target.value))}
            onPointerUp={commit}
            onKeyUp={commit}
            onBlur={commit}
            className="zk-range min-w-0 flex-1"
            style={{ "--fill": `${x.max > x.min ? ((limit - x.min) / (x.max - x.min)) * 100 : 0}%` } as React.CSSProperties}
          />
          <Button size="sm" aria-label={`More ${x.label.toLowerCase()} for Zakuro`} disabled={limit >= x.max} onClick={() => nudge(1)}>
            +
          </Button>
        </div>
      )}
      {overflow && <span className="text-[11.5px] text-warn">Your apps are borrowing Zakuro's idle share right now.</span>}
      {x.shortBy != null && <span className="text-[11.5px] text-warn">Only {x.fmt(x.shortBy)} is free on this disk, less than what's reserved.</span>}
    </Card>
  );
}

function Line({ k, v, strong }: { k: React.ReactNode; v: string; strong?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-2">
      <span className="text-fg-dim">{k}</span>
      <b className={"font-semibold " + (strong ? "text-wine-bright" : "text-fg")}>{v}</b>
    </div>
  );
}