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
fix(spatial-mcp): give the reference renderer a loading skeleton and an error state with a working retry, and name the page for what it is
nirholasda22a461b851
diff --git a/data/changelog.json b/data/changelog.jsonindex 48dafdac3..91d7d491e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -25450,6 +25450,16 @@"improvement"],"link": "/strategies"+ },+ {+ "date": "2026-09-01",+ "title": "Spatial MCP renderer: a clear message and a retry when a scene cannot be fetched",+ "summary": "The reference renderer on /spatial-mcp now shows a shimmer while a GLB downloads and, if the asset cannot be fetched or decoded, replaces the empty frame with a message that names the host, explains what to check (reachable, https, CORS, a valid .glb), and offers a Try again button that re-renders in place. Any host that embeds the renderer gets the same loading, ready, error, and empty states through a data-spatial-state attribute on the mount. The page title and description now say plainly what the page is: the reference renderer for the open Spatial MCP standard.",+ "tags": [+ "improvement",+ "fix"+ ],+ "link": "/spatial-mcp"}]}diff --git a/docs/spatial-mcp.md b/docs/spatial-mcp.mdindex ae4683a76..06c200e81 100644--- a/docs/spatial-mcp.md+++ b/docs/spatial-mcp.md@@ -91,7 +91,7 @@ The reference renderer is framework-free and reusable independent of three.ws:</script>```-It applies `camera`/`environment`/`affordances`, plays `animation` when present, offers AR when `ar` (or the GLB) supports it, and shows a designed fallback for an unusable payload — never a blank frame.+It applies `camera`/`environment`/`affordances`, plays `animation` when present, offers AR when `ar` (or the GLB) supports it, and never shows a blank frame: an unusable payload gets a designed fallback (`.spatial-empty`), a downloading GLB gets a skeleton under the viewer (`.spatial-loading`), and a GLB that cannot be fetched or decoded gets an error message that names the host, says what to check (reachable, https, `Access-Control-Allow-Origin`, a valid `.glb`), and offers a `.spatial-retry` button that re-renders in place (`.spatial-error`). The mount carries `data-spatial-state` (`empty`, `loading`, `ready`, `error`) so a host can style each state; the renderer ships no CSS of its own, so style those classes the way [`/spatial-mcp`](https://three.ws/spatial-mcp) does or the way your host already styles its own empty and error cards.## Data minimization (required for store-safe adoption)diff --git a/prompts/swarm-100/route-spatial-mcp.md b/prompts/swarm-100/route-spatial-mcp.mddeleted file mode 100644index 2c2280f45..000000000--- a/prompts/swarm-100/route-spatial-mcp.md+++ /dev/null@@ -1,119 +0,0 @@-# Route audit: /spatial-mcp (Spatial MCP: reference renderer)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. This route's declared entry (path, description, added date):-- node -e "const p=require('./data/pages.json');for(const s of p.sections)for(const g of s.pages)if(g.path==='/spatial-mcp')console.log(JSON.stringify(g,null,2))"--2. Find the serving implementation: grep "/spatial-mcp" in vercel.json (the live- route table server/index.mjs boots from), then list matching files in- pages/ and src/. STRUCTURE.md maps every surface to its directory if the- grep is ambiguous.-3. Production right now:-- curl -so /dev/null -w '%{http_code}\n' https://three.ws/spatial-mcp--4. Start (or reuse) the local dev server: npm run dev (vite, port 3000).--## Task: audit this one route end to end, then fix everything found--Route: /spatial-mcp ("Spatial MCP: reference renderer", section "labs").-Declared purpose: The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact: including ones transformed from other tools.--Drive the page in a real headless browser. Playwright is already a dev-dependency; keep your probe script in the session scratchpad, never in the-repo.--1. Load http://localhost:3000/spatial-mcp. Record the HTTP status, every console- error and warning, and every failed network request.-2. Exercise it like a first-time user: click the primary actions, run the- primary flow if one exists, follow the page's internal links. Every button- must do something real; every link must resolve. If the page renders data,- prove in the network log that it came from a live endpoint, not a baked-in- fallback array.-3. States: verify populated, empty, loading, and error states are designed and- reachable. Block the page's primary fetch in Playwright and confirm an- actionable error state appears, not a blank void or a raw exception.-4. Responsive: render at 320, 768, and 1440 px. No horizontal page scroll, no- overlapping or clipped controls.-5. Accessibility basics: one h1; interactive elements are real buttons or- links with visible focus states; images carry alt text; form fields have- labels.-6. Head: a specific title tag and meta description that match the declared- purpose above.-7. Fix every defect at its root in the page's real source files and re-run the- probe until clean. Defects in shared modules are in scope when this route- exercises them.--## Definition of done--- [ ] Local load of /spatial-mcp: HTTP 200, zero console errors, zero unhandled- failed requests (a third-party outage must land in a designed fallback,- not a broken page).-- [ ] No dead interactive element on the page: no stub href="#", no button- without a handler, no link to a missing path.-- [ ] Empty, loading, error, and populated states verified.-- [ ] 320 / 768 / 1440 px renders verified clean.-- [ ] Title and meta description present and specific.-- [ ] npm test passes; npm run check:rules -- --paths <touched files> exits 0.-- [ ] Production status from step 0 recorded in the report; if production- needs a deploy to pick up a fix, the report says so (deploys stay- owner-gated).--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/route-spatial-mcp.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/public/spatial-mcp/index.html b/public/spatial-mcp/index.htmlindex 5d5581b3e..708071db8 100644--- a/public/spatial-mcp/index.html+++ b/public/spatial-mcp/index.html@@ -3,8 +3,8 @@<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />-<title data-i18n="spatial_mcp_index.meta_title">Spatial MCP — reference renderer</title>-<meta name="description" content="Reference renderer for the open Spatial MCP artifact shape — 3D as a native conversational MCP response type." data-i18n-attr="content:spatial_mcp_index.meta_description"/>+<title data-i18n="spatial_mcp_index.meta_title">Spatial MCP: reference renderer</title>+<meta name="description" content="The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact: including ones transformed from other tools." data-i18n-attr="content:spatial_mcp_index.meta_description"/><script src="/model-viewer-meshopt.js"></script><script type="module" src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"></script><style>@@ -20,8 +20,17 @@@media (min-width: 760px){ .grid { grid-template-columns: 1fr 1fr; } }.card { border:1px solid rgba(255,255,255,0.08); border-radius:14px; overflow:hidden; background: rgba(12,14,19,0.6); }.card h2 { font-size:13px; letter-spacing:.02em; text-transform:uppercase; color:#aeb6c4; margin:0; padding:12px 14px; border-bottom:1px solid rgba(255,255,255,0.07); }- .stage { height: 340px; background: transparent; }+ .stage { height: 340px; background: transparent; position:relative; }.spatial-empty { display:flex; align-items:center; justify-content:center; height:100%; color:#9aa3b2; font-size:13px; text-align:center; padding:20px; }+ /* Renderer states (see the header of spatial-renderer.js). The skeleton sits+ under the viewer's transparent canvas while the GLB downloads; the error+ box replaces the viewer when the asset cannot be fetched or decoded. */+ .spatial-loading { position:absolute; inset:0; z-index:0;+ background: linear-gradient(100deg, rgba(255,255,255,0.03) 30%, rgba(255,255,255,0.09) 50%, rgba(255,255,255,0.03) 70%);+ background-size: 200% 100%; animation: spatial-shimmer 1.6s ease-in-out infinite; }+ @keyframes spatial-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }+ .spatial-error { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:10px; height:100%; padding:20px; text-align:center; color:#e8eaf0; font-size:13px; }+ .spatial-error p { margin:0; max-width:46ch; color:#9aa3b2; line-height:1.55; }pre { margin:0; padding:14px; font-size:12px; line-height:1.5; overflow:auto; max-height:340px; color:#cbd3e1; }.note { margin-top:24px; font-size:13px; color:#9aa3b2; line-height:1.6; }code { color:#dbe9ff; }@@ -38,12 +47,12 @@/* Payload checker */.checker { display:grid; gap:12px; padding:14px; }.checker-bar { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }- .btn { font:inherit; font-size:12px; padding:7px 12px; border-radius:8px; cursor:pointer; color:#e8eaf0;+ .btn, .spatial-retry { font:inherit; font-size:12px; padding:7px 12px; border-radius:8px; cursor:pointer; color:#e8eaf0;border:1px solid rgba(255,255,255,0.14); background:rgba(255,255,255,0.04);transition: background 140ms ease, border-color 140ms ease, transform 140ms ease; }- .btn:hover { background:rgba(255,255,255,0.08); border-color:rgba(255,255,255,0.24); }- .btn:active { transform:translateY(1px); }- .btn:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }+ .btn:hover, .spatial-retry:hover { background:rgba(255,255,255,0.08); border-color:rgba(255,255,255,0.24); }+ .btn:active, .spatial-retry:active { transform:translateY(1px); }+ .btn:focus-visible, .spatial-retry:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }.btn-primary { color:#cfe0ff; background:rgba(110,168,254,0.14); border-color:rgba(110,168,254,0.45); }.btn-primary:hover { background:rgba(110,168,254,0.22); border-color:rgba(110,168,254,0.65); }.checker textarea { width:100%; min-height:220px; resize:vertical; padding:12px; border-radius:10px;@@ -62,7 +71,7 @@.diag-warn { box-shadow: inset 2px 0 0 var(--warn); }.diag-note { color:#9aa3b2; }.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; border:0; }- @media (prefers-reduced-motion: reduce) { .btn { transition:none; } }+ @media (prefers-reduced-motion: reduce) { .btn, .spatial-retry { transition:none; } .spatial-loading { animation:none; } }</style><link rel="canonical" href="https://three.ws/spatial-mcp">@@ -70,28 +79,28 @@<meta property="og:type" content="website"><meta property="og:site_name" content="three.ws"><meta property="og:locale" content="en_US">- <meta property="og:title" content="Spatial MCP — reference renderer · three.ws" data-i18n-attr="content:spatial_mcp_index.meta_og_title">- <meta property="og:description" content="The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact — including ones transformed from other tools." data-i18n-attr="content:spatial_mcp_index.meta_og_description">+ <meta property="og:title" content="Spatial MCP: reference renderer · three.ws" data-i18n-attr="content:spatial_mcp_index.meta_og_title">+ <meta property="og:description" content="The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact: including ones transformed from other tools." data-i18n-attr="content:spatial_mcp_index.meta_og_description"><meta property="og:url" content="https://three.ws/spatial-mcp"><meta property="og:image" content="https://three.ws/api/page-og?s=labs&t=Spatial+MCP%3A+reference+renderer&d=The+open+standard+for+returning+a+live%2C+interactive+3D+scene+as+a+first-class+MCP+tool+result%2C+with+a+framework-free+reference+renderer+that+displays+any&p=%2Fspatial-mcp"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta property="og:image:type" content="image/png">- <meta property="og:image:alt" content="Spatial MCP — reference renderer — three.ws">+ <meta property="og:image:alt" content="Spatial MCP: reference renderer, on three.ws"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content="@trythreews">- <meta name="twitter:title" content="Spatial MCP — reference renderer · three.ws" data-i18n-attr="content:spatial_mcp_index.meta_twitter_title">- <meta name="twitter:description" content="The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact — including ones transformed from other tools." data-i18n-attr="content:spatial_mcp_index.meta_twitter_description">+ <meta name="twitter:title" content="Spatial MCP: reference renderer · three.ws" data-i18n-attr="content:spatial_mcp_index.meta_twitter_title">+ <meta name="twitter:description" content="The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact: including ones transformed from other tools." data-i18n-attr="content:spatial_mcp_index.meta_twitter_description"><meta name="twitter:image" content="https://three.ws/api/page-og?s=labs&t=Spatial+MCP%3A+reference+renderer&d=The+open+standard+for+returning+a+live%2C+interactive+3D+scene+as+a+first-class+MCP+tool+result%2C+with+a+framework-free+reference+renderer+that+displays+any&p=%2Fspatial-mcp">- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Spatial MCP — reference renderer","description":"The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact — including ones transformed from other tools.","url":"https://three.ws/spatial-mcp","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=labs&t=Spatial+MCP+%E2%80%94+reference+renderer&d=The+open+standard+for+returning+a+live%2C+interactive+3D+scene+as+a+first-class+MCP+tool+result%2C+with+a+framework-free+reference+renderer+that+displays+any+confor&p=%2Fspatial-mcp"}]}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Spatial MCP: reference renderer","description":"The open standard for returning a live, interactive 3D scene as a first-class MCP tool result, with a framework-free reference renderer that displays any conformant artifact: including ones transformed from other tools.","url":"https://three.ws/spatial-mcp","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=labs&t=Spatial+MCP%3A+reference+renderer&d=The+open+standard+for+returning+a+live%2C+interactive+3D+scene+as+a+first-class+MCP+tool+result%2C+with+a+framework-free+reference+renderer+that+displays+any&p=%2Fspatial-mcp"}]}</script></head><body><div class="page">- <h1 data-i18n="spatial_mcp_index.spatial_mcp_reference_renderer">Spatial MCP — reference renderer</h1>+ <h1 data-i18n="spatial_mcp_index.spatial_mcp_reference_renderer">Spatial MCP: reference renderer</h1><p class="lede" data-i18n-html="spatial_mcp_index.spatial_mcp_makes_a_live_interactive_3d"><strong>Spatial MCP</strong> makes a live, interactive 3D scene a first-class MCP tool result, not a URL in text.- This page is the reference renderer for the open artifact shape. It renders the conformant payload below —- including one <em>transformed from a different (foreign) tool's output</em> — proving the shape is portable.+ This page is the reference renderer for the open artifact shape. It renders the conformant payload below,+ including one <em>transformed from a different (foreign) tool's output</em>, proving the shape is portable.Spec: <a href="https://github.com/nirholas/three.ws/blob/main/specs/SPATIAL_MCP.md">SPATIAL_MCP.md</a>.</p>@@ -134,7 +143,7 @@</div><p class="note" data-i18n-html="spatial_mcp_index.a_third_party_mcp_server_that_returns">- A third-party MCP server that returns <code>{ url, previewImage }</code> becomes conformant with a tiny adapter —+ A third-party MCP server that returns <code>{ url, previewImage }</code> becomes conformant with a tiny adapter;see <a href="/docs/spatial-mcp">docs/spatial-mcp</a>. Any renderer that speaks this shape (this one included) thendisplays it. No payment, wallet, or coin surface anywhere in the shape or the renderer.</p>diff --git a/public/spatial-mcp/spatial-renderer.js b/public/spatial-mcp/spatial-renderer.jsindex e719f5cb4..829874ed9 100644--- a/public/spatial-mcp/spatial-renderer.js+++ b/public/spatial-mcp/spatial-renderer.js@@ -1,9 +1,9 @@-// Spatial MCP reference renderer — renders any conformant Spatial MCP artifact.+// Spatial MCP reference renderer: renders any conformant Spatial MCP artifact.//// A small, dependency-light, framework-free renderer that turns a Spatial MCP// artifact (specs/SPATIAL_MCP.md) into an interactive <model-viewer> scene:// orbit/zoom, animation playback, an AR button, and graceful fallback for every-// missing optional field. It is the REFERENCE IMPLEMENTATION of the spec — any+// missing optional field. It is the REFERENCE IMPLEMENTATION of the spec: any// MCP host or third-party app can adopt this shape and use (or reimplement) this// renderer. Zero payment/wallet/coin surface, so it drops into the free OpenAI// track unchanged.@@ -15,6 +15,16 @@// It expects the <model-viewer> custom element to be available on the page (load// @google/model-viewer). It never fetches anything itself beyond the GLB the// artifact points at, and only ever loads https assets.+//+// Every state is designed, never a blank frame. The mount carries+// `data-spatial-state` through the whole lifecycle so a host can style each one:+// "empty" the payload is unusable; a `.spatial-empty` message is shown+// "loading" the GLB is downloading; a `.spatial-loading` skeleton sits under+// the viewer until it decodes+// "ready" the scene is on screen+// "error" the GLB could not be fetched or decoded; the viewer is replaced by+// a `.spatial-error` message that names the host, says what to+// check, and offers a `.spatial-retry` button that re-rendersfunction isHttps(u) {try {@@ -24,8 +34,8 @@ function isHttps(u) {}}-// Minimal structural check mirroring api/_lib/spatial-mcp.js validateSpatialArtifact-// — enough to render safely. The full validator is the authority; this keeps the+// Minimal structural check mirroring api/_lib/spatial-mcp.js validateSpatialArtifact,+// enough to render safely. The full validator is the authority; this keeps the// renderer standalone (no build-time import) while refusing an unusable payload.export function canRenderSpatialArtifact(artifact) {return (@@ -37,16 +47,80 @@ export function canRenderSpatialArtifact(artifact) {);}+/** The host a scene is served from, for the error copy. */+function hostOf(url) {+ try {+ return new URL(url).host;+ } catch {+ return String(url);+ }+}++function setState(mount, state) {+ mount.dataset.spatialState = state;+ if (state === 'loading') mount.setAttribute('aria-busy', 'true');+ else mount.removeAttribute('aria-busy');+}++/**+ * The designed error state: what a host shows when the asset behind a conformant+ * artifact is unreachable. Actionable by construction: it names the host, lists+ * the three things that make a GLB unfetchable from a browser, and retries in+ * place.+ */+function renderLoadError(mount, artifact, attempt) {+ mount.textContent = '';+ setState(mount, 'error');++ const box = document.createElement('div');+ box.className = 'spatial-error';+ box.setAttribute('role', 'alert');++ const title = document.createElement('strong');+ title.textContent = 'The 3D scene could not be loaded.';++ const detail = document.createElement('p');+ detail.textContent =+ `${hostOf(artifact.scene.glbUrl)} did not return a readable GLB. Check that the URL is reachable, ` ++ 'served over https with an Access-Control-Allow-Origin header, and is a valid .glb file, then try again.';++ const retry = document.createElement('button');+ retry.type = 'button';+ retry.className = 'spatial-retry';+ retry.textContent = 'Try again';+ retry.addEventListener('click', () => render(mount, artifact, attempt + 1));++ box.append(title, detail, retry);+ mount.appendChild(box);+}++/**+ * The URL handed to <model-viewer>. model-viewer keeps a per-URL cache of loaded+ * scenes and, after a failed fetch, parks an empty scene under that URL, so a+ * retry with the identical string would show the failure again without a+ * single new request. A fragment is never sent to the server (the fetch, any+ * signature on the URL, and the CDN cache are all unchanged) but it is a+ * different cache key, so each retry genuinely refetches.+ */+function sourceUrl(glbUrl, attempt) {+ return attempt > 0 ? `${glbUrl}#spatial-retry-${attempt}` : glbUrl;+}+/*** Render a Spatial MCP artifact into `mount`. Returns the created <model-viewer>- * element (or null when the artifact can't be rendered — the mount then shows a+ * element (or null when the artifact can't be rendered; the mount then shows a* designed fallback message instead of a blank frame).*/export function renderSpatialArtifact(mount, artifact) {+ return render(mount, artifact, 0);+}++function render(mount, artifact, attempt) {if (!mount) return null;mount.textContent = '';if (!canRenderSpatialArtifact(artifact)) {+ setState(mount, 'empty');const msg = document.createElement('div');msg.className = 'spatial-empty';msg.textContent = 'No renderable 3D scene in this payload.';@@ -61,11 +135,11 @@ export function renderSpatialArtifact(mount, artifact) {const ar = artifact.ar || {};const mv = document.createElement('model-viewer');- mv.setAttribute('src', scene.glbUrl);+ mv.setAttribute('src', sourceUrl(scene.glbUrl, attempt));mv.setAttribute('alt', scene.alt || (artifact.meta && artifact.meta.title) || 'Interactive 3D model');if (isHttps(scene.poster)) mv.setAttribute('poster', scene.poster);- // Camera / interaction — honor affordances, default to a framed, orbitable view.+ // Camera / interaction: honor affordances, default to a framed, orbitable view.if (affordances.orbit !== false) mv.setAttribute('camera-controls', '');if (camera.autoRotate !== false) mv.setAttribute('auto-rotate', '');if (typeof camera.orbit === 'string') mv.setAttribute('camera-orbit', camera.orbit);@@ -80,7 +154,7 @@ export function renderSpatialArtifact(mount, artifact) {if (typeof env.shadowIntensity === 'number') mv.setAttribute('shadow-intensity', String(env.shadowIntensity));mv.setAttribute('tone-mapping', 'aces');- // Animation — autoplay when the artifact declares an animation block.+ // Animation: autoplay when the artifact declares an animation block.if (artifact.animation) {if (artifact.animation.autoplay !== false) mv.setAttribute('autoplay', '');if (Array.isArray(artifact.animation.clips) && artifact.animation.clips.length) {@@ -88,7 +162,7 @@ export function renderSpatialArtifact(mount, artifact) {}}- // AR handoff — enable AR when the artifact declares an AR asset/link, or always+ // AR handoff: enable AR when the artifact declares an AR asset/link, or always// offer WebXR/Scene-Viewer/Quick-Look from the GLB itself as a graceful default.mv.setAttribute('ar', '');mv.setAttribute('ar-modes', 'webxr scene-viewer quick-look');@@ -98,7 +172,41 @@ export function renderSpatialArtifact(mount, artifact) {mv.style.width = '100%';mv.style.height = '100%';mv.style.background = 'transparent';- mount.appendChild(mv);+ // The viewer paints above the skeleton; the skeleton shows through its+ // transparent canvas until the scene decodes, then goes away.+ mv.style.position = 'relative';+ mv.style.zIndex = '1';++ const skeleton = document.createElement('div');+ skeleton.className = 'spatial-loading';+ skeleton.setAttribute('aria-hidden', 'true');++ setState(mount, 'loading');+ mount.append(skeleton, mv);++ // A mount can be re-rendered while a previous viewer is still downloading.+ // That viewer is detached but its load still settles, so its events must not+ // touch the mount's current state: only a viewer that is still the mount's+ // child may report.+ const current = () => mv.parentNode === mount;+ mv.addEventListener(+ 'load',+ () => {+ if (!current()) return;+ skeleton.remove();+ setState(mount, 'ready');+ },+ { once: true },+ );+ // model-viewer reports a failed fetch or decode as an `error` event with+ // `detail.type === 'loadfailure'` (other types, such as a lost WebGL context,+ // are transient and the viewer recovers on its own).+ mv.addEventListener('error', (event) => {+ if (!current()) return;+ const type = event.detail && event.detail.type;+ if (type && type !== 'loadfailure') return;+ renderLoadError(mount, artifact, attempt);+ });return mv;}diff --git a/tests/e2e/spatial-mcp-render.spec.js b/tests/e2e/spatial-mcp-render.spec.jsindex ef746793e..c226a3aa2 100644--- a/tests/e2e/spatial-mcp-render.spec.js+++ b/tests/e2e/spatial-mcp-render.spec.js@@ -38,16 +38,20 @@ const STAGES = [// Vite's HMR socket cannot reach the dev server through a proxied port (Codespaces,// any remote container), which surfaces as a failed ws request and an uncaught// "WebSocket closed without opened." Both are dev-server plumbing that does not-// exist in the built page, so they are the only ignored signals here. Anything a-// visitor's browser could hit counts as a failure.-const DEV_SERVER_NOISE = /^ws|\/@vite\//;+// exist in the built page. The analytics loader under /ingest is the third+// exemption: in dev it is a vite proxy to PostHog's asset host, which+// intermittently answers 500 from a remote container, and the page is designed+// to run without analytics (the snippet fails silently), so its outage is not a+// rendering failure this spec guards. Anything else a visitor's browser could+// hit counts as a failure.+const DEV_SERVER_NOISE = /^ws|\/@vite\/|\/ingest\//;const DEV_SERVER_ERROR = /WebSocket closed without opened/;/** Collect every response that failed, plus uncaught page errors. */function watchFailures(page) {const failures = [];page.on('response', (r) => {- if (r.status() >= 400) failures.push(`HTTP ${r.status()} ${r.url()}`);+ if (r.status() >= 400 && !DEV_SERVER_NOISE.test(r.url())) failures.push(`HTTP ${r.status()} ${r.url()}`);});page.on('pageerror', (e) => {if (DEV_SERVER_ERROR.test(e.message)) return;@@ -126,4 +130,43 @@ test('the checker names the offending field on a broken payload', async ({ page// An unusable payload gets the designed fallback, never a blank frame.await expect(page.locator('#stage-check .spatial-empty')).toHaveCount(1);+ await expect(page.locator('#stage-check')).toHaveAttribute('data-spatial-state', 'empty');+});++// The other way a frame goes blank: the payload is conformant but the asset+// behind it is unreachable (host down, CORS missing, a dead CDN path). A+// visitor must get told what failed and be able to retry without reloading,+// so this blocks every GLB, demands the designed error state on every stage,+// then lifts the block and proves the retry button renders the scene.+test('an unreachable GLB gets a designed error state, and its retry renders the scene', async ({ page }) => {+ test.setTimeout(180_000);+ let blocked = true;+ await page.route(/\.glb(\?|$)/, (route) => (blocked ? route.abort() : route.continue()));++ await page.goto('/spatial-mcp', { waitUntil: 'load' });++ for (const stage of STAGES) {+ const error = page.locator(`#${stage.id} .spatial-error`);+ await expect(error, `${stage.label}: no error state after the GLB fetch failed`).toBeVisible({+ timeout: 60_000,+ });+ await expect(error).toContainText('could not be loaded');+ await expect(error.locator('.spatial-retry')).toBeVisible();+ await expect(page.locator(`#${stage.id} model-viewer`)).toHaveCount(0);+ await expect(page.locator(`#${stage.id}`)).toHaveAttribute('data-spatial-state', 'error');+ }++ blocked = false;+ await page.locator('#stage-native .spatial-retry').click();+ const viewer = page.locator('#stage-native model-viewer');+ await expect(viewer).toHaveCount(1);+ await expect+ .poll(() => viewer.evaluate((el) => el.loaded === true), {+ message: 'retry did not load the GLB once the network came back',+ timeout: 60_000,+ })+ .toBe(true);+ await expect(page.locator('#stage-native')).toHaveAttribute('data-spatial-state', 'ready');+ await expect(page.locator('#stage-native .spatial-loading')).toHaveCount(0);+ await expect(page.locator('#stage-native .spatial-error')).toHaveCount(0);});