import { useCallback, useEffect, useRef, useState } from "react";
import { host, listen } from "./lib/agent";
import { overviewOf, useAgent } from "./lib/useAgent";
import { yen } from "./lib/format";
import { Pill, Pomegranate } from "./components/ui";
import { AgentBanner } from "./components/AgentBanner";
import { ConfirmSheet, type LinkOutcome } from "./components/ConfirmSheet";
import { Notice } from "./components/ui";
import { Setup } from "./screens/Setup";
import { Contribution } from "./screens/Contribution";
import { Nodes } from "./screens/Nodes";
import { Jobs, Squads } from "./screens/V2Screens";
import { Environments } from "./screens/Environments";
import { BudgetPrice } from "./screens/BudgetPrice";
import { Wallet } from "./screens/Wallet";
import { Settings } from "./screens/Settings";
import { Logs } from "./screens/Logs";
export const SCREENS = [
"contribution",
"nodes",
"jobs",
"environments",
"squads",
"budget",
"wallet",
"settings",
"logs",
] as const;
export type Screen = (typeof SCREENS)[number];
const LABEL: Record<Screen, string> = {
contribution: "Contribution",
nodes: "Nodes",
jobs: "Jobs",
environments: "Environments",
squads: "Squads",
budget: "Budget & price",
wallet: "Wallet",
settings: "Settings",
logs: "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; switchAccount?: boolean } | 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);
useEffect(() => {
host.setupDone().then(
(done) => setSetup(done ? false : { step: 0 }),
() => setSetup(false),
);
}, []);
// The tray's "Settings…" item picks a screen.
useEffect(() => {
const un = listen<string>("navigate", (p) => {
if ((SCREENS as readonly string[]).includes(p)) setScreen(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);
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,
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));
setSetup({ step: 1, switchAccount: true });
}}
/>
) : null;
if (setup === null) return sheet;
if (setup)
return (
<>
<Setup key={`${setup.step}-${setup.switchAccount ? 1 : 0}`} hook={hook} ov={ov} startAt={setup.step} switchAccount={setup.switchAccount} onDone={finishSetup} />
{sheet}
</>
);
const count = (s: Screen): number | null => {
if (!ov) return null;
if (s === "nodes") return ov.nodesTotal;
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 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 : false} />
Zakuro
</div>
<nav className="grid gap-0.5" aria-label="Sections">
{SCREENS.filter((s) => s !== "logs" || isAdmin).map((s) => {
const n = count(s);
const on = s === screen;
return (
<button
key={s}
onClick={() => {
setScreen(s);
setNotice(null);
}}
aria-current={on ? "page" : undefined}
className={
"flex items-center justify-between rounded-sm px-2 py-1.5 text-left text-[13px] " +
(on ? "bg-wine/10 font-semibold text-wine-bright" : "text-fg hover:bg-raised")
}
>
{LABEL[s]}
{n !== null && <em className="tnum text-[11px] not-italic text-fg-dim">{n}</em>}
</button>
);
})}
</nav>
<div className="mt-auto grid gap-1.5 border-t border-hairline px-2 pt-2.5 text-[11.5px] text-fg-dim">
<b className="font-semibold text-fg">{ov?.account?.username ?? "Not signed in"}</b>
<span>Balance {yen(ov?.account?.balance)}</span>
{hook.state.status === "ok" ? (
<span className="justify-self-start">
<Pill tone="ok">Agent connected</Pill>
</span>
) : hook.state.status === "loading" ? (
<span className="justify-self-start">
<Pill>Connecting…</Pill>
</span>
) : (
<span className="justify-self-start">
<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="grid min-w-0 content-start gap-3.5 overflow-y-auto px-5 pb-6 pt-9">
<AgentBanner hook={hook} onSettings={() => setScreen("settings")} onLogs={() => setScreen("logs")} />
{notice && notice.screen === screen && (
<Notice tone="warn" title={notice.title} onClose={() => setNotice(null)}>
{notice.body}
</Notice>
)}
{screen === "contribution" && <Contribution hook={hook} ov={ov} />}
{screen === "nodes" && <Nodes ov={ov} />}
{screen === "jobs" && <Jobs ov={ov} />}
{screen === "environments" && <Environments />}
{screen === "squads" && <Squads />}
{screen === "budget" && <BudgetPrice hook={hook} ov={ov} prefill={prefill} onPrefillDone={() => setPrefill(null)} />}
{screen === "wallet" && <Wallet ov={ov} />}
{screen === "settings" && <Settings hook={hook} ov={ov} onRunSetup={() => setSetup({ step: 0 })} />}
{screen === "logs" && isAdmin && <Logs />}
</main>
{sheet}
</div>
);
}