Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

49.2 KB
Raw Blame

3D Editing, Viewing & Validation

UX Flow Atlas, cluster "3D Editing, Viewing & Validation". Each entry is traced from real source code (file + symbol citations). Routing was resolved by reading vite.config.js dev-server rewrites and each page's <script> imports.

Routing summary (from vite.config.js):

Route Page HTML Entry module
/scene pages/scene.html src/scene-studio/main.js (vendored three.js r184 editor)
/compose pages/compose.html src/scene-compose.js
/pose pages/pose.html src/pose-studio.js
/validation public/validation/index.html src/validation-ui.js + src/validation-page.js (+ src/validator.js)
/app pages/app-next.html (the Next shell; pages/app.html, the classic shell, serves /app-classic, /deploy, /showcase) src/app.js → src/viewer.js, src/editor/index.js, src/validator.js, plus src/app-next-overlay.js on the Next shell
/hydrate public/hydrate/index.html inline module (no src/ file)
/artifact public/artifact/index.html inline module (no src/ file)
/avatar-artifact pages/avatar-artifact.html src/avatar-artifact.js (bundled three.js; agent avatar, allowlisted GLB, or procedural portrait)

Scene Studio, /scene

  • Source: pages/scene.html, src/scene-studio/main.js, vendored editor under src/scene-studio/vendor/js/ (Editor.js, Viewport.js, Menubar.*.js, Sidebar.*.js, commands), src/scene-studio/studio.css, plus the sibling modules that layer three.ws behavior over the vendored editor without editing vendor/**: src/scene-studio/loader.js (the decoder-wired GLB add), actions.js (Import from Forge / Export presets / Share), empty-state.js (first-run overlay), toolbar-a11y.js (accessible names for the transform and animation transport buttons), src/shared/scene-handoff.js, agent-tab.js (the Agent sidebar tab) and tsl-editor.js (the Nodes sidebar tab).
  • Entry point: pages/scene.html loads the CodeMirror/Draco vendor <script> chain, then <script type="module" src="/src/scene-studio/main.js"> (scene.html:88). main.js constructs the vendored Editor (main.js:42), mounts Viewport/Toolbar/Script/Player/Sidebar/Menubar/Resizer/Animation panels into #studio-app, mounts the three.ws action bar, a11y labels and empty state over them (main.js:78-88), exposes window.editor/window.THREE, and inits IndexedDB-backed autosave/storage (editor.storage.init, main.js:109-164). The surface is dark-locked (data-theme='dark' re-pinned, main.js:11).
  • Prerequisites / gates: None. No auth, no wallet, no $THREE gate. Works fully anonymously; an empty default scene loads immediately. State persists locally via editor.storage (autosave to IndexedDB, debounced ~1s, main.js:133-163).
  • Steps (N):
    1. Arrive at /scene. Editor mounts; prior autosaved scene restored from IndexedDB, or sceneEnvironmentChanged('Default') fires for a fresh scene (main.js:111-116). A fresh scene is no longer a silent black grid: the first-run overlay (empty-state.js) names the three ways to start (drag a .glb/.gltf, pick a primitive from Add, or pull in a model you already generated) and retires itself the moment the scene holds anything, a restored autosave included. The transform toolbar is lifted above that card in studio.css, because the vendored #toolbar leaves z-index at auto and on a phone-height viewport it parks inside the band the overlay covers.
    2. (optional, deep-link) Arrive via /scene?model=<glb_url>&name=<label> (hand-off from Forge/Parts). importModelFromQuery() validates the URL is https:// or same-origin relative, fetches the GLB, parses it with the Draco/KTX2/Meshopt-wired GLTFLoader (loader.js), adds it via AddObjectCommand, selects it, and strips the query from the address bar (main.js:179-203).
    3. (optional, deep-link) Arrive via /scene?handoff=1 (hand-off from Animation Studio /pose). importHandoffAnimation() reads the baked GLB from IndexedDB via takeSceneHandoff(), adds it, and attaches a Play Animation player script so the embedded clip plays live and records to video (main.js:226-252).
    4. Import a model: drag a GLB/glTF (or a folder of glTF+textures) anywhere on the page → drop handler routes to editor.loader.loadItemList/loadFiles (main.js:261-274); or use File ▸ Import file picker (Menubar.File.js); or Import from Forge on the three.ws action bar, which takes a GLB URL in a shared <dialog> that validates the link inline rather than a native prompt() (actions.js).
    5. Add primitives/lights/cameras via the Add menu (Menubar.Add.js); add scripts via Script panel (CodeMirror). 5b. (optional) Open the Agent sidebar tab (agent-tab.js) and describe a change in plain language. Each turn posts to POST /api/scene/agent (a free, rate-limited tool-calling model); every tool call runs as a real editor.execute(Command), and every mutating prompt pushes an undoable version with a screenshot that the tab can restore.
    6. Select an object in the Viewport or the Outliner (Sidebar). The transform gizmo attaches.
    7. Transform with the gizmo, translate / rotate / scale (Toolbar mode buttons + Viewport TransformControls).
    8. Edit properties in the Sidebar: object transform, Geometry, Material (color/maps/roughness/metalness/etc.), Scene (background, environment, fog), per-light settings. The Nodes tab (tsl-editor.js) edits the selected object's material as a dropdown-wired TSL node graph.
    9. (optional) Edit a script in the Script panel; (optional) press Play (Player) to run scene scripts/animations live.
    10. (optional) Keyframe/inspect animations in the Animation panel (timeline at bottom; animationPanelChanged resizes Viewport, main.js:91-105; the play/pause/stop transport is given accessible names and pressed state by toolbar-a11y.js).
    11. (optional) File ▸ New (empty / templates) to reset; undo/redo via the command history.
    12. Export via File ▸ Export submenu: GLB, GLTF, OBJ, PLY (ASCII/binary), STL (ASCII/binary), USDZ, DRC/Draco (Menubar.File.js). A download is triggered (e.g. scene.glb, scene.gltf). The action bar's Export presets ("Web GLB", "AR bundle (USDZ)") are one click for the same two exports, and Share / Embed uploads the scene as a GLB and opens the platform's embed panel (iframe / web component / <agent-3d> snippet). The bar docks beside the sidebar and follows it as it is dragged, instead of sitting on top of the Scene/Project/Settings tabs.
    13. (optional) File ▸ Export Project saves the editor scene as a .json project; File ▸ Open re-imports a .json project (Menubar.File.js:91-185).
    14. (optional) Render menu → render an image or video of the scene via APP.Player (Menubar.Render.js).
  • Decision points / branches: Fresh scene vs restored autosave (main.js:110-119). Deep-link arrival (?model= add, ?handoff=1 animation import) vs plain manual import. #file=<url> hash → prompts to open a remote .json project, replacing the scene (main.js:287-307); the linked scene loads with its object scripts and undo history stripped (remote-scene.js, since scripts compile with new Function on Play) and a toast counts the scripts dropped, while a trusted scene keeps its scripts through File ▸ Import. Drag of a folder (DataTransferItemList) vs single files.
  • External calls / dependencies: fetch(modelUrl) for ?model= deep-link GLB (main.js:188); IndexedDB via editor.storage (autosave) and src/shared/scene-handoff.js (takeSceneHandoff, DB three-ws-scene-handoff); Draco decoder at /three/draco/gltf/ (shared with the main app), KTX2 transcoder at /scene-studio/basis/ (both wired in loader.js); local CodeMirror/esprima/acorn/tern vendor libs. Imports: glTF/GLB (+ companion textures), .json editor projects. Exports: GLB, GLTF, OBJ, PLY, STL, USDZ, DRC, JSON project, rendered image/video. The editor itself makes no platform API calls; the optional Agent tab calls POST /api/scene/agent, and Share / Embed uploads the scene GLB.
  • Success state: Imported/transformed objects appear in the Viewport + Outliner; autosave indicator (savingStarted/savingFinished) confirms persistence; export triggers a file download.
  • Empty / error states: A fresh scene shows the grid, the default environment, and the first-run card telling the visitor how to start (see step 1). Failures report through the shared toast (src/shared/toast.js), not a native alert(): ?model= fetch failure → "Could not load the handed-off model: … Download the GLB and drag the file into the editor instead." (main.js:197-201); ?handoff=1 IndexedDB unavailable → silently no-ops, load failure → "Could not load the animation from the Animation Studio: … Try Export GLB on /pose and drag the file in instead." (main.js:246-250). No-GLB-in-drop handled by the vendored loader.
  • Step count: ~7 required (arrive → import → select → transform → edit material → edit scene → export) + ~7 optional (deep-link arrival, primitives/lights, scripts, Play, animation timeline, project save/open, render).

Scene Composer, /compose

  • Source: pages/compose.html, src/scene-compose.js, src/shared/log.js.
  • Entry point: <script type="module" src="/src/scene-compose.js"> (compose.html:445). Module sets up a Three.js renderer/scene/PMREM environment, OrbitControls, a TransformControls gizmo, undo/redo stack, then on IIFE boot reads URL params (?glb= / ?avatar=) and renders the initial hierarchy (scene-compose.js:107-120, 940-964, 1343).
  • Prerequisites / gates: None to compose/forge/export. Forge ownership is auth-free via a generated forge_client_key in localStorage sent as the x-forge-client header (scene-compose.js:88-94). Saving an outfit requires an avatar loaded from /api/avatars/<id> (a real avatar id), otherwise it falls back to "Use Export GLB" (scene-compose.js:1318-1320). No wallet / $THREE gate.
  • Steps (N):
    1. Arrive at /compose. If ?glb=<url> present → load that GLB as an item (scene-compose.js:940-942). If ?avatar=<id-or-url> present → resolve via /api/avatars/<id> (or direct URL) and load as the avatar (scene-compose.js:948-960). Else show the avatar prompt / canvas hint.
    2. Choose a base avatar (optional): paste a URL and Load (btn-load-url, scene-compose.js:967-971); Browse opens a modal listing avatars from /api/explore?source=avatar&only3d=1&limit=24, with eight shimmering .gsk placeholder tiles while it loads (openAvatarModal, scene-compose.js:1171-1260); or Skip to compose without an avatar (scene-compose.js:973).
    3. Forge an item from text: type a prompt, optionally pick an intent chip (accessory/item/scene/creature/vehicle, drives suggestion pills + model_category), press Forge (startForge, scene-compose.js:1071-1103). Live progress bar with staged labels; polls /api/forge?job=<id> every 3s until done (then adds the GLB to the scene) or failed/timeout (scene-compose.js:1105-1142).
    4. (optional) Import a local GLB/glTF via drag-drop on the drop zone or the file input (loadFile, scene-compose.js:1240-1260).
    5. Select an object by clicking it (or via the hierarchy list #ol). Inspector #ins shows transform + scale-lock chain.
    6. Transform: gizmo modes translate/rotate/scale (toolbar buttons), toggle world/local space (X key), grid snap (Ctrl+G), duplicate (Ctrl+D), frame/focus selected (F).
    7. (optional) Attach an item to an avatar bone: when an avatar with bones is loaded, the inspector shows a bone <select> grouped by region (Head/Torso/Arms/Legs); choosing a bone calls attachToBone which parents the item group under the bone (scene-compose.js:783-895).
    8. (optional) Rename objects (double-click in hierarchy), toggle visibility, delete (with geometry/material/texture disposal).
    9. (optional) Use camera presets (Front/Back/Left/Right/Top/Isometric) via the camera menu.
    10. (optional) Screenshot (Ctrl+P / button) → downloads scene-compose.png (scene-compose.js:1265-1279).
    11. Export GLB → bundles all visible, non-bone-attached objects into one group and downloads scene-compose.glb (scene-compose.js:1284-1305).
    12. Save outfit → requires a loaded avatar with bone-attached items; PATCHes /api/avatars/<id> with the accessories array (bone, glbUrl, name) (scene-compose.js:1310-1335).
  • Decision points / branches: Boot branch on ?glb= vs ?avatar= vs neither (scene-compose.js:940-963). Forge synchronous done vs async job_id poll (scene-compose.js:1088-1097). Export (all objects, any state) vs Save outfit (avatar + bone-attached items only; requires a /api/avatars/<id>-sourced avatar id). Bone-attach UI only appears for non-avatar items when an avatar with bones exists.
  • External calls / dependencies: POST /api/forge + GET /api/forge?job=<id> (text-to-3D, with x-forge-client header); GET /api/forge-gallery?limit=24 plus ?scope=community&limit=24 (your forged creations and the community strip, rendered behind six .gsk skeleton tiles until they answer, scene-compose.js:1444-1472); GET /api/explore?source=avatar&only3d=1&limit=24 (avatar browse modal); GET /api/avatars/<id> (resolve avatar by id); PATCH /api/avatars/<id> (save outfit accessories). Imports: GLB/glTF (URL or local file). Exports: GLB (GLTFExporter, binary), PNG screenshot.
  • Success state: Forged/loaded items appear in scene + hierarchy with toasts ("Added: …", "Loaded: …", "Attached to "); export/save flash "Exported ✓" / "Outfit saved ✓" (flashSave, scene-compose.js:1337-1341).
  • Empty / error states: Empty hierarchy → "No objects" with the hint "load an avatar or forge an item." (scene-compose.js:734). Forge errors → red banner via showForgeError (auto-hides 6s); timeout → "Generation timed out. Try again." Avatar browse empty → "No public avatars are available yet." with a "Create one →" link to /create; browse fetch failure → "Could not load avatars: …" with a Retry button Export with nothing → toast "Nothing to export". Save outfit with no avatar → "Load an avatar first"; no attached items → "Attach at least one item to a bone first"; non-API avatar → "Use Export GLB to save this scene".
  • Step count: ~5 required (arrive → forge or import → select → transform → export) + ~7 optional (load/browse/skip avatar, intent chips, bone attach, rename/visibility, camera presets, screenshot, save outfit).

Animation Studio, /pose

  • Source: pages/pose.html, src/pose-studio.js (entry), src/pose-rig.js, src/pose-animation.js, src/pose-presets.js, src/pose-library.js, src/pose-share.js, src/animation-library.js, src/shared/scene-handoff.js. (Note: src/pose-mannequin.js and src/avatar-pose.js exist but are not on the /pose load path, the studio's mannequin comes from MannequinRig in pose-rig.js.)
  • Entry point: <script type="module" src="/src/pose-studio.js"> (pose.html:2082). boot() runs on DOMContentLoaded (pose-studio.js:361, 1634): builds the Three.js scene/renderer (preserveDrawingBuffer for screenshots), OrbitControls, a rotate TransformControls gizmo, lights/grid/prop layer, then immediately mounts the built-in MannequinRig (pose-studio.js:406-408) and starts tick() (423-436).
  • Prerequisites / gates: None to pose/keyframe/preview/export/screenshot/scene-handoff, the mannequin is mounted at boot, usable anonymously. Save to account and sell are auth-gated: PoseLibrary.openSaveDialog checks getUser() (GET /api/auth/me); if signed out it stashes the doc in sessionStorage and routes to /login?next=/pose, restoring on return (pose-library.js:85-129). The curated preset Animation Library and the AI text-to-motion generator require a rigged GLB avatar (mannequin shows a "Load a rigged avatar" empty state). No wallet / $THREE gate.
  • Steps (N):
    1. Arrive at /pose. Mannequin mounts with a starting pose (shared pose from #p=/?p= if present, else contrapposto, pose-studio.js:413-419). ?avatar=<id> loads that avatar (falls back to mannequin on failure); ?anim=<id> opens a saved clip into the editor (pose-studio.js:1608-1631).
    2. (optional) Choose the figure: Load avatar opens AvatarGalleryPicker → loadAvatarFromUrl() (GLTF load with % progress, builds rig via makeGltfRig, frames, writes ?avatar=, pose-studio.js:775-862); or Mannequin to return to the primitive rig (switchToMannequin, 821).
    3. (optional) Tune model/scene: mannequin body type/skin tone/constraints (GLB-disabled); background color, FOV, floor grid, key-light azimuth/elevation/intensity, floor props (chair/stool/cube/ball/plinth) (pose-studio.js:937-1019).
    4. Select a bone: click the figure (pickBoneAt, 471-518), click the searchable bone list (699-732), or grab an IK handle (auto-selects).
    5. Pose with FK (default mode): rotate gizmo on the selected bone + X/Y/Z rotation sliders + "Reset this bone" (renderControlsPanel, 640-696).
    6. (optional) Pose with IK: toggle IK (top bar or I key; disabled if the rig exposes no limb chains) and drag a glowing cyan hand/foot handle → rig.solveIK (pose-studio.js:585-630). FK and IK are mutually exclusive.
    7. (optional) Apply a preset pose from the grouped grid (Standing/Action/Sitting/Expressive, poseFromMannequinPreset, pose-studio.js:734-758).
    8. (optional, rigged GLB only) Apply a curated motion clip or AI-generate one: AnimationLibrary cards from /animations/manifest.json retarget+play live; a clip the curated manifest does not carry (an mx-* name deep-linked from the /animations gallery) is resolved one at a time through GET /api/animations/library?name=<name> rather than by downloading the whole multi-megabyte catalog (_lookupFullLibrary, animation-library.js:164-173); the text box POSTs /api/forge-motion and polls for the clip, which the finished poll returns already converted from HumanML3D's rest shape to the library's canonical basis (so it plays upright, head up and arms hanging), with the raw worker URL only as a fallback. That endpoint has exactly one backend, the self-hosted text2motion GPU worker behind GCP_TEXT2MOTION_URL (no vendor fallback, so an unset URL is an honest 503), and it meters against the free-lane rate bucket rather than the paid one.
    9. Keyframe the timeline: pose, then Add keyframe / K (captureKeyframe, 1262-1273); drag diamonds to retime, set per-key easing, set name/duration/FPS/loop (pose-studio.js:1275-1394).
    10. Scrub / play: drag the track or arrow keys; transport play/pause (Space), stop, jump start/end (Home/End), loop toggle. Playback slerp-interpolates poses via sampleAtTime (pose-animation.js:136). For a library or AI clip, the transport also carries trim start/end inputs, a loop-blend duration and a loop toggle; _computeEditedClip() (trimClip + blendClipLoop from animation-retarget.js) applies them non-destructively so preview, GLB export and library save always agree on the edit, and Save to library (animation-library.js) POSTs the canonical pre-retarget clip to /api/animations/clips so it plays on any future rig.
    11. (optional) Import a pose JSON (#pose-import-json) → applies a single static pose (pose-studio.js:917-934).
    12. Completion paths: Export JSON clip (serializeClip); Export GLB with embedded clip (bakeAnimatedGlb); Record in Scene → (bakes GLB, stashes in IndexedDB, navigates /scene?handoff=1); Save to account (Ctrl/Cmd+S → PoseLibrary dialog, POST/PATCH /api/animations/clips); Export pose JSON (single pose) / PNG screenshot; Sell a saved clip for USDC from the "My animations" drawer (pose-studio.js:1408-1491; pose-library.js). Export buttons disabled until ≥1 keyframe (refreshExportEnabled, 1206-1211).
  • Decision points / branches: Mannequin vs loaded GLB (changes bone-pick strategy, model-tuning availability, IK availability, preset/AI-library availability, and whether the saved clip links an avatar_id). Save vs Update vs Save-as-copy (PATCH existing clip vs POST new, pose-library.js:218-262). Four independent completion paths: Save (auth-gated) / Export / Sell (USDC) / Scene handoff. Boot branch on ?avatar= and chained ?anim=.
  • External calls / dependencies: GET /api/avatars/:id; GET /api/auth/me; clip CRUD POST/PATCH/DELETE/GET /api/animations/clips[/:id] (mine + include_public=true&visibility=public; a priced clip you do not own answers paywalled with no tracks rather than a 404, and a private one still 404s); POST /api/animations/thumbnail (admits a full-size poster PNG; an oversized one is a typed 413 too_large); sell flow POST /api/animations/presign → R2 PUT upload_url → POST /api/animations/sell (USDC on Base or Solana; payout addresses default to the seller's approved, already-effective payout wallets, and an API key may set an explicit payout address only with wallet:write); AI/preset clips GET /animations/manifest.json, POST /api/forge-motion + poll. Imports: pose JSON. Exports: pose JSON, clip JSON, animated GLB (GLTFExporter binary), PNG. Scene handoff: putSceneHandoff({glb,name}) to IndexedDB, then navigate /scene?handoff=1 (shared/scene-handoff.js). URL pose codec #p=/?p= (pose-share.js).
  • Success state: HUD #pose-status confirmations ("Loaded …", "Keyframe added at Xs · N total", "Screenshot saved"); export buttons show busy → "Saved ✓"/"Opening ↗"; save → "Saved '…' to your account"; sell → "Listed '…' for N USDC".
  • Empty / error states: Timeline #tl-empty "Pose the figure, then press K…" until a keyframe exists, with the ruler's tick labels faded out while it shows (#tl-track[data-empty='true']), since an empty timeline has nothing to measure and the ticks only competed with the hint; mode-aware no-selection hint; bone search "No bones match"; library drawer "No animations yet" / "Sign in to see your animations"; AnimationLibrary "Load a rigged avatar"/"can't be retargeted"; boot idle "Ready. Click a body part to pose, or load an avatar." Errors (red HUD): avatar load failure, "no recognizable humanoid skeleton", import parse failure, "Add a keyframe first, then play", export "… failed"; library/API errors show inline .pl-dialog-err + Retry; ?avatar= boot failure falls back to mannequin with explanation.
  • Step count: ~6 required (arrive → select bone → FK pose → add keyframe → scrub/play → export) + ~7 optional (load/switch avatar, scene/model tuning, IK, preset pose, motion library/AI, import pose JSON, save/sell/scene-handoff/screenshot).

glTF Validator, /validation

  • Source: public/validation/index.html, src/validation-page.js, src/validation-ui.js, src/validator.js, src/gltf-inspect.js, src/components/validator-report.jsx, src/components/inspect-report.jsx, src/erc8004/validation-recorder.js, src/erc8004/agent-registry.js.
  • Entry point: public/validation/index.html (module at line 1206) imports ValidationDashboard (validation-ui.js) and ValidationPage (validation-page.js); constructs the dashboard then the page (which references the dashboard for the on-chain hand-off). On construct, ValidationPage renders the Khronos sample chips, binds input events, and restores the active tab from the URL hash (validation-page.js:33-52). The three tabs are a roving-tabindex tablist: Arrow keys, Home and End move between them (switchTab, validation-page.js:53-70).
  • Prerequisites / gates: None to validate/inspect, runs fully client-side in the browser. The Records / "Pin & sign on-chain" path requires an Ethereum wallet (ensureWallet via ethers / window.ethereum, validation-ui.js:12) to sign + submit an on-chain attestation; that is the only gated sub-flow. No $THREE gate.
  • Steps (N):
    1. Arrive at /validation. Three tabs: Validate, Inspect, Records (default validate, restored from #validate|#inspect|#records).
    2. Provide a model: three input sources sharing one pipeline: drag-drop a GLB on the drop zone, pick a file via the file input, paste a URL and click the URL button (Enter also works), or click a Khronos sample chip (Box/Duck/BoomBox/DamagedHelmet/Avocado from jsdelivr) (loadFile / loadUrl, validation-page.js:145-176; each remembers lastSource so a failure card's Retry can rerun it).
    3. _run(bytes, name) fires both analyses in parallel (validation-page.js:177-243): the official Khronos validator (Validator.validateBuffer → gltf-validator validateBytes, validator.js:57-66) and the glTF-Transform inspector (inspectModel + suggestOptimizations).
    4. Validate tab renders the report (ValidatorReport): error/warning/info/hint counts bucketed by severity, aggregated repeated codes, generator/asset metadata (validator.js:106-189).
    5. Inspect tab renders glTF-Transform stats + optimization suggestions (InspectReport).
    6. (optional) Download either report as JSON (buildDownloadHref data URI on each report panel).
    7. (optional) View the validation report in a standalone lightbox tab (Validator.showLightbox, validator.js:198-212).
    8. (optional, wallet) Pin & sign on-chain: _handOffToDashboard switches to the Records tab, opens the submit modal pre-filled with the in-memory report + its hashReport hash (no file re-pick), then ValidationDashboard.submitReport connects the wallet, pins to IPFS, and records the attestation (validation-page.js:283-300; validation-ui.js). The submit modal traps focus, closes on Escape or a scrim click, and returns focus to the control that opened it.
    9. Records tab (independent): enter agent id + chain id (or arrive via ?agent=&chain=), Load past validation records (getLatestValidation; Enter in either input also loads, and IPFS report URIs resolve through the shared gateway list in src/ipfs.js), or Submit a new report by dropping/picking a report JSON file (validation-ui.js; the empty Records state carries its own "Submit a Validation" button).
  • Decision points / branches: Input source (file / URL / sample), all converge on _run. Validate vs Inspect (run together, two tabs). In-memory hand-off to Records vs manual report-file submission. Records load (?agent=&chain= auto-loads) vs manual entry. On-chain submit requires wallet; validation/inspection do not.
  • External calls / dependencies: fetch(url) for URL/sample inputs (validation-page.js:136); gltf-validator validateBytes (in-browser); src/gltf-inspect.js (glTF-Transform, in-browser). On-chain: IPFS pin (pinFile), recordValidation (validationRequest + validationResponse) / getLatestValidation (validation-recorder.js), ensureWallet/ethers + window.ethereum. Inputs: GLB (and glTF + external resources resolved from the dropped asset map). The Validate tab can read the GLTFLoader-cached ArrayBuffer when invoked from the viewer (validator.js:26-34). Outputs: JSON report download, on-chain attestation.
  • Success state: Status line " · · no issues found" (or "· N issues found", summed across errors, warnings, infos and hints; validation-page.js:226-241); rendered validate + inspect reports; Pin & sign button enabled once a report exists.
  • Empty / error states: Initial: three empty tab panels with sample chips inviting input. While running: "Validating…" / "Inspecting…" loading rows. Every failure renders a designed .result-error card (title, raw detail, what to try next, and a Retry that reruns the last input via retryLast; errorCard, validation-page.js:245-282): an unreadable file → " could not be read" in both panels (_failBoth); a fetch error → "Could not fetch " with CORS hints (the host must send Access-Control-Allow-Origin; download and drop the file instead); a validator failure → " is not valid glTF"; an inspector failure → "Could not inspect ". The status line flips to its failed style and Pin & sign is disabled again. On-chain hand-off with no report → toast "Run a validation first" (validation-page.js:222-224).
  • Step count: ~4 required (arrive → provide model → read Validate report → read Inspect report) + ~5 optional (download JSON, lightbox, pin & sign on-chain, browse records, submit report file).

3D Viewer / Editor (main app), /app

  • Source: pages/app-next.html (the Next shell served at /app), pages/app.html (the classic shell at /app-classic, /deploy, /showcase), src/app.js, src/app-next-overlay.js, src/viewer.js, src/editor/index.js, src/validator.js, src/account.js, src/wallet.js, src/erc8004/*, widget mounts under src/widgets/*, src/components/screenshot-modal.js, src/next-layout.js.
  • Entry point: <script defer type="module" src="/src/app.js"> (app-next.html:59, followed by /src/app-next-overlay.js, which re-skins the same app with the Next chrome; app.html:57 loads the identical module for the classic shell). _bootApp() constructs new App(document.body, location) and exposes window.VIEWER.app (app.js:2713-2717). The App constructor (app.js:183-424) parses hash + query into this.options, conditionally builds dropzone/avatar-creator/layout/nav, dispatches on route mode, then inits the agent system + widget bridge.
  • Prerequisites / gates: No hard gate blocks the viewer: the default CZ avatar (or ?model=/?agent= target) loads for everyone, anonymous included. The "gate" is presentation-only: in main mode _applyViewerMode sets data-authed (pending/false, app.js:647-662); on the classic shell that CSS (public/style.css) overlays the .auth-gate card ("Your agent lives here") and hides the agent sidebar + dat.GUI editor for anonymous/pending users, while the Next shell's overlay header shows a "Sign in to save" primary CTA that routes to /login?next=/app (src/app-next-overlay.js); getMe() (GET /api/auth/me) reconciles to the real state. A wallet button exists (initWalletButton, eager eagerConnectWallet) but connecting is never required. No $THREE token gate. "Save to account" and "Save edits" redirect to /login when signed out. The dat.GUI editor only exists once a model has loaded (built by the viewer on content load).
  • Steps (N):
    1. Arrive at /app. Constructor dispatches by mode; _maybeResumeOrLoad(options) runs for the default path (app.js:401, 431-491).
    2. A model auto-loads: ?resume=<token> restores a stashed editor session (optional), else options.model || '/avatars/cz.glb'; the default CZ avatar crossfades into a "taunt" landing clip (app.js:474-491).
    3. Viewer renders via view() → WebGL check, createViewer(), viewer.load(url, …) with a progress callback, then attach avatar, notify editor, configure animations, set AR target, run validator. Framing reads the rig's facing off its canonicalized shoulder, arm or leg bones (src/viewer/facing.js) so the camera seats in front of the face whether the rig was authored facing +Z or -Z; a model with no readable rig keeps the legacy +Z seat.
    4. (optional) Load your own model: drag-drop a .glb/.gltf or folder anywhere on .wrap (SimpleDropzone → load(files), app.js:1783-1864); or the #file-input picker; or ?model=<url>/#model= (host-validated by isSafeQueryModelUrl from src/shared/safe-model-url.js for the deploy path, app.js:326-330); or ?agent=<uuid>.
    5. (optional) Open the editor controls (dat.GUI / Next-layout drawer): Display (background, autoRotate, wireframe, skeleton, grid, point size, transparent bg, screenshot, model info, mesh labels), Lighting (IBL/envMap, exposure, tone mapping, punctual lights), Light Probes, Animation, Morph Targets, Cameras, Agent follow mode, Performance stats (viewer.js addGUI).
    6. (optional) Play animations: _configureAnimations fetches /animations/manifest.json, registers clips, honors ?anim=<name|uuid>; Next-layout dock gives clip picker + play/pause + scrubber + loop. When an agent is loaded, its per-slot gesture overrides (meta.edits.animations, written by PUT /api/agents/:id/animations with animationSlots) are applied via setAnimationMap; the /gestures page documents the slot vocabulary.
    7. (optional) Edit environment / lights / camera / display via the GUI (updateEnvironment, updateLights, setCamera, frameContent, etc. in viewer.js).
    8. (optional) Edit materials / textures / scene via the Editor (MaterialEditor, TextureInspector, SceneExplorer, MagicBrush; rebuilt on each new model, editor/index.js:19-55). 8b. (optional) A prop opened from /objects on the Next shell gets object actions in the header bar (Backdrop, Upload, Restyle, AR, Download), plus a Poly Haven credit link, since the catalog is CC0 Poly Haven content (wireObjectActions, src/app-next-overlay.js).
    9. (optional) Take a screenshot → viewer.captureScreenshot() → ScreenshotModal.show(blob) (app.js:869-881).
    10. (optional) Export GLB → editor export folder → exportEditedGLB(session) → downloadGLB(...); also a postMessage exportGLB bridge returns base64 GLB to a parent frame (editor/index.js:57-129; app.js:1535-1602).
    11. (optional) Save edits / save model to account: editor _saveEdits (R2 presign+upload+PATCH) or header "Save to account" (_triggerSaveToAccount → if signed out, stash + /login?next=/app?pending=1; if signed in, _performSave saves the GLB, creates/links an agent, redirects to /agents/<id>, app.js:883-1023).
    12. (automatic) Validate: validator.validate(...) runs on every non-kiosk load; surfaces a .validator-toggle badge + lightbox (app.js:1965; validator.js).
    13. (optional) Cross-links: "Make this a widget" → /studio?model=<url>; "Open in Composer" → /compose?glb=<url>; "Deploy on Solana" → guided on-chain deploy agent /app?agent=67bf6e67-… (app.js:803-855).
    14. (optional) Chat with the agent: _initNichAgent mounts the NichAgent chat/voice UI + thought bubble (skipped in widget/kiosk/deploy/showcase, app.js:1708-1723).
  • Decision points / branches: Route mode dispatch (app.js:311-402): kiosk/embedChat (chromeless), /deploy (RegisterUI wizard), /showcase (the ERC-8004 directory: every indexed on-chain agent that carries a 3D glTF body, rendered by src/erc8004/showcase.js; like /deploy it demotes the shell's wordmark h1 so the page has one real heading, and upgrades the legacy flex footer to the horizon footer, which is what used to drag the document sideways at 320px), on-chain /a/<chain>/<id> (anonymous-safe), legacy #agent= embed, chat embed /a/<uuid>?embed=1, #widget=<id> (slim shell vs full SPA, type-specific mounts), ?agent=<uuid> authenticated agent-edit, else default _maybeResumeOrLoad; ?pending=1 replays a stashed post-login save. Anonymous vs signed-in (auth-gate overlay + save gating only). Classic vs Next layout (localStorage toggle). File-drop vs URL vs agent vs on-chain model source.
  • External calls / dependencies: GET /api/auth/me, POST /api/auth/logout, GET /api/avatars/<id>, GET /api/agents/<id>, GET /api/agents/me, POST /api/agents, PUT /api/agents/<id>, POST /api/avatars/thumbnail, POST /api/widgets/<id>/view, GET /animations/manifest.json + HEAD /animations/*.glb; saveRemoteGlbToAccount (R2 presign/upload/commit); editor save (R2); on-chain dynamic imports (erc8004/queries|abi|register-ui|showcase) + Solana/ETH RPC; IPFS/Arweave URL resolution (ipfs.js). Imports: glTF/GLB (+ textures). Exports: binary GLB; PNG screenshot; AR uses USDZ (iOS) + GLB (Android). Validator: in-browser gltf-validator.
  • Success state: LOAD_END(success) fades the poster, hides the status overlay, fires three-ws:first-frame, runs first-time onboarding (agent-edit), backfills a missing thumbnail (_captureAndUploadThumbnail, app.js:2163-2168 and 2369+: the GLB is re-rendered offscreen by glbFileToThumbnail, with a humanoid stood in a natural rest pose rather than its T-pose bind pose, never read back from the live canvas, then posted to /api/avatars/thumbnail). Model renders, orbitable; editor + agent sidebar available for signed-in users.
  • Empty / error states: No true empty void: the CZ default always loads. Anonymous main mode shows the .auth-gate card ("Your agent lives here", classic shell) or the "Sign in to save" CTA (Next shell) with sidebar/GUI hidden; the dropzone invites upload/generate. Loading: spinner/determinate progress bar (_showViewerLoading/_updateLoadProgress) + poster thumbnail for agent-edit. Errors: _classifyLoadError → human message + Retry (_showViewerError, app.js:2122-2295); a drop or pick with no model file shows the error card "No .gltf or .glb file in that drop. Pick a model file to view it." with a "Choose a file" action that reopens the picker (app.js:1854-1858); _showWebglUnavailable reload card; _showWidgetError; on-chain _showOnChainError/_updateOnChainCard.
  • Step count: ~3 required (arrive → model auto-loads → view/orbit) + ~11 optional (load own model, GUI controls, animations, env/lights/camera, material/texture editing, screenshot, export GLB, save to account, validate review, cross-links, agent chat).

Hydrate (import on-chain agents), /hydrate

  • Source: public/hydrate/index.html (self-contained inline module, no src/ entry). NOTE: this is an on-chain agent import flow, not a 3D viewer/editor; it sits in this cluster only by route adjacency. Its product purpose is "attach a 3D body, voice, and skills to an existing on-chain agent."
  • Entry point: Inline <script type="module"> at hydrate/index.html:334. On load, loadAgents() runs: checkAuth() (GET /api/auth/wallets) then fetchDiscoveredAgents() (GET /api/erc8004/hydrate).
  • Prerequisites / gates: Wallet gate. checkAuth() requires an authenticated session with ≥1 connected wallet; otherwise the auth prompt ("connect a wallet first" → /dashboard/account#wallets) is shown and no agents load (hydrate/index.html:378-417). No $THREE gate.
  • Steps (N):
    1. Arrive at /hydrate. loadAgents() runs.
    2. Auth/wallet check, GET /api/auth/wallets. If unauthenticated or no wallets → show auth prompt and stop.
    3. Loading state, "Fetching your agents…" while GET /api/erc8004/hydrate resolves the wallets' on-chain agents (hydrate/index.html:419-422).
    4. Discovered agents render as cards (image, name, chain badge, description, agent id) (hydrate/index.html:439-465).
    5. For each agent: if already imported → "Go to agent →" link to /dashboard/?agent=<id>; else an Import button.
    6. Click Import → importAgent() → POST /api/erc8004/import ({chainId, agentId}); on success the button is replaced with a "Go to agent →" link and a success alert shows (hydrate/index.html:475-491).
  • Decision points / branches: Authenticated+wallet vs not (auth prompt). API not running / non-JSON response → treated as unauthenticated (graceful, hydrate/index.html:389-393). Per-agent: already-imported (link) vs importable (button). Zero discovered agents → empty state.
  • External calls / dependencies: GET /api/auth/wallets (auth + wallet list), GET /api/erc8004/hydrate (discover on-chain agents), POST /api/erc8004/import (import one). No 3D asset loading on this page. Links to /deploy, /dashboard/.
  • Success state: Imported agent's button becomes "Go to agent →" + success alert "Successfully imported !" (hydrate/index.html:487-491).
  • Empty / error states: Not authed / no wallets → auth prompt block. Zero agents → empty state "No on-chain agents found for your wallets." + register-at-/deploy hint. Discovery failure → red alert "Failed to load agents: …". Import failure → error alert from the API's error_description.
  • Step count: ~4 required (arrive → auth/wallet check → discover → import) + 0 optional (the "Go to agent" link is a navigation exit, not a step).

Artifact Viewer (Claude artifact bundle preview), /artifact

  • Source: public/artifact/index.html (self-contained inline module, no src/ entry), backend api/artifact. NOTE: product purpose is "Embed your agent in Claude.ai", it previews the standalone HTML artifact bundle that /api/artifact generates, not a glTF model.
  • Entry point: Inline <script type="module"> at artifact/index.html:798. On load, init() reads ?agentId=, ?theme=, ?idle= and ?bg= back into the form, auto-runs generate() when an id is present, and loadAgents() fills a picker of real public agents from GET /api/agents/public?sort=popular&limit=12&avatar=1 (avatar=1 is load-bearing: an agent without a publicly readable GLB cannot become an artifact) (artifact/index.html:1139, 1228-1240).
  • Prerequisites / gates: None on the page. Validity depends on a real agent id resolving server-side at /api/artifact. No auth/wallet/$THREE gate on the page itself (fetch(..., { credentials: 'omit' })).
  • Steps (N):
    1. Arrive at /artifact (optionally with ?agentId=).
    2. Enter an Agent ID (a UUID; /api/artifact rejects anything else with 400 invalid_request, and the page adds the hint "Agent IDs are UUIDs. Copy one from an agent profile page, or pick an agent on the left.") or click one of the public agents in the picker; optionally set theme (light), idle behavior, and a 6-hex background color (artifact/index.html:649-700).
    3. Click Generate (or Enter) → buildUrl() assembles /api/artifact?agent=…&theme=…&idle=…&bg=…, mirrors the whole configuration into this page's own query string (syncQueryString, so a shared builder URL rebuilds the same artifact), marks the picked agent, and fetches the artifact HTML with credentials: 'omit' (artifact/index.html:908-1010).
    4. On success: compute size (graded against the ceiling a 6 MiB model produces once base64-inlined on top of the ~565 KB viewer, about 8.6 MB; amber past 70%, red past 100%), fetch time, render time (the iframe's first paint, timed out at 30s), and CSP-sandbox compliance (checks frame-ancestors * in the response CSP), show the stats panel (color-coded ok/warn/bad), and render the artifact via iframe.srcdoc (artifact/index.html:1030-1075).
    5. (optional) Reload re-fetches; Copy URL; Copy raw HTML (with byte size); Open in a new tab.
    6. (optional) The page shows the documented Claude.ai sandbox CSP from our own origin, GET /claude-artifact-csp.txt (the vendored bytes tests/api/artifact.test.js pins the endpoint against; node scripts/refresh-claude-csp.mjs refreshes it), with a fallback line pointing at specs/CLAUDE_ARTIFACT.md if that fetch fails (artifact/index.html:1213-1226).
    7. Copy the generated Claude snippet ("Here's my agent for this conversation:\n") to paste into Claude.ai (artifact/index.html:1062).
  • Decision points / branches: ?agentId= present → auto-generate vs manual entry vs picking from the public-agent list. Fetch network error vs non-OK HTTP vs success. Size/fetch/render/sandbox stats branch into ok/warn/bad styling. CSP reference fetch success vs fallback copy.
  • External calls / dependencies: GET /api/artifact?agent=… (the artifact bundle, credentials: 'omit'); GET /api/agents/public?sort=popular&limit=12&avatar=1 (the picker); GET /claude-artifact-csp.txt (reference only, same origin). Output: the artifact HTML rendered in an iframe; copy-to-clipboard URL/HTML/snippet. No 3D file import/export.
  • Success state: Stats panel populated (size/TTFP/sandbox), artifact rendered in #previewFrame, action buttons enabled, snippet shown.
  • Empty / error states: Initial: "Enter an agent ID and press Generate" overlay; snippet placeholder "Generate to see the snippet…". No id → "Enter an agent ID first." error overlay. Network error → "Network error: ". Non-OK → server error_description/error/HTTP <status> shown in the overlay, followed by an actionable hint keyed on the error code (not_found, no_avatar → generate one at /create, too_large → re-export under 6 MB, invalid_request, rate_limited → 600 requests a minute per IP, upstream_error). Picker fetch failure leaves the list with its own message. CSP fetch failure → documented fallback text.
  • Step count: ~3 required (arrive → enter or pick an agent id → Generate) + ~4 optional (theme/idle/bg options, reload, copy URL/HTML/snippet, open in tab).

Avatar Artifact (standalone avatar viewer): /avatar-artifact

  • Source: pages/avatar-artifact.html (markup, the designed loading/error overlays with their data-msg-* copy, the embed/share snippet, and the inline failure + watchdog script) → src/avatar-artifact.js (scene, artifact resolution, GLB loading, retargeted idle). three.js ships with the bundle; there is no third-party CDN script, because the page is meant to be pasted into other sites as a bare iframe. NOTE: this is the "standalone Three.js viewer for avatar artifacts, embeddable and shareable without any wrapper page" (page OG meta). Three modes share one composed stage (lighting, ground, fog, drifting motes): ?agent=<uuid> renders that agent's avatar, ?model=<url> renders any GLB on an allowlisted host, and no params renders the house portrait, a procedural figure (cylinders/spheres/boxes) that tracks the visitor.
  • Entry point: <script type="module" src="/src/avatar-artifact.js"> (avatar-artifact.html:511), preceded by the inline script that defines window.__avatarArtifactFailed and arms a 12s watchdog (avatar-artifact.html:415-457). The module resolves the artifact from the query string (resolveArtifact), imports three (plus GLTFLoader and the meshopt decoder only on the model lane), and calls boot(artifact).
  • Prerequisites / gates: None. No auth, wallet, or $THREE gate. The agent lane reads the public GET /api/agents/:id; a ?model= URL must be https:// on three.ws, *.r2.dev, *.r2.cloudflarestorage.com, *.amazonaws.com, *.cloudfront.net, storage.googleapis.com, *.blob.core.windows.net, or *.vercel.app (the same allowlist /api/artifact enforces, ALLOWED_MODEL_HOSTS, avatar-artifact.js:28-40). Renders on a successful runtime + WebGL context.
  • Steps (N):
    1. Arrive at /avatar-artifact (optionally with ?agent= or ?model=). Loading overlay shows while the bundled runtime loads; the artifact lane holds it until the GLB has actually arrived, with a lane-specific loading note.
    2. Resolve the artifact: both params → msgBoth failure; a non-UUID or unknown ?agent= → msgNotFound with an action link to /agents; an agent whose lookup failed → msgAgentFetch; an agent with no avatar → msgNoAvatar, or msgAvatarPrivate when it has one it will not show, each linking the agent's profile; a ?model= off the allowlist → msgModelBlocked (avatar-artifact.js:60-165).
    3. Runtime + WebGL guard: if the runtime import fails, WebGL context creation throws, or the module never runs at all (the watchdog fires after 12s of silence; a heartbeat re-arms it while a large model is still downloading), the designed error state is shown (window.__avatarArtifactFailed, with a Retry that reloads). A GLB that fails to parse → msgModelFailed.
    4. On success the avatar (or the house portrait) renders and the loading overlay fades on the first painted frame, which also clears the watchdog and any error that raced it (avatar-artifact.js:378-392). A loaded humanoid rig plays the shared retargeted idle clip from /animations/manifest.json through AnimationManager (breatheLife); a rig the canonicalizer cannot drive simply stands still.
    5. Interact: the figure's gaze follows the mouse (mousemove), touch drag (touchmove), or keyboard (arrow keys / WASD nudge the gaze by KEY_STEP 0.25; the canvas is focusable, role="img", ARIA-labeled). A turntable orbits the look target unless prefers-reduced-motion is set.
    6. (optional) Copy embed: the page carries its own <iframe> snippet pointing at this URL; once a specific artifact resolves, the module hands its query back (__avatarArtifactSetEmbed) so the copied iframe shows the avatar on screen rather than the house portrait. Clipboard denied (cross-origin frame, insecure context) → the snippet field is revealed and selected for manual copying (avatar-artifact.html:459-507).
    7. The canvas keeps animating (idle motion, blink, drifting motes) and stays responsive to resize/orientation change.
  • Decision points / branches: Agent lane vs model lane vs house portrait. Runtime available + WebGL OK (render) vs runtime/WebGL/watchdog failure (error state). Coarse pointer (phones/tablets) → lighter render (no antialias, lower DPR, no shadow pass). Pointer/touch input vs keyboard gaze control. Clipboard write vs manual snippet.
  • External calls / dependencies: GET /api/agents/:id (agent lane), the avatar GLB itself (model lane; meshopt decoded), GET /animations/manifest.json + the retargeted idle clip; /api/page-og for OG/Twitter share images (meta only). No platform API on the house-portrait lane, no glTF validator, no export.
  • Success state: Animated avatar (or procedural portrait) that tracks cursor/touch/keys; loading overlay faded out; embed snippet copied.
  • Empty / error states: Loading overlay (#loading) during runtime and model load; designed error overlay (#error) with per-failure copy (data-msg-both, -not-found, -agent-fetch, -no-avatar, -avatar-private, -model-blocked, -model-failed, -no-webgl), one contextual action link, and a Retry. No empty "no model" state: without params the house portrait is always present once the runtime loads.
  • Step count: ~3 required (arrive → resolve + runtime/WebGL OK → avatar renders) + ~2 optional (interact via cursor/touch/keyboard, copy the embed snippet).