import { useCallback, useEffect, useState } from "react";
import { host, hosting, type LoginEvent, type MachineCheck, type ProvisionState } from "../lib/agent";
import { busy, mb, useProvision } from "../lib/provision";
import { groupChecks, pending, type CheckRow } from "../lib/checks";
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";
import { ConsentList } from "../components/Consent";
// The first-run screens (plan snapshot S2), the same five steps as `zc setup`:
// welcome → sign-in (done in-app on the login page) → machine check
// (`zc doctor --json`) → share defaults → done. Each screen asks one thing
// and the defaults are already chosen.
// "Sandbox" (zc#635) only on a Mac: there the agent downloads and boots the
// sandbox VM; Linux runs jobs in Incus, set up by the .deb.
const ALL_STEPS = ["Welcome", "Sign in", "Check", "Sandbox", "Public squad", "Your share", "Done"] as const;
type StepName = (typeof ALL_STEPS)[number];
export function Setup({ hook, ov, onDone, onSwitchAccount, startAt = 0 }: { hook: AgentHook; ov: Overview | null; onDone: () => void; onSwitchAccount: () => void; startAt?: number }) {
const [step, setStep] = useState(startAt);
const mac = navigator.userAgent.includes("Mac");
const machine = mac ? "Mac" : "machine";
const STEPS: readonly StepName[] = mac ? ALL_STEPS : ALL_STEPS.filter((s) => s !== "Sandbox");
const at = STEPS[step];
const next = () => setStep((s) => Math.min(s + 1, STEPS.length - 1));
// Started as soon as the agent answers (right after sign-in) and left to
// run while the owner goes on: the download takes minutes.
const provision = useProvision(mac && hook.state.status === "ok");
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">
{at === "Welcome" && <Welcome machine={machine} />}
{at === "Sign in" && <SignIn ov={ov} onSignedIn={next} onSwitchAccount={onSwitchAccount} />}
{at === "Check" && <Check onOk={next} onSignedOut={onSwitchAccount} provision={provision} />}
{at === "Sandbox" && <Sandbox p={provision} onNext={next} />}
{at === "Public squad" && <Consent onAgree={next} />}
{at === "Your share" && <Share hook={hook} ov={ov} machine={machine} onDone={next} />}
{at === "Done" && <Done mac={mac} hook={hook} provision={provision.state} />}
</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 < STEPS.length - 1 && (
<Button size="sm" onClick={onDone}>
Skip setup
</Button>
)}
{at === "Welcome" && (
<Button size="sm" variant="primary" onClick={next}>
Get started
</Button>
)}
{step === STEPS.length - 1 && (
<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>
</>
);
}
// Sign-in itself happens on the login page (screens/Login.tsx), in the app:
// by the time setup runs this machine is signed in. This step only confirms
// the account, or hands back to the login page for another one.
function SignIn({ ov, onSignedIn, onSwitchAccount }: { ov: Overview | null; onSignedIn: () => void; onSwitchAccount: () => void }) {
return (
<>
<h4 className="m-0 text-[17px] font-semibold">You're signed in</h4>
<p className="m-0 text-[13px] text-fg-dim">
{ov?.account ? (
<>
This machine is signed in as <b className="text-fg">{ov.account.username}</b>.
</>
) : (
"This machine is signed in. Your account shows here once the agent is running."
)}
</p>
<span className="flex gap-2">
<Button variant="primary" onClick={onSignedIn}>
Continue
</Button>
<Button onClick={onSwitchAccount}>Use another account</Button>
</span>
</>
);
}
export 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.`;
}
// The machine check (zc#637): what needs the owner (each with the one action
// that fixes it), what Zakuro is still setting up, and what is ready. It
// re-checks by itself while anything is pending and when the window comes
// back; "Check again" is only the fallback.
const MARK = { ok: "✓", warn: "!", fail: "✗" } as const;
const TONE = { ok: "text-live", warn: "text-warn", fail: "text-wine-bright" } as const;
function Check({ onOk, onSignedOut, provision }: { onOk: () => void; onSignedOut: () => void; provision: ReturnType<typeof useProvision> }) {
const [report, setReport] = useState<MachineCheck | null>(null);
const [error, setError] = useState<string | null>(null);
const [details, setDetails] = useState(false);
const [acting, setActing] = useState<string | null>(null);
const mac = navigator.userAgent.includes("Mac");
// Background re-checks keep the last report on screen: no flicker.
const run = useCallback(() => {
host.machineCheck().then(
(r) => {
setReport(r);
setError(null);
},
(e) => setError(String((e as { message?: string }).message ?? e)),
);
}, []);
useEffect(run, [run]);
const groups = report ? groupChecks(report.checks, provision.state, mac) : null;
const waiting = groups ? pending(groups) : false;
useEffect(() => {
if (!waiting) return;
const t = setInterval(run, 5000);
window.addEventListener("focus", run);
return () => {
clearInterval(t);
window.removeEventListener("focus", run);
};
}, [waiting, run]);
const act = async (id: string) => {
setActing(id);
setError(null);
try {
if (id === "sign_in") return onSignedOut();
if (id === "retry_sandbox") return provision.retry();
await host.machineFix(id);
// The key belonged to the other hub and went with it: sign in again.
if (id === "reset_hub") return onSignedOut();
run();
} catch (e) {
setError(String((e as { message?: string }).message ?? e));
} finally {
setActing(null);
}
};
const failed = report?.checks.some((c) => c.status === "fail") ?? false;
const section = (title: string, rows: CheckRow[]) =>
rows.length > 0 && (
<section className="grid gap-1.5" aria-label={title}>
<h5 className="m-0 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-fg-dim">{title}</h5>
{rows.map((c) => (
<div key={c.id} className="grid grid-cols-[16px_1fr_auto] items-start gap-x-2 text-[12.5px]">
<span className={"font-bold " + (c.progress ? "text-wine" : TONE[c.status])}>{c.progress ? "…" : MARK[c.status]}</span>
<span>
{c.label}
{(details || c.status !== "ok" || c.progress) && <span className="block text-[11.5px] text-fg-dim">{c.progress ? `${c.detail} · ${c.progress}` : c.detail}</span>}
{details && c.diagnostics && <span className="block break-words font-mono text-[10.5px] text-fg-dim">{c.diagnostics}</span>}
</span>
{c.action ? (
<Button size="sm" variant="primary" disabled={acting !== null} onClick={() => act(c.action!.id)}>
{acting === c.action.id ? "…" : c.action.label}
</Button>
) : (
<span />
)}
</div>
))}
</section>
);
return (
<>
<h4 className="m-0 text-[17px] font-semibold">{!groups ? "Checking this machine" : groups.needs.length ? "Needs your attention" : groups.setup.length ? "Almost ready" : "This machine is ready"}</h4>
{error && <p className="m-0 text-[13px] text-wine-bright">{error}</p>}
{!report && !error && <p className="m-0 text-[13px] text-fg-dim">Checking…</p>}
{groups && (
<div className="grid gap-3">
{section("Needs you", groups.needs)}
{section("Setting up", groups.setup)}
{section("Ready", groups.ready)}
</div>
)}
<span className="flex gap-2">
{report && !failed && (
<Button variant="primary" onClick={onOk}>
{groups?.setup.length ? "Continue while it finishes" : "Continue"}
</Button>
)}
{report && (
<Button size="sm" onClick={() => setDetails(!details)}>
{details ? "Hide details" : "Details"}
</Button>
)}
{(failed || error) && (
<Button size="sm" onClick={run}>
Check again
</Button>
)}
</span>
</>
);
}
// The sandbox VM (zc#635): the agent downloads its image and boots it once.
// The owner watches, or goes on: it keeps running, and Done says so.
function Sandbox({ p, onNext }: { p: ReturnType<typeof useProvision>; onNext: () => void }) {
const [details, setDetails] = useState(false);
const s = p.state;
const ready = s?.phase === "ready";
const failed = s?.phase === "failed";
const pct = s?.phase === "downloading" && s.total ? Math.min(100, Math.floor((s.done / s.total) * 100)) : ready ? 100 : null;
const line = !s
? p.error
? "The Zakuro agent isn't answering yet. The sandbox starts as soon as it does."
: "Waiting for the Zakuro agent…"
: s.phase === "downloading"
? `Downloading the sandbox · ${mb(s.done)}${s.total ? ` of ${mb(s.total)}` : ""}${p.left ? ` · ${p.left}` : ""}`
: s.phase === "verifying"
? "Checking the download…"
: s.phase === "ready"
? "Ready. Other people's jobs run inside it, never directly on your Mac."
: failed
? s.reason
: "Starting the sandbox…";
return (
<>
<h4 className="m-0 text-[17px] font-semibold">{ready ? "Your sandbox is ready" : failed ? "The sandbox didn't start" : "Preparing your sandbox"}</h4>
<p className="m-0 text-[13px] text-fg-dim">Jobs run in a small virtual machine on this Mac, walled off from your files. Zakuro sets it up once; it takes a few minutes.</p>
<div className="h-1.5 overflow-hidden rounded-full bg-hairline" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={pct ?? undefined}>
<div
className={"h-full rounded-full transition-[width] duration-500 " + (failed ? "bg-wine-bright" : ready ? "bg-live" : "bg-wine") + (pct === null && !failed ? " w-1/3 animate-pulse" : "")}
style={pct !== null ? { width: `${pct}%` } : failed ? { width: "100%" } : undefined}
/>
</div>
<p className={"m-0 text-[12.5px] " + (failed ? "text-wine-bright" : "text-fg-dim")} aria-live="polite">
{line}
</p>
{failed && details && s?.diagnostics && <p className="m-0 break-words font-mono text-[10.5px] text-fg-dim">{s.diagnostics}</p>}
<span className="flex gap-2">
{failed ? (
<>
<Button variant="primary" onClick={p.retry}>
Retry
</Button>
<Button onClick={onNext}>Skip for now</Button>
{s?.diagnostics && (
<Button size="sm" onClick={() => setDetails(!details)}>
{details ? "Hide details" : "Details"}
</Button>
)}
</>
) : (
<Button variant="primary" onClick={onNext}>
{ready ? "Continue" : "Continue while it finishes"}
</Button>
)}
</span>
</>
);
}
// The public squad is the default, so the owner reads what it means and
// agrees once, before anything is lent. Skipping setup lends nothing.
function Consent({ onAgree }: { onAgree: () => void }) {
return (
<>
<h4 className="m-0 text-[17px] font-semibold">Joining the public squad</h4>
<ConsentList />
<span>
<Button variant="primary" onClick={onAgree}>
I understand, continue
</Button>
</span>
</>
);
}
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 on the Price screen" />
<span className="tnum font-semibold">{perHour(ov?.prices.thisNode.effective ?? ov?.prices.accountDefault)}</span>
</Row>
<Row cols="1fr auto">
<RowName name="Public squad" sub="The default for every node. Leave by turning Share off." />
<Pill tone="ok">Joined</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, provision }: { mac: boolean; hook: AgentHook; provision: ProvisionState | null }) {
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 with the Sharing switch, or from the menu bar."}
</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 && busy(provision) && (
<Row cols="1fr auto">
<RowName name="Sandbox" sub="Still setting up; jobs start once it is ready, even with this window closed" />
<Pill tone="warn">{provision?.phase === "downloading" && provision.total ? `${Math.floor((provision.done / provision.total) * 100)}%` : "Starting"}</Pill>
</Row>
)}
{mac && (
<Row cols="1fr">
<RowName name="Add the widget" sub="Right-click the desktop › Edit Widgets › Zakuro" />
</Row>
)}
</div>
</>
);
}