Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(guardian): restore the recovery-context work a racing commit rolled back

nirholasb59c80492f28
diff --git a/STRUCTURE.md b/STRUCTURE.md
index d24fb321d..59351b14f 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -238,6 +238,7 @@ bottom.
| Agent voice cloning (your voice, on your agent) | Capture + BYOK panel [src/voice/voice-setup.js](src/voice/voice-setup.js) (`VoiceSetup`), mounted as step 5 of the create wizard ([src/create-agent.js](src/create-agent.js) `→ /create-agent`), in the agent editor, and in the talk-mode shell [src/voice/voice-clone-modal.js](src/voice/voice-clone-modal.js); server [api/agents/_id/voice.js](api/agents/_id/voice.js) `→ GET/PUT/DELETE /api/agents/:id/voice` + `POST /api/agents/:id/voice/clone`; credential resolver [api/_lib/agent-voice-key.js](api/_lib/agent-voice-key.js); playback config mapper `agentVoiceConfig` in [src/runtime/speech.js](src/runtime/speech.js), consumed by the hosted embed [pages/agent-embed.html](pages/agent-embed.html) `→ /agent/:id/embed` and the SDK runtime [src/runtime/index.js](src/runtime/index.js) | In-repo · BYOK live, platform lane awaits a key | Record or upload 30+ seconds and the agent speaks in that voice everywhere on three.ws. Three credential lanes, and they are not interchangeable: a clone only exists inside the ElevenLabs account that made it, so the winning lane is recorded on `agent_identities.voice_key_source` and replayed on every synthesis. **BYOK is the activation path today** (no platform `ELEVENLABS_API_KEY` is set on the service), and the panel renders inline key entry rather than a dead "not configured" message; setting that one variable lights up the platform lane, metered to $THREE credits. `/api/tts/eleven` only spends an owner's key when the request names the agent, which is what lets a bound voice speak to signed-out visitors inside a cross-origin embed. Docs: [docs/tutorials/voice-and-lipsync.md](docs/tutorials/voice-and-lipsync.md), [src/voice/README.md](src/voice/README.md). Tests: [tests/api/agents-voice.test.js](tests/api/agents-voice.test.js), [tests/runtime/agent-voice-config.test.js](tests/runtime/agent-voice-config.test.js) |
| Trading Copilot (conversational) | client [src/agent-copilot.js](src/agent-copilot.js), hub tab [src/agent-wallet-hub/tabs/copilot.js](src/agent-wallet-hub/tabs/copilot.js), server [api/agents/copilot.js](api/agents/copilot.js) `→ POST /api/agents/:id/copilot` (SSE) | In-repo | Owner-only chat over an agent's Solana wallet: text/voice in, markdown replies, live **data cards** (portfolio, firewall, quote, smart-money, intel) and **confirm-before-execute** trade/limits cards. Read-only tools run server-side; state-changing intents return as proposals the browser re-quotes and runs through the existing spend guards + firewall + custody audit. Slash commands, copy/regenerate, localStorage persistence. See [docs/trading-copilot.md](docs/trading-copilot.md) |
| Alpha Co-pilot (the agent narrates its own read) | page [pages/alpha-copilot.html](pages/alpha-copilot.html) `→ /alpha-copilot`, client [src/alpha-copilot.js](src/alpha-copilot.js), styles [src/alpha-copilot.css](src/alpha-copilot.css), profile cross-link [src/shared/alpha-copilot-link.js](src/shared/alpha-copilot-link.js), server [api/agents/alpha.js](api/agents/alpha.js) `→ GET /api/agents/:id/alpha/candidates` + `POST /api/agents/:id/alpha/read`, grounding + scrub [api/\_lib/alpha-read.js](api/_lib/alpha-read.js) | Live | The intelligence and voice layer on the same trade rails the Trading Copilot uses: pick a public agent from a real gallery, pick a real live pump.fun mint off the candidate feed, and the agent reads it in character while its `<agent-3d>` avatar speaks the verdict aloud (agent TTS provider, then the free server lane, then browser speech). Every figure it says is validated against the `signals` bundle the server actually fetched (bonding-curve state, a real non-binding reference buy quote for true price impact, graduation progress, smart-money wallets, and for the owner the wallet balance and spend limits); a mismatch replaces the line and raises `hallucination_guard.line_replaced`, which the page surfaces rather than hides. The narrator never signs: acting on a read is an owner-only drawer that re-quotes through `previewAgentTrade` and executes through `executeAgentTrade`, so the spend policy, firewall, and custody audit all still apply. Docs: [docs/alpha-copilot.md](docs/alpha-copilot.md) |
+| Social recovery & inheritance (guardian console) | page [pages/guardian.html](pages/guardian.html) `-> /guardian` + client [src/guardian.js](src/guardian.js), inbox [api/agents/recovery-inbox.js](api/agents/recovery-inbox.js) `-> GET /api/agents/recovery-inbox`, per-agent actions [api/agents/recovery.js](api/agents/recovery.js) `-> /api/agents/:id/recovery/...`, rules [api/_lib/agent-recovery.js](api/_lib/agent-recovery.js), owner-side tab [src/agent-wallet-hub/tabs/recovery.js](src/agent-wallet-hub/tabs/recovery.js), schema [api/_lib/migrations/20260623100000_social_recovery.sql](api/_lib/migrations/20260623100000_social_recovery.sql) | Live | The other side of a locked-out or departed owner. The owner names guardians, an approval threshold and a beneficiary from their agent's wallet hub; the guardians and beneficiaries act from `/guardian`, which lists every agent they are trusted to protect with the open recovery or inheritance process, the reason the requester gave, who has already voted, the safety-window and expiry countdowns, and their own approve / decline / confirm / complete actions. A key is never decrypted or exported: completing a process re-points ownership only. The requester cannot approve their own takeover, an open request freezes autonomous spend, threshold approvals start a 48h time-lock, and the real owner's return cancels the whole thing. Inheritance is a dead-man's switch armed from real owner activity plus a grace window. Docs: [docs/guardian.md](docs/guardian.md), [docs/custody.md](docs/custody.md). Tests: [tests/agent-recovery.test.js](tests/agent-recovery.test.js), [tests/api-agents-recovery-handler.test.js](tests/api-agents-recovery-handler.test.js) |
| Master wallet (per-user custodial hub) | page [pages/wallet.html](pages/wallet.html) `→ /wallet` + controller [src/master-wallet.js](src/master-wallet.js), client [src/wallet-api.js](src/wallet-api.js), styles [public/master-wallet.css](public/master-wallet.css); API [api/user/wallet/index.js](api/user/wallet/index.js) (create + balances), [send.js](api/user/wallet/send.js), [fund-agent.js](api/user/wallet/fund-agent.js), [history.js](api/user/wallet/history.js); schema [master_wallets](api/_lib/migrations/20260730040000_master_wallets.sql) | In-repo | One custodial Solana + EVM keypair per USER account (distinct from per-agent wallets): hold SOL/USDC across Solana and Base, top up any agent you own, send to any Solana address, and read history straight from chain. Session-cookie auth only, so no API key or agent can ever spend it; writes are CSRF-guarded and capped at 5 outbound transfers per user per day. The page prices every send through the server's `simulate` path first and requires an explicit confirm showing recipient, amount, asset and network before anything is signed. NOT [src/wallet.js](src/wallet.js), which connects an external Phantom/Seed-Vault wallet. Docs: [docs/user-wallet.md](docs/user-wallet.md). Tests: [tests/master-wallet-page.test.js](tests/master-wallet-page.test.js) |
| Real-funds risk acknowledgment | gate [public/risk-ack.js](public/risk-ack.js) `→ /legal/risk`, app wrapper [src/shared/risk-ack.js](src/shared/risk-ack.js), record endpoint [api/legal/risk-ack.js](api/legal/risk-ack.js), disclosure [public/legal/risk.html](public/legal/risk.html) | In-repo | Versioned, once-per-browser acceptance dialog every money-committing surface awaits before executing (trade, snipe, withdraw, swap, launch, x402, onramp — devnet exempt). Acceptances persist in `audit_log` (`risk-ack-accept`). See [docs/risk-acknowledgment.md](docs/risk-acknowledgment.md) |
| Global markets + coin detail pages | [pages/coins.html](pages/coins.html) + [src/coins-index.js](src/coins-index.js) `→ /coins`, [pages/coin.html](pages/coin.html) + [src/coin-page.js](src/coin-page.js) `→ /coin/:id`, backend [api/coin/](api/coin) (detail, tickers, ohlc, pool, markets, news, global over [api/_lib/coingecko.js](api/_lib/coingecko.js)) | In-repo | CoinGecko-style markets index (global stats bar, sortable top-coins table, search, sparklines) + a rich detail page per coin: interactive chart with a source switcher (native CoinGecko line chart, TradingView advanced candlesticks, or the DexScreener / GeckoTerminal on-chain terminal — each shown only when it can chart the coin; GeckoTerminal's pool resolved via [api/coin/pool.js](api/coin/pool.js)), 1h→1y price-performance matrix, market-stats grid, circulating/max supply bar with Mcap/FDV ratio, ATH/ATL with drawdown & recovery multiple, community sentiment vote split, community + developer (GitHub) activity grids, a paginated exchange-listings table (`api/coin/tickers`, ±2% depth + trust) linking into exchange detail, related news, and full link pills (site/social/whitepaper/forum/chat/explorers). Design adopted from cryptocurrency.cv; accepts CoinGecko slugs or Solana mints. Docs: [docs/coin-pages.md](docs/coin-pages.md) |
diff --git a/docs/guardian.md b/docs/guardian.md
index 4985ce5dc..4ddd52374 100644
--- a/docs/guardian.md
+++ b/docs/guardian.md
@@ -39,9 +39,9 @@ The response sorts agents that need your action first, then those with an open p
## Walkthrough
-1. Open [/guardian](https://three.ws/guardian). Signed out, it prompts you to sign in. Signed in with no roles, it explains what the console is for and invites you to ask a friend to name you.
+1. Open [/guardian](https://three.ws/guardian). Signed out, it prompts you to sign in or create an account, and returns you here afterwards. Signed in with no roles, it explains what the console is for, invites you to ask a friend to name you, and links you to setting up recovery on your own agents.
2. Each agent you protect renders as a card: its name (linked to its profile), who owns it, when you were trusted, and your roles (guardian, beneficiary, or both). A badge at the top counts how many agents need your action.
-3. If a process is open, the card tells its story in the agent's own voice ("I'm being recovered. If you trust this person is really my owner, approve."), plus the approval count, the safety-window countdown, and when it opened.
+3. If a process is open, the card tells its story in the agent's own voice ("I am being recovered. If you trust this person is really my owner, approve."), and then gives you what a decision actually needs: the reason the requester gave, the approval count, which guardians have already approved or declined by name, how long until the request expires if nobody acts, the safety-window countdown, and when it opened.
4. Act. For a recovery you trust, click **Approve recovery** (or **Decline**). For an inheritance you believe is real, click **Confirm inheritance**. Each action asks you to confirm, because these are consequential.
5. When the safety window has elapsed and the process is ready, click **Complete transfer** to pass control of the agent and its wallet to the new owner.
6. If you are the beneficiary or a guardian and the owner has gone silent past their threshold with no active process, you can try to arm inheritance, which begins the grace window.
@@ -68,7 +68,8 @@ The console reads this on load, resolves your viewer id (so it can tell whether
- **Time-locked and cancelable.** Threshold approvals start a safety window; the real owner can cancel any time before completion, and their return defeats the request outright.
- **Auto-freeze during a dispute.** An open request freezes autonomous spend (owner withdrawal stays open), tracked separately so it lifts on resolution without overriding a freeze the owner set.
- **Confirmation on every consequential action.** Approve, confirm, decline, and complete each prompt for confirmation before firing.
-- **Signed-out, empty, and error states** are all designed: sign-in prompt, "no one's named you yet", and an inline retry on failure.
+- **Signed-out, empty, loading, and error states** are all designed: a sign-in prompt that returns you to the console, "no one has named you yet" with a route to setting up your own guardians, skeleton cards while the inbox loads, and a plain-English failure with a retry (a dropped connection, a rate limit, and a server fault each read differently).
+- **The page tracks the process while you watch it.** It reloads itself the moment a safety window lifts, and again when you return to the tab, so a card never shows a countdown that expired while you were away.
- **Not the content-safety Guardian.** This console is unrelated to `@three-ws/guardian`, the AI content-moderation package that shares the name.
## Related
diff --git a/prompts/finish/104-swarm-100-route-guardian.md b/prompts/finish/104-swarm-100-route-guardian.md
deleted file mode 100644
index b194d5267..000000000
--- a/prompts/finish/104-swarm-100-route-guardian.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Route audit: /guardian (Guardian console: recover & inherit agent wallets)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If sibling swarm-100 files in
-prompts/finish/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. This route's declared entry (path, description, added date):
-
- node -e "const p=require('./data/pages.json');for(const s of p.sections)for(const g of s.pages)if(g.path==='/guardian')console.log(JSON.stringify(g,null,2))"
-
-2. Find the serving implementation: grep "/guardian" in vercel.json (the live
- route table server/index.mjs boots from), then list matching files in
- pages/ and src/. STRUCTURE.md maps every surface to its directory if the
- grep is ambiguous.
-3. Production right now:
-
- curl -so /dev/null -w '%{http_code}\n' https://three.ws/guardian
-
-4. Start (or reuse) the local dev server: npm run dev (vite, port 3000).
-
-## Task: audit this one route end to end, then fix everything found
-
-Route: /guardian ("Guardian console: recover & inherit agent wallets", section "crypto").
-Declared purpose: The agents you're trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet: through a threshold-approved, time-locked process that never exposes a private key.
-
-Drive the page in a real headless browser. Playwright is already a dev
-dependency; keep your probe script in the session scratchpad, never in the
-repo.
-
-1. Load http://localhost:3000/guardian. Record the HTTP status, every console
- error and warning, and every failed network request.
-2. Exercise it like a first-time user: click the primary actions, run the
- primary flow if one exists, follow the page's internal links. Every button
- must do something real; every link must resolve. If the page renders data,
- prove in the network log that it came from a live endpoint, not a baked-in
- fallback array.
-3. States: verify populated, empty, loading, and error states are designed and
- reachable. Block the page's primary fetch in Playwright and confirm an
- actionable error state appears, not a blank void or a raw exception.
-4. Responsive: render at 320, 768, and 1440 px. No horizontal page scroll, no
- overlapping or clipped controls.
-5. Accessibility basics: one h1; interactive elements are real buttons or
- links with visible focus states; images carry alt text; form fields have
- labels.
-6. Head: a specific title tag and meta description that match the declared
- purpose above.
-7. Fix every defect at its root in the page's real source files and re-run the
- probe until clean. Defects in shared modules are in scope when this route
- exercises them.
-
-## Definition of done
-
-- [ ] Local load of /guardian: HTTP 200, zero console errors, zero unhandled
- failed requests (a third-party outage must land in a designed fallback,
- not a broken page).
-- [ ] No dead interactive element on the page: no stub href="#", no button
- without a handler, no link to a missing path.
-- [ ] Empty, loading, error, and populated states verified.
-- [ ] 320 / 768 / 1440 px renders verified clean.
-- [ ] Title and meta description present and specific.
-- [ ] npm test passes; npm run check:rules -- --paths <touched files> exits 0.
-- [ ] Production status from step 0 recorded in the report; if production
- needs a deploy to pick up a fix, the report says so (deploys stay
- owner-gated).
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/finish/104-swarm-100-route-guardian.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/src/guardian.js b/src/guardian.js
index a2052f1c7..91818f1e4 100644
--- a/src/guardian.js
+++ b/src/guardian.js
@@ -38,7 +38,6 @@ const STYLE = `
.gd-pill { font-size:var(--text-2xs,.6875rem); font-weight:600; padding:2px 8px; border-radius:999px; border:1px solid transparent; }
.gd-pill.guardian { color:var(--wallet-accent-ink,#c4b5fd); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 14%,transparent); border-color:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 32%,transparent); }
.gd-pill.beneficiary { color:var(--success,#4ade80); background:color-mix(in srgb,var(--success,#4ade80) 12%,transparent); border-color:color-mix(in srgb,var(--success,#4ade80) 30%,transparent); }
-.gd-pill.neutral { color:var(--ink-dim,#999); background:var(--surface-2,rgba(255,255,255,.05)); border-color:var(--stroke,rgba(255,255,255,.08)); }
.gd-proc { margin-top:12px; padding-top:12px; border-top:1px solid var(--stroke,rgba(255,255,255,.08)); }
.gd-proc-h { font-size:var(--text-sm,.85rem); color:var(--ink-bright,#fff); display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
.gd-narrate { font-style:italic; color:var(--ink,#c8c8c8); font-size:var(--text-sm,.8rem); line-height:1.5; padding:10px 12px; margin-top:8px; border-left:2px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 50%,transparent); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 7%,transparent); border-radius:0 10px 10px 0; }
@@ -65,7 +64,7 @@ const STYLE = `
.gd-empty p{ margin:0 auto; max-width:46ch; line-height:1.55; }
.gd-empty .ill{ font-size:34px; opacity:.5; display:block; margin-bottom:10px; }
.gd-skel{ height:84px; border-radius:14px; background:linear-gradient(90deg,var(--surface-1,rgba(255,255,255,.03)) 25%,var(--surface-2,rgba(255,255,255,.05)) 37%,var(--surface-1,rgba(255,255,255,.03)) 63%); background-size:400% 100%; animation:gd-sh 1.4s ease infinite; }
-.gd-toast{ position:fixed; left:50%; bottom:24px; transform:translateX(-50%) translateY(8px); max-width:min(92vw,420px); text-align:center; background:var(--bg-1,#1a1a1a); color:var(--ink-bright,#fff); border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); border-radius:10px; padding:10px 16px; font-size:.85rem; box-shadow:0 8px 32px rgba(0,0,0,.5); opacity:0; pointer-events:none; transition:opacity .2s,transform .2s; z-index:9999; }
+.gd-toast{ position:fixed; left:50%; bottom:var(--gd-toast-bottom,24px); transform:translateX(-50%) translateY(8px); width:max-content; max-width:min(92vw,420px); text-align:center; background:var(--bg-1,#1a1a1a); color:var(--ink-bright,#fff); border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); border-radius:10px; padding:10px 16px; font-size:.85rem; line-height:1.45; box-shadow:0 8px 32px rgba(0,0,0,.5); opacity:0; pointer-events:none; transition:opacity .2s,transform .2s; z-index:2147483000; }
.gd-toast[data-show="true"]{ opacity:1; transform:translateX(-50%) translateY(0); }
@keyframes gd-sh{ 0%{background-position:100% 0} 100%{background-position:-100% 0} }
@media (prefers-reduced-motion: reduce){ .gd-skel{animation:none} .gd-btn,.gd-toast{transition:none} }
@@ -84,10 +83,30 @@ function esc(s) {
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
}
+// The site-wide corner stack (the companion, the tour pill, the language
+// switcher) is fixed to the bottom-right at a z-index no page can outrank, and
+// on a phone it is wide enough to sit under a centred toast. Measure it rather
+// than guessing a clearance: lift the toast above it only when the two would
+// actually overlap horizontally.
+function toastBottom() {
+ const stack = document.querySelector('.tws-corner-stack');
+ if (!stack) return null;
+ const b = stack.getBoundingClientRect();
+ if (!b.height) return null;
+ // A centred toast is at most min(92vw, 420px) wide.
+ const toastHalf = Math.min(window.innerWidth * 0.92, 420) / 2;
+ const toastLeft = window.innerWidth / 2 - toastHalf;
+ const toastRight = window.innerWidth / 2 + toastHalf;
+ if (b.left >= toastRight || b.right <= toastLeft) return null;
+ return Math.round(window.innerHeight - b.top) + 12;
+}
+
let toastTimer = null;
function toast(msg, ms = 2400) {
let el = document.querySelector('.gd-toast');
if (!el) { el = document.createElement('div'); el.className = 'gd-toast'; el.setAttribute('role', 'status'); el.setAttribute('aria-live', 'polite'); document.body.appendChild(el); }
+ const lift = toastBottom();
+ el.style.setProperty('--gd-toast-bottom', lift ? `${lift}px` : '24px');
el.textContent = msg;
el.dataset.show = 'true';
clearTimeout(toastTimer);
@@ -104,6 +123,15 @@ function fmtDuration(ms) {
return `${s}s`;
}
+// What a button says while its request is in the air.
+const PENDING_LABEL = {
+ approve: 'Approving',
+ confirm: 'Confirming',
+ decline: 'Declining',
+ complete: 'Transferring',
+ arm: 'Arming',
+};
+
// The API's phase names are storage identifiers. A guardian reads a sentence.
const STATUS_LABEL = {
pending_approvals: 'awaiting approvals',
@@ -119,6 +147,9 @@ const STATUS_LABEL = {
// about it. Anything unmapped falls through to the server's own sentence, which
// this API writes for humans; a raw exception string never reaches the page.
function humanError(res) {
+ if (res.code === 'timeout') {
+ return 'three.ws did not answer in time. Nothing was changed. Try again.';
+ }
if (res.code === 'network_error' || res.status === 0) {
return 'We could not reach three.ws. Check your connection, then try again.';
}
@@ -128,9 +159,22 @@ function humanError(res) {
return res.message || 'Something went wrong. Nothing was changed.';
}
+// Deadlines, matching the ones apiFetch applies site-wide: a read that never
+// answers must not hold the skeleton up forever, and a write whose response
+// body stalls mid-stream (seen for real through a proxied connection) must not
+// strand a guardian on a permanently disabled button.
+const READ_TIMEOUT_MS = 20_000;
+const WRITE_TIMEOUT_MS = 45_000;
+
+function deadline(ms) {
+ if (typeof AbortSignal === 'undefined' || typeof AbortSignal.timeout !== 'function') return undefined;
+ return AbortSignal.timeout(ms);
+}
+
async function call(url, { method = 'GET', body = null } = {}) {
try {
const opts = { method, credentials: 'include', headers: { accept: 'application/json' } };
+ opts.signal = deadline(method === 'GET' ? READ_TIMEOUT_MS : WRITE_TIMEOUT_MS);
if (body != null) { opts.headers['content-type'] = 'application/json'; opts.body = JSON.stringify(body); }
if (method !== 'GET') { const tok = await consumeCsrfToken(); if (tok) opts.headers['x-csrf-token'] = tok; }
const r = await fetch(url, opts);
@@ -138,7 +182,8 @@ async function call(url, { method = 'GET', body = null } = {}) {
if (!r.ok) return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, detail: j?.detail || null };
return { ok: true, status: r.status, data: j?.data ?? j };
} catch (err) {
- return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };
+ const timedOut = err?.name === 'TimeoutError' || err?.name === 'AbortError';
+ return { ok: false, status: 0, code: timedOut ? 'timeout' : 'network_error', message: err?.message || 'network error' };
}
}
@@ -337,7 +382,13 @@ function wire() {
if (confirmMsg && !confirm(confirmMsg)) return;
busy = true;
+ // A guardian action is a real round trip (CSRF issue, then the write).
+ // Say so on the button itself, so the seconds between click and toast
+ // read as work in progress rather than a dead control.
+ const restLabel = btn.textContent;
btn.disabled = true;
+ btn.setAttribute('aria-busy', 'true');
+ btn.textContent = PENDING_LABEL[act] || 'Working';
let res;
if (act === 'arm') {
res = await call(`/api/agents/${encodeURIComponent(agent)}/recovery/inheritance/arm`, { method: 'POST', body: {} });
@@ -348,7 +399,13 @@ function wire() {
// A session that expired while the page sat open must not read as a
// mystery failure: send them back to the signed-out door.
if (res.status === 401) { noteSession(false); renderSignedOut(); return; }
- if (!res.ok) { toast(humanError(res)); btn.disabled = false; return; }
+ if (!res.ok) {
+ toast(humanError(res));
+ btn.textContent = restLabel;
+ btn.removeAttribute('aria-busy');
+ btn.disabled = false;
+ return;
+ }
const msg = {
approve: 'Approved. Thank you for vouching.',
confirm: 'Confirmed',
@@ -362,6 +419,16 @@ function wire() {
});
}
+// Single-flight. A tab-focus refresh that overlapped an action's own reload
+// would replace the card mid-click and leave the guardian pressing a detached
+// button that answers nothing.
+let loading = null;
+function load() {
+ if (loading) return loading;
+ loading = loadOnce().finally(() => { loading = null; });
+ return loading;
+}
+
/**
* Resolve the viewer before asking for the inbox. /api/auth/me answers 200 with
* `{ user: null }` for a signed-out visitor, so the signed-out path costs one
@@ -369,7 +436,7 @@ function wire() {
* path gets the viewer id it needs for "you approved" out of the same response
* rather than a second lookup.
*/
-async function load() {
+async function loadOnce() {
renderLoading();
const me = await call('/api/auth/me');
if (!me.ok) { renderError(me); return; }