Skip to content

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

IRL: realtime presence + ambient reactions, agent-card/report hardening, and test coverage

nirholas35482d5ef2d2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c343150d8..2a6bfce9b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,7 +11,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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 now visibly react when someone engages them** — Walk past an agent placed in the real world and it now feels alive: the moment anyone standing nearby taps it, leaves it a message, or pays it, the agent does a little perk-up and a reaction floats up off its head — a 💜 for a glance, a ✨ 'paid' burst for a real on-chain payment, a 💬 for a message — and everyone viewing that spot sees it at once, not just the person who acted. A busy agent looks busy, which is the whole point of putting one somewhere public. Rapid taps are smoothed so the same person can't spam the reaction, while payments and messages always come through. The reaction is purely a visual flourish — it carries no one's location or wallet — and if your connection drops to the slower fallback the interaction is still recorded for the owner; only the live animation is skipped. (`/irl`) `[feature]`
- **IRL agents turn to look at you as you move around them** — On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you. (`/irl`) `[improvement]`
+- **IRL never shows a blank screen — every state is now designed** — Every corner of three.ws/irl now tells you what's going on instead of leaving a blank space. The radar minimap reads 'No agents in range' when an area is quiet, and 'Can't refresh' if the nearby feed briefly drops — then recovers on its own. The nearby count, when GPS is live but nobody's pinned around you yet, invites you to be the first to drop an agent there rather than simply disappearing. Tap an agent's Pay or Use button without a wallet connected and you now get a clear, lasting card explaining how to connect one — instead of a message that flashes away before you can read it. And your IRL Placements dashboard now has a proper loading skeleton, a friendly empty state when you haven't placed anything, and a retry button if the list can't load — never a spinner that hangs or a void. (`/irl`) `[improvement]`
- **IRL now fails gracefully — clear states instead of blank screens** — Every part of three.ws/irl now shows a designed state when something isn't right, instead of a blank screen or a message that flashes for three seconds and disappears. On a device or browser that can't run the AR view, IRL now says so up front and points you to browse agents and the marketplace on the web. If an agent's 3D avatar fails to load, you get a clear card with a Retry button instead of the scene just sitting empty. Your My pins list now tells the difference between 'you haven't placed any yet' and 'we couldn't load them right now' — the latter offers a retry instead of pretending the list is empty. When the nearby-agents view can't refresh, the count now says so and keeps retrying rather than silently looking deserted. And camera issues — no access granted, or a browser with no camera at all — now show a recoverable card explaining what to do, noting the 3D scene still works without the camera. (`/irl`) `[improvement, fix]`
- **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]`
@@ -21,7 +23,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
+- **Report a bad IRL pin — and guardrails that keep public spots usable** — Now that anyone standing at a location sees the agents others placed there, three.ws/irl has the moderation it needs to stay clean. Tap any agent that isn't yours and a new Report option lets you flag it for spam, hate or harassment, impersonation, a scam, sexual content, or anything else — with a clear sending, thanks, and try-again state, never a dead button. Reports are counted per person, so one account can't bury a pin it dislikes; once enough different people flag the same agent it's hidden from everyone — and if you're nearby when that happens it vanishes from your view within about a second rather than lingering until the next scan. Placing agents is now protected too: captions and names with slurs are refused, a pin can only ever reference $THREE, the only coin on three.ws, and its pay button can only point at three.ws — never an outside link. A single busy block holds a sensible maximum of agents and each person has an active-pin limit, so no one can carpet-bomb a plaza or spam placements, and every refusal tells you exactly what to do. Abandoned anonymous pins are cleaned up automatically while the agents you're signed in for stay put. (`/irl`) `[feature, security]`
+- **See a placed agent's on-chain reputation from your dashboard** — Your IRL Placements dashboard now shows each placed agent's on-chain reputation — the exact score and trust tier a passer-by sees when they tap it in the real world, so you know what the public sees. Tap an agent's Reputation chip to open a panel with its 0–100 score and tier (New, Emerging, Trusted, Elite), a star rating, and a breakdown of how many attestations are verified, credentialed, or disputed. A small 30-day trend line shows whether its reputation is climbing. Agents that haven't earned any attestations yet get a clear prompt to share them rather than an empty number, and a 'Manage on passport' link takes you to where you add or dispute attestations. If the reputation service is unreachable the panel offers a retry instead of failing silently. (`/dashboard/irl-placements`) `[feature, improvement]`
- **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]`
+- **Share a photo straight from the XR viewer** — three.ws/xr now has the same one-tap Share that three.ws/irl has had: it flattens your live camera view and the 3D agent into a single photo and hands it to your phone's share sheet to post or send — or downloads it as a PNG on desktop. With the camera on, the picture shows your agent standing in your real surroundings; with it off, it shares the 3D view on its own. If a snapshot can't be captured for any reason, Share falls back to sending the page link so it's never a dead end. The Share buttons on both pages now show a brief progress state while the image is being made, and the immersive buttons give keyboard users a clear focus outline. (`/xr`) `[feature, improvement]`
- **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]`
diff --git a/api/irl/agent-card.js b/api/irl/agent-card.js
index 6cad5464b..3a4de8d59 100644
--- a/api/irl/agent-card.js
+++ b/api/irl/agent-card.js
@@ -56,7 +56,7 @@ const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
*
* Tiers: >=85 elite · >=60 trusted · >=30 emerging · else new
*/
-function deriveReputation({ fbTotal, scoreAvg, uniqueAttesters, valPassed, valFailed, tasksAccepted }) {
+export function deriveReputation({ fbTotal, scoreAvg, uniqueAttesters, valPassed, valFailed, tasksAccepted }) {
// 1–5 stars → 0–1 (a 1-star floor contributes nothing; a 5-star avg is full).
const scoreNorm = fbTotal > 0 ? clamp((scoreAvg - 1) / 4, 0, 1) : 0;
// log10(1+n)/log10(51): 0 attesters → 0, ~50 attesters → ~1.
diff --git a/api/irl/report.js b/api/irl/report.js
index 87bcf2ff5..9166a6d1e 100644
--- a/api/irl/report.js
+++ b/api/irl/report.js
@@ -15,17 +15,24 @@
* 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.
+ * references. When the threshold hides a pin we publish a D1 pin:remove into its
+ * geocell room so already-loaded viewers see it vanish live; the hidden_at filter
+ * on every nearby/mine/bbox read is the durable backstop if that push ever drops.
*/
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';
+import { publishIrlPin } from '../_lib/irl-publish.js';
+import { encodeGeohash } from '../_lib/geohash.js';
// Distinct reporters required before a pin is queued out of public view.
const REPORT_HIDE_THRESHOLD = 3;
+// The irl_world realtime room is keyed by a precision-6 geocell (~1.2 km) — match
+// REALTIME_PRECISION in api/irl/pins.js so a hide publishes into the same live room
+// the pin's add/update/delete events used.
+const REALTIME_PRECISION = 6;
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.
@@ -78,7 +85,7 @@ export default wrap(async (req, res) => {
// 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
+ SELECT id, user_id, device_token, hidden_at, lat, lng
FROM irl_pins
WHERE id = ${pinId}
AND (expires_at IS NULL OR expires_at > NOW())
@@ -133,6 +140,21 @@ export default wrap(async (req, res) => {
RETURNING id
`;
hidden = rows.length > 0;
+ // Realtime (D1): the first reporter to cross the threshold pushes a pin:remove
+ // into the pin's geocell room, so every co-located viewer who already has it
+ // loaded sees it vanish within ~1 s — not just on their next nearby re-fetch.
+ // Guarded on the conditional UPDATE above so concurrent reports fire it once.
+ // Fire-and-forget: the hide is already persisted and the hidden_at filter on
+ // every read path is the durable contract if the push drops.
+ const plat = Number(pin.lat);
+ const plng = Number(pin.lng);
+ if (hidden && Number.isFinite(plat) && Number.isFinite(plng)) {
+ void publishIrlPin(
+ 'pin:remove',
+ encodeGeohash(plat, plng, REALTIME_PRECISION),
+ { id: pinId },
+ );
+ }
}
return json(res, 200, { ok: true, reports: n, hidden });
diff --git a/data/changelog.json b/data/changelog.json
index 861d14dc0..e2fc6b651 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,41 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-17",
+ "title": "IRL agents now visibly react when someone engages them",
+ "summary": "Walk past an agent placed in the real world and it now feels alive: the moment anyone standing nearby taps it, leaves it a message, or pays it, the agent does a little perk-up and a reaction floats up off its head — a 💜 for a glance, a ✨ 'paid' burst for a real on-chain payment, a 💬 for a message — and everyone viewing that spot sees it at once, not just the person who acted. A busy agent looks busy, which is the whole point of putting one somewhere public. Rapid taps are smoothed so the same person can't spam the reaction, while payments and messages always come through. The reaction is purely a visual flourish — it carries no one's location or wallet — and if your connection drops to the slower fallback the interaction is still recorded for the owner; only the live animation is skipped.",
+ "tags": ["feature"],
+ "link": "/irl"
+ },
+ {
+ "date": "2026-06-17",
+ "title": "IRL never shows a blank screen — every state is now designed",
+ "summary": "Every corner of three.ws/irl now tells you what's going on instead of leaving a blank space. The radar minimap reads 'No agents in range' when an area is quiet, and 'Can't refresh' if the nearby feed briefly drops — then recovers on its own. The nearby count, when GPS is live but nobody's pinned around you yet, invites you to be the first to drop an agent there rather than simply disappearing. Tap an agent's Pay or Use button without a wallet connected and you now get a clear, lasting card explaining how to connect one — instead of a message that flashes away before you can read it. And your IRL Placements dashboard now has a proper loading skeleton, a friendly empty state when you haven't placed anything, and a retry button if the list can't load — never a spinner that hangs or a void.",
+ "tags": ["improvement"],
+ "link": "/irl"
+ },
+ {
+ "date": "2026-06-17",
+ "title": "See a placed agent's on-chain reputation from your dashboard",
+ "summary": "Your IRL Placements dashboard now shows each placed agent's on-chain reputation — the exact score and trust tier a passer-by sees when they tap it in the real world, so you know what the public sees. Tap an agent's Reputation chip to open a panel with its 0–100 score and tier (New, Emerging, Trusted, Elite), a star rating, and a breakdown of how many attestations are verified, credentialed, or disputed. A small 30-day trend line shows whether its reputation is climbing. Agents that haven't earned any attestations yet get a clear prompt to share them rather than an empty number, and a 'Manage on passport' link takes you to where you add or dispute attestations. If the reputation service is unreachable the panel offers a retry instead of failing silently.",
+ "tags": ["feature", "improvement"],
+ "link": "/dashboard/irl-placements"
+ },
+ {
+ "date": "2026-06-17",
+ "title": "Report a bad IRL pin — and guardrails that keep public spots usable",
+ "summary": "Now that anyone standing at a location sees the agents others placed there, three.ws/irl has the moderation it needs to stay clean. Tap any agent that isn't yours and a new Report option lets you flag it for spam, hate or harassment, impersonation, a scam, sexual content, or anything else — with a clear sending, thanks, and try-again state, never a dead button. Reports are counted per person, so one account can't bury a pin it dislikes; once enough different people flag the same agent it's hidden from everyone — and if you're nearby when that happens it vanishes from your view within about a second rather than lingering until the next scan. Placing agents is now protected too: captions and names with slurs are refused, a pin can only ever reference $THREE, the only coin on three.ws, and its pay button can only point at three.ws — never an outside link. A single busy block holds a sensible maximum of agents and each person has an active-pin limit, so no one can carpet-bomb a plaza or spam placements, and every refusal tells you exactly what to do. Abandoned anonymous pins are cleaned up automatically while the agents you're signed in for stay put.",
+ "tags": ["feature", "security"],
+ "link": "/irl"
+ },
+ {
+ "date": "2026-06-17",
+ "title": "Share a photo straight from the XR viewer",
+ "summary": "three.ws/xr now has the same one-tap Share that three.ws/irl has had: it flattens your live camera view and the 3D agent into a single photo and hands it to your phone's share sheet to post or send — or downloads it as a PNG on desktop. With the camera on, the picture shows your agent standing in your real surroundings; with it off, it shares the 3D view on its own. If a snapshot can't be captured for any reason, Share falls back to sending the page link so it's never a dead end. The Share buttons on both pages now show a brief progress state while the image is being made, and the immersive buttons give keyboard users a clear focus outline.",
+ "tags": ["feature", "improvement"],
+ "link": "/xr"
+ },
{
"date": "2026-06-17",
"title": "Nearby agents on IRL now update live — no reload",
diff --git a/multiplayer/src/irl-reactions.js b/multiplayer/src/irl-reactions.js
new file mode 100644
index 000000000..6e07cac53
Binary files /dev/null and b/multiplayer/src/irl-reactions.js differ
diff --git a/multiplayer/src/irl-schemas.js b/multiplayer/src/irl-schemas.js
index c81027d51..706f4f372 100644
--- a/multiplayer/src/irl-schemas.js
+++ b/multiplayer/src/irl-schemas.js
@@ -47,17 +47,25 @@ defineTypes(IrlPin, {
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.
+// A live viewer present in this geocell — live presence (D2). D1 declared this
+// schema and left the map empty; D2 POPULATES it (IrlRoom.onJoin / heartbeat /
+// reaper) so the count and ghost markers are pure MapSchema deltas — no new
+// transport. lat/lng are ALWAYS the viewer's geocell centre + bounded jitter,
+// never their precise GPS: the only location a viewer reveals is "somewhere in
+// this ~1 km cell." The new D2 fields are appended (heading/avatar/ghost/
+// tsServer) so an older still-connected client isn't shifted off the wire format.
export class IrlViewer extends Schema {
constructor() {
super();
- this.id = ''; // session id
+ this.id = ''; // ephemeral session id (NOT the device token)
this.lat = 0; // cell-centre + bounded jitter (privacy — never precise GPS)
this.lng = 0;
this.agentId = ''; // the agent this viewer is embodying, if any
+ // — D2 (append-only) —
+ this.heading = 0; // optional compass facing 0–359°, for ghost orientation
+ this.avatar = ''; // GLB url — '' unless the viewer opted to share a ghost
+ this.ghost = false; // false = counted only; true = render a marker for this viewer
+ this.tsServer = 0; // server epoch ms of the last heartbeat (drives the reaper)
}
}
defineTypes(IrlViewer, {
@@ -65,6 +73,12 @@ defineTypes(IrlViewer, {
lat: 'float64',
lng: 'float64',
agentId: 'string',
+ // Append-only (D2): keep new fields at the end so a still-connected older
+ // client isn't shifted off the positional binary format mid-deploy.
+ heading: 'float32',
+ avatar: 'string',
+ ghost: 'boolean',
+ tsServer: 'float64',
});
export class IrlState extends Schema {
@@ -77,7 +91,8 @@ export class IrlState extends Schema {
// 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.
+ // Live viewers present in this cell (D2), keyed by session id. Populated by
+ // IrlRoom on join/heartbeat and pruned by its reaper — see IrlViewer above.
this.viewers = new MapSchema();
}
}
diff --git a/multiplayer/src/rooms/IrlRoom.js b/multiplayer/src/rooms/IrlRoom.js
index f2c075933..08fc80bb2 100644
--- a/multiplayer/src/rooms/IrlRoom.js
+++ b/multiplayer/src/rooms/IrlRoom.js
@@ -17,14 +17,23 @@
// 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.
+// Presence (live viewers) is D2 — onJoin adds a viewer at the cell centre +
+// bounded jitter (NEVER precise GPS), heartbeats refresh it, and a reaper prunes
+// the stale ones; Colyseus delta-broadcasts the `viewers` map so every client
+// derives the "N viewing nearby" count and optional ghost markers for free.
+// 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 { IrlPin, IrlViewer, IrlState } from '../irl-schemas.js';
+import { encodeGeohash, geohashNeighbors, decodeGeohashBounds, decodeGeohash } from '../geohash.js';
import { irlRegistry } from '../irl-registry.js';
+import {
+ isReactionType,
+ reactionAllowed,
+ pruneReactionLedger,
+ REACTION_LEDGER_MAX,
+} from '../irl-reactions.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
@@ -37,6 +46,23 @@ const MAX_CLIENTS = 200; // a busy real-world spot; viewers only receiv
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']);
+// ── D2 presence tuning ───────────────────────────────────────────────────────
+const HEARTBEAT_STALE_MS = 30_000; // drop a viewer this long without a heartbeat
+const REAPER_INTERVAL_MS = 10_000; // sweep cadence (≤ stale window, so a drop lands < HEARTBEAT_STALE_MS + this)
+const MAX_VIEWERS = 200; // cap the synced presence set (matches MAX_CLIENTS)
+const GHOST_AVATAR_MAX = 1024; // clamp a shared avatar URL, same ceiling as a pin's
+// Fraction of a cell's half-extent to jitter a viewer's marker within. < 1 keeps
+// the marker inside the cell it claims, while spreading co-located viewers apart
+// so two ghosts never stack perfectly. The jitter is set once on join and never
+// moves (a heartbeat only refreshes heading/tsServer), so a ghost holds still.
+const VIEWER_JITTER_FRAC = 0.55;
+
+// Normalize an arbitrary heading input to an integer compass bearing 0–359, or 0.
+function coerceHeading(v) {
+ const n = Number(v);
+ return Number.isFinite(n) ? ((Math.round(n) % 360) + 360) % 360 : 0;
+}
+
// 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.
@@ -72,6 +98,10 @@ export class IrlRoom extends Room {
this.maxClients = MAX_CLIENTS;
this.geocell = '';
this.window = new Set(); // centre + neighbour cells this room mirrors
+ // D3 debounce ledger: `${sessionId} ${pinId}` → lastTs of the last open/view
+ // reaction, so a jittery tap can't spam every co-located phone (pay/message
+ // bypass this entirely). Pruned when it crosses REACTION_LEDGER_MAX.
+ this._reactionLedger = new Map();
}
async onCreate(options) {
@@ -83,6 +113,23 @@ export class IrlRoom extends Room {
this.setPatchRate(PATCH_RATE_MS);
this.autoDispose = true;
+ // D3 — a viewer interacted with a pin in this cell. Fan an ambient `reaction`
+ // to everyone here so the agent visibly emotes for bystanders. This is the
+ // flourish only; the durable record + owner notification ride the REST
+ // `/api/irl/interactions` path, so we never write the DB here (no double count).
+ this.onMessage('interaction', (client, payload) => this._handleInteraction(client, payload));
+
+ // D2 presence — a heartbeat refreshes liveness + facing (so a backgrounded
+ // tab that stops firing is reaped), and set_ghost flips a viewer's "appear to
+ // others" opt-in live so the marker shows/hides without a reconnect.
+ this.onMessage('heartbeat', (client, payload) => this._handleHeartbeat(client, payload));
+ this.onMessage('set_ghost', (client, payload) => this._handleSetGhost(client, payload));
+
+ // Reaper: drop viewers whose last heartbeat is stale. Covers silent
+ // disconnects and backgrounded mobile tabs that never fire onLeave. The
+ // clock is owned by the room and torn down automatically on dispose.
+ this.clock.setInterval(() => this._reapStaleViewers(), REAPER_INTERVAL_MS);
+
// The cells this room is responsible for: its centre plus the 8 neighbours.
this.window = new Set([this.geocell, ...geohashNeighbors(this.geocell)].filter(Boolean));
@@ -217,18 +264,113 @@ export class IrlRoom extends Room {
// placedAt is immutable for a given pin; never patched.
}
+ // D3 — turn a viewer's interaction into an ambient reaction for the whole cell.
+ // Validates the type, requires a pin this room actually mirrors, debounces the
+ // noisy open/view types per (session, pin), then broadcasts a privacy-clean
+ // { pinId, type, ts } to everyone in the room (the sender included, so their own
+ // tap is driven by the same authoritative event the others see). No GPS, no
+ // wallet, no actor identity ever rides this channel.
+ _handleInteraction(client, payload) {
+ const type = typeof payload?.type === 'string' ? payload.type : '';
+ if (!isReactionType(type)) return;
+ const pinId = String(payload?.pinId || '').slice(0, 64);
+ if (!pinId || !this.state.pins.has(pinId)) return; // only react for pins we hold
+
+ const now = Date.now();
+ if (this._reactionLedger.size > REACTION_LEDGER_MAX) {
+ pruneReactionLedger(this._reactionLedger, now);
+ }
+ if (!reactionAllowed(this._reactionLedger, client.sessionId, pinId, type, now)) return;
+
+ this.broadcast('reaction', { pinId, type, ts: now }, { afterNextPatch: false });
+ }
+
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.
+ // Bind the join context: the device token (D4 moderation attribution) and the
+ // agent this viewer embodies. Nothing here ever reaches the synced state.
client.userData = {
deviceToken: typeof options?.deviceToken === 'string' ? options.deviceToken.slice(0, 80) : '',
agentId: typeof options?.agent === 'string' ? options.agent.slice(0, 64) : '',
};
+
+ // D2 presence — add this viewer to the synced map so everyone in the cell
+ // gets the live count (and, if they opted in, a ghost marker). The position
+ // is the viewer's OWN precision-6 cell centre plus bounded jitter, computed
+ // here and the raw GPS immediately discarded: the only location that leaves
+ // the server is "somewhere in this ~1 km cell." Guarded by MAX_VIEWERS so a
+ // flood can't bloat the state handed to every client.
+ if (this.state.viewers.size >= MAX_VIEWERS) return;
+ const ghost = options?.ghost === true;
+ const viewer = new IrlViewer();
+ viewer.id = client.sessionId;
+ const pos = this._coarseViewerPos(Number(options?.lat), Number(options?.lng));
+ viewer.lat = pos.lat;
+ viewer.lng = pos.lng;
+ viewer.agentId = client.userData.agentId;
+ viewer.heading = coerceHeading(options?.heading);
+ viewer.ghost = ghost;
+ // A viewer only reveals an avatar when they opted into being seen.
+ viewer.avatar = ghost && typeof options?.avatar === 'string' ? options.avatar.slice(0, GHOST_AVATAR_MAX) : '';
+ viewer.tsServer = Date.now();
+ this.state.viewers.set(client.sessionId, viewer);
+ }
+
+ onLeave(client) {
+ this.state.viewers.delete(client.sessionId);
+ }
+
+ // Heartbeat: prove the viewer is still here and refresh their facing. Updating
+ // tsServer is what keeps the reaper from dropping them; heading rides along so a
+ // shared ghost can be oriented. Never touches position — the join-time jitter is
+ // the viewer's fixed coarse spot.
+ _handleHeartbeat(client, payload) {
+ const viewer = this.state.viewers.get(client.sessionId);
+ if (!viewer) return;
+ viewer.tsServer = Date.now();
+ if (payload && payload.heading !== undefined) viewer.heading = coerceHeading(payload.heading);
+ }
+
+ // Live opt-in toggle: flip whether this viewer is rendered as a ghost for others
+ // and carry the avatar to show (cleared the moment they opt out), so "Appear to
+ // others nearby" takes effect immediately without a room rejoin.
+ _handleSetGhost(client, payload) {
+ const viewer = this.state.viewers.get(client.sessionId);
+ if (!viewer) return;
+ const ghost = payload?.ghost === true;
+ viewer.ghost = ghost;
+ viewer.avatar = ghost && typeof payload?.avatar === 'string' ? payload.avatar.slice(0, GHOST_AVATAR_MAX) : '';
+ viewer.tsServer = Date.now();
+ }
+
+ // Snap a viewer's reported GPS to their own precision-6 cell centre and add
+ // bounded jitter so the stored/broadcast coordinate is coarse by construction.
+ // Falls back to this room's centre cell when the GPS is missing/invalid, so a
+ // viewer with no fix still counts (at the cell centre) rather than at (0,0).
+ _coarseViewerPos(lat, lng) {
+ let cell = this.geocell;
+ if (Number.isFinite(lat) && Number.isFinite(lng)) {
+ const own = encodeGeohash(lat, lng, 6);
+ if (GEOCELL_RE.test(own)) cell = own;
+ }
+ const c = decodeGeohash(cell || this.geocell || '');
+ const jLat = (Math.random() * 2 - 1) * c.latErr * VIEWER_JITTER_FRAC;
+ const jLng = (Math.random() * 2 - 1) * c.lngErr * VIEWER_JITTER_FRAC;
+ return { lat: c.lat + jLat, lng: c.lng + jLng };
+ }
+
+ // Drop viewers whose last heartbeat is older than the stale window. The client
+ // heartbeats every 15 s, so a live viewer never trips this; only a silent drop
+ // (closed laptop, backgrounded tab that stopped firing) does, within one sweep.
+ _reapStaleViewers() {
+ const cutoff = Date.now() - HEARTBEAT_STALE_MS;
+ for (const [id, viewer] of this.state.viewers) {
+ if (viewer.tsServer < cutoff) this.state.viewers.delete(id);
+ }
}
onDispose() {
if (this.geocell) irlRegistry.unregister(this.geocell, this);
+ this._reactionLedger.clear();
console.log(`[irl_world ${this.roomId} cell=${this.geocell || 'invalid'}] disposed`);
}
}
diff --git a/package.json b/package.json
index e7f81488c..4c3417218 100644
--- a/package.json
+++ b/package.json
@@ -71,6 +71,7 @@
"smoke:onchain:ci": "node scripts/onchain-smoke.mjs --only=parity",
"audit:mcp": "node scripts/audit-mcp-manifests.mjs",
"smoke:mcp": "node scripts/smoke-mcp-remotes.mjs",
+ "smoke:irl-d1": "node scripts/irl-d1-smoke.mjs",
"test:mcp": "node scripts/test-mcp-all.mjs",
"audit:pages": "node scripts/audit-page-index.mjs",
"audit:handlers": "node scripts/audit-empty-handlers.mjs",
diff --git a/pages/irl.html b/pages/irl.html
index 82be18ff3..69a83d96c 100644
--- a/pages/irl.html
+++ b/pages/irl.html
@@ -183,9 +183,12 @@
font-family: inherit;
cursor: pointer;
padding: 6px 14px;
- transition: border-color 0.15s, color 0.15s;
+ transition: border-color 0.15s, color 0.15s, transform 0.1s;
}
.irl-share-btn:hover { border-color: var(--text-3); color: var(--text); }
+ .irl-share-btn:active { transform: scale(0.96); }
+ .irl-share-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ .irl-share-btn[disabled] { opacity: 0.6; cursor: progress; }
/* ── Joystick ────────────────────────────────────────────── */
#irl-joystick {
@@ -391,6 +394,17 @@
background: rgba(251,191,36,0.1);
}
#irl-lock-btn.is-active:hover { background: rgba(251,191,36,0.18); }
+ /* D2 "Appear nearby" presence toggle — only relevant in GPS mode (where
+ presence is live), so it's hidden until then. Blue active state matches the
+ ghost orbs / presence chip. */
+ #irl-ghost-toggle { display: none; }
+ body.gps-mode #irl-ghost-toggle { display: inline-flex; }
+ #irl-ghost-toggle.is-active {
+ color: #8ec5ff;
+ border-color: rgba(120,170,255,0.5);
+ background: rgba(120,170,255,0.12);
+ }
+ #irl-ghost-toggle.is-active:hover { background: rgba(120,170,255,0.2); }
/* WebXR floor-anchor entry — accent it as the premium placement path */
#irl-anchor-btn {
color: #c4b5fd;
@@ -554,6 +568,13 @@
background: rgba(251,191,36,0.12);
border-color: rgba(251,191,36,0.38);
}
+ /* Designed empty invite (E4) — GPS is live but nobody's pinned here yet.
+ Muted vs. the green "N nearby" so it reads as a prompt, not an alert. */
+ #irl-nearby-badge.is-empty {
+ color: #9aa6b2;
+ background: rgba(148,163,184,0.12);
+ border-color: rgba(148,163,184,0.3);
+ }
/* Realtime status pill (D1) — sits beside the nearby badge: live (green),
connecting (amber pulse), or polling (the fallback transport, tap to retry). */
@@ -608,6 +629,43 @@
.irl-net-pill.is-connecting::before { animation: none; }
}
+ /* Live viewer presence chip (D2) — "N viewing nearby" with a softly pulsing
+ dot. Blue, to match the ghost orbs and read as social/live, distinct from
+ the green nearby-agents badge. */
+ .irl-presence-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ margin-left: 6px;
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ color: #8ec5ff;
+ background: rgba(120,170,255,0.12);
+ border: 1px solid rgba(120,170,255,0.38);
+ border-radius: 999px;
+ padding: 2px 8px 2px 7px;
+ white-space: nowrap;
+ }
+ .irl-presence-chip[hidden] { display: none; }
+ .irl-presence-chip::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: currentColor;
+ box-shadow: 0 0 6px currentColor;
+ flex-shrink: 0;
+ animation: irl-presence-pulse 1.8s ease-in-out infinite;
+ }
+ @keyframes irl-presence-pulse {
+ 0%, 100% { opacity: 1; transform: scale(1); }
+ 50% { opacity: 0.4; transform: scale(0.78); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .irl-presence-chip::before { animation: none; }
+ }
+
/* Radar minimap */
#irl-radar {
position: fixed;
@@ -636,6 +694,18 @@
cursor: pointer;
box-shadow: 0 0 6px rgba(136,187,255,0.6);
}
+ /* Live presence ghost (D2) — smaller, fainter, hollow, and not interactive,
+ so a co-viewer's approximate position never reads as a placed agent. */
+ .irl-radar-ghost {
+ position: absolute;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: rgba(159,216,255,0.22);
+ border: 1px solid rgba(159,216,255,0.6);
+ transform: translate(-50%, -50%);
+ pointer-events: none;
+ }
.irl-radar-self {
position: absolute;
top: 50%; left: 50%;
@@ -656,6 +726,24 @@
.irl-radar-s { bottom: 4px; left: 50%; transform: translateX(-50%); }
.irl-radar-e { right: 5px; top: 50%; transform: translateY(-50%); }
.irl-radar-w { left: 5px; top: 50%; transform: translateY(-50%); }
+ /* Designed empty / error hint inside the radar (E4) — centred under the self
+ dot so a broken refresh or an empty area never reads as a blank dial. */
+ .irl-radar-hint {
+ position: absolute;
+ left: 50%;
+ top: 62%;
+ transform: translateX(-50%);
+ max-width: 92px;
+ text-align: center;
+ font-size: 8.5px;
+ font-weight: 600;
+ line-height: 1.25;
+ letter-spacing: 0.02em;
+ color: rgba(255,255,255,0.5);
+ pointer-events: none;
+ }
+ .irl-radar-hint[hidden] { display: none; }
+ .irl-radar-hint.is-error { color: #fbbf24; }
/* Agent interaction bottom sheet */
#irl-sheet {
@@ -948,6 +1036,70 @@
}
.irl-agent-label-name { display: block; }
+ /* Ambient interaction reactions (D3) — a glyph rises off an agent's head when
+ a co-located viewer taps / pays / messages it. Two layers: the OUTER is
+ reprojected to the agent's screen point each frame by irl.js; the INNER runs
+ the rise+fade. Pure transform/opacity (GPU), never interactive, auto-removed. */
+ .irl-reaction {
+ position: fixed;
+ transform: translate(-50%, -100%);
+ pointer-events: none;
+ z-index: 8; /* just above name labels (7), below the inspect sheet (19) */
+ will-change: transform;
+ }
+ .irl-reaction-burst {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 9px;
+ border-radius: 999px;
+ font-size: 13px;
+ font-weight: 700;
+ line-height: 1;
+ white-space: nowrap;
+ color: #f5d0fe;
+ background: rgba(139,92,246,0.28);
+ border: 1px solid rgba(167,139,250,0.55);
+ box-shadow: 0 0 14px rgba(139,92,246,0.4);
+ backdrop-filter: blur(6px);
+ -webkit-backdrop-filter: blur(6px);
+ will-change: transform, opacity;
+ animation: irl-reaction-rise 1.2s cubic-bezier(0.22, 1, 0.36, 1) forwards;
+ }
+ .irl-reaction-burst.is-pay {
+ color: #fde68a;
+ background: rgba(251,191,36,0.26);
+ border-color: rgba(251,191,36,0.62);
+ box-shadow: 0 0 16px rgba(251,191,36,0.5);
+ }
+ .irl-reaction-burst.is-msg {
+ color: #a5f3fc;
+ background: rgba(34,211,238,0.22);
+ border-color: rgba(34,211,238,0.55);
+ box-shadow: 0 0 14px rgba(34,211,238,0.4);
+ }
+ .irl-reaction-mark { font-size: 15px; }
+ .irl-reaction-text { letter-spacing: 0.02em; }
+ @keyframes irl-reaction-rise {
+ 0% { opacity: 0; transform: translateY(8px) scale(0.6); }
+ 16% { opacity: 1; transform: translateY(0) scale(1.12); }
+ 32% { opacity: 1; transform: translateY(-6px) scale(1); }
+ 100% { opacity: 0; transform: translateY(-44px) scale(0.96); }
+ }
+ /* Reduced motion: keep the acknowledgement, drop the travel — a gentle fade in
+ place so the flourish never becomes vestibular motion. */
+ @media (prefers-reduced-motion: reduce) {
+ .irl-reaction-burst {
+ animation: irl-reaction-fade 1.2s ease-out forwards;
+ }
+ @keyframes irl-reaction-fade {
+ 0% { opacity: 0; transform: scale(0.9); }
+ 16% { opacity: 1; transform: scale(1); }
+ 70% { opacity: 1; transform: scale(1); }
+ 100% { opacity: 0; transform: scale(1); }
+ }
+ }
+
/* ── Inspect card v2 ── */
/* Backdrop — dims the AR view behind the card so it reads as a focused dialog */
#irl-sheet-backdrop {
@@ -1122,6 +1274,17 @@
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: none; }
}
+ /* Wallet-needed notice (E4) — a designed, persistent state-kit card shown when
+ a Pay/Use tap has no connected wallet. Sits below the services it gates. */
+ .irl-pay-notice {
+ margin-top: 12px;
+ padding-top: 6px;
+ border-top: 1px solid rgba(255,255,255,0.08);
+ animation: irl-result-in 0.25s ease;
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .irl-pay-notice { animation: none; }
+ }
/* Multiplayer indicator row */
.irl-multiplayer-note {
display: flex;
@@ -1361,6 +1524,9 @@
</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>
+ <!-- D2 live viewer presence — "N viewing nearby" with a pulsing dot. Hidden
+ unless the live stream is up and more than just you are here. -->
+ <span id="irl-presence-chip" class="irl-presence-chip" 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>
@@ -1423,6 +1589,12 @@
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>
My pins
</button>
+ <!-- D2 — opt in to appearing as a ghost to other live viewers (default off).
+ Only shown in GPS mode, where presence is live. -->
+ <button class="irl-pill-btn" id="irl-ghost-toggle" type="button" aria-pressed="false" aria-label="Appear to others viewing nearby">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7z"/><circle cx="12" cy="12" r="3"/></svg>
+ Appear nearby
+ </button>
</div>
<!-- Object picker (revealed when Add Object is active) -->
diff --git a/pages/xr.html b/pages/xr.html
index 899233bc3..2e934e404 100644
--- a/pages/xr.html
+++ b/pages/xr.html
@@ -141,10 +141,13 @@
background: rgba(255,255,255,0.05);
color: var(--text-2); font: inherit; font-size: 12px; font-weight: 600;
cursor: pointer; backdrop-filter: blur(12px);
- transition: background 0.15s, color 0.15s, border-color 0.15s;
+ transition: background 0.15s, color 0.15s, border-color 0.15s, transform 0.1s;
flex-shrink: 0;
}
#xr-share-btn:hover { color: var(--text); border-color: rgba(255,255,255,0.18); background: rgba(255,255,255,0.1); }
+ #xr-share-btn:active { transform: scale(0.96); }
+ #xr-share-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ #xr-share-btn[disabled] { opacity: 0.6; cursor: progress; }
/* ── Loading overlay ── */
#xr-loading {
diff --git a/public/changelog.json b/public/changelog.json
index f2bfc0d4a..f3f04f29d 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T03:09:30.587Z",
+ "generated_at": "2026-06-17T04:11:05.851Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -58,6 +58,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "IRL agents now visibly react when someone engages them",
+ "summary": "Walk past an agent placed in the real world and it now feels alive: the moment anyone standing nearby taps it, leaves it a message, or pays it, the agent does a little perk-up and a reaction floats up off its head — a 💜 for a glance, a ✨ 'paid' burst for a real on-chain payment, a 💬 for a message — and everyone viewing that spot sees it at once, not just the person who acted. A busy agent looks busy, which is the whole point of putting one somewhere public. Rapid taps are smoothed so the same person can't spam the reaction, while payments and messages always come through. The reaction is purely a visual flourish — it carries no one's location or wallet — and if your connection drops to the slower fallback the interaction is still recorded for the owner; only the live animation is skipped.",
+ "link": "/irl",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
@@ -68,6 +78,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "IRL never shows a blank screen — every state is now designed",
+ "summary": "Every corner of three.ws/irl now tells you what's going on instead of leaving a blank space. The radar minimap reads 'No agents in range' when an area is quiet, and 'Can't refresh' if the nearby feed briefly drops — then recovers on its own. The nearby count, when GPS is live but nobody's pinned around you yet, invites you to be the first to drop an agent there rather than simply disappearing. Tap an agent's Pay or Use button without a wallet connected and you now get a clear, lasting card explaining how to connect one — instead of a message that flashes away before you can read it. And your IRL Placements dashboard now has a proper loading skeleton, a friendly empty state when you haven't placed anything, and a retry button if the list can't load — never a spinner that hangs or a void.",
+ "link": "/irl",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
@@ -163,6 +183,28 @@
"feature"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "Report a bad IRL pin — and guardrails that keep public spots usable",
+ "summary": "Now that anyone standing at a location sees the agents others placed there, three.ws/irl has the moderation it needs to stay clean. Tap any agent that isn't yours and a new Report option lets you flag it for spam, hate or harassment, impersonation, a scam, sexual content, or anything else — with a clear sending, thanks, and try-again state, never a dead button. Reports are counted per person, so one account can't bury a pin it dislikes; once enough different people flag the same agent it's hidden from everyone — and if you're nearby when that happens it vanishes from your view within about a second rather than lingering until the next scan. Placing agents is now protected too: captions and names with slurs are refused, a pin can only ever reference $THREE, the only coin on three.ws, and its pay button can only point at three.ws — never an outside link. A single busy block holds a sensible maximum of agents and each person has an active-pin limit, so no one can carpet-bomb a plaza or spam placements, and every refusal tells you exactly what to do. Abandoned anonymous pins are cleaned up automatically while the agents you're signed in for stay put.",
+ "link": "/irl",
+ "tags": [
+ "feature",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "See a placed agent's on-chain reputation from your dashboard",
+ "summary": "Your IRL Placements dashboard now shows each placed agent's on-chain reputation — the exact score and trust tier a passer-by sees when they tap it in the real world, so you know what the public sees. Tap an agent's Reputation chip to open a panel with its 0–100 score and tier (New, Emerging, Trusted, Elite), a star rating, and a breakdown of how many attestations are verified, credentialed, or disputed. A small 30-day trend line shows whether its reputation is climbing. Agents that haven't earned any attestations yet get a clear prompt to share them rather than an empty number, and a 'Manage on passport' link takes you to where you add or dispute attestations. If the reputation service is unreachable the panel offers a retry instead of failing silently.",
+ "link": "/dashboard/irl-placements",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
@@ -173,6 +215,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "Share a photo straight from the XR viewer",
+ "summary": "three.ws/xr now has the same one-tap Share that three.ws/irl has had: it flattens your live camera view and the 3D agent into a single photo and hands it to your phone's share sheet to post or send — or downloads it as a PNG on desktop. With the camera on, the picture shows your agent standing in your real surroundings; with it off, it shares the 3D view on its own. If a snapshot can't be captured for any reason, Share falls back to sending the page link so it's never a dead end. The Share buttons on both pages now show a brief progress state while the image is being made, and the immersive buttons give keyboard users a clear focus outline.",
+ "link": "/xr",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 2f106e2b1..c9581ea93 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -46,6 +46,14 @@
<category>fix</category>
<description>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.</description>
</item>
+ <item>
+ <title>IRL agents now visibly react when someone engages them</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-17:IRL agents now visibly react when someone engages them</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Walk past an agent placed in the real world and it now feels alive: the moment anyone standing nearby taps it, leaves it a message, or pays it, the agent does a little perk-up and a reaction floats up off its head — a 💜 for a glance, a ✨ 'paid' burst for a real on-chain payment, a 💬 for a message — and everyone viewing that spot sees it at once, not just the person who acted. A busy agent looks busy, which is the whole point of putting one somewhere public. Rapid taps are smoothed so the same person can't spam the reaction, while payments and messages always come through. The reaction is purely a visual flourish — it carries no one's location or wallet — and if your connection drops to the slower fallback the interaction is still recorded for the owner; only the live animation is skipped.</description>
+ </item>
<item>
<title>IRL agents turn to look at you as you move around them</title>
<link>https://three.ws/irl</link>
@@ -54,6 +62,14 @@
<category>improvement</category>
<description>On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you.</description>
</item>
+ <item>
+ <title>IRL never shows a blank screen — every state is now designed</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-17:IRL never shows a blank screen — every state is now designed</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Every corner of three.ws/irl now tells you what's going on instead of leaving a blank space. The radar minimap reads 'No agents in range' when an area is quiet, and 'Can't refresh' if the nearby feed briefly drops — then recovers on its own. The nearby count, when GPS is live but nobody's pinned around you yet, invites you to be the first to drop an agent there rather than simply disappearing. Tap an agent's Pay or Use button without a wallet connected and you now get a clear, lasting card explaining how to connect one — instead of a message that flashes away before you can read it. And your IRL Placements dashboard now has a proper loading skeleton, a friendly empty state when you haven't placed anything, and a retry button if the list can't load — never a spinner that hangs or a void.</description>
+ </item>
<item>
<title>IRL now fails gracefully — clear states instead of blank screens</title>
<link>https://three.ws/irl</link>
@@ -126,6 +142,22 @@
<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>Report a bad IRL pin — and guardrails that keep public spots usable</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-17:Report a bad IRL pin — and guardrails that keep public spots usable</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Now that anyone standing at a location sees the agents others placed there, three.ws/irl has the moderation it needs to stay clean. Tap any agent that isn't yours and a new Report option lets you flag it for spam, hate or harassment, impersonation, a scam, sexual content, or anything else — with a clear sending, thanks, and try-again state, never a dead button. Reports are counted per person, so one account can't bury a pin it dislikes; once enough different people flag the same agent it's hidden from everyone — and if you're nearby when that happens it vanishes from your view within about a second rather than lingering until the next scan. Placing agents is now protected too: captions and names with slurs are refused, a pin can only ever reference $THREE, the only coin on three.ws, and its pay button can only point at three.ws — never an outside link. A single busy block holds a sensible maximum of agents and each person has an active-pin limit, so no one can carpet-bomb a plaza or spam placements, and every refusal tells you exactly what to do. Abandoned anonymous pins are cleaned up automatically while the agents you're signed in for stay put.</description>
+ </item>
+ <item>
+ <title>See a placed agent's on-chain reputation from your dashboard</title>
+ <link>https://three.ws/dashboard/irl-placements</link>
+ <guid isPermaLink="false">2026-06-17:See a placed agent's on-chain reputation from your dashboard</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your IRL Placements dashboard now shows each placed agent's on-chain reputation — the exact score and trust tier a passer-by sees when they tap it in the real world, so you know what the public sees. Tap an agent's Reputation chip to open a panel with its 0–100 score and tier (New, Emerging, Trusted, Elite), a star rating, and a breakdown of how many attestations are verified, credentialed, or disputed. A small 30-day trend line shows whether its reputation is climbing. Agents that haven't earned any attestations yet get a clear prompt to share them rather than an empty number, and a 'Manage on passport' link takes you to where you add or dispute attestations. If the reputation service is unreachable the panel offers a retry instead of failing silently.</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>
@@ -134,6 +166,14 @@
<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>Share a photo straight from the XR viewer</title>
+ <link>https://three.ws/xr</link>
+ <guid isPermaLink="false">2026-06-17:Share a photo straight from the XR viewer</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>three.ws/xr now has the same one-tap Share that three.ws/irl has had: it flattens your live camera view and the 3D agent into a single photo and hands it to your phone's share sheet to post or send — or downloads it as a PNG on desktop. With the camera on, the picture shows your agent standing in your real surroundings; with it off, it shares the 3D view on its own. If a snapshot can't be captured for any reason, Share falls back to sending the page link so it's never a dead end. The Share buttons on both pages now show a brief progress state while the image is being made, and the immersive buttons give keyboard users a clear focus outline.</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>
diff --git a/public/features.json b/public/features.json
index 46632032c..31074316c 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T03:09:30.575Z",
+ "generated_at": "2026-06-17T04:11:05.838Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/irl-d1-smoke.mjs b/scripts/irl-d1-smoke.mjs
new file mode 100644
index 000000000..6be9960ce
--- /dev/null
+++ b/scripts/irl-d1-smoke.mjs
@@ -0,0 +1,206 @@
+// Live round-trip smoke for D1 — IRL realtime pin sync.
+//
+// node scripts/irl-d1-smoke.mjs
+//
+// Where irl-d3-smoke unit-tests the privacy filter, this one proves the actual
+// liveness contract end-to-end: it boots the REAL multiplayer server (the same
+// multiplayer/src/index.js prod runs, with the irl_world room + signed
+// /internal/irl-publish webhook wired exactly as deployed), connects two
+// colyseus.js clients to one geocell room, fires a signed publish, and asserts
+// the change lands on the other client within the ~1 s liveness budget.
+//
+// It mechanises the spec's manual "two phones at the same spot" checklist:
+// 1. A places a pin → it appears on B within ~1 s (schema delta). [add]
+// 2. A removes a pin → it disappears on B live. [remove]
+// 3. A late joiner is handed the full current pin set on join (schema sync). [late join]
+// 4. A forged / tampered / stale publish is rejected (401) and never reaches [auth]
+// the room — the channel can't be poisoned by an unsigned request.
+//
+// The server's pin hydration is pointed at a dead API base so onCreate loads an
+// empty cell deterministically (it degrades gracefully on load failure), and the
+// shared secret is fixed — so the run needs no DB, no env, and no network.
+// Assertions throw on failure; a clean run prints "D1 SMOKE: PASS".
+
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+import { Client, getStateCallbacks } from 'colyseus.js';
+import { IrlState } from '../multiplayer/src/irl-schemas.js';
+import { encodeGeohash } from '../multiplayer/src/geohash.js';
+import { hmacSha256, sha256Base64Url } from '../api/_lib/crypto.js';
+
+const ROOT = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..');
+const PORT = 2599;
+const HOST = '127.0.0.1';
+const BASE_HTTP = `http://${HOST}:${PORT}`;
+const BASE_WS = `ws://${HOST}:${PORT}`;
+const SECRET = 'd1-smoke-secret';
+const LIVENESS_MS = 1500; // the spec's "~1 s" plus headroom for CI scheduling jitter
+
+// A real coordinate (downtown SF) and the precision-6 cell it lands in — the
+// client's room key and the publish's geocell must agree, so we derive both from
+// the same encoder the app uses.
+const LAT = 37.7749;
+const LNG = -122.4194;
+const GEOCELL = encodeGeohash(LAT, LNG, 6);
+
+let failures = 0;
+function check(name, cond) {
+ if (cond) console.log(` ✓ ${name}`);
+ else { console.error(` ✗ ${name}`); failures++; }
+}
+
+// ── Boot the real multiplayer server ─────────────────────────────────────────
+function startServer() {
+ const child = spawn(process.execPath, ['multiplayer/src/index.js'], {
+ cwd: ROOT,
+ env: {
+ ...process.env,
+ PORT: String(PORT),
+ HOST,
+ NODE_ENV: 'development', // allows origin-less node-client upgrades
+ MULTIPLAYER_SHARED_SECRET: SECRET,
+ HOLDER_PASS_SECRET: SECRET,
+ // Dead API base → onCreate's pin hydration fails fast and the room starts
+ // empty, so the test set is exactly what THIS run publishes (deterministic).
+ WORLD_API_BASE: 'http://127.0.0.1:9',
+ REDIS_URI: '',
+ REDIS_URL: '',
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const ready = new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('server did not start within 15s')), 15000);
+ child.stdout.on('data', (b) => {
+ if (String(b).includes('listening on ws://')) { clearTimeout(timer); resolve(); }
+ });
+ child.stderr.on('data', (b) => {
+ const s = String(b);
+ // Surface real boot failures; the dead-API pin-load warning is expected noise.
+ if (/FATAL|Error:|failed to start/.test(s) && !/pin load failed/.test(s)) {
+ process.stderr.write(`[server] ${s}`);
+ }
+ });
+ child.on('exit', (code) => { if (code) reject(new Error(`server exited early (${code})`)); });
+ });
+ return { child, ready };
+}
+
+// ── A signed publish, mirroring api/_lib/irl-publish.js byte-for-byte ─────────
+async function publish(type, pin, { secret = SECRET, ts = Math.floor(Date.now() / 1000) } = {}) {
+ const pinHash = await sha256Base64Url(JSON.stringify(pin ?? {}));
+ const sig = await hmacSha256(secret, `irl:${GEOCELL}:${type}:${ts}:${pinHash}`);
+ const res = await fetch(`${BASE_HTTP}/internal/irl-publish`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-mp-signature': sig, 'x-mp-timestamp': String(ts) },
+ body: JSON.stringify({ geocell: GEOCELL, type, pin }),
+ });
+ const body = await res.json().catch(() => ({}));
+ return { status: res.status, body };
+}
+
+// Connect a client and expose the live pins map + a waiter for a specific pin id.
+async function connectClient(label) {
+ const client = new Client(BASE_WS);
+ const room = await client.joinOrCreate('irl_world', { geocell: GEOCELL, deviceToken: label, lat: LAT, lng: LNG }, IrlState);
+ const present = new Set();
+ const addWaiters = new Map(); // id → resolve
+ const removeWaiters = new Map();
+ const $ = getStateCallbacks(room);
+ $(room.state).pins.onAdd((pin, id) => {
+ present.add(id);
+ addWaiters.get(id)?.(pin); addWaiters.delete(id);
+ });
+ $(room.state).pins.onRemove((pin, id) => {
+ present.delete(id);
+ removeWaiters.get(id)?.(); removeWaiters.delete(id);
+ });
+ const waitFor = (map) => (id, ms) => new Promise((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error(`${label}: timeout waiting on ${id} (${ms}ms)`)), ms);
+ map.set(id, (v) => { clearTimeout(t); resolve(v); });
+ });
+ return {
+ room,
+ present,
+ has: (id) => present.has(id),
+ waitAdd: (id, ms) => (present.has(id) ? Promise.resolve(room.state.pins.get(id)) : waitFor(addWaiters)(id, ms)),
+ waitRemove: (id, ms) => (!present.has(id) ? Promise.resolve() : waitFor(removeWaiters)(id, ms)),
+ leave: () => room.leave().catch(() => {}),
+ };
+}
+
+async function main() {
+ const { child, ready } = startServer();
+ let A, B, C;
+ try {
+ await ready;
+ console.log(`server up on ${BASE_WS} — cell ${GEOCELL}\n`);
+
+ console.log('1) two viewers in one cell — a placed pin lands live on the other');
+ A = await connectClient('A');
+ B = await connectClient('B');
+ check('both clients joined the same room instance', A.room.roomId === B.room.roomId);
+
+ const pin = {
+ id: 'smoke-pin-1', lat: LAT, lng: LNG, heading: 90,
+ avatarUrl: 'https://three.ws/cdn/default.glb', avatarName: 'Greeter',
+ caption: 'gm', agentId: 'agent-xyz', placedAt: Date.now(),
+ };
+ const t0 = Date.now();
+ const pub = await publish('pin:add', pin);
+ check('publish accepted (signed)', pub.status === 200);
+ check('publish dispatched to ≥1 live room', Number(pub.body?.delivered) >= 1);
+
+ const landed = await B.waitAdd(pin.id, LIVENESS_MS);
+ const elapsed = Date.now() - t0;
+ check(`B received the pin within ${LIVENESS_MS}ms (took ${elapsed}ms)`, elapsed <= LIVENESS_MS);
+ check('B sees the full pin payload (caption + avatar + heading)',
+ landed?.caption === 'gm' && landed?.avatarUrl === pin.avatarUrl && Math.round(landed?.heading) === 90);
+
+ console.log('\n2) a late joiner is handed the full current set on join (schema sync)');
+ C = await connectClient('C');
+ // The pin was placed before C joined; Colyseus hands the full state on join,
+ // applied in the room-state message that lands just after joinOrCreate resolves.
+ // So we await the sync (resolves instantly if already present) rather than race it.
+ await C.waitAdd(pin.id, LIVENESS_MS);
+ check('C is handed the pin placed before it joined (join-time state sync)', C.has(pin.id));
+ check('C and B/A share the same room instance', C.room.roomId === A.room.roomId);
+
+ console.log('\n3) a removal disappears on the other viewers live');
+ const tR = Date.now();
+ const rem = await publish('pin:remove', { id: pin.id });
+ check('remove publish accepted', rem.status === 200);
+ await Promise.all([B.waitRemove(pin.id, LIVENESS_MS), C.waitRemove(pin.id, LIVENESS_MS)]);
+ check(`B & C saw the removal within ${LIVENESS_MS}ms (took ${Date.now() - tR}ms)`, !B.has(pin.id) && !C.has(pin.id));
+
+ console.log('\n4) the channel rejects forged / tampered / stale publishes');
+ const unsigned = await fetch(`${BASE_HTTP}/internal/irl-publish`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ geocell: GEOCELL, type: 'pin:add', pin: { id: 'forged' } }),
+ });
+ check('unsigned publish → 401', unsigned.status === 401);
+
+ const wrongSecret = await publish('pin:add', { id: 'forged-2', lat: LAT, lng: LNG }, { secret: 'not-the-secret' });
+ check('wrong-secret publish → 401', wrongSecret.status === 401);
+
+ const stale = await publish('pin:add', { id: 'forged-3', lat: LAT, lng: LNG }, { ts: Math.floor(Date.now() / 1000) - 600 });
+ check('stale-timestamp publish → 401', stale.status === 401);
+
+ check('no forged pin reached the room', !B.has('forged') && !B.has('forged-2') && !B.has('forged-3'));
+ } finally {
+ await Promise.allSettled([A?.leave(), B?.leave(), C?.leave()]);
+ child.kill('SIGTERM');
+ }
+
+ if (failures) {
+ console.error(`\nD1 SMOKE: FAIL (${failures} check${failures === 1 ? '' : 's'})`);
+ process.exit(1);
+ }
+ console.log('\nD1 SMOKE: PASS');
+}
+
+main().catch((err) => {
+ console.error('\nD1 SMOKE: ERROR —', err?.message || err);
+ process.exit(1);
+});
diff --git a/src/agent-detail.css b/src/agent-detail.css
index 27172bf18..ac33d5e59 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -153,10 +153,19 @@ a {
cursor: pointer;
display: inline-flex;
align-items: center;
+ transition: border-color 0.15s, transform 0.1s;
}
.ad-btn:hover {
border-color: var(--ad-line-2);
}
+.ad-btn:active {
+ border-color: var(--ad-line-2);
+ transform: translateY(1px);
+}
+.ad-btn:focus-visible {
+ outline: 2px solid var(--ad-cyan);
+ outline-offset: 2px;
+}
.ad-btn-primary {
background: #fff;
color: #000;
diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.js
index a76a6449b..62d396087 100644
--- a/src/dashboard-next/pages/irl-placements.js
+++ b/src/dashboard-next/pages/irl-placements.js
@@ -24,7 +24,8 @@
import { mountShell } from '../shell.js';
import { requireUser, get, post, patch, esc, relTime } from '../api.js';
-import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry } from '../../shared/state-kit.js';
+import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
+import { loadInto } from '../../shared/async-state.js';
import { mountReputationPanel } from './irl-reputation.js';
// ── Services / x402 skill pricing ───────────────────────────────────────────
@@ -564,28 +565,37 @@ async function mount(el) {
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;
- try {
- const [sumData, ixData] = await Promise.all([
- get('/api/irl/agent-summary?mine=1'),
- get('/api/irl/interactions?mine=1').catch(() => ({ interactions: [], unread: 0 })),
- ]);
- // agent-summary keys each row by pin_id and adds derived monitoring signals
- // (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 }));
- 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));
- return;
- }
+ // One network boundary for the four designed states: loading skeleton → list /
+ // empty / error+retry. The retry button re-runs this same load. Signed-out is
+ // handled earlier by requireUser()'s redirect to /login, so it never reaches here.
+ await loadInto(list, {
+ load: async () => {
+ // Pins + interactions in parallel — interactions power both the banner and
+ // each card's IRL feed.
+ const [sumData, ixData] = await Promise.all([
+ get('/api/irl/agent-summary?mine=1'),
+ get('/api/irl/interactions?mine=1').catch(() => ({ interactions: [], unread: 0 })),
+ ]);
+ inbox.interactions = ixData.interactions || [];
+ inbox.unread = ixData.unread || 0;
+ // agent-summary keys each row by pin_id and adds derived monitoring signals
+ // (status, interaction_count, last_interaction_at). Normalize pin_id→id so
+ // the existing card code is unchanged.
+ return (sumData.agents || []).map((a) => ({ ...a, id: a.pin_id }));
+ },
+ render: (pins, listC) => renderPlacements(pins, listC, el),
+ skeleton: { count: 3, variant: 'row' },
+ error: { title: "Couldn't load your IRL agents", body: 'Check your connection and try again.' },
+ errorScope: 'irl',
+ context: 'dashboard:irl-placements',
+ });
+}
+// Paint the populated placements — or the designed empty state — then wire the
+// live layers. Routed through loadInto's render hook (no `empty` config), so the
+// zero-pins CTA rides the same path as the populated list.
+function renderPlacements(pins, list, el) {
if (!pins.length) {
list.innerHTML = emptyStateHTML({
icon: '📍',
@@ -598,11 +608,18 @@ async function mount(el) {
}
renderBanner();
-
list.innerHTML = pins.map((p) => cardHtml(p, inbox.interactions)).join('');
applyBadges();
+ enrichCards(pins, list);
+ wireCardEvents(list, pins);
+ startPolling();
+ startLiveStream(); // D3 — upgrade the poll to instant realtime delivery
+}
- // ── Async enrichment per card: balance, reputation, services, geocode ──────
+// ── Async enrichment per card: balance, reputation, services, skills, geocode ──
+// Each call is best-effort and fills its skeleton chip on resolve (or an honest
+// "—" / "Unavailable" on failure) so a slow upstream never leaves a card blank.
+function enrichCards(pins, list) {
for (const pin of pins) {
const card = list.querySelector(`[data-id="${pin.id}"]`);
if (!card) continue;
@@ -658,10 +675,6 @@ async function mount(el) {
})
.catch(() => fillStatError(card, 'balance'));
}
-
- wireCardEvents(list, pins);
- startPolling();
- startLiveStream(); // D3 — upgrade the poll to instant realtime delivery
}
// ── Live header badge, per-card chips, and the "new interactions" banner ─────
diff --git a/src/dashboard-next/pages/irl-reputation.js b/src/dashboard-next/pages/irl-reputation.js
index 98a11acc8..77f8f1d6e 100644
--- a/src/dashboard-next/pages/irl-reputation.js
+++ b/src/dashboard-next/pages/irl-reputation.js
@@ -132,6 +132,7 @@ export function mountReputationPanel(card, { reputation, agentId, pinId } = {})
}
body.innerHTML = panelHtml(reputation, fb);
+ loadTrend(body, asset, network, reputation);
} catch {
body.innerHTML = errorStateHTML({
title: 'Couldn’t load reputation',
@@ -173,7 +174,51 @@ function panelHtml(rep, fb) {
<span class="irl-rep-chip ${disputed ? 'bad' : ''}">${disputed} disputed</span>
</div>
</div>
- </div>`;
+ </div>
+ <div class="irl-rep-trend" data-rep-trend hidden></div>`;
+}
+
+// History sparkline — optional, loaded after the panel paints. Stays silent on
+// any failure (incl. 404 / sparse data): the trend is a bonus, never a blocker,
+// so it must not surface an error or shift layout when there's nothing to draw.
+async function loadTrend(body, asset, network, rep) {
+ const slot = body?.querySelector('[data-rep-trend]');
+ if (!slot) return;
+ try {
+ const r = await fetch(
+ `/api/agents/solana-reputation-history?asset=${encodeURIComponent(asset)}&network=${encodeURIComponent(network)}&days=30`,
+ );
+ if (!r.ok) return;
+ const { series } = await r.json();
+ if (!Array.isArray(series) || series.length < 2) return; // need ≥2 points to draw a line
+ slot.innerHTML = sparklineHtml(series, tierMeta(rep?.tier || 'new').color);
+ slot.hidden = false;
+ } catch { /* trend is optional — never surface an error */ }
+}
+
+// Tiny inline-SVG sparkline of the daily reputation score (1–5 band) over the
+// trailing window. Stretches to the card width (preserveAspectRatio none) with a
+// non-scaling stroke so the line stays crisp; a faint area fill reads as trend at
+// a glance. A flat series renders as a centered line rather than a floor-hugging one.
+function sparklineHtml(series, color) {
+ const W = 220, H = 34, pad = 4;
+ const scores = series.map((p) => Number(p.score) || 0);
+ const n = scores.length;
+ const min = Math.min(...scores), max = Math.max(...scores);
+ const flat = max === min;
+ const px = (i) => +((i / (n - 1)) * (W - pad * 2) + pad).toFixed(1);
+ const py = (s) => flat ? H / 2 : +(H - pad - ((s - min) / (max - min)) * (H - pad * 2)).toFixed(1);
+ const line = scores.map((s, i) => `${px(i)},${py(s)}`).join(' ');
+ const area = `${pad},${H} ${line} ${W - pad},${H}`;
+ const first = scores[0], last = scores[n - 1];
+ const trend = last > first ? 'trending up' : last < first ? 'trending down' : 'steady';
+ const label = `Reputation trend over the last ${n} days: ${trend}; latest score ${last.toFixed(1)} of 5`;
+ return `<svg class="irl-rep-spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none"
+ role="img" aria-label="${label}" style="--spark:${color}">
+ <polygon class="irl-rep-spark-area" points="${area}" />
+ <polyline class="irl-rep-spark-line" points="${line}" />
+ </svg>
+ <span class="irl-rep-spark-cap">${n}-day trend · latest ★ ${last.toFixed(1)}</span>`;
}
const REP_CSS = `
@@ -209,6 +254,11 @@ const REP_CSS = `
.irl-rep-chip.ok { color: var(--nxt-success, #4ade80); border-color: color-mix(in srgb, var(--nxt-success, #4ade80) 30%, transparent); }
.irl-rep-chip.cred { color: #a78bfa; border-color: color-mix(in srgb, #a78bfa 30%, transparent); }
.irl-rep-chip.bad { color: var(--nxt-danger, #f87171); border-color: color-mix(in srgb, var(--nxt-danger, #f87171) 30%, transparent); }
+.irl-rep-trend { margin-top: 12px; display: flex; flex-direction: column; gap: 3px; animation: irl-rep-in .2s ease both; }
+.irl-rep-spark { width: 100%; height: 34px; display: block; overflow: visible; }
+.irl-rep-spark-line { fill: none; stroke: var(--spark, var(--nxt-accent, #4ea1ff)); stroke-width: 1.6; vector-effect: non-scaling-stroke; stroke-linejoin: round; stroke-linecap: round; }
+.irl-rep-spark-area { fill: var(--spark, var(--nxt-accent, #4ea1ff)); opacity: .1; }
+.irl-rep-spark-cap { font-size: 10px; text-transform: uppercase; letter-spacing: .04em; color: var(--nxt-ink-faint, #8a8f98); }
.irl-stat--btn { cursor: pointer; transition: border-color .12s, background .12s; }
.irl-stat--btn:hover { border-color: var(--nxt-stroke-strong, rgba(255,255,255,.25)); }
.irl-stat--btn:focus-visible { outline: 2px solid var(--nxt-accent, #4ea1ff); outline-offset: 2px; }
diff --git a/src/irl-net.js b/src/irl-net.js
index e45115e76..d992eace3 100644
--- a/src/irl-net.js
+++ b/src/irl-net.js
@@ -69,6 +69,8 @@ export class IrlNet {
* @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 {boolean} [opts.ghost] D2 — broadcast self as a ghost marker (opt-in; default off)
+ * @param {string} [opts.avatar] D2 — GLB url to show as this viewer's ghost (only when ghost)
* @param {string} [opts.url] override server URL (otherwise resolved from meta)
*/
constructor(opts = {}) {
@@ -76,6 +78,10 @@ export class IrlNet {
this.lng = Number(opts.lng);
this.deviceToken = opts.deviceToken || '';
this.agent = opts.agent || '';
+ // D2 presence opt-in — "appear to others nearby". Default off: a viewer is
+ // always counted, but only broadcasts a positioned ghost when they opt in.
+ this.ghost = opts.ghost === true;
+ this.avatar = opts.avatar || '';
this.url = opts.url || defaultServerUrl();
this.geocell = encodeGeohash(this.lat, this.lng, GEOCELL_PRECISION);
@@ -89,11 +95,13 @@ export class IrlNet {
'pin:update': new Set(),
'pin:remove': new Set(),
presence: new Set(), // D2 — declared now so the event API is stable
+ reaction: new Set(), // D3 — ambient interaction reactions from the room
};
this._retries = 0;
this._reconnectTimer = null;
this._destroyed = false;
this._connectGen = 0;
+ this._presenceQueued = false; // coalesces a join-time burst of viewer deltas
}
on(event, fn) {
@@ -168,6 +176,10 @@ export class IrlNet {
agent: this.agent,
lat: this.lat,
lng: this.lng,
+ // D2 — opt-in to being seen. The server snaps lat/lng to the cell centre
+ // (coarse) regardless; ghost/avatar only ride when the viewer opted in.
+ ghost: this.ghost,
+ avatar: this.ghost ? this.avatar : '',
}, IrlState);
if (this._destroyed || gen !== this._connectGen) {
try { room.leave(); } catch {}
@@ -189,6 +201,25 @@ export class IrlNet {
});
}
+ // D2 presence — the room's `viewers` MapSchema is the live crowd. Any
+ // add / remove / per-viewer change re-derives the { count, viewers } the
+ // HUD chip + ghost markers read. The join handshake fires onAdd once per
+ // existing viewer, so we coalesce the burst into a single emit next tick.
+ const $viewers = $(this.room.state)?.viewers;
+ if ($viewers) {
+ $viewers.onAdd((viewer) => {
+ $(viewer).onChange(() => this._queuePresence());
+ this._queuePresence();
+ });
+ $viewers.onRemove(() => this._queuePresence());
+ }
+
+ // D3 ambient reactions — the room broadcasts `reaction` to everyone in the
+ // geocell when a co-located viewer taps / pays / messages a pin here. It's a
+ // transient flourish (not schema state), so it rides a plain message, not a
+ // MapSchema. Payload is privacy-stripped server-side to { pinId, type, ts }.
+ this.room.onMessage('reaction', (msg) => this._emit('reaction', msg));
+
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.
@@ -240,6 +271,104 @@ export class IrlNet {
await this.connect(); // leave the old room, join the new one
}
+ /**
+ * D3 — tell the room a viewer interacted with a pin, so it can fan an ambient
+ * reaction (agent emote + floating 💜/✨) to everyone else viewing this geocell.
+ * This is the *flourish* channel only: the durable record + owner notification
+ * already flow over the REST `/api/irl/interactions` path, so this is fire-and-
+ * forget and a no-op whenever the WS isn't live (poll fallback) — the record is
+ * never lost, only the live flourish is skipped.
+ * @param {{type:'open'|'view'|'pay'|'message', pinId:string, agentId?:string}} payload
+ * @returns {boolean} whether the emit was actually sent over a live socket
+ */
+ interaction(payload) {
+ if (this.status !== 'online' || !this.room) return false;
+ const type = payload?.type;
+ const pinId = payload?.pinId;
+ if (!type || !pinId) return false;
+ try {
+ this.room.send('interaction', {
+ type: String(type),
+ pinId: String(pinId),
+ agentId: payload.agentId ? String(payload.agentId) : '',
+ });
+ return true;
+ } catch (e) {
+ log.warn('[irl-net] interaction send failed:', e?.message || e);
+ return false;
+ }
+ }
+
+ /**
+ * D2 — prove we're still viewing and report our facing. The server refreshes
+ * this viewer's heartbeat timestamp (so the reaper keeps us) and updates the
+ * heading a shared ghost is oriented by. No-op off a live socket; presence is
+ * inherently live-only, so a missed heartbeat in poll fallback is correct.
+ * @param {number} headingDeg compass bearing 0–359 the viewer is facing
+ */
+ heartbeat(headingDeg) {
+ if (this.status !== 'online' || !this.room) return;
+ const heading = Number.isFinite(headingDeg) ? headingDeg : 0;
+ try { this.room.send('heartbeat', { heading }); } catch (e) {
+ log.warn('[irl-net] heartbeat send failed:', e?.message || e);
+ }
+ }
+
+ /**
+ * D2 — flip the "appear to others nearby" opt-in. Stored so a later (re)connect
+ * re-joins with the right intent, and pushed live over `set_ghost` so the marker
+ * appears / disappears for everyone in the cell without a rejoin.
+ * @param {boolean} ghost broadcast self as a positioned ghost
+ * @param {string} [avatar] GLB url to show as the ghost (ignored when ghost=false)
+ */
+ setGhost(ghost, avatar) {
+ this.ghost = ghost === true;
+ if (avatar !== undefined) this.avatar = avatar || '';
+ if (this.status !== 'online' || !this.room) return;
+ try {
+ this.room.send('set_ghost', { ghost: this.ghost, avatar: this.ghost ? this.avatar : '' });
+ } catch (e) {
+ log.warn('[irl-net] set_ghost send failed:', e?.message || e);
+ }
+ }
+
+ // Coalesce a flurry of viewer deltas (notably the per-viewer onAdd burst the
+ // join handshake fires) into one presence emit on the next microtask.
+ _queuePresence() {
+ if (this._presenceQueued || this._destroyed) return;
+ this._presenceQueued = true;
+ Promise.resolve().then(() => {
+ this._presenceQueued = false;
+ this._emitPresence();
+ });
+ }
+
+ // Derive { count, viewers } from the live MapSchema and emit it. `count` is the
+ // whole crowd (self included — the chip hides at ≤1). `viewers` is everyone
+ // ELSE who opted into a ghost, mapped to the coarse render shape; non-ghost and
+ // self entries never appear, so a marker is only ever drawn for opted-in others.
+ _emitPresence() {
+ if (this._destroyed || !this.room) return;
+ const map = this.room.state?.viewers;
+ if (!map) return;
+ const selfId = this.room.sessionId;
+ let count = 0;
+ const viewers = [];
+ map.forEach((v, id) => {
+ count++;
+ if (id === selfId || !v.ghost) return;
+ viewers.push({
+ id,
+ glat: v.lat,
+ glng: v.lng,
+ heading: v.heading,
+ avatar: v.avatar || '',
+ ghost: true,
+ });
+ });
+ this._emit('presence', { count, viewers });
+ }
+
/** Force a reconnect (e.g. the user tapped the offline pill). */
retry() {
if (this._reconnectTimer) {
diff --git a/src/irl.js b/src/irl.js
index c1cbed4e4..b3addc691 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -1153,6 +1153,10 @@ function onGPSPosition(pos) {
updatePinRing(p);
}
+ // Re-anchor live presence ghosts against the shifted origin too, so a co-viewer's
+ // orb holds its real-world bearing as the user walks (same treatment as pins).
+ for (const g of ghostViewers.values()) positionGhostOrb(g);
+
// 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
@@ -1655,12 +1659,18 @@ function startPinSync() {
irlNet = new IrlNet({
lat: gpsState.lat, lng: gpsState.lng,
deviceToken: _deviceToken, agent: _currentAgentId || '',
+ // D2 — opt-in to being seen as a ghost (default off). Avatar only matters
+ // when sharing; the server drops it otherwise.
+ ghost: getShareGhost(), avatar: resolveAvatarUrl(_currentAvatarId),
});
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('reaction', (msg) => onReaction(msg)); // D3 ambient interaction reactions
+ irlNet.on('presence', ({ count, viewers }) => updatePresence(count, viewers)); // D2
irlNet.on('status', ({ status }) => onNetStatus(status));
irlNet.connect();
+ startHeartbeat();
}
function onNetStatus(status) {
@@ -1669,6 +1679,11 @@ function onNetStatus(status) {
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
+ // D2 presence is live-only: the chip + ghosts are meaningful only while the WS
+ // owns the stream. Any non-online status clears them so a stale count or frozen
+ // ghost never lingers in poll fallback / while reconnecting; online refreshes
+ // from the next presence delta.
+ if (status !== 'online') clearPresence();
}
function ingestStreamPin(kind, wire) {
@@ -1777,6 +1792,154 @@ function setNetPill(state) {
pill.setAttribute('aria-label', `Realtime status: ${pill.textContent || 'idle'}`);
}
+// ── Live viewer presence (D2) ───────────────────────────────────────────────
+// A pin is a static artifact; a person also looking at this spot right now is
+// social proof. Presence rides the SAME geocell room D1 opened — the server adds
+// each viewer to a `viewers` MapSchema at the cell centre + jitter (never precise
+// GPS) and Colyseus delta-broadcasts it, so we get a live "N viewing nearby"
+// count for free, plus optional ghost markers for viewers who opted to be seen.
+//
+// Privacy: you always SEE the count and others' ghosts; you only BROADCAST
+// yourself as a ghost if you opt in ("Appear to others nearby", default off,
+// stored in localStorage). Count-only presence reveals nothing beyond "someone
+// in this ~1 km cell." Presence is live-only — cleared in poll fallback / while
+// connecting (onNetStatus), never faked from the REST poll.
+const SHARE_GHOST_KEY = 'irl_share_ghost';
+function getShareGhost() {
+ try { return localStorage.getItem(SHARE_GHOST_KEY) === '1'; } catch { return false; }
+}
+function setShareGhost(on) {
+ try { localStorage.setItem(SHARE_GHOST_KEY, on ? '1' : '0'); } catch {}
+}
+
+// Compass-referenced facing we report on each heartbeat — the same absolute yaw
+// placement uses, so a shared ghost is oriented consistently for every viewer.
+function currentHeadingDeg() {
+ return ((cameraYaw * 180 / Math.PI) % 360 + 360) % 360;
+}
+
+// 15 s heartbeat: proves we're still here (the server's 30 s reaper drops silent
+// viewers) and refreshes our facing. A no-op off a live socket — presence is
+// inherently live, so we never heartbeat into the poll fallback.
+let _heartbeatTimer = null;
+const HEARTBEAT_MS = 15000;
+function startHeartbeat() {
+ stopHeartbeat();
+ _heartbeatTimer = setInterval(() => { irlNet?.heartbeat(currentHeadingDeg()); }, HEARTBEAT_MS);
+}
+function stopHeartbeat() {
+ if (_heartbeatTimer) { clearInterval(_heartbeatTimer); _heartbeatTimer = null; }
+}
+
+// Rendered ghosts (others who opted to be seen), keyed by session id. Each entry
+// carries its coarse coords + a faint scene orb. The count chip always shows the
+// true crowd size; only this bounded set is drawn.
+const ghostViewers = new Map();
+const GHOST_RENDER_CAP = 24; // bound drawn orbs/dots; the chip still shows the real count
+const GHOST_MAX_SCENE_M = 60; // clamp a coarse ghost to a soft nearby radius (it's approximate)
+const GHOST_HOVER_Y = 1.3; // float the orb near head height
+let _ghostPhase = 0; // shared gentle pulse phase
+
+// Coarse ghost → scene XZ, clamped to a comfortable radius. The position is
+// approximate by construction (cell centre + jitter), so a far cell-centre reads
+// as a soft nearby presence in roughly the right direction rather than a speck on
+// the horizon implying a precision we don't have.
+function ghostWorldXZ(g) {
+ const wp = gpsToWorld(g.glat, g.glng);
+ let x = wp.x, z = wp.z;
+ const d = Math.hypot(x, z);
+ if (d > GHOST_MAX_SCENE_M && d > 1e-3) {
+ const k = GHOST_MAX_SCENE_M / d;
+ x *= k; z *= k;
+ }
+ return { x, z };
+}
+
+// A ghost is deliberately distinct from a pin: a faint translucent orb, no name
+// label, no confidence ring, and never added to the raycast set (the tap/long-press
+// handlers only scan nearbyPins groups), so it can never be mistaken for or tapped
+// as a placed agent.
+function createGhostOrb() {
+ const orb = new Mesh(
+ new SphereGeometry(0.5, 16, 12),
+ new MeshBasicMaterial({ color: 0x9fd8ff, transparent: true, opacity: 0.28, depthWrite: false }),
+ );
+ orb.renderOrder = 4;
+ orb.userData.ghost = true; // marker; ghosts are never in the pin raycast list anyway
+ scene.add(orb);
+ return orb;
+}
+function positionGhostOrb(g) {
+ if (!g.orb || !gpsState.ready) return;
+ const { x, z } = ghostWorldXZ(g);
+ g.orb.position.set(x, GHOST_HOVER_Y, z);
+}
+function removeGhostOrb(g) {
+ if (!g.orb) return;
+ scene.remove(g.orb);
+ g.orb.geometry.dispose();
+ g.orb.material.dispose();
+ g.orb = null;
+}
+
+// Reconcile the live presence delta: update the count chip and the drawn ghost
+// set. `viewers` is already only OTHER opted-in viewers (self + count-only entries
+// filtered out in irl-net), so everything here is a renderable ghost.
+function updatePresence(count, viewers) {
+ const chip = document.getElementById('irl-presence-chip');
+ if (chip) {
+ const show = _streamOnline && count > 1; // 1 = just me; nothing social to show
+ chip.hidden = !show;
+ if (show) {
+ chip.textContent = `${count} viewing nearby`;
+ chip.setAttribute('aria-label', `${count} people viewing this location`);
+ }
+ }
+
+ const incoming = new Map();
+ for (const v of viewers) {
+ if (incoming.size >= GHOST_RENDER_CAP) break;
+ if (v && v.id) incoming.set(v.id, v);
+ }
+ // Despawn ghosts that left or stopped sharing.
+ for (const [id, g] of ghostViewers) {
+ if (!incoming.has(id)) { removeGhostOrb(g); ghostViewers.delete(id); }
+ }
+ // Spawn / refresh the rest.
+ for (const [id, v] of incoming) {
+ let g = ghostViewers.get(id);
+ if (!g) { g = { id }; ghostViewers.set(id, g); }
+ g.glat = v.glat; g.glng = v.glng; g.heading = v.heading; g.avatar = v.avatar;
+ if (!g.orb) g.orb = createGhostOrb();
+ positionGhostOrb(g);
+ }
+}
+
+// Hide the chip and drop every ghost cleanly — called whenever the live stream
+// isn't owning presence (connecting, poll fallback, offline) so a stale count or
+// frozen orb never lingers. Restored from the next presence delta on reconnect.
+function clearPresence() {
+ const chip = document.getElementById('irl-presence-chip');
+ if (chip) chip.hidden = true;
+ for (const g of ghostViewers.values()) removeGhostOrb(g);
+ ghostViewers.clear();
+}
+
+// Gentle shared pulse so ghosts read as "alive" without per-orb cost. Cheap: only
+// touches scale + opacity on the bounded ghost set, and early-outs when empty.
+function updateGhosts(dt) {
+ if (!ghostViewers.size) return;
+ _ghostPhase += dt;
+ const wave = Math.sin(_ghostPhase * 2);
+ const scale = 1 + wave * 0.08;
+ const opacity = 0.22 + (wave * 0.5 + 0.5) * 0.16; // 0.22 … 0.38
+ for (const g of ghostViewers.values()) {
+ if (!g.orb) continue;
+ g.orb.scale.setScalar(scale);
+ g.orb.material.opacity = opacity;
+ }
+}
+
async function loadNearbyPins() {
if (!gpsState.ready) return;
// While the live stream owns the nearby set, the poll is a no-op — it would fight
@@ -2188,16 +2351,32 @@ function updateNearbyBadge() {
const badge = document.getElementById('irl-nearby-badge');
if (!badge) return;
const n = nearbyPins.length;
+ // Compute the target text/class first, then only write when it changes — the badge
+ // is aria-live, so re-setting identical content on every reconcile would spam a
+ // screen reader.
+ let text, mod;
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;
+ text = n > 0 ? `${n} nearby · refresh failed` : 'Couldn’t load nearby — retrying…';
+ mod = 'is-error';
+ } else if (n > 0) {
+ text = `${n} nearby`;
+ mod = '';
+ } else if (gpsState.ready) {
+ // GPS-ready but nobody here yet — a designed empty state that invites the user
+ // to be the first, rather than hiding (which reads as "feature off").
+ text = 'No agents nearby — be the first to pin here';
+ mod = 'is-empty';
+ } else {
+ // No fix yet → nothing to say about "nearby"; stay hidden until GPS lands.
+ text = '';
+ mod = 'hidden';
}
- badge.classList.remove('is-error');
- badge.textContent = n > 0 ? `${n} nearby` : '';
- badge.hidden = n === 0;
+ badge.classList.toggle('is-error', mod === 'is-error');
+ badge.classList.toggle('is-empty', mod === 'is-empty');
+ if (mod === 'hidden') { badge.hidden = true; return; }
+ badge.hidden = false;
+ if (badge.textContent !== text) badge.textContent = text;
}
// ── My Pins management ────────────────────────────────────────────────────
@@ -2340,6 +2519,32 @@ function revealMyPinsBtn() {
document.getElementById('irl-mypins-btn')?.addEventListener('click', openMyPinsSheet);
+// ── "Appear to others nearby" toggle (D2) ──────────────────────────────────
+// Reflects the stored opt-in on the pill (default off) and flips it live: the
+// preference persists, and setGhost() pushes it to the room so co-viewers see the
+// ghost appear / disappear without anyone reconnecting. Seeing others is always
+// on; this gates only being seen.
+function syncGhostToggle() {
+ const btn = document.getElementById('irl-ghost-toggle');
+ if (!btn) return;
+ const on = getShareGhost();
+ btn.classList.toggle('is-active', on);
+ btn.setAttribute('aria-pressed', on ? 'true' : 'false');
+ btn.title = on
+ ? 'You appear as a ghost to others viewing this area. Tap to hide.'
+ : 'Only your presence count is shared. Tap to appear as a ghost to others nearby.';
+}
+document.getElementById('irl-ghost-toggle')?.addEventListener('click', () => {
+ const on = !getShareGhost();
+ setShareGhost(on);
+ syncGhostToggle();
+ // Push the change to the live room (no-op off a live socket; the next connect
+ // carries the stored intent regardless).
+ irlNet?.setGhost(on, resolveAvatarUrl(_currentAvatarId));
+ setStatus(on ? 'You now appear to others nearby' : 'You no longer appear to others');
+});
+syncGhostToggle();
+
document.getElementById('irl-mypins-close')?.addEventListener('click', () => {
document.getElementById('irl-mypins-sheet')?.classList.remove('is-open');
});
@@ -2592,6 +2797,32 @@ function showServiceResult(label, payload) {
block.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
+// Wallet-not-connected is a *state*, not a transient event: the user can't pay
+// until they have a wallet, so a 3 s toast that vanishes leaves them stuck with no
+// next step. Render a designed, persistent state-kit card into the inspect sheet
+// body (below the services it blocks) with the exact recovery path. Cleared the
+// moment a payment actually proceeds, and wiped automatically when loadAgentCard
+// re-renders the body for a different agent.
+function showWalletNeeded(body) {
+ const host = document.getElementById('irl-card-body');
+ if (!host) { setStatus(body, { error: true, sticky: true }); return; }
+ ensureStateKitStyles();
+ host.querySelector('.irl-pay-notice')?.remove();
+ const wrap = document.createElement('div');
+ wrap.className = 'irl-pay-notice';
+ wrap.innerHTML = emptyStateHTML({
+ icon: '👛',
+ title: 'Connect a wallet to pay',
+ body,
+ compact: true,
+ });
+ host.appendChild(wrap);
+ wrap.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+}
+function clearWalletNotice() {
+ document.getElementById('irl-card-body')?.querySelector('.irl-pay-notice')?.remove();
+}
+
// 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
@@ -2601,7 +2832,8 @@ 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 a wallet (MetaMask) to pay via x402', { error: true });
+ // No injected wallet at all — a designed, persistent recovery state, not a toast.
+ showWalletNeeded('This browser has no wallet. Open three.ws in a wallet browser (e.g. MetaMask) or install one, then tap Use again to pay in USDC.');
return;
}
@@ -2627,14 +2859,18 @@ async function runX402Payment(endpoint, btn) {
return;
}
if (!Array.isArray(accounts) || !accounts.length) {
- setStatus('Connect your wallet to pay', { error: true });
+ // Wallet present but locked / no account approved — designed recovery state.
+ showWalletNeeded('No wallet account is connected. Unlock your wallet and approve the connection, then tap Use again.');
btn.disabled = false; btn.textContent = origText;
return;
}
+ // A wallet is connected and we're proceeding — drop any prior "connect a wallet"
+ // notice so a resolved state doesn't linger under the now-working payment.
+ clearWalletNotice();
btn.textContent = 'Paying…';
try {
- const { withX402 } = await import('../packages/x402-fetch/dist/index.esm.js');
+ const { withX402 } = await import('../packages/x402-fetch/src/index.js');
// 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)
@@ -2685,6 +2921,10 @@ async function runX402Payment(endpoint, btn) {
amount: Number.isFinite(settledUsd) ? Math.round(settledUsd * 1e6) : null,
payload: { skill, payer: settlement.payer || null },
}).catch(() => {});
+ // D3 — high-signal: fan a "paid" reaction to co-located viewers. Only here,
+ // after a real on-chain settlement, never optimistically — so the agent's
+ // celebration (and the owner's earned event) is never a lie.
+ irlNet?.interaction({ type: 'pay', pinId: sheet.dataset.pinId, agentId: sheet.dataset.agentId || '' });
}
} catch (err) {
const m = err?.message ?? String(err);
@@ -2805,6 +3045,9 @@ function openPinSheet(pin) {
}),
}).catch(() => {});
pin.view_count = (pin.view_count ?? 0) + 1;
+ // D3 — fan an ambient reaction to co-located viewers (the REST POST above is the
+ // durable record + owner notification; this is the live flourish, no-op off-WS).
+ irlNet?.interaction({ type: 'view', pinId: pin.id, agentId: pin.agent_id ?? '' });
}
// Rich card: avatar bio + on-chain reputation + the agent's paid x402 services,
@@ -2865,6 +3108,8 @@ document.getElementById('irl-sheet-msg')?.addEventListener('submit', async (e) =
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
if (input) input.value = '';
+ // D3 — high-signal: the agent reacts to a left message for everyone nearby.
+ irlNet?.interaction({ type: 'message', pinId, agentId: sheet.dataset.agentId || '' });
if (status) {
status.textContent = 'Message delivered — the owner will see it.';
status.classList.remove('is-error');
@@ -3052,8 +3297,9 @@ document.getElementById('irl-sheet-pay')?.addEventListener('click', (e) => {
function updateRadar() {
const radar = document.getElementById('irl-radar');
if (!radar || !gpsModeActive) return;
- radar.querySelectorAll('.irl-radar-dot').forEach(d => d.remove());
+ radar.querySelectorAll('.irl-radar-dot, .irl-radar-ghost').forEach(d => d.remove());
const R = 60; // half of 120px radar
+ let shown = 0;
for (const pin of nearbyPins) {
if (!pin.group) continue;
const wx = pin.group.position.x;
@@ -3068,6 +3314,41 @@ function updateRadar() {
dot.title = `${pin.avatar_name || 'Agent'} · ${pin.distance_m ?? Math.round(Math.hypot(wx, wz))}m`;
dot.addEventListener('click', () => openPinSheet(pin));
radar.appendChild(dot);
+ shown++;
+ }
+ // Live presence ghosts (D2) — faint, smaller, not tappable, drawn beneath the
+ // agent dots. They sit at the orb's clamped coarse position, so they read as
+ // "someone roughly here" rather than a precise placement. Not counted in `shown`
+ // (the empty hint is about placed agents, not co-viewers).
+ for (const g of ghostViewers.values()) {
+ if (!g.orb) continue;
+ const px = R + (g.orb.position.x / NEARBY_RADIUS) * R;
+ const py = R + (-g.orb.position.z / NEARBY_RADIUS) * R;
+ if (px < 0 || px > 120 || py < 0 || py > 120) continue;
+ const gd = document.createElement('div');
+ gd.className = 'irl-radar-ghost';
+ gd.style.left = `${px}px`;
+ gd.style.top = `${py}px`;
+ gd.title = 'Someone viewing nearby';
+ radar.appendChild(gd);
+ }
+ // Designed in-radar states (E4): a failed nearby refresh and an empty dial each
+ // get an honest centred hint instead of a blank radar that reads as "nobody here"
+ // even when the fetch broke. The hint reuses the existing 15 s poll / live stream
+ // to recover, so it clears itself on the next good update.
+ let hint = radar.querySelector('.irl-radar-hint');
+ const message = _nearbyError ? 'Can’t refresh' : (shown === 0 ? 'No agents in range' : '');
+ if (message) {
+ if (!hint) {
+ hint = document.createElement('div');
+ hint.className = 'irl-radar-hint';
+ radar.appendChild(hint);
+ }
+ hint.textContent = message;
+ hint.classList.toggle('is-error', _nearbyError);
+ hint.hidden = false;
+ } else if (hint) {
+ hint.hidden = true;
}
}
@@ -3395,17 +3676,23 @@ function updateAgentAwareness(dt) {
pin.noticed = true;
pin.noticeT = NOTICE_BOOST_SEC; // snap the head to attention briefly
pin.popT = 0; // start the perk-up scale pop
+ pin._popAmp = 0; // default subtle amplitude (D3 reactions set their own)
} else if (pin.noticed && dist > NOTICE_RADIUS_M + 1) {
pin.noticed = false;
}
if (pin.noticeT > 0) pin.noticeT = Math.max(0, pin.noticeT - dt);
+ // Perk-up scale pop. The greet sets the default POP_AMOUNT; a D3 reaction
+ // (playEmote) reuses this same one-shot with a bigger _popAmp so a `pay`
+ // reads as a stronger bounce than a glance — one driver, never two fighting.
if (pin.popT >= 0) {
pin.popT += dt;
+ const amp = pin._popAmp || POP_AMOUNT;
if (pin.popT >= POP_DURATION) {
pin.popT = -1;
+ pin._popAmp = 0;
pin.group.scale.y = 1;
} else {
- pin.group.scale.y = 1 + POP_AMOUNT * Math.sin(Math.PI * pin.popT / POP_DURATION);
+ pin.group.scale.y = 1 + amp * Math.sin(Math.PI * pin.popT / POP_DURATION);
}
}
@@ -3418,6 +3705,112 @@ function updateAgentAwareness(dt) {
}
}
+// ── Ambient interaction reactions (D3) ──────────────────────────────────────
+// A co-located viewer tapped / paid / messaged a nearby agent; the room fanned a
+// `reaction` to everyone here (see irl-net.js + IrlRoom). We answer with the two
+// things a bystander actually sees: the agent perks up (a scale "emote" pop on its
+// loaded model) and a glyph rises off its head — 💜 for a glance, ✨ paid for a
+// settled payment, 💬 for a left message. Pure transform/opacity, GPU-only, capped
+// and auto-cleaned: never a layout reflow. A reaction whose pin scrolled out of
+// range is silently dropped — the durable record already landed over REST, so only
+// the live flourish is skipped, never the data.
+const REACTION_TTL = 1.2; // seconds a floating glyph lives (matches the CSS rise)
+const MAX_REACTIONS = 14; // concurrent floaters cap — a busy plaza can't churn the DOM
+const _reactions = []; // [{ pin, outer, t }]
+const _reactVec = new Vector3(); // scratch for per-frame projection (no per-call alloc)
+
+// Glyph + optional label + style hook per reaction type. open/view share the heart.
+const REACTION_GLYPH = {
+ open: { mark: '💜', text: '', cls: '' },
+ view: { mark: '💜', text: '', cls: '' },
+ pay: { mark: '✨', text: 'paid', cls: 'is-pay' },
+ message: { mark: '💬', text: '', cls: 'is-msg' },
+};
+
+function onReaction(msg) {
+ const pinId = msg?.pinId;
+ const type = msg?.type;
+ if (!pinId || !type) return;
+ const pin = nearbyPins.find((p) => p.id === pinId);
+ if (!pin?.group) return; // out of range / not spawned → drop the flourish
+ playEmote(pin, type);
+}
+
+// The agent's gesture: a one-shot perk-up scale pop on its loaded model, reusing
+// the E2 notice-pop driver in updateAgentAwareness. pay/message get a bigger pop
+// than a glance. A pin that's only a far dot/impostor (not glbLoaded) has no model
+// to pop — the floating glyph still plays, so it's always something, never a no-op.
+function playEmote(pin, type) {
+ if (!pin?.group) return;
+ if (pin.glbLoaded) {
+ pin.popT = 0;
+ pin._popAmp = type === 'pay' ? 0.16 : type === 'message' ? 0.11 : 0.07;
+ }
+ spawnFloatingReaction(pin, type);
+}
+
+// A glyph that rises off the agent's head and fades. Two layers so positioning and
+// the flourish never fight: the OUTER is reprojected to the pin's screen point each
+// frame (updateReactions); the INNER runs the CSS rise+fade and is never touched by
+// JS. Capped + auto-removed so the DOM stays tiny even in a crowd.
+function spawnFloatingReaction(pin, type) {
+ if (!pin?.group) return;
+ const g = REACTION_GLYPH[type] || REACTION_GLYPH.open;
+
+ // Evict the oldest floater at the cap so a stampede can't grow the DOM unbounded.
+ while (_reactions.length >= MAX_REACTIONS) {
+ const old = _reactions.shift();
+ old?.outer?.remove();
+ }
+
+ const outer = document.createElement('div');
+ outer.className = 'irl-reaction';
+ outer.setAttribute('aria-hidden', 'true'); // decorative; the action it mirrors is announced elsewhere
+ const inner = document.createElement('div');
+ inner.className = `irl-reaction-burst ${g.cls}`.trim();
+ inner.innerHTML = g.text
+ ? `<span class="irl-reaction-mark">${g.mark}</span><span class="irl-reaction-text">${g.text}</span>`
+ : `<span class="irl-reaction-mark">${g.mark}</span>`;
+ outer.appendChild(inner);
+ document.body.appendChild(outer);
+
+ const entry = { pin, outer, t: 0 };
+ _reactions.push(entry);
+ _projectReaction(entry); // place it now so it never flashes at (0,0) for a frame
+}
+
+// Project one reaction's anchor (just above the agent's head) to screen space and
+// move its outer wrapper there. Hidden when behind the camera. Mirrors updateLabels().
+function _projectReaction(entry) {
+ const pin = entry.pin;
+ if (!pin?.group) { entry.outer.style.display = 'none'; return; }
+ _reactVec.set(pin.group.position.x, pin.group.position.y + 2.9, pin.group.position.z);
+ _reactVec.project(camera);
+ if (_reactVec.z > 1) { entry.outer.style.display = 'none'; return; }
+ const sx = (_reactVec.x * 0.5 + 0.5) * window.innerWidth;
+ const sy = (-_reactVec.y * 0.5 + 0.5) * window.innerHeight;
+ entry.outer.style.display = 'block';
+ entry.outer.style.left = `${sx}px`;
+ entry.outer.style.top = `${sy}px`;
+}
+
+// Advance every live floater: age it, reproject it to follow its agent, retire it
+// (DOM removed) past its TTL or once its pin left the nearby set. Called each frame.
+function updateReactions(dt) {
+ if (!_reactions.length) return;
+ for (let i = _reactions.length - 1; i >= 0; i--) {
+ const entry = _reactions[i];
+ entry.t += dt;
+ const live = entry.pin?.group && nearbyPins.includes(entry.pin);
+ if (entry.t >= REACTION_TTL || !live) {
+ entry.outer.remove();
+ _reactions.splice(i, 1);
+ continue;
+ }
+ _projectReaction(entry);
+ }
+}
+
// ── 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
@@ -3566,6 +3959,10 @@ function tick() {
// Project nearby agent labels to screen space (capped to BUDGET.label nearest).
updateLabels();
+ // Advance any live ambient interaction reactions (D3): age, reproject, retire.
+ updateReactions(dt);
+ // Gentle pulse on live presence ghosts (D2) — early-outs when none are present.
+ updateGhosts(dt);
// 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(); }
diff --git a/tests/api/agent-skill-pricing.test.js b/tests/api/agent-skill-pricing.test.js
new file mode 100644
index 000000000..02f75a999
--- /dev/null
+++ b/tests/api/agent-skill-pricing.test.js
@@ -0,0 +1,266 @@
+// C2 — Skills & services management for an IRL agent.
+//
+// These are the two endpoints the dashboard Services panel
+// (src/dashboard-next/pages/irl-placements.js openServicesModal) drives so an
+// owner can attach skills to a placed agent and set the x402 per-call price a
+// passer-by then pays (B3):
+//
+// POST /api/agent-skill-price?agentId=:id single-skill upsert (amount=0 deactivates)
+// GET /api/agents/:id/skills-pricing read the agent's active prices
+// PUT /api/agents/:id/skills-pricing bulk replace the active price set
+//
+// The server is the trust boundary: ownership is checked against
+// agent_identities (never the caller), cookie-session mutations require CSRF, the
+// price body is validated, and a pause/remove is recorded as a deactivation
+// (is_active=false), never a phantom row. These tests pin that boundary down.
+// DB / auth / CSRF / limiter are mocked so the suite stays offline.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { invoke } from '../_helpers/monetization.js';
+
+// ── Content-addressed SQL mock ───────────────────────────────────────────────
+// Classify each tagged-template query by its text: the agent-ownership lookup,
+// the active-price read, and the write statements (UPDATE deactivate / INSERT
+// upsert) each get the right shape regardless of call order. Every call is
+// recorded so write-path assertions can verify the persisted atomic amount and
+// the deactivate path. `sql.transaction` mirrors postgres.js's array form (the
+// tagged calls have already run by the time the array is built, so awaiting them
+// in order is faithful).
+let agentRow = null; // agent_identities lookup → { id, user_id } or null
+let activePrices = []; // rows the GET returns
+let calls = []; // { q, values } for every query, in order
+
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ calls.push({ q, values });
+ if (/FROM agent_identities/i.test(q)) {
+ return Promise.resolve(agentRow ? [agentRow] : []);
+ }
+ if (/SELECT[\s\S]*FROM agent_skill_prices[\s\S]*is_active = true/i.test(q)) {
+ return Promise.resolve(activePrices);
+ }
+ // UPDATE (deactivate) / INSERT (upsert) / DDL — no RETURNING is consumed.
+ return Promise.resolve([]);
+});
+sqlMock.transaction = (queries) => Promise.all(queries);
+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
+
+let sessionUser = null;
+let bearerUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+ authenticateBearer: vi.fn(async () => bearerUser),
+ extractBearer: vi.fn(() => null),
+}));
+
+// CSRF passes by default; flip `csrfOk=false` to exercise the gate. On failure the
+// real requireCsrf writes the 403 itself, so the mock does too — the handler just
+// returns after a falsy result.
+let csrfOk = true;
+vi.mock('../../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async (req, res) => {
+ if (csrfOk) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf_invalid' }));
+ return false;
+ }),
+}));
+
+let rlSuccess = true;
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: rlSuccess, reset: Date.now() + 1000, limit: 60, remaining: 0 })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const { default: singleUpsert } = await import('../../api/agent-skill-price.js');
+const { default: pricing } = await import('../../api/agents/[id]/skills-pricing.js');
+
+// $THREE and Solana USDC — the only mints the dashboard offers; both base58.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const AGENT_ID = '00000000-0000-4000-8000-000000000abc';
+
+const findCall = (re) => calls.find((c) => re.test(c.q));
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ calls = [];
+ agentRow = { id: AGENT_ID, user_id: 'owner-uuid' };
+ activePrices = [];
+ sessionUser = null;
+ bearerUser = null;
+ csrfOk = true;
+ rlSuccess = true;
+});
+
+// ── POST /api/agent-skill-price — single-skill upsert (the dashboard write) ───
+describe('POST /api/agent-skill-price — auth + ownership', () => {
+ const url = `/api/agent-skill-price?agentId=${AGENT_ID}`;
+ const body = { skill: 'web-search', amount: 50000, currency_mint: THREE_MINT, chain: 'solana' };
+
+ it('401s when unauthenticated', async () => {
+ const { status, body: out } = await invoke(singleUpsert, { method: 'POST', url, body });
+ expect(status).toBe(401);
+ expect(out.error).toBe('unauthorized');
+ });
+
+ it('403s when the agent belongs to another user', async () => {
+ sessionUser = { id: 'not-the-owner' };
+ const { status, body: out } = await invoke(singleUpsert, { method: 'POST', url, body });
+ expect(status).toBe(403);
+ expect(out.error).toBe('forbidden');
+ // Ownership is rejected before any write touches agent_skill_prices.
+ expect(findCall(/INTO agent_skill_prices/i)).toBeUndefined();
+ });
+
+ it('404s when the agent does not exist', async () => {
+ sessionUser = { id: 'owner-uuid' };
+ agentRow = null;
+ const { status, body: out } = await invoke(singleUpsert, { method: 'POST', url, body });
+ expect(status).toBe(404);
+ expect(out.error).toBe('not_found');
+ });
+
+ it('400s without an agentId query param', async () => {
+ sessionUser = { id: 'owner-uuid' };
+ const { status } = await invoke(singleUpsert, { method: 'POST', url: '/api/agent-skill-price', body });
+ expect(status).toBe(400);
+ });
+
+ it('403s when the CSRF token is missing/invalid', async () => {
+ sessionUser = { id: 'owner-uuid' };
+ csrfOk = false;
+ const { status, body: out } = await invoke(singleUpsert, { method: 'POST', url, body });
+ expect(status).toBe(403);
+ expect(out.error).toBe('csrf_invalid');
+ });
+
+ it('429s when rate-limited', async () => {
+ sessionUser = { id: 'owner-uuid' };
+ rlSuccess = false;
+ const { status } = await invoke(singleUpsert, { method: 'POST', url, body });
+ expect(status).toBe(429);
+ });
+});
+
+describe('POST /api/agent-skill-price — validation + persistence', () => {
+ const url = `/api/agent-skill-price?agentId=${AGENT_ID}`;
+ beforeEach(() => { sessionUser = { id: 'owner-uuid' }; });
+
+ it('400s on a mint that is not base58', async () => {
+ const { status, body: out } = await invoke(singleUpsert, {
+ method: 'POST', url,
+ body: { skill: 'web-search', amount: 50000, currency_mint: 'not-base58!!', chain: 'solana' },
+ });
+ expect(status).toBe(400);
+ expect(out.error).toBe('validation_error');
+ expect(findCall(/INTO agent_skill_prices/i)).toBeUndefined();
+ });
+
+ it('400s on a non-integer / negative amount', async () => {
+ const { status } = await invoke(singleUpsert, {
+ method: 'POST', url,
+ body: { skill: 'web-search', amount: -5, currency_mint: THREE_MINT, chain: 'solana' },
+ });
+ expect(status).toBe(400);
+ });
+
+ it('writes the atomic price as an active row (0.05 USDC → 50000)', async () => {
+ const { status, body: out } = await invoke(singleUpsert, {
+ method: 'POST', url,
+ body: { skill: 'web-search', amount: 50000, currency_mint: THREE_MINT, chain: 'solana' },
+ });
+ expect(status).toBe(200);
+ expect(out.data.ok).toBe(true);
+ const ins = findCall(/INTO agent_skill_prices/i);
+ expect(ins).toBeDefined();
+ // VALUES (${agentId}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true)
+ expect(ins.values[0]).toBe(AGENT_ID);
+ expect(ins.values[1]).toBe('web-search');
+ expect(ins.values[2]).toBe(50000);
+ expect(ins.values[3]).toBe(THREE_MINT);
+ // No deactivate ran on a real price.
+ expect(findCall(/SET is_active = false/i)).toBeUndefined();
+ });
+
+ it('amount=0 deactivates (pause / remove) instead of inserting a row', async () => {
+ const { status } = await invoke(singleUpsert, {
+ method: 'POST', url,
+ body: { skill: 'web-search', amount: 0, currency_mint: THREE_MINT, chain: 'solana' },
+ });
+ expect(status).toBe(200);
+ const deact = findCall(/SET is_active = false/i);
+ expect(deact).toBeDefined();
+ expect(deact.values).toContain('web-search');
+ // A deactivate must never also insert a live row.
+ expect(findCall(/INTO agent_skill_prices/i)).toBeUndefined();
+ });
+});
+
+// ── GET/PUT /api/agents/:id/skills-pricing — read + bulk replace ──────────────
+describe('GET /api/agents/:id/skills-pricing', () => {
+ const url = `/api/agents/${AGENT_ID}/skills-pricing`;
+
+ it('401s when unauthenticated', async () => {
+ const { status } = await invoke(pricing, { method: 'GET', url });
+ expect(status).toBe(401);
+ });
+
+ it('403s for a non-owner', async () => {
+ sessionUser = { id: 'not-the-owner' };
+ const { status, body: out } = await invoke(pricing, { method: 'GET', url });
+ expect(status).toBe(403);
+ expect(out.error).toBe('forbidden');
+ });
+
+ it('returns the agent\'s active prices for the owner', async () => {
+ sessionUser = { id: 'owner-uuid' };
+ activePrices = [
+ { skill: 'web-search', amount: 50000, currency_mint: THREE_MINT, chain: 'solana' },
+ ];
+ const { status, body: out } = await invoke(pricing, { method: 'GET', url });
+ expect(status).toBe(200);
+ expect(out.prices).toHaveLength(1);
+ expect(out.prices[0].skill).toBe('web-search');
+ expect(out.prices[0].amount).toBe(50000);
+ });
+});
+
+describe('PUT /api/agents/:id/skills-pricing — bulk replace', () => {
+ const url = `/api/agents/${AGENT_ID}/skills-pricing`;
+ beforeEach(() => { sessionUser = { id: 'owner-uuid' }; });
+
+ it('403s when the CSRF token is missing/invalid', async () => {
+ csrfOk = false;
+ const { status } = await invoke(pricing, {
+ method: 'PUT', url,
+ body: { prices: [{ skill: 'web-search', amount: 50000, currency_mint: THREE_MINT, chain: 'solana' }] },
+ });
+ expect(status).toBe(403);
+ });
+
+ it('400s on an invalid price (amount below the minimum)', async () => {
+ const { status, body: out } = await invoke(pricing, {
+ method: 'PUT', url,
+ body: { prices: [{ skill: 'web-search', amount: 0, currency_mint: THREE_MINT, chain: 'solana' }] },
+ });
+ expect(status).toBe(400);
+ expect(out.error).toBe('validation_error');
+ });
+
+ it('atomically deactivates the old set then upserts the submitted prices', async () => {
+ const { status, body: out } = await invoke(pricing, {
+ method: 'PUT', url,
+ body: { prices: [
+ { skill: 'web-search', amount: 50000, currency_mint: THREE_MINT, chain: 'solana' },
+ { skill: 'summarize', amount: 100000, currency_mint: THREE_MINT, chain: 'solana' },
+ ] },
+ });
+ expect(status).toBe(200);
+ expect(out.ok).toBe(true);
+ // Deactivate-all runs first, then one upsert per submitted price.
+ expect(findCall(/SET is_active = false WHERE agent_id/i)).toBeDefined();
+ const inserts = calls.filter((c) => /INTO agent_skill_prices/i.test(c.q));
+ expect(inserts).toHaveLength(2);
+ expect(inserts.map((c) => c.values[1])).toEqual(['web-search', 'summarize']);
+ });
+});
diff --git a/tests/api/irl-agent-card.test.js b/tests/api/irl-agent-card.test.js
new file mode 100644
index 000000000..b2efd8ba3
--- /dev/null
+++ b/tests/api/irl-agent-card.test.js
@@ -0,0 +1,195 @@
+// GET /api/irl/agent-card — IRL Inspect Card v2 (B2).
+//
+// The card is ONE server-side fan-out — agent record + on-chain Solana reputation
+// + paid x402 services — merged into a single payload so a phone makes one call.
+// These tests pin the two things the client trusts the server to get right:
+// 1. the documented, explicit tier/score derivation from raw aggregates, and
+// 2. the merged shape — incl. the two non-negotiable degradations: a reputation
+// query failure must NOT fail the card (services still render), and an agent
+// with no on-chain asset must show available:false, never a fabricated score.
+// The DB / redis / rate-limit / r2 layers are mocked so the suite stays offline;
+// the real http.js + (pure) agent-paid-services helpers run, so the actual JSON
+// the client receives is what's asserted.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+import { deriveReputation } from '../../api/irl/agent-card.js';
+
+// ── Mutable fixtures the sql router reads, reset per test ──────────────────────
+let agentRow = null; // agent_identities row (null → agent 404)
+let repAgg = null; // reputation aggregate row
+let repThrows = false; // simulate a reputation-query failure (must degrade, not 500)
+let serviceRows = []; // agent_paid_services rows
+let pinRow = null; // irl_pins row when resolving by ?pin=
+
+// One tagged-template sql mock that routes by the query text, mirroring the real
+// fan-out in buildCard(): agent SELECT, reputation WITH fb/val, services SELECT.
+const sqlMock = vi.fn((strings) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/FROM agent_identities/i.test(q)) return Promise.resolve(agentRow ? [agentRow] : []);
+ if (/FROM irl_pins/i.test(q)) return Promise.resolve(pinRow ? [pinRow] : []);
+ if (/solana_attestations[\s\S]*threews\.feedback/i.test(q)) {
+ if (repThrows) return Promise.reject(new Error('rep table unavailable'));
+ return Promise.resolve([repAgg]);
+ }
+ if (/FROM agent_paid_services/i.test(q)) return Promise.resolve(serviceRows);
+ return Promise.resolve([]);
+});
+// The handler uses `.catch(() => [])` on the agent + services queries, so the mock
+// must expose `.catch`. Returning a real Promise (above) already does.
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+// No cache in tests — exercise the live fan-out every call, not a HIT.
+vi.mock('../../api/_lib/redis.js', () => ({ getRedis: vi.fn(async () => null) }));
+
+vi.mock('../../api/_lib/r2.js', () => ({ publicUrl: (key) => `/cdn/${key}` }));
+
+const { default: handler } = await import('../../api/irl/agent-card.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 getCard(qs) {
+ const res = makeRes();
+ await handler({ url: `/api/irl/agent-card?${qs}`, method: 'GET', headers: { host: 'x' } }, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON body */ }
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ agentRow = {
+ id: 'agent-1', name: 'Atlas', description: ' Trip-planning agent for explorers. ',
+ home_url: null, meta: { sol_mint_address: 'THREEsynthetic1111111111111111111111111111', network: 'mainnet' },
+ avatar_thumbnail_key: 'thumbs/atlas.png', avatar_visibility: 'public',
+ };
+ repAgg = { fb_total: 20, score_avg: 4.6, unique_attesters: 9, val_passed: 3, val_failed: 0, tasks_accepted: 14 };
+ repThrows = false;
+ serviceRows = [
+ { slug: 'route-plan', name: 'Route planning', description: 'Plan a multi-stop trip', price_atomics: '50000', network: 'base' },
+ { slug: 'weather', name: 'Weather brief', description: null, price_atomics: '10000', network: 'base' },
+ ];
+ pinRow = null;
+});
+
+describe('deriveReputation — documented tier/score formula', () => {
+ it('floors to "new" with no attestations (no fabricated score)', () => {
+ const r = deriveReputation({ fbTotal: 0, scoreAvg: 0, uniqueAttesters: 0, valPassed: 0, valFailed: 0, tasksAccepted: 0 });
+ expect(r.score).toBe(0);
+ expect(r.tier).toBe('new');
+ expect(r.attestation_count).toBe(0);
+ });
+
+ it('maps a strong on-chain record to a high tier', () => {
+ // 5-star avg (full quality), ~50 attesters (full breadth), all validations pass.
+ const r = deriveReputation({ fbTotal: 40, scoreAvg: 5, uniqueAttesters: 50, valPassed: 10, valFailed: 0, tasksAccepted: 30 });
+ expect(r.score).toBe(100);
+ expect(r.tier).toBe('elite');
+ expect(r.attestation_count).toBe(50); // fb_total(40) + val_passed(10)
+ });
+
+ it('is monotonic across the tier ladder new < emerging < trusted < elite', () => {
+ const score = (a) => deriveReputation(a).score;
+ const sNew = score({ fbTotal: 1, scoreAvg: 1.2, uniqueAttesters: 1, valPassed: 0, valFailed: 2, tasksAccepted: 0 });
+ const sEmerging = score({ fbTotal: 5, scoreAvg: 3, uniqueAttesters: 3, valPassed: 1, valFailed: 1, tasksAccepted: 1 });
+ const sTrusted = score({ fbTotal: 20, scoreAvg: 4.3, uniqueAttesters: 12, valPassed: 5, valFailed: 0, tasksAccepted: 8 });
+ const sElite = score({ fbTotal: 40, scoreAvg: 4.9, uniqueAttesters: 45, valPassed: 12, valFailed: 0, tasksAccepted: 30 });
+ expect(sNew).toBeLessThan(sEmerging);
+ expect(sEmerging).toBeLessThan(sTrusted);
+ expect(sTrusted).toBeLessThan(sElite);
+ expect(deriveReputation({ fbTotal: 40, scoreAvg: 4.9, uniqueAttesters: 45, valPassed: 12, valFailed: 0, tasksAccepted: 30 }).tier).toBe('elite');
+ });
+
+ it('clamps score into [0,100] and never exceeds it', () => {
+ const r = deriveReputation({ fbTotal: 999, scoreAvg: 5, uniqueAttesters: 9999, valPassed: 999, valFailed: 0, tasksAccepted: 999 });
+ expect(r.score).toBeGreaterThanOrEqual(0);
+ expect(r.score).toBeLessThanOrEqual(100);
+ });
+});
+
+describe('GET /api/irl/agent-card — merged payload', () => {
+ it('returns the merged agent + reputation + services shape in one response', async () => {
+ const { res, body } = await getCard('agent_id=agent-1');
+ expect(res.statusCode).toBe(200);
+ const card = body.card;
+ // agent
+ expect(card.agent).toMatchObject({ id: 'agent-1', name: 'Atlas', profile_url: '/agents/agent-1' });
+ expect(card.agent.bio).toBe('Trip-planning agent for explorers.'); // trimmed
+ expect(card.agent.thumbnail_url).toBe('/cdn/thumbs/atlas.png');
+ // reputation — real, derived, available
+ expect(card.reputation.available).toBe(true);
+ expect(card.reputation.tier).toBeDefined();
+ expect(card.reputation.score).toBeGreaterThan(0);
+ expect(card.reputation.unique_attesters).toBe(9);
+ // services — real USDC prices, ordered cheapest-first by the SQL, with endpoints
+ expect(card.services).toHaveLength(2);
+ expect(card.services[0]).toMatchObject({ skill: 'route-plan', name: 'Route planning', price_usd: 0.05, currency: 'USDC', chain: 'base' });
+ expect(card.services[0].x402_endpoint).toContain('/api/x402/service/route-plan');
+ expect(card.services[1].price_usd).toBe(0.01);
+ });
+
+ it('degrades gracefully when the reputation query fails — services still render', async () => {
+ repThrows = true;
+ const { res, body } = await getCard('agent_id=agent-1');
+ expect(res.statusCode).toBe(200);
+ expect(body.card.reputation.available).toBe(false);
+ expect(body.card.reputation.degraded).toBe(true);
+ expect(body.card.services).toHaveLength(2); // the menu is unaffected
+ });
+
+ it('shows no-reputation (available:false) for an agent with no on-chain asset, never a number', async () => {
+ agentRow.meta = {}; // no sol_mint_address
+ const { res, body } = await getCard('agent_id=agent-1');
+ expect(res.statusCode).toBe(200);
+ expect(body.card.reputation).toEqual({ asset: null, available: false });
+ expect(body.card.reputation.score).toBeUndefined();
+ });
+
+ it('renders an empty services array when the agent sells nothing', async () => {
+ serviceRows = [];
+ const { body } = await getCard('agent_id=agent-1');
+ expect(body.card.services).toEqual([]);
+ });
+
+ it('hides a private avatar thumbnail', async () => {
+ agentRow.avatar_visibility = 'private';
+ const { body } = await getCard('agent_id=agent-1');
+ expect(body.card.agent.thumbnail_url).toBeNull();
+ });
+
+ it('404s a genuine unknown agent_id', async () => {
+ agentRow = null;
+ const { res, body } = await getCard('agent_id=ghost');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBeDefined();
+ });
+
+ it('400s when neither agent_id nor pin is supplied', async () => {
+ const { res } = await getCard('');
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('degrades a pin whose linked agent is private/deleted to an anonymous card (no 404)', async () => {
+ pinRow = { agent_id: 'missing-agent', avatar_name: 'Wanderer', caption: 'hi', x402_endpoint: null };
+ agentRow = null; // the linked agent resolves to nothing
+ const { res, body } = await getCard('pin=pin-1');
+ expect(res.statusCode).toBe(200);
+ expect(body.card.anonymous).toBe(true);
+ expect(body.card.agent.name).toBe('Wanderer');
+ expect(body.card.reputation.available).toBe(false);
+ });
+});
diff --git a/tests/api/irl-agent-summary.test.js b/tests/api/irl-agent-summary.test.js
new file mode 100644
index 000000000..3495de251
--- /dev/null
+++ b/tests/api/irl-agent-summary.test.js
@@ -0,0 +1,142 @@
+// GET /api/irl/agent-summary?mine=1 — C1 owner dashboard overview.
+//
+// One round-trip that joins each owned pin to its agent + derived activity so the
+// dashboard paints without N blocking calls. The endpoint is the correctness
+// boundary for three things the card relies on and that must never 500:
+// • auth — only the signed-in owner's pins, never anyone else's;
+// • graceful degradation — a fresh DB (no irl_pins) or a pre-C4 deploy (no
+// irl_interactions) returns 0 / null instead of throwing;
+// • derived status — expired / online (interaction < 5 min) / visible.
+// DB + auth are mocked so the suite stays offline.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Content-addressed SQL mock. The to_regclass probe returns whatever the current
+// test set on `reg`; the pin SELECT returns `pinRows`. Which SELECT ran is
+// recorded so we can assert the table-existence guard picked the right query.
+let reg = { has_pins: true, has_ix: true };
+let pinRows = [];
+let ranWithIxJoin = false;
+const sqlMock = vi.fn((strings) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/to_regclass/i.test(q)) return Promise.resolve([reg]);
+ if (/FROM irl_pins p/i.test(q)) {
+ ranWithIxJoin = /LEFT JOIN \(\s*SELECT pin_id/i.test(q);
+ return Promise.resolve(pinRows);
+ }
+ 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),
+}));
+
+const { default: handler } = await import('../../api/irl/agent-summary.js');
+
+function makeReq() {
+ return { url: '/api/irl/agent-summary?mine=1', method: 'GET', headers: { host: 'x' }, query: { mine: '1' } };
+}
+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 getSummary() {
+ const res = makeRes();
+ await handler(makeReq(), res);
+ let body = null;
+ try { body = JSON.parse(res._body); } catch { /* body stays null for a non-JSON response */ }
+ return { res, body };
+}
+
+// A fixed "now" so online-window math is deterministic without Date mocking:
+// build interaction timestamps relative to the moment the test asserts.
+const minsAgo = (m) => new Date(Date.now() - m * 60 * 1000).toISOString();
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ ranWithIxJoin = false;
+ reg = { has_pins: true, has_ix: true };
+ pinRows = [];
+ sessionUser = { id: 'owner-uuid' };
+});
+
+describe('GET /api/irl/agent-summary — auth gate', () => {
+ it('401s an unauthenticated caller and never queries pins', async () => {
+ sessionUser = null;
+ const { res, body } = await getSummary();
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toMatch(/not authenticated/i);
+ // Only the (possible) probe must not run; no pin SELECT either.
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('GET /api/irl/agent-summary — graceful degradation (never 500)', () => {
+ it('returns empty agents when irl_pins does not exist yet', async () => {
+ reg = { has_pins: false, has_ix: false };
+ const { res, body } = await getSummary();
+ expect(res.statusCode).toBe(200);
+ expect(body).toEqual({ agents: [] });
+ // Guarded out before any pin query.
+ expect(sqlMock.mock.calls.some(([s]) => /FROM irl_pins p/i.test(Array.isArray(s) ? s.join(' ') : String(s)))).toBe(false);
+ });
+
+ it('runs the NO-interactions query form and zeroes counts when irl_interactions is absent (pre-C4)', async () => {
+ reg = { has_pins: true, has_ix: false };
+ pinRows = [{
+ pin_id: 'pin-1', agent_id: 'agent-1', lat: 1, lng: 2, heading: 0, caption: null,
+ avatar_url: '/a.glb', avatar_name: 'Aya', placed_at: minsAgo(60), expires_at: null,
+ view_count: 3, agent_name: 'Aya', solana_address: 'THREEsynthetic1111',
+ interaction_count: 0, last_interaction_at: null,
+ }];
+ const { res, body } = await getSummary();
+ expect(res.statusCode).toBe(200);
+ expect(ranWithIxJoin).toBe(false); // took the degraded query path
+ expect(body.agents).toHaveLength(1);
+ expect(body.agents[0].interaction_count).toBe(0);
+ expect(body.agents[0].last_interaction_at).toBeNull();
+ expect(body.agents[0].status).toBe('visible'); // live, no activity
+ });
+});
+
+describe('GET /api/irl/agent-summary — derived status', () => {
+ function pin(extra) {
+ return {
+ pin_id: 'p', agent_id: 'a', lat: 1, lng: 2, heading: 0, caption: null,
+ avatar_url: '/a.glb', avatar_name: 'A', placed_at: minsAgo(120), expires_at: null,
+ view_count: 0, agent_name: 'A', solana_address: null,
+ interaction_count: 0, last_interaction_at: null, ...extra,
+ };
+ }
+
+ it('joins interaction activity and marks a pin online when touched in the last 5 min', async () => {
+ reg = { has_pins: true, has_ix: true };
+ pinRows = [pin({ interaction_count: 7, last_interaction_at: minsAgo(2) })];
+ const { res, body } = await getSummary();
+ expect(res.statusCode).toBe(200);
+ expect(ranWithIxJoin).toBe(true); // took the joined query path
+ expect(body.agents[0].interaction_count).toBe(7);
+ expect(body.agents[0].status).toBe('online');
+ });
+
+ it('marks a pin visible when its last interaction is older than the online window', async () => {
+ pinRows = [pin({ interaction_count: 4, last_interaction_at: minsAgo(30) })];
+ const { body } = await getSummary();
+ expect(body.agents[0].status).toBe('visible');
+ });
+
+ it('marks an expired pin expired even if it had a recent interaction', async () => {
+ pinRows = [pin({ expires_at: minsAgo(1), last_interaction_at: minsAgo(1) })];
+ const { body } = await getSummary();
+ expect(body.agents[0].status).toBe('expired');
+ });
+});
diff --git a/tests/api/irl-pins-anchor-pose.test.js b/tests/api/irl-pins-anchor-pose.test.js
new file mode 100644
index 000000000..8e0e9a96b
--- /dev/null
+++ b/tests/api/irl-pins-anchor-pose.test.js
@@ -0,0 +1,188 @@
+// POST /api/irl/pins { anchor } — IRL-Live A2 anchor-pose persistence.
+//
+// A2 extends a placement from a 2D dot + compass heading to a full, reproducible
+// anchor pose: floor height, orientation, and the GPS-fix trust metadata. That
+// pose is the foundation A1 (WebXR anchors), A3 (everyone sees the agent in the
+// same real-world spot), and A4 (gyro-lock replay) all build on, so the POST
+// handler's capture + coercion of it is worth pinning down. These tests prove:
+// a present pose persists, an old client with no `anchor` still creates a valid
+// pin (NULL pose), and out-of-range values coerce/clamp rather than store noise.
+// The DB / auth / limiter / guardian 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()'s DDL, the density + owner-cap counts, and the INSERT each return
+// the right shape regardless of call order. The INSERT echoes its bound values
+// back as columns so success-path assertions see the EXACT coerced pose persisted.
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ // Density cap + per-owner cap both select count(*)::int — return 0 so neither trips.
+ if (/count\(\*\)::int/i.test(q)) {
+ return Promise.resolve([{ n: 0 }]);
+ }
+ if (/INSERT INTO irl_pins/i.test(q)) {
+ const [
+ user_id, agent_id, device_token, lat, lng, heading,
+ avatar_url, avatar_name, caption, x402_endpoint, expires_at,
+ anchor_height_m, anchor_yaw_deg, anchor_quat,
+ gps_accuracy_m, altitude_m, anchor_source, geocell7,
+ ] = values;
+ return Promise.resolve([{
+ id: 'pin-new', user_id, agent_id, device_token, lat, lng, heading,
+ avatar_url, avatar_name, caption, x402_endpoint,
+ placed_at: '2026-06-17T00:00:00Z', expires_at,
+ anchor_height_m, anchor_yaw_deg, anchor_quat,
+ gps_accuracy_m, altitude_m, anchor_source, geocell7,
+ view_count: 0, avatar_version: 0,
+ }]);
+ }
+ // CREATE TABLE / ALTER TABLE / CREATE INDEX from ensureTable(), and anything else.
+ return Promise.resolve([]);
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+// Anonymous by default (the common IRL placement); a test can flip to a session.
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+}));
+
+// All three placement limiters pass — A2 is about pose, not throttling.
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ irlPinIp: vi.fn(async () => ({ success: true })),
+ irlPinBurst: vi.fn(async () => ({ success: true })),
+ irlPinHourly: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+// Keep the AI content tier off so a captioned pin never reaches watsonx in CI.
+vi.mock('../../api/_lib/granite-guardian.js', () => ({
+ guardianConfig: () => ({ configured: false }),
+ assess: vi.fn(),
+ decide: vi.fn(),
+}));
+
+// Fire-and-forget realtime publish must never touch the network in a test.
+vi.mock('../../api/_lib/irl-publish.js', () => ({ publishIrlPin: vi.fn(async () => {}) }));
+
+const { default: handler } = await import('../../api/irl/pins.js');
+
+const ORIGIN = { lat: 40.7128, lng: -74.006 };
+
+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 basePin = () => ({
+ lat: ORIGIN.lat, lng: ORIGIN.lng, heading: 270,
+ avatarUrl: '/avatars/default.glb', avatarName: 'Scout',
+ deviceToken: 'device-A',
+});
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ sessionUser = null;
+});
+
+describe('POST /api/irl/pins — anchor pose persistence (A2)', () => {
+ it('stores a full pose when the client sends one', async () => {
+ const { res, body } = await post({
+ ...basePin(),
+ anchor: { heightM: 1.5, yawDeg: 270, quat: [0, 0, 0, 1], gpsAccuracyM: 8, altitudeM: 30.2, source: 'webxr' },
+ });
+ expect(res.statusCode).toBe(201);
+ const p = body.pin;
+ expect(p.anchor_height_m).toBe(1.5);
+ expect(p.anchor_yaw_deg).toBe(270);
+ expect(p.anchor_quat).toBe(JSON.stringify([0, 0, 0, 1]));
+ expect(p.gps_accuracy_m).toBe(8);
+ expect(p.altitude_m).toBe(30.2);
+ expect(p.anchor_source).toBe('webxr');
+ });
+
+ it('creates a valid pin with NULL pose for an old client (no anchor) — back-compat', async () => {
+ const { res, body } = await post(basePin());
+ expect(res.statusCode).toBe(201);
+ const p = body.pin;
+ expect(p.anchor_height_m).toBeNull();
+ expect(p.anchor_yaw_deg).toBeNull();
+ expect(p.anchor_quat).toBeNull();
+ expect(p.gps_accuracy_m).toBeNull();
+ expect(p.altitude_m).toBeNull();
+ // Source defaults to the gyro path, never null — A3 needs to know how it was placed.
+ expect(p.anchor_source).toBe('gyro-gps');
+ // The pin itself is fully valid.
+ expect(p.lat).toBeCloseTo(ORIGIN.lat, 9);
+ expect(p.permanent).toBe(false); // anonymous → 7-day expiry
+ });
+
+ it('coerces an absurd floor height (> ±50 m) to NULL rather than storing noise', async () => {
+ const { body: tooHigh } = await post({ ...basePin(), anchor: { heightM: 80, yawDeg: 10 } });
+ expect(tooHigh.pin.anchor_height_m).toBeNull();
+ const { body: tooLow } = await post({ ...basePin(), anchor: { heightM: -120, yawDeg: 10 } });
+ expect(tooLow.pin.anchor_height_m).toBeNull();
+ // A sane height on the boundary is kept.
+ const { body: ok } = await post({ ...basePin(), anchor: { heightM: -2.5, yawDeg: 10 } });
+ expect(ok.pin.anchor_height_m).toBe(-2.5);
+ });
+
+ it('clamps GPS accuracy to a sane 0–500 m band', async () => {
+ const { body: huge } = await post({ ...basePin(), anchor: { gpsAccuracyM: 9999, source: 'gyro-gps' } });
+ expect(huge.pin.gps_accuracy_m).toBe(500);
+ const { body: neg } = await post({ ...basePin(), anchor: { gpsAccuracyM: -5, source: 'gyro-gps' } });
+ expect(neg.pin.gps_accuracy_m).toBe(0);
+ const { body: ok } = await post({ ...basePin(), anchor: { gpsAccuracyM: 12.4, source: 'gyro-gps' } });
+ expect(ok.pin.gps_accuracy_m).toBe(12.4);
+ });
+
+ it('normalizes anchor yaw into 0–359°', async () => {
+ const { body: neg } = await post({ ...basePin(), anchor: { yawDeg: -10 } });
+ expect(neg.pin.anchor_yaw_deg).toBe(350);
+ const { body: over } = await post({ ...basePin(), anchor: { yawDeg: 730 } });
+ expect(over.pin.anchor_yaw_deg).toBe(10);
+ });
+
+ it('drops a malformed quaternion to NULL and only honours the known anchor sources', async () => {
+ // Wrong length / non-finite → NULL (we never store a half-orientation).
+ const { body: badQuat } = await post({ ...basePin(), anchor: { quat: [0, 0, 1], source: 'webxr' } });
+ expect(badQuat.pin.anchor_quat).toBeNull();
+ expect(badQuat.pin.anchor_source).toBe('webxr');
+ // The page-relative gyro variant (A3 down-weights it) is preserved verbatim.
+ const { body: rel } = await post({ ...basePin(), anchor: { source: 'gyro-gps:rel' } });
+ expect(rel.pin.anchor_source).toBe('gyro-gps:rel');
+ // Any unknown source collapses to the safe gyro default.
+ const { body: weird } = await post({ ...basePin(), anchor: { source: 'made-up' } });
+ expect(weird.pin.anchor_source).toBe('gyro-gps');
+ });
+
+ it('persists pose for an authenticated owner and marks the pin permanent', async () => {
+ sessionUser = { id: 'owner-uuid' };
+ const { res, body } = await post({
+ ...basePin(),
+ anchor: { heightM: 0, yawDeg: 90, gpsAccuracyM: 6, source: 'gyro-gps' },
+ });
+ expect(res.statusCode).toBe(201);
+ expect(body.pin.user_id).toBe('owner-uuid');
+ expect(body.pin.permanent).toBe(true); // signed-in → no expiry
+ expect(body.pin.anchor_yaw_deg).toBe(90);
+ expect(body.pin.gps_accuracy_m).toBe(6);
+ });
+});
diff --git a/tests/api/irl-report.test.js b/tests/api/irl-report.test.js
index a5ffc1414..7ebf6023e 100644
--- a/tests/api/irl-report.test.js
+++ b/tests/api/irl-report.test.js
@@ -40,6 +40,13 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
clientIp: () => '127.0.0.1',
}));
+// D1 realtime fan-out — spied so we can prove a threshold hide pushes a live
+// pin:remove into the pin's geocell room (and that a sub-threshold report does not).
+const publishIrlPin = vi.fn(async () => ({ delivered: false }));
+vi.mock('../../api/_lib/irl-publish.js', () => ({
+ publishIrlPin: (...a) => publishIrlPin(...a),
+}));
+
const { default: handler } = await import('../../api/irl/report.js');
function makeRes() {
@@ -62,7 +69,8 @@ async function report(body) {
beforeEach(() => {
sqlMock.mockClear();
- pinRow = { id: 'pin-1', user_id: null, device_token: 'owner-dev', hidden_at: null };
+ publishIrlPin.mockClear();
+ pinRow = { id: 'pin-1', user_id: null, device_token: 'owner-dev', hidden_at: null, lat: 40.7128, lng: -74.006 };
distinctReporters = 1;
hideUpdated = true;
sessionUser = null;
@@ -99,6 +107,31 @@ describe('POST /api/irl/report', () => {
expect(body.hidden).toBe(true);
});
+ it('emits a D1 pin:remove into the geocell room when the threshold hides a pin', async () => {
+ distinctReporters = 3;
+ await report({ pinId: 'pin-1', reason: 'harassment', deviceToken: 'dev-Z' });
+ expect(publishIrlPin).toHaveBeenCalledTimes(1);
+ const [type, geocell, payload] = publishIrlPin.mock.calls[0];
+ expect(type).toBe('pin:remove');
+ expect(typeof geocell).toBe('string');
+ expect(geocell.length).toBeGreaterThan(0);
+ expect(payload).toEqual({ id: 'pin-1' });
+ });
+
+ it('does NOT emit a pin:remove for a sub-threshold report', async () => {
+ distinctReporters = 1;
+ await report({ pinId: 'pin-1', reason: 'spam', deviceToken: 'dev-X' });
+ expect(publishIrlPin).not.toHaveBeenCalled();
+ });
+
+ it('does NOT re-emit pin:remove when the guarded hide UPDATE flips nothing (race)', async () => {
+ distinctReporters = 3;
+ hideUpdated = false; // a concurrent report already set hidden_at
+ const { body } = await report({ pinId: 'pin-1', reason: 'scam', deviceToken: 'dev-W' });
+ expect(body.hidden).toBe(false);
+ expect(publishIrlPin).not.toHaveBeenCalled();
+ });
+
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' });
diff --git a/tests/irl-net-presence.test.js b/tests/irl-net-presence.test.js
new file mode 100644
index 000000000..4374fbd77
--- /dev/null
+++ b/tests/irl-net-presence.test.js
@@ -0,0 +1,55 @@
+// D2 — the client's presence derivation. _emitPresence() turns the room's live
+// `viewers` MapSchema into the { count, viewers } the HUD reads: count is the whole
+// crowd (self included), but the rendered viewer list is ONLY other opted-in
+// ghosts (self + count-only entries filtered out, so a marker is never drawn for
+// someone who didn't opt to be seen, nor for yourself).
+
+import { describe, it, expect } from 'vitest';
+
+import { IrlNet } from '../src/irl-net.js';
+
+function viewer(over = {}) {
+ return { lat: 1, lng: 2, heading: 0, avatar: '', ghost: false, ...over };
+}
+
+// Stand up an IrlNet with a fake live room whose state.viewers is a plain Map
+// (same forEach(value, key) shape as a colyseus MapSchema).
+function netWith(entries, selfId) {
+ const net = new IrlNet({ lat: 0, lng: 0, url: '' });
+ net.room = { sessionId: selfId, state: { viewers: new Map(entries) } };
+ let captured = null;
+ net.on('presence', (p) => { captured = p; });
+ net._emitPresence();
+ return captured;
+}
+
+describe('IrlNet._emitPresence', () => {
+ it('counts everyone but renders only OTHER opted-in ghosts', () => {
+ const p = netWith([
+ ['self', viewer({ ghost: true })], // me — counted, never rendered
+ ['a', viewer({ ghost: true, avatar: 'a.glb', glat: undefined, lat: 10, lng: 20, heading: 90 })],
+ ['b', viewer({ ghost: false })], // count-only — never rendered
+ ], 'self');
+
+ expect(p.count).toBe(3);
+ expect(p.viewers).toHaveLength(1);
+ expect(p.viewers[0]).toMatchObject({ id: 'a', glat: 10, glng: 20, heading: 90, avatar: 'a.glb', ghost: true });
+ });
+
+ it('emits a zero/empty payload cleanly when only self is present', () => {
+ const p = netWith([['self', viewer({ ghost: true })]], 'self');
+ expect(p.count).toBe(1);
+ expect(p.viewers).toEqual([]);
+ });
+});
+
+describe('IrlNet.heartbeat / setGhost guards', () => {
+ it('are safe no-ops when no live socket is present', () => {
+ const net = new IrlNet({ lat: 0, lng: 0, url: '' });
+ expect(() => net.heartbeat(123)).not.toThrow();
+ // setGhost still records intent for the next connect, even offline.
+ net.setGhost(true, 'x.glb');
+ expect(net.ghost).toBe(true);
+ expect(net.avatar).toBe('x.glb');
+ });
+});
diff --git a/tests/irl-presence.test.js b/tests/irl-presence.test.js
new file mode 100644
index 000000000..820b4d1bf
--- /dev/null
+++ b/tests/irl-presence.test.js
@@ -0,0 +1,142 @@
+// D2 live viewer presence — exercises the real IrlRoom presence logic (coarse
+// jitter, heartbeat, set_ghost, reaper, leave) and the irl-net presence derivation
+// directly, without booting a Colyseus transport. The room methods operate on a
+// plain IrlState/MapSchema, so we drive them on a lightly-initialized room.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+
+import { IrlRoom } from '../multiplayer/src/rooms/IrlRoom.js';
+import { IrlState, IrlViewer } from '../multiplayer/src/irl-schemas.js';
+import { encodeGeohash, decodeGeohashBounds } from '../multiplayer/src/geohash.js';
+
+// A cell somewhere ordinary (San Francisco-ish) for coordinate assertions.
+const LAT = 37.7749;
+const LNG = -122.4194;
+const CELL = encodeGeohash(LAT, LNG, 6);
+
+function makeRoom(cell = CELL) {
+ const room = new IrlRoom();
+ room.geocell = cell;
+ room.state = new IrlState();
+ room.state.geocell = cell;
+ return room;
+}
+function client(sessionId, userData = {}) {
+ return { sessionId, userData };
+}
+
+describe('IrlViewer schema (D2 append-only fields)', () => {
+ it('carries the new presence fields with safe defaults', () => {
+ const v = new IrlViewer();
+ expect(v).toMatchObject({ id: '', lat: 0, lng: 0, agentId: '', heading: 0, avatar: '', ghost: false, tsServer: 0 });
+ });
+});
+
+describe('IrlRoom presence — join', () => {
+ let room;
+ beforeEach(() => { room = makeRoom(); });
+
+ it('adds a counted-only viewer by default (no ghost, no avatar)', () => {
+ room.onJoin(client('s1'), { lat: LAT, lng: LNG, agent: 'agent-1' });
+ expect(room.state.viewers.size).toBe(1);
+ const v = room.state.viewers.get('s1');
+ expect(v.id).toBe('s1');
+ expect(v.ghost).toBe(false);
+ expect(v.avatar).toBe('');
+ expect(v.agentId).toBe('agent-1');
+ expect(v.tsServer).toBeGreaterThan(0);
+ });
+
+ it('NEVER stores precise GPS — snaps to the cell centre + bounded jitter, inside the cell', () => {
+ room.onJoin(client('s1'), { lat: LAT, lng: LNG });
+ const v = room.state.viewers.get('s1');
+ // Privacy: the stored coordinate is not the precise input.
+ expect(v.lat).not.toBe(LAT);
+ expect(v.lng).not.toBe(LNG);
+ // ...and it stays inside the precision-6 cell it claims.
+ const b = decodeGeohashBounds(CELL);
+ expect(v.lat).toBeGreaterThanOrEqual(b.latMin);
+ expect(v.lat).toBeLessThanOrEqual(b.latMax);
+ expect(v.lng).toBeGreaterThanOrEqual(b.lngMin);
+ expect(v.lng).toBeLessThanOrEqual(b.lngMax);
+ });
+
+ it('snaps a neighbour-cell viewer to THEIR own cell, not the room centre', () => {
+ // A point ~2 cells east still joins this room (3x3 window) but must be placed
+ // in its own cell, never the room's centre cell.
+ const farLng = LNG + 0.05;
+ const ownCell = encodeGeohash(LAT, farLng, 6);
+ expect(ownCell).not.toBe(CELL);
+ room.onJoin(client('s2'), { lat: LAT, lng: farLng });
+ const v = room.state.viewers.get('s2');
+ const b = decodeGeohashBounds(ownCell);
+ expect(v.lng).toBeGreaterThanOrEqual(b.lngMin);
+ expect(v.lng).toBeLessThanOrEqual(b.lngMax);
+ });
+
+ it('stores an avatar + ghost flag ONLY when the viewer opted in', () => {
+ room.onJoin(client('opt'), { lat: LAT, lng: LNG, ghost: true, avatar: 'https://cdn/x.glb' });
+ const v = room.state.viewers.get('opt');
+ expect(v.ghost).toBe(true);
+ expect(v.avatar).toBe('https://cdn/x.glb');
+
+ room.onJoin(client('noopt'), { lat: LAT, lng: LNG, ghost: false, avatar: 'https://cdn/y.glb' });
+ expect(room.state.viewers.get('noopt').avatar).toBe('');
+ });
+
+ it('clamps heading to an integer 0–359 bearing', () => {
+ room.onJoin(client('h'), { lat: LAT, lng: LNG, heading: 725.6 });
+ expect(room.state.viewers.get('h').heading).toBe(6); // 725.6 → round 726 → 6
+ });
+});
+
+describe('IrlRoom presence — heartbeat / set_ghost / leave', () => {
+ let room;
+ beforeEach(() => {
+ room = makeRoom();
+ room.onJoin(client('s1'), { lat: LAT, lng: LNG });
+ });
+
+ it('heartbeat refreshes tsServer and heading without moving the marker', () => {
+ const v = room.state.viewers.get('s1');
+ const lat0 = v.lat, lng0 = v.lng;
+ v.tsServer = 1; // backdate
+ room._handleHeartbeat(client('s1'), { heading: 90 });
+ expect(v.heading).toBe(90);
+ expect(v.tsServer).toBeGreaterThan(1);
+ expect(v.lat).toBe(lat0); // position is fixed at join time
+ expect(v.lng).toBe(lng0);
+ });
+
+ it('set_ghost flips the opt-in live and clears the avatar on opt-out', () => {
+ room._handleSetGhost(client('s1'), { ghost: true, avatar: 'https://cdn/a.glb' });
+ expect(room.state.viewers.get('s1').ghost).toBe(true);
+ expect(room.state.viewers.get('s1').avatar).toBe('https://cdn/a.glb');
+ room._handleSetGhost(client('s1'), { ghost: false, avatar: 'https://cdn/a.glb' });
+ expect(room.state.viewers.get('s1').ghost).toBe(false);
+ expect(room.state.viewers.get('s1').avatar).toBe('');
+ });
+
+ it('onLeave removes the viewer', () => {
+ room.onLeave(client('s1'));
+ expect(room.state.viewers.has('s1')).toBe(false);
+ });
+
+ it('a heartbeat for an unknown session is a safe no-op', () => {
+ expect(() => room._handleHeartbeat(client('ghost'), { heading: 1 })).not.toThrow();
+ expect(room.state.viewers.size).toBe(1);
+ });
+});
+
+describe('IrlRoom presence — reaper', () => {
+ it('drops only viewers whose last heartbeat is stale', () => {
+ const room = makeRoom();
+ room.onJoin(client('fresh'), { lat: LAT, lng: LNG });
+ room.onJoin(client('stale'), { lat: LAT, lng: LNG });
+ // Backdate 'stale' well past the 30 s window; 'fresh' stays current.
+ room.state.viewers.get('stale').tsServer = Date.now() - 60_000;
+ room._reapStaleViewers();
+ expect(room.state.viewers.has('fresh')).toBe(true);
+ expect(room.state.viewers.has('stale')).toBe(false);
+ });
+});
diff --git a/tests/irl-reactions.test.js b/tests/irl-reactions.test.js
new file mode 100644
index 000000000..677f1bc54
--- /dev/null
+++ b/tests/irl-reactions.test.js
@@ -0,0 +1,107 @@
+// D3 — ambient interaction-reaction policy (multiplayer/src/irl-reactions.js).
+//
+// The room turns a viewer's tap/pay/message into a `reaction` broadcast. These
+// tests pin the two rules that protect bystanders from spam without ever dropping a
+// high-signal event: (1) only the four known types fan out; (2) open/view are
+// debounced per (session, pin) on a fixed window, while pay/message NEVER are. The
+// helpers are pure (a plain Map ledger + an injected clock), so the policy is proven
+// with no Colyseus room and no real time.
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ REACTION_TYPES,
+ DEBOUNCED_TYPES,
+ REACTION_DEBOUNCE_MS,
+ isReactionType,
+ reactionAllowed,
+ pruneReactionLedger,
+} from '../multiplayer/src/irl-reactions.js';
+
+describe('isReactionType', () => {
+ it('accepts exactly the four interaction types', () => {
+ for (const t of ['open', 'view', 'pay', 'message']) expect(isReactionType(t)).toBe(true);
+ expect([...REACTION_TYPES].sort()).toEqual(['message', 'open', 'pay', 'view']);
+ });
+
+ it('rejects unknown / malformed types', () => {
+ for (const t of ['', 'paid', 'PAY', 'like', 'follow', null, undefined, 0, {}]) {
+ expect(isReactionType(t)).toBe(false);
+ }
+ });
+});
+
+describe('reactionAllowed — open/view debounce', () => {
+ it('allows the first glance, suppresses a repeat inside the window, allows it after', () => {
+ const ledger = new Map();
+ const t0 = 1_000_000;
+ // First view from this session on this pin → fans out.
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'view', t0)).toBe(true);
+ // A jittery re-tap 1s later → suppressed.
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'view', t0 + 1000)).toBe(false);
+ // Just before the window closes → still suppressed.
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'view', t0 + REACTION_DEBOUNCE_MS - 1)).toBe(false);
+ // After the window → a deliberate re-glance fans out again.
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'view', t0 + REACTION_DEBOUNCE_MS)).toBe(true);
+ });
+
+ it('debounces open and view as the same noisy class', () => {
+ expect([...DEBOUNCED_TYPES].sort()).toEqual(['open', 'view']);
+ const ledger = new Map();
+ const t0 = 5_000;
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'open', t0)).toBe(true);
+ // open and view share a ledger key (session+pin), so an immediate view is gated too.
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'view', t0 + 100)).toBe(false);
+ });
+
+ it('scopes the debounce per session and per pin — never across them', () => {
+ const ledger = new Map();
+ const t0 = 0;
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'view', t0)).toBe(true);
+ // Different viewer, same pin → independent.
+ expect(reactionAllowed(ledger, 's2', 'pinA', 'view', t0)).toBe(true);
+ // Same viewer, different pin → independent.
+ expect(reactionAllowed(ledger, 's1', 'pinB', 'view', t0)).toBe(true);
+ // The original pair is still gated.
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'view', t0 + 10)).toBe(false);
+ });
+});
+
+describe('reactionAllowed — pay/message are never debounced', () => {
+ it('always fans out a pay, even back to back from the same viewer/pin', () => {
+ const ledger = new Map();
+ const t0 = 42;
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'pay', t0)).toBe(true);
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'pay', t0)).toBe(true);
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'pay', t0 + 1)).toBe(true);
+ // And it never writes the debounce ledger, so it can't gate a later glance.
+ expect(ledger.size).toBe(0);
+ });
+
+ it('always fans out a message', () => {
+ const ledger = new Map();
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'message', 0)).toBe(true);
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'message', 0)).toBe(true);
+ expect(ledger.size).toBe(0);
+ });
+
+ it('rejects an unknown type regardless of the ledger', () => {
+ const ledger = new Map();
+ expect(reactionAllowed(ledger, 's1', 'pinA', 'spam', 0)).toBe(false);
+ });
+});
+
+describe('pruneReactionLedger', () => {
+ it('drops only entries older than the window, keeps live ones', () => {
+ const ledger = new Map();
+ const now = 1_000_000;
+ ledger.set('s1 pinA', now - REACTION_DEBOUNCE_MS); // exactly aged out
+ ledger.set('s1 pinB', now - REACTION_DEBOUNCE_MS - 5000); // long expired
+ ledger.set('s2 pinA', now - 1000); // still live
+ pruneReactionLedger(ledger, now);
+ expect(ledger.has('s1 pinA')).toBe(false);
+ expect(ledger.has('s1 pinB')).toBe(false);
+ expect(ledger.has('s2 pinA')).toBe(true);
+ expect(ledger.size).toBe(1);
+ });
+});