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.

33.6 KB
Raw Blame
// /gestures: the agent gesture vocabulary, previewed live.
//
// Three things are on this page, all of them derived rather than restated:
//
//   • the slot grid, from SLOTS + DEFAULT_ANIMATION_MAP (src/runtime/animation-slots.js)
//   • the hint table, from /agent-hints.json (generated by scripts/build-agent-hints.mjs
//     out of the shipped skill definitions, so the attribution cannot go stale)
//   • the /walk gesture layers, from GESTURES (src/animation-state-machine.js)
//
// The 3D preview reuses the gallery's shared engine: one renderer, one avatar,
// moved into the stage on demand. Nothing 3D loads until the first gesture is
// played, so the page paints without a GL context.

import { SLOTS, DEFAULT_ANIMATION_MAP, HINT_ALIASES } from './runtime/animation-slots.js';
import { GESTURES, GESTURE_NAMES } from './animation-state-machine.js';
import { curate, CATEGORIES } from './animation-presets.js';
import {
	REGIONS,
	REGION_LABELS,
	describe,
	energyBand,
	similarTo,
	slotFit,
} from './runtime/motion-signature.js';

const MANIFEST_URL = '/animations/manifest.json';
const HINTS_URL = '/agent-hints.json';
const SIGNATURES_URL = '/animations/signatures.json';
const THUMB_BASE = '/animations/thumbs';

/** What each slot means, in one line. Prose, not derivable from the map. */
const SLOT_NOTES = {
	idle: 'The resting loop. Always playing underneath everything else.',
	wave: 'Greeting, and the first gesture most agents ever play.',
	nod: 'Acknowledging. Fired when a model finishes loading.',
	shake: 'Refusing. The only baked head-shake clip in the library.',
	think: 'Reasoning. Fired while a skill or a load is in flight.',
	celebrate: 'A win: a clean validation, a settled payment, a launch.',
	concern: 'Something failed. Paired with a downward gaze.',
	bow: 'Thanks. The one slot with no dedicated clip yet.',
	point: 'Deictic: referring to a thing on screen. Also the generic action gesture.',
	shrug: 'Uncertainty. Overlays locomotion on /walk, so an avatar can shrug mid-stride.',
	fidget: 'Idle restlessness for a long wait.',
	dance: 'Celebration with the whole body. The club stage books these by name.',
	inspect: 'Reading data. The most-declared hint in the skill catalog.',
	present: 'Showing a result off.',
	sign: 'Authorizing a wallet signature.',
	curiosity: 'Scanning, looking around, alert.',
	patience: 'Waiting on long-running work.',
	manipulate: 'Handling a scene object.',
	conjure: 'Creating something from nothing.',
};

/** Slots whose clip is an approximation rather than a match. */
const APPROXIMATE = new Set(['bow']);

const $ = (sel, root = document) => root.querySelector(sel);
const el = (role, root = document) => root.querySelector(`[data-role="${role}"]`);

const state = {
	manifest: [],
	byName: new Map(),
	hints: null,
	signatures: null, // { version, count, clips: { name: signature } }
	slot: null,
	clip: null, // the clip currently staged (default or override)
	preview: null, // lazily imported AnimationLivePreview
	paused: false,
	agents: null, // null = not fetched yet, [] = signed out or no agents
	agentsLoading: false,
	atlasFilter: 'all',
};

/** The measured signature for a clip, or null before the index loads. */
const sigFor = (clip) => state.signatures?.clips?.[clip] || null;

/* ── data ──────────────────────────────────────────────────────────────── */

// The gesture grid sets aria-busy before each of these loads. Without a
// deadline a stalled CDN left the grid busy with no error and no content, so
// every manifest/signature/hint fetch carries one and the catch below paints
// the designed error box instead.
async function fetchJson(url, { timeout = 8000 } = {}) {
	let res;
	try {
		res = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeout) });
	} catch (err) {
		// These messages are printed verbatim into the page's error boxes, so a
		// deadline reads as a sentence rather than the platform's "signal timed out".
		if (err?.name === 'TimeoutError') throw new Error(`${url} did not answer within ${timeout / 1000}s`, { cause: err });
		throw err;
	}
	if (!res.ok) throw new Error(`${url} responded ${res.status}`);
	return res.json();
}

async function loadManifest() {
	const grid = el('grid');
	const errorBox = el('grid-error');
	grid.setAttribute('aria-busy', 'true');
	errorBox.hidden = true;
	try {
		const manifest = await fetchJson(MANIFEST_URL);
		state.manifest = Array.isArray(manifest) ? manifest : [];
		state.byName = new Map(state.manifest.map((c) => [c.name, c]));
		renderGrid();
		renderOverrideOptions();
		renderStats();
		applyDeepLink();
	} catch (err) {
		grid.innerHTML = '';
		grid.setAttribute('aria-busy', 'false');
		errorBox.hidden = false;
		el('grid-error-detail').textContent = err?.message || String(err);
	}
}

/**
 * The measured motion index (public/animations/signatures.json, generated by
 * scripts/build-motion-signatures.mjs). Every surface that shows a fingerprint
 * degrades to nothing if this is missing, so a stale deploy loses the extra
 * detail rather than the page.
 */
async function loadSignatures() {
	try {
		state.signatures = await fetchJson(SIGNATURES_URL);
	} catch (err) {
		el('atlas-error').hidden = false;
		el('atlas-error-detail').textContent = err?.message || String(err);
		return;
	}
	renderGrid();
	renderAtlas();
	renderStats();
	if (state.slot) renderOverride();
}

async function loadHints() {
	const host = el('hints');
	try {
		state.hints = await fetchJson(HINTS_URL);
		renderHints();
		renderStats();
	} catch (err) {
		// The hint table is supporting detail: the vocabulary above it still works,
		// so degrade to a readable note instead of an error state for the page.
		host.innerHTML = `<div class="gv-hints-loading">The skill map did not load (${escapeHtml(
			err?.message || String(err),
		)}). Every hint is also listed in <a href="/docs/animations">docs/animations</a>.</div>`;
	}
}

/* ── render ────────────────────────────────────────────────────────────── */

function escapeHtml(s) {
	return String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
}

function renderStats() {
	el('stat-slots').textContent = String(SLOTS.length);
	el('stat-clips').textContent = String(state.manifest.length || '-');
	el('stat-hints').textContent = String(state.hints?.hints?.length ?? '-');
	el('stat-skills').textContent = String(state.hints?.total_skills ?? '-');
}

/* ── motion fingerprints ───────────────────────────────────────────────── */

/**
 * The stacked region bar: what share of a clip's movement each part of the
 * body accounts for, measured from its keyframes. Segments under 4% are still
 * rendered (a hairline is honest about a region that barely moves) but carry no
 * label, so the bar stays legible at card size.
 */
function regionBarHtml(sig, { compact = true } = {}) {
	const segments = REGIONS.map((r) => {
		const pct = Math.round((sig.regions[r] || 0) * 1000) / 10;
		return `<span class="gv-fp-seg" data-region="${r}" style="width:${pct}%" title="${REGION_LABELS[r]}: ${pct}%"></span>`;
	}).join('');
	const bar = `<span class="gv-fp-bar" role="img" aria-label="${escapeHtml(
		REGIONS.map((r) => `${REGION_LABELS[r]} ${Math.round((sig.regions[r] || 0) * 100)}%`).join(', '),
	)}">${segments}</span>`;
	if (compact) return bar;
	const legend = REGIONS.map(
		(r) =>
			`<span class="gv-fp-key"><i data-region="${r}"></i>${REGION_LABELS[r]} <b>${Math.round(
				(sig.regions[r] || 0) * 100,
			)}%</b></span>`,
	).join('');
	return `${bar}<span class="gv-fp-legend">${legend}</span>`;
}

/** The short badges that call out a clip's playback hazards and abilities. */
function motionBadges(sig) {
	const out = [];
	if (sig.static) out.push(['warn', 'held pose', 'A single frame. Nothing moves.']);
	if (sig.overlay) out.push(['ok', 'overlay', 'Reads correctly when the hips and legs are stripped for an upper-body overlay.']);
	if (!sig.anchored) out.push(['warn', `drifts ${sig.travel.toFixed(2)} m`, 'The root ends away from where it started, so the avatar slides and snaps back.']);
	if (sig.declaredLoop && !sig.loopClean) out.push(['warn', 'seam', 'Declared as a loop, but the last frame does not meet the first.']);
	return out
		.map(
			([level, label, why]) =>
				`<span class="gv-mbadge is-${level}" title="${escapeHtml(why)}">${escapeHtml(label)}</span>`,
		)
		.join('');
}

/** Card-sized fingerprint: the bar plus the two numbers that matter most. */
function fingerprintHtml(clip) {
	const sig = sigFor(clip);
	if (!sig) return '';
	const meta = [energyBand(sig)];
	if (sig.tempo) meta.push(`${sig.tempo} BPM`);
	meta.push(`${sig.duration}s`);
	return `
		<span class="gv-fp">
			${regionBarHtml(sig)}
			<span class="gv-fp-meta">${escapeHtml(meta.join(' · '))}</span>
		</span>`;
}

function cardHtml(slot) {
	const clip = DEFAULT_ANIMATION_MAP[slot];
	const def = state.byName.get(clip);
	const label = def?.label || clip;
	const icon = def?.icon || '🎞️';
	const badge = APPROXIMATE.has(slot)
		? '<span class="gv-badge gv-badge--warn" title="No dedicated clip for this slot yet">approx</span>'
		: def?.loop
			? '<span class="gv-badge" title="This clip loops">loop</span>'
			: '';
	// The note is rendered, not hidden behind a `title` tooltip: a browser
	// tooltip needs a second of hover, never appears on touch, and is the
	// difference between "what does `conjure` mean" being answered and not.
	return `
		<button type="button" class="gv-card" role="listitem" data-slot="${escapeHtml(slot)}"
			aria-current="false">
			<span class="gv-card-thumb">
				<span class="gv-card-thumb-fallback" aria-hidden="true">${icon}</span>
				<img src="${THUMB_BASE}/${encodeURIComponent(clip)}.webp" alt=""
					loading="lazy" decoding="async" width="480" height="480" />
				${badge}
			</span>
			<span class="gv-card-body">
				<span class="gv-card-slot">${escapeHtml(slot)}</span>
				<span class="gv-card-clip">${escapeHtml(label)}</span>
				<span class="gv-card-note">${escapeHtml(SLOT_NOTES[slot] || '')}</span>
				${fingerprintHtml(clip)}
			</span>
		</button>`;
}

function renderGrid() {
	const grid = el('grid');
	grid.innerHTML = SLOTS.map(cardHtml).join('');
	grid.setAttribute('aria-busy', 'false');
	// The signature index arrives after the first paint, so the grid re-renders.
	// Restore the selection rather than silently dropping it.
	if (state.slot) {
		for (const card of grid.querySelectorAll('.gv-card[data-slot]')) {
			card.setAttribute('aria-current', String(card.dataset.slot === state.slot));
		}
	}
	// The clip's emoji stands in until its poster paints, then gets out of the
	// way: leaving both would stamp an emoji over the avatar. A poster that never
	// loads keeps the emoji and drops the empty image box.
	for (const img of grid.querySelectorAll('.gv-card-thumb img')) {
		const fallback = img.previousElementSibling;
		const settle = () => fallback?.remove();
		if (img.complete && img.naturalWidth > 0) settle();
		else {
			img.addEventListener('load', settle, { once: true });
			img.addEventListener('error', () => img.remove(), { once: true });
		}
	}
}

function renderHints() {
	const rows = state.hints?.hints || [];
	const head = `
		<div class="gv-row gv-row--head">
			<span>Hint</span><span>Slot</span><span>Clip</span><span>Skills</span>
		</div>`;
	const body = rows
		.map((row) => {
			const alias = HINT_ALIASES[row.hint] ? ' <span class="gv-arrow">(alias)</span>' : '';
			const skills = row.skills
				.map((s) => `<code>${escapeHtml(s)}</code>`)
				.join('');
			return `
				<div class="gv-row">
					<span class="gv-mono">${escapeHtml(row.hint)}${alias}</span>
					<span class="gv-mono">${escapeHtml(row.slot)}</span>
					<span class="gv-mono">${escapeHtml(row.clip)}</span>
					<span class="gv-count">${row.skills.length}</span>
				</div>
				<details>
					<summary>Show the ${row.skills.length} skill${row.skills.length === 1 ? ' that declares' : 's that declare'} <code>${escapeHtml(row.hint)}</code></summary>
					<div class="gv-hints-skills">${skills}</div>
				</details>`;
		})
		.join('');
	el('hints').innerHTML = head + body;
}

function renderLayers() {
	const head = `
		<div class="gv-row gv-row--head">
			<span>Gesture</span><span>Clip</span><span>Layer</span><span>Hold</span>
		</div>`;
	const body = GESTURE_NAMES.map((name) => {
		const g = GESTURES[name];
		return `
			<div class="gv-row">
				<span class="gv-mono">${escapeHtml(name)}</span>
				<span class="gv-mono">${escapeHtml(g.clip)}</span>
				<span class="gv-mono">${g.layer}</span>
				<span class="gv-count">${g.loop ? 'held' : 'one-shot'}</span>
			</div>`;
	}).join('');
	el('layers').innerHTML = head + body;
}

function renderOverrideOptions() {
	const select = el('override-select');
	const { groups } = curate(state.manifest);
	const order = new Map(CATEGORIES.map((c, i) => [c.key, i]));
	const sorted = [...groups].sort((a, b) => (order.get(a.key) ?? 99) - (order.get(b.key) ?? 99));
	select.innerHTML = sorted
		.map(
			(g) => `<optgroup label="${escapeHtml(`${g.icon} ${g.label}`)}">${g.items
				.map(
					(item) =>
						`<option value="${escapeHtml(item.name)}">${escapeHtml(item.label || item.name)}</option>`,
				)
				.join('')}</optgroup>`,
		)
		.join('');
}

/**
 * The full readout for the staged clip: the sentence, the region breakdown, the
 * numbers behind it, and the badges. This is the panel that turns "that gesture
 * looks wrong" into "68% of that clip is below the waist".
 */
function renderStageSignature() {
	const box = el('signature');
	const sig = sigFor(state.clip);
	if (!state.clip || !sig) {
		box.hidden = true;
		return;
	}
	box.hidden = false;
	el('signature-sentence').textContent = describe(sig);
	el('signature-bar').innerHTML = regionBarHtml(sig, { compact: false });
	el('signature-badges').innerHTML = motionBadges(sig);

	const stats = [
		['Energy', `${energyBand(sig)} (${sig.energy.toFixed(2)})`, 'Mean joint rotation speed, on a saturating 0 to 1 scale.'],
		['Beat', sig.tempo ? `${sig.tempo} BPM` : 'none', 'Dominant period of the motion envelope. One-shots have no beat.'],
		['Lead', REGION_LABELS[sig.lead], 'The region carrying the most movement.'],
		['Travel', `${sig.travel.toFixed(2)} m`, 'How far the root ends from where it started.'],
		['Balance', sig.balance.toFixed(2), 'Left/right evenness. 1.00 is mirrored, 0.00 is entirely one-sided.'],
		['Loop seam', sig.loopClean ? 'clean' : `${sig.seam.toFixed(2)} rad`, 'Pose distance between the last frame and the first.'],
	];
	el('signature-stats').innerHTML = stats
		.map(
			([label, value, why]) =>
				`<div class="gv-sig-stat" title="${escapeHtml(why)}"><dt>${escapeHtml(label)}</dt><dd>${escapeHtml(value)}</dd></div>`,
		)
		.join('');
}

/**
 * Whether the staged clip can do the job the staged slot is for, and what else
 * moves like it. Both are measured, so the advice changes when a clip is
 * rebaked instead of going stale in a comment.
 */
function renderFit() {
	const box = el('fit');
	// Fit is a question about a slot. Browsing the atlas with no slot staged
	// still gets the signature and the neighbours, just not the verdict.
	const fit = state.slot && state.signatures ? slotFit(state.slot, sigFor(state.clip)) : null;
	if (!fit) {
		box.hidden = true;
	} else {
		box.hidden = false;
		box.className = `gv-fit is-${fit.level}`;
		el('fit-text').textContent = fit.message;
	}

	const similarBox = el('similar');
	const matches = state.signatures ? similarTo(state.clip, state.signatures.clips, 5) : [];
	if (!matches.length) {
		similarBox.hidden = true;
		return;
	}
	similarBox.hidden = false;
	el('similar-list').innerHTML = matches
		.map((m) => {
			const label = state.byName.get(m.clip)?.label || m.clip;
			return `<button type="button" class="gv-chip" data-clip="${escapeHtml(m.clip)}"
				title="${escapeHtml(describe(m.signature))}">${escapeHtml(label)}</button>`;
		})
		.join('');
}

function renderOverride() {
	const box = el('override');
	renderStageSignature();
	renderFit();
	highlightAtlas();
	if (!state.slot) {
		box.hidden = true;
		return;
	}
	box.hidden = false;
	el('override-slot').textContent = state.slot;
	el('override-select').value = state.clip;
	const json = JSON.stringify({ edits: { animations: { [state.slot]: state.clip } } }, null, 2);
	$('code', el('override-code')).textContent = json;
	const isDefault = state.clip === DEFAULT_ANIMATION_MAP[state.slot];
	el('override-reset').disabled = isDefault;
	// Hand the staged slot (and its clip, when it is not the default) to the
	// sequencer as a one-step routine. Same wire format /choreograph shares with,
	// so the link is the routine rather than a hint to go rebuild it there.
	const step = isDefault ? `${state.slot}:1.6` : `${state.slot}:1.6@${state.clip}`;
	el('override-sequence').href = `/choreograph?r=${encodeURIComponent(state.slot)}|${step}`;
	renderApply();
}

/* ── the motion atlas ──────────────────────────────────────────────────── */

/**
 * Every clip in the library plotted by two measured axes: how energetic it is,
 * and how much of that energy is above the waist. The result separates the
 * library into the shapes people actually reach for. Calm upper-body gestures
 * gather top-left, explosive full-body dances and runs bottom-right, and the
 * clips that only look similar by name stop looking similar at all.
 *
 * Drawn as inline SVG rather than canvas so every point is a real focusable
 * element with its own label: the atlas is keyboard-navigable and readable by a
 * screen reader, which a canvas scatter plot never is.
 */
const ATLAS = { w: 720, h: 420, pad: 44 };

const ATLAS_FILTERS = [
	{ key: 'all', label: 'Everything', test: () => true },
	{ key: 'overlay', label: 'Overlay-safe', test: (s) => s.overlay },
	{ key: 'anchored', label: 'Stays on the spot', test: (s) => s.anchored },
	{ key: 'loop', label: 'Loops cleanly', test: (s) => s.loopClean },
	{ key: 'flagged', label: 'Needs attention', test: (s) => s.static || (s.declaredLoop && !s.loopClean) },
];

function atlasX(sig) {
	return ATLAS.pad + sig.energy * (ATLAS.w - ATLAS.pad * 2);
}

function atlasY(sig) {
	return ATLAS.h - ATLAS.pad - (sig.upperShare ?? 0) * (ATLAS.h - ATLAS.pad * 2);
}

function renderAtlas() {
	const host = el('atlas');
	if (!state.signatures) return;
	const clips = Object.values(state.signatures.clips);
	const test = (ATLAS_FILTERS.find((f) => f.key === state.atlasFilter) || ATLAS_FILTERS[0]).test;

	const gridLines = [0.25, 0.5, 0.75]
		.map((t) => {
			const x = ATLAS.pad + t * (ATLAS.w - ATLAS.pad * 2);
			const y = ATLAS.h - ATLAS.pad - t * (ATLAS.h - ATLAS.pad * 2);
			return `<line class="gv-atlas-grid" x1="${x}" y1="${ATLAS.pad}" x2="${x}" y2="${ATLAS.h - ATLAS.pad}" />
				<line class="gv-atlas-grid" x1="${ATLAS.pad}" y1="${y}" x2="${ATLAS.w - ATLAS.pad}" y2="${y}" />`;
		})
		.join('');

	const points = clips
		// Draw the quiet clips first so the loud ones are never buried under them.
		.slice()
		.sort((a, b) => a.energy - b.energy)
		.map((sig) => {
			const dim = test(sig) ? '' : ' is-dim';
			const r = 4 + Math.min(6, Math.sqrt(sig.duration) * 1.2);
			const label = `${sig.clip}: ${describe(sig)}`;
			return `<circle class="gv-atlas-dot${dim}" data-clip="${escapeHtml(sig.clip)}"
				data-region="${sig.lead}" cx="${atlasX(sig).toFixed(1)}" cy="${atlasY(sig).toFixed(1)}"
				r="${r.toFixed(1)}" tabindex="0" role="button"
				aria-label="${escapeHtml(label)}"><title>${escapeHtml(label)}</title></circle>`;
		})
		.join('');

	host.innerHTML = `
		<svg viewBox="0 0 ${ATLAS.w} ${ATLAS.h}" class="gv-atlas-svg" role="group"
			aria-label="Every baked clip plotted by measured energy and how much of it is above the waist">
			${gridLines}
			<line class="gv-atlas-axis" x1="${ATLAS.pad}" y1="${ATLAS.h - ATLAS.pad}" x2="${ATLAS.w - ATLAS.pad}" y2="${ATLAS.h - ATLAS.pad}" />
			<line class="gv-atlas-axis" x1="${ATLAS.pad}" y1="${ATLAS.pad}" x2="${ATLAS.pad}" y2="${ATLAS.h - ATLAS.pad}" />
			<text class="gv-atlas-label" x="${ATLAS.w / 2}" y="${ATLAS.h - 10}" text-anchor="middle">Energy: calm to explosive</text>
			<text class="gv-atlas-label" x="${-ATLAS.h / 2}" y="14" text-anchor="middle" transform="rotate(-90)">Motion above the waist</text>
			${points}
		</svg>`;

	el('atlas-count').textContent = `${clips.filter(test).length} of ${clips.length} clips`;
	highlightAtlas();
}

/** Mark the staged clip on the atlas so the map and the stage agree. */
function highlightAtlas() {
	for (const dot of document.querySelectorAll('.gv-atlas-dot')) {
		dot.classList.toggle('is-active', dot.dataset.clip === state.clip);
	}
}

/* ── apply to an agent ─────────────────────────────────────────────────── */

/**
 * The signed-in user's agents. A 401 is the ordinary signed-out case, not an
 * error: the page is public and everything except this panel works without an
 * account. Runs once, lazily, the first time a gesture is selected.
 */
async function loadAgents() {
	if (state.agents !== null || state.agentsLoading) return;
	state.agentsLoading = true;
	try {
		const res = await fetch('/api/agents', {
			credentials: 'include',
			headers: { accept: 'application/json' },
		});
		state.agents = res.ok ? ((await res.json()).agents ?? []) : [];
	} catch {
		state.agents = [];
	} finally {
		state.agentsLoading = false;
		renderApply();
	}
}

function renderApply() {
	const panel = el('apply');
	const signedOut = el('apply-signedout');
	if (!state.slot) {
		panel.hidden = true;
		signedOut.hidden = true;
		return;
	}
	const agents = state.agents;
	if (agents === null) {
		// Still loading: show neither panel rather than flashing the signed-out
		// call to action at a user who is in fact signed in.
		panel.hidden = true;
		signedOut.hidden = true;
		return;
	}
	if (!agents.length) {
		panel.hidden = true;
		signedOut.hidden = false;
		return;
	}
	signedOut.hidden = true;
	panel.hidden = false;

	const select = el('apply-select');
	if (select.dataset.filled !== String(agents.length)) {
		select.dataset.filled = String(agents.length);
		select.innerHTML = agents
			.map((a) => `<option value="${escapeHtml(a.id)}">${escapeHtml(a.name || a.id)}</option>`)
			.join('');
	}
	// Saving the default is a no-op the server would accept; say so instead.
	const isDefault = state.clip === DEFAULT_ANIMATION_MAP[state.slot];
	const save = el('apply-save');
	save.disabled = false;
	save.textContent = isDefault ? 'Clear this override' : 'Save to agent';
}

async function applyToAgent() {
	const save = el('apply-save');
	const status = el('apply-status');
	const agentId = el('apply-select').value;
	const agent = (state.agents || []).find((a) => a.id === agentId);
	if (!agentId || !state.slot) return;

	// Merge over the agent's existing overrides so saving one gesture never
	// drops another. Selecting the platform default removes the entry.
	const current = { ...(agent?.meta?.edits?.animations || {}) };
	if (state.clip === DEFAULT_ANIMATION_MAP[state.slot]) delete current[state.slot];
	else current[state.slot] = state.clip;

	save.disabled = true;
	status.textContent = 'Saving…';
	status.className = 'gv-apply-status';
	try {
		const { apiFetch } = await import('./api.js');
		const res = await apiFetch(`/api/agents/${agentId}/animations`, {
			method: 'PUT',
			headers: { 'content-type': 'application/json' },
			credentials: 'include',
			body: JSON.stringify({ animationSlots: current }),
		});
		if (!res.ok) {
			const body = await res.json().catch(() => ({}));
			throw new Error(body.error_description || body.error || `HTTP ${res.status}`);
		}
		const saved = await res.json();
		// Keep the local copy in step so a second save merges against the truth.
		if (agent) agent.meta = { ...(agent.meta || {}), edits: { ...(agent.meta?.edits || {}), animations: saved.animationSlots || {} } };
		const count = Object.keys(saved.animationSlots || {}).length;
		status.innerHTML = `Saved. <a href="/a/${escapeHtml(agentId)}">Open ${escapeHtml(agent?.name || 'the agent')}</a> to see it, ${count} override${count === 1 ? '' : 's'} in total.`;
		status.className = 'gv-apply-status is-ok';
	} catch (err) {
		status.textContent = `Could not save: ${err.message}`;
		status.className = 'gv-apply-status is-err';
	} finally {
		save.disabled = false;
	}
}

/* ── preview ───────────────────────────────────────────────────────────── */

function setStageState(name, detail = '') {
	el('stage-empty').hidden = name !== 'empty';
	el('stage-loading').hidden = name !== 'loading';
	el('stage-error').hidden = name !== 'error';
	if (name === 'error' && detail) el('stage-error-title').textContent = detail;
}

async function getPreview() {
	if (!state.preview) {
		const mod = await import('./animations-live-preview.js');
		state.preview = mod.getLivePreview();
	}
	return state.preview;
}

/**
 * Stage a clip. `slot` is optional: browsing the motion atlas plays a clip that
 * belongs to no slot, and the stage, the signature panel and the neighbour list
 * all work the same way for it. Only the override and apply controls need a
 * slot, because only they write something.
 */
async function play(slot, clip = DEFAULT_ANIMATION_MAP[slot]) {
	state.slot = slot || null;
	state.clip = clip;
	const def = state.byName.get(clip);
	el('stage-slot').textContent = slot || def?.label || clip;
	el('stage-clip').textContent = slot
		? (def?.label ? `${def.label} · ${clip}` : clip)
		: 'Clip preview, no slot selected';
	const note = el('stage-note');
	note.textContent = SLOT_NOTES[slot] || '';
	note.hidden = !note.textContent;
	if (slot) loadAgents();
	el('stage-status').textContent = slot
		? `Playing ${slot}: ${def?.label || clip}`
		: `Playing ${def?.label || clip}`;
	for (const card of document.querySelectorAll('.gv-card[data-slot]')) {
		card.setAttribute('aria-current', String(card.dataset.slot === slot));
	}
	renderOverride();
	syncUrl();

	if (!def) {
		setStageState('error', `"${clip}" is not in the clip manifest.`);
		return;
	}

	setStageState('loading');
	el('stage-replay').disabled = true;
	el('stage-pause').disabled = true;
	try {
		const preview = await getPreview();
		await preview.play(el('stage'), {
			id: clip,
			source: 'curated',
			url: def.url,
			loop: def.loop !== false,
		});
		// A superseded play() resolves without mounting; only clear the overlay
		// when this call is still the current one.
		if (state.clip !== clip) return;
		setStageState('none');
		state.paused = false;
		el('stage-replay').disabled = false;
		el('stage-pause').disabled = false;
		el('stage-pause').setAttribute('aria-pressed', 'false');
	} catch (err) {
		if (state.clip !== clip) return;
		setStageState('error', err?.message ? `Preview failed: ${err.message}` : undefined);
	}
}

function stop() {
	state.preview?.stop();
	setStageState('empty');
	el('stage-slot').textContent = 'No gesture selected';
	el('stage-clip').innerHTML = '&nbsp;';
	el('stage-replay').disabled = true;
	// Reset the pause toggle: leaving it latched showed a play icon on a stage
	// with nothing to play.
	state.paused = false;
	const pause = el('stage-pause');
	pause.disabled = true;
	pause.setAttribute('aria-pressed', 'false');
	pause.textContent = '❙❙';
	el('stage-note').hidden = true;
	el('override').hidden = true;
	el('apply').hidden = true;
	el('apply-signedout').hidden = true;
	el('signature').hidden = true;
	el('fit').hidden = true;
	el('similar').hidden = true;
	state.slot = null;
	state.clip = null;
	for (const card of document.querySelectorAll('.gv-card[data-slot]')) {
		card.setAttribute('aria-current', 'false');
	}
	highlightAtlas();
	syncUrl();
}

/* ── url state ─────────────────────────────────────────────────────────── */

function syncUrl() {
	const url = new URL(window.location.href);
	if (state.slot) url.searchParams.set('slot', state.slot);
	else url.searchParams.delete('slot');
	// Carry the clip whenever it is not simply the slot's default, and always
	// when there is no slot, so an atlas find is a shareable link too.
	if (state.clip && state.clip !== DEFAULT_ANIMATION_MAP[state.slot]) {
		url.searchParams.set('clip', state.clip);
	} else {
		url.searchParams.delete('clip');
	}
	window.history.replaceState(null, '', url);
}

function applyDeepLink() {
	const params = new URLSearchParams(window.location.search);
	const slot = params.get('slot');
	const clip = params.get('clip');
	if (slot && SLOTS.includes(slot)) {
		play(slot, clip && state.byName.has(clip) ? clip : DEFAULT_ANIMATION_MAP[slot]);
		return;
	}
	if (clip && state.byName.has(clip)) play(null, clip);
}

/* ── events ────────────────────────────────────────────────────────────── */

function cardAt(index) {
	const cards = [...document.querySelectorAll('.gv-card[data-slot]')];
	if (!cards.length) return null;
	const wrapped = ((index % cards.length) + cards.length) % cards.length;
	return cards[wrapped];
}

function columnsInGrid() {
	const grid = el('grid');
	const style = getComputedStyle(grid);
	return Math.max(1, style.gridTemplateColumns.split(' ').filter(Boolean).length);
}

function wire() {
	el('grid').addEventListener('click', (e) => {
		const card = e.target.closest('.gv-card[data-slot]');
		if (card) play(card.dataset.slot);
	});

	// Arrow keys walk the grid; Enter plays. Roving focus, so the browser's own
	// focus ring is the selection indicator.
	el('grid').addEventListener('keydown', (e) => {
		const card = e.target.closest('.gv-card[data-slot]');
		if (!card) return;
		const cards = [...document.querySelectorAll('.gv-card[data-slot]')];
		const i = cards.indexOf(card);
		const cols = columnsInGrid();
		const moves = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: cols, ArrowUp: -cols };
		if (e.key in moves) {
			e.preventDefault();
			cardAt(i + moves[e.key])?.focus();
			return;
		}
		if (e.key === 'Home' || e.key === 'End') {
			e.preventDefault();
			cardAt(e.key === 'Home' ? 0 : cards.length - 1)?.focus();
		}
	});

	document.addEventListener('keydown', (e) => {
		if (e.key === 'Escape' && state.slot) stop();
	});

	// The atlas and the neighbour chips both stage a clip. With a slot selected
	// that is "try this clip in this slot"; with none it is a plain preview.
	const stageClip = (clip) => {
		if (!state.byName.has(clip)) return;
		play(state.slot, clip);
	};
	el('atlas').addEventListener('click', (e) => {
		const dot = e.target.closest('.gv-atlas-dot');
		if (dot) stageClip(dot.dataset.clip);
	});
	el('atlas').addEventListener('keydown', (e) => {
		const dot = e.target.closest?.('.gv-atlas-dot');
		if (!dot || (e.key !== 'Enter' && e.key !== ' ')) return;
		e.preventDefault();
		stageClip(dot.dataset.clip);
	});
	el('atlas-filters').innerHTML = ATLAS_FILTERS.map(
		(f) =>
			`<button type="button" class="gv-pill" data-filter="${f.key}" aria-pressed="${f.key === state.atlasFilter}">${escapeHtml(f.label)}</button>`,
	).join('');
	el('atlas-filters').addEventListener('click', (e) => {
		const pill = e.target.closest('[data-filter]');
		if (!pill) return;
		state.atlasFilter = pill.dataset.filter;
		for (const p of el('atlas-filters').querySelectorAll('[data-filter]')) {
			p.setAttribute('aria-pressed', String(p.dataset.filter === state.atlasFilter));
		}
		renderAtlas();
	});
	el('similar-list').addEventListener('click', (e) => {
		const chip = e.target.closest('[data-clip]');
		if (chip) stageClip(chip.dataset.clip);
	});
	el('atlas-retry').addEventListener('click', () => {
		el('atlas-error').hidden = true;
		loadSignatures();
	});

	el('grid-retry').addEventListener('click', loadManifest);
	el('stage-retry').addEventListener('click', () => {
		if (state.slot) play(state.slot, state.clip);
	});

	el('stage-replay').addEventListener('click', () => {
		if (state.slot) play(state.slot, state.clip);
	});

	el('stage-pause').addEventListener('click', async (e) => {
		const preview = await getPreview();
		state.paused = !state.paused;
		preview.setPaused(state.paused);
		e.currentTarget.setAttribute('aria-pressed', String(state.paused));
		e.currentTarget.textContent = state.paused ? '▶' : '❙❙';
		el('stage-status').textContent = state.paused ? 'Preview paused' : 'Preview playing';
	});

	el('override-select').addEventListener('change', (e) => {
		if (state.slot) play(state.slot, e.target.value);
	});

	el('override-reset').addEventListener('click', () => {
		if (state.slot) play(state.slot, DEFAULT_ANIMATION_MAP[state.slot]);
	});

	el('apply-save').addEventListener('click', applyToAgent);

	const copy = async (e) => {
		const btn = e.currentTarget;
		const text = $('code', el('override-code')).textContent;
		try {
			await navigator.clipboard.writeText(text);
			btn.textContent = 'Copied';
		} catch {
			// Clipboard is permission-gated in some browsers: select the block so
			// the user can copy it by hand instead of silently failing.
			const range = document.createRange();
			range.selectNodeContents(el('override-code'));
			const sel = window.getSelection();
			sel.removeAllRanges();
			sel.addRange(range);
			btn.textContent = 'Selected, press Cmd/Ctrl+C';
		}
		setTimeout(() => {
			btn.textContent = 'Copy JSON';
		}, 1800);
	};
	el('override-copy').addEventListener('click', copy);
	el('override-copy-2').addEventListener('click', copy);

	// Stop burning frames on a hidden tab, without stomping a pause the user
	// chose: state.paused stays the source of truth for the button.
	document.addEventListener('visibilitychange', () => {
		state.preview?.setPaused(document.hidden ? true : state.paused);
	});
}

renderLayers();
wire();
loadManifest();
loadHints();
loadSignatures();