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.

Add IRL privacy center, floor anchor, sniper status/guards; element skeleton

nirholase295a18f66de
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a2ae9e18..f78e53f59 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **IRL agents now materialize as you walk up to them** — On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going. (`/irl`) `[fix, improvement]`
- **IRL agents now visibly react when someone engages them** — Walk past an agent placed in the real world and it now feels alive: the moment anyone standing nearby taps it, leaves it a message, or pays it, the agent does a little perk-up and a reaction floats up off its head — a 💜 for a glance, a ✨ 'paid' burst for a real on-chain payment, a 💬 for a message — and everyone viewing that spot sees it at once, not just the person who acted. A busy agent looks busy, which is the whole point of putting one somewhere public. Rapid taps are smoothed so the same person can't spam the reaction, while payments and messages always come through. The reaction is purely a visual flourish — it carries no one's location or wallet — and if your connection drops to the slower fallback the interaction is still recorded for the owner; only the live animation is skipped. (`/irl`) `[feature]`
- **IRL agents turn to look at you as you move around them** — On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you. (`/irl`) `[improvement]`
+- **IRL floor anchoring now survives a locked phone, an incoming call, and lost tracking** — Placing an agent on the real floor in /irl now recovers gracefully from everything the real world throws at it. Lock your phone or take a call mid-session and it pauses cleanly, then resumes — or exits and puts you right back in Camera AR — instead of freezing on a stuck overlay. If the camera loses its fix on the room (low light, a blank wall), you get a clear 'move to a brighter, more textured spot' prompt that clears itself the moment tracking returns. On devices that can't lock an anchor perfectly, the agent is still placed and saved but now tells you honestly it may drift. And a quick tap before your location has locked in still saves your spot exactly once, the instant GPS catches up. (`/irl`) `[improvement, fix]`
- **IRL has its own logo** — The /irl world now carries a proper mark of its own: the three.ws crystal cube floating above an augmented-reality ground reticle, connected by a placement beam — a tiny picture of exactly what IRL does, anchor a 3D agent to a real spot. It replaces the plain text tag at the top of the camera view and shows up on the welcome screen too, and the cube's anchor glows green the moment Camera AR goes live. A full-resolution app-icon version ships alongside it. (`/irl`) `[improvement]`
- **IRL never shows a blank screen — every state is now designed** — Every corner of three.ws/irl now tells you what's going on instead of leaving a blank space. The radar minimap reads 'No agents in range' when an area is quiet, and 'Can't refresh' if the nearby feed briefly drops — then recovers on its own. The nearby count, when GPS is live but nobody's pinned around you yet, invites you to be the first to drop an agent there rather than simply disappearing. Tap an agent's Pay or Use button without a wallet connected and you now get a clear, lasting card explaining how to connect one — instead of a message that flashes away before you can read it. And your IRL Placements dashboard now has a proper loading skeleton, a friendly empty state when you haven't placed anything, and a retry button if the list can't load — never a spinner that hangs or a void. (`/irl`) `[improvement]`
- **IRL now fails gracefully — clear states instead of blank screens** — Every part of three.ws/irl now shows a designed state when something isn't right, instead of a blank screen or a message that flashes for three seconds and disappears. On a device or browser that can't run the AR view, IRL now says so up front and points you to browse agents and the marketplace on the web. If an agent's 3D avatar fails to load, you get a clear card with a Retry button instead of the scene just sitting empty. Your My pins list now tells the difference between 'you haven't placed any yet' and 'we couldn't load them right now' — the latter offers a retry instead of pretending the list is empty. When the nearby-agents view can't refresh, the count now says so and keeps retrying rather than silently looking deserted. And camera issues — no access granted, or a browser with no camera at all — now show a recoverable card explaining what to do, noting the 3D scene still works without the camera. (`/irl`) `[improvement, fix]`
@@ -26,6 +27,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **IRL stays smooth at crowded locations** — three.ws/irl now holds a steady frame rate even when a busy spot is packed with placed agents. Only the nearest few load as full 3D avatars; agents further out render as lightweight cardboard-style billboards that cost almost nothing, and ones far past that fade out entirely until you walk closer. As you move, avatars load nearest-first and the ones you leave behind are freed from memory, so a long walk past dozens of agents never piles up. IRL also reads your device on startup and picks a matching quality level — turning down resolution and shadows on lower-end phones — and if the frame rate dips under load it steps quality down on the fly and back up when there's room, so the camera view degrades gracefully instead of stuttering. (`/irl`) `[improvement, infra]`
- **IRL walks you through camera, motion & location — and never dead-ends on a blocked permission** — The first time you open three.ws/irl, a quick setup card explains why each sensor matters and asks for one at a time: the camera to see your agents in the real world, motion to look around, and location to place agents and discover the ones others left nearby. Every outcome is designed — you see why we’re asking, a green check when access is granted, and if you decline you get the exact steps to switch it back on (the precise iOS Settings path on iPhone) with a Try again button, not a toast that vanishes. Sensors your device doesn’t have are handled honestly, with a note on what still works. Block something later and a one-tap ‘Enable camera’ or ‘Enable location’ chip stays in the top bar so recovery is always within reach — and turning on the camera or pinning an agent re-asks through the same clear cards instead of failing silently. Your choices are remembered, so you’re never nagged twice. (`/irl`) `[feature, improvement]`
- **IRL world: placed agents are private by location — discovered only in person** — We changed how the /irl world reveals where agents are placed, for safety. There is no list, map, or feed of agent locations anywhere: an agent's spot is shared with your device only when you are physically within a short distance of it, so you come across one by walking up and pointing your camera — never by browsing locations from afar. The live realtime server no longer broadcasts a neighborhood's placements to everyone connected; it now carries only presence (how many people are viewing nearby) and ambient reactions, both kept coarse and anonymous. The 'nearby' read is hard-capped to a tight radius and rate-limited so it can't be swept to rebuild a map. Placing agents and the multiplayer presence layer keep working as before. (`/irl`) `[security, improvement]`
+- **IRL: a pinned agent stays rock-steady even when your phone's compass glitches** — Placing an agent in the real world leans on your phone's compass and motion sensors, and real phones hand those out badly all the time — an uncalibrated compass, a magnetic dead-zone as you walk past a fridge or a car, a dropped sensor frame. Any one of those could make a pinned agent suddenly spin, freeze, or vanish from the camera. IRL now shrugs them off: a bad reading is ignored and the last good one held rather than snapping the view, the compass is watched for going stale and the camera quietly falls back to motion-only tracking when it does, and the spot where the compass rolls past north is eased through instead of whipping around. The agent holds its place and its bearing no matter what the sensors do. (`/irl`) `[fix]`
+- **IRL: agents on the edge of range no longer flicker in and out as you stand still** — An agent placed right at the edge of your discovery range used to blink in and out: phone GPS wanders several metres every second, so an agent sitting near the boundary kept crossing the line, and its 3D avatar would spawn, vanish, and respawn on repeat — wasted loads and a jittery, unpolished feel. The /irl world now holds an agent steady once you've found it: you still discover one only by walking within range, but it then stays put until you genuinely move well away, and a single noisy GPS reading can no longer evict it. Agents also ease in and out with a smooth scale instead of popping (and stay instant if you've asked your device to reduce motion). (`/irl`) `[fix]`
- **IRL: extra guards so your location never leaks into our logs** — Two privacy hardening passes on the /irl world. First, when you look for nearby agents your device sends its position in the request — if that request ever hit a server error, your exact coordinates and your device's anonymous token could have been written into our internal error logs and alerts. We now scrub location and device tokens out of anything that gets logged, so a hiccup can never spill where you are. Second, the coordinates the 'nearby' feed hands back are now rounded to roughly a metre instead of full satellite precision: still exact enough to see an agent as you walk up to it, but no longer carrying a pinpoint-precise reading that could fingerprint a spot. Placing and discovering agents works exactly as before. (`/irl`) `[security]`
- **IRL: pinned agents now stay put in your room instead of following the camera** — When you turned on Camera AR and tapped Pin here, the agent was supposed to stay anchored to a real spot so you'd only see it by pointing your phone at it — but unless a precise GPS fix had already landed (or if location was off), it stayed glued to the center of the screen and panned around with you. The world-lock that rotates the view with your phone only ran in full GPS mode; without it the camera silently fell back to an orbit that kept the agent centered. Pinning now world-locks immediately using your phone's motion sensors: the agent holds the exact spot where you placed it, the view rotates as you turn, and it slides off-screen and back as you pan — with no wait for GPS. When a location fix does arrive it upgrades to the shared, cross-user anchor as before. (`/irl`) `[fix]`
- **Jump straight from an agent's profile into IRL or XR** — Every agent profile now has View in IRL and View in XR buttons next to See in 3D. View in IRL drops you into three.ws/irl already wearing that agent's body, and if the same agent is placed nearby it flashes its pin and opens its card so you land right on it. View in XR opens the immersive AR/VR viewer with that agent loaded. Both are real links, so you can open them in a new tab, and every agent has a body to show — its own 3D model or the shared mannequin — so the buttons are never dead ends. This matches the Walk IRL / View in XR buttons avatars already had, so the whole platform now routes into the immersive layer from one surface to the next. (`/irl`) `[feature]`
diff --git a/api/_lib/agent-trade-guards.js b/api/_lib/agent-trade-guards.js
new file mode 100644
index 000000000..e5e88a9fc
--- /dev/null
+++ b/api/_lib/agent-trade-guards.js
@@ -0,0 +1,322 @@
+// Per-agent spend guardrails + custody ledger — the single policy that governs
+// every outbound movement of a custodial agent wallet's funds.
+//
+// One policy, enforced everywhere:
+// - withdraw (api/agents/solana-wallet.js handleWithdraw)
+// - x402 pay (api/x402-pay.js)
+// - snipe (workers/agent-sniper/executor.js)
+// - trade (the authenticated agent-wallet trade endpoint — calls these)
+//
+// Limits are stored on the agent row at meta.spend_limits and are opt-in: an
+// unset ceiling (null) means "no global cap" so existing automated flows keep
+// their own per-feature caps until an owner tightens the policy. Once an owner
+// sets a ceiling it is a HARD limit applied uniformly across all four paths.
+//
+// daily_usd rolling-24h total USD-equivalent outflow ceiling
+// per_tx_usd max USD-equivalent for any single outbound tx
+// withdraw_allowlist if non-empty, withdraws may only target these addresses
+//
+// Spends are recorded into agent_custody_events (the audit trail + ledger). The
+// daily ceiling is enforced by summing the last 24h of priced spend rows. SOL
+// and USDC are always priceable; an arbitrary SPL withdraw that we can't price
+// is governed by the allowlist (+ the per-user withdraw rate limit) rather than
+// the USD cap — withdraw is an owner-initiated recovery path, not an autonomous
+// spend, so we never block the owner from sweeping their own funds out.
+
+import { PublicKey } from '@solana/web3.js';
+import { sql } from './db.js';
+import { solUsdPrice } from './avatar-wallet.js';
+import { logAudit } from './audit.js';
+
+// Base58 alphabet, 32–44 chars covers every ed25519 pubkey. A cheap pre-filter
+// before the (heavier) PublicKey parse + curve check.
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+const MAX_ALLOWLIST = 50;
+
+export const SPEND_LIMIT_DEFAULTS = Object.freeze({
+ daily_usd: null,
+ per_tx_usd: null,
+ withdraw_allowlist: [],
+});
+
+/**
+ * A spend-policy breach. Always a structured 4xx (never a 500) so the boundary
+ * can surface the reason to the user verbatim. `.code` is machine-readable;
+ * `.detail` carries the numbers behind the decision for the UI.
+ */
+export class SpendLimitError extends Error {
+ constructor(code, message, detail = {}) {
+ super(message);
+ this.name = 'SpendLimitError';
+ this.status = 403;
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+/**
+ * Validate a Solana destination address.
+ * @returns {{ valid: boolean, reason?: string, base58?: string, pubkey?: PublicKey, onCurve?: boolean }}
+ */
+export function validateSolanaAddress(addr) {
+ const s = typeof addr === 'string' ? addr.trim() : '';
+ if (!s) return { valid: false, reason: 'empty' };
+ if (!BASE58_RE.test(s)) return { valid: false, reason: 'not_base58' };
+ let pubkey;
+ try {
+ pubkey = new PublicKey(s);
+ } catch {
+ return { valid: false, reason: 'not_pubkey' };
+ }
+ // Off-curve addresses are program-derived (PDAs) and usually cannot sign or
+ // be swept again — sending custody funds there risks losing them. We surface
+ // `onCurve` so the withdraw endpoint can refuse a PDA destination.
+ let onCurve = false;
+ try {
+ onCurve = PublicKey.isOnCurve(pubkey.toBytes());
+ } catch {
+ onCurve = false;
+ }
+ return { valid: true, base58: pubkey.toBase58(), pubkey, onCurve };
+}
+
+function numOrNull(v) {
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < 0) return null;
+ return n;
+}
+
+/** Coerce arbitrary input into a clean, bounded spend-limit object. */
+export function normalizeSpendLimits(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const allow = (Array.isArray(r.withdraw_allowlist) ? r.withdraw_allowlist : [])
+ .map((a) => (typeof a === 'string' ? a.trim() : ''))
+ .map((a) => validateSolanaAddress(a))
+ .filter((v) => v.valid)
+ .map((v) => v.base58);
+ // De-dupe while preserving order, cap the list so meta can't be bloated.
+ const seen = new Set();
+ const deduped = [];
+ for (const a of allow) {
+ if (!seen.has(a)) {
+ seen.add(a);
+ deduped.push(a);
+ }
+ if (deduped.length >= MAX_ALLOWLIST) break;
+ }
+ return {
+ daily_usd: numOrNull(r.daily_usd),
+ per_tx_usd: numOrNull(r.per_tx_usd),
+ withdraw_allowlist: deduped,
+ updated_at: typeof r.updated_at === 'string' ? r.updated_at : null,
+ };
+}
+
+/** Read the effective spend limits off an agent's meta blob. */
+export function getSpendLimits(meta) {
+ return normalizeSpendLimits(meta?.spend_limits);
+}
+
+/**
+ * Persist a spend-limit patch onto the agent (owner-only). Only the keys present
+ * in `patch` are changed; the rest are preserved. Writes a custody audit event
+ * and a platform audit-log row. Returns the new normalized limits.
+ */
+export async function setSpendLimits(agentId, userId, patch, { req = null } = {}) {
+ const [row] = await sql`
+ SELECT id, user_id, meta FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row) throw Object.assign(new Error('agent not found'), { status: 404, code: 'not_found' });
+ if (row.user_id !== userId) throw Object.assign(new Error('not your agent'), { status: 403, code: 'forbidden' });
+
+ const prev = getSpendLimits(row.meta);
+ const next = normalizeSpendLimits({
+ daily_usd: 'daily_usd' in patch ? patch.daily_usd : prev.daily_usd,
+ per_tx_usd: 'per_tx_usd' in patch ? patch.per_tx_usd : prev.per_tx_usd,
+ withdraw_allowlist:
+ 'withdraw_allowlist' in patch ? patch.withdraw_allowlist : prev.withdraw_allowlist,
+ });
+ next.updated_at = new Date().toISOString();
+
+ const meta = { ...(row.meta || {}), spend_limits: next };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${agentId}`;
+
+ await recordCustodyEvent({
+ agentId,
+ userId,
+ eventType: 'limit_change',
+ reason: 'spend_limits_updated',
+ meta: { prev, next },
+ }).catch((e) => console.warn('[custody] limit_change record failed', e?.message));
+ logAudit({ userId, action: 'custody.limit_change', resourceId: agentId, meta: { prev, next }, req });
+
+ return next;
+}
+
+/** USD value of a lamports amount at the live SOL/USD price. Throws on price outage. */
+export async function lamportsToUsd(lamports) {
+ const price = await solUsdPrice();
+ return (Number(lamports) / 1e9) * price;
+}
+
+/**
+ * Sum the USD-equivalent of an agent's outbound spends over the trailing window.
+ * Only priced rows (usd not null) count — see module header on unpriced SPL.
+ */
+export async function getDailySpendUsd(agentId, network = 'mainnet', windowHours = 24) {
+ const [row] = await sql`
+ SELECT COALESCE(SUM(usd), 0)::float8 AS usd
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND network = ${network}
+ AND event_type = 'spend'
+ AND status IN ('ok', 'pending', 'confirmed')
+ AND usd IS NOT NULL
+ AND created_at > now() - (${windowHours} || ' hours')::interval
+ `;
+ return Number(row?.usd || 0);
+}
+
+/**
+ * Enforce the per-agent spend policy for one outbound movement.
+ *
+ * @param {object} o
+ * @param {string} o.agentId
+ * @param {object} [o.meta] agent meta (limits read from here if `limits` absent)
+ * @param {object} [o.limits] pre-resolved limits (skips the meta read)
+ * @param {'trade'|'snipe'|'x402'|'withdraw'} o.category
+ * @param {number|null} o.usdValue USD-equivalent of this tx (null = unpriceable)
+ * @param {string} [o.destination] base58 recipient (required for allowlist on withdraw)
+ * @param {string} [o.network]
+ * @returns {Promise<{ ok: true, limits: object, dailySpentUsd: number|null }>}
+ * @throws {SpendLimitError} on any breach (always 4xx)
+ */
+export async function enforceSpendLimit({
+ agentId,
+ meta,
+ limits,
+ category,
+ usdValue,
+ destination,
+ network = 'mainnet',
+}) {
+ const lim = limits || getSpendLimits(meta);
+
+ // 1. Withdraw allowlist — destination gate.
+ if (category === 'withdraw' && lim.withdraw_allowlist.length > 0) {
+ const dest = typeof destination === 'string' ? destination.trim() : '';
+ if (!dest || !lim.withdraw_allowlist.includes(dest)) {
+ throw new SpendLimitError(
+ 'destination_not_allowed',
+ 'That destination is not on this agent’s withdraw allowlist. Add it under Limits & Safety, or send to an allowed address.',
+ { destination: dest || null, allowlist_size: lim.withdraw_allowlist.length },
+ );
+ }
+ }
+
+ const hasUsd = typeof usdValue === 'number' && Number.isFinite(usdValue) && usdValue >= 0;
+
+ // 2. Per-transaction ceiling.
+ if (lim.per_tx_usd != null && hasUsd && usdValue > lim.per_tx_usd + 1e-9) {
+ throw new SpendLimitError(
+ 'per_tx_exceeded',
+ `This ${category} is $${usdValue.toFixed(2)}, over the per-transaction limit of $${lim.per_tx_usd.toFixed(2)}.`,
+ { usd: usdValue, per_tx_usd: lim.per_tx_usd },
+ );
+ }
+
+ // 3. Rolling daily ceiling.
+ let dailySpentUsd = null;
+ if (lim.daily_usd != null && hasUsd) {
+ dailySpentUsd = await getDailySpendUsd(agentId, network);
+ if (dailySpentUsd + usdValue > lim.daily_usd + 1e-9) {
+ throw new SpendLimitError(
+ 'daily_exceeded',
+ `This ${category} would bring today’s spend to $${(dailySpentUsd + usdValue).toFixed(2)}, over the daily limit of $${lim.daily_usd.toFixed(2)}.`,
+ { usd: usdValue, spent_usd: dailySpentUsd, daily_usd: lim.daily_usd },
+ );
+ }
+ }
+
+ return { ok: true, limits: lim, dailySpentUsd };
+}
+
+const CUSTODY_COLUMNS = [
+ 'agent_id', 'user_id', 'event_type', 'category', 'network', 'asset',
+ 'amount_lamports', 'amount_raw', 'usd', 'destination', 'signature',
+ 'reason', 'status', 'idempotency_key', 'meta',
+];
+
+/**
+ * Write a row into the custody audit trail / spend ledger.
+ * Returns the new row id. Callers in fire-and-forget contexts should `.catch()`.
+ */
+export async function recordCustodyEvent(e) {
+ const [row] = await sql`
+ INSERT INTO agent_custody_events
+ (agent_id, user_id, event_type, category, network, asset,
+ amount_lamports, amount_raw, usd, destination, signature,
+ reason, status, idempotency_key, meta)
+ VALUES (
+ ${e.agentId},
+ ${e.userId ?? null},
+ ${e.eventType},
+ ${e.category ?? null},
+ ${e.network ?? 'mainnet'},
+ ${e.asset ?? null},
+ ${e.amountLamports != null ? String(e.amountLamports) : null},
+ ${e.amountRaw != null ? String(e.amountRaw) : null},
+ ${e.usd ?? null},
+ ${e.destination ?? null},
+ ${e.signature ?? null},
+ ${e.reason ?? null},
+ ${e.status ?? 'ok'},
+ ${e.idempotencyKey ?? null},
+ ${JSON.stringify(e.meta ?? {})}::jsonb
+ )
+ RETURNING id
+ `;
+ return row?.id ?? null;
+}
+
+/** Update a custody row by id (e.g. flip a pending withdraw to confirmed/failed). */
+export async function updateCustodyEvent(id, patch) {
+ await sql`
+ UPDATE agent_custody_events
+ SET status = COALESCE(${patch.status ?? null}, status),
+ signature = COALESCE(${patch.signature ?? null}, signature),
+ usd = COALESCE(${patch.usd ?? null}, usd),
+ amount_lamports = COALESCE(${patch.amountLamports != null ? String(patch.amountLamports) : null}, amount_lamports),
+ meta = CASE WHEN ${patch.meta ? JSON.stringify(patch.meta) : null}::jsonb IS NULL
+ THEN meta ELSE meta || ${patch.meta ? JSON.stringify(patch.meta) : '{}'}::jsonb END,
+ updated_at = now()
+ WHERE id = ${id}
+ `;
+}
+
+/** Convenience wrapper for the common case: record one outbound 'spend'. */
+export async function recordSpend(e) {
+ return recordCustodyEvent({ ...e, eventType: 'spend' });
+}
+
+/**
+ * Read the agent's recent custody events for the owner-facing audit feed.
+ * Cursor is the `id` of the last row seen (descending, so strictly-less-than).
+ */
+export async function listCustodyEvents(agentId, { limit = 50, beforeId = null, network = null } = {}) {
+ const lim = Math.min(200, Math.max(1, Number(limit) || 50));
+ const rows = await sql`
+ SELECT id, event_type, category, network, asset, amount_lamports, amount_raw,
+ usd, destination, signature, reason, status, created_at, meta
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ AND (${network}::text IS NULL OR network = ${network})
+ AND (${beforeId}::bigint IS NULL OR id < ${beforeId})
+ ORDER BY id DESC
+ LIMIT ${lim}
+ `;
+ return rows;
+}
diff --git a/api/irl/pins.js b/api/irl/pins.js
index 0bdf903d6..c91ebacc7 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -846,8 +846,11 @@ export default wrap(async (req, res) => {
? Math.min(500, Math.max(0, pose.gpsAccuracyM)) : null;
const altitudeM = Number.isFinite(pose.altitudeM) ? pose.altitudeM : null;
// 'webxr' (A1) · 'gyro-gps' (absolute compass heading) · 'gyro-gps:rel'
- // (page-relative heading only — A3 down-weights its cross-user bearing).
+ // (page-relative heading only — A3 down-weights its cross-user bearing) ·
+ // 'map' (L2: a point chosen on the map, not a live fix — its bearing isn't
+ // compass-trustworthy, same down-weighting as ':rel').
const anchorSource = pose.source === 'webxr' ? 'webxr'
+ : pose.source === 'map' ? 'map'
: pose.source === 'gyro-gps:rel' ? 'gyro-gps:rel' : 'gyro-gps';
// Room frame (optional) — when the client places into a shared room it sends
@@ -923,6 +926,10 @@ export default wrap(async (req, res) => {
const body = req.body ?? {};
const { id } = body;
if (!id) return json(res, 400, { error: 'id required' });
+ // Reject a malformed pin id up front (covers calibrate / outfit / field-edit):
+ // the id is a server-minted UUID, so anything else is a bad request, not a
+ // row that happens not to exist.
+ if (!isValidPinId(id)) return json(res, 400, { error: 'invalid pin id' });
// ── Calibrate — a small, owner-gated pose correction (A3) ─────────────
// Owner-gated for both authenticated owners and the anonymous device that
diff --git a/api/sniper/status.js b/api/sniper/status.js
new file mode 100644
index 000000000..65c62fb96
--- /dev/null
+++ b/api/sniper/status.js
@@ -0,0 +1,129 @@
+// @ts-check
+/**
+ * Agent Sniper — worker liveness status.
+ *
+ * GET /api/sniper/status
+ *
+ * Answers "is the sniper worker alive AND is its feed actually live?" without
+ * SSHing into Cloud Run. The agent-sniper worker (workers/agent-sniper) is a
+ * long-lived process that holds the PumpPortal feed open and upserts a
+ * bot_heartbeat row (worker='agent-sniper') every SNIPER_HEARTBEAT_MS. This
+ * endpoint reads that row and derives the operational truth:
+ *
+ * alive — a heartbeat within the freshness window (process is up)
+ * feedLive — the worker reports its feed subscription is currently up
+ * degraded — alive but the feed has been silent past its watchdog window
+ * (the worst, otherwise-invisible failure: up but deaf)
+ *
+ * The two cheapest counts (active strategies, open positions) give the page a
+ * one-glance "what is it doing" without a second round-trip. Public + IP
+ * rate-limited — the worker's status carries no secrets, and the whole point of
+ * the platform's status surface is that anyone can see it's running.
+ *
+ * No heartbeat row yet (fresh deploy, never started) → ok:true with
+ * `state: 'unknown'`, so /status renders an honest "not yet reporting" state
+ * rather than a false-red "down".
+ */
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+
+const WORKER = 'agent-sniper';
+// Allow 2× the default heartbeat cadence (30s) plus slack before declaring the
+// worker dead, so one skipped beat under load doesn't flap the status.
+const HEARTBEAT_FRESH_MS = 90_000;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ let beat = null;
+ let strategies = null;
+ let openPositions = null;
+ try {
+ [beat] = await sql`
+ SELECT mode, last_beat_at, meta FROM bot_heartbeat
+ WHERE worker = ${WORKER}
+ LIMIT 1
+ `;
+ // Context counts are best-effort — never block the liveness answer on them.
+ const [stratRow] = await sql`
+ SELECT count(*)::int AS n FROM agent_sniper_strategies
+ WHERE enabled AND NOT kill_switch
+ `;
+ strategies = stratRow?.n ?? null;
+ const [posRow] = await sql`
+ SELECT count(*)::int AS n FROM agent_sniper_positions
+ WHERE status IN ('opening', 'open', 'closing')
+ `;
+ openPositions = posRow?.n ?? null;
+ } catch (err) {
+ // DB unreachable: report unknown rather than a misleading green/red. This
+ // endpoint's own answering is NOT proof the separate worker is alive.
+ return json(
+ res,
+ 200,
+ { ok: true, state: 'unknown', reason: 'status store unreachable', error: err?.code || 'db_error' },
+ { 'cache-control': 'public, max-age=5' },
+ );
+ }
+
+ if (!beat) {
+ return json(
+ res,
+ 200,
+ {
+ ok: true,
+ state: 'unknown',
+ reason: 'no heartbeat reported yet',
+ strategies,
+ openPositions,
+ },
+ { 'cache-control': 'public, max-age=10' },
+ );
+ }
+
+ const now = Date.now();
+ const lastBeatMs = beat.last_beat_at ? new Date(beat.last_beat_at).getTime() : 0;
+ const ageMs = lastBeatMs ? now - lastBeatMs : null;
+ const alive = ageMs != null && ageMs < HEARTBEAT_FRESH_MS;
+ const meta = beat.meta && typeof beat.meta === 'object' ? beat.meta : {};
+ const feedLive = alive && meta.feedConnected === true;
+ // Alive but the feed is silent past its watchdog window → degraded (deaf).
+ const watchdogMs = Number(meta.feedWatchdogMs) || 180_000;
+ const feedSilent = alive && Number(meta.lastEventAgeMs) > watchdogMs;
+
+ const state = !alive ? 'down' : feedSilent || !feedLive ? 'degraded' : 'live';
+
+ return json(
+ res,
+ 200,
+ {
+ ok: state === 'live',
+ state,
+ mode: beat.mode || meta.mode || 'unknown',
+ network: meta.network || 'mainnet',
+ feedLive,
+ feedSilent: !!feedSilent,
+ lastBeatAt: beat.last_beat_at ?? null,
+ heartbeatAgeMs: ageMs,
+ lastEventAgeMs: meta.lastEventAgeMs ?? null,
+ reconnects: meta.reconnects ?? null,
+ errors: meta.errors ?? null,
+ lastError: meta.lastError ?? null,
+ globalKill: meta.globalKill ?? null,
+ intel: meta.intel ?? null,
+ inFlightBuys: meta.inFlightBuys ?? null,
+ bootAt: meta.bootAt ?? null,
+ strategies: meta.strategies ?? strategies,
+ openPositions,
+ },
+ // Heartbeat refreshes every ~30s; a short shared cache absorbs status-page
+ // bursts without meaningfully staling the liveness answer.
+ { 'cache-control': 'public, max-age=5' },
+ );
+});
diff --git a/data/changelog.json b/data/changelog.json
index 15d859adf..b7e80ebc5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,27 @@
{
"$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-17",
+ "title": "IRL: a pinned agent stays rock-steady even when your phone's compass glitches",
+ "summary": "Placing an agent in the real world leans on your phone's compass and motion sensors, and real phones hand those out badly all the time — an uncalibrated compass, a magnetic dead-zone as you walk past a fridge or a car, a dropped sensor frame. Any one of those could make a pinned agent suddenly spin, freeze, or vanish from the camera. IRL now shrugs them off: a bad reading is ignored and the last good one held rather than snapping the view, the compass is watched for going stale and the camera quietly falls back to motion-only tracking when it does, and the spot where the compass rolls past north is eased through instead of whipping around. The agent holds its place and its bearing no matter what the sensors do.",
+ "tags": ["fix"],
+ "link": "/irl"
+ },
+ {
+ "date": "2026-06-17",
+ "title": "IRL: agents on the edge of range no longer flicker in and out as you stand still",
+ "summary": "An agent placed right at the edge of your discovery range used to blink in and out: phone GPS wanders several metres every second, so an agent sitting near the boundary kept crossing the line, and its 3D avatar would spawn, vanish, and respawn on repeat — wasted loads and a jittery, unpolished feel. The /irl world now holds an agent steady once you've found it: you still discover one only by walking within range, but it then stays put until you genuinely move well away, and a single noisy GPS reading can no longer evict it. Agents also ease in and out with a smooth scale instead of popping (and stay instant if you've asked your device to reduce motion).",
+ "tags": ["fix"],
+ "link": "/irl"
+ },
+ {
+ "date": "2026-06-17",
+ "title": "IRL floor anchoring now survives a locked phone, an incoming call, and lost tracking",
+ "summary": "Placing an agent on the real floor in /irl now recovers gracefully from everything the real world throws at it. Lock your phone or take a call mid-session and it pauses cleanly, then resumes — or exits and puts you right back in Camera AR — instead of freezing on a stuck overlay. If the camera loses its fix on the room (low light, a blank wall), you get a clear 'move to a brighter, more textured spot' prompt that clears itself the moment tracking returns. On devices that can't lock an anchor perfectly, the agent is still placed and saved but now tells you honestly it may drift. And a quick tap before your location has locked in still saves your spot exactly once, the instant GPS catches up.",
+ "tags": ["improvement", "fix"],
+ "link": "/irl"
+ },
{
"date": "2026-06-17",
"title": "Sniper dashboard: your live positions now show real-time profit and loss and reconnect on their own",
diff --git a/package.json b/package.json
index e7f81488c..8c3e207d9 100644
--- a/package.json
+++ b/package.json
@@ -82,6 +82,7 @@
"build": "NODE_OPTIONS='--no-deprecation --max-old-space-size=6144' vite build && node scripts/strip-sw-from-embeds.mjs",
"build:wasm": "PATH=\"$HOME/.cargo/bin:$PATH\" RUSTFLAGS='-C target-feature=+simd128' wasm-pack build crates/vanity-grinder --target web --release --out-dir ../../src/solana/vanity/wasm && printf '%s\\n' '# wasm-pack writes a default `*` gitignore that excludes everything.' '# Override it: the generated files in this directory ARE checked in so the' '# app builds without requiring a Rust toolchain at install time. Run' '# `npm run build:wasm` after editing /crates/vanity-grinder/src/lib.rs to' '# refresh these artifacts.' '!*' > src/solana/vanity/wasm/.gitignore",
"build:animations": "node scripts/build-animations.mjs",
+ "build:canonical-rest": "node scripts/build-canonical-rest.mjs",
"extract:animations": "node scripts/extract-glb-animations.mjs && npm run build:animations",
"bake:mannequin": "node scripts/bake-mannequin-glb.mjs",
"build:club-props": "node scripts/build-club-props.mjs",
diff --git a/pages/home.html b/pages/home.html
index 8833ef446..9da947510 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -5850,11 +5850,16 @@
// ── Live feature agents ─────────────────────────────────────────
(function initLiveFeatures() {
var O = location.origin;
+ // `clip` is declarative: the <agent-3d> component honors each clip's
+ // manifest loop flag automatically — one-shots (wave) play once and settle
+ // into idle, loops (rumba/idle) loop seamlessly. No forced loop, so the old
+ // celebrate hard-snap is gone. `framing="portrait"` crops head-to-mid-thigh
+ // so the avatar fills the card instead of standing tiny-and-low.
var LIVE_SPOTS = [
- { id: 'door-create', anim: 'celebrate', loop: true, glb: O + '/avatars/michelle.glb' },
- { id: 'door-embed', anim: 'wave', loop: false, glb: O + '/avatars/cz.glb' },
- { id: 'bento-studio', anim: 'idle', loop: true, glb: null },
- { id: 'bento-anim', anim: 'idle', loop: true, glb: null }
+ { id: 'door-create', clip: 'wave', framing: 'portrait', glb: O + '/avatars/michelle.glb' },
+ { id: 'door-embed', clip: 'rumba', framing: 'portrait', glb: O + '/avatars/cz.glb' },
+ { id: 'bento-studio', clip: 'idle', framing: 'portrait', glb: null },
+ { id: 'bento-anim', clip: 'idle', framing: 'full', glb: null }
];
function spawnMini(container, glb, opts) {
@@ -5866,11 +5871,13 @@
el.setAttribute('name-plate', 'off');
el.setAttribute('avatar-chat', 'off');
el.setAttribute('kiosk', '');
+ if (opts.clip) el.setAttribute('clip', opts.clip);
+ if (opts.framing) el.setAttribute('framing', opts.framing);
el.setAttribute('eager', '');
container.appendChild(el);
- el.addEventListener('agent:ready', function() {
- if (el.play) el.play(opts.anim, { loop: opts.loop !== false, fade_ms: 400 });
- }, { once: true });
+ // The component autoplays the declared clip with the polished embed
+ // defaults (skeleton load state, loop-honoring + one-shot→idle settle,
+ // reduced-motion static pose, offscreen render pause). No ready hook.
return el;
}
@@ -5908,7 +5915,11 @@
e.preventDefault(); e.stopPropagation();
var clip = btn.dataset.anim;
var agent = document.querySelector('#bento-anim agent-3d');
- if (agent && agent.play) agent.play(clip, { loop: clip === 'idle', fade_ms: 400 });
+ // Explicit user gesture → playClip honors the clip's loop flag,
+ // settles one-shots into idle, and is allowed to animate even under
+ // reduced motion. Fall back to play() on older bundles.
+ if (agent && agent.playClip) agent.playClip(clip, { userInitiated: true });
+ else if (agent && agent.play) agent.play(clip, { loop: clip === 'idle', fade_ms: 400 });
animPills.querySelectorAll('.bento-pill-btn').forEach(function(p) { p.classList.remove('active'); });
btn.classList.add('active');
});
diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.html
index 23a5395a1..2c324c076 100644
--- a/pages/ibm/x402-demo.html
+++ b/pages/ibm/x402-demo.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
-<meta name="color-scheme" content="light">
+<meta name="color-scheme" content="light dark">
<title>x402 live demo — three.ws × IBM</title>
<meta name="description" content="A live, self-contained x402 demo: pay $0.001 in USDC from your own wallet to call a real three.ws data API. Settled on-chain on Base or Solana. No backend, no account.">
<meta property="og:title" content="x402 live demo — three.ws × IBM">
@@ -23,24 +23,70 @@
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
- --ibm-blue:#0f62fe;
+ /* Carbon G10 (light) — defaults. Every surface token is themed so the dark
+ override below is a single, deliberate switch. */
+ --ibm-blue:#0f62fe; /* accent: text, borders, focus rings */
+ --ibm-blue-fill:#0f62fe; /* fills that carry white text (button, skip link) */
+ --ibm-blue-fill-hover:#0353e9;
--ibm-blue-hover:#0353e9;
+ --ibm-link:#0f62fe; /* AA on white (4.6:1) */
--ibm-ink:#161616;
--ibm-muted:#525252; /* AA on white (7.4:1) */
--ibm-subtle:#595959; /* AA on white (7:1) — was #6f6f6f (3.9:1, failed) */
--ibm-border:#e0e0e0;
--ibm-divider:#c6c6c6;
+ --ibm-surface:#ffffff; /* card / panel fill */
--ibm-field:#f4f4f4;
+ --ibm-field-focus:#ffffff;
--ibm-green:#0e7a32; /* darkened for AA on light fills */
+ --ibm-green-ink:#0e7a32; /* green text on light pill fills */
+ --ibm-green-fill:#defbe6;
--ibm-red:#da1e28;
- --ibm-amber:#8a6100;
+ --ibm-red-ink:#a2191f; /* red text on light fills (AA) */
+ --ibm-red-fill:#fff1f1;
+ --ibm-red-edge:#ffb3b8;
+ --ibm-amber:#8a6100; /* AA on white */
+ --ibm-amber-fill:#fcf4d6;
+ --ibm-skel-a:#e8e8e8;
+ --ibm-skel-b:#f4f4f4;
--font-sans:'IBM Plex Sans',system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;
--font-mono:'IBM Plex Mono',ui-monospace,'SF Mono',Menlo,Consolas,monospace;
--ease:cubic-bezier(.2,.7,.3,1);
}
+/* Carbon G100 (dark) — looks deliberate when embedded in a dark IBM context.
+ Background stays transparent so the page rides the host surface in both schemes. */
+@media (prefers-color-scheme: dark){
+ :root{
+ --ibm-blue:#78a9ff; /* accent on dark — AA as text on G100 (7.2:1) */
+ --ibm-blue-fill:#0f62fe; /* white text stays AA (4.84:1); recognizably IBM blue */
+ --ibm-blue-fill-hover:#1f6fff;
+ --ibm-blue-hover:#a6c8ff;
+ --ibm-link:#78a9ff; /* AA on #161616 (7.2:1) */
+ --ibm-ink:#f4f4f4;
+ --ibm-muted:#c6c6c6; /* AA on #161616 (12:1) */
+ --ibm-subtle:#a8a8a8; /* AA on #161616 (7.4:1) */
+ --ibm-border:#393939;
+ --ibm-divider:#525252;
+ --ibm-surface:#262626; /* card / panel fill on dark */
+ --ibm-field:#393939;
+ --ibm-field-focus:#4c4c4c;
+ --ibm-green:#42be65; /* used as accent edge/dot on dark */
+ --ibm-green-ink:#42be65; /* AA on dark green fill */
+ --ibm-green-fill:#0b2818;
+ --ibm-red:#fa4d56;
+ --ibm-red-ink:#ff8389; /* AA on dark red fill */
+ --ibm-red-fill:#2a1416;
+ --ibm-red-edge:#7f1d1d;
+ --ibm-amber:#f1c21b; /* AA on dark */
+ --ibm-amber-fill:#2a1d10;
+ --ibm-skel-a:#333333;
+ --ibm-skel-b:#3f3f3f;
+ }
+}
+
html,body{background:transparent;font-family:var(--font-sans);color:var(--ibm-ink);font-size:16px;line-height:1.5;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}
-a{color:var(--ibm-blue);text-decoration:none}
+a{color:var(--ibm-link);text-decoration:none}
a:hover{text-decoration:underline}
.mono{font-family:var(--font-mono)}
@@ -48,18 +94,21 @@ a:hover{text-decoration:underline}
:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:2px}
a:focus-visible{outline-offset:3px}
-.skip-link{position:absolute;left:-9999px;top:0;background:var(--ibm-blue);color:#fff;padding:10px 16px;z-index:50;font-weight:600;font-size:14px}
+.skip-link{position:absolute;left:-9999px;top:0;background:var(--ibm-blue-fill);color:#fff;padding:10px 16px;z-index:50;font-weight:600;font-size:14px}
.skip-link:focus{left:8px;top:8px;text-decoration:none}
+/* Visually hidden but available to assistive tech. */
+.sr-only{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
+
.inner{max-width:880px;margin:0 auto;padding:0 16px}
.section{padding:40px 0;border-bottom:1px solid var(--ibm-border)}
.section:last-child{border-bottom:none}
/* ── Global error banner (resilience safety net) ── */
-.err-banner{position:fixed;left:0;right:0;top:0;z-index:60;background:#fff1f1;border-bottom:1px solid #ffb3b8;color:#a2191f;font-size:13px;padding:10px 16px;display:none;align-items:center;gap:12px;justify-content:center}
+.err-banner{position:fixed;left:0;right:0;top:0;z-index:60;background:var(--ibm-red-fill);border-bottom:1px solid var(--ibm-red-edge);color:var(--ibm-red-ink);font-size:13px;padding:10px 16px;display:none;align-items:center;gap:12px;justify-content:center}
.err-banner.show{display:flex}
-.err-banner button{background:none;border:1px solid #ffb3b8;color:#a2191f;font-family:inherit;font-size:12px;font-weight:600;padding:4px 10px;cursor:pointer}
-.err-banner button:hover{background:#ffe0e0}
+.err-banner button{background:none;border:1px solid var(--ibm-red-edge);color:var(--ibm-red-ink);font-family:inherit;font-size:12px;font-weight:600;padding:4px 10px;cursor:pointer;border-radius:2px}
+.err-banner button:hover{background:rgba(218,30,40,.12)}
/* ── Hero ── */
.hero{padding:56px 0 36px}
@@ -71,7 +120,7 @@ a:focus-visible{outline-offset:3px}
/* ── How-it-works ── */
.steps{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:var(--ibm-border);border:1px solid var(--ibm-border);list-style:none;margin-top:24px}
-.step{background:#fff;padding:24px 22px}
+.step{background:var(--ibm-surface);padding:24px 22px}
.step-n{font-family:var(--font-mono);font-size:12px;color:var(--ibm-blue);font-weight:500;margin-bottom:10px}
.step h3{font-size:15px;font-weight:600;margin-bottom:6px}
.step p{font-size:13px;color:var(--ibm-muted);font-weight:300;line-height:1.55}
@@ -84,7 +133,7 @@ a:focus-visible{outline-offset:3px}
.section-lead{font-size:15px;color:var(--ibm-muted);max-width:620px;margin-top:10px;font-weight:300;line-height:1.6}
/* ── Demo card ── */
-.demo{border:1px solid var(--ibm-divider);margin-top:28px;background:#fff}
+.demo{border:1px solid var(--ibm-divider);margin-top:28px;background:var(--ibm-surface)}
.demo-head{padding:22px 24px 18px;border-bottom:1px solid var(--ibm-border);display:flex;flex-wrap:wrap;gap:16px;align-items:flex-end;justify-content:space-between}
.demo-title{font-size:20px;font-weight:600}
.demo-title span{color:var(--ibm-blue)}
@@ -92,6 +141,8 @@ a:focus-visible{outline-offset:3px}
.price-tag{text-align:right;flex:0 0 auto}
.price-tag .amt{font-size:30px;font-weight:300;line-height:1;font-variant-numeric:tabular-nums}
.price-tag .amt strong{font-weight:600;color:var(--ibm-blue)}
+.price-tag .amt.flash{animation:priceflash .42s var(--ease) 1}
+@keyframes priceflash{0%{transform:scale(1)}40%{transform:scale(1.06);opacity:.7}100%{transform:scale(1);opacity:1}}
.price-tag .net{font-size:12px;color:var(--ibm-muted);margin-top:6px}
.demo-body{padding:22px 24px}
@@ -111,7 +162,7 @@ a:focus-visible{outline-offset:3px}
.pv-retry{margin-top:10px;background:none;border:1px solid var(--ibm-divider);color:var(--ibm-ink);font-family:var(--font-sans);font-size:12px;font-weight:500;padding:6px 12px;cursor:pointer}
.pv-retry:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}
/* skeleton */
-.sk{height:11px;border-radius:2px;background:linear-gradient(90deg,#e8e8e8 25%,#f4f4f4 37%,#e8e8e8 63%);background-size:400% 100%;animation:sk 1.4s ease infinite}
+.sk{display:inline-block;height:11px;border-radius:2px;background:linear-gradient(90deg,var(--ibm-skel-a) 25%,var(--ibm-skel-b) 37%,var(--ibm-skel-a) 63%);background-size:400% 100%;animation:sk 1.4s ease infinite}
@keyframes sk{0%{background-position:100% 0}100%{background-position:0 0}}
/* input row */
@@ -119,26 +170,30 @@ a:focus-visible{outline-offset:3px}
.field-wrap{flex:1 1 240px;min-width:0}
.field-wrap label{display:block;font-size:12px;color:var(--ibm-muted);margin-bottom:6px;font-weight:500}
.field{width:100%;height:48px;padding:0 14px;border:none;border-bottom:1px solid var(--ibm-divider);background:var(--ibm-field);font-family:var(--font-mono);font-size:15px;color:var(--ibm-ink);letter-spacing:.04em;outline:none;transition:border-color .12s,background .12s}
-.field:focus{border-bottom:2px solid var(--ibm-blue);background:#fff}
+.field:focus{border-bottom:2px solid var(--ibm-blue);background:var(--ibm-field-focus)}
.field[aria-invalid="true"]{border-bottom:2px solid var(--ibm-red)}
.field-hint{font-size:11px;color:var(--ibm-subtle);margin-top:6px}
.field-hint.err{color:var(--ibm-red)}
-.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;background:var(--ibm-blue);color:#fff;border:none;cursor:pointer;font-family:var(--font-sans);font-size:15px;font-weight:500;letter-spacing:.01em;padding:0 24px;height:48px;min-width:200px;transition:background .12s,transform .04s}
-.btn:hover:not(:disabled){background:var(--ibm-blue-hover)}
+.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;background:var(--ibm-blue-fill);color:#fff;border:none;cursor:pointer;font-family:var(--font-sans);font-size:15px;font-weight:500;letter-spacing:.01em;padding:0 24px;height:48px;min-width:200px;transition:background .12s,transform .04s,box-shadow .12s}
+.btn:hover:not(:disabled){background:var(--ibm-blue-fill-hover)}
.btn:active:not(:disabled){transform:translateY(1px)}
-.btn:disabled{background:#c6c6c6;cursor:not-allowed}
+.btn:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:2px;box-shadow:0 0 0 4px rgba(15,98,254,.25)}
+.btn:disabled{background:var(--ibm-divider);color:var(--ibm-subtle);cursor:not-allowed}
.btn .arrow{font-size:17px;line-height:1}
.btn .spin{width:15px;height:15px;border:2px solid rgba(255,255,255,.45);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite;display:none}
.btn.loading .spin{display:inline-block}
.btn.loading .arrow{display:none}
@media(min-width:560px){.btn{margin-left:1px}}
-.wallet-hint{font-size:11px;color:var(--ibm-subtle);margin-bottom:18px;line-height:1.5}
+.wallet-hint{font-size:11px;color:var(--ibm-subtle);margin-bottom:18px;line-height:1.5;transition:color .12s}
+.wallet-hint b{color:var(--ibm-ink);font-weight:600}
.wallet-hint.offline{color:var(--ibm-amber);font-weight:500}
+.wallet-hint.detected{color:var(--ibm-green)}
+.wallet-hint.detected b{color:var(--ibm-green)}
/* result panel */
-.result{border:1px solid var(--ibm-border);min-height:96px;padding:18px 20px;background:#fff;transition:border-color .15s}
+.result{border:1px solid var(--ibm-border);min-height:96px;padding:18px 20px;background:var(--ibm-surface);transition:border-color .15s}
.result.is-empty{display:flex;align-items:center;justify-content:center;color:var(--ibm-subtle);font-size:13px;text-align:center;font-weight:300;border-style:dashed}
.result.is-loading{border-color:var(--ibm-blue)}
.result.is-error{border-color:var(--ibm-red)}
@@ -150,16 +205,16 @@ a:focus-visible{outline-offset:3px}
@keyframes spin{to{transform:rotate(360deg)}}
.r-status.err{color:var(--ibm-red)}
.r-status.ok{color:var(--ibm-green)}
-.r-check{display:inline-flex;width:18px;height:18px;border-radius:50%;background:var(--ibm-green);color:#fff;align-items:center;justify-content:center;font-size:11px;flex:0 0 auto;animation:pop .3s var(--ease)}
+.r-check{display:inline-flex;width:18px;height:18px;border-radius:50%;background:var(--ibm-green);color:#161616;align-items:center;justify-content:center;font-size:11px;font-weight:700;flex:0 0 auto;animation:pop .3s var(--ease)}
@keyframes pop{0%{transform:scale(0)}60%{transform:scale(1.15)}100%{transform:scale(1)}}
.r-headline{font-size:18px;font-weight:300;margin:12px 0 4px}
.r-headline strong{font-weight:600}
.r-reco{font-size:14px;color:var(--ibm-ink);margin-bottom:14px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.pill{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.05em;padding:2px 9px;border-radius:2px}
-.pill.ok{background:#defbe6;color:var(--ibm-green)}
-.pill.warn{background:#fcf4d6;color:var(--ibm-amber)}
-.pill.bad{background:#fff1f1;color:#a2191f}
+.pill.ok{background:var(--ibm-green-fill);color:var(--ibm-green-ink)}
+.pill.warn{background:var(--ibm-amber-fill);color:var(--ibm-amber)}
+.pill.bad{background:var(--ibm-red-fill);color:var(--ibm-red-ink)}
.matches{border-top:1px solid var(--ibm-border);margin-top:6px;padding-top:12px}
.matches h4{font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--ibm-subtle);margin-bottom:8px;font-weight:600}
@@ -170,8 +225,10 @@ a:focus-visible{outline-offset:3px}
.match .m-sim{font-family:var(--font-mono);color:var(--ibm-muted);font-size:12px;flex:0 0 auto}
.receipt{margin-top:14px;padding-top:12px;border-top:1px solid var(--ibm-border);display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px 20px}
+.receipt-pair{min-width:0}
.receipt .rk{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--ibm-subtle);margin-bottom:2px}
.receipt .rv{font-family:var(--font-mono);font-size:12px;color:var(--ibm-ink);word-break:break-all}
+.receipt .rv a{color:var(--ibm-link)}
.raw{margin-top:14px}
.raw summary{cursor:pointer;font-size:12px;color:var(--ibm-muted);font-weight:500;user-select:none}
@@ -203,16 +260,44 @@ a:focus-visible{outline-offset:3px}
.footer-nav a:hover{color:var(--ibm-blue)}
.footer-legal{padding-top:16px;border-top:1px solid var(--ibm-border);line-height:1.6}
+/* Tablet: keep the 3-up strip but let it breathe; stack the field row earlier. */
+@media(max-width:768px){
+ .section{padding:32px 0}
+ .hero{padding:44px 0 30px}
+}
+
@media(max-width:640px){
.steps{grid-template-columns:1fr}
- .demo-head{flex-direction:column;align-items:flex-start}
+ .demo-head{flex-direction:column;align-items:flex-start;gap:8px}
.price-tag{text-align:left}
.field-row{gap:14px}
.btn{width:100%;min-width:0}
+ .demo-head,.demo-body{padding-left:18px;padding-right:18px}
+}
+
+/* Small phones (≤360px, incl. 320px). Tighten gutters, keep mono strings contained,
+ and never let a long address/hash force a wide layout viewport (the documented iOS
+ overflow gotcha). overflow-wrap:anywhere is the belt-and-braces over word-break. */
+@media(max-width:360px){
+ .inner{padding:0 12px}
+ .demo-head,.demo-body{padding-left:14px;padding-right:14px}
+ .hero h1{font-size:clamp(26px,8vw,34px)}
+ .price-tag .amt{font-size:26px}
+ .preview-row{gap:6px}
+ .preview-row .k{min-width:72px}
+}
+.preview-row .v,.receipt .rv,.match .m-name{overflow-wrap:anywhere}
+
+/* Touch devices: every interactive control clears the 44×44 px minimum. The
+ coarse-pointer query keeps desktop sizing compact while guaranteeing mobile taps. */
+@media(pointer:coarse){
+ .pv-retry,.retry,.copy-btn,.err-banner button{min-height:44px;padding-top:10px;padding-bottom:10px}
+ .footer-nav a{display:inline-flex;align-items:center;min-height:44px}
+ .raw summary{min-height:44px;display:flex;align-items:center}
}
@media(prefers-reduced-motion:reduce){
- *,*::before,*::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important}
+ *,*::before,*::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important;scroll-behavior:auto!important}
}
</style>
</head>
@@ -277,12 +362,13 @@ a:focus-visible{outline-offset:3px}
<div class="demo">
<div class="demo-head">
<div>
- <div class="demo-title">three<span>.ws</span> Symbol Check</div>
+ <h3 class="demo-title">three<span>.ws</span> Symbol Check</h3>
<div class="demo-desc">Is a ticker already taken? Returns exact and look-alike matches across symbols indexed by three.ws.</div>
</div>
<div class="price-tag">
- <div class="amt" id="priceAmt">$<strong>0.001</strong></div>
- <div class="net">USDC · per call</div>
+ <div class="amt" id="priceAmt" aria-hidden="true">$<strong>0.001</strong></div>
+ <div class="net" aria-hidden="true">USDC · per call</div>
+ <span class="sr-only" id="priceSr">Price: one tenth of a cent in USDC per call.</span>
</div>
</div>
@@ -308,10 +394,13 @@ a:focus-visible{outline-offset:3px}
</div>
<div class="wallet-hint" id="walletHint">On a phone? Open this page inside your <b>MetaMask</b> or <b>Phantom</b> in-app browser to pay.</div>
- <!-- result -->
- <div id="result" class="result is-empty" role="status" aria-live="polite">
+ <!-- result. The visible panel is NOT a live region (its success state
+ contains a raw-JSON block that would otherwise be read aloud in full).
+ Concise spoken updates go to #announcer instead. -->
+ <div id="result" class="result is-empty">
Run the call to see live, on-chain-paid data appear here.
</div>
+ <p id="announcer" class="sr-only" role="status" aria-live="polite"></p>
<!-- requirements -->
<div class="note">
@@ -399,6 +488,20 @@ a:focus-visible{outline-offset:3px}
return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
});
}
+ function prefersReducedMotion() {
+ return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
+ }
+ // Replay a one-shot CSS animation class, no-op under reduced motion.
+ function flashPrice(el) {
+ if (!el || prefersReducedMotion()) return;
+ el.classList.remove('flash');
+ void el.offsetWidth; // reflow so the animation restarts on repeat changes
+ el.classList.add('flash');
+ el.addEventListener('animationend', function once() {
+ el.classList.remove('flash');
+ el.removeEventListener('animationend', once);
+ });
+ }
function sanitizeTicker(raw) {
return String(raw || '').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 32);
}
@@ -458,9 +561,16 @@ a:focus-visible{outline-offset:3px}
var first = nets[0];
var decimals = (first.extra && first.extra.decimals) || 6;
- $('priceAmt').innerHTML = first.amount === '1000'
+ var priceHtml = first.amount === '1000'
? '$<strong>0.001</strong>'
: escapeHtml(fmtUsd(first.amount, decimals)).replace(/^\$/, '$<strong>') + '</strong>';
+ var amtEl = $('priceAmt');
+ if (amtEl.innerHTML !== priceHtml) {
+ amtEl.innerHTML = priceHtml;
+ flashPrice(amtEl);
+ }
+ var priceText = escapeHtml(fmtUsd(first.amount, decimals));
+ var srEl = $('priceSr'); if (srEl) srEl.textContent = 'Price: ' + priceText + ' USDC per call.';
var label = $('pvLabel'); label.className = 'preview-label ok fresh';
$('pvLabelText').innerHTML = '<span class="mono">HTTP 402 Payment Required</span> — the server is quoting these terms right now';
@@ -477,18 +587,30 @@ a:focus-visible{outline-offset:3px}
}
// ── 2. result states ──────────────────────────────────────────────────────
+ // Concise spoken update to the off-screen live region. Clearing first guarantees
+ // the change is detected even when the same text repeats.
+ function announce(msg) {
+ var a = $('announcer'); if (!a) return;
+ a.textContent = '';
+ // microtask defer so screen readers register the text change as new
+ window.requestAnimationFrame(function () { a.textContent = msg || ''; });
+ }
function setResultEmpty() {
var el = $('result'); el.className = 'result is-empty';
el.innerHTML = 'Run the call to see live, on-chain-paid data appear here.';
+ announce('');
}
function setResultLoading(msg) {
var el = $('result'); el.className = 'result is-loading';
el.innerHTML = '<div class="r-status"><span class="spin" aria-hidden="true"></span><span>' + escapeHtml(msg || 'Waiting for your wallet…') + '</span></div>';
+ announce(msg || 'Waiting for your wallet.');
}
function setResultError(msg) {
+ var text = msg || 'Something went wrong.';
var el = $('result'); el.className = 'result is-error';
- el.innerHTML = '<div class="r-status err">✕ <span>' + escapeHtml(msg || 'Something went wrong.') + '</span></div><button class="retry" type="button" id="retryBtn">Try again</button>';
+ el.innerHTML = '<div class="r-status err"><span aria-hidden="true">✕</span> <span>' + escapeHtml(text) + '</span></div><button class="retry" type="button" id="retryBtn">Try again</button>';
var rb = $('retryBtn'); if (rb) rb.addEventListener('click', runPayment);
+ announce('Error: ' + text);
}
function recoPill(result) {
if (result.exact_collision) return '<span class="pill bad">taken</span>';
@@ -506,6 +628,12 @@ a:focus-visible{outline-offset:3px}
if (result.ticker) html += '<div class="r-headline">Ticker <strong>$' + escapeHtml(result.ticker) + '</strong></div>';
if (result.recommendation) html += '<div class="r-reco">' + recoPill(result) + '<span>' + escapeHtml(result.recommendation) + '</span></div>';
+ // Concise spoken summary — never the raw-JSON wall below.
+ var spoken = 'Payment settled.';
+ if (result.ticker) spoken += ' Ticker $' + result.ticker + '.';
+ if (result.recommendation) spoken += ' ' + result.recommendation;
+ announce(spoken);
+
var exact = Array.isArray(result.exact_matches) ? result.exact_matches : [];
var similar = Array.isArray(result.similar) ? result.similar : [];
if (exact.length || similar.length) {
@@ -526,14 +654,14 @@ a:focus-visible{outline-offset:3px}
}
var explorer = explorerUrl(payment.network, payment.transaction);
- html += '<div class="receipt">';
- html += '<div><div class="rk">Network</div><div class="rv">' + escapeHtml(networkLabel(payment.network)) + '</div></div>';
- html += '<div><div class="rk">Payer</div><div class="rv">' + escapeHtml(shortAddr(payment.payer)) + '</div></div>';
- html += '<div><div class="rk">Transaction</div><div class="rv">' +
+ html += '<dl class="receipt">';
+ html += '<div class="receipt-pair"><dt class="rk">Network</dt><dd class="rv">' + escapeHtml(networkLabel(payment.network)) + '</dd></div>';
+ html += '<div class="receipt-pair"><dt class="rk">Payer</dt><dd class="rv">' + escapeHtml(shortAddr(payment.payer)) + '</dd></div>';
+ html += '<div class="receipt-pair"><dt class="rk">Transaction</dt><dd class="rv">' +
(payment.transaction
- ? (explorer ? '<a href="' + explorer + '" target="_blank" rel="noopener">' + escapeHtml(shortAddr(payment.transaction)) + ' ↗</a>' : escapeHtml(shortAddr(payment.transaction)))
- : '—') + '</div></div>';
- html += '</div>';
+ ? (explorer ? '<a href="' + explorer + '" target="_blank" rel="noopener">' + escapeHtml(shortAddr(payment.transaction)) + ' <span aria-hidden="true">↗</span><span class="sr-only"> (opens block explorer in a new tab)</span></a>' : escapeHtml(shortAddr(payment.transaction)))
+ : '—') + '</dd></div>';
+ html += '</dl>';
html += '<details class="raw"><summary>View raw response &amp; settlement</summary><pre>' +
escapeHtml(JSON.stringify({ response: result, payment: payment }, null, 2)).slice(0, 6000) + '</pre></details>';
@@ -547,7 +675,7 @@ a:focus-visible{outline-offset:3px}
var btn = $('payBtn');
btn.disabled = b || !navigator.onLine;
btn.classList.toggle('loading', b);
- btn.querySelector('.label').textContent = b ? 'Working…' : 'Pay $0.001 & run';
+ btn.querySelector('.label').textContent = b ? 'Waiting for wallet…' : 'Pay $0.001 & run';
}
function setTickerError(msg) {
var f = $('ticker'); var h = $('tickerHint');
@@ -587,26 +715,55 @@ a:focus-visible{outline-offset:3px}
setResultError((err && err.message) || 'Payment failed. Please try again.');
}).then(function () {
setBusy(false);
- var t = (trigger && trigger.focus) ? trigger : $('payBtn');
- try { t.focus(); } catch (_) {}
+ // Return focus to the trigger; if it was re-rendered out of the DOM
+ // (e.g. the retry button), fall back to the pay button so focus is never
+ // dropped to <body>.
+ var t = (trigger && trigger.focus && document.body.contains(trigger)) ? trigger : $('payBtn');
+ try { t.focus(); } catch (_) { try { $('payBtn').focus(); } catch (_2) {} }
});
}
- // ── offline awareness ──────────────────────────────────────────────────────
- function syncOnline() {
+ // ── wallet detection ────────────────────────────────────────────────────────
+ // On phones, window.ethereum / window.solana only exist inside a wallet's in-app
+ // browser, not in mobile Safari/Chrome. Reflect that reality in the hint so the
+ // next step is obvious. The 402 preview stays fully functional regardless.
+ function hasInjectedWallet() {
+ return !!(window.ethereum || (window.solana && window.solana.isPhantom) || window.phantom);
+ }
+ function isCoarsePointer() {
+ return !!(window.matchMedia && window.matchMedia('(pointer: coarse)').matches);
+ }
+ function syncWalletHint() {
var hint = $('walletHint'); var btn = $('payBtn');
if (!navigator.onLine) {
- hint.classList.add('offline');
+ hint.classList.remove('detected'); hint.classList.add('offline');
hint.innerHTML = 'You are offline. Reconnect to read the live price and pay.';
btn.disabled = true;
+ return;
+ }
+ hint.classList.remove('offline');
+ if (!inFlight) btn.disabled = false;
+ if (hasInjectedWallet()) {
+ hint.classList.add('detected');
+ hint.innerHTML = '<b>Wallet detected.</b> You can pay this call directly.';
+ } else if (isCoarsePointer()) {
+ hint.classList.remove('detected');
+ hint.innerHTML = 'No wallet in this browser. On a phone, open this page inside your <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) in-app browser to pay. You can still read the live 402 challenge above.';
} else {
- hint.classList.remove('offline');
- hint.innerHTML = 'On a phone? Open this page inside your <b>MetaMask</b> or <b>Phantom</b> in-app browser to pay.';
- if (!inFlight) btn.disabled = false;
+ hint.classList.remove('detected');
+ hint.innerHTML = 'No wallet detected. Install <b>MetaMask</b> (Base) or <b>Phantom</b> (Solana) to pay — or just read the live 402 challenge above.';
}
}
- window.addEventListener('online', function () { syncOnline(); loadChallengePreview(); });
- window.addEventListener('offline', syncOnline);
+ // Wallet extensions inject asynchronously; re-check briefly after load.
+ var walletPolls = 0;
+ function pollForWallet() {
+ syncWalletHint();
+ if (!hasInjectedWallet() && walletPolls < 8) { walletPolls++; setTimeout(pollForWallet, 350); }
+ }
+ window.addEventListener('online', function () { syncWalletHint(); loadChallengePreview(); });
+ window.addEventListener('offline', syncWalletHint);
+ // EIP-6963 announce + Phantom late-inject both surface via this event in practice.
+ window.addEventListener('eip6963:announceProvider', syncWalletHint);
// ── wiring ──────────────────────────────────────────────────────────────────
$('payBtn').addEventListener('click', runPayment);
@@ -635,7 +792,7 @@ a:focus-visible{outline-offset:3px}
}
});
- syncOnline();
+ pollForWallet();
loadChallengePreview();
})();
</script>
diff --git a/public/changelog.json b/public/changelog.json
index 0029ebdb6..b14abb74b 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T11:52:57.271Z",
+ "generated_at": "2026-06-17T12:06:13.152Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -140,6 +140,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "IRL floor anchoring now survives a locked phone, an incoming call, and lost tracking",
+ "summary": "Placing an agent on the real floor in /irl now recovers gracefully from everything the real world throws at it. Lock your phone or take a call mid-session and it pauses cleanly, then resumes — or exits and puts you right back in Camera AR — instead of freezing on a stuck overlay. If the camera loses its fix on the room (low light, a blank wall), you get a clear 'move to a brighter, more textured spot' prompt that clears itself the moment tracking returns. On devices that can't lock an anchor perfectly, the agent is still placed and saved but now tells you honestly it may drift. And a quick tap before your location has locked in still saves your spot exactly once, the instant GPS catches up.",
+ "link": "/irl",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
@@ -215,6 +226,26 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "IRL: a pinned agent stays rock-steady even when your phone's compass glitches",
+ "summary": "Placing an agent in the real world leans on your phone's compass and motion sensors, and real phones hand those out badly all the time — an uncalibrated compass, a magnetic dead-zone as you walk past a fridge or a car, a dropped sensor frame. Any one of those could make a pinned agent suddenly spin, freeze, or vanish from the camera. IRL now shrugs them off: a bad reading is ignored and the last good one held rather than snapping the view, the compass is watched for going stale and the camera quietly falls back to motion-only tracking when it does, and the spot where the compass rolls past north is eased through instead of whipping around. The agent holds its place and its bearing no matter what the sensors do.",
+ "link": "/irl",
+ "tags": [
+ "fix"
+ ]
+ },
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "IRL: agents on the edge of range no longer flicker in and out as you stand still",
+ "summary": "An agent placed right at the edge of your discovery range used to blink in and out: phone GPS wanders several metres every second, so an agent sitting near the boundary kept crossing the line, and its 3D avatar would spawn, vanish, and respawn on repeat — wasted loads and a jittery, unpolished feel. The /irl world now holds an agent steady once you've found it: you still discover one only by walking within range, but it then stays put until you genuinely move well away, and a single noisy GPS reading can no longer evict it. Agents also ease in and out with a smooth scale instead of popping (and stay instant if you've asked your device to reduce motion).",
+ "link": "/irl",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index ffe148f76..230e9d194 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -110,6 +110,14 @@
<category>improvement</category>
<description>On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you.</description>
</item>
+ <item>
+ <title>IRL floor anchoring now survives a locked phone, an incoming call, and lost tracking</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-17:IRL floor anchoring now survives a locked phone, an incoming call, and lost tracking</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Placing an agent on the real floor in /irl now recovers gracefully from everything the real world throws at it. Lock your phone or take a call mid-session and it pauses cleanly, then resumes — or exits and puts you right back in Camera AR — instead of freezing on a stuck overlay. If the camera loses its fix on the room (low light, a blank wall), you get a clear 'move to a brighter, more textured spot' prompt that clears itself the moment tracking returns. On devices that can't lock an anchor perfectly, the agent is still placed and saved but now tells you honestly it may drift. And a quick tap before your location has locked in still saves your spot exactly once, the instant GPS catches up.</description>
+ </item>
<item>
<title>IRL has its own logo</title>
<link>https://three.ws/irl</link>
@@ -166,6 +174,22 @@
<category>security</category>
<description>We changed how the /irl world reveals where agents are placed, for safety. There is no list, map, or feed of agent locations anywhere: an agent's spot is shared with your device only when you are physically within a short distance of it, so you come across one by walking up and pointing your camera — never by browsing locations from afar. The live realtime server no longer broadcasts a neighborhood's placements to everyone connected; it now carries only presence (how many people are viewing nearby) and ambient reactions, both kept coarse and anonymous. The 'nearby' read is hard-capped to a tight radius and rate-limited so it can't be swept to rebuild a map. Placing agents and the multiplayer presence layer keep working as before.</description>
</item>
+ <item>
+ <title>IRL: a pinned agent stays rock-steady even when your phone's compass glitches</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-17:IRL: a pinned agent stays rock-steady even when your phone's compass glitches</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Placing an agent in the real world leans on your phone's compass and motion sensors, and real phones hand those out badly all the time — an uncalibrated compass, a magnetic dead-zone as you walk past a fridge or a car, a dropped sensor frame. Any one of those could make a pinned agent suddenly spin, freeze, or vanish from the camera. IRL now shrugs them off: a bad reading is ignored and the last good one held rather than snapping the view, the compass is watched for going stale and the camera quietly falls back to motion-only tracking when it does, and the spot where the compass rolls past north is eased through instead of whipping around. The agent holds its place and its bearing no matter what the sensors do.</description>
+ </item>
+ <item>
+ <title>IRL: agents on the edge of range no longer flicker in and out as you stand still</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-17:IRL: agents on the edge of range no longer flicker in and out as you stand still</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>An agent placed right at the edge of your discovery range used to blink in and out: phone GPS wanders several metres every second, so an agent sitting near the boundary kept crossing the line, and its 3D avatar would spawn, vanish, and respawn on repeat — wasted loads and a jittery, unpolished feel. The /irl world now holds an agent steady once you've found it: you still discover one only by walking within range, but it then stays put until you genuinely move well away, and a single noisy GPS reading can no longer evict it. Agents also ease in and out with a smooth scale instead of popping (and stay instant if you've asked your device to reduce motion).</description>
+ </item>
<item>
<title>IRL: extra guards so your location never leaks into our logs</title>
<link>https://three.ws/irl</link>
diff --git a/public/features.json b/public/features.json
index 1a9acb432..b9eee85fe 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T11:52:55.529Z",
+ "generated_at": "2026-06-17T12:06:13.120Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 05142975c..47ca31a87 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -1,12 +1,71 @@
-import { AnimationClip, AnimationMixer, LoopRepeat, LoopOnce } from 'three';
+import { AnimationClip, AnimationMixer, LoopRepeat, LoopOnce, Quaternion, Vector3 } from 'three';
import { canonicalizeBoneName } from './glb-canonicalize.js';
import {
canonicalNodeMapFromObject,
canonicalRestMapFromObject,
+ hipsParentWorldQuat,
retargetClip,
} from './animation-retarget.js';
import { log } from './shared/log.js';
+// Past this many degrees off vertical, the rig's Hips have tipped onto their
+// back — the catastrophic "lying down" retarget failure. The bind-correction in
+// animation-retarget.js keeps every healthy rig's at-rest Hips under ~18°
+// (measured across cz + michelle × the featured clips, locked in
+// tests/animation-upright-invariant.test.js), so 45° is a generous catastrophe
+// floor that only ever trips a genuinely broken retarget, never a healthy one
+// (dance, the most hip-led clip, peaks at ~30° mid-clip but rests near 18°).
+const CATASTROPHE_TILT_DEG = 45;
+
+// Reused scratch so the guard's once-per-clip measurement allocates nothing.
+const _worldUp = new Vector3();
+const _wq = new Quaternion();
+const _UP = new Vector3(0, 1, 0);
+
+/**
+ * At-rest Hips tilt (degrees off world vertical) a retargeted clip would impose
+ * on a model — the same world-matrix reconstruction the lying-down bug was
+ * diagnosed with, but evaluated from the clip's first Hips keyframe so it costs
+ * nothing per frame. Sets the Hips bone to the clip's keyframe-0 rotation,
+ * composes world matrices, and measures the angle between the bone's world
+ * up-axis and vertical. Restores the bone afterwards so it's side-effect free.
+ * Returns null when there's nothing to measure (no Hips, no quaternion track),
+ * which callers treat as "can't assess" — never as a failure.
+ *
+ * @param {THREE.AnimationClip|null} retargetedClip clip already renamed to the rig's nodes
+ * @param {THREE.Object3D|null} model the attached rig (world matrices may be stale)
+ * @param {Map<string,string>|null} canonicalToNode canonical bone → rig node name
+ * @returns {number|null} degrees off vertical, or null
+ */
+export function measureHipsTiltDeg(retargetedClip, model, canonicalToNode) {
+ if (!retargetedClip || !model || !canonicalToNode) return null;
+ const hipsName = canonicalToNode.get('Hips');
+ if (!hipsName) return null;
+ const hips = model.getObjectByName(hipsName);
+ if (!hips) return null;
+ const qTrack = retargetedClip.tracks.find((t) => t.name === `${hipsName}.quaternion`);
+ if (!qTrack || qTrack.values.length < 4) return null;
+
+ const v = qTrack.values;
+ const restX = hips.quaternion.x;
+ const restY = hips.quaternion.y;
+ const restZ = hips.quaternion.z;
+ const restW = hips.quaternion.w;
+
+ hips.quaternion.set(v[0], v[1], v[2], v[3]);
+ hips.updateWorldMatrix(true, false);
+ hips.getWorldQuaternion(_wq);
+ _worldUp.copy(_UP).applyQuaternion(_wq);
+
+ // Restore the authored rest so the measurement leaves no trace; the mixer
+ // drives the real pose from here on.
+ hips.quaternion.set(restX, restY, restZ, restW);
+ hips.updateWorldMatrix(true, false);
+
+ const dot = Math.max(-1, Math.min(1, _worldUp.dot(_UP)));
+ return (Math.acos(dot) * 180) / Math.PI;
+}
+
// Minimum number of canonical bones a skinned model must expose before the
// pre-baked clip library can drive it meaningfully. The clips address tracks by
// canonical Avaturn bone names; a model sharing only a stray bone or two would
@@ -55,6 +114,21 @@ export class AnimationManager {
this._canonicalToNode = null;
/** @type {boolean} Whether the attached model's rig can play the canonical clip library. */
this._canonicalClipsSupported = false;
+ /** @type {{ avatarId?: string, avatarUrl?: string }} Context for the fallen-pose guard's reports. */
+ this._avatarContext = {};
+ /** @type {Set<string>} `${avatarUrl}|${clip}` keys whose fallen-pose has already been reported (debounce). */
+ this._fallenReported = new Set();
+ /** @type {Set<string>} Clip names disabled because they retargeted to a fallen pose on this rig. */
+ this._fallen = new Set();
+ }
+
+ /**
+ * Tell the manager which avatar is attached so the fallen-pose guard can
+ * report actionable context. Both fields are optional; url alone is enough.
+ * @param {{ avatarId?: string, avatarUrl?: string }} ctx
+ */
+ setAvatarContext(ctx) {
+ this._avatarContext = ctx && typeof ctx === 'object' ? { ...ctx } : {};
}
// ── Model binding ──────────────────────────────────────────────────────────
@@ -63,14 +137,17 @@ export class AnimationManager {
* Attach to a loaded model. Call this every time a new model is loaded.
* Re-creates actions for any clips that are already in memory.
* @param {THREE.Object3D} model
+ * @param {{ avatarId?: string, avatarUrl?: string }} [context] avatar id/url for the fallen-pose guard
*/
- attach(model) {
+ attach(model, context) {
this.detach();
+ if (context) this.setAvatarContext(context);
this.model = model;
this.mixer = new AnimationMixer(model);
this.actions.clear();
this.currentAction = null;
this.currentName = null;
+ this._fallen.clear();
// Build the canonical→node map once. Every clip is retargeted through it,
// so the library drives ANY humanoid rig — Mixamo, VRM-via-Mixamo,
// CharacterStudio, Blender — not just an already-canonical Avaturn rig.
@@ -80,6 +157,9 @@ export class AnimationManager {
// (a Mixamo rig bakes the up-axis as a −90°X Hips rest the clips would
// otherwise overwrite, tipping the avatar onto its back).
this._canonicalRest = canonicalRestMapFromObject(model);
+ // World rotation of the Hips' parent (within the model), so root motion is
+ // re-expressed in the rig's own frame and travels the right way on any rig.
+ this._hipsParentWorldQuat = hipsParentWorldQuat(model);
this._canonicalClipsSupported = _modelSupportsCanonicalClips(model);
for (const [name, clip] of this.clips) {
@@ -103,10 +183,64 @@ export class AnimationManager {
if (!this._canonicalToNode || this._canonicalToNode.size === 0) return null;
const { clip: out } = retargetClip(clip, this._canonicalToNode, {
targetRest: this._canonicalRest,
+ hipsParentWorldQuat: this._hipsParentWorldQuat,
});
return out;
}
+ /**
+ * Runtime "fallen pose" guard. Before an action plays, sample the at-rest Hips
+ * world up-axis the retargeted clip would impose. If it tips past
+ * CATASTROPHE_TILT_DEG the retarget failed (the rig would lie on its back), so
+ * we disable that action, leave the rig in its authored bind pose — the same
+ * fallback the viewer already prefers over a broken retarget — and report once
+ * through the existing client-error channel with enough context to diagnose.
+ * Sampled once per (avatar, clip), never per frame.
+ *
+ * @param {string} name clip name
+ * @param {THREE.AnimationAction} action
+ * @returns {boolean} true if the clip is safe to play; false if it was rejected
+ */
+ _guardAgainstFallenPose(name, action) {
+ if (this._fallen.has(name)) return false;
+ const clip = action?.getClip?.();
+ const tiltDeg = measureHipsTiltDeg(clip, this.model, this._canonicalToNode);
+ if (tiltDeg == null || tiltDeg <= CATASTROPHE_TILT_DEG) return true;
+
+ // Reject: stop and disable the action, drop it so it can't be selected
+ // again, and fall back to the authored bind pose (do not play the broken
+ // clip). If it was the current action, clear playback state.
+ try {
+ action.stop();
+ } catch (e) {
+ log.warn('[AnimationManager] failed to stop fallen-pose action:', e);
+ }
+ action.enabled = false;
+ this.actions.delete(name);
+ this._fallen.add(name);
+ if (this.currentAction === action) {
+ this.currentAction = null;
+ this.currentName = null;
+ }
+
+ const avatarUrl = this._avatarContext.avatarUrl || '';
+ const avatarId = this._avatarContext.avatarId || '';
+ const dedupeKey = `${avatarId || avatarUrl}|${name}`;
+ if (!this._fallenReported.has(dedupeKey)) {
+ this._fallenReported.add(dedupeKey);
+ log.warn(
+ `[AnimationManager] "${name}" retargeted to a fallen pose (${tiltDeg.toFixed(1)}° off vertical) — falling back to bind pose`,
+ );
+ reportFallenPose({
+ avatarId,
+ avatarUrl,
+ clip: name,
+ tiltDeg: Math.round(tiltDeg * 10) / 10,
+ });
+ }
+ return false;
+ }
+
/** Detach, stop all actions, dispose mixer. */
detach() {
if (this.mixer) {
@@ -117,10 +251,12 @@ export class AnimationManager {
this.model = null;
this._canonicalToNode = null;
this._canonicalRest = null;
+ this._hipsParentWorldQuat = null;
this._canonicalClipsSupported = false;
this.actions.clear();
this.currentAction = null;
this.currentName = null;
+ this._fallen.clear();
}
// ── Definitions ────────────────────────────────────────────────────────────
@@ -270,6 +406,9 @@ export class AnimationManager {
}
const action = this.actions.get(name);
if (!action) return;
+ // Reject a retarget that would lie the avatar on its back; fall back to the
+ // authored bind pose rather than play a fallen clip.
+ if (!this._guardAgainstFallenPose(name, action)) return;
if (this.currentAction && this.currentAction !== action) {
this.currentAction.fadeOut(0.01);
@@ -294,7 +433,9 @@ export class AnimationManager {
fade = Math.max(0, Math.min(fade, 5));
const ready = await this.ensureLoaded(name);
const action = ready ? this.actions.get(name) : null;
- if (!action) {
+ // Reject a fallen-pose retarget the same way an unavailable clip is handled:
+ // settle into the looping fallback rather than play the broken one-shot.
+ if (!action || !this._guardAgainstFallenPose(name, action)) {
// One-shot unavailable on this rig — fall back to the settle clip so
// the avatar is never left frozen in its bind pose.
if (settleTo) return this.crossfadeTo(settleTo, fade);
@@ -360,6 +501,10 @@ export class AnimationManager {
}
const next = this.actions.get(name);
if (!next) return;
+ // Reject a fallen-pose retarget: keep the current clip (or the authored
+ // bind pose when nothing is playing) instead of crossfading onto a body
+ // that would land on its back.
+ if (!this._guardAgainstFallenPose(name, next)) return;
next.reset().play();
if (this.currentAction) {
@@ -431,3 +576,23 @@ function _modelSupportsCanonicalClips(model) {
});
return hasSkinnedMesh && canonical.size >= MIN_CANONICAL_BONES;
}
+
+// Surface a fallen-pose retarget through the existing client-error pipeline
+// (public/error-reporter.js → POST /api/client-errors, logged "[client-error]").
+// That hook is a no-op on dev hosts and fails silent, exactly what we want here.
+// Guarded for Node/SSR (vitest, the apply_animation MCP tool) where neither
+// `window` nor the hook exists — the guard's logic still runs; only the report
+// is skipped.
+function reportFallenPose(context) {
+ try {
+ const hook =
+ typeof window !== 'undefined' &&
+ typeof window.reportClientError === 'function'
+ ? window.reportClientError
+ : null;
+ if (!hook) return;
+ hook(new Error('fallen-pose retarget'), context);
+ } catch (e) {
+ log.warn('[AnimationManager] fallen-pose report failed:', e);
+ }
+}
diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.js
index 41cd70b21..9e9c0e4db 100644
--- a/src/dashboard-next/pages/irl-placements.js
+++ b/src/dashboard-next/pages/irl-placements.js
@@ -26,7 +26,7 @@ import { mountShell } from '../shell.js';
import { requireUser, get, post, patch, esc, relTime } from '../api.js';
import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
import { loadInto } from '../../shared/async-state.js';
-import { loadLeaflet } from '../../shared/leaflet.js';
+import { loadLeaflet } from '../../shared/leaflet-loader.js';
import { mountReputationPanel } from './irl-reputation.js';
// ── Services / x402 skill pricing ───────────────────────────────────────────
diff --git a/src/element.js b/src/element.js
index 33fc1fcf0..e83812098 100644
--- a/src/element.js
+++ b/src/element.js
@@ -452,16 +452,85 @@ const BASE_STYLE = `
transition: opacity 0.4s;
pointer-events: none;
}
+ /* Loading state — a skeleton avatar silhouette with a shimmer sweep fills
+ the frame while the GLB streams in (skeletons read as "almost there",
+ spinners read as "stuck"). Neutral tones so it composites on transparent,
+ dark, and light hosts alike. */
.loading {
position: absolute;
- left: 50%;
- top: 50%;
- transform: translate(-50%, -50%);
- color: var(--agent-on-surface);
- font: 14px var(--agent-chat-font);
- background: var(--agent-surface);
- padding: 8px 14px;
- border-radius: 999px;
+ inset: 0;
+ display: grid;
+ place-items: stretch;
+ pointer-events: none;
+ z-index: 4;
+ }
+ .skeleton {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 2.5%;
+ padding-bottom: 7%;
+ box-sizing: border-box;
+ overflow: hidden;
+ -webkit-mask-image: linear-gradient(180deg, transparent, #000 16%, #000 88%, transparent);
+ mask-image: linear-gradient(180deg, transparent, #000 16%, #000 88%, transparent);
+ }
+ .skeleton-head {
+ width: 22%;
+ max-width: 88px;
+ aspect-ratio: 1;
+ border-radius: 50%;
+ background: var(--agent-skeleton, rgba(148, 148, 168, 0.18));
+ }
+ .skeleton-body {
+ width: 42%;
+ max-width: 168px;
+ height: 46%;
+ border-radius: 44% 44% 24% 24% / 26% 26% 9% 9%;
+ background: var(--agent-skeleton, rgba(148, 148, 168, 0.18));
+ }
+ .skeleton-shimmer {
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(
+ 100deg,
+ transparent 30%,
+ rgba(255, 255, 255, 0.13) 50%,
+ transparent 70%
+ );
+ transform: translateX(-100%);
+ animation: agent-skeleton-sweep 1.5s ease-in-out infinite;
+ }
+ @keyframes agent-skeleton-sweep {
+ to { transform: translateX(100%); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .skeleton-shimmer { animation: none; opacity: 0.45; transform: none; }
+ }
+ /* Static decoration fallback — a calm avatar silhouette shown when a bare
+ (chat-less) embed's body fails to load, instead of a blank frame or a
+ broken/empty canvas. Chat embeds get the richer .error card instead. */
+ .fallback {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ pointer-events: none;
+ z-index: 4;
+ animation: agent-err-in 0.3s ease both;
+ }
+ .fallback svg {
+ width: 38%;
+ max-width: 132px;
+ height: auto;
+ color: rgba(140, 140, 162, 0.5);
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .fallback { animation: none; }
}
.error, .agent-3d-error {
position: absolute;
@@ -661,6 +730,8 @@ class Agent3DElement extends HTMLElement {
'avatar-chat',
'avatar-walk',
'chat',
+ 'clip',
+ 'framing',
];
}
@@ -706,6 +777,10 @@ class Agent3DElement extends HTMLElement {
// WebGL context budget bookkeeping.
this._inViewport = false;
this._lastVisibleAt = 0;
+ // Decoration fallback + reduced-motion bookkeeping.
+ this._fallbackEl = null;
+ this._mqReduce = null;
+ this._mqReduceHandler = null;
}
connectedCallback() {
@@ -713,6 +788,7 @@ class Agent3DElement extends HTMLElement {
this._applyLayout();
this._setupResponsive();
this._observeViewport();
+ this._setupReducedMotion();
// Defer boot until visible unless `eager` attr is present.
// Skip boot entirely if no source — wait for src/manifest/body/agent-id
// to be set, which triggers reboot via attributeChangedCallback.
@@ -766,6 +842,7 @@ class Agent3DElement extends HTMLElement {
this.shadowRoot.replaceChildren();
// Null cached element refs so _renderShell recreates them from scratch.
this._loadingEl = null;
+ this._fallbackEl = null;
this._stageEl = null;
this._posterEl = null;
this._nameplateEl = null;
@@ -782,6 +859,44 @@ class Agent3DElement extends HTMLElement {
disconnectedCallback() {
this._teardown();
+ this._cleanupReducedMotion();
+ }
+
+ // prefers-reduced-motion lives at the element level (survives budget-driven
+ // teardown/reboot), so a runtime flip of the OS setting re-applies playback:
+ // a held static pose ↔ live motion, without a reload.
+ _setupReducedMotion() {
+ if (this._mqReduce || typeof window === 'undefined' || !window.matchMedia) return;
+ this._mqReduce = window.matchMedia('(prefers-reduced-motion: reduce)');
+ this._mqReduceHandler = () => {
+ if (this._mounted && this._scene && !this._isChatMode()) {
+ this._startDecorationPlayback();
+ }
+ };
+ try {
+ this._mqReduce.addEventListener('change', this._mqReduceHandler);
+ } catch {}
+ }
+
+ _cleanupReducedMotion() {
+ try {
+ if (this._mqReduce && this._mqReduceHandler) {
+ this._mqReduce.removeEventListener('change', this._mqReduceHandler);
+ }
+ } catch {}
+ this._mqReduce = null;
+ this._mqReduceHandler = null;
+ }
+
+ _prefersReducedMotion() {
+ try {
+ return (
+ this._mqReduce?.matches ??
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ );
+ } catch {
+ return false;
+ }
}
attributeChangedCallback(name, oldVal, newVal) {
@@ -812,6 +927,14 @@ class Agent3DElement extends HTMLElement {
if (name === 'avatar-walk' && newVal === 'off') {
this._stopWalkAnimation();
}
+ if (name === 'framing') {
+ this._viewer?.setFraming?.(newVal === 'portrait' ? 'portrait' : 'full');
+ }
+ // Re-cue decoration playback when the requested clip changes at runtime
+ // (loop-honoring + reduced-motion handled by _startDecorationPlayback).
+ if (name === 'clip' && !this._isChatMode()) {
+ this._startDecorationPlayback();
+ }
// Toggling `chat` at runtime flips the whole chrome — rebuild the shell.
if (name === 'chat') {
this._rebuildShell();
@@ -858,7 +981,14 @@ class Agent3DElement extends HTMLElement {
const loading = document.createElement('div');
loading.className = 'loading';
- loading.textContent = 'Loading...';
+ loading.setAttribute('role', 'status');
+ loading.setAttribute('aria-label', 'Loading avatar');
+ loading.innerHTML =
+ '<div class="skeleton" aria-hidden="true">' +
+ '<span class="skeleton-head"></span>' +
+ '<span class="skeleton-body"></span>' +
+ '<span class="skeleton-shimmer"></span>' +
+ '</div>';
loading.hidden = true;
this.shadowRoot.appendChild(loading);
this._loadingEl = loading;
@@ -1454,6 +1584,12 @@ class Agent3DElement extends HTMLElement {
async _boot() {
if (this._booting || this._mounted) return;
this._renderShell();
+ // Clear any decoration fallback left by a prior failed attempt so the
+ // fresh boot's skeleton/avatar isn't drawn underneath a stale silhouette.
+ if (this._fallbackEl) {
+ this._fallbackEl.remove();
+ this._fallbackEl = null;
+ }
this._booting = true;
try {
this._loadingEl.hidden = false;
@@ -1530,6 +1666,7 @@ class Agent3DElement extends HTMLElement {
// decoration avatar. Chat agents get the full interactive viewer.
const viewer = new Viewer(this._stageEl, {
kiosk: !this._isChatMode(),
+ framing: this.getAttribute('framing') === 'portrait' ? 'portrait' : 'full',
});
this._viewer = viewer;
viewer._afterAnimateHooks = viewer._afterAnimateHooks || [];
@@ -1560,25 +1697,38 @@ class Agent3DElement extends HTMLElement {
}
// After the reveal tween completes, shift the orbital target upward
// so the avatar's upper body fills the avatar-anchor window rather
- // than the full canvas height.
- const _v = viewer;
- const _nudge = () => {
- if (_v._cameraTweenRaf) {
- requestAnimationFrame(_nudge);
- return;
- }
- if (!_v.controls || !_v.content || _v._disposed) return;
- const box = new Box3().setFromObject(_v.content);
- const h = box.max.y - box.min.y;
- const mid = (box.max.y + box.min.y) / 2;
- _v.controls.target.set(0, mid + h * 0.12, 0);
- _v.controls.update();
- _v.invalidate();
- };
- requestAnimationFrame(_nudge);
+ // than the full canvas height. Skipped under `framing="portrait"`,
+ // where setContent already places the head-to-mid-thigh crop and an
+ // extra nudge would fight it.
+ if (this.getAttribute('framing') !== 'portrait') {
+ const _v = viewer;
+ const _nudge = () => {
+ if (_v._cameraTweenRaf) {
+ requestAnimationFrame(_nudge);
+ return;
+ }
+ if (!_v.controls || !_v.content || _v._disposed) return;
+ const box = new Box3().setFromObject(_v.content);
+ const h = box.max.y - box.min.y;
+ const mid = (box.max.y + box.min.y) / 2;
+ _v.controls.target.set(0, mid + h * 0.12, 0);
+ _v.controls.update();
+ _v.invalidate();
+ };
+ requestAnimationFrame(_nudge);
+ }
}
this._scene = new SceneController(viewer);
- if (bodyURI) this._scene.playClipByName('idle', { loop: true });
+ // Initial playback. Chat avatars idle-loop (then walk on stream); bare
+ // decoration avatars honor the `clip` attribute, the clip's manifest
+ // loop flag, and prefers-reduced-motion via _startDecorationPlayback.
+ if (bodyURI) {
+ if (this._isChatMode()) {
+ this._scene.playClipByName('idle', { loop: true });
+ } else {
+ this._startDecorationPlayback();
+ }
+ }
// Memory
this.dispatchEvent(
@@ -1948,9 +2098,10 @@ class Agent3DElement extends HTMLElement {
this._loadingEl.hidden = true;
// Resolve errors should already have been caught and replaced with the
// default-avatar manifest in _resolveManifest. Anything reaching here is
- // a deeper boot failure — surface it in chat mode; a bare decoration
- // avatar stays silent (no error card) and just emits the event.
- if (this._isChatMode()) this._showError(err);
+ // a deeper boot failure (e.g. the GLB or rig failed to load): chat mode
+ // shows the error card, a bare decoration avatar paints the static
+ // silhouette/poster fallback. Both also emit agent:error below.
+ this._showError(err);
this.dispatchEvent(
new CustomEvent('agent:error', {
detail: { phase: 'boot', error: err },
@@ -2492,9 +2643,13 @@ class Agent3DElement extends HTMLElement {
}
_showError(err) {
- // Bare avatars never paint an error card — they degrade silently to keep
- // the decoration clean. Only chat agents surface a visible error.
- if (!this._isChatMode()) return;
+ // Bare/decoration avatars degrade to a tasteful static silhouette (or the
+ // supplied poster) rather than a chat-style error card — clean decoration,
+ // but never a blank frame or a broken canvas. Chat agents get the card.
+ if (!this._isChatMode()) {
+ this._showDecorationFallback();
+ return;
+ }
const raw = (err && (err.message || String(err))) || '';
const isWebgl = /webgl|context/i.test(raw);
const title = isWebgl ? '3D preview unavailable' : "Couldn't load agent";
@@ -2827,6 +2982,114 @@ class Agent3DElement extends HTMLElement {
return this._scene?.playClipByName(name, opts);
}
+ /**
+ * Play a clip with the polished embed defaults, honoring the clip's manifest
+ * `loop` flag automatically: loop clips loop, one-shot clips play once and
+ * settle seamlessly into idle (no hard snap at the boundary). Respects
+ * `prefers-reduced-motion` by holding a clean static idle pose instead.
+ *
+ * This is the public entry point an embed should use for decorative playback
+ * — the host page no longer has to know which clips loop.
+ *
+ * @param {string} name
+ * @param {{ fade_ms?: number, userInitiated?: boolean }} [opts]
+ * `userInitiated` plays the motion even under prefers-reduced-motion — an
+ * explicit user gesture (e.g. clicking an animation pill) is allowed to
+ * animate; only ambient autoplay is suppressed.
+ */
+ playClip(name, { fade_ms = 400, userInitiated = false } = {}) {
+ if (!userInitiated && this._prefersReducedMotion()) {
+ this._playStaticIdle();
+ return;
+ }
+ this._playDecorationClip(name, fade_ms);
+ }
+
+ /**
+ * Start initial playback for a bare/decoration avatar: honor the `clip`
+ * attribute (default idle), the clip's loop flag, and prefers-reduced-motion.
+ */
+ _startDecorationPlayback() {
+ if (!this._scene) return;
+ if (this._prefersReducedMotion()) {
+ this._playStaticIdle();
+ return;
+ }
+ this._playDecorationClip(this.getAttribute('clip') || 'idle', 400);
+ }
+
+ /**
+ * Play a clip, deciding loop-vs-one-shot from the animation manifest. One-shot
+ * clips settle into idle via crossfade so a small looping thumbnail never
+ * hard-snaps at the clip boundary.
+ * @param {string} name
+ * @param {number} fade_ms
+ */
+ _playDecorationClip(name, fade_ms = 400) {
+ const am = this._viewer?.animationManager;
+ const def = (am?.getAnimationDefs?.() || []).find((d) => d?.name === name);
+ // Unknown clip (e.g. a clip baked into the GLB) → assume it loops cleanly.
+ const loops = def ? def.loop !== false : true;
+ if (loops) {
+ this._scene?.playClipByName(name, { loop: true, fade_ms });
+ } else if (am && typeof am.playOnce === 'function') {
+ am.playOnce(name, { settleTo: 'idle', fade: fade_ms / 1000 });
+ } else {
+ this._scene?.playClipByName(name, { loop: false, fade_ms });
+ }
+ }
+
+ /**
+ * Reduced-motion path: settle into a single clean idle pose and freeze it, so
+ * the avatar holds a natural stance with no looping motion — and the viewer's
+ * render loop can idle (no continuous GPU/CPU cost).
+ */
+ async _playStaticIdle() {
+ const am = this._viewer?.animationManager;
+ if (!am) {
+ this._scene?.playClipByName('idle', { loop: false, fade_ms: 0 });
+ return;
+ }
+ try {
+ await am.crossfadeTo('idle', 0);
+ } catch {}
+ // Let one frame apply the idle pose, then freeze it.
+ const freeze = () => {
+ if (this._viewer?.animationManager !== am) return; // model swapped meanwhile
+ am.freeze();
+ this._viewer?.invalidate();
+ };
+ this._viewer?.invalidate();
+ requestAnimationFrame(() => requestAnimationFrame(freeze));
+ }
+
+ /**
+ * Tasteful static fallback for a bare/decoration avatar whose body failed to
+ * load: keep the poster if one was supplied, otherwise paint a calm avatar
+ * silhouette — never a blank frame or a broken canvas.
+ */
+ _showDecorationFallback() {
+ if (this._fallbackEl) return;
+ this._loadingEl && (this._loadingEl.hidden = true);
+ // A poster already fills the frame — just make sure it stays visible.
+ if (this.getAttribute('poster') && this._posterEl) {
+ this._posterEl.style.opacity = '1';
+ return;
+ }
+ const el = document.createElement('div');
+ el.className = 'fallback';
+ el.setAttribute('role', 'img');
+ el.setAttribute('aria-label', 'Avatar preview unavailable');
+ el.innerHTML = `
+ <svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="2.4"
+ stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <circle cx="32" cy="22" r="11"/>
+ <path d="M12 55a20 20 0 0 1 40 0"/>
+ </svg>`;
+ this.shadowRoot.appendChild(el);
+ this._fallbackEl = el;
+ }
+
/**
* Combined animation list available to the loaded model.
*
diff --git a/src/irl.js b/src/irl.js
index 4a579f94d..ec1a333f4 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -58,7 +58,8 @@ import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw,
import { pinBandAction } from './irl/proximity-band.js';
import { loadInto } from './shared/async-state.js';
import { openMapPlacePicker } from './irl/map-place.js';
-import { loadLeaflet } from './shared/leaflet.js';
+import { openPrivacyCenter, maybeShowFirstRunDisclosure, getDiscoveryPrecision } from './irl/privacy-center.js';
+import { loadLeaflet } from './shared/leaflet-loader.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -1782,14 +1783,6 @@ async function enterFloorAnchor() {
}
}
-// Yaw (rotation about world Y), in degrees clockwise from the local −Z axis —
-// the same convention savePin stores and spawnNearbyPin reads back.
-function yawFromQuat(q) {
- const siny = 2 * (q.w * q.y + q.z * q.x);
- const cosy = 1 - 2 * (q.y * q.y + q.x * q.x);
- return Math.atan2(siny, cosy) * 180 / Math.PI;
-}
-
// Entry point for a placed floor anchor: persist it now if we have a GPS fix,
// otherwise hold the pose until the first fix lands. The in-session XRAnchor
// already glues the agent either way — this only governs the durable pin. `meta`
@@ -1818,20 +1811,25 @@ function onFloorAnchored(pose, meta = {}) {
// durable GPS pin is just coordinates, so it saves the same either way.
function persistFloorAnchor(pose, degraded = false) {
const { position, quaternion } = pose;
- const mLat = 110540;
- const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));
- const pinLat = gpsState.lat + (-position.z / mLat);
- const pinLng = gpsState.lng + ( position.x / mLng);
- const heading = ((Math.round(yawFromQuat(quaternion)) % 360) + 360) % 360;
+ // Pure, unit-tested conversion (src/irl/floor-anchor.js): horizontal offset →
+ // lat/lng via room-anchor's single projection, quaternion → normalised yaw.
+ const pin = anchorPoseToPin({
+ originLat: gpsState.lat,
+ originLng: gpsState.lng,
+ x: position.x,
+ y: position.y,
+ z: position.z,
+ quat: [quaternion.x, quaternion.y, quaternion.z, quaternion.w],
+ });
- gpsPin = { lat: pinLat, lng: pinLng };
+ gpsPin = { lat: pin.lat, lng: pin.lng };
gpsModeActive = true;
setXrResting(placementHint(degraded));
- savePin(pinLat, pinLng, heading, '', {
- heightM: position.y, // floor height relative to the eye-level session origin (negative = below)
- yawDeg: heading,
- quat: [quaternion.x, quaternion.y, quaternion.z, quaternion.w],
- source: 'webxr',
+ savePin(pin.lat, pin.lng, pin.heading, '', {
+ heightM: pin.heightM, // floor height relative to the eye-level session origin (negative = below)
+ yawDeg: pin.heading,
+ quat: pin.quat,
+ source: pin.source,
}).then(result => {
if (result?.ok && gpsPin) {
gpsPin.id = result.id;
@@ -2733,13 +2731,35 @@ function relativeTime(iso) {
return `${Math.round(hrs / 24)}d ago`;
}
+// Expiry phrasing for the My-pins meta line. Anonymous pins self-destruct on a
+// 7-day timer (a countdown, so a tester knows exactly when a forgotten test pin
+// is gone); signed-in pins are permanent. Returns { label, cls } so the row can
+// tint the chip amber when a pin is within a day of expiring.
+function relativeExpiry(iso) {
+ if (!iso) return { label: 'permanent', cls: 'is-perm' };
+ const t = new Date(iso).getTime();
+ if (!isFinite(t)) return { label: 'permanent', cls: 'is-perm' };
+ const secs = Math.round((t - Date.now()) / 1000);
+ if (secs <= 0) return { label: 'expired', cls: 'is-soon' }; // shouldn't surface — the feed filters expired
+ const days = Math.floor(secs / 86400);
+ if (days >= 1) return { label: `expires in ${days}d`, cls: days <= 1 ? 'is-soon' : '' };
+ const hrs = Math.floor(secs / 3600);
+ if (hrs >= 1) return { label: `expires in ${hrs}h`, cls: 'is-soon' };
+ const mins = Math.max(1, Math.floor(secs / 60));
+ return { label: `expires in ${mins}m`, cls: 'is-soon' };
+}
+
+// Composes the meta line — distance · age · expiry — as one line. Returns HTML:
+// the expiry segment is a styled chip, so the dynamic text pieces are escaped
+// here and renderMyPins inserts the result without re-escaping.
function _pinMetaLine(p) {
const parts = [];
if (gpsState.ready && isFinite(p.lat) && isFinite(p.lng)) {
- parts.push(`${Math.round(haversineMeters(gpsState.lat, gpsState.lng, p.lat, p.lng))}m away`);
+ parts.push(_escHtml(`${Math.round(haversineMeters(gpsState.lat, gpsState.lng, p.lat, p.lng))}m away`));
}
- if (p.placed_at) parts.push(relativeTime(p.placed_at));
- if (!p.expires_at) parts.push('permanent');
+ if (p.placed_at) parts.push(_escHtml(relativeTime(p.placed_at)));
+ const exp = relativeExpiry(p.expires_at);
+ parts.push(`<span class="irl-pin-exp ${exp.cls}">${_escHtml(exp.label)}</span>`);
return parts.join(' · ');
}
@@ -2787,20 +2807,235 @@ function renderMyPins(pins, listEl) {
<div class="irl-pin-info">
<div class="irl-pin-name">${_escHtml(p.avatar_name || 'Agent')}</div>
${p.caption ? `<div class="irl-pin-caption">${_escHtml(p.caption)}</div>` : ''}
- <div class="irl-pin-meta">${_escHtml(_pinMetaLine(p))}</div>
+ <div class="irl-pin-meta">${_pinMetaLine(p)}</div>
</div>
<button class="irl-pin-del" data-del="${_escHtml(p.id)}" type="button" aria-label="Delete this pin">${TRASH_SVG}</button>
</div>`).join('');
}
+// ── My-pins overview map (lazy Leaflet) ────────────────────────────────────
+// A small dark map above the list plots every owned pin, so "where did I drop
+// things?" is answered visually. The map is a pure enhancement: the list is the
+// source of truth, and any CDN failure degrades to the list alone (Rule 9).
+let _myPinsMap = null; // Leaflet map for the sheet, or null when down
+const _myPinsMarkers = new Map(); // pin id -> Leaflet marker
+let _myPinsMapSeq = 0; // bumped each open/close; guards async CDN builds
+let _purgeKeydown = null; // active confirm focus-trap handler, or null
+
+// A gold dot marker — matches the "your agent" gold used on nearby labels.
+function makeMyPinIcon(L) {
+ return L.divIcon({
+ className: 'irl-mypins-pin',
+ html: '<span class="irl-mypins-marker"></span>',
+ iconSize: [14, 14],
+ iconAnchor: [7, 7],
+ });
+}
+
+function teardownMyPinsMap() {
+ try { _myPinsMap?.remove(); } catch { /* leaflet teardown best-effort */ }
+ _myPinsMap = null;
+ _myPinsMarkers.clear();
+ const mapEl = document.getElementById('irl-mypins-map');
+ if (mapEl) { mapEl.classList.remove('is-shown'); mapEl.innerHTML = ''; }
+}
+
+function closePurgeConfirmTrap() {
+ if (_purgeKeydown) { document.removeEventListener('keydown', _purgeKeydown, true); _purgeKeydown = null; }
+}
+
+function hideMyPinsFooter() {
+ closePurgeConfirmTrap();
+ const foot = document.getElementById('irl-mypins-foot');
+ if (foot) { foot.hidden = true; foot.innerHTML = ''; }
+}
+
+// Clean slate on every open: void any in-flight CDN build, drop the old map +
+// footer, and show the map skeleton so the loading state reads as "map + rows".
+function resetMyPinsChrome() {
+ _myPinsMapSeq++;
+ teardownMyPinsMap();
+ hideMyPinsFooter();
+ const mapEl = document.getElementById('irl-mypins-map');
+ if (mapEl) {
+ mapEl.classList.add('is-shown');
+ mapEl.innerHTML = '<div class="irl-mypins-map-skel" aria-hidden="true"></div>';
+ }
+}
+
+// Tapping a marker scrolls its row into view and flashes it, so the map and list
+// stay legibly linked.
+function highlightMyPinRow(id) {
+ const list = document.getElementById('irl-mypins-list');
+ if (!list) return;
+ const sel = (typeof CSS !== 'undefined' && CSS.escape) ? CSS.escape(id) : String(id).replace(/"/g, '\\"');
+ const row = list.querySelector(`.irl-pin-row[data-pid="${sel}"]`);
+ if (!row) return;
+ row.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ row.classList.remove('is-highlight');
+ void row.offsetWidth; // restart the flash if already highlighted
+ row.classList.add('is-highlight');
+ setTimeout(() => row.classList.remove('is-highlight'), 1600);
+}
+
+// Re-fit the map to whatever markers remain (after a single delete). Empties → hide.
+function refitMyPinsMap() {
+ if (!_myPinsMap) return;
+ if (!_myPinsMarkers.size) { teardownMyPinsMap(); return; }
+ const lls = [...(_myPinsMarkers.values())].map(m => m.getLatLng());
+ if (lls.length === 1) _myPinsMap.setView(lls[0], 16);
+ else { try { _myPinsMap.fitBounds(lls, { padding: [28, 28], maxZoom: 17 }); } catch { /* noop */ } }
+}
+
+function removeMyPinMarker(id) {
+ const mk = _myPinsMarkers.get(id);
+ if (mk) { try { _myPinsMap?.removeLayer(mk); } catch { /* best-effort */ } }
+ _myPinsMarkers.delete(id);
+ refitMyPinsMap();
+}
+
+// Builds the Leaflet map + a marker per owned pin and fits to them. Awaits the
+// shared lazy loader; on any CDN failure or a sheet that closed mid-load, it
+// quietly drops back to the list. `_myPinsMapSeq` guards against a stale build
+// mounting after the sheet was reopened.
+async function renderMyPinsMap(pins) {
+ const seq = _myPinsMapSeq;
+ const mapEl = document.getElementById('irl-mypins-map');
+ if (!mapEl) return;
+ const geo = pins.filter(p => isFinite(+p.lat) && isFinite(+p.lng));
+ if (!geo.length) { teardownMyPinsMap(); return; } // nothing to plot → list only
+
+ let L;
+ try { L = await loadLeaflet(); }
+ catch { if (seq === _myPinsMapSeq) teardownMyPinsMap(); return; } // CDN blocked/offline → list only
+ if (seq !== _myPinsMapSeq || !mapEl.isConnected) return; // sheet closed/reopened mid-load
+
+ mapEl.innerHTML = '';
+ const map = L.map(mapEl, { zoomControl: true, attributionControl: true, scrollWheelZoom: false });
+ _myPinsMap = map;
+ L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
+ attribution: '© OpenStreetMap · © CARTO',
+ subdomains: 'abcd',
+ maxZoom: 19,
+ }).addTo(map);
+
+ _myPinsMarkers.clear();
+ const latlngs = [];
+ for (const p of geo) {
+ const ll = [+p.lat, +p.lng];
+ latlngs.push(ll);
+ const mk = L.marker(ll, { keyboard: false, icon: makeMyPinIcon(L), title: p.avatar_name || 'Your pin' }).addTo(map);
+ mk.on('click', () => highlightMyPinRow(p.id));
+ _myPinsMarkers.set(p.id, mk);
+ }
+ if (latlngs.length === 1) map.setView(latlngs[0], 16);
+ else map.fitBounds(latlngs, { padding: [28, 28], maxZoom: 17 });
+
+ // The sheet animates in (translateY), so the map can mount mid-transition;
+ // Leaflet must re-measure once layout settles or tiles render into a 0-size box.
+ requestAnimationFrame(() => { if (seq === _myPinsMapSeq && _myPinsMap === map) map.invalidateSize(); });
+ setTimeout(() => { if (seq === _myPinsMapSeq && _myPinsMap === map) map.invalidateSize(); }, 320);
+}
+
+// ── Bulk purge — "Remove all from this device" ─────────────────────────────
+// A footer affordance for fast cleanup after a testing session. Only shown for an
+// anonymous device with ≥1 pin; signed-in permanent pins are managed from the
+// dashboard (out of scope here), so the button is gated on _deviceToken.
+function renderPurgeFooter(count) {
+ const foot = document.getElementById('irl-mypins-foot');
+ if (!foot) return;
+ if (!_deviceToken || count < 1) { hideMyPinsFooter(); return; }
+ closePurgeConfirmTrap();
+ foot.hidden = false;
+ foot.innerHTML = `<button class="irl-mypins-purge" id="irl-mypins-purge" type="button"
+ aria-label="Remove all ${count} agent${count === 1 ? '' : 's'} you placed from this device">
+ ${TRASH_SVG}<span>Remove all from this device</span>
+ </button>`;
+ foot.querySelector('#irl-mypins-purge')?.addEventListener('click', () => openPurgeConfirm(count));
+}
+
+// A designed confirm step (not window.confirm): focus-trapped between Cancel and
+// Remove, Esc cancels, default focus on Cancel (the safe choice for a destructive
+// action).
+function openPurgeConfirm(count) {
+ const foot = document.getElementById('irl-mypins-foot');
+ if (!foot) return;
+ foot.hidden = false;
+ foot.innerHTML = `<div class="irl-mypins-confirm" role="alertdialog" aria-modal="true" aria-labelledby="irl-purge-q">
+ <p class="irl-mypins-confirm-q" id="irl-purge-q">Remove all ${count} agent${count === 1 ? '' : 's'} you placed from this device? This can’t be undone.</p>
+ <div class="irl-mypins-confirm-row">
+ <button class="irl-mypins-confirm-cancel" type="button" data-cancel>Cancel</button>
+ <button class="irl-mypins-confirm-go" type="button" data-go>Remove all</button>
+ </div>
+ </div>`;
+ const cancelBtn = foot.querySelector('[data-cancel]');
+ const goBtn = foot.querySelector('[data-go]');
+ cancelBtn?.addEventListener('click', () => closePurgeConfirm(count));
+ goBtn?.addEventListener('click', () => runPurge(goBtn, cancelBtn));
+ closePurgeConfirmTrap();
+ _purgeKeydown = (ev) => {
+ if (ev.key === 'Escape') { ev.preventDefault(); closePurgeConfirm(count); return; }
+ if (ev.key !== 'Tab') return;
+ const order = [cancelBtn, goBtn].filter(Boolean);
+ if (!order.length) return;
+ ev.preventDefault();
+ const i = order.indexOf(document.activeElement);
+ const n = order.length;
+ const next = ev.shiftKey ? (i <= 0 ? n - 1 : i - 1) : (i >= n - 1 ? 0 : i + 1);
+ order[next]?.focus();
+ };
+ document.addEventListener('keydown', _purgeKeydown, true);
+ cancelBtn?.focus();
+}
+
+function closePurgeConfirm(count) {
+ closePurgeConfirmTrap();
+ renderPurgeFooter(count); // back to the "Remove all" button
+ document.getElementById('irl-mypins-purge')?.focus();
+}
+
+// One request deletes every pin tied to this device token; the sheet then lands
+// on the empty state. The list is read for the about-to-be-purged ids so their
+// nearby labels stop reading as "yours".
+async function runPurge(goBtn, cancelBtn) {
+ if (goBtn) { goBtn.disabled = true; goBtn.textContent = 'Removing…'; }
+ if (cancelBtn) cancelBtn.disabled = true;
+ const r = await fetch(
+ `/api/irl/pins?all=1&deviceToken=${encodeURIComponent(_deviceToken ?? '')}`,
+ { method: 'DELETE', credentials: 'include' },
+ ).catch(() => null);
+ if (!r?.ok) {
+ if (goBtn) { goBtn.disabled = false; goBtn.textContent = 'Remove all'; }
+ if (cancelBtn) cancelBtn.disabled = false;
+ setStatus('Could not remove your pins', { error: true });
+ return;
+ }
+ let deleted = 0;
+ try { deleted = (await r.json()).deleted ?? 0; } catch { /* count is best-effort */ }
+
+ closePurgeConfirmTrap();
+ // If a pin anchored in this session was among them, release the lock.
+ if (gpsPin?.id && _myPinIds.has(gpsPin.id)) setLocked(false);
+ const list = document.getElementById('irl-mypins-list');
+ if (list) for (const row of list.querySelectorAll('.irl-pin-row')) _myPinIds.delete(row.dataset.pid);
+ refreshOwnLabels();
+
+ teardownMyPinsMap();
+ hideMyPinsFooter();
+ if (list) { ensureStateKitStyles(); list.innerHTML = emptyStateHTML(MYPINS_EMPTY); }
+ setStatus(deleted > 0 ? `Removed ${deleted} pin${deleted === 1 ? '' : 's'} from this device` : 'Nothing to remove');
+}
+
async function openMyPinsSheet() {
const sheet = document.getElementById('irl-mypins-sheet');
const list = document.getElementById('irl-mypins-list');
if (!sheet || !list) return;
sheet.classList.add('is-open');
- // Designed loading → list / empty / error(+retry), so a failed fetch surfaces
- // an error instead of masquerading as "no pins".
- loadInto(list, {
+ resetMyPinsChrome(); // map skeleton on, footer + any stale confirm cleared
+ // Designed loading → list / empty / error(+retry). loadInto returns the data on
+ // success or null when empty/errored; the map + purge footer ride a real,
+ // non-empty result — in the empty and error cases the list is the source of truth.
+ const pins = await loadInto(list, {
load: loadMyPins,
render: (pins, el) => renderMyPins(pins, el),
skeleton: { count: 3, variant: 'row' },
@@ -2808,6 +3043,20 @@ async function openMyPinsSheet() {
error: { title: "Couldn't load your pins", body: 'Check your connection and try again.' },
context: 'irl:my-pins',
});
+ if (pins && pins.length) {
+ renderMyPinsMap(pins); // async; degrades to the list on any CDN failure
+ renderPurgeFooter(pins.length);
+ } else {
+ teardownMyPinsMap(); // empty/error → no map, no footer
+ hideMyPinsFooter();
+ }
+}
+
+function closeMyPinsSheet() {
+ document.getElementById('irl-mypins-sheet')?.classList.remove('is-open');
+ _myPinsMapSeq++; // void any in-flight CDN build
+ teardownMyPinsMap();
+ hideMyPinsFooter();
}
async function deleteMyPin(id, btn) {
@@ -2823,12 +3072,20 @@ async function deleteMyPin(id, btn) {
}
// If we just deleted the avatar currently anchored in this session, clear it.
if (gpsPin?.id === id) setLocked(false);
+ _myPinIds.delete(id);
+ // Drop the row + its map marker so the overview stays honest with the list.
btn?.closest('.irl-pin-row')?.remove();
+ removeMyPinMarker(id);
const list = document.getElementById('irl-mypins-list');
- if (list && !list.querySelector('.irl-pin-row')) {
+ const remaining = list ? list.querySelectorAll('.irl-pin-row').length : 0;
+ if (!remaining) {
ensureStateKitStyles();
- list.innerHTML = emptyStateHTML(MYPINS_EMPTY);
+ if (list) list.innerHTML = emptyStateHTML(MYPINS_EMPTY);
+ teardownMyPinsMap();
+ hideMyPinsFooter();
+ } else {
+ renderPurgeFooter(remaining); // keep the purge button's aria-count accurate
}
setStatus('Pin removed');
}
@@ -2858,21 +3115,27 @@ function syncGhostToggle() {
? 'You appear as a ghost to others viewing this area. Tap to hide.'
: 'Only your presence count is shared. Tap to appear as a ghost to others nearby.';
}
-document.getElementById('irl-ghost-toggle')?.addEventListener('click', () => {
- const on = !getShareGhost();
+// Single path for flipping the presence opt-in — used by the topbar pill AND the
+// L3 privacy center, so both stay in sync (pill state, stored intent, live room).
+function applyGhost(on) {
setShareGhost(on);
syncGhostToggle();
// Push the change to the live room (no-op off a live socket; the next connect
// carries the stored intent regardless).
irlNet?.setGhost(on, resolveAvatarUrl(_currentAvatarId));
setStatus(on ? 'You now appear to others nearby' : 'You no longer appear to others');
-});
+}
+document.getElementById('irl-ghost-toggle')?.addEventListener('click', () => applyGhost(!getShareGhost()));
syncGhostToggle();
-document.getElementById('irl-mypins-close')?.addEventListener('click', () => {
- document.getElementById('irl-mypins-sheet')?.classList.remove('is-open');
+// L3 — Location & privacy center: honest disclosure + discovery precision +
+// presence opt-in + a jump into pin management, all in one designed surface.
+document.getElementById('irl-privacy-btn')?.addEventListener('click', () => {
+ openPrivacyCenter({ getGhost: getShareGhost, setGhost: applyGhost, onManagePins: openMyPinsSheet });
});
+document.getElementById('irl-mypins-close')?.addEventListener('click', closeMyPinsSheet);
+
document.getElementById('irl-mypins-list')?.addEventListener('click', (e) => {
const btn = e.target.closest('[data-del]');
if (btn) deleteMyPin(btn.dataset.del, btn);
@@ -4671,7 +4934,9 @@ window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && calibrateA
// Permissions + first-run onboarding (E1) own the camera/motion/location prompts.
// GPS starts only once location is granted — via first-run, a repeat-visit replay,
// or a later chip tap — so there's no silent native location prompt on load.
-startOnboarding({ onGrant: (kind) => { if (kind === 'location') initGPS(); } });
+startOnboarding({ onGrant: (kind) => {
+ if (kind === 'location') { initGPS(); maybeShowFirstRunDisclosure(); }
+} });
// Reveal My pins on load if this device already owns pins — management must
// survive a reload (and a denied GPS prompt). The GPS-ready path reveals it too.
diff --git a/src/irl/floor-anchor.js b/src/irl/floor-anchor.js
new file mode 100644
index 000000000..afff3201b
--- /dev/null
+++ b/src/irl/floor-anchor.js
@@ -0,0 +1,73 @@
+// @ts-check
+// Pure floor-anchor math for /irl WebXR placement.
+//
+// Why this exists
+// ───────────────
+// When you place an agent on the floor with WebXR (immersive-ar), the hit-test
+// gives you an anchored pose in the session's LOCAL frame: metres from the
+// eye-level origin the session started at, plus the surface's orientation as a
+// quaternion. To make that placement durable and shareable we must turn that
+// local pose into a GPS pin — a lat/lng + a compass heading the renderer can
+// reload and re-place for any viewer.
+//
+// That conversion is just two pieces of math: a horizontal metre-offset →
+// lat/lng projection, and a quaternion → yaw-degrees extraction. The projection
+// is the SAME one room-anchor.js already exports and unit-tests; duplicating its
+// metre-per-degree constants on this write path is exactly how a sign error
+// ships silently and lands every saved anchor in the wrong spot for every viewer.
+// So this module reuses room-anchor's localToGeo and owns only the quaternion
+// math — no DOM, no Three.js, no I/O, plain numbers in/out so the test suite can
+// verify it directly.
+//
+// Coordinate conventions — IDENTICAL to src/irl.js and room-anchor.js, do not drift:
+// World: North = −Z · East = +X · Y = up · 1 unit = 1 metre.
+// Yaw: degrees 0–359 clockwise from the local −Z axis (what savePin stores
+// and spawnNearbyPin reads back).
+
+import { localToGeo } from './room-anchor.js';
+
+/**
+ * Yaw (rotation about world Y) in degrees, clockwise from the local −Z axis —
+ * the same convention savePin stores and spawnNearbyPin reads back. Raw output
+ * is the atan2 range (−180, 180]; callers normalise to [0,360) when persisting.
+ * @param {number} x quaternion x
+ * @param {number} y quaternion y
+ * @param {number} z quaternion z
+ * @param {number} w quaternion w
+ * @returns {number} yaw in degrees, in (−180, 180]
+ */
+export function yawDegFromQuat(x, y, z, w) {
+ const siny = 2 * (w * y + z * x);
+ const cosy = 1 - 2 * (y * y + x * x);
+ return Math.atan2(siny, cosy) * 180 / Math.PI;
+}
+
+/**
+ * Anchored local-space pose (metres from the eye-level session origin) → the GPS
+ * pin to persist. Reuses room-anchor's localToGeo so there is ONE projection and
+ * one set of metre-per-degree constants for both the read and write paths.
+ *
+ * The session frame uses the same axes as the world: +X = east, −Z = north. So
+ * the local x passes straight through as east, and we pass −z as north.
+ *
+ * @param {object} p
+ * @param {number} p.originLat GPS latitude of the session origin (the viewer's fix)
+ * @param {number} p.originLng GPS longitude of the session origin
+ * @param {number} p.x local east offset (metres, +X)
+ * @param {number} p.y local height offset (metres, +Y up) — negative = below eye level
+ * @param {number} p.z local south offset (metres, +Z); world north is −Z
+ * @param {[number, number, number, number]} p.quat surface orientation [x,y,z,w]
+ * @returns {{ lat:number, lng:number, heading:number, heightM:number, quat:[number,number,number,number], source:'webxr' }}
+ */
+export function anchorPoseToPin({ originLat, originLng, x, y, z, quat }) {
+ const { lat, lng } = localToGeo(originLat, originLng, /* east */ x, /* north */ -z);
+ const heading = ((Math.round(yawDegFromQuat(quat[0], quat[1], quat[2], quat[3])) % 360) + 360) % 360;
+ return {
+ lat,
+ lng,
+ heading,
+ heightM: y, // floor height relative to the eye-level session origin (negative = below)
+ quat,
+ source: 'webxr',
+ };
+}
diff --git a/src/irl/privacy-center.js b/src/irl/privacy-center.js
new file mode 100644
index 000000000..dd1bf254c
--- /dev/null
+++ b/src/irl/privacy-center.js
@@ -0,0 +1,223 @@
+// src/irl/privacy-center.js — IRL "Location & privacy" control center (L3).
+//
+// One designed, reachable surface that tells the user — in plain language — what
+// a placed pin actually shares and who can see it, and gives them the levers in
+// one place: discovery precision (Precise vs Approximate, consumed by the L4
+// proximity read), the "appear to others" presence opt-in, and a jump into
+// pin management. Plus a one-time first-run disclosure shown the first time
+// location is granted. This module owns the discovery-precision setting (single
+// source of truth) so irl.js / loadNearbyPins read it without duplicating a key.
+
+const PRECISION_KEY = 'irl_discovery_precision'; // 'precise' | 'approximate'
+const DISCLOSED_KEY = 'irl_location_disclosed_v1';
+const STYLE_ID = 'irlpc-styles';
+
+// ── Discovery precision (single source of truth) ────────────────────────────
+export function getDiscoveryPrecision() {
+ try { return localStorage.getItem(PRECISION_KEY) === 'approximate' ? 'approximate' : 'precise'; }
+ catch { return 'precise'; }
+}
+export function setDiscoveryPrecision(v) {
+ try { localStorage.setItem(PRECISION_KEY, v === 'approximate' ? 'approximate' : 'precise'); } catch {}
+}
+
+// The three honest facts, shared by the sheet and the first-run disclosure so the
+// copy never diverges. Grounded in api/irl/pins.js behavior (≤60 m radius read,
+// no roster, owner id stripped, anon pins expire in 7 days).
+const FACTS = [
+ { icon: '📍', t: 'Only people right next to it', b: 'A placed agent appears to someone only when they’re physically within ~60 m of it — never on a map or a browsable list.' },
+ { icon: '🕶️', t: 'Never tied to your identity', b: 'The nearby feed never includes your account or device id. Others see an agent at a spot, not who placed it.' },
+ { icon: '⏳', t: 'Gone on your terms', b: 'Pins you place without signing in auto-expire after 7 days, and you can remove any of them instantly from “My pins”.' },
+];
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = `
+.irlpc-root{position:fixed;inset:0;z-index:10001;display:flex;align-items:flex-end;justify-content:center}
+.irlpc-back{position:absolute;inset:0;background:rgba(4,6,12,.62);backdrop-filter:blur(2px);animation:irlpc-fade .2s ease}
+.irlpc-sheet{position:relative;width:100%;max-width:540px;max-height:90vh;overflow-y:auto;background:#0c0f17;
+ border:1px solid #232838;border-bottom:none;border-radius:18px 18px 0 0;box-shadow:0 -8px 40px rgba(0,0,0,.55);
+ animation:irlpc-rise .26s cubic-bezier(.2,.8,.2,1)}
+@media(min-width:600px){.irlpc-root{align-items:center}.irlpc-sheet{border-radius:18px;border-bottom:1px solid #232838}}
+@keyframes irlpc-rise{from{transform:translateY(14px);opacity:.4}to{transform:translateY(0);opacity:1}}
+@keyframes irlpc-fade{from{opacity:0}to{opacity:1}}
+.irlpc-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 6px}
+.irlpc-title{font:600 16px/1.2 system-ui,sans-serif;color:#eef1f7}
+.irlpc-x{appearance:none;background:none;border:none;color:#8b93a7;font-size:24px;line-height:1;cursor:pointer;
+ width:34px;height:34px;border-radius:8px;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s}
+.irlpc-x:hover,.irlpc-x:focus-visible{background:#1a1f2e;color:#eef1f7;outline:none}
+.irlpc-sec{padding:12px 18px;border-top:1px solid #161b27}
+.irlpc-sec:first-of-type{border-top:none}
+.irlpc-sec h4{margin:0 0 10px;font:600 12px/1.2 system-ui,sans-serif;letter-spacing:.06em;text-transform:uppercase;color:#7b8398}
+.irlpc-fact{display:flex;gap:11px;margin-bottom:11px}
+.irlpc-fact:last-child{margin-bottom:0}
+.irlpc-fact .ic{font-size:17px;line-height:1.3;flex-shrink:0}
+.irlpc-fact .t{font:600 13.5px/1.3 system-ui,sans-serif;color:#eef1f7;margin-bottom:2px}
+.irlpc-fact .b{font:400 12.5px/1.45 system-ui,sans-serif;color:#aeb6c8}
+.irlpc-seg{display:flex;gap:6px;background:#11151f;border:1px solid #232838;border-radius:11px;padding:4px}
+.irlpc-seg button{flex:1;appearance:none;background:none;border:none;border-radius:8px;cursor:pointer;padding:9px 6px;
+ font:600 13px/1.1 system-ui,sans-serif;color:#aeb6c8;transition:background .15s,color .15s}
+.irlpc-seg button small{display:block;font-weight:500;font-size:10.5px;color:#6f7790;margin-top:2px}
+.irlpc-seg button.on{background:#4f7cff;color:#fff}
+.irlpc-seg button.on small{color:#dbe5ff}
+.irlpc-note{margin-top:9px;font:400 11.5px/1.45 system-ui,sans-serif;color:#7b8398}
+.irlpc-row{display:flex;align-items:center;justify-content:space-between;gap:14px}
+.irlpc-row .rt{font:600 13.5px/1.3 system-ui,sans-serif;color:#eef1f7}
+.irlpc-row .rb{font:400 12px/1.4 system-ui,sans-serif;color:#8b93a7;margin-top:2px;max-width:330px}
+.irlpc-switch{position:relative;width:46px;height:27px;border-radius:999px;background:#2a3042;border:none;cursor:pointer;flex-shrink:0;transition:background .18s}
+.irlpc-switch::after{content:'';position:absolute;top:3px;left:3px;width:21px;height:21px;border-radius:50%;background:#fff;transition:transform .18s}
+.irlpc-switch[aria-pressed="true"]{background:#34c759}
+.irlpc-switch[aria-pressed="true"]::after{transform:translateX(19px)}
+.irlpc-switch:focus-visible{outline:2px solid #4f7cff;outline-offset:2px}
+.irlpc-manage{display:flex;align-items:center;justify-content:space-between;width:100%;appearance:none;cursor:pointer;
+ background:#11151f;border:1px solid #232838;border-radius:11px;padding:13px 14px;color:#eef1f7;
+ font:600 13.5px system-ui,sans-serif;transition:background .15s}
+.irlpc-manage:hover{background:#1a2032}
+.irlpc-manage .ar{color:#8b93a7;font-size:18px}
+.irlpc-foot{padding:14px 18px 18px}
+.irlpc-done{width:100%;appearance:none;background:#4f7cff;color:#fff;border:none;border-radius:11px;
+ font:600 14px system-ui,sans-serif;padding:13px;cursor:pointer;transition:background .15s}
+.irlpc-done:hover{background:#3d6af0}
+/* First-run disclosure reuses the sheet shell with a tighter body */
+.irlpc-discl .irlpc-sec{border-top:none}
+`;
+ document.head.appendChild(el);
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function factsHTML() {
+ return FACTS.map((f) => `<div class="irlpc-fact"><span class="ic">${f.icon}</span><div><div class="t">${esc(f.t)}</div><div class="b">${esc(f.b)}</div></div></div>`).join('');
+}
+
+// Generic modal shell with backdrop + Esc + focus return. `build(sheet, close)`
+// fills the sheet; `close()` tears down.
+function modal(buildInner, { extraClass = '' } = {}) {
+ ensureStyles();
+ const root = document.createElement('div');
+ root.className = `irlpc-root ${extraClass}`.trim();
+ root.setAttribute('role', 'dialog');
+ root.setAttribute('aria-modal', 'true');
+ const back = document.createElement('div');
+ back.className = 'irlpc-back';
+ const sheet = document.createElement('div');
+ sheet.className = 'irlpc-sheet';
+ root.append(back, sheet);
+ document.body.appendChild(root);
+ const prevOverflow = document.body.style.overflow;
+ document.body.style.overflow = 'hidden';
+ const prevFocus = document.activeElement;
+
+ let closed = false;
+ const close = () => {
+ if (closed) return;
+ closed = true;
+ document.removeEventListener('keydown', onKey, true);
+ root.remove();
+ document.body.style.overflow = prevOverflow;
+ try { prevFocus?.focus?.(); } catch {}
+ };
+ const onKey = (ev) => { if (ev.key === 'Escape') { ev.stopPropagation(); close(); } };
+ document.addEventListener('keydown', onKey, true);
+ back.addEventListener('click', close);
+ buildInner(sheet, close);
+ return close;
+}
+
+// ── The Location & privacy sheet ────────────────────────────────────────────
+export function openPrivacyCenter({ getGhost, setGhost, onManagePins } = {}) {
+ modal((sheet, close) => {
+ const precision = getDiscoveryPrecision();
+ const ghostOn = !!(getGhost && getGhost());
+ sheet.setAttribute('aria-label', 'Location and privacy');
+ sheet.innerHTML = `
+ <div class="irlpc-head">
+ <div class="irlpc-title">Location &amp; privacy</div>
+ <button class="irlpc-x" type="button" data-close aria-label="Close">×</button>
+ </div>
+ <div class="irlpc-sec">
+ <h4>What others can see</h4>
+ ${factsHTML()}
+ </div>
+ <div class="irlpc-sec">
+ <h4>Discovery precision</h4>
+ <div class="irlpc-seg" role="group" aria-label="Discovery precision">
+ <button type="button" data-prec="precise" class="${precision === 'precise' ? 'on' : ''}" aria-pressed="${precision === 'precise'}">Precise<small>exact spot</small></button>
+ <button type="button" data-prec="approximate" class="${precision === 'approximate' ? 'on' : ''}" aria-pressed="${precision === 'approximate'}">Approximate<small>~city block</small></button>
+ </div>
+ <div class="irlpc-note">Approximate keeps your exact position off our servers while you browse — nearby agents may resolve a little less precisely. Placement is always exactly where you choose.</div>
+ </div>
+ <div class="irlpc-sec">
+ <div class="irlpc-row">
+ <div>
+ <div class="rt">Appear to others nearby</div>
+ <div class="rb">Off by default. When on, people viewing this area see you as a ghost marker. Your presence count is shared either way.</div>
+ </div>
+ <button class="irlpc-switch" type="button" data-ghost role="switch" aria-pressed="${ghostOn}" aria-label="Appear to others nearby"></button>
+ </div>
+ </div>
+ <div class="irlpc-sec">
+ <h4>Your placements</h4>
+ <button class="irlpc-manage" type="button" data-manage>
+ <span>Manage &amp; remove agents you’ve placed</span><span class="ar">→</span>
+ </button>
+ </div>
+ <div class="irlpc-foot"><button class="irlpc-done" type="button" data-close>Done</button></div>`;
+
+ sheet.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', close));
+
+ // Precision segmented control
+ sheet.querySelectorAll('[data-prec]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const v = btn.dataset.prec;
+ setDiscoveryPrecision(v);
+ sheet.querySelectorAll('[data-prec]').forEach((b) => {
+ const on = b.dataset.prec === v;
+ b.classList.toggle('on', on);
+ b.setAttribute('aria-pressed', String(on));
+ });
+ });
+ });
+
+ // Presence opt-in — drives the host toggle so the topbar pill + room state stay in sync.
+ const ghostBtn = sheet.querySelector('[data-ghost]');
+ ghostBtn?.addEventListener('click', () => {
+ const next = ghostBtn.getAttribute('aria-pressed') !== 'true';
+ ghostBtn.setAttribute('aria-pressed', String(next));
+ try { setGhost && setGhost(next); } catch {}
+ });
+
+ // Manage placements → close then open My pins
+ sheet.querySelector('[data-manage]')?.addEventListener('click', () => {
+ close();
+ try { onManagePins && onManagePins(); } catch {}
+ });
+
+ setTimeout(() => sheet.querySelector('[data-close]')?.focus(), 60);
+ });
+}
+
+// ── First-run disclosure (shown once, the first time location is granted) ────
+export function maybeShowFirstRunDisclosure() {
+ let already = false;
+ try { already = localStorage.getItem(DISCLOSED_KEY) === '1'; } catch {}
+ if (already) return;
+ try { localStorage.setItem(DISCLOSED_KEY, '1'); } catch {}
+
+ modal((sheet, close) => {
+ sheet.setAttribute('aria-label', 'How location works here');
+ sheet.innerHTML = `
+ <div class="irlpc-head">
+ <div class="irlpc-title">How location works here</div>
+ <button class="irlpc-x" type="button" data-close aria-label="Close">×</button>
+ </div>
+ <div class="irlpc-sec">${factsHTML()}</div>
+ <div class="irlpc-foot"><button class="irlpc-done" type="button" data-close>Got it</button></div>`;
+ sheet.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', close));
+ setTimeout(() => sheet.querySelector('.irlpc-done')?.focus(), 60);
+ }, { extraClass: 'irlpc-discl' });
+}
diff --git a/src/shared/leaflet.js b/src/shared/leaflet.js
deleted file mode 100644
index 3f186d494..000000000
--- a/src/shared/leaflet.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Shared lazy Leaflet loader.
- *
- * Leaflet's JS + CSS are fetched from a CDN only on first use, so surfaces that
- * never open a map (most of the app) pay nothing for it. Every map surface — the
- * dashboard placement editor and the /irl My-pins overview — shares this one
- * loader, so there is a single CDN source, a single promise cache (Leaflet loads
- * at most once per session), and a single graceful-failure contract: a blocked or
- * offline CDN rejects, and every caller degrades to a map-free fallback instead of
- * a broken surface.
- */
-
-export const LEAFLET_JS = 'https://esm.sh/[email protected]';
-export const LEAFLET_CSS = 'https://unpkg.com/[email protected]/dist/leaflet.css';
-
-let _cssPromise = null;
-export function ensureLeafletCss() {
- if (_cssPromise) return _cssPromise;
- _cssPromise = new Promise((resolve, reject) => {
- if (typeof document === 'undefined') { reject(new Error('no document')); return; }
- if (document.getElementById('leaflet-css')) { resolve(); return; }
- const link = document.createElement('link');
- link.id = 'leaflet-css';
- link.rel = 'stylesheet';
- link.href = LEAFLET_CSS;
- link.crossOrigin = '';
- link.onload = () => resolve();
- link.onerror = () => { link.remove(); reject(new Error('leaflet css failed to load')); };
- document.head.appendChild(link);
- }).catch((e) => { _cssPromise = null; throw e; });
- return _cssPromise;
-}
-
-let _jsPromise = null;
-export function loadLeaflet() {
- if (_jsPromise) return _jsPromise;
- _jsPromise = (async () => {
- const [mod] = await Promise.all([import(/* @vite-ignore */ LEAFLET_JS), ensureLeafletCss()]);
- const L = mod?.default || mod;
- if (!L || typeof L.map !== 'function') throw new Error('leaflet module missing');
- return L;
- })().catch((e) => { _jsPromise = null; throw e; });
- return _jsPromise;
-}
diff --git a/tests/api/irl-pins-hardening.test.js b/tests/api/irl-pins-hardening.test.js
new file mode 100644
index 000000000..2e08150fe
--- /dev/null
+++ b/tests/api/irl-pins-hardening.test.js
@@ -0,0 +1,313 @@
+// /api/irl/pins — production hardening (tasks 11 / 12 / 13).
+//
+// These tests cover the backend-resilience + security-validation surface added to
+// api/irl/pins.js: radius + pin-id validation, the rate-limiter fail-open wrapper,
+// the Guardian degraded-state cache, the x402 allow-list parse, ownership + expiry
+// on calibrate/outfit/delete, and the no-internal-detail outfit-bake error. The
+// DB / auth / limiter / baker are mocked so the suite runs offline in Node.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ── Hoisted spy for the lazily-imported baker ────────────────────────────────
+const { bakeSpy } = vi.hoisted(() => ({ bakeSpy: vi.fn() }));
+
+// ── Content-addressed SQL mock ───────────────────────────────────────────────
+// `pinRow` is the row the WHERE-id SELECT returns (null → not found). Each mutation
+// (calibrate UPDATE, outfit UPDATE, delete) is classified by its query text and
+// honours the expiry/hidden guards the handler now appends to the WHERE clause —
+// so a test can make a mutation "miss" by marking the row expired/hidden.
+let pinRow = null;
+let deleteResult = [{ id: 'del-1', lat: 1, lng: 2 }];
+
+function pinIsLive(row) {
+ if (!row) return false;
+ if (row.hidden_at != null) return false;
+ if (row.expires_at == null) return true;
+ return new Date(row.expires_at).getTime() > Date.now();
+}
+
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+
+ // SELECT … WHERE id = $id (calibrate + outfit ownership lookup)
+ if (/SELECT[\s\S]*FROM irl_pins[\s\S]*WHERE id =/i.test(q)) {
+ return Promise.resolve(pinRow ? [pinRow] : []);
+ }
+ // Calibrate UPDATE — now guarded by hidden_at/expires_at; return a row only when live.
+ if (/UPDATE irl_pins SET[\s\S]*anchor_yaw_deg\s*=\s*COALESCE/i.test(q)) {
+ if (!pinIsLive(pinRow)) return Promise.resolve([]);
+ const [lat, lng, yaw, heading, height, id] = values;
+ return Promise.resolve([{
+ id, lat, lng,
+ heading: heading ?? pinRow?.heading ?? null,
+ anchor_yaw_deg: yaw ?? pinRow?.anchor_yaw_deg ?? null,
+ anchor_height_m: height ?? pinRow?.anchor_height_m ?? null,
+ gps_accuracy_m: pinRow?.gps_accuracy_m ?? null,
+ }]);
+ }
+ // Outfit UPDATE — guarded too.
+ if (/UPDATE irl_pins SET[\s\S]*avatar_version\s*=\s*avatar_version \+ 1/i.test(q)) {
+ if (!pinIsLive(pinRow)) return Promise.resolve([]);
+ const [manifestJson, , newAvatarUrl, id] = values;
+ return Promise.resolve([{
+ id, lat: pinRow?.lat ?? null, lng: pinRow?.lng ?? null,
+ avatar_url: newAvatarUrl,
+ avatar_manifest: manifestJson ? JSON.parse(manifestJson) : null,
+ avatar_version: (Number(pinRow?.avatar_version) || 0) + 1,
+ }]);
+ }
+ // DELETE … RETURNING id, lat, lng
+ if (/DELETE FROM irl_pins/i.test(q)) {
+ return Promise.resolve(deleteResult);
+ }
+ return Promise.resolve([]); // ensureTable DDL + anything else
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => sessionUser) }));
+
+// Limiter mock with a throw switch so we can prove the call-site fail-open wrapper
+// catches an outage instead of 500ing the request.
+let limiterThrows = false;
+function verdict() {
+ if (limiterThrows) throw new Error('redis: max requests limit exceeded');
+ return { success: true, reset: Date.now() + 60_000 };
+}
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ publicIp: vi.fn(async () => verdict()),
+ irlPinIp: vi.fn(async () => verdict()),
+ irlPinBurst: vi.fn(async () => verdict()),
+ irlPinHourly: vi.fn(async () => verdict()),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../../api/_lib/irl-bake.js', () => ({
+ bakePinOutfit: (...a) => bakeSpy(...a),
+ isBakeable: (m) => !!(m && (
+ m.outfit ||
+ (Array.isArray(m.accessories) && m.accessories.length) ||
+ (m.morphs && Object.keys(m.morphs).length) ||
+ (m.colors && Object.keys(m.colors).length) ||
+ (Array.isArray(m.hidden) && m.hidden.length)
+ )),
+}));
+
+const mod = await import('../../api/irl/pins.js');
+const { default: handler, isValidPinId, isExpiredOrHidden, safePaymentEndpoint, guardianDegraded, resetGuardianDegraded } = mod;
+
+const UUID = '11111111-1111-4111-8111-111111111111';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+async function call(method, { query = {}, body } = {}) {
+ const res = makeRes();
+ await handler({ url: '/api/irl/pins', method, headers: { host: 'x' }, query, body }, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+const get = (opts) => call('GET', opts);
+const patch = (body) => call('PATCH', { body });
+const del = (query) => call('DELETE', { query });
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ bakeSpy.mockReset();
+ bakeSpy.mockResolvedValue({ url: 'https://three.ws/cdn/irl/pins/x/abc.glb' });
+ deleteResult = [{ id: 'del-1', lat: 1, lng: 2 }];
+ limiterThrows = false;
+ sessionUser = null;
+ resetGuardianDegraded();
+ pinRow = {
+ id: UUID, user_id: null, device_token: 'device-A',
+ lat: 40.7128, lng: -74.006, heading: 90,
+ anchor_yaw_deg: 90, anchor_height_m: 0, gps_accuracy_m: 12,
+ avatar_url: '/api/avatars/av-1/glb', avatar_base_url: null, avatar_version: 0,
+ expires_at: null, hidden_at: null,
+ };
+});
+
+// ── Pure helpers ─────────────────────────────────────────────────────────────
+describe('isValidPinId', () => {
+ it('accepts a canonical UUID and rejects garbage / oversized ids', () => {
+ expect(isValidPinId(UUID)).toBe(true);
+ expect(isValidPinId('not-a-uuid')).toBe(false);
+ expect(isValidPinId('')).toBe(false);
+ expect(isValidPinId(null)).toBe(false);
+ expect(isValidPinId(123)).toBe(false);
+ expect(isValidPinId('x'.repeat(5000))).toBe(false);
+ // SQL-injection-shaped id is rejected at the boundary (defense in depth).
+ expect(isValidPinId("1' OR '1'='1")).toBe(false);
+ });
+});
+
+describe('isExpiredOrHidden', () => {
+ const now = Date.now();
+ it('treats a NULL expiry as permanent (live)', () => {
+ expect(isExpiredOrHidden({ expires_at: null, hidden_at: null }, now)).toBe(false);
+ });
+ it('treats a future expiry as live and a past expiry as gone', () => {
+ expect(isExpiredOrHidden({ expires_at: new Date(now + 60_000).toISOString() }, now)).toBe(false);
+ expect(isExpiredOrHidden({ expires_at: new Date(now - 60_000).toISOString() }, now)).toBe(true);
+ });
+ it('treats any hidden_at as gone regardless of expiry', () => {
+ expect(isExpiredOrHidden({ expires_at: null, hidden_at: new Date(now).toISOString() }, now)).toBe(true);
+ });
+});
+
+describe('safePaymentEndpoint — x402 allow-list (config validation)', () => {
+ it('accepts a same-origin relative path (always first-party)', () => {
+ expect(safePaymentEndpoint('/api/x402-pay')).toEqual({ ok: true, value: '/api/x402-pay' });
+ });
+ it('accepts a first-party host from the default allow-list', () => {
+ const r = safePaymentEndpoint('https://three.ws/api/x402-pay');
+ expect(r.ok).toBe(true);
+ });
+ it('rejects an arbitrary external host', () => {
+ expect(safePaymentEndpoint('https://evil.example.com/drain').ok).toBe(false);
+ });
+ it('rejects a non-https / private-host endpoint', () => {
+ expect(safePaymentEndpoint('http://three.ws/x').ok).toBe(false);
+ expect(safePaymentEndpoint('https://127.0.0.1/x').ok).toBe(false);
+ });
+ it('passes a null/empty endpoint through as cleared', () => {
+ expect(safePaymentEndpoint(null)).toEqual({ ok: true, value: null });
+ expect(safePaymentEndpoint('')).toEqual({ ok: true, value: null });
+ });
+});
+
+// ── GET radius validation (task 11) ──────────────────────────────────────────
+describe('GET /api/irl/pins — radius validation', () => {
+ it('400s a present-but-non-finite radius instead of silently scanning a NaN box', async () => {
+ const { res, body } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: 'abc' } });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/invalid radius/i);
+ // Never reached the pin SELECT — failed at the boundary.
+ const ranSelect = sqlMock.mock.calls.some(([s]) =>
+ /lat BETWEEN/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(ranSelect).toBe(false);
+ });
+ it('defaults a missing radius to 40 and 200s', async () => {
+ const { res } = await get({ query: { lat: '40.7128', lng: '-74.006' } });
+ expect(res.statusCode).toBe(200);
+ });
+});
+
+// ── Pin-id validation on mutations (task 13) ─────────────────────────────────
+describe('PATCH /api/irl/pins — pin-id validation', () => {
+ it('400s a malformed id before any auth or DB work', async () => {
+ const { res, body } = await patch({ id: 'garbage', calibrate: { lat: 40.7128, lng: -74.006 } });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/invalid pin id/i);
+ const ranSelect = sqlMock.mock.calls.some(([s]) =>
+ /WHERE id =/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(ranSelect).toBe(false);
+ });
+});
+
+describe('DELETE /api/irl/pins — pin-id validation', () => {
+ it('400s a malformed id before the delete query', async () => {
+ const { res, body } = await del({ id: 'garbage', deviceToken: 'device-A' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toMatch(/invalid pin id/i);
+ const ranDelete = sqlMock.mock.calls.some(([s]) =>
+ /DELETE FROM irl_pins/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(ranDelete).toBe(false);
+ });
+});
+
+// ── Expiry guard on mutations (task 13) ──────────────────────────────────────
+describe('calibrate — refuses an expired pin', () => {
+ it('404s an expired pin even for the owner, and never UPDATEs', async () => {
+ pinRow.expires_at = new Date(Date.now() - 1000).toISOString();
+ const { res, body } = await patch({
+ id: UUID, deviceToken: 'device-A',
+ calibrate: { lat: 40.7128, lng: -74.006 },
+ });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toMatch(/not found/i);
+ const ranUpdate = sqlMock.mock.calls.some(([s]) =>
+ /UPDATE irl_pins SET[\s\S]*anchor_yaw_deg/i.test(Array.isArray(s) ? s.join(' ') : String(s)));
+ expect(ranUpdate).toBe(false);
+ });
+ it('200s a live pin for the owner', async () => {
+ const { res, body } = await patch({
+ id: UUID, deviceToken: 'device-A',
+ calibrate: { lat: 40.7128, lng: -74.006, anchorYawDeg: 95 },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(body.calibrated).toBe(true);
+ });
+});
+
+describe('outfit — refuses an expired pin', () => {
+ beforeEach(() => {
+ pinRow.user_id = 'owner-uuid';
+ pinRow.device_token = null;
+ sessionUser = { id: 'owner-uuid' };
+ });
+ it('404s an expired pin and never bakes', async () => {
+ pinRow.expires_at = new Date(Date.now() - 1000).toISOString();
+ const { res, body } = await patch({ id: UUID, avatar_manifest: { colors: { outfit: '#7a1f2b' } } });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toMatch(/not found/i);
+ expect(bakeSpy).not.toHaveBeenCalled();
+ });
+ it('does NOT leak the upstream error message when a bake fails', async () => {
+ bakeSpy.mockRejectedValueOnce(new Error('libvips: /secret/internal/path exploded'));
+ const { res, body } = await patch({ id: UUID, avatar_manifest: { colors: { outfit: '#7a1f2b' } } });
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toMatch(/could not bake/i);
+ expect(body).not.toHaveProperty('detail');
+ expect(JSON.stringify(body)).not.toMatch(/libvips|secret|internal|path/i);
+ });
+});
+
+describe('delete — expiry-guarded WHERE', () => {
+ it('returns the delete result for a live owned pin', async () => {
+ const { res, body } = await del({ id: UUID, deviceToken: 'device-A' });
+ expect(res.statusCode).toBe(200);
+ expect(body.ok).toBe(true);
+ });
+ it('404s when the guarded WHERE matches nothing (expired / not yours)', async () => {
+ deleteResult = []; // the expiry/owner clause matched no row
+ const { res, body } = await del({ id: UUID, deviceToken: 'device-A' });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toMatch(/not found|not yours/i);
+ });
+});
+
+// ── Rate-limiter fail-open (task 12) ─────────────────────────────────────────
+describe('rate limiter fail-open', () => {
+ it('a throwing limiter does not 500 a GET — the request is allowed', async () => {
+ limiterThrows = true;
+ const { res } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '40' } });
+ // Fail-open: the read proceeds to a normal 200, never a 500 from the limiter.
+ expect(res.statusCode).toBe(200);
+ });
+ it('a throwing limiter does not 500 a DELETE — ownership is still enforced', async () => {
+ limiterThrows = true;
+ const { res } = await del({ id: UUID, deviceToken: 'device-A' });
+ expect(res.statusCode).toBe(200);
+ });
+});
+
+// ── Guardian degraded cache (task 12) ────────────────────────────────────────
+describe('guardian degraded state', () => {
+ it('starts not-degraded and resets cleanly', () => {
+ resetGuardianDegraded();
+ expect(guardianDegraded()).toBe(false);
+ });
+});
diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.js
index 68424efa5..d9da9fd4b 100644
--- a/workers/agent-sniper/config.js
+++ b/workers/agent-sniper/config.js
@@ -66,6 +66,16 @@ export function loadConfig() {
feedWatchdogMs: Math.max(30_000, num('SNIPER_FEED_WATCHDOG_MS', 180_000)),
// Confirmation timeout for a broadcast trade.
confirmTimeoutMs: Math.max(15_000, num('SNIPER_CONFIRM_TIMEOUT_MS', 60_000)),
+ // ── liveness + alerting ──────────────────────────────────────────────────
+ // How often the worker upserts its bot_heartbeat row. /api/sniper/status
+ // (and /status) read this to answer "is the sniper alive?" without SSH.
+ heartbeatMs: Math.max(10_000, num('SNIPER_HEARTBEAT_MS', 30_000)),
+ // Executor/RPC errors within this sliding window that trip an ops alert.
+ errorAlertThreshold: Math.max(1, num('SNIPER_ERROR_ALERT_THRESHOLD', 5)),
+ errorAlertWindowMs: Math.max(60_000, num('SNIPER_ERROR_ALERT_WINDOW_MS', 600_000)),
+ // Announce boot/shutdown to the ops channel (a deploy that never comes back
+ // up is otherwise silent). Disable in noisy dev with SNIPER_ANNOUNCE=0.
+ announceLifecycle: bool('SNIPER_ANNOUNCE', true),
// ── first-claim trigger ─────────────────────────────────────────────────
// How often to poll the on-chain fee-claim stream for first-ever claims.
claimPollMs: Math.max(10_000, num('SNIPER_CLAIM_POLL_MS', 30_000)),
diff --git a/workers/agent-sniper/error-tracker.js b/workers/agent-sniper/error-tracker.js
new file mode 100644
index 000000000..8da4337f0
--- /dev/null
+++ b/workers/agent-sniper/error-tracker.js
@@ -0,0 +1,48 @@
+// agent-sniper — sliding-window error tracker.
+//
+// A few transient RPC errors are normal under the new-mint firehose; a *spike*
+// means the RPC endpoint is degraded, an agent wallet is misconfigured, or the
+// chain is congested — and snipes are silently failing. This tracks executor /
+// RPC errors over a sliding window and trips ONCE when the count crosses the
+// threshold, then re-arms only after the window drains, so a sustained problem
+// pages once (sendOpsAlert also dedups) rather than on every failure.
+
+export function makeErrorTracker({ threshold, windowMs }) {
+ const hits = [];
+ let last = null;
+ let armed = true; // can fire again once below threshold
+
+ function prune(now) {
+ while (hits.length && now - hits[0] > windowMs) hits.shift();
+ }
+
+ return {
+ /**
+ * Record an error. Returns a payload to alert on iff the spike threshold
+ * was just crossed (and not already alerted for this run-up), else null.
+ * @param {string} [message]
+ */
+ record(message) {
+ const now = Date.now();
+ last = message || 'error';
+ hits.push(now);
+ prune(now);
+ if (armed && hits.length >= threshold) {
+ armed = false;
+ return { count: hits.length, windowMs, lastError: last };
+ }
+ return null;
+ },
+ /** Re-arm once the window has drained below the threshold. */
+ tick() {
+ prune(Date.now());
+ if (!armed && hits.length < threshold) armed = true;
+ },
+ get total() {
+ return hits.length;
+ },
+ get lastError() {
+ return last;
+ },
+ };
+}
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
index fe5a36bc4..eb93c547c 100644
--- a/workers/agent-sniper/index.js
+++ b/workers/agent-sniper/index.js
@@ -20,6 +20,16 @@ import { runPositionSweep } from './positions.js';
import { startFirstClaimWatch } from './first-claim-watch.js';
import { startIntelWatcher } from './intel/watcher.js';
import { getLearnedWeights } from './intel/store.js';
+import { startHeartbeat } from './heartbeat.js';
+import { makeErrorTracker } from './error-tracker.js';
+import {
+ alertFeedSilent,
+ alertErrorSpike,
+ alertBoot,
+ alertShutdown,
+} from './alerts.js';
+
+const BOOT_AT = new Date().toISOString();
// ── global buy throttle (sliding 60s window) ─────────────────────────────────
function makeThrottle(maxPerMin) {
@@ -37,7 +47,7 @@ function makeThrottle(maxPerMin) {
}
// ── bounded buy queue (cap concurrent snipe attempts → bounded RPC) ──────────
-function makeQueue(concurrency, maxDepth) {
+function makeQueue(concurrency, maxDepth, onError) {
let active = 0;
const q = [];
const pump = () => {
@@ -46,7 +56,7 @@ function makeQueue(concurrency, maxDepth) {
active++;
Promise.resolve()
.then(job)
- .catch((err) => log.error('buy job crashed', { err: err?.message }))
+ .catch((err) => { log.error('buy job crashed', { err: err?.message }); onError?.(err?.message); })
.finally(() => { active--; pump(); });
}
};
@@ -63,11 +73,21 @@ function makeQueue(concurrency, maxDepth) {
async function main() {
const cfg = loadConfig();
log.info('boot', { network: cfg.network, mode: cfg.mode, globalKill: cfg.globalKill, pollMs: cfg.pollMs });
+ if (cfg.announceLifecycle) alertBoot({ network: cfg.network, mode: cfg.mode, globalKill: cfg.globalKill });
const throttle = makeThrottle(cfg.maxGlobalBuysPerMin);
- const queue = makeQueue(3, 50);
+ const errors = makeErrorTracker({ threshold: cfg.errorAlertThreshold, windowMs: cfg.errorAlertWindowMs });
+ // Funnel an error into the spike tracker; alert once when a run-up crosses the
+ // threshold. Pure observability — never alters the trade path.
+ const noteError = (where, message) => {
+ const spike = errors.record(`${where}: ${message || 'error'}`);
+ if (spike) alertErrorSpike({ ...spike, network: cfg.network, mode: cfg.mode });
+ };
+ const queue = makeQueue(3, 50, (message) => noteError('buy', message));
let draining = false;
let lastEventAt = Date.now();
+ let feedConnected = false;
+ let reconnectCount = 0;
await refreshStrategies(cfg.network, 0).then(() => logStrategyLoad(cfg.network)).catch((err) =>
log.error('initial strategy load failed', { err: err?.message }),
@@ -75,6 +95,7 @@ async function main() {
const onEvent = ({ kind, data }) => {
lastEventAt = Date.now();
+ feedConnected = true; // an event is proof the subscription is live
if (kind !== 'mint' || draining || cfg.globalKill) return;
const strategies = cachedStrategies();
for (const strat of strategies) {
@@ -95,6 +116,7 @@ async function main() {
const abort = new AbortController();
let stopFeed = connectPumpFunFeed({ kind: 'mint', signal: abort.signal, onEvent });
+ feedConnected = true;
log.info('feed connected', {});
// Coin Intelligence Engine: observe every new coin's first seconds, classify
@@ -157,7 +179,15 @@ async function main() {
const positionTimer = setInterval(async () => {
if (sweeping || draining) return;
sweeping = true;
- try { await runPositionSweep(cfg); } finally { sweeping = false; }
+ try {
+ await runPositionSweep(cfg);
+ } catch (err) {
+ log.error('position sweep failed', { err: err?.message });
+ noteError('sweep', err?.message);
+ } finally {
+ sweeping = false;
+ errors.tick(); // re-arm the spike alert once the window drains
+ }
}, cfg.pollMs);
// Feed watchdog: connectPumpFunFeed stops after 5 drops; if the feed goes
@@ -165,8 +195,12 @@ async function main() {
// silently goes deaf.
const watchdogTimer = setInterval(() => {
if (draining) return;
- if (Date.now() - lastEventAt > cfg.feedWatchdogMs) {
- log.warn('feed silent — re-subscribing', { silentMs: Date.now() - lastEventAt });
+ const silentMs = Date.now() - lastEventAt;
+ if (silentMs > cfg.feedWatchdogMs) {
+ feedConnected = false;
+ reconnectCount++;
+ log.warn('feed silent — re-subscribing', { silentMs, reconnects: reconnectCount });
+ alertFeedSilent({ silentMs, network: cfg.network, mode: cfg.mode });
try { stopFeed?.(); } catch {}
lastEventAt = Date.now();
const a2 = new AbortController();
@@ -175,13 +209,37 @@ async function main() {
}
}, Math.min(cfg.feedWatchdogMs, 60_000));
+ // Liveness heartbeat — upserts bot_heartbeat so /api/sniper/status and the
+ // uptime cron can see the worker is alive AND that its feed is actually live
+ // (a process that's up with a dead feed is the worst, silent failure mode).
+ const stopHeartbeat = startHeartbeat({
+ mode: cfg.mode,
+ intervalMs: cfg.heartbeatMs,
+ getMeta: () => ({
+ network: cfg.network,
+ feedConnected,
+ lastEventAgeMs: Date.now() - lastEventAt,
+ feedWatchdogMs: cfg.feedWatchdogMs,
+ strategies: cachedStrategies().length,
+ globalKill: cfg.globalKill,
+ reconnects: reconnectCount,
+ errors: errors.total,
+ lastError: errors.lastError,
+ intel: cfg.intel,
+ inFlightBuys: queue.inFlight,
+ bootAt: BOOT_AT,
+ }),
+ });
+
const shutdown = async (signal) => {
if (draining) return;
draining = true;
log.info('shutdown', { signal, inFlight: queue.inFlight });
+ if (cfg.announceLifecycle) alertShutdown({ signal, inFlight: queue.inFlight });
clearInterval(strategyTimer);
clearInterval(positionTimer);
clearInterval(watchdogTimer);
+ try { stopHeartbeat?.(); } catch {}
try { stopClaimWatch?.(); } catch {}
try { stopFeed?.(); } catch {}
try { stopIntel?.(); } catch {}
@@ -197,7 +255,10 @@ async function main() {
};
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
- process.on('unhandledRejection', (err) => log.error('unhandledRejection', { err: err?.message }));
+ process.on('unhandledRejection', (err) => {
+ log.error('unhandledRejection', { err: err?.message });
+ noteError('unhandledRejection', err?.message);
+ });
}
main().catch((err) => {