zc2 0.0.52

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 { agent } from "../lib/agent";
import { MACHINE, ago, screenError } from "../lib/format";
import { duration, filterJobs, minutesRun, NO_FILTER, sourceLabel, sourcesOf, squadsOf, UNATTRIBUTED, type JobFilter } from "../lib/jobs";
import { Empty, Kpi, Notice, Panel, Pill, Row, RowName, ScreenHead, Seg } from "../components/ui";

// What this machine ran: live jobs first, then the last 200 finished ones
// (`GET /v2/jobs`). Filter by state, source and squad. Amounts per job are
// not in the agent's answer; the day and product totals are on Earnings.

const SHOWN = 100;

function Pick({ label, value, onChange, options }: { label: string; value: string; onChange: (v: string) => void; options: { value: string; label: string }[] }) {
  return (
    <label className="flex items-center gap-1.5 text-[12px] text-fg-dim">
      {label}
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="rounded-sm border border-hairline bg-surface px-1.5 py-1 text-[12px] text-fg"
      >
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </label>
  );
}

export function Jobs({ ov }: { ov: Overview | null }) {
  const [jobs, setJobs] = useState<Job[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [f, setF] = useState<JobFilter>(NO_FILTER);
  useEffect(() => {
    agent.jobs().then(
      (j) => {
        setJobs(j);
        setError(null);
      },
      (e) => {
        setJobs(null);
        setError(screenError(e));
      },
    );
  }, [ov?.jobs.done24h, ov?.jobs.live.length]);

  const shown = useMemo(() => filterJobs(jobs ?? [], f), [jobs, f]);
  const sources = useMemo(() => sourcesOf(jobs ?? []), [jobs]);
  const squads = useMemo(() => squadsOf(jobs ?? []), [jobs]);
  const w = ov?.thisNode.workers;
  const filtered = f.state !== "all" || f.source !== "all" || f.squad !== "all";

  return (
    <>
      <ScreenHead title="Jobs" sub={`What this ${MACHINE} runs and ran for Zakuro`} />
      <div className="grid grid-cols-[repeat(auto-fit,minmax(180px,1fr))] gap-2.5">
        <Kpi label="Running now" value={ov ? ov.jobs.live.length : "—"} sub={w ? `${w.busy} of ${w.running} workers busy` : undefined} />
        <Kpi label="Finished 24 h" value={ov ? ov.jobs.done24h : "—"} />
        <Kpi label="Requests 1 w" value={ov ? ov.thisNode.requests1w.toLocaleString("en-US") : "—"} />
      </div>
      {error && (
        <Notice tone="warn" title="Couldn't read the jobs">
          {error}
        </Notice>
      )}
      <Panel
        title={`Jobs${jobs ? ` · ${shown.length}` : ""}`}
        aside={
          <span className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
            <Seg<JobFilter["state"]>
              value={f.state}
              onChange={(state) => setF({ ...f, state })}
              options={[
                { value: "all", label: "All" },
                { value: "live", label: "Live" },
                { value: "done", label: "History" },
              ]}
            />
            <Pick
              label="Source"
              value={f.source}
              onChange={(source) => setF({ ...f, source })}
              options={[
                { value: "all", label: "All" },
                ...sources.map((s) => ({ value: s, label: sourceLabel(s) })),
                ...(jobs?.some((j) => j.source === null) ? [{ value: UNATTRIBUTED, label: "Unattributed" }] : []),
              ]}
            />
            <Pick
              label="Squad"
              value={f.squad}
              onChange={(squad) => setF({ ...f, squad })}
              options={[
                { value: "all", label: "All" },
                ...squads.map((s) => ({ value: s, label: s })),
                ...(jobs?.some((j) => j.squad === null) ? [{ value: UNATTRIBUTED, label: "No squad" }] : []),
              ]}
            />
          </span>
        }
      >
        {jobs === null ? (
          <Empty>{error ? "No answer from the agent." : "Waiting for the agent."}</Empty>
        ) : shown.length === 0 ? (
          <Empty>{filtered ? "No job matches these filters." : "No jobs yet. Each busy span of a worker shows up here as a job."}</Empty>
        ) : (
          shown.slice(0, SHOWN).map((j) => {
            const min = minutesRun(j);
            return (
              <Row key={j.id} cols="1fr auto auto auto">
                <RowName
                  name={`${j.id} · ${j.worker}`}
                  sub={`${j.live ? `started ${ago(j.startedAt)}` : `finished ${ago(j.finishedAt)}${min !== null ? ` · ran ${duration(min)}` : ""}`} · ${j.squad ?? "no squad"}`}
                />
                <Pill tone={j.source ? "wine" : "neutral"}>{sourceLabel(j.source)}</Pill>
                <Pill tone={j.live ? "ok" : "neutral"}>{j.live ? "Live" : "Done"}</Pill>
                <span className="tnum text-right font-semibold">{j.requests} req</span>
              </Row>
            );
          })
        )}
        {jobs && shown.length > SHOWN && <span className="text-[11.5px] text-fg-dim">Showing the latest {SHOWN} of {shown.length}.</span>}
      </Panel>
    </>
  );
}