zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useCallback, useEffect, useMemo, useState } from "react";
import { isAgentError, offers as offersApi, type Offer, type OffersResponse } from "../lib/agent";
import { Button, Pill, ScreenHead, Toggle } from "../components/ui";
import { mergeSaved, parsePrice, subscribeChange } from "../lib/offers";
import { perHour } from "../lib/format";

const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");

type Filter = { kind: "all" } | { kind: "subscribed" } | { kind: "category"; name: string };

interface CardState {
  saving: boolean;
  error: string | null;
}

const errText = (e: unknown): string => {
  if (isAgentError(e)) return e.code ? `${e.code}: ${e.message}` : e.message;
  return typeof e === "string" ? e : String(e);
};

const cr = perHour;

/** The provider catalogue: what this machine hosts for consumers, and at what price. */
export function Environments({ onOwnNode }: { onOwnNode: (templateId: string) => void }) {
  const [data, setData] = useState<OffersResponse | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [loadCode, setLoadCode] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<Filter>({ kind: "all" });
  const [query, setQuery] = useState("");
  const [cards, setCards] = useState<Record<string, CardState>>({});

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setData(await offersApi.list());
      setLoadError(null);
      setLoadCode(null);
    } catch (e) {
      setLoadError(isAgentError(e) ? e.message : String(e));
      setLoadCode(isAgentError(e) ? e.code : null);
    } finally {
      setLoading(false);
    }
  }, []);
  useEffect(() => {
    void load();
  }, [load]);

  const patchCard = (id: string, p: Partial<CardState>) =>
    setCards((c) => ({ ...c, [id]: { saving: false, error: null, ...c[id], ...p } }));

  /** Optimistic: show `next` at once, roll back to `prev` and show the error if the PUT fails. */
  const change = async (prev: Offer, next: Offer, body: Parameters<typeof offersApi.set>[1]) => {
    const id = prev.template.id;
    const put = (o: Offer) => setData((d) => d && { ...d, offers: d.offers.map((x) => (x.template.id === id ? o : x)) });
    put(next);
    patchCard(id, { saving: true, error: null });
    try {
      const saved = await offersApi.set(id, body);
      put(mergeSaved(prev, next, saved));
      patchCard(id, { saving: false });
    } catch (e) {
      put(prev);
      patchCard(id, { saving: false, error: errText(e) });
    }
  };

  const subscribe = (o: Offer, on: boolean) => {
    const { next, body } = subscribeChange(o, on);
    return change(o, next, body);
  };
  const setPrice = (o: Offer, price: "default" | number) =>
    change(
      o,
      price === "default"
        ? { ...o, price_mode: "auto", price_per_hour: o.default_price_per_hour }
        : { ...o, price_mode: "fixed", price_per_hour: price },
      { subscribed: true, price },
    );

  const all = data?.offers ?? [];
  const subscribedCount = all.filter((o) => o.subscribed).length;

  const visible = useMemo(() => {
    const q = query.trim().toLowerCase();
    return all.filter((o) => {
      if (filter.kind === "subscribed" && !o.subscribed) return false;
      if (filter.kind === "category" && o.template.category !== filter.name) return false;
      if (!q) return true;
      const t = o.template;
      return [t.name, t.description, t.publisher].some((s) => s.toLowerCase().includes(q));
    });
  }, [all, filter, query]);

  const groups = useMemo(() => {
    const order = data?.categories ?? [];
    const by = new Map<string, Offer[]>();
    for (const o of visible) by.set(o.template.category, [...(by.get(o.template.category) ?? []), o]);
    const names = [...by.keys()].sort((a, b) => {
      const ia = order.indexOf(a);
      const ib = order.indexOf(b);
      return (ia < 0 ? 999 : ia) - (ib < 0 ? 999 : ib) || a.localeCompare(b);
    });
    return names.map((n) => ({ name: n, items: by.get(n) ?? [] }));
  }, [visible, data]);

  const countIn = (cat: string) => all.filter((o) => o.template.category === cat).length;

  return (
    <>
      <ScreenHead title="Environments" sub="Choose what this machine hosts for consumers, and at what price. The switch hosts on the main node; “its own node” gives an environment a node and a share to itself.">
        <input
          type="search"
          aria-label="Search environments"
          placeholder="Search name, description, publisher"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          className="w-64 rounded-sm border border-hairline bg-surface px-2.5 py-1.5 text-[12.5px] outline-none focus:border-wine"
        />
      </ScreenHead>

      {loadError && (
        <div role="alert" className="flex flex-wrap items-center justify-between gap-2 rounded-r-md border-l-[3px] border-wine bg-wine/10 px-4 py-2.5 text-[12.5px]">
          <div className="grid gap-0.5">
            <b className="font-semibold">{loadCode ?? "Couldn't load environments"}</b>
            <span className="text-fg-dim">{loadError}</span>
          </div>
          <Button size="sm" disabled={loading} onClick={() => void load()}>
            Retry
          </Button>
        </div>
      )}

      <div className="grid min-w-0 grid-cols-[180px_1fr] items-start gap-4 max-[760px]:grid-cols-1">
        <nav aria-label="Categories" className="sticky top-0 grid gap-0.5 max-[760px]:static max-[760px]:flex max-[760px]:flex-wrap">
          <CatButton on={filter.kind === "all"} onClick={() => setFilter({ kind: "all" })} n={all.length}>
            All
          </CatButton>
          <CatButton on={filter.kind === "subscribed"} onClick={() => setFilter({ kind: "subscribed" })} n={subscribedCount}>
            Subscribed ({subscribedCount})
          </CatButton>
          <div className="mx-2 my-1.5 border-t border-hairline max-[760px]:hidden" />
          {(data?.categories ?? []).map((c) => (
            <CatButton key={c} on={filter.kind === "category" && filter.name === c} onClick={() => setFilter({ kind: "category", name: c })} n={countIn(c)}>
              {c}
            </CatButton>
          ))}
        </nav>

        <div className="grid min-w-0 gap-5">
          {loading && !data && <p className="m-0 text-[12.5px] text-fg-dim">Loading the catalogue…</p>}
          {data && groups.length === 0 && (
            <p className="m-0 py-8 text-center text-[12.5px] text-fg-dim">
              {filter.kind === "subscribed" && !query ? "This machine isn't subscribed to any environment yet." : "No environment matches."}
            </p>
          )}
          {groups.map((g) => (
            <section key={g.name} className="grid gap-2.5">
              <h5 className="m-0 flex items-baseline gap-2 text-[13px] font-semibold">
                {g.name}
                <span className="tnum text-[11.5px] font-normal text-fg-dim">{g.items.length}</span>
              </h5>
              <div className="grid grid-cols-[repeat(auto-fill,minmax(260px,1fr))] gap-2.5">
                {g.items.map((o) => (
                  <OfferCard key={o.template.id} offer={o} st={cards[o.template.id]} onSubscribe={(on) => subscribe(o, on)} onPrice={(p) => setPrice(o, p)} onOwnNode={() => onOwnNode(o.template.id)} />
                ))}
              </div>
            </section>
          ))}
        </div>
      </div>
    </>
  );
}

function CatButton({ on, onClick, n, children }: { on: boolean; onClick: () => void; n: number; children: React.ReactNode }) {
  return (
    <button
      onClick={onClick}
      aria-current={on ? "true" : undefined}
      className={cx(
        "flex items-center justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-[12.5px]",
        on ? "bg-wine/10 font-semibold text-wine-bright" : "text-fg hover:bg-raised",
      )}
    >
      <span>{children}</span>
      <em className="tnum text-[11px] not-italic text-fg-dim max-[760px]:hidden">{n}</em>
    </button>
  );
}

const STATE_TONE: Record<string, "ok" | "warn" | "bad" | "neutral"> = {
  healthy: "ok",
  running: "ok",
  pending: "neutral",
  idle: "neutral",
  starting: "warn",
  degraded: "warn",
  failed: "bad",
  unhealthy: "bad",
};

function Icon({ offer }: { offer: Offer }) {
  const t = offer.template;
  const [broken, setBroken] = useState(false);
  if (t.icon_url && !broken) {
    return <img src={t.icon_url} alt="" onError={() => setBroken(true)} className="h-9 w-9 flex-none rounded-md border border-hairline bg-bg object-contain p-1" />;
  }
  return (
    <span aria-hidden="true" className="grid h-9 w-9 flex-none place-items-center rounded-md bg-wine/10 text-[15px] font-semibold text-wine-bright">
      {t.name.trim().charAt(0).toUpperCase()}
    </span>
  );
}

function OfferCard({ offer: o, st, onSubscribe, onPrice, onOwnNode }: { offer: Offer; st: CardState | undefined; onSubscribe: (on: boolean) => void; onPrice: (p: "default" | number) => void; onOwnNode: () => void }) {
  const t = o.template;
  const blocked = o.fits === false;
  const gpu = t.gpu_required ? (t.min_vram_gb ? `GPU · ${t.min_vram_gb} GB VRAM` : "GPU") : "CPU only";
  return (
    <article className={cx("grid content-start gap-2 rounded-md border bg-surface px-3.5 py-3", o.subscribed ? "border-wine/50" : "border-hairline")}>
      <div className={cx("grid gap-2", blocked && "opacity-60")}>
        <div className="flex items-start gap-2.5">
          <Icon offer={o} />
          <div className="grid min-w-0 flex-1 gap-px">
            <span className="font-mono text-[10px] uppercase tracking-[0.06em] text-fg-dim">{t.kind}</span>
            <b className="truncate text-[13.5px] font-semibold">{t.name}</b>
            <span className="flex items-center gap-1 truncate text-[11.5px] text-fg-dim">
              {t.publisher}
              {t.verified && (
                <svg viewBox="0 0 16 16" className="h-3.5 w-3.5 flex-none text-cyan" role="img" aria-label="Verified publisher">
                  <path fill="currentColor" d="M8 0.8l1.9 1.3 2.3-.1.8 2.2 1.9 1.4-.7 2.2.7 2.2-1.9 1.4-.8 2.2-2.3-.1L8 15.2l-1.9-1.3-2.3.1-.8-2.2-1.9-1.4.7-2.2-.7-2.2 1.9-1.4.8-2.2 2.3.1z" />
                  <path fill="none" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" d="M5.2 8.2l2 2 3.6-3.8" className="stroke-surface" />
                </svg>
              )}
            </span>
          </div>
          <Toggle label={`Subscribe to ${t.name}`} on={o.subscribed} disabled={(blocked && !o.subscribed) || st?.saving} onChange={onSubscribe} />
        </div>
        <p className="m-0 line-clamp-3 text-[12px] leading-snug text-fg-dim">{t.description}</p>
        <div className="flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11.5px] text-fg-dim">
          <span className={cx(t.gpu_required && "text-fg")}>{gpu}</span>
          <span className="tnum">{o.hosts} {o.hosts === 1 ? "host" : "hosts"}</span>
          <span className="tnum">≈ {cr(o.default_price_per_hour)}</span>
        </div>
      </div>
      {blocked && o.fit_reason && <span className="text-[11.5px] text-warn">This machine can't host it: {o.fit_reason}</span>}
      {!blocked && !o.subscribed && (
        <button type="button" onClick={onOwnNode} className="justify-self-start text-[11.5px] font-medium text-wine-bright hover:underline">
          Host it in its own node ›
        </button>
      )}
      {o.subscribed && <PriceControl offer={o} saving={!!st?.saving} onPrice={onPrice} />}
      {st?.error && (
        <span role="alert" className="text-[11.5px] text-wine-bright">
          Couldn't save: {st.error}
        </span>
      )}
    </article>
  );
}

function PriceControl({ offer: o, saving, onPrice }: { offer: Offer; saving: boolean; onPrice: (p: "default" | number) => void }) {
  const custom = o.price_mode === "fixed";
  const [text, setText] = useState(String(o.price_per_hour ?? o.default_price_per_hour ?? ""));
  const [bad, setBad] = useState(false);
  // Follow the server's value when it changes (rollback, refresh).
  useEffect(() => {
    if (o.price_per_hour !== null) setText(String(o.price_per_hour));
  }, [o.price_per_hour]);

  const commit = () => {
    const n = parsePrice(text);
    if (n === null) {
      setBad(true);
      return;
    }
    setBad(false);
    if (custom && n === o.price_per_hour) return;
    onPrice(n);
  };

  const seg = (on: boolean) => cx("px-2 py-1 text-[11.5px] font-medium transition-colors disabled:opacity-60", on ? "bg-wine text-on-wine" : "bg-surface text-fg hover:bg-raised");
  return (
    <div className="grid gap-1.5 border-t border-hairline pt-2">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div role="group" aria-label="Price mode" className="inline-flex divide-x divide-hairline overflow-hidden rounded-sm border border-hairline">
          <button
            className={seg(!custom)}
            aria-pressed={!custom}
            disabled={saving}
            onClick={() => {
              setBad(false);
              if (custom) onPrice("default");
            }}
          >
            Default · {cr(o.default_price_per_hour)}
          </button>
          <button
            className={seg(custom)}
            aria-pressed={custom}
            disabled={saving}
            onClick={() => {
              if (!custom && o.default_price_per_hour && o.default_price_per_hour > 0) {
                setText(String(o.default_price_per_hour));
                setBad(false);
                onPrice(o.default_price_per_hour);
              }
            }}
          >
            Custom
          </button>
        </div>
        {o.state && <Pill tone={STATE_TONE[o.state] ?? "neutral"}>{o.state}</Pill>}
      </div>
      {custom ? (
        <label className="flex items-center gap-1.5 text-[12px]">
          <input
            aria-label={`${o.template.name} price per hour`}
            inputMode="decimal"
            value={text}
            disabled={saving}
            onChange={(e) => {
              setText(e.target.value);
              setBad(false);
            }}
            onBlur={commit}
            onKeyDown={(e) => e.key === "Enter" && e.currentTarget.blur()}
            className={cx("tnum w-20 rounded-sm border bg-bg px-2 py-1 font-mono text-[12.5px] outline-none", bad ? "border-wine" : "border-hairline focus:border-wine")}
          />
          <span className="text-fg-dim">¥ / h</span>
          {saving && <span className="text-fg-dim">Saving…</span>}
          {bad && <span className="text-wine-bright">Must be more than 0</span>}
        </label>
      ) : (
        <span className="text-[11.5px] text-fg-dim">
          {saving ? "Saving…" : `Follows the ${o.price_basis === "market" || o.price_basis === "mesh" ? "market" : "suggested"} price`}
        </span>
      )}
    </div>
  );
}