zc2 0.0.53

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 { SOURCES } from "../lib/jobs";
import { WeeklySummary } from "../components/WeeklySummary";
import { agent, hosting } from "../lib/agent";
import { notEarningCopy } from "../lib/deployments";
import { MACHINE, ago, perHour, yen } from "../lib/format";
import { Button, Empty, Go, Kpi, Meter, Notice, Panel, Pill, Pomegranate, 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 };

const SOURCE_PILL: Record<string, string> = { ...Object.fromEntries(SOURCES.map((s) => [s.key, s.pill])), peer: "Peer" };

export function Contribution({ ov, onNavigate }: { ov: Overview | null; onNavigate: (s: "nodes" | "jobs" | "resources" | "environments" | "wallet") => void }) {
  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

  // Why this machine may not be earning (`/v2/deployments`), shown when the
  // last 7 days earned nothing.
  const [notEarning, setNotEarning] = useState<string | null>(null);
  useEffect(() => {
    let live = true;
    hosting
      .deployments()
      .then((d) => live && setNotEarning(notEarningCopy(d.not_earning_reason)))
      .catch(() => live && setNotEarning(null));
    return () => {
      live = false;
    };
  }, [ov?.jobs.done24h, ov?.thisNode.sharing]);
  const weekEarned = (ov?.ledger?.days ?? []).slice(-7).reduce((a, d) => a + d.earned, 0);

  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="Overview" sub={ov ? `${month} · ${ov.nodesTotal === 1 ? `this ${MACHINE}` : `all ${ov.nodesTotal} of your nodes`}` : "Waiting for the agent"}>
        <Seg value={range} onChange={setRange} options={[{ value: "7d", label: "7 d" }, { value: "30d", label: "30 d" }]} />
      </ScreenHead>

      <Hero ov={ov} onNavigate={onNavigate} />

      <div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] 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 ${MACHINE}`}
        />
        <Kpi label="Hours lent" value={done ? `${fmtHours(stats.hours)}` : "—"} sub={done ? `busy worker time · ${RANGE_DAYS[range]} d` : `from this ${MACHINE}`} />
      </div>

      {ov?.ledger && weekEarned === 0 && notEarning && <Notice tone="warn" title="Nothing earned this week">{notEarning}</Notice>}

      <WeeklySummary ov={ov} />

      <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">Earned and spent by day and by product are on the Earnings screen.</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={<Go onClick={() => onNavigate("nodes")}>All nodes</Go>}>
          <NodeRows ov={ov} />
        </Panel>
        <Panel title={ov?.jobs.live.length ? `Running now · ${ov.jobs.live.length}` : "Running now"} aside={<Go onClick={() => onNavigate("jobs")}>All jobs</Go>}>
          <LiveJobs ov={ov} />
        </Panel>
      </div>
    </>
  );
}

/** The state of this machine in one sentence, and the two things an owner
 * does next: change what is lent, or host something. */
function Hero({ ov, onNavigate }: { ov: Overview | null; onNavigate: (s: "resources" | "environments" | "wallet") => void }) {
  const w = ov?.thisNode.workers;
  const state: { title: string; sub: string; tone: "live" | "idle" | "warn" } = !ov
    ? { title: "Waiting for the agent", sub: "Zakuro's background agent isn't answering yet.", tone: "idle" }
    : !ov.thisNode.sharing
      ? { title: "Sharing is paused", sub: `This ${MACHINE} takes no jobs. Turn Sharing on in the sidebar to start lending again.`, tone: "idle" }
      : !w || w.running === 0
        ? ov.problems.length
          ? { title: "Sharing is on, but nothing is running", sub: ov.problems[0]!.message, tone: "warn" }
          : { title: "Getting ready", sub: "The sandbox and the first worker are starting.", tone: "idle" }
        : ov.jobs.live.length
          ? { title: `Running ${ov.jobs.live.length} job${ov.jobs.live.length === 1 ? "" : "s"} right now`, sub: `${w.busy} of ${w.running} worker${w.running === 1 ? "" : "s"} busy on this ${MACHINE}.`, tone: "live" }
          : { title: `This ${MACHINE} is lending`, sub: `${w.running} worker${w.running === 1 ? "" : "s"} ready and waiting for jobs.`, tone: "live" };
  const ring = state.tone === "live" ? "bg-live/15 text-live" : state.tone === "warn" ? "bg-warn/15 text-warn" : "bg-raised text-fg-dim";
  return (
    <section className="flex flex-wrap items-center justify-between gap-4 rounded-lg border border-hairline bg-surface px-5 py-4">
      <div className="flex min-w-0 items-center gap-3.5">
        <span className={"grid h-12 w-12 flex-none place-items-center rounded-full " + ring}>
          <Pomegranate className="h-6 w-6" hollow={!ov?.thisNode.sharing} />
        </span>
        <div className="grid min-w-0 gap-0.5">
          <b className="text-[17px] font-semibold tracking-tight">{state.title}</b>
          <span className="text-[12.5px] text-fg-dim">{state.sub}</span>
        </div>
      </div>
      <div className="flex flex-wrap items-center gap-5">
        <div className="grid gap-px text-right">
          <span className="font-mono text-[10px] uppercase tracking-[0.06em] text-fg-dim">Earned today</span>
          <b className="tnum text-[22px] font-semibold tracking-tight text-earn">{yen(ov?.ledger?.todayEarned ?? ov?.earnings?.today)}</b>
        </div>
        <span className="flex gap-2">
          <Button onClick={() => onNavigate("resources")}>Change what you lend</Button>
          <Button variant="primary" onClick={() => onNavigate("environments")}>
            Host an environment
          </Button>
        </span>
      </div>
    </section>
  );
}

/** 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.filter((s) => s.key !== "test").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 split by source 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 : "the hub has no per-source split yet"} />
        <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 ${MACHINE}` : 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. Turn Sharing on in the sidebar 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;
}