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
feat(irl): iPhone Place in AR bakes the animated idle USDZ
nirholasc63a0864423b
diff --git a/.gitignore b/.gitignoreindex c524d73ee..d2f24a942 100644--- a/.gitignore+++ b/.gitignore@@ -381,3 +381,4 @@ prompts/robinhood-chain/11-toolkit-cli.md# archives at repo root are never committed/*.zip+tests/openai-comarketing-language.test.jsdiff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 71cc0eeac..ab4a999ff 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -611,7 +611,7 @@ Representative endpoints:| `POST /api/tts/speak` | NVIDIA Magpie (primary), OpenAI TTS (backstop) | Text → speech || `POST /api/asr` | NVIDIA Riva (gRPC) | Speech → text || `POST /api/a2f` | NVIDIA Audio2Face-3D (gRPC) | Audio → ARKit 52 blendshapes |-| `POST /api/vision` | NVIDIA NIM VLM → OpenAI gpt-4o-mini (backstop) | Image understanding |+| `POST /api/vision` | NVIDIA NIM VLM → OpenAI gpt-5.4-nano (backstop) | Image understanding || `POST /api/cosmos` | NVIDIA Cosmos | Text → world video (MP4, async) |#### Memory (`api/agent-memory.js`, `api/memory/*`)@@ -1429,7 +1429,7 @@ flowchart TDB["OpenRouter\nmeta-llama/llama-3.3-70b:free · openai/gpt-oss-120b:free"]C["NVIDIA NIM\nnemotron-super-120b · nemotron-super-49b · deepseek-v4-pro"]D["Anthropic\nclaude-sonnet-4-6"]- E["OpenAI\ngpt-4o-mini"]+ E["OpenAI\ngpt-5.4-nano"]F["IBM watsonx Orchestrate"]A -->|fallback| B -->|fallback| C -->|fallback| D -->|fallback| E -->|fallback| F```@@ -1441,7 +1441,7 @@ flowchart TD| Tier | Models ||------|--------|| Anthropic | claude-fable-5, claude-mythos-5 (restricted, moderation-gated, never auto-selected), claude-opus-4-7, claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5 (native `claude-haiku-4-5-20251001`) |-| OpenAI | gpt-4o, gpt-4o-mini, o3-mini |+| OpenAI | gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, gpt-5.5, gpt-5.5-pro, gpt-5.4 (+ pro/mini/nano), gpt-5.3-codex, o3, o3-pro (legacy gpt-4o/gpt-4o-mini/o3-mini ids alias forward) || NVIDIA NIM | `nvidia/nemotron-3-super-120b-a12b`, `nvidia/nvidia-nemotron-nano-9b-v2`, `deepseek-ai/deepseek-v4-pro`, `moonshotai/kimi-k2.6`, `meta/llama-4-maverick-17b-128e-instruct`, `minimaxai/minimax-m2.7` || IBM watsonx | `ibm-granite` (Granite 3.8B Instruct) || Groq | llama-3.3-70b-versatile, llama-3.1-8b-instant |@@ -1505,7 +1505,7 @@ flowchart TDVLM -->|"lane 2"| VLM2["meta/llama-3.2-11b-vision-instruct"]VLM --> DESC["description"]VLM2 --> DESC- VLM2 -->|"backstop"| MINI["OpenAI gpt-4o-mini"]+ VLM2 -->|"backstop"| MINI["OpenAI gpt-5.4-nano"]MINI --> DESC```@@ -2196,7 +2196,7 @@ sequenceDiagram| Service | Models / Usage ||---------|---------------|| Anthropic | claude-fable-5, claude-mythos-5, claude-opus-4-7, claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5 (chat, brain, reflect) |-| OpenAI | gpt-4o, gpt-4o-mini, o3-mini, text-embedding-3-small, TTS |+| OpenAI | GPT-5.6 family (sol/terra/luna), GPT-5.5 + GPT-5.4 tiers, gpt-5.3-codex, o3/o3-pro, text-embedding-3-small, TTS || NVIDIA NIM | Nemotron-super-120b, DeepSeek-v4-pro, Kimi-k2.6, Llama-4-Maverick, MiniMax-M2.7, nv-embedqa-e5-v5 || NVIDIA NIM Vision | Nemotron-nano-12B-v2-VL, Llama-3.2-11B-vision || NVIDIA Magpie TTS | gRPC/NVCF, multilingual TTS |@@ -2814,7 +2814,7 @@ The Python/FastAPI workers in `workers/` run on Google Cloud Run (GPU). Each exp| `POST /api/tts/eleven` · `eleven-clone` | `api/tts/eleven*.js` | ElevenLabs premium TTS + voice cloning || `POST /api/asr` | NVIDIA Riva (gRPC) | Free speech-to-text (voice in) || `POST /api/a2f` | NVIDIA Audio2Face-3D (gRPC) | Free audio → ARKit-52 facial animation |-| `POST /api/vision` | NVIDIA NIM VLM → OpenAI gpt-4o-mini | Public image understanding |+| `POST /api/vision` | NVIDIA NIM VLM → OpenAI gpt-5.4-nano | Public image understanding || `POST /api/cosmos` | NVIDIA Cosmos | Text → ~5s 1280×704@24fps world video (async MP4) |gRPC protobufs are vendored under `api/_lib/riva-protos/` and `api/_lib/a2f-protos/`; these endpoints require the Node runtime (not Edge).diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0a94128d..30c4c3467 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,10 +16,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`- **Cleaner pages: sitemap header fits, stray glow clipped, quieter console** — A site-wide polish pass on cosmetic issues found in a full-site sweep. The /sitemap page now uses the standard site header instead of a cramped custom top bar that pushed the navigation past the right edge of the screen. The walk companion's caption bubble and the decorative glow on /x402-revenue are both capped so they can never spill outside the viewport or cause sideways scrolling. The companion's expected avatar fallback (a non-humanoid model handing off to the robot) no longer prints a warning on every page view, and the live demo frames on /labs and /integrations no longer trigger a browser sandbox warning. (`/sitemap`) `[fix]`- **Coin Clash, coin worlds, and the sign-in page fail gracefully** — When the community battle service is offline, /clash and the /temporary world picker used to keep retrying and logging failed requests in the background. Both now recognize the outage on the first response, stop polling, and show a clear notice with live places to go instead (launches, markets, or walking the default world solo). The sign-in page also no longer throws a background error if its 3D greeter can't load; the form works exactly the same without him. (`/clash`) `[fix]`+- **IRL avatars now move in iPhone AR** — Tapping Place in AR on the IRL page from an iPhone now bakes your agent's idle animation into the AR preview, so it breathes and shifts on your real floor instead of standing frozen in a T-pose. If an avatar's rig can't take the animation, the proven static preview still opens, so AR always works. (`/irl`) `[improvement, fix]`- **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]`- **Launching a coin is clearer at every step** — The coin launch page now guides you properly: signed-out and no-agents states have one obvious button instead of buried links, the agent picker supports arrow keys and never shows a broken thumbnail, and the form has live character counters against pump.fun's real limits, auto-uppercased tickers, and inline validation. While a launch runs you see each stage progress, and success now links the actual transaction on Solscan next to your coin page. A subtle bug is also gone: retrying a launch after swapping the image no longer reuses the old image's metadata. (`/launch`) `[improvement, fix]`- **Launchpad Studio: loading, saving, and publishing you can trust** — The studio now shows a real loading state while it fetches a saved launchpad and a clear recovery screen if that fetch fails, instead of silently dropping you into a blank draft. Publishing validates your slug and wallet address inline before any network call, success puts your live URL front and center with a copy button, and a failure keeps your last live URL and offers retry. Edits to a published page warn before you navigate away, the editor finally works on phones with a stacked layout, and the Publish button is no longer white text on a white background. (`/launchpad`) `[improvement, fix]`- **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]`+- **Play and Club run cooler: smart frame caps and a power-saver toggle** — The 3D worlds on /play and /club used to render at your monitor's full refresh rate (up to 144+ frames a second) and kept working at full quality even when you clicked over to another window, which made laptops run hot with fans spinning. Both pages now cap rendering at 60fps, drop to 30fps whenever the window is in the background, and /play stops rendering the hidden 3D arena behind the coin-picker lobby entirely. There's also a new Eco toggle (the lightning button in /play, a checkbox in the /club panel) that holds everything at 30fps with lighter effects for a cooler, quieter machine; the setting is shared across both pages. (`/play`) `[improvement, fix]`- **Shared 3D viewer links load again** — Opening a shared model link at /viewer could hang on the loading spinner forever even though the model file itself was fine. The viewer now reveals the model as soon as it finishes rendering, and if a model genuinely cannot display, you get a clear message and a working download button instead of an endless spinner. (`/viewer`) `[fix]`- **The 3D viewer now funnels every model into a next step** — Every generated model's share page grew a "Do more with this model" panel: pose and animate it in Pose Studio (rigged models are detected automatically), restyle the material, drop it into Scene Studio or Parts Studio, place it in your room in AR, copy a paste-anywhere embed iframe, or launch it as a pump.fun coin with a rendered snapshot pre-filled as the token image. The viewer can now also be embedded on any site. (`/viewer`) `[feature, improvement]`- **The Agora and City worlds survive OpenStreetMap outages** — The 3D city on /agora and /city is built from live OpenStreetMap data, and a single overloaded map server used to mean an empty world with no buildings. Map data now fails over across three independent OpenStreetMap mirrors, and if every mirror is down the world rebuilds from the last map snapshot saved in your browser, so Manhattan stays standing even when the map providers do not. (`/agora`) `[fix, improvement]`diff --git a/chat/src/convo.js b/chat/src/convo.jsindex 727ea2ad3..f717fb7d7 100644--- a/chat/src/convo.js+++ b/chat/src/convo.js@@ -115,7 +115,7 @@ export async function complete(convo, onupdate, onabort) {param.reasoningEffort['range'] > 0)? undefined: param.temperature,- ...(model.provider === 'OpenAI' && (model.id === 'o4-mini' || model.id === 'o3')+ ...(model.provider === 'OpenAI' && model.kind === 'reasoner'? {max_completion_tokens:param.maxTokens != null && param.maxTokens > 0 ? param.maxTokens : undefined,diff --git a/chat/src/providers.js b/chat/src/providers.jsindex 03c099a8d..3d02f4e5d 100644--- a/chat/src/providers.js+++ b/chat/src/providers.js@@ -175,10 +175,12 @@ const capabilities = {'text-moderation-007',].includes(id) ||id.includes('realtime-preview') ||- id.includes('audio-preview'),+ id.includes('audio-preview') ||+ id.startsWith('gpt-image'),isMultimodal: (id) =>id === 'chatgpt-4o-latest' ||+ id.startsWith('gpt-5') ||id.startsWith('gpt-4o') ||(id.startsWith('gpt-4-turbo') && id !== 'gpt-4-turbo-preview') ||id === 'o3' ||@@ -187,12 +189,14 @@ const capabilities = {!id.startsWith('o1-mini') &&!id.startsWith('o1-preview')),- isReasoner: (id) => id.startsWith('o1') || id.startsWith('o3') || id.startsWith('o4'),+ isReasoner: (id) =>+ id.startsWith('gpt-5') || id.startsWith('o1') || id.startsWith('o3') || id.startsWith('o4'),isImageGenerator: (id) => ['dall-e-3'].includes(id),reasoningEffortControls: (id) =>(!id.startsWith('o1-preview') && !id.startsWith('o1-mini') && id.startsWith('o1')) ||+ id.startsWith('gpt-5') ||id.startsWith('o3') ||id.startsWith('o4')? 'low-medium-high'@@ -387,6 +391,8 @@ export const priorityOrder = [],},{ exactly: ['deepseek/deepseek-r1', 'deepseek/deepseek-chat'] },+ { startsWith: ['gpt-5.6', 'openai/gpt-5.6'] },+ { startsWith: ['gpt-5', 'openai/gpt-5'] },{exactly: ['openai/o4-mini',diff --git a/data/changelog.json b/data/changelog.jsonindex 3eb512bb7..3f639cc67 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-14",+ "title": "IRL avatars now move in iPhone AR",+ "summary": "Tapping Place in AR on the IRL page from an iPhone now bakes your agent's idle animation into the AR preview, so it breathes and shifts on your real floor instead of standing frozen in a T-pose. If an avatar's rig can't take the animation, the proven static preview still opens, so AR always works.",+ "tags": [+ "improvement",+ "fix"+ ],+ "link": "/irl"+ },{"date": "2026-07-14","title": "The on-chain deploy wizard got a full polish pass",@@ -13730,6 +13740,26 @@"improvement"],"link": "/viewer"+ },+ {+ "date": "2026-07-14",+ "title": "Play and Club run cooler: smart frame caps and a power-saver toggle",+ "summary": "The 3D worlds on /play and /club used to render at your monitor's full refresh rate (up to 144+ frames a second) and kept working at full quality even when you clicked over to another window, which made laptops run hot with fans spinning. Both pages now cap rendering at 60fps, drop to 30fps whenever the window is in the background, and /play stops rendering the hidden 3D arena behind the coin-picker lobby entirely. There's also a new Eco toggle (the lightning button in /play, a checkbox in the /club panel) that holds everything at 30fps with lighter effects for a cooler, quieter machine; the setting is shared across both pages.",+ "tags": [+ "improvement",+ "fix"+ ],+ "link": "/play"+ },+ {+ "date": "2026-07-14",+ "title": "Everything OpenAI, brought up to the GPT-5.6 era",+ "summary": "The whole OpenAI surface caught up with the current model family. The agent-brain tutorial, API reference, and architecture docs now describe the real lineup (GPT-5.6 Sol, Terra, and Luna, plus the GPT-5.5 and 5.4 tiers and o3), the agent-creation wizard offers GPT-5.6 Sol as its OpenAI pick, and the built-in chat app now recognizes GPT-5.x models properly: vision input, reasoning-effort controls, and the right token limits. The ChatGPT 3D Studio docs also grew: how the inline persona widget renders a living agent body, and the full REST contract behind the three.ws 3D Studio custom GPT. Old model names like gpt-4o keep working everywhere as aliases.",+ "tags": [+ "improvement",+ "docs"+ ],+ "link": "/docs/mcp-studio"}]}diff --git a/data/pages.json b/data/pages.jsonindex 4170a9658..84da93a2f 100644--- a/data/pages.json+++ b/data/pages.json@@ -2060,6 +2060,12 @@"description": "Expose your agent as an MCP server for Claude, ChatGPT, and other clients.","added": "2026-04-27"},+ {+ "path": "/docs/mcp-studio",+ "title": "Docs · 3D Studio MCP (free)",+ "description": "The free, no-auth MCP server behind the ChatGPT 3D Studio app: text and image to 3D, rigged avatars, conversational refinement, and living agent personas.",+ "added": "2026-07-14"+ },{"path": "/docs/mcp-scenes","title": "Docs · Scenes MCP",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex d9497ff3b..ae7747729 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -586,12 +586,14 @@ Server-Sent Events stream from a unified multi-provider LLM gateway. Used by the| `claude-opus-4-7` | Anthropic | flagship || `claude-sonnet-4-6` | Anthropic | balanced || `claude-haiku-4-5` | Anthropic | fast |-| `gpt-4o` | OpenAI | flagship |-| `gpt-4o-mini` | OpenAI | fast |+| `gpt-5.6-sol` | OpenAI | flagship |+| `gpt-5.6-terra` | OpenAI | balanced |+| `gpt-5.6-luna` | OpenAI | fast |+| `o3` / `o3-pro` | OpenAI | reasoning || `qwen-*` | Qwen / Alibaba | varies || `openrouter:*` | OpenRouter (any) | varies |-Call `GET /api/brain/chat` for the live list of providers actually available on the current deployment (depends on which provider keys are configured).+Legacy ids `gpt-4o`, `gpt-4o-mini`, and `o3-mini` are accepted and alias forward to `gpt-5.6-sol`, `gpt-5.6-luna`, and `o3`. Call `GET /api/brain/chat` for the live list of providers actually available on the current deployment (depends on which provider keys are configured).**Response (SSE)**@@ -730,6 +732,56 @@ curl -s -X POST https://three.ws/api/v1/ai/text-to-3d \| `503` | `not_configured` | The NVIDIA NIM lane isn't configured on this deployment (`NVIDIA_API_KEY`) || `502`/`504` | `lane_error` / `lane_timeout` | The generation lane failed or timed out — retry |+### Text→3D (ChatGPT Actions surface)++```+POST /api/3d/studio+GET /api/3d/studio?job=<id>+```++Public, CORS-open, no auth. The REST contract behind the **"three.ws 3D Studio"**+custom GPT (its OpenAPI Actions schema lives at+`prompts/store-submissions/_generated/openai-actions.yaml`). It is a thin shaper+over the same free NVIDIA NIM TRELLIS lane as `/api/v1/ai/text-to-3d` (same+per-IP quota buckets, no extra capacity), with two store-specific rules:+responses carry only model URLs and job state (no upsell block, no pricing+paths, no internal identifiers), and every prompt passes an age-13++content-safety gate before any GPU work starts.++**Request body**++```json+{ "prompt": "a small ceramic robot figurine" }+```++**Response, finished inline**++```json+{ "status": "done", "glbUrl": "https://cdn.three.ws/forge/anon/<id>.glb", "viewerUrl": "https://three.ws/viewer?src=…", "format": "glb" }+```++**Response, queued** (ChatGPT Actions time out at ~45s; the lane bounds its+synchronous hold to 30s, so a slow job always returns `pending` plus a poll+handle before the Action deadline)++```json+{ "status": "pending", "job": "f1.<signed-token>", "poll": "/api/3d/studio?job=f1.<signed-token>", "format": "glb" }+```++Poll `GET /api/3d/studio?job=<id>` until `status` is `"done"` (same shape as+above) or `"error"` (`{ "status": "error", "job", "error" }`; generation is+free, so a failed job costs nothing to retry).++**Errors**++| Status | Code | Meaning |+| ------ | -------------------------------- | -------------------------------------------------------------------- |+| `400` | `invalid_prompt` / `bad_request` | `prompt` missing, outside 3–1000 chars, or malformed JSON |+| `400` | `prompt_rejected` | The age-13+ safety gate refused the prompt; `message` says why |+| `429` | `rate_limited` | Free lane saturated; retry after `retry_after` seconds |+| `502` | `generation_failed` | The lane could not start the job; retry is free |+| `503` | `not_configured` / `lane_timeout`| Lane unavailable on this deployment, or slow to accept; retry later |+---## Material Studio APIdiff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex f16e9001e..8529d0e8f 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -85,7 +85,7 @@ Three modes, all configurable per agent:| **Self-hosted proxy** | You want to manage cost or use a private model | Set `key-proxy="/api/llm"` to point at your own serverless function that injects keys before forwarding to the provider. Keys never reach the client. || **Direct (advanced)** | Local-only experiments | The runtime can call providers directly if you pass an API key explicitly. Don't ship this to a public page. |-The brain proxy at [`/api/brain/chat`](./api-reference.md) supports Anthropic, OpenAI, Qwen, and OpenRouter — so the brain attribute can be `claude-opus-4-7`, `claude-sonnet-4-6`, `claude-haiku-4-5`, `gpt-4o`, `gpt-4o-mini`, and others.+The brain proxy at [`/api/brain/chat`](./api-reference.md) supports Anthropic, OpenAI, Qwen, and OpenRouter — so the brain attribute can be `claude-opus-4-7`, `claude-sonnet-4-6`, `claude-haiku-4-5`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, and others.---diff --git a/docs/mcp-studio.md b/docs/mcp-studio.mdindex 29b9a69c6..c67d68bc9 100644--- a/docs/mcp-studio.md+++ b/docs/mcp-studio.md@@ -25,7 +25,11 @@ answers every request synchronously over `POST`. `OPTIONS` is handled for CORS.Add the connector with the URL above and **No authentication**. Each generationtool renders its result inline in an interactive 3D viewer widget-(`ui://widget/three-studio-model.html`).+(`ui://widget/three-studio-model.html`); the persona tools render a living agent+body in their own widget (`ui://widget/three-studio-persona.html`). Both widgets+declare an `openai/widgetCSP` whose allowlist includes the GLB storage origin,+so models load inside real ChatGPT (which enforces the CSP), not just in+permissive test harnesses.### Any MCP client@@ -35,6 +39,15 @@ curl -s https://three.ws/api/mcp-studio \-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'```+### ChatGPT custom GPT (Actions)++The same free lane also ships as a REST Actions surface for the **"three.ws 3D+Studio"** custom GPT: `POST /api/3d/studio` submits a prompt and+`GET /api/3d/studio?job=<id>` polls it, with an age-13+ safety gate and+store-clean responses (model URLs and job state only). Full contract in the+[API reference](./api-reference.md). Use the MCP connector above when you want+inline 3D widgets; the custom GPT covers plans without connector support.+## ToolsAll six generation tools are free and run operator-funded on the platform's own@@ -120,8 +133,14 @@ or payments.Annotations: `create_agent_persona` and `persona_say` are writes(`readOnlyHint:false`); `get_agent_persona` is a pure read (`readOnlyHint:true`).-**How it renders.** Each persona tool returns an inline `text/html` resource that-frames the hosted embodiment page — `https://three.ws/embodiment/embed` — with the+**How it renders.** In ChatGPT (Apps SDK), each persona tool points its tool-level+`_meta["openai/outputTemplate"]` at the registered+`ui://widget/three-studio-persona.html` widget, which reads the tool's+`structuredContent` and mounts the hosted embodiment page (a result-level template+on an inline artifact is ignored by the Apps SDK, so the tool-level link is what+makes the body appear). In every other MCP host the tool result carries an inline+`text/html` resource that frames the same hosted page,+`https://three.ws/embodiment/embed`, with thepersona id and the turn's speak/emotion payload as query params. That page mounts`EmbodimentStage` (Three.js), which rides the platform's universalcanonicalize/retarget pipeline so the baked idle + gesture clip library drives anydiff --git a/docs/tutorials/connect-ai-brain.md b/docs/tutorials/connect-ai-brain.mdindex fcbe900b0..30280d425 100644--- a/docs/tutorials/connect-ai-brain.md+++ b/docs/tutorials/connect-ai-brain.md@@ -2,11 +2,11 @@The agent's body is the avatar. The agent's voice is the TTS. The agent's *brain* is whatever LLM is generating its replies. By default the platform routes through a managed Claude endpoint, which works out of the box but bills against your free tier. The moment you want real production traffic, full control over which model runs, or your own usage observability, you bring your own API key.-This tutorial covers the whole brain layer. Where the LLM call actually happens (and why your key never ends up in HTML), how to attach your Anthropic or OpenAI key in My Agents, choosing between Claude Sonnet 4.6, Claude Opus 4.7, GPT-4o, GPT-5, and the smaller models, the latency and cost tradeoffs, configuring streaming and system prompts, tool-use support per model, and where to watch your token spend. The embed snippet doesn't change when you switch models — every config is on the agent record.+This tutorial covers the whole brain layer. Where the LLM call actually happens (and why your key never ends up in HTML), how to attach your Anthropic or OpenAI key in My Agents, choosing between Claude Sonnet 4.6, Claude Opus 4.7, the GPT-5.6 family, and the smaller models, the latency and cost tradeoffs, configuring streaming and system prompts, tool-use support per model, and where to watch your token spend. The embed snippet doesn't change when you switch models — every config is on the agent record.**What you'll build:**- An agent powered by your own Anthropic key, with model selection-- An agent powered by your own OpenAI key, switchable to GPT-5+- An agent powered by your own OpenAI key, switchable across the GPT-5.6 family- A working understanding of which model fits which use case (cost, latency, capability)- A streaming-enabled brain so replies feel responsive- An observability dashboard you can use to monitor spend per agent@@ -31,7 +31,7 @@ This matters for three reasons:- **Keys stay secret.** Even a "view source" attack on your page reveals nothing. The key lives only in the platform's key store.- **Rate-limit shaping happens once, server-side.** The platform manages backoff and retries for you.-- **The embed snippet doesn't know which model is running.** You can swap from Claude Sonnet 4.6 to GPT-5 in My Agents and every page that embeds your agent picks up the change on next load. No code edits anywhere.+- **The embed snippet doesn't know which model is running.** You can swap from Claude Sonnet 4.6 to GPT-5.6 Sol in My Agents and every page that embeds your agent picks up the change on next load. No code edits anywhere.The corollary: setting `api-key="sk-ant-..."` directly on the `<agent-3d>` tag is supported but discouraged. It exposes your key in DOM. Use it only for local prototypes that never get deployed. Production agents store their key on the platform side.@@ -95,23 +95,36 @@ The current production-ready models, with the tradeoffs that actually matter for### OpenAI models-**GPT-4o** (`gpt-4o`) — the comparable peer to Sonnet 4.6.+**GPT-5.6 Terra** (`gpt-5.6-terra`) is the comparable peer to Sonnet 4.6.-- **Cost:** $2.50 per million input, $10 per million output. Slightly cheaper than Sonnet.+- **Cost:** $2.50 per million input, $15 per million output. The same band as Sonnet.- **Latency:** First token in ~700ms.-- **Capability:** Strong at multimodal input (vision, audio) and at general chat. Tool use is reliable.+- **Capability:** Strong at multimodal input and general chat. Tool use is reliable. The right OpenAI default for support, sales, and concierge agents.+- **Context window:** 1M tokens.-**GPT-5** (`gpt-5`) — OpenAI's reasoning-grade model, comparable to Opus.+**GPT-5.6 Sol** (`gpt-5.6-sol`) is the reasoning-grade OpenAI flagship, comparable to Opus.-- **Cost:** Premium. Comparable to Opus per token.-- **Latency:** Higher than GPT-4o; first token in ~1.5s, more if reasoning is engaged.-- **Capability:** Excellent at hard tasks, math, code, complex tool chains. Overkill for casual chat.+- **Cost:** Premium ($5 per million input, $30 per million output). Comparable to Opus per token.+- **Latency:** Higher than Terra; first token in ~1.5s, more if reasoning is engaged.+- **Capability:** Frontier reasoning, coding, and agentic work. Excellent at hard tasks, math, and complex tool chains. Overkill for casual chat.+- **Context window:** 1M tokens.-**GPT-4o-mini** (`gpt-4o-mini`) — the budget option.+**GPT-5.6 Luna** (`gpt-5.6-luna`) is the budget pick of the 5.6 family.-- **Cost:** Lowest in the OpenAI lineup.+- **Cost:** $1 per million input, $6 per million output.- **Latency:** Fast.-- **Capability:** Roughly comparable to Haiku for short interactions. Less coherent on long conversations.+- **Capability:** Vision-capable, and roughly comparable to Haiku for short interactions. Less coherent on long conversations.+- **Context window:** 1M tokens.++**o3** (`o3`) is the reasoning specialist, with `o3-pro` above it.++- **Cost:** Reasoning tokens bill as output, so replies cost more than their visible length suggests.+- **Latency:** Variable; it thinks before the first token arrives.+- **Capability:** Deep chain-of-thought for math, logic, and structured planning. Not a general chat pick; reach for it when the agent's job is to reason, not to converse.++The platform also carries the wider OpenAI lineup: GPT-5.5 and GPT-5.5 Pro, the more affordable GPT-5.4 tier (`gpt-5.4`, `gpt-5.4-pro`, `gpt-5.4-mini`, `gpt-5.4-nano`, the cheapest current GPT), and GPT-5.3 Codex (`gpt-5.3-codex`) for code-centric agents. The three 5.6 models above cover almost every agent use case; the rest are there when you want a specific cost or capability point.++Legacy ids keep working: `gpt-4o`, `gpt-4o-mini`, and `o3-mini` are accepted as aliases and resolve to `gpt-5.6-sol`, `gpt-5.6-luna`, and `o3` (the GPT-4o family was deprecated upstream in July 2026), so existing agents upgrade in place with no config change.### Picking a model@@ -119,15 +132,15 @@ A practical rule of thumb:| Use case | Recommended model ||---|---|-| Support / FAQ agent for a SaaS | Sonnet 4.6 or GPT-4o |+| Support / FAQ agent for a SaaS | Sonnet 4.6 or GPT-5.6 Terra || Personal-website-me agent | Sonnet 4.6 || Onboarding co-pilot, sales bot | Sonnet 4.6 || Museum tour guide, long-form domain agent | Sonnet 4.6, escalate to Opus only if needed |-| Legal, medical, financial assistant | Opus 4.7 or GPT-5 |-| Status-check, wave-and-greet, micro-interaction | Haiku 4.5 or GPT-4o-mini |-| Multi-step tool chains, code assistance | Opus 4.7 or GPT-5 |+| Legal, medical, financial assistant | Opus 4.7 or GPT-5.6 Sol |+| Status-check, wave-and-greet, micro-interaction | Haiku 4.5 or GPT-5.6 Luna |+| Multi-step tool chains, code assistance | Opus 4.7 or GPT-5.6 Sol |-Start at Sonnet 4.6 for almost everything. Move to Haiku if latency is the bottleneck. Move to Opus or GPT-5 only when you have a specific quality issue that the smaller model can't fix with prompt iteration.+Start at Sonnet 4.6 for almost everything. Move to Haiku if latency is the bottleneck. Move to Opus or GPT-5.6 Sol only when you have a specific quality issue that the smaller model can't fix with prompt iteration.---@@ -135,15 +148,15 @@ Start at Sonnet 4.6 for almost everything. Move to Haiku if latency is the bottlThe system prompt and the model are configured separately. You can swap models without touching the prompt, and vice versa.-In **Brain → System prompt**, paste your full prompt. The same prompt works across all the models above, with one caveat: smaller models (Haiku, GPT-4o-mini) follow instructions less precisely, so prompts written for them benefit from being shorter and more explicit. A 600-word prompt that Sonnet handles cleanly may overflow Haiku's instruction-following budget.+In **Brain → System prompt**, paste your full prompt. The same prompt works across all the models above, with one caveat: smaller models (Haiku, GPT-5.6 Luna) follow instructions less precisely, so prompts written for them benefit from being shorter and more explicit. A 600-word prompt that Sonnet handles cleanly may overflow Haiku's instruction-following budget.-If you're targeting Haiku or GPT-4o-mini specifically, trim:+If you're targeting Haiku or GPT-5.6 Luna specifically, trim:- Cut the longer "voice" descriptions to 2-3 traits- Reduce the rules list to 3-4 hard bans- Keep fallback responses but cut any explanatory commentary-For Sonnet, Opus, GPT-4o, and GPT-5, the full prompt template from the [agent personality](/tutorials/agent-personality) tutorial works without modification.+For Sonnet, Opus, GPT-5.6 Terra, and GPT-5.6 Sol, the full prompt template from the [agent personality](/tutorials/agent-personality) tutorial works without modification.A few configuration knobs alongside the prompt:@@ -196,11 +209,11 @@ Tool use (the model invoking a function you've defined — a `searchProducts(que| Claude Opus 4.7 | Excellent. Handles complex multi-tool chains and ambiguous tool selection cleanly. || Claude Sonnet 4.6 | Excellent. Indistinguishable from Opus for most tool flows. The default recommendation. || Claude Haiku 4.5 | Good for single-tool flows. Struggles with chains that require 3+ sequential tool calls. |-| GPT-5 | Excellent, similar to Opus. Strong at parallel tool calls. |-| GPT-4o | Very good. Slightly more prone to mis-formatting tool arguments than Sonnet. |-| GPT-4o-mini | Functional. Avoid for anything with 2+ tools or non-trivial schemas. |+| GPT-5.6 Sol | Excellent, similar to Opus. Strong at parallel tool calls. |+| GPT-5.6 Terra | Very good. Slightly more prone to mis-formatting tool arguments than Sonnet. |+| GPT-5.6 Luna | Functional. Avoid for anything with 2+ tools or non-trivial schemas. |-If you're building a skill-heavy agent — one that needs to look up products, check inventory, search documentation, and place orders, all in one conversation — pick Sonnet or GPT-4o at minimum. Haiku and mini are acceptable for single-purpose lookups but get confused on chains.+If you're building a skill-heavy agent — one that needs to look up products, check inventory, search documentation, and place orders, all in one conversation — pick Sonnet or GPT-5.6 Terra at minimum. Haiku and Luna are acceptable for single-purpose lookups but get confused on chains.See the [custom skill tutorial](/tutorials/custom-skill) for the full skill-writing workflow.@@ -238,13 +251,13 @@ If you have:<agent-3d agent-id="YOUR_AGENT_ID" id="agent"></agent-3d>```-…on a thousand pages, you can switch the brain from Sonnet to Opus to GPT-5 entirely from the dashboard. No deploy. No code edit. The next page load picks up the new model.+…on a thousand pages, you can switch the brain from Sonnet to Opus to GPT-5.6 Sol entirely from the dashboard. No deploy. No code edit. The next page load picks up the new model.This makes A/B testing painless. Common patterns:- **Cost optimisation pass.** Move a low-stakes agent from Sonnet to Haiku, watch the quality and spend for a week, decide whether to keep the change.- **Capability spike.** Promote an agent to Opus for a busy week (a launch, a marketing campaign), then dial back down to Sonnet for steady-state.-- **Provider failover.** If Anthropic has a brief outage, you can switch the agent to GPT-4o in the dashboard and keep traffic moving while you wait. Both keys are stored, both providers are reachable from the same agent record.+- **Provider failover.** If Anthropic has a brief outage, you can switch the agent to GPT-5.6 Terra in the dashboard and keep traffic moving while you wait. Both keys are stored, both providers are reachable from the same agent record.The trick to making this work cleanly is to write your system prompt in a model-agnostic style. Prompts that lean hard on Claude-specific quirks ("respond in XML tags") can produce slightly different output on GPT. The prompt template in the [agent personality](/tutorials/agent-personality) tutorial is intentionally portable across providers — use that style and your switch-day surprises are minimal.@@ -300,7 +313,7 @@ The brain layer in full:- LLM calls happen server-side; your key never leaves the platform's backend- Keys are stored per-account in My Agents; one key serves all your agents from that provider-- Sonnet 4.6 is the default; Opus 4.7 and GPT-5 are the reasoning-grade upgrades; Haiku and mini are the latency picks+- Sonnet 4.6 is the default; Opus 4.7 and GPT-5.6 Sol are the reasoning-grade upgrades; Haiku and GPT-5.6 Luna are the latency picks- Streaming is on by default and matters more than total latency for perceived speed- Tool-use quality varies by model — pick Sonnet or larger for skill-heavy agents- Usage and cost are visible in the dashboard, with alerts available for spend capsdiff --git a/docs/tutorials/multi-agent-coordination.md b/docs/tutorials/multi-agent-coordination.mdindex 5c7d01e19..cafb8952a 100644--- a/docs/tutorials/multi-agent-coordination.md+++ b/docs/tutorials/multi-agent-coordination.md@@ -45,7 +45,7 @@ The rest of this tutorial assumes you've decided yes, two agents.A SaaS pricing page. Two agents:-- **Riley (Sales)** — front-of-stage. Greets visitors, answers high-level pricing/positioning questions, sniffs intent. Cheap LLM (Claude Haiku or GPT-4o-mini class).+- **Riley (Sales)** — front-of-stage. Greets visitors, answers high-level pricing/positioning questions, sniffs intent. Cheap LLM (Claude Haiku or GPT-5.6 Luna class).- **Devon (Engineer)** — stays in the background until summoned. Answers integration, security, architecture, and SDK questions. More expensive LLM (Claude Sonnet/Opus class) because the answers must be technically accurate.The handoff rule is concrete: when Riley detects a "deep technical" question, Riley narrates the handoff and Devon steps forward. When Devon's done, control returns to Riley. There's a shared scratch memory so Devon knows what Riley already covered.diff --git a/docs/tutorials/voice-and-lipsync.md b/docs/tutorials/voice-and-lipsync.mdindex 73b89e6a5..8f861ee68 100644--- a/docs/tutorials/voice-and-lipsync.md+++ b/docs/tutorials/voice-and-lipsync.md@@ -72,7 +72,7 @@ The fastest path to a talking agent is a built-in TTS voice. The catalog lives i| `shimmer` | Light and airy || `verse` | Dynamic and conversational |-The default is `nova`. These are synthesized by `POST /api/tts/speak` ([`api/tts/speak.js`](../../api/tts/speak.js)), which tries the free NVIDIA NIM Magpie lane first and falls back to OpenAI's `/v1/audio/speech`. You don't choose the provider — you choose the voice id, and the endpoint renders it on whichever lane is configured.+The default is `nova`. These are synthesized by `POST /api/tts/speak` ([`api/tts/speak.js`](../../api/tts/speak.js)), which tries the free NVIDIA NIM Magpie lane first and falls back to the OpenAI `/v1/audio/speech` endpoint. You don't choose the provider — you choose the voice id, and the endpoint renders it on whichever lane is configured.You can hear all of these immediately in the next step.diff --git a/packages/brain-mcp/README.md b/packages/brain-mcp/README.mdindex 12e5e64af..0364e1351 100644--- a/packages/brain-mcp/README.md+++ b/packages/brain-mcp/README.md@@ -16,7 +16,7 @@----> A [Model Context Protocol](https://modelcontextprotocol.io) server that gives any AI assistant the three.ws **multi-provider LLM router** over stdio. Discover which models are available — Claude, GPT-4o, o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more — and run a chat completion through whichever one fits, without wiring each vendor SDK yourself.+> A [Model Context Protocol](https://modelcontextprotocol.io) server that gives any AI assistant the three.ws **multi-provider LLM router** over stdio. Discover which models are available — Claude, the GPT-5.6 family, o3, Qwen, DeepSeek, NVIDIA Nemotron, IBM Granite, and more — and run a chat completion through whichever one fits, without wiring each vendor SDK yourself.The router fronts every provider behind one endpoint and transparently falls back across mirrors and free tiers if the chosen model is briefly down. The free open-weight tiers (GPT-OSS 120B, NVIDIA NIM models) work with **no key**; the paid first-party flagships unlock with a three.ws API key.@@ -131,7 +131,7 @@ Both responses below are shape illustrations — the live provider set and gener| Model class | Needs a key? || ---------------------------------------------------------------------------- | --------------------------- || Free open-weight tiers (GPT-OSS 120B, NVIDIA NIM: Nemotron / Kimi / Llama 4) | No |-| Paid first-party flagships (Claude, GPT-4o, o3, Qwen Plus, DeepSeek, …) | Yes — set `THREE_WS_API_KEY` |+| Paid first-party flagships (Claude, GPT-5.6, o3, Qwen Plus, DeepSeek, …) | Yes — set `THREE_WS_API_KEY` |Create an API key at [three.ws/account](https://three.ws/account). Without it, paid models return a sign-in error and `list_providers` flags them with `requiresAuth: true`.diff --git a/pages/club.html b/pages/club.htmlindex 0a5d0ebc8..a4848dcc5 100644--- a/pages/club.html+++ b/pages/club.html@@ -2116,6 +2116,10 @@<input type="checkbox" id="club-auto-follow" aria-describedby="club-auto-follow-desc" /><span id="club-auto-follow-desc">Auto-follow tips (orbit cam during dance)</span></label>+ <label class="club-toggle" for="club-power-saver">+ <input type="checkbox" id="club-power-saver" aria-describedby="club-power-saver-desc" />+ <span id="club-power-saver-desc">Power saver (30fps, lighter effects — cooler, quieter machine)</span>+ </label><p class="club-hint">Shortcuts: <b>1</b>-<b>3</b> VIP <b>0</b> overhead <b>Esc</b> free</p>diff --git a/pages/start.html b/pages/start.htmlindex 8a49d2a97..ecd4c8d9c 100644--- a/pages/start.html+++ b/pages/start.html@@ -1134,8 +1134,8 @@<div class="wz-model-name">Claude Sonnet</div><div class="wz-model-desc">Smart & fast</div></button>- <button type="button" class="wz-model-card" data-model="gpt-4o" aria-pressed="false">- <div class="wz-model-name">GPT-4o</div>+ <button type="button" class="wz-model-card" data-model="gpt-5.6-sol" aria-pressed="false">+ <div class="wz-model-name">GPT-5.6 Sol</div><div class="wz-model-desc">OpenAI flagship</div></button><button type="button" class="wz-model-card" data-model="llama-3.3-70b" aria-pressed="false">diff --git a/public/changelog.json b/public/changelog.jsonindex 116e4d058..72059984e 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-14T15:44:46.402Z",+ "generated_at": "2026-07-14T15:53:50.382Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -107,6 +107,17 @@"fix"]},+ {+ "date": "2026-07-14",+ "type": "update",+ "title": "IRL avatars now move in iPhone AR",+ "summary": "Tapping Place in AR on the IRL page from an iPhone now bakes your agent's idle animation into the AR preview, so it breathes and shifts on your real floor instead of standing frozen in a T-pose. If an avatar's rig can't take the animation, the proven static preview still opens, so AR always works.",+ "link": "/irl",+ "tags": [+ "improvement",+ "fix"+ ]+ },{"date": "2026-07-14","type": "update",@@ -150,6 +161,17 @@"docs"]},+ {+ "date": "2026-07-14",+ "type": "update",+ "title": "Play and Club run cooler: smart frame caps and a power-saver toggle",+ "summary": "The 3D worlds on /play and /club used to render at your monitor's full refresh rate (up to 144+ frames a second) and kept working at full quality even when you clicked over to another window, which made laptops run hot with fans spinning. Both pages now cap rendering at 60fps, drop to 30fps whenever the window is in the background, and /play stops rendering the hidden 3D arena behind the coin-picker lobby entirely. There's also a new Eco toggle (the lightning button in /play, a checkbox in the /club panel) that holds everything at 30fps with lighter effects for a cooler, quieter machine; the setting is shared across both pages.",+ "link": "/play",+ "tags": [+ "improvement",+ "fix"+ ]+ },{"date": "2026-07-14","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 0a9f9c85a..b915aadaf 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -86,6 +86,14 @@<category>fix</category><description>When the community battle service is offline, /clash and the /temporary world picker used to keep retrying and logging failed requests in the background. Both now recognize the outage on the first response, stop polling, and show a clear notice with live places to go instead (launches, markets, or walking the default world solo). The sign-in page also no longer throws a background error if its 3D greeter can't load; the form works exactly the same without him.</description></item>+ <item>+ <title>IRL avatars now move in iPhone AR</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-07-14:IRL avatars now move in iPhone AR</guid>+ <pubDate>Tue, 14 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Tapping Place in AR on the IRL page from an iPhone now bakes your agent's idle animation into the AR preview, so it breathes and shifts on your real floor instead of standing frozen in a T-pose. If an avatar's rig can't take the animation, the proven static preview still opens, so AR always works.</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>@@ -118,6 +126,14 @@<category>docs</category><description>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.</description></item>+ <item>+ <title>Play and Club run cooler: smart frame caps and a power-saver toggle</title>+ <link>https://three.ws/play</link>+ <guid isPermaLink="false">2026-07-14:Play and Club run cooler: smart frame caps and a power-saver toggle</guid>+ <pubDate>Tue, 14 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The 3D worlds on /play and /club used to render at your monitor's full refresh rate (up to 144+ frames a second) and kept working at full quality even when you clicked over to another window, which made laptops run hot with fans spinning. Both pages now cap rendering at 60fps, drop to 30fps whenever the window is in the background, and /play stops rendering the hidden 3D arena behind the coin-picker lobby entirely. There's also a new Eco toggle (the lightning button in /play, a checkbox in the /club panel) that holds everything at 30fps with lighter effects for a cooler, quieter machine; the setting is shared across both pages.</description>+ </item><item><title>Shared 3D viewer links load again</title><link>https://three.ws/viewer</link>diff --git a/public/features.json b/public/features.jsonindex b6b9c401e..286372b73 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-14T14:39:05.322Z",+ "generated_at": "2026-07-14T15:53:50.358Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/club-entrance.js b/src/club-entrance.jsindex d48c9087a..9547d6db6 100644--- a/src/club-entrance.js+++ b/src/club-entrance.js@@ -56,6 +56,7 @@ import { gltfLoader } from './loaders/gltf.js';import { AnimationManager } from './animation-manager.js';import { ClubCrowd } from './club-crowd.js';import { detectProfile, PROFILES, createFrameWatchdog } from './club-perf.js';+import { getPowerSaver } from './shared/frame-governor.js';import { log } from './shared/log.js';import { isExpressEntry } from './shared/club-express.js';@@ -807,7 +808,9 @@ async function start(canvasEl) {// no visible benefit — the dominant cause of the fans spinning up. Simulation// still steps every animation frame; only the expensive composer.render is// gated, so movement stays smooth.- const FRAME_BUDGET_MS = 1000 / 60 - 1; // -1ms slack so a 60Hz panel never skips+ // Under the shared power-saver preference (see shared/frame-governor.js —+ // same toggle as the main club floor and /play) the cap halves to 30fps.+ const FRAME_BUDGET_MS = () => (getPowerSaver() ? 1000 / 30 : 1000 / 60) - 1; // -1ms slack so a 60Hz panel never skips// Sustained-slow-frame watchdog: drops pixel ratio one tier (and finally the// SMAA pass) when frames stay above budget, so a struggling GPU cools off// instead of grinding. Never upgrades — see club-perf.js.@@ -927,7 +930,7 @@ async function start(canvasEl) {// Draw at most ~60 fps, and never while the tab is hidden — the GPU// shouldn't keep rendering a club nobody is looking at. Simulation above// already ran this frame; here we only decide whether to paint it.- if (!document.hidden && now - lastDraw >= FRAME_BUDGET_MS) {+ if (!document.hidden && now - lastDraw >= FRAME_BUDGET_MS()) {// Clamp like the sim dt so the first draw after a hidden tab (interval// of seconds) can't single-handedly trip the slow-frame watchdog.const drawDt = Math.min((now - lastDraw) / 1000, 0.1);diff --git a/src/club.js b/src/club.jsindex 32d61fc6d..ec245c85d 100644--- a/src/club.js+++ b/src/club.js@@ -54,6 +54,10 @@ import { ClubCamera } from './club-camera.js';import { ClubAudio, styleAudioFor, TRACK_LABELS } from './club-audio.js';import { playSequence, ticketSteps } from './club-sequence.js';import { detectProfile, PROFILES, createFrameWatchdog, isMobileLayout } from './club-perf.js';+import {+ createFrameGovernor, trackWindowFocus, getPowerSaver, setPowerSaver, onPowerSaverChange,+ FPS_ACTIVE, FPS_IDLE, FPS_SAVER,+} from './shared/frame-governor.js';import { log } from './shared/log.js';import { emptyStateHTML } from './shared/state-kit.js';import { createRenderer } from './webgl-support.js';@@ -2272,10 +2276,12 @@ const watchdog = createFrameWatchdog({if (!next) return;activeProfile = next;if (typeof window !== 'undefined') window.__clubProfile = next;- renderer.setPixelRatio(next.pixelRatio);- renderer.shadowMap.enabled = next.shadows;- for (const station of stations) {- if (station.spot) station.spot.castShadow = next.shadows;+ if (!powerSaver) {+ renderer.setPixelRatio(next.pixelRatio);+ renderer.shadowMap.enabled = next.shadows;+ for (const station of stations) {+ if (station.spot) station.spot.castShadow = next.shadows;+ }}// Trim disco lights to the new cap so we render fewer point lights.while (disco.children.length > next.discoLights) {@@ -2286,15 +2292,58 @@ const watchdog = createFrameWatchdog({},});+// ── Power saver ──────────────────────────────────────────────────────────+// A machine can hold 60fps and still run hot — the watchdog above only+// reacts to SLOW frames, never to a GPU that is merely working flat out.+// Power saver is the user's direct lever: hard 30fps cap plus the cheapest+// render state (1x pixel ratio, no shadows), persisted across every three.ws+// 3D surface through one shared preference.+let powerSaver = getPowerSaver();+function applyPowerSaver(on) {+ powerSaver = on;+ const dprCap = on ? 1 : activeProfile.pixelRatio;+ const shadows = on ? false : activeProfile.shadows;+ renderer.setPixelRatio(dprCap);+ renderer.shadowMap.enabled = shadows;+ for (const station of stations) {+ if (station.spot) station.spot.castShadow = shadows;+ }+}+if (powerSaver) applyPowerSaver(true);+onPowerSaverChange((on) => {+ applyPowerSaver(on);+ const cb = document.getElementById('club-power-saver');+ if (cb) cb.checked = on;+});+{+ const cb = document.getElementById('club-power-saver');+ if (cb) {+ cb.checked = powerSaver;+ cb.addEventListener('change', () => setPowerSaver(cb.checked));+ }+}+// ── Render loop ──────────────────────────────────────────────────────────+// rAF fires at the display refresh rate (144Hz panels would render 2.4x the+// frames of a 60Hz one, for pure heat); the governor caps real work at 60fps,+// drops to 30 when the window loses focus (visible but not in front), and+// holds 30 under power saver. Skipped frames fold into the next dt.+const governor = createFrameGovernor();+const focusState = trackWindowFocus();const clock = new Timer();let rafId = null;-function animate() {+function animate(frameNow) {+ rafId = requestAnimationFrame(animate);+ const fpsCap = powerSaver ? FPS_SAVER : (focusState.focused ? FPS_ACTIVE : FPS_IDLE);+ if (!governor.shouldRun(frameNow ?? performance.now(), fpsCap)) return;clock.update();const dt = Math.min(clock.getDelta(), 0.066);const t = clock.getElapsed();- watchdog.tick(dt);+ // Only judge frame health at the full-rate cap — a deliberately throttled+ // frame (blur, power saver) is slow by design, not a struggling GPU, and+ // the watchdog never upgrades back.+ if (fpsCap >= FPS_ACTIVE) watchdog.tick(dt);// Beat level — drives both the bloom and the volumetric beams this frame.const peak = audio.getPeak();@@ -2350,7 +2399,6 @@ function animate() {if (!prefersReducedMotion) bloomEffect.intensity = 1.0 + peak * 1.5;composer.render(dt);- rafId = requestAnimationFrame(animate);}renderPoles();diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 05cc9cf1d..611f824cf 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -16,6 +16,7 @@ import { GUEST_SENTINEL, playAs } from './play-handoff.js';import { COMPOSITE_PIECES } from './build-voxels.js';import { PROP_CATALOG, GALLERY_PROP_PREFIX, registerGalleryProp } from './world-objects.js';import { makeIntroReopener } from './play-intro.js';+import { getPowerSaver, setPowerSaver, onPowerSaverChange } from '../shared/frame-governor.js';import { log } from '../shared/log.js';// localStorage throws in private mode and in third-party iframe contexts where@@ -1303,6 +1304,22 @@ export class CommunityUI {this.voiceLabel,]);+ // Power saver — one shared preference across every three.ws 3D surface+ // (also read by /club). Caps the render loop at 30fps and drops to the+ // cheapest render state so laptops stay cool and quiet. The button both+ // toggles and mirrors the preference, so a change made on another page+ // (or another tab) is reflected here live.+ this.powerBtn = el('button', {+ class: 'cc-power-btn', type: 'button',+ 'aria-pressed': getPowerSaver() ? 'true' : 'false',+ 'aria-label': 'Power saver', title: 'Power saver — 30fps + lighter rendering, for a cooler, quieter machine',+ onclick: () => setPowerSaver(this.powerBtn.getAttribute('aria-pressed') !== 'true'),+ }, [+ el('span', { class: 'cc-power-ico', 'aria-hidden': 'true', text: '⚡' }),+ el('span', { class: 'cc-power-label', text: 'Eco' }),+ ]);+ onPowerSaverChange((on) => this.powerBtn.setAttribute('aria-pressed', on ? 'true' : 'false'));+// Dance floor button — hidden until the player steps onto the pad.this.danceBtnLabel = el('span', { class: 'cc-dance-label', text: 'Dance' });this.danceBtn = el('button', {@@ -1321,7 +1338,7 @@ export class CommunityUI {this._buildTagHud();this._buildKingHud();- this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, this.voiceBtn, this.danceBtn, chat, this.emoteTray, this.reactionBar, hint, this.joystick]);+ this.hud = el('div', { id: 'cc-hud', hidden: true }, [banner, leave, this.statusPill, this.voiceBtn, this.powerBtn, this.danceBtn, chat, this.emoteTray, this.reactionBar, hint, this.joystick]);document.body.appendChild(this.hud);}diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex e2f086e7e..d61b3d9b6 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -807,6 +807,22 @@ html[data-bg="transparent"] #cc-lobby {.cc-label.cc-speaking::before { animation: none; }}+/* power saver — under the voice toggle, same visual family */+.cc-power-btn {+ position: fixed; top: 140px; right: 14px; z-index: 22;+ display: inline-flex; align-items: center; gap: 8px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);+ padding: 8px 13px 8px 11px; color: var(--cc-dim); cursor: pointer;+ font-weight: 600; font-size: 11px; letter-spacing: 0.06em; text-transform: uppercase;+ box-shadow: var(--cc-shadow); backdrop-filter: blur(10px);+ transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;+}+.cc-power-btn:hover { border-color: var(--cc-edge-hi); color: var(--cc-text); background: rgba(255, 255, 255, 0.05); }+.cc-power-btn:focus-visible { outline: none; border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi); }+.cc-power-btn[aria-pressed="true"] { color: #b8ffce; border-color: rgba(140, 255, 180, 0.55); }+.cc-power-ico { line-height: 1; }+.cc-power-label { line-height: 1; }+/* chat sidebar — dockable, minimizable, persistent log */#cc-chat {position: fixed; right: 14px; bottom: 14px; width: min(340px, 82vw);diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex fe7602801..a63d51e14 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -27,6 +27,11 @@ import { createWorldEnvironment, seedFromString } from './world-env.js';import { createDistrict } from './district.js';import { DISTRICT, clampToBounds } from './world-zones.js';import { PhysicsWorld } from '../physics/physics-world.js';+import { detectProfile, createFrameWatchdog } from '../club-perf.js';+import {+ createFrameGovernor, trackWindowFocus, getPowerSaver, onPowerSaverChange,+ FPS_ACTIVE, FPS_IDLE, FPS_SAVER,+} from '../shared/frame-governor.js';import { createDayNightCycle } from './day-night.js';import { worldClock } from '../shared/world-clock.js';import { createCameraModeController, CAMERA_MODE_LABELS } from './camera-modes.js';@@ -392,6 +397,31 @@ export class CoinCommunities {this._last = performance.now();this._lastKick = 0; // R05: timestamp of last ball:kick intent (client-side rate limit)+ // Heat control (same system as /club): rAF fires at the display refresh+ // rate, so an uncapped loop on a 120/144Hz panel renders 2-2.4x the+ // frames of a 60Hz one for no visible gain — that alone makes laptops+ // run hot. The governor caps real frame work at 60fps in-world, 30 when+ // the window loses focus, 30 under the shared power-saver preference,+ // and a near-idle trickle while the opaque lobby fully covers the+ // canvas (the arena keeps rendering behind it otherwise, pure waste).+ this._governor = createFrameGovernor();+ this._focus = trackWindowFocus();+ this._powerSaver = getPowerSaver();+ // Boot-time quality tier from real capability signals (deviceMemory,+ // cores, coarse pointer — same detector /club uses), then a watchdog+ // that steps the tier down on sustained slow frames. Applied to the+ // renderer in _initRenderer / _applyPerfTier.+ this._perfTier = detectProfile();+ this._watchdog = createFrameWatchdog({+ initialTier: this._perfTier,+ onDowngrade: (tier) => {+ this._perfTier = tier;+ this._applyPerfTier();+ log.info('[coincommunities] downgrading render tier to', tier);+ },+ });+ onPowerSaverChange((on) => { this._powerSaver = on; this._applyPerfTier(); });+// W01: real Rapier collision. A single physics world + character controller// persist for the whole session (Rapier's WASM init is memoized globally);// district building colliders are rebuilt per coin in enter(). Movement in@@ -636,10 +666,9 @@ export class CoinCommunities {e.code = 'NO_WEBGL';throw e;}- r.setPixelRatio(Math.min(window.devicePixelRatio, 2));r.setSize(window.innerWidth, window.innerHeight);if (this._transparentBg) r.setClearColor(0x000000, 0);- r.shadowMap.enabled = true; r.shadowMap.type = PCFShadowMap;+ r.shadowMap.type = PCFShadowMap;r.outputColorSpace = SRGBColorSpace;// ACES keeps the cool moonlight key and the bright avatars from clipping;// exposure is tuned for the dark monochrome arena (the LDR gradient backdrop@@ -647,9 +676,27 @@ export class CoinCommunities {r.toneMapping = ACESFilmicToneMapping;r.toneMappingExposure = 1.0;this.renderer = r;+ this._applyPerfTier();window.addEventListener('resize', () => this._onResize());}+ // Apply the current quality tier (or the power-saver floor) to the renderer.+ // Tier caps pixel ratio — the single biggest GPU cost on high-DPI screens —+ // and gates shadow maps. Power saver overrides everything with the cheapest+ // state; turning it off restores the tier the watchdog last settled on.+ _applyPerfTier() {+ const r = this.renderer;+ if (!r) return;+ if (this._powerSaver) {+ r.setPixelRatio(1);+ r.shadowMap.enabled = false;+ return;+ }+ const dprCap = this._perfTier === 'high' ? 2 : this._perfTier === 'medium' ? 1.5 : 1;+ r.setPixelRatio(Math.min(window.devicePixelRatio || 1, dprCap));+ r.shadowMap.enabled = this._perfTier !== 'low';+ }+_initScene() {// Nocturnal monochrome arena that flows out of the lobby: near-black ground// with a technical hairline grid, a glowing boundary ring, a silhouette@@ -3310,11 +3357,26 @@ export class CoinCommunities {}// ---------------------------------------------------------------- loop- _loop() {+ _loop(frameNow) {requestAnimationFrame(this._loop);- const now = performance.now();+ const now = frameNow ?? performance.now();+ // Frame cap (see constructor): 60 in-world, 30 blurred or power-saving,+ // and a 4fps trickle while the opaque lobby hides the canvas entirely+ // (the transparent embed keeps 30 — its arena stays visible behind the+ // grid). Skipped frames are cheap: everything below is dt-based.+ const lobbyHidden = this.phase === 'lobby' && !this._transparentBg;+ let fpsCap = !this._focus.focused ? FPS_IDLE+ : lobbyHidden ? 4+ : this.phase === 'world' ? FPS_ACTIVE+ : FPS_IDLE;+ if (this._powerSaver) fpsCap = Math.min(fpsCap, FPS_SAVER);+ if (!this._governor.shouldRun(now, fpsCap)) return;const dt = Math.min(0.05, (now - this._last) / 1000);this._last = now;+ // Only judge frame health at the full-rate cap — a deliberately+ // throttled frame (blur, lobby, saver) is slow by design, not a+ // struggling GPU.+ if (this.phase === 'world' && fpsCap >= FPS_ACTIVE) this._watchdog.tick(dt);if (this.phase === 'world') {// W02: while driving, the vehicle IS the local player's movement — skipdiff --git a/src/irl.js b/src/irl.jsindex 571e86c31..be3059dac 100644--- a/src/irl.js+++ b/src/irl.js@@ -3279,14 +3279,33 @@ async function resolveQuickLookUrl() {if (_usdzObjectUrl && _usdzObjectUrlFor === glbUrl) return _usdzObjectUrl;const res = await fetch(glbUrl);if (!res.ok) throw new Error(`GLB fetch failed: ${res.status}`);- const { glbBlobToUsdzBlob } = await import('./usdz-pipeline.js');- const usdzBlob = await glbBlobToUsdzBlob(await res.blob());+ const glbBlob = await res.blob();+ const usdzBlob = await bakeQuickLookUsdz(glbBlob);if (_usdzObjectUrl) URL.revokeObjectURL(_usdzObjectUrl);_usdzObjectUrl = URL.createObjectURL(usdzBlob);_usdzObjectUrlFor = glbUrl;return _usdzObjectUrl;}+// Prefer a living, animated avatar in Quick Look (same policy as /ar): bake the+// idle clip into the USDZ so the agent breathes on the real floor instead of+// standing frozen in its bind pose. Fall back to the static bake if the rig+// can't take the clip or the animation fetch fails — animation is upside,+// never a gate.+async function bakeQuickLookUsdz(glbBlob) {+ try {+ const { glbBlobToAnimatedUsdzBlob, DEFAULT_AR_ANIMATION } = await import('./usdz-animated.js');+ const animResp = await fetch(DEFAULT_AR_ANIMATION);+ if (!animResp.ok) throw new Error(`animation fetch ${animResp.status}`);+ const animationGlbBlob = await animResp.blob();+ return await glbBlobToAnimatedUsdzBlob(glbBlob, { animationGlbBlob });+ } catch (err) {+ log.warn('[irl] animated USDZ unavailable, using static:', err?.message);+ const { glbBlobToUsdzBlob } = await import('./usdz-pipeline.js');+ return glbBlobToUsdzBlob(glbBlob);+ }+}+async function enterQuickLookPlacement() {if (anchorBtn) { anchorBtn.classList.add('is-active'); anchorBtn.disabled = true; }setStatus('Preparing your agent for AR…', { loading: true, sticky: true });diff --git a/src/irl/room-mode.js b/src/irl/room-mode.jsindex 22b830384..6c4718be2 100644--- a/src/irl/room-mode.js+++ b/src/irl/room-mode.js@@ -41,9 +41,30 @@ function injectStyles() {_stylesInjected = true;const css = `.irl-room-fab.is-active{background:rgba(124,92,255,.22);border-color:rgba(124,92,255,.7);color:#fff}-#irl-aim-hud{position:fixed;inset:0;z-index:6;pointer-events:none;display:none;+/* z-index 12 clears the main dock (10) and the joystick (9), which anchor to the+ same bottom edge as .irl-aim-panel below. It stays under the modal sheets (19+)+ so an error/consent sheet still covers the aim HUD, which is the right order. */+#irl-aim-hud{position:fixed;inset:0;z-index:12;pointer-events:none;display:none;font:inherit;color:#fff}#irl-aim-hud.is-open{display:block}+/* While aiming, the aim panel IS the bottom of the screen. Every other control+ anchored down there (the dock, the joystick, the right-edge FABs) would land on+ top of the distance slider and the Place/Face/Done row and eat the taps this mode+ exists for. Worst of all is the dock's own "Place agents" pill, which sits directly+ over the Place button and toggles this mode straight back off when you reach for+ it. Fold them away for the duration; exit() drops the class and they return.+ visibility (not display) keeps the footer's layout box, so the live --irl-dock-h+ measurement in irl.js keeps reporting a real height. */+body.irl-room-mode .irl-bottom,+body.irl-room-mode #irl-joystick,+body.irl-room-mode .irl-immersive-toggle,+body.irl-room-mode .irl-immersive-hint,+body.irl-room-mode .irl-drops-fab,+/* The "be the first to pin here" empty-state prompt sits dead centre, right over+ the aim reticle and its distance readout. You are already placing an agent, so+ the invitation to place one is both moot and in the way. */+body.irl-room-mode .irl-dx-empty{+ opacity:0;visibility:hidden;pointer-events:none;transition:opacity .18s ease}.irl-aim-reticle{position:absolute;top:46%;left:50%;width:74px;height:74px;margin:-37px 0 0 -37px;border-radius:50%;border:2px solid rgba(255,255,255,.9);box-shadow:0 0 0 2px rgba(0,0,0,.35),0 0 18px rgba(124,92,255,.55);diff --git a/src/shared/frame-governor.js b/src/shared/frame-governor.jsnew file mode 100644index 000000000..51fed9efe--- /dev/null+++ b/src/shared/frame-governor.js@@ -0,0 +1,112 @@+// Shared frame governor — caps how often a rAF-driven 3D loop actually runs.+//+// requestAnimationFrame fires at the display's refresh rate: 120/144/240Hz+// panels render 2-4x the frames of a 60Hz one for zero visible benefit in+// our scenes, and an uncapped loop keeps the GPU pinned even when the user+// has clicked away to another window. That is exactly the "fans spin up and+// the laptop runs hot" complaint on /play and /club. The governor sits at+// the top of the loop: schedule rAF every frame as usual, but only run the+// sim + render body when the frame budget for the current cap has elapsed.+// Everything downstream is dt-based, so skipped frames simply arrive as a+// slightly larger delta on the next real one.+//+// It also owns the persisted "power saver" preference (one localStorage key+// shared by every 3D surface) so a user who turned it on in /play gets the+// same relief in /club without hunting for a second toggle.++const POWER_SAVER_KEY = 'tws-power-saver';+const POWER_SAVER_EVENT = 'tws-power-saver-change';++// One vocabulary for every surface, so the caps never drift between pages:+// - ACTIVE : focused tab, user is playing/watching+// - IDLE : tab visible but window unfocused, or a background scene+// (e.g. the /play lobby's ambient arena behind the coin grid)+// - SAVER : power-saver preference is on — hard 30fps everywhere+export const FPS_ACTIVE = 60;+export const FPS_IDLE = 30;+export const FPS_SAVER = 30;++/**+ * Create a frame-rate governor. Call `shouldRun(now, fpsCap)` at the top of+ * the rAF callback with the rAF timestamp; run the frame body only when it+ * returns true.+ *+ * The remainder-carry keeps the average rate honest on displays whose+ * refresh period doesn't divide the budget (a plain `last = now` on a 144Hz+ * panel quantizes a 60fps cap down to ~48fps), and the 0.5ms slack absorbs+ * timer jitter so a true 60Hz panel is never skipped.+ *+ * @returns {{ shouldRun(now: number, fpsCap: number): boolean, reset(): void }}+ */+export function createFrameGovernor() {+ let last = -Infinity;+ return {+ shouldRun(now, fpsCap) {+ if (!Number.isFinite(now)) return true;+ if (!Number.isFinite(fpsCap) || fpsCap <= 0) return false;+ const budget = 1000 / fpsCap - 0.5;+ if (now - last < budget) return false;+ // Carry the overshoot so skipped-frame quantization doesn't lower+ // the average rate; cap the carry at one budget so a long stall+ // (hidden tab, breakpoint) can't queue a burst of instant frames.+ last = Number.isFinite(last) ? now - ((now - last) % budget) : now;+ return true;+ },+ reset() { last = -Infinity; },+ };+}++/**+ * Read the persisted power-saver preference. Safe in private mode, sandboxed+ * iframes, and Node (vitest) — storage failures read as "off".+ */+export function getPowerSaver() {+ try { return localStorage.getItem(POWER_SAVER_KEY) === '1'; } catch { return false; }+}++/**+ * Persist the power-saver preference and notify listeners in this tab.+ * (Other tabs hear it through the native `storage` event.)+ */+export function setPowerSaver(on) {+ try { localStorage.setItem(POWER_SAVER_KEY, on ? '1' : '0'); } catch { /* storage disabled */ }+ if (typeof window !== 'undefined') {+ try { window.dispatchEvent(new CustomEvent(POWER_SAVER_EVENT, { detail: { on: !!on } })); } catch { /* CustomEvent unavailable */ }+ }+}++/**+ * Subscribe to power-saver changes from this tab (custom event) and other+ * tabs (storage event). Returns an unsubscribe function.+ *+ * @param {(on: boolean) => void} fn+ */+export function onPowerSaverChange(fn) {+ if (typeof window === 'undefined') return () => {};+ const onLocal = (e) => fn(!!e.detail?.on);+ const onStorage = (e) => { if (e.key === POWER_SAVER_KEY) fn(e.newValue === '1'); };+ window.addEventListener(POWER_SAVER_EVENT, onLocal);+ window.addEventListener('storage', onStorage);+ return () => {+ window.removeEventListener(POWER_SAVER_EVENT, onLocal);+ window.removeEventListener('storage', onStorage);+ };+}++/**+ * Track whether the window currently has focus, for the IDLE throttle.+ * `document.hasFocus()` seeds the state so a page opened in a background+ * window starts throttled instead of hot. Returns { focused } — read+ * `.focused` each frame; listeners keep it current.+ */+export function trackWindowFocus() {+ const state = { focused: true };+ if (typeof document !== 'undefined' && typeof document.hasFocus === 'function') {+ try { state.focused = document.hasFocus(); } catch { /* keep default */ }+ }+ if (typeof window !== 'undefined') {+ window.addEventListener('focus', () => { state.focused = true; });+ window.addEventListener('blur', () => { state.focused = false; });+ }+ return state;+}diff --git a/tests/frame-governor.test.js b/tests/frame-governor.test.jsnew file mode 100644index 000000000..67069ea96--- /dev/null+++ b/tests/frame-governor.test.js@@ -0,0 +1,142 @@+/**+ * Frame governor — unit tests.+ *+ * The governor is the heat fix for /play and /club: it caps how often a+ * rAF-driven loop actually does sim + render work, independent of the+ * display's refresh rate. These tests drive it with synthetic timestamps+ * (no rAF, no DOM) and assert the properties the pages rely on:+ *+ * - a 60fps cap on a 144Hz timestamp stream runs ~60 frames/sec, not 48+ * (the remainder-carry) and never more than the cap (+jitter slack)+ * - a true 60Hz stream under a 60fps cap never skips (the 0.5ms slack)+ * - cap changes take effect immediately (blur → 30fps)+ * - degenerate caps (0, NaN) refuse to run rather than running hot+ * - power-saver persistence round-trips and survives broken storage+ */++import { describe, it, expect, beforeEach } from 'vitest';+import {+ createFrameGovernor,+ getPowerSaver,+ setPowerSaver,+ FPS_ACTIVE,+ FPS_IDLE,+ FPS_SAVER,+} from '../src/shared/frame-governor.js';++// Count how many frames the governor lets through over `seconds` of a+// synthetic display running at `hz`, with a per-frame cap of `fps`.+function runStream({ hz, fps, seconds = 2, start = 1000 }) {+ const gov = createFrameGovernor();+ const period = 1000 / hz;+ const frames = Math.round(seconds * hz);+ let ran = 0;+ for (let i = 0; i < frames; i++) {+ if (gov.shouldRun(start + i * period, fps)) ran++;+ }+ return ran / seconds; // frames per second actually run+}++describe('createFrameGovernor', () => {+ it('caps a 144Hz stream to ~60fps (remainder-carry, no 48fps quantization)', () => {+ const rate = runStream({ hz: 144, fps: 60 });+ expect(rate).toBeGreaterThanOrEqual(55);+ expect(rate).toBeLessThanOrEqual(65);+ });++ it('caps a 240Hz stream to ~60fps', () => {+ const rate = runStream({ hz: 240, fps: 60 });+ expect(rate).toBeGreaterThanOrEqual(55);+ expect(rate).toBeLessThanOrEqual(65);+ });++ it('never skips frames on a true 60Hz panel at a 60fps cap', () => {+ const rate = runStream({ hz: 60, fps: 60 });+ expect(rate).toBe(60);+ });++ it('caps a 60Hz stream to ~30fps under the idle cap', () => {+ const rate = runStream({ hz: 60, fps: 30 });+ expect(rate).toBeGreaterThanOrEqual(28);+ expect(rate).toBeLessThanOrEqual(32);+ });++ it('applies a cap change on the very next frame', () => {+ const gov = createFrameGovernor();+ // 60Hz stream, active cap: every frame runs.+ expect(gov.shouldRun(0, 60)).toBe(true);+ expect(gov.shouldRun(16.67, 60)).toBe(true);+ // Blur → 30fps cap: the frame ~16ms later must now be skipped.+ expect(gov.shouldRun(33.33, 30)).toBe(false);+ expect(gov.shouldRun(50, 30)).toBe(true);+ });++ it('runs immediately after a long stall without a catch-up burst', () => {+ const gov = createFrameGovernor();+ expect(gov.shouldRun(0, 60)).toBe(true);+ // 5s hidden-tab gap: first frame back runs...+ expect(gov.shouldRun(5000, 60)).toBe(true);+ // ...and the next display frame does NOT get a queued burst.+ expect(gov.shouldRun(5006.9, 60)).toBe(false);+ });++ it('refuses to run on degenerate caps instead of running uncapped', () => {+ const gov = createFrameGovernor();+ expect(gov.shouldRun(0, 0)).toBe(false);+ expect(gov.shouldRun(16, -30)).toBe(false);+ expect(gov.shouldRun(32, NaN)).toBe(false);+ });++ it('fails open on a non-finite timestamp (never wedges the loop shut)', () => {+ const gov = createFrameGovernor();+ expect(gov.shouldRun(NaN, 60)).toBe(true);+ expect(gov.shouldRun(undefined, 60)).toBe(true);+ });++ it('reset() lets the next frame run regardless of recency', () => {+ const gov = createFrameGovernor();+ expect(gov.shouldRun(1000, 60)).toBe(true);+ expect(gov.shouldRun(1001, 60)).toBe(false);+ gov.reset();+ expect(gov.shouldRun(1002, 60)).toBe(true);+ });+});++describe('fps constants', () => {+ it('keeps the shared vocabulary sane (active > idle/saver > 0)', () => {+ expect(FPS_ACTIVE).toBeGreaterThan(FPS_IDLE);+ expect(FPS_IDLE).toBeGreaterThan(0);+ expect(FPS_SAVER).toBeGreaterThan(0);+ expect(FPS_SAVER).toBeLessThanOrEqual(FPS_IDLE);+ });+});++describe('power-saver persistence', () => {+ beforeEach(() => {+ // vitest environment may or may not provide localStorage; give the+ // module a working in-memory one for the round-trip test.+ const store = new Map();+ globalThis.localStorage = {+ getItem: (k) => (store.has(k) ? store.get(k) : null),+ setItem: (k, v) => store.set(k, String(v)),+ removeItem: (k) => store.delete(k),+ };+ });++ it('defaults off and round-trips on/off', () => {+ expect(getPowerSaver()).toBe(false);+ setPowerSaver(true);+ expect(getPowerSaver()).toBe(true);+ setPowerSaver(false);+ expect(getPowerSaver()).toBe(false);+ });++ it('reads as off when storage throws (private mode, sandboxed iframe)', () => {+ globalThis.localStorage = {+ getItem() { throw new Error('denied'); },+ setItem() { throw new Error('denied'); },+ };+ expect(getPowerSaver()).toBe(false);+ expect(() => setPowerSaver(true)).not.toThrow();+ });+});