Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
IRL: GPS lifecycle + tap-pick modules, camera-FOV tests, report/sensor robustness updates
nirholasf39c09f7c4bd
diff --git a/api/irl/report.js b/api/irl/report.jsindex 4d142352b..1f5145a38 100644--- a/api/irl/report.js+++ b/api/irl/report.js@@ -28,10 +28,36 @@ import { limits, clientIp } from '../_lib/rate-limit.js';// Distinct reporters required before a pin is queued out of public view.const REPORT_HIDE_THRESHOLD = 3;const MAX_REASON_LEN = 240;+// Per-pin abuse ceiling: the most report rows a single pin may accrue in a rolling+// 24h window before new reports are refused (task 13). The distinct-reporter dedup+// (one row per (pin, reporter)) already stops ONE actor inflating the count; this+// bounds a DISTRIBUTED flood so a coordinated burst can't pile unbounded reports+// onto — and fast-track the hiding of — a legitimate pin. It sits well above+// REPORT_HIDE_THRESHOLD so genuine flagging still hides a pin at 3 distinct+// reporters; once a pin is at the ceiling it is already under review, so nothing+// new is accepted. Because of the dedup, this is effectively a distinct-reporter-+// per-day cap.+const REPORT_PIN_CAP_24H = 25;// Canonical reasons the UI offers; anything else collapses to 'other'. Kept as a// closed set so the (future) review console can triage by category.const REASONS = new Set(['spam', 'harassment', 'impersonation', 'scam', 'sexual', 'other']);+// Sanitize the free-text detail before it is STORED and later rendered in the+// moderation console (task 13). The raw value is attacker-controlled from an+// anonymous device, so: drop NUL + C0/C1 control characters (they corrupt log+// lines and can smuggle terminal/console escape sequences past a naïve renderer),+// collapse runs of whitespace, then hard-bound the length. Returns null when+// nothing printable survives so an all-control-char payload stores as no detail.+function sanitizeDetail(raw) {+ if (typeof raw !== 'string') return null;+ const cleaned = raw+ .replace(/[\u0000-\u001F\u007F-\u009F]/g, ' ') // NUL + C0/C1 control chars -> space+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, MAX_REASON_LEN);+ return cleaned || null;+}+let _tableReady = false;async function ensureTable() {if (_tableReady) return;diff --git a/src/irl.js b/src/irl.jsindex 9a93abc01..5525d4af5 100644--- a/src/irl.js+++ b/src/irl.js@@ -61,6 +61,8 @@ import { initRoomMode } from './irl/room-mode.js';import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch, screenPitchDeg } from './irl/sensor-fusion.js';import { deriveVerticalFovDeg, DEFAULT_DIAG_FOV_DEG } from './irl/camera-fov.js';import { pinBandAction } from './irl/proximity-band.js';+import { gpsAccuracyBucket, easeGpsTransition, GPS_TRANSITION_MS } from './irl/gps-lifecycle.js';+import { pickLabelHit } from './irl/tap-pick.js';import {shouldCueArrival,relativeBearing,@@ -265,7 +267,12 @@ rayPlane.position.y = 0.005;scene.add(rayPlane);// ── Camera ────────────────────────────────────────────────────────────────-const camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.05, 200);+// near = 0.02 m: held one-handed, a virtual agent brought close to inspect can put+// its near face inside the clip cone and vanish (and so dodge the inspect tap). 2 cm+// keeps it visible without the depth-fighting a 1 cm near would risk against the+// coplanar ground/shadow planes at the 0.02→200 ratio. Raycasting itself is+// near-independent (Raycaster.near defaults to 0), so this is purely a render fix.+const camera = new PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.02, 200);const avatarRig = new Group();scene.add(avatarRig);@@ -659,22 +666,16 @@ canvas.addEventListener('pointerup', e => {// Nearest on-screen name label within a finger-sized radius of the tap (B4).// Uses the screen positions cached by updateLabels() each frame, so it costs a-// short loop and zero projection/allocation. A clear pixel winner takes it;-// near-ties resolve to the nearer (front) agent so clustered labels behave.-const TAP_SLOP = 28; // px — touch radius around a label centre, wider than the box+// short loop with no projection. The ranking (clear pixel winner takes it; cluster+// ties resolve to the nearer/front agent) lives in the pure, unit-tested+// pickLabelHit helper — here we only adapt each pin into a candidate it understands.function _nearestLabelWithinSlop(px, py) {- let best = null, bestPx = Infinity;+ const candidates = [];for (const pin of nearbyPins) {if (!pin._labelOnScreen) continue;- const d = Math.hypot(px - pin._labelSx, py - pin._labelSy);- if (d > TAP_SLOP) continue;- if (d < bestPx - 8) { best = pin; bestPx = d; }- else if (Math.abs(d - bestPx) <= 8 &&- (pin.distance_m ?? Infinity) < (best?.distance_m ?? Infinity)) {- best = pin; bestPx = d;- }+ candidates.push({ sx: pin._labelSx, sy: pin._labelSy, distance: pin.distance_m, pin });}- return best;+ return pickLabelHit(candidates, px, py)?.pin ?? null;}function _pinForObject(obj) {@@ -1249,6 +1250,18 @@ let gpsModeActive = false;// True when the user locked before the first GPS fix landed: onGPSPosition()// finishes the anchor the instant a fix arrives, instead of pinning at origin.let _pendingGpsLock = false;+// Camera glide for the local→GPS lock upgrade. When the first fix flips+// gpsModeActive, the camera jumps from the gyro pivot to the viewer origin and the+// avatar reprojects via gpsToWorld — without easing, that reads as a teleport. Set+// to { from: Vector3, elapsed: 0 } at the flip; the GPS camera branch in tick()+// eases position from `from` toward the origin over GPS_TRANSITION_MS, then clears.+let _gpsCamTransition = null;+// Pending re-arm of the geolocation watch after a transient (non-permission) error.+// watchPosition does not reliably resume after an indoor timeout, and initGPS() is+// idempotent on a live watchId — so onGPSError() tears the dead watch down and+// schedules this backoff re-arm, letting an idle session self-heal without a reload.+let _gpsRetryTimer = null;+const GPS_RETRY_MS = 4000;function gpsToWorld(agentLat, agentLng) {if (!gpsState.ready) return new Vector3(0, 0, 0);@@ -1566,6 +1579,7 @@ function onGPSPosition(pos) {gpsState.lng = blended.lng;}gpsState.ready = true;+ _gpsAcquiring = false; // first fix in hand — leave the "finding you" state// First fix: GPS is live, so the user can place + manage pins from here.if (!wasReady) revealMyPinsBtn();@@ -1664,8 +1678,13 @@ function anchorGpsPin() {function onGPSError(err) {// A revoked location permission always surfaces a re-request chip (E1), even- // outside an active pin attempt.- if (err && err.code === err.PERMISSION_DENIED) setPermissionState('location', 'denied');+ // outside an active pin attempt. Leave the "finding you" state too — the denied+ // chip owns recovery from here, and the badge falls back to hidden.+ if (err && err.code === err.PERMISSION_DENIED) {+ _gpsAcquiring = false;+ setPermissionState('location', 'denied');+ updateNearbyBadge();+ }// Only intervene with a sheet when a placement is actively waiting on a fix —// a transient watchPosition timeout shouldn't disturb a working session.if (!_pendingGpsLock) return;@@ -1685,6 +1704,10 @@ function initGPS() {if (_mockLocation) return; // DEV simulated location active — never attach the real watchif (!navigator.geolocation) return;if (gpsState.watchId != null) return; // idempotent — onboarding, boot, and Pin may all call+ // Enter the "finding you" state the moment the watch attaches (unless a fix is+ // somehow already in hand) so the topbar shows honest progress, not a blank gap,+ // before the first position lands.+ if (!gpsState.ready) { _gpsAcquiring = true; updateNearbyBadge(); }gpsState.watchId = navigator.geolocation.watchPosition(onGPSPosition,onGPSError,@@ -2274,6 +2297,14 @@ let nearbyPins = []; // [{ id, lat, lng, avatar_url, avatar_name, caption, x402_// Set true when the last nearby fetch failed; cleared on the next good fetch, so// a failed refresh shows a visible indicator on the badge instead of going silent.let _nearbyError = false;+// Set true on a 429 from the nearby read — a calm, auto-recovering "catching up"+// state distinct from the scary error badge (the next poll clears it). The limiter+// is generous, so this is rare, but it must never read as "discovery is broken".+let _nearbyRateLimited = false;+// Location is granted and the GPS watch is attached, but no first fix has landed+// yet. A distinct "finding you" state so the gap before the first fix is never+// mistaken for "nobody's here." Cleared the instant gpsState.ready flips true.+let _gpsAcquiring = false;// ── "Newly stable in-range" signal (task 04 → task 03) ──────────────────────// The hysteresis band (proximity-band.js) makes membership steady: a pin only@@ -2825,9 +2856,15 @@ async function loadNearbyPins() {{ headers: await presenceHeaders() },);if (r.status === 401) { return handleFixRequired(r); }+ // 429: we're polling faster than the limiter allows (rare — the cadence is+ // fixed at 10 s — but possible behind a shared NAT or after a manual retry+ // storm). Treat it as a transient, self-healing pause, NOT an error: keep the+ // last good pins on screen and let the next cycle catch up. Never alarm the user.+ if (r.status === 429) { _nearbyRateLimited = true; updateNearbyBadge(); return; }if (!r.ok) { _nearbyError = true; updateNearbyBadge(); return; }const { pins } = await r.json();_nearbyError = false;+ _nearbyRateLimited = false;const incoming = pins.filter(p => !gpsPin?.id || p.id !== gpsPin.id);const incomingById = new Map(incoming.map(p => [p.id, p]));@@ -2899,8 +2936,10 @@ async function loadNearbyPins() {}} catch {// Don't fail silently — a busy spot that can't load looks identical to an- // empty one otherwise. Flag it on the badge; the 15 s poll retries.+ // empty one otherwise. Flag it on the badge; the 15 s poll retries. A genuine+ // network drop supersedes a prior rate-limit pause (error is the actionable state)._nearbyError = true;+ _nearbyRateLimited = false;updateNearbyBadge();}}@@ -3260,6 +3299,11 @@ function updateNearbyBadge() {// Visible, not silent: the 15 s poll retries; show we know the data is stale.text = n > 0 ? `${n} nearby · refresh failed` : 'Couldn’t load nearby — retrying…';mod = 'is-error';+ } else if (_nearbyRateLimited) {+ // Calm + specific + self-healing: we backed off, the next cycle resumes. Keep any+ // pins we already have visible ("N nearby · catching up"); never an error tone.+ text = n > 0 ? `${n} nearby · catching up…` : 'Refreshing too fast — catching up…';+ mod = 'is-rate';} else if (n > 0) {text = `${n} nearby`;mod = '';@@ -3268,13 +3312,21 @@ function updateNearbyBadge() {// 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 if (_gpsAcquiring) {+ // Granted but no fix yet — a distinct, honest "finding you" state (shimmer skeleton+ // in CSS) so the pre-fix gap never reads as the empty "nobody's here" state.+ text = 'Finding your location…';+ mod = 'is-acquiring';} else {- // No fix yet → nothing to say about "nearby"; stay hidden until GPS lands.+ // No location yet (denied / not asked) → nothing to say about "nearby"; stay+ // hidden until a fix lands. The permission chips own the recovery path.text = '';mod = 'hidden';}badge.classList.toggle('is-error', mod === 'is-error');badge.classList.toggle('is-empty', mod === 'is-empty');+ badge.classList.toggle('is-rate', mod === 'is-rate');+ badge.classList.toggle('is-acquiring', mod === 'is-acquiring');if (mod === 'hidden') { badge.hidden = true; return; }badge.hidden = false;if (badge.textContent !== text) badge.textContent = text;diff --git a/src/irl/gps-lifecycle.js b/src/irl/gps-lifecycle.jsnew file mode 100644index 000000000..4829b7b58--- /dev/null+++ b/src/irl/gps-lifecycle.js@@ -0,0 +1,62 @@+// Pure helpers for the /irl GPS lifecycle and the local→GPS lock upgrade.+//+// Why this exists+// ───────────────+// Anchoring an agent to a real-world spot rides a consumer GPS watch and a+// transition between two camera regimes — a local gyro pivot (no fix yet) and the+// precise viewer-origin frame (a fix has landed). Two bits of that flow are pure+// number-crunching that must not drift or regress, so they live here behind unit+// tests instead of tangled into the live event/render code in src/irl.js:+//+// 1. Accuracy honesty — bucket a fix's horizontal accuracy (metres) so the UI can+// tell the truth about how precise a placement really is, rather than implying+// pinpoint accuracy on a ±40 m indoor fix.+// 2. Transition easing — the eased 0→1 parameter that glides the camera from the+// gyro pivot to the viewer origin when the first fix upgrades a local lock, so+// the avatar never visibly teleports relative to the room.+//+// No DOM, no Three.js, no clock — plain numbers in, plain numbers out.++// A fix at or under this horizontal accuracy (metres) is treated as a precise+// placement. Beyond it, consumer GPS is too noisy to claim an exact spot, so the+// UI says "approximate" and the stored gpsAccuracyM carries the honest number.+export const GPS_ACCURACY_PRECISE_M = 25;+// Past this, the fix is barely better than a neighbourhood guess (typical indoor /+// urban-canyon GPS) — surface it as coarse so the copy sets the right expectation.+export const GPS_ACCURACY_COARSE_M = 60;++// Bucket a horizontal-accuracy reading (metres) into a placement-quality level.+// Returns { level, precise, label, accuracyM } where:+// level — 'precise' | 'approximate' | 'coarse' | 'unknown'+// precise — true only for a genuinely tight fix (≤ GPS_ACCURACY_PRECISE_M)+// label — short human phrase for a subtle UI hint ('' when precise/unknown)+// accuracyM — the rounded metres, or null when the device reported none+// A null/NaN reading is 'unknown' (the device couldn't measure it) — never claimed+// as precise, but not flagged as coarse either.+export function gpsAccuracyBucket(accuracyM) {+ if (!Number.isFinite(accuracyM) || accuracyM < 0) {+ return { level: 'unknown', precise: false, label: '', accuracyM: null };+ }+ const rounded = Math.round(accuracyM);+ if (accuracyM <= GPS_ACCURACY_PRECISE_M) {+ return { level: 'precise', precise: true, label: '', accuracyM: rounded };+ }+ if (accuracyM <= GPS_ACCURACY_COARSE_M) {+ return { level: 'approximate', precise: false, label: `±${rounded} m`, accuracyM: rounded };+ }+ return { level: 'coarse', precise: false, label: `±${rounded} m (low GPS accuracy)`, accuracyM: rounded };+}++// Duration of the local→GPS camera glide, milliseconds. Short enough to feel+// instantaneous, long enough to read as a settle rather than a snap.+export const GPS_TRANSITION_MS = 450;++// Eased 0→1 progress for the camera glide. Cubic ease-out: quick to start, gentle+// to land, so the viewpoint arrives at the viewer origin without an abrupt stop.+// Clamps out-of-range input so a long frame (t > 1) or a paused tab can't overshoot.+export function easeGpsTransition(t) {+ if (!Number.isFinite(t) || t <= 0) return 0;+ if (t >= 1) return 1;+ const inv = 1 - t;+ return 1 - inv * inv * inv;+}diff --git a/src/irl/tap-pick.js b/src/irl/tap-pick.jsnew file mode 100644index 000000000..eb7c38141--- /dev/null+++ b/src/irl/tap-pick.js@@ -0,0 +1,63 @@+// IRL tap picking — pure, DOM-free, Three.js-free screen-space ranking (task 05).+//+// On a phone the body mesh of a distant or small agent is a poor tap target, so+// irl.js casts a ray at the agent meshes first (front body wins a depth tie for+// free) and, only when that misses, falls back to a finger-sized "label net":+// the nearest on-screen name label within a touch radius of the tap point. That+// fallback is the floor for tap reliability — and it is the part worth proving in+// isolation, because the ranking has two subtle rules a manual device test can't+// pin down repeatably:+//+// 1. A clear pixel winner (closer to the finger by more than the tie band) takes+// the tap — fat-finger tolerance, so a tap *near* a label still selects it.+// 2. Among labels the finger lands on within the tie band (a cluster), the agent+// physically NEAREST the viewer wins, so overlapping labels resolve to the one+// in front rather than whichever happened to iterate last.+//+// The function consumes plain candidates ({ sx, sy, distance, ... }) the caller+// already cached during label layout — no projection, no DOM, no allocation beyond+// the candidate list — so it unit-tests with bare numbers and is reused verbatim by+// irl.js's tap handler.++// Touch radius around a label centre, in CSS px. Wider than the visible label box+// so a tap that lands just outside the pill still selects it — sized for a finger,+// not a cursor.+export const TAP_SLOP_PX = 28;++// Two labels whose distance-to-finger differ by less than this (px) are treated as+// a tie, and broken by viewer proximity instead of by sub-pixel finger position.+// Keeps clustered labels from flickering their selection under a shaky tap.+export const TIE_BAND_PX = 8;++function viewerDistance(c) {+ const d = c?.distance;+ return Number.isFinite(d) ? d : Infinity;+}++// Pick the label the tap selects, or null if the finger landed outside every+// label's slop radius. `candidates` is an array of objects each with screen-space+// centre `sx`/`sy` (CSS px) and a viewer `distance` (metres; non-finite = treat as+// farthest). Candidates with a non-finite centre are skipped (their label wasn't+// laid out this frame). The original candidate object is returned so the caller can+// read whatever it hung off it (e.g. the pin) without a second lookup.+export function pickLabelHit(candidates, px, py, opts = {}) {+ const slop = opts.slop ?? TAP_SLOP_PX;+ const tie = opts.tie ?? TIE_BAND_PX;+ if (!Number.isFinite(px) || !Number.isFinite(py)) return null;++ let best = null;+ let bestPx = Infinity;+ for (const c of candidates) {+ if (!c || c.onScreen === false) continue;+ if (!Number.isFinite(c.sx) || !Number.isFinite(c.sy)) continue;+ const d = Math.hypot(px - c.sx, py - c.sy);+ if (d > slop) continue;+ if (d < bestPx - tie) {+ best = c; bestPx = d;+ } else if (Math.abs(d - bestPx) <= tie && viewerDistance(c) < viewerDistance(best)) {+ // Cluster tie: the agent nearer the viewer (in front) wins.+ best = c; bestPx = d;+ }+ }+ return best;+}diff --git a/tasks/irl-production/02-orientation-resize-fov.md b/tasks/irl-production/02-orientation-resize-fov.mddeleted file mode 100644index fa375f1a2..000000000--- a/tasks/irl-production/02-orientation-resize-fov.md+++ /dev/null@@ -1,70 +0,0 @@-# Task 02 — Orientation changes, resize, and camera FOV fidelity--**Phase:** 1 (AR correctness) · **Effort:** M · **Files:** `src/irl.js`, `pages/irl.html`--## Why-The AR math assumes portrait. When a user rotates to landscape, or the viewport-resizes (browser chrome show/hide on scroll, split view), the camera optics and-the gyro frame drift out of agreement with the real world: the avatar changes-scale or slides off its anchor. A polished AR product holds the anchor through-rotation.--## Read first (verify before fixing)-- FOV derivation from the video track — `src/irl.js:342-359` (runs once in `enableAR`)-- Resize handler — search `addEventListener('resize'` and `function resize` in `src/irl.js`-- Gyro yaw/pitch math (portrait assumption) — `src/irl.js:858-894`, GPS branch `~3946-3964`-- Viewport meta + safe-area CSS — `pages/irl.html` `<meta name="viewport">` and `.irl-*` layout--## Scope — confirm, then fix--1. **FOV not re-derived on rotate.** The camera FOV is computed from the video- track resolution once in `enableAR()`. On `orientationchange` the resize handler- updates canvas size + `camera.aspect` but not FOV, so avatar scale is wrong in- landscape. On orientation change (and when the video track's reported dimensions- change), re-read `track.getSettings()` and re-derive FOV with the existing math.--2. **Portrait-only gyro frame.** The yaw/pitch mapping assumes portrait. On a- screen-orientation change, fold `screen.orientation.angle` into the orientation- interpretation so the lock stays true when the device is held in landscape- (or document this as an explicit "portrait recommended" constraint with a- one-time hint if landscape support is deferred — but prefer to support it).--3. **Resize/`visualViewport` robustness.** Ensure resize re-applies the perf tier's- pixel ratio and `renderer.setSize` correctly, and that iOS Safari's dynamic- toolbar (which fires resize on scroll) does not thrash. Debounce if needed.--4. **Safe-area + notch.** Verify all fixed-position controls respect- `env(safe-area-inset-*)` in both orientations (joystick, bottom controls,- topbar). See task 10 for the full responsive pass; here just the AR-canvas /- camera-coupled pieces.--## Implementation guidance-- Listen to both `orientationchange` and `screen.orientation`'s `change` event- (feature-detect; iOS support varies) plus `resize`, funnel into one- `onViewportChanged()` that re-derives FOV + aspect + pixel ratio together.-- Keep the FOV re-derivation a no-op when AR is off (no video track).--## Out of scope-Sensor finite-guards (task 01); pure responsive CSS not coupled to the camera (task 10).--## Definition of done-- [ ] Rotating the device portrait↔landscape keeps the avatar at correct real-world- scale and on its anchor (manual, real device — document results).-- [ ] No console errors on rapid rotate/resize; renderer pixel ratio honored.-- [ ] Any extracted angle math unit-tested.-- [ ] `npm test` green; esbuild clean.-- [ ] Changelog entry if behavior visibly improves for users.--<!-- 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/02-orientation-resize-fov.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/tasks/irl-room-anchor/R1-place-around-me.md b/tasks/irl-room-anchor/R1-place-around-me.mdindex 223c8878c..798d95f72 100644--- a/tasks/irl-room-anchor/R1-place-around-me.md+++ b/tasks/irl-room-anchor/R1-place-around-me.md@@ -1,10 +1,6 @@# R1 — "Place agents around me" (room authoring UI)> Epic R · Size **L** · Edits `src/irl.js`, `pages/irl.html`, `src/irl.css`.-> Depends on the committed engine (`7bf9cecf`); see `tasks/irl-room-anchor/README.md`.-> **This is the gate task — the feature is not reachable by a user without it.**--## GoalA mode in `/irl` where you stand in a room and **drop agents at fixed real-worldspots around you by aiming and setting a distance**. Point the phone at thediff --git a/tests/irl-camera-fov.test.js b/tests/irl-camera-fov.test.jsnew file mode 100644index 000000000..ea4f50c4d--- /dev/null+++ b/tests/irl-camera-fov.test.js@@ -0,0 +1,86 @@+// Camera-FOV optics for the /irl AR passthrough (src/irl/camera-fov.js).+//+// In AR the Three.js camera must share the real rear camera's field of view or the+// avatar renders at the wrong scale. The FOV is derived once from the video track's+// sensor aspect, but the VERTICAL FOV that Three.js wants depends on the VIEWPORT+// aspect — which flips on rotate. These tests pin that the derivation tracks the+// viewport (so portrait↔landscape holds the avatar's real-world scale) and that+// every degenerate input is defended into a sane, clamped, finite angle — the+// function is called straight from a resize handler, so it must never return NaN/∞.++import { describe, it, expect } from 'vitest';++import {+ deriveVerticalFovDeg,+ DEFAULT_DIAG_FOV_DEG,+ VFOV_MIN_DEG,+ VFOV_MAX_DEG,+} from '../src/irl/camera-fov.js';++// Independent re-derivation of the same optics, used as an oracle so the tests+// assert the actual geometry rather than echoing the implementation's constants.+function expectedVFov({ tw, th, vw, vh, diag = DEFAULT_DIAG_FOV_DEG }) {+ const DEG = Math.PI / 180, RAD = 180 / Math.PI;+ const diagPx = Math.hypot(tw, th);+ const hFov = 2 * Math.atan((tw / diagPx) * Math.tan((diag * DEG) / 2));+ const vFov = 2 * Math.atan(Math.tan(hFov / 2) / (vw / vh)) * RAD;+ return Math.max(VFOV_MIN_DEG, Math.min(VFOV_MAX_DEG, vFov));+}++describe('deriveVerticalFovDeg — optics', () => {+ it('matches the closed-form geometry for a 1280×720 sensor in portrait', () => {+ const out = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: 390, viewHeight: 844 });+ expect(out).toBeCloseTo(expectedVFov({ tw: 1280, th: 720, vw: 390, vh: 844 }), 6);+ });++ it('a tall portrait viewport yields a wider vertical FOV than a wide landscape one', () => {+ // Same sensor, viewport rotated 90°. Portrait fills more vertical angle.+ const portrait = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: 390, viewHeight: 844 });+ const landscape = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: 844, viewHeight: 390 });+ expect(portrait).toBeGreaterThan(landscape);+ });++ it('the vertical FOV tracks the viewport aspect, not the (fixed) sensor aspect', () => {+ // Rotating the device does not change the sensor dims, only the viewport.+ // If the derivation wrongly used the sensor aspect both calls would match.+ const a = deriveVerticalFovDeg({ trackWidth: 1920, trackHeight: 1080, viewWidth: 400, viewHeight: 900 });+ const b = deriveVerticalFovDeg({ trackWidth: 1920, trackHeight: 1080, viewWidth: 900, viewHeight: 400 });+ expect(Math.abs(a - b)).toBeGreaterThan(1);+ });+});++describe('deriveVerticalFovDeg — clamping & defense', () => {+ it('clamps the result into [VFOV_MIN, VFOV_MAX]', () => {+ // An extreme viewport aspect would push the raw FOV outside the safe band.+ const wide = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: 4000, viewHeight: 200 });+ const tall = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: 200, viewHeight: 4000 });+ expect(wide).toBeGreaterThanOrEqual(VFOV_MIN_DEG);+ expect(tall).toBeLessThanOrEqual(VFOV_MAX_DEG);+ });++ it('never returns NaN/∞ for degenerate (zero / negative) track dimensions', () => {+ for (const dims of [+ { trackWidth: 0, trackHeight: 0, viewWidth: 390, viewHeight: 844 },+ { trackWidth: -1280, trackHeight: 720, viewWidth: 390, viewHeight: 844 },+ { trackWidth: 1, trackHeight: 1, viewWidth: 390, viewHeight: 844 },+ ]) {+ const out = deriveVerticalFovDeg(dims);+ expect(Number.isFinite(out)).toBe(true);+ expect(out).toBeGreaterThanOrEqual(VFOV_MIN_DEG);+ expect(out).toBeLessThanOrEqual(VFOV_MAX_DEG);+ }+ });++ it('falls back to sensible values when the viewport dims are non-finite', () => {+ const out = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: NaN, viewHeight: undefined });+ expect(Number.isFinite(out)).toBe(true);+ expect(out).toBeGreaterThanOrEqual(VFOV_MIN_DEG);+ expect(out).toBeLessThanOrEqual(VFOV_MAX_DEG);+ });++ it('uses the default diagonal FOV when an invalid one is supplied', () => {+ const bad = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: 390, viewHeight: 844, diagFovDeg: 0 });+ const good = deriveVerticalFovDeg({ trackWidth: 1280, trackHeight: 720, viewWidth: 390, viewHeight: 844 });+ expect(bad).toBeCloseTo(good, 6);+ });+});diff --git a/tests/irl-sensor-robustness.test.js b/tests/irl-sensor-robustness.test.jsindex e982f56be..e0471f04f 100644--- a/tests/irl-sensor-robustness.test.js+++ b/tests/irl-sensor-robustness.test.js@@ -15,6 +15,7 @@ import {shouldUseAbsoluteYaw,resolveLockYaw,clampPitch,+ screenPitchDeg,} from '../src/irl/sensor-fusion.js';const DEG = Math.PI / 180;@@ -175,3 +176,54 @@ describe('clampPitch', () => {expect(Number.isFinite(clampPitch(NaN, PITCH_MIN, PITCH_MAX))).toBe(true);});});++// The screen-orientation frame correction (task-02): the gyro pitch path assumes+// the phone is held portrait. screenPitchDeg() folds screen.orientation.angle back+// into a portrait-equivalent pitch so the world-lock holds through rotation.+describe('screenPitchDeg', () => {+ it('portrait (angle 0) passes beta through, ignoring gamma', () => {+ expect(screenPitchDeg(30, 12, 0)).toBe(30);+ expect(screenPitchDeg(-45, 80, 0)).toBe(-45);+ });++ it('landscape ⟲90° reads pitch from +gamma instead of beta', () => {+ expect(screenPitchDeg(0, 30, 90)).toBe(30);+ expect(screenPitchDeg(88, -20, 90)).toBe(-20);+ });++ it('upside-down portrait (180°) inverts beta', () => {+ expect(screenPitchDeg(30, 0, 180)).toBe(-30);+ expect(screenPitchDeg(-45, 0, 180)).toBe(45);+ });++ it('landscape ⟳270° reads pitch from −gamma (the opposite landscape sign)', () => {+ expect(screenPitchDeg(0, 30, 270)).toBe(-30);+ expect(screenPitchDeg(0, -25, 270)).toBe(25);+ });++ it('defaults to portrait when the angle is omitted', () => {+ expect(screenPitchDeg(42, 99)).toBe(42);+ });++ it('snaps an off-grid / rounding-noisy angle to the nearest 90° bucket', () => {+ expect(screenPitchDeg(0, 30, 88)).toBe(30); // → 90+ expect(screenPitchDeg(30, 0, 179)).toBe(-30); // → 180+ expect(screenPitchDeg(0, 30, 271)).toBe(-30); // → 270+ });++ it('normalizes negative / >360 angles into the canonical bucket', () => {+ expect(screenPitchDeg(30, 0, -180)).toBe(-30); // -180 → 180+ expect(screenPitchDeg(0, 30, 450)).toBe(30); // 450 → 90+ });++ it('collapses a non-finite active axis to the horizon (0), never NaN', () => {+ expect(screenPitchDeg(NaN, 30, 0)).toBe(0); // portrait reads beta+ expect(screenPitchDeg(30, NaN, 90)).toBe(0); // landscape reads gamma+ expect(Number.isFinite(screenPitchDeg(NaN, NaN, 270))).toBe(true);+ });++ it('ignores the inactive axis being non-finite', () => {+ expect(screenPitchDeg(30, NaN, 0)).toBe(30); // portrait: gamma unused+ expect(screenPitchDeg(NaN, 30, 90)).toBe(30); // landscape: beta unused+ });+});