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(splat): show the engine loading before awaiting it, and cover the viewer's element contract with tests
nirholas7d014f5f8f0d
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex dbd6c403c..98d6b8d27 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -43,6 +43,7 @@ bottom.| Scene Studio (3D scene editor) | [src/scene-studio/](src/scene-studio) `→ /scene`: boot [main.js](src/scene-studio/main.js), shared GLB loader [loader.js](src/scene-studio/loader.js), action bar [actions.js](src/scene-studio/actions.js), first-run overlay [empty-state.js](src/scene-studio/empty-state.js), icon-button labels [toolbar-a11y.js](src/scene-studio/toolbar-a11y.js), chrome [studio.css](src/scene-studio/studio.css) | Vendored [mrdoob/three.js](https://github.com/mrdoob/three.js) r184 editor, MIT, see [src/scene-studio/vendor/README.md](src/scene-studio/vendor/README.md) | Import GLBs, compose scenes, edit materials/lights, export. The sibling modules never touch `vendor/**`: they add the Import-from-Forge / Export-presets / Share bar (which docks beside the resizable sidebar rather than over its tabs), the empty-state card a brand-new scene needs, accessible names plus `aria-pressed` on the icon-only translate/rotate/scale buttons and names on the animation timeline's play/pause/stop transport, and toast-based failures in place of native `alert()`/`prompt()`. Below 600px the sidebar dock drops the vendored `.TabbedPanel` 335px floor so it fits a 320px screen instead of hanging 15px off it, and the empty-state card starts below the action bar and caps itself at the viewport region. Pinned under the nav by `--nav-h` (the real injected-header height), not `--header-h`. Deep links: `?model=<glb_url>`, `?handoff=1` from `/pose`, `#file=<url>`. Docs: [docs/scene-studio.md](docs/scene-studio.md), [src/scene-studio/README.md](src/scene-studio/README.md). Tests: [tests/scene-studio-actions.test.js](tests/scene-studio-actions.test.js) || Diorama (text → 3D world) | [src/diorama/](src/diorama) `→ /diorama` | In-repo · backend [api/diorama.js](api/diorama.js) | One sentence → an explorable 3D diorama: Claude composes the scene, each object is forged to a real GLB, assembled live, saved to a public gallery + shareable permalink || Scene Composer (dress an avatar) | [pages/compose.html](pages/compose.html) `→ /compose` + [src/scene-compose.js](src/scene-compose.js) | Live | Forge props from text and parent them to a rigged avatar's skeleton bones, then Export GLB or save them back onto the avatar record as `appearance.attachments`. Bones are grouped into readable regions and stripped of rig prefixes; transform gizmos, 50-deep undo, grid snap, camera presets. Feeds off [api/forge.js](api/forge.js), [api/forge-gallery.js](api/forge-gallery.js) (own creations, falling back to the community showcase for a first-time visitor), [api/explore.js](api/explore.js) `?source=avatar&only3d=1` for the avatar picker, and `PATCH /api/avatars/:id` for Save outfit. Below 900px the scene panel becomes a drawer. Docs: [docs/compose.md](docs/compose.md) |+| Splat Viewer (photoreal Gaussian avatars) | [pages/splat.html](pages/splat.html) `→ /splat` + page module [src/splat-viewer.js](src/splat-viewer.js), renderer [src/splat-stage.js](src/splat-stage.js) | Live | Renders Gaussian-splat and radiance-field scenes in the browser, the photoreal output of capture engines like GaussianAvatars and HumanGaussian. Loads a `.ply`, `.spz`, `.splat`, `.ksplat` or `.sog` by URL, by upload, by drag-and-drop onto the stage, or from a `?src=` deep link, plus two procedurally generated samples; decoding is entirely client-side and nothing is uploaded. The format is sniffed from the bytes rather than the filename, and the URL loader rewrites GitHub `blob`/`raw`, Hugging Face `/blob/` and Dropbox links to their CORS-enabled raw form so a pasted human-facing link still fetches. [src/splat-stage.js](src/splat-stage.js) is shared with the Forge Studio Lab ([src/forge-studio/lab/mesh-to-splat.js](src/forge-studio/lab/mesh-to-splat.js)) and wraps [Spark](https://github.com/sparkjsdev/spark) (`@sparkjsdev/spark`, MIT), lazy-loaded on first render and torn down explicitly (the WebGL context is released by hand on every scene swap, which Spark's own dispose stops short of). Every state is designed: idle/drop, engine load, fetch, decode, sort, error, and a live HUD carrying the scene label, its real splat count, a recenter control and a download of the loaded buffer. Docs: [docs/splat.md](docs/splat.md) || Creator portfolio (human profile) | [pages/profile.html](pages/profile.html) `→ /u/:username` (self-view `/profile`), backend [api/users/[username].js](api/users/%5Busername%5D.js) + paginated [api/users/[username]/creations.js](api/users/%5Busername%5D/creations.js) `→ /api/users/:username/creations` | Live | Every three.ws user's public portfolio: avatars, agents, widgets, skills, plugins, coins, memories, items for sale, and (added 2026-07-12, extended 2026-07-23) a **Creations** tab merging forged 3D models + Scene Studio worlds + Material Studio restyles — real, live, spinning `<model-viewer>` cards, cursor-paginated for 100+ items. `/forge`, `/diorama`, and `/restyle` all stay anonymous by default (no login required); a signed-in creator's `user_id` is attached to `forge_creations`/`dioramas` rows at generation/save time (migration [api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql](api/_lib/migrations/20260712010000_creator_portfolio_user_ids.sql)) and to a new `material_restyles` row per AI restyle or colorway variant (migration [api/_lib/migrations/20260723140000_material_restyles.sql](api/_lib/migrations/20260723140000_material_restyles.sql), store [api/_lib/material-restyle-store.js](api/_lib/material-restyle-store.js)) so those creations surface here. The same opt-in attribution now links back from the diorama viewer HUD, the diorama gallery cards, and the forge result bar ("by @user") whenever a creation's creator is known. `/@:handle` ([pages/handle.html](pages/handle.html)) is a separate, narrower agent-embed page — not the human portfolio. || Model detail page (`/m/:id`) | [pages/model.html](pages/model.html) `→ /m/:id`, page module [src/model-page.js](src/model-page.js) + pure helpers [src/model-lib.js](src/model-lib.js) + [src/model.css](src/model.css), backend [api/forge-creation.js](api/forge-creation.js) (`?related=&view=` + voted state; `DELETE`, scoped to the owning `x-forge-client`, lets a creator erase a creation, its stored GLB, preview, and recorded source uploads included) and [api/forge-comments.js](api/forge-comments.js), store reads [api/_lib/forge-store.js](api/_lib/forge-store.js) (`getPublicCreation`/`listRelated`/`recordCreationView`), schema [api/_lib/migrations/20260805120000_model_page.sql](api/_lib/migrations/20260805120000_model_page.sql) | Live | Every finished forge model as a first-class page in the classic model-platform detail layout: interactive viewer hero with AR and fullscreen, title + creator card with a real follow button (follow graph), live triangle/vertex stats from `GET /api/3d/inspect` (nothing persisted, nothing invented), the full prompt as the description, honest attribute chips, anonymous likes shared with the Forge-Off vote rail (`forge_votes`, same `forge:cid` id), a real page-view counter (`forge_creations.view_count`), a signed-in comment thread (`forge_comments`, bell-notifies the creator via the `comment` event type), paid remix via the existing x402 rail, embed/share/download, and a same-category suggested-models rail. Linked from the Details button on `/creations` cards and the Forge showcase. Tests: [tests/model-lib.test.js](tests/model-lib.test.js) || Labs (hidden-gems hub) | [pages/labs.html](pages/labs.html) + [src/labs.js](src/labs.js) `→ /labs` | In-repo | Data-driven discovery hub: renders every `data/pages.json` entry flagged `showcase: true` as a live card (status check + iframe preview), filterable by category |diff --git a/prompts/finish/243-swarm-100-route-splat.md b/prompts/finish/243-swarm-100-route-splat.mddeleted file mode 100644index a2efe7a49..000000000--- a/prompts/finish/243-swarm-100-route-splat.md+++ /dev/null@@ -1,119 +0,0 @@-# Route audit: /splat (Splat Viewer: Photoreal Gaussian Avatars)--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 sibling swarm-100 files in-prompts/finish/ 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==='/splat')console.log(JSON.stringify(g,null,2))"--2. Find the serving implementation: grep "/splat" 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/splat--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: /splat ("Splat Viewer: Photoreal Gaussian Avatars", section "build").-Declared purpose: Render Gaussian-splat and radiance-field avatars in the browser: the photoreal output of engines like GaussianAvatars and HumanGaussian. Load a .ply / .splat / .ksplat by URL or upload; decoding runs entirely client-side.--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/splat. 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 /splat: 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/finish/243-swarm-100-route-splat.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/locales/en.json b/public/locales/en.jsonindex f03e72e08..9d99703bb 100644--- a/public/locales/en.json+++ b/public/locales/en.json@@ -18590,6 +18590,7 @@"your_agent_s_llm_calls_four_tools": "Your agent's LLM calls four tools. Each one drives the visible avatar in the chat panel and returns a concise result the model reads back into the conversation — so the body language always matches what's happening on-chain."},"splat": {+ "choose_a_file": "Choose a file","couldn_t_load_that_splat": "Couldn’t load that splat","download_splat_arialabel": "Download splat","download_splat_title": "Download splat",@@ -18611,12 +18612,14 @@"radiance_shell_6k_splats": "<span class=\"sp-sample-dot\" style=\"background:#86efac\"></span> Radiance shell · 6k splats","recenter_camera_arialabel": "Recenter camera","recenter_camera_title": "Recenter camera",+ "render": "Render","render_gaussian_splat_and_radiance_field_ava": "Render Gaussian-splat and radiance-field avatars right in the browser — the photoreal output of engines like <a href=\"/avatar-engines?family=photoreal-head\">GaussianAvatars and HumanGaussian</a>. Load a <code>.ply</code>, <code>.spz</code>, <code>.splat</code>, <code>.ksplat</code>, or <code>.sog</code> by URL or drop a file in.","samples": "Samples","samples_are_procedurally_generated_to_exerci": "Samples are procedurally generated to exercise the renderer — not real captures.","splat_scene_url": "Splat scene URL","synthetic_head_bust_14k_splats": "<span class=\"sp-sample-dot\"></span> Synthetic head bust · 14k splats","try_a_sample": "Try a sample",+ "upload_a_file": "Upload a file","where_splats_come_from": "Where splats come from"},"stablecoin": {diff --git a/src/splat-viewer.js b/src/splat-viewer.jsindex f8d42ee80..2b29a58a1 100644--- a/src/splat-viewer.js+++ b/src/splat-viewer.js@@ -94,6 +94,23 @@ function setDownload(url, filename) {btn.hidden = false;}+// Enter a loading state, THEN await the engine. Spark is a multi-megabyte lazy+// chunk fetched on first use, and two of the three entry points used to await it+// before painting anything, so the first click on a sample or an upload sat on+// the idle overlay with no feedback for as long as the download took. An import+// that never settles read as a dead button. A failed import now lands in the+// page's designed error state instead of an unhandled rejection.+async function requireSpark(title, detail) {+ setLoading(title, detail);+ try {+ return await loadSpark();+ } catch (err) {+ setError('The splat engine did not load', 'The renderer is fetched on first use and that request did not complete. Check your connection, then try again.');+ console.error('[splat] engine load failed', err);+ return null;+ }+}+// -- Core render --------------------------------------------------------------async function renderBuffer(buffer, { label, fileType, fileName, flip = true }) {_lastRender = { buffer, fileType, fileName, label, flip };@@ -173,8 +190,8 @@ async function loadFromUrl(url, label) {let parsed;try { parsed = new URL(url, location.href); } catch { setError('That doesn’t look like a URL', url); return; }parsed = normalizeAssetUrl(parsed);- setLoading('Fetching splat…', parsed.hostname);- const SPARK = await loadSpark();+ const SPARK = await requireSpark('Fetching splat…', parsed.hostname);+ if (!SPARK) return;let buffer;try {const res = await fetch(parsed.href);@@ -194,8 +211,8 @@ async function loadFromUrl(url, label) {}async function loadFromFile(file) {- const SPARK = await loadSpark();- setLoading('Reading file…', file.name);+ const SPARK = await requireSpark('Reading file…', file.name);+ if (!SPARK) return;let buffer;try { buffer = await file.arrayBuffer(); }catch (err) { setError('Couldn’t read that file', err.message); return; }@@ -275,8 +292,9 @@ function sampleBust(count = 14000) {}async function loadSample(kind) {- const SPARK = await loadSpark();const isBust = kind === 'bust';+ const SPARK = await requireSpark('Loading splat engine\u2026', 'Preparing the Gaussian-splat renderer.');+ if (!SPARK) return;const buffer = isBust ? sampleBust() : sampleShell();const label = isBust ? 'Synthetic head bust' : 'Radiance shell';const name = isBust ? 'sample-bust.splat' : 'sample-shell.splat';diff --git a/tests/splat-viewer-page.test.js b/tests/splat-viewer-page.test.jsnew file mode 100644index 000000000..d1a5ab8d4--- /dev/null+++ b/tests/splat-viewer-page.test.js@@ -0,0 +1,115 @@+// @vitest-environment jsdom+//+// The Splat Viewer page and its module have to agree on element ids, and+// nothing in the build checks that. Three defects shipped from that gap and+// were live in production until this test landed:+//+// 1. `setLoading`/`setError` wrote their detail line into `#sp-loading-detail`+// and `#sp-error-detail`. The page calls those nodes `#sp-loading-sub` and+// `#sp-error-sub`, so every write landed on null. A failed load rendered a+// heading over an empty space, and the one sentence telling the visitor+// what to do (download the file and upload it when a host blocks CORS)+// was never shown.+// 2. `setHud` wrote the scene label with `hud.textContent = label`. `#sp-hud`+// is the container that also holds the recenter button and the download+// link, so the first successful render deleted both controls from the DOM+// and every later query for them returned null.+// 3. The state strings the script writes sit on nodes the markup annotates+// for translation. src/i18n.js reverts those unless the script claims the+// node with `data-i18n-owned`, so "Sorting splats" snapped back to the+// catalog's "Loading splat engine" seconds into every load.+//+// The first test is the general property: every id the module writes to must+// exist in the page. The rest pin the two mechanisms.++import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, it, expect } from 'vitest';+import { applyCatalog } from '../src/i18n.js';++const ROOT = resolve(import.meta.dirname, '..');+const PAGE = readFileSync(resolve(ROOT, 'pages/splat.html'), 'utf8');+const MODULE = readFileSync(resolve(ROOT, 'src/splat-viewer.js'), 'utf8');++/** Ids the page markup defines. */+function pageIds() {+ return new Set([...PAGE.matchAll(/\bid="([^"]+)"/g)].map((m) => m[1]));+}++/** Ids the module looks up through its `$('#…')` helper. */+function moduleIds() {+ return [...MODULE.matchAll(/\$\(`?#([a-z0-9-]+)/gi)].map((m) => m[1]);+}++const catalog = (locale) => (key) => {+ const [ns, ...rest] = key.split('.');+ const hit = locale[ns]?.[rest.join('.')];+ return hit === undefined ? key : hit;+};++function stage() {+ const match = PAGE.match(/<div class="sp-stage" id="sp-stage">[\s\S]*?\n\t\t\t\t\t<\/div>/);+ expect(match, 'the stage markup should still be in the page').toBeTruthy();+ document.body.innerHTML = match[0];+ return document.body;+}++describe('splat viewer page and module agree', () => {+ it('defines every element id the module writes to', () => {+ const defined = pageIds();+ const missing = [...new Set(moduleIds())].filter((id) => !defined.has(id));+ expect(missing, `pages/splat.html is missing ids used by src/splat-viewer.js: ${missing.join(', ')}`).toEqual([]);+ });++ it('gives the HUD label its own node, separate from the HUD controls', () => {+ const root = stage();+ const hud = root.querySelector('#sp-hud');+ const label = root.querySelector('#sp-hud-label');+ const recenter = root.querySelector('#sp-recenter');+ const download = root.querySelector('#sp-download');+ expect(label, '#sp-hud-label must exist').toBeTruthy();+ expect(recenter && download, 'the HUD must carry a recenter control and a download link').toBeTruthy();+ expect(label.contains(recenter), 'the controls must not live inside the label node').toBe(false);++ // What the module does on going live: write the label, leave the controls.+ label.textContent = 'Synthetic head bust · 14,000 splats';+ expect(hud.querySelector('#sp-recenter')).toBe(recenter);+ expect(hud.querySelector('#sp-download')).toBe(download);+ });++ it('never writes the scene label onto the HUD container itself', () => {+ expect(MODULE).not.toMatch(/hud\.textContent\s*=/);+ });++ it('keeps a script-written state string across the catalog pass', () => {+ const root = stage();+ const title = root.querySelector('#sp-loading-title');+ const sub = root.querySelector('#sp-loading-sub');+ expect(title.hasAttribute('data-i18n'), 'the loading title ships a translated placeholder').toBe(true);++ // setText(): write the live value and claim the node, as the module does.+ for (const [node, value] of [[title, 'Sorting splats…'], [sub, '14,000 splats']]) {+ node.textContent = value;+ node.dataset.i18nOwned = '1';+ }+ applyCatalog(document, catalog(JSON.parse(readFileSync(resolve(ROOT, 'public/locales/en.json'), 'utf8'))));++ expect(title.textContent).toBe('Sorting splats…');+ expect(sub.textContent).toBe('14,000 splats');+ });++ it('still translates the state copy that no script has claimed', () => {+ const root = stage();+ applyCatalog(document, catalog({ splat: { load_a_splat_to_begin: 'Lade ein Splat' } }));+ expect(root.querySelector('#sp-idle h3').textContent).toBe('Lade ein Splat');+ });++ it('shows a loading state before awaiting the splat engine', () => {+ // requireSpark() paints first and awaits second; a bare `await loadSpark()`+ // at an entry point is the regression (the click looked like a dead button+ // for as long as the multi-megabyte engine took to arrive).+ expect(MODULE).toMatch(/async function requireSpark\(/);+ expect(MODULE.match(/await loadSpark\(\)/g) || []).toHaveLength(1);+ });+});