zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useEffect, useRef, useState } from "react";
import { host, hosting, listen, type LoginEvent, type MachineCheck } from "../lib/agent";
import { GPU_LINE } from "../lib/deployments";
import type { Overview } from "../lib/overview";
import type { AgentHook } from "../lib/useAgent";
import { perHour } from "../lib/format";
import { Button, Pill, Pomegranate, Row, RowName, Toggle } from "../components/ui";

// The first-run screens (plan snapshot S2), the same five steps as `zc setup`:
// welcome → browser sign-in (`zc login --json`) → machine check
// (`zc doctor --json`) → share defaults → done. Each screen asks one thing
// and the defaults are already chosen.

const STEPS = ["Welcome", "Sign in", "Check", "Your share", "Done"] as const;

export function Setup({ hook, ov, onDone, startAt = 0, switchAccount = false }: { hook: AgentHook; ov: Overview | null; onDone: () => void; startAt?: number; switchAccount?: boolean }) {
  const [step, setStep] = useState(startAt);
  const mac = navigator.userAgent.includes("Mac");
  const machine = mac ? "Mac" : "machine";
  const next = () => setStep((s) => Math.min(s + 1, STEPS.length - 1));

  return (
    <div className="grid h-full place-items-center bg-bg p-6" data-tauri-drag-region>
      <div className="grid w-[460px] max-w-full grid-rows-[auto_1fr_auto] overflow-hidden rounded-lg border border-hairline bg-surface shadow-overlay">
        <div className="flex items-center justify-between border-b border-hairline bg-raised px-4 py-2 text-[11.5px] text-fg-dim">
          <span>{STEPS[step]}</span>
          <span className="font-mono">
            {step + 1} / {STEPS.length}
          </span>
        </div>
        <div className="grid min-h-[300px] content-start gap-3 px-6 py-5">
          {step === 0 && <Welcome machine={machine} />}
          {step === 1 && <SignIn ov={ov} onSignedIn={next} switchAccount={switchAccount} />}
          {step === 2 && <Check onOk={next} />}
          {step === 3 && <Share hook={hook} ov={ov} machine={machine} onDone={next} />}
          {step === 4 && <Done mac={mac} hook={hook} />}
        </div>
        <div className="flex items-center justify-between gap-2 px-6 pb-5">
          <span className="flex gap-1" aria-hidden="true">
            {STEPS.map((s, i) => (
              <i key={s} className={"block h-1 w-4 rounded-full " + (i <= step ? "bg-wine" : "bg-hairline")} />
            ))}
          </span>
          <span className="flex gap-2">
            {step < 4 && (
              <Button size="sm" onClick={onDone}>
                Skip setup
              </Button>
            )}
            {step === 0 && (
              <Button size="sm" variant="primary" onClick={next}>
                Get started
              </Button>
            )}
            {step === 4 && (
              <Button size="sm" variant="primary" onClick={onDone}>
                Open dashboard
              </Button>
            )}
          </span>
        </div>
      </div>
    </div>
  );
}

function Welcome({ machine }: { machine: string }) {
  return (
    <>
      <Pomegranate className="h-7 w-7 text-wine" />
      <h4 className="m-0 text-[17px] font-semibold leading-snug">Lend your {machine} when you're not using it</h4>
      <p className="m-0 text-[13px] text-fg-dim">
        Zakuro runs other people's jobs on this {machine} and pays you for the time. You decide how much of it to lend, and you can pause any time from the menu bar.
      </p>
    </>
  );
}

function SignIn({ ov, onSignedIn, switchAccount }: { ov: Overview | null; onSignedIn: () => void; switchAccount: boolean }) {
  const hasSession = !!ov?.account && !ov.problems.some((p) => p.code === "not_logged_in");
  // "Sign in as another account" (a link for another account): sign in again
  // with `--force` instead of offering the current session.
  const [force, setForce] = useState(switchAccount);
  const signedIn = hasSession && !force;
  const [code, setCode] = useState<LoginEvent | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [done, setDone] = useState(false);
  const [elapsed, setElapsed] = useState(0);
  const started = useRef(false);
  const doneRef = useRef(false);

  useEffect(() => {
    if (signedIn) return;
    let un: (() => void) | undefined;
    listen<LoginEvent>("login", (e) => {
      if (e.event === "code") setCode(e);
      if (e.event === "error") setError(e.message ?? "Sign-in failed.");
      if (e.event === "signed_in") {
        doneRef.current = true;
        setDone(true);
        window.setTimeout(onSignedIn, 900);
      }
      // zc exited without a JSON `error` or `signed_in` (an older zc that
      // rejects --json, a crash): say so instead of waiting forever.
      if (e.event === "exit") {
        if (!doneRef.current) setError((cur) => cur ?? exitMessage(e));
      }
    }).then((f) => (un = f));
    if (!started.current) {
      started.current = true;
      host.startLogin(false, force).catch((e) => setError(String((e as { message?: string }).message ?? e)));
    }
    const t = window.setInterval(() => setElapsed((s) => s + 1), 1000);
    return () => {
      un?.();
      window.clearInterval(t);
    };
  }, [signedIn]); // eslint-disable-line react-hooks/exhaustive-deps

  if (signedIn)
    return (
      <>
        <h4 className="m-0 text-[17px] font-semibold">You're signed in</h4>
        <p className="m-0 text-[13px] text-fg-dim">
          This {ov?.env} machine is signed in as <b className="text-fg">{ov?.account?.username}</b>.
        </p>
        <span className="flex gap-2">
          <Button variant="primary" onClick={onSignedIn}>
            Continue
          </Button>
          <Button onClick={() => setForce(true)}>Use another account</Button>
        </span>
      </>
    );

  const retry = () => {
    setError(null);
    setCode(null);
    setElapsed(0);
    host.startLogin(false, force).catch((e) => setError(String((e as { message?: string }).message ?? e)));
  };
  return (
    <>
      <h4 className="m-0 text-[17px] font-semibold">{force && hasSession ? "Sign in as another account" : "Sign in with your browser"}</h4>
      {force && hasSession && (
        <p className="m-0 text-[12.5px] text-fg-dim">
          This machine is signed in as <b className="text-fg">{ov?.account?.username}</b>. Approving the code below replaces that session.
        </p>
      )}
      {error ? (
        <>
          <p className="m-0 text-[13px] text-wine-bright">{error}</p>
          <span>
            <Button onClick={retry}>Try again</Button>
          </span>
        </>
      ) : done ? (
        <p className="m-0 text-[13px] text-live">✓ Signed in. One moment…</p>
      ) : code ? (
        <>
          <p className="m-0 text-[13px] text-fg-dim">
            {code.browser_opened ? "We opened the hub in your browser." : "Open this link in a browser on any device."} Check that the page shows this code, then approve it.
          </p>
          <div className="rounded-md border border-dashed border-hairline bg-bg py-2.5 text-center font-mono text-[20px] font-semibold tracking-[0.18em]">{code.user_code}</div>
          <p className="m-0 text-[12px] text-fg-dim">
            Waiting for the browser… <span className="font-mono">{fmtClock(elapsed)}</span>
          </p>
          <span className="flex gap-2">
            <Button size="sm" onClick={() => code.url && navigator.clipboard?.writeText(code.url)}>
              Copy link
            </Button>
            <Button size="sm" onClick={() => code.url && host.openExternal(code.url)}>
              Open again
            </Button>
          </span>
        </>
      ) : (
        <p className="m-0 text-[13px] text-fg-dim">Starting the sign-in…</p>
      )}
    </>
  );
}

function exitMessage(e: LoginEvent): string {
  // The line that says what went wrong, not the usage text after it.
  const lines = e.stderr?.trim().split("\n").map((l) => l.trim()).filter(Boolean) ?? [];
  const tail = [...lines].reverse().find((l) => /error|panicked/i.test(l)) ?? lines.pop();
  const what = e.code === 0 ? "zc finished without signing in" : `zc stopped (exit ${e.code ?? "signal"}) before signing in`;
  return tail ? `${what}: ${tail}` : `${what}. Update zc, or run zc login in a terminal.`;
}

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

function Check({ onOk }: { onOk: () => void }) {
  const [report, setReport] = useState<MachineCheck | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [details, setDetails] = useState(false);
  const run = () => {
    setReport(null);
    setError(null);
    host.machineCheck().then(setReport, (e) => setError(String((e as { message?: string }).message ?? e)));
  };
  useEffect(run, []);
  const failed = report?.checks.filter((c) => c.status === "fail") ?? [];
  const mark = { ok: "✓", warn: "!", fail: "✗" } as const;
  const tone = { ok: "text-live", warn: "text-warn", fail: "text-wine-bright" } as const;
  return (
    <>
      <h4 className="m-0 text-[17px] font-semibold">Checking this machine</h4>
      {error && <p className="m-0 text-[13px] text-wine-bright">{error}</p>}
      {!report && !error && <p className="m-0 text-[13px] text-fg-dim">Running zc doctor…</p>}
      {report && (
        <div className="grid gap-1.5 text-[12.5px]">
          {report.checks.map((c) => (
            <div key={c.id} className="grid grid-cols-[16px_1fr] gap-2">
              <span className={"font-bold " + tone[c.status]}>{mark[c.status]}</span>
              <span>
                {c.label}
                {(details || c.status !== "ok") && <span className="block text-[11.5px] text-fg-dim">{c.detail}</span>}
              </span>
            </div>
          ))}
        </div>
      )}
      <span className="flex gap-2">
        {report && failed.length === 0 && (
          <Button variant="primary" onClick={onOk}>
            Continue
          </Button>
        )}
        {(failed.length > 0 || error) && <Button onClick={run}>Check again</Button>}
        {report && (
          <Button size="sm" onClick={() => setDetails(!details)}>
            {details ? "Hide details" : "Details"}
          </Button>
        )}
      </span>
      {failed.length > 0 && <p className="m-0 text-[12px] text-fg-dim">Fix the items marked ✗, then check again.</p>}
    </>
  );
}

function Share({ hook, ov, machine, onDone }: { hook: AgentHook; ov: Overview | null; machine: string; onDone: () => void }) {
  const w = ov?.thisNode.workers;
  const [share, setShare] = useState(true);
  // On by default (the owner sees it once, here); saved to hosting.toml.
  const [gpu, setGpu] = useState(true);
  const [workers, setWorkers] = useState<number | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const max = w?.max ?? 0;
  const count = workers ?? (w && w.desired > 0 ? w.desired : max);

  const apply = async () => {
    setBusy(true);
    setError(null);
    try {
      if (hook.state.status === "no-agent") {
        await host.startAgent();
        await hook.retry();
      }
      if (share) {
        if (w && count !== w.desired) await hook.setWorkers(count);
        await hook.setSharing(true);
        const h = await hosting.settings();
        if (h.budget.gpu !== gpu) await hosting.saveSettings({ ...h, budget: { ...h.budget, gpu } });
      }
      onDone();
    } catch (e) {
      setError(String((e as { message?: string }).message ?? e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <h4 className="m-0 text-[17px] font-semibold">How much to lend</h4>
      <div className="grid">
        <Row cols="1fr auto">
          <RowName name={`Share this ${machine}`} sub="Pause any time from the menu bar" />
          <Toggle label="Share" on={share} onChange={setShare} />
        </Row>
        <Row cols="1fr auto">
          <RowName name={GPU_LINE} sub="LLM fine-tuning for your own jobs · only when plugged in and idle" />
          <Toggle label="Share the GPU" on={share && gpu} disabled={!share} onChange={setGpu} />
        </Row>
        <Row cols="1fr auto">
          <RowName name="Workers" sub={max ? `up to ${max} on this ${machine} (half its CPUs)` : "waiting for the agent"} />
          <span className="flex items-center gap-2">
            <Button size="sm" disabled={!share || count <= 1} onClick={() => setWorkers(count - 1)}>
              −
            </Button>
            <span className="tnum w-6 text-center font-mono">{max ? count : "—"}</span>
            <Button size="sm" disabled={!share || count >= max} onClick={() => setWorkers(count + 1)}>
              +
            </Button>
          </span>
        </Row>
        <Row cols="1fr auto">
          <RowName name="Price" sub="your account default; change it in Budget & price" />
          <span className="tnum font-semibold">{perHour(ov?.prices.thisNode.effective ?? ov?.prices.accountDefault)}</span>
        </Row>
        <Row cols="1fr auto">
          <RowName name="Join the public squad · only when idle" sub="the default for every node, with zc#514" />
          <Pill>Coming</Pill>
        </Row>
      </div>
      {error && <p className="m-0 text-[12.5px] text-wine-bright">{error}</p>}
      <span>
        <Button variant="primary" disabled={busy} onClick={apply}>
          {busy ? "Starting…" : "Continue"}
        </Button>
      </span>
    </>
  );
}

function Done({ mac, hook }: { mac: boolean; hook: AgentHook }) {
  const [autostart, setAutostart] = useState<boolean | null>(null);
  useEffect(() => {
    host.appInfo().then((a) => setAutostart(a.autostart), () => setAutostart(null));
  }, []);
  const sharing = hook.state.status === "ok" && hook.state.overview.thisNode.sharing;
  return (
    <>
      <div className="grid h-11 w-11 place-items-center rounded-full bg-live/15 text-[22px] font-bold text-live">✓</div>
      <h4 className="m-0 text-[17px] font-semibold">{sharing ? "You're contributing" : "You're set up"}</h4>
      <p className="m-0 text-[13px] text-fg-dim">
        {sharing ? "Jobs start arriving as the mesh routes them here. The Contribution screen shows each one live." : "Sharing is off. Turn it on any time from the menu bar or Budget & price."}
      </p>
      <div className="grid">
        <Row cols="1fr auto">
          <RowName name="Open Zakuro at login" sub="Starts in the menu bar, no window" />
          <Toggle label="Open at login" on={!!autostart} disabled={autostart === null} onChange={(v) => host.setAutostart(v).then(setAutostart)} />
        </Row>
        {mac && (
          <Row cols="1fr">
            <RowName name="Add the widget" sub="Right-click the desktop › Edit Widgets › Zakuro" />
          </Row>
        )}
      </div>
    </>
  );
}