Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
IRL: realtime pin sync, SSE owner inbox, moderation reports, and reaper cron
nirholas6d55fc1bc07e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2331f08a8..c343150d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,12 +6,24 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-17+- **An inbox for your IRL agents — see who tapped, messaged, or paid, and reply** — Your IRL Agents dashboard now has an Inbox: a live, chronological feed of everyone who met your placed agents in real life. Each entry shows what happened — a view, a tap, a message, or a payment — where it happened, and how long ago. Payments show the exact amount and link straight to the block-explorer receipt, and you can reply to anyone who left your agent a message; if they were signed in, your reply lands in their notifications. Unread counts appear on the Inbox button and on each agent's card, the feed refreshes itself every few seconds, and opening the inbox marks everything read. High-signal events (a payment or a message) also ping you in the notification bell, so you find out the moment a stranger across the city engages your agent. (`/dashboard/irl-placements`) `[feature]`+- **Change a placed agent's outfit from your dashboard — everyone nearby sees it** — Your IRL Agents dashboard now has a real outfit editor. Open Change outfit on any agent you've placed and a live 3D preview loads with wardrobe controls for the exact layers that avatar has — recolour its hair, skin, and clothing, strip back to the base body and dress it up again, or stack on hats, glasses, and earrings. Because your agents are public, the new look is baked into the agent itself and pushed to its real-world pin, so every person who walks up to that spot sees the updated outfit in their camera — not just you. Save when you're happy; the avatar is re-rendered for real before it confirms, the previous look stays untouched if anything fails, and nearby viewers refresh to the new outfit within seconds. Run a seasonal look, brand your agents as staff for an event, or just keep them fresh — all without walking back to where you pinned them. (`/dashboard/irl-placements`) `[feature]`- **Everyone at a location now sees your IRL agent in the same real spot** — three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry. (`/irl`) `[feature, improvement]`- **iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk** — iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated. (`/irl`) `[improvement]`- **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 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 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]`+- **IRL placements now have guardrails: report a pin, content checks, and area limits** — Now that anyone at a location can see anyone's placed agent on three.ws/irl, we've added the safety layer that makes a public shared space work. Tap any agent that isn't yours and you'll find a Report option — pick a reason (spam, hate, impersonation, scam, sexual content, or something else) and once enough different people flag the same pin it's automatically hidden from everyone, with the reporter seeing it disappear right away. One person can't hide someone else's agent, and repeat reports from the same device don't stack, so the system can't be gamed to silence a legitimate pin. At placement time, captions and agent names are screened for slurs and hateful content and rejected with a clear, fixable message, and a pin can only ever reference $THREE — no other coin can be advertised. Pay buttons are locked to three.ws payment endpoints so a pin can't point you at an off-platform drain. To stop one person from carpet-bombing a plaza, each small area caps how many agents it holds and each person has an active-pin limit — and if you hit a limit you get a plain-language nudge (shorten the text, move, wait a moment, or remove an old pin) instead of a silent failure. Abandoned anonymous pins are now cleaned up automatically; your signed-in permanent pins are never touched. (`/irl`) `[security, feature]`+- **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]`+- **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]`+- **Move your IRL agents on a real map — drag the pin from anywhere** — Your IRL Agents dashboard now has a live map. Open Move on map on any placed agent and you get an OpenStreetMap view with a draggable pin for each agent you've placed: drag the highlighted one to a new spot, or tap another to switch to it. As you drag, the new location is named for you (the nearest town or city) and a Save bar appears so nothing changes until you confirm — and if a save ever fails, the pin snaps back to where it was. A compass dial lets you re-aim which way the agent faces, in degrees or by dragging the needle, and a Remove from map button takes a pin down. You can relocate an agent across the city — or across the world — without walking back to it. The map loads only when you open it, works on a phone, and if it can't load it falls back to a simple latitude/longitude form so you can still move the pin. (`/dashboard/irl-placements`) `[feature]`+- **Nearby agents on IRL now update live — no reload** — Open three.ws/irl and the agents other people have placed around you now update in real time. When anyone nearby drops a new agent, moves one, changes its outfit, or takes one down, you see it appear, shift, or vanish on your screen within about a second — no refresh, no waiting for the next scan. It works both ways: pin an agent and everyone standing near you sees it pop in too, and walk into a new area and the live view follows you to the agents there. A small status pill next to the nearby count shows whether you're getting live updates; if the realtime connection can't be reached — some networks block it — IRL automatically falls back to refreshing every few seconds and the pill reads 'Polling', still fully working, just a touch slower. (`/irl`) `[feature, improvement]`+- **Pay an IRL agent for its services — and open its full profile — right from the card** — When you tap an agent on three.ws/irl, its card now does real things. View profile opens that agent's full page so you can see who you just met. If the agent offers paid services, each one shows its price and a Use button: tap it, approve the payment in your wallet, and you pay in USDC on the spot — the standard x402 flow, capped at the price shown so a misconfigured service can never overcharge you. The response you paid for appears right inside the card instead of vanishing into a toast. Every state is handled: no wallet, a cancelled signature, or a service error each show a clear message and leave the button ready to try again, and each service button works on its own so paying for one never freezes the others. Completed encounters quietly notify the agent's owner, receipt and all. (`/irl`) `[feature]`- **Place your IRL agent on the real floor with AR anchoring** — On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. If you tap to anchor before your location is ready, it holds the spot and saves it the instant your first GPS fix lands instead of losing the placement. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button. (`/irl`) `[feature]`+- **See your IRL agent's on-chain reputation right from the dashboard** — On your IRL Agents dashboard, the Reputation chip on each placed agent now opens an on-chain reputation panel — the exact score and trust tier (Elite, Trusted, Emerging, New) a passer-by sees when they tap your agent in real life. It breaks down how many attestations are verified, credentialed, and disputed, shows the average star rating and how many distinct people vouched, and links straight to the agent's passport to manage it. Agents without a Solana identity, or without any attestations yet, get a clear next step instead of an error. (`/dashboard/irl-placements`) `[feature]`- **Tapping an IRL agent is now reliable — hit the body, not just the tiny label** — On three.ws/irl you can now open an agent by tapping its 3D body, not only its small floating name tag. Tapping near a name also works, with a finger-sized target that meets Apple's 44-pixel minimum, so you no longer have to pixel-hunt on a phone. When two agents stand on top of each other, the one in front wins instead of a random pick. As you move, the nearest agent you can reach lights up with a soft focus ring so you can see what you'll tap before you tap it — and if you've turned on Reduce Motion, the ring stays still. Looking and panning around no longer misfires as a tap. (`/irl`) `[improvement]`+- **Your IRL agent dashboard now lights up the instant someone interacts** — When a stranger taps, messages, or pays one of your agents placed out in the real world, your dashboard now reflects it within about a second — no refresh. The agent's card flashes, the unread count ticks up live, and a payment or a new message pops a notification so you feel the moment it happens, even from the other side of the planet. A small Live indicator shows when the realtime connection is up; if it ever drops, the inbox keeps updating on a short delay instead, so you never miss an encounter. Only your agent's name and the kind of interaction are ever shared with you — never the visitor's location or wallet. (`/dashboard/irl-placements`) `[feature, improvement]`## 2026-06-16diff --git a/api/_lib/irl-bake.js b/api/_lib/irl-bake.jsnew file mode 100644index 000000000..a26c971e4--- /dev/null+++ b/api/_lib/irl-bake.js@@ -0,0 +1,74 @@+// IRL pin outfit baker — re-skin a placed agent for every nearby viewer.+//+// An IRL outfit change is the SAME appearance bake the avatar studio runs+// (api/_lib/bake.js → bakeAppearance); only the I/O differs:+// • the base GLB comes from a URL (the pin's stored avatar), not an R2 key+// • the output lands under an irl/pins/<id>/ namespace and is served through+// the first-party /cdn proxy (publicUrl).+//+// We REUSE the bake core verbatim — no forked transform pipeline — so a pin's+// dressed avatar is byte-for-byte what the studio would produce.+//+// Baking always starts from the pin's CAPTURED BASE GLB, never the previously+// baked avatar_url: re-applying a manifest on top of a prior bake would+// double-merge bone accessories and could never un-hide a stripped garment.+// The manifest is the single source of truth, applied fresh onto the base each+// time, so the result is a pure function of (base, manifest) — idempotent and+// stack-free.++import { bakeAppearance, appearanceHash, isBakeable } from './bake.js';+import { putObject, publicUrl } from './r2.js';+import { env } from './env.js';++export { isBakeable };++// A baked avatar GLB is small (the studio bake quantizes + meshopt-compresses),+// but guard against a pathological base so one fetch can't balloon memory.+const MAX_BASE_GLB_BYTES = 25 * 1024 * 1024;++// Resolve the pin's base GLB to absolute bytes. Relative URLs (the common+// `/api/avatars/:id/glb` form, or `/cdn/<key>`) resolve against the app origin —+// the avatar lives on our own API/CDN. Absolute URLs were already SSRF-screened+// by safeRemoteUrl() when the pin was created, so re-fetching them is safe.+async function fetchBaseGlb(baseUrl) {+ if (!baseUrl) throw new Error('pin has no base avatar GLB to dress');+ const abs = /^https?:\/\//i.test(baseUrl)+ ? baseUrl+ : `${env.APP_ORIGIN}${baseUrl.startsWith('/') ? '' : '/'}${baseUrl}`;+ const r = await fetch(abs);+ if (!r.ok) throw new Error(`base GLB fetch failed: ${abs} → ${r.status}`);+ const declared = Number(r.headers.get('content-length') || 0);+ if (declared && declared > MAX_BASE_GLB_BYTES) {+ throw new Error('base GLB exceeds 25 MB');+ }+ const buf = Buffer.from(await r.arrayBuffer());+ if (buf.byteLength > MAX_BASE_GLB_BYTES) throw new Error('base GLB exceeds 25 MB');+ return buf;+}++/**+ * Bake `manifest` onto a pin's base GLB and store the dressed result.+ *+ * The R2 key is namespaced by pin id and keyed by the appearance hash, so two+ * distinct looks for one pin get distinct, write-once URLs (cache-correct for+ * the viewer's GLTFLoader) while re-selecting the same look reuses its URL.+ *+ * @param {object} args+ * @param {string} args.pinId irl_pins.id (R2 key namespace)+ * @param {string} args.baseUrl the pin's captured base GLB (avatar_base_url ?? avatar_url)+ * @param {object} args.manifest { colors?, hidden?, accessories?, morphs?, outfit? }+ * @returns {Promise<{ url: string, hash: string, size_bytes: number }>}+ */+export async function bakePinOutfit({ pinId, baseUrl, manifest }) {+ const baseBytes = await fetchBaseGlb(baseUrl);+ const bakedBytes = await bakeAppearance(baseBytes, manifest);+ const hash = appearanceHash(manifest) || 'base';+ const key = `irl/pins/${pinId}/${hash.slice(0, 16)}.glb`;+ await putObject({+ key,+ body: Buffer.from(bakedBytes),+ contentType: 'model/gltf-binary',+ metadata: { 'irl-pin': String(pinId), 'appearance-hash': hash },+ });+ return { url: publicUrl(key), hash, size_bytes: bakedBytes.byteLength };+}diff --git a/api/_lib/irl-publish.js b/api/_lib/irl-publish.jsnew file mode 100644index 000000000..323efeaca--- /dev/null+++ b/api/_lib/irl-publish.js@@ -0,0 +1,60 @@+// IRL realtime publish transport — the Vercel→Colyseus webhook for D1 live pin+// sync. This is the single place that actually talks to the multiplayer host;+// callers (api/irl/pins.js lifecycle, api/_lib/irl-realtime.js reskin hook) hand+// it a typed pin change and never block on the result.+//+// Vercel functions can't hold a WebSocket, so when a pin is placed / moved /+// re-skinned / removed we fire a signed HTTP webhook at the standalone Colyseus+// host, which fans the change into the matching geocell room as a schema delta+// every viewer there receives within the patch interval. Best-effort by design:+// the pin is already persisted in Neon and every viewer's poll fallback / next+// room load reconciles it, so a publish failure degrades to "slightly slower",+// never to data loss. Never awaited on a request's critical path.+//+// Keep byte-for-byte in sync with the verifier (multiplayer/src/irl-publish-auth.js):+// signed = `irl:<geocell>:<type>:<ts>:<base64url(sha256(JSON(pin)))>`+// sig = base64url(HMAC_SHA256(MULTIPLAYER_SHARED_SECRET, signed))++import { env } from './env.js';+import { hmacSha256, sha256Base64Url } from './crypto.js';++const PUBLISH_TYPES = new Set(['pin:add', 'pin:update', 'pin:remove']);++/**+ * Publish a pin change to the multiplayer host. Returns a small result object;+ * callers fire-and-forget (`void publishIrlPin(...)`) and never block on it.+ * @param {'pin:add'|'pin:update'|'pin:remove'} type+ * @param {string} geocell precision-6 cell the pin lives in+ * @param {object} pin wire object — full ({ id, lat, lng, heading, avatarUrl, … })+ * for add, a partial subset for update, or just { id } for remove+ */+export async function publishIrlPin(type, geocell, pin = {}) {+ if (!PUBLISH_TYPES.has(type)) return { delivered: false, reason: 'bad_type' };+ if (typeof geocell !== 'string' || !geocell) return { delivered: false, reason: 'no_geocell' };+ const base = env.MULTIPLAYER_INTERNAL_URL;+ if (!base) return { delivered: false, reason: 'unconfigured' };+ try {+ const ts = Math.floor(Date.now() / 1000);+ const pinHash = await sha256Base64Url(JSON.stringify(pin ?? {}));+ const sig = await hmacSha256(+ env.MULTIPLAYER_SHARED_SECRET,+ `irl:${geocell}:${type}:${ts}:${pinHash}`,+ );+ const res = await fetch(`${base}/internal/irl-publish`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'x-mp-signature': sig,+ 'x-mp-timestamp': String(ts),+ },+ body: JSON.stringify({ geocell, type, pin }),+ signal: AbortSignal.timeout(2500),+ });+ if (!res.ok) return { delivered: false, reason: `http_${res.status}` };+ const body = await res.json().catch(() => ({}));+ const count = Number(body?.delivered) || 0;+ return { delivered: count > 0, count };+ } catch (err) {+ return { delivered: false, reason: err?.name === 'TimeoutError' ? 'timeout' : 'error' };+ }+}diff --git a/api/_lib/irl-realtime.js b/api/_lib/irl-realtime.jsnew file mode 100644index 000000000..b7a5adbf6--- /dev/null+++ b/api/_lib/irl-realtime.js@@ -0,0 +1,66 @@+// IRL realtime fan-out — the single server-side emit point for pin lifecycle+// events that co-located viewers react to in real time.+//+// Epic D owns the actual WS/geohash transport. Until it lands, this is a hook,+// not a live channel: it computes the geohash room a change belongs to and the+// minimal payload a viewer needs to swap a pin's rendered GLB in place, then+// hands them to whatever transport is wired (none yet). The DURABLE contract is+// the poll path — src/irl.js loadNearbyPins diffs avatar_version on its next+// cycle and swaps the GLB — so propagation is correct with or without D1; this+// hook only makes it feel instant once realtime exists.+//+// Wiring D1: implement publishPinEvent() to push `event` to room `irl:<room>`+// (e.g. d1.publish(`irl:${room}`, event)). Every caller already routes through+// here, so that one function is the only thing realtime has to fill in.++import { encodeGeohash } from './geohash.js';++// ~1.2 km cells (precision 6) — coarse enough that a viewer within the 150 m+// nearby radius always shares (or borders) the changed pin's room, fine enough+// that a city-wide change doesn't wake every client. The transport can fan a+// change out to the cell plus its 8 neighbours when it lands; the poll fallback+// covers any edge a single cell misses.+const ROOM_PRECISION = 6;++function roomFor(lat, lng) {+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;+ return encodeGeohash(lat, lng, ROOM_PRECISION) || null;+}++// D1 transport: a re-skin is a PARTIAL pin:update carrying only the new+// avatar_url, so the geocell room swaps the GLB without disturbing the pin's+// other live fields. Best-effort — the import is lazy so this file stays cheap to+// load, and any transport error is swallowed by the caller (Rule 9: a realtime+// hiccup must never fail the owner's save; the poll path still propagates).+async function publishPinEvent(room, event) {+ if (!room || !event?.id) return false;+ const pin = { id: event.id };+ if (event.avatar_url) pin.avatarUrl = event.avatar_url;+ const { publishIrlPin } = await import('./irl-publish.js');+ const res = await publishIrlPin('pin:update', room, pin);+ return !!res?.delivered;+}++/**+ * Emit a `pin_updated` event so co-located viewers swap a re-skinned pin's GLB+ * without waiting for their next nearby poll. Best-effort and non-throwing —+ * the caller never awaits propagation, and the poll path is authoritative.+ *+ * @param {object} pin { id, lat, lng, avatar_url, avatar_version }+ * @returns {{ room: string|null, event: object }} the room + payload that was emitted+ */+export function emitPinUpdated(pin) {+ const room = roomFor(Number(pin?.lat), Number(pin?.lng));+ const event = {+ type: 'pin_updated',+ id: pin?.id,+ avatar_url: pin?.avatar_url ?? null,+ avatar_version: Number(pin?.avatar_version) || 0,+ };+ if (room) {+ // Fire-and-forget; swallow transport errors (Rule 9 — a realtime hiccup+ // must never fail the owner's save, and the poll fallback still propagates).+ Promise.resolve(publishPinEvent(room, event)).catch(() => {});+ }+ return { room, event };+}diff --git a/api/cron/irl-reap.js b/api/cron/irl-reap.jsnew file mode 100644index 000000000..725d2b9c6--- /dev/null+++ b/api/cron/irl-reap.js@@ -0,0 +1,65 @@+// @ts-check+// GET /api/cron/irl-reap — IRL placement reaper (D4).+//+// Keeps the irl_pins table and every geocell density count lean by deleting dead+// rows the nearby/mine queries already filter out:+//+// 1. Expired anonymous pins, one day past expiry — long enough that a brief+// clock skew or a viewer mid-session never loses a still-relevant pin, short+// enough that ghosts don't accumulate. Signed-in permanent pins (expires_at+// IS NULL) are NEVER reaped.+// 2. Reports tied to pins that no longer exist — once the pin is gone the report+// trail is moot, so it's purged to keep irl_pin_reports bounded.+//+// Hidden pins are NOT deleted here: a moderation-hidden pin is queued for review ++// owner appeal, not garbage. It's reaped only when its own expiry passes (anon) or+// never (signed-in) — the same rule as any other pin.+//+// Runs hourly. Idempotent: re-running deletes nothing new once the table is clean.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ if (!requireCron(req, res)) return;++ // Expired anon pins, ≥ 1 day past expiry. expires_at IS NULL ⇒ permanent ⇒ kept.+ const reapedPins = await sql`+ DELETE FROM irl_pins+ WHERE expires_at IS NOT NULL+ AND expires_at < NOW() - INTERVAL '1 day'+ RETURNING id+ `;++ // Orphaned reports — their pin is gone, so the trail is moot.+ const reapedReports = await sql`+ DELETE FROM irl_pin_reports r+ WHERE NOT EXISTS (SELECT 1 FROM irl_pins p WHERE p.id = r.pin_id)+ RETURNING r.id+ `;++ return json(res, 200, {+ ok: true,+ reapedPins: reapedPins.length,+ reapedReports: reapedReports.length,+ ts: Date.now(),+ });+});diff --git a/api/irl/agent-summary.js b/api/irl/agent-summary.jsindex 6647528d3..8e684dd31 100644--- a/api/irl/agent-summary.js+++ b/api/irl/agent-summary.js@@ -8,10 +8,14 @@** Returns { agents: [ {* pin_id, agent_id, lat, lng, heading, caption, avatar_url, avatar_name,+ * avatar_manifest, avatar_base_url, avatar_version,* placed_at, expires_at, view_count, agent_name, solana_address,* interaction_count, last_interaction_at, status* } ] }*+ * avatar_manifest/avatar_base_url/avatar_version (C6) let the dashboard open the+ * remote Outfit editor seeded with the pin's current look and detect re-skins.+ ** `status` is derived: 'expired' (expires_at passed) · 'online' (an interaction* touched the pin in the last 5 min — proxy until D1/C4 write last_seen_at) ·* 'visible' (live, no recent activity). Degrades to 0 / null when the@@ -45,6 +49,7 @@ export default wrap(async (req, res) => {? await sql`SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,p.avatar_url, p.avatar_name, p.placed_at, p.expires_at, p.view_count,+ p.avatar_manifest, p.avatar_base_url, p.avatar_version,a.name AS agent_name,a.meta->>'solana_address' AS solana_address,COALESCE(ix.total, 0)::int AS interaction_count,@@ -61,6 +66,7 @@ export default wrap(async (req, res) => {: await sql`SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,p.avatar_url, p.avatar_name, p.placed_at, p.expires_at, p.view_count,+ p.avatar_manifest, p.avatar_base_url, p.avatar_version,a.name AS agent_name,a.meta->>'solana_address' AS solana_address,0 AS interaction_count,diff --git a/api/irl/interactions-stream.js b/api/irl/interactions-stream.jsnew file mode 100644index 000000000..1cb6d81e3--- /dev/null+++ b/api/irl/interactions-stream.js@@ -0,0 +1,287 @@+// GET /api/irl/interactions-stream — Server-Sent Events for the owner's IRL inbox.+//+// This is the realtime delivery layer for D3 (`A → server → owner`). The C4+// dashboard (src/dashboard-next/pages/irl-placements.js) does one fast GET+// /api/irl/interactions?mine=1 for first paint, then opens THIS stream so a tap,+// message, or pay on a placed agent lands in the open inbox within ~1s instead of+// only on the next reload — even though the owner is almost never standing in the+// same geocell as the passer-by.+//+// The geocell room (D1/D2) broadcasts the co-located *ambient reaction*; the+// owner is reached here instead, off the authoritative interaction log, so the+// owner channel never depends on the WS host being up. The interaction RECORD+// always flows through POST /api/irl/interactions (C4) → irl_interactions; this+// stream only tails that table for the connected owner and pushes new rows.+//+// ── Why poll Postgres instead of pub/sub ─────────────────────────────────────+// Vercel can't hold a WebSocket and the Upstash REST client this repo uses has no+// long-lived SUBSCRIBE, so — exactly like api/feed-stream.js — we tail the source+// with a cheap, bounded query and fan the result to every connection on the warm+// instance. The interaction table is low-volume per owner (a dashboard, not a+// firehose), so a single indexed `created_at` range scan per tick is trivial.+//+// ── Quota / load discipline ──────────────────────────────────────────────────+// Vercel runs each SSE connection in its own invocation, but concurrent+// connections frequently share a warm instance. A naive per-connection loop would+// multiply DB reads by the open-tab count, so all connections on an instance share+// ONE poll loop: each tick issues a single query for the union of connected+// owners and dispatches each row to the matching owner's connection(s). The+// cadence is adaptive — fast right after activity, ramping toward POLL_MS_MAX while+// the inbox is idle (which it mostly is) — and a quota/error breaker degrades to+// heartbeats so a dead DB never turns into a poll storm.+//+// Vercel: registered with maxDuration 300 in vercel.json; we send a `retry`+// directive and close just before the hard timeout, and EventSource reconnects.++import { cors, method } from '../_lib/http.js';+import { getSessionUser } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';++const HEARTBEAT_MS = 15_000;+const POLL_MS_MIN = 2_000; // fast cadence right after activity+const POLL_MS_MAX = 15_000; // idle ceiling — the inbox is idle most of the time+const IDLE_TICKS_BEFORE_RAMP = 3;+const OVERLAP_MS = 2_000; // re-scan window so a row committed mid-tick isn't skipped+const ROW_LIMIT = 200; // per-tick cap; deduped by id across the overlap+const SEEN_MAX = 1_000; // bound the dedupe set on a long-lived instance+const BREAKER_COOLDOWN_MS = 60_000;+const MAX_DURATION_MS = 275_000; // close before Vercel's 300s hard timeout++// Only the fields the owner is allowed to see leave the server. NEVER the actor's+// identity (viewer_user_id/viewer_device) or any actor GPS — the lat/lng below are+// the OWNER's own pin location, which they already know. For a `pay`, the payload+// is reduced to the settlement signature + network so the inbox can deep-link the+// receipt; everything else in payload is dropped. Mirrors the GET ?mine=1 row+// shape so the client renders a live row identically to a polled one.+export function publicRow(r) {+ const payload = {};+ if (r.type === 'pay' && r.payload && typeof r.payload === 'object') {+ if (r.payload.signature) payload.signature = String(r.payload.signature);+ if (r.payload.network) payload.network = String(r.payload.network);+ }+ return {+ id: r.id,+ pin_id: r.pin_id,+ agent_id: r.agent_id,+ type: r.type,+ message: r.message,+ amount: r.amount,+ currency_mint: r.currency_mint,+ avatar_name: r.avatar_name,+ caption: r.caption,+ lat: r.lat,+ lng: r.lng,+ payload,+ created_at: r.created_at,+ };+}++function isQuotaError(err) {+ const m = (err && (err.message || String(err))) || '';+ return /too many connections|rate limit|quota|429|max requests/i.test(m);+}++// ── Per-instance shared poller ───────────────────────────────────────────────+// Every connection on this warm Lambda registers here; one loop fans fresh rows+// to all of them. A connection only ever receives rows created AFTER it joined+// (connectedAt) for an owner identity it actually owns (server-derived auth).+const connections = new Set();+let pollTimer = null;+let polling = false;+let lastPollAt = 0; // ms; watermark floor for the next query+let seen = new Set(); // recently-dispatched ids — global dedupe across overlap+let currentDelay = POLL_MS_MIN;+let idleTicks = 0;+let breakerUntil = 0;+let breakerLogged = false;++function resetSharedState() {+ if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; }+ polling = false;+ lastPollAt = 0;+ seen = new Set();+ currentDelay = POLL_MS_MIN;+ idleTicks = 0;+ breakerUntil = 0;+ breakerLogged = false;+}++function scheduleNextPoll() {+ if (pollTimer) clearTimeout(pollTimer);+ if (connections.size === 0) { pollTimer = null; return; }+ pollTimer = setTimeout(runPoll, currentDelay);+}++export function matches(conn, row) {+ return (conn.ownerId && row.owner_id === conn.ownerId)+ || (conn.ownerDev && row.owner_dev === conn.ownerDev);+}++async function runPoll() {+ pollTimer = null;+ if (connections.size === 0) return;+ if (polling) { scheduleNextPoll(); return; }++ const now = Date.now();+ if (now < breakerUntil) { scheduleNextPoll(); return; } // cooling down++ // Distinct owner identities currently connected — one query covers them all.+ const ownerIds = [...new Set([...connections].map((c) => c.ownerId).filter(Boolean))];+ const ownerDevs = [...new Set([...connections].map((c) => c.ownerDev).filter(Boolean))];+ if (!ownerIds.length && !ownerDevs.length) { scheduleNextPoll(); return; }++ polling = true;+ const pollStart = now;+ const watermark = new Date(lastPollAt - OVERLAP_MS).toISOString();+ try {+ const rows = await sql`+ SELECT ix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,+ ix.amount, ix.currency_mint, ix.payload, ix.created_at,+ p.user_id AS owner_id, p.device_token AS owner_dev,+ p.avatar_name, p.caption, ix.lat, ix.lng+ FROM irl_interactions ix+ JOIN irl_pins p ON p.id = ix.pin_id+ WHERE ix.created_at >= ${watermark}+ AND ( p.user_id = ANY(${ownerIds}::uuid[])+ OR p.device_token = ANY(${ownerDevs}::text[]) )+ ORDER BY ix.created_at ASC+ LIMIT ${ROW_LIMIT}+ `;+ breakerLogged = false; // a successful read clears the trip state++ let dispatched = 0;+ for (const row of rows || []) {+ if (!row.id || seen.has(row.id)) continue;+ seen.add(row.id);+ const createdMs = new Date(row.created_at).getTime();+ const safe = publicRow(row);+ for (const conn of connections) {+ // Only the owner, and only events that happened after they connected+ // (so a fresh tab is never spammed with the pre-connect backlog).+ if (createdMs <= conn.connectedAt) continue;+ if (!matches(conn, row)) continue;+ try { conn.send('interaction', safe); dispatched++; } catch { /* dead socket; its own cleanup unregisters it */ }+ }+ }++ if (dispatched > 0) {+ currentDelay = POLL_MS_MIN; // activity → speed back up+ idleTicks = 0;+ } else if (++idleTicks >= IDLE_TICKS_BEFORE_RAMP) {+ currentDelay = Math.min(POLL_MS_MAX, currentDelay * 2);+ }++ // Advance the watermark to this poll's start so the next tick covers exactly+ // [pollStart - overlap, nextPoll], no gaps; the overlap + `seen` cover the+ // boundary. Bound the dedupe set on a long-lived instance.+ lastPollAt = pollStart;+ if (seen.size > SEEN_MAX) {+ const keep = (rows || []).map((r) => r.id).filter(Boolean);+ seen = new Set(keep);+ }+ } catch (err) {+ if (isQuotaError(err)) {+ breakerUntil = Date.now() + BREAKER_COOLDOWN_MS;+ if (!breakerLogged) {+ console.error('[irl-stream] DB busy — pausing poll for', BREAKER_COOLDOWN_MS, 'ms');+ breakerLogged = true;+ }+ } else {+ console.error('[irl-stream] poll failed', err?.message || err);+ }+ } finally {+ polling = false;+ scheduleNextPoll();+ }+}++function addConnection(conn) {+ if (connections.size === 0) lastPollAt = Date.now(); // first connection arms the loop+ connections.add(conn);+ if (!pollTimer && !polling) {+ currentDelay = POLL_MS_MIN; // a new subscriber wants prompt updates+ idleTicks = 0;+ scheduleNextPoll();+ }+}++function removeConnection(conn) {+ connections.delete(conn);+ if (connections.size === 0) resetSharedState();+}++export default async function handleIrlInteractionsStream(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ // Owner identity is server-derived, never trusted from a body. Signed-in owners+ // match by session; anonymous placements match by their device token (the same+ // dual identity the GET ?mine=1 inbox + PATCH mark-read use).+ const session = await getSessionUser(req, res).catch(() => null);+ const ownerId = session?.id ?? null;+ const rawTok = req.query?.deviceToken ?? null;+ const ownerDev = (typeof rawTok === 'string' && rawTok.length) ? rawTok : null;+ if (!ownerId && !ownerDev) {+ res.statusCode = 401;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ error: 'sign in or pass deviceToken' }));+ return;+ }++ res.writeHead(200, {+ 'Content-Type': 'text/event-stream; charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ 'Connection': 'keep-alive',+ // Vercel's edge gateway buffers responses by default; without this it holds+ // SSE frames until the function returns, defeating the stream.+ 'X-Accel-Buffering': 'no',+ });++ let closed = false;+ const send = (event, data) => {+ if (closed || res.writableEnded) return;+ res.write(`event: ${event}\n`);+ res.write(`data: ${JSON.stringify(data)}\n\n`);+ };++ send('hello', { ts: Date.now() });++ // No DB configured (e.g. local dev without DATABASE_URL): keep the socket alive+ // with heartbeats so the client's fallback poll path still runs, emit nothing.+ if (!process.env.DATABASE_URL) {+ const hb = setInterval(() => {+ if (closed || res.writableEnded) { clearInterval(hb); return; }+ res.write(':hb\n\n');+ }, HEARTBEAT_MS);+ const stop = () => { closed = true; clearInterval(hb); try { res.end(); } catch {} };+ req.on('close', stop); res.on('close', stop); req.on('error', stop);+ return;+ }++ const conn = { ownerId, ownerDev, connectedAt: Date.now(), send };+ addConnection(conn);++ const startMs = Date.now();+ const heartbeat = setInterval(() => {+ if (closed || res.writableEnded) return;+ if (Date.now() - startMs > MAX_DURATION_MS) {+ res.write('retry: 1000\n\n'); // EventSource reconnects after ~1s+ cleanup();+ return;+ }+ res.write(':hb\n\n');+ }, HEARTBEAT_MS);++ function cleanup() {+ if (closed) return;+ closed = true;+ removeConnection(conn);+ clearInterval(heartbeat);+ if (!res.writableEnded) { try { res.end(); } catch { /* torn down */ } }+ }++ req.on('close', cleanup);+ req.on('error', cleanup);+ res.on('close', cleanup);+ res.on('error', cleanup);+}diff --git a/api/irl/interactions.js b/api/irl/interactions.jsindex e64fb06aa..c4d63d2d4 100644--- a/api/irl/interactions.js+++ b/api/irl/interactions.js@@ -149,6 +149,7 @@ export default wrap(async (req, res) => {SELECT id, agent_id, lat, lng, user_id, device_tokenFROM irl_pinsWHERE id = ${pinId}+ AND hidden_at IS NULLAND (expires_at IS NULL OR expires_at > NOW())LIMIT 1`;diff --git a/api/irl/pins.js b/api/irl/pins.jsindex 19e06a31a..cc1f05a7e 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -19,6 +19,9 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { WORD_BLACKLIST } from '../../src/profanity.js';import { guardianConfig, assess, decide } from '../_lib/granite-guardian.js';import { encodeGeohash } from '../_lib/geohash.js';+import { publishIrlPin } from '../_lib/irl-publish.js';+import { validateAppearance } from '../_lib/accessories.js';+import { emitPinUpdated } from '../_lib/irl-realtime.js';// ── Moderation, safety & density caps (D4) ──────────────────────────────────// Everything below makes the public, shared IRL world safe to launch: content@@ -41,7 +44,7 @@ const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';// Always-on hard gate: lower-case substring match against the shared slur/severe// list. No external dependency, fails closed and fast — the floor under the// smarter Guardian tier. Reused verbatim from the pump.fun feed filter.-function hardBlocked(text) {+export function hardBlocked(text) {const t = String(text || '').toLowerCase();return WORD_BLACKLIST.some((w) => t.includes(w));}@@ -50,7 +53,7 @@ function hardBlocked(text) {// `$TICKER` cashtag that isn't $THREE, or a pump.fun-style mint address (…pump)// that isn't the $THREE contract. Generic by construction so no competitor is// ever written into source; $THREE (cashtag or contract) is explicitly allowed.-function namesOffBrandCoin(text) {+export function namesOffBrandCoin(text) {const t = String(text || '');const cashtags = t.match(/\$[A-Za-z][A-Za-z0-9]{1,9}\b/g) || [];if (cashtags.some((c) => c.slice(1).toUpperCase() !== 'THREE')) return true;@@ -112,10 +115,13 @@ const X402_ALLOWED_HOSTS = (.map((h) => h.trim().toLowerCase()).filter(Boolean);-function safePaymentEndpoint(raw) {- const base = safeRemoteUrl(raw, { allowRelative: false });+export function safePaymentEndpoint(raw) {+ // allowRelative so a same-origin path (unambiguously first-party three.ws)+ // passes; safeRemoteUrl still enforces https + no-private-host on absolute URLs.+ const base = safeRemoteUrl(raw, { allowRelative: true });if (!base.ok) return { ok: false };if (base.value == null) return { ok: true, value: null };+ if (base.value.startsWith('/')) return { ok: true, value: base.value };let host;try { host = new URL(base.value).hostname.toLowerCase(); } catch { return { ok: false }; }const allowed = X402_ALLOWED_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));@@ -201,6 +207,20 @@ async function ensureTable() {await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS geocell7 TEXT`;await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS hidden_at TIMESTAMPTZ`;await sql`CREATE INDEX IF NOT EXISTS irl_pins_geocell7 ON irl_pins (geocell7) WHERE hidden_at IS NULL`;+ // Remote outfit change (C6) — a placed agent owns its look independent of the+ // source avatar so an owner can re-skin it for EVERY nearby viewer.+ // avatar_manifest : the editable appearance — { colors, hidden, accessories }+ // (the same shape the avatar studio produces).+ // avatar_base_url : the un-dressed GLB the manifest bakes ONTO, captured once+ // on the first outfit edit. Re-baking always starts from this+ // clean base so garment hides / accessories never stack across+ // edits (avatar_url stays the derived, baked GLB served today).+ // avatar_version : bumped on every outfit change — the cheap signal the nearby+ // feed/viewer diffs to swap a re-skinned pin's GLB, and a+ // cache-bust companion to the hash-keyed baked URL.+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS avatar_manifest JSONB`;+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS avatar_base_url TEXT`;+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS avatar_version INTEGER NOT NULL DEFAULT 0`;_tableReady = true;}@@ -286,9 +306,116 @@ async function handleCalibrate(res, { id, session, body }) {WHERE id = ${id}RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m, gps_accuracy_m`;+ // Realtime (D1): a calibrate is a partial pin:update of position + heading, so+ // every nearby viewer sees the corrected spot move live instead of on re-fetch.+ void publishIrlPin('pin:update', realtimeCell(row.lat, row.lng), pinWire(row));return json(res, 200, { pin: row, calibrated: true });}+// ── Remote outfit change (C6) ───────────────────────────────────────────────+// Re-skin a placed agent for EVERY nearby viewer. The owner sends the appearance+// manifest ({ colors, hidden, accessories }); we validate it against the same+// slot/preset allow-list the studio uses, bake a new GLB onto the pin's clean+// BASE avatar (never the prior bake — so layers/accessories can't stack), store+// it on the first-party CDN, bump avatar_version, and persist. Every nearby+// viewer's loadNearbyPins poll then diffs the version and swaps the GLB; D1+// (emitPinUpdated) pushes it instantly once realtime lands. A null/empty+// manifest reverts the pin to its bare base avatar.+async function handleOutfitChange(res, { id, session, body }) {+ const manifest = body.avatar_manifest ?? body.avatarManifest ?? null;+ if (manifest !== null && (typeof manifest !== 'object' || Array.isArray(manifest))) {+ return json(res, 400, { error: 'avatar_manifest must be an object or null' });+ }+ // Validate shape + preset/slot allow-list BEFORE baking, so an invented slot+ // or preset is a clean 400 and never burns a bake.+ if (manifest) {+ const err = validateAppearance(manifest);+ if (err) return json(res, 400, { error: err });+ }++ // Owner-gated: only the authenticated owner re-skins their agent. (Appearance+ // is never editable from an anonymous device token — same stance as the+ // avatar/location edits below.)+ const [pin] = await sql`+ SELECT id, user_id, avatar_url, avatar_base_url, avatar_version+ FROM irl_pins+ WHERE id = ${id}+ `;+ if (!pin) return json(res, 404, { error: 'not found' });+ if (!pin.user_id || pin.user_id !== session.id) {+ return json(res, 403, { error: "only the owner can change this agent's outfit" });+ }++ // The base GLB the manifest dresses. Captured once (the agent as it looked+ // before any outfit edit) so re-bakes always start from a clean model.+ const baseUrl = pin.avatar_base_url || pin.avatar_url;+ if (!baseUrl) return json(res, 422, { error: 'this agent has no avatar to dress' });++ let newAvatarUrl = baseUrl;+ try {+ // Lazy import: irl-bake → bake.js pulls in sharp (native libvips). Loading+ // it only on this path keeps every other pins route alive even where the+ // native module can't load.+ const { bakePinOutfit, isBakeable } = await import('../_lib/irl-bake.js');+ if (manifest && isBakeable(manifest)) {+ const baked = await bakePinOutfit({ pinId: id, baseUrl, manifest });+ newAvatarUrl = baked.url;+ }+ // else: cleared / empty manifest → serve the bare base GLB again.+ } catch (err) {+ console.error('[irl/pins] outfit bake failed', { pinId: id, message: err?.message });+ return json(res, 502, { error: 'could not bake the new outfit', detail: err?.message });+ }++ const [row] = await sql`+ UPDATE irl_pins SET+ avatar_manifest = ${manifest ? JSON.stringify(manifest) : null}::jsonb,+ avatar_base_url = COALESCE(avatar_base_url, ${baseUrl}),+ avatar_url = ${newAvatarUrl},+ avatar_version = avatar_version + 1+ WHERE id = ${id} AND user_id = ${session.id}+ RETURNING id, lat, lng, avatar_url, avatar_manifest, avatar_version+ `;+ if (!row) return json(res, 404, { error: 'not found' });++ // Realtime fan-out (D1) — co-located viewers swap the GLB within seconds+ // without waiting for their next poll. No-op until D1 lands; the poll path+ // (avatar_version diff) is the durable contract either way.+ emitPinUpdated(row);++ return json(res, 200, { pin: row });+}++// ── Realtime publish helpers (D1) ───────────────────────────────────────────+// The irl_world room is keyed by a precision-6 geocell (~1.2 km), the coarse cell+// every nearby viewer joins. Matches src/irl-net.js and multiplayer/src/rooms/+// IrlRoom.js so a publish always lands in the right live room. (The committed+// geocell7/GEOCELL_PRECISION column is the FINER precision-7 cell used for the D4+// density cap — a different lattice; both derive from the same encoder.)+const REALTIME_PRECISION = 6;+function realtimeCell(lat, lng) {+ return encodeGeohash(Number(lat), Number(lng), REALTIME_PRECISION);+}++// Build the camelCase wire object the room consumes from a DB row, including ONLY+// the columns the row actually has. An add returns the full row (RETURNING *) so+// every field rides; an update / calibrate returns a narrow column set, so only+// those become a partial pin:update — the room never zeroes a field the caller+// didn't touch.+function pinWire(row) {+ const w = { id: row.id };+ if ('lat' in row) w.lat = Number(row.lat);+ if ('lng' in row) w.lng = Number(row.lng);+ if ('heading' in row) w.heading = Number(row.heading) || 0;+ if ('avatar_url' in row) w.avatarUrl = row.avatar_url ?? '';+ if ('avatar_name' in row) w.avatarName = row.avatar_name ?? '';+ if ('caption' in row) w.caption = row.caption ?? '';+ if ('x402_endpoint' in row) w.x402Endpoint = row.x402_endpoint ?? '';+ if ('agent_id' in row) w.agentId = row.agent_id ?? '';+ if ('placed_at' in row) w.placedAt = row.placed_at ? Date.parse(row.placed_at) || 0 : 0;+ return w;+}+export default wrap(async (req, res) => {cors(req, res, { methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'] });if (req.method === 'OPTIONS') return res.end();@@ -324,7 +451,8 @@ export default wrap(async (req, res) => {SELECT id, lat, lng, heading, avatar_url, avatar_name, caption, agent_id,placed_at, expires_at, view_count,anchor_height_m, anchor_yaw_deg, anchor_quat,- gps_accuracy_m, altitude_m, anchor_source+ gps_accuracy_m, altitude_m, anchor_source,+ avatar_manifest, avatar_base_url, avatar_versionFROM irl_pinsWHERE user_id = ${session.id}AND hidden_at IS NULL@@ -334,6 +462,38 @@ export default wrap(async (req, res) => {return json(res, 200, { pins: rows });}+ // ── GET — pins in a bounding box (IRL realtime room hydration, D1) ─────────+ // The Colyseus irl_world room loads its 3×3 geocell window on create through+ // this box query (server-to-server). Same public projection as the nearby feed+ // — never owner ids — but selected by an explicit lat/lng box instead of a+ // radius, because a 3×3 precision-6 window (~3.6 km) exceeds the nearby radius+ // cap. Reuses the existing lat/lng index; capped + size-guarded against scrapes.+ if (req.method === 'GET' && req.query.bbox != null) {+ const parts = String(req.query.bbox).split(',').map((s) => parseFloat(s));+ if (parts.length !== 4 || parts.some((n) => !isFinite(n))) {+ return json(res, 400, { error: 'bbox must be minLat,minLng,maxLat,maxLng' });+ }+ let [minLat, minLng, maxLat, maxLng] = parts;+ if (minLat > maxLat) [minLat, maxLat] = [maxLat, minLat];+ if (minLng > maxLng) [minLng, maxLng] = [maxLng, minLng];+ // A legit 3×3 window is < ~0.05°; 1° (~111 km) is a generous abuse ceiling.+ if ((maxLat - minLat) > 1 || (maxLng - minLng) > 1) {+ return json(res, 400, { error: 'bbox too large' });+ }+ const rows = await sql`+ SELECT id, agent_id, lat, lng, heading,+ avatar_url, avatar_name, caption, x402_endpoint, placed_at, avatar_version+ FROM irl_pins+ WHERE lat BETWEEN ${minLat} AND ${maxLat}+ AND lng BETWEEN ${minLng} AND ${maxLng}+ AND hidden_at IS NULL+ AND (expires_at IS NULL OR expires_at > NOW())+ ORDER BY placed_at DESC+ LIMIT 500+ `;+ return json(res, 200, { pins: rows });+ }+// ── GET — nearby pins ─────────────────────────────────────────────────────if (req.method === 'GET') {const lat = parseFloat(req.query.lat);@@ -358,7 +518,7 @@ export default wrap(async (req, res) => {SELECT id, user_id, device_token, agent_id, lat, lng, heading,avatar_url, avatar_name, caption, x402_endpoint, placed_at, view_count,anchor_height_m, anchor_yaw_deg, anchor_quat,- gps_accuracy_m, altitude_m, anchor_source+ gps_accuracy_m, altitude_m, anchor_source, avatar_versionFROM irl_pinsWHERE lat BETWEEN ${lat - latDelta} AND ${lat + latDelta}AND lng BETWEEN ${lng - lngDelta} AND ${lng + lngDelta}@@ -390,6 +550,10 @@ export default wrap(async (req, res) => {gps_accuracy_m: r.gps_accuracy_m,altitude_m: r.altitude_m,anchor_source: r.anchor_source,+ // C6 — cheap re-skin signal: the viewer diffs this against its loaded+ // pin and swaps the GLB when it bumps. (The editable manifest/base URL+ // stay owner-private — viewers only ever need the rendered avatar_url.)+ avatar_version: Number(r.avatar_version) || 0,is_mine: (!!myId && r.user_id === myId) || (!!myTok && r.device_token === myTok),distance_m: Math.round(haversineDist(lat, lng, r.lat, r.lng)),}))@@ -569,6 +733,11 @@ export default wrap(async (req, res) => {RETURNING *`;+ // Realtime (D1): fan this placement to every viewer in the geocell so it+ // appears on their screen within ~1 s, no reload. Fire-and-forget — the pin+ // is already persisted and the poll fallback reconciles if the push drops.+ void publishIrlPin('pin:add', realtimeCell(lat, lng), pinWire(pin));+return json(res, 201, { pin: { ...pin, permanent: expiresAt === null } });}@@ -596,6 +765,13 @@ export default wrap(async (req, res) => {// Field edits (caption / avatar / location / heading / x402) require auth.if (!session) return json(res, 401, { error: 'not authenticated' });+ // ── Outfit change (C6) — re-skin a placed agent for all nearby viewers ──+ // A manifest PATCH bakes a new GLB + bumps avatar_version; routed before+ // the simple field-edit SET below because it has its own bake/persist path.+ if ('avatar_manifest' in body || 'avatarManifest' in body) {+ return handleOutfitChange(res, { id, session, body });+ }+// Build update SET clause only for fields the caller providedconst updates = {};if ('caption' in body) updates.caption = body.caption ?? null;@@ -653,6 +829,11 @@ export default wrap(async (req, res) => {RETURNING id, caption, avatar_url, avatar_name, lat, lng, heading, x402_endpoint`;if (!row) return json(res, 404, { error: 'not found' });++ // Realtime (D1): push the edit live to nearby viewers. pinWire carries only+ // the RETURNING columns, so it's a partial pin:update — untouched fields stay.+ void publishIrlPin('pin:update', realtimeCell(row.lat, row.lng), pinWire(row));+return json(res, 200, { pin: row });}@@ -686,12 +867,15 @@ export default wrap(async (req, res) => {(${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))- RETURNING id+ RETURNING id, lat, lng`;if (!result.length) {return json(res, 404, { error: 'pin not found or not yours' });}+ // Realtime (D1): tell every nearby viewer to remove the pin live.+ const gone = result[0];+ void publishIrlPin('pin:remove', realtimeCell(gone.lat, gone.lng), { id: gone.id });return json(res, 200, { ok: true });}diff --git a/api/irl/report.js b/api/irl/report.jsnew file mode 100644index 000000000..87bcf2ff5--- /dev/null+++ b/api/irl/report.js@@ -0,0 +1,139 @@+/**+ * IRL pin reports — community moderation for placed agents (D4).+ *+ * POST /api/irl/report { pinId, reason, deviceToken? }+ * Files a report against a public pin. Reports are de-duped per distinct+ * reporter (a session user, else the device token, else the caller IP) so one+ * actor can't inflate the count by re-submitting. When a pin crosses+ * REPORT_HIDE_THRESHOLD *distinct* reporters it is hidden (hidden_at = NOW()):+ * it vanishes from every nearby/mine query and stops accepting interactions.+ * Hidden, never deleted — the row survives for owner appeal + later review.+ *+ * Owner-protected: a single reporter can never hide a pin, and the owner's own+ * reports against their own pin are ignored. This is a queue-at-threshold gate,+ * not an instant delete — report-bombing is bounded by the distinct-reporter+ * dedup, real abuse is taken down once enough independent people flag it.+ *+ * References no coin and no third-party token; $THREE is the only coin three.ws+ * references. Realtime push of the removal to already-loaded viewers rides on D1;+ * here the next nearby re-fetch (which filters hidden_at) drops it for everyone.+ */++import { cors, json, wrap, rateLimited } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++// Distinct reporters required before a pin is queued out of public view.+const REPORT_HIDE_THRESHOLD = 3;+const MAX_REASON_LEN = 240;+// Canonical reasons the UI offers; anything else collapses to 'other'. Kept as a+// closed set so the (future) review console can triage by category.+const REASONS = new Set(['spam', 'harassment', 'impersonation', 'scam', 'sexual', 'other']);++let _tableReady = false;+async function ensureTable() {+ if (_tableReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS irl_pin_reports (+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY,+ pin_id UUID NOT NULL,+ reporter_token TEXT NOT NULL,+ reason TEXT,+ created_at TIMESTAMPTZ DEFAULT NOW()+ )+ `;+ // One report per (pin, reporter) — the dedup that makes report-bombing inert.+ await sql`CREATE UNIQUE INDEX IF NOT EXISTS irl_pin_reports_uniq ON irl_pin_reports (pin_id, reporter_token)`;+ await sql`CREATE INDEX IF NOT EXISTS irl_pin_reports_pin ON irl_pin_reports (pin_id)`;+ _tableReady = true;+}++export default wrap(async (req, res) => {+ cors(req, res, { methods: ['POST', 'OPTIONS'] });+ if (req.method === 'OPTIONS') return res.end();++ if (req.method !== 'POST') return json(res, 405, { error: 'method not allowed' });++ const ip = clientIp(req);+ const rl = await limits.irlReportIp(ip);+ if (!rl.success) return rateLimited(res, rl);++ await ensureTable();++ const body = req.body ?? {};+ const pinId = body.pinId;+ if (!pinId) return json(res, 400, { error: 'pinId required' });++ const reason = REASONS.has(body.reason) ? body.reason : 'other';+ const detail = typeof body.detail === 'string'+ ? body.detail.trim().slice(0, MAX_REASON_LEN) || null+ : null;+ const reasonStored = detail ? `${reason}: ${detail}` : reason;++ const session = await getSessionUser(req).catch(() => null);+ const deviceToken = (typeof body.deviceToken === 'string' && body.deviceToken.length)+ ? body.deviceToken : null;++ // The pin must exist and still be live. A 404 here is honest — you can't report+ // a pin that isn't there (already expired, deleted, or never existed).+ const [pin] = await sql`+ SELECT id, user_id, device_token, hidden_at+ FROM irl_pins+ WHERE id = ${pinId}+ AND (expires_at IS NULL OR expires_at > NOW())+ LIMIT 1+ `;+ if (!pin) return json(res, 404, { error: 'pin not found' });++ // Distinct-reporter identity, most-accountable first: the signed-in user, else+ // the placing device, else the caller IP. IP fallback means many anonymous+ // reporters behind one NAT count as one — the safe direction (it makes hiding+ // HARDER to abuse, never easier).+ const reporterToken = session?.id+ ? `user:${session.id}`+ : deviceToken || `ip:${ip}`;++ // Owner reporting their own pin is a no-op — not an independent flag. (A signed-in+ // owner or the placing device both count as the owner.)+ const isOwner =+ (!!session?.id && !!pin.user_id && session.id === pin.user_id) ||+ (!!deviceToken && !!pin.device_token && deviceToken === pin.device_token);+ if (isOwner) {+ return json(res, 200, { ok: true, self: true });+ }++ // Already hidden — accept the report idempotently (still record it for the+ // review trail) but report the terminal state to the client.+ // Insert is dedup'd by the unique (pin_id, reporter_token) index.+ await sql`+ INSERT INTO irl_pin_reports (pin_id, reporter_token, reason)+ VALUES (${pinId}, ${reporterToken}, ${reasonStored})+ ON CONFLICT (pin_id, reporter_token) DO NOTHING+ `;++ if (pin.hidden_at) {+ return json(res, 200, { ok: true, hidden: true });+ }++ // Count DISTINCT reporters and hide once the threshold is crossed. The hide is+ // guarded on hidden_at IS NULL so concurrent reports can't double-fire it.+ const [{ n }] = await sql`+ SELECT count(DISTINCT reporter_token)::int AS n+ FROM irl_pin_reports+ WHERE pin_id = ${pinId}+ `;++ let hidden = false;+ if (n >= REPORT_HIDE_THRESHOLD) {+ const rows = await sql`+ UPDATE irl_pins+ SET hidden_at = NOW()+ WHERE id = ${pinId} AND hidden_at IS NULL+ RETURNING id+ `;+ hidden = rows.length > 0;+ }++ return json(res, 200, { ok: true, reports: n, hidden });+});diff --git a/data/changelog.json b/data/changelog.jsonindex c90aee14c..861d14dc0 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,90 @@{"$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": "Nearby agents on IRL now update live — no reload",+ "summary": "Open three.ws/irl and the agents other people have placed around you now update in real time. When anyone nearby drops a new agent, moves one, changes its outfit, or takes one down, you see it appear, shift, or vanish on your screen within about a second — no refresh, no waiting for the next scan. It works both ways: pin an agent and everyone standing near you sees it pop in too, and walk into a new area and the live view follows you to the agents there. A small status pill next to the nearby count shows whether you're getting live updates; if the realtime connection can't be reached — some networks block it — IRL automatically falls back to refreshing every few seconds and the pill reads 'Polling', still fully working, just a touch slower.",+ "tags": ["feature", "improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL stays smooth at crowded locations",+ "summary": "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.",+ "tags": ["improvement", "infra"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL walks you through camera, motion & location — and never dead-ends on a blocked permission",+ "summary": "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.",+ "tags": ["feature", "improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL now fails gracefully — clear states instead of blank screens",+ "summary": "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.",+ "tags": ["improvement", "fix"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "Change a placed agent's outfit from your dashboard — everyone nearby sees it",+ "summary": "Your IRL Agents dashboard now has a real outfit editor. Open Change outfit on any agent you've placed and a live 3D preview loads with wardrobe controls for the exact layers that avatar has — recolour its hair, skin, and clothing, strip back to the base body and dress it up again, or stack on hats, glasses, and earrings. Because your agents are public, the new look is baked into the agent itself and pushed to its real-world pin, so every person who walks up to that spot sees the updated outfit in their camera — not just you. Save when you're happy; the avatar is re-rendered for real before it confirms, the previous look stays untouched if anything fails, and nearby viewers refresh to the new outfit within seconds. Run a seasonal look, brand your agents as staff for an event, or just keep them fresh — all without walking back to where you pinned them.",+ "tags": ["feature"],+ "link": "/dashboard/irl-placements"+ },+ {+ "date": "2026-06-17",+ "title": "Move your IRL agents on a real map — drag the pin from anywhere",+ "summary": "Your IRL Agents dashboard now has a live map. Open Move on map on any placed agent and you get an OpenStreetMap view with a draggable pin for each agent you've placed: drag the highlighted one to a new spot, or tap another to switch to it. As you drag, the new location is named for you (the nearest town or city) and a Save bar appears so nothing changes until you confirm — and if a save ever fails, the pin snaps back to where it was. A compass dial lets you re-aim which way the agent faces, in degrees or by dragging the needle, and a Remove from map button takes a pin down. You can relocate an agent across the city — or across the world — without walking back to it. The map loads only when you open it, works on a phone, and if it can't load it falls back to a simple latitude/longitude form so you can still move the pin.",+ "tags": ["feature"],+ "link": "/dashboard/irl-placements"+ },+ {+ "date": "2026-06-17",+ "title": "Your IRL agent dashboard now lights up the instant someone interacts",+ "summary": "When a stranger taps, messages, or pays one of your agents placed out in the real world, your dashboard now reflects it within about a second — no refresh. The agent's card flashes, the unread count ticks up live, and a payment or a new message pops a notification so you feel the moment it happens, even from the other side of the planet. A small Live indicator shows when the realtime connection is up; if it ever drops, the inbox keeps updating on a short delay instead, so you never miss an encounter. Only your agent's name and the kind of interaction are ever shared with you — never the visitor's location or wallet.",+ "tags": ["feature", "improvement"],+ "link": "/dashboard/irl-placements"+ },+ {+ "date": "2026-06-17",+ "title": "Jump straight from an agent's profile into IRL or XR",+ "summary": "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.",+ "tags": ["feature"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "An inbox for your IRL agents — see who tapped, messaged, or paid, and reply",+ "summary": "Your IRL Agents dashboard now has an Inbox: a live, chronological feed of everyone who met your placed agents in real life. Each entry shows what happened — a view, a tap, a message, or a payment — where it happened, and how long ago. Payments show the exact amount and link straight to the block-explorer receipt, and you can reply to anyone who left your agent a message; if they were signed in, your reply lands in their notifications. Unread counts appear on the Inbox button and on each agent's card, the feed refreshes itself every few seconds, and opening the inbox marks everything read. High-signal events (a payment or a message) also ping you in the notification bell, so you find out the moment a stranger across the city engages your agent.",+ "tags": ["feature"],+ "link": "/dashboard/irl-placements"+ },+ {+ "date": "2026-06-17",+ "title": "See your IRL agent's on-chain reputation right from the dashboard",+ "summary": "On your IRL Agents dashboard, the Reputation chip on each placed agent now opens an on-chain reputation panel — the exact score and trust tier (Elite, Trusted, Emerging, New) a passer-by sees when they tap your agent in real life. It breaks down how many attestations are verified, credentialed, and disputed, shows the average star rating and how many distinct people vouched, and links straight to the agent's passport to manage it. Agents without a Solana identity, or without any attestations yet, get a clear next step instead of an error.",+ "tags": ["feature"],+ "link": "/dashboard/irl-placements"+ },+ {+ "date": "2026-06-17",+ "title": "Pay an IRL agent for its services — and open its full profile — right from the card",+ "summary": "When you tap an agent on three.ws/irl, its card now does real things. View profile opens that agent's full page so you can see who you just met. If the agent offers paid services, each one shows its price and a Use button: tap it, approve the payment in your wallet, and you pay in USDC on the spot — the standard x402 flow, capped at the price shown so a misconfigured service can never overcharge you. The response you paid for appears right inside the card instead of vanishing into a toast. Every state is handled: no wallet, a cancelled signature, or a service error each show a clear message and leave the button ready to try again, and each service button works on its own so paying for one never freezes the others. Completed encounters quietly notify the agent's owner, receipt and all.",+ "tags": ["feature"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL placements now have guardrails: report a pin, content checks, and area limits",+ "summary": "Now that anyone at a location can see anyone's placed agent on three.ws/irl, we've added the safety layer that makes a public shared space work. Tap any agent that isn't yours and you'll find a Report option — pick a reason (spam, hate, impersonation, scam, sexual content, or something else) and once enough different people flag the same pin it's automatically hidden from everyone, with the reporter seeing it disappear right away. One person can't hide someone else's agent, and repeat reports from the same device don't stack, so the system can't be gamed to silence a legitimate pin. At placement time, captions and agent names are screened for slurs and hateful content and rejected with a clear, fixable message, and a pin can only ever reference $THREE — no other coin can be advertised. Pay buttons are locked to three.ws payment endpoints so a pin can't point you at an off-platform drain. To stop one person from carpet-bombing a plaza, each small area caps how many agents it holds and each person has an active-pin limit — and if you hit a limit you get a plain-language nudge (shorten the text, move, wait a moment, or remove an old pin) instead of a silent failure. Abandoned anonymous pins are now cleaned up automatically; your signed-in permanent pins are never touched.",+ "tags": ["security", "feature"],+ "link": "/irl"+ },{"date": "2026-06-17","title": "Tapping an IRL agent is now reliable — hit the body, not just the tiny label",diff --git a/multiplayer/src/geohash.js b/multiplayer/src/geohash.jsindex 41055204d..dfb368a90 100644--- a/multiplayer/src/geohash.js+++ b/multiplayer/src/geohash.js@@ -86,3 +86,64 @@ export function decodeGeohash(geohash) {lngErr: (b.lngMax - b.lngMin) / 2,};}++// ── Neighbour expansion ──────────────────────────────────────────────────────+// Standard base32 borrow tables for stepping a geohash one cell N/S/E/W. The two+// rows in each entry are for even- vs odd-length geohashes (the bit interleave+// alternates lat/lng parity by cell length). This is the canonical geohash-js+// adjacency algorithm — it handles wrap-around at the ±180° antimeridian and the+// poles by recursively carrying into the parent cell.+const ADJ_NEIGHBORS = {+ n: ['p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjyznpkmstqrwx'],+ s: ['14365h7k9dcfesgujnmqp0r2twvyx8zb', '238967debc01fg45kmstqrwxuvhjyznp'],+ e: ['bc01fg45238967deuvhjyznpkmstqrwx', 'p0r21436x8zb9dcf5h7kjnmqesgutwvy'],+ w: ['238967debc01fg45kmstqrwxuvhjyznp', '14365h7k9dcfesgujnmqp0r2twvyx8zb'],+};+const ADJ_BORDERS = {+ n: ['prxz', 'bcfguvyz'],+ s: ['028b', '0145hjnp'],+ e: ['bcfguvyz', 'prxz'],+ w: ['0145hjnp', '028b'],+};++/**+ * The geohash one cell away from `geohash` in compass direction `dir`+ * ('n' | 's' | 'e' | 'w'). Returns '' for empty/invalid input.+ */+export function geohashAdjacent(geohash, dir) {+ const gh = String(geohash || '').toLowerCase();+ const d = String(dir || '').toLowerCase();+ if (!gh || !ADJ_NEIGHBORS[d]) return '';+ const lastCh = gh.slice(-1);+ let parent = gh.slice(0, -1);+ const type = gh.length % 2; // 0 → even-length, 1 → odd-length+ // On a border cell the step carries into the parent first (wrap-around).+ if (ADJ_BORDERS[d][type].indexOf(lastCh) !== -1 && parent !== '') {+ parent = geohashAdjacent(parent, d);+ }+ const idx = ADJ_NEIGHBORS[d][type].indexOf(lastCh);+ if (idx < 0) return ''; // stray char that isn't in the base32 alphabet+ return parent + BASE32[idx];+}++/**+ * The up-to-8 geohash cells surrounding `geohash` (4 edges + 4 corners), so a+ * viewer near a cell edge still sees pins that straddle the boundary inside the+ * nearby radius. De-duplicated; never includes the centre cell itself.+ * @returns {string[]}+ */+export function geohashNeighbors(geohash) {+ const gh = String(geohash || '').toLowerCase();+ if (!gh) return [];+ const n = geohashAdjacent(gh, 'n');+ const s = geohashAdjacent(gh, 's');+ const e = geohashAdjacent(gh, 'e');+ const w = geohashAdjacent(gh, 'w');+ const cells = [+ n, s, e, w,+ geohashAdjacent(n, 'e'), geohashAdjacent(n, 'w'),+ geohashAdjacent(s, 'e'), geohashAdjacent(s, 'w'),+ ];+ // De-dupe and drop empties / the centre (degenerate near the poles).+ return [...new Set(cells)].filter((c) => c && c !== gh);+}diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex d7e5948e0..5222350c8 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -20,11 +20,14 @@ import { WebSocketTransport } from '@colyseus/ws-transport';import { monitor } from '@colyseus/monitor';import { WalkRoom } from './rooms/WalkRoom.js';+import { IrlRoom } from './rooms/IrlRoom.js';import { blockStore } from './block-store.js';import { worldPersistence } from './persistence.js';import { flushAllPlayers } from './playerStore.js';import { socialHub } from './social-hub.js';import { verifyNotifySignature } from './presence-token.js';+import { irlRegistry } from './irl-registry.js';+import { verifyIrlPublish } from './irl-publish-auth.js';const PORT = Number(process.env.PORT || 2567);const HOST = process.env.HOST || '0.0.0.0';@@ -91,6 +94,27 @@ app.post('/internal/notify', express.json({ limit: '16kb' }), (req, res) => {res.json({ delivered });});+// IRL realtime pin publish webhook (D1). Vercel can't hold a WebSocket, so when+// the three.ws API mutates a pin (/api/irl/pins POST/PATCH/DELETE) it fires this+// signed webhook; we fan the change into every live geocell room whose 3×3 window+// covers the pin's cell, where it becomes a Colyseus schema delta the viewers+// there receive within the patch interval. HMAC-signed with the shared secret and+// bound to the exact body + a fresh timestamp, so only the API can inject pin+// changes and a captured request can't be replayed or tampered.+app.post('/internal/irl-publish', express.json({ limit: '32kb' }), (req, res) => {+ const { geocell, type, pin } = req.body || {};+ const sig = req.headers['x-mp-signature'];+ const ts = req.headers['x-mp-timestamp'];+ if (typeof geocell !== 'string' || typeof type !== 'string' || !geocell || !type) {+ return res.status(400).json({ error: 'bad_request' });+ }+ if (!verifyIrlPublish(geocell, type, pin || {}, ts, sig)) {+ return res.status(401).json({ error: 'bad_signature' });+ }+ const delivered = irlRegistry.dispatch(geocell, type, pin || {});+ res.json({ delivered });+});+// Admin monitor UI — exposes live room/client state, so it must NOT be open to// the world in production. Mount it only when protected by basic-auth creds// (MONITOR_USER + MONITOR_PASS), or, outside production, openly for local dev.@@ -187,12 +211,18 @@ const gameServer = new Server({ transport, ...(driver && { driver }), ...(presen// to the shared mainland world; a missing tier is the open General world (see// WalkRoom.onCreate / onAuth / schemas.js).gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);+// The IRL realtime world (D1): one room instance per precision-6 geocell, so+// every viewer standing in the same ~1 km cell shares a live mirror of the pins+// there. filterBy(['geocell']) makes joinOrCreate match only rooms for the same+// cell; the room itself mirrors a 3×3 window (centre + neighbours) so edge pins+// inside the nearby radius are never missed (see rooms/IrlRoom.js).+gameServer.define('irl_world', IrlRoom).filterBy(['geocell']);gameServer.listen(PORT, HOST).then(() => {console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);- console.log(`[multiplayer] rooms: walk_world`);+ console.log(`[multiplayer] rooms: walk_world, irl_world`);console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);}).catch((err) => {diff --git a/multiplayer/src/irl-publish-auth.js b/multiplayer/src/irl-publish-auth.jsnew file mode 100644index 000000000..3e8913141--- /dev/null+++ b/multiplayer/src/irl-publish-auth.js@@ -0,0 +1,54 @@+// Verifier for the IRL pin publish webhook (POST /internal/irl-publish).+//+// Vercel can't hold a WebSocket, so when the three.ws API mutates a pin+// (POST/PATCH/DELETE /api/irl/pins) it fires this signed HTTP webhook at the+// standalone Colyseus host, which fans the change into the matching geocell room+// as a schema patch. The signature binds the request to the exact delivered body+// and a fresh timestamp, so a captured tuple can't be replayed with a different+// pin or after the freshness window.+//+// Keep byte-for-byte in sync with the API signer (api/_lib/irl-realtime.js):+// signed = `irl:<geocell>:<type>:<ts>:<base64url(sha256(JSON(pin)))>`+// sig = base64url(HMAC_SHA256(secret, signed))+// secret = MULTIPLAYER_SHARED_SECRET (→ HOLDER_PASS_SECRET → public dev secret),+// the same fallback chain presence-token.js / persistence.js use.++import crypto from 'node:crypto';++function secret() {+ return (+ process.env.MULTIPLAYER_SHARED_SECRET ||+ process.env.HOLDER_PASS_SECRET ||+ 'dev-insecure-multiplayer-secret'+ );+}++function timingSafeEqualStr(a, b) {+ const ab = Buffer.from(String(a || ''));+ const bb = Buffer.from(String(b || ''));+ if (ab.length !== bb.length) return false;+ return crypto.timingSafeEqual(ab, bb);+}++// Maximum age (seconds) an irl-publish signature stays valid. The API mints and+// delivers within a couple of round-trips, so a tight window bounds replay while+// clearing normal network + clock-skew jitter. Mirrors NOTIFY_MAX_AGE_S.+const PUBLISH_MAX_AGE_S = 120;++export function verifyIrlPublish(geocell, type, pin, ts, sig) {+ if (typeof sig !== 'string' || !sig) return false;+ if (typeof geocell !== 'string' || typeof type !== 'string') return false;+ const tsNum = Number(ts);+ if (!Number.isFinite(tsNum)) return false;+ const nowS = Math.floor(Date.now() / 1000);+ if (Math.abs(nowS - tsNum) > PUBLISH_MAX_AGE_S) return false;+ const pinHash = crypto+ .createHash('sha256')+ .update(JSON.stringify(pin ?? {}))+ .digest('base64url');+ const expected = crypto+ .createHmac('sha256', secret())+ .update(`irl:${geocell}:${type}:${tsNum}:${pinHash}`)+ .digest('base64url');+ return timingSafeEqualStr(sig, expected);+}diff --git a/multiplayer/src/irl-registry.js b/multiplayer/src/irl-registry.jsnew file mode 100644index 000000000..0bb99d9bd--- /dev/null+++ b/multiplayer/src/irl-registry.js@@ -0,0 +1,68 @@+// IRL room registry — the lookup that lets the HTTP publish webhook find the live+// Colyseus room(s) a pin change belongs to.+//+// Colyseus routes WebSocket traffic through the matchmaker, but the publish+// webhook arrives as a plain Express POST with no room context. Each IrlRoom+// registers itself here under its CENTRE geocell on create and unregisters on+// dispose; the webhook then resolves the rooms whose 3×3 window covers a pin's+// cell and patches their state directly.+//+// Why fan out to neighbours: a room centred on cell C holds pins for C plus its 8+// neighbours. A pin in cell P therefore belongs in every room whose window+// includes P — i.e. every room centred on P or one of P's neighbours. Geohash+// 8-neighbour adjacency is symmetric, so the set of covering centres is exactly+// { P } ∪ neighbours(P). We register by centre and dispatch over that 9-cell set.++import { geohashNeighbors } from './geohash.js';++class IrlRegistry {+ constructor() {+ this._byCell = new Map(); // centre geocell → Set<IrlRoom>+ }++ register(cell, room) {+ if (!cell || !room) return;+ let set = this._byCell.get(cell);+ if (!set) {+ set = new Set();+ this._byCell.set(cell, set);+ }+ set.add(room);+ }++ unregister(cell, room) {+ const set = this._byCell.get(cell);+ if (!set) return;+ set.delete(room);+ if (set.size === 0) this._byCell.delete(cell);+ }++ // Apply a pin change to every room whose window covers `cell`. Returns how many+ // rooms received it (0 = nobody is watching this area right now, which is fine —+ // the pin is already persisted and the next viewer to join loads it from Neon).+ dispatch(cell, type, pin) {+ if (!cell) return 0;+ const centres = [cell, ...geohashNeighbors(cell)];+ const seen = new Set();+ let delivered = 0;+ for (const c of centres) {+ const set = this._byCell.get(c);+ if (!set) continue;+ for (const room of set) {+ if (seen.has(room)) continue;+ seen.add(room);+ try {+ room.applyPublish(type, pin);+ delivered++;+ } catch (err) {+ console.warn('[irl-registry] applyPublish threw:', err?.message);+ }+ }+ }+ return delivered;+ }+}++// One registry shared by every IrlRoom in the process — that shared map is what+// lets the stateless webhook reach the right live rooms.+export const irlRegistry = new IrlRegistry();diff --git a/multiplayer/src/irl-schemas.js b/multiplayer/src/irl-schemas.jsnew file mode 100644index 000000000..c81027d51--- /dev/null+++ b/multiplayer/src/irl-schemas.js@@ -0,0 +1,88 @@+// Schema definitions for the IRL realtime world (irl_world room), shared between+// the IrlRoom (server) and src/irl-net.js (client, bundled by Vite the same way+// it bundles walk's schemas.js).+//+// @colyseus/schema uses delta encoding: only fields that changed since the last+// patch ride the wire, and a late joiner receives the full current set on join+// for free. That delta sync is exactly what makes the pin set LIVE — a placed /+// moved / removed pin is a one-entry patch the room broadcasts to everyone in the+// geocell, and a fresh viewer is handed the whole MapSchema on connect.+//+// IMPORTANT: append-only. Field indices are positional in @colyseus/schema's+// binary protocol — inserting in the middle shifts every later index and breaks+// clients still connected to an older deployed server. Always add at the end.++import { Schema, MapSchema, defineTypes } from '@colyseus/schema';++// One placed 3D agent anchored at a real-world GPS coordinate. Keyed in the pins+// MapSchema by its pin id (the Neon row UUID), so a place/move/remove is a single+// MapSchema patch. lat/lng are float64 — float32 quantizes a degree to ~1 m of+// error, which is fine for distance but loses the precision a placement actually+// stored, so we pay the extra bytes for an honest coordinate.+export class IrlPin extends Schema {+ constructor() {+ super();+ this.id = '';+ this.lat = 0;+ this.lng = 0;+ this.heading = 0; // compass bearing 0–359° the agent faces+ this.avatarUrl = ''; // GLB the viewer loads (validated server-side before the row existed)+ this.avatarName = '';+ this.caption = '';+ this.x402Endpoint = ''; // optional paid endpoint the IRL Pay button calls+ this.agentId = ''; // three.ws agent id this pin embodies (cross-links)+ this.placedAt = 0; // epoch ms, for age / ordering on the client+ }+}+defineTypes(IrlPin, {+ id: 'string',+ lat: 'float64',+ lng: 'float64',+ heading: 'float32',+ avatarUrl: 'string',+ avatarName: 'string',+ caption: 'string',+ x402Endpoint: 'string',+ agentId: 'string',+ placedAt: 'float64',+});++// A live viewer present in this geocell — the seed of D2 (presence / ghost+// viewers). Declared now so D2 only has to POPULATE the map, never alter the+// schema mid-deploy (which the append-only rule would otherwise complicate). D1+// leaves `viewers` empty; the room defines it but writes no entries yet.+export class IrlViewer extends Schema {+ constructor() {+ super();+ this.id = ''; // session id+ this.lat = 0; // cell-centre + bounded jitter (privacy — never precise GPS)+ this.lng = 0;+ this.agentId = ''; // the agent this viewer is embodying, if any+ }+}+defineTypes(IrlViewer, {+ id: 'string',+ lat: 'float64',+ lng: 'float64',+ agentId: 'string',+});++export class IrlState extends Schema {+ constructor() {+ super();+ // The set of pins in this room's 3×3 geocell window (centre cell + up to 8+ // neighbours), keyed by pin id. This is the live, delta-synced collection+ // the client reconciles into its scene.+ this.pins = new MapSchema();+ // The centre geocell this room instance serves (filterBy key). Seeded by the+ // first client to land here; identical for every viewer in the instance.+ this.geocell = '';+ // Live viewers in this cell (D2). Empty in D1 — see IrlViewer above.+ this.viewers = new MapSchema();+ }+}+defineTypes(IrlState, {+ pins: { map: IrlPin },+ geocell: 'string',+ viewers: { map: IrlViewer },+});diff --git a/multiplayer/src/rooms/IrlRoom.js b/multiplayer/src/rooms/IrlRoom.jsnew file mode 100644index 000000000..f2c075933--- /dev/null+++ b/multiplayer/src/rooms/IrlRoom.js@@ -0,0 +1,238 @@+// IrlRoom — the realtime broadcast hub for the three.ws /irl world (D1).+//+// Unlike WalkRoom, this room is NOT the source of truth. Neon (via the Vercel API+// at /api/irl/pins) owns the pins; this room is a live mirror of the pins inside+// one geocell window, so every viewer standing in that cell sees a place / move /+// remove the instant it happens instead of on their next poll.+//+// Data flow:+// - onCreate loads the cell's current pins from the API into state.pins.+// - A Vercel POST/PATCH/DELETE on a pin fires the signed /internal/irl-publish+// webhook → irlRegistry.dispatch → this room's applyPublish() patches the+// MapSchema → Colyseus delta-broadcasts to everyone in the room.+// - A late joiner is handed the whole MapSchema on connect (schema sync), so it+// never misses pins that were placed before it arrived.+//+// The room holds a 3×3 geocell window (centre + up to 8 neighbours) so a pin that+// straddles a cell edge within the client's nearby radius is still present in the+// stream; the client does the final per-viewer radius filtering.+//+// Presence (live viewers) is D2 — this room defines the `viewers` map but writes+// no entries yet. Interaction reactions are D3. Moderation / caps are D4.++import { Room } from '@colyseus/core';++import { IrlPin, IrlState } from '../irl-schemas.js';+import { encodeGeohash, geohashNeighbors, decodeGeohashBounds } from '../geohash.js';+import { irlRegistry } from '../irl-registry.js';++// The three.ws API this server reads authoritative pins from. Mirrors+// persistence.js / WalkRoom's WORLD_API_BASE — the multiplayer process has no DB+// of its own; Neon is reached only through the Vercel API.+const API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');++const GEOCELL_RE = /^[0-9bcdefghjkmnpqrstuvwxyz]{6}$/; // precision-6 base32 (no a/i/l/o)+const PATCH_RATE_MS = 100; // 10 Hz delta flush — well under the ~1 s liveness target+const MAX_CLIENTS = 200; // a busy real-world spot; viewers only receive broadcasts+const MAX_PINS = 500; // hard ceiling on the synced set, guards the join-time sync+const PUBLISH_TYPES = new Set(['pin:add', 'pin:update', 'pin:remove']);++// Coerce a pin from either the API's snake_case row projection (room load) or the+// webhook's camelCase wire object (publish) into the IrlPin field set, clamped so+// a single oversized field can't bloat the synced state handed to every viewer.+function coercePin(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const id = String(raw.id || '').slice(0, 64);+ if (!id) return null;+ const lat = Number(raw.lat);+ const lng = Number(raw.lng);+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;+ const str = (v, max) => (v == null ? '' : String(v).slice(0, max));+ let placedAt = 0;+ if (Number.isFinite(Number(raw.placedAt))) placedAt = Number(raw.placedAt);+ else if (raw.placed_at) { const t = Date.parse(raw.placed_at); if (Number.isFinite(t)) placedAt = t; }+ const headingRaw = Number(raw.heading);+ return {+ id,+ lat,+ lng,+ heading: Number.isFinite(headingRaw) ? ((Math.round(headingRaw) % 360) + 360) % 360 : 0,+ avatarUrl: str(raw.avatarUrl ?? raw.avatar_url, 1024),+ avatarName: str(raw.avatarName ?? raw.avatar_name, 64),+ caption: str(raw.caption, 200),+ x402Endpoint: str(raw.x402Endpoint ?? raw.x402_endpoint, 512),+ agentId: str(raw.agentId ?? raw.agent_id, 64),+ placedAt,+ };+}++export class IrlRoom extends Room {+ constructor() {+ super();+ this.maxClients = MAX_CLIENTS;+ this.geocell = '';+ this.window = new Set(); // centre + neighbour cells this room mirrors+ }++ async onCreate(options) {+ const cell = String(options?.geocell || '').toLowerCase();+ this.geocell = GEOCELL_RE.test(cell) ? cell : '';++ this.setState(new IrlState());+ this.state.geocell = this.geocell;+ this.setPatchRate(PATCH_RATE_MS);+ this.autoDispose = true;++ // The cells this room is responsible for: its centre plus the 8 neighbours.+ this.window = new Set([this.geocell, ...geohashNeighbors(this.geocell)].filter(Boolean));++ // Register so the publish webhook can reach this room (by centre cell).+ if (this.geocell) irlRegistry.register(this.geocell, this);++ // Hydrate the current live pins for this window from the authoritative API+ // before the first client renders, so newcomers drop into the real world —+ // not an empty one that fills in only as future changes arrive.+ if (this.geocell) {+ try {+ await this._loadPins();+ } catch (err) {+ console.warn(`[irl_world ${this.roomId} cell=${this.geocell}] pin load failed:`, err?.message);+ }+ }++ console.log(`[irl_world ${this.roomId} cell=${this.geocell || 'invalid'}] created (${this.state.pins.size} pins)`);+ }++ async _loadPins() {+ // Bounding box of the 3×3 window (centre + neighbours). A box query reuses the+ // API's lat/lng index and needs no geohash decode server-side — the window is+ // a coarse pre-filter; the client does the final per-viewer radius filtering.+ const bbox = this._windowBounds();+ if (!bbox) return;+ const url = `${API_BASE}/api/irl/pins?bbox=${bbox.minLat},${bbox.minLng},${bbox.maxLat},${bbox.maxLng}`;+ const res = await fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const body = await res.json();+ const pins = Array.isArray(body?.pins) ? body.pins : [];+ for (const raw of pins) {+ if (this.state.pins.size >= MAX_PINS) break;+ const p = coercePin(raw);+ if (p && !this.state.pins.has(p.id)) this.state.pins.set(p.id, this._toSchema(p));+ }+ }++ // Union of the decoded bounds of every cell in this room's window → the lat/lng+ // box the API hydration query selects.+ _windowBounds() {+ let minLat = Infinity, minLng = Infinity, maxLat = -Infinity, maxLng = -Infinity;+ for (const cell of this.window) {+ const b = decodeGeohashBounds(cell);+ if (b.latMin < minLat) minLat = b.latMin;+ if (b.lngMin < minLng) minLng = b.lngMin;+ if (b.latMax > maxLat) maxLat = b.latMax;+ if (b.lngMax > maxLng) maxLng = b.lngMax;+ }+ if (!Number.isFinite(minLat)) return null;+ return { minLat, minLng, maxLat, maxLng };+ }++ _toSchema(p) {+ const pin = new IrlPin();+ pin.id = p.id;+ pin.lat = p.lat;+ pin.lng = p.lng;+ pin.heading = p.heading;+ pin.avatarUrl = p.avatarUrl;+ pin.avatarName = p.avatarName;+ pin.caption = p.caption;+ pin.x402Endpoint = p.x402Endpoint;+ pin.agentId = p.agentId;+ pin.placedAt = p.placedAt;+ return pin;+ }++ // Apply a publish webhook to the synced state. Called by irlRegistry.dispatch+ // for every room whose window covers the pin's cell. A remove deletes the entry;+ // an add (re)writes the full pin; an update on an EXISTING pin is a partial merge+ // — only the fields present in the payload change, so a re-skin that carries just+ // { id, avatarUrl } can't blank the caption/name. Colyseus then delta-broadcasts+ // only what actually changed. (The placer's own client filters its own pin out,+ // see src/irl.js.)+ applyPublish(type, raw) {+ if (!PUBLISH_TYPES.has(type)) return;++ if (type === 'pin:remove') {+ const id = String(raw?.id || '').slice(0, 64);+ if (id) this.state.pins.delete(id);+ return;+ }++ const id = String(raw?.id || '').slice(0, 64);+ if (!id) return;+ const existing = this.state.pins.get(id);++ // Full write: a fresh placement, or an update for a pin this room hasn't seen+ // yet (it joined the window between this room's load and now).+ if (type === 'pin:add' || !existing) {+ const p = coercePin(raw);+ if (!p) return;+ if (existing) { this._assignFull(existing, p); return; }+ if (this.state.pins.size >= MAX_PINS) return; // guard the synced set+ this.state.pins.set(id, this._toSchema(p));+ return;+ }++ // Partial update of an existing pin — only the provided fields move.+ this._applyPartial(existing, raw);+ }++ _assignFull(pin, p) {+ pin.lat = p.lat;+ pin.lng = p.lng;+ pin.heading = p.heading;+ pin.avatarUrl = p.avatarUrl;+ pin.avatarName = p.avatarName;+ pin.caption = p.caption;+ pin.x402Endpoint = p.x402Endpoint;+ pin.agentId = p.agentId;+ pin.placedAt = p.placedAt;+ }++ // Merge only the fields actually present in a partial pin:update wire object+ // (camelCase, as the API's pinWire emits), clamped the same way as a full coerce.+ _applyPartial(pin, raw) {+ const lat = Number(raw.lat);+ const lng = Number(raw.lng);+ if (Number.isFinite(lat)) pin.lat = lat;+ if (Number.isFinite(lng)) pin.lng = lng;+ if (raw.heading !== undefined) {+ const h = Number(raw.heading);+ if (Number.isFinite(h)) pin.heading = ((Math.round(h) % 360) + 360) % 360;+ }+ if (raw.avatarUrl !== undefined) pin.avatarUrl = String(raw.avatarUrl || '').slice(0, 1024);+ if (raw.avatarName !== undefined) pin.avatarName = String(raw.avatarName || '').slice(0, 64);+ if (raw.caption !== undefined) pin.caption = String(raw.caption || '').slice(0, 200);+ if (raw.x402Endpoint !== undefined) pin.x402Endpoint = String(raw.x402Endpoint || '').slice(0, 512);+ if (raw.agentId !== undefined) pin.agentId = String(raw.agentId || '').slice(0, 64);+ // placedAt is immutable for a given pin; never patched.+ }++ onJoin(client, options) {+ // Bind the join context for D2 presence (lat/lng → cell-jittered marker) and+ // so a future moderation pass (D4) can attribute actions. D1 only reads pins,+ // so we store it but write nothing to the synced state yet.+ client.userData = {+ deviceToken: typeof options?.deviceToken === 'string' ? options.deviceToken.slice(0, 80) : '',+ agentId: typeof options?.agent === 'string' ? options.agent.slice(0, 64) : '',+ };+ }++ onDispose() {+ if (this.geocell) irlRegistry.unregister(this.geocell, this);+ console.log(`[irl_world ${this.roomId} cell=${this.geocell || 'invalid'}] disposed`);+ }+}++// Re-exported so callers (and tests) can derive a centre cell without importing+// geohash separately. Keeps the room's precision the single source of truth.+export { encodeGeohash };diff --git a/pages/agent-detail.html b/pages/agent-detail.htmlindex 314de478f..3ced266d6 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -292,6 +292,30 @@</svg>See in 3D</a>+ <a+ id="ad-irl-link"+ class="ad-btn"+ href="/irl"+ aria-label="View this agent in IRL — place it in your real space"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="margin-right: 6px">+ <circle cx="12" cy="8" r="4" />+ <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7" />+ </svg>+ View in IRL+ </a>+ <a+ id="ad-xr-link"+ class="ad-btn"+ href="/xr"+ aria-label="View this agent in XR — immersive AR/VR"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="margin-right: 6px">+ <path d="M3 7l9-4 9 4v10l-9 4-9-4V7z" />+ <path d="M12 3v18M3 7l9 4 9-4" />+ </svg>+ View in XR+ </a><buttontype="button"id="ad-share-btn"diff --git a/pages/irl.html b/pages/irl.htmlindex 2836533a8..82be18ff3 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -5,6 +5,10 @@<meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" /><meta name="theme-color" content="#000000" />+ <!-- Realtime pin sync (D1) — the IRL world runs as a room on the same Colyseus+ host as /walk. Lets nearby pins stream live; absent/unreachable it falls back+ to polling automatically (see src/irl-net.js). -->+ <meta name="irl-server" content="wss://three-ws-multiplayer-93741856042.us-central1.run.app" /><title>IRL · three.ws</title><meta name="description" content="Walk a 3D avatar in your real space. Camera AR passthrough, joystick movement, tap-to-place objects." /><meta property="og:type" content="website" />@@ -271,6 +275,34 @@.irl-status-spinner.hidden { display: none; }@keyframes irl-spin { to { transform: rotate(360deg); } }+ /* E4 — full-screen designed-state host above the canvas. Used for the+ unsupported-device state (rendered before irl.js loads) and the+ avatar-load-failure Retry card. Sits below the bottom sheets (z 50–70)+ so a sheet can still open over it, but above the canvas/topbar. */+ #irl-overlay {+ position: fixed;+ inset: 0;+ z-index: 45;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 24px;+ background: radial-gradient(120% 120% at 50% 30%, rgba(13,16,24,0.82), rgba(7,9,14,0.96));+ backdrop-filter: blur(3px);+ -webkit-backdrop-filter: blur(3px);+ animation: irl-overlay-in 0.22s ease;+ }+ #irl-overlay[hidden] { display: none; }+ #irl-overlay .irl-overlay-card {+ width: min(420px, 100%);+ background: rgba(15,18,27,0.9);+ border: 1px solid rgba(255,255,255,0.10);+ border-radius: 18px;+ box-shadow: 0 24px 64px rgba(0,0,0,0.5);+ }+ @keyframes irl-overlay-in { from { opacity: 0; } to { opacity: 1; } }+ @media (prefers-reduced-motion: reduce) { #irl-overlay { animation: none; } }+/* Hero camera button */#irl-camera-btn {width: 100%;@@ -516,6 +548,65 @@white-space: nowrap;}#irl-nearby-badge[hidden] { display: none; }+ /* Refresh-failed indicator (E4) — the nearby poll couldn't reach the server. */+ #irl-nearby-badge.is-error {+ color: #fbbf24;+ background: rgba(251,191,36,0.12);+ border-color: rgba(251,191,36,0.38);+ }++ /* Realtime status pill (D1) — sits beside the nearby badge: live (green),+ connecting (amber pulse), or polling (the fallback transport, tap to retry). */+ .irl-net-pill {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin-left: 6px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.04em;+ border-radius: 999px;+ padding: 2px 8px 2px 7px;+ white-space: nowrap;+ border: 1px solid transparent;+ cursor: default;+ -webkit-user-select: none;+ user-select: none;+ }+ .irl-net-pill[hidden] { display: none; }+ .irl-net-pill::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: currentColor;+ flex-shrink: 0;+ }+ .irl-net-pill.is-live {+ color: var(--green);+ background: rgba(74,222,128,0.12);+ border-color: rgba(74,222,128,0.35);+ }+ .irl-net-pill.is-live::before { box-shadow: 0 0 6px currentColor; }+ .irl-net-pill.is-connecting {+ color: #fbbf24;+ background: rgba(251,191,36,0.12);+ border-color: rgba(251,191,36,0.38);+ }+ .irl-net-pill.is-connecting::before { animation: irl-net-pulse 1.1s ease-in-out infinite; }+ .irl-net-pill.is-polling {+ color: #9aa6b2;+ background: rgba(148,163,184,0.12);+ border-color: rgba(148,163,184,0.3);+ cursor: pointer;+ }+ @keyframes irl-net-pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.35; }+ }+ @media (prefers-reduced-motion: reduce) {+ .irl-net-pill.is-connecting::before { animation: none; }+ }/* Radar minimap */#irl-radar {@@ -999,6 +1090,38 @@.irl-service-use:active { transform: translateY(1px); }.irl-service-use:focus-visible { outline: 2px solid rgba(52,211,153,0.6); outline-offset: 2px; }.irl-service-use:disabled { opacity: 0.6; cursor: default; }+ /* Paid-service response, rendered inline after an x402 settlement */+ .irl-service-result {+ margin-top: 12px;+ padding: 10px 12px;+ border-radius: 10px;+ background: rgba(52,211,153,0.07);+ border: 1px solid rgba(52,211,153,0.22);+ animation: irl-result-in 0.25s ease;+ }+ .irl-service-result-label {+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: #34d399;+ font-weight: 600;+ margin-bottom: 6px;+ }+ .irl-service-result pre {+ margin: 0;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+ line-height: 1.5;+ color: #d1d5db;+ white-space: pre-wrap;+ word-break: break-word;+ max-height: 220px;+ overflow: auto;+ }+ @keyframes irl-result-in {+ from { opacity: 0; transform: translateY(4px); }+ to { opacity: 1; transform: none; }+ }/* Multiplayer indicator row */.irl-multiplayer-note {display: flex;@@ -1043,6 +1166,64 @@.irl-sheet-status { margin-top: 10px; font-size: 12.5px; color: #34d399; }.irl-sheet-status.is-error { color: #f87171; }+ /* Report affordance (D4) — deliberately low-prominence; it's a safety tool,+ not a primary action. Sits under the message composer. */+ .irl-sheet-report {+ display: block;+ margin: 14px auto 0;+ padding: 6px 10px;+ background: none;+ border: none;+ color: #6b7280;+ font-size: 12px;+ cursor: pointer;+ border-radius: 8px;+ transition: color 0.15s, background 0.15s;+ }+ .irl-sheet-report:hover { color: #f87171; background: rgba(248,113,113,0.08); }+ .irl-sheet-report:focus-visible { outline: 2px solid rgba(248,113,113,0.6); outline-offset: 2px; }++ /* Report reason sheet */+ #irl-report-sheet {+ position: fixed;+ bottom: 0;+ left: 0;+ right: 0;+ z-index: 23;+ background: rgba(12,14,20,0.98);+ border-top: 1px solid rgba(255,255,255,0.10);+ border-radius: 18px 18px 0 0;+ padding: 20px 22px 36px;+ backdrop-filter: blur(22px);+ -webkit-backdrop-filter: blur(22px);+ transform: translateY(100%);+ transition: transform 0.28s cubic-bezier(0.32,0.72,0,1);+ pointer-events: none;+ max-height: 72vh;+ overflow-y: auto;+ }+ #irl-report-sheet.is-open { transform: translateY(0); pointer-events: all; }+ #irl-report-sheet .irl-sheet-handle { margin-bottom: 14px; }+ .irl-report-header { display: flex; align-items: center; justify-content: space-between; }+ .irl-report-header h3 { font-size: 16px; font-weight: 700; color: #e5e7eb; margin: 0; }+ .irl-report-sub { font-size: 12.5px; color: #9ca3af; margin: 8px 0 16px; line-height: 1.5; }+ .irl-report-reasons { display: flex; flex-direction: column; gap: 8px; }+ .irl-report-reason {+ text-align: left;+ padding: 13px 14px;+ border-radius: 12px;+ border: 1px solid rgba(255,255,255,0.08);+ background: rgba(255,255,255,0.03);+ color: #e5e7eb;+ font-size: 14px;+ cursor: pointer;+ transition: border-color 0.15s, background 0.15s, transform 0.05s;+ }+ .irl-report-reason:hover { border-color: rgba(248,113,113,0.5); background: rgba(248,113,113,0.08); }+ .irl-report-reason:active { transform: scale(0.99); }+ .irl-report-reason:focus-visible { outline: 2px solid rgba(248,113,113,0.6); outline-offset: 2px; }+ .irl-report-reason:disabled { opacity: 0.5; cursor: default; }+/* Agent picker sheet */#irl-agents-sheet {position: fixed;@@ -1162,6 +1343,11 @@<!-- Three.js canvas --><canvas id="irl-canvas"></canvas>+<!-- Full-screen designed-state host (E4): unsupported-device state (filled by the+ capability gate below before irl.js loads) and avatar-load-failure Retry card+ (filled by irl.js). Empty + hidden until a full-screen state is needed. -->+<div id="irl-overlay" hidden role="alertdialog" aria-modal="true" aria-label="IRL status"></div>+<!-- Top bar --><header class="irl-topbar"><a class="irl-back" id="irl-back-link" href="/walk">@@ -1174,10 +1360,15 @@IRL</span><span id="irl-nearby-badge" hidden aria-live="polite"></span>+ <span id="irl-net-pill" class="irl-net-pill" hidden role="status" aria-live="polite"></span></div><button class="irl-share-btn" id="irl-share-btn" type="button" aria-label="Share">Share</button></header>+<!-- E1 permission re-request chips — a denied sensor leaves a one-tap recovery+ chip here; src/irl/onboarding.js shows/hides this strip and renders into it. -->+<div id="irl-perm-chips" class="irl-perm-chips" hidden aria-label="Permissions needing attention"></div>+<!-- Joystick zone --><div id="irl-joystick"></div>@@ -1356,6 +1547,27 @@<button id="irl-msg-send" class="irl-msg-send" type="submit">Send</button></form><div id="irl-sheet-status" class="irl-sheet-status" role="status" hidden></div>+ <!-- Report — community moderation (D4). Hidden on your own pins. Opens a reason sheet. -->+ <button id="irl-sheet-report" class="irl-sheet-report" type="button" hidden>Report this pin</button>+</div>++<!-- Report reason sheet (D4) — choose why, POST /api/irl/report, threshold-hide server-side -->+<div id="irl-report-sheet" role="dialog" aria-modal="true" aria-label="Report this pin">+ <div class="irl-sheet-handle" aria-hidden="true"></div>+ <div class="irl-report-header">+ <h3>Report this pin</h3>+ <button class="irl-sheet-close" id="irl-report-close" type="button" aria-label="Close">×</button>+ </div>+ <p class="irl-report-sub">Tell us what’s wrong. Reports are reviewed; a pin is hidden once enough people flag it.</p>+ <div class="irl-report-reasons" role="group" aria-label="Reason">+ <button class="irl-report-reason" type="button" data-reason="spam">Spam or advertising</button>+ <button class="irl-report-reason" type="button" data-reason="harassment">Hate or harassment</button>+ <button class="irl-report-reason" type="button" data-reason="impersonation">Impersonation</button>+ <button class="irl-report-reason" type="button" data-reason="scam">Scam or off-brand coin</button>+ <button class="irl-report-reason" type="button" data-reason="sexual">Sexual content</button>+ <button class="irl-report-reason" type="button" data-reason="other">Something else</button>+ </div>+ <div id="irl-report-status" class="irl-sheet-status" role="status" hidden></div></div><!-- Agent picker sheet — lists authenticated user's agents to switch which one is placed -->@@ -1444,69 +1656,47 @@</div><div id="irl-cal-denied" role="alertdialog" aria-modal="false" aria-label="Calibration locked" hidden></div>-<script type="module" src="/src/irl.js"></script>--<script>-document.getElementById('irl-share-btn').addEventListener('click', async () => {- const btn = document.getElementById('irl-share-btn');- const origText = btn.textContent;-- // Capture the current frame from the Three.js canvas (+ camera feed if in AR)- async function captureFrame() {- const irl = document.getElementById('irl-canvas');- if (!irl) return null;- const w = irl.width; const h = irl.height;- if (!w || !h) return null;- const out = document.createElement('canvas');- out.width = w; out.height = h;- const ctx2 = out.getContext('2d');- const vid = document.getElementById('irl-camera');- if (document.body.classList.contains('is-ar') && vid && !vid.paused) {- try { ctx2.drawImage(vid, 0, 0, w, h); } catch {}- }- try { ctx2.drawImage(irl, 0, 0); } catch {}- return new Promise(res => out.toBlob(res, 'image/png'));- }+<!-- E1 first-run permission + onboarding overlay. Cards (prompt / granted /+ denied-with-recovery / unsupported) are rendered by src/irl/onboarding.js. -->+<div id="irl-onboard" class="irl-onboard" hidden role="dialog" aria-modal="true" aria-label="Set up IRL"></div>- btn.disabled = true;- btn.textContent = '…';-- try {- const blob = await captureFrame();- if (blob) {- const file = new File([blob], 'three-ws-irl.png', { type: 'image/png' });- if (navigator.share && navigator.canShare?.({ files: [file] })) {- await navigator.share({ title: 'IRL · three.ws', files: [file] });- btn.textContent = 'Shared!';- setTimeout(() => { btn.textContent = origText; btn.disabled = false; }, 2000);- return;- }- // Download on desktop- const objUrl = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = objUrl; a.download = 'three-ws-irl.png';- a.click();- setTimeout(() => URL.revokeObjectURL(objUrl), 4000);- btn.textContent = 'Saved!';- setTimeout(() => { btn.textContent = origText; btn.disabled = false; }, 2000);- return;- }- } catch {}-- // Fallback: share / copy URL- const url = location.href;- if (navigator.share) {- try { await navigator.share({ title: 'IRL · three.ws', url }); btn.textContent = 'Shared!'; setTimeout(() => { btn.textContent = origText; btn.disabled = false; }, 2000); return; } catch {}+<!-- E4 capability gate — IRL renders 3D agents with WebGL; without it irl.js's+ renderer throws at import time and leaves a blank canvas. Detect support first+ and boot the AR module only when WebGL is real; otherwise render a designed+ "unsupported device" state into #irl-overlay and never load the heavy module+ (so no thrown context error reaches the console). -->+<script type="module">+ function webglSupported() {+ try {+ const c = document.createElement('canvas');+ return !!(window.WebGLRenderingContext &&+ (c.getContext('webgl') || c.getContext('experimental-webgl')));+ } catch { return false; }}- try {- await navigator.clipboard.writeText(url);- btn.textContent = 'Copied!';- } catch {- btn.textContent = origText;++ if (webglSupported()) {+ import('/src/irl.js');+ } else {+ import('/src/shared/state-kit.js').then(({ emptyStateHTML, ensureStateKitStyles }) => {+ ensureStateKitStyles();+ const host = document.getElementById('irl-overlay');+ if (!host) return;+ const nameEl = document.getElementById('irl-avatar-name');+ if (nameEl) nameEl.textContent = 'IRL unavailable';+ const subEl = document.getElementById('irl-subtitle');+ if (subEl) subEl.textContent = 'This device can’t render the AR view';+ host.innerHTML = '<div class="irl-overlay-card">' + emptyStateHTML({+ icon: '🛰️',+ title: 'This device can’t run IRL AR',+ body: 'IRL places 3D agents in your space using WebGL, which isn’t available in this browser. You can still browse agents and services on the web — or reopen IRL in an up-to-date Chrome, Safari, or Edge.',+ actions: [+ { label: 'Browse agents', href: '/agents', primary: true },+ { label: 'Open the marketplace', href: '/marketplace' },+ ],+ }) + '</div>';+ host.hidden = false;+ }).catch(() => {});}- btn.disabled = false;- setTimeout(() => { if (btn.textContent !== origText) { btn.textContent = origText; } }, 1800);-});</script></body></html>diff --git a/pages/xr.html b/pages/xr.htmlindex 7f58daad6..899233bc3 100644--- a/pages/xr.html+++ b/pages/xr.html@@ -464,60 +464,5 @@})();</script><script src="/brand.js" defer></script>- <script>- document.getElementById('xr-share-btn').addEventListener('click', async () => {- const btn = document.getElementById('xr-share-btn');- const origHTML = btn.innerHTML;- btn.disabled = true;- btn.querySelector('svg') && (btn.querySelector('svg').style.display = 'none');- btn.lastChild.textContent = '…';-- async function captureFrame() {- const cvs = document.getElementById('xr-canvas');- if (!cvs) return null;- const w = cvs.width; const h = cvs.height;- if (!w || !h) return null;- const out = document.createElement('canvas');- out.width = w; out.height = h;- const ctx2 = out.getContext('2d');- const vid = document.getElementById('xr-camera-feed');- if (vid && !vid.paused && vid.videoWidth) {- try { ctx2.drawImage(vid, 0, 0, w, h); } catch {}- }- try { ctx2.drawImage(cvs, 0, 0); } catch {}- return new Promise(res => out.toBlob(res, 'image/png'));- }-- try {- const blob = await captureFrame();- if (blob) {- const file = new File([blob], 'three-ws-xr.png', { type: 'image/png' });- if (navigator.share && navigator.canShare?.({ files: [file] })) {- await navigator.share({ title: 'XR · three.ws', files: [file] });- btn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg> Shared!';- setTimeout(() => { btn.innerHTML = origHTML; btn.disabled = false; }, 2000);- return;- }- const objUrl = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = objUrl; a.download = 'three-ws-xr.png'; a.click();- setTimeout(() => URL.revokeObjectURL(objUrl), 4000);- btn.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg> Saved!';- setTimeout(() => { btn.innerHTML = origHTML; btn.disabled = false; }, 2000);- return;- }- } catch {}-- // Fallback: share URL- const url = location.href;- if (navigator.share) {- try { await navigator.share({ title: 'XR · three.ws', url }); } catch {}- } else {- try { await navigator.clipboard.writeText(url); } catch {}- }- btn.innerHTML = origHTML;- btn.disabled = false;- });- </script></body></html>diff --git a/public/changelog.json b/public/changelog.jsonindex 2953be945..f2bfc0d4a 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,31 @@{- "generated_at": "2026-06-17T02:32:22.903Z",+ "generated_at": "2026-06-17T03:09:30.587Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "An inbox for your IRL agents — see who tapped, messaged, or paid, and reply",+ "summary": "Your IRL Agents dashboard now has an Inbox: a live, chronological feed of everyone who met your placed agents in real life. Each entry shows what happened — a view, a tap, a message, or a payment — where it happened, and how long ago. Payments show the exact amount and link straight to the block-explorer receipt, and you can reply to anyone who left your agent a message; if they were signed in, your reply lands in their notifications. Unread counts appear on the Inbox button and on each agent's card, the feed refreshes itself every few seconds, and opening the inbox marks everything read. High-signal events (a payment or a message) also ping you in the notification bell, so you find out the moment a stranger across the city engages your agent.",+ "link": "/dashboard/irl-placements",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Change a placed agent's outfit from your dashboard — everyone nearby sees it",+ "summary": "Your IRL Agents dashboard now has a real outfit editor. Open Change outfit on any agent you've placed and a live 3D preview loads with wardrobe controls for the exact layers that avatar has — recolour its hair, skin, and clothing, strip back to the base body and dress it up again, or stack on hats, glasses, and earrings. Because your agents are public, the new look is baked into the agent itself and pushed to its real-world pin, so every person who walks up to that spot sees the updated outfit in their camera — not just you. Save when you're happy; the avatar is re-rendered for real before it confirms, the previous look stays untouched if anything fails, and nearby viewers refresh to the new outfit within seconds. Run a seasonal look, brand your agents as staff for an event, or just keep them fresh — all without walking back to where you pinned them.",+ "link": "/dashboard/irl-placements",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-17","type": "update",@@ -48,6 +68,91 @@"improvement"]},+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "IRL now fails gracefully — clear states instead of blank screens",+ "summary": "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.",+ "link": "/irl",+ "tags": [+ "improvement",+ "fix"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "IRL placements now have guardrails: report a pin, content checks, and area limits",+ "summary": "Now that anyone at a location can see anyone's placed agent on three.ws/irl, we've added the safety layer that makes a public shared space work. Tap any agent that isn't yours and you'll find a Report option — pick a reason (spam, hate, impersonation, scam, sexual content, or something else) and once enough different people flag the same pin it's automatically hidden from everyone, with the reporter seeing it disappear right away. One person can't hide someone else's agent, and repeat reports from the same device don't stack, so the system can't be gamed to silence a legitimate pin. At placement time, captions and agent names are screened for slurs and hateful content and rejected with a clear, fixable message, and a pin can only ever reference $THREE — no other coin can be advertised. Pay buttons are locked to three.ws payment endpoints so a pin can't point you at an off-platform drain. To stop one person from carpet-bombing a plaza, each small area caps how many agents it holds and each person has an active-pin limit — and if you hit a limit you get a plain-language nudge (shorten the text, move, wait a moment, or remove an old pin) instead of a silent failure. Abandoned anonymous pins are now cleaned up automatically; your signed-in permanent pins are never touched.",+ "link": "/irl",+ "tags": [+ "security",+ "feature"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "IRL stays smooth at crowded locations",+ "summary": "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.",+ "link": "/irl",+ "tags": [+ "improvement",+ "infra"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "IRL walks you through camera, motion & location — and never dead-ends on a blocked permission",+ "summary": "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.",+ "link": "/irl",+ "tags": [+ "feature",+ "improvement"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Jump straight from an agent's profile into IRL or XR",+ "summary": "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.",+ "link": "/irl",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Move your IRL agents on a real map — drag the pin from anywhere",+ "summary": "Your IRL Agents dashboard now has a live map. Open Move on map on any placed agent and you get an OpenStreetMap view with a draggable pin for each agent you've placed: drag the highlighted one to a new spot, or tap another to switch to it. As you drag, the new location is named for you (the nearest town or city) and a Save bar appears so nothing changes until you confirm — and if a save ever fails, the pin snaps back to where it was. A compass dial lets you re-aim which way the agent faces, in degrees or by dragging the needle, and a Remove from map button takes a pin down. You can relocate an agent across the city — or across the world — without walking back to it. The map loads only when you open it, works on a phone, and if it can't load it falls back to a simple latitude/longitude form so you can still move the pin.",+ "link": "/dashboard/irl-placements",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Nearby agents on IRL now update live — no reload",+ "summary": "Open three.ws/irl and the agents other people have placed around you now update in real time. When anyone nearby drops a new agent, moves one, changes its outfit, or takes one down, you see it appear, shift, or vanish on your screen within about a second — no refresh, no waiting for the next scan. It works both ways: pin an agent and everyone standing near you sees it pop in too, and walk into a new area and the live view follows you to the agents there. A small status pill next to the nearby count shows whether you're getting live updates; if the realtime connection can't be reached — some networks block it — IRL automatically falls back to refreshing every few seconds and the pill reads 'Polling', still fully working, just a touch slower.",+ "link": "/irl",+ "tags": [+ "feature",+ "improvement"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Pay an IRL agent for its services — and open its full profile — right from the card",+ "summary": "When you tap an agent on three.ws/irl, its card now does real things. View profile opens that agent's full page so you can see who you just met. If the agent offers paid services, each one shows its price and a Use button: tap it, approve the payment in your wallet, and you pay in USDC on the spot — the standard x402 flow, capped at the price shown so a misconfigured service can never overcharge you. The response you paid for appears right inside the card instead of vanishing into a toast. Every state is handled: no wallet, a cancelled signature, or a service error each show a clear message and leave the button ready to try again, and each service button works on its own so paying for one never freezes the others. Completed encounters quietly notify the agent's owner, receipt and all.",+ "link": "/irl",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-17","type": "update",@@ -58,6 +163,16 @@"feature"]},+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "See your IRL agent's on-chain reputation right from the dashboard",+ "summary": "On your IRL Agents dashboard, the Reputation chip on each placed agent now opens an on-chain reputation panel — the exact score and trust tier (Elite, Trusted, Emerging, New) a passer-by sees when they tap your agent in real life. It breaks down how many attestations are verified, credentialed, and disputed, shows the average star rating and how many distinct people vouched, and links straight to the agent's passport to manage it. Agents without a Solana identity, or without any attestations yet, get a clear next step instead of an error.",+ "link": "/dashboard/irl-placements",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-17","type": "update",@@ -68,6 +183,17 @@"improvement"]},+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Your IRL agent dashboard now lights up the instant someone interacts",+ "summary": "When a stranger taps, messages, or pays one of your agents placed out in the real world, your dashboard now reflects it within about a second — no refresh. The agent's card flashes, the unread count ticks up live, and a payment or a new message pops a notification so you feel the moment it happens, even from the other side of the planet. A small Live indicator shows when the realtime connection is up; if it ever drops, the inbox keeps updating on a short delay instead, so you never miss an encounter. Only your agent's name and the kind of interaction are ever shared with you — never the visitor's location or wallet.",+ "link": "/dashboard/irl-placements",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-16","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 6ec361aba..2f106e2b1 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>An inbox for your IRL agents — see who tapped, messaged, or paid, and reply</title>+ <link>https://three.ws/dashboard/irl-placements</link>+ <guid isPermaLink="false">2026-06-17:An inbox for your IRL agents — see who tapped, messaged, or paid, and reply</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your IRL Agents dashboard now has an Inbox: a live, chronological feed of everyone who met your placed agents in real life. Each entry shows what happened — a view, a tap, a message, or a payment — where it happened, and how long ago. Payments show the exact amount and link straight to the block-explorer receipt, and you can reply to anyone who left your agent a message; if they were signed in, your reply lands in their notifications. Unread counts appear on the Inbox button and on each agent's card, the feed refreshes itself every few seconds, and opening the inbox marks everything read. High-signal events (a payment or a message) also ping you in the notification bell, so you find out the moment a stranger across the city engages your agent.</description>+ </item>+ <item>+ <title>Change a placed agent's outfit from your dashboard — everyone nearby sees it</title>+ <link>https://three.ws/dashboard/irl-placements</link>+ <guid isPermaLink="false">2026-06-17:Change a placed agent's outfit from your dashboard — everyone nearby sees it</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your IRL Agents dashboard now has a real outfit editor. Open Change outfit on any agent you've placed and a live 3D preview loads with wardrobe controls for the exact layers that avatar has — recolour its hair, skin, and clothing, strip back to the base body and dress it up again, or stack on hats, glasses, and earrings. Because your agents are public, the new look is baked into the agent itself and pushed to its real-world pin, so every person who walks up to that spot sees the updated outfit in their camera — not just you. Save when you're happy; the avatar is re-rendered for real before it confirms, the previous look stays untouched if anything fails, and nearby viewers refresh to the new outfit within seconds. Run a seasonal look, brand your agents as staff for an event, or just keep them fresh — all without walking back to where you pinned them.</description>+ </item><item><title>Everyone at a location now sees your IRL agent in the same real spot</title><link>https://three.ws/irl</link>@@ -38,6 +54,70 @@<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 now fails gracefully — clear states instead of blank screens</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:IRL now fails gracefully — clear states instead of blank screens</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>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.</description>+ </item>+ <item>+ <title>IRL placements now have guardrails: report a pin, content checks, and area limits</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:IRL placements now have guardrails: report a pin, content checks, and area limits</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>security</category>+ <description>Now that anyone at a location can see anyone's placed agent on three.ws/irl, we've added the safety layer that makes a public shared space work. Tap any agent that isn't yours and you'll find a Report option — pick a reason (spam, hate, impersonation, scam, sexual content, or something else) and once enough different people flag the same pin it's automatically hidden from everyone, with the reporter seeing it disappear right away. One person can't hide someone else's agent, and repeat reports from the same device don't stack, so the system can't be gamed to silence a legitimate pin. At placement time, captions and agent names are screened for slurs and hateful content and rejected with a clear, fixable message, and a pin can only ever reference $THREE — no other coin can be advertised. Pay buttons are locked to three.ws payment endpoints so a pin can't point you at an off-platform drain. To stop one person from carpet-bombing a plaza, each small area caps how many agents it holds and each person has an active-pin limit — and if you hit a limit you get a plain-language nudge (shorten the text, move, wait a moment, or remove an old pin) instead of a silent failure. Abandoned anonymous pins are now cleaned up automatically; your signed-in permanent pins are never touched.</description>+ </item>+ <item>+ <title>IRL stays smooth at crowded locations</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:IRL stays smooth at crowded locations</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>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.</description>+ </item>+ <item>+ <title>IRL walks you through camera, motion & location — and never dead-ends on a blocked permission</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:IRL walks you through camera, motion & location — and never dead-ends on a blocked permission</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item>+ <item>+ <title>Jump straight from an agent's profile into IRL or XR</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:Jump straight from an agent's profile into IRL or XR</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item>+ <item>+ <title>Move your IRL agents on a real map — drag the pin from anywhere</title>+ <link>https://three.ws/dashboard/irl-placements</link>+ <guid isPermaLink="false">2026-06-17:Move your IRL agents on a real map — drag the pin from anywhere</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your IRL Agents dashboard now has a live map. Open Move on map on any placed agent and you get an OpenStreetMap view with a draggable pin for each agent you've placed: drag the highlighted one to a new spot, or tap another to switch to it. As you drag, the new location is named for you (the nearest town or city) and a Save bar appears so nothing changes until you confirm — and if a save ever fails, the pin snaps back to where it was. A compass dial lets you re-aim which way the agent faces, in degrees or by dragging the needle, and a Remove from map button takes a pin down. You can relocate an agent across the city — or across the world — without walking back to it. The map loads only when you open it, works on a phone, and if it can't load it falls back to a simple latitude/longitude form so you can still move the pin.</description>+ </item>+ <item>+ <title>Nearby agents on IRL now update live — no reload</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:Nearby agents on IRL now update live — no reload</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Open three.ws/irl and the agents other people have placed around you now update in real time. When anyone nearby drops a new agent, moves one, changes its outfit, or takes one down, you see it appear, shift, or vanish on your screen within about a second — no refresh, no waiting for the next scan. It works both ways: pin an agent and everyone standing near you sees it pop in too, and walk into a new area and the live view follows you to the agents there. A small status pill next to the nearby count shows whether you're getting live updates; if the realtime connection can't be reached — some networks block it — IRL automatically falls back to refreshing every few seconds and the pill reads 'Polling', still fully working, just a touch slower.</description>+ </item>+ <item>+ <title>Pay an IRL agent for its services — and open its full profile — right from the card</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:Pay an IRL agent for its services — and open its full profile — right from the card</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>When you tap an agent on three.ws/irl, its card now does real things. View profile opens that agent's full page so you can see who you just met. If the agent offers paid services, each one shows its price and a Use button: tap it, approve the payment in your wallet, and you pay in USDC on the spot — the standard x402 flow, capped at the price shown so a misconfigured service can never overcharge you. The response you paid for appears right inside the card instead of vanishing into a toast. Every state is handled: no wallet, a cancelled signature, or a service error each show a clear message and leave the button ready to try again, and each service button works on its own so paying for one never freezes the others. Completed encounters quietly notify the agent's owner, receipt and all.</description>+ </item><item><title>Place your IRL agent on the real floor with AR anchoring</title><link>https://three.ws/irl</link>@@ -46,6 +126,14 @@<category>feature</category><description>On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. If you tap to anchor before your location is ready, it holds the spot and saves it the instant your first GPS fix lands instead of losing the placement. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.</description></item>+ <item>+ <title>See your IRL agent's on-chain reputation right from the dashboard</title>+ <link>https://three.ws/dashboard/irl-placements</link>+ <guid isPermaLink="false">2026-06-17:See your IRL agent's on-chain reputation right from the dashboard</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>On your IRL Agents dashboard, the Reputation chip on each placed agent now opens an on-chain reputation panel — the exact score and trust tier (Elite, Trusted, Emerging, New) a passer-by sees when they tap your agent in real life. It breaks down how many attestations are verified, credentialed, and disputed, shows the average star rating and how many distinct people vouched, and links straight to the agent's passport to manage it. Agents without a Solana identity, or without any attestations yet, get a clear next step instead of an error.</description>+ </item><item><title>Tapping an IRL agent is now reliable — hit the body, not just the tiny label</title><link>https://three.ws/irl</link>@@ -54,6 +142,14 @@<category>improvement</category><description>On three.ws/irl you can now open an agent by tapping its 3D body, not only its small floating name tag. Tapping near a name also works, with a finger-sized target that meets Apple's 44-pixel minimum, so you no longer have to pixel-hunt on a phone. When two agents stand on top of each other, the one in front wins instead of a random pick. As you move, the nearest agent you can reach lights up with a soft focus ring so you can see what you'll tap before you tap it — and if you've turned on Reduce Motion, the ring stays still. Looking and panning around no longer misfires as a tap.</description></item>+ <item>+ <title>Your IRL agent dashboard now lights up the instant someone interacts</title>+ <link>https://three.ws/dashboard/irl-placements</link>+ <guid isPermaLink="false">2026-06-17:Your IRL agent dashboard now lights up the instant someone interacts</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>When a stranger taps, messages, or pays one of your agents placed out in the real world, your dashboard now reflects it within about a second — no refresh. The agent's card flashes, the unread count ticks up live, and a payment or a new message pops a notification so you feel the moment it happens, even from the other side of the planet. A small Live indicator shows when the realtime connection is up; if it ever drops, the inbox keeps updating on a short delay instead, so you never miss an encounter. Only your agent's name and the kind of interaction are ever shared with you — never the visitor's location or wallet.</description>+ </item><item><title>Agent Activity — Oracle conviction in real time</title><link>https://three.ws/activity</link>diff --git a/public/features.json b/public/features.jsonindex 8fca97bec..46632032c 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T02:32:22.882Z",+ "generated_at": "2026-06-17T03:09:30.575Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/irl-d3-smoke.mjs b/scripts/irl-d3-smoke.mjsnew file mode 100644index 000000000..91448529b--- /dev/null+++ b/scripts/irl-d3-smoke.mjs@@ -0,0 +1,136 @@+// Smoke test for D3 — IRL interaction broadcast, owner live-delivery layer.+//+// node scripts/irl-d3-smoke.mjs+//+// Exercises the SSE owner-stream endpoint (api/irl/interactions-stream.js) with a+// mock req/res — no live DB needed — plus unit checks on the two security-critical+// pure functions that decide what leaves the server:+// • publicRow() — the privacy filter: the actor's identity (viewer_user_id /+// viewer_device) and any non-receipt payload must NEVER reach+// the owner. (Acceptance: "No raw GPS or wallet address of A+// reaches the owner or other viewers.")+// • matches() — owner isolation: an interaction is only ever delivered to the+// pin's actual owner, by session id OR device token.+//+// Assertions throw on failure; a clean run prints "D3 SMOKE: PASS".++// Force the no-DB path so the stream test is deterministic regardless of env.+delete process.env.DATABASE_URL;++import handler, { publicRow, matches } from '../api/irl/interactions-stream.js';++let failures = 0;+function check(name, cond) {+ if (cond) { console.log(` ✓ ${name}`); }+ else { console.error(` ✗ ${name}`); failures++; }+}++// ── Minimal mock req/res ─────────────────────────────────────────────────────+function mockReq({ method = 'GET', query = {}, headers = {} } = {}) {+ const listeners = {};+ return {+ method,+ query,+ headers,+ url: '/api/irl/interactions-stream',+ on(ev, cb) { (listeners[ev] ||= []).push(cb); return this; },+ emit(ev, ...a) { (listeners[ev] || []).forEach((cb) => cb(...a)); },+ };+}+function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ _h: {},+ setHeader(k, v) { this._h[String(k).toLowerCase()] = v; },+ getHeader(k) { return this._h[String(k).toLowerCase()]; },+ writeHead(status, headers = {}) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(headers)) this._h[String(k).toLowerCase()] = v;+ return this;+ },+ write(chunk) { if (!this.writableEnded) this.body += chunk; return true; },+ end(chunk) { if (chunk) this.body += chunk; this.writableEnded = true; return this; },+ on() { return this; },+ };+}++console.log('1) publicRow() — privacy filter');+{+ const row = {+ id: 'ix1', pin_id: 'pin1', agent_id: 'ag1', type: 'pay',+ message: null, amount: 50000, currency_mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ avatar_name: 'Greeter', caption: 'say hi', lat: 37.76, lng: -122.42,+ created_at: '2026-06-17T00:00:00Z',+ // Hostile/extra fields that must NOT survive the filter:+ viewer_user_id: 'actor-user-uuid', viewer_device: 'actor-device-token',+ owner_id: 'owner-uuid', owner_dev: null,+ payload: { signature: '0x' + 'a'.repeat(64), network: 'base', actorWallet: '0xdeadbeef', secret: 'leak' },+ };+ const safe = publicRow(row);+ check('drops viewer_user_id', !('viewer_user_id' in safe));+ check('drops viewer_device', !('viewer_device' in safe));+ check('drops owner_id/owner_dev', !('owner_id' in safe) && !('owner_dev' in safe));+ check('keeps the receipt signature', safe.payload.signature === row.payload.signature);+ check('keeps the receipt network', safe.payload.network === 'base');+ check('strips actorWallet from payload', !('actorWallet' in safe.payload));+ check('strips arbitrary payload keys', !('secret' in safe.payload));+ check('keeps owner-safe fields (amount, mint, avatar_name)',+ safe.amount === 50000 && safe.currency_mint === row.currency_mint && safe.avatar_name === 'Greeter');++ // A non-pay event must carry an EMPTY payload (no signature surface at all).+ const viewSafe = publicRow({ ...row, type: 'view', payload: { signature: 'x', anything: 1 } });+ check('view/tap payload is emptied (no signature surface)', Object.keys(viewSafe.payload).length === 0);+}++console.log('2) matches() — owner isolation');+{+ const row = { owner_id: 'owner-A', owner_dev: null };+ check('matches the owning session', matches({ ownerId: 'owner-A', ownerDev: null }, row) === true);+ check('rejects a different session', !matches({ ownerId: 'owner-B', ownerDev: null }, row));+ const anonRow = { owner_id: null, owner_dev: 'dev-token-1' };+ check('matches the owning device token', matches({ ownerId: null, ownerDev: 'dev-token-1' }, anonRow) === true);+ check('rejects a different device token', !matches({ ownerId: null, ownerDev: 'dev-token-2' }, anonRow));+ check('a null owner identity never matches a null row owner',+ !matches({ ownerId: null, ownerDev: null }, { owner_id: null, owner_dev: null }));+}++console.log('3) handler — OPTIONS preflight');+{+ const req = mockReq({ method: 'OPTIONS' });+ const res = mockRes();+ await handler(req, res);+ check('preflight is handled (response ended)', res.writableEnded === true);+}++console.log('4) handler — unauthenticated GET is rejected');+{+ const req = mockReq({ method: 'GET', query: {} });+ const res = mockRes();+ await handler(req, res);+ check('401 when no session and no deviceToken', res.statusCode === 401);+ check('error body explains how to authenticate', /sign in or pass deviceToken/.test(res.body));+}++console.log('5) handler — authed GET opens an SSE stream, degrades to heartbeat with no DB');+{+ const req = mockReq({ method: 'GET', query: { deviceToken: 'dev-token-1' } });+ const res = mockRes();+ await handler(req, res);+ check('200 OK', res.statusCode === 200);+ check('content-type is text/event-stream', String(res._h['content-type']).includes('text/event-stream'));+ check('disables Vercel edge buffering (X-Accel-Buffering: no)', res._h['x-accel-buffering'] === 'no');+ check('emits an initial hello frame', /event: hello/.test(res.body));+ // Simulate the client disconnecting — must tear down cleanly, no throw.+ let threw = false;+ try { req.emit('close'); } catch { threw = true; }+ check('clean teardown on client close', threw === false);+}++if (failures) {+ console.error(`\nD3 SMOKE: FAIL (${failures} check${failures === 1 ? '' : 's'})`);+ process.exit(1);+}+console.log('\nD3 SMOKE: PASS');diff --git a/src/agent-detail.js b/src/agent-detail.jsindex b310b036b..e38650c5f 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -94,6 +94,26 @@ function shortAddr(s, head = 4, tail = 4) {return `${str.slice(0, head)}…${str.slice(-tail)}`;}+// Deep-link this agent into /irl. Prefer the avatar id (resolveAvatarUrl reads it+// directly); fall back to the always-real GLB (custom or mannequin) so the body+// is never missing. `agent=` lets /irl pre-focus this agent's pin + inspect card.+function irlHref(agent) {+ const av = agent?.avatar_id || agentAvatarGlb(agent); // agentAvatarGlb never returns empty+ const sp = new URLSearchParams();+ if (av) sp.set('avatar', av);+ if (agent?.id) sp.set('agent', agent.id);+ const q = sp.toString();+ return q ? `/irl?${q}` : '/irl';+}++// Deep-link into /xr. Its resolver takes an avatar id (a raw GLB URL would 404 and+// fall back to the default body), so pass the id when present, else let /xr load+// its default — the link is always live either way.+function xrHref(agent) {+ const id = agent?.avatar_id;+ return id ? `/xr?avatar=${encodeURIComponent(id)}` : '/xr';+}+function el(tag, props = {}, children = []) {const node = document.createElement(tag);for (const [k, v] of Object.entries(props)) {@@ -428,6 +448,15 @@ function render(agent) {const see3d = $('ad-see-3d');if (see3d) see3d.href = seeInWorldHref(agent);+ // "View in IRL" / "View in XR" drop this agent's body into the immersive layer+ // with the pin pre-focused. Every agent has a resolvable body — its own avatar+ // id, or the always-real mannequin GLB — so both links are never dead (same+ // invariant the world link relies on above).+ const irlLink = $('ad-irl-link');+ if (irlLink) irlLink.href = irlHref(agent);+ const xrLink = $('ad-xr-link');+ if (xrLink) xrLink.href = xrHref(agent);+// View switcher: flip this agent between its detail, 3D world, and embed// presentations. Every agent has a 3D body (custom GLB or mannequin).mountViewSwitcher($('view-switch-slot'), {diff --git a/src/dashboard-next/pages/irl-outfit-editor.js b/src/dashboard-next/pages/irl-outfit-editor.jsnew file mode 100644index 000000000..78913d378--- /dev/null+++ b/src/dashboard-next/pages/irl-outfit-editor.js@@ -0,0 +1,332 @@+// Remote Outfit editor (C6) — re-skin a placed agent for every nearby viewer.+//+// Opens from a "My IRL Agents" card. Loads the pin's BASE avatar GLB into a live+// preview and renders the SAME wardrobe machinery the studio uses+// (src/avatar-wardrobe.js): recolour / hide the garment layers the GLB actually+// exposes, plus toggle bone-attached accessories. On Save it PATCHes+// /api/irl/pins { id, avatar_manifest }; the server bakes a new GLB onto the+// base, bumps avatar_version, and every nearby viewer's poll swaps to the new+// look (D1 makes it instant once it lands).+//+// The preview always loads `avatar_base_url ?? avatar_url` — the exact base the+// server bakes onto — so what the owner sees here is byte-for-byte what nearby+// viewers will get. The heavy 3D stack (Three.js via TalkScene + the+// AccessoryManager) is dynamically imported the first time the editor opens, so+// the dashboard's initial bundle stays light.++import { patch } from '../api.js';+import { skeletonHTML, errorStateHTML, emptyStateHTML, ensureStateKitStyles, attachRetry } from '../../shared/state-kit.js';++// Bone-attached presets the owner can stack (hats/glasses/earrings). Morph-based+// "outfit" presets need targets only some rigs expose, so the wardrobe panel's+// recolour/hide of the avatar's own garments is the reliable outfit control here.+const ACCESSORY_KINDS = ['hat', 'glasses', 'earrings'];++// Normalize a pin's stored manifest into the working shape the editor mutates.+function seedManifest(manifest) {+ const m = manifest && typeof manifest === 'object' ? manifest : {};+ return {+ colors: { ...(m.colors || {}) },+ hidden: Array.isArray(m.hidden) ? [...m.hidden] : [],+ accessories: Array.isArray(m.accessories) ? [...m.accessories] : [],+ };+}++// Drop empty branches so a cleared look serializes to {} (which bakes back to the+// bare base server-side) — mirrors avatar-edit's collapseAppearance.+function collapseManifest(working) {+ const out = {};+ if (working.colors && Object.keys(working.colors).length) out.colors = working.colors;+ if (working.hidden && working.hidden.length) out.hidden = working.hidden;+ if (working.accessories && working.accessories.length) out.accessories = working.accessories;+ return out;+}++/**+ * Open the remote Outfit editor for one placed agent.+ * @param {object} opts+ * @param {object} opts.pin the card's pin row (needs id, avatar_url, avatar_base_url, avatar_manifest, avatar_name)+ * @param {(updated:object)=>void} [opts.onSaved] called with the PATCH response pin after a successful save+ */+export async function openOutfitEditor({ pin, onSaved }) {+ ensureStateKitStyles();+ injectStyles();++ const baseUrl = pin.avatar_base_url || pin.avatar_url || null;+ const working = seedManifest(pin.avatar_manifest);++ // ── Modal shell ──────────────────────────────────────────────────────────+ const root = makeNode(`<div class="oe-root" role="presentation">+ <div class="oe-back"></div>+ <div class="oe-modal" role="dialog" aria-modal="true" aria-label="Change outfit">+ <div class="oe-head">+ <div class="oe-titles">+ <div class="oe-title">Change outfit</div>+ <div class="oe-sub">${esc(pin.avatar_name || 'Placed agent')} · updates for everyone nearby</div>+ </div>+ <button class="oe-x" data-close type="button" aria-label="Close">×</button>+ </div>+ <div class="oe-body">+ <div class="oe-stage" data-stage>+ <div class="oe-stage-skel" data-stage-skel><span class="oe-spin" aria-hidden="true"></span><span>Loading avatar…</span></div>+ </div>+ <div class="oe-panel" data-panel>${skeletonHTML(3, 'row')}</div>+ </div>+ <div class="oe-foot">+ <div class="oe-foot-msg" data-msg></div>+ <div class="oe-foot-actions">+ <button class="oe-btn" data-close type="button">Cancel</button>+ <button class="oe-btn primary" data-save type="button" disabled>Apply outfit</button>+ </div>+ </div>+ </div>+ </div>`);++ document.body.appendChild(root);+ document.body.style.overflow = 'hidden';++ const stageEl = root.querySelector('[data-stage]');+ const panelEl = root.querySelector('[data-panel]');+ const saveBtn = root.querySelector('[data-save]');+ const msgEl = root.querySelector('[data-msg]');++ let scene = null;+ let accessoryManager = null;+ let idleDispose = null;+ let presets = [];+ let closed = false;+ let saving = false;++ const setMsg = (text, kind = '') => {+ msgEl.textContent = text || '';+ msgEl.className = `oe-foot-msg${kind ? ' ' + kind : ''}`;+ };+ // Any change (recolour, hide, accessory toggle) makes the look saveable.+ const setDirty = () => {+ if (!saving) { saveBtn.disabled = false; setMsg(''); }+ };++ // ── Teardown ─────────────────────────────────────────────────────────────+ const close = () => {+ if (closed) return;+ closed = true;+ document.removeEventListener('keydown', onKey, true);+ try { idleDispose?.(); } catch { /* tick may already be detached */ }+ try { scene?.unmount(); } catch { /* renderer may not have mounted */ }+ root.remove();+ document.body.style.overflow = '';+ };+ const onKey = (ev) => { if (ev.key === 'Escape' && !saving) close(); };+ document.addEventListener('keydown', onKey, true);+ root.querySelectorAll('[data-close]').forEach((b) => b.addEventListener('click', () => { if (!saving) close(); }));+ root.querySelector('.oe-back').addEventListener('click', () => { if (!saving) close(); });+ setTimeout(() => root.querySelector('[data-close]')?.focus(), 0);++ // No avatar to dress at all → designed empty state, no 3D load.+ if (!baseUrl) {+ stageEl.innerHTML = `<div class="oe-stage-empty">This agent has no 3D avatar to dress.</div>`;+ panelEl.innerHTML = emptyStateHTML({+ compact: true,+ title: 'No avatar attached',+ body: 'Re-place this agent with a 3D avatar, or attach one from the avatars dashboard, to customize its outfit.',+ });+ return;+ }++ // ── Boot the live preview + wardrobe ──────────────────────────────────────+ try {+ const [{ TalkScene }, { AccessoryManager }, wardrobe] = await Promise.all([+ import('../../voice/talk-scene.js'),+ import('../../agent-accessories.js'),+ import('../../avatar-wardrobe.js'),+ ]);+ if (closed) return;++ scene = new TalkScene();+ await scene.mount({ container: stageEl, glbUrl: baseUrl });+ if (closed) { try { scene.unmount(); } catch { /* closed mid-load */ } return; }+ root.querySelector('[data-stage-skel]')?.remove();++ accessoryManager = new AccessoryManager({ content: scene.root, invalidate: () => {} });+ // Seed the preview from the pin's current look (colours/hidden/accessories).+ await accessoryManager.hydrateFromAppearance(collapseManifest(working));++ // Gentle auto-spin so the owner can read the whole avatar without dragging.+ idleDispose = scene.addOnTick?.((dt) => { if (scene?.root) scene.root.rotation.y += dt * 0.35; }) || null;++ // Wardrobe controls — only the slots THIS GLB exposes (same detection+ // contract as the studio). Empty state handled inside renderWardrobePanel.+ wardrobe.renderWardrobePanel({+ container: panelEl,+ root: scene.root,+ working,+ applyLayers: (layers) => accessoryManager?.applyLayers(layers),+ onDirty: setDirty,+ });++ // Accessories ("swap") — bone-attached presets toggled on top of the layers.+ await mountAccessories();+ } catch (err) {+ if (closed) return;+ root.querySelector('[data-stage-skel]')?.remove();+ stageEl.innerHTML = `<div class="oe-stage-empty">Preview unavailable</div>`;+ panelEl.innerHTML = errorStateHTML({+ title: "Couldn't load the avatar",+ body: esc(err?.message || 'Check your connection and try again.'),+ });+ attachRetry(panelEl, () => { close(); openOutfitEditor({ pin, onSaved }); });+ return;+ }++ // ── Accessories picker ─────────────────────────────────────────────────────+ async function mountAccessories() {+ let host = root.querySelector('[data-acc]');+ if (!host) {+ host = makeNode(`<div class="oe-acc" data-acc>+ <div class="oe-acc-h">Accessories</div>+ <div class="oe-acc-grid" data-acc-grid></div>+ </div>`);+ panelEl.appendChild(host);+ }+ const grid = host.querySelector('[data-acc-grid]');+ try {+ const r = await fetch('/accessories/presets.json');+ presets = r.ok ? await r.json() : [];+ } catch { presets = []; }+ const items = presets.filter((p) => ACCESSORY_KINDS.includes(p.kind) && p.glbUrl);+ if (!items.length) { host.remove(); return; }++ const active = new Set(working.accessories);+ grid.innerHTML = items.map((p) => {+ const on = active.has(p.id);+ return `<button class="oe-acc-item${on ? ' on' : ''}" type="button" data-acc-id="${esc(p.id)}" aria-pressed="${on}" title="${esc(p.name)}">+ ${p.thumbnail ? `<img src="${esc(p.thumbnail)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />` : '<span class="oe-acc-ph" aria-hidden="true">✦</span>'}+ <span class="oe-acc-name">${esc(p.name)}</span>+ </button>`;+ }).join('');++ grid.addEventListener('click', async (e) => {+ const btn = e.target.closest('[data-acc-id]');+ if (!btn || saving) return;+ const id = btn.dataset.accId;+ const preset = items.find((p) => p.id === id);+ if (!preset) return;+ const wasOn = btn.getAttribute('aria-pressed') === 'true';+ btn.setAttribute('aria-pressed', String(!wasOn));+ btn.classList.toggle('on', !wasOn);+ try {+ if (wasOn) {+ accessoryManager?.removePreset(id);+ working.accessories = working.accessories.filter((x) => x !== id);+ } else {+ await accessoryManager?.applyPreset(preset);+ if (!working.accessories.includes(id)) working.accessories.push(id);+ }+ setDirty();+ } catch {+ // Roll the toggle back if the GLB couldn't load.+ btn.setAttribute('aria-pressed', String(wasOn));+ btn.classList.toggle('on', wasOn);+ }+ });+ }++ // ── Save → PATCH → bake → propagate ────────────────────────────────────────+ saveBtn.addEventListener('click', async () => {+ if (saving) return;+ saving = true;+ saveBtn.disabled = true;+ saveBtn.textContent = 'Applying outfit…';+ setMsg('Baking the new look…');+ try {+ // Real async — the server bakes a GLB and stores it before responding.+ const res = await patch('/api/irl/pins', { id: pin.id, avatar_manifest: collapseManifest(working) });+ const updated = res?.pin;+ if (!updated) throw new Error('Save failed');+ // Reflect the new state back onto the pin so a second edit re-bakes from+ // the right base and the card preview can refresh.+ pin.avatar_url = updated.avatar_url;+ pin.avatar_manifest = updated.avatar_manifest ?? collapseManifest(working);+ pin.avatar_version = updated.avatar_version;+ saveBtn.textContent = 'Applied ✓';+ setMsg('Saved — nearby viewers will see the new look shortly.', 'ok');+ onSaved?.(updated);+ setTimeout(() => { if (!closed) close(); }, 1100);+ } catch (err) {+ saving = false;+ saveBtn.disabled = false;+ saveBtn.textContent = 'Retry';+ const m = err?.status === 403 ? 'Only the owner can change this agent.'+ : err?.status === 502 ? "The avatar couldn't be baked. Try again."+ : (err?.message || 'Could not save. Try again.');+ setMsg(m, 'err');+ }+ });+}++// ── DOM + style helpers ──────────────────────────────────────────────────────++function makeNode(html) {+ const t = document.createElement('template');+ t.innerHTML = html.trim();+ return t.content.firstElementChild;+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++let _stylesInjected = false;+function injectStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.id = 'oe-css';+ style.textContent = `+ .oe-root { position: fixed; inset: 0; z-index: 1100; display: flex; align-items: center; justify-content: center; padding: 16px; }+ .oe-back { position: absolute; inset: 0; background: rgba(0,0,0,.62); backdrop-filter: blur(2px); animation: oe-fade .16s ease; }+ .oe-modal { position: relative; width: min(880px, 100%); max-height: min(90vh, 760px); display: flex; flex-direction: column; background: var(--nxt-panel, var(--nxt-bg-1, #0d0f15)); border: 1px solid var(--nxt-stroke, #23262f); border-radius: var(--nxt-radius, 14px); box-shadow: 0 24px 64px rgba(0,0,0,.5); animation: oe-rise .2s cubic-bezier(.2,.7,.3,1); overflow: hidden; }+ .oe-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 15px 18px; border-bottom: 1px solid var(--nxt-stroke, #23262f); }+ .oe-title { font-size: 16px; font-weight: 700; color: var(--nxt-ink, #f4f5f7); }+ .oe-sub { font-size: 12px; color: var(--nxt-ink-faint, #8a8f9c); margin-top: 2px; }+ .oe-x { background: none; border: none; color: var(--nxt-ink-faint, #8a8f9c); font-size: 22px; line-height: 1; cursor: pointer; padding: 0 4px; border-radius: 8px; transition: color .14s; }+ .oe-x:hover, .oe-x:focus-visible { color: var(--nxt-ink, #f4f5f7); outline: none; }+ .oe-body { display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); gap: 0; flex: 1; min-height: 0; }+ .oe-stage { position: relative; min-height: 320px; background: radial-gradient(120% 120% at 50% 10%, #161a26 0%, #0a0c12 70%); border-right: 1px solid var(--nxt-stroke, #23262f); overflow: hidden; }+ .oe-stage canvas { display: block; width: 100%; height: 100%; }+ .oe-stage-skel { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; color: var(--nxt-ink-faint, #8a8f9c); font-size: 13px; }+ .oe-stage-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 24px; text-align: center; color: var(--nxt-ink-faint, #8a8f9c); font-size: 13px; line-height: 1.5; }+ .oe-spin { width: 26px; height: 26px; border-radius: 50%; border: 3px solid color-mix(in srgb, var(--nxt-accent, #6ea8fe) 30%, transparent); border-top-color: var(--nxt-accent, #6ea8fe); animation: oe-spin .8s linear infinite; }+ .oe-panel { padding: 16px 18px; overflow-y: auto; }+ .oe-acc { margin-top: 18px; border-top: 1px solid var(--nxt-line, var(--nxt-stroke, #23262f)); padding-top: 14px; }+ .oe-acc-h { font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--nxt-ink-faint, #8a8f9c); margin-bottom: 10px; }+ .oe-acc-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(78px, 1fr)); gap: 8px; }+ .oe-acc-item { display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 8px 6px; border-radius: 10px; border: 1px solid var(--nxt-stroke, #23262f); background: var(--nxt-bg-2, #14171f); color: var(--nxt-ink-dim, #c5c9d3); cursor: pointer; transition: border-color .14s, background .14s, transform .1s; }+ .oe-acc-item:hover { border-color: var(--nxt-stroke-strong, #353a47); transform: translateY(-1px); }+ .oe-acc-item.on { border-color: var(--nxt-accent, #6ea8fe); background: color-mix(in srgb, var(--nxt-accent, #6ea8fe) 12%, var(--nxt-bg-2, #14171f)); }+ .oe-acc-item img { width: 40px; height: 40px; object-fit: contain; }+ .oe-acc-ph { width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; font-size: 18px; color: var(--nxt-ink-faint, #8a8f9c); }+ .oe-acc-name { font-size: 11px; line-height: 1.2; text-align: center; }+ .oe-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 18px; border-top: 1px solid var(--nxt-stroke, #23262f); }+ .oe-foot-msg { font-size: 12px; color: var(--nxt-ink-faint, #8a8f9c); flex: 1; min-width: 0; }+ .oe-foot-msg.ok { color: var(--nxt-success, #4ade80); }+ .oe-foot-msg.err { color: var(--nxt-danger, #f87171); }+ .oe-foot-actions { display: flex; gap: 8px; flex-shrink: 0; }+ .oe-btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: var(--nxt-radius-sm, 9px); border: 1px solid var(--nxt-stroke, #23262f); background: var(--nxt-bg-2, #14171f); color: var(--nxt-ink, #f4f5f7); cursor: pointer; font-size: 13px; font-weight: 600; transition: border-color .14s, transform .12s, opacity .14s; }+ .oe-btn:hover:not(:disabled) { border-color: var(--nxt-stroke-strong, #353a47); transform: translateY(-1px); }+ .oe-btn.primary { background: var(--nxt-accent, #6ea8fe); color: #061018; border-color: transparent; }+ .oe-btn:disabled { opacity: .5; cursor: default; }+ @keyframes oe-fade { from { opacity: 0; } to { opacity: 1; } }+ @keyframes oe-rise { from { opacity: 0; transform: translateY(10px) scale(.99); } to { opacity: 1; transform: none; } }+ @keyframes oe-spin { to { transform: rotate(360deg); } }+ @media (max-width: 680px) {+ .oe-body { grid-template-columns: 1fr; }+ .oe-stage { min-height: 240px; border-right: none; border-bottom: 1px solid var(--nxt-stroke, #23262f); }+ .oe-modal { max-height: 92vh; }+ }+ @media (prefers-reduced-motion: reduce) {+ .oe-back, .oe-modal { animation: none; }+ }+ `;+ document.head.appendChild(style);+}diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.jsindex 3cd114c6b..a76a6449b 100644--- a/src/dashboard-next/pages/irl-placements.js+++ b/src/dashboard-next/pages/irl-placements.js@@ -107,15 +107,6 @@ function statusBadge(status) {+ `<span style="width:7px;height:7px;border-radius:50%;background:${s.c}"></span>${s.label}</span>`;}-// Derive the avatar-editor (wardrobe) URL from a pin's avatar_url. IRL pins store-// either /api/avatars/<id>/glb or /avatars/<id>... — pull the id so "Change outfit"-// deep-links to the real wardrobe; fall back to the avatars dashboard otherwise.-function outfitHref(pin) {- const url = pin.avatar_url || '';- const m = url.match(/\/avatars\/([^/?#]+)/) || url.match(/\/api\/avatars\/([^/?#]+)/);- return m ? `/avatars/${m[1]}/edit` : '/dashboard/avatars';-}-async function reverseGeocode(lat, lng) {try {const r = await fetch(@@ -128,14 +119,79 @@ async function reverseGeocode(lat, lng) {} catch { return null; }}-const INTERACTION_ICON = { view: '👁', message: '💬', pay: '💸' };+// Memoized reverse-geocode shared by the cards and the inbox modal — keeps us+// polite to Nominatim (one lookup per ~11 m cell, not per render).+const geoCache = new Map();+function placeFor(lat, lng) {+ if (lat == null || lng == null) return Promise.resolve(null);+ const key = `${Number(lat).toFixed(4)},${Number(lng).toFixed(4)}`;+ if (!geoCache.has(key)) geoCache.set(key, reverseGeocode(lat, lng));+ return geoCache.get(key);+}++const INTERACTION_ICON = { view: '👁', tap: '👆', message: '💬', pay: '💸' };++// Mints we can name in a pay row. $THREE + Solana USDC come from CURRENCIES;+// Base USDC (an EVM 0x mint) is matched case-insensitively. Anything else renders+// as a truncated mint — we never invent or substitute a coin name.+const PAY_MINTS = {+ 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump': { label: '$THREE', decimals: 6 },+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v': { label: 'USDC', decimals: 6 },+ '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913': { label: 'USDC', decimals: 6 },+};+function payMint(mint) {+ if (!mint) return { label: '', decimals: 6 };+ return PAY_MINTS[mint] || PAY_MINTS[String(mint).toLowerCase()]+ || { label: `${String(mint).slice(0, 4)}…${String(mint).slice(-4)}`, decimals: 6 };+}+// "0.05 USDC" from atomic units + the row's mint. Empty when the amount is absent.+function payAmountLabel(ix) {+ const m = payMint(ix.currency_mint);+ if (ix.amount == null) return m.label;+ const human = (Number(ix.amount) / 10 ** m.decimals).toLocaleString('en-US', { maximumFractionDigits: m.decimals });+ return m.label ? `${human} ${m.label}` : human;+}++// Block-explorer deep link, chain inferred from signature shape / network hint+// (mirrors api/irl/interactions.js explorerTxUrl). Solscan is the default.+const EVM_TX_RE = /^0x[0-9a-fA-F]{64}$/;+function explorerTxUrl(sig, network) {+ if (!sig || typeof sig !== 'string') return null;+ const net = String(network || '').toLowerCase();+ if (EVM_TX_RE.test(sig) || net.includes('base') || net.includes('eip155')) return `https://basescan.org/tx/${sig}`;+ return `https://solscan.io/tx/${sig}`;+}++// Whether a row is the owner's own reply (server-stamped, never client-trusted).+const isOwnerReply = (ix) => ix.payload?.from === 'owner';+// One-line "who did what", with the paid amount inlined for pays.+function ixHeadline(ix) {+ if (ix.type === 'pay') {+ const amt = payAmountLabel(ix);+ return amt ? `Someone paid ${esc(amt)}` : 'Someone paid your agent';+ }+ if (ix.type === 'tap') return 'Tapped your agent';+ if (ix.type === 'message') return isOwnerReply(ix) ? 'You replied' : 'Someone left a message';+ return 'Someone viewed your agent';+}++const EMPTY_IX_HTML = `<div class="irl-ix-empty">No one has interacted with this agent in person yet. Share its location to get discovered.</div>`;++// Compact feed row shown inside each placement card.function interactionLine(ix) {- const icon = INTERACTION_ICON[ix.type] || '•';- const who = ix.type === 'message' ? 'Someone left a message' : ix.type === 'pay' ? 'Someone paid your agent' : 'Someone viewed your agent';- const msg = ix.message ? `<span class="irl-ix-msg">“${esc(ix.message)}”</span>` : '';- return `<div class="irl-ix"><span class="irl-ix-icon" aria-hidden="true">${icon}</span>- <div class="irl-ix-body"><span class="irl-ix-who">${who}</span>${msg}- <span class="irl-ix-time">${esc(relTime(ix.created_at))}</span></div></div>`;+ const owner = isOwnerReply(ix);+ const unread = !ix.seen_at && !owner;+ const icon = INTERACTION_ICON[ix.type] || '•';+ const msg = ix.message ? `<span class="irl-ix-msg">“${esc(ix.message)}”</span>` : '';+ const tx = ix.type === 'pay' ? explorerTxUrl(ix.payload?.signature, ix.payload?.network) : null;+ const txLink = tx ? ` · <a class="irl-ix-link" href="${esc(tx)}" target="_blank" rel="noopener">View tx ↗</a>` : '';+ // Replies are composed in the inbox surface — the card row just opens it.+ const reply = (ix.type === 'message' && !owner)+ ? ` · <button class="irl-ix-link" data-reply-open type="button">Reply</button>` : '';+ return `<div class="irl-ix${owner ? ' owner' : ''}${unread ? ' unread' : ''}">+ <span class="irl-ix-icon" aria-hidden="true">${icon}</span>+ <div class="irl-ix-body"><span class="irl-ix-who">${ixHeadline(ix)}</span>${msg}+ <span class="irl-ix-time">${esc(relTime(ix.created_at))}${txLink}${reply}</span></div></div>`;}const STYLE = `@@ -153,7 +209,6 @@ const STYLE = `/* Skills chips */.irl-skills { display: flex; flex-wrap: wrap; gap: 6px; }.irl-skill { font-size: 11px; padding: 3px 9px; border-radius: 999px; background: color-mix(in srgb, #7c3aed 12%, transparent); color: #a78bfa; border: 1px solid color-mix(in srgb, #7c3aed 30%, transparent); white-space: nowrap; }-.irl-unread-pill { font-size: 12px; font-weight: 700; padding: 3px 9px; border-radius: 999px; background: color-mix(in srgb, var(--nxt-accent) 16%, transparent); color: var(--nxt-accent); border: 1px solid color-mix(in srgb, var(--nxt-accent) 32%, transparent); }.irl-btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 16px; border-radius: var(--nxt-radius-sm); border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); color: var(--nxt-ink); cursor: pointer; font-size: 13px; font-weight: 600; text-decoration: none; transition: border-color .14s, transform .12s; }.irl-btn:hover { border-color: var(--nxt-stroke-strong); transform: translateY(-1px); }.irl-btn.primary { background: var(--nxt-accent); color: #061018; border-color: transparent; }@@ -245,12 +300,17 @@ const STYLE = `@keyframes irl-rise { from { opacity: 0; transform: translateY(10px) scale(.99); } to { opacity: 1; transform: none; } }/* Interactions feed */-.irl-ix { display: flex; gap: 9px; padding: 6px 0; }+.irl-ix { display: flex; gap: 9px; padding: 6px 0; position: relative; }+.irl-ix.unread { padding-left: 12px; }+.irl-ix.unread::before { content: ''; position: absolute; left: 0; top: 12px; width: 6px; height: 6px; border-radius: 50%; background: var(--nxt-accent); }+.irl-ix.owner .irl-ix-who { color: var(--nxt-accent); }.irl-ix-icon { font-size: 14px; line-height: 1.4; flex-shrink: 0; }.irl-ix-body { display: flex; flex-direction: column; gap: 1px; font-size: 13px; min-width: 0; }.irl-ix-who { color: var(--nxt-ink-dim); }.irl-ix-msg { color: var(--nxt-ink); }-.irl-ix-time { font-size: 11px; color: var(--nxt-ink-faint); }+.irl-ix-time { font-size: 11px; color: var(--nxt-ink-faint); display: flex; flex-wrap: wrap; gap: 2px 4px; align-items: center; }+.irl-ix-link { background: none; border: none; padding: 0; font: inherit; font-size: 11px; color: var(--nxt-accent); cursor: pointer; text-decoration: none; }+.irl-ix-link:hover { text-decoration: underline; }.irl-ix-empty { font-size: 12px; color: var(--nxt-ink-faint); }/* Caption + management */@@ -265,19 +325,117 @@ const STYLE = `.irl-action.remove { color: var(--nxt-danger, #f87171); border-color: color-mix(in srgb, var(--nxt-danger, #f87171) 30%, transparent); }.irl-action.remove:hover { background: color-mix(in srgb, var(--nxt-danger, #f87171) 8%, transparent); }-/* Location editor */-.irl-loc-edit { border-top: 1px dashed var(--nxt-stroke); padding: 12px 16px; display: none; gap: 10px; flex-wrap: wrap; align-items: flex-end; }-.irl-loc-edit.open { display: flex; }+/* ── Location map modal ──────────────────────────────────────────────────── */+.irlmap-modal .irl-modal-body { padding: 0; }+.irlmap { position: relative; width: 100%; height: 340px; background: var(--nxt-bg-2); z-index: 0; }+.irlmap-canvas { position: absolute; inset: 0; }+.irlmap-skel { position: absolute; inset: 0; z-index: 600; display: flex; align-items: center; justify-content: center; gap: 10px; background: var(--nxt-bg-2); color: var(--nxt-ink-faint); font-size: 13px; transition: opacity .3s; }+.irlmap-skel.gone { opacity: 0; pointer-events: none; }+.irlmap-spin { width: 18px; height: 18px; border-radius: 50%; border: 2px solid var(--nxt-stroke); border-top-color: var(--nxt-accent); animation: irl-spin .8s linear infinite; }+@keyframes irl-spin { to { transform: rotate(360deg); } }+@media (max-width: 520px) { .irlmap { height: 280px; } }++/* Leaflet dark-theme touch-ups (zoom + attribution) */+.irlmap .leaflet-control-zoom a { background: var(--nxt-bg-1); color: var(--nxt-ink); border-color: var(--nxt-stroke); }+.irlmap .leaflet-control-zoom a:hover { background: var(--nxt-bg-2); }+.irlmap .leaflet-bar { border-color: var(--nxt-stroke); box-shadow: 0 1px 5px rgba(0,0,0,.5); }+.irlmap .leaflet-control-attribution { background: rgba(8,10,16,.7); color: #99a; font-size: 10px; }+.irlmap .leaflet-control-attribution a { color: #9cf; }+.irlmap .leaflet-marker-icon.irlmap-pin { background: none; border: none; }++/* Custom GPS markers */+.irlmap-marker { position: relative; width: 40px; height: 40px; }+.irlmap-dot { position: absolute; inset: 7px; border-radius: 50%; background: linear-gradient(135deg, #1a2035, #0d1018); border: 2px solid var(--nxt-ink-faint); display: flex; align-items: center; justify-content: center; overflow: hidden; font-size: 13px; box-shadow: 0 2px 6px rgba(0,0,0,.55); transition: border-color .15s, box-shadow .15s; }+.irlmap-dot img { width: 100%; height: 100%; object-fit: cover; }+.irlmap-marker.is-focused .irlmap-dot { border-color: var(--nxt-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--nxt-accent) 28%, transparent), 0 3px 10px rgba(0,0,0,.6); }+.irlmap-marker:not(.is-focused) { cursor: pointer; opacity: .82; transition: opacity .15s; }+.irlmap-marker:not(.is-focused):hover { opacity: 1; }+.irlmap-heading { position: absolute; inset: 0; pointer-events: none; transform-origin: 50% 50%; transition: transform .1s linear; }+.irlmap-heading i { position: absolute; top: -4px; left: 50%; margin-left: -5px; width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 9px solid var(--nxt-ink-faint); filter: drop-shadow(0 1px 1px rgba(0,0,0,.5)); }+.irlmap-marker.is-focused .irlmap-heading i { border-bottom-color: var(--nxt-accent); }++/* Heading dial + locate controls */+.irlmap-controls { display: flex; align-items: center; gap: 14px; padding: 12px 16px; border-top: 1px solid var(--nxt-stroke); flex-wrap: wrap; }+.irlmap-compass { width: 58px; height: 58px; flex-shrink: 0; cursor: grab; touch-action: none; border-radius: 50%; }+.irlmap-compass:active { cursor: grabbing; }+.irlmap-compass:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }+.irlmap-compass svg { width: 100%; height: 100%; display: block; }+.irlmap-compass .ring { fill: var(--nxt-bg-2); stroke: var(--nxt-stroke); stroke-width: 3; }+.irlmap-compass .tick { stroke: var(--nxt-ink-faint); stroke-width: 2; }+.irlmap-compass .lbl { fill: var(--nxt-ink-faint); font: 700 15px/1 system-ui, sans-serif; text-anchor: middle; dominant-baseline: central; }+.irlmap-compass .lbl.n { fill: var(--nxt-accent); }+.irlmap-compass .needle { fill: var(--nxt-accent); }+.irlmap-headbox { display: flex; flex-direction: column; gap: 4px; }+.irlmap-headbox > span { font-size: 10px; text-transform: uppercase; letter-spacing: .05em; color: var(--nxt-ink-faint); }+.irlmap-headrow { display: flex; align-items: center; gap: 8px; }+.irlmap-headrow input { width: 72px; background: var(--nxt-bg-2); border: 1px solid var(--nxt-stroke); border-radius: 7px; color: var(--nxt-ink); padding: 6px 9px; font-size: 13px; font-family: inherit; outline: none; font-variant-numeric: tabular-nums; }+.irlmap-headrow input:focus { border-color: var(--nxt-accent); }+.irlmap-headrow .cmp { font-size: 14px; font-weight: 700; color: var(--nxt-ink); min-width: 30px; }+.irlmap-controls .grow { flex: 1; }++/* Save bar — appears on drag / heading change */+.irlmap-savebar { display: none; align-items: center; gap: 10px 12px; padding: 12px 16px; border-top: 1px solid var(--nxt-stroke); background: color-mix(in srgb, var(--nxt-accent) 7%, transparent); flex-wrap: wrap; animation: irl-fade .16s ease; }+.irlmap-savebar.open { display: flex; }+.irlmap-savebar .lbl { flex: 1; min-width: 170px; font-size: 13px; color: var(--nxt-ink-dim); line-height: 1.45; }+.irlmap-savebar .lbl b { color: var(--nxt-ink); }+.irlmap-savebar .locating { opacity: .6; }+.irlmap-savebar .err { flex-basis: 100%; font-size: 12px; color: var(--nxt-danger, #f87171); }++/* Modal footer: hint + remove */+.irlmap-foot { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; border-top: 1px solid var(--nxt-stroke); flex-wrap: wrap; }+.irlmap-hint { font-size: 12px; color: var(--nxt-ink-faint); flex: 1; min-width: 150px; }++/* CDN-failure fallback — manual coordinate entry */+.irlmap-fallback { padding: 4px 18px 18px; }+.irlmap-fallback .row { display: flex; gap: 10px; flex-wrap: wrap; align-items: flex-end; margin-top: 14px; }+.irlmap-fallback .fb-err { font-size: 12px; color: var(--nxt-danger, #f87171); margin-top: 10px; }.irl-loc-field { display: flex; flex-direction: column; gap: 4px; }.irl-loc-field label { font-size: 10px; text-transform: uppercase; letter-spacing: .05em; color: var(--nxt-ink-faint); }-.irl-loc-field input { width: 110px; background: var(--nxt-bg-2); border: 1px solid var(--nxt-stroke); border-radius: 7px; color: var(--nxt-ink); padding: 6px 9px; font-size: 13px; font-family: inherit; outline: none; font-variant-numeric: tabular-nums; }+.irl-loc-field input { width: 120px; background: var(--nxt-bg-2); border: 1px solid var(--nxt-stroke); border-radius: 7px; color: var(--nxt-ink); padding: 7px 9px; font-size: 13px; font-family: inherit; outline: none; font-variant-numeric: tabular-nums; }.irl-loc-field input:focus { border-color: var(--nxt-accent); }-.irl-loc-field.heading input { width: 78px; }+.irl-loc-field.heading input { width: 86px; }.irl-empty { text-align: center; padding: 60px 20px; color: var(--nxt-ink-faint); }.irl-empty b { display: block; font-size: 16px; color: var(--nxt-ink); margin-bottom: 8px; }.irl-skel { height: 120px; border-radius: var(--nxt-radius); background: var(--nxt-bg-2); animation: irl-pulse 1.4s ease infinite; }@keyframes irl-pulse { 0%,100%{opacity:.55} 50%{opacity:1} }++/* Header actions + inbox button */+.irl-header-actions { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }+#irl-inbox-btn { position: relative; }+.irl-inbox-badge { display: inline-flex; align-items: center; justify-content: center; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 999px; background: var(--nxt-accent); color: #061018; font-size: 11px; font-weight: 800; line-height: 1; font-variant-numeric: tabular-nums; }++/* Per-card unread chip */+.irl-card-unread { font-size: 10.5px; font-weight: 700; padding: 2px 7px; border-radius: 999px; background: color-mix(in srgb, var(--nxt-accent) 18%, transparent); color: var(--nxt-accent); border: 1px solid color-mix(in srgb, var(--nxt-accent) 34%, transparent); white-space: nowrap; flex-shrink: 0; }++/* ── Inbox modal feed ─────────────────────────────────────────────────────── */+.irl-inbox-list { display: flex; flex-direction: column; }+.irl-inbox-row { display: flex; gap: 11px; padding: 12px 2px; border-bottom: 1px solid var(--nxt-line, var(--nxt-stroke)); position: relative; }+.irl-inbox-row:last-child { border-bottom: none; }+.irl-inbox-row.unread { padding-left: 14px; }+.irl-inbox-row.unread::before { content: ''; position: absolute; left: 0; top: 17px; width: 7px; height: 7px; border-radius: 50%; background: var(--nxt-accent); }+.irl-inbox-row.owner { padding-left: 14px; border-left: 2px solid color-mix(in srgb, var(--nxt-accent) 45%, transparent); margin-left: 2px; }+.irl-inbox-icon { font-size: 18px; line-height: 1.3; flex-shrink: 0; }+.irl-inbox-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px; }+.irl-inbox-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }+.irl-inbox-who { font-size: 14px; font-weight: 600; color: var(--nxt-ink); }+.irl-inbox-row.owner .irl-inbox-who { color: var(--nxt-accent); }+.irl-inbox-time { font-size: 11.5px; color: var(--nxt-ink-faint); white-space: nowrap; flex-shrink: 0; }+.irl-inbox-msg { font-size: 13px; color: var(--nxt-ink); line-height: 1.45; }+.irl-inbox-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 10px; font-size: 12px; color: var(--nxt-ink-faint); }+.irl-inbox-agent { color: var(--nxt-ink-dim); }+.irl-inbox-place { color: var(--nxt-ink-faint); }+.irl-inbox-action { background: none; border: none; padding: 0; font: inherit; font-size: 12px; font-weight: 600; color: var(--nxt-accent); cursor: pointer; text-decoration: none; }+.irl-inbox-action:hover { text-decoration: underline; }++/* Reply composer (inline in an inbox row) */+.irl-reply-box { margin-top: 8px; display: flex; flex-direction: column; gap: 8px; animation: irl-fade .14s ease; }+.irl-reply-input { width: 100%; resize: vertical; min-height: 38px; background: var(--nxt-bg-2); border: 1px solid var(--nxt-accent); border-radius: 9px; color: var(--nxt-ink); padding: 8px 10px; font: inherit; font-size: 13px; outline: none; }+.irl-reply-actions { display: flex; align-items: center; gap: 10px; justify-content: flex-end; }+.irl-reply-hint { flex: 1; font-size: 12px; color: var(--nxt-ink-dim); }+.irl-reply-hint.ok { color: var(--nxt-success); }+.irl-reply-hint.err { color: var(--nxt-danger, #f87171); }+.irl-inbox-flash { margin: 4px 0 10px; padding: 9px 12px; border-radius: 9px; font-size: 12.5px; font-weight: 600; color: var(--nxt-success); background: color-mix(in srgb, var(--nxt-success) 10%, transparent); border: 1px solid color-mix(in srgb, var(--nxt-success) 28%, transparent); }</style>`;let userPos = null;@@ -294,6 +452,20 @@ function metaLine(pin, geo) {return `📍 ${loc}${dist}${dir}`;}+// ── Live inbox state (shared by the cards, the header badge, the poll loop, and+// the inbox modal) ──────────────────────────────────────────────────────────+const inbox = { interactions: [], unread: 0 };+let rootEl = null; // the page root, for header/banner queries+let listEl = null; // the placement-cards container+let pollTimer = null;+let inboxModal = null; // { refresh(rows), isComposing() } while the modal is open++// Unread = a visitor row not yet seen. The owner's own replies are excluded —+// they're authored, never "unread", so they must not light a badge.+function unreadForPin(pinId, list = inbox.interactions) {+ return list.filter((x) => x.pin_id === pinId && !x.seen_at && !isOwnerReply(x)).length;+}+function cardHtml(pin, ixList) {const caption = pin.caption || '';const img = pin.avatar_url@@ -302,9 +474,8 @@ function cardHtml(pin, ixList) {const visitors = Number(pin.view_count) || 0;const pinIx = ixList.filter((x) => x.pin_id === pin.id).slice(0, 4);- const ixHtml = pinIx.length- ? pinIx.map(interactionLine).join('')- : `<div class="irl-ix-empty">No one has interacted with this agent in person yet. Share its location to get discovered.</div>`;+ const ixHtml = pinIx.length ? pinIx.map(interactionLine).join('') : EMPTY_IX_HTML;+ const unread = unreadForPin(pin.id, ixList);// Stat chips — balance & reputation fill in async (skeleton until then).const agentStats = pin.agent_id ? `@@ -320,6 +491,7 @@ function cardHtml(pin, ixList) {<div class="irl-name-row" style="display:flex;align-items:center;gap:8px;min-width:0"><span class="irl-name">${esc(pin.avatar_name || 'Placed agent')}</span>${statusBadge(pin.status)}+ <span class="irl-card-unread" data-card-unread title="Unread interactions"${unread ? '' : ' hidden'}>${unread} new</span></div><div class="irl-meta"><span class="irl-meta-loc">${esc(metaLine(pin, null))}</span>@@ -330,8 +502,8 @@ function cardHtml(pin, ixList) {<div class="irl-stats">${agentStats}- <div class="irl-stat"><span class="k">Interactions</span><span class="v">${Number(pin.interaction_count) || visitors}</span></div>- <div class="irl-stat"><span class="k">Last seen</span><span class="v" style="font-size:12.5px">${esc(pin.last_interaction_at ? relTime(pin.last_interaction_at) : 'No visits')}</span></div>+ <div class="irl-stat" data-stat="interactions"><span class="k">Interactions</span><span class="v">${Number(pin.interaction_count) || visitors}</span></div>+ <div class="irl-stat" data-stat="lastseen"><span class="k">Last seen</span><span class="v" style="font-size:12.5px">${esc(pin.last_interaction_at ? relTime(pin.last_interaction_at) : 'No visits')}</span></div></div><div class="irl-section" data-skills-section hidden>@@ -354,33 +526,33 @@ function cardHtml(pin, ixList) {<div class="irl-card-body"><div class="irl-caption" data-caption="${esc(caption)}" title="Click to edit caption">${caption ? esc(caption) : '<span style="color:var(--nxt-ink-faint);font-style:italic">Add a caption…</span>'}</div><div class="irl-actions">- <a class="irl-action" href="${esc(outfitHref(pin))}" target="_blank" rel="noopener">Change outfit ↗</a>- <button class="irl-action" data-loc-toggle>Move / re-aim</button>+ <button class="irl-action" data-outfit="${esc(pin.id)}">Change outfit</button>+ <button class="irl-action" data-loc-toggle>Move on map</button><a class="irl-action" href="/irl?highlight=${esc(pin.id)}" target="_blank" rel="noopener">View in IRL ↗</a><button class="irl-action remove" data-remove="${esc(pin.id)}">Remove</button></div></div>-- <div class="irl-loc-edit" data-loc-edit>- <div class="irl-loc-field"><label>Latitude</label><input type="number" step="0.00001" data-loc="lat" value="${esc(Number(pin.lat).toFixed(5))}" /></div>- <div class="irl-loc-field"><label>Longitude</label><input type="number" step="0.00001" data-loc="lng" value="${esc(Number(pin.lng).toFixed(5))}" /></div>- <div class="irl-loc-field heading"><label>Heading°</label><input type="number" min="0" max="359" step="1" data-loc="heading" value="${esc(Math.round(pin.heading ?? 0))}" /></div>- <button class="irl-action" data-loc-here>Use my location</button>- <button class="irl-btn primary" data-loc-save>Save location</button>- </div></div>`;}async function mount(el) {+ rootEl = el;el.innerHTML = STYLE + `<div class="irl-wrap"><div class="irl-header">- <h2>My IRL Agents <span class="irl-unread-pill" id="irl-unread" hidden></span></h2>- <a class="irl-btn primary" href="/irl" id="irl-place-btn">+ Place new ↗</a>+ <h2>My IRL Agents</h2>+ <div class="irl-header-actions">+ <button class="irl-btn" id="irl-inbox-btn" type="button" aria-haspopup="dialog">+ <span aria-hidden="true">📥</span> Inbox+ <span class="irl-inbox-badge" id="irl-inbox-badge" hidden></span>+ </button>+ <a class="irl-btn primary" href="/irl" id="irl-place-btn">+ Place new ↗</a>+ </div></div><div id="irl-mp-banner"></div><div id="irl-banner"></div><div id="irl-list"></div></div>`;+ el.querySelector('#irl-inbox-btn')?.addEventListener('click', openInboxModal);// Multiplayer AR explainer — shown once at the top so owners understand// that their placed agents are visible to ALL users who visit that location.@@ -391,11 +563,12 @@ async function mount(el) {</div>`;const list = el.querySelector('#irl-list');+ listEl = list;list.innerHTML = skeletonHTML(3, 'row');// Pins + interactions in parallel — interactions power both the banner and// each card's IRL feed.- let pins, interactions = [], unread = 0;+ let pins;try {const [sumData, ixData] = await Promise.all([get('/api/irl/agent-summary?mine=1'),@@ -405,8 +578,8 @@ async function mount(el) {// (status, interaction_count, last_interaction_at). Normalize pin_id→id so// the existing card code is unchanged.pins = (sumData.agents || []).map((a) => ({ ...a, id: a.pin_id }));- interactions = ixData.interactions || [];- unread = ixData.unread || 0;+ inbox.interactions = ixData.interactions || [];+ inbox.unread = ixData.unread || 0;} catch {list.innerHTML = errorStateHTML({ title: "Couldn't load your IRL agents", body: 'Check your connection and try again.', scope: 'irl' });attachRetry(list, () => mount(el));@@ -424,32 +597,18 @@ async function mount(el) {return;}- // Unread banner + pill- const unreadEl = el.querySelector('#irl-unread');- if (unread > 0) {- unreadEl.textContent = `${unread} new`;- unreadEl.hidden = false;- el.querySelector('#irl-banner').innerHTML = `<div class="irl-feed-banner">- <span class="txt"><b>${unread}</b> ${unread === 1 ? 'person' : 'people'} interacted with your agents in real life.</span>- <button class="irl-btn" id="irl-mark-seen">Mark all seen</button>- </div>`;- el.querySelector('#irl-mark-seen')?.addEventListener('click', async (e) => {- e.target.disabled = true;- await patch('/api/irl/interactions', {}).catch(() => {});- unreadEl.hidden = true;- el.querySelector('#irl-banner').innerHTML = '';- });- }+ renderBanner();- list.innerHTML = pins.map((p) => cardHtml(p, interactions)).join('');+ list.innerHTML = pins.map((p) => cardHtml(p, inbox.interactions)).join('');+ applyBadges();// ── Async enrichment per card: balance, reputation, services, geocode ──────for (const pin of pins) {const card = list.querySelector(`[data-id="${pin.id}"]`);if (!card) continue;- // Reverse-geocode the location label (serial, polite to Nominatim).- reverseGeocode(pin.lat, pin.lng).then((geo) => {+ // Reverse-geocode the location label (cached + polite to Nominatim).+ placeFor(pin.lat, pin.lng).then((geo) => {if (geo) {const locEl = card.querySelector('.irl-meta-loc');if (locEl) locEl.textContent = metaLine(pin, geo);@@ -501,6 +660,219 @@ async function mount(el) {}wireCardEvents(list, pins);+ startPolling();+ startLiveStream(); // D3 — upgrade the poll to instant realtime delivery+}++// ── Live header badge, per-card chips, and the "new interactions" banner ─────+function applyBadges() {+ const badge = rootEl?.querySelector('#irl-inbox-badge');+ if (badge) {+ if (inbox.unread > 0) { badge.textContent = String(inbox.unread); badge.hidden = false; }+ else { badge.hidden = true; }+ }+ listEl?.querySelectorAll('.irl-card').forEach((card) => {+ const chip = card.querySelector('[data-card-unread]');+ if (!chip) return;+ const n = unreadForPin(card.dataset.id);+ if (n > 0) { chip.textContent = `${n} new`; chip.hidden = false; }+ else { chip.hidden = true; }+ });+}++function renderBanner() {+ const host = rootEl?.querySelector('#irl-banner');+ if (!host) return;+ if (inbox.unread > 0) {+ host.innerHTML = `<div class="irl-feed-banner">+ <span class="txt"><b>${inbox.unread}</b> ${inbox.unread === 1 ? 'person' : 'people'} interacted with your agents in real life.</span>+ <button class="irl-btn" data-inbox-open type="button">Open inbox →</button>+ </div>`;+ host.querySelector('[data-inbox-open]')?.addEventListener('click', openInboxModal);+ } else {+ host.innerHTML = '';+ }+}++// Re-render one card's compact feed + its "Last seen" chip from current state.+function refreshCardFeed(pinId) {+ const card = listEl?.querySelector(`[data-id="${CSS.escape(pinId)}"]`);+ if (!card) return;+ const host = card.querySelector('[data-ix-list]');+ if (host) {+ const pinIx = inbox.interactions.filter((x) => x.pin_id === pinId).slice(0, 4);+ host.innerHTML = pinIx.length ? pinIx.map(interactionLine).join('') : EMPTY_IX_HTML;+ }+ const last = inbox.interactions+ .filter((x) => x.pin_id === pinId)+ .reduce((acc, x) => Math.max(acc, new Date(x.created_at).getTime() || 0), 0);+ const seenEl = card.querySelector('[data-stat="lastseen"] .v');+ if (seenEl && last > 0) seenEl.textContent = relTime(new Date(last).toISOString());+}++// ── Poll loop ────────────────────────────────────────────────────────────────+// D1/D3 will replace this with realtime push; until then a 20 s pull keeps the+// dashboard alive. We pause in background tabs (no point burning Nominatim/Neon+// when no one's looking) and tear down on navigation away.+const POLL_MS = 20_000;+function startPolling() {+ stopPolling();+ pollTimer = setInterval(() => {+ if (document.visibilityState === 'visible') pollOnce();+ }, POLL_MS);+ window.addEventListener('pagehide', stopPolling, { once: true });+}+function stopPolling() {+ if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }+}+async function pollOnce() {+ let data;+ try { data = await get('/api/irl/interactions?mine=1'); }+ catch { return; } // transient — the next tick retries+ inbox.interactions = data.interactions || [];+ inbox.unread = data.unread || 0;+ listEl?.querySelectorAll('.irl-card').forEach((card) => refreshCardFeed(card.dataset.id));+ applyBadges();+ renderBanner();+ // Keep an open inbox current — but never yank a half-typed reply out from+ // under the owner.+ if (inboxModal && !inboxModal.isComposing()) inboxModal.refresh(inbox.interactions);+}++// ── D3 · realtime owner delivery ─────────────────────────────────────────────+// The 20 s poll above is the floor that keeps the inbox alive everywhere; this+// SSE stream (GET /api/irl/interactions-stream) makes a tap / message / pay on a+// placed agent land in the open dashboard within ~1 s — the owner gets the+// dopamine of "someone engaged my agent right now" even from the other side of+// the world. Each live event triggers one authoritative pollOnce() (so unread+// counts and the open modal stay exactly server-correct) plus an instant flash ++// toast on the agent that was touched. EventSource auto-reconnects; if the stream+// is unavailable (blocked, offline, no infra) the poll alone keeps the inbox+// live, just slower — degrade the flourish, never the record.+let liveStream = null;+let liveNudge = null;++function startLiveStream() {+ stopLiveStream();+ ensureLiveStyles();+ let es;+ try { es = new EventSource('/api/irl/interactions-stream', { withCredentials: true }); }+ catch { return; } // EventSource unsupported → the 20 s poll still covers us+ liveStream = es;+ es.addEventListener('interaction', (e) => {+ let ix; try { ix = JSON.parse(e.data); } catch { return; }+ flashInteraction(ix);+ // Coalesce a burst of events into a single authoritative refresh.+ clearTimeout(liveNudge);+ liveNudge = setTimeout(() => { if (document.visibilityState === 'visible') pollOnce(); }, 350);+ });+ es.addEventListener('open', () => setLivePill('live'));+ es.addEventListener('error', () => setLivePill('polling')); // EventSource retries on its own+ window.addEventListener('pagehide', stopLiveStream, { once: true });+}++function stopLiveStream() {+ if (liveStream) { try { liveStream.close(); } catch { /* already torn down */ } liveStream = null; }+ if (liveNudge) { clearTimeout(liveNudge); liveNudge = null; }+}++// Instant per-card feedback the moment an interaction streams in: a soft accent+// flash on the touched agent, and a toast for the high-signal events (pay /+// message — never the chatty view/tap). Pure box-shadow/opacity, auto-cleaned.+const IX_TOAST = {+ pay: '💸 Someone just paid your agent',+ message: '💬 New message from a visitor',+ tap: '👆 Someone tapped your agent',+ view: '👁 Someone is viewing your agent',+};+function flashInteraction(ix) {+ const card = ix.pin_id && listEl?.querySelector(`[data-id="${CSS.escape(ix.pin_id)}"]`);+ if (card) {+ card.classList.remove('irl-flash');+ void card.offsetWidth; // restart the animation even if one is mid-flight+ card.classList.add('irl-flash');+ card.addEventListener('animationend', () => card.classList.remove('irl-flash'), { once: true });+ }+ if (ix.type === 'pay' || ix.type === 'message') {+ const who = ix.avatar_name ? ` · ${ix.avatar_name}` : '';+ irlToast((IX_TOAST[ix.type] || 'New IRL interaction') + who);+ }+}++// A "Live" / "Polling" pill in the header — green when the realtime stream is+// connected, muted when we've fallen back to the poll. Created lazily so it never+// depends on render order; a no-op if the header isn't present.+function setLivePill(state) {+ const actions = rootEl?.querySelector('.irl-header-actions');+ if (!actions) return;+ let pill = actions.querySelector('#irl-live-pill');+ if (!pill) {+ pill = document.createElement('span');+ pill.id = 'irl-live-pill';+ pill.className = 'irl-live-pill';+ actions.prepend(pill);+ }+ const live = state === 'live';+ pill.classList.toggle('on', live);+ pill.innerHTML = `<i aria-hidden="true"></i>${live ? 'Live' : 'Polling'}`;+ pill.title = live+ ? 'Connected — interactions appear the instant they happen.'+ : 'Reconnecting — interactions still arrive, just on a short delay.';+}++// Lightweight toast scoped to this page (bottom-center, auto-dismiss, stacking).+function irlToast(msg) {+ let host = document.getElementById('irl-toast-host');+ if (!host) {+ host = document.createElement('div');+ host.id = 'irl-toast-host';+ host.className = 'irl-toast-host';+ host.setAttribute('role', 'status');+ host.setAttribute('aria-live', 'polite');+ document.body.appendChild(host);+ }+ const t = document.createElement('div');+ t.className = 'irl-toast';+ t.textContent = msg;+ host.appendChild(t);+ requestAnimationFrame(() => t.classList.add('show'));+ setTimeout(() => {+ t.classList.remove('show');+ t.addEventListener('transitionend', () => t.remove(), { once: true });+ }, 4200);+}++// D3 styles injected once into <head> so we never have to edit the page's big+// STYLE template (shared, and edited by sibling surfaces) — keeps this layer+// self-contained. Honors prefers-reduced-motion: no animation, just the colour.+let _liveStylesInjected = false;+function ensureLiveStyles() {+ if (_liveStylesInjected || document.getElementById('irl-live-styles')) return;+ _liveStylesInjected = true;+ const s = document.createElement('style');+ s.id = 'irl-live-styles';+ s.textContent = `+ .irl-card.irl-flash { animation: irl-flash 1.25s cubic-bezier(.2,.7,.3,1); }+ @keyframes irl-flash {+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--nxt-accent) 55%, transparent); }+ 30% { box-shadow: 0 0 0 3px color-mix(in srgb, var(--nxt-accent) 40%, transparent); }+ 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--nxt-accent) 0%, transparent); }+ }+ .irl-live-pill { display: inline-flex; align-items: center; gap: 6px; padding: 3px 9px; border-radius: 999px; font-size: 11px; font-weight: 700; letter-spacing: .02em; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-faint); background: var(--nxt-bg-2); user-select: none; }+ .irl-live-pill i { width: 6px; height: 6px; border-radius: 50%; background: var(--nxt-ink-faint); flex-shrink: 0; }+ .irl-live-pill.on { color: var(--nxt-success); border-color: color-mix(in srgb, var(--nxt-success) 34%, transparent); background: color-mix(in srgb, var(--nxt-success) 9%, transparent); }+ .irl-live-pill.on i { background: var(--nxt-success); animation: irl-live-ping 2s ease-out infinite; }+ @keyframes irl-live-ping { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--nxt-success) 60%, transparent); } 70%,100% { box-shadow: 0 0 0 5px color-mix(in srgb, var(--nxt-success) 0%, transparent); } }+ .irl-toast-host { position: fixed; left: 50%; bottom: 24px; transform: translateX(-50%); z-index: 1200; display: flex; flex-direction: column; gap: 8px; align-items: center; pointer-events: none; }+ .irl-toast { pointer-events: auto; max-width: min(92vw, 420px); padding: 11px 16px; border-radius: 12px; background: var(--nxt-panel, #11151f); color: var(--nxt-ink); border: 1px solid var(--nxt-stroke); box-shadow: 0 14px 40px rgba(0,0,0,.45); font-size: 13px; font-weight: 600; opacity: 0; transform: translateY(10px) scale(.98); transition: opacity .22s ease, transform .22s cubic-bezier(.2,.7,.3,1); }+ .irl-toast.show { opacity: 1; transform: none; }+ @media (prefers-reduced-motion: reduce) {+ .irl-card.irl-flash { animation: none; }+ .irl-live-pill.on i { animation: none; }+ .irl-toast { transition: opacity .2s ease; transform: none; }+ }+ `;+ document.head.appendChild(s);}function fillStat(card, key, value) {@@ -543,11 +915,44 @@ function renderServices(card, services) {}function wireCardEvents(list, pins) {+ // Remove a card from the DOM (after its pin is deleted server-side) and drop+ // it from the in-memory list; fall back to the empty state when none remain.+ function dropCard(id) {+ list.querySelector(`[data-id="${CSS.escape(id)}"]`)?.remove();+ const idx = pins.findIndex((p) => p.id === id);+ if (idx >= 0) pins.splice(idx, 1);+ if (!list.querySelector('.irl-card')) {+ list.innerHTML = `<div class="irl-empty"><b>No placements</b>All agents removed. <a class="irl-btn" href="/irl" style="display:inline-flex;margin-top:12px">Place a new one →</a></div>`;+ }+ }++ // Reflect a persisted relocation back into the C1 card: update the stored pin,+ // the data-* attributes, and the visible location/heading label in place.+ function onSaved(saved, label) {+ const pin = pins.find((p) => p.id === saved.id);+ if (pin) { pin.lat = saved.lat; pin.lng = saved.lng; pin.heading = saved.heading; }+ const card = list.querySelector(`[data-id="${CSS.escape(saved.id)}"]`);+ if (!card) return;+ card.dataset.lat = saved.lat;+ card.dataset.lng = saved.lng;+ card.dataset.heading = saved.heading ?? 0;+ const locEl = card.querySelector('.irl-meta-loc');+ if (!locEl) return;+ locEl.textContent = metaLine(pin || saved, label || null);+ if (!label) placeFor(saved.lat, saved.lng).then((geo) => { if (geo) locEl.textContent = metaLine(pin || saved, geo); });+ }+list.addEventListener('click', async (e) => {const card = e.target.closest('.irl-card');if (!card) return;const id = card.dataset.id;+ // Reply to a visitor message — composed in the dedicated inbox surface.+ if (e.target.closest('[data-reply-open]')) {+ openInboxModal();+ return;+ }+// Manage paid services (x402 skill pricing) for this agentif (e.target.closest('[data-manage-services]')) {const agentId = card.dataset.agent;@@ -558,6 +963,37 @@ function wireCardEvents(list, pins) {return;}+ // Change outfit (C6) — open the in-dashboard remote outfit editor. The 3D+ // editor (Three.js) is lazy-loaded so the dashboard's initial bundle stays+ // light; on save it re-skins the pin for every nearby viewer.+ const outfitBtn = e.target.closest('[data-outfit]');+ if (outfitBtn) {+ const pin = pins.find((p) => p.id === id);+ if (!pin) return;+ outfitBtn.disabled = true;+ const prev = outfitBtn.textContent;+ outfitBtn.textContent = 'Opening…';+ try {+ const { openOutfitEditor } = await import('./irl-outfit-editor.js');+ await openOutfitEditor({+ pin,+ onSaved: () => {+ // The editor mutates the shared `pin` object in place, so a re-edit+ // re-bakes from the right base. Confirm the change on the card.+ card.classList.remove('irl-flash'); void card.offsetWidth; card.classList.add('irl-flash');+ card.addEventListener('animationend', () => card.classList.remove('irl-flash'), { once: true });+ irlToast('Outfit updated — nearby viewers will see it shortly');+ },+ });+ } catch {+ irlToast("Couldn't open the outfit editor. Try again.");+ } finally {+ outfitBtn.disabled = false;+ outfitBtn.textContent = prev;+ }+ return;+ }+// Removeconst removeBtn = e.target.closest('[data-remove]');if (removeBtn) {@@ -565,61 +1001,15 @@ function wireCardEvents(list, pins) {removeBtn.textContent = 'Removing…';try {const r = await fetch(`/api/irl/pins?id=${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include' });- if (r.ok) {- card.remove();- if (!list.querySelector('.irl-card')) {- list.innerHTML = `<div class="irl-empty"><b>No placements</b>All agents removed. <a class="irl-btn" href="/irl" style="display:inline-flex;margin-top:12px">Place a new one →</a></div>`;- }- } else { removeBtn.disabled = false; removeBtn.textContent = 'Remove'; }+ if (r.ok) { dropCard(id); }+ else { removeBtn.disabled = false; removeBtn.textContent = 'Remove'; }} catch { removeBtn.disabled = false; removeBtn.textContent = 'Remove'; }return;}- // Toggle location editor+ // Open the relocation map — drag the pin, re-aim, or remove from anywhere.if (e.target.closest('[data-loc-toggle]')) {- card.querySelector('[data-loc-edit]')?.classList.toggle('open');- return;- }-- // "Use my location" — fill lat/lng from the browser- if (e.target.closest('[data-loc-here]')) {- const btn = e.target.closest('[data-loc-here]');- btn.disabled = true; btn.textContent = 'Locating…';- navigator.geolocation?.getCurrentPosition(- (p) => {- card.querySelector('[data-loc="lat"]').value = p.coords.latitude.toFixed(5);- card.querySelector('[data-loc="lng"]').value = p.coords.longitude.toFixed(5);- btn.disabled = false; btn.textContent = 'Use my location';- },- () => { btn.disabled = false; btn.textContent = 'Location unavailable'; },- { enableHighAccuracy: true, timeout: 8000 },- );- return;- }-- // Save location- if (e.target.closest('[data-loc-save]')) {- const btn = e.target.closest('[data-loc-save]');- const lat = parseFloat(card.querySelector('[data-loc="lat"]').value);- const lng = parseFloat(card.querySelector('[data-loc="lng"]').value);- const heading = parseInt(card.querySelector('[data-loc="heading"]').value, 10);- if (!isFinite(lat) || !isFinite(lng)) { btn.textContent = 'Invalid coordinates'; return; }- btn.disabled = true; btn.textContent = 'Saving…';- try {- // Omit heading when the field is blank so a blank input PRESERVES the- // stored bearing instead of silently re-aiming the agent to North (0°).- const r = await patch('/api/irl/pins', { id, lat, lng, ...(isFinite(heading) ? { heading } : {}) });- if (r.pin) {- const pin = pins.find((p) => p.id === id);- if (pin) { pin.lat = r.pin.lat; pin.lng = r.pin.lng; pin.heading = r.pin.heading; }- card.querySelector('.irl-meta-loc').textContent = metaLine(r.pin, null);- reverseGeocode(r.pin.lat, r.pin.lng).then((geo) => {- if (geo) card.querySelector('.irl-meta-loc').textContent = metaLine(r.pin, geo);- });- btn.textContent = 'Saved ✓';- setTimeout(() => { btn.disabled = false; btn.textContent = 'Save location'; card.querySelector('[data-loc-edit]')?.classList.remove('open'); }, 900);- } else { btn.disabled = false; btn.textContent = 'Save location'; }- } catch { btn.disabled = false; btn.textContent = 'Retry save'; }+ openLocationMap({ pins, focusId: id, onSaved, onRemoved: dropCard });return;}@@ -672,6 +1062,668 @@ function restoreCaption(card, caption) {editEl?.replaceWith(node);}+// ── Location map (Leaflet, lazy-loaded) ─────────────────────────────────────+// A real OSM map with a draggable marker per placed agent, so the owner can+// relocate / re-aim / remove a pin from anywhere — not just standing at the+// spot. Leaflet (JS + CSS) is imported from a CDN only when the panel opens, so+// the rest of the dashboard never pays for it.+const LEAFLET_JS = 'https://esm.sh/[email protected]';+const LEAFLET_CSS = 'https://unpkg.com/[email protected]/dist/leaflet.css';++// North-up compass dial; the needle <g> is rotated by the heading at runtime.+const COMPASS_SVG = `<svg viewBox="-50 -50 100 100" aria-hidden="true">+ <circle class="ring" cx="0" cy="0" r="45"/>+ <line class="tick" x1="0" y1="-45" x2="0" y2="-39"/><line class="tick" x1="0" y1="45" x2="0" y2="39"/>+ <line class="tick" x1="-45" y1="0" x2="-39" y2="0"/><line class="tick" x1="45" y1="0" x2="39" y2="0"/>+ <text class="lbl n" x="0" y="-27">N</text><text class="lbl" x="27" y="0">E</text>+ <text class="lbl" x="0" y="27">S</text><text class="lbl" x="-27" y="0">W</text>+ <g class="needle" data-needle transform="rotate(0)"><polygon points="0,-30 6,6 0,1 -6,6"/></g>+</svg>`;++let _leafletCssPromise = null;+function ensureLeafletCss() {+ if (_leafletCssPromise) return _leafletCssPromise;+ _leafletCssPromise = new Promise((resolve, reject) => {+ 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) => { _leafletCssPromise = null; throw e; });+ return _leafletCssPromise;+}++let _leafletPromise = null;+function loadLeaflet() {+ if (_leafletPromise) return _leafletPromise;+ _leafletPromise = (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) => { _leafletPromise = null; throw e; });+ return _leafletPromise;+}++const norm360 = (h) => ((Math.round(Number(h) || 0) % 360) + 360) % 360;++// Relocation map modal. `pins` is the live page list (shared ref); `focusId` is+// the pin opened from its C1 card; `onSaved(pin,label)` reflects a persisted move+// back into the card; `onRemoved(id)` drops the card after a delete.+function openLocationMap({ pins, focusId, onSaved, onRemoved }) {+ let L = null;+ let map = null;+ const markers = new Map(); // id -> Leaflet marker+ let saved = null; // last-persisted { lat, lng, heading } of the focus+ let pending = null; // current marker/dial { lat, lng, heading }+ let pendingLabel = null; // reverse-geocoded label for the pending position+ let geocoding = false;+ let geoSeq = 0;+ let dirty = false;+ let dragCompass = false;+ let ui = {};++ const pinById = (id) => pins.find((p) => p.id === id);++ const root = makeNode(`<div class="irl-modal-root irlmap-modal">+ <div class="irl-modal-back"></div>+ <div class="irl-modal" role="dialog" aria-modal="true" aria-label="Move agent on the map">+ <div class="irl-modal-head">+ <div class="irl-modal-titles">+ <div class="irl-modal-title">Move on map</div>+ <div class="irl-modal-sub" data-sub>Loading map…</div>+ </div>+ <button class="irl-modal-x" data-close type="button" aria-label="Close">×</button>+ </div>+ <div class="irl-modal-body" data-body></div>+ </div>+ </div>`);+ ensureStateKitStyles();+ document.body.appendChild(root);+ document.body.style.overflow = 'hidden';++ const modalEl = root.querySelector('.irl-modal');+ const subEl = root.querySelector('[data-sub]');+ const body = root.querySelector('[data-body]');++ const close = () => {+ try { map?.remove(); } catch { /* leaflet teardown best-effort */ }+ map = null;+ root.remove();+ document.body.style.overflow = '';+ document.removeEventListener('keydown', onKey, true);+ };+ const onKey = (ev) => { if (ev.key === 'Escape') close(); };+ document.addEventListener('keydown', onKey, true);+ root.querySelector('[data-close]').addEventListener('click', close);+ root.querySelector('.irl-modal-back').addEventListener('click', close);+ setTimeout(() => root.querySelector('[data-close]')?.focus(), 0);++ // ── Markers ────────────────────────────────────────────────────────────+ function makeIcon(p, focused) {+ const av = p.avatar_url+ ? `<img src="${esc(p.avatar_url)}" alt="" onerror="this.remove()" />`+ : '📍';+ return L.divIcon({+ className: 'irlmap-pin',+ html: `<div class="irlmap-marker${focused ? ' is-focused' : ''}"><div class="irlmap-dot">${av}</div><div class="irlmap-heading" style="transform:rotate(${norm360(p.heading)}deg)"><i></i></div></div>`,+ iconSize: [40, 40],+ iconAnchor: [20, 20],+ });+ }++ function hideSkel() { ui.skel?.classList.add('gone'); }+ function updateSub(p) { if (subEl) subEl.textContent = `${p.avatar_name || 'Placed agent'} · drag the pin to relocate`; }++ // ── Heading (dial + input + focused marker) ──────────────────────────────+ function setHeading(h, { user = false, fromInput = false } = {}) {+ h = norm360(h);+ pending.heading = h;+ ui.needle?.setAttribute('transform', `rotate(${h})`);+ if (ui.headCmp) ui.headCmp.textContent = compassLabel(h);+ if (!fromInput && ui.headInput) ui.headInput.value = String(h);+ ui.compass?.setAttribute('aria-valuenow', String(h));+ const hd = markers.get(focusId)?.getElement()?.querySelector('.irlmap-heading');+ if (hd) hd.style.transform = `rotate(${h}deg)`;+ if (user) { dirty = true; refreshSaveBar(); }+ }++ // ── Save bar ─────────────────────────────────────────────────────────────+ function refreshSaveBar() {+ if (!ui.savebar) return;+ const moved = pending.lat !== saved.lat || pending.lng !== saved.lng;+ const turned = pending.heading !== saved.heading;+ if (!moved && !turned) { hideSaveBar(); return; }+ const parts = [];+ if (moved) {+ const loc = pendingLabel || `${pending.lat.toFixed(5)}°, ${pending.lng.toFixed(5)}°`;+ parts.push(`Move to <b>${esc(loc)}</b>${geocoding ? ' <span class="locating">(locating…)</span>' : ''}`);+ }+ if (turned) parts.push(`${moved ? 'facing' : 'Re-aim to'} <b>${compassLabel(pending.heading)} (${pending.heading}°)</b>`);+ ui.saveLbl.innerHTML = parts.join(', ');+ ui.saveErr.hidden = true; ui.saveErr.textContent = '';+ ui.saveBtn.disabled = false; ui.saveBtn.textContent = 'Save';+ ui.cancelBtn.textContent = 'Cancel';+ ui.savebar.classList.add('open');+ }+ function hideSaveBar() { ui.savebar?.classList.remove('open'); }++ // Snap the focused marker + dial back to the last persisted values.+ function revertToSaved() {+ markers.get(focusId)?.setLatLng([saved.lat, saved.lng]);+ pending = { ...saved };+ pendingLabel = null; geocoding = false; geoSeq++; // void any in-flight geocode+ setHeading(saved.heading, {});+ dirty = false;+ }++ // Move the focused pin (drag end, "pin to my location"); reverse-geocode async.+ function applyMove(lat, lng) {+ markers.get(focusId)?.setLatLng([lat, lng]);+ pending.lat = lat; pending.lng = lng;+ dirty = true;+ pendingLabel = null; geocoding = true;+ refreshSaveBar();+ const seq = ++geoSeq;+ placeFor(lat, lng).then((label) => { if (seq === geoSeq) { pendingLabel = label; geocoding = false; refreshSaveBar(); } });+ }++ async function persist(lat, lng, heading, label) {+ const r = await patch('/api/irl/pins', { id: focusId, lat, lng, ...(Number.isFinite(heading) ? { heading } : {}) });+ if (!r?.pin) throw new Error('save failed');+ onSaved(r.pin, label || null);+ return r.pin;+ }++ async function doSave() {+ ui.saveBtn.disabled = true; ui.saveBtn.textContent = 'Saving…';+ try {+ const pin = await persist(pending.lat, pending.lng, pending.heading, pendingLabel);+ saved = { lat: pin.lat, lng: pin.lng, heading: norm360(pin.heading ?? pending.heading) };+ pending = { ...saved };+ dirty = false;+ markers.get(focusId)?.setLatLng([saved.lat, saved.lng]);+ setHeading(saved.heading, {});+ ui.saveBtn.textContent = 'Saved ✓';+ setTimeout(() => { hideSaveBar(); if (ui.saveBtn) { ui.saveBtn.disabled = false; ui.saveBtn.textContent = 'Save'; } }, 1100);+ } catch {+ // Snap back to the last saved position and surface the failure inline.+ revertToSaved();+ ui.savebar.classList.add('open');+ ui.saveLbl.innerHTML = 'Last saved position restored.';+ ui.saveErr.textContent = 'Couldn’t save the move. Re-drag the pin and try again.';+ ui.saveErr.hidden = false;+ ui.saveBtn.disabled = true; ui.saveBtn.textContent = 'Save';+ ui.cancelBtn.textContent = 'Dismiss';+ }+ }++ function onCancel() { revertToSaved(); hideSaveBar(); }++ // ── Focus handling ───────────────────────────────────────────────────────+ function focusInit(p) {+ saved = { lat: +p.lat, lng: +p.lng, heading: norm360(p.heading) };+ pending = { ...saved };+ dirty = false;+ setHeading(saved.heading, {});+ updateSub(p);+ }+ function focusPin(id) {+ if (dirty) revertToSaved();+ markers.get(focusId)?.dragging?.disable();+ focusId = id;+ const p = pinById(id);+ saved = { lat: +p.lat, lng: +p.lng, heading: norm360(p.heading) };+ pending = { ...saved };+ dirty = false;+ for (const [pid, mk] of markers) mk.setIcon(makeIcon(pinById(pid), pid === focusId));+ markers.get(id)?.dragging?.enable();+ setHeading(saved.heading, {});+ updateSub(p);+ hideSaveBar();+ map?.panTo([saved.lat, saved.lng]);+ }++ // ── Remove ───────────────────────────────────────────────────────────────+ function restoreFoot() {+ const foot = root.querySelector('.irlmap-foot');+ if (!foot) return;+ foot.innerHTML = `<span class="irlmap-hint">Drag the highlighted pin to relocate. Tap another pin to switch.</span>+ <button class="irl-action remove" data-remove-pin type="button">Remove from map</button>`;+ ui.removeBtn = foot.querySelector('[data-remove-pin]');+ ui.removeBtn.addEventListener('click', onRemoveClick);+ }+ function onRemoveClick() {+ const foot = root.querySelector('.irlmap-foot');+ if (!foot) return;+ const p = pinById(focusId) || {};+ foot.innerHTML = `<span class="irlmap-hint">Remove <b>${esc(p.avatar_name || 'this agent')}</b> from the map? This deletes the pin.</span>+ <span style="display:flex;gap:8px;flex-shrink:0">+ <button class="irl-action" data-remove-keep type="button">Keep</button>+ <button class="irl-action remove" data-remove-yes type="button">Remove</button>+ </span>`;+ foot.querySelector('[data-remove-keep]').addEventListener('click', restoreFoot);+ foot.querySelector('[data-remove-yes]').addEventListener('click', doRemove);+ }+ async function doRemove() {+ const yes = root.querySelector('[data-remove-yes]');+ if (yes) { yes.disabled = true; yes.textContent = 'Removing…'; }+ try {+ const removedId = focusId;+ const r = await fetch(`/api/irl/pins?id=${encodeURIComponent(removedId)}`, { method: 'DELETE', credentials: 'include' });+ if (!r.ok) throw new Error('delete failed');+ markers.get(removedId)?.remove();+ markers.delete(removedId);+ onRemoved(removedId);+ hideSaveBar();+ const next = markers.size ? [...markers.keys()][0] : null;+ if (next) { restoreFoot(); focusPin(next); }+ else { close(); }+ } catch {+ if (yes) { yes.disabled = false; yes.textContent = 'Remove'; }+ }+ }++ // ── Compass dial interaction (pointer drag + keyboard) ───────────────────+ function wireCompass() {+ const el = ui.compass;+ if (!el) return;+ const applyPointer = (clientX, clientY) => {+ const r = el.getBoundingClientRect();+ const dx = clientX - (r.left + r.width / 2);+ const dy = clientY - (r.top + r.height / 2);+ if (dx === 0 && dy === 0) return;+ setHeading((Math.atan2(dx, -dy) * 180 / Math.PI), { user: true });+ };+ el.addEventListener('pointerdown', (ev) => {+ ev.preventDefault();+ dragCompass = true;+ try { el.setPointerCapture(ev.pointerId); } catch { /* capture optional */ }+ applyPointer(ev.clientX, ev.clientY);+ });+ el.addEventListener('pointermove', (ev) => { if (dragCompass) applyPointer(ev.clientX, ev.clientY); });+ const end = (ev) => { dragCompass = false; try { el.releasePointerCapture(ev.pointerId); } catch { /* noop */ } };+ el.addEventListener('pointerup', end);+ el.addEventListener('pointercancel', end);+ el.addEventListener('keydown', (ev) => {+ const step = ev.shiftKey ? 10 : 1;+ let h = pending.heading;+ if (ev.key === 'ArrowRight' || ev.key === 'ArrowUp') h += step;+ else if (ev.key === 'ArrowLeft' || ev.key === 'ArrowDown') h -= step;+ else if (ev.key === 'Home') h = 0;+ else if (ev.key === 'PageUp') h += 45;+ else if (ev.key === 'PageDown') h -= 45;+ else return;+ ev.preventDefault();+ setHeading(h, { user: true });+ });+ }++ function onLocate() {+ const btn = ui.locateBtn;+ if (!navigator.geolocation) { btn.textContent = 'Location unavailable'; return; }+ btn.disabled = true; btn.textContent = 'Locating…';+ navigator.geolocation.getCurrentPosition(+ (pos) => {+ btn.disabled = false; btn.textContent = 'Pin to my location';+ map?.panTo([pos.coords.latitude, pos.coords.longitude]);+ applyMove(pos.coords.latitude, pos.coords.longitude);+ },+ () => { btn.disabled = false; btn.textContent = 'Location unavailable'; },+ { enableHighAccuracy: true, timeout: 8000 },+ );+ }++ // ── Map shell + build ────────────────────────────────────────────────────+ function renderMapShell() {+ body.innerHTML = `+ <div class="irlmap">+ <div class="irlmap-canvas" data-canvas></div>+ <div class="irlmap-skel" data-skel><span class="irlmap-spin"></span> Loading map…</div>+ </div>+ <div class="irlmap-controls">+ <div class="irlmap-compass" data-compass role="slider" tabindex="0" aria-label="Agent heading in degrees" aria-valuemin="0" aria-valuemax="359" aria-valuenow="0">${COMPASS_SVG}</div>+ <div class="irlmap-headbox">+ <span>Heading</span>+ <div class="irlmap-headrow">+ <input type="number" min="0" max="359" step="1" data-head-input aria-label="Heading in degrees" />+ <span class="cmp" data-head-cmp>N</span>+ </div>+ </div>+ <span class="grow"></span>+ <button class="irl-action" data-locate type="button">Pin to my location</button>+ </div>+ <div class="irlmap-savebar" data-savebar>+ <span class="lbl" data-save-lbl></span>+ <button class="irl-action" data-save-cancel type="button">Cancel</button>+ <button class="irl-btn primary" data-save type="button">Save</button>+ <span class="err" data-save-err hidden></span>+ </div>+ <div class="irlmap-foot">+ <span class="irlmap-hint">Drag the highlighted pin to relocate. Tap another pin to switch.</span>+ <button class="irl-action remove" data-remove-pin type="button">Remove from map</button>+ </div>`;+ ui = {+ canvas: body.querySelector('[data-canvas]'),+ skel: body.querySelector('[data-skel]'),+ compass: body.querySelector('[data-compass]'),+ needle: body.querySelector('[data-needle]'),+ headInput: body.querySelector('[data-head-input]'),+ headCmp: body.querySelector('[data-head-cmp]'),+ savebar: body.querySelector('[data-savebar]'),+ saveLbl: body.querySelector('[data-save-lbl]'),+ saveErr: body.querySelector('[data-save-err]'),+ saveBtn: body.querySelector('[data-save]'),+ cancelBtn: body.querySelector('[data-save-cancel]'),+ locateBtn: body.querySelector('[data-locate]'),+ removeBtn: body.querySelector('[data-remove-pin]'),+ };+ }++ function buildMap() {+ markers.clear();+ const p0 = pinById(focusId);+ if (!p0) { close(); return; }+ map = L.map(ui.canvas, { zoomControl: true, attributionControl: true }).setView([+p0.lat, +p0.lng], 16);+ L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors', maxZoom: 19 })+ .addTo(map)+ .on('load', hideSkel);++ for (const p of pins) {+ const mk = L.marker([+p.lat, +p.lng], { draggable: true, autoPan: true, keyboard: false, icon: makeIcon(p, p.id === focusId) }).addTo(map);+ markers.set(p.id, mk);+ if (p.id !== focusId) mk.dragging?.disable();+ mk.on('dragend', () => { if (p.id === focusId) { const ll = mk.getLatLng(); applyMove(ll.lat, ll.lng); } });+ mk.on('click', () => { if (p.id !== focusId) focusPin(p.id); });+ }++ focusInit(p0);+ ui.saveBtn.addEventListener('click', doSave);+ ui.cancelBtn.addEventListener('click', onCancel);+ ui.locateBtn.addEventListener('click', onLocate);+ ui.removeBtn.addEventListener('click', onRemoveClick);+ ui.headInput.addEventListener('input', () => {+ const v = parseInt(ui.headInput.value, 10);+ if (Number.isFinite(v)) setHeading(v, { user: true, fromInput: true });+ });+ wireCompass();++ // Leaflet measures its container; the modal animates in, so re-measure+ // after layout (rAF) and again once the entrance animation ends. A final+ // timer hides the skeleton in case the tile 'load' event was missed.+ requestAnimationFrame(() => map?.invalidateSize());+ modalEl.addEventListener('animationend', () => map?.invalidateSize(), { once: true });+ setTimeout(() => { map?.invalidateSize(); hideSkel(); }, 1800);+ }++ // ── CDN-failure fallback: manual coordinate entry ────────────────────────+ function renderFallback() {+ try { map?.remove(); } catch { /* noop */ }+ map = null;+ const p = pinById(focusId) || {};+ if (subEl) subEl.textContent = `${p.avatar_name || 'Placed agent'} · manual coordinates`;+ body.innerHTML = errorStateHTML({+ title: 'Map unavailable',+ body: 'The map library couldn’t load (offline or blocked). You can still relocate this agent by entering coordinates below.',+ actions: [{ label: 'Retry map', id: 'retry', primary: true }],+ }) + `<div class="irlmap-fallback">+ <div class="row">+ <div class="irl-loc-field"><label>Latitude</label><input type="number" step="0.00001" data-fb="lat" value="${esc(Number(p.lat ?? 0).toFixed(5))}" /></div>+ <div class="irl-loc-field"><label>Longitude</label><input type="number" step="0.00001" data-fb="lng" value="${esc(Number(p.lng ?? 0).toFixed(5))}" /></div>+ <div class="irl-loc-field heading"><label>Heading°</label><input type="number" min="0" max="359" step="1" data-fb="heading" value="${esc(norm360(p.heading))}" /></div>+ <button class="irl-action" data-fb-here type="button">Use my location</button>+ <button class="irl-btn primary" data-fb-save type="button">Save</button>+ </div>+ <div class="fb-err" data-fb-err hidden></div>+ </div>`;++ body.querySelector('[data-sk-action="retry"]')?.addEventListener('click', () => { initMap(); });+ body.querySelector('[data-fb-here]')?.addEventListener('click', (ev) => {+ const btn = ev.currentTarget;+ if (!navigator.geolocation) { btn.textContent = 'Location unavailable'; return; }+ btn.disabled = true; btn.textContent = 'Locating…';+ navigator.geolocation.getCurrentPosition(+ (pos) => {+ body.querySelector('[data-fb="lat"]').value = pos.coords.latitude.toFixed(5);+ body.querySelector('[data-fb="lng"]').value = pos.coords.longitude.toFixed(5);+ btn.disabled = false; btn.textContent = 'Use my location';+ },+ () => { btn.disabled = false; btn.textContent = 'Location unavailable'; },+ { enableHighAccuracy: true, timeout: 8000 },+ );+ });+ body.querySelector('[data-fb-save]')?.addEventListener('click', async (ev) => {+ const btn = ev.currentTarget;+ const err = body.querySelector('[data-fb-err]');+ const lat = parseFloat(body.querySelector('[data-fb="lat"]').value);+ const lng = parseFloat(body.querySelector('[data-fb="lng"]').value);+ const heading = parseInt(body.querySelector('[data-fb="heading"]').value, 10);+ err.hidden = true;+ if (!Number.isFinite(lat) || lat < -90 || lat > 90 || !Number.isFinite(lng) || lng < -180 || lng > 180) {+ err.textContent = 'Enter a valid latitude (−90…90) and longitude (−180…180).'; err.hidden = false; return;+ }+ btn.disabled = true; btn.textContent = 'Saving…';+ try {+ await persist(lat, lng, Number.isFinite(heading) ? heading : undefined, null);+ btn.textContent = 'Saved ✓';+ setTimeout(close, 800);+ } catch {+ btn.disabled = false; btn.textContent = 'Retry save';+ err.textContent = 'Couldn’t save. Check your connection and try again.'; err.hidden = false;+ }+ });+ }++ async function initMap() {+ try { map?.remove(); } catch { /* noop */ }+ map = null;+ renderMapShell();+ try { L = await loadLeaflet(); }+ catch { renderFallback(); return; }+ try { buildMap(); }+ catch { renderFallback(); }+ }++ initMap();+}++// ── Inbox modal: the chronological feed of every IRL encounter ──────────────+// One rich row per interaction across all of the owner's pins. Pays deep-link to+// the block explorer; visitor messages can be replied to inline (the reply+// notifies the visitor when they were signed in). Opening the inbox marks+// everything read.+function inboxRow(ix) {+ const owner = isOwnerReply(ix);+ const unread = !ix.seen_at && !owner;+ const icon = INTERACTION_ICON[ix.type] || '•';+ const place = ix.avatar_name ? `“${esc(ix.avatar_name)}”` : 'Your agent';+ const tx = ix.type === 'pay' ? explorerTxUrl(ix.payload?.signature, ix.payload?.network) : null;+ const txLink = tx ? `<a class="irl-inbox-action" href="${esc(tx)}" target="_blank" rel="noopener">View tx ↗</a>` : '';+ const reply = (ix.type === 'message' && !owner)+ ? `<button class="irl-inbox-action" data-reply="${esc(ix.id)}" type="button">Reply</button>` : '';+ const msg = ix.message ? `<div class="irl-inbox-msg">“${esc(ix.message)}”</div>` : '';+ const coords = (ix.lat != null && ix.lng != null)+ ? `<span class="irl-inbox-place">@ ${esc(Number(ix.lat).toFixed(4))}, ${esc(Number(ix.lng).toFixed(4))}</span>` : '';+ return `<div class="irl-inbox-row${owner ? ' owner' : ''}${unread ? ' unread' : ''}" data-row="${esc(ix.id)}" data-row-pin="${esc(ix.pin_id)}">+ <span class="irl-inbox-icon" aria-hidden="true">${icon}</span>+ <div class="irl-inbox-main">+ <div class="irl-inbox-head"><span class="irl-inbox-who">${ixHeadline(ix)}</span><span class="irl-inbox-time">${esc(relTime(ix.created_at))}</span></div>+ ${msg}+ <div class="irl-inbox-meta"><span class="irl-inbox-agent">${place}</span>${coords}${txLink}${reply}</div>+ </div>+ </div>`;+}++function openInboxModal() {+ if (document.querySelector('.irl-modal-root[data-inbox]')) return; // single instance+ const root = makeNode(`<div class="irl-modal-root" data-inbox>+ <div class="irl-modal-back"></div>+ <div class="irl-modal" role="dialog" aria-modal="true" aria-label="IRL interactions inbox">+ <div class="irl-modal-head">+ <div class="irl-modal-titles">+ <div class="irl-modal-title">Inbox</div>+ <div class="irl-modal-sub">Everyone who met your agents in real life</div>+ </div>+ <button class="irl-modal-x" data-close type="button" aria-label="Close">×</button>+ </div>+ <div class="irl-modal-body" data-body>${skeletonHTML(5, 'row')}</div>+ </div>+ </div>`);+ ensureStateKitStyles();+ document.body.appendChild(root);+ document.body.style.overflow = 'hidden';++ const body = root.querySelector('[data-body]');+ let composingCount = 0; // open reply composers — guards close + poll refresh+ let flash = null; // one-shot confirmation strip shown on the next render++ const close = () => {+ root.remove();+ document.body.style.overflow = '';+ document.removeEventListener('keydown', onKey, true);+ inboxModal = null;+ };+ const onKey = (ev) => { if (ev.key === 'Escape' && composingCount === 0) close(); };+ document.addEventListener('keydown', onKey, true);+ root.querySelector('[data-close]').addEventListener('click', close);+ root.querySelector('.irl-modal-back').addEventListener('click', () => { if (composingCount === 0) close(); });+ setTimeout(() => root.querySelector('[data-close]')?.focus(), 0);++ // Exposed so the poll loop can keep an open inbox fresh (unless mid-reply).+ inboxModal = { isComposing: () => composingCount > 0, refresh: (rows) => render(rows) };++ function render(rows) {+ composingCount = 0; // a full rebuild drops any open composer+ const flashHtml = flash ? `<div class="irl-inbox-flash">${esc(flash)}</div>` : '';+ flash = null;+ if (!rows.length) {+ body.innerHTML = flashHtml + emptyStateHTML({+ icon: '📍',+ title: 'No interactions yet',+ body: 'When someone taps or pays your agent IRL, it shows up here.',+ actions: [{ label: 'View in IRL', href: '/irl', primary: true }],+ });+ return;+ }+ body.innerHTML = flashHtml + `<div class="irl-inbox-list">${rows.map(inboxRow).join('')}</div>`;+ // Lazy-label each unique pin's location (cached, shared with the cards).+ const seen = new Set();+ for (const ix of rows) {+ if (ix.lat == null || seen.has(ix.pin_id)) continue;+ seen.add(ix.pin_id);+ placeFor(ix.lat, ix.lng).then((place) => {+ if (!place) return;+ body.querySelectorAll(`[data-row-pin="${CSS.escape(ix.pin_id)}"] .irl-inbox-place`)+ .forEach((elp) => { elp.textContent = `@ ${place}`; });+ });+ }+ }++ async function load() {+ try {+ const data = await get('/api/irl/interactions?mine=1');+ inbox.interactions = data.interactions || [];+ const hadUnread = (data.unread || 0) > 0;+ inbox.unread = data.unread || 0;+ render(inbox.interactions); // shows unread highlights for this view+ if (hadUnread) {+ // Opening the inbox IS the read action. Persist it, then clear the badge,+ // the per-card chips and the banner — but leave the modal's highlights so+ // the owner can see what was new this visit.+ patch('/api/irl/interactions', {}).catch(() => {});+ inbox.interactions = inbox.interactions.map((x) => x.seen_at ? x : { ...x, seen_at: new Date().toISOString() });+ inbox.unread = 0;+ applyBadges();+ renderBanner();+ }+ } catch {+ body.innerHTML = errorStateHTML({+ title: "Couldn't load your inbox",+ body: 'Check your connection and try again.',+ scope: 'inbox',+ });+ body.querySelector('[data-sk-retry]')?.addEventListener('click', () => {+ body.innerHTML = skeletonHTML(5, 'row');+ load();+ });+ }+ }++ // ── Reply composer ─────────────────────────────────────────────────────────+ body.addEventListener('click', async (e) => {+ const replyBtn = e.target.closest('[data-reply]');+ if (replyBtn) return openComposer(replyBtn.dataset.reply);+ if (e.target.closest('[data-reply-cancel]')) return closeComposer(e.target.closest('.irl-inbox-row'));+ const sendBtn = e.target.closest('[data-reply-send]');+ if (sendBtn) return sendReply(sendBtn);+ });++ function openComposer(ixId) {+ const row = body.querySelector(`[data-row="${CSS.escape(ixId)}"]`);+ if (!row || row.querySelector('.irl-reply-box')) return;+ composingCount++;+ const boxEl = makeNode(`<div class="irl-reply-box">+ <textarea class="irl-reply-input" rows="2" maxlength="280" placeholder="Reply to this visitor…" aria-label="Reply to visitor"></textarea>+ <div class="irl-reply-actions">+ <span class="irl-reply-hint" data-reply-hint></span>+ <button class="irl-action" data-reply-cancel type="button">Cancel</button>+ <button class="irl-btn primary" data-reply-send="${esc(ixId)}" type="button">Send reply</button>+ </div>+ </div>`);+ row.querySelector('.irl-inbox-main').appendChild(boxEl);+ boxEl.querySelector('.irl-reply-input')?.focus();+ }++ function closeComposer(row) {+ const boxEl = row?.querySelector('.irl-reply-box');+ if (boxEl) { boxEl.remove(); composingCount = Math.max(0, composingCount - 1); }+ }++ async function sendReply(sendBtn) {+ const ixId = sendBtn.dataset.replySend;+ const row = body.querySelector(`[data-row="${CSS.escape(ixId)}"]`);+ const input = row?.querySelector('.irl-reply-input');+ const hint = row?.querySelector('[data-reply-hint]');+ const text = input?.value?.trim() ?? '';+ const ix = inbox.interactions.find((x) => x.id === ixId);+ if (!text || !ix) { input?.focus(); return; }+ sendBtn.disabled = true; sendBtn.textContent = 'Sending…';+ if (hint) { hint.className = 'irl-reply-hint'; hint.textContent = ''; }+ try {+ const r = await post('/api/irl/interactions', {+ pinId: ix.pin_id, type: 'message', message: text, replyTo: ixId,+ });+ // Optimistically thread the reply into state; the next poll reconciles it+ // with the server row. The flash strip carries the "did it reach them" note.+ inbox.interactions.unshift({+ id: r?.interaction?.id || `tmp-${ixId}-${text.length}`,+ pin_id: ix.pin_id,+ agent_id: ix.agent_id ?? null,+ type: 'message',+ message: text,+ created_at: r?.interaction?.created_at || new Date().toISOString(),+ seen_at: r?.interaction?.created_at || new Date().toISOString(),+ payload: { from: 'owner' },+ avatar_name: ix.avatar_name,+ lat: ix.lat, lng: ix.lng,+ });+ flash = r?.notified ? 'Reply sent — visitor notified ✓' : 'Reply saved ✓';+ render(inbox.interactions);+ refreshCardFeed(ix.pin_id);+ applyBadges();+ } catch (err) {+ sendBtn.disabled = false; sendBtn.textContent = 'Send reply';+ if (hint) { hint.className = 'irl-reply-hint err'; hint.textContent = err?.message || 'Could not send'; }+ }+ }++ load();+}+// ── Services modal: attach/price the skills this agent offers IRL ───────────function openServicesModal(agentId, agentName) {const root = makeNode(`<div class="irl-modal-root">diff --git a/src/irl-net.js b/src/irl-net.jsnew file mode 100644index 000000000..e45115e76--- /dev/null+++ b/src/irl-net.js@@ -0,0 +1,262 @@+// Realtime client for /irl — wraps colyseus.js with a tiny event API so irl.js+// can subscribe to live pin changes without knowing anything about Colyseus.+// Mirrors walk-net.js in shape (status model, single-retry reconnect, no storms)+// so the two transports read the same.+//+// What it does: joins the irl_world room for the viewer's precision-6 geocell and+// relays the pin MapSchema as pin:add / pin:update / pin:remove events. A late+// joiner is handed the room's full current pin set on connect (schema sync), so+// it never misses pins placed before it arrived. When the viewer physically walks+// into a new geocell, moveTo() re-joins the new room.+//+// Graceful degradation: if no server is configured for this environment, or the+// socket can't be reached after one retry, it settles into a distinct status+// (`unavailable` / `failed`) so irl.js drops to the poll fallback and the HUD pill+// says "Polling" — never a dead "reconnecting…" forever.++import { Client, getStateCallbacks } from 'colyseus.js';+import { IrlState } from '../multiplayer/src/irl-schemas.js';+import { encodeGeohash } from '../multiplayer/src/geohash.js';+import { log } from './shared/log.js';++const ROOM_NAME = 'irl_world';+const GEOCELL_PRECISION = 6;+const MAX_RETRIES = 1; // one jittered retry on failure/drop, then drop to poll++function defaultServerUrl() {+ // The IRL world runs on the SAME Colyseus host as /walk (a new room, not a new+ // process), so we resolve the walk-server config as a fallback — production sets+ // <meta name="walk-server">, and an explicit irl-server meta/env can override it.+ // 1. window.IRL_SERVER_URL / window.WALK_SERVER_URL (runtime / test override)+ // 2. <meta name="irl-server"> / <meta name="walk-server"> (per-page prod config)+ // 3. VITE_IRL_SERVER_URL / VITE_WALK_SERVER_URL (build-time prod config)+ // 4. Codespaces / Gitpod port-subdomain forwarding (-3000 → -2567)+ // 5. Same host on :2567 (DEV ONLY convenience)+ // In production with none set we return '' so the caller stays in graceful poll+ // mode — the public domain doesn't expose :2567.+ if (typeof window !== 'undefined') {+ if (window.IRL_SERVER_URL) return String(window.IRL_SERVER_URL).trim().replace(/\/$/, '');+ if (window.WALK_SERVER_URL) return String(window.WALK_SERVER_URL).trim().replace(/\/$/, '');+ }+ if (typeof document !== 'undefined') {+ for (const name of ['irl-server', 'walk-server']) {+ const v = document.querySelector(`meta[name="${name}"]`)?.getAttribute('content')?.trim();+ if (v) return v.replace(/\/$/, '');+ }+ }+ try {+ const envUrl = import.meta?.env?.VITE_IRL_SERVER_URL || import.meta?.env?.VITE_WALK_SERVER_URL;+ if (envUrl) return String(envUrl).trim().replace(/\/$/, '');+ } catch (_) {}+ if (typeof location !== 'undefined') {+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';+ const host = location.hostname;+ const fwd = host.match(/^(.*)-(\d+)\.(app\.github\.dev|githubpreview\.dev|gitpod\.io)$/);+ if (fwd) return `${proto}//${fwd[1]}-2567.${fwd[3]}`;+ let isProd = false;+ try { isProd = import.meta?.env?.PROD === true; } catch (_) {}+ const isLocalHost = host === 'localhost' || host === '127.0.0.1';+ if (!isProd || isLocalHost) return `${proto}//${host}:2567`;+ return '';+ }+ return '';+}++export class IrlNet {+ /**+ * @param {object} opts+ * @param {number} opts.lat viewer latitude (picks the geocell)+ * @param {number} opts.lng viewer longitude+ * @param {string} [opts.deviceToken] anonymous device id (D2 presence / D4 attribution)+ * @param {string} [opts.agent] three.ws agent id this viewer is embodying+ * @param {string} [opts.url] override server URL (otherwise resolved from meta)+ */+ constructor(opts = {}) {+ this.lat = Number(opts.lat);+ this.lng = Number(opts.lng);+ this.deviceToken = opts.deviceToken || '';+ this.agent = opts.agent || '';+ this.url = opts.url || defaultServerUrl();+ this.geocell = encodeGeohash(this.lat, this.lng, GEOCELL_PRECISION);++ this.client = null;+ this.room = null;+ this.status = 'idle'; // idle | connecting | online | offline | failed | unavailable+ this.error = null;+ this._handlers = {+ status: new Set(),+ 'pin:add': new Set(),+ 'pin:update': new Set(),+ 'pin:remove': new Set(),+ presence: new Set(), // D2 — declared now so the event API is stable+ };+ this._retries = 0;+ this._reconnectTimer = null;+ this._destroyed = false;+ this._connectGen = 0;+ }++ on(event, fn) {+ const bucket = this._handlers[event];+ if (!bucket) throw new Error(`IrlNet: unknown event "${event}"`);+ bucket.add(fn);+ return () => bucket.delete(fn);+ }++ _emit(event, ...args) {+ for (const fn of this._handlers[event]) {+ try { fn(...args); } catch (e) { log.error(`[irl-net] ${event} handler threw:`, e); }+ }+ }++ _setStatus(status, error = null) {+ this.status = status;+ this.error = error;+ this._emit('status', { status, error });+ }++ // Detach and close the current room without triggering a reconnect — every+ // (re)connect/moveTo replaces this.room, and a leftover socket would keep firing+ // schema callbacks alongside the new one (the same duplicate-event leak walk-net+ // guards against).+ _closeRoom() {+ const room = this.room;+ if (!room) return;+ this.room = null;+ try { room.removeAllListeners(); } catch {}+ try { room.leave(); } catch {}+ }++ _pinToObj(pin) {+ return {+ id: pin.id,+ lat: pin.lat,+ lng: pin.lng,+ heading: pin.heading,+ avatarUrl: pin.avatarUrl,+ avatarName: pin.avatarName,+ caption: pin.caption,+ x402Endpoint: pin.x402Endpoint,+ agentId: pin.agentId,+ placedAt: pin.placedAt,+ };+ }++ async connect() {+ if (this._destroyed) return;+ this._closeRoom();+ // No server resolved for this environment → honest 'unavailable' (the page+ // still works via the poll fallback) instead of looping on a dead endpoint.+ if (!this.url) {+ this._setStatus('unavailable');+ return;+ }+ if (!this.geocell) {+ // No valid GPS cell yet — nothing to join; the caller polls until a fix lands.+ this._setStatus('unavailable');+ return;+ }+ const gen = ++this._connectGen;+ this._setStatus('connecting');+ try {+ this.client = new Client(this.url);+ // `geocell` is the server's filterBy key (matchmaking): every viewer in the+ // same precision-6 cell joins one room instance.+ const room = await this.client.joinOrCreate(ROOM_NAME, {+ geocell: this.geocell,+ deviceToken: this.deviceToken,+ agent: this.agent,+ lat: this.lat,+ lng: this.lng,+ }, IrlState);+ if (this._destroyed || gen !== this._connectGen) {+ try { room.leave(); } catch {}+ return;+ }+ this.room = room;+ this._retries = 0; // a clean connection resets the retry budget++ // Colyseus 0.16 moved schema callbacks behind getStateCallbacks(room).+ const $ = getStateCallbacks(this.room);+ const $pins = $(this.room.state)?.pins;+ if ($pins) {+ $pins.onAdd((pin) => {+ this._emit('pin:add', this._pinToObj(pin));+ $(pin).onChange(() => this._emit('pin:update', this._pinToObj(pin)));+ });+ $pins.onRemove((pin, id) => {+ this._emit('pin:remove', { id: pin?.id || id });+ });+ }++ this.room.onLeave((code) => {+ // A clean leave (1000) is us calling _closeRoom on destroy/moveTo — don't+ // reconnect. An unexpected drop schedules the single retry, then poll.+ if (this._destroyed || code === 1000) return;+ this._setStatus('offline');+ this._scheduleReconnect();+ });+ this.room.onError((code, message) => {+ log.warn('[irl-net] room.onError', code, message);+ });++ this._setStatus('online');+ } catch (err) {+ const reason = err?.message || (err?.code != null ? `code ${err.code}` : String(err));+ log.warn('[irl-net] connect failed:', reason);+ this._setStatus('failed', reason);+ this._scheduleReconnect();+ }+ }++ _scheduleReconnect() {+ if (this._reconnectTimer || this._destroyed) return;+ if (this._retries >= MAX_RETRIES) {+ // Out of retries — settle into 'unavailable' so the caller polls instead of+ // looping forever on a dead endpoint.+ this._setStatus('unavailable', this.error);+ return;+ }+ this._retries++;+ const delay = 2500 + Math.random() * 1500;+ this._reconnectTimer = setTimeout(() => {+ this._reconnectTimer = null;+ if (this._destroyed) return;+ this.connect();+ }, delay);+ }++ /**+ * Re-join the room for a new geocell when the viewer physically walks into one.+ * No-op while still inside the current cell (the common case — cells are ~1.2 km).+ */+ async moveTo(lat, lng) {+ this.lat = Number(lat);+ this.lng = Number(lng);+ const cell = encodeGeohash(this.lat, this.lng, GEOCELL_PRECISION);+ if (!cell || cell === this.geocell) return;+ this.geocell = cell;+ this._retries = 0; // a deliberate move gets a fresh connection budget+ await this.connect(); // leave the old room, join the new one+ }++ /** Force a reconnect (e.g. the user tapped the offline pill). */+ retry() {+ if (this._reconnectTimer) {+ clearTimeout(this._reconnectTimer);+ this._reconnectTimer = null;+ }+ this._retries = 0;+ this.connect();+ }++ destroy() {+ this._destroyed = true;+ if (this._reconnectTimer) {+ clearTimeout(this._reconnectTimer);+ this._reconnectTimer = null;+ }+ this._closeRoom();+ this.client = null;+ }+}diff --git a/src/irl.js b/src/irl.jsindex 0f38630b3..c1cbed4e4 100644--- a/src/irl.js+++ b/src/irl.js@@ -14,9 +14,11 @@ import {Group,HemisphereLight,Mesh,+ MeshBasicMaterial,MeshPhysicalMaterial,MeshStandardMaterial,OctahedronGeometry,+ OrthographicCamera,PCFShadowMap,PerspectiveCamera,PlaneGeometry,@@ -26,20 +28,31 @@ import {Scene,ShadowMaterial,SphereGeometry,+ Sprite,+ SpriteMaterial,+ SRGBColorSpace,Timer,TorusGeometry,Vector2,Vector3,WebGLRenderer,+ WebGLRenderTarget,} from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';import { WebXRSession } from './ar/webxr.js';+import { IrlNet } from './irl-net.js';+import { wireShareButton } from './irl/share-frame.js';import { log } from './shared/log.js';import { createAvatarPicker } from './avatar-picker.js';import { errorStateEl, skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry } from './shared/state-kit.js';+import { startOnboarding, ensurePermission, needsMotionGesture, setPermissionState } from './irl/onboarding.js';+import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';+import { detectTier, BUDGETS, TIER_ORDER, shiftTier } from './irl/perf-budget.js';+import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';+import { loadInto } from './shared/async-state.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';@@ -81,6 +94,11 @@ const POP_AMOUNT = 0.04; // peak +Y scale during the pop (1.0 → 1.04const params = new URLSearchParams(location.search);const avatarIdParam = params.get('avatar') || '';const highlightPinId = params.get('highlight') || '';+// Deep-focus a specific agent's pin (from an agent profile's "View in IRL" link):+// once that agent's pin loads nearby, flash it and open its inspect card. Fires+// once so it doesn't re-open the sheet on every nearby refresh.+const agentFocusId = params.get('agent') || '';+let _agentFocusDone = false;function resolveAvatarUrl(id) {if (!id) return AVATAR_URL_DEFAULT;@@ -157,6 +175,48 @@ sun.shadow.camera.bottom = -12;sun.shadow.bias = -0.0005;scene.add(sun);+// ── Performance tier + render budget (E2) ───────────────────────────────────+// IRL owns ONE long-lived WebGL context shared by every pin (all pins live in+// this single scene). Reserve it against the page-wide budget so the homepage's+// other renderers stay under the browser's ~16-context cap; never spawn a+// per-pin context. Released on pagehide.+reserveWebGLContext();+window.addEventListener('pagehide', releaseWebGLContext, { once: true });++// Pick a device class from REAL signals (cores, memory, DPR, mobile UA, GPU+// capabilities) and hold its budget. `baseTier` is the hardware ceiling: the+// runtime watchdog may degrade below it under load and recover back up to it,+// but never above what the device can actually carry.+let activeTier = detectTier(renderer);+const baseTier = activeTier;+let budget = BUDGETS[activeTier];++// One shared GLTFLoader (Draco + meshopt) behind a nearest-first, concurrency+// capped queue — replaces the old `new GLTFLoader()` per pin + `loadedCount < 5`+// guard. Priority is the pin's live camera distance (set in enforceLOD).+const glbQueue = createLoadQueue({+ run: (pin) => sharedGLTFLoader().loadAsync(pin.avatar_url),+ maxActive: budget.maxGLB,+ priorityOf: (pin) => (pin._lodDist != null ? pin._lodDist : (pin.distance_m != null ? pin.distance_m : 1e9)),+});++// Apply the active tier to the renderer + load queue. Called at boot and each+// time the watchdog steps the tier. Idempotent.+function applyTierToRenderer() {+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, budget.pixelRatio));+ renderer.setSize(window.innerWidth, window.innerHeight, false);+ const wantShadow = budget.shadow > 0;+ renderer.shadowMap.enabled = wantShadow;+ sun.castShadow = wantShadow;+ if (wantShadow && sun.shadow.mapSize.x !== budget.shadow) {+ sun.shadow.mapSize.set(budget.shadow, budget.shadow);+ // Force the shadow map to regenerate at the new resolution.+ if (sun.shadow.map) { sun.shadow.map.dispose(); sun.shadow.map = null; }+ }+ glbQueue.setMaxActive(budget.maxGLB);+}+applyTierToRenderer();+// ── Ground ────────────────────────────────────────────────────────────────const groundOpaque = new Mesh(new CircleGeometry(GROUND_RADIUS, 64),@@ -217,9 +277,20 @@ let arFrozenCamLook = null;async function enableAR() {if (!navigator.mediaDevices?.getUserMedia) {- setStatus('Camera API not available in this browser', { error: true, sticky: true });+ // Designed state via the shared guidance sheet, not a toast — the 3D scene+ // still works without the camera, so say so instead of just "unavailable".+ setPermissionState('camera', 'unsupported');+ showErrorState({+ title: 'Camera not available here',+ body: 'This browser can’t open the camera, so AR passthrough is off. The 3D scene still works — or reopen IRL in Chrome or Safari.',+ });return;}+ // Permission routes through the onboarding module (E1): a denial lands on the+ // designed card + topbar re-request chip. The granted fast-path resolves+ // immediately so AR proceeds within the same user gesture.+ const camPerm = await ensurePermission('camera');+ if (camPerm !== 'granted') return;setStatus('Requesting camera…', { loading: true, sticky: true });try {mediaStream = await navigator.mediaDevices.getUserMedia({@@ -227,10 +298,25 @@ async function enableAR() {audio: false,});} catch (err) {- const msg = err?.name === 'NotAllowedError'- ? 'Camera permission denied — allow in browser settings'- : `Camera unavailable: ${err?.message ?? err}`;- setStatus(msg, { error: true, sticky: true });+ // Clear the "Requesting camera…" progress toast, then surface a recoverable+ // card (the full onboarding copy is E1's; this is the reactive recovery).+ setStatus(null);+ if (err?.name === 'NotAllowedError') {+ setPermissionState('camera', 'denied');+ showErrorState({+ title: 'Camera access needed for AR',+ body: 'Allow camera access in your browser settings, then tap Try again to drop your agent into the real world.',+ actionLabel: 'Try again',+ onAction: enableAR,+ });+ } else {+ showErrorState({+ title: 'Couldn’t start the camera',+ body: `The camera didn’t start (${err?.message ?? err}). Close any other app using it, then tap Try again.`,+ actionLabel: 'Try again',+ onAction: enableAR,+ });+ }return;}@@ -707,13 +793,18 @@ const irlAvatarPicker = createAvatarPicker({const sp = new URLSearchParams(location.search);if (id) sp.set('avatar', id); else sp.delete('avatar');history.replaceState(null, '', location.pathname + (sp.toString() ? '?' + sp : ''));+ // Pass UUID id (not the CDN url) so loadAvatar fetches metadata+ // and captures agent_id for pin attribution (task-06). On failure show the+ // designed overlay with a Retry that re-loads this same selection.+ const retry = () => loadAvatar(id || url, name)+ .then(hideOverlay)+ .catch((err) => { log.error('[irl] avatar swap failed:', err); showAvatarLoadError(err, retry); });try {- // Pass UUID id (not the CDN url) so loadAvatar fetches metadata- // and captures agent_id for pin attribution (task-06).await loadAvatar(id || url, name);+ hideOverlay();} catch (err) {log.error('[irl] avatar swap failed:', err);- setStatus(`Couldn't load avatar: ${err?.message ?? err}`, { error: true, sticky: true });+ showAvatarLoadError(err, retry);}},});@@ -766,16 +857,24 @@ async function setLocked(next) {// A declined prompt rejects (or returns 'denied') — either way the gyro// world-lock can't work, so surface the designed recovery state instead of// silently locking a glued, sensor-less avatar.- if (next && typeof DeviceOrientationEvent?.requestPermission === 'function') {- let perm = 'denied';- try {- perm = await DeviceOrientationEvent.requestPermission();- } catch (err) {- log.error('[irl] orientation permission:', err);- }- if (perm !== 'granted') {- showMotionPermissionHelp();- return;+ // Permissions for the world-lock route through the onboarding module (E1) so a+ // denial lands on a designed recovery card + topbar chip, not a dead toast.+ // Location (the real-world anchor) surfaces its prompt and starts the GPS watch+ // the instant it is granted; motion (look-around) is gesture-gated on iOS.+ let locGranted = false;+ if (next && arActive) {+ const locState = await ensurePermission('location');+ locGranted = locState === 'granted';+ if (locGranted) initGPS();+ if (needsMotionGesture()) {+ const motionState = await ensurePermission('motion');+ if (motionState !== 'granted') {+ if (lockBtn) {+ lockBtn.setAttribute('aria-pressed', 'false');+ lockBtn.classList.remove('is-active');+ }+ return;+ }}}avatarLocked = next;@@ -800,9 +899,12 @@ async function setLocked(next) {// dropping the agent at a default origin — locking still works locally.if (gpsState.ready) {anchorGpsPin();- } else {+ } else if (locGranted) {_pendingGpsLock = true;setStatus('Waiting for location to pin precisely…', { loading: true, sticky: true });+ } else {+ // Location unavailable — lock the gyro view locally; no cross-user pin.+ setStatus('Pinned to your view — enable location to anchor it for others', { warn: true });}} else {devOrientBaseAlpha = null;@@ -870,12 +972,32 @@ if (errorActionEl) errorActionEl.addEventListener('click', () => {});if (errorDismissEl) errorDismissEl.addEventListener('click', hideErrorState);-function showMotionPermissionHelp() {- showErrorState({- title: 'Motion access needed to pin',- body: 'Pinning your agent in real space uses your phone’s motion & orientation sensors. Turn them on in Settings › Safari › Motion & Orientation Access, then tap Try again.',- actionLabel: 'Try again',- onAction: () => setLocked(true),+// ── Full-screen overlay state (E4) ─────────────────────────────────────────+// #irl-overlay is the canvas-level designed-state host (shared with the+// capability gate in irl.html). It carries states the user can't act on through+// a vanishing toast — chiefly a failed avatar load, which otherwise leaves a+// blank scene with a 3-second error message. Render a retryable card instead.+const overlayEl = document.getElementById('irl-overlay');++function hideOverlay() {+ if (overlayEl) { overlayEl.hidden = true; overlayEl.innerHTML = ''; }+}++function showAvatarLoadError(err, onRetry) {+ if (!overlayEl) {+ setStatus(`Couldn't load avatar: ${err?.message ?? err}`, { error: true, sticky: true });+ return;+ }+ ensureStateKitStyles();+ overlayEl.innerHTML = `<div class="irl-overlay-card">${errorStateHTML({+ title: "Couldn't load this agent",+ body: 'The 3D avatar failed to load. Check your connection and try again.',+ scope: 'irl-avatar',+ })}</div>`;+ overlayEl.hidden = false;+ overlayEl.querySelector('[data-sk-retry]')?.addEventListener('click', () => {+ hideOverlay();+ onRetry?.();});}@@ -986,6 +1108,9 @@ function onGPSPosition(pos) {// First fix: GPS is live, so the user can place + manage pins from here.if (!wasReady) revealMyPinsBtn();+ // First fix: open the live pin stream for this location (D1). Falls back to the+ // poll automatically if the realtime host is unreachable.+ if (!wasReady) startPinSync();// A lock was requested before the first fix — finish anchoring now that we// have real coordinates, rather than dropping the agent at a default origin.@@ -1012,10 +1137,11 @@ function onGPSPosition(pos) {}// Update world positions of all nearby agents. Because each agent's world- // position is in metres relative to the user at the origin, its live- // distance is simply hypot(x, z) — so recompute it every fix (the server's- // distance_m goes stale the moment the user moves) and lazily upgrade the- // glowing beacon to the real GLB the instant the user walks within range.+ // position is in metres relative to the user at the origin, its live distance+ // is simply hypot(x, z) — so recompute it every fix (the server's distance_m+ // goes stale the moment the user moves). The LOD/load decision is NOT made here+ // any more: enforceLOD() (4 Hz, from tick) owns band assignment and the queued+ // GLB load / impostor bake / eviction off the live camera distance.for (const p of nearbyPins) {if (!p.group) continue;// The agent being calibrated is driven by the nudge gesture this frame, not@@ -1025,13 +1151,22 @@ function onGPSPosition(pos) {p.group.position.set(wp.x, pinHeightM(p), wp.z);p.distance_m = Math.round(Math.hypot(wp.x, wp.z));updatePinRing(p);- maybeLoadPinGLB(p);}- const now = Date.now();- if (now - _lastNearbyFetch > NEARBY_INTERVAL) {- _lastNearbyFetch = now;- loadNearbyPins();+ // Live transport: re-join the room when we cross into a new geocell, and+ // reconcile the rendered set against the stream as the viewer walks (pins move+ // into / out of the nearby radius). Not streaming and not yet polling → keep the+ // throttled poll so the first fixes still show content before the transport+ // settles; once the poll fallback's own timer owns refreshes, this stays quiet.+ if (irlNet && _streamOnline) {+ irlNet.moveTo(gpsState.lat, gpsState.lng);+ scheduleReconcile();+ } else if (!_pollTimer) {+ const now = Date.now();+ if (now - _lastNearbyFetch > NEARBY_INTERVAL) {+ _lastNearbyFetch = now;+ loadNearbyPins();+ }}}@@ -1065,8 +1200,11 @@ function anchorGpsPin() {}function onGPSError(err) {- // Only intervene when a placement is actively waiting on a fix — otherwise a- // transient watchPosition timeout shouldn't disturb a working session.+ // A revoked location permission always surfaces a re-request chip (E1), even+ // outside an active pin attempt.+ if (err && err.code === err.PERMISSION_DENIED) setPermissionState('location', 'denied');+ // Only intervene with a sheet when a placement is actively waiting on a fix —+ // a transient watchPosition timeout shouldn't disturb a working session.if (!_pendingGpsLock) return;_pendingGpsLock = false;const denied = err && err.code === err.PERMISSION_DENIED;@@ -1082,6 +1220,7 @@ function onGPSError(err) {function initGPS() {if (!navigator.geolocation) return;+ if (gpsState.watchId != null) return; // idempotent — onboarding, boot, and Pin may all callgpsState.watchId = navigator.geolocation.watchPosition(onGPSPosition,onGPSError,@@ -1128,10 +1267,41 @@ async function savePin(lat, lng, heading = 0, caption = '', anchor = null) {anchor: anchorBody,}),});- if (!r.ok) return null;+ if (!r.ok) {+ // Surface the server's designed moderation/cap/rate rejection (D4) so the+ // caller can show an actionable message instead of a silent failure.+ let payload = {};+ try { payload = await r.json(); } catch {}+ return {+ ok: false,+ status: r.status,+ error: payload.error || 'error',+ message: payload.message || saveErrorFallback(payload.error),+ retryAfter: Number.isFinite(payload.retryAfter) ? payload.retryAfter : null,+ };+ }const data = await r.json();- return data.pin ? { id: data.pin.id, permanent: !!data.pin.permanent } : null;- } catch { return null; }+ return data.pin+ ? { ok: true, id: data.pin.id, permanent: !!data.pin.permanent }+ : { ok: false, error: 'error', message: saveErrorFallback() };+ } catch {+ return { ok: false, error: 'network', message: saveErrorFallback('network') };+ }+}++// Human fallback for a placement rejection when the server didn't ship a message.+// The API always sends one for D4 rejections; this covers network/parse gaps.+function saveErrorFallback(code) {+ switch (code) {+ case 'content': return 'That text isn’t allowed on a public pin. Try rewording it.';+ case 'coin': return 'A pin can only reference $THREE.';+ case 'endpoint': return 'Pay endpoints must be hosted on three.ws.';+ case 'area_full': return 'This area already has the maximum number of agents. Try another spot.';+ case 'pin_limit': return 'You’ve reached your active pin limit. Remove an old pin first.';+ case 'rate': return 'You’re placing agents too fast. Wait a moment and try again.';+ case 'network': return 'Couldn’t reach the server — check your connection and try again.';+ default: return 'Couldn’t place the agent. Try again.';+ }}// ── Caption panel (pre-save) ──────────────────────────────────────────────@@ -1169,14 +1339,21 @@ function commitPin(pinLat, pinLng, headingDeg, caption, source = 'gyro-gps') {// from the live GPS fix inside savePin().const anchor = { heightM: 0, yawDeg: headingDeg, source };savePin(pinLat, pinLng, headingDeg, caption, anchor).then(result => {- if (result && gpsPin) {+ if (result?.ok && gpsPin) {gpsPin.id = result.id;_myPinIds.add(result.id);+ dropOwnPinFromStream(result.id); // the server echoes my pin over the stream; never double-spawn itconst dir = compassLabel(headingDeg);setStatus(result.permanent? `Pinned facing ${dir} — permanently visible to nearby users`: `Pinned facing ${dir} — others nearby can see you for 7 days`);revealMyPinsBtn();+ } else {+ // Rejected (content / area_full / pin_limit / rate / network) — show the+ // designed, actionable message and release the lock so the user can fix it+ // and retry, never a silent dead end.+ setStatus(result?.message || saveErrorFallback(result?.error), { error: true });+ setLocked(false);}});}@@ -1356,14 +1533,16 @@ function persistFloorAnchor(pose) {quat: [quaternion.x, quaternion.y, quaternion.z, quaternion.w],source: 'webxr',}).then(result => {- if (result && gpsPin) {+ if (result?.ok && gpsPin) {gpsPin.id = result.id;+ dropOwnPinFromStream(result.id); // the server echoes my pin over the stream; never double-spawn itrevealMyPinsBtn();setXrHint(result.permanent? 'Anchored & saved — permanently visible to nearby users': 'Anchored & saved — nearby users can see you for 7 days');} else {- setXrHint('Anchored here — couldn’t save the pin, retry on exit');+ // Surface the moderation/cap/rate reason; the in-session anchor still holds.+ setXrHint(result?.message || 'Anchored here — couldn’t save the pin, retry on exit');}});}@@ -1381,17 +1560,235 @@ if (xrOverlay) {});}+// Composite share — flatten the camera feed (when AR is on) under the 3D canvas+// into one PNG and offer it through the native share sheet, desktop download, or+// URL/clipboard fallback. Shared module so /irl and /xr never drift; the renderer+// is built with preserveDrawingBuffer:true so the canvas reads back non-blank.+wireShareButton($('irl-share-btn'), {+ getCanvas: () => canvas,+ getVideo: () => videoEl,+ getIsAR: () => arActive,+ filename: 'three-ws-irl.png',+ title: 'IRL · three.ws',+});+// ── Nearby agents ─────────────────────────────────────────────────────────let nearbyPins = []; // [{ id, lat, lng, avatar_url, avatar_name, caption, x402_endpoint, distance_m, group, labelEl, glbLoaded }]+// Set true when the last nearby fetch failed; cleared on the next good fetch, so+// a failed refresh shows a visible indicator on the badge instead of going silent.+let _nearbyError = false;++// Briefly tint a pin's floating label so a deep-linked target (?highlight= or+// ?agent=) is easy to spot among the nearby agents. No-op for a missing pin/label.+function flashPinLabel(pin) {+ const label = pin?.labelEl;+ if (!label) return;+ label.style.transition = 'background .2s, color .2s';+ label.style.background = 'rgba(139,92,246,0.9)';+ label.style.color = '#fff';+ setTimeout(() => {+ if (pin.labelEl) {+ pin.labelEl.style.background = '';+ pin.labelEl.style.color = '';+ }+ }, 2500);+}++// Free every GPU resource a pin holds: cancel any queued load, dispose the group+// (geometry/materials/textures of dot, ring, model and impostor sprite) and the+// impostor render target's framebuffer (not reached by the group traversal), then+// drop the DOM label. The single place that knows the full E2 resource set.+function disposePin(p) {+ cancelPinGLB(p);+ if (p.group) { scene.remove(p.group); disposeObject3D(p.group); }+ if (p._impostorRT) { p._impostorRT.dispose(); p._impostorRT = null; }+ if (p.labelEl) p.labelEl.remove();+}++// Drop one nearby pin from the scene now — disposing its GPU resources — instead+// of waiting for the next loadNearbyPins() reconcile. Used when a pin is hidden by+// a report (D4) so the reporter sees it vanish immediately.+function removeNearbyPin(id) {+ nearbyPins = nearbyPins.filter(p => {+ if (p.id !== id) return true;+ disposePin(p);+ return false;+ });+ updateNearbyBadge();+}++// ── Realtime pin sync (D1) ──────────────────────────────────────────────────+// Polling told you about a new / moved / removed pin only on the next 15 s cycle.+// This streams them live: IrlNet joins the irl_world room for the viewer's geocell+// and relays the shared pin set as pin:add / pin:update / pin:remove, which we+// reconcile into the SAME nearbyPins the poll feeds — so the rest of the app (LOD,+// radar, sheet, badge) never knows which transport fed it. The poll stays as a+// real fallback for when the realtime host is unreachable.+let irlNet = null;+let _streamOnline = false; // true only while the WS is live and owns nearbyPins+let _pollTimer = null; // fallback poll interval handle+let _reconcileRaf = 0; // coalesces a burst of stream events into one reconcile+const streamPins = new Map(); // id → normalized snake_case pin (the room's full window)+const POLL_FALLBACK_MS = 10000; // fallback refresh cadence when the stream is down++// Map the room's camelCase wire pin to the snake_case shape the rest of irl.js+// already reads (spawnNearbyPin / openPinSheet / radar), so those paths are untouched.+function normalizeStreamPin(w) {+ return {+ id: w.id,+ lat: Number(w.lat),+ lng: Number(w.lng),+ heading: Number(w.heading) || 0,+ avatar_url: w.avatarUrl || null,+ avatar_name: w.avatarName || null,+ caption: w.caption || null,+ x402_endpoint: w.x402Endpoint || null,+ agent_id: w.agentId || null,+ placed_at: w.placedAt || null,+ };+}++function startPinSync() {+ if (!gpsState.ready) return;+ if (irlNet) irlNet.destroy();+ streamPins.clear();+ irlNet = new IrlNet({+ lat: gpsState.lat, lng: gpsState.lng,+ deviceToken: _deviceToken, agent: _currentAgentId || '',+ });+ irlNet.on('pin:add', (w) => ingestStreamPin('add', w));+ irlNet.on('pin:update', (w) => ingestStreamPin('update', w));+ irlNet.on('pin:remove', (w) => ingestStreamPin('remove', w));+ irlNet.on('status', ({ status }) => onNetStatus(status));+ irlNet.connect();+}++function onNetStatus(status) {+ _streamOnline = status === 'online';+ if (status === 'online') { stopPollFallback(); setNetPill('live'); scheduleReconcile(); }+ else if (status === 'connecting') { streamPins.clear(); setNetPill('connecting'); }+ else if (status === 'offline') { setNetPill('connecting'); } // mid single-retry — pins persist+ else { startPollFallback(); setNetPill('polling'); } // failed | unavailable | idle+}++function ingestStreamPin(kind, wire) {+ if (!wire || !wire.id) return;+ if (kind === 'remove') streamPins.delete(wire.id);+ else streamPins.set(wire.id, normalizeStreamPin(wire));+ scheduleReconcile();+}++// Coalesce the burst of onAdd callbacks Colyseus fires on join (and any flurry of+// deltas) into a single reconcile next frame.+function scheduleReconcile() {+ if (_reconcileRaf) return;+ _reconcileRaf = requestAnimationFrame(() => { _reconcileRaf = 0; reconcileFromStream(); });+}++// Reconcile the rendered nearby set against the live stream, filtered to the nearby+// radius — the room holds a coarse ~3 km geocell window, so the per-viewer 150 m+// filter lives here. Spawns arrivals, refreshes changed pins, despawns pins that+// left the radius or were removed. The placer's own live pin is never doubled.+function reconcileFromStream() {+ if (!_streamOnline || !gpsState.ready) return;+ for (const known of [...nearbyPins]) {+ const src = streamPins.get(known.id);+ const within = src && Number.isFinite(src.lat) &&+ haversineMeters(gpsState.lat, gpsState.lng, src.lat, src.lng) <= NEARBY_RADIUS;+ if (!within) removeNearbyPin(known.id);+ }+ for (const [id, src] of streamPins) {+ if (gpsPin?.id && id === gpsPin.id) continue; // never my own anchored pin+ if (!Number.isFinite(src.lat) || !Number.isFinite(src.lng)) continue;+ const d = haversineMeters(gpsState.lat, gpsState.lng, src.lat, src.lng);+ if (d > NEARBY_RADIUS) continue;+ const known = nearbyPins.find((n) => n.id === id);+ if (known) applyStreamFields(known, src);+ else {+ const entry = { ...src, distance_m: Math.round(d), group: null, labelEl: null, glbLoaded: false };+ nearbyPins.push(entry);+ spawnNearbyPin(entry);+ }+ }+ updateNearbyBadge();+}++// Update a rendered pin from a stream delta: position / heading / caption / name+// (which applyPinUpdate skips when there's no avatar version bump — the stream has+// none), then hand off to applyPinUpdate for the avatar GLB swap (a C6 re-skin),+// which no-ops when the URL is unchanged.+function applyStreamFields(known, src) {+ if (Number.isFinite(src.lat)) known.lat = src.lat;+ if (Number.isFinite(src.lng)) known.lng = src.lng;+ if (src.heading != null) known.heading = src.heading;+ if (src.caption !== undefined) known.caption = src.caption;+ if (src.x402_endpoint !== undefined) known.x402_endpoint = src.x402_endpoint;+ // Name lives on the floating label; update it here because applyPinUpdate only+ // reaches its name branch on an avatar change, so a rename-only edit would miss it.+ if (src.avatar_name != null && src.avatar_name !== known.avatar_name) {+ known.avatar_name = src.avatar_name;+ const nameEl = known.labelEl?.querySelector('.irl-agent-label-name');+ if (nameEl) nameEl.textContent = known.avatar_name || 'Agent';+ }+ if (known.group) {+ const wp = gpsToWorld(known.lat, known.lng);+ known.group.position.set(wp.x, pinHeightM(known), wp.z);+ known.group.rotation.y = pinYawRad(known);+ if ('baseYaw' in known) known.baseYaw = known.group.rotation.y;+ }+ applyPinUpdate(known, src);+}++// When this device places its own pin, the server echoes it back over the stream;+// drop it so the placer never sees a duplicate of their own anchored agent.+function dropOwnPinFromStream(id) {+ if (!id) return;+ streamPins.delete(id);+ removeNearbyPin(id);+}++function startPollFallback() {+ if (_pollTimer) return;+ loadNearbyPins(); // immediate refresh, don't wait a full cycle+ _pollTimer = setInterval(loadNearbyPins, POLL_FALLBACK_MS);+}+function stopPollFallback() {+ if (_pollTimer) { clearInterval(_pollTimer); _pollTimer = null; }+}++// The realtime status pill in the topbar: live (green), connecting (amber pulse),+// or polling (the fallback transport is active — still fully functional, tap to retry).+function setNetPill(state) {+ const pill = document.getElementById('irl-net-pill');+ if (!pill) return;+ pill.classList.remove('is-live', 'is-connecting', 'is-polling');+ if (state === 'live') {+ pill.classList.add('is-live'); pill.hidden = false;+ pill.textContent = 'Live'; pill.title = 'Live — nearby agents update in realtime';+ } else if (state === 'connecting') {+ pill.classList.add('is-connecting'); pill.hidden = false;+ pill.textContent = 'Connecting'; pill.title = 'Connecting to live sync…';+ } else if (state === 'polling') {+ pill.classList.add('is-polling'); pill.hidden = false;+ pill.textContent = 'Polling'; pill.title = 'Live sync unavailable — refreshing nearby agents every 10s. Tap to retry.';+ } else {+ pill.hidden = true;+ }+ pill.setAttribute('aria-label', `Realtime status: ${pill.textContent || 'idle'}`);+}async function loadNearbyPins() {if (!gpsState.ready) return;+ // While the live stream owns the nearby set, the poll is a no-op — it would fight+ // the reconcile. It runs only as the fallback transport (see startPollFallback).+ if (_streamOnline) return;try {const r = await fetch(`/api/irl/pins?lat=${gpsState.lat}&lng=${gpsState.lng}&radius=${NEARBY_RADIUS}`,);- if (!r.ok) return;+ if (!r.ok) { _nearbyError = true; updateNearbyBadge(); return; }const { pins } = await r.json();+ _nearbyError = false;const incoming = pins.filter(p => !gpsPin?.id || p.id !== gpsPin.id);const inIds = new Set(incoming.map(p => p.id));@@ -1401,14 +1798,19 @@ async function loadNearbyPins() {// freeing geometries/materials/textures a long session leaks steadily.nearbyPins = nearbyPins.filter(p => {if (inIds.has(p.id)) return true;- if (p.group) { scene.remove(p.group); disposeObject3D(p.group); }- if (p.labelEl) p.labelEl.remove();+ disposePin(p);return false;});- // Spawn new arrivals+ // Spawn new arrivals; refresh any already-known pin whose owner re-skinned+ // it (C6 remote outfit change). The nearby feed carries avatar_version, so a+ // bumped version on a pin we already render means swap its GLB to the new+ // (versioned, cache-busted) avatar_url — every viewer sees the new look on+ // the next poll, the same diff D1's pin_updated push reuses in realtime.for (const pin of incoming) {- if (!nearbyPins.find(n => n.id === pin.id)) {+ const known = nearbyPins.find(n => n.id === pin.id);+ if (known) applyPinUpdate(known, pin);+ else {const entry = { ...pin, group: null, labelEl: null, glbLoaded: false };nearbyPins.push(entry);spawnNearbyPin(entry);@@ -1419,20 +1821,26 @@ async function loadNearbyPins() {// Flash pin label if ?highlight= matchesif (highlightPinId) {- const target = nearbyPins.find(p => p.id === highlightPinId);- if (target?.labelEl) {- target.labelEl.style.transition = 'background .2s, color .2s';- target.labelEl.style.background = 'rgba(139,92,246,0.9)';- target.labelEl.style.color = '#fff';- setTimeout(() => {- if (target.labelEl) {- target.labelEl.style.background = '';- target.labelEl.style.color = '';- }- }, 2500);+ flashPinLabel(nearbyPins.find(p => p.id === highlightPinId));+ }++ // Deep-focus this agent's pin if ?agent= matches one that just loaded — flash+ // its label and open its inspect card so an agent profile's "View in IRL"+ // link lands the visitor right on that agent. Once only (see _agentFocusDone).+ if (agentFocusId && !_agentFocusDone) {+ const target = nearbyPins.find(p => String(p.agent_id) === agentFocusId);+ if (target) {+ _agentFocusDone = true;+ flashPinLabel(target);+ openPinSheet(target);}}- } catch {}+ } catch {+ // Don't fail silently — a busy spot that can't load looks identical to an+ // empty one otherwise. Flag it on the badge; the 15 s poll retries.+ _nearbyError = true;+ updateNearbyBadge();+ }}// ── Confidence ring (A3) ────────────────────────────────────────────────────@@ -1492,17 +1900,20 @@ function spawnNearbyPin(pin) {g.position.set(wp.x, pinHeightM(pin), wp.z);g.rotation.y = pinYawRad(pin);- // Glowing beacon placeholder (replaced by real GLB when close)- const beacon = new Mesh(- new SphereGeometry(0.22, 24, 18),- new MeshPhysicalMaterial({- color: 0x88bbff, emissive: 0x1a44ff, emissiveIntensity: 0.9,- metalness: 0.1, roughness: 0.06, transmission: 0.35, thickness: 0.3,- }),+ // Cheap unlit "dot" — the agent's far/low-cost representation (E2). The old+ // placeholder was a transmission+emissive MeshPhysicalMaterial sphere with a+ // shadow: far too expensive for a marker that's often just a distant speck and+ // multiplied across dozens of pins. enforceLOD() promotes this to an impostor+ // billboard, then the full skinned GLB, as the viewer approaches — and demotes+ // back as they leave. The dot, ring and label persist for the pin's lifetime;+ // only the model + impostor are swapped in and out.+ const dot = new Mesh(+ new SphereGeometry(0.18, 12, 8),+ new MeshBasicMaterial({ color: 0x88bbff }),);- beacon.position.y = 1.2;- beacon.castShadow = true;- g.add(beacon);+ dot.position.y = 1.2;+ g.add(dot);+ pin.dotMesh = dot;pin.group = g;// Cache the owning pin on the group so a mesh raycast (_pinForObject) maps a// hit back to its agent without scanning nearbyPins per node.@@ -1529,9 +1940,9 @@ function spawnNearbyPin(pin) {document.body.appendChild(el);pin.labelEl = el;- // Load the real GLB if the user is already close; otherwise it upgrades from- // the beacon automatically as they approach (see maybeLoadPinGLB on GPS fix).- maybeLoadPinGLB(pin);+ // No load here: enforceLOD() (4 Hz, from tick) assigns this pin a band from its+ // live camera distance and the active budget, and drives the queued GLB load /+ // impostor bake / eviction. The dot is visible immediately in the meantime.}function _escHtml(s) {@@ -1555,77 +1966,236 @@ function disposeObject3D(root) {});}-// At most this many remote agents render their full GLB at once; the rest stay-// lightweight glowing beacons until the user gets close. Keeps a crowded-// location from loading a dozen rigged models simultaneously.-const MAX_LOADED_GLB = 5;--// Load a pin's real avatar GLB once the user is within range — idempotent, so-// it's safe to call every GPS fix. This is what turns the beacon into the agent-// as you walk up to it.-function maybeLoadPinGLB(pin) {+// ── GLB load queue, impostor bake + eviction (E2) ───────────────────────────+//+// Pins no longer each `new GLTFLoader()` behind a crude count gate; they go+// through the shared, nearest-first, concurrency-capped `glbQueue`. Every GLB+// that loads is baked ONCE into a small impostor texture, so when the agent+// later recedes past lodNear we drop the skinned mesh (freeing geometry /+// materials / textures) and show a ~1 draw-call billboard instead — bounded+// memory no matter how many pins the user walks past. Re-approach re-queues the+// full model. enforceLOD() (below) decides each pin's band and drives all this.++// Shared offscreen rig for impostor snapshots. Renders to a render target with+// the MAIN renderer — no extra WebGL context, so the page's context budget is+// untouched. Created lazily on the first bake.+const IMPOSTOR_PX = 256;+let _snapScene = null, _snapCam = null;+function _ensureSnapRig() {+ if (_snapScene) return;+ _snapScene = new Scene();+ _snapCam = new OrthographicCamera(-1, 1, 1, -1, 0.01, 100);+ _snapScene.add(new AmbientLight(0xffffff, 0.9));+ const key = new DirectionalLight(0xffffff, 1.25);+ key.position.set(2, 4, 5);+ _snapScene.add(key);+}++const _snapBox = new Box3();+const _snapSize = new Vector3();+const _snapCenter = new Vector3();+// Render `model` head-on to a fresh render target; return { rt, side, centerY }.+// `side` is the world size of the square billboard; `centerY` its local centre so+// the impostor's feet land where the model's did.+function bakeImpostor(model) {+ _ensureSnapRig();+ _snapBox.setFromObject(model);+ _snapBox.getSize(_snapSize);+ _snapBox.getCenter(_snapCenter);+ const side = (Math.max(_snapSize.x, _snapSize.y, _snapSize.z) * 1.08) || 1;+ const half = side / 2;+ _snapCam.left = -half; _snapCam.right = half; _snapCam.top = half; _snapCam.bottom = -half;+ _snapCam.near = 0.01; _snapCam.far = side * 4 + 10;+ _snapCam.position.set(_snapCenter.x, _snapCenter.y, _snapCenter.z + side * 2 + 1);+ _snapCam.lookAt(_snapCenter.x, _snapCenter.y, _snapCenter.z);+ _snapCam.updateProjectionMatrix();++ const rt = new WebGLRenderTarget(IMPOSTOR_PX, IMPOSTOR_PX);+ rt.texture.colorSpace = SRGBColorSpace;+ _snapScene.add(model);+ const prevTarget = renderer.getRenderTarget();+ renderer.setRenderTarget(rt);+ renderer.clear(); // page clear colour is transparent → cutout bg+ renderer.render(_snapScene, _snapCam);+ renderer.setRenderTarget(prevTarget);+ _snapScene.remove(model);+ return { rt, side, centerY: _snapCenter.y };+}++function disposeImpostor(pin) {+ if (pin._impostorSprite) {+ pin.group?.remove(pin._impostorSprite);+ pin._impostorSprite.material.dispose();+ pin._impostorSprite = null;+ }+ if (pin._impostorRT) { pin._impostorRT.dispose(); pin._impostorRT = null; }+ pin._impostorSide = 0; pin._impostorCenterY = 0;+}++function showImpostor(pin) {+ if (!pin._impostorRT) return false;+ if (!pin._impostorSprite) {+ const mat = new SpriteMaterial({ map: pin._impostorRT.texture, transparent: true, depthWrite: false });+ const sp = new Sprite(mat);+ sp.scale.set(pin._impostorSide, pin._impostorSide, 1);+ sp.position.y = pin._impostorCenterY;+ sp.userData.impostor = true;+ pin.group.add(sp);+ pin._impostorSprite = sp;+ }+ pin._impostorSprite.visible = true;+ return true;+}+function hideImpostor(pin) { if (pin._impostorSprite) pin._impostorSprite.visible = false; }+function showDot(pin) { if (pin.dotMesh) pin.dotMesh.visible = true; }+function hideDot(pin) { if (pin.dotMesh) pin.dotMesh.visible = false; }++// Enqueue a pin's GLB through the shared queue. `bakeOnly` loads purely to bake+// the impostor (the model is disposed right after) — used for mid-distance pins+// that have never been close. Idempotent while a load is in flight.+function requestPinGLB(pin, bakeOnly = false) {if (pin.glbLoaded || pin._glbLoading || !pin.avatar_url) return;- if (pin.distance_m >= 80) return;- const loadedCount = nearbyPins.filter(p => p.glbLoaded || p._glbLoading).length;- if (loadedCount >= MAX_LOADED_GLB) return;- loadPinGLB(pin);-}--async function loadPinGLB(pin) {+ if (bakeOnly && pin._impostorRT) return; // already have a snapshotpin._glbLoading = true;- try {- const gltf = await new GLTFLoader().loadAsync(pin.avatar_url);- // The pin may have been removed (walked out of range) while the GLB- // was in flight — free the just-loaded model rather than orphaning it.- if (!pin.group) { disposeObject3D(gltf.scene); return; }- const model = gltf.scene;- model.traverse(n => { if (n.isMesh) n.castShadow = true; });- const box = new Box3().setFromObject(model);- model.position.y -= box.min.y;- // Dispose the placeholder beacon before swapping in the real model.- while (pin.group.children.length) {- const child = pin.group.children[0];- pin.group.remove(child);- disposeObject3D(child);- }- pin.group.add(model);- pin.glbLoaded = true;- // Re-apply the stored absolute pose — the GLTF swap (and the dispose loop- // above, which also removed the confidence ring) reset the group transform.- pin.group.rotation.y = pinYawRad(pin);- pin.group.position.y = pinHeightM(pin);- attachPinRing(pin);- updatePinRing(pin);-- // Cache the head/torso bone + rest pose once so the per-frame awareness- // step never walks the tree. baseYaw is the placed heading we ease back to- // when the viewer leaves; the gaze bone (head preferred, torso fallback)- // drives the "looks at you" turn. Agents with neither just turn whole-body.- pin.baseYaw = pin.group.rotation.y;- pin.headBone = null; pin.spineBone = null;- model.traverse(n => {- if (!n.isBone) return;- const nm = n.name.toLowerCase();- if (!pin.headBone && /head|neck/.test(nm)) pin.headBone = n;- if (!pin.spineBone && /spine|chest|torso/.test(nm)) pin.spineBone = n;+ pin._bakeOnly = bakeOnly;+ glbQueue.request(pin)+ .then(gltf => onPinGLBLoaded(pin, gltf))+ .catch(() => { /* network/CDN blip or cancelled — a later LOD pass retries */ })+ .finally(() => {+ pin._glbLoading = false;+ pin._bakeOnly = false;+ // A re-skin (C6) that arrived mid-load fetched the OLD url — swap again.+ if (pin._reloadQueued) { pin._reloadQueued = false; reloadPinGLB(pin); }});- pin.restHeadQuat = pin.headBone ? pin.headBone.quaternion.clone() : null;- pin.restSpineQuat = pin.spineBone ? pin.spineBone.quaternion.clone() : null;- pin.idleT = 0; // idle-drift phase clock- pin.noticed = false; // has the viewer already crossed the notice radius?- pin.noticeT = 0; // remaining head-slerp boost time after a notice- pin.popT = -1; // perk-up pop clock (-1 = inactive)- } catch {- // Allow a later GPS fix to retry the load (transient network/CDN blip).- } finally {- pin._glbLoading = false;+}++function onPinGLBLoaded(pin, gltf) {+ // The pin may have been removed (walked out of the fetch radius) mid-flight.+ if (!pin.group) { disposeObject3D(gltf.scene); return; }+ const model = gltf.scene;+ const castShadow = budget.shadow > 0;+ model.traverse(n => { if (n.isMesh) { n.castShadow = castShadow; n.frustumCulled = false; } });+ const box = new Box3().setFromObject(model);+ model.position.y -= box.min.y; // feet to ground++ // Bake the impostor once; reused whenever this agent later recedes past lodNear.+ if (!pin._impostorRT) {+ try {+ const imp = bakeImpostor(model);+ pin._impostorRT = imp.rt; pin._impostorSide = imp.side; pin._impostorCenterY = imp.centerY;+ } catch { /* impostor unavailable — the pin falls back to its dot */ }+ }++ // If the viewer receded past lodNear during the load (or this was a bake-only+ // request), don't mount the skinned mesh — the impostor we just baked covers it.+ if (pin._bakeOnly || pin._lod !== 'full') {+ disposeObject3D(model);+ if (pin._lod === 'impostor') { hideDot(pin); showImpostor(pin); }+ return;}++ // Mount the full skinned avatar; hide the cheaper representations.+ hideDot(pin); hideImpostor(pin);+ pin.group.add(model);+ pin.model = model;+ pin.glbLoaded = true;+ pin.group.rotation.y = pinYawRad(pin);+ pin.group.position.y = pinHeightM(pin);++ // Cache the head/torso bone + rest pose once so the per-frame awareness step+ // (camera-aware gaze, B1) never walks the tree. baseYaw is the placed heading+ // we ease back to; the gaze bone (head preferred, torso fallback) drives the+ // "looks at you" turn. Agents with neither just turn whole-body.+ pin.baseYaw = pin.group.rotation.y;+ pin.headBone = null; pin.spineBone = null;+ model.traverse(n => {+ if (!n.isBone) return;+ const nm = n.name.toLowerCase();+ if (!pin.headBone && /head|neck/.test(nm)) pin.headBone = n;+ if (!pin.spineBone && /spine|chest|torso/.test(nm)) pin.spineBone = n;+ });+ pin.restHeadQuat = pin.headBone ? pin.headBone.quaternion.clone() : null;+ pin.restSpineQuat = pin.spineBone ? pin.spineBone.quaternion.clone() : null;+ pin.idleT = 0; // idle-drift phase clock+ pin.noticed = false; // has the viewer already crossed the notice radius?+ pin.noticeT = 0; // remaining head-slerp boost time after a notice+ pin.popT = -1; // perk-up pop clock (-1 = inactive)+}++// Evict a pin's skinned GLB — dispose geometry/materials/textures and fall back to+// the cheaper representation. The impostor snapshot + dot + ring persist, so this+// is reversible: enforceLOD re-queues the full model on re-approach. Bounded+// memory regardless of how many pins the user walks past.+function evictPinGLB(pin) {+ if (!pin.glbLoaded || !pin.model) return;+ pin.group.remove(pin.model);+ disposeObject3D(pin.model);+ pin.model = null;+ pin.glbLoaded = false;+ pin.headBone = pin.spineBone = null;+ pin.restHeadQuat = pin.restSpineQuat = null;+}++// Cancel a still-queued (not yet started) load when a pin is culled.+function cancelPinGLB(pin) {+ if (pin._glbLoading) glbQueue.cancel(p => p === pin);+}++// Apply a re-skin (C6) detected by the nearby-poll diff or a D1 pin_updated push:+// adopt the new versioned avatar_url + name and swap the rendered GLB. Cheap when+// nothing changed (version equal) so it's safe to call for every incoming pin.+function applyPinUpdate(pin, next) {+ const nextVer = Number(next.avatar_version) || 0;+ const prevVer = Number(pin.avatar_version) || 0;+ const urlChanged = next.avatar_url && next.avatar_url !== pin.avatar_url;+ if (nextVer === prevVer && !urlChanged) return;++ pin.avatar_version = nextVer || prevVer;+ if (next.avatar_url) pin.avatar_url = next.avatar_url;+ if (next.avatar_name != null && next.avatar_name !== pin.avatar_name) {+ pin.avatar_name = next.avatar_name;+ const nameEl = pin.labelEl?.querySelector('.irl-agent-label-name');+ if (nameEl) nameEl.textContent = pin.avatar_name || 'Agent';+ }+ reloadPinGLB(pin);+}++// Swap a pin's rendered GLB to its current avatar_url after a re-skin (C6). Safe+// whether the pin is mid-load (queues the swap for when the in-flight load+// settles), or already showing a model/impostor. The baked impostor + mounted+// model are of the OLD avatar, so drop both and reset the LOD band; enforceLOD+// re-bakes and re-mounts from the new (versioned, cache-busting) url next pass.+function reloadPinGLB(pin) {+ if (pin._glbLoading) { pin._reloadQueued = true; return; }+ evictPinGLB(pin);+ disposeImpostor(pin);+ pin._lod = null; // force enforceLOD to re-evaluate + reload this pin+ showDot(pin);+}++// Realtime hook (D1) — entry point a `pin_updated { id, avatar_url,+// avatar_version }` event calls so co-located viewers swap a re-skinned agent's+// GLB the instant the owner saves, without waiting for the next nearby poll. The+// poll diff is the durable fallback; this just makes it feel instant. When Epic+// D's geohash-room transport lands, dispatch its pin_updated payloads here.+export function handleRealtimePinUpdate(evt) {+ if (!evt || evt.type !== 'pin_updated' || !evt.id) return;+ const pin = nearbyPins.find(p => p.id === evt.id);+ if (pin) applyPinUpdate(pin, evt);}function updateNearbyBadge() {const badge = document.getElementById('irl-nearby-badge');if (!badge) return;const n = nearbyPins.length;+ if (_nearbyError) {+ // Visible, not silent: the 15 s poll retries; show we know the data is stale.+ badge.textContent = n > 0 ? `${n} nearby · refresh failed` : 'Couldn’t load nearby — retrying…';+ badge.hidden = false;+ badge.classList.add('is-error');+ return;+ }+ badge.classList.remove('is-error');badge.textContent = n > 0 ? `${n} nearby` : '';badge.hidden = n === 0;}@@ -1671,23 +2241,31 @@ function _pinMetaLine(p) {return parts.join(' · ');}+// Designed empty state for the My-pins sheet — shared by loadInto (sheet open)+// and deleteMyPin (when the last pin is removed) so the copy never diverges.+const MYPINS_EMPTY = {+ icon: '📍',+ title: 'No active pins yet',+ body: 'Pin your agent to a real-world spot and it shows up here to manage.',+};++// Throws on failure (network or non-2xx) so callers can tell a real error from a+// genuinely empty list — openMyPinsSheet routes that through loadInto's error+// state instead of silently showing "no pins". Returns [] only when this device+// has no token yet (nothing could have been placed).async function loadMyPins() {if (!_deviceToken) return [];- try {- const r = await fetch(`/api/irl/pins/mine?deviceToken=${encodeURIComponent(_deviceToken)}`, {- credentials: 'include',- });- if (!r.ok) return [];- const pins = (await r.json()).pins ?? [];- // Track which nearby pins this device owns so the calibrate affordance (and- // the gold "your agent" label) light up. The server re-checks ownership on- // PATCH, so this is purely a client-side gate.- for (const p of pins) _myPinIds.add(p.id);- refreshOwnLabels();- return pins;- } catch {- return [];- }+ const r = await fetch(`/api/irl/pins/mine?deviceToken=${encodeURIComponent(_deviceToken)}`, {+ credentials: 'include',+ });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const pins = (await r.json()).pins ?? [];+ // Track which nearby pins this device owns so the calibrate affordance (and+ // the gold "your agent" label) light up. The server re-checks ownership on+ // PATCH, so this is purely a client-side gate.+ for (const p of pins) _myPinIds.add(p.id);+ refreshOwnLabels();+ return pins;}// Re-mark already-spawned nearby labels as own once /mine resolves (the pins may@@ -1698,13 +2276,11 @@ function refreshOwnLabels() {}}-function renderMyPins(pins) {- const list = document.getElementById('irl-mypins-list');+// Renders the populated list into the sheet container. Empty/error/loading are+// owned by loadInto in openMyPinsSheet — this only paints rows.+function renderMyPins(pins, listEl) {+ const list = listEl || document.getElementById('irl-mypins-list');if (!list) return;- if (!pins.length) {- list.innerHTML = '<p class="irl-mypins-empty">No active pins yet — pin your agent to a real-world spot and it shows up here.</p>';- return;- }list.innerHTML = pins.map(p => `<div class="irl-pin-row" data-pid="${_escHtml(p.id)}"><div class="irl-pin-info"><div class="irl-pin-name">${_escHtml(p.avatar_name || 'Agent')}</div>@@ -1720,8 +2296,16 @@ async function openMyPinsSheet() {const list = document.getElementById('irl-mypins-list');if (!sheet || !list) return;sheet.classList.add('is-open');- list.innerHTML = '<p class="irl-mypins-empty">Loading…</p>';- renderMyPins(await loadMyPins());+ // Designed loading → list / empty / error(+retry), so a failed fetch surfaces+ // an error instead of masquerading as "no pins".+ loadInto(list, {+ load: loadMyPins,+ render: (pins, el) => renderMyPins(pins, el),+ skeleton: { count: 3, variant: 'row' },+ empty: MYPINS_EMPTY,+ error: { title: "Couldn't load your pins", body: 'Check your connection and try again.' },+ context: 'irl:my-pins',+ });}async function deleteMyPin(id, btn) {@@ -1741,7 +2325,8 @@ async function deleteMyPin(id, btn) {btn?.closest('.irl-pin-row')?.remove();const list = document.getElementById('irl-mypins-list');if (list && !list.querySelector('.irl-pin-row')) {- list.innerHTML = '<p class="irl-mypins-empty">No active pins</p>';+ ensureStateKitStyles();+ list.innerHTML = emptyStateHTML(MYPINS_EMPTY);}setStatus('Pin removed');}@@ -1832,8 +2417,10 @@ function _servicesHTML(services) {? `$${Number(s.price_usd).toFixed(2)} ${s.currency || 'USDC'}`: 'Free';const ep = s.x402_endpoint || '';+ // Stamp price + skill + name on the button so the pay handler can bound+ // maxPaymentUsd to exactly what's displayed and attribute the interaction.const useBtn = ep- ? `<button type="button" class="irl-service-use" data-x402="${_escHtml(ep)}">Use</button>`+ ? `<button type="button" class="irl-service-use" data-x402="${_escHtml(ep)}" data-price="${s.price_usd != null ? Number(s.price_usd) : ''}" data-skill="${_escHtml(s.skill || '')}" data-name="${_escHtml(s.name || s.skill || 'Service')}">Use</button>`: '';return `<div class="irl-service-row"><div class="irl-service-info">@@ -1940,62 +2527,169 @@ function closeInspectSheet() {_lastFocus = null;}-// Run an x402 payment against a service endpoint, driving button state through-// the flow. Shared by the footer Pay button and per-service "Use" buttons.-async function runX402Payment(endpoint, btn) {- if (!endpoint || !btn) return;+// USDC on Base mainnet — the asset every hosted x402 service settles in. The+// interactions API only records a `pay` whose currency_mint is $THREE or USDC;+// this is the mint that backs the EVM x402 rail window.ethereum signs.+const USDC_BASE_MINT = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';+// Upper safety bound (USD) for a pin-level Pay button whose price isn't on the+// card. The 402 challenge carries the real amount; withX402 rejects anything+// above this, so a misconfigured endpoint can't silently over-charge.+const PIN_PAY_CAP_USD = 5;++// Best-effort interaction telemetry → C4's /api/irl/interactions+// ({ pinId, type, deviceToken, ... }). Never blocks or breaks the UX: callers+// swallow failures (a 404 before C4 shipped is harmless). agent_id + owner are+// derived from the pin server-side; a `pay` is only recorded with a real+// on-chain settlement signature + an allowed mint.+function postInteraction(body) {+ return fetch('/api/irl/interactions', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ deviceToken: _deviceToken, ...body }),+ });+}+// Decode the x402 settlement receipt a paywall returns on a paid retry: header+// `x-payment-response` is base64 JSON { success, transaction, network, payer }.+// `transaction` is the on-chain signature the owner's inbox links to. Null when+// the response carried no receipt (e.g. a free / already-granted endpoint that+// never issued a 402).+function decodeSettlement(resp) {+ try {+ const h = resp.headers.get('x-payment-response') || resp.headers.get('payment-response');+ if (!h) return null;+ const txt = typeof atob === 'function'+ ? decodeURIComponent(escape(atob(h)))+ : Buffer.from(h, 'base64').toString('utf8');+ return JSON.parse(txt);+ } catch {+ return null;+ }+}++// Surface the paid service's response inside the card — the value the user paid+// for, not just a toast. Small JSON/text only; a large body is truncated.+function showServiceResult(label, payload) {+ const body = document.getElementById('irl-card-body');+ if (!body) return;+ let text;+ try {+ text = typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2);+ } catch {+ text = String(payload);+ }+ body.querySelector('.irl-service-result')?.remove();+ const block = document.createElement('div');+ block.className = 'irl-service-result';+ const title = document.createElement('div');+ title.className = 'irl-service-result-label';+ title.textContent = `${label} — response`;+ const pre = document.createElement('pre');+ pre.textContent = text.length > 1800 ? `${text.slice(0, 1800)}…` : text;+ block.append(title, pre);+ body.appendChild(block);+ block.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+}++// Run a real x402 payment against one service endpoint and, on success, surface+// the response inline + record a verified `pay` interaction. Drives ONLY the+// clicked button's state, so per-service buttons stay independent. Shared by the+// footer Pay button and each service row's "Use" button; price / skill / name+// ride on the button's dataset so the cap binds to exactly what's displayed.+async function runX402Payment(endpoint, btn) {+ if (!btn) return;+ if (!endpoint) { setStatus('This service has no endpoint yet', { error: true }); return; }if (!window.ethereum) {- setStatus('Connect an Ethereum wallet (MetaMask) to pay via x402', { error: true });+ setStatus('Connect a wallet (MetaMask) to pay via x402', { error: true });return;}- btn.disabled = true;- const origText = btn.textContent;+ const sheet = document.getElementById('irl-sheet');+ const priceAttr = btn.dataset.price;+ const priceUsd = priceAttr ? Number(priceAttr) : null;+ const skill = btn.dataset.skill || null;+ const label = btn.dataset.name || sheet?.dataset.agentName || 'Service';- // Gate on an authorized wallet before signing so we can bail cleanly if the- // user declines, rather than letting the x402 adapter prompt mid-flow.+ const origText = btn.textContent;+ btn.disabled = true;btn.textContent = 'Connecting…';++ // Gate on an authorized wallet up front so a decline bails cleanly here rather+ // than surfacing mid-signature inside the x402 adapter.+ let accounts;try {- const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });- if (!Array.isArray(accounts) || !accounts.length) {- setStatus('Connect your wallet to pay via x402', { error: true });- btn.disabled = false;- btn.textContent = origText;- return;- }+ accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });} catch (err) {const m = err?.message ?? String(err);- setStatus(/reject|denied|4001/i.test(m) ? 'Wallet connection cancelled' : `Couldn't connect wallet — ${m}`, { error: true });- btn.disabled = false;- btn.textContent = origText;+ setStatus(/reject|denied|4001|cancel/i.test(m) ? 'Wallet connection cancelled' : `Couldn't connect wallet — ${m}`, { error: true });+ btn.disabled = false; btn.textContent = origText;+ return;+ }+ if (!Array.isArray(accounts) || !accounts.length) {+ setStatus('Connect your wallet to pay', { error: true });+ btn.disabled = false; btn.textContent = origText;return;}- btn.textContent = 'Sending…';+ btn.textContent = 'Paying…';try {const { withX402 } = await import('../packages/x402-fetch/dist/index.esm.js');- const pay = withX402(window.ethereum, { maxPaymentUsd: 1.00 });- const r = await pay(endpoint, { method: 'POST' });- if (r.ok) {- setStatus('Payment sent');- btn.textContent = 'Paid ✓';- btn.disabled = true;- } else {- const msg = await r.text().catch(() => r.status);- setStatus(`Payment failed (${msg})`, { error: true });- btn.disabled = false;- btn.textContent = origText;+ // Cap the payment at the displayed price (small epsilon for rounding); a+ // pin-level endpoint with no shown price falls back to a fixed ceiling.+ const maxPaymentUsd = priceUsd != null && Number.isFinite(priceUsd)+ ? Math.max(priceUsd, 0.01)+ : PIN_PAY_CAP_USD;+ // Capture the exact amount from the 402 challenge (authoritative even when+ // the card showed no price) so the recorded settlement is accurate.+ let settledUsd = priceUsd;+ const pay = withX402(window.ethereum, {+ maxPaymentUsd,+ onPayment: ({ amount }) => { if (Number.isFinite(amount)) settledUsd = amount; },+ });+ const r = await pay(endpoint, { method: 'POST' }); // 402 → sign → retry inside+ if (!r.ok) {+ const detail = await r.text().catch(() => `HTTP ${r.status}`);+ setStatus(`Service error — ${String(detail).slice(0, 140)}`, { error: true });+ btn.disabled = false; btn.textContent = origText;+ return;}- } catch (err) {- const msg = err?.message ?? String(err);- if (msg.includes('rejected') || msg.includes('denied')) {- setStatus('Payment cancelled', { error: true });- } else {- setStatus(`Payment failed — ${msg}`, { error: true });++ btn.textContent = 'Used ✓';+ btn.disabled = true;+ setStatus('Service paid — response delivered');++ // Show the response the user paid for. Hosted services wrap the upstream+ // payload as { service, result, … }; unwrap to the inner result.+ let result = null;+ try {+ result = (r.headers.get('content-type') || '').includes('json') ? await r.json() : await r.text();+ } catch { /* empty / unreadable body — the receipt below still records the pay */ }+ if (result != null && result !== '') {+ const shown = result && typeof result === 'object' && 'result' in result ? result.result : result;+ showServiceResult(label, shown);+ }++ // Record the verified pay. The interactions API requires the on-chain+ // settlement signature, so log ONLY when the receipt carried one — never a+ // fabricated tx. Best-effort; a failure never disrupts the user.+ const settlement = decodeSettlement(r);+ if (settlement?.transaction && sheet?.dataset.pinId) {+ postInteraction({+ pinId: sheet.dataset.pinId,+ type: 'pay',+ agentId: sheet.dataset.agentId || null,+ signature: settlement.transaction,+ currencyMint: USDC_BASE_MINT,+ network: settlement.network || 'base',+ amount: Number.isFinite(settledUsd) ? Math.round(settledUsd * 1e6) : null,+ payload: { skill, payer: settlement.payer || null },+ }).catch(() => {});}- btn.disabled = false;- btn.textContent = origText;+ } catch (err) {+ const m = err?.message ?? String(err);+ setStatus(/reject|denied|4001|cancel/i.test(m) ? 'Payment cancelled' : `Payment failed — ${m}`, { error: true });+ btn.disabled = false; btn.textContent = origText;}}@@ -2030,6 +2724,17 @@ function openPinSheet(pin) {: null;}+ // Report (D4) — community moderation. Pointless on your own pin (the server+ // no-ops owner self-reports), so it's shown only on someone else's placement.+ const reportBtn = document.getElementById('irl-sheet-report');+ if (reportBtn) {+ const own = isOwnPin(pin);+ reportBtn.hidden = own || !pin.id;+ reportBtn.onclick = (!own && pin.id)+ ? () => openReportSheet(pin.id)+ : null;+ }+// Honest accuracy line (A3) — never imply the placement is centimetre-perfect.const accEl = document.getElementById('irl-sheet-accuracy');if (accEl) {@@ -2177,6 +2882,76 @@ document.getElementById('irl-sheet-msg')?.addEventListener('submit', async (e) =}});+// ── Report flow (D4) ───────────────────────────────────────────────────────+// A visitor flags a pin for moderation. The server de-dupes per reporter and+// hides the pin once enough distinct people flag it — so this is a single,+// honest action with loading / success / error states, never a dead button.++let _reportPinId = null;++function openReportSheet(pinId) {+ const sheet = document.getElementById('irl-report-sheet');+ if (!sheet || !pinId) return;+ _reportPinId = pinId;+ closeInspectSheet();+ const status = document.getElementById('irl-report-status');+ if (status) { status.hidden = true; status.classList.remove('is-error'); }+ sheet.querySelectorAll('.irl-report-reason').forEach((b) => { b.disabled = false; });+ sheet.classList.add('is-open');+}++function closeReportSheet() {+ document.getElementById('irl-report-sheet')?.classList.remove('is-open');+ _reportPinId = null;+}++document.getElementById('irl-report-close')?.addEventListener('click', closeReportSheet);++document.querySelectorAll('.irl-report-reason').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const pinId = _reportPinId;+ const reason = btn.dataset.reason || 'other';+ const status = document.getElementById('irl-report-status');+ const sheet = document.getElementById('irl-report-sheet');+ if (!pinId) return;++ sheet?.querySelectorAll('.irl-report-reason').forEach((b) => { b.disabled = true; });+ if (status) {+ status.textContent = 'Sending…';+ status.classList.remove('is-error');+ status.hidden = false;+ }+ try {+ const r = await fetch('/api/irl/report', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ pinId, reason, deviceToken: _deviceToken }),+ });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const data = await r.json().catch(() => ({}));+ if (status) {+ status.textContent = data.hidden+ ? 'Thanks — enough reports came in, so this pin has been hidden.'+ : 'Thanks, we’ll review it.';+ status.classList.remove('is-error');+ status.hidden = false;+ }+ // If it was hidden, drop it from the scene immediately rather than waiting+ // for the next nearby re-fetch.+ if (data.hidden) removeNearbyPin(pinId);+ setTimeout(closeReportSheet, 1400);+ } catch {+ if (status) {+ status.textContent = 'Couldn’t submit the report — try again.';+ status.classList.add('is-error');+ status.hidden = false;+ }+ // Re-enable so the failed report is retryable, never a dead end.+ sheet?.querySelectorAll('.irl-report-reason').forEach((b) => { b.disabled = false; });+ }+ });+});+// ── Agent picker ──────────────────────────────────────────────────────────// Lists the authenticated user's agents. Selecting one loads its avatar GLB// into the scene and sets it as the current agent for any new pins.@@ -2254,7 +3029,12 @@ document.getElementById('irl-agents-list')?.addEventListener('click', async (e)document.getElementById('irl-sheet-view')?.addEventListener('click', () => {const sheet = document.getElementById('irl-sheet');const agentId = sheet?.dataset.agentId;+ const pinId = sheet?.dataset.pinId;const name = sheet?.dataset.agentName || document.getElementById('irl-sheet-name')?.textContent || '';+ // Opening the profile is active engagement — record a 'tap' (the API's+ // active-sighting type), distinct from the passive 'view' logged on card open.+ // Best-effort; capture pinId before closeInspectSheet and never block nav.+ if (pinId) postInteraction({ pinId, type: 'tap', agentId: agentId || null }).catch(() => {});closeInspectSheet();if (agentId) {window.open(`/agents/${agentId}`, '_blank', 'noopener');@@ -2302,7 +3082,14 @@ function updateLabels() {// (B4) in the same projection pass — the "you'll tap this" affordance.let focusPin = null, focusDist = Infinity;for (const pin of nearbyPins) {- if (!pin.labelEl || !pin.group) { pin._labelOnScreen = false; continue; }+ // Skip pins with no label/group, ones culled by enforceLOD, and ones past the+ // tier's label cap (_labelAllowed === false). This bounds the live DOM label+ // nodes to BUDGET.label nearest-first and keeps the loop off-screen-cheap.+ if (!pin.labelEl || !pin.group || pin._lod === 'hidden' || pin._labelAllowed === false) {+ if (pin.labelEl) pin.labelEl.style.display = 'none';+ pin._labelOnScreen = false;+ continue;+ }_lblVec.set(pin.group.position.x,pin.group.position.y + 2.5,@@ -2335,6 +3122,132 @@ function updateLabels() {}}+// ── Distance LOD + draw/label budget (E2) ───────────────────────────────────+// Called ~4 Hz from tick(), not per frame. Sorts loaded pins nearest-first, then+// assigns each a band — full (skinned GLB) | impostor (billboard) | dot (cheap+// marker) | hidden (no draw, no label) — from its LIVE camera distance and the+// active tier budget. Caps concurrent fulls (maxGLB) and simultaneous labels,+// demoting the farthest pins first, so a crowded plaza can't blow the frame.+const _lodList = [];+const _lodProj = new Vector3();+function _byLodDist(a, b) { return a._lodDist - b._lodDist; }++function liveDist2D(pin) {+ return Math.hypot(+ camera.position.x - pin.group.position.x,+ camera.position.z - pin.group.position.z,+ );+}+// Cheap NDC bounds test so we never bake/keep impostors for agents behind the viewer.+function pinOnScreen(pin) {+ _lodProj.set(pin.group.position.x, pin.group.position.y + 1.2, pin.group.position.z).project(camera);+ return _lodProj.z < 1 && Math.abs(_lodProj.x) < 1.3 && Math.abs(_lodProj.y) < 1.3;+}++let _drawEstimate = 0; // approx scene draw calls the last LOD pass projected++// Pick a pin's band from its live distance, with hysteresis: each band's outer+// (farther/cheaper) edge is sticky by LOD_HYST metres relative to the pin's+// CURRENT band, so a pin idling right on a boundary (GPS jitter) doesn't flap+// between loading and evicting its GLB. Getting closer promotes immediately;+// only moving away by the margin demotes.+const LOD_HYST = 1.5;+function bandFor(d, cur) {+ const nearT = budget.lodNear + (cur === 'full' ? LOD_HYST : 0);+ const farT = budget.lodFar + (cur === 'full' || cur === 'impostor' ? LOD_HYST : 0);+ const cullT = budget.cull + (cur && cur !== 'hidden' ? LOD_HYST : 0);+ if (d > cullT) return 'hidden';+ if (d > farT) return 'dot';+ if (d > nearT) return 'impostor';+ return 'full';+}++function enforceLOD() {+ _lodList.length = 0;+ for (const pin of nearbyPins) {+ if (!pin.group) continue;+ pin._lodDist = liveDist2D(pin);+ _lodList.push(pin);+ }+ _lodList.sort(_byLodDist);++ let fullBudget = budget.maxGLB;+ let labelBudget = budget.label;+ // Approximate draw-call budget: base scene (ground, lights, avatar, UI) ≈ 30,+ // each full skinned avatar ≈ 6 draws, impostor/dot ≈ 1. Demote the farthest+ // fulls to impostors once the projection would exceed the tier ceiling.+ let draws = 30;++ for (let i = 0; i < _lodList.length; i++) {+ const pin = _lodList[i];+ const d = pin._lodDist;+ let band = bandFor(d, pin._lod);++ // Concurrency + draw-budget demotion: full → impostor when out of GLB slots+ // or over the draw ceiling. Nearest-first ordering spends the budget on the+ // agents the viewer is closest to.+ if (band === 'full') {+ const cost = draws + 6;+ if (fullBudget > 0 && cost <= budget.draw) { fullBudget--; draws = cost; }+ else band = 'impostor';+ }+ if (band === 'impostor' || band === 'dot') draws += 1;++ pin._labelAllowed = band !== 'hidden' && labelBudget > 0;+ if (pin._labelAllowed) labelBudget--;++ applyBand(pin, band);+ }+ _drawEstimate = draws;+}++function applyBand(pin, band) {+ if (pin._lod === band) {+ // Already in this band — but an impostor still waiting on its background bake+ // shows the dot; promote it the instant the snapshot exists.+ if (band === 'impostor' && pin._impostorRT && !(pin._impostorSprite && pin._impostorSprite.visible)) {+ hideDot(pin); showImpostor(pin);+ }+ return;+ }+ pin._lod = band;+ switch (band) {+ case 'hidden':+ pin.group.visible = false;+ cancelPinGLB(pin);+ evictPinGLB(pin);+ break;+ case 'dot':+ pin.group.visible = true;+ evictPinGLB(pin);+ hideImpostor(pin);+ showDot(pin);+ break;+ case 'impostor':+ pin.group.visible = true;+ evictPinGLB(pin);+ if (pin._impostorRT) { hideDot(pin); showImpostor(pin); }+ else {+ // No snapshot yet (never been close). Show the dot now and bake one in+ // the background — but only for on-screen pins, so a load slot is never+ // spent on an agent behind the viewer.+ showDot(pin);+ if (pinOnScreen(pin)) requestPinGLB(pin, true);+ }+ break;+ case 'full':+ pin.group.visible = true;+ if (!pin.glbLoaded) {+ // Show the impostor (if already baked) or the dot while the full model+ // streams in; onPinGLBLoaded swaps to the skinned mesh on arrival.+ if (pin._impostorRT) { hideDot(pin); showImpostor(pin); }+ else showDot(pin);+ requestPinGLB(pin, false);+ }+ break;+ }+}+// ── Resize ────────────────────────────────────────────────────────────────function resize() {renderer.setSize(window.innerWidth, window.innerHeight, false);@@ -2505,6 +3418,40 @@ function updateAgentAwareness(dt) {}}+// ── LOD / radar throttles + frame-time watchdog (E2) ────────────────────────+const LOD_INTERVAL = 0.25; // enforceLOD at ~4 Hz — band changes don't need 60 Hz+const RADAR_INTERVAL = 0.2; // rebuild radar DOM at ~5 Hz, not every frame+let _lodAccum = 0, _radarAccum = 0;++// Rolling frame-time governor. If the average frame stays slow for ~2 s we step+// the tier DOWN live (lower DPR, then shadows off, then fewer GLBs); if it runs+// with headroom for ~4 s we step back UP, but never above the device's detected+// `baseTier`. The app degrades visibly-gracefully instead of freezing.+const _fps = { ema: 16, over: 0, under: 0 };+function frameWatchdog(dt) {+ const ms = dt * 1000;+ _fps.ema += (ms - _fps.ema) * 0.1;+ if (_fps.ema > 28) { // < ~36 fps+ _fps.over += dt; _fps.under = 0;+ if (_fps.over > 2) { _fps.over = 0; stepTier(-1); }+ } else if (_fps.ema < 20) { // > ~50 fps, room to recover+ _fps.under += dt; _fps.over = 0;+ if (_fps.under > 4) { _fps.under = 0; stepTier(+1); }+ } else {+ _fps.over *= 0.5; _fps.under *= 0.5;+ }+}+function stepTier(dir) {+ const next = shiftTier(activeTier, dir);+ // Never climb above the hardware ceiling detected at boot.+ if (dir > 0 && TIER_ORDER.indexOf(next) > TIER_ORDER.indexOf(baseTier)) return;+ if (next === activeTier) return;+ activeTier = next;+ budget = BUDGETS[activeTier];+ applyTierToRenderer();+ log.info(`[irl] perf tier → ${activeTier} (frame ~${_fps.ema.toFixed(0)}ms)`);+}+function tick() {clock.update();const dt = Math.min(clock.getDelta(), 0.05);@@ -2608,14 +3555,23 @@ function tick() {}}+ // Distance LOD / draw budget (E2) — ~4 Hz. Decides each pin's band, drives the+ // queued GLB loads, impostor bakes and evictions, and sets the per-pin label+ // allowance. Runs before awareness so head-tracking only touches mounted models.+ _lodAccum += dt;+ if (_lodAccum >= LOD_INTERVAL) { _lodAccum = 0; enforceLOD(); }+// Nearby agents notice the viewer — body/head turn, idle drift, greet pop.updateAgentAwareness(dt);- // Project nearby agent labels to screen space+ // Project nearby agent labels to screen space (capped to BUDGET.label nearest).updateLabels();- updateRadar();+ // Radar DOM is rebuilt at ~5 Hz, not every frame (it was a per-frame churn).+ _radarAccum += dt;+ if (_radarAccum >= RADAR_INTERVAL) { _radarAccum = 0; updateRadar(); }renderer.render(scene, camera);+ frameWatchdog(dt);xrViewer._rafId = requestAnimationFrame(tick);}@@ -2955,30 +3911,99 @@ document.getElementById('irl-cal-denied')?.addEventListener('click', (e) => {window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && calibrateActive) exitCalibrate(true); });// ── Boot ──────────────────────────────────────────────────────────────────-initGPS();+// 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(); } });// 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.-loadMyPins().then(pins => { if (pins.length) revealMyPinsBtn(); });+loadMyPins().then(pins => { if (pins.length) revealMyPinsBtn(); }).catch(() => {});++// Tap the realtime pill to force a reconnect when it's in the polling fallback.+document.getElementById('irl-net-pill')?.addEventListener('click', () => irlNet?.retry());+// Tear down the live stream + poll on navigation away so we never leak a socket or+// an interval across an SPA transition / tab close.+window.addEventListener('pagehide', () => { irlNet?.destroy(); stopPollFallback(); });// URL ?avatar= wins over the saved session (an explicit link is intentional);// otherwise fall back to whatever avatar was active last visit.const _targetAvatarId = avatarIdParam || _savedSession?.avatarId || null;-loadAvatar(_targetAvatarId)- .then(() => {- _restoreSession();- startTick();- })- .catch(err => {- log.error('[irl] avatar load failed:', err);- nameEl.textContent = 'Avatar';- setStatus(`Couldn't load avatar: ${err?.message ?? err}`, { error: true, sticky: true });- cameraBtn.disabled = false;- cameraBtn.removeAttribute('aria-busy');- startTick();- });++// Start the render loop exactly once; the avatar streams in (or retries) on top+// of it, so a failed first load never freezes the scene or double-starts the tick.+let _tickStarted = false;+function ensureTick() { if (!_tickStarted) { _tickStarted = true; startTick(); } }++function bootAvatar() {+ return loadAvatar(_targetAvatarId)+ .then(() => {+ hideOverlay();+ _restoreSession();+ ensureTick();+ })+ .catch(err => {+ log.error('[irl] avatar load failed:', err);+ nameEl.textContent = 'Avatar';+ cameraBtn.disabled = false;+ cameraBtn.removeAttribute('aria-busy');+ ensureTick();+ // Designed, retryable state instead of a 3-second toast over a blank scene.+ showAvatarLoadError(err, bootAvatar);+ });+}+bootAvatar();// Detect WebXR floor-anchoring support and reveal the entry once ready. iOS// Safari (no immersive-ar) never sees the button and stays on the gyro+GPS Pin// path; desktop Chrome reports false and adds no console noise.detectFloorAnchorSupport();++// ── Dev-only perf harness (E2) ──────────────────────────────────────────────+// Gated behind import.meta.env.DEV → tree-shaken out of production builds, so no+// synthetic pins ever ship. Lets us verify the LOD/culling/queue budget under a+// dense crowd: `__irlSeedPins(30)` lays 30 default-avatar pins in a grid around+// the avatar; `__irlPerf()` reports the live tier, band counts and draw calls.+if (import.meta.env.DEV) {+ window.__irlSeedPins = (n = 30, spacing = 6) => {+ const cols = Math.ceil(Math.sqrt(n));+ for (let i = 0; i < n; i++) {+ const id = `dev-seed-${i}`;+ if (nearbyPins.find(p => p.id === id)) continue;+ const entry = {+ id, lat: 0, lng: 0,+ avatar_url: AVATAR_URL_DEFAULT,+ avatar_name: `Seed ${i + 1}`,+ caption: '', x402_endpoint: null,+ distance_m: 0, group: null, labelEl: null, glbLoaded: false,+ };+ nearbyPins.push(entry);+ spawnNearbyPin(entry);+ // Lay them in a grid around the avatar, overriding the GPS-derived spawn+ // position so they don't stack at the origin when there's no live fix.+ const gx = (i % cols) - cols / 2;+ const gz = Math.floor(i / cols) - cols / 2;+ entry.group.position.set(+ avatarRig.position.x + gx * spacing,+ entry.group.position.y,+ avatarRig.position.z + gz * spacing,+ );+ }+ updateNearbyBadge();+ log.info(`[irl] seeded ${n} synthetic pins for LOD stress test`);+ return n;+ };+ window.__irlPerf = () => ({+ tier: activeTier,+ baseTier,+ pins: nearbyPins.length,+ full: nearbyPins.filter(p => p._lod === 'full').length,+ impostor: nearbyPins.filter(p => p._lod === 'impostor').length,+ dot: nearbyPins.filter(p => p._lod === 'dot').length,+ hidden: nearbyPins.filter(p => p._lod === 'hidden').length,+ drawsEstimate: _drawEstimate,+ drawCalls: renderer.info.render.calls,+ queue: { active: glbQueue.active, pending: glbQueue.pending },+ reservedContexts: window.__agent3dReservedContexts,+ });+}diff --git a/src/irl/load-queue.js b/src/irl/load-queue.jsnew file mode 100644index 000000000..5af972adb--- /dev/null+++ b/src/irl/load-queue.js@@ -0,0 +1,83 @@+// src/irl/load-queue.js — one shared GLTF loader + a priority-ordered, concurrency+// capped async runner for IRL pin avatars.+//+// Before this, every nearby pin spun up its own `new GLTFLoader()` and any pin+// under 80 m raced straight into a load with only a crude `loadedCount < 5`+// guard — no nearest-first ordering, no real cap, no way to cancel a queued load+// when the user walks away. This module fixes both: a single Draco/meshopt-wired+// loader reused across every pin (the decoders init once, not per pin), and a+// generic queue that runs at most `maxActive` jobs at a time, nearest-first.++import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { dracoLoader } from '../game/avatar-rig.js';+import { getMeshoptDecoder } from '../viewer/internal.js';++let _loader = null;++// One GLTFLoader for the whole IRL scene. Pin avatars come from arbitrary+// `avatar_url`s — pump.fun/Sketchfab exports are commonly Draco-compressed and+// server-baked avatars emit EXT_meshopt_compression — so we wire BOTH decoders.+// Draco is ready synchronously (shared vendored decoder); meshopt resolves async+// and attaches as soon as it's ready, so uncompressed/Draco GLBs never wait on it.+export function sharedGLTFLoader() {+ if (_loader) return _loader;+ _loader = new GLTFLoader();+ _loader.setDRACOLoader(dracoLoader);+ getMeshoptDecoder()+ .then((d) => _loader.setMeshoptDecoder(d))+ .catch(() => { /* meshopt GLBs will fail loudly at load; Draco/plain still work */ });+ return _loader;+}++// Generic priority queue with a concurrency cap. `run(item)` returns a promise;+// jobs start nearest-first via `priorityOf(item)` (lower number = sooner). The+// queue never rejects the caller's promise on cancellation silently — a+// cancelled job rejects with an Error('cancelled') the caller can ignore.+export function createLoadQueue({ run, maxActive = 5, priorityOf = () => 0 }) {+ const queue = []; // [{ item, resolve, reject, cancelled }]+ let active = 0;+ const cfg = { run, maxActive, priorityOf };++ function pump() {+ // Re-sort on every pump so freshly-updated distances (the user moved) reorder+ // the pending loads before the next slot opens. O(n log n) over a small list.+ if (queue.length > 1) queue.sort((a, b) => cfg.priorityOf(a.item) - cfg.priorityOf(b.item));+ while (active < cfg.maxActive && queue.length) {+ const job = queue.shift();+ if (job.cancelled) continue;+ active++;+ Promise.resolve()+ .then(() => cfg.run(job.item))+ .then(job.resolve, job.reject)+ .finally(() => { active--; pump(); });+ }+ }++ return {+ // Enqueue `item`; resolves with `run(item)`'s result when a slot runs it.+ request(item) {+ return new Promise((resolve, reject) => {+ queue.push({ item, resolve, reject, cancelled: false });+ pump();+ });+ },+ // Drop still-queued jobs matching `pred` (already-running jobs finish).+ // Returns how many were cancelled.+ cancel(pred) {+ let n = 0;+ for (const job of queue) {+ if (!job.cancelled && pred(job.item)) {+ job.cancelled = true;+ job.reject(new Error('cancelled'));+ n++;+ }+ }+ return n;+ },+ // Live-tune the concurrency cap (the perf watchdog lowers it on low-end+ // devices) and immediately pump in case the cap rose.+ setMaxActive(n) { cfg.maxActive = Math.max(1, n | 0); pump(); },+ get active() { return active; },+ get pending() { return queue.reduce((c, j) => c + (j.cancelled ? 0 : 1), 0); },+ };+}diff --git a/src/irl/onboarding.js b/src/irl/onboarding.jsnew file mode 100644index 000000000..5da8b5788--- /dev/null+++ b/src/irl/onboarding.js@@ -0,0 +1,609 @@+// src/irl/onboarding.js — IRL permission + first-run onboarding (E1)+//+// IRL is a phone-camera product riding on three sensors: the camera+// (getUserMedia), motion/orientation (DeviceOrientationEvent — the gyro+// world-lock), and location (geolocation — real-world pins + nearby discovery).+// Every one of them can be prompted, granted, denied, or simply absent, and a+// denied prompt used to strand the user behind a 3-second toast. This module is+// the single source of truth for asking: a designed card per state (prompt /+// granted / denied-with-recovery / unsupported), an iOS-correct motion gesture,+// a first-run sequence, persisted outcomes so we never re-nag, and a topbar+// re-request chip so recovery is always one tap away.+//+// irl.js never re-implements permission logic — enableAR(), setLocked(), and the+// boot path call ensurePermission()/startOnboarding() and react to the result.++import { emptyStateHTML, errorStateHTML, ensureStateKitStyles } from '../shared/state-kit.js';++// ── Permission catalogue ────────────────────────────────────────────────────+export const PERMS = {+ camera: { label: 'Camera', why: 'See your agents anchored in the real world through your camera.' },+ motion: { label: 'Motion', why: 'Turn your phone to look around — agents stay pinned to real space.' },+ location: { label: 'Location', why: 'Place agents at real spots and discover the ones others left nearby.' },+};++// Feature detection — drives the "unsupported" state per sensor.+export const support = {+ camera: () => !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),+ motion: () => typeof DeviceOrientationEvent !== 'undefined',+ location: () => 'geolocation' in navigator,+};++// iOS 13+ gates motion behind an explicit gesture-bound requestPermission().+export const needsMotionGesture = () =>+ typeof DeviceOrientationEvent !== 'undefined' &&+ typeof DeviceOrientationEvent.requestPermission === 'function';++const KINDS = ['camera', 'motion', 'location'];+const SAVE_KEY = 'irl_onboarded_v1';+const VALID = new Set(['granted', 'denied', 'unsupported', 'skip']);++// ── Platform hints (recovery copy) ──────────────────────────────────────────+const ua = (typeof navigator !== 'undefined' && navigator.userAgent) || '';+const isIOS = () =>+ /iP(hone|ad|od)/.test(ua) ||+ (/Macintosh/.test(ua) && typeof navigator !== 'undefined' && navigator.maxTouchPoints > 1); // iPadOS desktop UA+const isAndroid = () => /Android/.test(ua);+const isTouch = () =>+ typeof window !== 'undefined' &&+ (('ontouchstart' in window) || (navigator.maxTouchPoints || 0) > 0);+// Motion is only worth prompting on devices that actually move; desktops use+// drag-to-orbit, so we skip the motion card + chip there entirely.+const motionRelevant = () => needsMotionGesture() || isTouch();+const reducedMotion = () =>+ typeof window !== 'undefined' &&+ window.matchMedia &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;++// ── Sensor SVGs (stroke = currentColor; tuned for the state-kit icon slot) ───+const ICONS = {+ camera: '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M23 7 16 12l7 5V7z"/><rect x="1" y="5" width="15" height="14" rx="2.5"/></svg>',+ motion: '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><polygon points="16 8 13.5 13.5 8 16 10.5 10.5 16 8"/></svg>',+ location: '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0z"/><circle cx="12" cy="10" r="3"/></svg>',+};++function recoverySteps(kind) {+ if (kind === 'camera') {+ if (isIOS()) return 'Open <b>Settings › Safari › Camera</b> and choose <b>Allow</b>, then tap Try again.';+ if (isAndroid()) return 'Tap the lock icon in the address bar › <b>Permissions › Camera › Allow</b>, then tap Try again.';+ return 'Click the camera icon in your browser’s address bar and choose <b>Allow</b>, then tap Try again.';+ }+ if (kind === 'motion') {+ if (isIOS()) return 'Open <b>Settings › Safari › Motion & Orientation Access</b> and turn it on, then tap Try again.';+ return 'Reload the page and allow motion access when your browser asks, then tap Try again.';+ }+ if (kind === 'location') {+ if (isIOS()) return 'Open <b>Settings › Privacy & Security › Location Services › Safari Websites</b> and pick <b>While Using</b>, then tap Try again.';+ if (isAndroid()) return 'Tap the lock icon in the address bar › <b>Permissions › Location › Allow</b>, then tap Try again.';+ return 'Click the location icon in your browser’s address bar and choose <b>Allow</b>, then tap Try again.';+ }+ return 'Update your browser permissions, then tap Try again.';+}++function unsupportedBody(kind) {+ if (kind === 'camera') return 'This device can’t open a camera here, so AR passthrough isn’t available — you can still explore your agent in orbit view.';+ if (kind === 'motion') return 'This device doesn’t report motion, so look-around is off. Drag to orbit the scene instead.';+ if (kind === 'location') return 'This device can’t share location, so pinning to real spots and nearby discovery are off — everything else still works.';+ return 'This feature isn’t available on this device.';+}++// ── Sensor requests (the only place each browser API is asked for permission) ─+async function requestCamera() {+ if (!support.camera()) return 'unsupported';+ try {+ const stream = await navigator.mediaDevices.getUserMedia({+ video: { facingMode: { ideal: 'environment' } },+ audio: false,+ });+ // Permission-prime only — enableAR() acquires the real stream it renders.+ stream.getTracks().forEach((t) => { try { t.stop(); } catch {} });+ return 'granted';+ } catch (err) {+ const name = err && err.name;+ if (name === 'NotAllowedError' || name === 'SecurityError') return 'denied';+ if (name === 'NotFoundError' || name === 'OverconstrainedError') return 'unsupported';+ return 'error';+ }+}++function probeOrientation() {+ // Android / non-gated: no permission API, so confirm the sensor actually+ // fires. A real reading resolves 'granted'; silence for 1.5s → 'denied'.+ return new Promise((resolve) => {+ let settled = false;+ const onEvt = (e) => {+ if (settled || !e) return;+ if (e.alpha != null || e.beta != null || e.gamma != null) {+ settled = true; cleanup(); resolve('granted');+ }+ };+ const to = setTimeout(() => { if (!settled) { settled = true; cleanup(); resolve('denied'); } }, 1500);+ function cleanup() {+ clearTimeout(to);+ window.removeEventListener('deviceorientation', onEvt, true);+ window.removeEventListener('deviceorientationabsolute', onEvt, true);+ }+ window.addEventListener('deviceorientation', onEvt, true);+ window.addEventListener('deviceorientationabsolute', onEvt, true);+ });+}++async function requestMotion() {+ if (!support.motion()) return 'unsupported';+ if (needsMotionGesture()) {+ try {+ const res = await DeviceOrientationEvent.requestPermission(); // MUST run inside a user gesture+ return res === 'granted' ? 'granted' : 'denied';+ } catch {+ return 'denied'; // throws if not called from a gesture, or the user declined+ }+ }+ return probeOrientation();+}++function requestLocation() {+ if (!support.location()) return Promise.resolve('unsupported');+ return new Promise((resolve) => {+ let done = false;+ navigator.geolocation.getCurrentPosition(+ () => { if (!done) { done = true; resolve('granted'); } },+ (err) => {+ if (done) return;+ done = true;+ resolve(err && err.code === 1 /* PERMISSION_DENIED */ ? 'denied' : 'error');+ },+ { enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 },+ );+ });+}++const REQUESTERS = { camera: requestCamera, motion: requestMotion, location: requestLocation };++// Live permission read without a prompt (Chromium/Android). Lets "Try again"+// after a Settings fix succeed silently, and skips a redundant card when the OS+// already granted access. Returns null where the Permissions API is absent+// (Safari) or doesn't know the name (camera on some engines).+async function queryPermission(kind) {+ const name = kind === 'camera' ? 'camera' : kind === 'location' ? 'geolocation' : null;+ if (!name || !navigator.permissions || !navigator.permissions.query) return null;+ try {+ const status = await navigator.permissions.query({ name });+ return status.state; // 'granted' | 'denied' | 'prompt'+ } catch {+ return null;+ }+}++// ── State + persistence ─────────────────────────────────────────────────────+const state = { camera: null, motion: null, location: null };+let onGrant = null;+let started = false;++function persist() {+ try {+ localStorage.setItem(SAVE_KEY, JSON.stringify({+ camera: state.camera, motion: state.motion, location: state.location, ts: Date.now(),+ }));+ } catch {}+}+function readSaved() {+ try { const raw = localStorage.getItem(SAVE_KEY); return raw ? JSON.parse(raw) : null; } catch { return null; }+}+function fireGrant(kind) {+ if (typeof onGrant === 'function') { try { onGrant(kind); } catch {} }+}+function applyResult(kind, result) {+ if (!KINDS.includes(kind) || !VALID.has(result)) return;+ const prev = state[kind];+ state[kind] = result;+ persist();+ renderChips();+ if (result === 'granted' && prev !== 'granted') fireGrant(kind);+}++/** Push a runtime outcome irl.js learns on its own (e.g. a revoked GPS watch). */+export function setPermissionState(kind, result) {+ applyResult(kind, result);+}++// ── CSS (injected once, co-located with the module like state-kit) ───────────+const STYLE_ID = 'irl-onboard-styles';+function ensureStyles() {+ ensureStateKitStyles();+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = ONBOARD_CSS;+ (document.head || document.documentElement).appendChild(style);+}++// ── Overlay shell ────────────────────────────────────────────────────────────+let overlayEl = null;+let cardSlot = null;+let cardActionHandler = null;+let currentDone = null;+let bailed = false;++function getOverlay() {+ if (!overlayEl) overlayEl = document.getElementById('irl-onboard');+ return overlayEl;+}++function buildShell(opts) {+ const el = getOverlay();+ if (!el) return null;+ const multi = !opts.single;+ el.innerHTML = `+ <div class="irl-ob-scrim"></div>+ <div class="irl-ob-panel" role="document">+ <div class="irl-ob-head">+ <span class="irl-ob-badge"><span class="irl-ob-badge-dot"></span> IRL</span>+ <h2 class="irl-ob-title">${multi ? 'Bring your agents into the real world' : 'Permission needed'}</h2>+ <p class="irl-ob-sub">${multi ? 'Three quick permissions power the camera, look-around, and real-world pins. You stay in control.' : 'Grant access to continue — you can change this anytime.'}</p>+ </div>+ <div class="irl-ob-card" aria-live="polite"></div>+ <div class="irl-ob-progress"${multi ? '' : ' hidden'} aria-hidden="true"></div>+ </div>`;+ cardSlot = el.querySelector('.irl-ob-card');+ cardSlot.addEventListener('click', onCardClick);+ el.querySelector('.irl-ob-scrim').addEventListener('click', () => { if (currentDone) { bailed = true; currentDone(); } });+ return el;+}++function onCardClick(e) {+ const btn = e.target.closest('[data-sk-action]');+ if (!btn) return;+ if (cardActionHandler) cardActionHandler(btn.dataset.skAction);+}++function onKeydown(e) {+ if (e.key === 'Escape' && currentDone) { bailed = true; currentDone(); }+}++function openOverlay() {+ const el = getOverlay();+ if (!el) return;+ bailed = false;+ el.hidden = false;+ document.addEventListener('keydown', onKeydown, true);+ const reveal = () => el.classList.add('is-open');+ if (reducedMotion()) reveal(); else requestAnimationFrame(reveal);+}++function closeOverlay() {+ const el = getOverlay();+ if (!el) return;+ document.removeEventListener('keydown', onKeydown, true);+ el.classList.remove('is-open');+ currentDone = null;+ cardActionHandler = null;+ const after = () => { el.hidden = true; el.innerHTML = ''; cardSlot = null; };+ if (reducedMotion()) after(); else setTimeout(after, 260);+}++function updateProgress(opts) {+ const el = getOverlay();+ const bar = el && el.querySelector('.irl-ob-progress');+ if (!bar || opts.single || !Number.isFinite(opts.total)) return;+ bar.innerHTML = Array.from({ length: opts.total }, (_, i) =>+ `<span class="irl-ob-dot${i === opts.index ? ' is-active' : ''}${i < opts.index ? ' is-done' : ''}"></span>`,+ ).join('');+}++function focusPrimary() {+ const btn = cardSlot && (cardSlot.querySelector('.tws-es-btn--primary') || cardSlot.querySelector('.tws-es-btn'));+ if (btn) { try { btn.focus(); } catch {} }+}++// ── Per-card flow ─────────────────────────────────────────────────────────────+function runCard(kind, opts = {}) {+ return new Promise((resolve) => {+ const finish = () => { if (currentDone === doneRef) currentDone = null; resolve(state[kind] || 'skip'); };+ const doneRef = finish;+ currentDone = doneRef;+ present(kind, opts, finish);+ });+}++function present(kind, opts, done) {+ const meta = PERMS[kind];+ let busy = false;++ const stage = (html) => { if (cardSlot) cardSlot.innerHTML = html; };++ const stagePrompt = () => {+ updateProgress(opts);+ stage(emptyStateHTML({+ icon: ICONS[kind],+ title: `Enable ${meta.label}`,+ body: meta.why,+ actions: [+ { label: `Enable ${meta.label}`, id: 'enable', primary: true },+ ...(opts.allowSkip ? [{ label: opts.single ? 'Not now' : 'Skip for now', id: 'skip' }] : []),+ ],+ }));+ focusPrimary();+ };++ const stageRequesting = () => {+ stage(`<div class="tws-es" role="status" aria-live="polite">+ <div class="irl-ob-spinner" aria-hidden="true"></div>+ <h3 class="tws-es-title">Requesting ${meta.label}…</h3>+ <p class="tws-es-body">Confirm the permission prompt to continue.</p>+ </div>`);+ };++ const stageGranted = () => {+ stage(`<div class="tws-es irl-ob-granted" role="status">+ <div class="irl-ob-check" aria-hidden="true"><svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></div>+ <h3 class="tws-es-title">${meta.label} enabled</h3>+ <p class="tws-es-body">You’re all set.</p>+ </div>`);+ setTimeout(done, reducedMotion() ? 120 : 720);+ };++ const stageDenied = () => {+ stage(errorStateHTML({+ title: `${meta.label} is blocked`,+ body: recoverySteps(kind),+ actions: [+ { label: 'Try again', id: 'retry', primary: true },+ { label: kind === 'motion' ? 'Use orbit instead' : 'Continue without', id: 'continue' },+ ],+ }));+ focusPrimary();+ };++ const stageError = () => {+ stage(errorStateHTML({+ title: `Couldn’t reach ${meta.label.toLowerCase()}`,+ body: kind === 'location'+ ? 'We couldn’t get a location fix. Move somewhere with a clearer view of the sky, then try again.'+ : 'Something interrupted the request. Try again in a moment.',+ actions: [+ { label: 'Try again', id: 'retry', primary: true },+ { label: 'Continue without', id: 'continue' },+ ],+ }));+ focusPrimary();+ };++ const stageUnsupported = () => {+ updateProgress(opts);+ stage(emptyStateHTML({+ icon: ICONS[kind],+ title: `${meta.label} isn’t available`,+ body: unsupportedBody(kind),+ compact: true,+ actions: [{ label: 'Got it', id: 'continue', primary: true }],+ }));+ focusPrimary();+ };++ cardActionHandler = async (action) => {+ if (busy) return;+ if (action === 'skip') { applyResult(kind, 'skip'); done(); return; }+ if (action === 'continue') { done(); return; }+ if (action === 'enable' || action === 'retry') {+ busy = true;+ stageRequesting();+ let result = 'error';+ try { result = await REQUESTERS[kind](); } catch { result = 'error'; }+ busy = false;+ if (bailed) return; // overlay dismissed mid-request+ if (VALID.has(result)) applyResult(kind, result);+ if (result === 'granted') stageGranted();+ else if (result === 'unsupported') stageUnsupported();+ else if (result === 'denied') stageDenied();+ else stageError();+ }+ };++ if (!support[kind]()) { applyResult(kind, 'unsupported'); stageUnsupported(); }+ else stagePrompt();+}++// ── First-run sequence ────────────────────────────────────────────────────────+async function runFirstRun() {+ ensureStyles();+ if (!buildShell({ single: false })) return; // no overlay element in DOM+ openOverlay();+ try {+ const kinds = ['camera', 'location'];+ if (motionRelevant()) kinds.push('motion');+ else applyResult('motion', 'unsupported');+ for (let i = 0; i < kinds.length; i++) {+ if (bailed) break;+ await runCard(kinds[i], { index: i, total: kinds.length, allowSkip: true });+ }+ } finally {+ persist();+ closeOverlay();+ }+}++// ── Public API ────────────────────────────────────────────────────────────────++/**+ * On-demand permission gate used by enableAR()/setLocked(): resolves the cached+ * or live-granted state immediately, otherwise opens the designed card and+ * resolves once the user acts. Always resolves to a state string.+ */+export async function ensurePermission(kind) {+ if (!KINDS.includes(kind)) return 'unsupported';+ if (!support[kind]()) { applyResult(kind, 'unsupported'); return 'unsupported'; }+ if (state[kind] === 'granted') return 'granted';+ const live = await queryPermission(kind);+ if (live === 'granted') { applyResult(kind, 'granted'); return 'granted'; }+ ensureStyles();+ if (!buildShell({ single: true })) {+ // No overlay in the DOM — fall back to a bare request so we never dead-end.+ let result = 'error';+ try { result = await REQUESTERS[kind](); } catch {}+ if (VALID.has(result)) applyResult(kind, result);+ return result;+ }+ openOverlay();+ let result;+ try { result = await runCard(kind, { single: true, allowSkip: true }); }+ finally { closeOverlay(); }+ return result || state[kind] || 'denied';+}++/**+ * Boot entry. First visit → runs the onboarding overlay; repeat visit → hydrates+ * saved outcomes, renders re-request chips for denied sensors, and replays grants+ * (so a previously-granted location restarts GPS). Idempotent.+ *+ * @param {{ onGrant?: (kind: string) => void }} [opts]+ */+export async function startOnboarding(opts = {}) {+ if (started) return state;+ started = true;+ onGrant = typeof opts.onGrant === 'function' ? opts.onGrant : null;+ ensureStyles();+ wireChips();++ const saved = readSaved();+ if (saved) {+ for (const k of KINDS) if (VALID.has(saved[k])) state[k] = saved[k];+ renderChips();+ for (const k of KINDS) if (state[k] === 'granted') fireGrant(k);+ return state;+ }++ try { await runFirstRun(); } catch { closeOverlay(); }+ return state;+}++// ── Re-request chips (topbar) ─────────────────────────────────────────────────+let chipsEl = null;+function wireChips() {+ chipsEl = document.getElementById('irl-perm-chips');+ if (!chipsEl || chipsEl._wired) return;+ chipsEl._wired = true;+ chipsEl.addEventListener('click', async (e) => {+ const chip = e.target.closest('[data-perm]');+ if (!chip) return;+ await ensurePermission(chip.dataset.perm);+ });+}+function renderChips() {+ if (!chipsEl) chipsEl = document.getElementById('irl-perm-chips');+ if (!chipsEl) return;+ const denied = KINDS.filter((k) => state[k] === 'denied');+ if (!denied.length) { chipsEl.hidden = true; chipsEl.innerHTML = ''; return; }+ chipsEl.innerHTML = denied.map((k) =>+ `<button type="button" class="irl-perm-chip" data-perm="${k}" aria-label="Enable ${PERMS[k].label}">+ <span class="irl-perm-chip-icon" aria-hidden="true">${ICONS[k]}</span>+ Enable ${PERMS[k].label}+ </button>`,+ ).join('');+ chipsEl.hidden = false;+}++// ── CSS ────────────────────────────────────────────────────────────────────────+const ONBOARD_CSS = `+#irl-onboard {+ position: fixed; inset: 0; z-index: 120;+ display: flex; align-items: center; justify-content: center;+ padding: 24px;+ opacity: 0; pointer-events: none;+ transition: opacity .26s ease;+}+#irl-onboard[hidden] { display: none; } /* honour the attr — the id rule above would otherwise force display:flex */+#irl-onboard.is-open { opacity: 1; pointer-events: auto; }+#irl-onboard .irl-ob-scrim {+ position: absolute; inset: 0;+ background: radial-gradient(120% 90% at 50% 0%, rgba(20,26,40,0.72), rgba(6,8,13,0.92));+ backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);+}+#irl-onboard .irl-ob-panel {+ position: relative;+ width: min(440px, 100%);+ max-height: calc(100dvh - 48px);+ overflow-y: auto;+ background: linear-gradient(180deg, rgba(15,18,27,0.98), rgba(9,11,17,0.99));+ border: 1px solid rgba(255,255,255,0.10);+ border-radius: 22px;+ box-shadow: 0 24px 70px rgba(0,0,0,0.6);+ padding: 22px 22px 18px;+ transform: translateY(10px) scale(.99);+ transition: transform .28s cubic-bezier(.22,.61,.36,1);+}+#irl-onboard.is-open .irl-ob-panel { transform: none; }+.irl-ob-head { text-align: center; padding: 0 4px 4px; }+.irl-ob-badge {+ display: inline-flex; align-items: center; gap: 6px;+ font: 600 11px/1 var(--font-body, system-ui, sans-serif);+ letter-spacing: .09em; text-transform: uppercase;+ color: #7dd3fc;+ background: rgba(125,211,252,0.10);+ border: 1px solid rgba(125,211,252,0.28);+ border-radius: 999px; padding: 5px 10px; margin-bottom: 12px;+}+.irl-ob-badge-dot { width: 6px; height: 6px; border-radius: 50%; background: #7dd3fc; box-shadow: 0 0 8px #7dd3fc; }+.irl-ob-title { margin: 0 0 6px; font-size: 18px; font-weight: 700; letter-spacing: -.015em; color: #f1f4fa; line-height: 1.25; }+.irl-ob-sub { margin: 0; font-size: 13px; line-height: 1.5; color: #93a1b5; }+.irl-ob-card .tws-es { padding: 22px 8px 6px; }+.irl-ob-card .tws-es-icon { color: #cdd6e4; opacity: .92; }+.irl-ob-card .tws-es-icon--err { color: #f87171; }+.irl-ob-card .tws-es-actions { width: 100%; flex-direction: column; gap: 8px; margin-top: 14px; }+.irl-ob-card .tws-es-btn { width: 100%; padding: 12px 16px; font-size: 14px; }+.irl-ob-card .tws-es-body b { color: #cdd6e4; font-weight: 600; }+.irl-ob-progress { display: flex; gap: 7px; justify-content: center; padding: 14px 0 4px; }+.irl-ob-progress[hidden] { display: none; }+.irl-ob-dot { width: 7px; height: 7px; border-radius: 50%; background: rgba(255,255,255,0.16); transition: background .2s, transform .2s; }+.irl-ob-dot.is-active { background: #7dd3fc; transform: scale(1.25); }+.irl-ob-dot.is-done { background: rgba(125,211,252,0.5); }+.irl-ob-granted .irl-ob-check {+ width: 52px; height: 52px; border-radius: 50%;+ display: flex; align-items: center; justify-content: center;+ color: #34d399; background: rgba(52,211,153,0.14); border: 1px solid rgba(52,211,153,0.4);+ margin-bottom: 6px;+}+.irl-ob-spinner {+ width: 30px; height: 30px; border-radius: 50%;+ border: 2.5px solid rgba(255,255,255,0.14); border-top-color: #7dd3fc;+ animation: irl-ob-spin .8s linear infinite; margin-bottom: 8px;+}+@keyframes irl-ob-spin { to { transform: rotate(360deg); } }++/* ── Topbar re-request chips ── */+.irl-perm-chips {+ position: fixed; left: 0; right: 0;+ top: calc(env(safe-area-inset-top, 0px) + 52px);+ z-index: 11;+ display: flex; gap: 8px; justify-content: center; flex-wrap: wrap;+ padding: 0 12px; pointer-events: none;+}+.irl-perm-chips[hidden] { display: none; }+.irl-perm-chip {+ pointer-events: auto;+ display: inline-flex; align-items: center; gap: 6px;+ padding: 7px 13px 7px 10px;+ font: 600 12.5px/1 var(--font-body, system-ui, sans-serif);+ color: #fde68a;+ background: rgba(251,191,36,0.14);+ border: 1px solid rgba(251,191,36,0.42);+ border-radius: 999px;+ cursor: pointer;+ box-shadow: 0 4px 16px rgba(0,0,0,0.35);+ transition: background .15s, border-color .15s, transform .12s;+}+.irl-perm-chip:hover { background: rgba(251,191,36,0.22); border-color: rgba(251,191,36,0.6); }+.irl-perm-chip:active { transform: translateY(1px); }+.irl-perm-chip:focus-visible { outline: 2px solid rgba(251,191,36,0.7); outline-offset: 2px; }+.irl-perm-chip-icon { display: inline-flex; }+.irl-perm-chip-icon svg { width: 14px; height: 14px; }++@media (prefers-reduced-motion: reduce) {+ #irl-onboard, #irl-onboard .irl-ob-panel { transition: none; }+ .irl-ob-spinner { animation: none; border-top-color: rgba(255,255,255,0.4); }+ .irl-ob-dot { transition: none; }+}+`;++if (typeof window !== 'undefined') {+ window.irlOnboarding = { PERMS, support, needsMotionGesture, ensurePermission, startOnboarding, setPermissionState };+}diff --git a/src/irl/perf-budget.js b/src/irl/perf-budget.jsnew file mode 100644index 000000000..c07b3c8cb--- /dev/null+++ b/src/irl/perf-budget.js@@ -0,0 +1,99 @@+// src/irl/perf-budget.js — device tiering + render budgets for the IRL AR scene.+//+// A busy plaza can carry dozens of pins; a handful of skinned-mesh avatars plus+// per-frame label projection will tank a mid-range phone and trip "Too many+// active WebGL contexts" on top of the rest of the page. These budgets are the+// hard ceilings the renderer holds to per device class — they are *defined*+// here, never left implicit.+//+// detectTier() reads only REAL device signals (hardwareConcurrency, deviceMemory,+// devicePixelRatio, a coarse mobile UA check, and — when a renderer is passed —+// real GPU capabilities). Unknown signals contribute nothing; we default to+// 'mid' rather than fabricate a value.++export const TIER_ORDER = ['low', 'mid', 'high'];++// maxGLB = concurrent full skinned avatars+// lodNear = full GLB rendered at or below this many metres+// lodFar = impostor billboard at or below this many metres (dot beyond)+// cull = beyond this many metres a pin is hidden entirely (no draw, no label)+// pixelRatio = renderer DPR ceiling+// shadow = directional shadow-map size (0 disables shadows)+// label = max simultaneous HTML labels (nearest-first)+// draw = approximate draw-call ceiling; fulls demote to impostors above it+export const BUDGETS = {+ high: { maxGLB: 8, lodNear: 18, lodFar: 45, cull: 150, pixelRatio: 2, shadow: 1024, label: 24, draw: 220 },+ mid: { maxGLB: 5, lodNear: 14, lodFar: 35, cull: 120, pixelRatio: 1.5, shadow: 512, label: 16, draw: 140 },+ low: { maxGLB: 2, lodNear: 10, lodFar: 22, cull: 80, pixelRatio: 1, shadow: 0, label: 8, draw: 70 },+};++// Score from the signals we actually have. Each branch only moves the score when+// the underlying API reported a real value — a browser that hides deviceMemory+// (Safari) simply doesn't contribute that term instead of guessing.+function baseScore() {+ if (typeof navigator === 'undefined') return 0;+ const cores = navigator.hardwareConcurrency || 0; // 0 = unknown+ const mem = navigator.deviceMemory || 0; // GB, Chrome/Android only+ const dpr = (typeof window !== 'undefined' && window.devicePixelRatio) || 1;+ const ua = navigator.userAgent || '';+ const mobile = /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle/i.test(ua);++ let score = 0;+ if (cores >= 8) score += 2;+ else if (cores >= 6) score += 1;+ else if (cores > 0 && cores <= 4) score -= 1;++ if (mem >= 8) score += 2;+ else if (mem >= 4) score += 1;+ else if (mem > 0 && mem <= 2) score -= 2;++ if (mobile) score -= 1; // phones push fewer triangles than laptops+ if (mobile && dpr >= 3) score -= 1; // …and a 3× panel is a lot more pixels++ return score;+}++// Real GPU capability nudge from an existing renderer. No fabricated values:+// returns 0 when nothing can be read.+function gpuScore(renderer) {+ try {+ const caps = renderer && renderer.capabilities;+ const max = caps && caps.maxTextureSize;+ let adj = 0;+ if (max >= 16384) adj += 1;+ else if (max && max <= 4096) adj -= 1;++ const gl = renderer && renderer.getContext && renderer.getContext();+ const dbg = gl && gl.getExtension && gl.getExtension('WEBGL_debug_renderer_info');+ const rs = dbg ? String(gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL) || '') : '';+ // A software rasteriser (headless CI, locked-down browsers) can't carry a+ // real-time AR scene — force the floor.+ if (/swiftshader|llvmpipe|software|basic render|microsoft basic/i.test(rs)) adj -= 3;+ return adj;+ } catch {+ return 0;+ }+}++function scoreToTier(score) {+ if (score >= 3) return 'high';+ if (score <= -2) return 'low';+ return 'mid';+}++// Pass the live renderer to fold real GPU capabilities into the decision; omit it+// for a signals-only estimate before the renderer exists.+export function detectTier(renderer) {+ let score = baseScore();+ if (renderer) score += gpuScore(renderer);+ return scoreToTier(score);+}++// Move a tier name one step along TIER_ORDER, clamped. The runtime watchdog uses+// this to degrade (or recover) live without re-reading device signals.+export function shiftTier(tier, dir) {+ const i = TIER_ORDER.indexOf(tier);+ if (i < 0) return tier;+ const next = Math.max(0, Math.min(TIER_ORDER.length - 1, i + dir));+ return TIER_ORDER[next];+}diff --git a/src/irl/share-frame.js b/src/irl/share-frame.jsnew file mode 100644index 000000000..274ab3370--- /dev/null+++ b/src/irl/share-frame.js@@ -0,0 +1,140 @@+// Composite-share for the immersive surfaces (IRL + XR).+//+// Flattens the WebGL canvas over the live camera feed into a single PNG and+// offers it through the native share sheet (navigator.share with files), with a+// desktop download fallback and a final URL-share → clipboard chain when the+// frame can't be captured. One module so /irl and /xr never drift apart.+//+// Requires the renderer to be built with `preserveDrawingBuffer: true`, or the+// canvas reads back blank between frames (set in src/irl.js and src/xr.js).++/**+ * Flatten the camera feed (when in AR) and the 3D canvas into one PNG blob.+ *+ * @param {object} opts+ * @param {HTMLCanvasElement} opts.canvas The WebGL canvas (drawn on top, alpha).+ * @param {HTMLVideoElement} [opts.video] The camera passthrough (drawn behind).+ * @param {boolean} opts.isAR True when the camera feed is the backdrop.+ * @returns {Promise<Blob|null>} PNG blob, or null if the canvas has no pixels yet.+ */+export async function captureComposite({ canvas, video, isAR }) {+ if (!canvas) return null;+ const w = canvas.width, h = canvas.height; // renderer pixel size, not CSS size+ if (!w || !h) return null;++ const out = document.createElement('canvas');+ out.width = w;+ out.height = h;+ const ctx = out.getContext('2d');+ if (!ctx) return null;++ // Camera feed first (background), then the 3D canvas (alpha) over the top, so+ // the agent sits in the room. videoWidth guards against a not-yet-playing feed.+ if (isAR && video && !video.paused && video.videoWidth) {+ try { ctx.drawImage(video, 0, 0, w, h); } catch { /* tainted/!ready — skip backdrop */ }+ }+ try { ctx.drawImage(canvas, 0, 0); } catch { /* canvas not readable — bail to null below */ }++ return await new Promise((resolve) => out.toBlob(resolve, 'image/png'));+}++/**+ * Share a blob through the native sheet, falling back to a desktop download.+ *+ * @param {Blob} blob+ * @param {object} [opts]+ * @param {string} [opts.filename]+ * @param {string} [opts.title]+ * @returns {Promise<'shared'|'downloaded'>}+ */+export async function shareOrDownload(blob, { filename = 'three-ws-irl.png', title = 'IRL · three.ws' } = {}) {+ const file = new File([blob], filename, { type: 'image/png' });+ if (navigator.share && navigator.canShare?.({ files: [file] })) {+ await navigator.share({ title, files: [file] });+ return 'shared';+ }+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ a.click();+ setTimeout(() => URL.revokeObjectURL(url), 4000);+ return 'downloaded';+}++// Swap a button's trailing label without disturbing a leading icon: update the+// last text node in place (icon'd XR button) or fall back to textContent (the+// text-only IRL button).+function setButtonLabel(btn, text) {+ const last = btn.lastChild;+ if (last && last.nodeType === 3 /* TEXT_NODE */) last.textContent = ` ${text}`;+ else btn.textContent = text;+}++/**+ * Wire a share button to the full capture → share/download → URL-share → clipboard+ * flow with designed transient states (… / Shared! / Saved! / Copied!). Returns a+ * disposer that removes the listener.+ *+ * @param {HTMLButtonElement} btn+ * @param {object} opts+ * @param {() => HTMLCanvasElement} opts.getCanvas+ * @param {() => HTMLVideoElement} [opts.getVideo]+ * @param {() => boolean} opts.getIsAR+ * @param {string} [opts.filename]+ * @param {string} [opts.title]+ * @returns {() => void} disposer+ */+export function wireShareButton(btn, { getCanvas, getVideo, getIsAR, filename = 'three-ws-irl.png', title = 'IRL · three.ws' }) {+ if (!btn) return () => {};++ const onClick = async () => {+ const origHTML = btn.innerHTML;+ const restore = (ms = 2000) => setTimeout(() => { btn.innerHTML = origHTML; btn.disabled = false; }, ms);++ btn.disabled = true;+ setButtonLabel(btn, '…');++ try {+ const blob = await captureComposite({+ canvas: getCanvas(),+ video: getVideo?.(),+ isAR: !!getIsAR(),+ });+ if (blob) {+ const result = await shareOrDownload(blob, { filename, title });+ setButtonLabel(btn, result === 'shared' ? 'Shared!' : 'Saved!');+ restore();+ return;+ }+ } catch (err) {+ // A user-cancelled share sheet (AbortError) is not a failure — restore+ // quietly without dropping to the URL fallback.+ if (err?.name === 'AbortError') { btn.innerHTML = origHTML; btn.disabled = false; return; }+ }++ // Capture failed (blank canvas / unsupported toBlob) — share the page URL,+ // then copy it as a last resort so the action is never a dead end.+ const url = location.href;+ if (navigator.share) {+ try {+ await navigator.share({ title, url });+ setButtonLabel(btn, 'Shared!');+ restore();+ return;+ } catch (err) {+ if (err?.name === 'AbortError') { btn.innerHTML = origHTML; btn.disabled = false; return; }+ }+ }+ try {+ await navigator.clipboard.writeText(url);+ setButtonLabel(btn, 'Copied!');+ } catch {+ btn.innerHTML = origHTML;+ }+ restore(1800);+ };++ btn.addEventListener('click', onClick);+ return () => btn.removeEventListener('click', onClick);+}diff --git a/src/notifications.js b/src/notifications.jsindex e93687a6b..218afd132 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -72,6 +72,8 @@ const TYPE_ICON = {embed: '🔗',remix: '🔄',reply: '💬',+ irl_interaction: '📍',+ irl_reply: '💬',};function notifLabel(n) {@@ -100,11 +102,35 @@ function notifLabel(n) {return `Someone remixed your creation`;case 'reply':return `New reply on your agent`;+ case 'irl_interaction':+ if (p.kind === 'pay') {+ const amt = irlPayLabel(p.amount, p.currency_mint);+ return amt ? `Your agent was paid ${amt} in person` : `Your agent was paid in person`;+ }+ return p.message+ ? `Someone messaged your agent in person: “${p.message}”`+ : `Someone messaged your agent in person`;+ case 'irl_reply':+ return p.message ? `An agent replied: “${p.message}”` : `An agent replied to your message`;default:return n.type.replace(/_/g, ' ');}}+// Human "0.05 USDC" from a pay notification's atomic amount + mint. $THREE and+// Solana/Base USDC are the only mints this platform references (each 6-decimal);+// an unrecognized mint degrades to a bare number rather than naming a coin.+function irlPayLabel(amount, mint) {+ if (amount == null) return '';+ const human = (Number(amount) / 1e6).toLocaleString('en-US', { maximumFractionDigits: 6 });+ if (!Number.isFinite(Number(amount))) return '';+ const m = String(mint || '').toLowerCase();+ const label = mint === 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' ? '$THREE'+ : (m === 'epjfwdd5aufqssqem2qn1xzybapc8g4weggkzwytdt1v' || m === '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913') ? 'USDC'+ : '';+ return label ? `${human} ${label}` : human;+}+function notifLink(n) {const p = n.payload || {};const raw = p.linkdiff --git a/src/xr.js b/src/xr.jsindex fd8192905..c8b3b16ec 100644--- a/src/xr.js+++ b/src/xr.js@@ -23,6 +23,7 @@ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';import { AnimationManager } from './animation-manager.js';import { WebXRSession } from './ar/webxr.js';+import { wireShareButton } from './irl/share-frame.js';import { canUseQuickLook } from './ar/quick-look.js';import { canUseSceneViewer, openSceneViewer } from './ar/scene-viewer.js';import { log } from './shared/log.js';@@ -536,5 +537,16 @@ if (changeAvatarBtn) {// Body toggle: start on full bodyfullBtn.classList.add('active');+ // Composite share — same module /irl uses, so the two surfaces never drift.+ // Flattens the camera passthrough (when AR is on) under the 3D canvas into one+ // PNG; renderer is built with preserveDrawingBuffer:true for a non-blank readback.+ wireShareButton(document.getElementById('xr-share-btn'), {+ getCanvas: () => canvas,+ getVideo: () => videoEl,+ getIsAR: () => arCameraActive,+ filename: 'three-ws-xr.png',+ title: 'XR · three.ws',+ });+await _detectARMode();})();diff --git a/tests/api/irl-interactions.test.js b/tests/api/irl-interactions.test.jsnew file mode 100644index 000000000..275028193--- /dev/null+++ b/tests/api/irl-interactions.test.js@@ -0,0 +1,287 @@+// POST/GET/PATCH /api/irl/interactions — C4 interaction log + inbox + reply.+//+// This is the IRL feedback loop: a passer-by's view/tap/message/pay is logged+// against a placed pin, the owner reads it back from their dashboard inbox, and+// the owner can reply to a visitor's message. The server is the trust boundary —+// owner/agent are resolved from the pin (never the caller), a `pay` is only+// recorded with a real settlement signature + a $THREE/USDC mint, and an owner+// reply must NOT notify the owner (it notifies the visitor instead). These tests+// pin that boundary down. DB / auth / limiter / notify are mocked so the suite+// stays offline.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Content-addressed SQL mock: classify each tagged-template query by its text so+// ensureTable() DDL, the pin lookup, the two de-dupe SELECTs, the reply lookup,+// and the INSERT each return the right shape regardless of call order. The INSERT+// echoes a row and records its bound values so success-path assertions can check+// the persisted payload (from='owner') and seen_at.+let pinRow = null;+let viewDupeRow = null; // row returned by the same-device view de-dupe SELECT+let paySigDupeRow = null; // row returned by the pay-signature de-dupe SELECT+let replyOrigRow = null; // row returned by the owner-reply origin lookup+let lastInsert = null; // { values } of the most recent irl_interactions INSERT++const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/FROM irl_pins[\s\S]*WHERE id =/i.test(q)) {+ return Promise.resolve(pinRow ? [pinRow] : []);+ }+ if (/SELECT id FROM irl_interactions[\s\S]*type = 'view'/i.test(q)) {+ return Promise.resolve(viewDupeRow ? [viewDupeRow] : []);+ }+ if (/type = 'pay' AND payload->>'signature'/i.test(q)) {+ return Promise.resolve(paySigDupeRow ? [paySigDupeRow] : []);+ }+ if (/SELECT[\s\S]*viewer_user_id FROM irl_interactions/i.test(q)) {+ return Promise.resolve(replyOrigRow ? [replyOrigRow] : []);+ }+ if (/INSERT INTO irl_interactions/i.test(q)) {+ lastInsert = { values };+ // RETURNING id, type, created_at — values[2] is `type`.+ return Promise.resolve([{ id: 'ix-new', type: values[2], created_at: '2026-06-17T00:00:00Z' }]);+ }+ // CREATE TABLE / ALTER TABLE / CREATE INDEX from ensureTable(), the view_count+ // UPDATE, and anything else.+ return Promise.resolve([]);+});+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { irlInteractIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));++const notifyMock = vi.fn();+vi.mock('../../api/_lib/notify.js', () => ({+ insertNotification: (...a) => notifyMock(...a),+}));++const alertMock = vi.fn();+vi.mock('../../api/_lib/alerts.js', () => ({+ sendOpsAlert: (...a) => alertMock(...a),+}));++const { default: handler } = await import('../../api/irl/interactions.js');++// A real Solana settlement signature (base58, 43–88 chars) and the $THREE mint —+// the only signature/mint a `pay` row is allowed to carry.+const SOL_SIG = '5'.repeat(64);+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++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, { body, query } = {}) {+ const res = makeRes();+ await handler({ url: '/api/irl/interactions', method, headers: { host: 'x' }, query: query || {}, body }, res);+ let parsed = null;+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON body */ }+ return { res, body: parsed };+}+const post = (body) => call('POST', { body });++function insertedPayload() {+ // INSERT columns: pin_id, agent_id, type, message, viewer_user_id, viewer_device,+ // lat, lng, amount, currency_mint, payload(JSON), seen_at.+ return lastInsert ? JSON.parse(lastInsert.values[10]) : null;+}+const insertedSeenAt = () => (lastInsert ? lastInsert.values[11] : undefined);++beforeEach(() => {+ sqlMock.mockClear();+ notifyMock.mockClear();+ alertMock.mockClear();+ lastInsert = null;+ viewDupeRow = null;+ paySigDupeRow = null;+ replyOrigRow = null;+ sessionUser = null;+ pinRow = {+ id: 'pin-1',+ agent_id: 'agent-1',+ lat: 40.7128,+ lng: -74.006,+ user_id: 'owner-uuid',+ device_token: null,+ };+});++describe('POST — validation + ownership resolution', () => {+ it('400s without a pinId', async () => {+ const { res } = await post({ type: 'view' });+ expect(res.statusCode).toBe(400);+ });++ it('404s when the pin is missing / expired / hidden', async () => {+ pinRow = null;+ const { res, body } = await post({ pinId: 'gone', type: 'tap' });+ expect(res.statusCode).toBe(404);+ expect(body.error).toMatch(/not found/i);+ });++ it('logs a tap and never trusts a caller-supplied owner — uses the pin', async () => {+ const { res } = await post({ pinId: 'pin-1', type: 'tap', deviceToken: 'dev-A' });+ expect(res.statusCode).toBe(201);+ // agent_id taken from the pin (values[1]), not the body.+ expect(lastInsert.values[1]).toBe('agent-1');+ });+});++describe('POST — view de-dupe', () => {+ it('collapses a repeat view from the same device within the window', async () => {+ viewDupeRow = { id: 'ix-existing' };+ const { res, body } = await post({ pinId: 'pin-1', type: 'view', deviceToken: 'dev-A' });+ expect(res.statusCode).toBe(200);+ expect(body.deduped).toBe(true);+ expect(lastInsert).toBeNull(); // no new row written+ });++ it("doesn't log the owner viewing their own pin", async () => {+ sessionUser = { id: 'owner-uuid' };+ const { res, body } = await post({ pinId: 'pin-1', type: 'view' });+ expect(res.statusCode).toBe(200);+ expect(body.self).toBe(true);+ expect(lastInsert).toBeNull();+ });+});++describe('POST — pay is only recorded with a verified settlement', () => {+ it('400s a pay with no signature', async () => {+ const { res, body } = await post({ pinId: 'pin-1', type: 'pay', amount: 50000, currencyMint: THREE_MINT });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/signature/i);+ expect(lastInsert).toBeNull();+ });++ it('400s a pay whose mint is neither $THREE nor USDC', async () => {+ const { res, body } = await post({+ pinId: 'pin-1', type: 'pay', amount: 50000,+ currencyMint: 'SomeOtherMint1111111111111111111111111111111', signature: SOL_SIG,+ });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/\$THREE or USDC/i);+ expect(lastInsert).toBeNull();+ });++ it('records a verified $THREE pay and notifies the owner + ops', async () => {+ const { res } = await post({+ pinId: 'pin-1', type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,+ });+ expect(res.statusCode).toBe(201);+ expect(insertedPayload().signature).toBe(SOL_SIG);+ expect(notifyMock).toHaveBeenCalledWith('owner-uuid', 'irl_interaction', expect.objectContaining({ kind: 'pay' }));+ expect(alertMock).toHaveBeenCalled();+ });++ it('de-dupes a pay by signature (one settlement → one row)', async () => {+ paySigDupeRow = { id: 'ix-paid' };+ const { res, body } = await post({+ pinId: 'pin-1', type: 'pay', amount: 50000, currencyMint: THREE_MINT, signature: SOL_SIG,+ });+ expect(res.statusCode).toBe(200);+ expect(body.deduped).toBe(true);+ expect(lastInsert).toBeNull();+ });+});++describe('POST — messages + owner replies', () => {+ it('a visitor message notifies the owner', async () => {+ const { res } = await post({ pinId: 'pin-1', type: 'message', message: 'is this the meetup?', deviceToken: 'dev-A' });+ expect(res.statusCode).toBe(201);+ expect(notifyMock).toHaveBeenCalledWith('owner-uuid', 'irl_interaction', expect.objectContaining({ kind: 'message' }));+ // not an owner reply → no from:'owner' stamp, stays unread (seen_at null).+ expect(insertedPayload().from).toBeUndefined();+ expect(insertedSeenAt()).toBeNull();+ });++ it("a visitor can't forge an owner reply via payload.from", async () => {+ const { res } = await post({+ pinId: 'pin-1', type: 'message', message: 'totally the owner', deviceToken: 'dev-A',+ payload: { from: 'owner' },+ });+ expect(res.statusCode).toBe(201);+ expect(insertedPayload().from).toBeUndefined(); // server stripped it+ expect(notifyMock).toHaveBeenCalledWith('owner-uuid', 'irl_interaction', expect.anything());+ });++ it('an authenticated owner message is a reply: from=owner, auto-seen, owner NOT notified', async () => {+ sessionUser = { id: 'owner-uuid' };+ replyOrigRow = { viewer_user_id: 'visitor-uuid' };+ const { res, body } = await post({+ pinId: 'pin-1', type: 'message', message: 'yes! see you there',+ replyTo: '11111111-1111-1111-1111-111111111111',+ });+ expect(res.statusCode).toBe(201);+ expect(insertedPayload().from).toBe('owner');+ expect(insertedSeenAt()).not.toBeNull(); // authored → already seen+ // The owner is never self-notified; the signed-in visitor is.+ expect(notifyMock).not.toHaveBeenCalledWith('owner-uuid', expect.anything(), expect.anything());+ expect(notifyMock).toHaveBeenCalledWith('visitor-uuid', 'irl_reply', expect.objectContaining({ pin_id: 'pin-1' }));+ expect(body.notified).toBe(true);+ });++ it('an owner reply to an anonymous visitor records but reports notified:false', async () => {+ sessionUser = { id: 'owner-uuid' };+ replyOrigRow = { viewer_user_id: null }; // visitor was anonymous+ const { res, body } = await post({+ pinId: 'pin-1', type: 'message', message: 'thanks for stopping by',+ replyTo: '11111111-1111-1111-1111-111111111111',+ });+ expect(res.statusCode).toBe(201);+ expect(insertedPayload().from).toBe('owner');+ expect(body.notified).toBe(false);+ expect(notifyMock).not.toHaveBeenCalled();+ });+});++describe('GET ?mine=1 + PATCH', () => {+ it('GET requires a session or deviceToken', async () => {+ const { res } = await call('GET', { query: { mine: '1' } });+ expect(res.statusCode).toBe(400);+ });++ it('GET returns interactions + unread for the owner', async () => {+ sessionUser = { id: 'owner-uuid' };+ // The mine=1 path runs two SELECTs (rows, then the unread COUNT). Serve both+ // off the default branch shape by special-casing the COUNT here.+ sqlMock.mockImplementation((strings) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/FILTER \(WHERE ix\.seen_at IS NULL\)/i.test(q)) return Promise.resolve([{ unread: 2 }]);+ if (/JOIN irl_pins p ON p\.id = ix\.pin_id/i.test(q)) {+ return Promise.resolve([{ id: 'ix-1', type: 'pay', seen_at: null, payload: {} }]);+ }+ return Promise.resolve([]);+ });+ const { res, body } = await call('GET', { query: { mine: '1' } });+ expect(res.statusCode).toBe(200);+ expect(Array.isArray(body.interactions)).toBe(true);+ expect(body.unread).toBe(2);+ sqlMock.mockClear();+ });++ it('PATCH requires a session or deviceToken', async () => {+ const { res } = await call('PATCH', { body: {} });+ expect(res.statusCode).toBe(400);+ });++ it('PATCH marks the owner rows seen', async () => {+ sessionUser = { id: 'owner-uuid' };+ const { res, body } = await call('PATCH', { body: {} });+ expect(res.statusCode).toBe(200);+ expect(body.ok).toBe(true);+ });+});diff --git a/tests/api/irl-pins-moderation.test.js b/tests/api/irl-pins-moderation.test.jsnew file mode 100644index 000000000..c5858bcca--- /dev/null+++ b/tests/api/irl-pins-moderation.test.js@@ -0,0 +1,169 @@+// POST /api/irl/pins — IRL-Live D4 moderation, safety & density caps.+//+// The POST chokepoint is where a public, shared placement turns dangerous: a slur+// in a caption, a non-$THREE coin shill, a pin pointing its Pay button at an+// off-platform drain, one actor carpet-bombing a plaza, or a scripted flood. These+// tests prove each gate fires with its designed error code, in the right order+// (content → endpoint → rate → density → owner cap), and that a clean placement+// still succeeds. DB / auth / limiter are mocked so the suite stays offline.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Content-addressed SQL mock: the density count, the per-owner count, and the+// INSERT each return a shape keyed off the query text, so call order doesn't+// matter. `densityCount` / `ownerCount` are tunable per test.+let densityCount = 0;+let ownerCount = 0;+const sqlMock = vi.fn((strings) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/count\(\*\)::int AS n[\s\S]*geocell7 =/i.test(q)) {+ return Promise.resolve([{ n: densityCount }]);+ }+ if (/count\(\*\)::int AS n[\s\S]*user_id =/i.test(q)) {+ return Promise.resolve([{ n: ownerCount }]);+ }+ if (/INSERT INTO irl_pins/i.test(q)) {+ return Promise.resolve([{ id: 'new-pin', expires_at: '2030-01-01T00:00:00Z' }]);+ }+ // ensureTable DDL + anything else.+ return Promise.resolve([]);+});+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+}));++// Tunable limiter verdicts. Default: everything passes. A test flips one to+// model that bucket being exhausted.+let limiterVerdicts = {};+function verdict(name) {+ return limiterVerdicts[name] ?? { success: true, reset: Date.now() + 60_000 };+}+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ irlPinIp: vi.fn(async () => verdict('irlPinIp')),+ irlPinBurst: vi.fn(async () => verdict('irlPinBurst')),+ irlPinHourly: vi.fn(async () => verdict('irlPinHourly')),+ },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../../api/irl/pins.js');++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 post(body) {+ const res = makeRes();+ await handler({ url: '/api/irl/pins', method: 'POST', headers: { host: 'x' }, query: {}, body }, res);+ let parsed = null;+ try { parsed = JSON.parse(res._body); } catch {}+ return { res, body: parsed };+}++const BASE = { lat: 40.7128, lng: -74.006, avatarName: 'Aria', caption: 'hello world' };++beforeEach(() => {+ sqlMock.mockClear();+ densityCount = 0;+ ownerCount = 0;+ limiterVerdicts = {};+ sessionUser = null;+});++describe('POST /api/irl/pins — content gate', () => {+ it('422s a caption with a blacklisted term and never inserts', async () => {+ const { res, body } = await post({ ...BASE, caption: 'you absolute retard' });+ expect(res.statusCode).toBe(422);+ expect(body.error).toBe('content');+ expect(body.field).toBe('caption');+ const inserted = sqlMock.mock.calls.some(([s]) =>+ /INSERT INTO irl_pins/i.test(Array.isArray(s) ? s.join(' ') : String(s)));+ expect(inserted).toBe(false);+ });++ it('422s a blacklisted avatar name', async () => {+ const { res, body } = await post({ ...BASE, avatarName: 'kys bot' });+ expect(res.statusCode).toBe(422);+ expect(body.field).toBe('avatarName');+ });++ it('422s an off-brand coin cashtag with a $THREE-only message', async () => {+ const { res, body } = await post({ ...BASE, caption: 'aping $DOGE hard' });+ expect(res.statusCode).toBe(422);+ expect(body.error).toBe('content');+ expect(body.message).toMatch(/\$THREE/);+ });++ it('allows a caption that references $THREE', async () => {+ const { res } = await post({ ...BASE, caption: 'powered by $THREE' });+ expect(res.statusCode).toBe(201);+ });+});++describe('POST /api/irl/pins — endpoint allow-list', () => {+ it('422s an x402 endpoint on an arbitrary external host', async () => {+ const { res, body } = await post({ ...BASE, x402Endpoint: 'https://evil.example.com/drain' });+ expect(res.statusCode).toBe(422);+ expect(body.error).toBe('endpoint');+ });++ it('201s an x402 endpoint on a first-party host', async () => {+ const { res } = await post({ ...BASE, x402Endpoint: 'https://three.ws/api/x402-pay' });+ expect(res.statusCode).toBe(201);+ });+});++describe('POST /api/irl/pins — rate limit', () => {+ it('429s with retryAfter when the burst bucket is exhausted', async () => {+ limiterVerdicts.irlPinBurst = { success: false, reset: Date.now() + 30_000 };+ const { res, body } = await post({ ...BASE });+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate');+ expect(body.retryAfter).toBeGreaterThan(0);+ expect(res.getHeader('Retry-After')).toBeTruthy();+ });+});++describe('POST /api/irl/pins — density + owner caps', () => {+ it('429 area_full when the geocell is at capacity (40 pins → 41st rejected)', async () => {+ densityCount = 40;+ const { res, body } = await post({ ...BASE });+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('area_full');+ });++ it('429 pin_limit when an anonymous device is at its active-pin cap (20)', async () => {+ ownerCount = 20;+ const { res, body } = await post({ ...BASE, deviceToken: 'dev-A' });+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('pin_limit');+ expect(body.limit).toBe(20);+ });++ it('a signed-in owner gets the higher cap (19 anon-over-limit still passes)', async () => {+ sessionUser = { id: 'owner-uuid' };+ ownerCount = 19; // over the anon 20? no — 19 < 60 signed ceiling, so it passes+ const { res } = await post({ ...BASE });+ expect(res.statusCode).toBe(201);+ });+});++describe('POST /api/irl/pins — clean placement', () => {+ it('201s and returns the created pin with permanent=false for anonymous', async () => {+ const { res, body } = await post({ ...BASE, deviceToken: 'dev-A' });+ expect(res.statusCode).toBe(201);+ expect(body.pin.id).toBe('new-pin');+ expect(body.pin.permanent).toBe(false);+ });+});diff --git a/tests/api/irl-pins-outfit.test.js b/tests/api/irl-pins-outfit.test.jsnew file mode 100644index 000000000..ea239ac7e--- /dev/null+++ b/tests/api/irl-pins-outfit.test.js@@ -0,0 +1,205 @@+// PATCH /api/irl/pins { avatar_manifest } — C6 remote outfit change.+//+// Changing a placed agent's outfit re-skins it for EVERY nearby viewer, so the+// server is the security + correctness boundary: it must reject non-owners,+// reject invented slots/presets before baking, bake onto the pin's clean BASE+// (never the prior bake), bump avatar_version, and emit the realtime hook. These+// tests prove that boundary with the DB / auth / baker / realtime mocked so the+// suite stays offline (the bake core itself is covered by avatar-bake.test.js).++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Hoisted spies so the vi.mock factories (which hoist above imports) can close+// over them. bakeSpy stands in for the real GLB bake+upload; emitSpy for the D1+// fan-out hook.+const { bakeSpy, emitSpy } = vi.hoisted(() => ({ bakeSpy: vi.fn(), emitSpy: vi.fn() }));++// Content-addressed SQL mock: ensureTable DDL → []; the WHERE-id SELECT returns+// the current pin (null → not found); the outfit UPDATE echoes the new look with+// a bumped version so success-path assertions see what every viewer will fetch.+let pinRow = null;+const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/SELECT[\s\S]*FROM irl_pins[\s\S]*WHERE id =/i.test(q)) {+ return Promise.resolve(pinRow ? [pinRow] : []);+ }+ if (/UPDATE irl_pins SET[\s\S]*avatar_version\s*=\s*avatar_version \+ 1/i.test(q)) {+ // values: [manifestJson, baseUrl, newAvatarUrl, id, sessionId]+ 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,+ }]);+ }+ return Promise.resolve([]); // CREATE/ALTER/INDEX + 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),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { irlPinIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));++// Baker stub — re-implements isBakeable with the real semantics (so the empty /+// cleared-manifest path is exercised honestly) and records bake calls.+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)+ )),+}));++vi.mock('../../api/_lib/irl-realtime.js', () => ({ emitPinUpdated: (...a) => emitSpy(...a) }));++const { default: handler } = await import('../../api/irl/pins.js');++const BAKED_URL = 'https://three.ws/cdn/irl/pins/pin-1/abc1234567890def.glb';++function makeReq(body) {+ return { url: '/api/irl/pins', method: 'PATCH', headers: { host: 'x' }, query: {}, body };+}+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 patch(body) {+ const res = makeRes();+ await handler(makeReq(body), res);+ let parsed = null;+ try { parsed = JSON.parse(res._body); } catch {}+ return { res, body: parsed };+}+function ranOutfitUpdate() {+ return sqlMock.mock.calls.some(([s]) =>+ /UPDATE irl_pins SET[\s\S]*avatar_version\s*=\s*avatar_version \+ 1/i.test(Array.isArray(s) ? s.join(' ') : String(s)));+}++beforeEach(() => {+ sqlMock.mockClear();+ bakeSpy.mockReset();+ bakeSpy.mockResolvedValue({ url: BAKED_URL });+ emitSpy.mockReset();+ pinRow = {+ id: 'pin-1',+ user_id: 'owner-uuid',+ avatar_url: '/api/avatars/av-1/glb',+ avatar_base_url: null,+ avatar_version: 0,+ };+ sessionUser = { id: 'owner-uuid' };+});++describe('PATCH /api/irl/pins outfit — auth + ownership gate', () => {+ it('401s an unauthenticated caller (auth gate precedes the handler)', async () => {+ sessionUser = null;+ const { res } = await patch({ id: 'pin-1', avatar_manifest: { colors: { outfit: '#7a1f2b' } } });+ expect(res.statusCode).toBe(401);+ expect(bakeSpy).not.toHaveBeenCalled();+ });++ it('404s when the pin no longer exists', async () => {+ pinRow = null;+ const { res, body } = await patch({ id: 'gone', avatar_manifest: { colors: { outfit: '#7a1f2b' } } });+ expect(res.statusCode).toBe(404);+ expect(body.error).toMatch(/not found/i);+ });++ it('403s a signed-in non-owner and never bakes or updates', async () => {+ sessionUser = { id: 'someone-else' };+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: { colors: { outfit: '#7a1f2b' } } });+ expect(res.statusCode).toBe(403);+ expect(body.error).toMatch(/only the owner/i);+ expect(bakeSpy).not.toHaveBeenCalled();+ expect(ranOutfitUpdate()).toBe(false);+ });+});++describe('PATCH /api/irl/pins outfit — manifest validation (before bake)', () => {+ it('400s a non-object manifest', async () => {+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: ['nope'] });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/must be an object or null/i);+ expect(bakeSpy).not.toHaveBeenCalled();+ });++ it('400s an invented colour slot before any bake runs', async () => {+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: { colors: { cape: '#000000' } } });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/unknown color slot/i);+ expect(bakeSpy).not.toHaveBeenCalled();+ });++ it('400s an invented accessory preset id', async () => {+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: { accessories: ['jetpack-9000'] } });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/unknown preset id/i);+ expect(bakeSpy).not.toHaveBeenCalled();+ });+});++describe('PATCH /api/irl/pins outfit — owner re-skin persists for everyone', () => {+ it('bakes onto the captured base, bumps version, returns the new avatar_url, and emits the realtime hook', async () => {+ const manifest = { colors: { outfit: '#7a1f2b' }, hidden: ['glasses'] };+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: manifest });+ expect(res.statusCode).toBe(200);+ // Bake targets the pin's base GLB (avatar_base_url null → falls back to avatar_url).+ expect(bakeSpy).toHaveBeenCalledWith({ pinId: 'pin-1', baseUrl: '/api/avatars/av-1/glb', manifest });+ expect(body.pin.avatar_url).toBe(BAKED_URL);+ expect(body.pin.avatar_version).toBe(1);+ expect(body.pin.avatar_manifest).toEqual(manifest);+ // Realtime fan-out fired with the persisted row.+ expect(emitSpy).toHaveBeenCalledTimes(1);+ expect(emitSpy.mock.calls[0][0]).toMatchObject({ id: 'pin-1', avatar_url: BAKED_URL, avatar_version: 1 });+ });++ it('re-bakes from the stored base on a later edit (never stacks on the prior bake)', async () => {+ // Second edit: the pin already has a captured base + a previously baked url.+ pinRow.avatar_base_url = '/api/avatars/av-1/glb';+ pinRow.avatar_url = 'https://three.ws/cdn/irl/pins/pin-1/oldhash.glb';+ pinRow.avatar_version = 3;+ const manifest = { accessories: ['hat-baseball'] };+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: manifest });+ expect(res.statusCode).toBe(200);+ // Critically: baseUrl is the captured base, NOT the already-baked avatar_url.+ expect(bakeSpy).toHaveBeenCalledWith({ pinId: 'pin-1', baseUrl: '/api/avatars/av-1/glb', manifest });+ expect(body.pin.avatar_version).toBe(4);+ });++ it('reverts to the bare base for an empty/cleared manifest (no bake)', async () => {+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: {} });+ expect(res.statusCode).toBe(200);+ expect(bakeSpy).not.toHaveBeenCalled(); // nothing bakeable → skip the bake+ expect(body.pin.avatar_url).toBe('/api/avatars/av-1/glb'); // served base again+ expect(body.pin.avatar_version).toBe(1); // still a versioned change+ expect(emitSpy).toHaveBeenCalledTimes(1);+ });++ it('502s and does not persist when the bake throws', async () => {+ bakeSpy.mockRejectedValueOnce(new Error('libvips exploded'));+ const { res, body } = await patch({ id: 'pin-1', avatar_manifest: { colors: { hair: '#0e0e0e' } } });+ expect(res.statusCode).toBe(502);+ expect(body.error).toMatch(/could not bake/i);+ expect(ranOutfitUpdate()).toBe(false);+ expect(emitSpy).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/irl-report.test.js b/tests/api/irl-report.test.jsnew file mode 100644index 000000000..a5ffc1414--- /dev/null+++ b/tests/api/irl-report.test.js@@ -0,0 +1,135 @@+// POST /api/irl/report — IRL-Live D4 community moderation.+//+// A pin is queued out of public view once enough DISTINCT reporters flag it — not+// on a single report, and not twice from the same reporter. These tests prove the+// threshold gate, the owner protection (you can't self-report your own pin into+// hiding, one actor can't hide someone else's), and the terminal states. DB / auth+// / limiter are mocked so the suite stays offline.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// `pinRow` is what the pin lookup returns (null → 404). `distinctReporters` is what+// the COUNT(DISTINCT reporter_token) returns. `hideUpdated` models whether the+// guarded UPDATE ... WHERE hidden_at IS NULL actually flipped a row.+let pinRow = null;+let distinctReporters = 1;+let hideUpdated = true;+const sqlMock = vi.fn((strings) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/SELECT[\s\S]*FROM irl_pins[\s\S]*WHERE id =/i.test(q)) {+ return Promise.resolve(pinRow ? [pinRow] : []);+ }+ if (/count\(DISTINCT reporter_token\)/i.test(q)) {+ return Promise.resolve([{ n: distinctReporters }]);+ }+ if (/UPDATE irl_pins[\s\S]*hidden_at = NOW\(\)/i.test(q)) {+ return Promise.resolve(hideUpdated ? [{ id: pinRow?.id }] : []);+ }+ // INSERT INTO irl_pin_reports, ensureTable DDL, anything else.+ return Promise.resolve([]);+});+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { irlReportIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../../api/irl/report.js');++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ 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 report(body) {+ const res = makeRes();+ await handler({ url: '/api/irl/report', method: 'POST', headers: { host: 'x' }, query: {}, body }, res);+ let parsed = null;+ try { parsed = JSON.parse(res._body); } catch {}+ return { res, body: parsed };+}++beforeEach(() => {+ sqlMock.mockClear();+ pinRow = { id: 'pin-1', user_id: null, device_token: 'owner-dev', hidden_at: null };+ distinctReporters = 1;+ hideUpdated = true;+ sessionUser = null;+});++describe('POST /api/irl/report', () => {+ it('400s without a pinId', async () => {+ const { res, body } = await report({ reason: 'spam' });+ expect(res.statusCode).toBe(400);+ expect(body.error).toMatch(/pinId/);+ });++ it('404s when the pin does not exist', async () => {+ pinRow = null;+ const { res } = await report({ pinId: 'gone', reason: 'spam', deviceToken: 'dev-X' });+ expect(res.statusCode).toBe(404);+ });++ it('records a single report without hiding the pin (below threshold)', async () => {+ distinctReporters = 1;+ const { res, body } = await report({ pinId: 'pin-1', reason: 'spam', deviceToken: 'dev-X' });+ expect(res.statusCode).toBe(200);+ expect(body.hidden).toBe(false);+ expect(body.reports).toBe(1);+ const updated = sqlMock.mock.calls.some(([s]) =>+ /hidden_at = NOW\(\)/i.test(Array.isArray(s) ? s.join(' ') : String(s)));+ expect(updated).toBe(false);+ });++ it('hides the pin once distinct reporters reach the threshold (3)', async () => {+ distinctReporters = 3;+ const { res, body } = await report({ pinId: 'pin-1', reason: 'harassment', deviceToken: 'dev-Z' });+ expect(res.statusCode).toBe(200);+ expect(body.hidden).toBe(true);+ });++ it('a single reporter cannot hide a pin (one distinct token, threshold not met)', async () => {+ distinctReporters = 1;+ const { body } = await report({ pinId: 'pin-1', reason: 'scam', deviceToken: 'lone-dev' });+ expect(body.hidden).toBe(false);+ });++ it('ignores an owner self-report (device-token owner) without counting it', async () => {+ const { res, body } = await report({ pinId: 'pin-1', reason: 'spam', deviceToken: 'owner-dev' });+ expect(res.statusCode).toBe(200);+ expect(body.self).toBe(true);+ const inserted = sqlMock.mock.calls.some(([s]) =>+ /INSERT INTO irl_pin_reports/i.test(Array.isArray(s) ? s.join(' ') : String(s)));+ expect(inserted).toBe(false);+ });++ it('ignores an authenticated owner self-report', async () => {+ pinRow = { id: 'pin-1', user_id: 'owner-uuid', device_token: null, hidden_at: null };+ sessionUser = { id: 'owner-uuid' };+ const { body } = await report({ pinId: 'pin-1', reason: 'spam' });+ expect(body.self).toBe(true);+ });++ it('reports an already-hidden pin idempotently', async () => {+ pinRow.hidden_at = '2026-06-17T00:00:00Z';+ const { res, body } = await report({ pinId: 'pin-1', reason: 'spam', deviceToken: 'dev-Y' });+ expect(res.statusCode).toBe(200);+ expect(body.hidden).toBe(true);+ });++ it('normalizes an unknown reason to "other" (still accepted)', async () => {+ const { res } = await report({ pinId: 'pin-1', reason: 'banana', deviceToken: 'dev-Q' });+ expect(res.statusCode).toBe(200);+ });+});diff --git a/vercel.json b/vercel.jsonindex 18ae8200f..2b05a4e6a 100644--- a/vercel.json+++ b/vercel.json@@ -172,12 +172,18 @@"api/irl/interactions.js": {"maxDuration": 15},+ "api/irl/interactions-stream.js": {+ "maxDuration": 300+ },"api/irl/agent-summary.js": {"maxDuration": 15},"api/irl/agent-card.js": {"maxDuration": 15},+ "api/irl/report.js": {+ "maxDuration": 15+ },"api/**/*.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 30@@ -1952,6 +1958,10 @@"src": "/api/irl/pins","dest": "/api/irl/pins.js"},+ {+ "src": "/api/irl/interactions-stream",+ "dest": "/api/irl/interactions-stream.js"+ },{"src": "/api/irl/interactions","dest": "/api/irl/interactions.js"@@ -1964,6 +1974,10 @@"src": "/api/irl/agent-card","dest": "/api/irl/agent-card.js"},+ {+ "src": "/api/irl/report",+ "dest": "/api/irl/report.js"+ },{"src": "/api/copy/executions","dest": "/api/copy/executions.js"@@ -3528,6 +3542,10 @@"path": "/api/cron/audit-log-cleanup","schedule": "0 4 * * *"},+ {+ "path": "/api/cron/irl-reap",+ "schedule": "17 * * * *"+ },{"path": "/api/cron/expire-pending-purchases","schedule": "*/5 * * * *"