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(sign): sign-language mirror page, grader and MCP tool coverage

nirholas4306296bf457
diff --git a/docs/sign-language.md b/docs/sign-language.md
index bc2e7e075..42e7759e3 100644
--- a/docs/sign-language.md
+++ b/docs/sign-language.md
@@ -201,6 +201,86 @@ const { clip, signed, spelled } = compileUtterance('happy to meet you', { signs:
The package README covers every export, the authoring format, and a runnable Node example: [packages/sign-language](../packages/sign-language/README.md).
+## The sign API
+
+`GET /api/sign` compiles text into a signed utterance on the server and hands back both halves of it: the animation, and the timeline it performs on. No account, no API key, no SDK, and CORS is open, so a browser, a worker, a Unity build, a Python script or an agent can all call it directly.
+
+![The sign API console on three.ws, showing the phrase "happy to meet you" compiled into four timeline blocks with the spelled word broken into its letters](/docs/img/sign-api-console.webp)
+
+The console on [/sign-language](https://three.ws/sign-language#sl-api) is this endpoint, live: it calls the real URL, draws the response, and plays the same utterance on the avatar so you can see that the JSON and the hands agree.
+
+```bash
+curl -s "https://three.ws/api/sign?text=happy+to+meet+you" | jq '.timeline'
+```
+
+```json
+[
+ { "word": "HAPPY", "signed": true, "gloss": "Both flat hands brush up the chest in circles.",
+ "start": 0, "end": 1.46, "letters": null },
+ { "word": "TO", "signed": false, "gloss": null,
+ "start": 1.64, "end": 2.64,
+ "letters": [ { "letter": "T", "start": 1.64, "end": 2.14 },
+ { "letter": "O", "start": 2.14, "end": 2.64 } ] },
+ { "word": "MEET", "signed": true, "gloss": "Two upright index fingers come together.",
+ "start": 2.82, "end": 3.98, "letters": null },
+ { "word": "YOU", "signed": true, "gloss": "Index finger points at the person addressed.",
+ "start": 4.16, "end": 5.0, "letters": null }
+]
+```
+
+### Parameters
+
+| Parameter | Values | What it does |
+|---|---|---|
+| `text` | up to 600 characters | The text to sign. A-Z, 0-9 and spaces are performed; punctuation is dropped. Required to compile |
+| `hand` | `right` (default), `left` | Dominant hand. The whole sign mirrors, not just the hand |
+| `speed` | `0.25`-`1.5`, default `1` | Below 1 is a signer taking longer over the same signs, not a clip played back slowly |
+| `max_seconds` | `1`-`60`, default `45` | Cap the utterance. Longer text truncates at a word boundary and comes back with `truncated: true` |
+| `format` | `clip` (default), `timeline` | `timeline` omits the clip: a few hundred bytes instead of tens of kilobytes, when all you need is what would be signed |
+
+`POST` takes the same fields as a JSON body (`max_seconds` may also be written `maxSeconds`).
+
+### The response
+
+| Field | What it is |
+|---|---|
+| `duration` | Seconds the whole utterance takes |
+| `words`, `signed`, `spelled` | The utterance as words, and which of them had a real sign vs were fingerspelled |
+| `timeline` | One entry per word in performance order: `start`, `end`, `signed`, the `gloss` of the sign, and for a spelled word the `start`/`end` of every letter |
+| `clip` | A three.js `AnimationClip` document keyed to the canonical humanoid skeleton, rotation lanes only |
+| `truncated` | Whether `max_seconds` cut the utterance short |
+| `viewer` | A `/sign-language?say=…` link that performs the same text on a live avatar |
+
+`GET /api/sign` with no `text` returns the descriptor: every parameter, and the whole vocabulary with each sign's description. That is the call to make first if you want to know what will sign and what will spell.
+
+### Playing what comes back
+
+The clip is the same document the animation library ships, so it retargets onto any rigged humanoid through [`@three-ws/retarget`](https://www.npmjs.com/package/@three-ws/retarget) and plays like any other clip:
+
+```js
+const res = await fetch('https://three.ws/api/sign?text=hello+friend');
+const { clip, timeline, duration } = await res.json();
+
+const action = mixer.clipAction(THREE.AnimationClip.parse(retargetClip(clip, rig)));
+action.setLoop(THREE.LoopOnce, 1).play();
+
+// Caption it in sync: the timeline is in the same seconds as the clip.
+const at = (t) => timeline.find((s) => t >= s.start && t < s.end)?.word ?? '';
+```
+
+Responses are deterministic (the same text, hand and speed always compile to the same clip), so they cache hard at the edge and are cheap to call repeatedly. It is rate-limited per IP; a 429 comes back with the standard headers.
+
+### From an agent
+
+The same compiler is on the [three.ws MCP server](https://three.ws/mcp-tools) as two free tools:
+
+| Tool | What it does |
+|---|---|
+| `list_sign_vocabulary` | Every word with a real sign, and what the sign does. Optional `search` filter |
+| `sign_text` | Compiles text and returns the timeline, a link that plays it, and the clip URL. Pass `include_clip: true` to inline the clip document itself |
+
+`sign_text` withholds the clip by default on purpose: a sentence is tens of thousands of numbers, which is worth fetching over HTTP and worthless inside a chat transcript.
+
## Reading signing: the recognition API
`/api/asl-recognition` is the endpoint behind the webcam input. No API key, no account; it is rate-limited per IP.
diff --git a/pages/gestures.html b/pages/gestures.html
index 32cd6c5c4..028fb5eb7 100644
--- a/pages/gestures.html
+++ b/pages/gestures.html
@@ -113,6 +113,30 @@
<p class="gv-sr-status" data-role="stage-status" role="status" aria-live="polite"></p>
</div>
+ <!-- Motion signature: measured from the clip's own keyframes by
+ scripts/build-motion-signatures.mjs, not authored by hand. -->
+ <div class="gv-sig" data-role="signature" hidden>
+ <h2 class="gv-sig-title">What this clip actually does</h2>
+ <p class="gv-sig-sentence" data-role="signature-sentence"></p>
+ <div class="gv-fp gv-fp--full" data-role="signature-bar"></div>
+ <dl class="gv-sig-stats" data-role="signature-stats"></dl>
+ <div class="gv-sig-badges" data-role="signature-badges"></div>
+ </div>
+
+ <!-- The verdict: can this clip do the job this slot is for. -->
+ <div class="gv-fit" data-role="fit" hidden>
+ <span class="gv-fit-icon" aria-hidden="true"></span>
+ <p data-role="fit-text"></p>
+ </div>
+
+ <div class="gv-similar" data-role="similar" hidden>
+ <h2 class="gv-similar-title">Moves like this one</h2>
+ <p class="gv-similar-lede">
+ Nearest clips in the measured motion space, not by name.
+ </p>
+ <div class="gv-chips" data-role="similar-list"></div>
+ </div>
+
<!-- Override builder. The output is exactly the shape an agent's
meta.edits.animations takes, so it is copy-paste usable. -->
<div class="gv-override" data-role="override" hidden>
@@ -205,6 +229,35 @@
<div class="gv-hints-loading">Loading the skill map&hellip;</div>
</div>
+ <div class="gv-section-head">
+ <h2 id="atlas">The motion atlas</h2>
+ <p>
+ Every clip in the library, measured from its own keyframes and plotted
+ by how energetic it is and how much of that energy is above the waist.
+ Calm upper-body gestures gather top-left; explosive full-body dances and
+ runs sit bottom-right. Colour is the region leading the movement. Click
+ any point to play it, or to try it in the slot you have selected.
+ </p>
+ </div>
+
+ <div class="gv-atlas-tools">
+ <div class="gv-pills" data-role="atlas-filters" role="group" aria-label="Filter the atlas"></div>
+ <span class="gv-atlas-count" data-role="atlas-count" aria-live="polite"></span>
+ </div>
+ <div class="gv-atlas" data-role="atlas"></div>
+ <div class="gv-atlas-legend">
+ <span class="gv-fp-key"><i data-region="head"></i>Head</span>
+ <span class="gv-fp-key"><i data-region="arms"></i>Arms</span>
+ <span class="gv-fp-key"><i data-region="torso"></i>Torso</span>
+ <span class="gv-fp-key"><i data-region="root"></i>Hips</span>
+ <span class="gv-fp-key"><i data-region="legs"></i>Legs</span>
+ </div>
+ <div class="gv-error" data-role="atlas-error" hidden>
+ <p class="gv-error-title">The motion index did not load.</p>
+ <p class="gv-error-body" data-role="atlas-error-detail"></p>
+ <button type="button" class="gv-btn gv-btn--secondary" data-role="atlas-retry">Retry</button>
+ </div>
+
<div class="gv-section-head">
<h2 id="layers">Player gestures on /walk</h2>
<p>
diff --git a/public/gestures.css b/public/gestures.css
index 5c2bb5973..2b3e36f66 100644
--- a/public/gestures.css
+++ b/public/gestures.css
@@ -784,3 +784,373 @@
animation: none;
}
}
+
+/* ── Motion signatures ─────────────────────────────────────────────────── */
+/* Region colours are shared by the fingerprint bars, the legends and the
+ * atlas, so a colour means the same body part everywhere on the page. */
+
+:root {
+ --gv-r-head: #a78bfa;
+ --gv-r-arms: #7dd3fc;
+ --gv-r-torso: #34d399;
+ --gv-r-root: #fbbf24;
+ --gv-r-legs: #f472b6;
+ --gv-warn: #f59e0b;
+ --gv-ok: #34d399;
+}
+:root[data-theme='light'] {
+ --gv-r-head: #7c3aed;
+ --gv-r-arms: #0284c7;
+ --gv-r-torso: #059669;
+ --gv-r-root: #b45309;
+ --gv-r-legs: #db2777;
+ --gv-warn: #b45309;
+ --gv-ok: #047857;
+}
+
+[data-region='head'] { --gv-region: var(--gv-r-head); }
+[data-region='arms'] { --gv-region: var(--gv-r-arms); }
+[data-region='torso'] { --gv-region: var(--gv-r-torso); }
+[data-region='root'] { --gv-region: var(--gv-r-root); }
+[data-region='legs'] { --gv-region: var(--gv-r-legs); }
+
+.gv-fp {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-top: 10px;
+}
+
+.gv-fp-bar {
+ display: flex;
+ width: 100%;
+ height: 6px;
+ border-radius: 999px;
+ overflow: hidden;
+ background: var(--gv-surface-2);
+}
+
+.gv-fp-seg {
+ display: block;
+ height: 100%;
+ background: var(--gv-region, var(--gv-muted));
+ /* A region that barely moves still gets a visible hairline rather than
+ * rounding away to nothing, so the bar never implies zero when it is not. */
+ min-width: 1px;
+}
+
+.gv-fp-meta {
+ font-size: 11px;
+ letter-spacing: 0.02em;
+ color: var(--gv-muted);
+ text-transform: lowercase;
+}
+
+.gv-fp--full {
+ margin-top: 0;
+ gap: 10px;
+}
+.gv-fp--full .gv-fp-bar {
+ height: 10px;
+}
+
+.gv-fp-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px 14px;
+}
+
+.gv-fp-key {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ color: var(--gv-muted);
+}
+.gv-fp-key i {
+ width: 9px;
+ height: 9px;
+ border-radius: 3px;
+ background: var(--gv-region, var(--gv-muted));
+}
+.gv-fp-key b {
+ color: var(--text, #fafafa);
+ font-variant-numeric: tabular-nums;
+ font-weight: 600;
+}
+
+.gv-sig {
+ margin-top: 14px;
+ padding: 18px;
+ border: 1px solid var(--gv-border);
+ border-radius: var(--gv-radius);
+ background: var(--gv-surface);
+}
+
+.gv-sig-title {
+ margin: 0 0 6px;
+ font-size: 13px;
+ font-weight: 620;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--gv-muted);
+}
+
+.gv-sig-sentence {
+ margin: 0 0 14px;
+ font-size: 14px;
+ line-height: 1.55;
+}
+
+.gv-sig-stats {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(112px, 1fr));
+ gap: 10px;
+ margin: 14px 0 0;
+}
+
+.gv-sig-stat {
+ padding: 8px 10px;
+ border: 1px solid var(--gv-border);
+ border-radius: 10px;
+ background: var(--gv-surface-2);
+}
+.gv-sig-stat dt {
+ font-size: 10px;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ color: var(--gv-muted);
+}
+.gv-sig-stat dd {
+ margin: 3px 0 0;
+ font-size: 13px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+
+.gv-sig-badges {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 12px;
+}
+.gv-sig-badges:empty {
+ display: none;
+}
+
+.gv-mbadge {
+ padding: 3px 9px;
+ border-radius: 999px;
+ border: 1px solid color-mix(in srgb, var(--gv-ok) 50%, transparent);
+ background: color-mix(in srgb, var(--gv-ok) 14%, transparent);
+ color: var(--gv-ok);
+ font-size: 11px;
+ font-weight: 620;
+ letter-spacing: 0.02em;
+}
+.gv-mbadge.is-warn {
+ border-color: color-mix(in srgb, var(--gv-warn) 55%, transparent);
+ background: color-mix(in srgb, var(--gv-warn) 14%, transparent);
+ color: var(--gv-warn);
+}
+
+/* ── Slot fit verdict ──────────────────────────────────────────────────── */
+
+.gv-fit {
+ display: flex;
+ gap: 10px;
+ align-items: flex-start;
+ margin-top: 12px;
+ padding: 12px 14px;
+ border: 1px solid var(--gv-border);
+ border-radius: 12px;
+ background: var(--gv-surface);
+ font-size: 13px;
+ line-height: 1.5;
+}
+.gv-fit p {
+ margin: 0;
+}
+.gv-fit-icon::before {
+ content: '✓';
+ font-weight: 700;
+}
+.gv-fit.is-ok {
+ border-color: color-mix(in srgb, var(--gv-ok) 40%, transparent);
+}
+.gv-fit.is-ok .gv-fit-icon {
+ color: var(--gv-ok);
+}
+.gv-fit.is-warn {
+ border-color: color-mix(in srgb, var(--gv-warn) 50%, transparent);
+ background: color-mix(in srgb, var(--gv-warn) 8%, transparent);
+}
+.gv-fit.is-warn .gv-fit-icon {
+ color: var(--gv-warn);
+}
+.gv-fit.is-warn .gv-fit-icon::before {
+ content: '!';
+}
+
+/* ── Nearest clips ─────────────────────────────────────────────────────── */
+
+.gv-similar {
+ margin-top: 14px;
+ padding: 16px 18px;
+ border: 1px solid var(--gv-border);
+ border-radius: var(--gv-radius);
+ background: var(--gv-surface);
+}
+.gv-similar-title {
+ margin: 0;
+ font-size: 13px;
+ font-weight: 620;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--gv-muted);
+}
+.gv-similar-lede {
+ margin: 4px 0 12px;
+ font-size: 12px;
+ color: var(--gv-muted);
+}
+
+.gv-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.gv-chip,
+.gv-pill {
+ padding: 6px 12px;
+ border: 1px solid var(--gv-border-strong);
+ border-radius: 999px;
+ background: var(--gv-surface-2);
+ color: inherit;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ transition: background 0.16s ease, border-color 0.16s ease, transform 0.16s ease;
+}
+.gv-chip:hover,
+.gv-pill:hover {
+ background: var(--gv-surface-3);
+ transform: translateY(-1px);
+}
+.gv-chip:active,
+.gv-pill:active {
+ transform: translateY(0);
+}
+.gv-chip:focus-visible,
+.gv-pill:focus-visible {
+ outline: 2px solid var(--gv-accent);
+ outline-offset: 2px;
+}
+.gv-pill[aria-pressed='true'] {
+ background: var(--gv-accent);
+ border-color: var(--gv-accent);
+ color: var(--gv-accent-ink);
+ font-weight: 620;
+}
+
+/* ── The motion atlas ──────────────────────────────────────────────────── */
+
+.gv-atlas-tools {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 12px;
+}
+
+.gv-pills {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.gv-atlas-count {
+ font-size: 12px;
+ color: var(--gv-muted);
+ font-variant-numeric: tabular-nums;
+}
+
+.gv-atlas {
+ border: 1px solid var(--gv-border);
+ border-radius: var(--gv-radius);
+ background:
+ radial-gradient(120% 90% at 50% 0%, var(--gv-surface-2), transparent 70%),
+ var(--gv-surface);
+ overflow: hidden;
+}
+
+.gv-atlas-svg {
+ display: block;
+ width: 100%;
+ height: auto;
+}
+
+.gv-atlas-grid {
+ stroke: var(--gv-border);
+ stroke-width: 1;
+ stroke-dasharray: 3 5;
+}
+.gv-atlas-axis {
+ stroke: var(--gv-border-strong);
+ stroke-width: 1;
+}
+.gv-atlas-label {
+ fill: var(--gv-muted);
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+
+.gv-atlas-dot {
+ fill: var(--gv-region, var(--gv-accent));
+ fill-opacity: 0.55;
+ stroke: var(--gv-region, var(--gv-accent));
+ stroke-width: 1;
+ cursor: pointer;
+ transition: fill-opacity 0.16s ease, stroke-width 0.16s ease;
+}
+.gv-atlas-dot:hover {
+ fill-opacity: 0.95;
+ stroke-width: 2;
+}
+.gv-atlas-dot:focus-visible {
+ outline: none;
+ stroke: var(--text, #fafafa);
+ stroke-width: 2.5;
+ fill-opacity: 0.95;
+}
+.gv-atlas-dot.is-dim {
+ fill-opacity: 0.06;
+ stroke-opacity: 0.18;
+}
+.gv-atlas-dot.is-active {
+ fill-opacity: 1;
+ stroke: var(--text, #fafafa);
+ stroke-width: 2.5;
+}
+
+.gv-atlas-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 18px;
+ margin-top: 10px;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .gv-chip,
+ .gv-pill,
+ .gv-atlas-dot {
+ transition: none;
+ }
+ .gv-chip:hover,
+ .gv-pill:hover {
+ transform: none;
+ }
+}
diff --git a/src/gestures-page.js b/src/gestures-page.js
index ff16504f4..16445604f 100644
--- a/src/gestures-page.js
+++ b/src/gestures-page.js
@@ -14,9 +14,18 @@
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. */
@@ -52,14 +61,19 @@ 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 ──────────────────────────────────────────────────────────────── */
async function fetchJson(url) {
@@ -89,6 +103,26 @@ async function loadManifest() {
}
}
+/**
+ * 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 {
@@ -117,6 +151,61 @@ function renderStats() {
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);
@@ -143,6 +232,7 @@ function cardHtml(slot) {
<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>`;
}
@@ -151,6 +241,13 @@ 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.
@@ -228,8 +325,78 @@ function renderOverrideOptions() {
.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;
@@ -249,6 +416,89 @@ function renderOverride() {
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 ─────────────────────────────────────────────────── */
/**
@@ -370,17 +620,27 @@ async function getPreview() {
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;
+ state.slot = slot || null;
state.clip = clip;
const def = state.byName.get(clip);
- el('stage-slot').textContent = slot;
- el('stage-clip').textContent = def?.label ? `${def.label} · ${clip}` : 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;
- loadAgents();
- el('stage-status').textContent = `Playing ${slot}: ${def?.label || clip}`;
+ 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));
}
@@ -434,11 +694,15 @@ function stop() {
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();
}
@@ -448,7 +712,9 @@ function syncUrl() {
const url = new URL(window.location.href);
if (state.slot) url.searchParams.set('slot', state.slot);
else url.searchParams.delete('slot');
- if (state.slot && state.clip !== DEFAULT_ANIMATION_MAP[state.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');
@@ -459,9 +725,12 @@ function syncUrl() {
function applyDeepLink() {
const params = new URLSearchParams(window.location.search);
const slot = params.get('slot');
- if (!slot || !SLOTS.includes(slot)) return;
const clip = params.get('clip');
- play(slot, clip && state.byName.has(clip) ? clip : DEFAULT_ANIMATION_MAP[slot]);
+ 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 ────────────────────────────────────────────────────────────── */
@@ -509,6 +778,44 @@ function wire() {
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);
@@ -571,3 +878,4 @@ renderLayers();
wire();
loadManifest();
loadHints();
+loadSignatures();
diff --git a/src/sign-mirror-page.js b/src/sign-mirror-page.js
new file mode 100644
index 000000000..62696e371
--- /dev/null
+++ b/src/sign-mirror-page.js
@@ -0,0 +1,483 @@
+// /sign-mirror: learn a handshape by making it, not by watching one.
+//
+// The avatar forms the target letter. Your camera watches your hand. The two
+// are compared against the SAME handshape spec (src/sign-handshapes.js), so the
+// thing being taught and the thing being graded can never drift apart. Hold the
+// shape and the letter passes; hold it wrong and the page names the finger.
+//
+// Everything on the camera side stays on the device. MediaPipe's hand
+// landmarker runs in this tab, the grading is arithmetic in src/sign-grader.js,
+// and no frame, landmark, or score is ever uploaded. There is no network call
+// in the practice loop at all.
+
+import { PoseStage } from './avatar-pose.js';
+import { buildFingerspellingClip, normalizeWord } from './fingerspelling.js';
+import { LETTERS, LETTER_NOTES } from './asl-alphabet-data.js';
+import { GradeSmoother, gradeHandshape, rankHandshapes } from './sign-grader.js';
+import { HAND_CONNECTIONS, handshapeLandmarks, projectHand } from './sign-hand-model.js';
+import { log } from './shared/log.js';
+
+const AVATARS = [
+ { id: 'classic', label: 'Classic', url: '/avatars/cz.glb' },
+ { id: 'expressive', label: 'Expressive face', url: '/avatars/default.glb' },
+];
+const PREFS_KEY = 'threews:sign-prefs';
+const PROGRESS_KEY = 'threews:sign-mirror-progress';
+
+// Letters whose handshape is identical to another letter's: in ASL they differ
+// by which way the hand points, which a handshape score cannot see. They are
+// still taught, with the difference spelled out, but never marked wrong for it.
+const SHARED_SHAPE = { G: 'Q', Q: 'G', K: 'P', P: 'K' };
+
+// The manual alphabet in the order it is easiest to learn: closed shapes first,
+// then the open hands, then the pairs people confuse, then the moving letters.
+const COURSE = [
+ { id: 'closed', title: 'Closed hands', blurb: 'Four letters made with the fingers folded in. The thumb does all the work.', letters: ['A', 'S', 'E', 'O'] },
+ { id: 'open', title: 'Open hands', blurb: 'The flat and spread shapes. Easy to hold, easy to read.', letters: ['B', 'C', 'F', 'L'] },
+ { id: 'points', title: 'Pointing fingers', blurb: 'One or two fingers up. Watch the gap between them.', letters: ['D', 'U', 'V', 'W'] },
+ { id: 'tricky', title: 'The confusable ones', blurb: 'The pairs that trip up every beginner. Take these slowly.', letters: ['M', 'N', 'T', 'R'] },
+ { id: 'rest', title: 'The rest', blurb: 'Everything left, including the two letters that move.', letters: ['G', 'H', 'I', 'K', 'P', 'Q', 'X', 'Y', 'J', 'Z'] },
+];
+
+const MOVING = new Set(['J', 'Z']);
+const ALL_COURSE_LETTERS = COURSE.flatMap((s) => s.letters);
+const $ = (sel, root = document) => root.querySelector(sel);
+
+function readJSON(key, fallback) {
+ try {
+ return JSON.parse(localStorage.getItem(key)) || fallback;
+ } catch {
+ return fallback;
+ }
+}
+function writeJSON(key, value) {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ /* private mode: progress just does not persist */
+ }
+}
+
+/** Draw a hand skeleton into an SVG element from 21 projected points. */
+function drawSkeleton(svg, points, { className = '' } = {}) {
+ const ns = 'http://www.w3.org/2000/svg';
+ svg.textContent = '';
+ const g = document.createElementNS(ns, 'g');
+ if (className) g.setAttribute('class', className);
+ for (const [a, b] of HAND_CONNECTIONS) {
+ const line = document.createElementNS(ns, 'line');
+ line.setAttribute('x1', points[a].x.toFixed(1));
+ line.setAttribute('y1', points[a].y.toFixed(1));
+ line.setAttribute('x2', points[b].x.toFixed(1));
+ line.setAttribute('y2', points[b].y.toFixed(1));
+ g.append(line);
+ }
+ points.forEach((p, i) => {
+ const dot = document.createElementNS(ns, 'circle');
+ dot.setAttribute('cx', p.x.toFixed(1));
+ dot.setAttribute('cy', p.y.toFixed(1));
+ dot.setAttribute('r', i === 0 || i % 4 === 0 ? '3.6' : '2.4');
+ g.append(dot);
+ });
+ svg.append(g);
+}
+
+async function boot() {
+ const stageHost = $('#sm-stage');
+ if (!stageHost) return;
+
+ const prefs = readJSON(PREFS_KEY, {});
+ const progress = readJSON(PROGRESS_KEY, { passed: {}, best: {} });
+ let avatar = AVATARS.find((a) => a.id === prefs.avatar) || AVATARS[0];
+ let dominant = prefs.dominant === 'Left' ? 'Left' : 'Right';
+
+ let stage = null;
+ let canSign = false;
+ let current = ALL_COURSE_LETTERS[0];
+ let playToken = 0;
+
+ const statusEl = $('#sm-status');
+ const setStatus = (msg, tone = '') => {
+ if (!statusEl) return;
+ statusEl.textContent = msg || '';
+ statusEl.dataset.tone = tone;
+ };
+
+ // ── The avatar half ──────────────────────────────────────────────────────
+ const mountStage = async () => {
+ stage?.dispose();
+ stage = new PoseStage(stageHost, { glbUrl: avatar.url, framing: 'portrait' });
+ try {
+ const { supported } = await stage.mount();
+ stage.start();
+ canSign = !!supported;
+ if (!supported) setStatus('This avatar has no finger bones. Practice still works: the target diagram and the scoring do not need it.', 'warn');
+ return canSign;
+ } catch (err) {
+ log.warn('[sign-mirror] stage mount failed', err?.message);
+ canSign = false;
+ setStatus('The 3D preview could not start. The target diagram and scoring still work.', 'warn');
+ return false;
+ }
+ };
+
+ const showOnAvatar = (letter) => {
+ if (!stage?.anim || !canSign) return;
+ const token = ++playToken;
+ let clip;
+ try {
+ clip = buildFingerspellingClip(letter, { holdSeconds: 1.6, transitionSeconds: 0.3, dominant, settle: false });
+ } catch (err) {
+ log.warn('[sign-mirror] clip failed', err?.message);
+ return;
+ }
+ const name = `sm-${token}`;
+ stage.anim.injectClip(name, clip, { loop: false });
+ stage.anim.playOnce(name, { settleTo: null });
+ };
+
+ // ── The target diagram ───────────────────────────────────────────────────
+ const targetSvg = $('#sm-target');
+ const drawTarget = (letter) => {
+ if (!targetSvg) return;
+ const box = targetSvg.viewBox.baseVal;
+ const pts = projectHand(handshapeLandmarks(letter, dominant), {
+ width: box.width,
+ height: box.height,
+ padding: 20,
+ flip: dominant === 'Left',
+ });
+ drawSkeleton(targetSvg, pts, { className: 'sm-skel sm-skel-target' });
+ };
+
+ // ── The camera half ──────────────────────────────────────────────────────
+ const video = $('#sm-video');
+ const overlay = $('#sm-overlay');
+ const scoreEl = $('#sm-score');
+ const scoreBar = $('#sm-score-bar');
+ const hintEl = $('#sm-hint');
+ const fingersEl = $('#sm-fingers');
+ const cameraBtn = $('#sm-camera');
+ const cameraNote = $('#sm-camera-note');
+
+ let landmarker = null;
+ let stream = null;
+ let raf = 0;
+ let running = false;
+ let lastVideoTime = -1;
+ const smoother = new GradeSmoother({ passScore: 78, holdMs: 800 });
+
+ const setScore = (value, holding, heldMs) => {
+ const pct = Math.max(0, Math.min(100, value));
+ if (scoreEl) scoreEl.textContent = `${Math.round(pct)}`;
+ if (scoreBar) {
+ scoreBar.style.setProperty('--sm-fill', `${pct}%`);
+ scoreBar.dataset.state = pct >= 78 ? 'good' : pct >= 55 ? 'close' : 'far';
+ scoreBar.setAttribute('aria-valuenow', String(Math.round(pct)));
+ }
+ if (holding && heldMs > 0) {
+ const held = Math.min(1, heldMs / smoother.holdMs);
+ scoreBar?.style.setProperty('--sm-hold', `${(held * 100).toFixed(0)}%`);
+ } else {
+ scoreBar?.style.setProperty('--sm-hold', '0%');
+ }
+ };
+
+ const renderFingers = (grade) => {
+ if (!fingersEl) return;
+ fingersEl.textContent = '';
+ for (const f of grade.fingers) {
+ const row = document.createElement('div');
+ row.className = 'sm-finger';
+ row.dataset.state = f.score >= 0.8 ? 'good' : f.score >= 0.5 ? 'close' : 'far';
+ const name = document.createElement('span');
+ name.className = 'sm-finger-name';
+ name.textContent = f.finger;
+ const bar = document.createElement('span');
+ bar.className = 'sm-finger-bar';
+ bar.style.setProperty('--sm-fill', `${Math.round(f.score * 100)}%`);
+ row.append(name, bar);
+ fingersEl.append(row);
+ }
+ };
+
+ const markPassed = (letter) => {
+ progress.passed[letter] = true;
+ writeJSON(PROGRESS_KEY, progress);
+ document.querySelector(`.sm-letter[data-char="${letter}"]`)?.setAttribute('data-passed', 'true');
+ renderProgress();
+ };
+
+ const onPassed = (letter) => {
+ markPassed(letter);
+ setStatus(`${letter} is right. Well held.`, 'good');
+ if (hintEl) hintEl.textContent = `${letter} passed. Next letter loaded.`;
+ const idx = ALL_COURSE_LETTERS.indexOf(letter);
+ const next = ALL_COURSE_LETTERS.slice(idx + 1).find((l) => !progress.passed[l]) || ALL_COURSE_LETTERS.find((l) => !progress.passed[l]);
+ if (next) window.setTimeout(() => selectLetter(next), 900);
+ else setStatus('Every letter passed. You can read and make the whole manual alphabet.', 'good');
+ };
+
+ const gradeFrame = (landmarks, now) => {
+ const target = MOVING.has(current) ? current : current;
+ let grade;
+ try {
+ grade = gradeHandshape(landmarks, target);
+ } catch (err) {
+ log.warn('[sign-mirror] grade failed', err?.message);
+ return;
+ }
+ const state = smoother.push(grade, now);
+ setScore(state.score, state.holding, state.heldMs);
+ renderFingers(grade);
+ if (progress.best[current] == null || state.score > progress.best[current]) {
+ progress.best[current] = Math.round(state.score);
+ }
+ if (state.passed) {
+ smoother.reset();
+ onPassed(current);
+ return;
+ }
+ if (hintEl) {
+ // When the hand is a long way off, say what it DOES look like: a
+ // learner making a clean B while aiming for D is helped far more by
+ // "that is a B" than by "straighten your ring finger".
+ if (state.score < 45) {
+ const [best] = rankHandshapes(landmarks, LETTERS.filter((l) => !MOVING.has(l)));
+ hintEl.textContent = best && best.name !== current && best.score > 70 ? `That is a clean ${best.name}. For ${current}: ${grade.hint}` : grade.hint;
+ } else {
+ hintEl.textContent = grade.hint;
+ }
+ }
+ };
+
+ const stopCamera = () => {
+ running = false;
+ cancelAnimationFrame(raf);
+ stream?.getTracks().forEach((t) => t.stop());
+ stream = null;
+ lastVideoTime = -1;
+ smoother.reset();
+ if (video) video.srcObject = null;
+ document.body.dataset.smCamera = 'off';
+ if (cameraBtn) {
+ cameraBtn.textContent = 'Turn the camera on';
+ cameraBtn.setAttribute('aria-pressed', 'false');
+ }
+ overlay?.replaceChildren();
+ setScore(0, false, 0);
+ if (fingersEl) fingersEl.textContent = '';
+ if (hintEl) hintEl.textContent = '';
+ };
+
+ const startCamera = async () => {
+ if (running) return;
+ if (!navigator.mediaDevices?.getUserMedia) {
+ setStatus('This browser has no camera API. Practice with the target diagram instead.', 'warn');
+ return;
+ }
+ cameraBtn.disabled = true;
+ cameraBtn.textContent = 'Starting the camera...';
+ try {
+ if (!landmarker) {
+ setStatus('Loading the hand tracker (about 8 MB, once per browser).');
+ const { FilesetResolver, HandLandmarker } = await import('@mediapipe/tasks-vision');
+ const fileset = await FilesetResolver.forVisionTasks('https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm');
+ landmarker = await HandLandmarker.createFromOptions(fileset, {
+ baseOptions: {
+ modelAssetPath: 'https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task',
+ delegate: 'GPU',
+ },
+ runningMode: 'VIDEO',
+ numHands: 1,
+ });
+ }
+ stream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 480, facingMode: 'user' }, audio: false });
+ video.srcObject = stream;
+ await video.play();
+ running = true;
+ document.body.dataset.smCamera = 'on';
+ cameraBtn.textContent = 'Turn the camera off';
+ cameraBtn.setAttribute('aria-pressed', 'true');
+ setStatus('Camera on. Nothing leaves this tab.', 'good');
+ if (cameraNote) cameraNote.hidden = false;
+ loop();
+ } catch (err) {
+ log.warn('[sign-mirror] camera failed', err?.message);
+ const denied = /denied|not allowed/i.test(err?.message || '');
+ setStatus(
+ denied
+ ? 'Camera permission was refused. Allow it in your browser address bar, then try again.'
+ : `The camera could not start: ${err?.message || 'unknown error'}. The target diagram still works.`,
+ 'warn',
+ );
+ stopCamera();
+ } finally {
+ cameraBtn.disabled = false;
+ }
+ };
+
+ const loop = () => {
+ if (!running) return;
+ raf = requestAnimationFrame(loop);
+ if (!video.videoWidth || video.currentTime === lastVideoTime) return;
+ lastVideoTime = video.currentTime;
+ const result = landmarker.detectForVideo(video, performance.now());
+ const hand = result?.landmarks?.[0];
+ if (!hand?.length) {
+ if (hintEl) hintEl.textContent = 'No hand in frame. Hold one hand up, palm toward the camera.';
+ overlay?.replaceChildren();
+ setScore(0, false, 0);
+ return;
+ }
+ // The preview is mirrored so it reads like a mirror; the overlay has to
+ // be mirrored with it or the skeleton lands on the wrong side.
+ const box = overlay.viewBox.baseVal;
+ drawSkeleton(
+ overlay,
+ hand.map((p) => ({ x: (1 - p.x) * box.width, y: p.y * box.height })),
+ { className: 'sm-skel sm-skel-live' },
+ );
+ gradeFrame(hand, performance.now());
+ };
+
+ // ── Letter selection ─────────────────────────────────────────────────────
+ const bigEl = $('#sm-big');
+ const noteEl = $('#sm-note');
+ const lookEl = $('#sm-look');
+ const sharedEl = $('#sm-shared');
+ const movingEl = $('#sm-moving');
+
+ function selectLetter(letter) {
+ if (!LETTER_NOTES[letter]) return;
+ current = letter;
+ smoother.reset();
+ setScore(0, false, 0);
+ if (bigEl) bigEl.textContent = letter;
+ if (noteEl) noteEl.textContent = LETTER_NOTES[letter].hand;
+ if (lookEl) {
+ lookEl.textContent = LETTER_NOTES[letter].look || '';
+ lookEl.hidden = !LETTER_NOTES[letter].look;
+ }
+ if (sharedEl) {
+ const twin = SHARED_SHAPE[letter];
+ sharedEl.hidden = !twin;
+ if (twin) sharedEl.textContent = `${letter} and ${twin} are the same handshape. What separates them is which way the hand points, so the score below cannot tell them apart: check the direction against the avatar.`;
+ }
+ if (movingEl) {
+ movingEl.hidden = !MOVING.has(letter);
+ if (MOVING.has(letter)) movingEl.textContent = `${letter} moves. The score checks the handshape only; watch the avatar for the path it traces.`;
+ }
+ document.querySelectorAll('.sm-letter').forEach((el) => {
+ el.setAttribute('aria-pressed', String(el.dataset.char === letter));
+ });
+ drawTarget(letter);
+ showOnAvatar(letter);
+ if (hintEl && !running) hintEl.textContent = 'Turn the camera on to be graded, or just copy the diagram.';
+ const url = new URL(location.href);
+ url.searchParams.set('letter', letter);
+ history.replaceState(null, '', url);
+ }
+
+ // ── Course rail ──────────────────────────────────────────────────────────
+ const railEl = $('#sm-rail');
+ const buildRail = () => {
+ if (!railEl) return;
+ railEl.textContent = '';
+ for (const section of COURSE) {
+ const wrap = document.createElement('section');
+ wrap.className = 'sm-group';
+ const h = document.createElement('h3');
+ h.textContent = section.title;
+ const p = document.createElement('p');
+ p.textContent = section.blurb;
+ const row = document.createElement('div');
+ row.className = 'sm-letters';
+ for (const letter of section.letters) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'sm-letter';
+ btn.dataset.char = letter;
+ btn.textContent = letter;
+ btn.setAttribute('aria-pressed', String(letter === current));
+ btn.setAttribute('aria-label', `Practise the letter ${letter}`);
+ if (progress.passed[letter]) btn.dataset.passed = 'true';
+ btn.addEventListener('click', () => selectLetter(letter));
+ row.append(btn);
+ }
+ wrap.append(h, p, row);
+ railEl.append(wrap);
+ }
+ };
+
+ const progressEl = $('#sm-progress');
+ const progressBar = $('#sm-progress-bar');
+ function renderProgress() {
+ const done = ALL_COURSE_LETTERS.filter((l) => progress.passed[l]).length;
+ const pct = Math.round((done / ALL_COURSE_LETTERS.length) * 100);
+ if (progressEl) progressEl.textContent = `${done} of ${ALL_COURSE_LETTERS.length} letters held correctly`;
+ if (progressBar) {
+ progressBar.style.setProperty('--sm-fill', `${pct}%`);
+ progressBar.setAttribute('aria-valuenow', String(done));
+ }
+ }
+
+ // ── Controls ─────────────────────────────────────────────────────────────
+ cameraBtn?.addEventListener('click', () => (running ? stopCamera() : startCamera()));
+
+ $('#sm-replay')?.addEventListener('click', () => showOnAvatar(current));
+
+ $('#sm-reset')?.addEventListener('click', () => {
+ progress.passed = {};
+ progress.best = {};
+ writeJSON(PROGRESS_KEY, progress);
+ document.querySelectorAll('.sm-letter[data-passed]').forEach((el) => el.removeAttribute('data-passed'));
+ renderProgress();
+ setStatus('Progress cleared.');
+ });
+
+ const handBtns = document.querySelectorAll('[data-hand]');
+ handBtns.forEach((btn) => {
+ btn.setAttribute('aria-pressed', String(btn.dataset.hand === dominant));
+ btn.addEventListener('click', () => {
+ dominant = btn.dataset.hand === 'Left' ? 'Left' : 'Right';
+ handBtns.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.hand === dominant)));
+ writeJSON(PREFS_KEY, { ...readJSON(PREFS_KEY, {}), dominant });
+ drawTarget(current);
+ showOnAvatar(current);
+ });
+ });
+
+ document.addEventListener('keydown', (e) => {
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ const tag = e.target?.tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA') return;
+ const key = e.key.toUpperCase();
+ if (LETTER_NOTES[key]) {
+ selectLetter(key);
+ e.preventDefault();
+ }
+ });
+
+ // ── Boot ─────────────────────────────────────────────────────────────────
+ buildRail();
+ renderProgress();
+ await mountStage();
+ const wanted = new URLSearchParams(location.search).get('letter')?.toUpperCase();
+ const first = LETTER_NOTES[wanted] ? wanted : ALL_COURSE_LETTERS.find((l) => !progress.passed[l]) || ALL_COURSE_LETTERS[0];
+ // The stage crossfades into its idle after mounting; a letter played before
+ // that lands is overwritten by it, so wait for the idle to take hold.
+ for (let i = 0; i < 60 && stage?.anim && !stage.anim.currentName; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ selectLetter(first);
+ setStatus('');
+
+ window.addEventListener('pagehide', stopCamera);
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden && running) stopCamera();
+ });
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true });
+else boot();
diff --git a/tests/api-sign.test.js b/tests/api-sign.test.js
new file mode 100644
index 000000000..b5c26c1cf
--- /dev/null
+++ b/tests/api-sign.test.js
@@ -0,0 +1,258 @@
+// Coverage for api/sign.js: the text → American Sign Language endpoint, and
+// for the per-word timeline the compiler now reports underneath it.
+//
+// What matters here is not that the handler returns 200. It is that the numbers
+// it returns describe the clip it returns: the timeline has to tile the whole
+// utterance in order, every letter of a fingerspelled word has to sit inside
+// that word's span, and the clip's own duration has to agree with both. A
+// caption track built from a timeline that drifts from the animation is worse
+// than no caption track, so those invariants are asserted directly.
+//
+// The compiler is pure and in-process (no three.js, no DOM, no network), so
+// these run against the real thing; only the rate limiter is stubbed.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const signCompileIp = vi.fn(async () => ({ success: true }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ get signCompileIp() {
+ return signCompileIp;
+ },
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const { default: handler, compile, readParams, descriptor, MAX_TEXT_CHARS } = await import(
+ '../api/sign.js'
+);
+
+function mockReq(search = '', method = 'GET', body = null) {
+ const req = { method, headers: { host: 'localhost' }, url: `/api/sign${search}` };
+ if (body != null) {
+ req.headers['content-type'] = 'application/json';
+ req.rawBody = Buffer.from(JSON.stringify(body));
+ }
+ return req;
+}
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ ended: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(b) {
+ this.body = b;
+ this.ended = true;
+ },
+ };
+}
+
+const json = (res) => JSON.parse(String(res.body));
+
+beforeEach(() => {
+ signCompileIp.mockClear();
+ signCompileIp.mockResolvedValue({ success: true });
+});
+
+describe('GET /api/sign with no text', () => {
+ it('describes itself and lists the whole vocabulary', async () => {
+ const res = mockRes();
+ await handler(mockReq(''), res);
+ expect(res.statusCode).toBe(200);
+ const body = json(res);
+ expect(body.service).toBe('three.ws sign');
+ expect(body.vocabulary_size).toBe(body.vocabulary.length);
+ expect(body.vocabulary_size).toBeGreaterThan(20);
+ for (const entry of body.vocabulary) {
+ expect(entry.word).toMatch(/^[A-Z]+$/);
+ expect(entry.gloss.length).toBeGreaterThan(8);
+ }
+ // Discovery must not cost a compile slot.
+ expect(signCompileIp).not.toHaveBeenCalled();
+ });
+
+ it('is cacheable, and readable from any origin', async () => {
+ const res = mockRes();
+ await handler(mockReq(''), res);
+ expect(res.headers['cache-control']).toMatch(/max-age=\d+/);
+ expect(res.headers['access-control-allow-origin']).toBe('*');
+ });
+});
+
+describe('GET /api/sign?text=', () => {
+ it('signs the words it knows and spells the rest', async () => {
+ const res = mockRes();
+ await handler(mockReq('?text=happy%20to%20meet%20you'), res);
+ expect(res.statusCode).toBe(200);
+ const body = json(res);
+ expect(body.words).toEqual(['HAPPY', 'TO', 'MEET', 'YOU']);
+ expect(body.signed).toEqual(['HAPPY', 'MEET', 'YOU']);
+ expect(body.spelled).toEqual(['TO']);
+ expect(body.truncated).toBe(false);
+ expect(body.viewer).toContain('/sign-language?say=');
+ });
+
+ it('returns a clip whose duration the timeline actually covers', async () => {
+ const res = mockRes();
+ await handler(mockReq('?text=hello%20nich'), res);
+ const body = json(res);
+
+ expect(body.timeline.length).toBe(body.words.length);
+ expect(body.timeline[0].start).toBe(0);
+ // Segments run in order and never overlap.
+ for (let i = 1; i < body.timeline.length; i++) {
+ expect(body.timeline[i].start).toBeGreaterThanOrEqual(body.timeline[i - 1].end);
+ }
+ const last = body.timeline[body.timeline.length - 1];
+ expect(last.end).toBeCloseTo(body.duration, 4);
+ expect(body.clip.duration).toBeCloseTo(body.duration, 4);
+
+ // Every clip track is strictly increasing in time and ends within the clip.
+ for (const track of body.clip.tracks) {
+ for (let i = 1; i < track.times.length; i++) {
+ expect(track.times[i], track.name).toBeGreaterThan(track.times[i - 1]);
+ }
+ expect(track.times[track.times.length - 1]).toBeLessThanOrEqual(body.clip.duration + 1e-3);
+ }
+ });
+
+ it('places every spelled letter inside its own word', async () => {
+ const res = mockRes();
+ await handler(mockReq('?text=nich'), res);
+ const word = json(res).timeline[0];
+ expect(word.signed).toBe(false);
+ expect(word.letters.map((l) => l.letter).join('')).toBe('NICH');
+ for (const letter of word.letters) {
+ expect(letter.start).toBeGreaterThanOrEqual(word.start);
+ expect(letter.end).toBeLessThanOrEqual(word.end);
+ expect(letter.end).toBeGreaterThan(letter.start);
+ }
+ });
+
+ it('carries the gloss on a signed word and nothing on a spelled one', async () => {
+ const res = mockRes();
+ await handler(mockReq('?text=hello%20nich'), res);
+ const [signed, spelled] = json(res).timeline;
+ expect(signed.gloss).toMatch(/hand/i);
+ expect(signed.letters).toBeNull();
+ expect(spelled.gloss).toBeNull();
+ });
+
+ it('mirrors onto the left hand without changing the utterance', async () => {
+ const right = mockRes();
+ const left = mockRes();
+ await handler(mockReq('?text=hello'), right);
+ await handler(mockReq('?text=hello&hand=left'), left);
+ const r = json(right);
+ const l = json(left);
+ expect(l.hand).toBe('left');
+ expect(l.words).toEqual(r.words);
+ expect(l.duration).toBeCloseTo(r.duration, 4);
+ // Same performance, different arm: the clips must not be identical.
+ expect(JSON.stringify(l.clip.tracks)).not.toBe(JSON.stringify(r.clip.tracks));
+ });
+
+ it('takes longer at a slower speed', async () => {
+ const fast = mockRes();
+ const slow = mockRes();
+ await handler(mockReq('?text=hello%20world'), fast);
+ await handler(mockReq('?text=hello%20world&speed=0.5'), slow);
+ expect(json(slow).duration).toBeGreaterThan(json(fast).duration * 1.5);
+ });
+
+ it('omits the clip for format=timeline', async () => {
+ const res = mockRes();
+ await handler(mockReq('?text=hello&format=timeline'), res);
+ const body = json(res);
+ expect(body.clip).toBeUndefined();
+ expect(body.timeline.length).toBe(1);
+ });
+
+ it('truncates long text at a word boundary and says so', async () => {
+ const res = mockRes();
+ const text = Array.from({ length: 40 }, () => 'hello').join('+');
+ await handler(mockReq(`?text=${text}&max_seconds=8`), res);
+ const body = json(res);
+ expect(body.truncated).toBe(true);
+ expect(body.timeline.length).toBeLessThan(40);
+ expect(body.duration).toBeLessThan(12);
+ });
+});
+
+describe('POST /api/sign', () => {
+ it('accepts a JSON body', async () => {
+ const res = mockRes();
+ await handler(mockReq('', 'POST', { text: 'three ws', speed: 0.5 }), res);
+ expect(res.statusCode).toBe(200);
+ const body = json(res);
+ expect(body.words).toEqual(['THREE', 'WS']);
+ expect(body.speed).toBe(0.5);
+ });
+
+ it('rejects a body with no text', async () => {
+ const res = mockRes();
+ await handler(mockReq('', 'POST', { speed: 1 }), res);
+ expect(res.statusCode).toBe(400);
+ expect(json(res).error).toBe('missing_text');
+ });
+});
+
+describe('bad input', () => {
+ it('explains text with nothing signable in it', async () => {
+ const res = mockRes();
+ await handler(mockReq('?text=%E2%9C%93%E2%9C%93'), res);
+ expect(res.statusCode).toBe(400);
+ const body = json(res);
+ expect(body.error).toBe('unsignable_text');
+ expect(body.message).toMatch(/A-Z and 0-9/);
+ });
+
+ it('rate-limits per IP rather than failing open', async () => {
+ signCompileIp.mockResolvedValue({ success: false, limit: 120, remaining: 0, reset: 1 });
+ const res = mockRes();
+ await handler(mockReq('?text=hello'), res);
+ expect(res.statusCode).toBe(429);
+ });
+});
+
+describe('readParams', () => {
+ it('clamps every knob into range instead of erroring', () => {
+ expect(readParams({ text: 'x', speed: 99 }).speed).toBe(1.5);
+ expect(readParams({ text: 'x', speed: -4 }).speed).toBe(0.25);
+ expect(readParams({ text: 'x', speed: 'nonsense' }).speed).toBe(1);
+ expect(readParams({ text: 'x', max_seconds: 9999 }).maxSeconds).toBe(60);
+ expect(readParams({ text: 'x', hand: 'LEFT' }).hand).toBe('Left');
+ expect(readParams({ text: 'x', hand: 'sideways' }).hand).toBe('Right');
+ });
+
+ it('caps the text length', () => {
+ expect(readParams({ text: 'a'.repeat(5000) }).text.length).toBe(MAX_TEXT_CHARS);
+ });
+});
+
+describe('compile', () => {
+ it('rounds clip numbers to keep the payload small', () => {
+ const body = compile(readParams({ text: 'hello' }), 'https://three.ws');
+ for (const track of body.clip.tracks) {
+ for (const value of track.values) {
+ expect(String(value).replace(/^-?\d*\.?/, '').length).toBeLessThanOrEqual(5);
+ }
+ }
+ });
+
+ it('agrees with the descriptor about what is signable', () => {
+ const { vocabulary } = descriptor('https://three.ws');
+ const word = vocabulary[0].word;
+ const body = compile(readParams({ text: word }), 'https://three.ws');
+ expect(body.signed).toEqual([word]);
+ expect(body.spelled).toEqual([]);
+ });
+});
diff --git a/tests/fingerspelling.test.js b/tests/fingerspelling.test.js
index b36e99c12..028a8c11e 100644
--- a/tests/fingerspelling.test.js
+++ b/tests/fingerspelling.test.js
@@ -83,8 +83,11 @@ describe('letter shapes', () => {
const right = handshapeLocals('V', 'Right');
const left = handshapeLocals('V', 'Left');
expect(quatAngleDeg(left.LeftHandIndex1)).toBeCloseTo(quatAngleDeg(right.RightHandIndex1), 5);
- // Curl hinge is mirrored: z components flip sign.
- expect(left.LeftHandRing2[2]).toBeCloseTo(-right.RightHandRing2[2], 6);
+ // Curl hinge is mirrored: z components flip sign. The hinge is derived
+ // from the rig's MEASURED rest pose, which is not symmetric to the last
+ // decimal the way a hardcoded axis would be, so this holds to five
+ // places rather than exactly.
+ expect(left.LeftHandRing2[2]).toBeCloseTo(-right.RightHandRing2[2], 5);
});
it('rejects unknown characters', () => {
diff --git a/tests/mcp-sign-tools.test.js b/tests/mcp-sign-tools.test.js
new file mode 100644
index 000000000..1051a3778
--- /dev/null
+++ b/tests/mcp-sign-tools.test.js
@@ -0,0 +1,111 @@
+// Coverage for api/_mcp/tools/sign.js: the two MCP tools that let any agent
+// ask a three.ws avatar to sign something.
+//
+// The interesting property is restraint: a signed sentence compiles to tens of
+// thousands of numbers, and pasting that into a chat transcript is a way to
+// destroy an agent's context for no benefit. So sign_text answers with the
+// timeline and a URL by default, and only inlines the clip when the caller
+// explicitly asks. These tests hold that line, plus the readable text rendering
+// an MCP client actually shows a human.
+
+import { describe, it, expect } from 'vitest';
+
+const { toolDefs } = await import('../api/_mcp/tools/sign.js');
+
+const byName = Object.fromEntries(toolDefs.map((t) => [t.name, t]));
+const req = { headers: { host: 'three.ws' } };
+const call = (name, args) => byName[name].handler(args, {}, req);
+
+describe('tool definitions', () => {
+ it('declares both tools as pure reads', () => {
+ expect(Object.keys(byName).sort()).toEqual(['list_sign_vocabulary', 'sign_text']);
+ for (const tool of toolDefs) {
+ expect(tool.annotations.readOnlyHint).toBe(true);
+ expect(tool.annotations.destructiveHint).toBe(false);
+ expect(tool.annotations.idempotentHint).toBe(true);
+ expect(tool.inputSchema.additionalProperties).toBe(false);
+ expect(tool.description.length).toBeGreaterThan(80);
+ }
+ });
+
+ it('requires text on sign_text and nothing on the vocabulary listing', () => {
+ expect(byName.sign_text.inputSchema.required).toEqual(['text']);
+ expect(byName.list_sign_vocabulary.inputSchema.required).toBeUndefined();
+ });
+});
+
+describe('list_sign_vocabulary', () => {
+ it('lists every sign with its description', async () => {
+ const out = await call('list_sign_vocabulary', {});
+ expect(out.structuredContent.count).toBeGreaterThan(20);
+ expect(out.structuredContent.count).toBe(out.structuredContent.vocabulary.length);
+ expect(out.content[0].text).toMatch(/everything else fingerspells/);
+ // Aliases resolve onto the same signs, so the recognized set is wider.
+ expect(out.structuredContent.recognized_words.length).toBeGreaterThan(
+ out.structuredContent.count,
+ );
+ });
+
+ it('filters on the word and on the description', async () => {
+ const byWord = await call('list_sign_vocabulary', { search: 'hello' });
+ expect(byWord.structuredContent.vocabulary.map((v) => v.word)).toEqual(['HELLO']);
+
+ const byGloss = await call('list_sign_vocabulary', { search: 'forehead' });
+ expect(byGloss.structuredContent.count).toBeGreaterThan(0);
+ for (const entry of byGloss.structuredContent.vocabulary) {
+ expect(entry.gloss.toLowerCase()).toContain('forehead');
+ }
+ });
+
+ it('returns an empty list rather than failing on a miss', async () => {
+ const out = await call('list_sign_vocabulary', { search: 'zzzzzz' });
+ expect(out.structuredContent.count).toBe(0);
+ expect(out.isError).toBeUndefined();
+ });
+});
+
+describe('sign_text', () => {
+ it('reports the timeline and links, and withholds the clip by default', async () => {
+ const out = await call('sign_text', { text: 'happy to meet you' });
+ const s = out.structuredContent;
+ expect(s.ok).toBe(true);
+ expect(s.signed).toEqual(['HAPPY', 'MEET', 'YOU']);
+ expect(s.spelled).toEqual(['TO']);
+ expect(s.clip).toBeUndefined();
+ expect(s.clip_url).toContain('/api/sign?text=');
+ expect(s.viewer_url).toContain('/sign-language?say=');
+ expect(s.timeline).toHaveLength(4);
+ });
+
+ it('inlines the clip only when asked', async () => {
+ const out = await call('sign_text', { text: 'hello', include_clip: true });
+ expect(out.structuredContent.clip.tracks.length).toBeGreaterThan(10);
+ expect(out.structuredContent.clip.duration).toBeCloseTo(
+ out.structuredContent.duration,
+ 4,
+ );
+ });
+
+ it('renders a line a human can read, signed and spelled marked differently', async () => {
+ const { content } = await call('sign_text', { text: 'hello nich' });
+ const text = content[0].text;
+ expect(text).toMatch(/HELLO\s+signed/);
+ expect(text).toMatch(/NICH\s+spelled\s+\S+\s+N-I-C-H/);
+ expect(text).toMatch(/Watch it: https:\/\/three\.ws\/sign-language\?say=/);
+ });
+
+ it('carries the hand and speed into the clip url', async () => {
+ const out = await call('sign_text', { text: 'hello', hand: 'left', speed: 0.5 });
+ expect(out.structuredContent.hand).toBe('left');
+ expect(out.structuredContent.clip_url).toContain('hand=left');
+ expect(out.structuredContent.clip_url).toContain('speed=0.5');
+ });
+
+ it('rejects text with nothing signable in it, with a usable reason', async () => {
+ await expect(call('sign_text', { text: '✓✓✓' })).rejects.toThrow(/A-Z and 0-9/);
+ });
+
+ it('rejects empty text', async () => {
+ await expect(call('sign_text', { text: ' ' })).rejects.toThrow(/required/);
+ });
+});
diff --git a/tests/sign-grader.test.js b/tests/sign-grader.test.js
new file mode 100644
index 000000000..c524de218
--- /dev/null
+++ b/tests/sign-grader.test.js
@@ -0,0 +1,185 @@
+import { describe, expect, it } from 'vitest';
+import { HANDSHAPES } from '../src/sign-handshapes.js';
+import { HAND_CONNECTIONS, HAND_LANDMARKS, handshapeLandmarks, projectHand } from '../src/sign-hand-model.js';
+import { GradeSmoother, gradeHandshape, handMetrics, handshapeMetrics, rankHandshapes } from '../src/sign-grader.js';
+
+const LETTERS = 'ABCDEFGHIKLMNOPQRSTUVWXY'.split('');
+
+/** Rigid-body transform: grading must not care where a hand is or how it is turned. */
+function transform(points, { angle = 0, scale = 1, offset = [0, 0, 0] } = {}) {
+ const c = Math.cos(angle);
+ const s = Math.sin(angle);
+ return points.map(([x, y, z]) => [
+ (x * c - z * s) * scale + offset[0],
+ y * scale + offset[1],
+ (x * s + z * c) * scale + offset[2],
+ ]);
+}
+
+/** Mirror across X, which is what a left hand is. */
+const mirror = (points) => points.map(([x, y, z]) => [-x, y, z]);
+
+describe('the reference hand', () => {
+ it('lays a handshape out in MediaPipe landmark order', () => {
+ const hand = handshapeLandmarks('B');
+ expect(hand).toHaveLength(21);
+ for (const p of hand) expect(p.every(Number.isFinite)).toBe(true);
+ // Fingertips are further from the wrist than their own knuckles.
+ const dist = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
+ const wrist = hand[HAND_LANDMARKS.WRIST];
+ expect(dist(hand[HAND_LANDMARKS.INDEX_TIP], wrist)).toBeGreaterThan(dist(hand[HAND_LANDMARKS.INDEX_MCP], wrist));
+ });
+
+ it('builds every handshape in the catalogue', () => {
+ for (const name of Object.keys(HANDSHAPES)) {
+ expect(handshapeLandmarks(name), name).toHaveLength(21);
+ }
+ });
+
+ it('draws with connections that stay inside the point set', () => {
+ for (const [a, b] of HAND_CONNECTIONS) {
+ expect(a).toBeGreaterThanOrEqual(0);
+ expect(b).toBeLessThan(21);
+ }
+ });
+
+ it('projects into the requested box', () => {
+ const pts = projectHand(handshapeLandmarks('5'), { width: 200, height: 240, padding: 10 });
+ expect(pts).toHaveLength(21);
+ for (const { x, y } of pts) {
+ expect(x).toBeGreaterThanOrEqual(0);
+ expect(x).toBeLessThanOrEqual(200);
+ expect(y).toBeGreaterThanOrEqual(0);
+ expect(y).toBeLessThanOrEqual(240);
+ }
+ });
+});
+
+describe('handMetrics', () => {
+ it('reads a closed fist as curled and an open hand as straight', () => {
+ const fist = handMetrics(handshapeLandmarks('S'));
+ const open = handMetrics(handshapeLandmarks('5'));
+ for (const finger of ['Index', 'Middle', 'Ring', 'Pinky']) {
+ expect(fist.curl[finger], finger).toBeGreaterThan(180);
+ expect(open.curl[finger], finger).toBeLessThan(60);
+ }
+ });
+
+ it('separates a spread hand from a flat one', () => {
+ const five = handMetrics(handshapeLandmarks('5'));
+ const flat = handMetrics(handshapeLandmarks('B'));
+ expect(five.spread['Index-Middle']).toBeGreaterThan(flat.spread['Index-Middle']);
+ });
+
+ it('measures V as two fingers apart and U as two fingers together', () => {
+ expect(handMetrics(handshapeLandmarks('V')).spread['Index-Middle']).toBeGreaterThan(12);
+ expect(handMetrics(handshapeLandmarks('U')).spread['Index-Middle']).toBeLessThan(4);
+ });
+
+ it('reads a pinch as a short thumb-to-fingertip distance', () => {
+ // F closes the index onto the thumb and leaves the rest open.
+ const f = handMetrics(handshapeLandmarks('F'));
+ expect(f.pinch.Index).toBeLessThan(f.pinch.Pinky);
+ });
+
+ it('rejects anything that is not 21 points', () => {
+ expect(() => handMetrics([])).toThrow(/21 landmarks/);
+ expect(() => handMetrics(null)).toThrow(/21 landmarks/);
+ });
+
+ it('accepts MediaPipe {x, y, z} objects as well as arrays', () => {
+ const arr = handshapeLandmarks('C');
+ const objs = arr.map(([x, y, z]) => ({ x, y, z }));
+ expect(handMetrics(objs).curl.Index).toBeCloseTo(handMetrics(arr).curl.Index, 6);
+ });
+});
+
+describe('gradeHandshape', () => {
+ it('gives the rig its own handshape back at full marks', () => {
+ for (const letter of LETTERS) {
+ expect(gradeHandshape(handshapeLandmarks(letter), letter).score, letter).toBeGreaterThan(99.5);
+ }
+ });
+
+ it('scores a different letter far lower than the right one', () => {
+ expect(gradeHandshape(handshapeLandmarks('B'), 'A').score).toBeLessThan(45);
+ expect(gradeHandshape(handshapeLandmarks('A'), 'B').score).toBeLessThan(45);
+ });
+
+ it('ranks the correct letter first for every letter that has a shape of its own', () => {
+ // G/Q and K/P are the same handshape in ASL and differ only by which way
+ // the hand points, which a handshape score cannot and should not see.
+ const shared = new Set(['G', 'Q', 'K', 'P']);
+ for (const letter of LETTERS) {
+ if (shared.has(letter)) continue;
+ expect(rankHandshapes(handshapeLandmarks(letter), LETTERS)[0].name, letter).toBe(letter);
+ }
+ });
+
+ it('is invariant to where the hand is, how big it is, and which way it faces', () => {
+ const moved = transform(handshapeLandmarks('D'), { angle: 0.9, scale: 3.4, offset: [12, -5, 7] });
+ expect(gradeHandshape(moved, 'D').score).toBeGreaterThan(99.5);
+ });
+
+ it('grades a left hand against a right-hand target', () => {
+ expect(gradeHandshape(mirror(handshapeLandmarks('W')), 'W').score).toBeGreaterThan(99);
+ });
+
+ it('names the finger that is wrong', () => {
+ // I is the pinky alone; holding up the index instead should call that out.
+ const grade = gradeHandshape(handshapeLandmarks('D'), 'I');
+ expect(grade.score).toBeLessThan(70);
+ expect(grade.hint).toMatch(/index|pinky/i);
+ });
+
+ it('tells a learner to hold it once the shape is right', () => {
+ expect(gradeHandshape(handshapeLandmarks('L'), 'L').hint).toMatch(/hold/i);
+ });
+
+ it('reports per-finger detail against the same target the avatar wears', () => {
+ const grade = gradeHandshape(handshapeLandmarks('A'), 'A');
+ expect(grade.fingers).toHaveLength(4);
+ for (const f of grade.fingers) {
+ expect(f.target).toBeCloseTo(handshapeMetrics('A').curl[f.finger], 6);
+ expect(Math.abs(f.delta)).toBeLessThan(1e-6);
+ }
+ });
+
+ it('refuses a handshape it does not know', () => {
+ expect(() => gradeHandshape(handshapeLandmarks('A'), 'NOT_A_SHAPE')).toThrow(/handshape/i);
+ });
+});
+
+describe('GradeSmoother', () => {
+ const frame = (score) => ({ score, hint: 'x' });
+
+ it('needs a sustained hold, not one lucky frame', () => {
+ const s = new GradeSmoother({ alpha: 1, passScore: 80, holdMs: 500 });
+ expect(s.push(frame(95), 1000).passed).toBe(false);
+ expect(s.push(frame(95), 1200).passed).toBe(false);
+ expect(s.push(frame(95), 1600).passed).toBe(true);
+ });
+
+ it('drops the hold when the hand leaves the shape', () => {
+ const s = new GradeSmoother({ alpha: 1, passScore: 80, holdMs: 300 });
+ s.push(frame(95), 0);
+ expect(s.push(frame(20), 200).holding).toBe(false);
+ expect(s.push(frame(95), 400).passed).toBe(false);
+ expect(s.push(frame(95), 750).passed).toBe(true);
+ });
+
+ it('smooths a jittering score instead of following every frame', () => {
+ const s = new GradeSmoother({ alpha: 0.25 });
+ s.push(frame(90), 0);
+ const jittered = s.push(frame(10), 40).score;
+ expect(jittered).toBeGreaterThan(50);
+ expect(jittered).toBeLessThan(90);
+ });
+
+ it('starts clean after a reset', () => {
+ const s = new GradeSmoother({ alpha: 0.5 });
+ s.push(frame(100), 0);
+ s.reset();
+ expect(s.push(frame(40), 100).score).toBe(40);
+ });
+});
diff --git a/tests/sign-speech.test.js b/tests/sign-speech.test.js
index 2c524d0cf..88beb1f6a 100644
--- a/tests/sign-speech.test.js
+++ b/tests/sign-speech.test.js
@@ -1,11 +1,13 @@
import { describe, expect, it, vi } from 'vitest';
import { buildFingerspellingClip } from '../src/fingerspelling.js';
+import { signLookup } from '../src/sign-dictionary.js';
import {
CHAT_TIMING,
SignSpeaker,
compileUtterance,
estimateDuration,
+ scaledTiming,
utteranceWords,
} from '../src/sign-speech.js';
@@ -75,6 +77,78 @@ describe('compileUtterance', () => {
});
});
+// The segment timeline is what a caption track, a scrubber, or the /api/sign
+// console reads to follow an utterance along. It is only useful if it describes
+// the clip exactly: gaps or drift show up as a caption running ahead of the
+// hands, which is worse than no caption at all.
+describe('compileUtterance segments', () => {
+ const signs = signLookup();
+
+ it('tiles the whole clip in order, one entry per word', () => {
+ const out = compileUtterance('happy to meet you', { signs });
+ expect(out.segments.map((s) => s.word)).toEqual(out.words);
+ expect(out.segments[0].start).toBe(0);
+ for (let i = 1; i < out.segments.length; i++) {
+ expect(out.segments[i].start).toBeGreaterThanOrEqual(out.segments[i - 1].end);
+ }
+ expect(out.segments[out.segments.length - 1].end).toBeCloseTo(out.clip.duration, 6);
+ });
+
+ it('marks signed words with their gloss and spelled words with their letters', () => {
+ const [hello, name] = compileUtterance('hello nich', { signs }).segments;
+ expect(hello.signed).toBe(true);
+ expect(hello.gloss).toMatch(/temple/);
+ expect(hello.letters).toBeNull();
+
+ expect(name.signed).toBe(false);
+ expect(name.gloss).toBeNull();
+ expect(name.letters.map((l) => l.letter).join('')).toBe('NICH');
+ });
+
+ it('keeps every letter inside its own word, in order', () => {
+ const word = compileUtterance('abc', { signs }).segments[0];
+ let previous = word.start;
+ for (const letter of word.letters) {
+ expect(letter.start).toBeGreaterThanOrEqual(previous - 1e-9);
+ expect(letter.end).toBeGreaterThan(letter.start);
+ expect(letter.end).toBeLessThanOrEqual(word.end + 1e-9);
+ previous = letter.end;
+ }
+ });
+
+ it('describes the truncated utterance, not the requested one', () => {
+ const out = compileUtterance(Array(30).fill('hello').join(' '), { signs, maxSeconds: 6 });
+ expect(out.truncated).toBe(true);
+ expect(out.segments.length).toBeLessThan(out.words.length);
+ expect(out.segments[out.segments.length - 1].end).toBeCloseTo(out.clip.duration, 6);
+ });
+
+ it('stretches with the rate rather than reporting citation timings', () => {
+ const fast = compileUtterance('hello', { signs: signLookup({ rate: 1 }) });
+ const slow = compileUtterance('hello', {
+ signs: signLookup({ rate: 0.5 }),
+ timing: scaledTiming(0.5),
+ });
+ expect(slow.segments[0].end).toBeGreaterThan(fast.segments[0].end * 1.5);
+ expect(slow.segments[0].end).toBeCloseTo(slow.clip.duration, 6);
+ });
+});
+
+describe('scaledTiming', () => {
+ it('divides every duration by the rate and leaves 1x untouched', () => {
+ expect(scaledTiming(1)).toEqual({ ...CHAT_TIMING });
+ const half = scaledTiming(0.5);
+ for (const [key, value] of Object.entries(CHAT_TIMING)) {
+ expect(half[key]).toBeCloseTo(value * 2, 9);
+ }
+ });
+
+ it('ignores a nonsense rate instead of producing Infinity', () => {
+ expect(scaledTiming(0)).toEqual({ ...CHAT_TIMING });
+ expect(scaledTiming(Number.NaN)).toEqual({ ...CHAT_TIMING });
+ });
+});
+
describe('estimateDuration', () => {
it('tracks compiled duration closely for plain fingerspelling', () => {
// `signed: false` matches compileUtterance with no dictionary — both spell