/* 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 // -unreadable-