import { useCallback, useEffect, useRef, useState } from "react";
import { host, listen } from "./lib/agent";
import { overviewOf, useAgent } from "./lib/useAgent";
import { MACHINE, yen } from "./lib/format";
import { pausedLabel } from "./lib/overview";
import { Pill, Pomegranate, Toggle } from "./components/ui";
import { Icon, type IconName } from "./components/kit";
import { AgentBanner } from "./components/AgentBanner";
import { ConfirmSheet, type LinkOutcome } from "./components/ConfirmSheet";
import { Notice } from "./components/ui";
import { Setup } from "./screens/Setup";
import { Login } from "./screens/Login";
import { Contribution } from "./screens/Contribution";
import { Nodes } from "./screens/Nodes";
import { Squads } from "./screens/V2Screens";
import { Jobs } from "./screens/Jobs";
import { Environments } from "./screens/Environments";
import { Hosting } from "./screens/Hosting";
import { Resources } from "./screens/Resources";
import { Wallet } from "./screens/Wallet";
import { Settings } from "./screens/Settings";
import { Logs } from "./screens/Logs";
export const SCREENS = ["contribution", "resources", "hosting", "environments", "jobs", "nodes", "squads", "budget", "wallet", "settings", "logs"] as const;
export type Screen = (typeof SCREENS)[number];
// `budget` keeps its id for links (zakuro://open?view=budget, share/budget):
// it opens Earnings, where the price now lives.
const LABEL: Record<Screen, string> = {
contribution: "Overview",
resources: "Resources",
hosting: "Hosting",
environments: "Environments",
jobs: "Jobs",
nodes: "Nodes",
squads: "Squads",
budget: "Earnings",
wallet: "Earnings",
settings: "Settings",
logs: "Logs",
};
const ICON: Record<Screen, IconName> = {
contribution: "home",
resources: "gauge",
nodes: "nodes",
hosting: "box",
environments: "grid",
jobs: "list",
squads: "users",
budget: "wallet",
wallet: "wallet",
settings: "gear",
logs: "log",
};
/** The sidebar: the home screen, this machine, the account, then the app. */
const GROUPS: { title: string | null; screens: Screen[] }[] = [
{ title: null, screens: ["contribution"] },
{ title: `This ${MACHINE}`, screens: ["resources", "nodes", "hosting", "environments", "jobs"] },
{ title: "Account", screens: ["wallet", "squads"] },
{ title: "App", screens: ["settings", "logs"] },
];
/** Screens a `zakuro://open?view=` may name: the sidebar plus first run. */
const VIEWS = [...SCREENS, "setup"] as const;
export function App() {
const hook = useAgent();
const [screen, setScreen] = useState<Screen>("contribution");
const ov = overviewOf(hook.state);
const isAdmin = ov?.account?.isAdmin === true;
// null while unknown, so the first frame never flashes the dashboard.
const [setup, setSetup] = useState<{ step: number } | null | false>(null);
// Each queued link gets its own id: the same link twice (a double click,
// the OS re-delivering it) is two sheets, each verified on its own.
const [links, setLinks] = useState<{ id: number; link: string }[]>([]);
const nextLinkId = useRef(0);
const [notice, setNotice] = useState<{ screen: Screen; title: string; body: string } | null>(null);
const [prefill, setPrefill] = useState<Record<string, unknown> | null>(null);
// Environments › "Host it in its own node": the template for Nodes' form.
const [nodePreset, setNodePreset] = useState<string | null>(null);
// Cold start: no credentials → the login page (it opens the hub) before
// anything that needs an account or an agent. null while unknown.
const [signedIn, setSignedIn] = useState<boolean | null>(null);
const agentStarted = useRef(false);
useEffect(() => {
host.authStatus().then(
(a) => setSignedIn(a.signedIn),
() => setSignedIn(true),
);
host.setupDone().then(
(done) => setSetup(done ? false : { step: 0 }),
() => setSetup(false),
);
}, []);
// Signed in but no agent yet (a fresh install): install it once instead of
// greeting the user with "agent.json missing". Failures stay in the banner.
const { retry } = hook;
useEffect(() => {
if (!signedIn || agentStarted.current || hook.state.status !== "no-agent" || hook.state.error.kind !== "not_installed") return;
agentStarted.current = true;
host.startAgent().then(retry, retry);
}, [signedIn, hook.state, retry]);
const onSignedIn = useCallback(() => {
setSignedIn(true);
// The account is new to this machine: skip Welcome and Sign in, go on
// to the machine check unless setup already ran.
setSetup((s) => (s === false ? false : { step: 2 }));
}, []);
// The tray's "Settings…" item picks a screen.
useEffect(() => {
const un = listen<string>("navigate", (p) => {
if ((SCREENS as readonly string[]).includes(p)) setScreen(p === "budget" ? "wallet" : (p as Screen));
});
return () => {
un.then((f) => f());
};
}, []);
// zakuro:// links (ADR ZC-0020): queued by the Rust side, one sheet each.
useEffect(() => {
const drain = () => host.takeDeepLinks().then((l) => l.length && setLinks((q) => [...q, ...l.map((link) => ({ id: nextLinkId.current++, link }))]), () => {});
drain();
const un = listen<string>("deep-link", drain);
return () => {
un.then((f) => f());
};
}, []);
const finishSetup = useCallback(() => {
host.finishSetup().catch(() => {});
setSetup(false);
setScreen("contribution");
}, []);
const onLink = (o: LinkOutcome | null) => {
setLinks((q) => q.slice(1));
if (!o) return;
if (o.view === "setup") {
setSetup({ step: o.notAvailable ? 1 : 0 });
return;
}
const target = ((SCREENS as readonly string[]).includes(o.view) ? o.view : "contribution") as Screen;
setSetup(false);
setScreen(target === "budget" ? "wallet" : target);
setPrefill(o.prefill ?? null);
if (o.notAvailable) {
const mins = o.notAvailable.exp ? Math.max(0, Math.ceil((o.notAvailable.exp - Date.now() / 1000) / 60)) : null;
setNotice({
screen: target === "budget" ? "wallet" : target,
title: `${o.notAvailable.title}: not available in this zc yet`,
body: `It ships with ${o.notAvailable.until ?? "a later zc"}. Nothing changed${mins !== null ? `, and the link stays valid for ${mins} more min` : ""}.`,
});
} else {
setNotice(null);
}
};
const head = links[0];
const sheet = head ? (
<ConfirmSheet
key={head.id}
link={head.link}
views={VIEWS}
onClose={onLink}
onSignIn={() => {
setLinks((q) => q.slice(1));
setSignedIn(false);
}}
/>
) : null;
if (signedIn === false) return <Login onSignedIn={onSignedIn} />;
if (setup === null || signedIn === null) return sheet;
if (setup)
return (
<>
<Setup key={setup.step} hook={hook} ov={ov} startAt={setup.step} onDone={finishSetup} onSwitchAccount={() => setSignedIn(false)} />
{sheet}
</>
);
const go = (s: Screen) => {
setScreen(s === "budget" ? "wallet" : s);
setNotice(null);
};
const count = (s: Screen): number | null => {
if (!ov) return null;
if (s === "jobs") return ov.jobs.live.length || null;
return null;
};
return (
<div className="grid h-full grid-cols-[190px_1fr]">
<aside className="flex flex-col gap-0.5 overflow-y-auto border-r border-hairline bg-surface px-2.5 pb-3 pt-9" data-tauri-drag-region>
<div className="flex items-center gap-2 px-2 pb-3.5 text-[14px] font-semibold" data-tauri-drag-region>
<Pomegranate className="h-4 w-4 text-wine" hollow={ov ? !ov.thisNode.sharing || !!ov.thisNode.ownerYield : false} />
Zakuro
</div>
<div className="mb-2 flex items-center justify-between gap-2 rounded-sm border border-hairline bg-bg px-2 py-1.5 text-[12px]">
<span className="grid gap-px">
<b className="font-semibold">Sharing</b>
<span className="text-[11px] text-fg-dim">{!ov ? "—" : !ov.thisNode.sharing ? "Paused" : (pausedLabel(ov.thisNode.ownerYield, MACHINE) ?? (ov.thisNode.workers.running > 0 ? `This ${MACHINE} takes jobs` : ov.problems.length ? "On, but not running" : "Starting…"))}</span>
</span>
<Toggle label={`Share this ${MACHINE}`} on={!!ov?.thisNode.sharing} disabled={!ov || hook.busy} onChange={(v) => hook.setSharing(v)} />
</div>
<nav className="grid gap-0.5" aria-label="Sections">
{GROUPS.map((g) => {
const items = g.screens.filter((s) => s !== "logs" || isAdmin);
return (
<div key={g.title ?? "home"} className="grid gap-0.5" role="group" aria-label={g.title ?? "Home"}>
{g.title && <span className="px-2 pb-0.5 pt-2.5 font-mono text-[10px] uppercase tracking-[0.08em] text-fg-dim">{g.title}</span>}
{items.map((s) => {
const n = count(s);
const on = s === screen;
return (
<button
key={s}
onClick={() => go(s)}
aria-current={on ? "page" : undefined}
className={"flex items-center justify-between rounded-sm px-2 py-1 text-left text-[13px] " + (on ? "bg-wine/10 font-semibold text-wine-bright" : "text-fg hover:bg-raised")}
>
<span className="flex items-center gap-2">
<Icon name={ICON[s]} className={on ? "" : "text-fg-dim"} />
{LABEL[s]}
</span>
{n !== null && <em className="tnum text-[11px] not-italic text-fg-dim">{n}</em>}
</button>
);
})}
</div>
);
})}
</nav>
<div className="mt-auto grid gap-1.5 border-t border-hairline px-2 pt-2.5 text-[11.5px] text-fg-dim">
{/* Without the agent the account is unknown, not signed out. */}
{ov && <b className="font-semibold text-fg">{ov.account?.username ?? "Not signed in"}</b>}
{ov?.account && <span>Balance {yen(ov.account.balance)}</span>}
{hook.state.status !== "ok" && <span className="justify-self-start">{hook.state.status === "loading" ? <Pill>Connecting…</Pill> : <Pill tone="warn">Agent offline</Pill>}</span>}
<span className="font-mono text-[10.5px]">
{ov ? `zc ${ov.agentVersion} · agent ${ov.apiVersion}` : "agent —"}
</span>
</div>
</aside>
<main className="min-w-0 overflow-y-auto px-6 pb-8 pt-9">
{/* One readable column: cards wrap inside it, nothing stretches across a wide window. */}
<div className="mx-auto grid w-full max-w-[1180px] content-start gap-4">
<AgentBanner hook={hook} onSettings={() => go("settings")} onLogs={() => go("logs")} onSignIn={() => setSignedIn(false)} />
{notice && notice.screen === screen && (
<Notice tone="warn" title={notice.title} onClose={() => setNotice(null)}>
{notice.body}
</Notice>
)}
{screen === "contribution" && <Contribution ov={ov} onNavigate={go} />}
{screen === "resources" && <Resources hook={hook} ov={ov} onNodes={() => go("nodes")} />}
{screen === "hosting" && <Hosting onResources={() => go("resources")} />}
{screen === "environments" && (
<Environments
onOwnNode={(t) => {
setNodePreset(t);
go("nodes");
}}
/>
)}
{screen === "jobs" && <Jobs ov={ov} />}
{screen === "nodes" && <Nodes hook={hook} ov={ov} onResources={() => go("resources")} preset={nodePreset} onPresetDone={() => setNodePreset(null)} />}
{screen === "squads" && <Squads />}
{screen === "wallet" && <Wallet hook={hook} ov={ov} prefill={prefill} onPrefillDone={() => setPrefill(null)} onResources={() => go("resources")} />}
{screen === "settings" && <Settings hook={hook} ov={ov} onRunSetup={() => setSetup({ step: 0 })} onSignedOut={() => setSignedIn(false)} />}
{screen === "logs" && isAdmin && <Logs />}
</div>
</main>
{sheet}
</div>
);
}