zc2 0.0.46

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useEffect, useMemo, useState } from "react";
import type { Job, Overview } from "../lib/overview";
import type { AgentHook } from "../lib/useAgent";
import { agent } from "../lib/agent";
import { ago, perHour, yen } from "../lib/format";
import { Button, Empty, Kpi, Meter, Panel, Pill, Row, RowName, ScreenHead, Seg } from "../components/ui";

// Contribution, the home screen (plan snapshot S4): earned, spent, jobs and
// hours, earned per day, earned by source, nodes and what runs now. Every
// figure comes from agent API v2: `GET /v2/summary` (ledger, nodes, live
// jobs) and `GET /v2/jobs?state=done` (the finished spans behind "jobs run"
// and "hours lent"). Amounts are yen (ADR 0027).

type Range = "7d" | "30d";
const RANGE_DAYS: Record<Range, number> = { "7d": 7, "30d": 30 };

/** The four job sources the hub pays for (plan, "Products"), in display order. */
const SOURCES: { key: string; label: string; pill: string }[] = [
  { key: "spaces", label: "Spaces batches", pill: "Spaces" },
  { key: "env_guest", label: "Environment guests", pill: "Env" },
  { key: "hub_serving", label: "Hub serving", pill: "Hub" },
  { key: "atelier", label: "L'Atelier runs", pill: "Atelier" },
];
const SOURCE_PILL: Record<string, string> = { ...Object.fromEntries(SOURCES.map((s) => [s.key, s.pill])), peer: "Peer", test: "Test" };

export function Contribution({ hook, ov }: { hook: AgentHook; ov: Overview | null }) {
  const [range, setRange] = useState<Range>("30d");
  const [done, setDone] = useState<Job[] | null>(null);

  // Finished jobs: re-read when a job finishes (done_24h moves) or the range changes.
  useEffect(() => {
    let live = true;
    agent
      .jobs("done")
      .then((j) => live && setDone(j))
      .catch(() => live && setDone(null));
    return () => {
      live = false;
    };
  }, [ov?.jobs.done24h, ov !== null]); // eslint-disable-line react-hooks/exhaustive-deps

  const since = Date.now() - RANGE_DAYS[range] * 86400_000;
  const stats = useMemo(() => jobStats(done, ov?.jobs.live ?? [], since), [done, ov?.jobs.live, since]);
  const l = ov?.ledger ?? null;
  const delta = l ? paceDelta(l.monthEarned, l.prevMonthEarned, new Date()) : null;
  const month = new Date().toLocaleDateString("en-US", { month: "long", year: "numeric" });

  return (
    <>
      <ScreenHead title="Contribution" sub={ov ? `${month} · ${ov.nodesTotal === 1 ? "this node" : `all ${ov.nodesTotal} nodes`}` : "Waiting for the agent"}>
        <Seg value={range} onChange={setRange} options={[{ value: "7d", label: "7 d" }, { value: "30d", label: "30 d" }]} />
        <Button variant={ov?.thisNode.sharing ? "default" : "primary"} disabled={!ov || hook.busy} onClick={() => ov && hook.setSharing(!ov.thisNode.sharing)}>
          {ov?.thisNode.sharing ? "Pause sharing" : "Resume sharing"}
        </Button>
      </ScreenHead>

      <div className="grid grid-cols-4 gap-2.5">
        <Kpi
          label="Earned"
          value={yen(l?.monthEarned)}
          up={delta !== null && delta > 0}
          sub={l ? (delta !== null ? `${delta >= 0 ? "+" : ""}${Math.round(delta * 100)}% vs last month's pace` : `this month · ${yen(l.todayEarned)} today`) : "the hub's ledger, once it answers"}
        />
        <Kpi label="Spent" value={yen(l?.monthSpent)} sub={l ? "this month" : "the hub's ledger, once it answers"} />
        <Kpi
          label="Jobs run"
          value={done ? stats.count.toLocaleString("en-US") : "—"}
          sub={done ? `${RANGE_DAYS[range]} d · ${stats.live} running now${stats.capped ? " · last 200 kept" : ""}` : "from this node's agent"}
        />
        <Kpi label="Hours lent" value={done ? `${fmtHours(stats.hours)}` : "—"} sub={done ? `busy worker time · ${RANGE_DAYS[range]} d` : "from this node's agent"} />
      </div>

      <div className="grid grid-cols-[1.35fr_1fr] gap-3">
        <Panel
          title="Earned per day"
          aside={
            <span className="flex gap-3">
              <span className="flex items-center gap-1.5">
                <i className="inline-block h-2 w-2 rounded-[2px] bg-wine" />
                Earned
              </span>
              <span>last 7 days{l ? ` · ${l.tz}` : ""}</span>
            </span>
          }
        >
          <DayBars days={l?.days ?? []} />
          <span className="text-[11px] text-fg-dim">Spent per day arrives with the ledger breakdown (GET /v2/ledger, zc#516); this month's spend is in the Spent total.</span>
        </Panel>
        <Panel title="Earned by source" aside="this month">
          <BySource ledger={l} />
        </Panel>
      </div>

      <div className="grid grid-cols-[1.35fr_1fr] gap-3">
        <Panel title="Nodes" aside="workers busy">
          <NodeRows ov={ov} />
        </Panel>
        <Panel title="Running now" aside={ov?.jobs.live.length ? `${ov.jobs.live.length} live` : "live"}>
          <LiveJobs ov={ov} />
        </Panel>
      </div>
    </>
  );
}

/** Finished jobs since `since` (and the live ones), with their busy time. */
export function jobStats(done: Job[] | null, live: Job[], since: number) {
  const now = Date.now();
  let count = 0;
  let ms = 0;
  for (const j of done ?? []) {
    const end = Date.parse(j.finishedAt ?? "");
    if (!Number.isFinite(end) || end < since) continue;
    count++;
    ms += Math.max(0, end - Math.max(Date.parse(j.startedAt), since));
  }
  for (const j of live) ms += Math.max(0, now - Math.max(Date.parse(j.startedAt), since));
  return { count, live: live.length, hours: ms / 3600_000, capped: (done?.length ?? 0) >= 200 };
}

function fmtHours(h: number): string {
  if (h === 0) return "0 h";
  if (h < 1) return `${Math.max(1, Math.round(h * 60))} min`;
  return `${h < 10 ? h.toFixed(1) : Math.round(h).toLocaleString("en-US")} h`;
}

function niceMax(v: number): number {
  if (v <= 0) return 100;
  const p = 10 ** Math.floor(Math.log10(v));
  return [1, 2, 2.5, 5, 10].map((m) => m * p).find((m) => m >= v) ?? 10 * p;
}

function DayBars({ days }: { days: { date: string; earned: number }[] }) {
  const H = 104;
  const max = niceMax(Math.max(0, ...days.map((d) => d.earned)));
  const ticks = [1, 0.75, 0.5, 0.25, 0].map((f) => max * f);
  const total = days.reduce((a, d) => a + d.earned, 0);
  const label = (d: string) => new Date(`${d}T00:00:00`).toLocaleDateString("en-US", { day: "numeric", month: "short" });
  // Without the hub's series, still draw the frame: an empty week, not a hole.
  const bars = days.length ? days : Array.from({ length: 7 }, (_, i) => ({ date: new Date(Date.now() - (6 - i) * 86400_000).toISOString().slice(0, 10), earned: 0 }));
  return (
    <div className="grid grid-cols-[40px_1fr] gap-1.5">
      <div className="flex flex-col justify-between text-right font-mono text-[10px] text-fg-dim" style={{ height: H }}>
        {ticks.map((t) => (
          <span key={t}>{t === 0 ? "0" : yen(t)}</span>
        ))}
      </div>
      <div className="relative flex items-end gap-1.5 border-b border-hairline" style={{ height: H, background: `repeating-linear-gradient(to top, transparent 0 ${H / 4 - 0.5}px, oklch(var(--hairline)) ${H / 4 - 0.5}px ${H / 4}px)` }}>
        {bars.map((d, i) => (
          <span key={d.date} className="flex h-full flex-1 flex-col justify-end" title={`${label(d.date)} · ${yen(d.earned)}`}>
            <i className={"block rounded-t-[2px] bg-wine " + (i === bars.length - 1 ? "" : "opacity-55")} style={{ height: `${(d.earned / max) * H}px`, minHeight: d.earned > 0 ? 2 : 0 }} />
          </span>
        ))}
        {total === 0 && (
          <span className="absolute inset-0 grid place-items-center">
            <span className="rounded-sm bg-surface px-2 py-0.5 text-[12px] text-fg-dim">
              {days.length ? "Nothing earned this week yet. Your first job's earnings land here." : "Waiting for the hub's ledger."}
            </span>
          </span>
        )}
      </div>
      <div className="col-start-2 flex justify-between font-mono text-[10px] text-fg-dim">
        <span>{label(bars[0]!.date)}</span>
        <span>{label(bars[Math.floor(bars.length / 2)]!.date)}</span>
        <span>today</span>
      </div>
    </div>
  );
}

function BySource({ ledger }: { ledger: Overview["ledger"] }) {
  const by = ledger?.bySource ?? null;
  const total = ledger?.monthEarned ?? 0;
  const max = by ? Math.max(1, ...Object.values(by)) : 1;
  return (
    <div className="grid">
      {SOURCES.map((s) => {
        const v = by ? (by[s.key] ?? 0) : null;
        return (
          <Row key={s.key} cols="1fr 90px auto">
            <RowName name={s.label} sub={v === null ? "not attributed yet" : undefined} />
            <Meter parts={v === null ? [] : [{ pct: (v / max) * 100 }]} />
            <span className={"tnum text-right font-semibold " + (v === null ? "text-fg-dim" : "")}>{v === null ? "—" : yen(v)}</span>
          </Row>
        );
      })}
      <Row cols="1fr auto">
        <RowName name="All sources" sub={by ? undefined : "per-source split arrives with zc#516"} />
        <span className="tnum text-right font-semibold">{ledger ? yen(total) : "—"}</span>
      </Row>
    </div>
  );
}

function NodeRows({ ov }: { ov: Overview | null }) {
  if (!ov) return <Empty>Waiting for the agent.</Empty>;
  return (
    <div className="grid">
      {ov.nodes.map((n) => {
        const w = n.thisNode ? ov.thisNode.workers : null;
        const live = n.thisNode ? ov.jobs.live.length : null;
        const sub = [n.thisNode ? "this node" : null, n.backend === "container" ? "container workers" : n.backend === "host" ? "host workers" : null, `${n.workers} worker${n.workers === 1 ? "" : "s"}`, n.online ? null : `seen ${ago(n.lastSeenAt)}`]
          .filter(Boolean)
          .join(" · ");
        return (
          <Row key={n.id} cols="1fr 110px auto 72px">
            <RowName name={n.name} sub={sub} />
            {w && w.max > 0 ? <Meter parts={[{ pct: (w.busy / w.max) * 100 }, { pct: ((w.running - w.busy) / w.max) * 100, dim: true }]} /> : <span className="text-[11px] text-fg-dim">{n.thisNode ? "not sharing" : "—"}</span>}
            {live !== null ? (
              <Pill tone={live > 0 ? "ok" : "neutral"}>{live > 0 ? `${live} job${live === 1 ? "" : "s"}` : ov.thisNode.sharing ? "Idle" : "Paused"}</Pill>
            ) : (
              <Pill tone={n.online ? "ok" : "neutral"}>{n.online ? "Online" : n.freshness}</Pill>
            )}
            <span className="tnum text-right font-semibold">{n.priceMin === null ? "—" : n.priceMin === n.priceMax ? perHour(n.priceMin) : `${yen(n.priceMin)}+`}</span>
          </Row>
        );
      })}
    </div>
  );
}

function LiveJobs({ ov }: { ov: Overview | null }) {
  if (!ov) return <Empty>Waiting for the agent.</Empty>;
  if (ov.jobs.live.length === 0)
    return <Empty>{ov.thisNode.sharing ? "Nothing running right now. A job shows up here the moment a worker picks one up." : "Sharing is paused, so nothing runs here. Resume sharing to take jobs."}</Empty>;
  return (
    <div className="grid">
      {ov.jobs.live.map((j) => (
        <Row key={j.id} cols="1fr auto auto">
          <RowName name={`${j.source ? (SOURCES.find((s) => s.key === j.source)?.label ?? j.source) : "Job"} · ${j.id}`} sub={`${j.worker} · started ${ago(j.startedAt)}${j.squad ? ` · ${j.squad}` : ""}`} />
          <Pill tone={j.source ? "wine" : "neutral"}>{j.source ? (SOURCE_PILL[j.source] ?? j.source) : "Unattributed"}</Pill>
          <span className="tnum text-right font-semibold">{j.requests.toLocaleString("en-US")} req</span>
        </Row>
      ))}
    </div>
  );
}

/** This month so far against last month at the same point. The hub only
 * reports last month's total, so it is prorated by the share of the month
 * elapsed. `null` during the first day, when the base is too small to mean
 * anything, or when there is no last month to compare with. */
export function paceDelta(monthEarned: number, prevMonthEarned: number | null, now: Date): number | null {
  if (!prevMonthEarned || prevMonthEarned <= 0) return null;
  const start = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
  const end = new Date(now.getFullYear(), now.getMonth() + 1, 1).getTime();
  const elapsed = (now.getTime() - start) / (end - start);
  if (now.getTime() - start < 86400_000) return null;
  const base = prevMonthEarned * elapsed;
  return (monthEarned - base) / base;
}