Skip to content

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

feat: avatar-studio save/utils refactor + IBM design-system polish

nirholas268608c4f414
diff --git a/pages/avatar-studio.html b/pages/avatar-studio.html
index 05084c1f0..7804b5337 100644
--- a/pages/avatar-studio.html
+++ b/pages/avatar-studio.html
@@ -781,6 +781,101 @@
justify-content: flex-end;
}
+ /* ── Icon-only buttons ────────────────────────────────── */
+ .as-icon-btn {
+ padding: 7px 9px;
+ }
+
+ /* ── Draft restore bar ─────────────────────────────────── */
+ #as-draft-bar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 9px 20px;
+ background: rgba(234, 179, 8, 0.08);
+ border-bottom: 1px solid rgba(234, 179, 8, 0.25);
+ font-size: 12px;
+ color: #eab308;
+ flex-wrap: wrap;
+ }
+ #as-draft-bar span { flex: 1; min-width: 0; }
+ .as-draft-btn {
+ background: transparent;
+ border: 1px solid rgba(234, 179, 8, 0.4);
+ color: #eab308;
+ padding: 4px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ font-size: 12px;
+ font-family: inherit;
+ font-weight: 600;
+ transition: background 0.15s;
+ }
+ .as-draft-btn:hover { background: rgba(234, 179, 8, 0.12); }
+ .as-draft-dismiss { border-color: transparent; color: var(--text-3); }
+ .as-draft-dismiss:hover { background: rgba(255,255,255,0.05); color: var(--text-2); border-color: var(--border-2); }
+
+ /* ── Empty-state action button ─────────────────────────── */
+ .as-empty-action {
+ display: inline-block;
+ margin-top: 10px;
+ background: transparent;
+ border: 1px solid var(--border-2);
+ color: var(--text-2);
+ padding: 6px 14px;
+ border-radius: 8px;
+ cursor: pointer;
+ font: 500 12px/1 inherit;
+ transition: border-color 0.15s, color 0.15s;
+ }
+ .as-empty-action:hover { border-color: var(--text-3); color: var(--text); }
+
+ /* ── Save-success toast ────────────────────────────────── */
+ .as-toast {
+ position: fixed;
+ bottom: 24px;
+ left: 50%;
+ transform: translateX(-50%) translateY(24px);
+ opacity: 0;
+ transition: opacity 0.25s, transform 0.25s;
+ background: #1a2e1a;
+ border: 1px solid rgba(34, 197, 94, 0.35);
+ color: #86efac;
+ padding: 10px 18px;
+ border-radius: 10px;
+ font-size: 13px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ z-index: 400;
+ box-shadow: 0 8px 32px rgba(0,0,0,0.5);
+ pointer-events: none;
+ white-space: nowrap;
+ }
+ .as-toast.visible {
+ opacity: 1;
+ transform: translateX(-50%) translateY(0);
+ pointer-events: auto;
+ }
+ .as-toast-icon { flex-shrink: 0; color: #4ade80; }
+ .as-toast-link {
+ color: #4ade80;
+ text-decoration: none;
+ font-weight: 600;
+ margin-left: 4px;
+ }
+ .as-toast-link:hover { text-decoration: underline; }
+
+ /* ── Mobile: icon tabs ─────────────────────────────────── */
+ @media (max-width: 480px) {
+ .as-tab-label { display: none; }
+ .as-tab::before {
+ font-size: 16px;
+ line-height: 1;
+ }
+ .as-btn-label { display: none; }
+ }
+
/* ── Save overlay ─────────────────────────────────────── */
.as-save-overlay {
position: fixed;
@@ -835,6 +930,16 @@
</a>
<div class="as-bar-title">Avatar Studio</div>
<div class="as-actions">
+ <button class="as-btn as-icon-btn" id="as-undo" type="button" title="Undo (Ctrl+Z)" aria-label="Undo" disabled>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 7v6h6"/><path d="M3 13C5.5 7.5 12 5 17 8s6 9 3 13"/></svg>
+ </button>
+ <button class="as-btn as-icon-btn" id="as-redo" type="button" title="Redo (Ctrl+Shift+Z)" aria-label="Redo" disabled>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 7v6h-6"/><path d="M21 13C18.5 7.5 12 5 7 8S1 17 4 21"/></svg>
+ </button>
+ <button class="as-btn" id="as-randomize" type="button" title="Randomise look">
+ <svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:5px" aria-hidden="true"><polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/></svg>
+ <span class="as-btn-label">Randomise</span>
+ </button>
<button class="as-btn" id="as-reset" type="button">Reset</button>
<button class="as-btn primary" id="as-save" type="button">Save avatar</button>
</div>
diff --git a/pages/ibm/identity.html b/pages/ibm/identity.html
index 8297d99d4..564f5df16 100644
--- a/pages/ibm/identity.html
+++ b/pages/ibm/identity.html
@@ -18,17 +18,9 @@
<meta name="twitter:image" content="https://three.ws/ibm-og.png" />
<link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/ibm.css" />
<style>
- :root {
- color-scheme: dark;
- --bg:#05070d; --panel:rgba(18,22,32,0.80); --panel-solid:#0e121b;
- --border:rgba(255,255,255,0.10); --border-strong:rgba(255,255,255,0.18);
- --text:#e9edf6; --muted:#8b93a7; --faint:#5a6276;
- --ibm:#0f62fe; --ibm-light:#78a9ff;
- --allow:#42be65; --review:#f1c21b; --block:#fa4d56;
- --shadow:0 18px 50px rgba(0,0,0,0.55);
- --mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace;
- }
+ /* Design tokens come from the shared system: /ibm.css */
* { box-sizing:border-box; margin:0; padding:0; }
html,body { min-height:100%; }
body {
diff --git a/pages/ibm/proof.html b/pages/ibm/proof.html
index 8616de08a..89b6df632 100644
--- a/pages/ibm/proof.html
+++ b/pages/ibm/proof.html
@@ -15,14 +15,9 @@
<meta name="twitter:card" content="summary_large_image" />
<link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/ibm.css" />
<style>
- :root {
- --bg:#05070d; --panel:#0c1018; --panel2:#11161f; --border:#1c2330; --border2:#283142;
- --text:#e8ecf4; --muted:#8a93a6; --faint:#5a6376;
- --ibm:#0f62fe; --ibm-light:#78a9ff; --ibm-dim:rgba(15,98,254,0.12);
- --up:#42be65; --down:#fa4d56; --warn:#f1c21b;
- --mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
- }
+ /* Design tokens come from the shared system: /ibm.css */
* { box-sizing: border-box; margin: 0; padding: 0; }
html { scroll-behavior: smooth; }
body { font: 15px/1.6 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif; color: var(--text); background: var(--bg); min-height: 100vh; -webkit-font-smoothing: antialiased; }
diff --git a/pages/ibm/trust-layer.html b/pages/ibm/trust-layer.html
index a3fc16068..f1c821fbe 100644
--- a/pages/ibm/trust-layer.html
+++ b/pages/ibm/trust-layer.html
@@ -18,30 +18,9 @@
<meta name="twitter:image" content="https://three.ws/ibm-og.png" />
<link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/ibm.css" />
<style>
- /* ── Design tokens ──────────────────────────────────── */
- :root {
- color-scheme: dark;
- --bg: #05070d;
- --panel: rgba(18,22,32,0.82);
- --panel-solid: #0e121b;
- --panel-hover: rgba(30,36,52,0.92);
- --border: rgba(255,255,255,0.09);
- --border-hi: rgba(255,255,255,0.18);
- --text: #e9edf6;
- --muted: #8b93a7;
- --faint: #505a70;
- --ibm: #0f62fe;
- --ibm-lt: #78a9ff;
- --allow: #42be65;
- --review: #f1c21b;
- --block: #fa4d56;
- --mono: ui-monospace,"SF Mono",Menlo,Consolas,monospace;
- --radius-lg: 16px;
- --radius-md: 12px;
- --radius-sm: 9px;
- --shadow: 0 20px 56px rgba(0,0,0,0.6);
- }
+ /* Design tokens come from the shared system: /ibm.css */
*,*::before,*::after { box-sizing:border-box; margin:0; padding:0; }
html,body { height:100%; }
body {
diff --git a/pages/ibm/vision.html b/pages/ibm/vision.html
index c40cb2379..2c75edafc 100644
--- a/pages/ibm/vision.html
+++ b/pages/ibm/vision.html
@@ -21,20 +21,9 @@
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Granite Vision — IBM watsonx sees your 3D avatar" />
<link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/ibm.css" />
<style>
- :root {
- --ibm-blue: #0f62fe;
- --ibm-blue-2: #4589ff;
- --ibm-light: #78a9ff;
- --ink: #f4f4f4;
- --muted: #a6b0c3;
- --faint: #6b7589;
- --panel: rgba(13, 17, 28, 0.72);
- --panel-solid: #0d111c;
- --stroke: rgba(120, 169, 255, 0.22);
- --line: rgba(255, 255, 255, 0.08);
- --font: 'IBM Plex Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
- }
+ /* Design tokens come from the shared system: /ibm.css */
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body {
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 8953476ba..bcd7c063b 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -1,4 +1,12 @@
import { AnimationClip, AnimationMixer, LoopRepeat, LoopOnce } from 'three';
+import { canonicalizeBoneName } from './glb-canonicalize.js';
+
+// Minimum number of canonical bones a skinned model must expose before the
+// pre-baked clip library can drive it meaningfully. The clips address tracks by
+// canonical Avaturn bone names; a model sharing only a stray bone or two would
+// twitch a single joint rather than perform the motion. Eight covers the torso
+// + a limb, which is enough to read as a real humanoid performance.
+const MIN_CANONICAL_BONES = 8;
/**
* Manages pre-baked animation clips for skinned agents.
@@ -39,6 +47,8 @@ export class AnimationManager {
this._failed = new Set();
/** @type {Set<string>|null} Bone/node names of the currently attached model. */
this._boneNames = null;
+ /** @type {boolean} Whether the attached model's rig can play the canonical clip library. */
+ this._canonicalClipsSupported = false;
}
// ── Model binding ──────────────────────────────────────────────────────────
@@ -56,6 +66,7 @@ export class AnimationManager {
this.currentAction = null;
this.currentName = null;
this._boneNames = _collectBoneNames(model);
+ this._canonicalClipsSupported = _modelSupportsCanonicalClips(model);
for (const [name, clip] of this.clips) {
const filtered = _filterClip(clip, this._boneNames);
@@ -74,6 +85,7 @@ export class AnimationManager {
}
this.model = null;
this._boneNames = null;
+ this._canonicalClipsSupported = false;
this.actions.clear();
this.currentAction = null;
this.currentName = null;
@@ -99,6 +111,19 @@ export class AnimationManager {
return this._failed.has(name);
}
+ /**
+ * Whether the currently attached model can be driven by the pre-baked
+ * canonical clip library. True only for a skinned humanoid whose skeleton
+ * shares enough bones with the canonical Avaturn rig that a retargeted clip
+ * actually moves it. A static mesh (no skeleton) or a non-humanoid rig
+ * returns false, so callers can hide animation affordances that would
+ * otherwise play to no visible effect.
+ * @returns {boolean}
+ */
+ supportsCanonicalClips() {
+ return this._canonicalClipsSupported;
+ }
+
// ── Loading ────────────────────────────────────────────────────────────────
/**
@@ -284,6 +309,23 @@ function _collectBoneNames(model) {
return names;
}
+// A pre-baked clip only deforms the mesh when its tracks address real skeleton
+// bones. Require both a SkinnedMesh and enough canonically-named bones so we
+// don't mistake a static prop (whose node happens to be named "Head") for a
+// rig the library can animate.
+function _modelSupportsCanonicalClips(model) {
+ let hasSkinnedMesh = false;
+ const canonical = new Set();
+ model.traverse((node) => {
+ if (node.isSkinnedMesh) hasSkinnedMesh = true;
+ if (node.name) {
+ const c = canonicalizeBoneName(node.name);
+ if (c) canonical.add(c);
+ }
+ });
+ return hasSkinnedMesh && canonical.size >= MIN_CANONICAL_BONES;
+}
+
function _filterClip(clip, boneNames) {
if (!boneNames || boneNames.size === 0) return clip;
const valid = clip.tracks.filter((t) => {
diff --git a/src/app-next-overlay.js b/src/app-next-overlay.js
index 477265f4c..1b20b0d1a 100644
--- a/src/app-next-overlay.js
+++ b/src/app-next-overlay.js
@@ -216,8 +216,18 @@ function startChatChipRotation(viewer) {
let cursor = Math.floor(Math.random() * pool.length);
const render = () => {
- const available = new Set((viewer.animationManager?.getAnimationDefs?.() || []).map((d) => d.name));
- const filtered = pool.filter((p) => !p.clip || available.size === 0 || available.has(p.clip));
+ const mgr = viewer.animationManager;
+ // Clip-bearing chips ("Show me a dance") only make sense when the loaded
+ // model can actually perform the pre-baked library. A user's own GLB with
+ // no compatible skeleton retargets every clip to nothing, so for those we
+ // drop the animation chips and keep only the conversational prompts.
+ const canPerform = mgr?.supportsCanonicalClips?.() !== false;
+ const available = new Set((mgr?.getAnimationDefs?.() || []).map((d) => d.name));
+ const filtered = pool.filter((p) => {
+ if (!p.clip) return true;
+ if (!canPerform) return false;
+ return available.size === 0 || available.has(p.clip);
+ });
const showPool = filtered.length >= VISIBLE_CHIPS ? filtered : pool;
chipsEl.innerHTML = '';
for (let i = 0; i < VISIBLE_CHIPS; i++) {
@@ -242,6 +252,10 @@ function startChatChipRotation(viewer) {
render();
}, CHIP_ROTATE_MS);
+ // A new model can change which clips are performable — re-filter the chips
+ // the moment it loads instead of waiting for the next rotation tick.
+ window.addEventListener('viewer:model-loaded', () => render());
+
// Pause rotation when the chat dock is focused/hovered
const dock = document.getElementById('nxt-chat-dock');
if (dock) {
@@ -464,6 +478,13 @@ function wireAnimationSheet() {
btn.setAttribute('aria-expanded', 'false');
};
+ // A new model can have a different set of (or no) usable animations — drop the
+ // cached grid so the next open rebuilds it, and rebuild live if it's open now.
+ window.addEventListener('viewer:model-loaded', () => {
+ rendered = false;
+ if (!sheet.hidden) renderGrid().then(() => { rendered = true; });
+ });
+
btn.addEventListener('click', () => {
if (sheet.hidden) open();
else close();
@@ -495,6 +516,14 @@ function wireAnimationSheet() {
grid.innerHTML = '<div class="nxt-anim-empty">This avatar has no animations.</div>';
return;
}
+ // The built-in library only retargets onto a compatible humanoid rig. For a
+ // custom upload with no matching skeleton, every clip would play to no
+ // effect — say so instead of listing actions that do nothing.
+ if (viewer.animationManager.supportsCanonicalClips?.() === false) {
+ grid.innerHTML =
+ '<div class="nxt-anim-empty">This model’s rig isn’t compatible with the built-in animations. Upload a humanoid avatar (Mixamo, Ready Player Me, Avaturn) to use them.</div>';
+ return;
+ }
grid.innerHTML = '';
const activeName = viewer.animationManager.currentName;
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 1e68902f0..cb8f8af36 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -262,6 +262,12 @@ function renderShell(glbUrl) {
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
Edit
</a>
+ ${avatar.source_meta?.generator === 'avatar-studio' ? `
+ <a class="av-owner-btn" href="/create/studio?edit=${encodeURIComponent(avatar.id || avatarId)}">
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
+ Edit in Studio
+ </a>
+ ` : ''}
<button class="av-owner-btn" id="av-deploy-onchain" type="button">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>
Deploy on-chain
diff --git a/src/avatar-studio-utils.js b/src/avatar-studio-utils.js
new file mode 100644
index 000000000..55dbb37e6
--- /dev/null
+++ b/src/avatar-studio-utils.js
@@ -0,0 +1,84 @@
+/**
+ * Pure utility helpers for the Avatar Studio — no DOM, no Three.js, no side
+ * effects. Exported so they can be unit-tested in isolation.
+ */
+
+export const DRAFT_KEY = 'avatar-studio-draft';
+export const DRAFT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
+
+/** Collapse a working appearance to only non-empty fields. Returns null if nothing set. */
+export function collapseAppearance(a) {
+ if (!a) return null;
+ const out = {};
+ if (a.accessories?.length) out.accessories = [...a.accessories];
+ if (a.morphs && Object.keys(a.morphs).length) out.morphs = { ...a.morphs };
+ if (a.colors && Object.keys(a.colors).length) out.colors = { ...a.colors };
+ if (a.hidden?.length) out.hidden = [...a.hidden];
+ return Object.keys(out).length ? out : null;
+}
+
+/** Hydrate a saved appearance record into a mutable working object. */
+export function hydrateAppearance(raw) {
+ if (!raw || typeof raw !== 'object') {
+ return { accessories: [], morphs: {}, colors: {}, hidden: [] };
+ }
+ return {
+ accessories: Array.isArray(raw.accessories) ? [...raw.accessories] : [],
+ morphs: raw.morphs && typeof raw.morphs === 'object' ? { ...raw.morphs } : {},
+ colors: raw.colors && typeof raw.colors === 'object' ? { ...raw.colors } : {},
+ hidden: Array.isArray(raw.hidden) ? [...raw.hidden] : [],
+ };
+}
+
+/** Deep clone a working appearance. */
+export function cloneAppearance(a) {
+ return {
+ accessories: [...a.accessories],
+ morphs: { ...a.morphs },
+ colors: { ...a.colors },
+ hidden: [...a.hidden],
+ };
+}
+
+/** True when two appearances are semantically identical. */
+export function appearanceEqual(a, b) {
+ return JSON.stringify(collapseAppearance(a)) === JSON.stringify(collapseAppearance(b));
+}
+
+/** Parse the edit avatar ID from a URLSearchParams (or query string). */
+export function parseEditId(searchOrParams) {
+ const p = typeof searchOrParams === 'string'
+ ? new URLSearchParams(searchOrParams)
+ : searchOrParams;
+ const v = p.get('edit');
+ return v && v.trim() ? v.trim() : null;
+}
+
+/** Read a persisted draft from a storage-like object (localStorage interface). */
+export function readDraft(storage) {
+ try {
+ const raw = storage.getItem(DRAFT_KEY);
+ if (!raw) return null;
+ const draft = JSON.parse(raw);
+ if (!draft?.ts) return null;
+ if (Date.now() - draft.ts > DRAFT_MAX_AGE_MS) {
+ storage.removeItem(DRAFT_KEY);
+ return null;
+ }
+ return draft;
+ } catch {
+ return null;
+ }
+}
+
+/** Write a draft to storage. */
+export function writeDraft(storage, appearance, name) {
+ try {
+ storage.setItem(DRAFT_KEY, JSON.stringify({ appearance, name, ts: Date.now() }));
+ } catch {}
+}
+
+/** Remove a draft from storage. */
+export function clearDraft(storage) {
+ try { storage.removeItem(DRAFT_KEY); } catch {}
+}
diff --git a/src/avatar-studio.js b/src/avatar-studio.js
index f1a1e9cab..8749f9fbd 100644
--- a/src/avatar-studio.js
+++ b/src/avatar-studio.js
@@ -2,19 +2,21 @@
* Avatar Studio — /create/studio
*
* Build a custom 3D avatar from a base template without needing a selfie.
- * Loads the base GLB, lets the user sculpt face/body morphs, pick outfits
- * and accessories, then saves the result to their account (upload base GLB +
- * create avatar record + PATCH appearance for server-side bake).
+ * Two modes:
+ * - Create: /create/studio → start from default.glb
+ * - Edit: /create/studio?edit=ID → reload a previously-saved avatar
+ *
+ * On Save, the live Three.js scene is exported via GLTFExporter (colours,
+ * morphs, and accessories are already applied to the scene graph), so the
+ * resulting GLB is exactly what the user saw. No server-side bake required
+ * for the model to look right — the appearance JSON is still PATCHed as
+ * metadata so the avatar is re-editable later.
*
* Reuses the same building blocks as avatar-edit.js:
* - TalkScene for the 3D viewport
* - AccessoryManager for outfit/accessory application
* - renderSculptPanel from avatar-sculpt.js for face/body morphs
* - IdleAnimation for ambient breathing/blinking
- *
- * The save flow mirrors create.js → create-review.js: upload the base GLB
- * via presign + direct R2 PUT, create the avatar record, then PATCH it with
- * the appearance JSON so the server bakes a canonical GLB.
*/
import { TalkScene } from './voice/talk-scene.js';
@@ -23,8 +25,20 @@ import { IdleAnimation } from './idle-animation.js';
import { renderSculptPanel, applyMorphsToRoot } from './avatar-sculpt.js';
import { saveRemoteGlbToAccount, apiFetch } from './account.js';
import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';
+import {
+ collapseAppearance,
+ hydrateAppearance,
+ cloneAppearance,
+ appearanceEqual,
+ parseEditId,
+ readDraft,
+ writeDraft as writeDraftStorage,
+ clearDraft as clearDraftStorage,
+ DRAFT_KEY,
+} from './avatar-studio-utils.js';
const BASE_GLB_URL = '/avatars/default.glb';
+const MAX_HISTORY = 50;
const $ = (id) => document.getElementById(id);
const esc = (s) =>
@@ -42,6 +56,12 @@ let presets = [];
let presetsById = new Map();
let workingAppearance = { accessories: [], morphs: {}, colors: {}, hidden: [] };
+let savedAppearance = null; // null = unsaved / the appearance at last save
+let editAvatarId = null; // non-null when in edit mode (?edit=ID)
+
+let history = [];
+let historyIndex = -1;
+
let previewedId = null;
let previewToken = 0;
let opQueue = Promise.resolve();
@@ -67,11 +87,6 @@ const KIND_LABEL = { hat: 'Hat', glasses: 'Glasses', earrings: 'Earrings' };
let activeTab = 'color';
// ── Color customization ──────────────────────────────────────────────
-// The base avatar is a ReadyPlayerMe (Wolf3D) mesh with named, texture-backed
-// materials. We tint a slot by multiplying every material in that slot by a
-// chosen color (white = original texture, untinted). The same slot→material
-// map and tint semantics are mirrored server-side in api/_lib/bake.js so the
-// saved/baked GLB looks identical to the live preview.
const COLOR_SLOTS = [
{
id: 'skin',
@@ -94,15 +109,9 @@ const COLOR_SLOTS = [
];
const COLOR_SLOT_BY_ID = new Map(COLOR_SLOTS.map((s) => [s.id, s]));
const HEX_RE = /^#[0-9a-f]{6}$/i;
-const BODY_TYPE = 'feminine'; // the single shipped base mesh is feminine-presenting
+const BODY_TYPE = 'feminine';
// ── Garment layers (show/hide) ───────────────────────────────────────
-// The base avatar ships its garments as separate skinned meshes, so we can
-// strip it back toward the base body and build the look up again. Hiding a
-// layer toggles its meshes' `visible`; the hidden slot ids persist in
-// appearance.hidden, bake out server-side (api/_lib/bake.js applyHidden), and
-// re-apply on the editor via AccessoryManager.applyLayers. `strip` marks the
-// layers the "Start minimal" shortcut removes — hair is kept.
const LAYER_SLOTS = [
{ id: 'outfit', label: 'Outfit', materials: ['Wolf3D_Outfit_Top', 'Wolf3D_Outfit_Bottom', 'Wolf3D_Outfit_Footwear'], strip: true },
{ id: 'glasses', label: 'Glasses', materials: ['Wolf3D_Glasses'], strip: true },
@@ -121,7 +130,40 @@ init().catch((err) => {
});
async function init() {
- const scenePromise = bootScene();
+ const params = new URLSearchParams(location.search);
+ editAvatarId = parseEditId(params);
+
+ let editAvatar = null;
+ if (editAvatarId) {
+ try {
+ editAvatar = await fetchEditAvatar(editAvatarId);
+ } catch (err) {
+ setStatus('err', `Could not load avatar: ${err.message}`);
+ }
+ }
+
+ if (editAvatar) {
+ workingAppearance = hydrateAppearance(editAvatar.appearance);
+ savedAppearance = cloneAppearance(workingAppearance);
+ const nameEl = $('as-name');
+ if (nameEl) nameEl.value = editAvatar.name || '';
+ const titleEl = document.querySelector('.as-bar-title');
+ if (titleEl) titleEl.textContent = 'Edit Avatar';
+ const backEl = $('as-back');
+ if (backEl) backEl.href = `/avatars/${encodeURIComponent(editAvatarId)}`;
+ } else {
+ // Offer to restore a saved draft (only in create mode, not edit)
+ maybeSuggestDraft();
+ }
+
+ // History starts at the hydrated initial state
+ pushHistory();
+
+ const glbUrl = editAvatar
+ ? (editAvatar.base_model_url || editAvatar.model_url || BASE_GLB_URL)
+ : BASE_GLB_URL;
+
+ const scenePromise = bootScene(glbUrl, editAvatar);
presets = await fetchPresets();
presetsById = new Map(presets.map((p) => [p.id, p]));
@@ -130,24 +172,187 @@ async function init() {
renderChips();
renderActivePanel();
bindHeader();
+ bindKeyboard();
await scenePromise;
- // Re-render once the mesh is live so the active panel (sculpt morphs, color
- // preview) reflects the loaded avatar instead of the "waiting" placeholder,
- // and replay any colours/hidden layers chosen before the GLB finished loading.
if (scene?.root) {
applyAllColors();
applyAllLayers();
}
renderActivePanel();
+ updateDirtyState();
+}
+
+async function fetchEditAvatar(id) {
+ const res = await apiFetch(`/api/avatars/${encodeURIComponent(id)}`);
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw new Error(body.message || `Failed to load avatar (${res.status})`);
+ }
+ const { avatar } = await res.json();
+ return avatar;
+}
+
+// ── Draft autosave ───────────────────────────────────────────────────
+
+let _draftTimer = null;
+function scheduleDraftSave() {
+ clearTimeout(_draftTimer);
+ _draftTimer = setTimeout(() => {
+ if (editAvatarId) return;
+ writeDraftStorage(localStorage, collapseAppearance(workingAppearance), ($('as-name')?.value || '').trim());
+ }, 2000);
}
-async function bootScene() {
+function clearDraft() {
+ clearDraftStorage(localStorage);
+}
+
+function maybeSuggestDraft() {
+ const draft = readDraft(localStorage);
+ if (!draft?.appearance) return;
+ const ageMins = (Date.now() - draft.ts) / 60000;
+
+ const bar = document.createElement('div');
+ bar.id = 'as-draft-bar';
+ bar.innerHTML = `
+ <span>You have unsaved work from ${ageMins < 60 ? `${Math.round(ageMins)}m ago` : `${Math.round(ageMins/60)}h ago`}.</span>
+ <button class="as-draft-btn" id="as-draft-restore">Restore</button>
+ <button class="as-draft-btn as-draft-dismiss" id="as-draft-dismiss">Dismiss</button>
+ `;
+ $('as-shell').prepend(bar);
+
+ $('as-draft-restore').addEventListener('click', () => {
+ bar.remove();
+ workingAppearance = hydrateAppearance(draft.appearance);
+ const nameEl = $('as-name');
+ if (nameEl && draft.name) nameEl.value = draft.name;
+ if (scene?.root) {
+ applyAllColors();
+ applyAllLayers();
+ applyMorphsToRoot(scene.root, workingAppearance.morphs);
+ if (accessoryManager) accessoryManager.hydrateFromAppearance(workingAppearance);
+ }
+ pushHistory();
+ renderChips();
+ renderActivePanel();
+ updateDirtyState();
+ setStatus('ok', 'Draft restored.');
+ });
+ $('as-draft-dismiss').addEventListener('click', () => { bar.remove(); clearDraft(); });
+}
+
+// ── History (undo / redo) ────────────────────────────────────────────
+
+function pushHistory() {
+ // drop any "future" when a new action is taken
+ history = history.slice(0, historyIndex + 1);
+ history.push(cloneAppearance(workingAppearance));
+ if (history.length > MAX_HISTORY) history.shift();
+ historyIndex = history.length - 1;
+ updateUndoRedoBtns();
+}
+
+function undoAppearance() {
+ if (historyIndex <= 0) return;
+ historyIndex--;
+ applyHistoryState(history[historyIndex]);
+}
+
+function redoAppearance() {
+ if (historyIndex >= history.length - 1) return;
+ historyIndex++;
+ applyHistoryState(history[historyIndex]);
+}
+
+async function applyHistoryState(state) {
+ workingAppearance = cloneAppearance(state);
+ if (accessoryManager) {
+ await queueOp(() => accessoryManager.hydrateFromAppearance(workingAppearance));
+ }
+ if (scene?.root) {
+ applyAllColors();
+ applyAllLayers();
+ applyMorphsToRoot(scene.root, workingAppearance.morphs);
+ }
+ renderChips();
+ renderActivePanel();
+ updateUndoRedoBtns();
+ updateDirtyState();
+ scheduleDraftSave();
+}
+
+function updateUndoRedoBtns() {
+ const u = $('as-undo');
+ const r = $('as-redo');
+ if (u) u.disabled = historyIndex <= 0;
+ if (r) r.disabled = historyIndex >= history.length - 1;
+}
+
+// ── Dirty state ──────────────────────────────────────────────────────
+
+function updateDirtyState() {
+ const isDirty = savedAppearance !== null
+ ? !appearanceEqual(workingAppearance, savedAppearance)
+ : collapseAppearance(workingAppearance) !== null;
+
+ const titleEl = document.querySelector('.as-bar-title');
+ if (titleEl) {
+ const base = editAvatarId ? 'Edit Avatar' : 'Avatar Studio';
+ titleEl.textContent = isDirty ? `${base} ·` : base;
+ }
+
+ const saveBtn = $('as-save');
+ if (saveBtn && !saveBtn.disabled) {
+ // keep save always enabled — just mark with dirty dot
+ }
+}
+
+// ── Randomise ────────────────────────────────────────────────────────
+
+function randomizeAppearance() {
+ // Pick one random swatch per color slot
+ for (const slot of COLOR_SLOTS) {
+ const swatch = slot.swatches[Math.floor(Math.random() * slot.swatches.length)];
+ workingAppearance.colors[slot.id] = swatch.toLowerCase();
+ applySlotColor(slot, swatch);
+ }
+
+ // Clear existing accessories, add one hat + one glasses from presets
+ const hats = presets.filter((p) => p.kind === 'hat');
+ const glasses = presets.filter((p) => p.kind === 'glasses');
+ if (accessoryManager) {
+ for (const id of [...workingAppearance.accessories]) accessoryManager.removePreset(id);
+ }
+ workingAppearance.accessories = [];
+
+ const pick = (arr) => arr.length ? arr[Math.floor(Math.random() * arr.length)] : null;
+ const hat = pick(hats);
+ const glass = pick(glasses);
+ const toApply = [hat, glass].filter(Boolean);
+ for (const p of toApply) workingAppearance.accessories.push(p.id);
+ if (accessoryManager) {
+ queueOp(async () => {
+ for (const p of toApply) await accessoryManager.applyPreset(p);
+ });
+ }
+
+ pushHistory();
+ renderChips();
+ renderActivePanel();
+ updateDirtyState();
+ scheduleDraftSave();
+ setStatus('ok', 'Randomised! Click Save when happy.');
+}
+
+// ── Boot scene ────────────────────────────────────────────────────────
+
+async function bootScene(glbUrl, editAvatar) {
scene = new TalkScene();
try {
await scene.mount({
container: $('as-stage'),
- glbUrl: BASE_GLB_URL,
+ glbUrl,
});
$('as-loading')?.remove();
accessoryManager = new AccessoryManager({
@@ -155,20 +360,27 @@ async function bootScene() {
invalidate: () => {},
});
+ // In edit mode, replay accessories from saved appearance
+ if (editAvatar?.appearance) {
+ await accessoryManager.hydrateFromAppearance(workingAppearance);
+ }
+
idle = new IdleAnimation({
getRoot: () => scene.root,
seed: 'avatar-studio',
});
scene.addOnTick((dt) => idle.update(dt));
- setStatus('', 'Choose a style below to get started.');
+ setStatus('', editAvatar
+ ? 'Loaded your saved avatar. Make changes and save to update it.'
+ : 'Choose a style below to get started.');
} catch (err) {
const loadingEl = $('as-loading');
if (loadingEl) loadingEl.textContent = `Could not load base avatar: ${err.message}`;
}
}
-// ── API ──────────────────────────────────────────────────────────────
+// ── Fetch presets ────────────────────────────────────────────────────
async function fetchPresets() {
const r = await fetch('/accessories/presets.json');
@@ -186,7 +398,7 @@ function renderTabs() {
<button class="as-tab${active ? ' active' : ''}" data-tab="${t.id}" role="tab"
id="as-tab-${t.id}" aria-selected="${active ? 'true' : 'false'}"
aria-controls="as-panel" tabindex="${active ? '0' : '-1'}">
- ${t.label}
+ <span class="as-tab-label">${t.label}</span>
</button>`;
}).join('');
@@ -210,7 +422,6 @@ function renderTabs() {
tabs.forEach((btn, i) => {
btn.addEventListener('click', () => selectTab(btn));
- // Roving-tabindex keyboard nav per WAI-ARIA tablist pattern.
btn.addEventListener('keydown', (e) => {
let target = null;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') target = tabs[(i + 1) % tabs.length];
@@ -244,7 +455,10 @@ function renderActivePanel() {
root: scene.root,
working: workingAppearance,
onDirty: () => {
+ pushHistory();
renderChips();
+ updateDirtyState();
+ scheduleDraftSave();
},
});
return;
@@ -262,9 +476,19 @@ function renderActivePanel() {
value="${esc(searchQuery)}" autocomplete="off" />
</div>`;
- if (items.length === 0 && q) {
- panel.innerHTML = searchHtml + `<div class="as-empty">No matches for "${esc(searchQuery)}".</div>`;
+ if (items.length === 0) {
+ const emptyMsg = q
+ ? `No matches for "${esc(searchQuery)}".`
+ : `No ${esc(tab.label.toLowerCase())} available yet.`;
+ const clearBtn = q
+ ? `<button class="as-empty-action" id="as-clear-search">Clear search</button>`
+ : '';
+ panel.innerHTML = searchHtml + `<div class="as-empty">${emptyMsg}${clearBtn}</div>`;
bindSearch();
+ $('as-clear-search')?.addEventListener('click', () => {
+ searchQuery = '';
+ renderActivePanel();
+ });
return;
}
@@ -327,7 +551,6 @@ function renderColorPanel(panel) {
})
.join('');
const noneSel = !current;
- // A custom (non-palette) color counts as the custom swatch being active.
const customSel = current && !presetMatch;
return `
<div class="as-color-group" data-group="${slot.id}">
@@ -394,7 +617,7 @@ function layersBlockHtml() {
function bindLayersBlock(panel) {
panel.querySelectorAll('.as-layer[data-layer]').forEach((btn) => {
btn.addEventListener('click', () => {
- const nowHidden = btn.getAttribute('aria-checked') === 'true'; // visible → hide
+ const nowHidden = btn.getAttribute('aria-checked') === 'true';
setLayerHidden(btn.dataset.layer, nowHidden);
});
});
@@ -410,7 +633,10 @@ function setLayerHidden(slotId, hidden) {
else if (!hidden && i >= 0) workingAppearance.hidden.splice(i, 1);
applyLayerVisibility(slot, hidden);
if (activeTab === 'color') renderActivePanel();
+ pushHistory();
renderChips();
+ updateDirtyState();
+ scheduleDraftSave();
setStatus('', `${slot.label} ${hidden ? 'hidden' : 'shown'}.`);
}
@@ -421,7 +647,10 @@ function stripToBase() {
applyLayerVisibility(slot, true);
}
if (activeTab === 'color') renderActivePanel();
+ pushHistory();
renderChips();
+ updateDirtyState();
+ scheduleDraftSave();
setStatus('', 'Stripped to the base body. Add layers back to dress it up.');
}
@@ -429,11 +658,13 @@ function dressFully() {
for (const slot of LAYER_SLOTS) applyLayerVisibility(slot, false);
workingAppearance.hidden = [];
if (activeTab === 'color') renderActivePanel();
+ pushHistory();
renderChips();
+ updateDirtyState();
+ scheduleDraftSave();
setStatus('', 'All layers shown.');
}
-// Toggle visibility of every mesh whose material belongs to the slot.
function applyLayerVisibility(slot, hidden) {
if (!scene?.root) return;
const names = new Set(slot.materials);
@@ -494,14 +725,14 @@ function setSlotColor(slotId, hex) {
}
applySlotColor(slot, workingAppearance.colors[slotId] || null);
if (activeTab === 'color') renderActivePanel();
+ pushHistory();
renderChips();
+ updateDirtyState();
+ scheduleDraftSave();
const c = workingAppearance.colors[slotId];
setStatus('', c ? `${slot.label} → ${c.toUpperCase()}` : `${slot.label} reset to default.`);
}
-// Live (uncommitted) preview while dragging the native color picker — applies
-// to the mesh and updates the slot's readout without a full re-render so the
-// picker stays open.
function liveSlotColor(slotId, hex) {
const slot = COLOR_SLOT_BY_ID.get(slotId);
if (!slot || !HEX_RE.test(hex)) return;
@@ -514,7 +745,6 @@ function liveSlotColor(slotId, hex) {
if (label) label.textContent = hex.toUpperCase();
}
-// Multiply every material in the slot by `hex` (null → white = original texture).
function applySlotColor(slot, hex) {
if (!scene?.root) return;
const color = hex || '#ffffff';
@@ -716,8 +946,11 @@ async function onTileClick(tab, presetId) {
await queueOp(async () => {
await applyAccessory(tab, presetId || null);
});
+ pushHistory();
renderActivePanel();
renderChips();
+ updateDirtyState();
+ scheduleDraftSave();
}
async function removeCommitted(id) {
@@ -729,8 +962,11 @@ async function removeCommitted(id) {
accessoryManager?.removePreset(id);
});
workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== id);
+ pushHistory();
renderActivePanel();
renderChips();
+ updateDirtyState();
+ scheduleDraftSave();
}
async function applyAccessory(tab, presetId) {
@@ -773,11 +1009,24 @@ async function applyAccessory(tab, presetId) {
}
}
-// ── Header / body type / status ──────────────────────────────────────
+// ── Header / keyboard ────────────────────────────────────────────────
function bindHeader() {
$('as-save').addEventListener('click', () => saveAvatar());
$('as-reset').addEventListener('click', () => resetAll());
+ $('as-randomize')?.addEventListener('click', () => randomizeAppearance());
+ $('as-undo')?.addEventListener('click', () => undoAppearance());
+ $('as-redo')?.addEventListener('click', () => redoAppearance());
+}
+
+function bindKeyboard() {
+ document.addEventListener('keydown', (e) => {
+ const mod = e.metaKey || e.ctrlKey;
+ if (!mod) return;
+ if (e.key === 'z' && !e.shiftKey) { e.preventDefault(); undoAppearance(); }
+ else if ((e.key === 'z' && e.shiftKey) || e.key === 'y') { e.preventDefault(); redoAppearance(); }
+ else if (e.key === 's') { e.preventDefault(); saveAvatar(); }
+ });
}
async function resetAll() {
@@ -796,8 +1045,11 @@ async function resetAll() {
}
if (accessoryManager) await accessoryManager.hydrateFromAppearance(workingAppearance);
});
+ pushHistory();
renderChips();
renderActivePanel();
+ updateDirtyState();
+ scheduleDraftSave();
setStatus('', 'Reset to default.');
}
@@ -811,15 +1063,29 @@ function setStatus(kind, text) {
el.innerHTML = kind === 'spin' ? `<span class="spin"></span>${esc(text)}` : esc(text);
}
-// ── Save flow ────────────────────────────────────────────────────────
-
-function collapseAppearance(a) {
- const out = {};
- if (a.accessories?.length) out.accessories = [...a.accessories];
- if (a.morphs && Object.keys(a.morphs).length) out.morphs = { ...a.morphs };
- if (a.colors && Object.keys(a.colors).length) out.colors = { ...a.colors };
- if (a.hidden?.length) out.hidden = [...a.hidden];
- return Object.keys(out).length ? out : null;
+// ── Save flow ─────────────────────────────────────────────────────────
+
+// Export the live Three.js scene as a GLB blob using GLTFExporter.
+// This captures colours (applied to material.color), morph weights, and
+// bone-attached accessories — all already in the scene graph. No server
+// bake required; what the user sees is what gets uploaded.
+async function exportSceneGlb() {
+ if (!scene?.root) throw new Error('Scene not ready — cannot export.');
+ const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
+ const exporter = new GLTFExporter();
+ const buf = await new Promise((resolve, reject) => {
+ exporter.parse(
+ scene.root,
+ resolve,
+ reject,
+ {
+ binary: true,
+ embedImages: true,
+ animations: scene._clips || [],
+ },
+ );
+ });
+ return new Blob([buf], { type: 'model/gltf-binary' });
}
function showSaveOverlay(label, sublabel) {
@@ -863,47 +1129,73 @@ async function saveAvatar() {
const resetBtn = $('as-reset');
saveBtn.disabled = true;
resetBtn.disabled = true;
- showSaveOverlay('Uploading avatar...', 'This may take a moment');
- try {
- const glbRes = await fetch(BASE_GLB_URL);
- if (!glbRes.ok) throw new Error(`Failed to fetch base GLB: ${glbRes.status}`);
- const glbBlob = await glbRes.blob();
+ // For edit mode, nudge the user if nothing changed
+ if (editAvatarId && !collapseAppearance(workingAppearance) &&
+ JSON.stringify(collapseAppearance(workingAppearance)) === JSON.stringify(collapseAppearance(savedAppearance))) {
+ setStatus('', 'No changes to save.');
+ saveBtn.disabled = false;
+ resetBtn.disabled = false;
+ return;
+ }
- updateSaveOverlay('Uploading base model...');
+ showSaveOverlay(editAvatarId ? 'Updating avatar...' : 'Exporting avatar...', 'Building your customised model');
+ updateProgress(5);
- const avatar = await saveRemoteGlbToAccount(
- glbBlob,
- {
- name,
- source: 'direct-upload',
- source_meta: { generator: 'avatar-studio', body_type: BODY_TYPE },
- visibility: 'public',
- },
- {
- onProgress: (pct) => updateProgress(pct * 0.7),
- },
- );
+ try {
+ // ── Step 1: Export the live scene as a GLB ──────────────────
+ // This captures all colours, morphs, and accessories already applied
+ // to the Three.js scene — no server-side bake needed.
+ updateSaveOverlay('Exporting model...', 'Capturing colours and accessories');
+ const glbBlob = await exportSceneGlb();
+ updateProgress(20);
+
+ // ── Step 2: Upload the GLB + create/update the DB record ────
+ updateSaveOverlay('Uploading...', 'Sending to your library');
+
+ let avatar;
+ if (editAvatarId) {
+ // Edit mode: upload new GLB version, PATCH it onto the existing record
+ avatar = await uploadEditedAvatar(editAvatarId, name, glbBlob);
+ } else {
+ avatar = await saveRemoteGlbToAccount(
+ glbBlob,
+ {
+ name,
+ source: 'direct-upload',
+ source_meta: { generator: 'avatar-studio', body_type: BODY_TYPE },
+ visibility: 'public',
+ },
+ {
+ onProgress: (pct) => updateProgress(20 + pct * 0.6),
+ },
+ );
+ }
+ updateProgress(82);
+ // ── Step 3: PATCH appearance for re-editability ─────────────
+ // The exported GLB already has everything baked; this PATCH only stores
+ // the appearance JSON as metadata so /create/studio?edit= can reload it.
const appearance = collapseAppearance(workingAppearance);
if (appearance) {
- updateSaveOverlay('Applying customizations...', 'Baking appearance into GLB');
- updateProgress(75);
-
+ updateSaveOverlay('Saving customisation data...');
const patchRes = await apiFetch(`/api/avatars/${encodeURIComponent(avatar.id)}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ appearance }),
});
if (!patchRes.ok) {
- const err = await patchRes.json().catch(() => ({}));
- console.warn('[avatar-studio] appearance PATCH failed:', err);
+ // Appearance metadata failed, but the GLB is already uploaded and correct.
+ // Log for debugging but don't block the save — the avatar will look right,
+ // it just won't be re-editable via ?edit= until this is retried.
+ const body = await patchRes.json().catch(() => ({}));
+ console.warn('[avatar-studio] appearance PATCH failed (non-fatal):', body);
}
}
+ updateProgress(92);
- updateProgress(90);
+ // ── Step 4: Thumbnail snapshot ──────────────────────────────
updateSaveOverlay('Capturing thumbnail...');
-
try {
await uploadAvatarSnapshot({ avatarId: avatar.id, scene });
} catch (err) {
@@ -911,17 +1203,27 @@ async function saveAvatar() {
}
updateProgress(100);
- updateSaveOverlay('Done! Redirecting...');
+ updateSaveOverlay('Done!', editAvatarId ? 'Avatar updated.' : 'Avatar saved to your library.');
+
+ // Mark saved state, clear draft
+ savedAppearance = cloneAppearance(workingAppearance);
+ clearDraft();
+ updateDirtyState();
+
+ await new Promise((r) => setTimeout(r, 700));
+ hideSaveOverlay();
- await new Promise((r) => setTimeout(r, 600));
+ // Show a save-success toast briefly before redirecting
+ showSaveToast(avatar.id);
+ await new Promise((r) => setTimeout(r, 1400));
window.location.href = `/avatars/${encodeURIComponent(avatar.id)}`;
} catch (err) {
hideSaveOverlay();
console.error('[avatar-studio] save failed:', err);
if (err.code === 'not_signed_in' || err.stage === 'auth') {
- const next = encodeURIComponent('/create/studio');
+ const next = encodeURIComponent(location.pathname + location.search);
window.location.replace(`/login?next=${next}`);
return;
}
@@ -931,3 +1233,46 @@ async function saveAvatar() {
resetBtn.disabled = false;
}
}
+
+// Upload a new GLB version for an existing avatar in edit mode.
+// Reuses saveRemoteGlbToAccount to presign + upload the blob, then PATCHes
+// the existing avatar record with the new storage key and updated name.
+async function uploadEditedAvatar(avatarId, name, glbBlob, onProgress) {
+ // Upload the new GLB to a fresh R2 key under the user's namespace
+ const tmp = await saveRemoteGlbToAccount(
+ glbBlob,
+ {
+ name,
+ source: 'direct-upload',
+ source_meta: { generator: 'avatar-studio', body_type: BODY_TYPE },
+ visibility: 'public',
+ },
+ { onProgress },
+ );
+
+ // Replace the target avatar's GLB with the freshly uploaded key
+ const patchRes = await apiFetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ glbUrl: tmp.storage_key, name }),
+ });
+ if (!patchRes.ok) {
+ const body = await patchRes.json().catch(() => ({}));
+ throw new Error(body.message || `Avatar update failed (${patchRes.status})`);
+ }
+ const { avatar } = await patchRes.json();
+ return avatar;
+}
+
+function showSaveToast(avatarId) {
+ const el = document.createElement('div');
+ el.className = 'as-toast';
+ el.innerHTML = `
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="as-toast-icon" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>
+ <span>Saved! Opening your avatar…</span>
+ <a href="/avatars/${esc(avatarId)}" class="as-toast-link">View now</a>
+ `;
+ document.body.appendChild(el);
+ // Animate in
+ requestAnimationFrame(() => el.classList.add('visible'));
+}
diff --git a/src/viewer.js b/src/viewer.js
index 95f0af818..f8db650e6 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -1054,6 +1054,12 @@ export class Viewer {
this._pendingReveal = null;
this._tweenCamera(framedPos, target, 1500);
}
+
+ // Announce the swap so overlays can react to the new rig (e.g. re-filter
+ // animation suggestions against what this model can actually perform).
+ try {
+ window.dispatchEvent(new CustomEvent('viewer:model-loaded', { detail: { viewer: this } }));
+ } catch {}
}
setClips(clips) {
diff --git a/tests/avatar-studio-save.test.js b/tests/avatar-studio-save.test.js
new file mode 100644
index 000000000..092bce7ce
--- /dev/null
+++ b/tests/avatar-studio-save.test.js
@@ -0,0 +1,264 @@
+/**
+ * Unit tests for the Avatar Studio pure utility helpers.
+ *
+ * Tests cover:
+ * - collapseAppearance: empty, partial, and full appearance collapsing
+ * - hydrateAppearance: null/missing inputs, valid inputs, field defaults
+ * - cloneAppearance: deep isolation — mutations don't bleed between copies
+ * - appearanceEqual: identity, structural equality, inequality
+ * - parseEditId: URL params with and without the `edit` key
+ * - readDraft / writeDraft / clearDraft: localStorage round-trips + expiry
+ */
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ collapseAppearance,
+ hydrateAppearance,
+ cloneAppearance,
+ appearanceEqual,
+ parseEditId,
+ readDraft,
+ writeDraft,
+ clearDraft,
+ DRAFT_KEY,
+ DRAFT_MAX_AGE_MS,
+} from '../src/avatar-studio-utils.js';
+
+// ── collapseAppearance ────────────────────────────────────────────────────────
+
+describe('collapseAppearance', () => {
+ it('returns null for a fully empty appearance', () => {
+ expect(collapseAppearance({ accessories: [], morphs: {}, colors: {}, hidden: [] })).toBeNull();
+ });
+
+ it('returns null for null/undefined input', () => {
+ expect(collapseAppearance(null)).toBeNull();
+ expect(collapseAppearance(undefined)).toBeNull();
+ });
+
+ it('includes accessories when non-empty', () => {
+ const result = collapseAppearance({ accessories: ['hat-01'], morphs: {}, colors: {}, hidden: [] });
+ expect(result).toEqual({ accessories: ['hat-01'] });
+ });
+
+ it('includes morphs when non-empty', () => {
+ const result = collapseAppearance({ accessories: [], morphs: { jawOpen: 0.3 }, colors: {}, hidden: [] });
+ expect(result).toEqual({ morphs: { jawOpen: 0.3 } });
+ });
+
+ it('includes colors when non-empty', () => {
+ const result = collapseAppearance({ accessories: [], morphs: {}, colors: { skin: '#f3c1a3' }, hidden: [] });
+ expect(result).toEqual({ colors: { skin: '#f3c1a3' } });
+ });
+
+ it('includes hidden when non-empty', () => {
+ const result = collapseAppearance({ accessories: [], morphs: {}, colors: {}, hidden: ['outfit'] });
+ expect(result).toEqual({ hidden: ['outfit'] });
+ });
+
+ it('includes all non-empty fields together', () => {
+ const input = {
+ accessories: ['hat-01', 'earrings-02'],
+ morphs: { jawOpen: 0.2 },
+ colors: { hair: '#3b2417', skin: '#e0a878' },
+ hidden: ['glasses'],
+ };
+ const result = collapseAppearance(input);
+ expect(result).toEqual(input);
+ });
+
+ it('copies arrays — mutations to result do not affect input', () => {
+ const input = { accessories: ['hat-01'], morphs: {}, colors: {}, hidden: [] };
+ const result = collapseAppearance(input);
+ result.accessories.push('mutated');
+ expect(input.accessories).toHaveLength(1);
+ });
+});
+
+// ── hydrateAppearance ─────────────────────────────────────────────────────────
+
+describe('hydrateAppearance', () => {
+ it('returns defaults for null', () => {
+ const result = hydrateAppearance(null);
+ expect(result).toEqual({ accessories: [], morphs: {}, colors: {}, hidden: [] });
+ });
+
+ it('returns defaults for undefined', () => {
+ const result = hydrateAppearance(undefined);
+ expect(result).toEqual({ accessories: [], morphs: {}, colors: {}, hidden: [] });
+ });
+
+ it('returns defaults for a non-object (string)', () => {
+ const result = hydrateAppearance('bad');
+ expect(result).toEqual({ accessories: [], morphs: {}, colors: {}, hidden: [] });
+ });
+
+ it('fills in missing fields with defaults', () => {
+ const result = hydrateAppearance({ colors: { skin: '#abc123' } });
+ expect(result.accessories).toEqual([]);
+ expect(result.morphs).toEqual({});
+ expect(result.hidden).toEqual([]);
+ expect(result.colors).toEqual({ skin: '#abc123' });
+ });
+
+ it('round-trips a full appearance', () => {
+ const raw = {
+ accessories: ['hat-01'],
+ morphs: { browDownLeft: 0.5 },
+ colors: { hair: '#0e0e0e' },
+ hidden: ['outfit'],
+ };
+ expect(hydrateAppearance(raw)).toEqual(raw);
+ });
+
+ it('copies arrays — mutations do not affect the source', () => {
+ const raw = { accessories: ['hat-01'], morphs: {}, colors: {}, hidden: [] };
+ const result = hydrateAppearance(raw);
+ result.accessories.push('mutated');
+ expect(raw.accessories).toHaveLength(1);
+ });
+});
+
+// ── cloneAppearance ───────────────────────────────────────────────────────────
+
+describe('cloneAppearance', () => {
+ it('produces an identical but distinct object', () => {
+ const a = { accessories: ['hat-01'], morphs: { jawOpen: 0.1 }, colors: { skin: '#fff' }, hidden: ['glasses'] };
+ const b = cloneAppearance(a);
+ expect(b).toEqual(a);
+ expect(b).not.toBe(a);
+ });
+
+ it('accessories mutation does not affect clone source', () => {
+ const a = { accessories: ['hat-01'], morphs: {}, colors: {}, hidden: [] };
+ const b = cloneAppearance(a);
+ b.accessories.push('new');
+ expect(a.accessories).toHaveLength(1);
+ });
+
+ it('morphs mutation does not affect clone source', () => {
+ const a = { accessories: [], morphs: { jawOpen: 0.5 }, colors: {}, hidden: [] };
+ const b = cloneAppearance(a);
+ b.morphs.extra = 1;
+ expect(a.morphs.extra).toBeUndefined();
+ });
+});
+
+// ── appearanceEqual ───────────────────────────────────────────────────────────
+
+describe('appearanceEqual', () => {
+ it('empty appearances are equal', () => {
+ const a = { accessories: [], morphs: {}, colors: {}, hidden: [] };
+ const b = { accessories: [], morphs: {}, colors: {}, hidden: [] };
+ expect(appearanceEqual(a, b)).toBe(true);
+ });
+
+ it('identical full appearances are equal', () => {
+ const a = { accessories: ['hat-01'], morphs: { jawOpen: 0.3 }, colors: { skin: '#fff' }, hidden: ['outfit'] };
+ expect(appearanceEqual(a, cloneAppearance(a))).toBe(true);
+ });
+
+ it('appearances with different accessories are not equal', () => {
+ const a = { accessories: ['hat-01'], morphs: {}, colors: {}, hidden: [] };
+ const b = { accessories: ['hat-02'], morphs: {}, colors: {}, hidden: [] };
+ expect(appearanceEqual(a, b)).toBe(false);
+ });
+
+ it('appearances with different colors are not equal', () => {
+ const a = { accessories: [], morphs: {}, colors: { skin: '#fff' }, hidden: [] };
+ const b = { accessories: [], morphs: {}, colors: { skin: '#000' }, hidden: [] };
+ expect(appearanceEqual(a, b)).toBe(false);
+ });
+});
+
+// ── parseEditId ───────────────────────────────────────────────────────────────
+
+describe('parseEditId', () => {
+ it('returns null when no edit param', () => {
+ expect(parseEditId(new URLSearchParams(''))).toBeNull();
+ });
+
+ it('returns null when edit param is empty', () => {
+ expect(parseEditId(new URLSearchParams('edit='))).toBeNull();
+ });
+
+ it('returns null when edit param is whitespace', () => {
+ expect(parseEditId(new URLSearchParams('edit= '))).toBeNull();
+ });
+
+ it('returns the ID when edit param is present', () => {
+ const params = new URLSearchParams('edit=abc-123-def');
+ expect(parseEditId(params)).toBe('abc-123-def');
+ });
+
+ it('trims whitespace from the ID', () => {
+ const params = new URLSearchParams('edit= abc-123 ');
+ expect(parseEditId(params)).toBe('abc-123');
+ });
+
+ it('accepts a raw query string', () => {
+ expect(parseEditId('?edit=my-id')).toBe('my-id');
+ });
+});
+
+// ── draft storage ─────────────────────────────────────────────────────────────
+
+function makeStorage(initial = {}) {
+ const store = { ...initial };
+ return {
+ getItem: (k) => store[k] ?? null,
+ setItem: (k, v) => { store[k] = v; },
+ removeItem: (k) => { delete store[k]; },
+ _store: store,
+ };
+}
+
+describe('writeDraft / readDraft / clearDraft', () => {
+ it('writes and reads back a draft', () => {
+ const storage = makeStorage();
+ const appearance = { accessories: ['hat-01'], morphs: {}, colors: { skin: '#fff' }, hidden: [] };
+ writeDraft(storage, appearance, 'My Avatar');
+ const draft = readDraft(storage);
+ expect(draft).not.toBeNull();
+ expect(draft.appearance).toEqual(appearance);
+ expect(draft.name).toBe('My Avatar');
+ expect(typeof draft.ts).toBe('number');
+ });
+
+ it('clearDraft removes the entry', () => {
+ const storage = makeStorage();
+ writeDraft(storage, { accessories: [] }, 'test');
+ clearDraft(storage);
+ expect(readDraft(storage)).toBeNull();
+ });
+
+ it('returns null for missing key', () => {
+ expect(readDraft(makeStorage())).toBeNull();
+ });
+
+ it('returns null and removes expired drafts', () => {
+ const storage = makeStorage();
+ const oldTs = Date.now() - DRAFT_MAX_AGE_MS - 1000;
+ storage.setItem(DRAFT_KEY, JSON.stringify({ appearance: {}, name: 'x', ts: oldTs }));
+ expect(readDraft(storage)).toBeNull();
+ expect(storage._store[DRAFT_KEY]).toBeUndefined();
+ });
+
+ it('returns null for malformed JSON', () => {
+ const storage = makeStorage({ [DRAFT_KEY]: 'not-json{{{' });
+ expect(readDraft(storage)).toBeNull();
+ });
+
+ it('returns null for draft without ts field', () => {
+ const storage = makeStorage({ [DRAFT_KEY]: JSON.stringify({ appearance: {} }) });
+ expect(readDraft(storage)).toBeNull();
+ });
+
+ it('allows null appearance in the draft (collapseAppearance returns null for empty)', () => {
+ const storage = makeStorage();
+ writeDraft(storage, null, 'Empty');
+ const draft = readDraft(storage);
+ expect(draft).not.toBeNull();
+ expect(draft.appearance).toBeNull();
+ });
+});
diff --git a/tests/ibm-design-system.test.js b/tests/ibm-design-system.test.js
new file mode 100644
index 000000000..83a08c491
--- /dev/null
+++ b/tests/ibm-design-system.test.js
@@ -0,0 +1,137 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync, existsSync, readdirSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, '..');
+const ibmCssPath = resolve(repoRoot, 'public/ibm.css');
+const ibmPagesDir = resolve(repoRoot, 'pages/ibm');
+
+/**
+ * Guards the three.ws × IBM design system (public/ibm.css).
+ *
+ * WHY THIS EXISTS
+ * ---------------
+ * Every /ibm page used to carry its own :root with the same IBM Carbon colors
+ * spelled eight different ways — that drift is why the pages looked like eight
+ * sites. We unified them onto one shared stylesheet. With ~20 agents editing
+ * this tree, this test is the latch that keeps it unified: it fails the moment
+ * a page stops linking the system, re-introduces local design tokens, or
+ * references a token the system doesn't define.
+ */
+
+const ibmCss = existsSync(ibmCssPath) ? readFileSync(ibmCssPath, 'utf8') : '';
+
+// Tokens that are intentionally set per-element (inline style=) or in JS, never
+// globally in :root. Referencing these without a global definition is correct.
+const DYNAMIC_TOKENS = new Set(['col', 'pct', 'dot-color', 'card-bg', 'vborder']);
+
+// Names every legacy page relies on; deleting any of these aliases would break
+// pages that still say var(--up) / var(--ibm) etc.
+const REQUIRED_ALIASES = [
+ 'bg', 'panel', 'panel-solid', 'panel-2', 'panel2', 'border', 'border-hi',
+ 'text', 'ink', 'muted', 'faint', 'ibm', 'ibm-light', 'ibm-dim',
+ 'up', 'down', 'green', 'allow', 'block', 'warn', 'review', 'amber',
+ 'radius', 'shadow', 'mono', 'font',
+];
+
+const CANONICAL_TOKENS = [
+ 'ibm-bg', 'ibm-panel', 'ibm-border', 'ibm-text', 'ibm-muted',
+ 'ibm-blue', 'ibm-blue-light', 'ibm-green', 'ibm-red', 'ibm-amber',
+];
+
+function definedTokens(css) {
+ const out = new Set();
+ for (const m of css.matchAll(/(--[a-z0-9-]+)\s*:/g)) out.add(m[1].slice(2));
+ return out;
+}
+
+function ibmPages() {
+ if (!existsSync(ibmPagesDir)) return [];
+ return readdirSync(ibmPagesDir)
+ .filter((f) => f.endsWith('.html'))
+ .map((f) => ({ name: f, html: readFileSync(resolve(ibmPagesDir, f), 'utf8') }));
+}
+
+describe('IBM design system — public/ibm.css', () => {
+ it('the shared stylesheet exists', () => {
+ expect(existsSync(ibmCssPath), 'public/ibm.css must exist').toBe(true);
+ });
+
+ it('defines the canonical IBM Carbon tokens', () => {
+ const defs = definedTokens(ibmCss);
+ for (const t of CANONICAL_TOKENS) {
+ expect(defs.has(t), `ibm.css must define --${t}`).toBe(true);
+ }
+ });
+
+ it('keeps the back-compat aliases the pages depend on', () => {
+ const defs = definedTokens(ibmCss);
+ for (const a of REQUIRED_ALIASES) {
+ expect(defs.has(a), `ibm.css must alias --${a} (a page still uses it)`).toBe(true);
+ }
+ });
+
+ it('uses the real IBM Carbon palette', () => {
+ expect(ibmCss).toMatch(/#0f62fe/i); // Blue 60
+ expect(ibmCss).toMatch(/#42be65/i); // Green 50
+ expect(ibmCss).toMatch(/#fa4d56/i); // Red 50
+ expect(ibmCss).toMatch(/#f1c21b/i); // Yellow 30
+ });
+
+ it('ships the shared state + a11y primitives', () => {
+ // the fix for "blank panel / spinner-forever on 503" lives here
+ expect(ibmCss).toContain('.ibm-state');
+ expect(ibmCss).toContain('.ibm-skeleton');
+ expect(ibmCss).toContain('.ibm-spinner');
+ expect(ibmCss).toContain(':focus-visible');
+ expect(ibmCss).toContain('prefers-reduced-motion');
+ });
+});
+
+describe('IBM design system — page conformance', () => {
+ const pages = ibmPages();
+
+ it('there are /ibm pages to check', () => {
+ expect(pages.length).toBeGreaterThan(0);
+ });
+
+ for (const { name, html } of pages) {
+ describe(name, () => {
+ it('links the shared design system', () => {
+ expect(
+ /href="\/ibm\.css"/.test(html),
+ `${name} must <link> /ibm.css`,
+ ).toBe(true);
+ });
+
+ it('does not re-define design tokens in a local :root', () => {
+ // A local :root means the page is drifting away from the system again.
+ const rootBlocks = html.match(/:root\s*\{[^}]*\}/g) || [];
+ const offenders = rootBlocks.filter((b) => /--[a-z]/.test(b));
+ expect(
+ offenders.length,
+ `${name} defines tokens in a local :root — move them to public/ibm.css`,
+ ).toBe(0);
+ });
+
+ it('only references tokens the system defines (or dynamic/inline ones)', () => {
+ const defs = definedTokens(ibmCss);
+ const undefinedRefs = new Set();
+ // match var(--token ...) and capture whether a fallback (comma) follows
+ for (const m of html.matchAll(/var\(\s*(--[a-z0-9-]+)\s*(,)?/g)) {
+ const token = m[1].slice(2);
+ const hasFallback = Boolean(m[2]);
+ if (hasFallback) continue; // var(--x, fallback) is always safe
+ if (defs.has(token) || DYNAMIC_TOKENS.has(token)) continue;
+ undefinedRefs.add(token);
+ }
+ expect(
+ [...undefinedRefs],
+ `${name} references undefined token(s); define them in public/ibm.css or give a var() fallback`,
+ ).toEqual([]);
+ });
+ });
+ }
+});
diff --git a/tests/src/animation-canonical-support.test.js b/tests/src/animation-canonical-support.test.js
new file mode 100644
index 000000000..44f252cfa
--- /dev/null
+++ b/tests/src/animation-canonical-support.test.js
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest';
+import { AnimationManager } from '../../src/animation-manager.js';
+import { CANONICAL_BONES } from '../../src/glb-canonicalize.js';
+
+// AnimationManager.attach() builds a three AnimationMixer over the model but
+// only ever reads `.traverse`, `.isSkinnedMesh`, and `.name` for the canonical
+// support check — so a lightweight fake tree exercises the logic without
+// loading real GLB assets.
+function fakeModel(nodes) {
+ const all = [{ name: 'root' }, ...nodes];
+ return {
+ name: 'root',
+ traverse(cb) {
+ for (const n of all) cb(n);
+ },
+ };
+}
+
+function boneNodes(names, { skinned = true } = {}) {
+ const nodes = names.map((name) => ({ name }));
+ if (skinned) nodes.push({ name: 'Body', isSkinnedMesh: true });
+ return nodes;
+}
+
+describe('AnimationManager.supportsCanonicalClips', () => {
+ it('is false before any model is attached', () => {
+ const mgr = new AnimationManager();
+ expect(mgr.supportsCanonicalClips()).toBe(false);
+ });
+
+ it('is true for a skinned humanoid matching the canonical rig', () => {
+ const mgr = new AnimationManager();
+ mgr.attach(fakeModel(boneNodes(CANONICAL_BONES.slice())));
+ expect(mgr.supportsCanonicalClips()).toBe(true);
+ });
+
+ it('is true for a Mixamo-prefixed humanoid (names canonicalize)', () => {
+ const mgr = new AnimationManager();
+ const mixamo = CANONICAL_BONES.slice(0, 12).map((b) => `mixamorig:${b}`);
+ mgr.attach(fakeModel(boneNodes(mixamo)));
+ expect(mgr.supportsCanonicalClips()).toBe(true);
+ });
+
+ it('is false for a static mesh with no skeleton', () => {
+ const mgr = new AnimationManager();
+ // Canonical bone *names* present, but nothing is a SkinnedMesh.
+ mgr.attach(fakeModel(boneNodes(CANONICAL_BONES.slice(), { skinned: false })));
+ expect(mgr.supportsCanonicalClips()).toBe(false);
+ });
+
+ it('is false for a skinned non-humanoid rig (few canonical bones)', () => {
+ const mgr = new AnimationManager();
+ mgr.attach(fakeModel(boneNodes(['tail_01', 'tail_02', 'wing_L', 'wing_R', 'jaw'])));
+ expect(mgr.supportsCanonicalClips()).toBe(false);
+ });
+
+ it('resets to false after detach', () => {
+ const mgr = new AnimationManager();
+ mgr.attach(fakeModel(boneNodes(CANONICAL_BONES.slice())));
+ expect(mgr.supportsCanonicalClips()).toBe(true);
+ mgr.detach();
+ expect(mgr.supportsCanonicalClips()).toBe(false);
+ });
+});