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: onboarding + room-anchor updates, GPS lifecycle tests, floor/room anchor + reap test updates

nirholas8a57f895135a
diff --git a/pages/irl.html b/pages/irl.html
index 748e1f1b8..a187a1b3f 100644
--- a/pages/irl.html
+++ b/pages/irl.html
@@ -134,6 +134,7 @@
padding: 6px 0;
}
.irl-back:hover { color: var(--text); }
+ .irl-back:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 6px; }
.irl-back svg { flex-shrink: 0; }
.irl-topbar-center {
@@ -378,6 +379,7 @@
}
#irl-camera-btn:active:not(:disabled) { transform: translateY(0); }
#irl-camera-btn:disabled { opacity: 0.4; cursor: not-allowed; }
+ #irl-camera-btn:focus-visible { outline: 2px solid #000; outline-offset: -4px; box-shadow: 0 0 0 4px rgba(255,255,255,0.9); }
#irl-camera-btn.is-active {
background: rgba(74,222,128,0.15);
color: var(--green);
@@ -424,6 +426,7 @@
background: rgba(255,255,255,0.1);
}
.irl-pill-btn:disabled { opacity: 0.35; cursor: not-allowed; }
+ .irl-pill-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
/* Touch devices: every fixed control meets the 44×44 Apple HIG tap target. */
@media (hover: none) {
.irl-pill-btn { min-height: 44px; }
@@ -616,6 +619,7 @@
}
.irl-obj-btn:hover { color: var(--text); border-color: var(--border-hi); }
.irl-obj-btn:active { transform: scale(0.95); }
+ .irl-obj-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.irl-obj-btn.active {
color: var(--text);
border-color: rgba(255,255,255,0.4);
@@ -1778,15 +1782,11 @@
}
/* ── Accessibility: shared keyboard focus ring (task 07) ───────────────
- Every interactive control surfaces the same crisp 2px ring on
- :focus-visible — keyboard navigation only, so a mouse/touch press never
- shows it. Grouped here (rather than per-element) so no control can be
- reached by Tab without a visible focus indicator. White on the dark / AR
- background clears non-text contrast comfortably. */
- #irl-camera-btn:focus-visible,
- .irl-pill-btn:focus-visible,
- .irl-obj-btn:focus-visible,
- .irl-back:focus-visible,
+ The same crisp 2px ring on :focus-visible (keyboard nav only) for the
+ interactive controls that lacked one — the hero button, pills, object
+ picker and topbar Back are styled individually just above. Grouped so no
+ sheet control can be Tab-reached without a visible focus indicator. White
+ on the dark sheets clears non-text contrast comfortably. */
.irl-sheet-close:focus-visible,
.irl-sheet-btn:focus-visible,
.irl-msg-send:focus-visible,
@@ -1798,9 +1798,6 @@
outline: 2px solid var(--accent);
outline-offset: 2px;
}
- /* The green Camera-On state needs the ring tinted so it stays visible
- against its own green border. */
- #irl-camera-btn.is-active:focus-visible { outline-color: var(--green); }
/* ── Reduced motion: still ambient/decorative UI loops (task 07) ───────
Continuous, purely-decorative animations are paused. Avatar movement is
@@ -1928,14 +1925,14 @@
<!-- Bottom panel -->
<footer class="irl-bottom">
<h1 class="irl-avatar-name" id="irl-avatar-name">Loading…</h1>
- <p class="irl-subtitle" id="irl-subtitle">Turn on camera to place in your space</p>
+ <p class="irl-subtitle" id="irl-subtitle">Turn on Camera AR, then tap Pin here to anchor your agent in real space.</p>
<p class="irl-status is-hidden" id="irl-status">
<span class="irl-status-spinner hidden" id="irl-spinner" aria-hidden="true"></span>
<span id="irl-status-text"></span>
</p>
- <button id="irl-camera-btn" type="button" disabled aria-busy="true">
+ <button id="irl-camera-btn" type="button" disabled aria-busy="true" aria-pressed="false">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M23 7 16 12l7 5V7z"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>
<span id="irl-camera-label">Camera AR</span>
</button>
@@ -2071,7 +2068,7 @@
<!-- Dimmed backdrop behind the inspect card — click to dismiss. Stays in the DOM
(opacity/pointer-events toggled via .is-open) so it can fade in and out. -->
<div id="irl-sheet-backdrop"></div>
-<div id="irl-sheet" role="dialog" aria-modal="false" aria-label="Nearby agent" tabindex="-1">
+<div id="irl-sheet" role="dialog" aria-modal="false" aria-labelledby="irl-sheet-name" tabindex="-1">
<div class="irl-sheet-handle" aria-hidden="true"></div>
<div class="irl-sheet-header">
<img id="irl-sheet-thumb" class="irl-sheet-thumb" alt="" hidden />
@@ -2111,10 +2108,10 @@
</div>
<!-- Report reason sheet (D4) — choose why, POST /api/irl/report, threshold-hide server-side -->
-<div id="irl-report-sheet" role="dialog" aria-modal="true" aria-label="Report this pin">
+<div id="irl-report-sheet" role="dialog" aria-modal="true" aria-labelledby="irl-report-title">
<div class="irl-sheet-handle" aria-hidden="true"></div>
<div class="irl-report-header">
- <h3>Report this pin</h3>
+ <h3 id="irl-report-title">Report this pin</h3>
<button class="irl-sheet-close" id="irl-report-close" type="button" aria-label="Close">×</button>
</div>
<p class="irl-report-sub">Tell us what’s wrong. Reports are reviewed; a pin is hidden once enough people flag it.</p>
@@ -2130,11 +2127,11 @@
</div>
<!-- Agent picker sheet — lists authenticated user's agents to switch which one is placed -->
-<div id="irl-agents-sheet" role="dialog" aria-modal="true" aria-label="My agents">
+<div id="irl-agents-sheet" role="dialog" aria-modal="true" aria-labelledby="irl-agents-title">
<div class="irl-sheet-handle" aria-hidden="true"></div>
<div class="irl-agents-header">
<div>
- <h3>My Agents</h3>
+ <h3 id="irl-agents-title">My Agents</h3>
</div>
<button class="irl-sheet-close" id="irl-agents-close" type="button" aria-label="Close">×</button>
</div>
diff --git a/src/irl.js b/src/irl.js
index ce9a87dc4..c971107df 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -73,6 +73,7 @@ import { loadInto } from './shared/async-state.js';
import { openMapPlacePicker } from './irl/map-place.js';
import { openPrivacyCenter, maybeShowFirstRunDisclosure, getDiscoveryPrecision } from './irl/privacy-center.js';
import { loadLeaflet } from './shared/leaflet-loader.js';
+import { initDiscovery } from './irl/discovery.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -5590,7 +5591,9 @@ function tick() {
renderer.render(scene, camera);
frameWatchdog(dt);
- xrViewer._rafId = requestAnimationFrame(tick);
+ // Decline to reschedule if a pause landed mid-frame (tab hidden / context lost),
+ // so the loop truly stops instead of resurrecting itself the next frame.
+ xrViewer._rafId = _renderPaused ? null : requestAnimationFrame(tick);
}
// ── Nudge-to-calibrate (A3) ────────────────────────────────────────────────
@@ -6047,6 +6050,17 @@ if (import.meta.env.DEV) {
log.info(`[irl] seeded ${n} synthetic pins for LOD stress test`);
return n;
};
+ // Dispose every synthetic pin and return the count cleared. Pair with
+ // __irlSeedPins to run seed→clear churn and confirm renderer.info.memory returns
+ // to baseline (the task-06 leak check) rather than climbing each cycle.
+ window.__irlClearSeed = () => {
+ const seeded = nearbyPins.filter(p => String(p.id).startsWith('dev-seed-'));
+ for (const p of seeded) disposePin(p);
+ nearbyPins = nearbyPins.filter(p => !String(p.id).startsWith('dev-seed-'));
+ updateNearbyBadge();
+ log.info(`[irl] cleared ${seeded.length} synthetic pins`);
+ return seeded.length;
+ };
window.__irlPerf = () => ({
tier: activeTier,
baseTier,
@@ -6057,6 +6071,9 @@ if (import.meta.env.DEV) {
hidden: nearbyPins.filter(p => p._lod === 'hidden').length,
drawsEstimate: _drawEstimate,
drawCalls: renderer.info.render.calls,
+ // GPU resource counts — the leak signal. Across repeated avatar swaps and
+ // seed/clear cycles these must return to baseline, not grow monotonically.
+ memory: { geometries: renderer.info.memory.geometries, textures: renderer.info.memory.textures },
queue: { active: glbQueue.active, pending: glbQueue.pending },
reservedContexts: window.__agent3dReservedContexts,
});
diff --git a/src/irl/discovery.js b/src/irl/discovery.js
index bc842f615..993330787 100644
--- a/src/irl/discovery.js
+++ b/src/irl/discovery.js
@@ -219,6 +219,77 @@ export function maybeFirstRun() {
}
const MODAL_CSS = `
+/* ── Designed discovery empty state ──────────────────────────────────────────
+ A centered, low-contrast "keep exploring" prompt for the common case of a
+ live-but-empty area. The container catches no pointer events (camera taps pass
+ through); only the CTA is interactive. Calm blue, never red/amber — visually
+ distinct from the error state (task 06). */
+.irl-dx-empty {
+ position: fixed; inset: 0; z-index: 11;
+ display: flex; align-items: center; justify-content: center;
+ pointer-events: none;
+ opacity: 0; transition: opacity .4s ease;
+}
+.irl-dx-empty[hidden] { display: none; }
+.irl-dx-empty.is-visible { opacity: 1; }
+.irl-dx-empty-card {
+ display: flex; flex-direction: column; align-items: center;
+ gap: 16px; text-align: center; padding: 0 24px;
+ /* Sit a touch above centre so the bottom panel never overlaps the CTA. */
+ transform: translateY(-7%);
+}
+.irl-dx-empty-pulse { position: relative; width: 56px; height: 56px; flex-shrink: 0; }
+.irl-dx-empty-pulse::before {
+ content: ''; position: absolute; left: 50%; top: 50%;
+ width: 12px; height: 12px; margin: -6px 0 0 -6px;
+ border-radius: 50%; background: #8ec5ff; box-shadow: 0 0 10px rgba(140,197,255,0.85);
+}
+.irl-dx-empty-pulse::after {
+ content: ''; position: absolute; inset: 0; border-radius: 50%;
+ border: 1.5px solid rgba(140,197,255,0.55);
+ animation: irl-dx-ripple 2.4s ease-out infinite;
+}
+@keyframes irl-dx-ripple {
+ 0% { transform: scale(0.32); opacity: 0.9; }
+ 100% { transform: scale(1); opacity: 0; }
+}
+.irl-dx-empty-hint {
+ margin: 0; max-width: 280px;
+ font: 600 14px/1.45 system-ui, sans-serif;
+ color: #c6d2e2; text-shadow: 0 1px 10px rgba(0,0,0,0.65);
+}
+.irl-dx-place {
+ pointer-events: auto; appearance: none; cursor: pointer;
+ border: 1px solid rgba(140,197,255,0.5);
+ background: rgba(20,30,48,0.72); color: #eaf4ff;
+ border-radius: 999px; padding: 11px 20px;
+ font: 600 13.5px system-ui, sans-serif;
+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
+ box-shadow: 0 6px 24px rgba(0,0,0,0.4);
+ transition: background .15s, border-color .15s, transform .12s;
+}
+.irl-dx-place:hover { background: rgba(30,44,68,0.88); border-color: rgba(140,197,255,0.8); }
+.irl-dx-place:active { transform: translateY(1px); }
+.irl-dx-place:focus-visible { outline: 2px solid #8ec5ff; outline-offset: 2px; }
+
+/* Re-openable "?" explainer affordance — below the topbar on the left, clear of
+ the joystick (bottom) and the perm chips (top-centre). */
+.irl-dx-help {
+ position: fixed; left: 12px; top: calc(env(safe-area-inset-top, 0px) + 58px);
+ z-index: 12; width: 30px; height: 30px; border-radius: 50%;
+ display: flex; align-items: center; justify-content: center;
+ appearance: none; cursor: pointer;
+ font: 700 15px system-ui, sans-serif; color: #aeb6c8;
+ background: rgba(18,26,40,0.7); border: 1px solid rgba(255,255,255,0.14);
+ -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
+ transition: background .15s, color .15s, transform .12s;
+}
+.irl-dx-help[hidden] { display: none; }
+.irl-dx-help:hover { background: rgba(30,40,58,0.88); color: #eaf4ff; }
+.irl-dx-help:active { transform: scale(0.94); }
+.irl-dx-help:focus-visible { outline: 2px solid #8ec5ff; outline-offset: 2px; }
+
+/* ── First-run explainer modal ──────────────────────────────────────────────── */
#irl-discovery-explainer {
position: fixed; inset: 0; z-index: 130;
display: flex; align-items: center; justify-content: center;
@@ -302,6 +373,8 @@ const MODAL_CSS = `
.irl-dx-learn:focus-visible { outline: 2px solid #7dd3fc; outline-offset: 3px; border-radius: 6px; }
@media (prefers-reduced-motion: reduce) {
#irl-discovery-explainer, .irl-dx-panel { transition: none; }
+ .irl-dx-empty { transition: opacity .001s; }
+ .irl-dx-empty-pulse::after { animation: none; opacity: 0.5; transform: scale(0.85); }
}
`;
diff --git a/src/irl/onboarding.js b/src/irl/onboarding.js
index f11f32f97..669ead2cf 100644
--- a/src/irl/onboarding.js
+++ b/src/irl/onboarding.js
@@ -81,7 +81,7 @@ function recoverySteps(kind) {
}
function unsupportedBody(kind) {
- if (kind === 'camera') return 'This device can’t open a camera here, so AR passthrough isn’t available — you can still explore your agent in orbit view.';
+ if (kind === 'camera') return 'This device can’t open a camera here, so the live camera view isn’t available — you can still explore your agent in orbit view.';
if (kind === 'motion') return 'This device doesn’t report motion, so look-around is off. Drag to orbit the scene instead.';
if (kind === 'location') return 'This device can’t share location, so pinning to real spots and nearby discovery are off — everything else still works.';
return 'This feature isn’t available on this device.';
diff --git a/src/irl/room-anchor.js b/src/irl/room-anchor.js
index 8ff8f0371..3e2855010 100644
--- a/src/irl/room-anchor.js
+++ b/src/irl/room-anchor.js
@@ -155,6 +155,49 @@ export function compassToYaw(deg) {
return -(deg * DEG);
}
+/**
+ * The absolute lat/lng an agent should be stored at, given its UNCHANGED
+ * room-frame offset and the room's (possibly recalibrated) origin. This is the
+ * inverse-to-geo twin of {@link agentWorldPosition} — where that projects an
+ * agent into the VIEWER's world frame, this re-derives the agent's GPS index so a
+ * proximity read stays consistent after the room moves. Used by the room-scoped
+ * calibrate to persist each agent's lat/lng without ever touching its relEast/
+ * relNorth, so the cluster's internal layout is preserved exactly.
+ * @returns {{ lat:number, lng:number }}
+ */
+export function pinAbsoluteFromOrigin({ originLat, originLng, originYawDeg = 0, relEast, relNorth }) {
+ const tn = localToTrueNorth(relEast, relNorth, originYawDeg);
+ return localToGeo(originLat, originLng, tn.east, tn.north);
+}
+
+/**
+ * Apply a one-gesture ROOM calibrate to a room's origin. The owner grabs the
+ * whole cluster and slides it by a true-north metre offset (dEast/dNorth) and/or
+ * twists it about the origin by dYawDeg. Because every agent is rigidly tied to
+ * the shared origin via its relEast/relNorth, moving the origin moves the entire
+ * cluster together with its internal layout intact — no per-agent shear. The
+ * agents' room-frame offsets are NOT changed here; only the origin translates and
+ * the frame rotates. Pair with {@link pinAbsoluteFromOrigin} to re-derive each
+ * agent's absolute lat/lng under the returned origin.
+ *
+ * @param {object} p
+ * @param {number} p.originLat current room origin latitude
+ * @param {number} p.originLng current room origin longitude
+ * @param {number} [p.originYawDeg=0] current room frame rotation vs true north
+ * @param {number} [p.dEastM=0] ground translation east, metres (true-north frame)
+ * @param {number} [p.dNorthM=0] ground translation north, metres
+ * @param {number} [p.dYawDeg=0] cluster rotation about the origin, degrees
+ * @returns {{ originLat:number, originLng:number, originYawDeg:number }}
+ */
+export function calibrateRoomOrigin({ originLat, originLng, originYawDeg = 0, dEastM = 0, dNorthM = 0, dYawDeg = 0 }) {
+ const moved = localToGeo(originLat, originLng, dEastM, dNorthM);
+ return {
+ originLat: moved.lat,
+ originLng: moved.lng,
+ originYawDeg: (((originYawDeg + dYawDeg) % 360) + 360) % 360,
+ };
+}
+
/**
* "Place an agent around me." Turns the placer's live pose (where they stand +
* which way the phone points) and a distance into a durable room-relative
diff --git a/tasks/irl-production/06-memory-gpu-hygiene.md b/tasks/irl-production/06-memory-gpu-hygiene.md
deleted file mode 100644
index df04059d5..000000000
--- a/tasks/irl-production/06-memory-gpu-hygiene.md
+++ /dev/null
@@ -1,75 +0,0 @@
-# Task 06 — Memory, GPU resource, and context-loss hygiene
-
-**Phase:** 1 (AR correctness) · **Effort:** M · **Files:** `src/irl.js`, `src/irl/load-queue.js`
-
-## Why
-IRL is a long-lived single-page session: users swap avatars, walk through dense
-pin areas, and leave the tab backgrounded. Three.js does not auto-free GPU
-resources — every undisposed geometry/material/texture/render-target is a leak
-that eventually crashes the WebGL context on mobile. A production AR app must run
-for an hour without degrading.
-
-## Read first (verify before fixing)
-- Avatar (re)load + clear — `src/irl.js:742-770` (`loadAvatar`, `_clearAvatar`, mixer handling)
-- Pin disposal — `src/irl.js:~1896-1905` (`disposePin`, `disposeObject3D`)
-- Impostor render targets — `src/irl.js:~2250-2260` (creation) + disposal site
-- Load queue + cancel — `src/irl/load-queue.js` (priority pump, `cancel()`)
-- LOD/eviction — `enforceLOD()` `src/irl.js:~3448-3550`
-- Renderer creation — `src/irl.js:150-158` (single WebGL context, per memory `irl-perf-e2`)
-
-## Scope — confirm, then fix
-
-1. **Animation mixer leak on avatar swap.** On hot-swap, confirm the old mixer is
- stopped (`stopAllAction()` / `uncacheRoot`) and detached before the new model
- loads, and that a **failed** load leaves the manager in a clean state (not a
- nulled mixer with orphaned clips). Fix any dangling references.
-
-2. **Impostor render-target / texture disposal order.** Before disposing a pin's
- `_impostorRT`, null the sprite material's texture reference so no live material
- points at a freed texture. Dispose RT + texture + sprite material/geometry.
-
-3. **Cancel in-flight loads on large distance jumps.** When a pin's live camera
- distance jumps far (teleport, unlock snap, walking past), cancel its queued/
- in-flight GLB load so a now-distant pin doesn't hold a slot ahead of the nearest
- one. Use the queue's `cancel()` hook from `enforceLOD()`.
-
-4. **WebGL context-loss recovery.** Add `webglcontextlost`/`webglcontextrestored`
- handlers: preventDefault on loss, pause the tick, and on restore rebuild what's
- needed (or show a designed "tap to reload AR" recovery state). Today a context
- loss likely leaves a black canvas with no recovery.
-
-5. **Backgrounded-tab throttling.** On `visibilitychange` to hidden, pause the RAF /
- stop the camera track to save battery and avoid sensor churn; resume cleanly on
- return. Confirm no leak across pause/resume cycles.
-
-## Implementation guidance
-- There is an existing DEV harness (`__irlSeedPins(30)`, `__irlPerf()` per memory
- `irl-perf-e2`). Use it to drive churn and watch `renderer.info.memory`
- (geometries/textures) across repeated swaps + seed/clear cycles — counts must
- return to baseline, not climb.
-
-## Out of scope
-The LOD band tuning itself (shipped); adding new visual effects.
-
-## Definition of done
-- [ ] Repeated avatar swaps and `__irlSeedPins`/clear cycles return
- `renderer.info.memory` to baseline (no monotonic growth) — paste the numbers.
-- [ ] Impostor RTs/textures provably disposed; no console GL warnings.
-- [ ] Context loss recovers (or shows a designed recovery), never a silent black canvas.
-- [ ] Backgrounding pauses/resumes cleanly with no leak.
-- [ ] esbuild clean; `npm test` green; changelog entry if user-visible (e.g. "AR runs
- stably in long sessions").
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/irl-production/06-memory-gpu-hygiene.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tests/api/irl-reap-cron.test.js b/tests/api/irl-reap-cron.test.js
index b8290fa69..c8b278a3b 100644
--- a/tests/api/irl-reap-cron.test.js
+++ b/tests/api/irl-reap-cron.test.js
@@ -16,7 +16,13 @@ vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));
-const { default: handler } = await import('../../api/cron/irl-reap.js');
+const { sendOpsAlert } = await import('../../api/_lib/alerts.js');
+const {
+ default: handler,
+ isReapSpike,
+ reapTotal,
+ REAP_SPIKE_THRESHOLD,
+} = await import('../../api/cron/irl-reap.js');
process.env.CRON_SECRET = 'test-cron-secret';
@@ -38,8 +44,37 @@ function makeReqRes() {
return { req, res };
}
+describe('reapTotal / isReapSpike (pure)', () => {
+ it('sums the three sweep counts, treating missing fields as 0', () => {
+ expect(reapTotal({ pins: 2, reports: 1, interactions: 3 })).toBe(6);
+ expect(reapTotal({ pins: 5 })).toBe(5);
+ expect(reapTotal({})).toBe(0);
+ expect(reapTotal(null)).toBe(0);
+ expect(reapTotal(undefined)).toBe(0);
+ });
+
+ it('is not a spike at steady-state volume', () => {
+ expect(isReapSpike({ pins: 3, reports: 1, interactions: 12 })).toBe(false);
+ expect(isReapSpike({})).toBe(false);
+ });
+
+ it('trips exactly at the threshold and above', () => {
+ expect(isReapSpike({ pins: REAP_SPIKE_THRESHOLD })).toBe(true);
+ expect(isReapSpike({ pins: REAP_SPIKE_THRESHOLD - 1 })).toBe(false);
+ expect(isReapSpike({ pins: REAP_SPIKE_THRESHOLD + 500 })).toBe(true);
+ });
+
+ it('honors a custom threshold so callers can tune sensitivity', () => {
+ expect(isReapSpike({ pins: 10 }, 10)).toBe(true);
+ expect(isReapSpike({ pins: 9 }, 10)).toBe(false);
+ });
+});
+
describe('irl-reap cron', () => {
- beforeEach(() => sqlMock.mockReset());
+ beforeEach(() => {
+ sqlMock.mockReset();
+ sendOpsAlert.mockClear();
+ });
it('returns 200 (not 500) when no table exists yet — nothing to reap', async () => {
// to_regclass probe → all NULL. No DELETE should ever be issued.
@@ -121,6 +156,38 @@ describe('irl-reap cron', () => {
expect(res.body).toMatchObject({ ok: true, reapedPins: 0, reapedReports: 2, reapedInteractions: 1 });
});
+ it('fires an ops alert when one run deletes an anomalous number of rows', async () => {
+ const aged = Array.from({ length: REAP_SPIKE_THRESHOLD + 1 }, (_, i) => ({ id: `ix${i}` }));
+ sqlMock
+ .mockResolvedValueOnce([{ pins: 'irl_pins', reports: 'irl_pin_reports', interactions: 'irl_interactions' }]) // probe
+ .mockResolvedValueOnce([]) // pins delete
+ .mockResolvedValueOnce([]) // reports delete
+ .mockResolvedValueOnce([]) // interactions orphan delete
+ .mockResolvedValueOnce(aged); // interactions age-out delete — anomalous volume
+
+ const { req, res } = makeReqRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(sendOpsAlert).toHaveBeenCalledTimes(1);
+ expect(sendOpsAlert.mock.calls[0][0]).toBe('IRL reaper spike');
+ });
+
+ it('does NOT alert on a normal-volume sweep', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ pins: 'irl_pins', reports: 'irl_pin_reports', interactions: 'irl_interactions' }]) // probe
+ .mockResolvedValueOnce([{ id: 'p1' }]) // pins delete
+ .mockResolvedValueOnce([]) // reports delete
+ .mockResolvedValueOnce([]) // interactions orphan delete
+ .mockResolvedValueOnce([{ id: 'ix1' }]); // interactions age-out delete
+
+ const { req, res } = makeReqRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(sendOpsAlert).not.toHaveBeenCalled();
+ });
+
it('rejects an unauthenticated request with 401', async () => {
const { req, res } = makeReqRes();
req.headers.authorization = 'Bearer wrong';
diff --git a/tests/irl-floor-anchor.test.js b/tests/irl-floor-anchor.test.js
index fffac1564..c81d7e853 100644
--- a/tests/irl-floor-anchor.test.js
+++ b/tests/irl-floor-anchor.test.js
@@ -11,8 +11,8 @@
import { describe, it, expect } from 'vitest';
-import { yawDegFromQuat, anchorPoseToPin } from '../src/irl/floor-anchor.js';
-import { geoToLocal } from '../src/irl/room-anchor.js';
+import { yawDegFromQuat, anchorPoseToPin, roomRelFromGeo, roomPlacementFromHit } from '../src/irl/floor-anchor.js';
+import { geoToLocal, agentWorldPosition, roomOriginWorld } from '../src/irl/room-anchor.js';
const ORIGIN = { lat: 37.7749, lng: -122.4194 }; // arbitrary; math is origin-relative
const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;
@@ -140,6 +140,91 @@ describe('anchor_quat precision survives the persist → render-back round-trip'
});
});
+// ── WebXR → room frame (R3) ──────────────────────────────────────────────────
+// A floor hit must land in the SHARED room frame, not a standalone GPS pin, so a
+// WebXR-placed agent renders identically for every viewer. These pin the two new
+// write-path conversions: roomRelFromGeo (lat/lng → exact room offset, used by the
+// calibrate/refine PATCH) and roomPlacementFromHit (XR hit pose → room placement).
+describe('roomRelFromGeo', () => {
+ const QUAT = yawQuat(0);
+
+ it('inverts anchorPoseToPin: a point 2 m E / 3 m N of the origin → rel (2, 3)', () => {
+ const pin = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 2, y: 0, z: -3, quat: QUAT });
+ const rel = roomRelFromGeo({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, lat: pin.lat, lng: pin.lng });
+ expect(near(rel.relEast, 2, 1e-3)).toBe(true);
+ expect(near(rel.relNorth, 3, 1e-3)).toBe(true);
+ });
+
+ it('a rotated room (originYawDeg) round-trips back through agentWorldPosition', () => {
+ // Store an offset in a 30°-rotated room, then render it from the origin: the
+ // world position must match the un-rotated true-north offset the point implies.
+ const originYawDeg = 30;
+ const trueEast = 4, trueNorth = -1; // arbitrary true-north metres from origin
+ const { lat, lng } = anchorPoseToPin({
+ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: trueEast, y: 0, z: trueNorth, quat: QUAT,
+ }); // note z passed as north here is +trueNorth → world north is −z, see below
+ const rel = roomRelFromGeo({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, originYawDeg, lat, lng });
+ // Re-render from the origin (viewer ON the origin → originWorld = {0,0}).
+ const world = agentWorldPosition({ originWorld: { x: 0, z: 0 }, relEast: rel.relEast, relNorth: rel.relNorth, originYawDeg });
+ // anchorPoseToPin treated z as the SOUTH axis (north = −z), so the stored point
+ // is trueEast east and −trueNorth north; agentWorldPosition must reproduce that.
+ expect(near(world.x, trueEast, 1e-3)).toBe(true);
+ expect(near(world.z, trueNorth, 1e-3)).toBe(true);
+ });
+});
+
+describe('roomPlacementFromHit', () => {
+ const QUAT = yawQuat(0);
+
+ it('a hit placed by a viewer standing ON the origin re-renders at the same spot', () => {
+ // Viewer == origin: a hit 2 m east / 3 m north (z = −3) of them must store as
+ // rel (2, 3) and render back to world (2, 0, −3) for that same viewer.
+ const p = roomPlacementFromHit({
+ originLat: ORIGIN.lat, originLng: ORIGIN.lng,
+ viewerLat: ORIGIN.lat, viewerLng: ORIGIN.lng,
+ x: 2, y: -1.4, z: -3, quat: QUAT,
+ });
+ expect(near(p.relEast, 2, 1e-6)).toBe(true);
+ expect(near(p.relNorth, 3, 1e-6)).toBe(true);
+ const world = agentWorldPosition({ originWorld: { x: 0, z: 0 }, relEast: p.relEast, relNorth: p.relNorth });
+ expect(near(world.x, 2, 1e-6)).toBe(true);
+ expect(near(world.z, -3, 1e-6)).toBe(true);
+ expect(p.heightM).toBe(-1.4); // real floor height rides through
+ expect(p.source).toBe('webxr');
+ });
+
+ it('folds in the placer offset: an off-origin viewer’s hit lands where they aimed', () => {
+ // The placer stands 5 m east of the origin and drops an agent 2 m north of
+ // themselves. Rendered for that same placer (viewer at world 0), the agent must
+ // sit at their local hit (x=0, z=−2) — proving the GPS offset is folded in.
+ const viewer = geoToLocal(ORIGIN.lat, ORIGIN.lng, 0, 0); // unused; build viewer geo below
+ void viewer;
+ const east5 = anchorPoseToPin({ originLat: ORIGIN.lat, originLng: ORIGIN.lng, x: 5, y: 0, z: 0, quat: QUAT });
+ const p = roomPlacementFromHit({
+ originLat: ORIGIN.lat, originLng: ORIGIN.lng,
+ viewerLat: east5.lat, viewerLng: east5.lng,
+ x: 0, y: -1.4, z: -2, quat: QUAT,
+ });
+ // Stored offset is from the ORIGIN: 5 m east, 2 m north.
+ expect(near(p.relEast, 5, 1e-3)).toBe(true);
+ expect(near(p.relNorth, 2, 1e-3)).toBe(true);
+ // Render for the placer (who is 5 m east of origin): agent lands at their hit.
+ const originWorld = roomOriginWorld(east5.lat, east5.lng, ORIGIN.lat, ORIGIN.lng);
+ const world = agentWorldPosition({ originWorld, relEast: p.relEast, relNorth: p.relNorth });
+ expect(near(world.x, 0, 1e-3)).toBe(true);
+ expect(near(world.z, -2, 1e-3)).toBe(true);
+ });
+
+ it('heading comes from the surface quat, normalised to [0,360)', () => {
+ const p = roomPlacementFromHit({
+ originLat: ORIGIN.lat, originLng: ORIGIN.lng,
+ viewerLat: ORIGIN.lat, viewerLng: ORIGIN.lng,
+ x: 0, y: 0, z: 0, quat: yawQuat(270),
+ });
+ expect(p.relYawDeg).toBe(270); // −90° from atan2, normalised
+ });
+});
+
describe('round-trip property: anchorPoseToPin then geoToLocal is identity', () => {
it('survives within 1e-6 for assorted offsets', () => {
for (const [x, z] of [[0, 0], [2, -3], [-4, 1], [12, 12], [-7.5, -2.25], [0.1, -0.1]]) {
diff --git a/tests/irl-gps-lifecycle.test.js b/tests/irl-gps-lifecycle.test.js
new file mode 100644
index 000000000..dc6973934
--- /dev/null
+++ b/tests/irl-gps-lifecycle.test.js
@@ -0,0 +1,95 @@
+// Pure GPS-lifecycle helpers (src/irl/gps-lifecycle.js).
+//
+// These pin two contracts the live AR code in src/irl.js depends on but can't
+// easily exercise on CI: telling the truth about a fix's accuracy, and the eased
+// progress that glides the camera from the gyro pivot to the precise GPS anchor on
+// the local→GPS lock upgrade. Both are plain numbers in / numbers out — no DOM, no
+// Three.js, no clock — so the math is proven here directly.
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ gpsAccuracyBucket,
+ easeGpsTransition,
+ GPS_ACCURACY_PRECISE_M,
+ GPS_ACCURACY_COARSE_M,
+ GPS_TRANSITION_MS,
+} from '../src/irl/gps-lifecycle.js';
+
+describe('gpsAccuracyBucket', () => {
+ it('treats a tight fix (≤ threshold) as precise with no hint label', () => {
+ for (const m of [0, 5, 12, GPS_ACCURACY_PRECISE_M]) {
+ const b = gpsAccuracyBucket(m);
+ expect(b.level).toBe('precise');
+ expect(b.precise).toBe(true);
+ expect(b.label).toBe('');
+ expect(b.accuracyM).toBe(Math.round(m));
+ }
+ });
+
+ it('flags a mid-range fix as approximate and never claims precision', () => {
+ const b = gpsAccuracyBucket(40);
+ expect(b.level).toBe('approximate');
+ expect(b.precise).toBe(false);
+ expect(b.label).toContain('40');
+ expect(b.accuracyM).toBe(40);
+ });
+
+ it('flags a very noisy fix (> coarse threshold) as coarse with a low-accuracy note', () => {
+ const b = gpsAccuracyBucket(GPS_ACCURACY_COARSE_M + 30);
+ expect(b.level).toBe('coarse');
+ expect(b.precise).toBe(false);
+ expect(b.label.toLowerCase()).toContain('low');
+ expect(b.accuracyM).toBe(GPS_ACCURACY_COARSE_M + 30);
+ });
+
+ it('rounds the displayed metres but keeps the bucket boundary on the raw value', () => {
+ // 25.4 m rounds to 25 for display yet is past the precise threshold, so it must
+ // NOT be claimed precise — the boundary is tested against the raw reading.
+ const b = gpsAccuracyBucket(25.4);
+ expect(b.precise).toBe(false);
+ expect(b.accuracyM).toBe(25);
+ });
+
+ it('returns unknown (never precise, no label) for a missing/invalid reading', () => {
+ for (const v of [null, undefined, NaN, -1]) {
+ const b = gpsAccuracyBucket(v);
+ expect(b.level).toBe('unknown');
+ expect(b.precise).toBe(false);
+ expect(b.label).toBe('');
+ expect(b.accuracyM).toBe(null);
+ }
+ });
+});
+
+describe('easeGpsTransition', () => {
+ it('pins the endpoints exactly', () => {
+ expect(easeGpsTransition(0)).toBe(0);
+ expect(easeGpsTransition(1)).toBe(1);
+ });
+
+ it('clamps out-of-range progress so a long frame or paused tab cannot overshoot', () => {
+ expect(easeGpsTransition(-0.5)).toBe(0);
+ expect(easeGpsTransition(1.4)).toBe(1);
+ expect(easeGpsTransition(NaN)).toBe(0);
+ });
+
+ it('eases out — fast at the start, gentle at the end, always within [0,1]', () => {
+ const mid = easeGpsTransition(0.5);
+ expect(mid).toBeGreaterThan(0.5); // ease-out is ahead of linear at the midpoint
+ expect(mid).toBeLessThan(1);
+ // Monotonic increase across the curve.
+ let prev = -1;
+ for (let t = 0; t <= 1.0001; t += 0.1) {
+ const e = easeGpsTransition(t);
+ expect(e).toBeGreaterThanOrEqual(prev);
+ expect(e).toBeGreaterThanOrEqual(0);
+ expect(e).toBeLessThanOrEqual(1);
+ prev = e;
+ }
+ });
+
+ it('reaches 1 exactly when elapsed hits the configured duration', () => {
+ expect(easeGpsTransition(GPS_TRANSITION_MS / GPS_TRANSITION_MS)).toBe(1);
+ });
+});
diff --git a/tests/irl-room-anchor.test.js b/tests/irl-room-anchor.test.js
index 7f5b50dee..4bc5ecb59 100644
--- a/tests/irl-room-anchor.test.js
+++ b/tests/irl-room-anchor.test.js
@@ -21,6 +21,8 @@ import {
agentWorldPosition,
compassToYaw,
placeAround,
+ pinAbsoluteFromOrigin,
+ calibrateRoomOrigin,
} from '../src/irl/room-anchor.js';
const ORIGIN = { lat: 37.7749, lng: -122.4194 }; // arbitrary; math is origin-relative
@@ -187,3 +189,77 @@ describe('intra-room geometry is exact under GPS drift (the headline guarantee)'
expect(near(cW.x, -12 + 2, 1e-6)).toBe(true);
});
});
+
+describe('one-gesture room calibrate (calibrateRoomOrigin + pinAbsoluteFromOrigin)', () => {
+ // The canonical cluster: couch-agent 2 m east, wall-agent 2 m west of a
+ // true-north origin (the same scene as above, expressed as stored offsets).
+ const couch = { relEast: 2, relNorth: 0 };
+ const wall = { relEast: -2, relNorth: 0 };
+ const absOf = (origin, pin) => pinAbsoluteFromOrigin({
+ originLat: origin.originLat, originLng: origin.originLng,
+ originYawDeg: origin.originYawDeg ?? 0, relEast: pin.relEast, relNorth: pin.relNorth,
+ });
+ const base = { originLat: ORIGIN.lat, originLng: ORIGIN.lng, originYawDeg: 0 };
+
+ it('pinAbsoluteFromOrigin inverts agentWorldPosition through the same origin', () => {
+ // Project a pin into a viewer's frame, then re-derive its absolute coord from
+ // the origin — the round-trip must land back on the geodesy localToGeo gives.
+ const abs = absOf(base, couch);
+ const direct = localToGeo(base.originLat, base.originLng, couch.relEast, couch.relNorth);
+ expect(near(abs.lat, direct.lat, 1e-12)).toBe(true);
+ expect(near(abs.lng, direct.lng, 1e-12)).toBe(true);
+ });
+
+ it('a pure translation slides every agent by the same metre offset, layout intact', () => {
+ const before = { couch: absOf(base, couch), wall: absOf(base, wall) };
+ const next = calibrateRoomOrigin({ ...base, dEastM: 1.2, dNorthM: -0.4 });
+ expect(next.originYawDeg).toBe(0); // no rotation
+ const after = { couch: absOf(next, couch), wall: absOf(next, wall) };
+
+ // Each agent moved by exactly (+1.2 m E, −0.4 m N) from its old spot.
+ for (const tag of ['couch', 'wall']) {
+ const d = geoToLocal(base.originLat, base.originLng, after[tag].lat, after[tag].lng);
+ const d0 = geoToLocal(base.originLat, base.originLng, before[tag].lat, before[tag].lng);
+ expect(near(d.east - d0.east, 1.2, 1e-6)).toBe(true);
+ expect(near(d.north - d0.north, -0.4, 1e-6)).toBe(true);
+ }
+ // And they stay exactly 4 m apart on opposite sides — the cluster is rigid.
+ const sep = geoToLocal(after.wall.lat, after.wall.lng, after.couch.lat, after.couch.lng);
+ expect(near(sep.east, 4, 1e-6)).toBe(true);
+ });
+
+ it('a rotation about the origin preserves each agent’s distance and turns its bearing by dYaw', () => {
+ const next = calibrateRoomOrigin({ ...base, dYawDeg: 30 });
+ expect(next.originYawDeg).toBe(30);
+ // The origin itself didn't move (no translation).
+ expect(near(next.originLat, base.originLat, 1e-12)).toBe(true);
+ expect(near(next.originLng, base.originLng, 1e-12)).toBe(true);
+
+ const before = absOf(base, couch);
+ const after = absOf(next, couch);
+ const b = geoToLocal(base.originLat, base.originLng, before.lat, before.lng);
+ const a = geoToLocal(next.originLat, next.originLng, after.lat, after.lng);
+ // Distance from the origin is unchanged (rigid rotation).
+ expect(near(Math.hypot(a.east, a.north), Math.hypot(b.east, b.north), 1e-6)).toBe(true);
+ // Bearing advanced by exactly the rotation.
+ const bb = localToBearingDistance(b.east, b.north);
+ const ab = localToBearingDistance(a.east, a.north);
+ expect(near(((ab.bearingDeg - bb.bearingDeg + 540) % 360) - 180, 30, 1e-4)).toBe(true);
+ });
+
+ it('normalizes the new frame rotation into 0–359°', () => {
+ expect(calibrateRoomOrigin({ ...base, originYawDeg: 350, dYawDeg: 20 }).originYawDeg).toBe(10);
+ expect(calibrateRoomOrigin({ ...base, originYawDeg: 10, dYawDeg: -20 }).originYawDeg).toBe(350);
+ });
+
+ it('translate + rotate compose: the origin moves and the cluster twists in one call', () => {
+ const next = calibrateRoomOrigin({ ...base, dEastM: 3, dNorthM: 2, dYawDeg: -15 });
+ const moved = localToGeo(base.originLat, base.originLng, 3, 2);
+ expect(near(next.originLat, moved.lat, 1e-12)).toBe(true);
+ expect(near(next.originLng, moved.lng, 1e-12)).toBe(true);
+ expect(next.originYawDeg).toBe(345);
+ // Agent stays 2 m from the (now-moved) origin — rigid through the compound move.
+ const a = geoToLocal(next.originLat, next.originLng, absOf(next, couch).lat, absOf(next, couch).lng);
+ expect(near(Math.hypot(a.east, a.north), 2, 1e-6)).toBe(true);
+ });
+});