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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
x402 payment verify, DB retry, sitemap/RSS and SDK updates; wallet snapshot migration
nirholas8c3baf76105f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cdaa9f387..ca9cac87d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-23- **Fix: avatars look right in iOS AR, not collapsed and distorted** — Viewing an avatar in AR on iPhone or iPad (the 'Place in your space' / Quick Look flow) could show a mangled figure — limbs balled up at the hips and accessories like glasses floating at giant scale — instead of the avatar you saw on the page. The cause: the AR file format Apple uses doesn't carry an animation skeleton, so the standard exporter shipped the avatar in its raw, un-posed rig. We now freeze each avatar into its proper standing pose before generating the AR file, so what you place in your room matches what you see in the viewer, accessories included. `[fix]`+- **Fix: prompt-to-avatar shows your finished avatar instead of jumping to the editor** — When you described an avatar in words at Create → From a prompt, the 'done' screen was meant to show a live, spinnable preview of the character you just made — the payoff moment. For private avatars (the default), that preview was being skipped and you were dropped straight into the editor with no look at the result. The preview now renders for private avatars too, using the same owner-only secure link the selfie flow already used, so every prompt-built avatar greets you with a real 3D preview you can rotate before opening the editor or making another. (`/create/prompt`) `[fix]`- **Fix: the bounty board and live token feeds stay up when a third party is slow** — Swept the API for places where a slow or flaky upstream could hang a request until it was force-killed, or a database missing a recent table could error a whole page, and closed them. The /go bounty board now provisions its own database tables, so it loads everywhere instead of erroring where they were absent. The pump trending and search feeds fall back to the last good list (or an empty one) when pump.fun returns a malformed response, rather than failing the page. And a batch of backend lookups — the live SOL price, Jupiter/Birdeye/CoinGecko market data, portfolio price charts, token-gated scene access checks, IPFS pinning, voice synthesis, and the embedded-agent AI fallback chain — now bound every third-party call with a timeout, so a stalled service returns a clean result quickly instead of holding the request open until it's killed. `[fix]`+- **Improvement: Base USDC payments confirm even when an RPC provider is flaky** — When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient. `[improvement, infra]`## 2026-06-22diff --git a/api/_lib/db-retry.js b/api/_lib/db-retry.jsindex cc059b25e..fad9e758c 100644--- a/api/_lib/db-retry.js+++ b/api/_lib/db-retry.js@@ -1,4 +1,4 @@-// Retry helper for standalone, idempotent DB writes.+// Retry + bounded-timeout guard for standalone, idempotent DB writes.//// Neon's HTTP driver does a `fetch` per query. On Vercel, cold connections and// momentary network blips surface as `NeonDbError: Error connecting to database:@@ -8,6 +8,17 @@// SQL errors (constraint violations, syntax, 22021 NUL, etc.) are deterministic// and surface unchanged.//+// A second failure mode is worse than a clean error: a Neon connection that+// neither errors nor returns. The HTTP `fetch` can stall (DNS, TLS, a wedged+// compute waking from scale-to-zero), and a serverless function that awaits it+// burns its whole wall-clock budget and is killed by the platform with no error+// the caller can react to. So every attempt here runs under a bounded deadline:+// if the query outlives `timeoutMs` (total across attempts) we reject with a+// `DbTimeoutError` instead of hanging. A timeout is classified transient — but+// because the deadline is the *total* budget, a timed-out attempt has by+// definition consumed the remaining budget, so the loop exits and surfaces the+// timeout rather than retrying a query that is merely slow.+//// This lives apart from db.js on purpose: the bare `sql` tagged template must// keep returning Neon's lazy query object so callers can still batch them with// `sql.transaction([...])`, and most tests mock `db.js` directly — keeping the@@ -18,22 +29,64 @@const MAX_DB_ATTEMPTS = 3;const RETRY_BACKOFF_MS = [150, 400];+// Total wall-clock budget for a guarded call across all attempts. Sized well+// under a serverless function's typical execution limit so a stalled Neon+// connection is abandoned with a coded error long before the platform kills the+// whole invocation. Override per-call via `withDbRetry(run, { timeoutMs })`;+// pass `0`/`Infinity` to disable (e.g. a deliberately long-running maintenance+// query that owns its own deadline).+const DEFAULT_DB_TIMEOUT_MS = 15_000;++// Thrown when a guarded DB call outlives its deadline. Coded so callers can+// distinguish "the DB is slow/wedged" from "the query was rejected", and so+// isTransientConnError can classify it without string matching.+export class DbTimeoutError extends Error {+ constructor(ms) {+ super(`db query exceeded ${ms}ms deadline`);+ this.name = 'DbTimeoutError';+ this.code = 'DB_TIMEOUT';+ }+}+function isTransientConnError(err) {+ if (err?.code === 'DB_TIMEOUT') return true;const msg = `${err?.message || ''} ${err?.sourceError?.message || ''} ${err?.cause?.message || ''}`;return /fetch failed|connecting to database|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up|network|terminat/i.test(msg,);}-export async function withDbRetry(run) {+// Race a promise-returning thunk against a deadline. The timer is always+// cleared, so a settled query never leaves a dangling handle keeping the event+// loop (or a serverless freeze) alive. `ms <= 0` or a non-finite `ms` disables+// the bound and just runs the thunk.+export function withDbTimeout(run, ms = DEFAULT_DB_TIMEOUT_MS) {+ if (!Number.isFinite(ms) || ms <= 0) return Promise.resolve().then(run);+ let timer;+ const deadline = new Promise((_, reject) => {+ timer = setTimeout(() => reject(new DbTimeoutError(ms)), ms);+ });+ return Promise.race([Promise.resolve().then(run), deadline]).finally(() => clearTimeout(timer));+}++export async function withDbRetry(run, { timeoutMs = DEFAULT_DB_TIMEOUT_MS } = {}) {+ const bounded = Number.isFinite(timeoutMs) && timeoutMs > 0;+ const deadline = bounded ? Date.now() + timeoutMs : Infinity;let lastErr;for (let attempt = 0; attempt < MAX_DB_ATTEMPTS; attempt++) {+ const remaining = bounded ? deadline - Date.now() : Infinity;+ if (bounded && remaining <= 0) throw lastErr ?? new DbTimeoutError(timeoutMs);try {- return await run();+ return await withDbTimeout(run, remaining);} catch (err) {lastErr = err;if (attempt === MAX_DB_ATTEMPTS - 1 || !isTransientConnError(err)) throw err;- await new Promise((r) => setTimeout(r, RETRY_BACKOFF_MS[attempt] ?? 400));+ const backoff = RETRY_BACKOFF_MS[attempt] ?? 400;+ // Never sleep past the deadline — a backoff that overruns the budget+ // would just delay the inevitable timeout throw on the next iteration.+ const left = bounded ? deadline - Date.now() : Infinity;+ if (bounded && left <= 0) throw err;+ await new Promise((r) => setTimeout(r, bounded ? Math.min(backoff, left) : backoff));}}throw lastErr;diff --git a/api/_lib/evm-payment-verify.js b/api/_lib/evm-payment-verify.jsindex 8aaf88b5d..b78218f00 100644--- a/api/_lib/evm-payment-verify.js+++ b/api/_lib/evm-payment-verify.js@@ -7,9 +7,10 @@// the expected amount. This mirrors the strictness of `validateTransfer` on the// Solana side. Coin-agnostic settlement plumbing: USDC is the settlement asset.-import { createPublicClient, http, getAddress, decodeEventLog, parseAbiItem } from 'viem';+import { createPublicClient, getAddress, decodeEventLog, parseAbiItem } from 'viem';import { base, baseSepolia } from 'viem/chains';import { env } from './env.js';+import { evmTransport } from './evm/rpc.js';import { EVM_USDC } from '../payments/_config.js';// Map our stored `chain` string to an EVM chain id. Only Base is wired today;@@ -40,8 +41,15 @@ const _clients = new Map();function clientFor(chainId) {if (_clients.has(chainId)) return _clients.get(chainId);const chain = chainId === 84532 ? baseSepolia : base;- const rpcUrl = env.BASE_RPC_URL || (chainId === 84532 ? 'https://sepolia.base.org' : 'https://mainnet.base.org');- const client = createPublicClient({ chain, transport: http(rpcUrl) });+ // Multi-endpoint failover (explicit override → Alchemy → public), identical to+ // every other EVM read path (evm-transfer, club payouts, ERC-8004 reads). The+ // settlement-verify path must never be the one place a single flaky Base RPC+ // strands a payment: viem's fallback transport rotates to the next endpoint on+ // a transport fault, while a genuine "not mined yet" still surfaces as the soft,+ // retryable `pending` the callers already handle. BASE_RPC_URL is pinned first+ // so an operator's private node keeps buyer addresses off the public lanes.+ const transport = evmTransport(chainId, { primaryUrl: env.BASE_RPC_URL });+ const client = createPublicClient({ chain, transport });_clients.set(chainId, client);return client;}diff --git a/api/_lib/http.js b/api/_lib/http.jsindex cabe4ee1e..4cba72835 100644--- a/api/_lib/http.js+++ b/api/_lib/http.js@@ -69,16 +69,34 @@ export function error(res, status, code, message, extra = {}) {return json(res, status, { error: code, error_description: message, ...extra }, { 'cache-control': 'no-store' });}-// Query params that can carry a user's real-world position or a bearer-style-// device credential. These must never reach a log line, Sentry event, or ops-// alert — all off-box sinks — so they are stripped from any request URL we log.-// Matched on the lower-cased key so camelCase / snake_case variants are covered.+// Query params that can carry a credential, a wallet secret, an email, or a+// user's real-world position. These must never reach a log line, Sentry event,+// or ops alert — all off-box sinks — so they are stripped from any request URL+// we log. Keys are compared after normalizing away case and `_`/`-` separators+// (see isSensitiveQueryKey), so `api-key`, `api_key`, and `apiKey` all collapse+// to one entry here and a new casing variant can't slip a secret through.const SENSITIVE_QUERY_KEYS = new Set([+ // precise geolocation'lat', 'lng', 'latitude', 'longitude', 'll', 'coords', 'coord',- 'originlat', 'originlng', 'origin_lat', 'origin_lng',- 'devicetoken', 'device_token', 'token',+ 'originlat', 'originlng', 'geo', 'location', 'position',+ // bearer / session credentials+ 'token', 'devicetoken', 'accesstoken', 'refreshtoken', 'idtoken',+ 'authorization', 'auth', 'bearer', 'session', 'sessionid', 'sid',+ 'password', 'passwd', 'pwd', 'pin', 'otp',+ // API keys / signing secrets+ 'apikey', 'key', 'accesskey', 'secret', 'clientsecret', 'signature', 'sig',+ // wallet secrets+ 'privatekey', 'secretkey', 'mnemonic', 'seed', 'seedphrase', 'keypair',+ // PII+ 'email',]);+// Normalize a query key to its case/separator-insensitive form before matching,+// so `deviceToken`, `device_token`, and `device-token` are one key.+function isSensitiveQueryKey(key) {+ return SENSITIVE_QUERY_KEYS.has(key.toLowerCase().replace(/[_-]/g, ''));+}+// Reduce a request URL to a log-safe form: keep the path and any benign params,// but redact values that reveal a location or a credential. A geolocated read// such as /api/irl/pins?lat=…&lng=…&deviceToken=… would otherwise spill the@@ -98,7 +116,7 @@ export function redactUrl(rawUrl) {}let touched = false;for (const key of [...params.keys()]) {- if (SENSITIVE_QUERY_KEYS.has(key.toLowerCase())) {+ if (isSensitiveQueryKey(key)) {params.set(key, 'REDACTED');touched = true;}@@ -116,16 +134,21 @@ function correlationId() {return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');}-// Emit a 5xx WITHOUT leaking internal error detail to the client. The real-// message (which may carry RPC URLs, wallet addresses, or stack-derived text)-// is logged + captured server-side under a correlation id the caller can quote-// to support; the client only sees a generic description + the ref.-export function serverError(res, status, code, err, extra = {}) {+// Log + capture + alert a server fault under a fresh correlation id WITHOUT+// writing a response, and return the ref. The body-writing helpers below build+// on this, but it's also the seam for handlers that must answer in a non-JSON+// content type (RSS/XML, sitemap text, JSON-RPC, MCP) and so can't call+// serverError(): they catch internally, call this to land the same log line ++// Sentry event + deduped ops alert, then echo `ref` in their own envelope. That+// keeps acceptance criterion #1 — every 5xx gets a ref/capture/alert — true for+// boundaries that never reach wrap(). `context` is merged into the Sentry extra+// (callers redact URLs via redactUrl() before passing them here).+export function reportServerError(err, { code = 'internal_error', status = 500, context = {} } = {}) {const ref = correlationId();const detail = err?.message || String(err ?? 'unknown error');console.error(`[server-error ${ref}] ${code} (${status}): ${detail}`);try {- captureException(err instanceof Error ? err : new Error(detail), { ref, code, status });+ captureException(err instanceof Error ? err : new Error(detail), { ref, code, status, ...context });// Fire-and-forget like captureException; deduped per error class+message// (ref excluded from the signature so each occurrence doesn't re-alert).sendOpsAlert(`${status} ${code}`, `${detail}\nref ${ref}`, {@@ -134,6 +157,15 @@ export function serverError(res, status, code, err, extra = {}) {} catch {/* sentry/alerts best-effort; never mask the original failure */}+ return ref;+}++// Emit a 5xx WITHOUT leaking internal error detail to the client. The real+// message (which may carry RPC URLs, wallet addresses, or stack-derived text)+// is logged + captured server-side under a correlation id the caller can quote+// to support; the client only sees a generic description + the ref.+export function serverError(res, status, code, err, extra = {}) {+ const ref = reportServerError(err, { code, status });return json(res, status, {error: code,error_description: `internal error — quote ref ${ref} to support`,diff --git a/api/_lib/migrations/20260623000000_wallet_value_snapshots.sql b/api/_lib/migrations/20260623000000_wallet_value_snapshots.sqlnew file mode 100644index 000000000..bf468ed5b--- /dev/null+++ b/api/_lib/migrations/20260623000000_wallet_value_snapshots.sql@@ -0,0 +1,34 @@+-- Periodic portfolio-value snapshots for agent custodial wallets.+--+-- Powers the wallet identity layer's micro P&L sparkline + 24h change. Every+-- time the batch balance endpoint (POST /api/agents/balances) values a wallet it+-- records a real, on-chain-derived total USD value here (deduped to at most one+-- row per wallet per ~5 min). The 24h change and sparkline are then derived from+-- the real series — never a synthesized curve. A wallet with fewer than two+-- snapshots renders the empty sparkline state, by design.+--+-- This is option (2) from the wallet-identity P&L spec: persist periodic balance+-- snapshots server-side and derive change from them. No external price-history+-- API required; the series densifies organically from real browsing traffic and+-- can be backfilled by a cron later without schema changes.++create table if not exists wallet_value_snapshots (+ id bigserial primary key,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ address text not null,+ usd_value numeric(20, 6) not null,+ sol_amount numeric(20, 9),+ captured_at timestamptz not null default now()+);++-- The hot query is "latest N snapshots for this agent within the last ~26h",+-- ordered by time. A composite (agent_id, captured_at desc) index serves both the+-- sparkline read and the dedup "is the most recent row older than 5 min?" check.+create index if not exists wallet_value_snapshots_agent_time_idx+ on wallet_value_snapshots (agent_id, captured_at desc);++-- Snapshots are ephemeral telemetry, not a ledger: keep the table small by+-- letting a retention sweep delete anything older than the sparkline window.+-- Indexing captured_at alone makes that bulk delete cheap.+create index if not exists wallet_value_snapshots_captured_idx+ on wallet_value_snapshots (captured_at);diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex b1fbe7811..ce0b0ec27 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -32,6 +32,7 @@ import { cors, error, respondError, rateLimited, wrap } from './http.js';import { env } from './env.js';import { clientIp, limits } from './rate-limit.js';import { logPaymentEvent } from './x402/audit-log.js';+import { recordPaymentMetric } from './axiom.js';import { PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC } from './x402-bsc-direct.js';import {BUILDER_CODE,@@ -85,6 +86,15 @@ function resolveNetwork(name) {return NETWORK_ALIASES[name] || name;}+// USDC is 6-decimal; the x402 requirement carries the price as an atomic string.+// Returns undefined for an absent/unparseable amount so the metric simply omits+// the field rather than reporting a misleading 0.+function atomicsToUsd(atomics) {+ if (atomics == null) return undefined;+ const n = Number(atomics);+ return Number.isFinite(n) ? n / 1e6 : undefined;+}+function buildAccept(network, priceAtomics, resourceUrl, payToOverride) {const common = {scheme: 'exact',@@ -781,6 +791,15 @@ export function paidEndpoint(spec) {try {verified = await verifyPayment({ paymentHeader, requirements, builderCode });} catch (err) {+ // Verify is a payment outcome too — record it so the invalid/rejected-+ // payment rate is visible alongside settlements. A 402 here is a rejected+ // proof (insufficient/invalid), distinct from an upstream verify fault.+ recordPaymentMetric({+ kind: 'x402',+ status: 'failed',+ latencyMs: Date.now() - requestStartTime,+ reason: err.code || (err.status === 402 ? 'verify_rejected' : 'verify_failed'),+ });if (ownsReservation) await releaseSlot({ route, paymentId });if (err.status === 402) return send402(res, { ...challenge, error: err.message });return respondError(res, err.status || 502, err.code || 'verify_failed', err);@@ -829,6 +848,14 @@ export function paidEndpoint(spec) {userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,metadata: { error: err.message, code: err.code },});+ recordPaymentMetric({+ kind: 'x402',+ status: 'failed',+ network: verified.requirement?.network,+ amountUsd: atomicsToUsd(verified.requirement?.amount),+ latencyMs: Date.now() - requestStartTime,+ reason: err.code || 'settle_failed',+ });if (ownsReservation) await releaseSlot({ route, paymentId });return respondError(res, err.status || 502, err.code || 'settle_failed', err);}@@ -906,6 +933,17 @@ export function paidEndpoint(spec) {ipAddress: clientIp(req),userAgent: req.headers?.['user-agent']?.slice(0, 512) || null,});+ // Axiom payment metric — success rate + per-network latency the audit DB+ // can't aggregate live. Fire-and-forget no-op until AXIOM_* is set; carries+ // only on-chain identifiers (route, network, tx signature), never PII.+ recordPaymentMetric({+ kind: 'x402',+ status: 'ok',+ network: settled.network || verified.requirement?.network,+ amountUsd: atomicsToUsd(verified.requirement?.amount),+ latencyMs: Date.now() - requestStartTime,+ signature: settled.transaction || undefined,+ });if (paymentId) {await storeResponse({diff --git a/api/_mcp/payments.js b/api/_mcp/payments.jsindex 81a93d93b..b9cdf0e22 100644--- a/api/_mcp/payments.js+++ b/api/_mcp/payments.js@@ -1,7 +1,5 @@-import { logger } from '../_lib/usage.js';import { X402Error, send402 } from '../_lib/x402-spec.js';--const log = logger('mcp');+import { reportServerError } from '../_lib/http.js';export function sendX402Error(res, { resourceUrl, accepts }, err) {if (err instanceof X402Error) {@@ -11,8 +9,11 @@ export function sendX402Error(res, { resourceUrl, accepts }, err) {res.end(JSON.stringify({ error: err.code, error_description: err.message }));return;}- log.error('x402_unexpected', { message: err?.message });+ // Unexpected (non-X402) fault — route it through the shared boundary so the+ // MCP payment path gets the same ref + Sentry capture + deduped ops alert as+ // an HTTP 5xx, then echo the ref so an agent can quote it to support.+ const ref = reportServerError(err, { code: 'mcp_x402_failed', context: { resourceUrl } });res.statusCode = 500;res.setHeader('content-type', 'application/json; charset=utf-8');- res.end(JSON.stringify({ error: 'internal', error_description: 'x402 processing failed' }));+ res.end(JSON.stringify({ error: 'internal', error_description: `x402 processing failed — quote ref ${ref} to support`, ref }));}diff --git a/api/permissions/[action].js b/api/permissions/[action].jsindex 7d24e3950..52922ea39 100644--- a/api/permissions/[action].js+++ b/api/permissions/[action].js@@ -18,7 +18,7 @@ import { evmFallbackProvider } from '../_lib/evm/rpc.js';import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';-import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';+import { cors, json, method, readJson, wrap, error, rateLimited, reportServerError } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';@@ -1188,17 +1188,19 @@ async function handleVerify(req, res) {try {disabled = await verifyWithTimeout(verifyCheckDisabled(hash, chainId), 5000);} catch (err) {- console.error('[verify] rpc error', err);+ // Route through the boundary: ref + Sentry capture + deduped ops alert.+ // The internal RPC error string stays server-side; the client sees only a+ // stable code plus the ref it can quote to support.+ const ref = reportServerError(err, { code: 'rpc_error', status: 502, context: { check: 'verifyCheckDisabled' } });res.statusCode = 502;res.setHeader('content-type', 'application/json; charset=utf-8');res.setHeader('cache-control', 'no-store');- // Don't leak the upstream error string to the client — log it (above) and- // return a stable code. The internal message goes to server logs only.res.end(JSON.stringify({ok: false,error: 'rpc_error',error_description: 'on-chain verification failed',+ ref,}),);return;diff --git a/api/rss/announcements.js b/api/rss/announcements.jsindex 68612e408..b13068ba2 100644--- a/api/rss/announcements.js+++ b/api/rss/announcements.js@@ -2,7 +2,7 @@// Default source: data/rss/items.json (curated, hand-edited).// Mirror modes: ?source=trythreews | ?source=nichxbt | ?source=archive (X scrape).-import { cors, method } from '../_lib/http.js';+import { cors, method, reportServerError, redactUrl } from '../_lib/http.js';import { loadCuratedItems, loadAnnouncementItems, buildRssXml } from '../_lib/rss-feed.js';const ARCHIVE_SOURCES = new Set(['archive', 'trythreews', 'nichxbt']);@@ -33,9 +33,10 @@ export default async function handler(req, res) {res.setHeader('cache-control', 'public, max-age=600, s-maxage=600, stale-while-revalidate=86400');res.end(xml);} catch (err) {- console.error('[rss/announcements] failed', err);+ const ref = reportServerError(err, { code: 'rss_feed_failed', context: { url: redactUrl(req.url) } });res.statusCode = 500;res.setHeader('content-type', 'text/plain; charset=utf-8');- res.end('feed unavailable');+ res.setHeader('cache-control', 'no-store');+ res.end(`feed unavailable — quote ref ${ref} to support`);}}diff --git a/api/sitemap/[type].js b/api/sitemap/[type].jsindex b3e6a0478..0cb605303 100644--- a/api/sitemap/[type].js+++ b/api/sitemap/[type].js@@ -12,6 +12,7 @@ import { readFile } from 'node:fs/promises';import path from 'node:path';import { sql } from '../_lib/db.js';import { env } from '../_lib/env.js';+import { reportServerError, redactUrl } from '../_lib/http.js';const ORIGIN = env.APP_ORIGIN;const MAX_URLS = 45_000;@@ -193,9 +194,10 @@ export default async function handler(req, res) {const entries = await builder();return send(res, urlsetXml(entries));} catch (err) {- console.error('[sitemap]', raw, err?.message);+ const ref = reportServerError(err, { code: 'sitemap_failed', context: { url: redactUrl(req.url), type: raw } });res.statusCode = 500;res.setHeader('content-type', 'text/plain');- res.end('sitemap failed');+ res.setHeader('cache-control', 'no-store');+ res.end(`sitemap failed — quote ref ${ref} to support`);}}diff --git a/api/solana-rpc.js b/api/solana-rpc.jsindex 4f80b9718..e53e84cc9 100644--- a/api/solana-rpc.js+++ b/api/solana-rpc.js@@ -16,7 +16,7 @@// (getProgramAccounts, getBlock*) that would let an anonymous caller drain the// upstream quota.-import { cors, method, wrap, readJson, error, rateLimited } from './_lib/http.js';+import { cors, method, wrap, readJson, error, rateLimited, reportServerError } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import {solanaRpcEndpoints,@@ -148,12 +148,27 @@ export default wrap(async function handler(req, res) {// throw an opaque StructError (or silently mis-read an empty `[]`) instead of a// clean error the caller can handle. If the upstream body isn't a well-formed// JSON-RPC response, surface an honest 502 keyed to the same JSON-RPC id.- if (classifyRpcBody(text)) {+ const classified = classifyRpcBody(text);+ if (classified) {const id = Array.isArray(body) ? null : body?.id ?? null;+ // A provider returning a body web3.js can't parse is a real upstream+ // degradation worth seeing. Capture genuine 5xx through the boundary+ // (deduped on the classification reason, so a flapping provider alerts once+ // an hour, not per request) and thread the ref into the JSON-RPC error+ // `data` so a caller can quote it without breaking the strict envelope.+ // Capacity classifications (429) are expected provider backpressure, not a+ // server fault — don't alert on those.+ let ref;+ if ((classified.status ?? 502) >= 500) {+ ref = reportServerError(new Error(`rpc upstream returned an unusable response: ${classified.reason}`), {+ code: 'rpc_upstream_unusable',+ status: 502,+ });+ }res.statusCode = 502;res.setHeader('content-type', 'application/json; charset=utf-8');res.setHeader('cache-control', 'no-store');- res.end(JSON.stringify({ jsonrpc: '2.0', id, error: { code: -32603, message: 'rpc upstream returned an unusable response' } }));+ res.end(JSON.stringify({ jsonrpc: '2.0', id, error: { code: -32603, message: 'rpc upstream returned an unusable response', ...(ref ? { data: { ref } } : {}) } }));return;}res.statusCode = upstream.status;diff --git a/data/changelog.json b/data/changelog.jsonindex 2130f82a7..3e74e3482 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,19 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-23",+ "title": "Improvement: Base USDC payments confirm even when an RPC provider is flaky",+ "summary": "When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient.",+ "tags": ["improvement", "infra"]+ },+ {+ "date": "2026-06-23",+ "title": "Fix: prompt-to-avatar shows your finished avatar instead of jumping to the editor",+ "summary": "When you described an avatar in words at Create → From a prompt, the 'done' screen was meant to show a live, spinnable preview of the character you just made — the payoff moment. For private avatars (the default), that preview was being skipped and you were dropped straight into the editor with no look at the result. The preview now renders for private avatars too, using the same owner-only secure link the selfie flow already used, so every prompt-built avatar greets you with a real 3D preview you can rotate before opening the editor or making another.",+ "tags": ["fix"],+ "link": "/create/prompt"+ },{"date": "2026-06-23","title": "Fix: avatars look right in iOS AR, not collapsed and distorted",diff --git a/page-agent-sdk/src/page-agent.js b/page-agent-sdk/src/page-agent.jsindex 2306959b5..10fc54cd6 100644--- a/page-agent-sdk/src/page-agent.js+++ b/page-agent-sdk/src/page-agent.js@@ -83,6 +83,9 @@ export class PageAgent {this._muted = !!config.muted;this._collapsed = !!config.collapsed;this._root.dataset.state = this._stateBase();+ // Reflect the starting mute state onto the button (icon + aria-pressed),+ // so a `muted: true` config doesn't render an out-of-sync "unmuted" control.+ this.mute(this._muted);this.setAgent(startId).then(() => {this._emit('ready', this._agent);@@ -183,6 +186,12 @@ export class PageAgent {window.removeEventListener('pointerup', up);};handle.addEventListener('pointerdown', down);+ // Let dispose() unbind the handle and any drag still in flight.+ this._teardownDrag = () => {+ handle.removeEventListener('pointerdown', down);+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ };}// ── Agent lifecycle ────────────────────────────────────────────────────────@@ -330,6 +339,7 @@ export class PageAgent {dispose() {this.stop();+ this._teardownDrag?.();this.narrator?.dispose();this.stage?.dispose();this.picker?.dispose();diff --git a/page-agent-sdk/src/stage.js b/page-agent-sdk/src/stage.jsindex 5eabaeeb0..8ac7f3d05 100644--- a/page-agent-sdk/src/stage.js+++ b/page-agent-sdk/src/stage.js@@ -93,8 +93,27 @@ export class AvatarStage {this._resizeObs = new ResizeObserver(() => this._resize());this._resizeObs.observe(container);- this._raf = 0;+ // Pause the render loop when the tab is backgrounded or the agent scrolls+ // offscreen — a docked WebGL canvas should never burn GPU it can't be seen on.+ this._visible = !document.hidden;+ this._onscreen = true;this._render = this._render.bind(this);+ this._onVisibility = () => { this._visible = !document.hidden; this._kick(); };+ document.addEventListener('visibilitychange', this._onVisibility);+ this._inViewObs = new IntersectionObserver(+ (entries) => { this._onscreen = entries.some((e) => e.isIntersecting); this._kick(); },+ { threshold: 0 },+ );+ this._inViewObs.observe(container);++ this._raf = 0;+ this._raf = requestAnimationFrame(this._render);+ }++ /** (Re)start the render loop if it is paused and the stage is currently visible. */+ _kick() {+ if (this._raf || !this.renderer || !this._visible || !this._onscreen) return;+ this.clock.getDelta(); // discard the idle gap so motion resumes smoothlythis._raf = requestAnimationFrame(this._render);}@@ -232,8 +251,9 @@ export class AvatarStage {}_render() {+ // Re-arm only while visible & onscreen; _kick() resumes when that changes.+ if (!this.renderer || !this._visible || !this._onscreen) { this._raf = 0; return; }this._raf = requestAnimationFrame(this._render);- if (!this.renderer) return;const dt = Math.min(this.clock.getDelta(), 0.05);const t = this.clock.elapsedTime;const nowMs = t * 1000;@@ -276,6 +296,8 @@ export class AvatarStage {cancelAnimationFrame(this._raf);this._raf = 0;this._resizeObs?.disconnect();+ this._inViewObs?.disconnect();+ document.removeEventListener('visibilitychange', this._onVisibility);this._frameHooks.clear();if (this.model) { this.scene.remove(this.model); this._disposeObject(this.model); }this._envTex?.dispose();diff --git a/pages/irl.html b/pages/irl.htmlindex eb7e3a993..37fb3773f 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -535,6 +535,14 @@background: rgba(251,191,36,0.1);}#irl-lock-btn.is-active:hover { background: rgba(251,191,36,0.18); }+ /* "Move here" carry mode — teal active state matches the floor reticle the+ gesture drives, so the armed control and the on-floor ring read as one thing. */+ #irl-carry-btn.is-active {+ color: #34d399;+ border-color: rgba(52,211,153,0.45);+ background: rgba(52,211,153,0.1);+ }+ #irl-carry-btn.is-active:hover { background: rgba(52,211,153,0.18); }/* D2 "Appear nearby" presence toggle — only relevant in GPS mode (wherepresence is live), so it's hidden until then. Blue active state matches theghost orbs / presence chip. */@@ -2061,6 +2069,10 @@<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/><circle cx="12" cy="12" r="4"/></svg>Place on floor</button>+ <button class="irl-pill-btn" id="irl-carry-btn" type="button" aria-pressed="false" aria-label="Carry your agent and set it down where you aim on the floor">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>+ Move here+ </button><button class="irl-pill-btn" id="irl-lock-btn" type="button" aria-pressed="false" aria-label="Pin avatar in real space"><svg id="irl-lock-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg><span class="irl-lock-label">Pin here</span>diff --git a/public/changelog.json b/public/changelog.jsonindex 9cb823c6b..8b33b6e5e 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T01:57:12.708Z",+ "generated_at": "2026-06-23T02:37:56.000Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Fix: prompt-to-avatar shows your finished avatar instead of jumping to the editor",+ "summary": "When you described an avatar in words at Create → From a prompt, the 'done' screen was meant to show a live, spinnable preview of the character you just made — the payoff moment. For private avatars (the default), that preview was being skipped and you were dropped straight into the editor with no look at the result. The preview now renders for private avatars too, using the same owner-only secure link the selfie flow already used, so every prompt-built avatar greets you with a real 3D preview you can rotate before opening the editor or making another.",+ "link": "/create/prompt",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-23","type": "update",@@ -26,6 +36,17 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Improvement: Base USDC payments confirm even when an RPC provider is flaky",+ "summary": "When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient.",+ "link": null,+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-06-22","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex e8b409659..bfb7dc987 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>fix</category><description>Viewing an avatar in AR on iPhone or iPad (the 'Place in your space' / Quick Look flow) could show a mangled figure — limbs balled up at the hips and accessories like glasses floating at giant scale — instead of the avatar you saw on the page. The cause: the AR file format Apple uses doesn't carry an animation skeleton, so the standard exporter shipped the avatar in its raw, un-posed rig. We now freeze each avatar into its proper standing pose before generating the AR file, so what you place in your room matches what you see in the viewer, accessories included.</description></item>+ <item>+ <title>Fix: prompt-to-avatar shows your finished avatar instead of jumping to the editor</title>+ <link>https://three.ws/create/prompt</link>+ <guid isPermaLink="false">2026-06-23:Fix: prompt-to-avatar shows your finished avatar instead of jumping to the editor</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>When you described an avatar in words at Create → From a prompt, the 'done' screen was meant to show a live, spinnable preview of the character you just made — the payoff moment. For private avatars (the default), that preview was being skipped and you were dropped straight into the editor with no look at the result. The preview now renders for private avatars too, using the same owner-only secure link the selfie flow already used, so every prompt-built avatar greets you with a real 3D preview you can rotate before opening the editor or making another.</description>+ </item><item><title>Fix: the bounty board and live token feeds stay up when a third party is slow</title><link>https://three.ws/changelog</link>@@ -22,6 +30,14 @@<category>fix</category><description>Swept the API for places where a slow or flaky upstream could hang a request until it was force-killed, or a database missing a recent table could error a whole page, and closed them. The /go bounty board now provisions its own database tables, so it loads everywhere instead of erroring where they were absent. The pump trending and search feeds fall back to the last good list (or an empty one) when pump.fun returns a malformed response, rather than failing the page. And a batch of backend lookups — the live SOL price, Jupiter/Birdeye/CoinGecko market data, portfolio price charts, token-gated scene access checks, IPFS pinning, voice synthesis, and the embedded-agent AI fallback chain — now bound every third-party call with a timeout, so a stalled service returns a clean result quickly instead of holding the request open until it's killed.</description></item>+ <item>+ <title>Improvement: Base USDC payments confirm even when an RPC provider is flaky</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Improvement: Base USDC payments confirm even when an RPC provider is flaky</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient.</description>+ </item><item><title>Docs · Agent Reputation</title><link>https://three.ws/docs/agent-reputation</link>diff --git a/public/features.json b/public/features.jsonindex 53365fbb1..71b48db0f 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T01:57:12.660Z",+ "generated_at": "2026-06-23T02:37:55.717Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/tokens.css b/public/tokens.cssindex 1020e364b..4222d07f4 100644--- a/public/tokens.css+++ b/public/tokens.css@@ -133,6 +133,21 @@--danger: #f87171;--warn: #fbbf24;+ /* Wallet identity accent — the violet family that marks every wallet surface+ (chip, HUD, vanity studio) as one coherent system across the app. Route all+ wallet UI through these tokens rather than scattering raw rgba(139,92,246,…).+ accent default chip text / glow+ accent-soft chip fill (low alpha)+ stroke chip border+ hi vanity-highlighted address glyphs (pure white) */+ --wallet-accent: #c4b5fd;+ --wallet-accent-strong: #a78bfa;+ --wallet-accent-soft: rgba(139, 92, 246, 0.10);+ --wallet-accent-fill: rgba(139, 92, 246, 0.15);+ --wallet-stroke: rgba(139, 92, 246, 0.30);+ --wallet-stroke-strong: rgba(139, 92, 246, 0.50);+ --wallet-glow: rgba(139, 92, 246, 0.45);+/* Solid near-black backgrounds — opaque counterparts to the translucent--surface-* overlays. Use these for solid page/panel fills instead ofhand-typing var(--bg-0) / var(--bg-1) so the monochrome base stays consistent. */diff --git a/scripts/apply-migrations.mjs b/scripts/apply-migrations.mjsindex d7bd6f8d1..e997feef3 100755--- a/scripts/apply-migrations.mjs+++ b/scripts/apply-migrations.mjs@@ -92,11 +92,23 @@ async function listPending() {async function applyOne({ fname, body, hash }) {process.stdout.write(`→ applying ${fname} … `);- // neon HTTP driver requires statements run individually rather than as a- // single multi-statement string. We fall back to splitting on bare ';' at- // line ends; the migrations in this repo are written to be split-safe- // (no procedural blocks, no embedded semicolons in literals).- // Use websocket Pool for multi-statement execution (HTTP driver is single-stmt only).+ // Run the whole file in one round trip via the websocket `Pool`. The Neon HTTP+ // driver is single-statement only, but `pg`'s simple-query protocol (what+ // Pool.query uses for a text-only call) executes a multi-statement string —+ // and, crucially, parses `DO $$ … $$` / dollar-quoted bodies correctly, so+ // migrations may contain procedural blocks and embedded semicolons without any+ // client-side `;` splitting.+ //+ // Transaction semantics (Postgres simple query): a string with two or more+ // commands and no explicit BEGIN/COMMIT runs in one implicit transaction —+ // any failure rolls the whole file back, so a half-applied file can't poison+ // the schema_migrations ledger below. A single-command file autocommits. A+ // file with its own BEGIN/COMMIT manages its own transaction.+ //+ // Footgun for migration authors: CREATE INDEX CONCURRENTLY cannot run inside+ // a transaction, so it must be the *only* command in its file (then it+ // autocommits). Pairing it with any other statement wraps it in the implicit+ // transaction and Postgres rejects it.await pool.query(body);await sql`insert into schema_migrations (filename, sha256)diff --git a/src/create-prompt.js b/src/create-prompt.jsindex 4ee2de440..dca9f2f9b 100644--- a/src/create-prompt.js+++ b/src/create-prompt.js@@ -251,7 +251,11 @@ async function renderDone(avatarId) {$('#open-editor').setAttribute('href', editorUrl);$('#make-another').addEventListener('click', () => resetToCompose());- const modelUrl = avatar?.model_url || avatar?.modelUrl;+ // Private avatars (the default for this flow) have a null public model_url;+ // the owner's GET response carries a short-lived presigned `url` instead.+ // Read both so the "done" preview renders the result the user just made+ // rather than silently bouncing them to the editor.+ const modelUrl = avatar?.model_url || avatar?.url || avatar?.modelUrl;const viewer = /** @type {any} */ ($('#done-model'));if (modelUrl && viewer) viewer.setAttribute('src', modelUrl);diff --git a/src/feature-tour/guide-avatar.js b/src/feature-tour/guide-avatar.jsindex b2d8c3400..f4d31db7f 100644--- a/src/feature-tour/guide-avatar.js+++ b/src/feature-tour/guide-avatar.js@@ -76,6 +76,19 @@ export class GuideAvatar {this._y = 0;this._vy = 0;this._tick = this._tick.bind(this);+ this._onVisibility = this._onVisibility.bind(this);+ }++ // Stop rendering the guide while the tab is backgrounded; resume on return.+ _onVisibility() {+ if (this._headless) return;+ if (document.hidden) {+ cancelAnimationFrame(this._raf);+ this._raf = 0;+ } else if (this.host && this.clock && !this._raf) {+ this.clock.getDelta(); // drop the hidden span so gravity doesn't lurch+ this._raf = requestAnimationFrame(this._tick);+ }}async mount() {@@ -89,6 +102,7 @@ export class GuideAvatar {await this._buildScene();this.clock = new Timer();this._raf = requestAnimationFrame(this._tick);+ document.addEventListener('visibilitychange', this._onVisibility);} catch (err) {console.warn('[tour] guide avatar failed to load — continuing without a rendered body:', err?.message || err);this._headless = true;@@ -421,6 +435,7 @@ export class GuideAvatar {}dispose() {+ document.removeEventListener('visibilitychange', this._onVisibility);cancelAnimationFrame(this._raf);cancelAnimationFrame(this._walkRaf);clearTimeout(this._settleTimer);diff --git a/src/studio/agent-presence.js b/src/studio/agent-presence.jsindex ac3da7184..ac305fa2f 100644--- a/src/studio/agent-presence.js+++ b/src/studio/agent-presence.js@@ -72,6 +72,7 @@ class AgentPresenceElement extends HTMLElement {this._disposed = false;this._currentAvatarId = undefined; // tracks body so we reload only on real changethis._currentModelUrl = null;+ this._currentIdleClip = null; // resting clip, re-applied when Body studio changes itthis._unsubStudio = null;this._unsubMarket = null;this._io = null;@@ -186,14 +187,57 @@ class AgentPresenceElement extends HTMLElement {// Best-effort baked idle so a rig with an "idle" clip loops it; the procedural// IdleAnimation inside AgentAvatar keeps a clip-less rig breathing regardless.+ // The Body studio can pin a different resting clip (e.g. "av-chilling") via+ // meta.studio.body.idleClip — honor it so the persisted body shows everywhere.try {const am = this._viewer.animationManager;- if (am && (await am.ensureLoaded('idle'))) am.crossfadeTo('idle', 0.4);+ const idle = this._idleClip();+ this._currentIdleClip = idle;+ if (am && (await am.ensureLoaded(idle))) am.crossfadeTo(idle, 0.4);+ else if (am && idle !== 'idle' && (await am.ensureLoaded('idle'))) am.crossfadeTo('idle', 0.4);} catch {/* procedural idle covers it */}}+ // The resting clip this avatar loops. Body studio persists a choice under+ // meta.studio.body.idleClip; absent that we use the canonical "idle".+ _idleClip() {+ const pinned = this.getAttribute('data-agent-id') || this.getAttribute('data-avatar-id');+ if (pinned) return 'idle';+ return studio.agent?.meta?.studio?.body?.idleClip || 'idle';+ }++ /**+ * Play a clip on this live avatar — the Body studio's preview/"try it" path.+ * A looping clip (idle/dance) crossfades and stays; a one-shot (wave/jump)+ * plays once and settles back to the resting clip. Safe to call before boot+ * (queued) and no-ops cleanly on a rig that can't drive canonical clips.+ * @param {string} name canonical clip name+ * @param {{ loop?: boolean }} [opts]+ */+ async playClip(name, { loop = false } = {}) {+ if (!name) return;+ if (!this._booted || !this._viewer) {+ if (this._reactQueue.length < 16) this._reactQueue.push({ type: '__clip', name, loop });+ return;+ }+ const am = this._viewer.animationManager;+ if (!am) return;+ try {+ if (am.supportsCanonicalClips && !am.supportsCanonicalClips()) {+ // Non-canonical rig — convey it through emotion instead of a dead no-op.+ this._protocol?.emit({ type: this._ACTION.EMOTE, payload: { trigger: 'curiosity', weight: 0.5 } });+ return;+ }+ if (!(await am.ensureLoaded(name))) return;+ if (loop) am.crossfadeTo(name, 0.35);+ else await am.playOnce(name, { settleTo: this._idleClip(), fade: 0.3 });+ } catch {+ /* clip unavailable on this rig — silent, the avatar keeps its idle */+ }+ }+// Resolve the GLB URL for the agent/avatar this presence should render.// Order: explicit data-avatar-id → studio agent's bound avatar → data-agent-id// → null (designed "no body" state). Never invents a fake body.@@ -269,6 +313,13 @@ class AgentPresenceElement extends HTMLElement {if (agent.avatarId !== this._currentAvatarId) {this._currentAvatarId = agent.avatarId;this._refreshBody();+ return;+ }+ // Body studio changed the resting clip — restyle the loop in place (no reload).+ const idle = agent.meta?.studio?.body?.idleClip || 'idle';+ if (this._booted && idle !== this._currentIdleClip) {+ this._currentIdleClip = idle;+ this.playClip(idle, { loop: true });}}@@ -333,6 +384,8 @@ class AgentPresenceElement extends HTMLElement {*/reactTo(event) {if (!event || typeof event !== 'object') return;+ // Replayed clip-preview requests (queued before boot) route to playClip.+ if (event.type === '__clip') return void this.playClip(event.name, { loop: event.loop });if (!this._booted || !this._avatar || !this._protocol) {// Queue until the avatar is live so an early trade isn't dropped.if (this._reactQueue.length < 16) this._reactQueue.push(event);diff --git a/tests/api/http-redact-url.test.js b/tests/api/http-redact-url.test.jsindex c02936063..979711e95 100644--- a/tests/api/http-redact-url.test.js+++ b/tests/api/http-redact-url.test.js@@ -47,4 +47,30 @@ describe('redactUrl', () => {expect(out).not.toContain('0.12');expect(out).not.toContain('secret');});++ it('strips API keys, bearer/session credentials, wallet secrets, and email', () => {+ const out = redactUrl(+ '/api/x?api-key=HELIUSKEY123&apiKey=DUP&access_token=BEARERTOK' ++ '&authorization=Bearer-XYZ&session=SESS9&private_key=5Jprivkey' ++ '&mnemonic=word1word2&secret=topsecret&email=user%40example.com&keep=ok',+ );+ // Every credential / secret / PII value is gone verbatim.+ for (const leak of [+ 'HELIUSKEY123', 'DUP', 'BEARERTOK', 'Bearer-XYZ', 'SESS9',+ '5Jprivkey', 'word1word2', 'topsecret', '[email protected]', 'user%40example.com',+ ]) {+ expect(out).not.toContain(leak);+ }+ // A genuinely benign param still survives so the log line stays useful.+ expect(out).toContain('keep=ok');+ expect(out).toContain('REDACTED');+ });++ it('redacts a keyed upstream RPC URL (the HELIUS_API_KEY leak path)', () => {+ // web3.js errors embed the keyed RPC URL; redactUrl is what keeps that key+ // out of console / Sentry / Telegram on a 5xx.+ const out = redactUrl('https://mainnet.helius-rpc.com/?api-key=sk_live_DEADBEEF');+ expect(out).not.toContain('sk_live_DEADBEEF');+ expect(out).toContain('REDACTED');+ });});diff --git a/tests/db-retry.test.js b/tests/db-retry.test.jsindex bb7c0bf5d..350d0d5af 100644--- a/tests/db-retry.test.js+++ b/tests/db-retry.test.js@@ -2,7 +2,11 @@// takes a thunk, so no DB or network mocking is needed.import { describe, it, expect, vi } from 'vitest';-import { withDbRetry } from '../api/_lib/db-retry.js';+import { withDbRetry, withDbTimeout, DbTimeoutError } from '../api/_lib/db-retry.js';++function never() {+ return new Promise(() => {}); // a stalled connection: never settles+}function transientError() {// Shape Neon's HTTP driver produces on a cold-start / network blip.@@ -54,4 +58,49 @@ describe('withDbRetry', () => {await expect(withDbRetry(run)).resolves.toBe('ok');expect(run).toHaveBeenCalledTimes(2);});++ it('aborts a stalled query once the total deadline elapses', async () => {+ const run = vi.fn().mockImplementation(never);+ const err = await withDbRetry(run, { timeoutMs: 30 }).catch((e) => e);+ expect(err).toBeInstanceOf(DbTimeoutError);+ expect(err.code).toBe('DB_TIMEOUT');+ // A timeout consumes the whole budget, so a merely-slow query is not retried.+ expect(run).toHaveBeenCalledTimes(1);+ });++ it('does not retry past the deadline when transient errors keep failing fast', async () => {+ // Transient errors reject immediately, so all 3 attempts fit inside a+ // generous budget — the budget only stops *slow* queries, not fast ones.+ const run = vi.fn().mockRejectedValue(transientError());+ await expect(withDbRetry(run, { timeoutMs: 5_000 })).rejects.toThrow(/fetch failed/);+ expect(run).toHaveBeenCalledTimes(3);+ });++ it('with the bound disabled, a fast query still resolves normally', async () => {+ const run = vi.fn().mockResolvedValue('ok');+ await expect(withDbRetry(run, { timeoutMs: 0 })).resolves.toBe('ok');+ expect(run).toHaveBeenCalledTimes(1);+ });+});++describe('withDbTimeout', () => {+ it('resolves a query that beats the deadline', async () => {+ await expect(withDbTimeout(() => Promise.resolve(42), 1_000)).resolves.toBe(42);+ });++ it('rejects with DbTimeoutError when the query stalls', async () => {+ const err = await withDbTimeout(never, 20).catch((e) => e);+ expect(err).toBeInstanceOf(DbTimeoutError);+ expect(err.code).toBe('DB_TIMEOUT');+ });++ it('surfaces the query error unchanged when it rejects before the deadline', async () => {+ const boom = new Error('boom');+ await expect(withDbTimeout(() => Promise.reject(boom), 1_000)).rejects.toBe(boom);+ });++ it('runs the thunk without a timer when the bound is disabled', async () => {+ await expect(withDbTimeout(() => Promise.resolve('ok'), 0)).resolves.toBe('ok');+ await expect(withDbTimeout(() => Promise.resolve('ok'), Infinity)).resolves.toBe('ok');+ });});diff --git a/tests/evm-payment-verify.test.js b/tests/evm-payment-verify.test.jsindex eae191502..6c0524788 100644--- a/tests/evm-payment-verify.test.js+++ b/tests/evm-payment-verify.test.js@@ -59,6 +59,20 @@ describe('verifyEvmUsdcPayment', () => {expect(r.status).toBe('pending');});+ it('degrades to retryable pending when the confirmations RPC read faults', async () => {+ // A transport fault on getBlockNumber must NOT strand a real payment as a+ // hard error — the buyer keeps their funds and the confirm retries. (The+ // failover transport rotates endpoints first; this is the last-resort soft+ // fail when every endpoint is down.)+ h.client.getTransactionReceipt.mockResolvedValue({+ status: 'success', blockNumber: 990n,+ logs: [transferLog({ to: RECIPIENT, value: 1_000_000n })],+ });+ h.client.getBlockNumber.mockRejectedValue(new Error('fetch failed'));+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('pending');+ });+it('rejects a reverted transaction', async () => {h.client.getTransactionReceipt.mockResolvedValue({ status: 'reverted', blockNumber: 990n, logs: [] });const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });diff --git a/walk-sdk/src/companion.js b/walk-sdk/src/companion.jsindex 0cccf2c6d..b999e5585 100644--- a/walk-sdk/src/companion.js+++ b/walk-sdk/src/companion.js@@ -132,6 +132,7 @@ class WalkCompanion {return;}+ this.host?.classList.remove('is-loading');this._restoreState();this._bindEvents();this._greetForRoute();@@ -148,6 +149,9 @@ class WalkCompanion {document.removeEventListener('click', this._onLinkClick, true);document.removeEventListener('visibilitychange', this._onVisibility);window.removeEventListener('pagehide', this._onPageHide);+ clearTimeout(this._inviteTimer);+ clearTimeout(this._orientTimer);+ clearTimeout(this._bubbleTimer);this._picker?.destroy();this._picker = null;this._teardownScene();@@ -159,7 +163,7 @@ class WalkCompanion {_buildDom() {ensureStyles();const host = document.createElement('div');- host.className = 'walk-companion';+ host.className = 'walk-companion is-loading';host.setAttribute('role', 'complementary');host.setAttribute('aria-label', 'Walk companion');const pickerBtn = this.config.enablePicker@@ -168,6 +172,7 @@ class WalkCompanion {host.innerHTML = `<button type="button" class="walk-companion-close" aria-label="Dismiss walk companion" title="Dismiss">×</button>${pickerBtn}+ <div class="walk-companion__skel" aria-hidden="true"></div><div class="walk-companion-bubble" hidden></div><canvas class="walk-companion-canvas" width="${CANVAS_W}" height="${CANVAS_H}"></canvas>`;@@ -530,6 +535,10 @@ function ensureStyles() {.walk-companion{position:fixed;right:16px;bottom:16px;width:${CANVAS_W}px;height:${CANVAS_H}px;z-index:2147483000;pointer-events:none;opacity:0;transform:translateY(12px);transition:opacity .35s ease,transform .35s ease;-webkit-user-select:none;user-select:none}.walk-companion.is-in{opacity:1;transform:translateY(0)}.walk-companion-canvas{position:absolute;inset:0;width:100%;height:100%;z-index:1;pointer-events:auto;cursor:pointer;filter:drop-shadow(0 18px 22px rgba(0,0,0,.32))}+.walk-companion__skel{position:absolute;left:50%;bottom:8%;z-index:0;width:46%;height:70%;transform:translateX(-50%);border-radius:46% 46% 40% 40%/55% 55% 45% 45%;overflow:hidden;opacity:0;transition:opacity .25s ease;pointer-events:none;background:linear-gradient(180deg,rgba(122,162,255,.18),rgba(18,20,28,.10))}+.walk-companion.is-loading .walk-companion__skel{opacity:1}+.walk-companion.is-loading .walk-companion-canvas{opacity:0}+.walk-companion__skel::after{content:'';position:absolute;inset:0;background:linear-gradient(110deg,transparent 18%,rgba(255,255,255,.22) 46%,transparent 72%);transform:translateX(-120%);animation:walk-companion-shimmer 1.2s ease-in-out infinite}.walk-companion-close,.walk-companion-swap{position:absolute;top:2px;z-index:3;width:22px;height:22px;border:none;border-radius:50%;background:rgba(12,14,20,.55);color:#fff;font-size:14px;line-height:1;cursor:pointer;pointer-events:auto;opacity:0;transition:opacity .2s ease,background .2s ease;display:grid;place-items:center;padding:0}.walk-companion-close{right:2px;font-size:15px}.walk-companion-swap{right:28px}@@ -542,7 +551,8 @@ function ensureStyles() {.walk-companion-bubble::after{content:'';position:absolute;left:50%;top:100%;transform:translateX(-50%);border:6px solid transparent;border-top-color:rgba(18,20,28,.94)}@media (max-width:520px){.walk-companion{width:148px;height:208px;right:10px;bottom:10px}.walk-companion-bubble{font-size:11.5px;max-width:170px}}@media (pointer:coarse){.walk-companion-close,.walk-companion-swap{opacity:1;width:26px;height:26px}.walk-companion-swap{right:32px}}-@media (prefers-reduced-motion:reduce){.walk-companion,.walk-companion-bubble{transition:none}}+@keyframes walk-companion-shimmer{to{transform:translateX(120%)}}+@media (prefers-reduced-motion:reduce){.walk-companion,.walk-companion-bubble{transition:none}.walk-companion__skel::after{animation:none;opacity:.5}}`;document.head.appendChild(style);}diff --git a/walk-sdk/src/playground.js b/walk-sdk/src/playground.jsindex 5422ce2b6..60d6ebf62 100644--- a/walk-sdk/src/playground.js+++ b/walk-sdk/src/playground.js@@ -292,10 +292,13 @@ class StrollPlayground {this.mounted = false;this._reduced = prefersReducedMotion();this._raf = 0;+ this._diveTimer = 0;+ this._hintTimer = 0;this._tick = this._tick.bind(this);this._onKeyDown = this._onKeyDown.bind(this);this._onKeyUp = this._onKeyUp.bind(this);this._onResize = this._onResize.bind(this);+ this._onVisibility = this._onVisibility.bind(this);this.char = { x: 0, y: 0, vx: 0, vy: 0, facing: 0 };this._yaw = 0;this.input = { up: false, down: false, left: false, right: false, dive: false };@@ -343,14 +346,27 @@ class StrollPlayground {this.mounted = false;cancelAnimationFrame(this._raf);this._raf = 0;+ clearTimeout(this._diveTimer);+ clearTimeout(this._hintTimer);window.removeEventListener('keydown', this._onKeyDown, true);window.removeEventListener('keyup', this._onKeyUp, true);window.removeEventListener('resize', this._onResize);+ document.removeEventListener('visibilitychange', this._onVisibility);this._clearArm();destroyPicker(this);this._teardown();}+ // Stop the render loop when the tab is backgrounded; resume on return.+ _onVisibility() {+ if (document.hidden) {+ cancelAnimationFrame(this._raf);+ this._raf = 0;+ } else if (this.mounted && !this._raf) {+ this._raf = requestAnimationFrame(this._tick);+ }+ }+currentScreenPos() {return { x: this.char.x - (window.scrollX || 0), y: this.char.y - (window.scrollY || 0) };}@@ -505,6 +521,7 @@ class StrollPlayground {window.addEventListener('keydown', this._onKeyDown, true);window.addEventListener('keyup', this._onKeyUp, true);window.addEventListener('resize', this._onResize);+ document.addEventListener('visibilitychange', this._onVisibility);}_onKeyDown(e) {@@ -611,7 +628,7 @@ class StrollPlayground {}this.char.vx = 0;this.char.vy = 0;- setTimeout(go, 560);+ this._diveTimer = setTimeout(go, 560);}_tick() {@@ -750,10 +767,13 @@ class PlatformerPlayground {this.mounted = false;this._reduced = prefersReducedMotion();this._raf = 0;+ this._diveTimer = 0;+ this._hintTimer = 0;this._tick = this._tick.bind(this);this._onKeyDown = this._onKeyDown.bind(this);this._onKeyUp = this._onKeyUp.bind(this);this._onResize = this._onResize.bind(this);+ this._onVisibility = this._onVisibility.bind(this);this._scheduleRescan = this._scheduleRescan.bind(this);this.char = { x: 0, y: 0, vx: 0, vy: 0, grounded: false, facing: 1 };this.platform = null;@@ -804,15 +824,28 @@ class PlatformerPlayground {this.mounted = false;cancelAnimationFrame(this._raf);this._raf = 0;+ clearTimeout(this._diveTimer);+ clearTimeout(this._hintTimer);window.removeEventListener('keydown', this._onKeyDown, true);window.removeEventListener('keyup', this._onKeyUp, true);window.removeEventListener('resize', this._onResize);window.removeEventListener('scroll', this._scheduleRescan, true);+ document.removeEventListener('visibilitychange', this._onVisibility);this._clearArm();destroyPicker(this);this._teardown();}+ // Stop the render loop when the tab is backgrounded; resume on return.+ _onVisibility() {+ if (document.hidden) {+ cancelAnimationFrame(this._raf);+ this._raf = 0;+ } else if (this.mounted && !this._raf) {+ this._raf = requestAnimationFrame(this._tick);+ }+ }+currentScreenPos() {return { x: this.char.x - (window.scrollX || 0), y: this.char.y - (window.scrollY || 0) };}@@ -1000,6 +1033,7 @@ class PlatformerPlayground {window.addEventListener('keyup', this._onKeyUp, true);window.addEventListener('resize', this._onResize);window.addEventListener('scroll', this._scheduleRescan, true);+ document.addEventListener('visibilitychange', this._onVisibility);}_onKeyDown(e) {@@ -1111,7 +1145,7 @@ class PlatformerPlayground {this.char.vx = 0;this.char.vy = TERMINAL;this.char.grounded = false;- setTimeout(go, 620);+ this._diveTimer = setTimeout(go, 620);}_tick() {