zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useEffect, useRef, useState } from "react";
import { agent, isAgentError } from "../lib/agent";
import type { HandoffPreview } from "../lib/summaryV2";
import { Button } from "./ui";

// The confirmation sheet for a `zakuro://` link (ADR ZC-0020 §4). The agent
// verifies the link (`POST /v2/handoff`) and says what it would change; only
// the Confirm click runs it (`POST /v2/handoff/{jti}/confirm`). Every link
// gets this sheet, `open?view=` included: nothing happens without the click.

/** Where a handled link leaves the app. */
export interface LinkOutcome {
  view: string;
  /** share/budget: the proposal to prefill. */
  prefill?: Record<string, unknown> | null;
  /** A verified action this zc cannot run yet. */
  notAvailable?: { title: string; until: string | null; exp: number | null };
}

type State =
  | { s: "verifying" }
  | { s: "preview"; p: HandoffPreview }
  | { s: "running"; p: HandoffPreview }
  | { s: "error"; title: string; message: string; code: string | null };

const ERROR_TITLE: Record<string, string> = {
  expired: "This link has expired",
  already_used: "This link was already used",
  wrong_account: "This link is for another account",
  account_unknown: "Not signed in yet",
  wrong_node: "This link is for another node",
  no_action_key: "Open in Zakuro is not set up here",
  unknown_key: "Unrecognised link signature",
  bad_signature: "This link's signature does not verify",
  unsigned: "This link is not signed by the hub",
  invalid_link: "Not a Zakuro link",
  storage: "This machine can't record used links",
  agent_busy: "The Zakuro agent is busy",
};

/** `open?view=` needs no agent: when the agent is down, read the view here. */
export function localOpenView(link: string, views: readonly string[]): string | null {
  const m = /^zakuro:\/\/open\/?\?view=([a-z]+)$/i.exec(link.trim());
  return m && views.includes(m[1]!) ? m[1]! : null;
}

export function ConfirmSheet({ link, views, onClose, onSignIn }: { link: string; views: readonly string[]; onClose: (o: LinkOutcome | null) => void; onSignIn: () => void }) {
  const [st, setSt] = useState<State>({ s: "verifying" });
  const [now, setNow] = useState(() => Math.floor(Date.now() / 1000));
  // While /confirm is in flight the sheet cannot be dismissed (the action
  // may already have run), and it closes exactly once: a second onClose
  // would dequeue the next link unseen.
  const running = useRef(false);
  const closed = useRef(false);
  const close = (o: LinkOutcome | null) => {
    if (closed.current) return;
    closed.current = true;
    onClose(o);
  };
  const dismiss = () => {
    if (!running.current) close(null);
  };

  useEffect(() => {
    let live = true;
    agent.handoff(link).then(
      (p) => live && setSt({ s: "preview", p }),
      (e) => {
        if (!live) return;
        const view = localOpenView(link, views);
        if (view && isAgentError(e) && (e.kind === "not_installed" || e.kind === "unreachable")) {
          setSt({
            s: "preview",
            p: { act: "open", jti: null, sub: null, node: null, exp: null, title: `Open ${view[0]!.toUpperCase()}${view.slice(1)}`, summary: "Shows a screen of the app. Nothing on this machine changes.", details: [], view, available: true, until: null, prefill: null, args: null },
          });
          return;
        }
        const code = isAgentError(e) ? e.code : null;
        setSt({ s: "error", code, title: (code && ERROR_TITLE[code]) ?? "This link can't be opened", message: isAgentError(e) ? e.message : String(e) });
      },
    );
    const t = window.setInterval(() => setNow(Math.floor(Date.now() / 1000)), 1000);
    return () => {
      live = false;
      window.clearInterval(t);
    };
  }, [link]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && dismiss();
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }); // re-bound each render: dismiss reads the latest refs

  const confirm = async (p: HandoffPreview) => {
    if (!p.jti) {
      // Token-less: `open` lands on its screen; `auth/callback` on setup.
      close(p.available ? { view: p.view } : { view: p.view, notAvailable: { title: p.title, until: p.until, exp: null } });
      return;
    }
    if (!p.available) {
      // Verified, but this zc cannot run it: route to the screen and say so.
      // The link is not used, so it still works once the feature ships.
      close({ view: p.view, notAvailable: { title: p.title, until: p.until, exp: p.exp } });
      return;
    }
    if (running.current) return;
    running.current = true;
    setSt({ s: "running", p });
    try {
      const done = await agent.confirmHandoff(p.jti);
      running.current = false;
      close({ view: done.view, prefill: done.prefill });
    } catch (e) {
      running.current = false;
      const code = isAgentError(e) ? e.code : null;
      if (code === "not_implemented") {
        close({ view: p.view, notAvailable: { title: p.title, until: p.until, exp: p.exp } });
        return;
      }
      setSt({ s: "error", code, title: (code && ERROR_TITLE[code]) ?? "The action did not run", message: isAgentError(e) ? e.message : String(e) });
    }
  };

  const p = st.s === "preview" || st.s === "running" ? st.p : null;
  const left = p?.exp ? p.exp - now : null;
  const expired = left !== null && left <= 0;
  const verb = !p ? "" : !p.jti ? "Open" : p.act === "squad/join" ? "Join" : p.act === "env/launch" ? "Launch" : p.act === "env/connect" ? "Connect" : "Continue";

  return (
    <div className="fixed inset-0 z-50 grid place-items-center bg-[oklch(0.15_0.01_18/0.38)] p-5" role="dialog" aria-modal="true" aria-labelledby="sheet-title">
      <div className="grid w-[400px] max-w-full gap-3 rounded-lg border border-hairline bg-surface p-[18px] shadow-overlay">
        <span className="font-mono text-[10.5px] uppercase tracking-[0.08em] text-fg-dim">From the hub · zakuro://{p?.act ?? linkAct(link)}</span>
        {st.s === "verifying" && <h4 id="sheet-title" className="m-0 text-[15.5px] font-semibold">Checking the link…</h4>}
        {st.s === "error" && (
          <>
            <h4 id="sheet-title" className="m-0 text-[15.5px] font-semibold">
              {st.title}
            </h4>
            <p className="m-0 text-[12.5px] text-fg-dim">{st.message}</p>
            <p className="m-0 text-[12px] text-fg-dim">Nothing on this machine changed.</p>
            <div className="flex justify-end gap-2">
              {(st.code === "wrong_account" || st.code === "account_unknown") && <Button
                  onClick={() => {
                    if (closed.current) return;
                    closed.current = true;
                    onSignIn();
                  }}
                >
                  Sign in as another account
                </Button>}
              <Button variant="primary" onClick={() => close(null)}>
                Close
              </Button>
            </div>
          </>
        )}
        {p && (
          <>
            <h4 id="sheet-title" className="m-0 text-[15.5px] font-semibold">
              {p.title}
            </h4>
            <p className="m-0 text-[12.5px] text-fg-dim">{p.summary}</p>
            {p.details.length > 0 && (
              <dl className="m-0 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-[12.5px]">
                {p.details.map((d) => (
                  <div key={d.label} className="contents">
                    <dt className="text-fg-dim">{d.label}</dt>
                    <dd className="m-0 font-medium">{d.value}</dd>
                  </div>
                ))}
              </dl>
            )}
            {!p.available && <p className="m-0 rounded-sm bg-warn/10 px-2.5 py-1.5 text-[12px]">Not available in this zc yet{p.until ? ` (ships with ${p.until})` : ""}. Continuing opens the screen; nothing changes.</p>}
            {left !== null && <p className="m-0 font-mono text-[11px] text-fg-dim">{expired ? "expired" : `valid ${Math.ceil(left / 60)} more min · signed by the hub`}</p>}
            <div className="flex justify-end gap-2">
              <Button disabled={st.s === "running"} onClick={dismiss}>
                Cancel
              </Button>
              <Button variant="primary" autoFocus disabled={st.s === "running" || expired} onClick={() => confirm(p)}>
                {st.s === "running" ? "Working…" : verb}
              </Button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function linkAct(link: string): string {
  return link.replace(/^zakuro:\/\//i, "").split("?")[0] ?? "";
}