zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useEffect, useRef, useState } from "react";
import { host, listen, type AppUpdateEvent, type AppUpdateInfo, type ZcUpdateCheck, type ZcUpdateEvent } from "../lib/agent";
import { Button, Panel, Pill, Row, RowName } from "../components/ui";

// Settings › Updates. zc: the agent's zc against the newest zc2 on crates.io;
// Install builds that version with cargo, swaps it in and restarts the agent
// (`zc update --from-crates --agent`). The app: the signed update manifest
// (`updater.rs`); release builds carry zc's version, so crates.io's zc2 also
// says when a newer app exists.

/** `a` newer than `b`, comparing `x.y.z` numerically; unparseable is never newer. */
export function newerVersion(a: string | null | undefined, b: string | null | undefined): boolean {
  const p = (v: string | null | undefined) => {
    const m = /^(\d+)\.(\d+)\.(\d+)/.exec((v ?? "").trim());
    return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
  };
  const x = p(a);
  const y = p(b);
  if (!x || !y) return false;
  for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i]! > y[i]!;
  return false;
}

const errText = (e: unknown) => String((e as { message?: string })?.message ?? e);

type ZcPhase = { s: "idle" } | { s: "running"; step: string; started: number } | { s: "done"; text: string } | { s: "error"; text: string };

export function UpdatesPanel({ appVersion, onAgentRestarted }: { appVersion: string | null; onAgentRestarted: () => void }) {
  const [zc, setZc] = useState<ZcUpdateCheck | null>(null);
  const [zcErr, setZcErr] = useState<string | null>(null);
  const [checking, setChecking] = useState(false);
  const [phase, setPhase] = useState<ZcPhase>({ s: "idle" });
  const [now, setNow] = useState(Date.now());
  const [appUpd, setAppUpd] = useState<AppUpdateInfo | null>(null);
  const [appErr, setAppErr] = useState<string | null>(null);
  const [appBusy, setAppBusy] = useState(false);
  const [bg, setBg] = useState<AppUpdateEvent | null>(null);
  const restarted = useRef(false);

  useEffect(() => {
    let un: (() => void) | undefined;
    listen<AppUpdateEvent>("app-update", setBg).then((f) => (un = f));
    return () => un?.();
  }, []);

  const check = () => {
    setChecking(true);
    setZcErr(null);
    setAppErr(null);
    host
      .zcUpdateCheck()
      .then((c) => {
        setZc(c);
        if (c.error) setZcErr(c.error);
      }, (e) => setZcErr(errText(e)))
      .finally(() => setChecking(false));
    host.appUpdateCheck().then(setAppUpd, (e) => {
      setAppUpd(null);
      setAppErr(errText(e));
    });
  };
  useEffect(check, []);

  useEffect(() => {
    if (phase.s !== "running") return;
    const t = window.setInterval(() => setNow(Date.now()), 1000);
    return () => window.clearInterval(t);
  }, [phase.s]);

  useEffect(() => {
    let un: (() => void) | undefined;
    listen<ZcUpdateEvent>("zc-update", (e) => {
      const started = Date.now();
      switch (e.event) {
        case "building":
          setPhase({ s: "running", step: `Building zc ${e.version} from crates.io`, started });
          break;
        case "verifying":
          setPhase((p) => ({ s: "running", step: `Checking zc ${e.version}`, started: p.s === "running" ? p.started : started }));
          break;
        case "installed":
          setPhase((p) => ({ s: "running", step: "Restarting the agent", started: p.s === "running" ? p.started : started }));
          break;
        case "agent_restarted":
          restarted.current = true;
          break;
        case "agent_not_restarted":
          setPhase({ s: "done", text: `Installed. The agent was not restarted: ${e.reason ?? "unknown reason"}` });
          break;
        case "up_to_date":
          setPhase({ s: "done", text: "Already up to date." });
          break;
        case "done":
          setPhase((p) => (p.s === "done" ? p : { s: "done", text: `✓ zc ${e.version} installed${restarted.current ? " · agent restarted" : ""}` }));
          if (restarted.current) onAgentRestarted();
          check();
          break;
        case "error":
          setPhase({ s: "error", text: e.message ?? "The update failed." });
          break;
        case "exit":
          setPhase((p) => (p.s === "running" ? { s: "error", text: `zc stopped (exit ${e.code ?? "signal"}) before finishing` } : p));
          break;
      }
    }).then((f) => (un = f));
    return () => un?.();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const installZc = () => {
    restarted.current = false;
    setPhase({ s: "running", step: "Starting", started: Date.now() });
    host.zcUpdateInstall().catch((e) => setPhase({ s: "error", text: errText(e) }));
  };

  const installApp = () => {
    setAppBusy(true);
    setAppErr(null);
    // On success the app relaunches; this promise only settles on failure.
    host.appUpdateInstall().catch((e) => {
      setAppBusy(false);
      setAppErr(errText(e));
    });
  };

  const running = phase.s === "running";
  const elapsed = running ? Math.max(0, Math.floor((now - phase.started) / 1000)) : 0;
  const latest = zc?.latest ?? null;
  const appBehindCrates = newerVersion(latest, appVersion);

  return (
    <Panel title="Updates" aside={latest ? `crates.io ${zc?.crate ?? "zc2"} ${latest}` : "crates.io"}>
      <Row cols="1fr auto">
        <RowName
          name="zc (agent)"
          sub={zc ? `${zc.current || "?"}${latest ? ` → ${latest}` : ""} · ${zc.exe}` : checking ? "checking…" : undefined}
        />
        <span className="flex items-center gap-2">
          {running ? (
            <span className="font-mono text-[12px] text-fg-dim">
              {phase.step}… {fmtClock(elapsed)}
            </span>
          ) : zc?.newer ? (
            !zc.cargo ? (
              <span className="text-[12px] text-fg-dim">needs cargo (rustup.rs)</span>
            ) : !zc.writable ? (
              <span className="text-[12px] text-fg-dim">{zc.exe} is not writable</span>
            ) : (
              <Button size="sm" variant="primary" onClick={installZc}>
                Install {latest}
              </Button>
            )
          ) : zc && !zcErr ? (
            <Pill tone="ok">up to date</Pill>
          ) : null}
        </span>
      </Row>
      {running && phase.step.startsWith("Building") && <p className="m-0 text-[11.5px] text-fg-dim">cargo builds zc from source: a few minutes. The agent keeps running until the new binary is ready.</p>}
      {phase.s === "done" && <p className="m-0 text-[12px] text-live">{phase.text}</p>}
      {phase.s === "error" && <p className="m-0 text-[12px] text-wine-bright">{phase.text}</p>}
      {zcErr && <p className="m-0 text-[12px] text-wine-bright">{zcErr}</p>}

      <Row cols="1fr auto">
        <RowName
          name="Zakuro Desktop"
          sub={`${appVersion ?? "?"}${appUpd?.available ? ` → ${appUpd.available}` : appBehindCrates ? ` → ${latest}` : ""}${appUpd?.channel ? ` · ${appUpd.channel === "edge" ? "edge (master builds)" : "stable"}` : ""}${appUpd?.auto ? " · auto-update on" : ""}`}
        />
        <span className="flex items-center gap-2">
          {appUpd?.available ? (
            <Button size="sm" variant="primary" disabled={appBusy} onClick={installApp}>
              {appBusy ? "Installing…" : `Install ${appUpd.available}`}
            </Button>
          ) : appUpd && !appUpd.supported ? (
            <span className="text-[12px] text-fg-dim">{appUpd.notes}</span>
          ) : appBehindCrates ? (
            <span className="text-[12px] text-fg-dim">not on the update server yet</span>
          ) : appUpd ? (
            <Pill tone="ok">up to date</Pill>
          ) : null}
        </span>
      </Row>
      {bg && (
        <p className="m-0 text-[12px] text-fg-dim">
          {bg.phase === "downloading"
            ? `Downloading ${bg.version} (${bg.channel})…`
            : bg.phase === "installed"
              ? `${bg.version} is installed. Zakuro relaunches when you close this window.`
              : `The background update to ${bg.version} failed; it retries within the hour.`}
        </p>
      )}
      {appErr && (
        <p className="m-0 text-[12px] text-fg-dim">
          The app update server did not answer: {appErr}
          {appBehindCrates ? `. zc2 ${latest} is out; its app build installs from the release page until the server publishes it.` : ""}
        </p>
      )}

      <div className="flex justify-end">
        <Button size="sm" disabled={checking || running || appBusy} onClick={check}>
          {checking ? "Checking…" : "Check again"}
        </Button>
      </div>
    </Panel>
  );
}

function fmtClock(s: number): string {
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
}