zc2 0.0.48

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useEffect, useState } from "react";
import type { Overview } from "../lib/overview";
import type { AgentHook } from "../lib/useAgent";
import { perHour } from "../lib/format";
import { Button, Notice, Panel, Row, RowName, ScreenHead, Seg, Toggle } from "../components/ui";
import { hosting, isAgentError, type HostingSettings } from "../lib/agent";

/** Workers and price are v1 writes; the CPU/RAM/GPU budget is policy (v2).
 * `prefill` is a hub proposal from a confirmed `zakuro://share/budget` link:
 * it fills the form, and nothing is saved until the owner saves. */
export function BudgetPrice({ hook, ov, prefill, onPrefillDone }: { hook: AgentHook; ov: Overview | null; prefill?: Record<string, unknown> | null; onPrefillDone?: () => void }) {
  const [price, setPrice] = useState<string>("");
  const [defaultPrice, setDefaultPrice] = useState<string>("");
  const proposed = typeof prefill?.price_per_hour === "number" ? (prefill.price_per_hour as number) : null;
  useEffect(() => {
    if (!ov) return;
    setDefaultPrice(ov.prices.accountDefault?.toString() ?? "");
    // Reset the inputs only when the agent's values change, not on every poll.
  }, [ov?.prices.accountDefault]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    // A hub proposal owns the field until it is saved or dismissed: the
    // agent's price arriving (or moving) must not put back the old value.
    if (!ov || proposed !== null) return;
    setPrice(ov.prices.thisNode.perHour?.toString() ?? "");
  }, [ov?.prices.thisNode.perHour, proposed]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    // Keyed on the prefill object, not the number: a second link with the
    // same proposal fills the field again.
    if (proposed !== null) setPrice(String(proposed));
  }, [prefill]); // eslint-disable-line react-hooks/exhaustive-deps

  const w = ov?.thisNode.workers;
  const parse = (s: string) => (s.trim() === "" ? null : Number(s));
  const valid = (s: string) => {
    const n = parse(s);
    return n === null || (ov !== null && Number.isFinite(n) && n >= ov.prices.min && n <= ov.prices.max);
  };

  return (
    <>
      <ScreenHead title="Budget & price" sub={ov ? `${ov.thisNode.name} · what this node lends` : undefined} />
      {prefill && (
        <Notice title="Proposed from the hub" onClose={onPrefillDone}>
          {proposed !== null ? `This node's price is filled in at ¥${proposed}/h. Review it, then Save to apply.` : "The link proposed no change this zc can apply yet."}
          {Object.keys(prefill).some((k) => k !== "price_per_hour") && " CPU, memory and GPU limits arrive with zc#513."}
        </Notice>
      )}
      <div className="grid grid-cols-2 gap-3">
        <Panel title="Sharing" aside="this node">
          <Row cols="1fr auto">
            <RowName name="Share this node" sub="Drains running work before it stops" />
            <Toggle label="Share this node" on={!!ov?.thisNode.sharing} disabled={!ov || hook.busy} onChange={(v) => hook.setSharing(v)} />
          </Row>
          <Row cols="1fr auto">
            <RowName name="Workers" sub={w ? `up to ${w.max} on this node · ${w.running} running` : undefined} />
            <div className="flex items-center gap-2">
              <Button size="sm" disabled={!w || hook.busy || w.desired <= 0} onClick={() => w && hook.setWorkers(w.desired - 1)}>
                −
              </Button>
              <span className="tnum w-6 text-center font-mono">{w?.desired ?? "—"}</span>
              <Button size="sm" disabled={!w || hook.busy || w.desired >= w.max} onClick={() => w && hook.setWorkers(w.desired + 1)}>
                +
              </Button>
            </div>
          </Row>
        </Panel>
        <Panel title="Price" aside={ov ? `per hour · ${ov.prices.min}–${ov.prices.max}` : "per hour"}>
          <PriceRow
            label="This node"
            hint={ov ? `now ${perHour(ov.prices.thisNode.effective)} (${ov.prices.thisNode.state}) · empty = account default` : undefined}
            value={price}
            onChange={setPrice}
            valid={valid(price)}
            disabled={!ov || hook.busy}
            onSave={() => {
              hook.setPrice("device", parse(price));
              onPrefillDone?.();
            }}
          />
          <PriceRow
            label="Account default"
            hint="Every node without its own price · empty = none"
            value={defaultPrice}
            onChange={setDefaultPrice}
            valid={valid(defaultPrice)}
            disabled={!ov || hook.busy}
            onSave={() => hook.setPrice("default", parse(defaultPrice))}
          />
        </Panel>
      </div>
      <HostingBudget />
    </>
  );
}

function PriceRow(props: { label: string; hint?: string; value: string; onChange: (s: string) => void; valid: boolean; disabled: boolean; onSave: () => void }) {
  return (
    <Row cols="1fr auto auto">
      <RowName name={props.label} sub={props.hint} />
      <label className="flex items-center gap-1.5">
        <span className="text-fg-dim">¥</span>
        <input
          aria-label={`${props.label} price per hour`}
          inputMode="decimal"
          value={props.value}
          onChange={(e) => props.onChange(e.target.value)}
          className={"tnum w-20 rounded-sm border bg-bg px-2 py-1 font-mono text-[12.5px] outline-none " + (props.valid ? "border-hairline" : "border-wine")}
        />
        <span className="text-[12px] text-fg-dim">/ h</span>
      </label>
      <Button size="sm" variant="primary" disabled={props.disabled || !props.valid} onClick={props.onSave}>
        Save
      </Button>
    </Row>
  );
}

/** The resources Zakuro may use on this machine (`/v2/hosting`). Saving
 * answers with the deployments that still fit. */
function HostingBudget() {
  const [h, setH] = useState<HostingSettings | null>(null);
  const [saved, setSaved] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  useEffect(() => {
    hosting.settings().then(setH, (e) => setError(isAgentError(e) ? e.message : String(e)));
  }, []);
  if (!h) return error ? <Notice title="Budget unavailable">{error}</Notice> : null;
  const set = (patch: Partial<HostingSettings["budget"]>) => setH({ ...h, budget: { ...h.budget, ...patch } });
  const field = (label: string, key: "cpu" | "memory" | "disk", hint: string) => (
    <Row cols="1fr auto">
      <RowName name={label} sub={hint} />
      <input
        aria-label={label}
        value={h.budget[key]}
        onChange={(e) => set({ [key]: e.target.value })}
        className="tnum w-24 rounded-sm border border-hairline bg-bg px-2 py-1 font-mono text-[12.5px] outline-none"
      />
    </Row>
  );
  const save = async () => {
    try {
      const d = await hosting.saveSettings(h);
      setError(null);
      setSaved(d.budget_full ? "Saved. Some deployments no longer fit and are greyed out on Hosting." : "Saved.");
    } catch (e) {
      setSaved(null);
      setError(isAgentError(e) ? e.message : String(e));
    }
  };
  return (
    <Panel title="Resources Zakuro may use" aside="this machine">
      {field("Memory", "memory", "On Apple silicon this includes GPU memory · 50% or 8g")}
      {field("CPU", "cpu", "Cores or a share · 50% or 4")}
      {field("Disk", "disk", "Images, envs and job files · 50G")}
      <Row cols="1fr auto">
        <RowName name="Share this Mac's GPU (unified memory)" sub="Lets LLM fine-tuning run here" />
        <Toggle label="Share the GPU" on={h.budget.gpu} onChange={(v) => set({ gpu: v })} />
      </Row>
      <Row cols="1fr auto">
        <RowName name="Only when plugged in" sub="A running job wraps up when you unplug" />
        <Toggle label="Only when plugged in" on={h.budget.on_ac_only} onChange={(v) => set({ on_ac_only: v })} />
      </Row>
      <Row cols="1fr auto">
        <RowName name="When" sub="Idle: a running job wraps up when you come back" />
        <Seg value={h.sharing.when === "always" ? "always" : "idle"} options={[{ value: "idle", label: "Idle" }, { value: "always", label: "Always" }]} onChange={(v) => setH({ ...h, sharing: { ...h.sharing, when: v } })} />
      </Row>
      <Row cols="1fr auto">
        <RowName name="Remove unused images after" sub="Days without any job or you using them" />
        <input
          aria-label="Cleanup days"
          inputMode="numeric"
          value={h.cleanup.idle_ttl.replace(/d$/, "")}
          onChange={(e) => setH({ ...h, cleanup: { idle_ttl: `${e.target.value.replace(/\D/g, "")}d` } })}
          className="tnum w-16 rounded-sm border border-hairline bg-bg px-2 py-1 font-mono text-[12.5px] outline-none"
        />
      </Row>
      <div className="flex items-center justify-end gap-3 pt-2">
        {saved && <span className="text-[12px] text-fg-dim">{saved}</span>}
        {error && <span className="text-[12px] text-wine">{error}</span>}
        <Button size="sm" variant="primary" onClick={save}>
          Save
        </Button>
      </div>
    </Panel>
  );
}