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.

feat(irl): true AR placement leads the dock, pinch-to-resize with persisted scale

nirholas33aea77ef4e3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 85f5e26dc..950883641 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **AR Forge** (`/ar`) — Type a prompt, get a real 3D model, and place it in your room: free text-to-3D with one-tap AR on any phone (WebXR, Scene Viewer, Quick Look) and a QR handoff from desktop.
- **End-User License Agreement** (`/legal/eula`) — License terms for the three.ws Seeker/Saga app.
- **AR Forge: type a prompt, place the model in your room** — A new mobile-first app at /ar turns a one-line prompt into a real, downloadable 3D model on the free generation lane, then puts it in your space with one tap: WebXR or Scene Viewer on Android, Quick Look on iPhone. On a desktop it shows a QR code that hands the finished model straight to your phone's camera app, and every creation gets a shareable viewer link. No account, no payment, fair-use rate limits only. (`/ar`) `[feature]`
+- **IRL placement grows up: true AR anchoring leads the dock, and you can pinch-resize your agent** — Placing an avatar in the real world through /irl now feels like a native AR app. On phones with a real AR surface the new Place in AR button leads the dock: a floor-finding reticle, a tap to anchor the agent to the actual detected surface, and now a two-finger pinch to resize it live, from a 25% desk figurine to a 400% statue. The size you choose saves with the pin, so everyone who walks up sees your agent exactly where and how big you left it. iPhones open the same placement in ARKit Quick Look. The compass-and-GPS pin path is unchanged and remains the fallback everywhere else. (`/irl`) `[feature, improvement]`
- **New doc: IRL, agents in the real world** — The IRL layer finally has a front door in the docs: one page that explains the whole vision and how the shipped pieces fit together. It covers placing an agent at a real GPS spot from your phone, walk-up discovery with proof of presence, paying agents in person via x402, Money Drops (real SOL, USDC, or $THREE escrowed at a place and claimable only by walking up), World Lines (agent-signed proofs that you were really there), and the privacy model that makes it all safe. The docs sidebar now also links the hands-on IRL tutorial, which was previously unreachable from the navigation. (`/docs/irl`) `[docs]`
- **Tour and Walk SDK update: switch between Stroll and Platformer from the tour controls** — Embedded tours built with the Tour Builder now include a labeled Stroll / Platformer toggle right in the tour controls next to Exit, so visitors can switch how they explore (tap it or press M) instead of hunting for a hidden corner button. Published as @three-ws/walk 0.2.1 and @three-ws/tour 0.5.1 on npm; the Tour Builder's exported embed snippet now uses the new versions automatically, and also picks up the latest @three-ws/page-agent with its five persona presets. (`/tour-builder`) `[sdk, improvement]`
diff --git a/api/irl/pins.js b/api/irl/pins.js
index e2d1f1279..9ae3f5248 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -396,6 +396,7 @@ async function runMigrations() {
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS gps_accuracy_m DOUBLE PRECISION`;
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS altitude_m DOUBLE PRECISION`;
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS anchor_source TEXT`; // 'webxr' | 'gyro-gps'
+ await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS anchor_scale DOUBLE PRECISION`; // pinch-resized render scale (0.25–4), NULL = natural size
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS vps_provider TEXT`; // reserved for visual positioning
await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS vps_id TEXT`; // reserved
// Moderation + density (D4). geocell7 is the ~150m density key (precision-7
@@ -547,6 +548,39 @@ export function isExpiredOrHidden(pin, now = Date.now()) {
return Number.isFinite(t) && t <= now;
}
+// Owner-gated render-scale update. A pinch during the WebXR placement session
+// lands AFTER the pin was persisted on the placement tap, so the final size
+// arrives as this small follow-up PATCH. Same ownership + liveness gates as
+// calibrate; the clamp matches the POST path and the client gesture bounds.
+async function handleScale(res, { id, session, body, deviceToken = null }) {
+ const raw = Number(body.scale);
+ if (!Number.isFinite(raw) || raw <= 0) {
+ return json(res, 400, { error: 'invalid scale' });
+ }
+ const scale = Math.min(4, Math.max(0.25, raw));
+
+ const [pin] = await sql`
+ SELECT id, user_id, device_token, expires_at, hidden_at
+ FROM irl_pins
+ WHERE id = ${id}
+ `;
+ if (!pin) return json(res, 404, { error: 'not found' });
+ const owns =
+ (!!session?.id && !!pin.user_id && pin.user_id === session.id) ||
+ (!!pin.device_token && !!deviceToken && pin.device_token === deviceToken);
+ if (!owns) return json(res, 403, { error: 'only the owner can resize this agent' });
+ if (isExpiredOrHidden(pin)) return json(res, 404, { error: 'not found' });
+
+ // Scale 1 is "natural size" — store NULL so legacy readers see no change.
+ const stored = scale === 1 ? null : scale;
+ const [updated] = await sql`
+ UPDATE irl_pins SET anchor_scale = ${stored}
+ WHERE id = ${id}
+ RETURNING id, anchor_scale
+ `;
+ return json(res, 200, { pin: updated });
+}
+
// Owner-gated, bounds-checked pose correction. Mutates the A2 pose columns so the
// re-fetch every nearby viewer already runs picks up the corrected spot. (Pushing
// the correction to already-loaded viewers in realtime rides on D1; a re-fetch
@@ -905,7 +939,7 @@ export default wrap(async (req, res) => {
const rows = await sql`
SELECT id, lat, lng, heading, avatar_url, avatar_name, caption, agent_id,
placed_at, expires_at, view_count,
- anchor_height_m, anchor_yaw_deg, anchor_quat,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source,
avatar_manifest, avatar_base_url, avatar_version,
placement_kind, fuzz_radius_m
@@ -963,7 +997,7 @@ export default wrap(async (req, res) => {
const rows = await sql`
SELECT id, user_id, device_token, agent_id, lat, lng, heading,
avatar_url, avatar_name, caption, x402_endpoint, placed_at, view_count,
- anchor_height_m, anchor_yaw_deg, anchor_quat,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source, avatar_version,
placement_kind, fuzz_radius_m, published,
vps_provider, vps_id,
@@ -997,6 +1031,7 @@ export default wrap(async (req, res) => {
anchor_height_m: r.anchor_height_m,
anchor_yaw_deg: r.anchor_yaw_deg,
anchor_quat: r.anchor_quat,
+ anchor_scale: r.anchor_scale,
gps_accuracy_m: r.gps_accuracy_m,
altitude_m: r.altitude_m,
anchor_source: r.anchor_source,
@@ -1074,7 +1109,7 @@ export default wrap(async (req, res) => {
const rows = await sql`
SELECT id, user_id, device_token, agent_id, lat, lng, heading,
avatar_url, avatar_name, caption, x402_endpoint, placed_at, view_count,
- anchor_height_m, anchor_yaw_deg, anchor_quat,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source, avatar_version,
placement_kind, fuzz_radius_m, published,
room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg
@@ -1111,6 +1146,7 @@ export default wrap(async (req, res) => {
anchor_height_m: r.anchor_height_m,
anchor_yaw_deg: r.anchor_yaw_deg,
anchor_quat: r.anchor_quat,
+ anchor_scale: r.anchor_scale,
gps_accuracy_m: r.gps_accuracy_m,
altitude_m: r.altitude_m,
anchor_source: r.anchor_source,
@@ -1293,6 +1329,10 @@ export default wrap(async (req, res) => {
const gpsAccuracyM = Number.isFinite(pose.gpsAccuracyM)
? Math.min(500, Math.max(0, pose.gpsAccuracyM)) : null;
const altitudeM = Number.isFinite(pose.altitudeM) ? pose.altitudeM : null;
+ // Pinch-resized render scale — clamped to the same band the client gesture
+ // enforces (desk figurine ↔ statue). Absent/1 stores NULL = natural size.
+ const anchorScale = Number.isFinite(pose.scale) && pose.scale > 0 && pose.scale !== 1
+ ? Math.min(4, Math.max(0.25, pose.scale)) : null;
// 'webxr' (A1) · 'gyro-gps' (absolute compass heading) · 'gyro-gps:rel'
// (page-relative heading only — A3 down-weights its cross-user bearing) ·
// 'map' (L2: a point chosen on the map, not a live fix — its bearing isn't
@@ -1355,7 +1395,7 @@ export default wrap(async (req, res) => {
INSERT INTO irl_pins
(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,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source, geocell7,
room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg,
placement_kind, fuzz_radius_m, vps_provider, vps_id, published)
@@ -1373,6 +1413,7 @@ export default wrap(async (req, res) => {
${anchorHeightM},
${anchorYawDeg},
${anchorQuat},
+ ${anchorScale},
${gpsAccuracyM},
${altitudeM},
${anchorSource},
@@ -1433,6 +1474,13 @@ export default wrap(async (req, res) => {
return handleCalibrate(res, { id, session, body, deviceToken: readDeviceToken(req) });
}
+ // ── Resize — owner-gated pinch scale follow-up (same gate as calibrate) ──
+ // Routed before the auth gate below: the anonymous placing device may resize
+ // its own agent; ownership is enforced inside handleScale.
+ if ('scale' in body && !('caption' in body) && !('avatarUrl' in body) && !('lat' in body)) {
+ return handleScale(res, { id, session, body, deviceToken: readDeviceToken(req) });
+ }
+
// Field edits (caption / avatar / location / heading / x402) require auth.
if (!session) return json(res, 401, { error: 'not authenticated' });
diff --git a/data/changelog.json b/data/changelog.json
index 34d3cc24c..9ba1c4baf 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -13543,6 +13543,16 @@
"feature"
],
"link": "/ar"
+ },
+ {
+ "date": "2026-07-14",
+ "title": "IRL placement grows up: true AR anchoring leads the dock, and you can pinch-resize your agent",
+ "summary": "Placing an avatar in the real world through /irl now feels like a native AR app. On phones with a real AR surface the new Place in AR button leads the dock: a floor-finding reticle, a tap to anchor the agent to the actual detected surface, and now a two-finger pinch to resize it live, from a 25% desk figurine to a 400% statue. The size you choose saves with the pin, so everyone who walks up sees your agent exactly where and how big you left it. iPhones open the same placement in ARKit Quick Look. The compass-and-GPS pin path is unchanged and remains the fallback everywhere else.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/irl"
}
]
}
diff --git a/docs/irl.md b/docs/irl.md
index 98c4ce3c8..ea57b315a 100644
--- a/docs/irl.md
+++ b/docs/irl.md
@@ -30,8 +30,8 @@ Everything below is live on [/irl](/irl) and exposed by the [`@three-ws/irl`](ht
Open /irl on your phone, pick one of your agents (or try it anonymously), and drop a pin:
+- **Place in AR** is the flagship path on devices with a real AR surface. On Chrome for Android (ARCore) a WebXR hit-test reticle finds the floor; tap to anchor the agent to the detected surface, then **pinch with two fingers to resize it** — from a desk figurine (25%) to a statue (400%). The placement and the chosen size both save to the pin, so everyone nearby sees the agent exactly where and how big you left it. On iOS the same button opens the agent in ARKit Quick Look. This button leads the dock whenever the device supports it.
- **Pin here** places it at your current GPS spot using the camera and gyroscope. Works on every supported phone, including iOS Safari.
-- **Place on floor** uses a WebXR hit-test to anchor the agent to a real detected surface (Chrome on Android with ARCore).
- **Place on map** puts an agent somewhere you are not currently standing.
Anonymous pins work immediately from a device token and expire after 7 days. Signed-in pins are permanent until you remove them. The full walkthrough is in [Place a 3D agent in your real environment](/docs/tutorials/place-agent-irl).
diff --git a/pages/irl.html b/pages/irl.html
index 5e5718af6..9a5614276 100644
--- a/pages/irl.html
+++ b/pages/irl.html
@@ -2403,7 +2403,7 @@
</button>
<button class="irl-pill-btn" id="irl-anchor-btn" type="button" hidden aria-label="Place agent on the floor with AR">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/><circle cx="12" cy="12" r="4"/></svg>
- Place on floor
+ Place in AR
</button>
<button class="irl-pill-btn" id="irl-mapplace-btn" type="button" aria-label="Place this agent at a spot you choose on a map">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M21 10c0 6-9 12-9 12s-9-6-9-12a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>
diff --git a/public/changelog.json b/public/changelog.json
index 49339eff4..a100f407b 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-14T07:31:01.395Z",
+ "generated_at": "2026-07-14T09:20:07.194Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -36,6 +36,17 @@
"feature"
]
},
+ {
+ "date": "2026-07-14",
+ "type": "update",
+ "title": "IRL placement grows up: true AR anchoring leads the dock, and you can pinch-resize your agent",
+ "summary": "Placing an avatar in the real world through /irl now feels like a native AR app. On phones with a real AR surface the new Place in AR button leads the dock: a floor-finding reticle, a tap to anchor the agent to the actual detected surface, and now a two-finger pinch to resize it live, from a 25% desk figurine to a 400% statue. The size you choose saves with the pin, so everyone who walks up sees your agent exactly where and how big you left it. iPhones open the same placement in ARKit Quick Look. The compass-and-GPS pin path is unchanged and remains the fallback everywhere else.",
+ "link": "/irl",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-14",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 0032650fc..56b1f91ff 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -30,6 +30,14 @@
<category>feature</category>
<description>A new mobile-first app at /ar turns a one-line prompt into a real, downloadable 3D model on the free generation lane, then puts it in your space with one tap: WebXR or Scene Viewer on Android, Quick Look on iPhone. On a desktop it shows a QR code that hands the finished model straight to your phone's camera app, and every creation gets a shareable viewer link. No account, no payment, fair-use rate limits only.</description>
</item>
+ <item>
+ <title>IRL placement grows up: true AR anchoring leads the dock, and you can pinch-resize your agent</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-07-14:IRL placement grows up: true AR anchoring leads the dock, and you can pinch-resize your agent</guid>
+ <pubDate>Tue, 14 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Placing an avatar in the real world through /irl now feels like a native AR app. On phones with a real AR surface the new Place in AR button leads the dock: a floor-finding reticle, a tap to anchor the agent to the actual detected surface, and now a two-finger pinch to resize it live, from a 25% desk figurine to a 400% statue. The size you choose saves with the pin, so everyone who walks up sees your agent exactly where and how big you left it. iPhones open the same placement in ARKit Quick Look. The compass-and-GPS pin path is unchanged and remains the fallback everywhere else.</description>
+ </item>
<item>
<title>New doc: IRL, agents in the real world</title>
<link>https://three.ws/docs/irl</link>
diff --git a/public/features.json b/public/features.json
index a65329e19..a02838c84 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-14T07:31:01.382Z",
+ "generated_at": "2026-07-14T09:20:07.180Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/ar/pinch-scale.js b/src/ar/pinch-scale.js
new file mode 100644
index 000000000..15a161dc4
--- /dev/null
+++ b/src/ar/pinch-scale.js
@@ -0,0 +1,86 @@
+// Pure pinch-to-resize math for WebXR AR placement (no DOM, no THREE).
+//
+// A two-finger pinch during an immersive-ar session resizes the placed agent,
+// matching the native Scene Viewer / Quick Look gesture users already know.
+// The state machine is deliberately tiny and allocation-free so the session
+// controller (src/ar/webxr.js) can drive it from raw touch points every frame:
+//
+// const p = createPinchState();
+// pinchStart(p, dist, currentScale) // two fingers down
+// pinchMove(p, dist) → new scale // fingers move (null = not pinching)
+// pinchEnd(p) → final scale // a finger lifts (null = wasn't pinching)
+//
+// Scale is the ratio of the current finger distance to the distance at pinch
+// start, applied to the scale the content already had — so consecutive pinches
+// compose naturally instead of snapping back to 1. Clamped to sane bounds: a
+// life-size avatar squeezed to a desk figurine (MIN) or grown to a statue (MAX).
+
+export const PINCH_SCALE_MIN = 0.25;
+export const PINCH_SCALE_MAX = 4;
+
+/** Minimum finger distance (px) considered a real pinch — rejects palm noise. */
+export const PINCH_DEADZONE_PX = 24;
+
+export function createPinchState() {
+ return { active: false, startDist: 0, baseScale: 1, scale: 1 };
+}
+
+/**
+ * Begin a pinch. Ignored (returns false) when the finger spread is inside the
+ * dead zone or inputs are not finite — the caller keeps treating input as taps.
+ *
+ * @param {ReturnType<createPinchState>} p
+ * @param {number} dist Distance between the two touch points, px.
+ * @param {number} baseScale The content's current uniform scale.
+ * @returns {boolean} true when the pinch is engaged.
+ */
+export function pinchStart(p, dist, baseScale) {
+ if (!Number.isFinite(dist) || dist < PINCH_DEADZONE_PX) return false;
+ const base = Number.isFinite(baseScale) && baseScale > 0 ? baseScale : 1;
+ p.active = true;
+ p.startDist = dist;
+ p.baseScale = base;
+ p.scale = base;
+ return true;
+}
+
+/**
+ * Advance an engaged pinch. Returns the new clamped scale, or null when no
+ * pinch is engaged or the distance is degenerate (caller applies nothing).
+ *
+ * @param {ReturnType<createPinchState>} p
+ * @param {number} dist Current distance between the two touch points, px.
+ * @returns {number|null}
+ */
+export function pinchMove(p, dist) {
+ if (!p.active || !Number.isFinite(dist) || dist <= 0 || p.startDist <= 0) return null;
+ const next = p.baseScale * (dist / p.startDist);
+ p.scale = Math.min(PINCH_SCALE_MAX, Math.max(PINCH_SCALE_MIN, next));
+ return p.scale;
+}
+
+/**
+ * End the pinch (a finger lifted). Returns the final scale to persist, or
+ * null when no pinch was engaged (a plain tap — nothing to save).
+ *
+ * @param {ReturnType<createPinchState>} p
+ * @returns {number|null}
+ */
+export function pinchEnd(p) {
+ if (!p.active) return null;
+ p.active = false;
+ return p.scale;
+}
+
+/**
+ * Clamp a persisted pin scale for rendering. Anything non-finite or
+ * non-positive (legacy pins, absent column) renders at natural size.
+ *
+ * @param {unknown} v Raw anchor_scale from the API (may be null/undefined).
+ * @returns {number}
+ */
+export function clampPinScale(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n) || n <= 0) return 1;
+ return Math.min(PINCH_SCALE_MAX, Math.max(PINCH_SCALE_MIN, n));
+}
diff --git a/src/ar/webxr.js b/src/ar/webxr.js
index e2c0c0f31..8323a2b5e 100644
--- a/src/ar/webxr.js
+++ b/src/ar/webxr.js
@@ -17,6 +17,7 @@ import {
advancePulse, isXrVisible, nextTrackingState, reticleVisual, TRACKING_LOSS_FRAMES,
} from './anchor-lifecycle.js';
import { DepthOcclusion } from './depth-occlusion.js';
+import { createPinchState, pinchEnd, pinchMove, pinchStart } from './pinch-scale.js';
/** prefers-reduced-motion: calm, static reticle/confirm states when set. */
function _prefersReducedMotion() {
@@ -66,8 +67,13 @@ export class WebXRSession {
* is foregrounded/backgrounded (lock, incoming call, app switch).
* @param {Element} [opts.domOverlayRoot] Element to surface as the WebXR
* `dom-overlay` root (in-session hint + exit affordance). Optional.
+ * @param {Function} [opts.onScale] Called with the new uniform scale as a
+ * two-finger pinch resizes the agent (and once more with the settled value
+ * when the pinch ends, flagged `{ final: true }`). Pinch-to-resize needs a
+ * dom-overlay root (touches are only observable through it) — without one
+ * the gesture is quietly unavailable, exactly as before.
*/
- constructor(viewer, { onEnd, halfBody = false, onAnchored, onHit, onTracking, onVisibility, domOverlayRoot } = {}) {
+ constructor(viewer, { onEnd, halfBody = false, onAnchored, onHit, onTracking, onVisibility, domOverlayRoot, onScale } = {}) {
this._viewer = viewer;
this._halfBody = halfBody;
this._onEnd = onEnd;
@@ -76,6 +82,18 @@ export class WebXRSession {
this._onTracking = onTracking;
this._onVisibility = onVisibility;
this._domOverlayRoot = domOverlayRoot ?? null;
+ this._onScale = onScale;
+ /** Pinch-to-resize state (pure math in ./pinch-scale.js). */
+ this._pinch = createPinchState();
+ /** Wall-clock of the last pinch end — a tap right after a pinch is the
+ * second finger lifting, not a placement intent. */
+ this._pinchEndedAt = 0;
+ /** Content scale captured at session start, restored on exit. */
+ this._savedScale = null;
+ this._handleTouchStart = this._handleTouchStart.bind(this);
+ this._handleTouchMove = this._handleTouchMove.bind(this);
+ this._handleTouchEnd = this._handleTouchEnd.bind(this);
+ this._handleBeforeSelect = this._handleBeforeSelect.bind(this);
this._session = null;
this._hitTestSource = null;
this._localSpace = null;
@@ -217,6 +235,20 @@ export class WebXRSession {
const content = viewer.content;
this._savedPos = content?.position.clone() ?? null;
this._savedRot = content?.rotation.clone() ?? null;
+ this._savedScale = content?.scale.clone() ?? null;
+
+ // Pinch-to-resize rides the dom-overlay: during immersive-ar, screen touches
+ // are only observable as DOM events on the overlay root. Two fingers resize
+ // the agent; `beforexrselect` suppresses the placement tap while (and just
+ // after) a pinch so the second finger can't accidentally place/anchor.
+ if (this._domOverlayRoot) {
+ const root = this._domOverlayRoot;
+ root.addEventListener('touchstart', this._handleTouchStart, { passive: true });
+ root.addEventListener('touchmove', this._handleTouchMove, { passive: true });
+ root.addEventListener('touchend', this._handleTouchEnd, { passive: true });
+ root.addEventListener('touchcancel', this._handleTouchEnd, { passive: true });
+ root.addEventListener('beforexrselect', this._handleBeforeSelect);
+ }
// Half-body mode is opt-in. The live AR button never sets it; only the
// /demos/halfbody preview passes halfBody:true.
@@ -333,11 +365,62 @@ export class WebXRSession {
renderer.render(viewer.scene, viewer.activeCamera);
}
+ // ── Pinch-to-resize ────────────────────────────────────────────────────────
+ // Raw touch geometry → the pure pinch state machine → a uniform scale on the
+ // content group (and its contact shadow, so the grounding grows with it).
+
+ static _touchDist(touches) {
+ const dx = touches[0].clientX - touches[1].clientX;
+ const dy = touches[0].clientY - touches[1].clientY;
+ return Math.hypot(dx, dy);
+ }
+
+ _handleTouchStart(e) {
+ if (e.touches.length !== 2) return;
+ const base = this._viewer.content?.scale?.x ?? 1;
+ pinchStart(this._pinch, WebXRSession._touchDist(e.touches), base);
+ }
+
+ _handleTouchMove(e) {
+ if (!this._pinch.active || e.touches.length !== 2) return;
+ const s = pinchMove(this._pinch, WebXRSession._touchDist(e.touches));
+ if (s == null) return;
+ this._applyContentScale(s);
+ this._onScale?.(s, { final: false });
+ }
+
+ _handleTouchEnd() {
+ const s = pinchEnd(this._pinch);
+ if (s == null) return;
+ this._pinchEndedAt = performance.now();
+ this._onScale?.(s, { final: true });
+ }
+
+ // While a pinch is live (or a beat after it ends), the tap must not place —
+ // the "tap" is just the second finger. Cancels the upcoming XR select event.
+ _handleBeforeSelect(e) {
+ if (this._pinch.active || performance.now() - this._pinchEndedAt < 350) {
+ e.preventDefault();
+ }
+ }
+
+ _applyContentScale(s) {
+ const content = this._viewer.content;
+ if (!content) return;
+ content.scale.setScalar(s);
+ // The contact shadow grounds the agent — grow it with the body so a
+ // statue-sized avatar doesn't stand on a coin-sized shadow.
+ if (this._shadow) this._shadow.scale.setScalar(s);
+ }
+
// First tap anchors the agent at the current hit-test position. Creates a real
// XRAnchor when the device supports it (survives the small tracking corrections
// a raw hit pose does not); falls back to frozen hit-follow otherwise.
async _handleSelect() {
if (this._anchored || !this._latestHit) return;
+ // Belt-and-braces with _handleBeforeSelect: some browsers deliver the select
+ // anyway — a pinch (or its trailing finger-lift) is never a placement.
+ if (this._pinch.active || performance.now() - this._pinchEndedAt < 350) return;
this._anchored = true;
// Capture the tap-moment pose now — before the anchor's own drift correction
// nudges it — so the persisted GPS pin matches where the user actually tapped.
@@ -601,6 +684,16 @@ export class WebXRSession {
// Stop listening before tearing down so a late visibilitychange during
// teardown can't re-pause a session that's already gone.
this._session?.removeEventListener('visibilitychange', this._handleVisibilityChange);
+ if (this._domOverlayRoot) {
+ const root = this._domOverlayRoot;
+ root.removeEventListener('touchstart', this._handleTouchStart);
+ root.removeEventListener('touchmove', this._handleTouchMove);
+ root.removeEventListener('touchend', this._handleTouchEnd);
+ root.removeEventListener('touchcancel', this._handleTouchEnd);
+ root.removeEventListener('beforexrselect', this._handleBeforeSelect);
+ }
+ this._pinch = createPinchState();
+ this._pinchEndedAt = 0;
renderer.setAnimationLoop(null);
renderer.xr.enabled = false;
@@ -631,9 +724,11 @@ export class WebXRSession {
viewer.scene.background = this._savedBg;
renderer.setClearColor(0x000000, 1);
- // Restore agent content to its pre-AR transform
+ // Restore agent content to its pre-AR transform (a pinch-resized scale is
+ // persisted on the pin, not carried back into the non-AR view).
if (viewer.content && this._savedPos) viewer.content.position.copy(this._savedPos);
if (viewer.content && this._savedRot) viewer.content.rotation.copy(this._savedRot);
+ if (viewer.content && this._savedScale) viewer.content.scale.copy(this._savedScale);
// Restore full-body bone scales captured at XR start (no-op when halfBody
// mode was never entered — _halfBodyBones is empty).
diff --git a/src/irl.js b/src/irl.js
index 9db5282f5..49ec6cf09 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -42,6 +42,7 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
import { WebXRSession } from './ar/webxr.js';
+import { clampPinScale } from './ar/pinch-scale.js';
import { resolvePlacementCapability } from './ar/placement-capability.js';
import { openQuickLook } from './ar/quick-look.js';
import { createPersistGate, placementHint } from './ar/anchor-lifecycle.js';
@@ -1587,6 +1588,11 @@ function pinYawRad(pin) {
: (pin.heading != null ? pin.heading : 0);
return -(deg * Math.PI / 180);
}
+// Pinch-resized render scale — the owner's chosen size, honoured for every
+// viewer. clampPinScale() maps a legacy/absent column to natural size (1).
+function pinScale(pin) {
+ return clampPinScale(pin.anchor_scale);
+}
function pinHeightM(pin) {
const h = pin.anchor_height_m;
// Honour only a small, genuine floor offset — a deliberate calibrate height
@@ -2333,6 +2339,9 @@ async function postRoomPin({ lat, lng, heading, room, anchor, vps = null }) {
gpsAccuracyM: anchor?.gpsAccuracyM ?? gpsState.accuracy,
altitudeM: anchor?.altitudeM ?? gpsState.altitude,
source: anchor?.source || 'gyro-gps',
+ // Pinch-resized size (WebXR path) — omitted at natural scale so
+ // non-XR placements are byte-identical to before.
+ scale: Number.isFinite(anchor?.scale) && anchor.scale !== 1 ? anchor.scale : undefined,
},
// Visual-positioning identity (Epic M) — present only on a marker
// placement; the server persists it to vps_provider/vps_id and ignores it
@@ -2363,6 +2372,7 @@ async function postRoomPin({ lat, lng, heading, room, anchor, vps = null }) {
heading: h, anchor_yaw_deg: anchor?.yawDeg ?? h,
anchor_height_m: anchor?.heightM ?? 0,
anchor_quat: quat,
+ anchor_scale: Number.isFinite(anchor?.scale) && anchor.scale !== 1 ? anchor.scale : null,
anchor_source: anchor?.source || 'gyro-gps',
vps_provider: vps?.id ? (vps.provider || 'qr') : null, vps_id: vps?.id || null,
room_id: room.id, rel_east_m: room.relEast, rel_north_m: room.relNorth,
@@ -2378,7 +2388,7 @@ async function postRoomPin({ lat, lng, heading, room, anchor, vps = null }) {
updateNearbyBadge();
revealMyPinsBtn();
}
- return { ok: true, id: pin.id };
+ return { ok: true, id: pin.id, permanent: data.pin.permanent === true };
} catch {
return { ok: false, error: 'network', message: saveErrorFallback('network') };
}
@@ -2847,6 +2857,38 @@ let markerModeApi = null;
// enterFloorPlacement clears it so a plain "Place on floor" never re-targets a stale
// pin. Bounds-checked server-side — refine only sharpens this one agent's offset.
let _refinePin = null;
+// Pinch-resize state for the live WebXR session. _xrScale is the current uniform
+// scale the user pinched to (1 = natural); it rides into the pin persisted on the
+// placement tap. A pinch AFTER the tap (the usual order — place first, then size)
+// lands as an owner-gated PATCH against _xrPlacedPinId, so the final size always
+// wins no matter which order the gestures happened in.
+let _xrScale = 1;
+let _xrPlacedPinId = null;
+
+function onXrScaled(scale, { final } = {}) {
+ _xrScale = scale;
+ setXrResting(`Size ${Math.round(scale * 100)}% — pinch to resize`);
+ if (!final || !_xrPlacedPinId) return;
+ const pinId = _xrPlacedPinId;
+ fetch('/api/irl/pins', {
+ method: 'PATCH', credentials: 'include',
+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),
+ body: JSON.stringify({ id: pinId, deviceToken: _deviceToken, scale }),
+ }).then((r) => {
+ if (!r.ok) { setXrResting('Placed — the new size couldn’t be saved, pinch again to retry'); return; }
+ // Commit onto the live local pin so the size holds after the session ends
+ // (the XR exit restores the avatar rig itself to its pre-AR transform).
+ const pin = nearbyPins.find((p) => p.id === pinId);
+ if (pin) {
+ pin.anchor_scale = scale;
+ if (pin.group && pin._spawnT >= SPAWN_DURATION) pin.group.scale.setScalar(pinScale(pin));
+ }
+ setXrResting(`Saved at ${Math.round(scale * 100)}% size — nearby viewers see it this big too`);
+ }).catch(() => {
+ setXrResting('Placed — the new size couldn’t be saved (offline?), pinch again to retry');
+ });
+}
+
// A floor anchor placed before the first GPS fix is held here and persisted the
// instant onGPSPosition() lands real coordinates (mirrors _pendingGpsLock for the
// gyro path). The in-session XRAnchor already glues the agent; this rescues its
@@ -2907,6 +2949,9 @@ async function detectFloorAnchorSupport() {
anchorBtn.setAttribute('aria-label', _placementCapability === 'quicklook'
? 'View your agent on the floor in AR (iOS Quick Look)'
: 'Place agent on the floor with AR');
+ // This device has a true AR surface — lead with it. The gyro Pin path stays
+ // one pill away, but the flagship placement should be the first thing seen.
+ anchorBtn.parentElement?.prepend(anchorBtn);
anchorBtn.hidden = false;
}
@@ -2969,12 +3014,16 @@ async function enterFloorAnchor() {
if (anchorBtn) anchorBtn.classList.add('is-active');
if (xrOverlay) xrOverlay.hidden = false;
resetXrHint();
+ // Fresh session, fresh size: the pinch composes from natural scale, and there
+ // is no placed pin yet for a resize PATCH to target.
+ _xrScale = 1;
+ _xrPlacedPinId = null;
let failedStart = false;
try {
xrSession = new WebXRSession(xrViewer, {
domOverlayRoot: xrOverlay,
- onHit: (has) => setXrResting(has ? 'Looks good — tap to place your agent' : SEARCHING_HINT),
+ onHit: (has) => setXrResting(has ? 'Looks good — tap to place, pinch to resize' : SEARCHING_HINT),
// Tracking loss / recovery is a transient, higher-priority overlay on the
// resting hint — recoverable, self-clearing, never a dead reticle.
onTracking: (ok) => { xrHintState.trackingLost = !ok; renderXrHint(); },
@@ -2982,6 +3031,9 @@ async function enterFloorAnchor() {
// resume hint and restore the resting line when foregrounded again.
onVisibility: (visible) => { xrHintState.paused = !visible; renderXrHint(); },
onAnchored: (pose, meta) => onFloorAnchored(pose, meta),
+ // Two-finger pinch resizes the agent live; the final value persists onto
+ // the placed pin (or rides into the tap's pin when sized before placing).
+ onScale: (scale, meta) => onXrScaled(scale, meta),
onEnd: () => {
xrSession = null;
// Drop any anchor still waiting on a GPS fix — the user left this
@@ -3125,13 +3177,16 @@ function persistFloorAnchor(pose, degraded = false) {
anchor: {
heightM: placement.heightM, yawDeg: placement.relYawDeg, quat: placement.quat,
gpsAccuracyM: gpsState.accuracy, altitudeM: gpsState.altitude, source: 'webxr',
+ scale: _xrScale,
},
}).then(result => {
if (result?.ok) {
+ // Later pinches in this session resize THIS pin (owner-gated PATCH).
+ _xrPlacedPinId = result.id;
roomModeApi?.notePlacement();
setXrResting(result.permanent
- ? 'Saved on the floor — your agent is here for everyone nearby'
- : 'Saved on the floor — people nearby can see your agent for 7 days');
+ ? 'Saved on the floor — pinch to resize; your agent is here for everyone nearby'
+ : 'Saved on the floor — pinch to resize; people nearby can see your agent for 7 days');
} else {
// Surface the moderation/cap/rate reason; the in-session anchor still holds.
setXrResting(result?.message || 'Placed — couldn’t save the pin yet, retry on exit');
@@ -6417,9 +6472,10 @@ function updateAgentAwareness(dt) {
if (pin.popT >= POP_DURATION) {
pin.popT = -1;
pin._popAmp = 0;
- pin.group.scale.y = 1;
+ pin.group.scale.y = pinScale(pin);
} else {
- pin.group.scale.y = 1 + amp * Math.sin(Math.PI * pin.popT / POP_DURATION);
+ // The pop rides on top of the pin's persisted size (scale.x/z untouched).
+ pin.group.scale.y = pinScale(pin) * (1 + amp * Math.sin(Math.PI * pin.popT / POP_DURATION));
}
}
@@ -6755,14 +6811,15 @@ function tick() {
if (pin.group && pin._spawnT < SPAWN_DURATION) {
pin._spawnT += dt;
const t = Math.min(1, pin._spawnT / SPAWN_DURATION);
- pin.group.scale.setScalar(1 - Math.pow(1 - t, 3));
+ // Ease up to the owner's pinch-resized size, not a hardcoded 1.
+ pin.group.scale.setScalar((1 - Math.pow(1 - t, 3)) * pinScale(pin));
}
}
for (let i = _despawningPins.length - 1; i >= 0; i--) {
const pin = _despawningPins[i];
pin._despawnT += dt;
const t = Math.min(1, pin._despawnT / DESPAWN_DURATION);
- if (pin.group) pin.group.scale.setScalar(Math.max(0.001, (1 - t) * (1 - t)));
+ if (pin.group) pin.group.scale.setScalar(Math.max(0.001, (1 - t) * (1 - t) * pinScale(pin)));
if (t >= 1) { disposePin(pin); _despawningPins.splice(i, 1); }
}
diff --git a/tests/api/irl-pins-anchor-pose.test.js b/tests/api/irl-pins-anchor-pose.test.js
index 94270e03d..9b8c55647 100644
--- a/tests/api/irl-pins-anchor-pose.test.js
+++ b/tests/api/irl-pins-anchor-pose.test.js
@@ -25,14 +25,14 @@ const sqlMock = vi.fn((strings, ...values) => {
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,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
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,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source, geocell7,
view_count: 0, avatar_version: 0,
}]);
@@ -170,6 +170,26 @@ describe('POST /api/irl/pins — anchor pose persistence (A2)', () => {
expect(weird.pin.anchor_source).toBe('gyro-gps');
});
+ it('persists a pinch-resized scale, clamped to the 0.25–4 band', async () => {
+ const { body: ok } = await post({ ...basePin(), anchor: { source: 'webxr', scale: 2.5 } });
+ expect(ok.pin.anchor_scale).toBe(2.5);
+ const { body: huge } = await post({ ...basePin(), anchor: { source: 'webxr', scale: 50 } });
+ expect(huge.pin.anchor_scale).toBe(4);
+ const { body: tiny } = await post({ ...basePin(), anchor: { source: 'webxr', scale: 0.01 } });
+ expect(tiny.pin.anchor_scale).toBe(0.25);
+ });
+
+ it('stores NULL scale for natural size, absent scale, and garbage — never noise', async () => {
+ const { body: natural } = await post({ ...basePin(), anchor: { source: 'webxr', scale: 1 } });
+ expect(natural.pin.anchor_scale).toBeNull();
+ const { body: absent } = await post({ ...basePin(), anchor: { source: 'webxr' } });
+ expect(absent.pin.anchor_scale).toBeNull();
+ const { body: garbage } = await post({ ...basePin(), anchor: { source: 'webxr', scale: 'big' } });
+ expect(garbage.pin.anchor_scale).toBeNull();
+ const { body: negative } = await post({ ...basePin(), anchor: { source: 'webxr', scale: -3 } });
+ expect(negative.pin.anchor_scale).toBeNull();
+ });
+
it('persists pose for an authenticated owner and marks the pin permanent', async () => {
sessionUser = { id: 'owner-uuid' };
const { res, body } = await post({
diff --git a/tests/api/irl-pins-placement-consent.test.js b/tests/api/irl-pins-placement-consent.test.js
index 02036ef99..eb30908b8 100644
--- a/tests/api/irl-pins-placement-consent.test.js
+++ b/tests/api/irl-pins-placement-consent.test.js
@@ -21,7 +21,7 @@ const sqlMock = vi.fn((strings, ...values) => {
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,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source, geocell7,
room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg,
placement_kind, fuzz_radius_m, vps_provider, vps_id,
diff --git a/tests/api/irl-pins-room.test.js b/tests/api/irl-pins-room.test.js
index 01112a181..674b29690 100644
--- a/tests/api/irl-pins-room.test.js
+++ b/tests/api/irl-pins-room.test.js
@@ -24,7 +24,7 @@ const sqlMock = vi.fn((strings, ...values) => {
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,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source, geocell7,
room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg,
] = values;
@@ -32,7 +32,7 @@ const sqlMock = vi.fn((strings, ...values) => {
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,
+ anchor_height_m, anchor_yaw_deg, anchor_quat, anchor_scale,
gps_accuracy_m, altitude_m, anchor_source, geocell7,
room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg,
view_count: 0, avatar_version: 0,
diff --git a/tests/api/irl-pins-scale.test.js b/tests/api/irl-pins-scale.test.js
new file mode 100644
index 000000000..26732aeae
--- /dev/null
+++ b/tests/api/irl-pins-scale.test.js
@@ -0,0 +1,130 @@
+// PATCH /api/irl/pins { scale } — pinch-to-resize persistence.
+//
+// A pinch during the WebXR placement session usually happens AFTER the pin was
+// persisted on the placement tap, so the final size arrives as an owner-gated
+// PATCH. Because a resized agent re-renders at that size for EVERY nearby
+// viewer, the server is the security boundary: it must reject non-owners,
+// refuse expired/hidden pins, and clamp the scale to the same 0.25–4 band the
+// gesture and the POST path enforce. The DB / auth / limiter are mocked so the
+// suite stays offline — mirrors tests/api/irl-pins-calibrate.test.js.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Content-addressed SQL mock: the ownership SELECT returns `pinRow` (null →
+// "not found"); the UPDATE echoes back the bound scale so success-path
+// assertions see exactly what would persist.
+let pinRow = null;
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/SELECT[\s\S]*FROM irl_pins[\s\S]*WHERE id =/i.test(q)) {
+ return Promise.resolve(pinRow ? [pinRow] : []);
+ }
+ if (/UPDATE irl_pins SET anchor_scale/i.test(q)) {
+ const [scale, id] = values;
+ return Promise.resolve([{ id, anchor_scale: scale }]);
+ }
+ // CREATE TABLE / ALTER TABLE / CREATE INDEX from ensureTable(), and anything else.
+ return Promise.resolve([]);
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a), isDbUnavailableError: () => false, isDbCapacityError: () => false }));
+
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { irlPinIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: handler } = await import('../../api/irl/pins.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+async function patch(body) {
+ const res = makeRes();
+ await handler({ url: '/api/irl/pins', method: 'PATCH', headers: { host: 'x' }, query: {}, body }, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch {}
+ return { res, body: parsed };
+}
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ sessionUser = null;
+ pinRow = {
+ id: 'pin-1',
+ user_id: null,
+ device_token: 'device-A',
+ expires_at: null,
+ hidden_at: null,
+ };
+});
+
+describe('PATCH /api/irl/pins { scale } — resize persistence', () => {
+ it('lets the placing device resize its own pin', async () => {
+ const { res, body } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 2.5 });
+ expect(res.statusCode).toBe(200);
+ expect(body.pin.anchor_scale).toBe(2.5);
+ });
+
+ it('lets the authenticated owner resize', async () => {
+ pinRow.user_id = 'owner-uuid';
+ pinRow.device_token = null;
+ sessionUser = { id: 'owner-uuid' };
+ const { res, body } = await patch({ id: 'pin-1', scale: 0.5 });
+ expect(res.statusCode).toBe(200);
+ expect(body.pin.anchor_scale).toBe(0.5);
+ });
+
+ it('rejects a non-owner — resizing someone else’s agent is denied, never silent', async () => {
+ const { res } = await patch({ id: 'pin-1', deviceToken: 'device-EVIL', scale: 4 });
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('clamps to the shared 0.25–4 band', async () => {
+ const { body: huge } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 100 });
+ expect(huge.pin.anchor_scale).toBe(4);
+ const { body: tiny } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 0.001 });
+ expect(tiny.pin.anchor_scale).toBe(0.25);
+ });
+
+ it('stores NULL for natural size (scale 1) so legacy readers see no change', async () => {
+ const { res, body } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 1 });
+ expect(res.statusCode).toBe(200);
+ expect(body.pin.anchor_scale).toBeNull();
+ });
+
+ it('rejects garbage scales', async () => {
+ const { res: nan } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 'big' });
+ expect(nan.statusCode).toBe(400);
+ const { res: neg } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: -2 });
+ expect(neg.statusCode).toBe(400);
+ });
+
+ it('refuses an expired or hidden pin (nobody would ever see the new size)', async () => {
+ pinRow.expires_at = '2020-01-01T00:00:00Z';
+ const { res: expired } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 2 });
+ expect(expired.statusCode).toBe(404);
+ pinRow.expires_at = null;
+ pinRow.hidden_at = '2026-01-01T00:00:00Z';
+ const { res: hidden } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 2 });
+ expect(hidden.statusCode).toBe(404);
+ });
+
+ it('404s on a pin that does not exist', async () => {
+ pinRow = null;
+ const { res } = await patch({ id: 'pin-1', deviceToken: 'device-A', scale: 2 });
+ expect(res.statusCode).toBe(404);
+ });
+});
diff --git a/tests/ar-pinch-scale.test.js b/tests/ar-pinch-scale.test.js
new file mode 100644
index 000000000..a4856aee1
--- /dev/null
+++ b/tests/ar-pinch-scale.test.js
@@ -0,0 +1,118 @@
+// Pure pinch-to-resize math (src/ar/pinch-scale.js).
+//
+// The contract these tests pin is the WebXR resize gesture: a two-finger pinch
+// during placement must scale the agent by the ratio of finger spread, compose
+// across consecutive pinches (never snap back to 1), clamp to the same band the
+// server enforces, and reject palm noise inside the dead zone. clampPinScale is
+// the read half — every viewer renders a persisted anchor_scale through it, so
+// legacy pins (NULL column) and garbage must map to natural size, not NaN.
+// Pure math, no DOM / Three.js — mirrors tests/irl-floor-anchor.test.js.
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ clampPinScale, createPinchState, pinchEnd, pinchMove, pinchStart,
+ PINCH_DEADZONE_PX, PINCH_SCALE_MAX, PINCH_SCALE_MIN,
+} from '../src/ar/pinch-scale.js';
+
+describe('pinchStart', () => {
+ it('engages on a real finger spread and captures the base scale', () => {
+ const p = createPinchState();
+ expect(pinchStart(p, 120, 1.5)).toBe(true);
+ expect(p.active).toBe(true);
+ expect(p.baseScale).toBe(1.5);
+ });
+
+ it('rejects spreads inside the dead zone (palm noise)', () => {
+ const p = createPinchState();
+ expect(pinchStart(p, PINCH_DEADZONE_PX - 1, 1)).toBe(false);
+ expect(p.active).toBe(false);
+ });
+
+ it('treats a missing/invalid base scale as natural size', () => {
+ const p = createPinchState();
+ pinchStart(p, 100, NaN);
+ expect(p.baseScale).toBe(1);
+ const q = createPinchState();
+ pinchStart(q, 100, 0);
+ expect(q.baseScale).toBe(1);
+ });
+});
+
+describe('pinchMove', () => {
+ it('scales by the ratio of finger spread', () => {
+ const p = createPinchState();
+ pinchStart(p, 100, 1);
+ expect(pinchMove(p, 200)).toBeCloseTo(2);
+ expect(pinchMove(p, 50)).toBeCloseTo(0.5);
+ });
+
+ it('composes with the scale the content already had', () => {
+ const p = createPinchState();
+ pinchStart(p, 100, 2); // agent already pinched to 2x earlier
+ expect(pinchMove(p, 150)).toBeCloseTo(3);
+ });
+
+ it('clamps to the shared band', () => {
+ const p = createPinchState();
+ pinchStart(p, 100, 1);
+ expect(pinchMove(p, 10000)).toBe(PINCH_SCALE_MAX);
+ expect(pinchMove(p, 1)).toBe(PINCH_SCALE_MIN);
+ });
+
+ it('returns null when not engaged or on degenerate distances', () => {
+ const p = createPinchState();
+ expect(pinchMove(p, 200)).toBe(null); // never started
+ pinchStart(p, 100, 1);
+ expect(pinchMove(p, NaN)).toBe(null);
+ expect(pinchMove(p, 0)).toBe(null);
+ });
+});
+
+describe('pinchEnd', () => {
+ it('returns the final scale exactly once', () => {
+ const p = createPinchState();
+ pinchStart(p, 100, 1);
+ pinchMove(p, 300);
+ expect(pinchEnd(p)).toBeCloseTo(3);
+ expect(p.active).toBe(false);
+ expect(pinchEnd(p)).toBe(null); // a plain tap after — nothing to save
+ });
+
+ it('a second pinch composes from where the first ended', () => {
+ const p = createPinchState();
+ pinchStart(p, 100, 1);
+ pinchMove(p, 200);
+ const first = pinchEnd(p); // 2x
+ pinchStart(p, 100, first);
+ pinchMove(p, 150);
+ expect(pinchEnd(p)).toBeCloseTo(3); // 2x · 1.5 — no snap back to 1
+ });
+});
+
+describe('clampPinScale (render read path)', () => {
+ it('maps a legacy/absent column to natural size', () => {
+ expect(clampPinScale(null)).toBe(1);
+ expect(clampPinScale(undefined)).toBe(1);
+ });
+
+ it('maps garbage to natural size, never NaN', () => {
+ expect(clampPinScale('huge')).toBe(1);
+ expect(clampPinScale(NaN)).toBe(1);
+ expect(clampPinScale(-2)).toBe(1);
+ expect(clampPinScale(0)).toBe(1);
+ });
+
+ it('passes valid scales through, clamped to the shared band', () => {
+ expect(clampPinScale(0.5)).toBe(0.5);
+ expect(clampPinScale(2)).toBe(2);
+ expect(clampPinScale('1.75')).toBe(1.75); // numeric string from JSON is fine
+ expect(clampPinScale(100)).toBe(PINCH_SCALE_MAX);
+ expect(clampPinScale(0.01)).toBe(PINCH_SCALE_MIN);
+ });
+
+ it('agrees with the gesture clamp band', () => {
+ expect(PINCH_SCALE_MIN).toBeLessThan(1);
+ expect(PINCH_SCALE_MAX).toBeGreaterThan(1);
+ });
+});