~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/socialweb-computer-console

console.socialweb.computer: kcp, kubectl and ssh compiled to wasm in a browser tab with a terminal; a kcp fork

0
0
main
4266 lines · 156.5 KB Raw History
/*
Copyright 2026 The KCP Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// app.js runs a just-bash shell in the browser. kubectl and goat are custom
// just-bash commands that bridge to their own WebAssembly workers; kcp runs
// in a third worker. The Deno server serves files and proxies goat's
// cross-origin HTTP.

import { Terminal } from "https://esm.sh/@xterm/xterm@5.5.0";
import { FitAddon } from "https://esm.sh/@xterm/addon-fit@0.10.0";
import { WebLinksAddon } from "https://esm.sh/@xterm/addon-web-links@0.11.0";
import {
  Bash,
  defineCommand,
  getCommandNames,
} from "https://esm.sh/just-bash@3.6.0/browser";
import { buildDiagram, nodeID } from "./diagram.js";
import { cancelOAuthPopup, OAUTH_CALLBACK_MESSAGE, openOAuthPopup } from "./oauth.js";
import { GRACE_MS, normalizeHandle, signInURL, signInView, signInLinkRequest } from "./identity_ui.js";
import {
  assembleSnapshot,
  backendNotice,
  backupUnreadable,
  createPersister,
  isNotOwner,
  OWNER_KEY,
  UNREADABLE_PREFIXES,
  openBestBackend,
  snapshotRecords,
  unreadableMessage,
} from "./state_store.js";
import { createBanners } from "./page_banner.js";
import { createReadyGate } from "./ready_gate.js";
import { createRequestRunner } from "./request_vm.js";
import { BUSY_MESSAGE, createKcpLock, FORCE_WARNING, TAKEN_OVER_MESSAGE } from "./kcp_lock.js";
import * as vmshell from "./vmshell.js";
import * as webrtcGuest from "./webrtc_guest.js";
import * as sshCmd from "./ssh_cmd.js";
import { discardSnapshot } from "./kcp_hibernate.js";
import { wasmBuildId } from "./wasm_fetch.js";
import { ControlStream, DebugLogSender } from "./debug_link.js";
import { connectFrame, policyEngineStatus, startFrame } from "./policy_sandbox.js";

const config = await (await fetch("/config")).json();
const apiServer = String(config.apiServer);
const intervalMs = Number(config.intervalMs ?? 1500);
const stateKey = "kcp";
const socialwebStateKey = "socialweb";
const legacyStateKey = "kcp-wasm-state";
// kcp storage is saved as one IndexedDB record per object under this prefix;
// the single-string snapshot under stateKey is the pre-delta format.
const kcpRecordPrefix = `${stateKey}\u0000`;
const stateDB = "kcp-wasm";
const stateMaxBytes = 256 * 1024 * 1024;
const shellStateKey = "kcp-shell-state";
const maxLogEntries = 500;
const homeDir = "/home/user";

const statusEl = document.getElementById("status");
const banners = createBanners(document.getElementById("banners"));
const retryEl = document.getElementById("retry");
retryEl.addEventListener("click", () => location.reload());
const serverEl = document.getElementById("server");
const diagramEl = document.getElementById("diagram");
const diagramUpdatedEl = document.getElementById("diagram-updated");
const diagramToggleEl = document.getElementById("diagram-toggle");
let diagramVisible = localStorage.getItem("kcp-diagram-open") === "1";
const logEl = document.getElementById("log");
const logClearEl = document.getElementById("log-clear");
const logVerboseEl = document.getElementById("log-verbose");
const leftPaneEl = document.getElementById("left-pane");
const logPaneEl = document.getElementById("log-pane");
const splitterEl = document.getElementById("splitter");
const logToggleEl = document.getElementById("log-toggle");
const identityModeEl = document.getElementById("identity-mode");
const identityHandleEl = document.getElementById("identity-handle");
const identitySignInEl = document.getElementById("identity-signin");
const identityStatusEl = document.getElementById("identity-status");
const identitySecondaryEl = document.getElementById("identity-secondary");

serverEl.textContent = apiServer;

// --- low-memory mode ---------------------------------------------------------
// iOS gives a whole tab (page and workers) roughly 1-1.5 GB before it kills
// the WebContent process ("A problem repeatedly occurred"). kcp alone grows a
// Go heap of 800+ MiB, so on iOS (or with localStorage kcp.lowmem=1) the page
// loads kubectl only after kcp is up, loads goat/yq on first use, skips the
// snapshot hibernate (a restore briefly holds two copies of the heap) and asks
// Go to keep its heap small. kcp.lowmem=0 turns it off.
const isIOS = /iPhone|iPad|iPod/.test(navigator.userAgent) ||
  (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
const lowMemory = localStorage.getItem("kcp.lowmem") === "1" ||
  (localStorage.getItem("kcp.lowmem") !== "0" && isIOS);

// --- remote debug log ------------------------------------------------------
// The activity log, uncaught errors and the kcp heap size go to the page's
// server (/debug/log), so a crash on a phone can be read on the server side.
// On by default; ?debuglog=0 (sticky) turns it off, and the page stops when
// the host has no such endpoint (404/405: a static host, or a server without
// --debug-log).
const debugLogParam = new URLSearchParams(location.search).get("debuglog");
if (debugLogParam !== null) localStorage.setItem("kcp.debuglog", debugLogParam === "0" ? "0" : "1");
let debugLog = localStorage.getItem("kcp.debuglog") !== "0";
// The kcp worker's Go console goes to the activity log too; ?debuggo=0
// (sticky) turns it off.
const debugGoParam = new URLSearchParams(location.search).get("debuggo");
if (debugGoParam !== null) localStorage.setItem("kcp.debugGo", debugGoParam === "0" ? "0" : "1");
// One id per tab, kept across reloads, so remote debug commands keep
// reaching the same tab.
const debugSession = (() => {
  try {
    const kept = sessionStorage.getItem("kcp.debugSession");
    if (kept) return kept;
    const fresh = Math.random().toString(36).slice(2, 8);
    sessionStorage.setItem("kcp.debugSession", fresh);
    return fresh;
  } catch {
    return Math.random().toString(36).slice(2, 8);
  }
})();
// Requests to the dev server give up after a while: a stalled tunnel holds
// them open without an answer.
const debugTimeout = (ms) => typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(ms) : undefined;
// The control stream client (startDebugControl, below).
let debugControl = null;
// Lines go out ~100 ms after the first one queued, so a driven session
// (debug control) sees terminal output and results promptly. While the dev
// server or its tunnel is unreachable they wait (debug_link.js) and the page
// logs one line with the outage and the dropped count once it is back.
const debugSender = new DebugLogSender({
  encode: (lines) => JSON.stringify({ session: debugSession, ua: navigator.userAgent, lines }),
  post: (body) =>
    fetch("/debug/log", { method: "POST", body, signal: debugTimeout(20_000) }).then((res) => res.status, () => 0),
  onDisabled: () => {
    debugLog = false;
  },
  onReconnect: ({ downMs, dropped }) => {
    debugSend("info", downMs
      ? `debug log reconnected after ${Math.round(downMs / 1000)} s; ${dropped} lines dropped`
      : `debug log buffer full; ${dropped} lines dropped`);
    // The control stream is likely a dead connection after an outage too.
    debugControl?.kick();
  },
});
function debugSend(level, message) {
  if (!debugLog) return;
  const limit = level === "result" ? 60_000 : 4000;
  debugSender.push({ t: new Date().toISOString(), level, message: String(message).slice(0, limit) });
}
function debugFlush() {
  if (debugLog) debugSender.flush();
}
if (debugLog) {
  addEventListener("error", (e) => debugSend("error", `uncaught: ${e.message} ${e.filename}:${e.lineno}`));
  addEventListener("unhandledrejection", (e) => debugSend("error", `unhandled rejection: ${e.reason}`));
  addEventListener("pagehide", () => {
    const body = debugSender.takeAll();
    if (body) fetch("/debug/log", { method: "POST", body, keepalive: body.length < 60000 }).catch(() => {});
  });
  debugSend("info", `debug log on; lowMemory=${lowMemory} isIOS=${isIOS} ` +
    `hardwareConcurrency=${navigator.hardwareConcurrency} screen=${screen.width}x${screen.height}`);
}

// With the debug log on, everything the page and its workers print also goes
// to /debug/log: console output, worker errors, and the terminal (below).
if (debugLog) {
  for (const level of ["log", "info", "warn", "error", "debug"]) {
    const original = console[level].bind(console);
    console[level] = (...args) => {
      original(...args);
      debugSend(`console.${level}`, args.map((a) => {
        if (a instanceof Error) return `${a.message}\n${a.stack ?? ""}`;
        if (typeof a === "string") return a;
        try {
          return JSON.stringify(a);
        } catch {
          return String(a);
        }
      }).join(" "));
    };
  }
  const NativeWorker = globalThis.Worker;
  globalThis.Worker = class extends NativeWorker {
    constructor(url, options) {
      super(url, options);
      const name = String(url).split("/").pop();
      this.addEventListener("error", (e) => debugSend("error", `worker ${name}: ${e.message ?? "error"} ${e.filename ?? ""}:${e.lineno ?? ""}`));
      this.addEventListener("messageerror", () => debugSend("error", `worker ${name}: messageerror`));
    }
  };
}

// --- activity log ----------------------------------------------------------

// pinned rows (the state backend line, which probes read) are never trimmed.
function addLog(level, message, { pinned = false } = {}) {
  const nearBottom =
    logEl.scrollHeight - logEl.scrollTop - logEl.clientHeight < 40;
  const row = document.createElement("div");
  row.className = `log-${level}${pinned ? " log-pinned" : ""}`;
  const time = new Date().toLocaleTimeString(undefined, { hour12: false });
  row.textContent = `${time} ${message}`;
  debugSend(level, message);
  logEl.appendChild(row);
  while (logEl.childElementCount > maxLogEntries) {
    const oldest = logEl.querySelector(":scope > div:not(.log-pinned)");
    if (!oldest) break;
    oldest.remove();
  }
  if (nearBottom) logEl.scrollTop = logEl.scrollHeight;
}

logClearEl.addEventListener("click", () => logEl.replaceChildren());

document.getElementById("log-save").addEventListener("click", () => {
  const text = [...logEl.children].map((row) => row.textContent).join("\n");
  const blob = new Blob([`${text}\n`], { type: "text/plain" });
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = `kcp-browser-log-${Date.now()}.txt`;
  anchor.click();
  URL.revokeObjectURL(url);
});

const verboseKey = "kcp-log-verbose";
logVerboseEl.checked = localStorage.getItem(verboseKey) === "1";
logEl.classList.toggle("verbose", logVerboseEl.checked);
logVerboseEl.addEventListener("change", () => {
  localStorage.setItem(verboseKey, logVerboseEl.checked ? "1" : "0");
  logEl.classList.toggle("verbose", logVerboseEl.checked);
  logEl.scrollTop = logEl.scrollHeight;
});

// --- terminal --------------------------------------------------------------

const term = new Terminal({
  cursorBlink: true,
  convertEol: true,
  fontSize: 13,
  fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
  scrollback: 5000,
  theme: {
    background: "#0b0e14",
    foreground: "#d5dbe5",
    cursor: "#7aa2f7",
    selectionBackground: "#2b3a55",
  },
});
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.loadAddon(new WebLinksAddon());
term.open(document.getElementById("terminal"));
if (debugLog) {
  // Tee the terminal to the debug log, a line at a time, without ANSI codes.
  let termLine = "";
  const tee = (data) => {
    const text = typeof data === "string" ? data : new TextDecoder().decode(data);
    termLine += text.replace(/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07]*\x07/g, "").replace(/\r(?!\n)/g, "");
    const lines = termLine.split("\n");
    termLine = lines.pop() ?? "";
    for (const line of lines) debugSend("term", line);
    if (termLine.length > 1000) {
      debugSend("term", termLine);
      termLine = "";
    }
  };
  const write = term.write.bind(term);
  term.write = (data, cb) => {
    tee(data);
    return write(data, cb);
  };
  const writeln = term.writeln.bind(term);
  term.writeln = (data, cb) => {
    tee(`${typeof data === "string" ? data : new TextDecoder().decode(data)}\n`);
    return writeln.call(term, data, cb);
  };
}
const isNarrow = () => window.innerWidth < 700;

fitAddon.fit();
new ResizeObserver(() => {
  try {
    const size = isNarrow() ? 11 : 13;
    if (term.options.fontSize !== size) term.options.fontSize = size;
    fitAddon.fit();
  } catch { /* layout not ready */ }
}).observe(document.getElementById("terminal-pane"));
term.focus();
document.getElementById("terminal-pane").addEventListener("click", () => term.focus());

// Ctrl+Shift+C/V copy and paste terminal selections without stealing Ctrl-C
// (which cancels) or plain Ctrl-V (browser paste into xterm's textarea).
term.attachCustomKeyEventHandler((event) => {
  if (event.type !== "keydown") return true;
  if (event.ctrlKey && event.shiftKey && event.code === "KeyC") {
    const selection = term.getSelection();
    if (selection) navigator.clipboard?.writeText(selection).catch(() => {});
    return false;
  }
  if (event.ctrlKey && event.shiftKey && event.code === "KeyV") {
    navigator.clipboard?.readText()
      .then((text) => {
        if (text) term.paste(text);
      })
      .catch(() => {});
    return false;
  }
  return true;
});

// xterm.js has no native touch scrolling (xtermjs/xterm.js#5377). Translate
// single-finger vertical drags into scrollLines(), with sub-row remainder and
// momentum. touch-action:none on the host keeps iOS page rubber-banding out.
const touchHost = document.getElementById("terminal");
let touchLastY = null;
let touchAccum = 0;
let touchVelocity = 0;
let touchLastTime = 0;
let momentumFrame = null;

function stopTouchMomentum() {
  if (momentumFrame !== null) {
    cancelAnimationFrame(momentumFrame);
    momentumFrame = null;
  }
}

function scrollPixels(dy) {
  const rowHeight = Math.max(
    1,
    (term.element?.clientHeight ?? 300) / Math.max(1, term.rows),
  );
  touchAccum += dy;
  const lines = Math.trunc(touchAccum / rowHeight);
  if (lines !== 0) {
    touchAccum -= lines * rowHeight;
    // Finger drag down (dy > 0) reveals older output: scroll up.
    term.scrollLines(-lines);
  }
}

touchHost.addEventListener("touchstart", (event) => {
  if (event.touches.length !== 1) {
    touchLastY = null;
    return;
  }
  stopTouchMomentum();
  touchLastY = event.touches[0].clientY;
  touchAccum = 0;
  touchVelocity = 0;
  touchLastTime = performance.now();
}, { passive: true, capture: true });

touchHost.addEventListener("touchmove", (event) => {
  if (touchLastY === null || event.touches.length !== 1) return;
  const y = event.touches[0].clientY;
  const dy = y - touchLastY;
  touchLastY = y;
  if (dy === 0) return;
  event.preventDefault();
  event.stopPropagation();
  const now = performance.now();
  const dt = Math.max(1, now - touchLastTime);
  touchVelocity = 0.8 * (dy / dt) + 0.2 * touchVelocity;
  touchLastTime = now;
  scrollPixels(dy);
}, { passive: false, capture: true });

function finishTouchScroll() {
  touchLastY = null;
  const velocity = touchVelocity;
  touchVelocity = 0;
  if (Math.abs(velocity) < 0.05) return;
  let v = velocity;
  const step = () => {
    v *= 0.94;
    if (Math.abs(v) < 0.02) {
      momentumFrame = null;
      return;
    }
    scrollPixels(v * 16);
    momentumFrame = requestAnimationFrame(step);
  };
  momentumFrame = requestAnimationFrame(step);
}

touchHost.addEventListener("touchend", finishTouchScroll, {
  passive: true,
  capture: true,
});
touchHost.addEventListener("touchcancel", () => {
  touchLastY = null;
  touchVelocity = 0;
}, { passive: true, capture: true });

const dim = (text) => `\x1b[90m${text}\x1b[0m`;
const red = (text) => `\x1b[31m${text}\x1b[0m`;
const cyan = (text) => `\x1b[36m${text}\x1b[0m`;

// --- splitter --------------------------------------------------------------

const splitKey = "kcp-log-height";
const logExpandedKey = "kcp-log-expanded";
const savedSplit = localStorage.getItem(splitKey);
if (savedSplit) logPaneEl.style.height = savedSplit;

let logExpanded = localStorage.getItem(logExpandedKey) === "1";

function setLogExpanded(expanded) {
  logExpanded = expanded;
  logPaneEl.classList.toggle("collapsed", !expanded);
  leftPaneEl.classList.toggle("log-collapsed", !expanded);
  logPaneEl.style.height = expanded ? (savedSplit ?? "190px") : "";
  logToggleEl.textContent = expanded ? "hide" : "show";
  localStorage.setItem(logExpandedKey, expanded ? "1" : "0");
  if (expanded) logEl.scrollTop = logEl.scrollHeight;
}

logPaneEl.classList.toggle("collapsed", !logExpanded);
leftPaneEl.classList.toggle("log-collapsed", !logExpanded);
logPaneEl.style.height = logExpanded ? logPaneEl.style.height : "";
logToggleEl.textContent = logExpanded ? "hide" : "show";
logToggleEl.addEventListener("click", () => setLogExpanded(!logExpanded));

let draggingSplitter = false;
splitterEl.addEventListener("pointerdown", (event) => {
  draggingSplitter = true;
  if (!logExpanded) setLogExpanded(true);
  splitterEl.setPointerCapture(event.pointerId);
});
splitterEl.addEventListener("pointermove", (event) => {
  if (!draggingSplitter) return;
  const rect = leftPaneEl.getBoundingClientRect();
  const height = Math.max(60, Math.min(rect.height - 160, rect.bottom - event.clientY));
  logPaneEl.style.height = `${Math.round(height)}px`;
});
for (const type of ["pointerup", "pointercancel"]) {
  splitterEl.addEventListener(type, () => {
    draggingSplitter = false;
    localStorage.setItem(splitKey, logPaneEl.style.height || "190px");
  });
}

// --- shared worker helpers -------------------------------------------------

let ready = false;
let busy = false;

function setStatus(text, className) {
  statusEl.textContent = text;
  statusEl.className = className;
}

// term.write parses asynchronously; scroll after the rows exist so the new
// prompt is the last thing in view.
function scrollToBottomSettled() {
  term.scrollToBottom();
  requestAnimationFrame(() => term.scrollToBottom());
  setTimeout(() => term.scrollToBottom(), 120);
}

function waitReady(worker) {
  return new Promise((resolve, reject) => {
    const cleanup = () => {
      worker.removeEventListener("message", onMessage);
      worker.removeEventListener("error", onError);
    };
    const onMessage = (event) => {
      if (event.data?.type === "ready") {
        cleanup();
        resolve(event.data);
      }
    };
    const onError = (event) => {
      cleanup();
      reject(new Error(event.message ?? "worker error"));
    };
    worker.addEventListener("message", onMessage);
    worker.addEventListener("error", onError);
  });
}

class CancelledError extends Error {
  constructor() {
    super("cancelled");
    this.name = "CancelledError";
  }
}

function serializeQueue() {
  let queue = Promise.resolve();
  return (task) => {
    const result = queue.then(task);
    queue = result.catch(() => {});
    return result;
  };
}

// --- kcp worker ------------------------------------------------------------

let kcpWorker = null;
// Opens with the worker once kcp is ready (spawnKcp). With a snapshot restore
// the status feed says MarketIdentity Ready before that, so kcp calls wait
// here rather than fail and switch features off (rc130 boot race).
const kcpGate = createReadyGate();
async function kcpWorkerReady(timeoutMs) {
  if (kcpWorker) return kcpWorker;
  if (kcpGate.state === "open") throw new Error("kcp worker is not running");
  return await kcpGate.wait(timeoutMs);
}
const pendingBridges = new Map();
const pendingPageRequests = new Map();
let nextPageRequestID = -1;

// Send a request straight to the kcp/socialweb bridge. kubectl has its own
// worker; the identity callback needs this page-origin path.
async function kcpPageRequest(request, timeoutMs = 60_000) {
  const worker = await kcpWorkerReady();
  const id = nextPageRequestID--;
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      if (pendingPageRequests.delete(id)) {
        reject(new Error("kcp request timed out"));
      }
    }, timeoutMs);
    pendingPageRequests.set(id, { resolve, reject, timer });
    worker.postMessage({ type: "request", id, request });
  });
}

// A REST call to kcp through the same bridge kubectl's requests use, without
// kubectl itself (a 120 MiB module). The identity and Compute panels use it,
// so a phone in low-memory mode loads kubectl only when someone types it.
async function kcpREST(method, path, body, contentType = "application/json") {
  const headers = { Host: new URL(apiServer).host, Accept: "application/json" };
  if (body !== undefined) headers["Content-Type"] = contentType;
  const response = await kcpPageRequest({
    method,
    path,
    headers,
    body: body === undefined ? "" : typeof body === "string" ? body : JSON.stringify(body),
  });
  const text = response?.bodyBase64 ? atob(response.bodyBase64) : String(response?.body ?? "");
  const status = response?.status ?? 500;
  if (status >= 400) {
    let message = text;
    try {
      message = JSON.parse(text).message ?? text;
    } catch {
      // not a Status object
    }
    const err = new Error(`${method} ${path}: ${status} ${message}`.trim());
    err.status = status;
    throw err;
  }
  return text ? JSON.parse(text) : null;
}

const SOCIALWEB_API = "/apis/socialweb.computer/v1alpha1";

// Market calls to a bidder's webrtc endpoint (market_webrtc.js): kcp.wasm's
// requester sends each call here; the signalling offer record is written by
// Go (the worker) in the user's repo.
let marketCalls = null;
const marketWrites = new Map();
let marketWriteNext = 0;
function marketFetch(worker, id, request) {
  const write = (op, fields) => new Promise((resolve, reject) => {
    const writeId = ++marketWriteNext;
    marketWrites.set(writeId, { resolve, reject });
    worker.postMessage({ type: "market-record", id: writeId, op, ...fields });
  });
  Promise.resolve().then(async () => {
    marketCalls ??= (await import("./market_webrtc.js")).marketTransport();
    const call = JSON.parse(request);
    addLog("debug", `market ${call.method} ${new URL(call.url).pathname} over WebRTC`);
    return marketCalls.fetch(call, {
      putRecord: ({ collection, rkey, record }) => write("put", { collection, rkey, record: JSON.stringify(record) }),
      deleteRecord: ({ collection, rkey }) => write("delete", { collection, rkey }),
    });
  }).then(
    (response) => worker.postMessage({ type: "market-fetch-result", id, response: JSON.stringify(response) }),
    (err) => {
      addLog("warn", `market call over WebRTC failed: ${err?.message ?? err}`);
      worker.postMessage({ type: "market-fetch-result", id, error: String(err?.message ?? err) });
    },
  );
}

function attachKcp(worker) {
  worker.addEventListener("error", (event) => {
    const message = event.message ?? "worker error";
    addLog("error", `kcp worker crashed: ${message}`);
    for (const id of pendingBridges.keys()) {
      kubectlWorker?.postMessage({
        type: "fetchResult",
        id,
        request: { error: `kcp worker crashed: ${message}` },
      });
    }
    pendingBridges.clear();
  });
  worker.addEventListener("message", (event) => {
    const data = event.data ?? {};
    if (data.type === "state") {
      applyState(data.state);
      return;
    }
    if (data.type === "socialweb-ingress-status") {
      renderIngress(data.entries ?? []);
      return;
    }
    if (data.type === "oauth-refresh") {
      oauthRefreshWorker().then((w) => {
        const channel = new MessageChannel();
        channel.port1.onmessage = (e) => {
          worker.postMessage({ type: "oauth-refresh-result", id: data.id, response: e.data.response });
          channel.port1.close();
        };
        w.postMessage({ id: data.id, request: data.request }, [channel.port2]);
      });
      return;
    }
    if (data.type === "market-fetch") {
      marketFetch(worker, data.id, data.request);
      return;
    }
    if (data.type === "market-record-result") {
      const write = marketWrites.get(data.id);
      marketWrites.delete(data.id);
      if (data.error) write?.reject(new Error(data.error));
      else write?.resolve();
      return;
    }
    if (data.type === "heap-profile") {
      for (const [kind, b64] of [["heap", data.heapBase64], ["goroutine", data.goroutineBase64]]) {
        if (!b64) continue;
        const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
        fetch(`/debug/heap?session=${encodeURIComponent(debugSession)}&kind=${kind}`, { method: "POST", body: bytes })
          .then(() => addLog("debug", `${kind} profile uploaded (${bytes.length} bytes)`), () => {});
      }
      return;
    }
    if (data.type === "response") {
      const page = pendingPageRequests.get(data.id);
      if (page) {
        pendingPageRequests.delete(data.id);
        clearTimeout(page.timer);
        if (data.error) page.reject(new Error(String(data.error)));
        else page.resolve(data.response);
        return;
      }
      pendingBridges.delete(data.id);
      noteKcpAnswer();
      kubectlWorker?.postMessage({
        type: "fetchResult",
        id: data.id,
        request: { response: data.response, error: data.error },
      });
    } else if (data.type === "persist") {
      if (!kcpStateOwned()) return;
      persistKcp(data.snapshot, data.seq);
    } else if (data.type === "socialweb-persist") {
      if (!kcpStateOwned()) return;
      void persister.schedule(socialwebStateKey, data.snapshot, data.seq);
    } else if (data.type === "restore-unreadable") {
      void restoreUnreadable(data.channel, data.message);
    } else if (data.type === "persist-flushed") {
      // Only the flush this answer belongs to (a late answer to a timed-out
      // flush must not resolve a take over's flush before its writes land).
      persistFlushWaiters.get(data.id)?.(Boolean(data.flushed));
    } else if (data.type === "socialweb-started") {
      recordKcpBuild();
    } else if (data.type === "log") {
      addLog(data.level ?? "info", `kcp: ${data.message}`);
      const message = String(data.message);
      if (message.includes("MiB downloaded")) {
        setStatus(message.replace("kcp.wasm ", "kcp "), "running");
      } else if (message.includes("waiting for real kcp readiness")) {
        const match = message.match(/\((\d+)s\)/);
        setStatus(`booting kcp ${match ? match[1] : ""}s…`, "running");
      }
    }
  });
}

let stateBackendPromise = null;
function stateBackend() {
  if (!stateBackendPromise) {
    stateBackendPromise = openBestBackend({ dbName: stateDB, maxBytes: stateMaxBytes })
      .then(({ backend, kind, reason }) => {
        // Always in #log at a level that is never filtered (probes read it).
        // Memory: a visible banner and console.warn; minting is not blocked
        // (open with the owner).
        const notice = backendNotice({ kind, reason });
        addLog(notice.level, notice.line, { pinned: true });
        if (notice.banner) {
          banners.show("memory", { text: notice.banner, level: "warn" });
          console.warn(notice.warn);
        }
        return backend;
      });
  }
  return stateBackendPromise;
}

async function loadInitialState(key = stateKey) {
  const backend = await stateBackend();
  const saved = await backend.load(key);
  if (saved || key !== stateKey) return saved ?? "";
  // One-time migration from the 5 MB localStorage era.
  const legacy = localStorage.getItem(legacyStateKey);
  if (legacy) {
    await backend.save(stateKey, legacy).catch(() => {});
    localStorage.removeItem(legacyStateKey);
    return legacy;
  }
  return "";
}

// Rebuilds the full snapshot kcp restores from: per-object records when they
// exist, otherwise a saved single-string snapshot.
async function loadKcpState() {
  const backend = await stateBackend();
  const records = await backend.loadPrefix(kcpRecordPrefix);
  if (records.length > 0) return JSON.stringify(assembleSnapshot(records));
  return loadInitialState(stateKey);
}

// kcp posts a full snapshot after boot and deltas afterwards, so every
// message is applied, in order; none may be coalesced away.
let kcpPersistQueue = Promise.resolve();
function persistKcp(snapshot, seq) {
  kcpPersistQueue = kcpPersistQueue.then(async () => {
    if (!kcpStateOwned()) return;
    const message = JSON.parse(snapshot);
    const backend = await stateBackend();
    if (!message.stores) {
      // Not a storage envelope (older shard): keep it as one string.
      await backend.apply({ clearPrefix: kcpRecordPrefix });
      await backend.save(stateKey, snapshot);
      return;
    }
    const ops = snapshotRecords(kcpRecordPrefix, message);
    if (!message.delta) ops.deletes.push(stateKey);
    // Same transaction as the data: the hibernation snapshot compares it.
    if (seq) ops.puts.push([kcpSeqKey, seq]);
    await backend.apply(ops);
  }).catch((err) => {
    stateWriteFailed("kcp state save", err);
  });
}

// Whole-snapshot keys (state_store.js createPersister): one save at a time
// per key, the newest wins. The socialweb vault snapshot saves at once, not
// debounced: in rc127 it holds the requester's atirc revoke marker and
// atircMinted, and a reload right after such a write must not lose it.
// Pending saves start at once when the tab is hidden or unloads (below).
const persister = createPersister({
  backend: stateBackend,
  immediate: [socialwebStateKey],
  onError: (key, err) => stateWriteFailed(`state save (${key})`, err),
});
addEventListener("pagehide", () => void persister.flushAll());
addEventListener("pagehide", () => void flushKcpSoon("pagehide"));

// --- saved state this build cannot read (rc129) -------------------------------
// Go reports a kcp or socialweb value it could not read and never persists
// that channel then, so nothing is saved over it. The raw value is copied to
// <channel>-unreadable-<time> first, then the error is shown.
let restoredRaw = { kcp: "", socialweb: "" };
// Set when Go runs kcp without saving (its saved state was unreadable).
let kcpPersistOff = false;
async function restoreUnreadable(channel, message) {
  if (channel === "kcp") kcpPersistOff = true;
  const raw = restoredRaw[channel] ?? "";
  let backup = null;
  try {
    backup = await backupUnreadable(await stateBackend(), channel, raw);
  } catch (err) {
    stateWriteFailed(`backing up the unreadable ${channel} state`, err);
  }
  const text = `${unreadableMessage(channel)}${backup ? ` (a copy is saved as ${backup})` : ""}. ` +
    "This session runs without saving it; reload with a build that reads it, or Reset. " +
    "The copies hold secrets (sign-in tokens and keys of the vault); Reset keeps them.";
  addLog("error", `${unreadableMessage(channel)}: ${message}${backup ? `; backed up as ${backup}` : backup === "" ? "; already backed up" : ""}`);
  console.error(`${unreadableMessage(channel)}: ${message}`);
  banners.show(`unreadable-${channel}`, {
    text,
    level: "error",
    actions: [{ label: "Reset", onClick: () => void resetState() }],
  });
}

// --- one kcp per origin (kcp_lock.js) -------------------------------------------
// The tab boots kcp only while it holds the Web Lock "kcp-state"; another tab
// of this browser asks it to hand over (Take over), or steals it from a tab
// that does not answer. After that this tab must never write the shared
// state again: kcpStateOwned() gates every kcp and socialweb persist.
let kcpWorkerBooting = null;
const persistFlushWaiters = new Map();
let nextPersistFlushId = 1;
const kcpLock = createKcpLock({ log: (level, message) => addLog(level, message), onYield: yieldKcp });

// "yielding": a take over is flushing; those last writes must land.
function kcpStateOwned() {
  return !stateFenced && ["held", "yielding", "unsupported", "idle"].includes(kcpLock.state);
}

// Owner fence (state_store.js claimOwner): right after this tab takes the
// lock, and before its first persist, it writes its token; a write from a
// tab whose token was replaced aborts whole (NotOwner). The first such
// refusal stops every persist of this tab.
const stateOwnerToken = vmshell.randomToken();
let stateFenced = false;
// The owner before this tab's claim (the tab that wrote the saved state), for
// the hibernation snapshot check; undefined while the state is not fenced.
let stateOwnerPrevious;
async function claimStateOwner() {
  const backend = await stateBackend();
  if (backend.kind === "indexeddb") stateOwnerPrevious = (await backend.load(OWNER_KEY).catch(() => null)) ?? null;
  await backend.claimOwner(stateOwnerToken);
  addLog("debug", `saved state owner: this tab (${stateOwnerToken.slice(0, 8)})`);
}

function stateWriteFailed(what, err) {
  if (!isNotOwner(err)) {
    addLog("warn", `${what} failed: ${err instanceof Error ? err.message : err}`);
    return;
  }
  if (stateFenced) return;
  stateFenced = true;
  persister.stop();
  addLog("error", `${what} refused: another tab owns the saved state now; this tab stops saving`);
}

// Clears the kcp and socialweb state (one transaction) and the shell, then
// reloads: the terminal reset and the unreadable-state banner's Reset. The
// <channel>-unreadable-* backups stay unless all is set (reset --all).
async function resetState({ all = false } = {}) {
  // A worker may hold the snapshot's OPFS file open; stop it first.
  kcpWorker?.terminate();
  kcpWorker = null;
  await discardSnapshot().catch(() => {});
  try {
    const backend = await stateBackend();
    await backend.apply({ clearPrefix: kcpRecordPrefix, deletes: [stateKey, socialwebStateKey, socialwebSeqKey] });
    if (all) for (const prefix of UNREADABLE_PREFIXES) await backend.apply({ clearPrefix: prefix });
  } catch (err) {
    // A missing or read-only store is already a reset; another owner is not.
    if (isNotOwner(err)) stateWriteFailed("reset", err);
  }
  localStorage.removeItem(legacyStateKey);
  localStorage.removeItem(shellStateKey);
  addLog("warn", `shell, kcp and socialweb state cleared${all ? " with the unreadable-state backups" : ""}; reloading`);
  setTimeout(() => location.reload(), 300);
}

// Has the kcp worker persist what its coalescer still holds; resolves once
// that message is queued (it arrives before the answer), or false.
function flushKcpWorker(worker, timeoutMs = 8000) {
  return new Promise((resolve) => {
    const id = nextPersistFlushId++;
    const timer = setTimeout(() => {
      persistFlushWaiters.delete(id);
      resolve(false);
    }, timeoutMs);
    persistFlushWaiters.set(id, (ok) => {
      clearTimeout(timer);
      persistFlushWaiters.delete(id);
      resolve(ok);
    });
    worker.postMessage({ type: "persist-flush", id });
  });
}

// The holder's half of a take over: save everything (only when asked; a tab
// whose lock was stolen must not write over the new owner), stop kcp, show it.
async function yieldKcp(why) {
  ready = false;
  const worker = kcpWorker ?? kcpWorkerBooting;
  if (why === "takeover") {
    // A worker still booting answers no messages yet; its writes are boot
    // state the next kcp recreates.
    if (kcpWorker) {
      const flushed = await flushKcpWorker(worker);
      addLog(flushed ? "info" : "warn", flushed ? "kcp writes flushed for the other tab" : "kcp flush unanswered; saving what arrived");
    }
    // Forced meanwhile (kcpLock state "stolen"): the new owner's state must
    // not be written over.
    if (kcpStateOwned()) {
      await kcpPersistQueue;
      await persister.flushAll();
    }
  }
  persister.stop();
  worker?.terminate();
  kcpWorker = null;
  kcpWorkerBooting = null;
  kcpGate.fail(new Error(TAKEN_OVER_MESSAGE));
  // An idle tab gets no feed update after this: disable Request VM now.
  refreshComputeRequest();
  setStatus("taken over by another tab", "disconnected");
  banners.show("lock", {
    text: TAKEN_OVER_MESSAGE,
    level: "warn",
    actions: [{
      label: "Take over",
      onClick: () => {
        try {
          sessionStorage.setItem("kcp.takeover", "1");
        } catch {
          // no sessionStorage: the reload offers Take over instead
        }
        location.reload();
      },
    }],
  });
}

// Resolves once this tab may boot kcp. Another tab running it shows the
// choice (Retry, Take over; Force take over after no answer) and waits.
async function acquireKcpLock() {
  let takeover = false;
  try {
    takeover = sessionStorage.getItem("kcp.takeover") === "1";
    sessionStorage.removeItem("kcp.takeover");
  } catch {
    // no sessionStorage
  }
  let outcome = takeover ? await kcpLock.takeover() : await kcpLock.acquire();
  if (outcome === "unsupported") {
    addLog("warn", "navigator.locks is not available; booting kcp without the one-kcp-per-origin check");
    return;
  }
  while (outcome !== "held") outcome = await kcpLockChoice(outcome);
  banners.hide("lock");
  addLog("ok", "kcp lock held: this tab runs kcp");
}

function kcpLockChoice(outcome) {
  setStatus("kcp is running in another tab", "disconnected");
  addLog("warn", `kcp lock: ${outcome}`);
  return new Promise((resolve) => {
    const run = (label, step) => ({
      label,
      onClick: () => {
        banners.show("lock", { text: `${label}…`, level: "info" });
        step().then(resolve, (err) => {
          addLog("error", `kcp lock: ${err instanceof Error ? err.message : err}`);
          resolve("busy");
        });
      },
    });
    const retry = run("Retry", () => kcpLock.acquire());
    const takeOver = run("Take over", () => kcpLock.takeover());
    const force = run("Force take over", () => kcpLock.force());
    const choices = {
      busy: { text: BUSY_MESSAGE, actions: [retry, takeOver] },
      "no-answer": { text: FORCE_WARNING, actions: [force, takeOver, retry] },
      timeout: {
        text: "The other tab answered but is still saving. Wait again, or force take over (unsaved changes there may be lost).",
        actions: [takeOver, force],
      },
    };
    const choice = choices[outcome] ?? choices.busy;
    banners.show("lock", { text: choice.text, level: "warn", actions: choice.actions });
  });
}

// socialweb skips its provider manifests when the restored kcp state already
// has Ready APIBindings, so state saved by an older kcp.wasm would keep that
// build's schemas. Re-apply once whenever kcp.wasm changed since the state was
// saved (its ETag is the build's identity).
// The kcp.wasm ETag the saved state was last fully booted with. It is only
// recorded once kcp (and the socialweb manifest apply) is ready, so a load
// interrupted mid-apply re-applies on the next one.
let kcpBuildEtag = null;
// One refresh worker per tab, outliving kcp worker restarts; it answers on
// the MessagePort each request brings.
let refreshWorker = null;
function oauthRefreshWorker() {
  refreshWorker ??= Promise.resolve(new Worker("/oauth_refresh_worker.js", { type: "module" }));
  return refreshWorker;
}

// One fenced policy sandbox frame per tab (policy_sandbox.js, plan 0037),
// outliving kcp worker restarts; each kcp worker gets its own port. Without
// it the PolicyEngine stays not Ready (no bridge) and policy denies.
let policyFrame = null;
function policySandboxFrame() {
  policyFrame ??= startFrame().catch((err) => {
    addLog("warn", `policy sandbox frame: ${err?.message ?? err}`);
    policyFrame = null;
    return null;
  });
  return policyFrame;
}

let devServerProbe = null;
function devServer() {
  devServerProbe ??= fetch("/debug/control?session=probe", { method: "HEAD" }).then((r) => r.status === 204, () => false);
  return devServerProbe;
}

// recordKcpBuild runs when socialweb reports it started, which is only after
// its provider manifests were applied: a load that dies or fails before that
// keeps the old id, so the next load forces the apply again.
function recordKcpBuild() {
  if (kcpBuildEtag === null) return;
  try {
    localStorage.setItem("kcp.stateBuild", kcpBuildEtag);
  } catch {
    // no localStorage: the next load re-applies, which is only slower
  }
}

async function kcpBuildChanged() {
  try {
    kcpBuildEtag = await wasmBuildId("/kcp.wasm");
    // No record means state from before this check, and no build id means the
    // host told us nothing (pages before this fix stored ""): re-apply to be safe.
    return kcpBuildEtag === "" || localStorage.getItem("kcp.stateBuild") !== kcpBuildEtag;
  } catch {
    return false;
  }
}

async function spawnKcp(useSnapshot = true) {
  const spawnStarted = performance.now();
  logPreviousSnapshotOutcome();
  const [initialState, socialwebSnapshot, hibernate, buildChanged, sandboxFrame] = await Promise.all([
    loadKcpState(),
    loadInitialState(socialwebStateKey),
    hibernateInit(useSnapshot),
    kcpBuildChanged(),
    policySandboxFrame(),
  ]);
  const policySandboxPort = sandboxFrame ? connectFrame(sandboxFrame) : undefined;
  if (buildChanged) {
    addLog("info", `kcp.wasm build ${JSON.stringify(kcpBuildEtag)} is not the saved state's ${JSON.stringify(localStorage.getItem("kcp.stateBuild"))}; re-applying the socialweb manifests`);
  }
  // The values handed to Go, for a backup if it cannot read them.
  restoredRaw = { kcp: initialState, socialweb: socialwebSnapshot };
  const worker = new Worker("/kcp_worker.js", { type: "module" });
  kcpWorkerBooting = worker;
  attachKcp(worker);
  const readyPromise = waitReady(worker);
  worker.postMessage({
    type: "init",
    wasmUrl: "/kcp.wasm",
    execUrl: "/wasm_exec.js",
    initialState,
    hibernate,
    debugGo: localStorage.getItem("kcp.debugGo") !== "0",
    noopLog: localStorage.getItem("kcp.noopLog") === "1",
    lowMemory,
    gogcReady: Number(localStorage.getItem("kcp.gogcReady")) || undefined,
    // Profiles only when served by the dev server (it answers HEAD
    // /debug/control); a static deploy never turns them on.
    oauthRefreshWorker: typeof Worker === "function",
    heapProfile: (await devServer()) ? Number(localStorage.getItem("kcp.heapProfile")) || undefined : undefined,
    debugMemory: debugLog,
    socialweb: {
      origin: location.origin,
      identityMode: localStorage.getItem("socialweb.identity") === "localRepo"
        ? "oauthBrowser"
        : (localStorage.getItem("socialweb.identity") ?? "oauthBrowser"),
      handle: localStorage.getItem("socialweb.handle") ?? "",
      did: localStorage.getItem("socialweb.did") ?? "",
      pdsUrl: localStorage.getItem("socialweb.pdsUrl") ?? "",
      oauthClientId: `${location.origin}/oauth-client-metadata.json`,
      oauthRedirectUri: `${location.origin}/oauth/callback/requester`,
      forceApply: buildChanged || localStorage.getItem("socialweb.forceApply") === "1",
      commsMode: localStorage.getItem("socialweb.commsMode") ?? "Firehose",
      statusFeed: localStorage.getItem("socialweb.statusFeed") !== "0",
      restore: socialwebSnapshot,
    },
    policySandboxPort,
  }, policySandboxPort ? [policySandboxPort] : []);
  const ready = await readyPromise;
  kcpWorkerBooting = null;
  if (!kcpStateOwned()) {
    // Taken over while booting: yieldKcp already stopped it and shows why.
    worker.terminate();
    await new Promise(() => {});
  }
  if (ready?.restart) {
    worker.terminate();
    return spawnKcp(false);
  }
  logBootKind(ready, spawnStarted);
  kcpWorker = worker;
  kcpGate.open(worker);
  if (kcpFlushSkipped) {
    kcpFlushSkipped = false;
    void flushKcpSoon("changes seen while kcp started");
  }
  // Whatever the feed's identity Ready started before kcp was ready (feature
  // probes, the infra GC) waited for this; run the handler again in case one
  // gave up meanwhile.
  if (lastFeedState) queueMicrotask(() => applyState(lastFeedState));
  worker.postMessage({ type: "state-subscribe" });
}

// --- kcp hibernation (kcp_hibernate.js) --------------------------------------

const kcpSeqKey = `${kcpRecordPrefix}q`;
const socialwebSeqKey = `${socialwebStateKey}-seq`;
let firstKcpAnswerLogged = false;
let kcpSpawnStarted = 0;

// Snapshots are per user and local; localStorage "kcp.snapshot" = "0" turns
// them off, "kcp.snapshot.gzip" = "0" stores them raw, "kcp.snapshot.store" =
// "indexeddb" forces the fallback store.
async function hibernateInit(useSnapshot) {
  const enabled = localStorage.getItem("kcp.snapshot") !== "0" && !lowMemory;
  if (enabled) {
    navigator.storage?.persist?.().then((granted) => {
      if (!granted) addLog("debug", "persistent storage not granted; the browser may evict the kcp snapshot");
    }).catch(() => {});
  }
  const backend = await stateBackend();
  const [kcp, socialweb] = await Promise.all([
    backend.load(kcpSeqKey).catch(() => null),
    backend.load(socialwebSeqKey).catch(() => null),
  ]);
  return {
    enabled,
    restore: useSnapshot,
    persistSeq: { kcp: Number(kcp ?? 0), socialweb: Number(socialweb ?? 0) },
    // Owner fence for snapshots (kcp_hibernate.js): captures carry and check
    // this tab's token; a restore needs the previous owner's.
    owner: stateOwnerPrevious === undefined ? null : { token: stateOwnerToken, previous: stateOwnerPrevious, db: stateDB },
    gzip: localStorage.getItem("kcp.snapshot.gzip") !== "0",
    store: localStorage.getItem("kcp.snapshot.store") ?? undefined,
  };
}

function logBootKind(ready, spawnStarted) {
  kcpSpawnStarted = spawnStarted;
  const seconds = ((performance.now() - spawnStarted) / 1000).toFixed(1);
  if (ready?.restored) {
    addLog("ok", `kcp restored from snapshot (${seconds}s)`);
    addLog("debug", `kcp snapshot restore: ${JSON.stringify(ready.restored)}`);
  } else {
    addLog("ok", `kcp cold boot (${seconds}s)`);
  }
  if (ready?.restoreOutcome) {
    addLog("info", `kcp snapshot: ${ready.restoreOutcome}`);
    try {
      localStorage.setItem(SNAPSHOT_LAST_KEY, JSON.stringify({ at: new Date().toISOString(), outcome: ready.restoreOutcome }));
    } catch {
      // storage full or blocked: the line above still shows it.
    }
  }
}

// The last load's snapshot outcome, logged again early in the next load: a
// long cold boot scrolls its own early lines out of the log.
const SNAPSHOT_LAST_KEY = "kcp.snapshot.last";

function logPreviousSnapshotOutcome() {
  try {
    const last = JSON.parse(localStorage.getItem(SNAPSHOT_LAST_KEY) ?? "null");
    if (last?.outcome) addLog("info", `kcp snapshot on the previous load (${last.at}): ${last.outcome}`);
  } catch {
    // unreadable or blocked: nothing to report.
  }
}

// Logged once: time from spawn to the first kcp answer kubectl got.
function noteKcpAnswer() {
  if (firstKcpAnswerLogged || !kcpSpawnStarted) return;
  firstKcpAnswerLogged = true;
  addLog("debug", `first kubectl answer ${((performance.now() - kcpSpawnStarted) / 1000).toFixed(1)}s after kcp start`);
}

// Capture when the tab is hidden: the next visit restores from it.
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState !== "hidden") return;
  void persister.flushAll();
  void flushKcpSoon("hidden");
  kcpWorker?.postMessage({ type: "hibernate" });
});

// The kcp coalescer holds writes for up to 10 s (750 ms quiet), so a status
// written just before a reload (a contract turning Held), or a Release
// clicked just before the tab closes, would be lost and the older state
// restored. On hidden, pagehide and after every user action that writes spec
// (Request VM, Release, Start R2, the infra GC) the worker persists them at
// once (kcpPersistFlush); the messages land through the kcp persist queue.
// Only a running kcp of the owning tab that saves at all (not fail-closed).
// A call while one runs flushes again after it (the new write may be later).
let kcpFlushRunning = null;
let kcpFlushAgain = false;
// Returns a promise that settles once the flush landed (or at once when
// there is nothing to flush). An unload does not wait for it: pagehide is
// best effort, which is why every spec-writing action flushes itself.
let kcpFlushSkipped = false;
function flushKcpSoon(why) {
  if (!kcpStateOwned() || kcpPersistOff) return Promise.resolve();
  if (!kcpWorker) {
    // kcp still boots (a phase change from the restored feed): flush once
    // the gate opens (spawnKcp), or this change would never be flushed.
    kcpFlushSkipped = true;
    return Promise.resolve();
  }
  if (kcpFlushRunning) {
    kcpFlushAgain = true;
    return kcpFlushRunning;
  }
  kcpFlushRunning = flushKcpWorker(kcpWorker, 3000)
    .then(async (flushed) => {
      await kcpPersistQueue;
      if (!flushed) addLog("debug", `kcp flush after ${why} unanswered`);
    })
    .finally(() => {
      kcpFlushRunning = null;
      if (kcpFlushAgain) {
        kcpFlushAgain = false;
        void flushKcpSoon(why);
      }
    });
  return kcpFlushRunning;
}

// Deletes the stored snapshot; the next load cold boots. The running worker
// stops capturing until reload.
async function discardKcpSnapshot() {
  if (kcpWorker) {
    kcpWorker.postMessage({ type: "snapshot-discard" });
    return;
  }
  await discardSnapshot();
}

// --- kubectl worker --------------------------------------------------------

let kubectlWorker = null;
let kubectlGate = Promise.resolve();
let kubectlGateResolve = null;
let kubectlRestarting = false;
let kubectlInFlight = 0;
const pendingRuns = new Map();
let nextRunID = 1;
const runKubectlQueued = serializeQueue();

// A kubectl write of an EphemeralInfra gets what Request VM gives its
// contracts (vmshell.infraWritePlan) before kcp sees it: an ssh key held in
// this browser for every Requested contract (re-added on each write, since a
// merge patch replaces spec.contracts) and, for agent contracts, the secrets
// bundle the requester reads once before the RFP, written only when absent so
// the ATIRC_TOKEN it fills in stays. Anything else passes through unchanged.
async function prepareKubectlInfraWrite(request) {
  const method = String(request?.method ?? "").toUpperCase();
  if (!["POST", "PUT", "PATCH"].includes(method) || !String(request?.path ?? "").includes("/ephemeralinfras")) return request;
  let current = null;
  const existing = /\/ephemeralinfras\/([^/?]+)/.exec(request.path)?.[1];
  if (method === "PATCH" && existing) {
    current = await kcpREST("GET", `${SOCIALWEB_API}/ephemeralinfras/${existing}`).catch(() => null);
  }
  const plan = vmshell.infraWritePlan(request, { current });
  if (!plan) return request;
  for (const { index, cc } of plan.keys) {
    let key = await webrtcGuest.loadSSHKey(cc).catch(() => null);
    if (!key?.authorized) {
      key = await webrtcGuest.newSSHKey();
      await webrtcGuest.saveSSHKey(cc, key);
    }
    localStorage.setItem(computePrefs.transport(cc), "webrtc");
    const contract = plan.body.spec.contracts[index];
    const authorized = Array.isArray(contract.sshAuthorizedKeys) ? contract.sshAuthorizedKeys : [];
    if (!authorized.includes(key.authorized)) contract.sshAuthorizedKeys = [key.authorized, ...authorized];
  }
  for (const { mount, path } of plan.bundles) {
    await socialwebCall("socialwebVaultPut", {
      workspace: "root",
      mount,
      path,
      bundle: vmshell.secretsBundle({ agent: true }),
      ifAbsent: true,
    });
  }
  addLog("info", `kubectl ${method} EphemeralInfra ${plan.name}: ${plan.keys.length} ssh key(s) from this browser, ${plan.bundles.length} agent secrets bundle(s)`);
  const headers = Object.fromEntries(Object.entries(request.headers ?? {}).filter(([k]) => k.toLowerCase() !== "content-length"));
  return { ...request, headers, body: JSON.stringify(plan.body) };
}

function attachKubectl(worker) {
  worker.addEventListener("message", (event) => {
    const data = event.data ?? {};
    if (data.type === "fetch") {
      // kcp restarts (e.g. a discarded snapshot) leave a gap with no worker;
      // fail the request instead of leaving kubectl waiting for its timeout.
      if (!kcpWorker) {
        worker.postMessage({ type: "fetchResult", id: data.id, request: { error: "kcp worker is not running" } });
        return;
      }
      pendingBridges.set(data.id, true);
      void prepareKubectlInfraWrite(data.request).then(
        (request) => request,
        (err) => {
          addLog("warn", `kubectl EphemeralInfra write: ${err?.message ?? err}; sent unchanged`);
          return data.request;
        },
      ).then((request) => {
        if (!kcpWorker) {
          pendingBridges.delete(data.id);
          worker.postMessage({ type: "fetchResult", id: data.id, request: { error: "kcp worker is not running" } });
          return;
        }
        kcpWorker.postMessage({ type: "request", id: data.id, request });
      });
      return;
    }
    if (data.type === "result" && typeof data.id === "number") {
      const entry = pendingRuns.get(data.id);
      if (!entry) return;
      pendingRuns.delete(data.id);
      entry.resolve(data.result ?? {});
      return;
    }
    if (data.type === "log") {
      addLog(data.level ?? "info", `kubectl: ${data.message}`);
      return;
    }
    if (data.type === "exit") {
      const message = `kubectl exited (code ${data.code ?? "?"})`;
      for (const entry of pendingRuns.values()) entry.reject(new Error(message));
      pendingRuns.clear();
      pendingBridges.clear();
      if (!kubectlRestarting) void restartKubectl(message);
    }
  });

  worker.addEventListener("error", (event) => {
    const message = event.message ?? "kubectl worker error";
    addLog("error", `kubectl worker crashed: ${message}`);
    for (const entry of pendingRuns.values()) entry.reject(new Error(message));
    pendingRuns.clear();
    pendingBridges.clear();
  });
}

async function spawnKubectl() {
  const worker = new Worker("/kubectl_worker.js", { type: "module" });
  attachKubectl(worker);
  const readyPromise = waitReady(worker);
  worker.postMessage({
    type: "init",
    // The mobile kubectl links only the commands the page and a typical
    // shell session use (see contrib/wasm/kubectl/cmd_slim.go).
    wasmUrl: lowMemory ? "/kubectl-slim.wasm" : "/kubectl.wasm",
    fallbackUrl: lowMemory ? "/kubectl.wasm" : undefined,
    execUrl: "/wasm_exec.js",
    apiServer,
  });
  await readyPromise;
  kubectlWorker = worker;
}

async function restartKubectl(reason) {
  if (kubectlRestarting) return;
  kubectlRestarting = true;
  setStatus("restarting kubectl…", "running");
  addLog("warn", `restarting kubectl worker: ${reason}`);
  kubectlGate = new Promise((resolve) => {
    kubectlGateResolve = resolve;
  });
  const old = kubectlWorker;
  kubectlWorker = null;
  for (const entry of pendingRuns.values()) entry.reject(new CancelledError());
  pendingRuns.clear();
  pendingBridges.clear();
  old?.terminate();
  try {
    await spawnKubectl();
    addLog("ok", "kubectl worker restarted");
  } catch (err) {
    addLog("error", `kubectl restart failed: ${err instanceof Error ? err.message : err}`);
  } finally {
    kubectlRestarting = false;
    kubectlGateResolve?.();
    kubectlGateResolve = null;
    if (kubectlWorker && !cliRestarting) setStatus("connected", "connected");
  }
}

// Low-memory mode starts kubectl (a 120 MiB module) only when something first
// needs it: a shell command, the Compute panel or the diagram.
let kubectlLoading = null;
function ensureKubectl() {
  if (kubectlWorker) return Promise.resolve();
  kubectlLoading ??= spawnKubectl().catch((err) => {
    kubectlLoading = null;
    throw err;
  });
  return kubectlLoading;
}

function runKubectl(args, stdin = "") {
  return runKubectlQueued(async () => {
    if (!kubectlWorker && !kubectlRestarting) await ensureKubectl();
    await kubectlGate;
    const worker = kubectlWorker;
    if (!worker) throw new Error("kubectl worker is not running");
    kubectlInFlight++;
    try {
      return await new Promise((resolve, reject) => {
        const id = nextRunID++;
        pendingRuns.set(id, { resolve, reject });
        worker.postMessage({ type: "run", id, request: { args, stdin } });
      });
    } finally {
      kubectlInFlight--;
    }
  });
}

function withServer(args) {
  if (args.some((arg) => arg === "--server" || arg.startsWith("--server="))) {
    return args;
  }
  return [...args, `--server=${apiServer}`];
}

// --- CLI worker (goat, yq) -------------------------------------------------

const cliBaseEnv = {
  HOME: homeDir,
  XDG_STATE_HOME: `${homeDir}/.local/state`,
  XDG_DATA_HOME: `${homeDir}/.local/share`,
  XDG_CONFIG_HOME: `${homeDir}/.config`,
  XDG_CACHE_HOME: `${homeDir}/.cache`,
  TMPDIR: "/tmp",
  PATH: "/usr/local/bin:/usr/bin:/bin",
  USER: "user",
  LOGNAME: "user",
  LANG: "C.UTF-8",
};

let cliWorker = null;
let cliGate = Promise.resolve();
let cliGateResolve = null;
let cliRestarting = false;
let cliInFlight = 0;
const pendingCli = new Map();
let nextCliID = 1;
const runCliQueued = serializeQueue();

function attachCli(worker) {
  worker.addEventListener("message", (event) => {
    const data = event.data ?? {};
    if (data.type === "log") {
      addLog(data.level ?? "info", `cli: ${data.message}`);
      return;
    }
    if (data.type === "result" && typeof data.id === "number") {
      const entry = pendingCli.get(data.id);
      if (!entry) return;
      pendingCli.delete(data.id);
      entry.resolve(data.result ?? {});
    }
  });

  worker.addEventListener("error", (event) => {
    const message = event.message ?? "cli worker error";
    addLog("error", `cli worker crashed: ${message}`);
    for (const entry of pendingCli.values()) entry.reject(new Error(message));
    pendingCli.clear();
  });
}

async function spawnCli() {
  const worker = new Worker("/cli_worker.js", { type: "module" });
  attachCli(worker);
  const readyPromise = waitReady(worker);
  worker.postMessage({
    type: "init",
    execUrl: "/wasm_exec_cli.js",
    modules: { goat: "/goat.wasm", yq: "/yq.wasm" },
    env: cliBaseEnv,
    cwd: homeDir,
  });
  await readyPromise;
  cliWorker = worker;
}

let cliLoading = null;
function ensureCli() {
  cliLoading ??= spawnCli().catch((err) => {
    cliLoading = null;
    addLog("warn", `goat/yq unavailable: ${err instanceof Error ? err.message : err}`);
    throw err;
  });
  return cliLoading;
}

async function restartCli(reason) {
  if (cliRestarting) return;
  cliRestarting = true;
  addLog("warn", `restarting CLI worker: ${reason}`);
  cliGate = new Promise((resolve) => {
    cliGateResolve = resolve;
  });
  const old = cliWorker;
  cliWorker = null;
  for (const entry of pendingCli.values()) entry.reject(new CancelledError());
  pendingCli.clear();
  old?.terminate();
  try {
    await spawnCli();
    addLog("ok", "CLI worker restarted");
  } catch (err) {
    addLog("error", `CLI restart failed: ${err instanceof Error ? err.message : err}`);
  } finally {
    cliRestarting = false;
    cliGateResolve?.();
    cliGateResolve = null;
  }
}

function runCli(tool, args, env, cwd, stdin, files, dirs) {
  return runCliQueued(async () => {
    await cliGate;
    const worker = cliWorker;
    if (!worker) throw new Error(`${tool} worker is not running`);
    cliInFlight++;
    try {
      return await new Promise((resolve, reject) => {
        const id = nextCliID++;
        pendingCli.set(id, { resolve, reject });
        worker.postMessage({
          type: "run",
          id,
          request: { tool, args, env, cwd, stdin, files, dirs },
        });
      });
    } finally {
      cliInFlight--;
    }
  });
}

// --- just-bash shell and filesystem sharing --------------------------------

let bash = null;
let shellAbort = null;
let ttyTool = null;

function decodeStdin(value) {
  if (!value) return "";
  if (typeof value === "string") {
    const bytes = new Uint8Array(value.length);
    for (let i = 0; i < value.length; i++) bytes[i] = value.charCodeAt(i) & 0xff;
    return new TextDecoder().decode(bytes);
  }
  return new TextDecoder().decode(value);
}

async function walkBashFs(fs, dir = "/", files = {}, dirs = []) {
  let names = [];
  try {
    names = await fs.readdir(dir);
  } catch {
    return { files, dirs };
  }
  if (dir !== "/") dirs.push(dir);
  for (const name of names) {
    const path = dir === "/" ? `/${name}` : `${dir}/${name}`;
    if (path === "/dev" || path === "/proc") continue;
    let stat;
    try {
      stat = await fs.stat(path);
    } catch {
      continue;
    }
    if (stat.isDirectory) {
      await walkBashFs(fs, path, files, dirs);
    } else if (stat.isFile && stat.size < 1_000_000) {
      try {
        files[path] = await fs.readFile(path);
      } catch {
        // Binary or unreadable file; not shareable with goat.
      }
    }
  }
  return { files, dirs };
}

async function applyCliFiles(files, sent) {
  for (const path of Object.keys(sent)) {
    if (!(path in files)) {
      await bash.fs.rm(path, { force: true }).catch(() => {});
    }
  }
  for (const [path, content] of Object.entries(files)) {
    if (sent[path] === content) continue;
    const directory = path.slice(0, path.lastIndexOf("/")) || "/";
    await bash.fs.mkdir(directory, { recursive: true }).catch(() => {});
    await bash.fs.writeFile(path, content).catch((err) => {
      addLog("warn", `cli fs: ${path}: ${err instanceof Error ? err.message : err}`);
    });
  }
}

function shellHelp() {
  return [
    "just-bash shell. kubectl and goat run as WebAssembly workers in this tab.",
    "",
    "examples:",
    "  get crds",
    "  get fetches | grep demo",
    "  kubectl get fetch demo -o yaml > demo.yaml",
    "  kubectl apply -f - <<'EOF' ... EOF",
    "  goat resolve bsky.app",
    "  goat account login -u handle -p app-password",
    "  goat xrpc query https://public.api.bsky.app app.bsky.actor.getProfile actor==atproto.com",
    "  yq '.items[].metadata.name' fetches.json",
    "  echo '{\"a\":1}' | jq .a    (jq is built into just-bash)",
    "  export GOAT_USERNAME=... GOAT_PASSWORD=...",
    "  ls /tmp; cat demo.yaml",
    "  ssh vmshell-abc123            (a Held ComputeContract, over WebRTC; see ~/.ssh/config)",
    "  ssh vmshell-abc123 uname -a | grep Linux",
    "",
    "builtins: help · clear · reset [--all] (wipe kcp state and reload; --all also the unreadable-state backups) · snapshot-discard (cold boot next load)",
    "keys: Ctrl-C cancel · Ctrl-D finish stdin · Tab complete · ↑/↓ history",
    "",
  ].join("\n");
}

function lastPipelineSegment(script) {
  const source = stripHeredocBodies(script);
  const segments = [];
  let current = "";
  let quote = null;
  for (let i = 0; i < source.length; i++) {
    const ch = source[i];
    if (quote) {
      current += ch;
      if (ch === quote) quote = null;
      continue;
    }
    if (ch === "'" || ch === '"') {
      quote = ch;
      current += ch;
      continue;
    }
    if (ch === "|" && source[i + 1] !== "|") {
      segments.push(current);
      current = "";
      continue;
    }
    current += ch;
  }
  segments.push(current);
  return segments[segments.length - 1].trim();
}

// A native shell gives the last pipeline command a terminal stdout. Use that
// to set KCP_TTY for CLI tools that colorize on isatty (yq).
function detectTtyTool(script) {
  const segment = lastPipelineSegment(script);
  if (/[<>]/.test(segment)) return null;
  const first = splitArgs(segment)[0];
  return ["kubectl", "goat", "yq", "ssh"].includes(first) ? first : null;
}

function makeCommands() {
  const kubectl = defineCommand("kubectl", async (args, ctx) => {
    const result = await runKubectl(withServer(args), decodeStdin(ctx.stdin));
    return {
      stdout: result.stdout ?? "",
      stderr: result.stderr ?? "",
      exitCode: result.code ?? 0,
    };
  });

  const runCliCommand = async (tool, args, ctx) => {
    if (!cliWorker && !cliRestarting) await ensureCli().catch(() => {});
    if (!cliWorker && !cliRestarting) {
      return { stdout: "", stderr: `${tool} worker is not available\n`, exitCode: 1 };
    }
    if (cliRestarting) await cliGate;
    const env = { ...cliBaseEnv, ...Object.fromEntries(ctx.env) };
    if (tool === ttyTool) env.KCP_TTY = "1";
    const { files, dirs } = await walkBashFs(bash.fs);
    const result = await runCli(
      tool,
      args,
      env,
      ctx.cwd,
      decodeStdin(ctx.stdin),
      files,
      dirs,
    );
    await applyCliFiles(result.files ?? {}, files);
    return {
      stdout: result.stdout ?? "",
      stderr: result.stderr ?? "",
      exitCode: result.code ?? 0,
    };
  };

  const goat = defineCommand("goat", (args, ctx) => runCliCommand("goat", args, ctx));
  const yq = defineCommand("yq", (args, ctx) => runCliCommand("yq", args, ctx));

  const help = defineCommand("help", async () => ({
    stdout: shellHelp(),
    stderr: "",
    exitCode: 0,
  }));

  const clear = defineCommand("clear", async () => {
    term.clear();
    return { stdout: "", stderr: "", exitCode: 0 };
  });

  const snapshotDiscard = defineCommand("snapshot-discard", async () => {
    await discardKcpSnapshot();
    return { stdout: "kcp snapshot discarded; the next load cold boots\n", stderr: "", exitCode: 0 };
  });

  const reset = defineCommand("reset", async (args) => {
    const all = (args ?? []).includes("--all");
    if ((args ?? []).some((a) => a !== "--all")) {
      return { stdout: "", stderr: "usage: reset [--all]\n", exitCode: 2 };
    }
    await resetState({ all });
    return {
      stdout: `cleared shell and kcp state${all ? " and the unreadable-state backups" : " (unreadable-state backups kept; reset --all removes them)"}; reloading…\n`,
      stderr: "",
      exitCode: 0,
    };
  });

  const ssh = defineCommand("ssh", (args, ctx) => runSsh(args, ctx));

  return [kubectl, goat, yq, ssh, help, clear, reset, snapshotDiscard];
}

async function restoreShell() {
  let saved = {};
  try {
    saved = JSON.parse(localStorage.getItem(shellStateKey) ?? "{}");
  } catch {
    saved = {};
  }

  bash = new Bash({
    cwd: homeDir,
    env: { HOME: homeDir, ...(saved.env ?? {}) },
    customCommands: makeCommands(),
    executionLimits: { maxExecutionTimeMs: 60 * 60 * 1000 },
  });

  for (const directory of ["/home", homeDir, "/tmp", "/etc", "/bin", "/usr/bin"]) {
    await bash.fs.mkdir(directory, { recursive: true }).catch(() => {});
  }
  for (const directory of saved.dirs ?? []) {
    await bash.fs.mkdir(directory, { recursive: true }).catch(() => {});
  }
  for (const [path, content] of Object.entries(saved.files ?? {})) {
    await bash.fs.writeFile(path, content).catch(() => {});
  }
  if (saved.cwd && saved.cwd !== bash.getCwd()) {
    await bash.exec(`cd '${saved.cwd.replace(/'/g, "'\\''")}'`).catch(() => {});
  }
}

let persistShellTimer = null;
function scheduleShellPersist(env) {
  if (!bash) return;
  if (persistShellTimer) clearTimeout(persistShellTimer);
  persistShellTimer = setTimeout(async () => {
    try {
      const { files, dirs } = await walkBashFs(bash.fs);
      const payload = JSON.stringify({
        files,
        dirs,
        env: env ?? bash.getEnv(),
        cwd: bash.getCwd(),
      });
      localStorage.setItem(shellStateKey, payload);
    } catch (err) {
      addLog(
        "warn",
        `could not persist shell filesystem: ${err instanceof Error ? err.message : err}`,
      );
    }
  }, 250);
}

// --- shell prompt and execution --------------------------------------------

let line = "";
let cursor = 0;
let history = [];
let historyIndex = 0;
let continuation = [];
let stdinMode = false;
let stdinScript = "";
let stdinLines = [];
let stdinCurrent = "";
let completing = false;

try {
  const saved = JSON.parse(localStorage.getItem("kcp-cmd-history") ?? "[]");
  if (Array.isArray(saved)) {
    history = saved.filter((entry) => typeof entry === "string");
  }
} catch {
  // Corrupt history is not worth surfacing.
}
historyIndex = history.length;

function promptText() {
  const cwd = bash?.getCwd() ?? homeDir;
  return `${cyan(cwd)} $ `;
}

const stdinPrompt = () => "\x1b[90m...\x1b[0m ";
const continuationPrompt = () => "\x1b[90m> \x1b[0m ";

function prompt() {
  term.write(`\r\n${promptText()}`);
}

function redraw() {
  term.write(`\r\x1b[2K${promptText()}${line}`);
  const back = line.length - cursor;
  if (back > 0) term.write(`\x1b[${back}D`);
}

function visiblePromptLength() {
  const cwd = bash?.getCwd() ?? homeDir;
  return cwd.length + 3; // "<cwd> $ "
}

function replaceLine(next) {
  // Erase the whole logical input, including wrapped rows, then redraw.
  // Assumes the cursor is at the end of the current input (history recall).
  const columns = term.cols || 80;
  const rows = Math.max(1, Math.ceil((visiblePromptLength() + line.length) / columns));
  if (rows > 1) term.write(`\x1b[${rows - 1}A`);
  term.write("\r\x1b[0J");
  line = next;
  cursor = next.length;
  term.write(promptText() + line);
}

function insertText(text) {
  if (!text) return;
  if (cursor === line.length) {
    line += text;
    cursor = line.length;
    term.write(text);
  } else {
    line = line.slice(0, cursor) + text + line.slice(cursor);
    cursor += text.length;
    redraw();
  }
}

function deleteWordBeforeCursor() {
  if (cursor === 0) return;
  let index = cursor;
  while (index > 0 && line[index - 1] === " ") index--;
  while (index > 0 && line[index - 1] !== " ") index--;
  line = line.slice(0, index) + line.slice(cursor);
  cursor = index;
  redraw();
}

function saveHistory() {
  try {
    localStorage.setItem("kcp-cmd-history", JSON.stringify(history.slice(-100)));
  } catch {
    // History is best-effort.
  }
}

function splitArgs(text) {
  const args = [];
  let current = "";
  let quote = null;
  for (const ch of text) {
    if (quote) {
      if (ch === quote) quote = null;
      else current += ch;
    } else if (ch === '"' || ch === "'") {
      quote = ch;
    } else if (ch === " " || ch === "\t") {
      if (current) {
        args.push(current);
        current = "";
      }
    } else {
      current += ch;
    }
  }
  if (current) args.push(current);
  return args;
}

function needsStdin(args) {
  for (let index = 0; index < args.length; index++) {
    const arg = args[index];
    if ((arg === "-f" || arg === "--filename") && args[index + 1] === "-") {
      return true;
    }
    if (arg === "--filename=-") return true;
  }
  return false;
}

function normalizeNewlines(text) {
  return String(text).replace(/\r\n/g, "\n").replace(/\n/g, "\r\n");
}

function heredocDelimiter(script) {
  const lines = script.split("\n");
  for (let i = 0; i < lines.length; i++) {
    const match = lines[i].match(/<<-?\s*(['"]?)([A-Za-z0-9_]+)\1/);
    if (!match) continue;
    const delimiter = match[2];
    const closes = lines.slice(i + 1).some((entry) => entry.trim() === delimiter);
    if (!closes) return delimiter;
  }
  return null;
}

function stripHeredocBodies(script) {
  const lines = script.split("\n");
  const kept = [];
  let active = null;
  for (const current of lines) {
    if (active !== null) {
      if (current.trim() === active) active = null;
      continue;
    }
    kept.push(current);
    const match = current.match(/<<-?\s*(['"]?)([A-Za-z0-9_]+)\1/);
    if (match) active = match[2];
  }
  return kept.join("\n");
}

function unbalancedQuote(script) {
  let quote = null;
  for (let i = 0; i < script.length; i++) {
    const ch = script[i];
    if (ch === "\\" && quote !== "'") {
      i++;
      continue;
    }
    if (quote) {
      if (ch === quote) quote = null;
    } else if (ch === "'" || ch === '"') {
      quote = ch;
    }
  }
  return quote;
}

function needsContinuation(script) {
  if (heredocDelimiter(script)) return true;
  if (unbalancedQuote(stripHeredocBodies(script))) return true;
  const trimmed = script.replace(/\s+$/, "");
  if (trimmed.endsWith("\\")) return true;
  if (/(\||&&|\|\||\()$/.test(trimmed)) return true;
  return false;
}

async function runScript(script, stdin = "") {
  busy = true;
  const label = script.split("\n")[0].slice(0, 80);
  addLog("info", `$ ${label.replace(/\s+/g, " ")}${script.includes("\n") ? " …" : ""}`);
  const started = performance.now();
  ttyTool = detectTtyTool(script);
  shellAbort = new AbortController();

  try {
    const result = await bash.exec(script, {
      signal: shellAbort.signal,
      stdin,
      rawScript: script.includes("\n"),
    });
    const elapsed = Math.round(performance.now() - started);
    if (result.stdout) term.write(normalizeNewlines(result.stdout));
    if (result.stderr) term.write(red(normalizeNewlines(result.stderr)));
    scrollToBottomSettled();
    addLog(
      result.exitCode === 0 ? "ok" : "warn",
      `exit ${result.exitCode} · ${elapsed}ms`,
    );
    scheduleShellPersist(result.env);
  } catch (err) {
    if (err instanceof CancelledError || err?.name === "AbortError") {
      term.writeln(dim("[cancelled]"));
      addLog("warn", "script cancelled");
    } else {
      const message = err instanceof Error ? err.message : String(err);
      term.writeln(red(`error: ${message}`));
      addLog("error", `script failed: ${message}`);
    }
    scheduleShellPersist();
  } finally {
    shellAbort = null;
    ttyTool = null;
    busy = false;
    if (!kubectlRestarting && !cliRestarting) setStatus("connected", "connected");
    prompt();
    scrollToBottomSettled();
    void poll();
    runQueuedDiagramCommand();
  }
}

function submit() {
  const current = line.trimEnd();
  line = "";
  cursor = 0;
  term.write("\r\n");

  if (!current && continuation.length === 0) {
    prompt();
    return;
  }

  continuation.push(current);
  const script = continuation.join("\n");
  if (needsContinuation(script)) {
    term.write(continuationPrompt());
    return;
  }
  continuation = [];

  if (!current) {
    prompt();
    return;
  }

  history.push(current);
  saveHistory();
  historyIndex = history.length;

  if (!ready) {
    term.writeln(red("still loading WASM modules…"));
    prompt();
    return;
  }

  const words = splitArgs(current);
  if (needsStdin(words) && !script.includes("\n") && !/[|<>&]/.test(current)) {
    stdinMode = true;
    stdinScript = script;
    stdinLines = [];
    stdinCurrent = "";
    term.writeln(
      dim("stdin mode: paste or type the manifest. Ctrl-D runs, Ctrl-C aborts."),
    );
    term.write(stdinPrompt());
    return;
  }

  void runScript(script);
}

function abortStdin() {
  stdinMode = false;
  stdinScript = "";
  stdinLines = [];
  stdinCurrent = "";
  term.write("^C\r\n");
  addLog("warn", "stdin aborted");
  prompt();
}

function finishStdin() {
  if (stdinCurrent) {
    stdinLines.push(stdinCurrent);
    stdinCurrent = "";
  }
  const stdin = stdinLines.length > 0 ? `${stdinLines.join("\n")}\n` : "";
  const script = stdinScript;
  stdinMode = false;
  stdinScript = "";
  stdinLines = [];
  term.write("\r\n");
  term.writeln(dim(`[stdin ${stdin.split("\n").length - 1} line(s), ${stdin.length} bytes]`));
  void runScript(script, stdin);
}

function handleStdinData(data) {
  if (data.startsWith("\u001b")) return;
  for (const ch of data) {
    if (ch === "\r" || ch === "\n") {
      stdinLines.push(stdinCurrent);
      stdinCurrent = "";
      term.write("\r\n" + stdinPrompt());
    } else if (ch === "\u007f") {
      if (stdinCurrent.length > 0) {
        stdinCurrent = stdinCurrent.slice(0, -1);
        term.write("\b \b");
      }
    } else if (ch === "\t") {
      stdinCurrent += "  ";
      term.write("  ");
    } else if (ch >= " ") {
      stdinCurrent += ch;
      term.write(ch);
    }
  }
}

function cancelRunning() {
  line = "";
  cursor = 0;
  if (continuation.length > 0) {
    continuation = [];
    term.write("\r\x1b[2K^C");
    prompt();
    return;
  }
  if (!busy) {
    term.write("\r\x1b[2K");
    prompt();
    return;
  }
  term.write("^C");
  addLog("warn", "Ctrl-C: cancelling");
  shellAbort?.abort();
  if (kubectlInFlight > 0) void restartKubectl("Ctrl-C");
  if (cliInFlight > 0) void restartCli("Ctrl-C");
}

// --- completion ------------------------------------------------------------

function commonPrefix(values) {
  if (values.length === 0) return "";
  let prefix = values[0];
  for (const value of values.slice(1)) {
    let index = 0;
    while (
      index < prefix.length &&
      index < value.length &&
      prefix[index] === value[index]
    ) {
      index++;
    }
    prefix = prefix.slice(0, index);
  }
  return prefix;
}

function shellCommandNames() {
  const builtins = [
    "cd", "export", "unset", "alias", "source", ".", "history",
    "kubectl", "goat", "yq", "ssh", "help", "clear", "reset", "snapshot-discard",
  ];
  return [...new Set([...getCommandNames(), ...builtins])].sort();
}

async function pathCompletions(token) {
  const slash = token.lastIndexOf("/");
  const directory = slash === -1 ? "." : (token.slice(0, slash) || "/");
  const prefix = slash === -1 ? token : token.slice(slash + 1);
  const absolute = directory.startsWith("/")
    ? directory
    : `${bash.getCwd().replace(/\/$/, "")}/${directory}`;
  const names = await bash.fs.readdir(absolute).catch(() => []);
  const results = [];
  for (const name of names) {
    if (!name.startsWith(prefix)) continue;
    const parent = slash === -1 ? token.slice(0, token.length - prefix.length) : token.slice(0, slash + 1);
    let isDir = false;
    try {
      isDir = (await bash.fs.stat(`${absolute.replace(/\/$/, "")}/${name}`)).isDirectory;
    } catch {
      isDir = false;
    }
    results.push({ value: `${parent}${name}${isDir ? "/" : ""}`, description: isDir ? "dir" : "" });
  }
  return results;
}

async function kubectlCompletions(parts, token) {
  const result = await runKubectl([
    "__complete",
    `--server=${apiServer}`,
    ...parts,
    token,
  ]);
  return String(result.stdout ?? "")
    .split("\n")
    .filter((entry) => entry && !entry.startsWith(":") && !entry.startsWith("_activeHelp_"))
    .map((entry) => {
      const [value, ...description] = entry.split("\t");
      return { value, description: description.join(" ").trim() };
    });
}

async function completeLine() {
  if (completing || busy || stdinMode || !ready || continuation.length > 0) return;
  const original = line;
  const endsWithSpace = /\s$/.test(original);
  const parts = splitArgs(original);
  const token = endsWithSpace ? "" : (parts.pop() ?? "");

  completing = true;
  try {
    let candidates;
    if (parts[0] === "kubectl") {
      candidates = await kubectlCompletions(parts.slice(1), token);
    } else if (parts[0] === "ssh" && !token.startsWith("-") && !parts.slice(1).some((p) => !p.startsWith("-"))) {
      candidates = sshCmd.sshHosts(lastFeedState, { testPeer: Boolean(sshTestPeer) })
        .filter((name) => name.startsWith(token))
        .map((name) => ({ value: name, description: "ComputeContract" }));
    } else if (parts.length === 0) {
      candidates = shellCommandNames()
        .filter((name) => name.startsWith(token))
        .map((name) => ({ value: name, description: "" }));
    } else {
      candidates = await pathCompletions(token);
    }

    if (line !== original || busy) return;
    if (candidates.length === 0) {
      term.write("\x07");
      return;
    }

    const base = endsWithSpace ? line : line.slice(0, line.length - token.length);
    if (candidates.length === 1) {
      line = `${base}${candidates[0].value}${candidates[0].value.endsWith("/") ? "" : " "}`;
      cursor = line.length;
      redraw();
      return;
    }

    const prefix = commonPrefix(candidates.map((candidate) => candidate.value));
    if (prefix.length > token.length) {
      line = `${base}${prefix}`;
      cursor = line.length;
    }

    term.write("\r\n");
    for (const candidate of candidates.slice(0, 40)) {
      term.writeln(
        candidate.description
          ? `${cyan(candidate.value)}  ${dim(candidate.description)}`
          : candidate.value,
      );
    }
    if (candidates.length > 40) {
      term.writeln(dim(`... ${candidates.length - 40} more`));
    }
    term.write("\r\n");
    redraw();
  } catch (err) {
    addLog("warn", `completion failed: ${err instanceof Error ? err.message : err}`);
  } finally {
    completing = false;
  }
}

// --- live Pele diagram -----------------------------------------------------

let lastDiagram = "";
let polling = false;

function applyDiagramVisibility() {
  diagramEl.classList.toggle("hidden", !diagramVisible);
  diagramToggleEl.textContent = diagramVisible ? "hide" : "show";
  if (!diagramVisible) diagramUpdatedEl.textContent = "closed";
}

diagramToggleEl.addEventListener("click", () => {
  diagramVisible = !diagramVisible;
  localStorage.setItem("kcp-diagram-open", diagramVisible ? "1" : "0");
  applyDiagramVisibility();
  if (diagramVisible) void poll();
});
applyDiagramVisibility();
let pendingDiagramCommand = null;
let diagramTargets = new Map();

function runQueuedDiagramCommand() {
  if (!pendingDiagramCommand || busy || booting || bootActive || stdinMode) return;
  const command = pendingDiagramCommand;
  pendingDiagramCommand = null;
  term.focus();
  term.write(`\r\n${promptText()}${command}`);
  line = command;
  cursor = line.length;
  submit();
}

diagramEl.addEventListener("click", (event) => {
  const node = event.target.closest?.("[data-id]");
  if (!node) return;
  const command = diagramTargets.get(node.getAttribute("data-id"));
  if (!command) return;
  if (busy || booting) {
    pendingDiagramCommand = command;
    addLog("info", `queued diagram command: ${command}`);
    return;
  }
  if (stdinMode) {
    addLog("warn", "finish or abort stdin before describing from the diagram");
    return;
  }
  term.focus();
  term.write(`\r\n${promptText()}${command}`);
  line = command;
  cursor = line.length;
  submit();
});

async function kubectlJSON(args) {
  const result = await runKubectl(withServer([...args, "-o", "json"]));
  if (result.code !== 0) {
    throw new Error(String(result.stderr ?? "kubectl failed").trim());
  }
  return JSON.parse(result.stdout ?? "{}");
}

async function poll() {
  if (!ready || polling || busy || bootActive || stdinMode || !diagramVisible) return;
  polling = true;
  let mermaid = null;
  let crds = null;
  try {
    crds = await kubectlJSON(["get", "crds"]);
    mermaid = buildDiagram(
      apiServer,
      crds.items ?? [],
      [],
      isNarrow() ? "TD" : "LR",
    );

    const targets = new Map();
    for (const crd of crds.items ?? []) {
      const name = crd?.metadata?.name;
      if (name) targets.set(nodeID("crd", name), `kubectl describe crd ${name}`);
    }
    diagramTargets = targets;
  } catch (err) {
    if (err instanceof CancelledError) return;
    const message = String(err instanceof Error ? err.message : err);
    addLog("error", `poll failed: ${message}`);
    mermaid = [
      "flowchart LR",
      `  api["kcp-wasm<br/>${apiServer}"]`,
      `  err["kubectl error<br/>${message.replace(/"/g, "'").slice(0, 120)}"]`,
      "  api --> err",
    ].join("\n");
  } finally {
    polling = false;
  }

  if (mermaid !== lastDiagram) {
    lastDiagram = mermaid;
    const crdCount = crds?.items?.length ?? 0;
    renderDiagram(
      mermaid,
      crds ? `${crdCount} CRD${crdCount === 1 ? "" : "s"}` : "error",
    );
    addLog(crds ? "info" : "warn", `state: ${crdCount} CRD(s)`);
  }
}

function renderDiagram(mermaid, summary = "") {
  diagramEl.replaceChildren();
  const stamp = new Date().toLocaleTimeString();
  diagramUpdatedEl.textContent = summary ? `updated ${stamp} · ${summary}` : `updated ${stamp}`;
  try {
    pele.mount(diagramEl, mermaid);
  } catch (err) {
    const pre = document.createElement("pre");
    pre.className = "error";
    pre.textContent = String(err);
    diagramEl.appendChild(pre);
  }
}


// Boot sequence: show the real in-browser kcp surface. The full socialweb
// provider/app manifests are applied by the worker; these commands are a
// clean, copy-pasteable checkpoint that they are being served.
const BOOT_STEPS = [
  "kubectl get workspaces",
  "kubectl get shards.core.kcp.io",
  "kubectl get --raw /clusters/root/version | jq -r '.gitVersion'",
];

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let booting = false;
let bootActive = false;

async function typeBootSteps(steps) {
  if (!ready || !kubectlWorker) return;
  bootActive = true;
  booting = true;
  busy = true;

  for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
    const lines = steps[stepIndex].split("\n");
    let heredoc = null;
    for (let i = 0; i < lines.length; i++) {
      const current = lines[i];
      if (i === 0) {
        if (stepIndex === 0) term.write(promptText());
        // Later steps already have a prompt from the previous run.
      } else {
        term.write(`\r\n${heredoc ? continuationPrompt() : promptText()}`);
      }
      if (heredoc) {
        if (current.trim() === heredoc) heredoc = null;
      } else {
        const match = current.match(/<<-?\s*(['"]?)([A-Za-z0-9_]+)\1/);
        if (match) heredoc = match[2];
      }
      for (const ch of current) {
        term.write(ch);
        await sleep(2);
      }
    }

    const entry = steps[stepIndex].trim();
    if (entry && history[history.length - 1] !== entry) {
      history.push(entry);
      saveHistory();
    }
    historyIndex = history.length;

    // Visible Enter press before the step runs.
    await sleep(150);
    term.write("\r\n");
    await sleep(150);
    booting = false;
    await runScript(steps[stepIndex]);
    booting = true;
    busy = true;
  }
  booting = false;
  bootActive = false;
  busy = false;
  setStatus("connected", "connected");
  runQueuedDiagramCommand();
}

// --- socialweb requester UI ------------------------------------------------

// The requester's comms mode is read once at boot (the orchestrator brings the
// MarketRequester to it), so a change reloads the page. Firehose is the
// default; Ingress (comms mode Both) keeps the relay-hosted XRPC endpoints
// (submitBid, submitEvent, getSecrets) as a backstop next to the streams.
const commsEl = document.getElementById("compute-comms");
commsEl.value = localStorage.getItem("socialweb.commsMode") ?? "Firehose";
commsEl.addEventListener("change", () => {
  localStorage.setItem("socialweb.commsMode", commsEl.value);
  addLog("info", `comms mode ${commsEl.value}; reloading to apply it`);
  setTimeout(() => location.reload(), 300);
});

const identityPrefs = {
  mode: "socialweb.identity",
  handle: "socialweb.handle",
  pdsUrl: "socialweb.pdsUrl",
};
// Earlier pages stored a cleared handle as the string "undefined".
if (localStorage.getItem(identityPrefs.handle) === "undefined") localStorage.removeItem(identityPrefs.handle);

function setAppStatus(el, text, className = "") {
  el.textContent = text;
  el.className = `app-status ${className}`.trim();
}

// Without a handle, sign in through bsky.social's authorization server and
// pick the account on its page; the placeholder looks like a value but is not.
const DEFAULT_PDS_URL = "https://bsky.social";

function requesterIdentity() {
  const handle = identityHandleEl.value.trim();
  // The page origin is the OAuth client (static metadata and callback), so
  // sign-in never depends on this tab's ingress, which iOS pauses while the
  // user is on the PDS.
  const identity = {
    mode: identityModeEl.value,
    association: "Skip",
    oauthClientID: `${location.origin}/oauth-client-metadata.json`,
    oauthRedirectURI: `${location.origin}/oauth/callback/requester`,
  };
  if (handle) identity.handle = handle;
  else identity.pdsUrl = DEFAULT_PDS_URL;
  return identity;
}

async function patchRequesterIdentity() {
  const identity = requesterIdentity();
  localStorage.setItem(identityPrefs.mode, identity.mode);
  localStorage.setItem(identityPrefs.handle, identity.handle ?? "");
  // A merge patch: unset fields are dropped, so a cleared handle must be null.
  const patch = { spec: { identity: { handle: null, pdsUrl: null, ...identity } } };
  await kcpREST("PATCH", `${SOCIALWEB_API}/marketrequesters/app`, patch, "application/merge-patch+json");
  addLog("info", `identity ${identity.mode} ${identity.handle ? `handle=${identity.handle}` : `pds=${identity.pdsUrl}`}`);
}

async function completeOAuth(message) {
  const query = new URLSearchParams();
  for (const key of ["code", "state", "iss", "error", "error_description"]) {
    const value = message?.[key];
    if (value) query.set(key, String(value));
  }
  // An error goes to socialweb too: the callback spends the URL's state, so
  // the controller issues a new one. socialweb only says "names no code";
  // show what the authorization server said.
  const response = await kcpPageRequest({
    method: "GET",
    path: `/oauth/callback/requester?${query.toString()}`,
    headers: { Host: location.host, Accept: "text/plain" },
  });
  if (!message?.code) {
    const reason = [message?.error, message?.error_description].filter(Boolean).join(": ");
    throw new Error(`the authorization server returned no code${reason ? ` (${reason})` : " and no error"}`);
  }
  if (response.status >= 400) {
    throw new Error(String(response.body ?? `callback returned ${response.status}`));
  }
  addLog("ok", "OAuth callback accepted");
}

// The page's half of the sign-in state; signInView (identity_ui.js) combines
// it with the MarketIdentity status into what the panel shows.
const USED_URLS_KEY = "socialweb.signin.used";
const signIn = { step: "idle", since: 0, error: "", notice: "", url: "", account: null, used: [] };
try {
  signIn.used = JSON.parse(localStorage.getItem(USED_URLS_KEY) ?? "[]");
} catch {
  // unreadable; every URL counts as new
}
let identityState = null;
let requesterSeen = false;
let identityView = null;
let identityTimer = 0;
let lastIdentitySummary = "";

function signInLocal() {
  return { ...signIn, typed: identityHandleEl.value, applied: localStorage.getItem(identityPrefs.handle) ?? "" };
}

function setSignIn(patch) {
  if ("step" in patch) {
    patch.since = Date.now();
    if (!("notice" in patch)) patch.notice = "";
  }
  Object.assign(signIn, patch);
  renderIdentity();
}

// A callback spends the URL's state even when it fails; kept across reloads
// so a page iOS reloaded behind the popup does not reopen it.
function markUsed(url) {
  signIn.used = [...signIn.used.filter((u) => u !== url), url].slice(-5);
  localStorage.setItem(USED_URLS_KEY, JSON.stringify(signIn.used));
}

function renderIdentity() {
  const view = signInView({ requester: requesterSeen, identity: identityState, local: signInLocal() });
  if (view.state === "failed" && signIn.step !== "idle") Object.assign(signIn, { step: "idle", error: view.error });
  if (view.state === "signedIn") signIn.step = "idle";
  identityView = view;
  identitySignInEl.textContent = view.primary.label;
  identitySignInEl.disabled = !socialwebUIReady || Boolean(view.primary.disabled);
  identitySecondaryEl.hidden = !view.secondary;
  identitySecondaryEl.textContent = view.secondary?.label ?? "";
  identityHandleEl.disabled = view.busy;
  setAppStatus(identityStatusEl, view.detail ? `${view.text}\n${view.detail}` : view.text, view.tone);
  clearTimeout(identityTimer);
  if (view.busy && signIn.step !== "idle" && signIn.step !== "authorizing") {
    identityTimer = setTimeout(renderIdentity, Math.max(50, GRACE_MS - (Date.now() - signIn.since) + 50));
  }
  const did = identityState?.phase === "Ready" ? identityState.did : "";
  if (did && signIn.account?.did !== did) void resolveAccount(did);
}

// status.handle is the spec's handle in builds before rc110, so the panel
// names the session's DID by the handle the AppView verified for it.
async function resolveAccount(did) {
  signIn.account = { did, handle: "" };
  try {
    const res = await fetch(`https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(did)}`);
    const handle = res.ok ? String((await res.json()).handle ?? "") : "";
    if (signIn.account?.did === did && handle && handle !== "handle.invalid") signIn.account = { did, handle };
  } catch (err) {
    addLog("warn", `could not resolve the handle of ${did}: ${err instanceof Error ? err.message : err}`);
  }
  renderIdentity();
}

// Runs inside the tap: iOS Safari opens a popup only there, and pauses this
// tab while the popup is in front, so a popup opened early cannot be pointed
// at the URL later. With a URL ready the tap opens it; otherwise it asks for
// one and the button becomes Continue sign-in once the PDS has answered.
function identityAction(action) {
  const run = { start: startSignIn, open: openSignInPopup, switch: switchAccount, signOut: signOutIdentity,
    cancel: cancelOAuthPopup,
    // A new link for a permission upgrade; the old failure no longer applies.
    refresh: () => (setSignIn({ error: "" }), requestSignInLink()) }[action];
  if (!run) return;
  const fail = (err) => {
    const message = err instanceof Error ? err.message : String(err);
    addLog("error", `sign-in: ${message}`);
    setSignIn({ step: "idle", error: message });
  };
  try {
    void Promise.resolve(run()).catch(fail);
  } catch (err) {
    fail(err);
  }
}

// A changed spec makes the controller issue a URL for it; an unchanged one
// keeps the URL it has, which a callback spends.
async function startSignIn() {
  identityGeneration++;
  setSignIn({ step: "preparing", error: "" });
  await patchRequesterIdentity();
}

// A permission upgrade asks for a new link by stamping the MarketIdentity
// (socialweb r134 spec.signInRequestedAt, its own field manager): the spec
// change reissues the URL at once, where clearing status.pendingAction waited
// for the 15 min expiry. Not a new sign-in, so a queued Request VM keeps going.
async function requestSignInLink() {
  const req = signInLinkRequest(SOCIALWEB_API);
  await kcpREST(req.method, req.path, req.body, req.contentType);
  addLog("info", "asked socialweb for a new sign-in link");
}

// Builds before rc110 can reissue a spent URL after a failed callback; clear
// it before the reconcile that callback queued.
async function restartSignIn() {
  try {
    await kcpREST("PATCH", `${SOCIALWEB_API}/marketidentities/requester/status`,
      { status: { pendingAction: null } }, "application/merge-patch+json");
    addLog("info", "asked the PDS for a fresh sign-in URL");
  } catch (err) {
    addLog("warn", `could not reset the sign-in URL: ${err instanceof Error ? err.message : err}`);
  }
}

// No await before openOAuthPopup: window.open has to run inside the tap.
async function openSignInPopup() {
  const url = signInURL(identityState, signInLocal());
  if (!url) throw new Error("the sign-in link is gone; tap Try again for a new one");
  const parsed = new URL(url);
  const expires = identityState?.pendingAction?.expiresAt || "unset";
  addLog("info", `authorize at ${parsed.origin} client_id=${parsed.searchParams.get("client_id")} expires=${expires}`);
  const popup = openOAuthPopup(url);
  setSignIn({ step: "authorizing", url, error: "" });
  let message;
  try {
    message = await popup;
  } catch (err) {
    if (/cancelled/.test(err.message)) {
      setSignIn({ step: "idle" });
      return;
    }
    throw err;
  }
  if (message.type !== OAUTH_CALLBACK_MESSAGE) return;
  // A cancelled or timed-out tab spent nothing; this URL still opens.
  markUsed(url);
  setSignIn({ step: "completing" });
  try {
    await completeOAuth(message);
  } catch (err) {
    await restartSignIn();
    throw err;
  }
}

// The stored session lives in the socialweb vault, which only Go reaches:
// socialwebSignOut (a page-only export) deletes it and drops the held
// session, so the controller starts a fresh authorization. Builds without the
// export can still switch to a named account.
async function signOutIdentity() {
  identityGeneration++;
  setSignIn({ step: "signingOut", error: "" });
  try {
    // As long as a queued Request VM waits for kcp (a slow cold boot).
    await socialwebCall("socialwebSignOut", { workspace: "root", name: "requester" }, 30_000, REQUEST_KCP_WAIT_MS);
  } catch (err) {
    if (!/not available/.test(err.message)) throw err;
    setSignIn({ step: "idle", notice: "This kcp build cannot sign out yet. To use another account, type its handle and tap Switch account." });
    return false;
  }
  addLog("ok", "signed out; the stored session is removed");
  return true;
}

async function switchAccount() {
  identityGeneration++;
  const typed = normalizeHandle(identityHandleEl.value);
  const current = signIn.account?.did === identityState?.did ? normalizeHandle(signIn.account?.handle) : "";
  if (typed && typed !== current && typed !== identityState?.did) return startSignIn();
  if (await signOutIdentity()) {
    setSignIn({ notice: "Signed out. Type the other account's handle, then tap Sign in." });
  } else {
    identityHandleEl.focus();
  }
}

function applyState(state) {
  if (!state) return;
  applyComputeState(state);
  requesterSeen = Boolean(state.marketRequester);
  identityState = state.marketIdentity ?? null;
  if (identityState?.phase === "Ready" && identityState.did) void collectOtherTabInfras(identityState.did);
  if (!requesterSeen) {
    renderIdentity();
    return;
  }
  const identity = identityState;
  const phase = identity?.phase ?? "Pending";
  const action = identity?.pendingAction;
  const summary = `MarketIdentity ${phase}${identity?.handle ? ` ${identity.handle}` : ""}` +
    `${identity?.did ? ` did=${identity.did}` : ""}` +
    `${action ? ` action=${action.kind} expires=${action.expiresAt || "unset"}` : ""}` +
    `${identity?.message ? `: ${identity.message}` : ""}`;
  if (summary !== lastIdentitySummary) {
    lastIdentitySummary = summary;
    addLog("info", summary);
  }
  renderIdentity();

  if (diagramVisible && Array.isArray(state.crds)) {
    const crds = state.crds.map((name) => ({
      metadata: { name },
      spec: { names: { kind: name.split(".")[0] } },
    }));
    const mermaid = buildDiagram(apiServer, crds, [], isNarrow() ? "TD" : "LR");
    if (mermaid !== lastDiagram) {
      lastDiagram = mermaid;
      renderDiagram(mermaid, `${crds.length} CRD${crds.length === 1 ? "" : "s"}`);
    }
  }
}

// Bound at page init, before kcp boots (start()): the status feed can report
// MarketIdentity Ready from restored state before kcp is ready, and a button
// it enables must already have its listener (session 9xc9tc: a Request VM
// click vanished). Until then applyComputeState and renderIdentity keep the
// buttons disabled.
let socialwebUIReady = false;
function initSocialwebUI() {
  if (socialwebUIReady) return;
  const storedMode = localStorage.getItem(identityPrefs.mode);
  identityModeEl.value = storedMode === "localRepo" ? "oauthBrowser" : (storedMode ?? "oauthBrowser");
  if (storedMode === "localRepo") {
    // The local PDS adapter is not wired yet; boot with the supported mode.
    localStorage.setItem(identityPrefs.mode, "oauthBrowser");
  }
  identityHandleEl.value = localStorage.getItem(identityPrefs.handle) ?? "";
  // Typing a handle only relabels the button; Sign in applies it, so a URL
  // issued for the applied handle is never opened for another one.
  identityHandleEl.addEventListener("input", renderIdentity);
  identitySignInEl.addEventListener("click", () => identityAction(identityView?.primary.action));
  identitySecondaryEl.addEventListener("click", () => identityAction(identityView?.secondary?.action));
  initComputeUI();
  // Only now, with every listener bound, may the buttons enable.
  socialwebUIReady = true;
  renderIdentity();
  refreshComputeRequest();
}

// --- compute -----------------------------------------------------------------
// One panel for ComputeContracts. "Request VM" applies a contract for the
// discovered bidders with both shells: ssh over WebRTC (plan 0034; the public
// half of a non-extractable WebCrypto Ed25519 key kept in IndexedDB per
// contract) and, when the served schema has spec.tunnels[].shell, the wootty
// web terminal behind opentunnel (plan 0032; a browser-made token written to
// the vault bundle the guest fetches through secretsRef, kept in localStorage
// by contract name). Every contract from the status feed is listed with its
// phase, a Shell button and its own Release button; a toast says when a
// shell is ready. Shell tries ssh over WebRTC in the main terminal first and
// opens the wootty link when WebRTC cannot connect. One VM at a time:
// Request stays disabled while a contract is active, so repeated clicks
// cannot rent more. ?sshTestPeer=http://127.0.0.1:7795 adds a button that
// connects to contrib/wasm/sshclient/testpeer instead of a guest. Nothing
// here loads kubectl: kcpREST talks to kcp directly.

const computeRequestEl = document.getElementById("compute-request");
const computeStatusEl = document.getElementById("compute-status");
const computeListEl = document.getElementById("compute-list");
const vmshellIngressEl = document.getElementById("compute-ingress");
const computePolicyEl = document.getElementById("compute-policy");
let lastPolicySummary = "";
const computeTestPeerEl = document.getElementById("compute-testpeer");
// The atirc agent opt-in (plan 0035), on unless unchecked; shown once the
// served ComputeContract schema has spec.agent.
const computeAgentRowEl = document.getElementById("compute-agent-row");
const computeAgentEl = document.getElementById("compute-agent");
computeAgentEl.checked = localStorage.getItem("socialweb.compute.agent") !== "0";
computeAgentEl.addEventListener("change", () => {
  localStorage.setItem("socialweb.compute.agent", computeAgentEl.checked ? "1" : "0");
});
// R2 guest tools: shown once the served schema has spec.guestTools; off by default.
const computeGuestToolsRowEl = document.getElementById("compute-guesttools-row");
const computeGuestToolsEl = document.getElementById("compute-guesttools");
computeGuestToolsEl.checked = localStorage.getItem("socialweb.compute.guestTools") === "1";
computeGuestToolsEl.addEventListener("change", () => {
  localStorage.setItem("socialweb.compute.guestTools", computeGuestToolsEl.checked ? "1" : "0");
});
// Associate DID (plan 0036 P1): optional, remembered per viewer.
const computeAssociateEl = document.getElementById("compute-associate");
try {
  computeAssociateEl.value = localStorage.getItem("socialweb.compute.associate") ?? "";
} catch {
  // no localStorage: the field starts empty
}
computeAssociateEl.addEventListener("change", () => {
  try {
    localStorage.setItem("socialweb.compute.associate", computeAssociateEl.value.trim());
  } catch {
    // not remembered
  }
});
const toastEl = document.getElementById("toast");
const computePrefs = {
  token: (name) => `socialweb.vmshell.token.${name}`,
  transport: (name) => `socialweb.compute.transport.${name}`,
};
// Contracts whose "ready" toast was shown in this tab.
const computeToasted = new Set();
// Contracts whose next ssh dial falls back to wootty when WebRTC cannot connect.
const shellFallback = new Set();
const sshTestPeer = new URLSearchParams(location.search).get("sshTestPeer");
const feedWatchers = new Set();
let lastFeedState = null;
let computeBusy = false;
let computeReleasing = false;
let computeLastRender = "";
// Contract name -> the spec.releaseRequestedAt this tab last sent.
const computeReleaseAsked = new Map();
// Contracts already marked Released in the tab infra after a terminal phase.
const infraAutoReleased = new Set();
let infraAutoSync = false;

// socialwebCall invokes a page-only Go export through kcp_worker.js.
async function socialwebCall(fn, payload, timeoutMs = 30_000, readyWaitMs = undefined) {
  const worker = await kcpWorkerReady(readyWaitMs);
  const id = nextPageRequestID--;
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      if (pendingPageRequests.delete(id)) reject(new Error(`${fn} timed out`));
    }, timeoutMs);
    pendingPageRequests.set(id, { resolve, reject, timer });
    worker.postMessage({ type: "socialweb-call", id, fn, payload: JSON.stringify(payload) });
  }).then((res) => {
    if (res?.error) throw new Error(String(res.error));
    return res;
  });
}

// One EphemeralInfra per tab: the object name is also the atproto record rkey,
// so the origin and a stable per-tab id survive a reload without making tabs
// fight over one record.
const INFRA_TAB_KEY = "socialweb.infraTab";
const INFRA_RECORD_POLL_MS = 750;
const infraTabFallback = vmshell.randomTabId();
let infraPatchQueue = Promise.resolve();

function infraTabId() {
  try {
    let id = sessionStorage.getItem(INFRA_TAB_KEY);
    if (!id) {
      id = vmshell.randomTabId();
      sessionStorage.setItem(INFRA_TAB_KEY, id);
    }
    return id;
  } catch {
    return infraTabFallback;
  }
}

function kcpStatus(err) {
  return Number(err?.status ?? 0);
}

// Serialize page-side infra writes: Request VM, Release and terminal
// reconciliation all replace spec.contracts whole (an atomic list), so two
// concurrent read-modify-writes lose VMs or a release stamp.
function infraQueued(run) {
  const next = infraPatchQueue.then(run, run);
  infraPatchQueue = next.catch(() => {});
  return next;
}

async function waitInfraGone(path, timeoutMs = 120_000) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    await sleep(500);
    try {
      await kcpREST("GET", path);
    } catch (err) {
      if (kcpStatus(err) === 404) return null;
      throw err;
    }
  }
  throw new Error("the previous EphemeralInfra is still terminating");
}

async function waitInfraRecord(name, did, timeoutMs = 60_000) {
  const path = `${SOCIALWEB_API}/ephemeralinfras/${name}`;
  const deadline = Date.now() + timeoutMs;
  for (;;) {
    const infra = await kcpREST("GET", path);
    const error = vmshell.recordSyncError(infra);
    if (error) throw new Error(error);
    if (vmshell.recordSynced(infra) && vmshell.infraRecordURI(infra, did, name)) return infra;
    if (Date.now() >= deadline) {
      throw new Error(`EphemeralInfra ${name} did not publish its record in time`);
    }
    await sleep(INFRA_RECORD_POLL_MS);
  }
}

// This tab's EphemeralInfra. GET only creates on 404; every other failure is
// thrown so a transient kcp/PDS error cannot orphan the tab's VMs in a new
// object. Existing record bindings are repaired, and the record must be
// synced before the caller adds its first contract (the first sync pulls an
// existing record and would otherwise erase it).
async function sessionInfra(onStep = () => {}, expectDid = "", expectGen = identityGeneration) {
  const did = identityState?.phase === "Ready" ? identityState.did : "";
  if (!did) throw new Error("sign in before requesting a VM");
  if (expectDid && !identityReadyFor(expectDid, expectGen)) throw new Error("the signed-in identity changed or is signing out; request again");
  try {
    sessionStorage.removeItem("socialweb.sessionInfra");
  } catch {
    // no sessionStorage
  }
  const name = vmshell.originInfraName(location.origin, infraTabId());
  const path = `${SOCIALWEB_API}/ephemeralinfras/${name}`;
  const record = vmshell.infraRecordBinding(did);
  const repoRef = record.repoRef;
  let infra = null;
  try {
    infra = await kcpREST("GET", path);
  } catch (err) {
    if (kcpStatus(err) !== 404) throw err;
  }
  if (infra && (infra.metadata?.deletionTimestamp || infra.status?.endedAt)) {
    await kcpREST("DELETE", path).catch((err) => {
      if (kcpStatus(err) !== 404) throw err;
    });
    infra = await waitInfraGone(path);
  }
  if (infra) {
    const binding = infra.spec?.record;
    if (binding?.uri || (binding?.repoRef?.name && binding.repoRef.name !== repoRef.name)) {
      await kcpREST("DELETE", path).catch((err) => {
        if (kcpStatus(err) !== 404) throw err;
      });
      infra = await waitInfraGone(path);
    } else if (vmshell.infraRecordStale(binding)) {
      infra = await infraQueued(() => vmshell.composeInfra({
        rest: kcpREST,
        api: SOCIALWEB_API,
        infra: name,
        update: (spec) => ({ ...spec, record }),
      }));
    }
  }
  if (!infra) {
    // Create only if absent: a 409 reads it and re-applies the full spec
    // with its resourceVersion (vmshell.createInfra).
    const spec = vmshell.sessionInfraManifest(name, undefined, record).spec;
    infra = await infraQueued(() => vmshell.createInfra({ rest: kcpREST, api: SOCIALWEB_API, name, spec }));
    addLog("info", `EphemeralInfra ${name} holds this tab's VMs`);
  }
  onStep("syncing its record");
  const synced = await waitInfraRecord(name, did);
  addLog("info", `EphemeralInfra ${name} record ${vmshell.infraRecordURI(synced, did, name)}`);
  return synced;
}

// Other tabs' EphemeralInfras of this origin (vmshell.planInfraGC), once per
// load after the identity is Ready: an infra without a live ComputeContract
// is deleted; one with a live contract keeps running and gets its record
// binding repaired as sessionInfra does (composeInfra, the page's full-spec
// apply). Other origins' infras, this tab's own and ending ones are left
// alone. A failed pass runs again a minute later.
let infraGCState = "";
const INFRA_GC_REBIND_MS = 30_000;
async function collectOtherTabInfras(did) {
  if (infraGCState) return;
  infraGCState = "running";
  try {
    const [infras, contracts] = await Promise.all([
      kcpREST("GET", `${SOCIALWEB_API}/ephemeralinfras`),
      kcpREST("GET", `${SOCIALWEB_API}/computecontracts`),
    ]);
    const plan = vmshell.planInfraGC({
      infras: infras?.items ?? [],
      contracts: (contracts?.items ?? []).map(vmshell.feedContract),
      origin: location.origin,
      tabId: infraTabId(),
      did,
    });
    if (plan.length === 0) addLog("debug", "no other tabs' EphemeralInfras to collect");
    for (const step of plan) {
      const live = step.live.length ? ` (${step.live.join(", ")})` : "";
      try {
        if (step.action === "delete") {
          await kcpREST("DELETE", `${SOCIALWEB_API}/ephemeralinfras/${step.name}`).catch((err) => {
            if (kcpStatus(err) !== 404) throw err;
          });
          void flushKcpSoon("infra GC");
          addLog("info", `EphemeralInfra ${step.name} of another tab deleted: ${step.reason}`);
        } else if (step.action === "rebind-delete") {
          // Its record repo does not resolve: deleting now would orphan the
          // PDS record. Rebind to this identity's repo, wait for the record,
          // and delete only then.
          const settled = await vmshell.rebindThenDelete({
            rest: kcpREST,
            api: SOCIALWEB_API,
            name: step.name,
            did,
            serialize: infraQueued,
            timeoutMs: INFRA_GC_REBIND_MS,
            pollMs: INFRA_RECORD_POLL_MS,
          });
          void flushKcpSoon("infra GC");
          if (settled) {
            addLog("info", `EphemeralInfra ${step.name} of another tab deleted after rebinding its record: ${step.reason}`);
          } else {
            addLog("info", `EphemeralInfra ${step.name} of another tab kept: record unresolved (rebind did not resolve in ${INFRA_GC_REBIND_MS / 1000} s)`);
          }
        } else if (step.action === "rebind") {
          const record = vmshell.infraRecordBinding(did);
          await infraQueued(() => vmshell.composeInfra({
            rest: kcpREST,
            api: SOCIALWEB_API,
            infra: step.name,
            update: (spec) => (vmshell.infraRecordStale(spec.record) ? { ...spec, record } : null),
          }));
          void flushKcpSoon("infra GC");
          addLog("info", `EphemeralInfra ${step.name} of another tab kept and its record rebound: ${step.reason}${live}`);
        } else {
          addLog("info", `EphemeralInfra ${step.name} of another tab left alone: ${step.reason}${live}`);
        }
      } catch (err) {
        addLog("warn", `EphemeralInfra ${step.name} ${step.action} failed: ${err instanceof Error ? err.message : err}`);
      }
    }
    infraGCState = "done";
  } catch (err) {
    addLog("warn", `collecting other tabs' EphemeralInfras failed: ${err instanceof Error ? err.message : err}`);
    setTimeout(() => {
      infraGCState = "";
    }, 60_000);
  }
}

// Sets the state of contract short in the session infra (Requested adds it).
// addContract prunes released entries only when the record reaches 64.
function setInfraContract(infraName, entry, secret) {
  return infraQueued(() => vmshell.composeInfra({
    rest: kcpREST,
    api: SOCIALWEB_API,
    infra: infraName,
    update: (spec) => vmshell.withInfraContract(spec, entry, secret),
  }));
}

// A VM that ends without the Release button (guest exit, bidder release or
// failure) still leaves state Requested in the record. Mark it Released once
// so the record says terminated and the next reconcile does not request it
// again. It is marked like a Release, with a fresh releaseRequestedAt, so
// the infra controller re-asks a Failed contract whose guest may still run
// (the requester's guestMayRun) instead of leaving it held. Each entry is
// read again inside the write queue and only a Requested one is changed
// (vmshell.finishedEntry), so a Release queued meanwhile keeps its stamp.
async function markFinishedInfraContracts(contracts) {
  if (infraAutoSync || !contracts?.length) return;
  const pending = contracts.filter((contract) =>
    (contract.phase === "Released" || contract.phase === "Failed") && !infraAutoReleased.has(contract.name));
  if (pending.length === 0) return;
  const did = identityState?.phase === "Ready" ? identityState.did : "";
  if (!did) return;
  const name = vmshell.originInfraName(location.origin, infraTabId());
  infraAutoSync = true;
  try {
    const infra = await kcpREST("GET", `${SOCIALWEB_API}/ephemeralinfras/${name}`).catch((err) => {
      if (kcpStatus(err) === 404) return null;
      throw err;
    });
    if (!infra) {
      for (const contract of pending) infraAutoReleased.add(contract.name);
      return;
    }
    const matched = new Set();
    for (const entry of vmshell.finishedInfraContracts(infra, pending)) {
      const child = vmshell.infraContractName(name, entry.name);
      matched.add(child);
      await infraQueued(() => vmshell.updateInfraEntry({
        rest: kcpREST,
        api: SOCIALWEB_API,
        infra: name,
        match: (c) => c?.name === entry.name,
        update: (current) => vmshell.finishedEntry(current, pending.find((c) => c.name === child)?.releaseRequestedAt),
        what: entry.name,
      }));
      infraAutoReleased.add(child);
    }
    for (const contract of pending) {
      if (!matched.has(contract.name)) infraAutoReleased.add(contract.name);
    }
  } catch (err) {
    addLog("warn", `marking finished VMs in ${name} failed: ${err instanceof Error ? err.message : err}`);
  } finally {
    infraAutoSync = false;
  }
}

// Request VM's own state: the identity it was clicked for must still be
// signed in (a Sign out may run while the request waits for kcp).
// identityGeneration is bumped synchronously by every Sign in, Switch
// account and Sign out tap; signIn.step alone resets to idle after
// GRACE_MS while kcp may still boot (review page-rc130 e0707955c, A).
let identityGeneration = 0;
function identityReadyFor(did, gen) {
  return Boolean(did) && identityState?.phase === "Ready" && identityState.did === did &&
    signIn.step !== "signingOut" && gen === identityGeneration;
}

// How long a queued click waits for kcp (a slow phone cold boot takes minutes).
const REQUEST_KCP_WAIT_MS = 10 * 60_000;

// The click's control flow (request_vm.js): busy first, wait for kcp, the
// same identity afterwards, and the button state recomputed on every way out.
const runRequest = createRequestRunner({
  getBusy: () => computeBusy,
  setBusy: (busy) => {
    computeBusy = busy;
  },
  kcpUp: () => Boolean(kcpWorker),
  waitKcp: async () => {
    try {
      await kcpWorkerReady(REQUEST_KCP_WAIT_MS);
    } catch (err) {
      throw new Error(kcpGate.state === "waiting"
        ? `kcp did not finish starting in ${REQUEST_KCP_WAIT_MS / 60_000} min; reload the page and request again`
        : String(err?.message ?? err));
    }
  },
  identityReadyFor,
  refresh: () => refreshComputeRequest(),
  status: (text, kind) => setAppStatus(computeStatusEl, text, kind),
  log: (level, message) => addLog(level, message),
});

function requestVM() {
  const did = identityState?.phase === "Ready" ? identityState.did : "";
  const gen = identityGeneration;
  return runRequest({
    did,
    gen,
    prepare: async () => {
      const association = vmshell.associationSubject(computeAssociateEl.value, did);
      if (association.error) return { error: association.error };
      if (association.subject && computeGuestToolsEl.checked && await guestToolsServed()) {
        return { error: vmshell.R2_ASSOCIATES_ITSELF };
      }
      return association;
    },
    request: (association) => requestVMFor(did, gen, association),
  });
}

// The request itself, for the identity did it was clicked for. True once the
// contract is in the infra.
async function requestVMFor(did, gen, association) {
  {
    const sshKeys = [];
    // The infra and its PDS record take a while (~18 s seen on dev); say so.
    const progress = (step) => setAppStatus(computeStatusEl, `requesting a VM: ${step}…`, "warn");
    progress("preparing this tab's infra");
    const infraName = (await sessionInfra((step) => progress(step), did, gen)).metadata.name;
    const short = vmshell.contractName();
    const name = vmshell.infraContractName(infraName, short);
    const wootty = await woottyServed();
    const agent = computeAgentEl.checked && await agentServed();
    const guestTools = computeGuestToolsEl.checked && await guestToolsServed();
    const shells = (wootty ? "ssh over WebRTC and wootty" : "ssh over WebRTC (no wootty in this socialweb)") +
      (agent ? ", and the atirc agent" : "") + (guestTools ? ", with socialweb-computer in the VM" : "") + (association.subject ? `, associated with ${association.subject}` : "");
    addLog("info", `requesting ComputeContract ${name} from discovered bidders with ${shells}`);
    // Before anything is written for the contract (its key, tokens, vault
    // bundle): a sign out meanwhile leaves nothing behind.
    if (!identityReadyFor(did, gen)) throw new Error("signed out while the request ran; nothing was created");
    const key = await webrtcGuest.newSSHKey();
    await webrtcGuest.saveSSHKey(name, key);
    sshKeys.unshift(key.authorized);
    localStorage.setItem(computePrefs.transport(name), "webrtc");
    // The association ref file (or R2's association request) reaches the
    // guest through the same bundle.
    if (wootty || agent || association.subject || guestTools) {
      const woottyToken = wootty ? vmshell.randomToken() : "";
      if (woottyToken) localStorage.setItem(computePrefs.token(name), woottyToken);
      // The requester reads the bundle once and fails a contract whose
      // secretsRef is missing, so it must exist before the contract does.
      await socialwebCall("socialwebVaultPut", {
        workspace: "root",
        mount: vmshell.SECRETS_MOUNT,
        path: vmshell.secretsPath(name),
        bundle: vmshell.secretsBundle({ woottyToken, agent }),
      });
    }
    const { contract, secret } = vmshell.infraContract({ infra: infraName, short, wootty, agent, sshKeys, association: association.subject, guestTools });
    if (!identityReadyFor(did, gen)) {
      // A sign out in the last moments: drop what this request wrote (the
      // vault bundle stays; it is keyed by a contract that never exists).
      void webrtcGuest.deleteSSHKey(name).catch(() => {});
      localStorage.removeItem(computePrefs.transport(name));
      localStorage.removeItem(computePrefs.token(name));
      throw new Error("signed out while the request ran; no contract was created");
    }
    progress("creating the contract");
    await setInfraContract(infraName, contract, secret);
    void flushKcpSoon("Request VM");
    setAppStatus(computeStatusEl, `${name} requested; waiting for bids`, "ok");
    addLog("ok", `ComputeContract ${name} requested from discovered bidders with ${shells}`);
    // Show what is in flight; the user can watch it go Held in the terminal.
    runInTerminal("kubectl get computecontracts");
  }
  // computeBusy clears when the status feed shows the new contract.
  return true;
}

// Every Release (button, Release again, d.release, the demo's leftover
// sweep) sets the contract's EphemeralInfra entry to Released with a fresh
// releaseRequestedAt; the infra controller copies both onto the contract
// (vmshell.requestRelease). The page never writes the ComputeContract.
async function releaseContract(name) {
  const previous = computeReleaseAsked.get(name);
  computeReleaseAsked.set(name, new Date().toISOString()); // hides Release again while in flight
  computeLastRender = "";
  let requestedAt;
  try {
    requestedAt = await vmshell.requestRelease({
      rest: kcpREST,
      api: SOCIALWEB_API,
      name,
      serialize: infraQueued,
    });
    computeReleaseAsked.set(name, requestedAt);
    void flushKcpSoon("Release");
  } catch (err) {
    if (previous === undefined) computeReleaseAsked.delete(name);
    else computeReleaseAsked.set(name, previous);
    setAppStatus(computeStatusEl, String(err.message ?? err), "err");
    return;
  }
  computeLastRender = "";
  addLog("info", `ComputeContract ${name} release requested in its EphemeralInfra entry (releaseRequestedAt ${requestedAt})`);
  void webrtcGuest.deleteSSHKey(name).catch(() => {});
}

// The release runs in this tab's requester: closing the tab mid-release
// leaves the guest running until the bidder's release deadline, and pending
// atirc token revokes or the R2 release cascade stall (rows' state:
// vmshell.releaseWorkPending). A reload resumes them, but warn before the tab
// goes away.
addEventListener("beforeunload", (event) => {
  if (!computeReleasing) return;
  event.preventDefault();
  event.returnValue = "";
});

function computeRow(fed) {
  const name = fed.name;
  // A Release this tab sent shows as requested until the contract carries it.
  const contract = vmshell.withReleaseSent(fed, computeReleaseAsked.get(name));
  const li = document.createElement("li");
  const head = document.createElement("div");
  const title = document.createElement("strong");
  title.textContent = name;
  const phaseEl = document.createElement("span");
  const label = vmshell.phaseLabel(contract);
  phaseEl.className = `phase-${label.phase}`;
  phaseEl.textContent = label.text;
  head.append(title, phaseEl);
  if (vmshell.canReleaseAgain(contract, computeReleaseAsked.get(name))) {
    // A release the requester gave up on (ReleaseFailed): a newer
    // releaseRequestedAt restarts it without a tab reload.
    const again = document.createElement("button");
    again.type = "button";
    again.textContent = "Release again";
    again.addEventListener("click", () => {
      again.disabled = true;
      void releaseContract(name);
    });
    head.append(again);
  }
  if (vmshell.releaseOffered(contract) && !computeReleaseAsked.has(name)) {
    const release = document.createElement("button");
    release.type = "button";
    release.textContent = "Release";
    release.addEventListener("click", () => {
      release.disabled = true;
      void releaseContract(name);
    });
    head.append(release);
  }
  const detail = document.createElement("div");
  detail.className = "detail";
  detail.textContent = [
    contract.chosenDid ? `bidder ${contract.chosenDid}` : "",
    contract.association ? `Associated ${contract.association}` : "",
    contract.associationMessage ? `association: ${contract.associationMessage}` : "",
    vmshell.agentTokenNote(contract),
    ...vmshell.releaseNotes(contract, lastFeedState?.contractEvents ?? []),
    contract.guestRequester ? `R2: ${contract.guestRequester.did} ${contract.guestRequester.state ?? "Pending"}` +
      `${contract.guestRequester.message ? ` (${contract.guestRequester.message})` : ""}` : "",
    contract.secretsFetchedAt ? `secrets fetched ${contract.secretsFetchedAt}` : "",
    vmshell.releasePending(contract) ? "" : contract.message ?? "",
  ].filter(Boolean).join(" · ");
  li.append(head, detail);
  if (vmshell.isActive(contract) && shellsOf(contract).mine) li.append(shellAction(contract));
  return li;
}

// What this browser can open for a contract: ssh over WebRTC once the guest's
// publicKey, fingerprint and host keys are in the feed, and the wootty link
// once its address is. mine: the contract was requested from this browser.
function shellsOf(contract) {
  const name = contract.name;
  const webrtc = localStorage.getItem(computePrefs.transport(name)) === "webrtc";
  const token = localStorage.getItem(computePrefs.token(name)) ?? "";
  const held = contract.phase === "Held";
  return {
    mine: webrtc || Boolean(token),
    webrtc: webrtc && held && webrtcGuest.guestFromState(lastFeedState, name) !== null,
    wootty: Boolean(token),
    link: held ? vmshell.shellLink(contract, token) : "",
  };
}

function shellAction(contract) {
  const el = document.createElement("div");
  const s = shellsOf(contract);
  if (!s.webrtc && !s.link) {
    el.className = "detail";
    if (contract.phase === "Held") el.textContent = "Held; the shells are starting…";
    el.append(...agentAction(contract), ...r2Action(contract));
    return el;
  }
  // SSH over WebRTC runs in the page terminal and falls back to the web shell
  // when it cannot connect; the Web shell link is a plain link, so a tap
  // always opens it (iOS blocks only opens the page starts on its own).
  if (s.webrtc) {
    const button = document.createElement("button");
    button.type = "button";
    button.textContent = "SSH";
    button.title = "ssh over WebRTC in the terminal below; falls back to the web shell";
    button.addEventListener("click", () => openShell(contract.name));
    el.append(button);
  }
  if (s.link) {
    const link = document.createElement("a");
    link.href = s.link;
    link.target = "_blank";
    link.rel = "noopener";
    link.className = "button";
    link.textContent = "Web shell";
    link.addEventListener("click", () => addLog("info", `opening the web shell of ${contract.name}`));
    el.append(link);
  }
  const note = document.createElement("span");
  note.className = "detail";
  note.textContent = s.link ? "" : s.wootty ? " web shell starting (usually 1-3 min after Held)" : "";
  el.append(note, ...agentAction(contract), ...r2Action(contract));
  return el;
}

// The Agent button of a Held spec.agent contract: an outbound agentStart
// ContractEvent the requester publishes and the guest agent turns into
// `systemctl start atirc-agent.service`. Disabled while the last one is not
// Published yet; its phase and message (a requester refusal) show next to it.
function agentAction(contract) {
  const name = contract.name;
  if (contract.phase !== "Held" || !contract.agent || computeReleaseAsked.has(name)) return [];
  const last = (lastFeedState?.contractEvents ?? [])
    .filter((e) => e.contract === name && e.direction === "outbound" && e.nsid === webrtcGuest.NSID_AGENT_START)
    .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)) || a.name.localeCompare(b.name))
    .at(-1);
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = "Agent";
  button.title = "start the atirc agent on the VM (set it up at irc.fedfork.com)";
  button.disabled = Boolean(last) && (last.phase ?? "Pending") === "Pending";
  button.addEventListener("click", async () => {
    button.disabled = true;
    try {
      await createContractEvent(webrtcGuest.agentStartEvent(name, Math.random().toString(36).slice(2, 8)));
      addLog("info", `asked ${name} to start the atirc agent`);
    } catch (err) {
      button.disabled = false;
      setAppStatus(computeStatusEl, `${name}: starting the agent failed: ${err.message ?? err}`, "err");
    }
  });
  const note = document.createElement("span");
  note.className = "detail";
  note.textContent = last ? ` agent ${last.phase ?? "Pending"}${last.message ? `: ${last.message}` : ""}` : "";
  return [button, note];
}

// The Start R2 button (plan 0036 A7): on a Held contract running R2 that
// associates itself, an outbound guest.r2Start ContractEvent asks the guest's
// socialweb-computer to start R2 (with the agent when the Agent box is
// checked). Shown only once the served ContractEvent schema has the NSID and
// spec.r2Start (socialweb rc127).
function r2Action(contract) {
  const name = contract.name;
  if (!r2StartServed || !vmshell.r2StartShown(contract) || computeReleaseAsked.has(name)) return [];
  const last = (lastFeedState?.contractEvents ?? [])
    .filter((e) => e.contract === name && e.direction === "outbound" && e.nsid === webrtcGuest.NSID_R2_START)
    .sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)) || a.name.localeCompare(b.name))
    .at(-1);
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = "Start R2";
  button.title = "start socialweb-computer (R2) on the VM";
  button.disabled = Boolean(last) && (last.phase ?? "Pending") === "Pending";
  button.addEventListener("click", async () => {
    button.disabled = true;
    try {
      await createContractEvent(webrtcGuest.r2StartEvent(name, Math.random().toString(36).slice(2, 8), { agent: computeAgentEl.checked }));
      void flushKcpSoon("Start R2");
      addLog("info", `asked ${name} to start R2`);
    } catch (err) {
      button.disabled = false;
      setAppStatus(computeStatusEl, `${name}: starting R2 failed: ${err.message ?? err}`, "err");
    }
  });
  const note = document.createElement("span");
  note.className = "detail";
  note.textContent = last ? ` R2 ${last.phase ?? "Pending"}${last.message ? `: ${last.message}` : ""}` : "";
  return [button, note];
}

let toastTimer = null;
function showToast(text, onTap = null, ms = 8000) {
  clearTimeout(toastTimer);
  toastEl.textContent = text;
  toastEl.hidden = false;
  toastEl.onclick = () => {
    hideToast();
    onTap?.();
  };
  if (ms) toastTimer = setTimeout(hideToast, ms);
}

function hideToast() {
  clearTimeout(toastTimer);
  toastEl.hidden = true;
}

const contractNamed = (state, name) => (state?.contracts ?? []).find((c) => c.name === name);

// Shell: ssh over WebRTC in the main terminal when it is ready (falling back
// to wootty if WebRTC cannot connect), else the wootty web shell.
function openShell(name) {
  hideToast();
  const contract = contractNamed(lastFeedState, name);
  if (contract && shellsOf(contract).webrtc) {
    shellFallback.add(name);
    if (!runInTerminal(`ssh ${name}`)) shellFallback.delete(name);
    return;
  }
  if (!openWootty(name)) setAppStatus(computeStatusEl, `${name}: no shell is ready yet`, "warn");
}

function openLink(link) {
  const w = globalThis.open(link, "_blank");
  if (w) {
    w.opener = null;
    return;
  }
  // Popup blocked (an open that does not follow a tap): let a tap do it.
  addLog("info", "the browser blocked opening the web shell; showing a tap-to-open notice");
  showToast("WebRTC could not connect. Tap here to open the web shell (or use Web shell on the VM's row).",
    () => globalThis.open(link, "_blank"), 60_000);
}

// Opens the contract's wootty link, or waits for its address (the
// opentunnel certificate takes 70-165 s). False when it has no wootty shell.
function openWootty(name, why = "") {
  const token = localStorage.getItem(computePrefs.token(name));
  if (!token) return false;
  const link = vmshell.shellLink(contractNamed(lastFeedState, name), token);
  if (link) {
    addLog("info", `opening the web shell of ${name}${why ? ` (${why})` : ""}`);
    openLink(link);
    return true;
  }
  addLog("info", `${name}: waiting for the web shell address${why ? ` (${why})` : ""}`);
  showToast(`${why ? `${why}. ` : ""}The web shell is still starting (usually 1-3 min); this notice turns into a link when it is ready.`, null, 0);
  void watchFeed((state) => {
    const c = contractNamed(state, name);
    if (!c || !vmshell.isActive(c)) return "gone";
    return vmshell.shellLink(c, token);
  }).then((ready) => {
    if (ready === "gone") hideToast();
    else showToast("The web shell is ready: tap to open it", () => globalThis.open(ready, "_blank"), 60_000);
  });
  return true;
}

// The toast for a contract of this browser's whose first shell is usable.
function toastReadyShells(contracts) {
  for (const c of contracts) {
    if (computeToasted.has(c.name) || !vmshell.isActive(c)) continue;
    const s = shellsOf(c);
    if (!s.mine || (!s.webrtc && !s.link)) continue;
    computeToasted.add(c.name);
    showToast(`${c.name} is ready: tap to open a shell`, () => openShell(c.name));
  }
}

// The served ComputeContract schema decides whether wootty can be asked for
// (socialweb rc109 dropped spec.tunnels[].shell; the lead's rc110 restores
// it next to webrtc) and whether the agent can (plan 0035 spec.agent). Read
// once through kcpREST, retried after an error.
// The ContractEvent schema (same export) gates the Start R2 button.
const servedSchemas = new Map();
function servedSchema(resource) {
  const provider = "/clusters/root:socialweb-provider";
  if (!servedSchemas.has(resource)) {
    servedSchemas.set(resource, (async () => {
      const exported = await kcpREST("GET", `${provider}/apis/apis.kcp.io/v1alpha2/apiexports/computecontracts`);
      const schema = (exported?.spec?.resources ?? []).find((r) => r.name === resource)?.schema;
      if (!schema) return null;
      return await kcpREST("GET", `${provider}/apis/apis.kcp.io/v1alpha1/apiresourceschemas/${schema}`);
    })().catch((err) => {
      // undefined (not null: "not served"): the next feed update asks again.
      servedSchemas.delete(resource);
      addLog("warn", `could not read the ${resource} schema; the features it gates (wootty, agent, R2) are off until it is read: ${err.message ?? err}`);
      return undefined;
    }));
  }
  return servedSchemas.get(resource);
}
const contractSchema = () => servedSchema("computecontracts");
// null until the served ContractEvent schema was read once.
let r2StartServed = null;
async function woottyServed() {
  return vmshell.schemaHasShell(await contractSchema());
}
async function agentServed() {
  return vmshell.schemaHasAgent(await contractSchema());
}
async function guestToolsServed() {
  return vmshell.schemaHasGuestTools(await contractSchema());
}

/** Resolves with fn's first truthy result over the current and later feed snapshots. */
function watchFeed(fn) {
  return new Promise((resolve, reject) => {
    const watcher = (state) => {
      try {
        const value = fn(state);
        if (value) {
          feedWatchers.delete(watcher);
          resolve(value);
        }
      } catch (err) {
        feedWatchers.delete(watcher);
        reject(err);
      }
    };
    feedWatchers.add(watcher);
    if (lastFeedState) watcher(lastFeedState);
  });
}

// Creates a ContractEvent through kcpREST, so a shell never loads kubectl.
async function createContractEvent(manifest) {
  await kcpREST("POST", `${SOCIALWEB_API}/contractevents`, manifest);
}

// Runs a command line in the main terminal as if typed (the panel's Connect).
function runInTerminal(command) {
  term.focus();
  if (!ready || busy || stdinMode) {
    setAppStatus(computeStatusEl, `the terminal is busy; run: ${command}`, "warn");
    return false;
  }
  replaceLine(command);
  submit();
  return true;
}

// --- ssh -----------------------------------------------------------------------
// The shell's `ssh` (ssh.wasm in ssh_worker.js): hosts are ComputeContract
// names, ~/.ssh/config is seeded with "Host vmshell-* / ProxyCommand
// kcp-webrtc %h %p", and kcp-webrtc is this page dialing the guest over a
// WebRTC datachannel. Only public material is written to ~/.ssh (config,
// known_hosts from status.contract.hostKeys, <contract>.pub); the private
// key is the contract's non-extractable WebCrypto key in IndexedDB, and the
// shell filesystem (persisted to localStorage) never sees it.

const sshDir = `${homeDir}/.ssh`;
// While an interactive ssh runs it owns the main terminal's input.
let sshSession = null;
let testPeerKey = null;

function latin1Bytes(value) {
  if (!value) return null;
  if (typeof value !== "string") return value.length ? value : null;
  const bytes = new Uint8Array(value.length);
  for (let i = 0; i < value.length; i++) bytes[i] = value.charCodeAt(i) & 0xff;
  return bytes.length ? bytes : null;
}

async function sshResolve(host) {
  const target = sshCmd.resolveHost(lastFeedState, host, { testPeer: Boolean(sshTestPeer) });
  let key;
  let hostKeys;
  if (target.kind === "testpeer") {
    testPeerKey ??= await webrtcGuest.newSSHKey();
    key = testPeerKey;
    hostKeys = (await webrtcGuest.httpSignaling(sshTestPeer, key.authorized).guest()).hostKeys;
  } else {
    key = await webrtcGuest.loadSSHKey(host);
    if (!key) throw new Error("this browser holds no SSH key for the contract (it was requested elsewhere)");
    hostKeys = target.contract.hostKeys ?? [];
    if (hostKeys.length === 0) throw new Error("the guest has not reported its host keys yet");
  }
  const khPath = `${sshDir}/known_hosts`;
  let known = await bash.fs.readFile(khPath).catch(() => "");
  // The test peer makes a new host key per run; real guests never get
  // their lines rewritten.
  if (target.kind === "testpeer") known = sshCmd.dropKnownHost(known, host);
  const merged = sshCmd.mergeKnownHosts(known, host, hostKeys);
  await bash.fs.writeFile(khPath, merged);
  await bash.fs.writeFile(`${sshDir}/${host}.pub`, `${key.authorized}\n`);
  return { publicKey: key.raw, knownHosts: merged, key: key.privateKey };
}

async function sshDial(host, port, status, onEof) {
  if (port !== 22) throw new Error(`no webrtc tunnel for port ${port} (only ssh on 22)`);
  const target = sshCmd.resolveHost(lastFeedState, host, { testPeer: Boolean(sshTestPeer) });
  const signaling = target.kind === "testpeer"
    ? webrtcGuest.httpSignaling(sshTestPeer, testPeerKey.authorized)
    : webrtcGuest.contractEventSignaling({ contract: host, create: createContractEvent, watch: watchFeed });
  // Only a Shell tap falls back; a typed ssh just reports the error.
  const fallback = shellFallback.delete(host);
  try {
    const logged = (message) => {
      addLog("info", `ssh ${host} over WebRTC: ${message}`);
      status(message);
    };
    return await webrtcGuest.dialGuest({ signaling, tag: "ssh", status: logged, onEof });
  } catch (err) {
    if (fallback && err.connectivity && openWootty(host, "WebRTC could not connect")) {
      throw new Error(`${err.message}\r\n` +
        "WebRTC could not connect (common when this device and the VM's bidder share a Wi-Fi network).\r\n" +
        "Opening the web shell instead: if no tab opens, tap the notice at the bottom or the Web shell link on the VM's row.");
    }
    throw err;
  }
}

async function runSsh(args, ctx) {
  await bash.fs.mkdir(sshDir, { recursive: true }).catch(() => {});
  let config = await bash.fs.readFile(`${sshDir}/config`).catch(() => null);
  if (config === null || sshCmd.OLD_SSH_CONFIGS.includes(config)) {
    config = sshCmd.DEFAULT_SSH_CONFIG;
    await bash.fs.writeFile(`${sshDir}/config`, config);
  }
  // A terminal stdout (ssh last in its pipeline, not redirected) streams to
  // the terminal; otherwise output is buffered for the pipeline.
  const toTerminal = ttyTool === "ssh";
  const stdin = latin1Bytes(ctx.stdin);
  const interactive = toTerminal && !stdin;
  const decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
  const buffered = { stdout: "", stderr: "" };
  const write = (stream, u8) => {
    if (toTerminal) term.write(u8);
    else buffered[stream] += decoders[stream].decode(u8, { stream: true });
  };
  const verboseErr = (text) => write("stderr", new TextEncoder().encode(`debug1: kcp-webrtc: ${text}\n`));
  const worker = new Worker(new URL("./ssh_worker.js", import.meta.url), { type: "module" });
  let dialed = null;
  return await new Promise((resolve) => {
    let raw = false;
    let done = false;
    const finish = (code) => {
      if (done) return;
      done = true;
      worker.terminate();
      dialed?.close();
      sshSession = null;
      if (toTerminal && raw) term.write("\r\n");
      resolve({ stdout: buffered.stdout, stderr: buffered.stderr, exitCode: code });
    };
    ctx.signal?.addEventListener("abort", () => finish(130));
    if (interactive) {
      sshSession = {
        // With a pty every key goes to the guest (Ctrl-C included); without
        // one, Ctrl-C ends ssh here and Ctrl-D closes its stdin.
        key(data) {
          if (!raw && data === "\u0003") return finish(130);
          if (!raw && data === "\u0004") return worker.postMessage({ type: "stdinEOF" });
          worker.postMessage({ type: "input", data: new TextEncoder().encode(data) });
        },
        resize: (cols, rows) => worker.postMessage({ type: "resize", cols, rows }),
      };
    }
    const reply = (id, value, transfer = []) => worker.postMessage({ type: "reply", id, ...value }, transfer);
    worker.onmessage = async (event) => {
      const m = event.data ?? {};
      if (m.type === "stdout" || m.type === "stderr") write(m.type, m.data);
      else if (m.type === "raw") raw = m.on;
      else if (m.type === "exit") finish(m.code);
      else if (m.type === "addKnownHost") {
        const path = `${sshDir}/known_hosts`;
        const text = await bash.fs.readFile(path).catch(() => "");
        await bash.fs.writeFile(path, `${text}${text && !text.endsWith("\n") ? "\n" : ""}${m.line}\n`);
      } else if (m.type === "resolve") {
        try {
          reply(m.id, await sshResolve(m.host));
        } catch (err) {
          reply(m.id, { error: String(err.message ?? err) });
        }
      } else if (m.type === "dial") {
        try {
          dialed = await sshDial(m.host, m.port, m.verbose ? verboseErr : () => {},
            () => worker.postMessage({ type: "eof" }));
          reply(m.id, { port: dialed.port }, [dialed.port]);
        } catch (err) {
          reply(m.id, { error: String(err.message ?? err) });
        }
      }
    };
    worker.postMessage({
      type: "run",
      execUrl: new URL("/wasm_exec.js", location.href).href,
      wasmUrl: new URL("/ssh.wasm", location.href).href,
      cfg: { argv: args, config, interactive, stdin, cols: term.cols, rows: term.rows },
    });
  });
}

// The PolicyEngine's fenced sandbox (plan 0037): Fenced and Ready come from
// the resource (the probe's facts are the Fenced message).
function renderPolicyEngine(engine) {
  const { text, className } = policyEngineStatus(engine);
  if (text === lastPolicySummary) return;
  lastPolicySummary = text;
  setAppStatus(computePolicyEl, text, className);
  if (engine) addLog("info", `PolicyEngine ${engine.name} ${engine.phase ?? "Pending"} ready=${Boolean(engine.ready)} fenced=${engine.fenced ?? "unset"}: ${engine.message ?? ""}`);
}

// The Request VM button's state for a feed state: one VM at a time, only
// signed in, not while a request runs, and only once its listener is bound.
function computeRequestDisabled(state) {
  const active = (state?.contracts ?? [])
    .map((c) => vmshell.withReleaseSent(c, computeReleaseAsked.get(c?.name)))
    .filter(vmshell.isActive);
  // A failed kcp gate (taken over by another tab): nothing can run here.
  return !socialwebUIReady || computeBusy || kcpGate.state === "failed" ||
    state?.marketIdentity?.phase !== "Ready" || active.length > 0;
}
function refreshComputeRequest() {
  computeRequestEl.disabled = computeRequestDisabled(lastFeedState);
}

// The last contracts phase/step fingerprint (vmshell.contractTransitions).
let lastContractTransitions = null;
function applyComputeState(state) {
  lastFeedState = state;
  // Session 5ne4ov: Held, written by the requester 2 s before a reload, sat
  // in kcp's persist coalescer and was lost. A phase or step change is
  // flushed once per feed update (flushKcpSoon coalesces).
  const transitions = vmshell.contractTransitions(lastContractTransitions, state.contracts);
  lastContractTransitions = transitions.key;
  if (transitions.changed) void flushKcpSoon("contract status");
  renderPolicyEngine(state.policyEngine);
  for (const watcher of [...feedWatchers]) watcher(state);
  const contracts = state.contracts ?? [];
  void markFinishedInfraContracts(contracts);
  const seen = contracts.map((c) => vmshell.withReleaseSent(c, computeReleaseAsked.get(c?.name)));
  const active = seen.filter(vmshell.isActive);
  if (computeBusy && active.length > 0) computeBusy = false;
  computeReleasing = seen.some(vmshell.releaseWorkPending);
  const ready = state.marketIdentity?.phase === "Ready";
  computeRequestEl.disabled = computeRequestDisabled(state);
  if (ready && computeAgentRowEl.hidden) void agentServed().then((served) => { computeAgentRowEl.hidden = !served; });
  if (ready && computeGuestToolsRowEl.hidden) void guestToolsServed().then((served) => { computeGuestToolsRowEl.hidden = !served; });
  if (ready && r2StartServed === null) {
    r2StartServed = false;
    void servedSchema("contractevents").then((schema) => {
      if (schema === undefined) {
        r2StartServed = null; // read failed: ask again on the next update
        return;
      }
      r2StartServed = webrtcGuest.schemaHasR2Start(schema);
      if (r2StartServed) applyComputeState(lastFeedState);
    });
  }
  if (!computeBusy && !computeStatusEl.classList.contains("err")) {
    setAppStatus(computeStatusEl,
      !ready ? "sign in to request a VM"
        : active.length > 0 ? `release ${active.map((c) => c.name).join(", ")} to request another VM`
        : "ready to request a VM",
      !ready ? "warn" : "ok");
  }
  const render = JSON.stringify(contracts) + [...computeReleaseAsked].join() +
    JSON.stringify((state.contractEvents ?? []).map((e) => [e.name, e.phase, e.message]));
  if (render === computeLastRender) return;
  for (const c of contracts) {
    addLog("info", `ComputeContract ${c.name} ${c.phase ?? "Pending"}${c.release ? " (release asked)" : ""}${c.message ? `: ${c.message}` : ""}`);
  }
  computeLastRender = render;
  computeListEl.replaceChildren(...vmshell.orderContracts(contracts).map(computeRow));
  toastReadyShells(contracts);
}

function initComputeUI() {
  localStorage.removeItem("socialweb.vmshell.bidders");
  computeRequestEl.addEventListener("click", () => {
    computeStatusEl.classList.remove("err");
    void requestVM();
  });
}

// The test peer needs no kcp, so it is wired before the page boots.
if (sshTestPeer) {
  computeTestPeerEl.hidden = false;
  computeTestPeerEl.addEventListener("click", () => runInTerminal(`ssh ${sshCmd.TEST_PEER_HOST}`));
}

// --- ingress relay -------------------------------------------------------------
// Ingress-mode Exposures (the requester's svc-requester-requester-ingress,
// which serves getSecrets to the guest) are reachable at
// https://<did label>.<relay>. kcp_worker.js holds their relay subscriptions
// (ingress_manager.js) and posts status; the page only renders it.

function renderIngress(entries) {
  vmshellIngressEl.textContent = entries.map((entry) => {
    const detail = [entry.state];
    if (entry.closeCode) detail.push(`close ${entry.closeCode}`);
    if (entry.lastError) detail.push(entry.lastError);
    return `${entry.name}: ${entry.url} (${detail.join(", ")})`;
  }).join("\n");
}

// --- startup ---------------------------------------------------------------

async function start() {
  startDebugControl();
  // One kcp per origin: wait here while another tab of this browser runs it.
  await acquireKcpLock();
  // Before kcp boots (its first persist): later writes of a tab that loses
  // the state are refused.
  await claimStateOwner();
  term.writeln(cyan("kcp-wasm") + dim(" loading real kcp.wasm…"));
  term.writeln(cyan("kubectl-wasm") + dim(lowMemory ? " loads on first use (low-memory mode)" : " loading kubectl.wasm…"));
  setStatus("loading kcp + kubectl…", "running");
  // kcp boots for tens of seconds; download and compile kubectl meanwhile.
  // goat/yq follow kubectl at low priority, or load on first use.
  if (lowMemory) {
    addLog("info", "low-memory mode: kubectl, goat and yq on first use, no boot commands, no snapshot");
    await spawnKcp();
  } else {
    const kubectlLoaded = spawnKubectl();
    kubectlLoaded.then(ensureCli).catch(() => {});
    await Promise.all([spawnKcp(), kubectlLoaded]);
  }

  term.writeln(dim("loading just-bash shell…"));
  await restoreShell();

  ready = true;
  retryEl.hidden = true;
  setStatus("connected", "connected");
  term.writeln(dim(`kcp + kubectl + goat + yq running in this browser tab (api ${apiServer})`));
  term.writeln(dim("type 'help' for examples; Ctrl-C cancels a running command"));
  prompt();
  term.focus();

  void poll();
  setInterval(() => void poll(), Math.max(intervalMs, 5000));
  void typeBootSteps(BOOT_STEPS);
}

// Dropping a manifest runs `apply -f -` with the file contents as stdin.
const terminalPaneEl = document.getElementById("terminal-pane");
terminalPaneEl.addEventListener("dragover", (event) => {
  event.preventDefault();
});
terminalPaneEl.addEventListener("drop", async (event) => {
  event.preventDefault();
  const file = event.dataTransfer?.files?.[0];
  if (!file) return;
  if (busy || stdinMode || !ready) {
    addLog("warn", "busy; cannot apply the dropped manifest right now");
    return;
  }
  const text = await file.text();
  term.focus();
  term.write(
    `\r\n${promptText()}kubectl apply -f - ${dim(`(dropped ${file.name}, ${text.length} bytes)`)}\r\n`,
  );
  void runScript("kubectl apply -f -", text);
});

// --- input -----------------------------------------------------------------

term.onResize(({ cols, rows }) => sshSession?.resize(cols, rows));

term.onData((data) => handleTermData(data));

function handleTermData(data) {
  if (sshSession) {
    sshSession.key(data);
    return;
  }
  if (stdinMode) {
    if (data === "\u0003") {
      abortStdin();
      return;
    }
    if (data === "\u0004") {
      finishStdin();
      return;
    }
    handleStdinData(data);
    return;
  }

  if (busy && data !== "\u0003") return;

  if (data === "\r" || data === "\n") {
    if (!busy) submit();
    return;
  }
  if (data === "\u0003") {
    if (booting) return;
    cancelRunning();
    return;
  }
  if (busy) return;
  if (data === "\u007f") {
    if (cursor > 0) {
      line = line.slice(0, cursor - 1) + line.slice(cursor);
      cursor--;
      redraw();
    }
    return;
  }
  if (data === "\u001b[3~") {
    if (cursor < line.length) {
      line = line.slice(0, cursor) + line.slice(cursor + 1);
      redraw();
    }
    return;
  }
  if (data === "\u001b[D") {
    if (cursor > 0) {
      cursor--;
      term.write("\u001b[D");
    }
    return;
  }
  if (data === "\u001b[C") {
    if (cursor < line.length) {
      cursor++;
      term.write("\u001b[C");
    }
    return;
  }
  if (data === "\u001b[H" || data === "\u001b[1~") {
    if (cursor > 0) {
      cursor = 0;
      redraw();
    }
    return;
  }
  if (data === "\u001b[F" || data === "\u001b[4~") {
    if (cursor < line.length) {
      cursor = line.length;
      redraw();
    }
    return;
  }
  if (data === "\u000c") {
    term.clear();
    prompt();
    return;
  }
  if (data === "\u0001") {
    cursor = 0;
    redraw();
    return;
  }
  if (data === "\u0005") {
    cursor = line.length;
    redraw();
    return;
  }
  if (data === "\u0015") {
    line = line.slice(cursor);
    cursor = 0;
    redraw();
    return;
  }
  if (data === "\u0017") {
    deleteWordBeforeCursor();
    return;
  }
  if (data === "\t") {
    void completeLine();
    return;
  }
  if (data === "\u001b[A") {
    if (history.length === 0) return;
    historyIndex = Math.max(0, historyIndex - 1);
    replaceLine(history[historyIndex] ?? "");
    return;
  }
  if (data === "\u001b[B") {
    if (history.length === 0) return;
    historyIndex = Math.min(history.length, historyIndex + 1);
    replaceLine(history[historyIndex] ?? "");
    return;
  }
  if (data.startsWith("\u001b")) return;

  let text = "";
  for (let index = 0; index < data.length; index++) {
    const ch = data[index];
    if (ch === "\r" || ch === "\n") {
      insertText(text);
      text = "";
      submit();
      const rest = data.slice(index + 1);
      if (rest) {
        if (stdinMode) handleStdinData(rest);
        else insertText(rest);
      }
      return;
    }
    if (ch >= " ") text += ch;
  }
  insertText(text);
}

// --- remote debug control (dev server only) ---------------------------------
// The dev server started with --debug-control streams operator commands for
// this session (debugSession) at /debug/control. Each is {id, js}: the body of
// an async function run with `d` (the handle below) in scope; its result or
// error goes to the debug log as "result <id> …". A static host answers 404
// and the page never connects again.
const debugHandle = {
  session: debugSession,
  type: (text) => handleTermData(text),
  run: (line) => handleTermData(`${line}\r`),
  state: () => lastFeedState,
  rest: (method, path, body, contentType) => kcpREST(method, path, body, contentType),
  release: (name) => releaseContract(name),
  call: (fn, payload, timeoutMs) => socialwebCall(fn, payload, timeoutMs),
  click: (selector) => {
    const el = document.querySelector(selector);
    if (!el) throw new Error(`no element ${selector}`);
    el.click();
    return el.textContent?.trim() ?? "";
  },
  text: (selector = "body") => document.querySelector(selector)?.innerText ?? null,
  set: (selector, value) => {
    const el = document.querySelector(selector);
    if (!el) throw new Error(`no element ${selector}`);
    el.value = value;
    el.dispatchEvent(new Event("input", { bubbles: true }));
    el.dispatchEvent(new Event("change", { bubbles: true }));
    return true;
  },
  screen: () => {
    const buf = term.buffer.active;
    const out = [];
    for (let i = Math.max(0, buf.length - term.rows); i < buf.length; i++) out.push(buf.getLine(i)?.translateToString(true) ?? "");
    return out.join("\n");
  },
  log: (message) => addLog("info", `debug: ${message}`),
  lock: () => kcpLock.state,
  // kcp's held writes now, as a phase change or an action would.
  flush: () => flushKcpSoon("debug").then(() => "flushed"),
  banners: () => banners.ids().map((id) => [id, banners.text(id)]),
  // Flushes kcp's held writes first (at most 3 s): a reload does not wait
  // for the pagehide flush.
  reload: (query) => {
    debugSend("info", "debug: reloading");
    debugFlush();
    const go = () =>
      setTimeout(() => {
        if (query === undefined) location.reload();
        else location.search = query;
      }, 300);
    Promise.race([flushKcpSoon("reload"), sleep(3000)]).then(go, go);
    return "reloading";
  },
  // Wipe this origin's saved state (what "clear website data" would do for
  // the page) and reload: localStorage except the debug switches, and every
  // IndexedDB database and the OPFS snapshots.
  reset: async () => {
    const keep = ["kcp.debuglog", "kcp.debugGo", "kcp.lowmem"].map((k) => [k, localStorage.getItem(k)]);
    localStorage.clear();
    for (const [k, v] of keep) if (v !== null) localStorage.setItem(k, v);
    const dbs = typeof indexedDB.databases === "function" ? await indexedDB.databases() : [];
    for (const db of dbs) if (db.name) indexedDB.deleteDatabase(db.name);
    try {
      const root = await navigator.storage.getDirectory();
      for await (const name of root.keys()) await root.removeEntry(name, { recursive: true });
    } catch {
      // no OPFS
    }
    debugSend("info", `debug: reset; deleted ${dbs.map((db) => db.name).join(", ") || "no"} IndexedDB databases`);
    return debugHandle.reload();
  },
};

// The stream is reopened with backoff after errors, a stalled open and a
// silent stream (debug_link.js ControlStream); a server without
// --debug-control (404 before the first open) is left alone.
function startDebugControl() {
  if (!debugLog || typeof EventSource !== "function" || debugControl) return;
  debugControl = new ControlStream({
    url: `/debug/control?session=${encodeURIComponent(debugSession)}`,
    open: (url) => new EventSource(url),
    probe: () =>
      fetch(`/debug/control?session=probe`, { method: "HEAD", signal: debugTimeout(10_000) }).then((r) => r.status, () => 0),
    log: (what) => debugSend("info", `debug control ${what} for session ${debugSession}`),
    onCommand: runDebugCommand,
  });
  debugControl.start();
}
async function runDebugCommand(data) {
  let cmd;
  try {
    cmd = JSON.parse(data);
  } catch {
    return;
  }
  const id = cmd.id ?? "?";
  let done = [];
  try {
    done = JSON.parse(sessionStorage.getItem("kcp.debugDone") ?? "[]");
  } catch {
    done = [];
  }
  if (done.includes(id)) return;
  try {
    sessionStorage.setItem("kcp.debugDone", JSON.stringify([...done.slice(-200), id]));
  } catch {
    // no sessionStorage: a replayed command may run twice
  }
  try {
    const fn = new Function("d", `return (async () => { ${cmd.js} })();`);
    const value = await fn(debugHandle);
    let text;
    try {
      text = typeof value === "string" ? value : JSON.stringify(value);
    } catch {
      text = String(value);
    }
    debugSend("result", `${id} ok ${text ?? "undefined"}`);
  } catch (err) {
    debugSend("result", `${id} error ${err instanceof Error ? `${err.message}\n${err.stack ?? ""}` : err}`);
  }
  debugFlush();
}

// Touch devices have no Ctrl key: expose the control actions the terminal
// needs on a small toolbar.
document.getElementById("mobile-keys").addEventListener("click", (event) => {
  const action = event.target.closest("button")?.dataset.action;
  if (!action) return;
  term.focus();
  if (sshSession) {
    const keys = { "ctrl-c": "\u0003", "ctrl-d": "\u0004", enter: "\r", tab: "\t", up: "\u001b[A" };
    if (keys[action]) sshSession.key(keys[action]);
    return;
  }
  if (action === "ctrl-c") {
    if (stdinMode) abortStdin();
    else cancelRunning();
    return;
  }
  if (action === "ctrl-d") {
    if (stdinMode) finishStdin();
    return;
  }
  if (busy) return;
  if (stdinMode) {
    if (action === "enter") handleStdinData("\r");
    else if (action === "tab") handleStdinData("\t");
    return;
  }
  if (action === "enter") {
    submit();
  } else if (action === "tab") {
    void completeLine();
  } else if (action === "up") {
    if (history.length > 0) {
      historyIndex = Math.max(0, historyIndex - 1);
      replaceLine(history[historyIndex] ?? "");
    }
  }
});

let lastNarrow = isNarrow();
window.addEventListener("resize", () => {
  if (isNarrow() === lastNarrow) return;
  lastNarrow = isNarrow();
  // Different Mermaid direction changes the diagram text; force a repaint.
  lastDiagram = "";
  void poll();
});

setStatus("starting…", "running");
// Listeners first, outside start(), so no boot step that throws or hangs
// (debug control, the kcp lock, kcp, restoreShell) can skip them: a click on
// a button the feed enables early reaches requestVM / identityAction, which
// wait for kcp (kcpWorkerReady).
try {
  initSocialwebUI();
} catch (err) {
  addLog("error", `binding the identity and compute buttons failed: ${err instanceof Error ? err.message : err}`);
}
start().catch((err) => {
  setStatus("failed", "disconnected");
  retryEl.hidden = false;
  addLog("error", `startup failed: ${err instanceof Error ? err.message : err}`);
  term.writeln(red(`startup failed: ${err instanceof Error ? err.message : err}`));
});